references/backend_security_practices.md · 24000
Key', ], censor: '[REDACTED]', }, });
// Security event types type SecurityEventType = | 'AUTH_SUCCESS' | 'AUTH_FAILURE' | 'AUTH_LOCKOUT' | 'PASSWORD_CHANGED' | 'PASSWORD_RESET_REQUEST' | 'PERMISSION_DENIED' | 'RATE_LIMIT_EXCEEDED' | 'SUSPICIOUS_ACTIVITY' | 'TOKEN_REVOKED';
interface SecurityEvent { type: SecurityEventType; userId?: string; ip: string; userAgent: string; path: string; details?: Record<string, unknown>; }
function logSecurityEvent(event: SecurityEvent): void {
logger.info({
security: true,
...event,
timestamp: new Date().toISOString(),
}, Security: ${event.type});
}
### Request Logging
```typescript
import pinoHttp from 'pino-http';
app.use(pinoHttp({
logger,
genReqId: (req) => req.headers['x-request-id'] || crypto.randomUUID(),
serializers: {
req: (req) => ({
id: req.id,
method: req.method,
url: req.url,
remoteAddress: req.remoteAddress,
// Don't log headers by default (may contain sensitive data)
}),
res: (res) => ({
statusCode: res.statusCode,
}),
},
customLogLevel: (req, res, err) => {
if (res.statusCode >= 500 || err) return 'error';
if (res.statusCode >= 400) return 'warn';
return 'info';
},
}));
Alerting Thresholds
| Metric | Warning | Critical | |--------|---------|----------| | Failed logins per IP (15 min) | > 5 | > 10 | | Failed logins per account (1 hour) | > 3 | > 5 | | 403 responses per IP (5 min) | > 10 | > 50 | | 500 errors (5 min) | > 5 | > 20 | | Request rate per IP (1 min) | > 100 | > 500 |
Quick Reference: Security Checklist
Authentication
- [ ] bcrypt with cost >= 12 for password hashing
- [ ] JWT with RS256, short expiry (15-30 min)
- [ ] Refresh token rotation with family detection
- [ ] Session regeneration on login
- [ ] Secure cookie flags (httpOnly, secure, sameSite)
Input Validation
- [ ] Schema validation on all inputs (Zod)
- [ ] Parameterized queries (never string concat)
- [ ] File path sanitization
- [ ] Content-Type validation
Headers
- [ ] Strict-Transport-Security
- [ ] Content-Security-Policy
- [ ] X-Content-Type-Options: nosniff
- [ ] X-Frame-Options: DENY
- [ ] CORS with specific origins
Logging
- [ ] Redact sensitive fields
- [ ] Log security events
- [ ] Include request IDs
- [ ] Alert on anomalies
Dependencies
- [ ] npm audit in CI
- [ ] Automated dependency updates
- [ ] Lock file committed