[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7F6WHKNP59N2DKRHDCPYVZV":3,"skill-same:01M7F6WHKNP59N2DKRHDCPYVZV":58},{"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},"01M7F6WHKNP59N2DKRHDCPYVZV","security",null,"Web application security best practices based on OWASP Top 10:2025. Use when reviewing code for vulnerabilities, implementing auth\u002Fauthorization, handling user input, working with file uploads, managing secrets, or building API endpoints. Covers React, Express, MongoDB, and JWT security.","yrazub\u002Fgen-bin","yrazub","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F3244321?v=4","01M7F6TT4HKB003QGEXJTY5G5V","Iurii Razubaiev","01M7F6TT55ZA0E2G698HA8T0E9",0,"MIT","https:\u002F\u002Fgithub.com\u002Fyrazub\u002Fgen-bin\u002Fblob\u002Fmain\u002Fplugins\u002Fengineering-paved-path\u002Fskills\u002Fsecurity\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: security\ndescription: \"Web application security best practices based on OWASP Top 10:2025. Use when reviewing code for vulnerabilities, implementing auth\u002Fauthorization, handling user input, working with file uploads, managing secrets, or building API endpoints. Covers React, Express, MongoDB, and JWT security.\"\n---\n\n# Security Best Practices — OWASP Top 10:2025\n\nSecurity guidance for React + Express + MongoDB + JWT stacks. See `examples.md` for unsafe\u002Fsafe code pairs, `checklists.md` for quick checklists, `references.md` for all sources.\n\n---\n\n## Core Philosophy — Confidence-Based Review\n\nBefore flagging any issue, **trace the data flow** and confirm the input source.\n\n| Confidence | Criteria | Action |\n|------------|----------|--------|\n| **HIGH** | Vulnerable pattern + attacker-controlled input confirmed | **Report** with file, line, exploit, and fix |\n| **MEDIUM** | Vulnerable pattern, input source unclear | **Note** for manual verification |\n| **LOW** | Theoretical \u002F best-practice deviation | **Do not report** — mention only if asked |\n\n**Do NOT flag**: test files, dead code, server-controlled values (env vars, config constants), framework-mitigated patterns (React JSX escaping, Mongoose parameterized queries), development-only code gated by `NODE_ENV`.\n\n> **Golden rule**: `fetch(process.env.API_URL)` = safe. `fetch(req.query.url)` = vulnerable. Always ask: **\"Can an attacker control this value?\"**\n\n---\n\n## OWASP Top 10:2025\n\n| # | Category | Key Risk in This Stack |\n|---|----------|----------------------|\n| A01 | **Broken Access Control** | Missing auth middleware, IDOR, no ownership checks |\n| A02 | **Security Misconfiguration** | Helmet disabled, CORS wildcard, stack traces in prod |\n| A03 | **Supply Chain Failures** | Compromised npm packages, typosquatting |\n| A04 | **Cryptographic Failures** | Weak JWT secret, low bcrypt cost, hardcoded secrets |\n| A05 | **Injection** | MongoDB operator injection, XSS, command injection |\n| A06 | **Insecure Design** | Missing rate limiting, no threat model |\n| A07 | **Authentication Failures** | jwt.decode() instead of verify(), brute force |\n| A08 | **Integrity Failures** | Mass assignment via req.body spread, unvalidated uploads |\n| A09 | **Logging Failures** | Passwords in logs, missing auth event audit trail |\n| A10 | **Exceptional Conditions** | Fail-open auth, stack trace leaks, missing async error handling |\n\n---\n\n## A01 — Broken Access Control\n\n- **Deny by default** — every route is protected unless explicitly public\n- Apply `auth` middleware as a **barrier** (via `router.use(auth)`) rather than per-route to prevent omissions\n- **Always check ownership** on update\u002Fdelete — being authenticated does not mean authorized for all resources\n- Compare `resource.author.toString() === req.user.userId` plus admin role escape hatch\n- React route guards are UX only — **server must enforce all access control**\n- Test both horizontal (user A → user B's data) and vertical (author → admin endpoints) escalation\n\n---\n\n## A02 — Security Misconfiguration\n\n- **Helmet**: Enable with `crossOriginResourcePolicy: 'cross-origin'` for uploads. If CSP disabled, implement custom CSP restricting `script-src` to `'self'`\n- **CORS**: Explicit origin allowlist with `credentials: true`. Never `origin: '*'` or `origin: true` with credentials\n- **Error handler**: Generic message in production, stack traces only when `NODE_ENV === 'development'`\n- **Vite env vars**: `VITE_*` prefixed vars are **public in the client bundle** — never put secrets there\n- **MongoDB**: Require auth + TLS in production, never expose port 27017 to internet, use `serverSelectionTimeoutMS`\n- **Defaults**: Change seed credentials, disable debug middleware in production\n\n---\n\n## A03 — Supply Chain Failures\n\n- Run `npm audit` before every release. Commit `package-lock.json` always.\n- Pin exact versions for security-sensitive packages\n- Before adding a dependency: check CVEs, maintenance activity (\u003C 6 months), download count (> 10K\u002Fweek), scope of access (network\u002Ffs\u002Fenv)\n- Watch for typosquatting (`expres` vs `express`)\n- Vite plugins run with full Node.js access during build — use only well-known publishers\n\n---\n\n## A04 — Cryptographic Failures\n\n- **Passwords**: bcrypt with salt rounds >= 10 (never MD5, SHA-1\u002F256, or plain text). Preferred: Argon2id > bcrypt > scrypt\n- **JWT secret**: Minimum 256-bit (32 bytes) cryptographically random, from `process.env.JWT_SECRET`\n- **JWT signing**: Explicitly set `algorithm: 'HS256'` and `expiresIn`. Never allow `none` algorithm\n- **JWT verification**: Always `jwt.verify()`, never `jwt.decode()` (decode doesn't check signature)\n- **JWT payload**: Never store sensitive data (it's base64-encoded, not encrypted)\n- **Transit**: HTTPS in production, `Strict-Transport-Security` header via Helmet\n- **At rest**: Encrypt sensitive fields if storing PII. Never store raw credentials in MongoDB\n\n---\n\n## A05 — Injection\n\n### MongoDB NoSQL Injection\n- **Cast input types explicitly**: `String(req.body.email)` — neutralizes operator objects like `{ \"$gt\": \"\" }`\n- Never put user input in `$where`, `$expr`, or `$function` (server-side JS execution)\n- Never construct regex from user input without escaping (`str.replace(\u002F[.*+?^${}()|[\\]\\\\]\u002Fg, '\\\\$&')`)\n- Use Mongoose strict schemas with type definitions. Consider `mongo-sanitize` to strip `$` keys\n\n### Cross-Site Scripting (XSS)\n- React auto-escapes JSX — that's your default safety net\n- **Never** use `dangerouslySetInnerHTML` without DOMPurify sanitization (allowlist tags\u002Fattributes)\n- Validate URLs before `href`\u002F`src` — reject `javascript:` protocol, allow only `http:`\u002F`https:`\n- Blog content and AI-generated content are high-risk for stored XSS — sanitize on input AND output\n- Set CSP headers to mitigate any XSS that slips through\n\n### Command Injection\n- Never use `exec()` or `spawn({ shell: true })` with user input\n- Use `execFile()` which passes arguments directly without shell interpretation\n\n---\n\n## A06 — Insecure Design\n\n**Rate limiting strategy:**\n\n| Endpoint | Limit | Window |\n|----------|-------|--------|\n| Login | 5 req | 15 min |\n| Comments | 5 req | 1 min |\n| AI generation | 3 req | 1 min |\n| File upload | 10 req | 1 min |\n| General API | 100 req | 1 min |\n\n- **AI content generation**: Sanitize AI output before storing (XSS risk), validate prompt length, set request timeouts, never expose API keys to client, log prompts for audit\n- **Comments**: Rate limit + sanitize + moderation (`isApproved` flag)\n\n---\n\n## A07 — Authentication Failures\n\n- **Login**: Find user by email with `isActive: true`, compare with bcrypt, return generic \"Invalid credentials\" for both wrong email and wrong password (prevents enumeration)\n- **JWT claims**: `{ userId, email, name, role }` — minimum viable\n- **Token extraction**: Support `Bearer \u003Ctoken>` from Authorization header\n- **Auth middleware must be fail-closed**: `next()` only called on successful `jwt.verify()`. Missing `return` before error response = fail-open vulnerability\n- **Rate limit login**: `loginLimiter` on login endpoint (5 attempts \u002F 15 min)\n- **Password model**: Hash in `pre('save')` hook only if modified, `comparePassword` instance method, `toJSON` strips password from all responses\n- Consider account lockout, progressive delays, CAPTCHA after N failures\n\n---\n\n## A08 — Software and Data Integrity\n\n- **Mass assignment prevention**: Destructure only expected fields from `req.body` — never `Model.create(req.body)` (attacker can set `role: 'admin'`)\n- **Mongoose schemas**: Use `enum` for fixed values, `required` on mandatory fields, `minlength`\u002F`maxlength`, `strict: true` (default)\n- **File upload integrity**: MIME type allowlist, check magic bytes for high-security. MIME types can be spoofed\n- **CSP**: Restrict `script-src`, `frame-ancestors 'none'`, `object-src 'none'`\n\n---\n\n## A09 — Logging and Alerting\n\n**Log these**: Login success\u002Ffailure, token rejection, admin actions, file uploads, rate limit hits, 5xx errors, 403 denials\n**Never log**: Passwords, JWT tokens, API keys, credit cards, SSNs\n\n- Redact sensitive fields (`password`, `token`, `secret`, `authorization`) before logging — replace with `***`\n- Use structured JSON logging for production (searchable, integrates with aggregation)\n- Log auth events with userId, IP, timestamp, and action\n\n---\n\n## A10 — Exceptional Conditions\n\n- **Fail-closed**: Errors must deny access, not grant it. `catch` blocks must `return` error response before any `next()` call\n- **Global error handler**: Must have 4 params `(err, req, res, next)`. Return generic message in production.\n- **Async wrapper**: Use `asyncHandler` to catch Promise rejections — eliminates need for try-catch in every controller\n- **DB connection**: `serverSelectionTimeoutMS: 5000`, `process.exit(1)` on connection failure\n- **404 handler**: Catch-all for unmatched routes (`app.use('*', ...)`)\n\n---\n\n## File Upload Security\n\n- **MIME allowlist**: `['image\u002Fjpeg', 'image\u002Fpng', 'image\u002Fgif', 'image\u002Fwebp']` — whitelist, not blacklist\n- **Size limit**: `5 * 1024 * 1024` (5MB) via `multer.limits`\n- **Filename**: Server-generated (`blog-{timestamp}-{random9digits}.{ext}`) — never user-provided\n- **Path traversal**: Use `path.basename()` to strip directory components. Validate `path.resolve()` starts with upload directory before deletion\n- **Cleanup**: Delete uploaded file when resource is deleted, validate path is within uploads dir\n- **Serving**: `crossOriginResourcePolicy: 'cross-origin'` for static files, no directory listing\n\n---\n\n## Secret Detection\n\nScan for these patterns in all code and config:\n\n| Type | Pattern |\n|------|---------|\n| AWS Key | `AKIA[0-9A-Z]{16}` |\n| Google API | `AIza[0-9A-Za-z_-]{35}` |\n| JWT\u002FGeneric | `(secret\\|key\\|token\\|password)\\s*[:=]\\s*['\"][^'\"]{8,}` |\n| MongoDB URI | `mongodb(\\+srv)?:\u002F\u002F[^:]+:[^@]+@` |\n| Private Key | `-----BEGIN .* PRIVATE KEY-----` |\n| GitHub Token | `gh[ps]_[A-Za-z0-9]{36,}` |\n| npm Token | `npm_[A-Za-z0-9]{36}` |\n| Slack Token | `xox[bpsa]-[0-9a-zA-Z-]+` |\n\n**Never commit**: `.env`, `.env.local`, `.env.production`, `logs\u002F`, `uploads\u002F`\n\n---\n\n## Agentic AI Security (OWASP 2026)\n\nRelevant to AI content generation features (Gemini API):\n\n- **ASI01 Goal Hijacking**: Sanitize prompt input, set max length, strip control characters\n- **ASI02 Tool Misuse**: AI should not have access to system tools without explicit scoping\n- **ASI03 Identity Abuse**: API keys server-side only, short-lived if possible\n- **ASI05 Code Execution**: Never execute AI-generated code without review\n- **ASI09 Trust Exploitation**: Label AI-generated content, validate before storing\n- Sanitize AI output before storing — it could contain XSS, malicious links, or script tags\n\n---\n\n## Framework Security Quirks\n\n### JavaScript\u002FNode.js\n- Prototype pollution via `__proto__`\u002F`constructor.prototype` — validate object keys\n- `JSON.parse()` throws on malformed input — always wrap in try-catch\n- `RegExp(userInput)` enables ReDoS — escape special characters\n- `path.join()` with user input allows traversal — use `path.basename()` first\n- `setTimeout(string)` is implicit eval — always pass a function\n\n### MongoDB\u002FMongoose\n- Query operator injection via JSON body `{ password: { \"$gt\": \"\" } }` — cast to `String()`\n- `$where` clause = server-side JS execution — never use with user input\n- Unbounded queries exhaust memory — always `.limit()` and `.skip()`\n- `strict: false` accepts arbitrary fields — keep default `strict: true`\n\n### React\n- `dangerouslySetInnerHTML` bypasses escaping — require DOMPurify\n- `href={userUrl}` allows `javascript:` XSS — validate protocol\n- `VITE_*` env vars are public — never prefix secrets\n\n### Express\n- Middleware ordering matters — auth bypass if `router.use(auth)` placed after unprotected routes\n- `req.query` values are always strings — validate and cast types\n- Error handler must have exactly 4 params — missing `next` breaks error handling\n- Set `trust proxy` behind reverse proxy — otherwise rate limiter gets wrong IP\n\n---\n\n## Security Review Process\n\n1. **Detect context** — API endpoint, auth logic, DB query, file handling, frontend, config, or dependency change\n2. **Load relevant rules** — Only the OWASP categories that apply to this context\n3. **Trace data flow** — Where does the input come from? Is it attacker-controlled?\n4. **Check upstream controls** — Middleware, framework defaults, validation already applied?\n5. **Verify exploitability** — Can an attacker actually reach and control this?\n6. **Report HIGH confidence only** — Include file, line, exploit scenario, specific fix\n\n---\n\n## Severity Classification\n\n| Severity | Criteria | Stack Examples |\n|----------|----------|----------------|\n| **CRITICAL** | Direct exploit, no auth required | NoSQL injection auth bypass, hardcoded prod secrets, missing auth on admin endpoint, RCE |\n| **HIGH** | Exploitable with conditions | Stored XSS in blog content, IDOR on delete, JWT with weak secret, passwords in logs |\n| **MEDIUM** | Specific conditions, limited impact | Missing rate limiter, CORS misconfiguration, verbose prod errors, missing input validation |\n| **LOW** | Defense-in-depth | Low bcrypt cost, missing security event logging, sequential ObjectId exposure |\n\n---\n\n## ASVS 5.0 Quick Reference\n\n**Level 1 (All Apps)**: 12+ char passwords, breached list check, login rate limiting, 128+ bit session entropy, HTTPS, server-side validation, generic error messages\n\n**Level 2 (Sensitive)**: + MFA for sensitive ops, crypto key management, comprehensive security logging, schema-based input validation, CSRF protection\n\n**Level 3 (Critical)**: + HSM key storage, documented threat model, anomaly detection, penetration testing, supply chain verification\n","# Security Best Practices — OWASP Top 10:2025\n\nSecurity guidance for React + Express + MongoDB + JWT stacks. See `examples.md` for unsafe\u002Fsafe code pairs, `checklists.md` for quick checklists, `references.md` for all sources.\n\n---\n\n## Core Philosophy — Confidence-Based Review\n\nBefore flagging any issue, **trace the data flow** and confirm the input source.\n\n| Confidence | Criteria | Action |\n|------------|----------|--------|\n| **HIGH** | Vulnerable pattern + attacker-controlled input confirmed | **Report** with file, line, exploit, and fix |\n| **MEDIUM** | Vulnerable pattern, input source unclear | **Note** for manual verification |\n| **LOW** | Theoretical \u002F best-practice deviation | **Do not report** — mention only if asked |\n\n**Do NOT flag**: test files, dead code, server-controlled values (env vars, config constants), framework-mitigated patterns (React JSX escaping, Mongoose parameterized queries), development-only code gated by `NODE_ENV`.\n\n> **Golden rule**: `fetch(process.env.API_URL)` = safe. `fetch(req.query.url)` = vulnerable. Always ask: **\"Can an attacker control this value?\"**\n\n---\n\n## OWASP Top 10:2025\n\n| # | Category | Key Risk in This Stack |\n|---|----------|----------------------|\n| A01 | **Broken Access Control** | Missing auth middleware, IDOR, no ownership checks |\n| A02 | **Security Misconfiguration** | Helmet disabled, CORS wildcard, stack traces in prod |\n| A03 | **Supply Chain Failures** | Compromised npm packages, typosquatting |\n| A04 | **Cryptographic Failures** | Weak JWT secret, low bcrypt cost, hardcoded secrets |\n| A05 | **Injection** | MongoDB operator injection, XSS, command injection |\n| A06 | **Insecure Design** | Missing rate limiting, no threat model |\n| A07 | **Authentication Failures** | jwt.decode() instead of verify(), brute force |\n| A08 | **Integrity Failures** | Mass assignment via req.body spread, unvalidated uploads |\n| A09 | **Logging Failures** | Passwords in logs, missing auth event audit trail |\n| A10 | **Exceptional Conditions** | Fail-open auth, stack trace leaks, missing async error handling |\n\n---\n\n## A01 — Broken Access Control\n\n- **Deny by default** — every route is protected unless explicitly public\n- Apply `auth` middleware as a **barrier** (via `router.use(auth)`) rather than per-route to prevent omissions\n- **Always check ownership** on update\u002Fdelete — being authenticated does not mean authorized for all resources\n- Compare `resource.author.toString() === req.user.userId` plus admin role escape hatch\n- React route guards are UX only — **server must enforce all access control**\n- Test both horizontal (user A → user B's data) and vertical (author → admin endpoints) escalation\n\n---\n\n## A02 — Security Misconfiguration\n\n- **Helmet**: Enable with `crossOriginResourcePolicy: 'cross-origin'` for uploads. If CSP disabled, implement custom CSP restricting `script-src` to `'self'`\n- **CORS**: Explicit origin allowlist with `credentials: true`. Never `origin: '*'` or `origin: true` with credentials\n- **Error handler**: Generic message in production, stack traces only when `NODE_ENV === 'development'`\n- **Vite env vars**: `VITE_*` prefixed vars are **public in the client bundle** — never put secrets there\n- **MongoDB**: Require auth + TLS in production, never expose port 27017 to internet, use `serverSelectionTimeoutMS`\n- **Defaults**: Change seed credentials, disable debug middleware in production\n\n---\n\n## A03 — Supply Chain Failures\n\n- Run `npm audit` before every release. Commit `package-lock.json` always.\n- Pin exact versions for security-sensitive packages\n- Before adding a dependency: check CVEs, maintenance activity (\u003C 6 months), download count (> 10K\u002Fweek), scope of access (network\u002Ffs\u002Fenv)\n- Watch for typosquatting (`expres` vs `express`)\n- Vite plugins run with full Node.js access during build — use only well-known publishers\n\n---\n\n## A04 — Cryptographic Failures\n\n- **Passwords**: bcrypt with salt rounds >= 10 (never MD5, SHA-1\u002F256, or plain text). Preferred: Argon2id > bcrypt > scrypt\n- **JWT secret**: Minimum 256-bit (32 bytes) cryptographically random, from `process.env.JWT_SECRET`\n- **JWT signing**: Explicitly set `algorithm: 'HS256'` and `expiresIn`. Never allow `none` algorithm\n- **JWT verification**: Always `jwt.verify()`, never `jwt.decode()` (decode doesn't check signature)\n- **JWT payload**: Never store sensitive data (it's base64-encoded, not encrypted)\n- **Transit**: HTTPS in production, `Strict-Transport-Security` header via Helmet\n- **At rest**: Encrypt sensitive fields if storing PII. Never store raw credentials in MongoDB\n\n---\n\n## A05 — Injection\n\n### MongoDB NoSQL Injection\n- **Cast input types explicitly**: `String(req.body.email)` — neutralizes operator objects like `{ \"$gt\": \"\" }`\n- Never put user input in `$where`, `$expr`, or `$function` (server-side JS execution)\n- Never construct regex from user input without escaping (`str.replace(\u002F[.*+?^${}()|[\\]\\\\]\u002Fg, '\\\\$&')`)\n- Use Mongoose strict schemas with type definitions. Consider `mongo-sanitize` to strip `$` keys\n\n### Cross-Site Scripting (XSS)\n- React auto-escapes JSX — that's your default safety net\n- **Never** use `dangerouslySetInnerHTML` without DOMPurify sanitization (allowlist tags\u002Fattributes)\n- Validate URLs before `href`\u002F`src` — reject `javascript:` protocol, allow only `http:`\u002F`https:`\n- Blog content and AI-generated content are high-risk for stored XSS — sanitize on input AND output\n- Set CSP headers to mitigate any XSS that slips through\n\n### Command Injection\n- Never use `exec()` or `spawn({ shell: true })` with user input\n- Use `execFile()` which passes arguments directly without shell interpretation\n\n---\n\n## A06 — Insecure Design\n\n**Rate limiting strategy:**\n\n| Endpoint | Limit | Window |\n|----------|-------|--------|\n| Login | 5 req | 15 min |\n| Comments | 5 req | 1 min |\n| AI generation | 3 req | 1 min |\n| File upload | 10 req | 1 min |\n| General API | 100 req | 1 min |\n\n- **AI content generation**: Sanitize AI output before storing (XSS risk), validate prompt length, set request timeouts, never expose API keys to client, log prompts for audit\n- **Comments**: Rate limit + sanitize + moderation (`isApproved` flag)\n\n---\n\n## A07 — Authentication Failures\n\n- **Login**: Find user by email with `isActive: true`, compare with bcrypt, return generic \"Invalid credentials\" for both wrong email and wrong password (prevents enumeration)\n- **JWT claims**: `{ userId, email, name, role }` — minimum viable\n- **Token extraction**: Support `Bearer \u003Ctoken>` from Authorization header\n- **Auth middleware must be fail-closed**: `next()` only called on successful `jwt.verify()`. Missing `return` before error response = fail-open vulnerability\n- **Rate limit login**: `loginLimiter` on login endpoint (5 attempts \u002F 15 min)\n- **Password model**: Hash in `pre('save')` hook only if modified, `comparePassword` instance method, `toJSON` strips password from all responses\n- Consider account lockout, progressive delays, CAPTCHA after N failures\n\n---\n\n## A08 — Software and Data Integrity\n\n- **Mass assignment prevention**: Destructure only expected fields from `req.body` — never `Model.create(req.body)` (attacker can set `role: 'admin'`)\n- **Mongoose schemas**: Use `enum` for fixed values, `required` on mandatory fields, `minlength`\u002F`maxlength`, `strict: true` (default)\n- **File upload integrity**: MIME type allowlist, check magic bytes for high-security. MIME types can be spoofed\n- **CSP**: Restrict `script-src`, `frame-ancestors 'none'`, `object-src 'none'`\n\n---\n\n## A09 — Logging and Alerting\n\n**Log these**: Login success\u002Ffailure, token rejection, admin actions, file uploads, rate limit hits, 5xx errors, 403 denials\n**Never log**: Passwords, JWT tokens, API keys, credit cards, SSNs\n\n- Redact sensitive fields (`password`, `token`, `secret`, `authorization`) before logging — replace with `***`\n- Use structured JSON logging for production (searchable, integrates with aggregation)\n- Log auth events with userId, IP, timestamp, and action\n\n---\n\n## A10 — Exceptional Conditions\n\n- **Fail-closed**: Errors must deny access, not grant it. `catch` blocks must `return` error response before any `next()` call\n- **Global error handler**: Must have 4 params `(err, req, res, next)`. Return generic message in production.\n- **Async wrapper**: Use `asyncHandler` to catch Promise rejections — eliminates need for try-catch in every controller\n- **DB connection**: `serverSelectionTimeoutMS: 5000`, `process.exit(1)` on connection failure\n- **404 handler**: Catch-all for unmatched routes (`app.use('*', ...)`)\n\n---\n\n## File Upload Security\n\n- **MIME allowlist**: `['image\u002Fjpeg', 'image\u002Fpng', 'image\u002Fgif', 'image\u002Fwebp']` — whitelist, not blacklist\n- **Size limit**: `5 * 1024 * 1024` (5MB) via `multer.limits`\n- **Filename**: Server-generated (`blog-{timestamp}-{random9digits}.{ext}`) — never user-provided\n- **Path traversal**: Use `path.basename()` to strip directory components. Validate `path.resolve()` starts with upload directory before deletion\n- **Cleanup**: Delete uploaded file when resource is deleted, validate path is within uploads dir\n- **Serving**: `crossOriginResourcePolicy: 'cross-origin'` for static files, no directory listing\n\n---\n\n## Secret Detection\n\nScan for these patterns in all code and config:\n\n| Type | Pattern |\n|------|---------|\n| AWS Key | `AKIA[0-9A-Z]{16}` |\n| Google API | `AIza[0-9A-Za-z_-]{35}` |\n| JWT\u002FGeneric | `(secret\\|key\\|token\\|password)\\s*[:=]\\s*['\"][^'\"]{8,}` |\n| MongoDB URI | `mongodb(\\+srv)?:\u002F\u002F[^:]+:[^@]+@` |\n| Private Key | `-----BEGIN .* PRIVATE KEY-----` |\n| GitHub Token | `gh[ps]_[A-Za-z0-9]{36,}` |\n| npm Token | `npm_[A-Za-z0-9]{36}` |\n| Slack Token | `xox[bpsa]-[0-9a-zA-Z-]+` |\n\n**Never commit**: `.env`, `.env.local`, `.env.production`, `logs\u002F`, `uploads\u002F`\n\n---\n\n## Agentic AI Security (OWASP 2026)\n\nRelevant to AI content generation features (Gemini API):\n\n- **ASI01 Goal Hijacking**: Sanitize prompt input, set max length, strip control characters\n- **ASI02 Tool Misuse**: AI should not have access to system tools without explicit scoping\n- **ASI03 Identity Abuse**: API keys server-side only, short-lived if possible\n- **ASI05 Code Execution**: Never execute AI-generated code without review\n- **ASI09 Trust Exploitation**: Label AI-generated content, validate before storing\n- Sanitize AI output before storing — it could contain XSS, malicious links, or script tags\n\n---\n\n## Framework Security Quirks\n\n### JavaScript\u002FNode.js\n- Prototype pollution via `__proto__`\u002F`constructor.prototype` — validate object keys\n- `JSON.parse()` throws on malformed input — always wrap in try-catch\n- `RegExp(userInput)` enables ReDoS — escape special characters\n- `path.join()` with user input allows traversal — use `path.basename()` first\n- `setTimeout(string)` is implicit eval — always pass a function\n\n### MongoDB\u002FMongoose\n- Query operator injection via JSON body `{ password: { \"$gt\": \"\" } }` — cast to `String()`\n- `$where` clause = server-side JS execution — never use with user input\n- Unbounded queries exhaust memory — always `.limit()` and `.skip()`\n- `strict: false` accepts arbitrary fields — keep default `strict: true`\n\n### React\n- `dangerouslySetInnerHTML` bypasses escaping — require DOMPurify\n- `href={userUrl}` allows `javascript:` XSS — validate protocol\n- `VITE_*` env vars are public — never prefix secrets\n\n### Express\n- Middleware ordering matters — auth bypass if `router.use(auth)` placed after unprotected routes\n- `req.query` values are always strings — validate and cast types\n- Error handler must have exactly 4 params — missing `next` breaks error handling\n- Set `trust proxy` behind reverse proxy — otherwise rate limiter gets wrong IP\n\n---\n\n## Security Review Process\n\n1. **Detect context** — API endpoint, auth logic, DB query, file handling, frontend, config, or dependency change\n2. **Load relevant rules** — Only the OWASP categories that apply to this context\n3. **Trace data flow** — Where does the input come from? Is it attacker-controlled?\n4. **Check upstream controls** — Middleware, framework defaults, validation already applied?\n5. **Verify exploitability** — Can an attacker actually reach and control this?\n6. **Report HIGH confidence only** — Include file, line, exploit scenario, specific fix\n\n---\n\n## Severity Classification\n\n| Severity | Criteria | Stack Examples |\n|----------|----------|----------------|\n| **CRITICAL** | Direct exploit, no auth required | NoSQL injection auth bypass, hardcoded prod secrets, missing auth on admin endpoint, RCE |\n| **HIGH** | Exploitable with conditions | Stored XSS in blog content, IDOR on delete, JWT with weak secret, passwords in logs |\n| **MEDIUM** | Specific conditions, limited impact | Missing rate limiter, CORS misconfiguration, verbose prod errors, missing input validation |\n| **LOW** | Defense-in-depth | Low bcrypt cost, missing security event logging, sequential ObjectId exposure |\n\n---\n\n## ASVS 5.0 Quick Reference\n\n**Level 1 (All Apps)**: 12+ char passwords, breached list check, login rate limiting, 128+ bit session entropy, HTTPS, server-side validation, generic error messages\n\n**Level 2 (Sensitive)**: + MFA for sensitive ops, crypto key management, comprehensive security logging, schema-based input validation, CSRF protection\n\n**Level 3 (Critical)**: + HSM key storage, documented threat model, anomaly detection, penetration testing, supply chain verification\n",{"name":5,"description":7},"main","fe6b8af9977e97284d18d1179d55c021dd0a4a0a","plugins\u002Fengineering-paved-path\u002Fskills\u002Fsecurity","https:\u002F\u002Fgithub.com\u002Fyrazub\u002Fgen-bin","https:\u002F\u002Fgithub.com\u002Fyrazub","2026-11-05 19:09:18",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add yrazub\u002Fgen-bin --skill security",{"tool":36,"command":37},"bunx","bunx skills add yrazub\u002Fgen-bin --skill security",{"tool":39,"command":40},"pnpm","pnpm dlx skills add yrazub\u002Fgen-bin --skill security","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fyrazub\u002Fgen-bin\u002Fblob\u002Fmain\u002Fplugins\u002Fengineering-paved-path\u002Fskills\u002Fsecurity\u002FSKILL.md",true,[44,50,54],{"path":45,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":48,"sourceHtmlUrl":49},"checklists.md","REFERENCE","参考文档",8173,"https:\u002F\u002Fgithub.com\u002Fyrazub\u002Fgen-bin\u002Fblob\u002Fmain\u002Fplugins\u002Fengineering-paved-path\u002Fskills\u002Fsecurity\u002Fchecklists.md",{"path":51,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":52,"sourceHtmlUrl":53},"examples.md",21804,"https:\u002F\u002Fgithub.com\u002Fyrazub\u002Fgen-bin\u002Fblob\u002Fmain\u002Fplugins\u002Fengineering-paved-path\u002Fskills\u002Fsecurity\u002Fexamples.md",{"path":55,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":56,"sourceHtmlUrl":57},"references.md",11259,"https:\u002F\u002Fgithub.com\u002Fyrazub\u002Fgen-bin\u002Fblob\u002Fmain\u002Fplugins\u002Fengineering-paved-path\u002Fskills\u002Fsecurity\u002Freferences.md",[59,65,72,79,85,91],{"skillNo":60,"name":61,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":19},"01M7F6Y3T2E5DXEPZ71KC9GX2N","s","https:\u002F\u002Fgithub.com\u002Fyrazub\u002Fgen-bin\u002Fblob\u002Fmain\u002Fsite\u002Ftest\u002Ffixtures\u002Fmissing-description\u002Fplugins\u002Fa\u002Fskills\u002Fs\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":19},"01M7F6Y2JH0M9YW9194HT28S92","talk","Says a lot.","https:\u002F\u002Fgithub.com\u002Fyrazub\u002Fgen-bin\u002Fblob\u002Fmain\u002Fsite\u002Ftest\u002Ffixtures\u002Flong-description\u002Fplugins\u002Fwordy\u002Fskills\u002Ftalk\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":19},"01M7F6Y02Z4197HV8ANJYP8WK3","review","Review code in the beta plugin.","https:\u002F\u002Fgithub.com\u002Fyrazub\u002Fgen-bin\u002Fblob\u002Fmain\u002Fsite\u002Ftest\u002Ffixtures\u002Fduplicates\u002Fplugins\u002Fbeta\u002Fskills\u002Freview\u002FSKILL.md",[],[],{"skillNo":80,"name":74,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M7F6XZ3Z4M2YTEKZJYN5MBYJ","Review code in the alpha plugin.","https:\u002F\u002Fgithub.com\u002Fyrazub\u002Fgen-bin\u002Fblob\u002Fmain\u002Fsite\u002Ftest\u002Ffixtures\u002Fduplicates\u002Fplugins\u002Falpha\u002Fskills\u002Freview\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M7F6XY9V4HSXSVD348E52GEK","bad","https:\u002F\u002Fgithub.com\u002Fyrazub\u002Fgen-bin\u002Fblob\u002Fmain\u002Fsite\u002Ftest\u002Ffixtures\u002Fbroken-yaml\u002Fplugins\u002Fbroken\u002Fskills\u002Fbad\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M7F6XW4C3V6VHDK6ZHKNXSC3","execute-plan","Executes an approved implementation plan phase by phase with the project agents.","https:\u002F\u002Fgithub.com\u002Fyrazub\u002Fgen-bin\u002Fblob\u002Fmain\u002Fsite\u002Ftest\u002Ffixtures\u002Fbasic\u002Fplugins\u002Fsdd-workflow\u002Fskills\u002Fexecute-plan\u002FSKILL.md",[],[]]