Security Compliance Toolkit
Enterprise-grade skill for guides, security, professionals, implementing. Includes structured workflows, validation checks, and reusable patterns for development.
Security Compliance Toolkit
A comprehensive skill for implementing security controls, compliance frameworks, and vulnerability prevention in web applications. Covers OWASP Top 10 mitigations, authentication hardening, data protection, audit logging, and regulatory compliance patterns.
When to Use This Skill
Choose this skill when:
- Implementing authentication, authorization, and session management securely
- Hardening APIs against injection, XSS, CSRF, and SSRF attacks
- Adding audit logging and compliance reporting for SOC 2 or GDPR requirements
- Reviewing code for security vulnerabilities before production deployment
- Setting up secrets management, encryption at rest, and TLS configuration
Consider alternatives when:
- Need penetration testing tooling → use a security testing skill
- Working on network/infrastructure security → use a DevSecOps skill
- Building OAuth/OIDC identity provider → use an identity provider skill
- Need container security scanning → use a container security skill
Quick Start
// Security middleware stack for Express/Node.js import helmet from 'helmet'; import rateLimit from 'express-rate-limit'; import cors from 'cors'; // Apply security headers app.use(helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], scriptSrc: ["'self'", "'nonce-{random}'"], styleSrc: ["'self'", "'unsafe-inline'"], imgSrc: ["'self'", "data:", "https:"], connectSrc: ["'self'", "https://api.example.com"], }, }, hsts: { maxAge: 31536000, includeSubDomains: true, preload: true }, })); // Rate limiting app.use('/api/', rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, standardHeaders: true, legacyHeaders: false, })); // CORS with explicit origins app.use(cors({ origin: ['https://app.example.com'], credentials: true, methods: ['GET', 'POST', 'PUT', 'DELETE'], }));
Core Concepts
OWASP Top 10 Mitigations
| Vulnerability | Mitigation | Implementation |
|---|---|---|
| Injection (SQL/NoSQL) | Parameterized queries | ORM/prepared statements, never string concat |
| Broken Auth | MFA, secure sessions | bcrypt hashing, JWT rotation, session timeout |
| XSS | Output encoding | CSP headers, template auto-escaping, DOMPurify |
| CSRF | Token validation | SameSite cookies, anti-CSRF tokens |
| SSRF | URL validation | Allowlist domains, block private IPs |
| Security Misconfiguration | Hardened defaults | Helmet.js, disable debug in prod |
| Broken Access Control | Authorization middleware | RBAC/ABAC, resource-level checks |
| Cryptographic Failures | Strong algorithms | AES-256-GCM, bcrypt cost 12+, TLS 1.3 |
Input Validation and Sanitization
import { z } from 'zod'; import DOMPurify from 'isomorphic-dompurify'; // Schema validation at API boundary const createUserSchema = z.object({ email: z.string().email().max(254).toLowerCase(), password: z.string().min(12).max(128) .regex(/[A-Z]/, 'Must contain uppercase') .regex(/[0-9]/, 'Must contain number') .regex(/[^A-Za-z0-9]/, 'Must contain special character'), name: z.string().min(1).max(100).trim(), bio: z.string().max(500).transform(val => DOMPurify.sanitize(val)), }); // Middleware for request validation function validate(schema: z.ZodType) { return (req: Request, res: Response, next: NextFunction) => { const result = schema.safeParse(req.body); if (!result.success) { return res.status(400).json({ error: 'Validation failed', details: result.error.issues.map(i => ({ field: i.path.join('.'), message: i.message, })), }); } req.body = result.data; next(); }; }
Audit Logging Pattern
interface AuditEvent { timestamp: string; actor: { id: string; email: string; ip: string }; action: string; resource: { type: string; id: string }; outcome: 'success' | 'failure'; metadata: Record<string, unknown>; } class AuditLogger { async log(event: AuditEvent): Promise<void> { // Write to append-only audit log (immutable) await this.store.append({ ...event, timestamp: new Date().toISOString(), id: crypto.randomUUID(), }); } async logAuth(userId: string, action: string, success: boolean, req: Request) { await this.log({ timestamp: new Date().toISOString(), actor: { id: userId, email: '', ip: req.ip }, action: `auth.${action}`, resource: { type: 'session', id: req.sessionID || '' }, outcome: success ? 'success' : 'failure', metadata: { userAgent: req.get('user-agent') }, }); } }
Configuration
| Parameter | Type | Default | Description |
|---|---|---|---|
passwordMinLength | number | 12 | Minimum password length |
bcryptCostFactor | number | 12 | bcrypt hashing rounds |
sessionTimeout | number | 3600 | Session inactivity timeout (seconds) |
rateLimitMax | number | 100 | Max requests per window per IP |
csrfProtection | boolean | true | Enable CSRF token validation |
auditLogRetention | number | 365 | Days to retain audit logs |
Best Practices
-
Validate all input at system boundaries, reject by default — Every API endpoint must validate request bodies, query parameters, and headers against strict schemas. Use allowlists rather than denylists — reject anything not explicitly permitted.
-
Hash passwords with bcrypt at cost factor 12 or higher — Never use MD5, SHA-256, or plain hashing for passwords. bcrypt includes a salt and is intentionally slow. Increase cost factor as hardware improves. Consider Argon2id for new applications.
-
Implement defense in depth for authorization — Check permissions at the route level (middleware), the service level (business logic), and the data level (row-level security). A bug in one layer shouldn't grant unauthorized access.
-
Log security events immutably and completely — Authentication attempts, permission changes, data access, and admin actions must produce audit logs. Logs must be append-only and tamper-evident. Include actor, action, resource, and outcome in every entry.
-
Rotate secrets and tokens on a schedule — API keys, JWT signing keys, database passwords, and encryption keys must be rotated periodically. Use a secrets manager (Vault, AWS Secrets Manager) rather than environment variables for production secrets.
Common Issues
CSRF tokens not working with SPAs — Traditional CSRF tokens rely on server-rendered forms. For SPAs, use the double-submit cookie pattern: set a random token in a cookie and require the same value in a custom header. SameSite=Strict cookies also prevent CSRF for same-site requests.
Rate limiting bypassed via distributed IPs — IP-based rate limiting fails against distributed attacks. Combine IP limiting with user/API-key-based limits. For unauthenticated endpoints, add CAPTCHA or proof-of-work challenges when rate limits are exceeded.
Sensitive data appearing in logs — Passwords, tokens, and PII must never appear in application logs. Use a structured logging library with field redaction. Define a denylist of field names (password, token, ssn, creditCard) that are automatically masked in log output.
Reviews
No reviews yet. Be the first to review this template!
Similar Templates
Full-Stack Code Reviewer
Comprehensive code review skill that checks for security vulnerabilities, performance issues, accessibility, and best practices across frontend and backend code.
Test Suite Generator
Generates comprehensive test suites with unit tests, integration tests, and edge cases. Supports Jest, Vitest, Pytest, and Go testing.
Pro Architecture Workspace
Battle-tested skill for architectural, decision, making, framework. Includes structured workflows, validation checks, and reusable patterns for development.