[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7514EDYT0FBA0ZXTA0DATTV":3,"skill-same:01M7514EDYT0FBA0ZXTA0DATTV":44},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M7514EDYT0FBA0ZXTA0DATTV","security-and-hardening",null,"Hardens code against vulnerabilities. Use when handling user input, authentication, data storage, or external integrations. The non-negotiable security MUSTs live in `.agents\u002Frules\u002Fsecurity-baseline.md`; this skill shows how to apply them with code patterns, decision trees, and review checklists.","chrisbarrantes\u002Fmandrel","chrisbarrantes","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F4534419?v=4","01M7511VXT2H7WE09JE4ZMBESG","Chris Barrantes","01M7511VYGPFHQCE9HNVKES0QN",0,"MIT","https:\u002F\u002Fgithub.com\u002Fchrisbarrantes\u002Fmandrel\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fcore\u002Fsecurity-and-hardening\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: security-and-hardening\ndescription:\n  Hardens code against vulnerabilities. Use when handling user input,\n  authentication, data storage, or external integrations. The non-negotiable\n  security MUSTs live in `.agents\u002Frules\u002Fsecurity-baseline.md`; this skill shows\n  how to apply them with code patterns, decision trees, and review checklists.\n---\n\n# Security and Hardening\n\n## Policy Capsule\n\n- The non-negotiable MUSTs live in `.agents\u002Frules\u002Fsecurity-baseline.md`; that rule wins on conflict. Open a PR against the rule rather than working around it in this skill.\n- Validate ALL client input (body, query, headers, path params) at the edge with a strict schema (e.g., Zod). Never trust client-side validation as a security boundary.\n- Parameterize every database query. Never concatenate user input into SQL\u002FNoSQL filters or shell commands.\n- Hash passwords with bcrypt (≥12 rounds), scrypt, or argon2; plaintext storage is forbidden. Session cookies MUST be `httpOnly`, `secure`, and carry an explicit `sameSite`. Never put auth tokens in `localStorage`\u002F`sessionStorage`.\n- Every protected endpoint checks **authorization**, not just authentication; verify resource ownership server-side before any state change and never trust client-asserted roles.\n- Encode HTML output via the framework's auto-escaping; sanitize any unavoidable raw HTML with a vetted library (e.g., DOMPurify). Never feed user data to `eval()`, `Function()`, or `innerHTML`\u002F`dangerouslySetInnerHTML` unsanitized.\n- Exclude sensitive fields (password hashes, reset tokens, internal IDs) from API responses and never expose stack traces or internal error details to clients.\n- Never log PII (emails, full credit cards, session tokens, phone numbers). Destructure safe properties; don't log whole objects.\n- Configure security headers (`Content-Security-Policy`, `Strict-Transport-Security`, `X-Frame-Options`, `X-Content-Type-Options`) and restrict CORS to an explicit allowlist — wildcard `*` is forbidden on credentialed endpoints.\n- Pull all secrets from environment variables; never commit `.env`, default API keys, or fallback secrets. `.env.example` (placeholders only) is the committed shape.\n- Surface security-expanding changes (new auth flows, new PII categories, new integrations, CORS \u002F rate-limit changes, file uploads, elevated permissions) under a \"Security surface\" section in the PR body and on the ticket, label `risk::high`, and link the relevant baseline MUST. This documents the surface — it does not pause execution. `agent::blocked` is only for unrecoverable runtime blockers.\n\nThe non-negotiable MUSTs — input validation, authentication, authorization,\noutput encoding, transport, headers, secrets, forbidden practices — live in\n[`.agents\u002Frules\u002Fsecurity-baseline.md`](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md),\nwhich is the SSOT. This skill shows **how** to apply those MUSTs with code\npatterns and process guidance; read the rule for the **what**. When the rule\nand this skill diverge, the rule wins — open a PR against the rule rather\nthan working around it here.\n\n## When to Use\n\n- Building anything that accepts user input\n- Implementing authentication or authorization\n- Storing or transmitting sensitive data\n- Integrating with external APIs or services\n- Adding file uploads, webhooks, or callbacks\n- Handling payment or PII data\n\n## Security Surfacing, Not Runtime Pause\n\nSome changes are not unsafe by themselves but expand the security surface\nenough that the change must be **explicitly documented** in the PR\ndescription and on the originating ticket so a reviewer can sign off in\nband. Documenting them is the gate — they do **not** pause execution:\n\n- Adding new authentication flows or changing auth logic\n- Storing new categories of sensitive data (PII, payment info)\n- Adding new external service integrations\n- Changing CORS configuration\n- Adding file upload handlers\n- Modifying rate limiting or throttling\n- Granting elevated permissions or roles\n\nFor each item that applies, call it out under a \"Security surface\" section\nin the PR body and on the parent ticket, label the change `risk::high`,\nand link the relevant `security-baseline.md` MUST. Reviewers gate the\nmerge; the agent keeps moving.\n\n`agent::blocked` remains the **only** runtime pause label. Use it for\nunrecoverable blockers (missing prerequisite, ambiguous spec a sub-agent\ncannot resolve), not for \"this change is sensitive.\" Sensitive changes\nship through the documentation path above.\n\n## OWASP Top 10 Prevention Patterns\n\nThe patterns below show **how** to satisfy the MUSTs in\n[`security-baseline.md`](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md). The MUSTs\nthemselves (parameterize queries, hash passwords, encode output, verify\nownership, set headers, restrict CORS, exclude sensitive fields) are listed\nin the rule.\n\n### 1. Injection (SQL, NoSQL, OS Command)\n\nSee [security-baseline § Output & Rendering](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#output--rendering).\n\n```typescript\n\u002F\u002F BAD: SQL injection via string concatenation\nconst query = `SELECT * FROM users WHERE id = '${userId}'`;\n\n\u002F\u002F GOOD: Parameterized query\nconst user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);\n\n\u002F\u002F GOOD: ORM with parameterized input\nconst user = await prisma.user.findUnique({ where: { id: userId } });\n```\n\n### 2. Broken Authentication\n\nSee [security-baseline § Authentication](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#authentication).\n\n```typescript\nimport { hash, compare } from 'bcrypt';\n\nconst SALT_ROUNDS = 12;\nconst hashedPassword = await hash(plaintext, SALT_ROUNDS);\nconst isValid = await compare(plaintext, hashedPassword);\n\n\u002F\u002F Session management\napp.use(\n  session({\n    secret: process.env.SESSION_SECRET, \u002F\u002F From environment, not code\n    resave: false,\n    saveUninitialized: false,\n    cookie: {\n      httpOnly: true,\n      secure: true,\n      sameSite: 'lax',\n      maxAge: 24 * 60 * 60 * 1000,\n    },\n  }),\n);\n```\n\n### 3. Cross-Site Scripting (XSS)\n\nSee [security-baseline § Output & Rendering](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#output--rendering).\n\n```typescript\n\u002F\u002F BAD: Rendering user input as HTML\nelement.innerHTML = userInput;\n\n\u002F\u002F GOOD: Use framework auto-escaping (React does this by default)\nreturn \u003Cdiv>{userInput}\u003C\u002Fdiv>;\n\n\u002F\u002F If you MUST render HTML, sanitize first\nimport DOMPurify from 'dompurify';\nconst clean = DOMPurify.sanitize(userInput);\n```\n\n### 4. Broken Access Control\n\nSee [security-baseline § Authorization](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#authorization).\n\n```typescript\napp.patch('\u002Fapi\u002Ftasks\u002F:id', authenticate, async (req, res) => {\n  const task = await taskService.findById(req.params.id);\n\n  if (task.ownerId !== req.user.id) {\n    return res.status(403).json({\n      error: {\n        code: 'FORBIDDEN',\n        message: 'Not authorized to modify this task',\n      },\n    });\n  }\n\n  const updated = await taskService.update(req.params.id, req.body);\n  return res.json(updated);\n});\n```\n\n### 5. Security Misconfiguration\n\nSee [security-baseline § Transport & Headers](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#transport--headers).\n\n```typescript\nimport helmet from 'helmet';\napp.use(helmet());\n\napp.use(\n  helmet.contentSecurityPolicy({\n    directives: {\n      defaultSrc: [\"'self'\"],\n      scriptSrc: [\"'self'\"],\n      styleSrc: [\"'self'\", \"'unsafe-inline'\"],\n      imgSrc: [\"'self'\", 'data:', 'https:'],\n      connectSrc: [\"'self'\"],\n    },\n  }),\n);\n\napp.use(\n  cors({\n    origin: process.env.ALLOWED_ORIGINS?.split(',') || 'http:\u002F\u002Flocalhost:3000',\n    credentials: true,\n  }),\n);\n```\n\n### 6. Sensitive Data Exposure\n\nSee [security-baseline § Output & Rendering](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#output--rendering)\nand [§ Secrets Management](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#secrets-management).\n\n```typescript\nfunction sanitizeUser(user: UserRecord): PublicUser {\n  const { passwordHash, resetToken, ...publicFields } = user;\n  return publicFields;\n}\n\nconst API_KEY = process.env.STRIPE_API_KEY;\nif (!API_KEY) throw new Error('STRIPE_API_KEY not configured');\n```\n\n## Input Validation Patterns\n\nSee [security-baseline § Input Validation](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#input-validation).\n\n### Schema Validation at Boundaries\n\n```typescript\nimport { z } from 'zod';\n\nconst CreateTaskSchema = z.object({\n  title: z.string().min(1).max(200).trim(),\n  description: z.string().max(2000).optional(),\n  priority: z.enum(['low', 'medium', 'high']).default('medium'),\n  dueDate: z.string().datetime().optional(),\n});\n\napp.post('\u002Fapi\u002Ftasks', async (req, res) => {\n  const result = CreateTaskSchema.safeParse(req.body);\n  if (!result.success) {\n    return res.status(422).json({\n      error: {\n        code: 'VALIDATION_ERROR',\n        message: 'Invalid input',\n        details: result.error.flatten(),\n      },\n    });\n  }\n  const task = await taskService.create(result.data);\n  return res.status(201).json(task);\n});\n```\n\n### File Upload Safety\n\n```typescript\nconst ALLOWED_TYPES = ['image\u002Fjpeg', 'image\u002Fpng', 'image\u002Fwebp'];\nconst MAX_SIZE = 5 * 1024 * 1024; \u002F\u002F 5MB\n\nfunction validateUpload(file: UploadedFile) {\n  if (!ALLOWED_TYPES.includes(file.mimetype)) {\n    throw new ValidationError('File type not allowed');\n  }\n  if (file.size > MAX_SIZE) {\n    throw new ValidationError('File too large (max 5MB)');\n  }\n  \u002F\u002F Don't trust the file extension — check magic bytes if critical\n}\n```\n\n## Triaging npm audit Results\n\nThe MUST is in [security-baseline § Dependency Hygiene](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#dependency-hygiene).\nThis decision tree shows how to prioritize:\n\n```text\nnpm audit reports a vulnerability\n├── Severity: critical or high\n│   ├── Is the vulnerable code reachable in your app?\n│   │   ├── YES --> Fix immediately (update, patch, or replace the dependency)\n│   │   └── NO (dev-only dep, unused code path) --> Fix soon, but not a blocker\n│   └── Is a fix available?\n│       ├── YES --> Update to the patched version\n│       └── NO --> Check for workarounds, consider replacing the dependency, or add to allowlist with a review date\n├── Severity: moderate\n│   ├── Reachable in production? --> Fix in the next release cycle\n│   └── Dev-only? --> Fix when convenient, track in backlog\n└── Severity: low\n    └── Track and fix during regular dependency updates\n```\n\n**Key questions:**\n\n- Is the vulnerable function actually called in your code path?\n- Is the dependency a runtime dependency or dev-only?\n- Is the vulnerability exploitable given your deployment context (e.g., a\n  server-side vulnerability in a client-only app)?\n\nWhen you defer a fix, document the reason and set a review date.\n\n## Rate Limiting\n\n```typescript\nimport rateLimit from 'express-rate-limit';\n\n\u002F\u002F General API rate limit\napp.use(\n  '\u002Fapi\u002F',\n  rateLimit({\n    windowMs: 15 * 60 * 1000,\n    max: 100,\n    standardHeaders: true,\n    legacyHeaders: false,\n  }),\n);\n\n\u002F\u002F Stricter limit for auth endpoints (the rule MUSTs rate-limiting on auth)\napp.use(\n  '\u002Fapi\u002Fauth\u002F',\n  rateLimit({\n    windowMs: 15 * 60 * 1000,\n    max: 10,\n  }),\n);\n```\n\n## Secrets Management Layout\n\nSee [security-baseline § Secrets Management](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#secrets-management).\n\n```text\n.env files:\n  ├── .env.example  → Committed (template with placeholder values)\n  ├── .env          → NOT committed (contains real secrets)\n  └── .env.local    → NOT committed (local overrides)\n\n.gitignore must include:\n  .env\n  .env.local\n  .env.*.local\n  *.pem\n  *.key\n```\n\n**Always check before committing:**\n\n```bash\n# Check for accidentally staged secrets\ngit diff --cached | grep -i \"password\\|secret\\|api_key\\|token\"\n```\n\n## Security Review Checklist\n\nUse this when reviewing your own change before requesting human review. Each\nitem maps to a section in\n[`security-baseline.md`](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md).\n\n```markdown\n### Authentication\n\n- [ ] Passwords hashed with bcrypt\u002Fscrypt\u002Fargon2 (salt rounds ≥ 12)\n- [ ] Session tokens are httpOnly, secure, sameSite\n- [ ] Login has rate limiting\n- [ ] Password reset tokens expire\n\n### Authorization\n\n- [ ] Every endpoint checks user permissions\n- [ ] Users can only access their own resources\n- [ ] Admin actions require admin role verification\n\n### Input\n\n- [ ] All user input validated at the boundary\n- [ ] SQL queries are parameterized\n- [ ] HTML output is encoded\u002Fescaped\n\n### Data\n\n- [ ] No secrets in code or version control\n- [ ] Sensitive fields excluded from API responses\n- [ ] PII encrypted at rest (if applicable)\n\n### Infrastructure\n\n- [ ] Security headers configured (CSP, HSTS, etc.)\n- [ ] CORS restricted to known origins\n- [ ] Dependencies audited for vulnerabilities\n- [ ] Error messages don't expose internals\n```\n\n## Common Rationalizations\n\n| Rationalization                                     | Reality                                                                         |\n| --------------------------------------------------- | ------------------------------------------------------------------------------- |\n| \"This is an internal tool, security doesn't matter\" | Internal tools get compromised. Attackers target the weakest link.              |\n| \"We'll add security later\"                          | Security retrofitting is 10x harder than building it in. Add it now.            |\n| \"No one would try to exploit this\"                  | Automated scanners will find it. Security by obscurity is not security.         |\n| \"The framework handles security\"                    | Frameworks provide tools, not guarantees. You still need to use them correctly. |\n| \"It's just a prototype\"                             | Prototypes become production. Security habits from day one.                     |\n\n## Red Flags\n\n- User input passed directly to database queries, shell commands, or HTML\n  rendering\n- Secrets in source code or commit history\n- API endpoints without authentication or authorization checks\n- Missing CORS configuration or wildcard (`*`) origins\n- No rate limiting on authentication endpoints\n- Stack traces or internal errors exposed to users\n- Dependencies with known critical vulnerabilities\n\n## Verification\n\nAfter implementing security-relevant code, confirm against the rule:\n\n- [ ] `npm audit` shows no critical or high vulnerabilities\n- [ ] No secrets in source code or git history\n- [ ] All user input validated at system boundaries\n- [ ] Authentication and authorization checked on every protected endpoint\n- [ ] Security headers present in response (check with browser DevTools)\n- [ ] Error responses don't expose internal details\n- [ ] Rate limiting active on auth endpoints\n","# Security and Hardening\n\n## Policy Capsule\n\n- The non-negotiable MUSTs live in `.agents\u002Frules\u002Fsecurity-baseline.md`; that rule wins on conflict. Open a PR against the rule rather than working around it in this skill.\n- Validate ALL client input (body, query, headers, path params) at the edge with a strict schema (e.g., Zod). Never trust client-side validation as a security boundary.\n- Parameterize every database query. Never concatenate user input into SQL\u002FNoSQL filters or shell commands.\n- Hash passwords with bcrypt (≥12 rounds), scrypt, or argon2; plaintext storage is forbidden. Session cookies MUST be `httpOnly`, `secure`, and carry an explicit `sameSite`. Never put auth tokens in `localStorage`\u002F`sessionStorage`.\n- Every protected endpoint checks **authorization**, not just authentication; verify resource ownership server-side before any state change and never trust client-asserted roles.\n- Encode HTML output via the framework's auto-escaping; sanitize any unavoidable raw HTML with a vetted library (e.g., DOMPurify). Never feed user data to `eval()`, `Function()`, or `innerHTML`\u002F`dangerouslySetInnerHTML` unsanitized.\n- Exclude sensitive fields (password hashes, reset tokens, internal IDs) from API responses and never expose stack traces or internal error details to clients.\n- Never log PII (emails, full credit cards, session tokens, phone numbers). Destructure safe properties; don't log whole objects.\n- Configure security headers (`Content-Security-Policy`, `Strict-Transport-Security`, `X-Frame-Options`, `X-Content-Type-Options`) and restrict CORS to an explicit allowlist — wildcard `*` is forbidden on credentialed endpoints.\n- Pull all secrets from environment variables; never commit `.env`, default API keys, or fallback secrets. `.env.example` (placeholders only) is the committed shape.\n- Surface security-expanding changes (new auth flows, new PII categories, new integrations, CORS \u002F rate-limit changes, file uploads, elevated permissions) under a \"Security surface\" section in the PR body and on the ticket, label `risk::high`, and link the relevant baseline MUST. This documents the surface — it does not pause execution. `agent::blocked` is only for unrecoverable runtime blockers.\n\nThe non-negotiable MUSTs — input validation, authentication, authorization,\noutput encoding, transport, headers, secrets, forbidden practices — live in\n[`.agents\u002Frules\u002Fsecurity-baseline.md`](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md),\nwhich is the SSOT. This skill shows **how** to apply those MUSTs with code\npatterns and process guidance; read the rule for the **what**. When the rule\nand this skill diverge, the rule wins — open a PR against the rule rather\nthan working around it here.\n\n## When to Use\n\n- Building anything that accepts user input\n- Implementing authentication or authorization\n- Storing or transmitting sensitive data\n- Integrating with external APIs or services\n- Adding file uploads, webhooks, or callbacks\n- Handling payment or PII data\n\n## Security Surfacing, Not Runtime Pause\n\nSome changes are not unsafe by themselves but expand the security surface\nenough that the change must be **explicitly documented** in the PR\ndescription and on the originating ticket so a reviewer can sign off in\nband. Documenting them is the gate — they do **not** pause execution:\n\n- Adding new authentication flows or changing auth logic\n- Storing new categories of sensitive data (PII, payment info)\n- Adding new external service integrations\n- Changing CORS configuration\n- Adding file upload handlers\n- Modifying rate limiting or throttling\n- Granting elevated permissions or roles\n\nFor each item that applies, call it out under a \"Security surface\" section\nin the PR body and on the parent ticket, label the change `risk::high`,\nand link the relevant `security-baseline.md` MUST. Reviewers gate the\nmerge; the agent keeps moving.\n\n`agent::blocked` remains the **only** runtime pause label. Use it for\nunrecoverable blockers (missing prerequisite, ambiguous spec a sub-agent\ncannot resolve), not for \"this change is sensitive.\" Sensitive changes\nship through the documentation path above.\n\n## OWASP Top 10 Prevention Patterns\n\nThe patterns below show **how** to satisfy the MUSTs in\n[`security-baseline.md`](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md). The MUSTs\nthemselves (parameterize queries, hash passwords, encode output, verify\nownership, set headers, restrict CORS, exclude sensitive fields) are listed\nin the rule.\n\n### 1. Injection (SQL, NoSQL, OS Command)\n\nSee [security-baseline § Output & Rendering](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#output--rendering).\n\n```typescript\n\u002F\u002F BAD: SQL injection via string concatenation\nconst query = `SELECT * FROM users WHERE id = '${userId}'`;\n\n\u002F\u002F GOOD: Parameterized query\nconst user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);\n\n\u002F\u002F GOOD: ORM with parameterized input\nconst user = await prisma.user.findUnique({ where: { id: userId } });\n```\n\n### 2. Broken Authentication\n\nSee [security-baseline § Authentication](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#authentication).\n\n```typescript\nimport { hash, compare } from 'bcrypt';\n\nconst SALT_ROUNDS = 12;\nconst hashedPassword = await hash(plaintext, SALT_ROUNDS);\nconst isValid = await compare(plaintext, hashedPassword);\n\n\u002F\u002F Session management\napp.use(\n  session({\n    secret: process.env.SESSION_SECRET, \u002F\u002F From environment, not code\n    resave: false,\n    saveUninitialized: false,\n    cookie: {\n      httpOnly: true,\n      secure: true,\n      sameSite: 'lax',\n      maxAge: 24 * 60 * 60 * 1000,\n    },\n  }),\n);\n```\n\n### 3. Cross-Site Scripting (XSS)\n\nSee [security-baseline § Output & Rendering](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#output--rendering).\n\n```typescript\n\u002F\u002F BAD: Rendering user input as HTML\nelement.innerHTML = userInput;\n\n\u002F\u002F GOOD: Use framework auto-escaping (React does this by default)\nreturn \u003Cdiv>{userInput}\u003C\u002Fdiv>;\n\n\u002F\u002F If you MUST render HTML, sanitize first\nimport DOMPurify from 'dompurify';\nconst clean = DOMPurify.sanitize(userInput);\n```\n\n### 4. Broken Access Control\n\nSee [security-baseline § Authorization](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#authorization).\n\n```typescript\napp.patch('\u002Fapi\u002Ftasks\u002F:id', authenticate, async (req, res) => {\n  const task = await taskService.findById(req.params.id);\n\n  if (task.ownerId !== req.user.id) {\n    return res.status(403).json({\n      error: {\n        code: 'FORBIDDEN',\n        message: 'Not authorized to modify this task',\n      },\n    });\n  }\n\n  const updated = await taskService.update(req.params.id, req.body);\n  return res.json(updated);\n});\n```\n\n### 5. Security Misconfiguration\n\nSee [security-baseline § Transport & Headers](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#transport--headers).\n\n```typescript\nimport helmet from 'helmet';\napp.use(helmet());\n\napp.use(\n  helmet.contentSecurityPolicy({\n    directives: {\n      defaultSrc: [\"'self'\"],\n      scriptSrc: [\"'self'\"],\n      styleSrc: [\"'self'\", \"'unsafe-inline'\"],\n      imgSrc: [\"'self'\", 'data:', 'https:'],\n      connectSrc: [\"'self'\"],\n    },\n  }),\n);\n\napp.use(\n  cors({\n    origin: process.env.ALLOWED_ORIGINS?.split(',') || 'http:\u002F\u002Flocalhost:3000',\n    credentials: true,\n  }),\n);\n```\n\n### 6. Sensitive Data Exposure\n\nSee [security-baseline § Output & Rendering](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#output--rendering)\nand [§ Secrets Management](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#secrets-management).\n\n```typescript\nfunction sanitizeUser(user: UserRecord): PublicUser {\n  const { passwordHash, resetToken, ...publicFields } = user;\n  return publicFields;\n}\n\nconst API_KEY = process.env.STRIPE_API_KEY;\nif (!API_KEY) throw new Error('STRIPE_API_KEY not configured');\n```\n\n## Input Validation Patterns\n\nSee [security-baseline § Input Validation](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#input-validation).\n\n### Schema Validation at Boundaries\n\n```typescript\nimport { z } from 'zod';\n\nconst CreateTaskSchema = z.object({\n  title: z.string().min(1).max(200).trim(),\n  description: z.string().max(2000).optional(),\n  priority: z.enum(['low', 'medium', 'high']).default('medium'),\n  dueDate: z.string().datetime().optional(),\n});\n\napp.post('\u002Fapi\u002Ftasks', async (req, res) => {\n  const result = CreateTaskSchema.safeParse(req.body);\n  if (!result.success) {\n    return res.status(422).json({\n      error: {\n        code: 'VALIDATION_ERROR',\n        message: 'Invalid input',\n        details: result.error.flatten(),\n      },\n    });\n  }\n  const task = await taskService.create(result.data);\n  return res.status(201).json(task);\n});\n```\n\n### File Upload Safety\n\n```typescript\nconst ALLOWED_TYPES = ['image\u002Fjpeg', 'image\u002Fpng', 'image\u002Fwebp'];\nconst MAX_SIZE = 5 * 1024 * 1024; \u002F\u002F 5MB\n\nfunction validateUpload(file: UploadedFile) {\n  if (!ALLOWED_TYPES.includes(file.mimetype)) {\n    throw new ValidationError('File type not allowed');\n  }\n  if (file.size > MAX_SIZE) {\n    throw new ValidationError('File too large (max 5MB)');\n  }\n  \u002F\u002F Don't trust the file extension — check magic bytes if critical\n}\n```\n\n## Triaging npm audit Results\n\nThe MUST is in [security-baseline § Dependency Hygiene](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#dependency-hygiene).\nThis decision tree shows how to prioritize:\n\n```text\nnpm audit reports a vulnerability\n├── Severity: critical or high\n│   ├── Is the vulnerable code reachable in your app?\n│   │   ├── YES --> Fix immediately (update, patch, or replace the dependency)\n│   │   └── NO (dev-only dep, unused code path) --> Fix soon, but not a blocker\n│   └── Is a fix available?\n│       ├── YES --> Update to the patched version\n│       └── NO --> Check for workarounds, consider replacing the dependency, or add to allowlist with a review date\n├── Severity: moderate\n│   ├── Reachable in production? --> Fix in the next release cycle\n│   └── Dev-only? --> Fix when convenient, track in backlog\n└── Severity: low\n    └── Track and fix during regular dependency updates\n```\n\n**Key questions:**\n\n- Is the vulnerable function actually called in your code path?\n- Is the dependency a runtime dependency or dev-only?\n- Is the vulnerability exploitable given your deployment context (e.g., a\n  server-side vulnerability in a client-only app)?\n\nWhen you defer a fix, document the reason and set a review date.\n\n## Rate Limiting\n\n```typescript\nimport rateLimit from 'express-rate-limit';\n\n\u002F\u002F General API rate limit\napp.use(\n  '\u002Fapi\u002F',\n  rateLimit({\n    windowMs: 15 * 60 * 1000,\n    max: 100,\n    standardHeaders: true,\n    legacyHeaders: false,\n  }),\n);\n\n\u002F\u002F Stricter limit for auth endpoints (the rule MUSTs rate-limiting on auth)\napp.use(\n  '\u002Fapi\u002Fauth\u002F',\n  rateLimit({\n    windowMs: 15 * 60 * 1000,\n    max: 10,\n  }),\n);\n```\n\n## Secrets Management Layout\n\nSee [security-baseline § Secrets Management](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md#secrets-management).\n\n```text\n.env files:\n  ├── .env.example  → Committed (template with placeholder values)\n  ├── .env          → NOT committed (contains real secrets)\n  └── .env.local    → NOT committed (local overrides)\n\n.gitignore must include:\n  .env\n  .env.local\n  .env.*.local\n  *.pem\n  *.key\n```\n\n**Always check before committing:**\n\n```bash\n# Check for accidentally staged secrets\ngit diff --cached | grep -i \"password\\|secret\\|api_key\\|token\"\n```\n\n## Security Review Checklist\n\nUse this when reviewing your own change before requesting human review. Each\nitem maps to a section in\n[`security-baseline.md`](..\u002F..\u002F..\u002Frules\u002Fsecurity-baseline.md).\n\n```markdown\n### Authentication\n\n- [ ] Passwords hashed with bcrypt\u002Fscrypt\u002Fargon2 (salt rounds ≥ 12)\n- [ ] Session tokens are httpOnly, secure, sameSite\n- [ ] Login has rate limiting\n- [ ] Password reset tokens expire\n\n### Authorization\n\n- [ ] Every endpoint checks user permissions\n- [ ] Users can only access their own resources\n- [ ] Admin actions require admin role verification\n\n### Input\n\n- [ ] All user input validated at the boundary\n- [ ] SQL queries are parameterized\n- [ ] HTML output is encoded\u002Fescaped\n\n### Data\n\n- [ ] No secrets in code or version control\n- [ ] Sensitive fields excluded from API responses\n- [ ] PII encrypted at rest (if applicable)\n\n### Infrastructure\n\n- [ ] Security headers configured (CSP, HSTS, etc.)\n- [ ] CORS restricted to known origins\n- [ ] Dependencies audited for vulnerabilities\n- [ ] Error messages don't expose internals\n```\n\n## Common Rationalizations\n\n| Rationalization                                     | Reality                                                                         |\n| --------------------------------------------------- | ------------------------------------------------------------------------------- |\n| \"This is an internal tool, security doesn't matter\" | Internal tools get compromised. Attackers target the weakest link.              |\n| \"We'll add security later\"                          | Security retrofitting is 10x harder than building it in. Add it now.            |\n| \"No one would try to exploit this\"                  | Automated scanners will find it. Security by obscurity is not security.         |\n| \"The framework handles security\"                    | Frameworks provide tools, not guarantees. You still need to use them correctly. |\n| \"It's just a prototype\"                             | Prototypes become production. Security habits from day one.                     |\n\n## Red Flags\n\n- User input passed directly to database queries, shell commands, or HTML\n  rendering\n- Secrets in source code or commit history\n- API endpoints without authentication or authorization checks\n- Missing CORS configuration or wildcard (`*`) origins\n- No rate limiting on authentication endpoints\n- Stack traces or internal errors exposed to users\n- Dependencies with known critical vulnerabilities\n\n## Verification\n\nAfter implementing security-relevant code, confirm against the rule:\n\n- [ ] `npm audit` shows no critical or high vulnerabilities\n- [ ] No secrets in source code or git history\n- [ ] All user input validated at system boundaries\n- [ ] Authentication and authorization checked on every protected endpoint\n- [ ] Security headers present in response (check with browser DevTools)\n- [ ] Error responses don't expose internal details\n- [ ] Rate limiting active on auth endpoints\n",{"name":5,"description":7},"main","22b1847659cc2a98f4fb8c24858f2199d91fda66",".agents\u002Fskills\u002Fcore\u002Fsecurity-and-hardening","https:\u002F\u002Fgithub.com\u002Fchrisbarrantes\u002Fmandrel","https:\u002F\u002Fgithub.com\u002Fchrisbarrantes","2026-05-27 08:16:47",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add chrisbarrantes\u002Fmandrel --skill security-and-hardening",{"tool":36,"command":37},"bunx","bunx skills add chrisbarrantes\u002Fmandrel --skill security-and-hardening",{"tool":39,"command":40},"pnpm","pnpm dlx skills add chrisbarrantes\u002Fmandrel --skill security-and-hardening","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fchrisbarrantes\u002Fmandrel\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fcore\u002Fsecurity-and-hardening\u002FSKILL.md",true,[],[45,52,59,66,73,80],{"skillNo":46,"name":47,"nameZh":6,"description":48,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":49,"categories":50,"keywords":51,"publishedAt":19},"01M75171YZD373TXY5ZWJNXGS9","no-capsule-skill","Fixture without a Policy Capsule section.","https:\u002F\u002Fgithub.com\u002Fchrisbarrantes\u002Fmandrel\u002Fblob\u002Fmain\u002Ftests\u002Forchestration\u002Ffixtures\u002Fskill-capsule\u002Fno-capsule-skill\u002FSKILL.md",[],[],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M7516ZA88ESAAY3JWXBNA56K","backend-security-patterns","Combined backend protocols for authentication (Clerk JWT verification) and PII-safe observability. Use when handling auth on the server, verifying Clerk webhooks via `svix`, scoping metadata via `publicMetadata`\u002F `privateMetadata`, or sanitizing logs to keep emails, tokens, and request bodies out of telemetry.","https:\u002F\u002Fgithub.com\u002Fchrisbarrantes\u002Fmandrel\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fstack\u002Fsecurity\u002Fbackend-security-patterns\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M7516WFQMKD2NGFMDNFG6C4A","vitest","Writes fast, isolated unit and integration tests with Vitest. Use when each test must run on file-save without shared state — `vi.mock()` for external deps, `vi.spyOn()` for call monitoring, AAA structure, and edge-case coverage for null\u002Fundefined\u002Fboundary inputs.","https:\u002F\u002Fgithub.com\u002Fchrisbarrantes\u002Fmandrel\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fstack\u002Fqa\u002Fvitest\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7516T8FX7B0B0D510EE2FAP","playwright","Robust E2E browser testing with Playwright. Use when writing browser-driven tests — leverage auto-waiting (no `waitForTimeout`), prefer user-visible locators (`getByRole`, `getByText`, `getByLabel`) over CSS\u002FXPath, reuse `storageState` for auth, and enable trace-on-first-retry for CI debugging.","https:\u002F\u002Fgithub.com\u002Fchrisbarrantes\u002Fmandrel\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fstack\u002Fqa\u002Fplaywright\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7516PHY868BJXHHZJ0FRYSX","playwright-bdd","Wires Gherkin `.feature` files to Playwright via the `playwright-bdd` library. Use when running BDD scenarios on a Playwright runtime — pairs with the `gherkin-authoring` skill (scenario prose) and the `playwright` skill (browser conventions). Drives execution by tag expression with trace-first debugging and Playwright-native sharding.","https:\u002F\u002Fgithub.com\u002Fchrisbarrantes\u002Fmandrel\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fstack\u002Fqa\u002Fplaywright-bdd\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7516KEGSBBFJXRZWYBKYM4P","lighthouse-baseline","Codifies the capture-and-check baseline pattern for long-running quality signals (Lighthouse scores, bundle size, p95 latency, runtime memory). Use when wiring a new metric that needs a baseline file, paired :capture \u002F :check npm scripts, a tolerance-bounded gate, and a weekly refresh cadence — the goal is a hard CI signal that ratchets only with intent.","https:\u002F\u002Fgithub.com\u002Fchrisbarrantes\u002Fmandrel\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fstack\u002Fqa\u002Flighthouse-baseline\u002FSKILL.md",[],[]]