| name | security-hardening |
| description | Advanced security patterns including zero-trust architecture, secret management, CSP, and compliance frameworks |
| category | security |
| triggers | ["security hardening","zero trust","secret management","csp","security headers","compliance","penetration testing"] |
Security Hardening
Implement advanced security patterns beyond basic OWASP guidelines. This skill covers zero-trust architecture, secret management, security headers, and compliance frameworks.
Purpose
Build defense-in-depth for production systems:
- Implement zero-trust security model
- Manage secrets securely with Vault
- Configure comprehensive security headers
- Design Content Security Policy (CSP)
- Prepare for security audits
- Meet compliance requirements (SOC2, GDPR)
Features
1. Zero-Trust Architecture
import { Request, Response, NextFunction } from 'express';
async function verifyIdentity(req: Request, res: Response, next: NextFunction) {
const token = extractToken(req);
if (!token) {
return res.status(401).json({ error: 'Authentication required' });
}
try {
const decoded = await verifyToken(token);
if (await isTokenRevoked(decoded.jti)) {
return res.status(401).json({ error: 'Token revoked' });
}
const user = await getUserById(decoded.sub);
if (!user || user.status !== 'active') {
return res.status(401).json({ error: 'User not found or inactive' });
}
req.user = user;
req.tokenClaims = decoded;
next();
} catch (error) {
return res.status(401).json({ error: 'Invalid token' });
}
}
async function verifyAuthorization(resource: string, action: string) {
return (req: Request, res: Response, next: NextFunction) => {
const allowed = checkPermission(req.user, resource, action);
if (!allowed) {
auditLog({
event: 'authorization_denied',
userId: req.user.id,
resource,
action,
ip: req.ip,
});
return res.status(403).json({ error: 'Access denied' });
}
next();
};
}
async function verifyContext(req: Request, res: Response, next: NextFunction) {
const deviceFingerprint = req.headers['x-device-fingerprint'];
const geoLocation = await getGeoLocation(req.ip);
const risk = await assessRisk({
userId: req.user.id,
deviceFingerprint,
geoLocation,
userAgent: req.headers['user-agent'],
timestamp: Date.now(),
});
if (risk.score > 0.8) {
return res.status(403).json({
error: 'Additional verification required',
challenge: risk.challengeType,
});
}
if (risk.score > 0.5) {
auditLog({
event: 'suspicious_activity',
userId: req.user.id,
riskScore: risk.score,
factors: risk.factors,
});
}
next();
}
app.use('/api', verifyIdentity, verifyContext);
app.get('/api/users/:id', verifyAuthorization('users', 'read'), getUser);
app.put('/api/users/:id', verifyAuthorization('users', 'write'), updateUser);
2. Secret Management with Vault
import Vault from 'node-vault';
class SecretManager {
private vault: Vault.client;
private cache: Map<string, { value: any; expires: number }> = new Map();
private cacheTTL = 300000;
constructor() {
this.vault = Vault({
apiVersion: 'v1',
endpoint: process.env.VAULT_ADDR,
token: process.env.VAULT_TOKEN,
});
}
async getSecret(path: string): Promise<any> {
const cached = this.cache.get(path);
if (cached && cached.expires > Date.now()) {
return cached.value;
}
response = ..();
secret = response..;
..(path, {
: secret,
: .() + .,
});
secret;
}
(): <{ : ; : }> {
response = ..();
{
: response..,
: response..,
};
}
(: , : ): <> {
..(, {
: newValue,
});
..(path);
}
(): <.> {
response = ..();
{
: response..,
: response..,
: response..,
};
}
}
{ createCipheriv, createDecipheriv, randomBytes, scrypt } ;
(): <> {
salt = ();
key = <>( {
(password, salt, , {
(err) (err);
(key);
});
});
iv = ();
cipher = (, key, iv);
encrypted = cipher.(envContent, , );
encrypted += cipher.();
authTag = cipher.();
.({
: salt.(),
: iv.(),
: authTag.(),
encrypted,
});
}
3. Security Headers
import helmet from 'helmet';
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: [
"'self'",
"'strict-dynamic'",
(req, res) => `'nonce-${res.locals.nonce}'`,
],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
fontSrc: ["'self'", "https://fonts.gstatic.com"],
connectSrc: ["'self'", "https://api.example.com"],
frameSrc: ["'none'"],
objectSrc: ["'none'"],
baseUri: ["'self'"],
formAction: ["'self'"],
upgradeInsecureRequests: [],
blockAllMixedContent: [],
},
reportOnly: false,
},
crossOriginEmbedderPolicy: true,
crossOriginOpenerPolicy: { policy: 'same-origin' },
crossOriginResourcePolicy: { : },
: { : },
: { : },
: {
: ,
: ,
: ,
},
: ,
: ,
: ,
: { : },
: { : },
: ,
}));
app.( {
res.. = crypto.().();
();
});
app.( {
(req..()) {
res.(, );
res.(, );
res.(, );
}
res.(,
+
);
(req. === ) {
res.(, );
}
();
});
app.(, express.({ : }), {
report = req.[];
logger.({
: ,
: report[],
: report[],
: report[],
: report[],
: report[],
});
res.().();
});
4. Input Validation & Sanitization
import { z } from 'zod';
import DOMPurify from 'isomorphic-dompurify';
import sqlstring from 'sqlstring';
const UserInputSchema = z.object({
email: z.string().email().max(255).toLowerCase(),
name: z.string()
.min(2)
.max(100)
.regex(/^[a-zA-Z\s'-]+$/, 'Invalid characters in name'),
phone: z.string()
.regex(/^\+?[1-9]\d{1,14}$/, 'Invalid phone number')
.optional(),
bio: z.string().max(1000).optional(),
});
function sanitizeHTML(html: string): string {
return DOMPurify.sanitize(html, {
ALLOWED_TAGS: [, , , , , , , , , ],
: [, , ],
: ,
});
}
(): {
sqlstring.(input);
}
(): {
resolvedPath = path.(basePath, userPath);
(!resolvedPath.(path.(basePath))) {
();
}
resolvedPath;
}
= [, , , ];
= * * ;
(): <> {
(file. > ) {
();
}
fileType = ();
= fileType.(file.);
(! || !.(.)) {
();
}
(..()) {
(file.);
}
}
5. Audit Logging
interface AuditEvent {
timestamp: Date;
eventType: string;
userId?: string;
resourceType?: string;
resourceId?: string;
action: string;
outcome: 'success' | 'failure';
ipAddress: string;
userAgent?: string;
details?: Record<string, any>;
requestId?: string;
}
class AuditLogger {
async log(event: AuditEvent): Promise<void> {
await db.auditLog.create({
data: {
...event,
timestamp: event.timestamp || new Date(),
hash: this.calculateHash(event),
},
});
await this.sendToSIEM(event);
}
(: ): {
content = .({
...event,
: event..(),
});
crypto
.(, process..!)
.(content)
.();
}
(: ): <> {
(process..!, {
: ,
: { : },
: .(event),
});
}
}
() {
(: , : , : ) => {
startTime = .();
res.(, () => {
auditLogger.({
: (),
: ,
: req.?.,
resourceType,
: req..,
action,
: res. < ? : ,
: req.,
: req.[],
: req.[] ,
: {
: req.,
: req.,
: res.,
: .() - startTime,
},
});
});
();
};
}
app.(,
(, ),
deleteUser
);
app.(,
(, ),
createRole
);
6. Compliance Frameworks
class GDPRCompliance {
async exportUserData(userId: string): Promise<UserDataExport> {
const user = await db.user.findUnique({
where: { id: userId },
include: {
orders: true,
addresses: true,
preferences: true,
activityLog: true,
},
});
return {
personalData: {
name: user.name,
email: user.email,
phone: user.phone,
createdAt: user.createdAt,
},
orders: user.orders,
addresses: user.addresses,
preferences: user.preferences,
activityLog: user.activityLog,
exportedAt: new Date(),
};
}
async eraseUserData(userId: ): <> {
db.$transaction([
db..({ : { userId } }),
db..({ : { userId } }),
db..({ : { userId } }),
db..({
: { userId },
: { : , : },
}),
db..({ : { : userId } }),
]);
auditLogger.({
: (),
: ,
userId,
: ,
: ,
});
}
(): <> {
retentionPolicies = [
{ : , : },
{ : , : },
{ : , : * },
];
( policy retentionPolicies) {
cutoff = ();
cutoff.(cutoff.() - policy.);
db[policy.].({
: { : { : cutoff } },
});
}
}
}
pciCompliance = {
(: ): {
{
: data..(-),
: (data.),
: data.,
: data.,
};
},
(: ): {
pan.(, ) + + pan.(-);
},
};
Use Cases
1. API Security Hardening
app.use(helmet());
app.use(rateLimiter);
app.use(verifyIdentity);
app.use(auditMiddleware);
2. Secure File Handling
app.post('/upload', authenticate, async (req, res) => {
await validateFileUpload(req.file);
const safePath = sanitizePath(req.body.path, UPLOAD_DIR);
});
Best Practices
Do's
- Defense in depth - Multiple layers of security
- Principle of least privilege - Minimal permissions
- Regular security audits - Penetration testing
- Automated vulnerability scanning - CI/CD integration
- Incident response planning - Document procedures
- Security training - Educate team members
Don'ts
- Don't store secrets in code
- Don't trust client input
- Don't expose stack traces
- Don't use deprecated crypto
- Don't skip security headers
- Don't ignore security alerts
Related Skills
- owasp - Security fundamentals
- oauth - Authentication patterns
- defense-in-depth - Layered security
Reference Resources