[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7A0539Y98MQB8H4YPMSMWJQ":3,"skill-same:01M7A0539Y98MQB8H4YPMSMWJQ":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},"01M7A0539Y98MQB8H4YPMSMWJQ","security",null,"Application-CODE security review based on OWASP Top 10:2025, for a React + Express + MongoDB\u002FMongoose + JWT stack. Use when reviewing source code for vulnerabilities, implementing or auditing auth\u002Fauthorization, handling untrusted input, working with file uploads, managing secrets in code, or hardening an API endpoint. Covers A01-A10 for that stack, including supply-chain risk in npm dependencies. Trigger terms: security review, is this code safe, vulnerability, OWASP, injection, XSS, IDOR, broken access control, auth bypass, mass assignment, rate limiting, JWT verification. NOT for infrastructure or network security — VPC and security-group design, firewall rules, which ports to open, public IPs, TLS termination, OS or container hardening, and cloud IAM policy are all out of scope: this skill reads application source code and has nothing to say about them.","SyukPublic\u002Fai-dev-toolkit","SyukPublic","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211482903?v=4","01M799WENGJRH924NQACAF41WB","Roman","01M7A037ZP1Z7TM9RR30JJJYN1",0,"MIT","https:\u002F\u002Fgithub.com\u002FSyukPublic\u002Fai-dev-toolkit\u002Fblob\u002Fmain\u002Fplugins\u002Fengineering-paved-path\u002Fskills\u002Fsecurity\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: security\ndescription: \"Application-CODE security review based on OWASP Top 10:2025, for a React + Express + MongoDB\u002FMongoose + JWT stack. Use when reviewing source code for vulnerabilities, implementing or auditing auth\u002Fauthorization, handling untrusted input, working with file uploads, managing secrets in code, or hardening an API endpoint. Covers A01-A10 for that stack, including supply-chain risk in npm dependencies. Trigger terms: security review, is this code safe, vulnerability, OWASP, injection, XSS, IDOR, broken access control, auth bypass, mass assignment, rate limiting, JWT verification. NOT for infrastructure or network security — VPC and security-group design, firewall rules, which ports to open, public IPs, TLS termination, OS or container hardening, and cloud IAM policy are all out of scope: this skill reads application source code and has nothing to say about them.\"\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","ea14fd47c2127bf21f1edd83a9ffb39040f322f2","plugins\u002Fengineering-paved-path\u002Fskills\u002Fsecurity","https:\u002F\u002Fgithub.com\u002FSyukPublic\u002Fai-dev-toolkit","https:\u002F\u002Fgithub.com\u002FSyukPublic","2026-10-22 11:45:11",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add SyukPublic\u002Fai-dev-toolkit --skill security",{"tool":36,"command":37},"bunx","bunx skills add SyukPublic\u002Fai-dev-toolkit --skill security",{"tool":39,"command":40},"pnpm","pnpm dlx skills add SyukPublic\u002Fai-dev-toolkit --skill security","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSyukPublic\u002Fai-dev-toolkit\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\u002FSyukPublic\u002Fai-dev-toolkit\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\u002FSyukPublic\u002Fai-dev-toolkit\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\u002FSyukPublic\u002Fai-dev-toolkit\u002Fblob\u002Fmain\u002Fplugins\u002Fengineering-paved-path\u002Fskills\u002Fsecurity\u002Freferences.md",[59,66,73,80,87,94],{"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},"01M7A06HE8FF5S1MG986C2K19R","sample-skill","Reviews recent changes and reports actionable findings for testing purposes","https:\u002F\u002Fgithub.com\u002FSyukPublic\u002Fai-dev-toolkit\u002Fblob\u002Fmain\u002Fsite\u002Ftest-fixtures\u002Frepo-good\u002Fplugins\u002Ffixture-plugin\u002Fskills\u002Fsample-skill\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},"01M7A069XFAMZSSVQPQEKMCCCH","workflow-retro","Post-run retrospective of the multi-agent SDD pipeline (spec-creator → implementation-planner → implementer \u002F test-writer → architecture-reviewer \u002F plan-verifier, plus nested researcher\u002FExplore agents). Manually invoked after a run to produce TRUE token\u002Ftool\u002Fduration\u002Fparallelism metrics — deep mode parses session + subagent journals from disk because parent-visible usage EXCLUDES subagent tokens — plus insights with concrete optimization actions, a trend row appended to the retro ledger (default docs\u002Fretros\u002Fledger.md), and an audit verdict. Trigger terms: workflow retro, retro, ретро, retrospective, pipeline metrics, agent token usage, cache hit, parallelism, як пройшов конвеєр.","https:\u002F\u002Fgithub.com\u002FSyukPublic\u002Fai-dev-toolkit\u002Fblob\u002Fmain\u002Fplugins\u002Fsdd-engineering\u002Fskills\u002Fworkflow-retro\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},"01M7A060WWM0BE90HWSJQ8TM2G","run-plan","Executes an APPROVED Development Plan through the SDD implementation pipeline: implementer wave(s) → test-writer gap pass → green barrier (tests + typecheck) → architecture-reviewer ∥ plan-verifier → bounded fix loop (max 2 iterations) → final report. HARD GATE: an existing plan file is a required input — no plan, no run. Unlike implementer (ships ONE slice) — this skill orchestrates the WHOLE plan across agents; unlike workflow-retro (measures a PAST run) — this skill performs the run; unlike a pre-publish diff review — this skill implements and verifies, it never publishes. Trigger terms: run-plan, run the plan, execute the plan, run the implementation pipeline, запусти план, запусти конвеєр, виконай план, прожени план через конвеєр.","https:\u002F\u002Fgithub.com\u002FSyukPublic\u002Fai-dev-toolkit\u002Fblob\u002Fmain\u002Fplugins\u002Fsdd-engineering\u002Fskills\u002Frun-plan\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},"01M7A05WMWZ4QPGQYBAABS5AD2","mermaid-diagram","Create Mermaid diagrams in markdown. Use when the user wants to visualize workflows, architectures, API flows, data models, state machines, or system designs. Covers flowcharts, sequence diagrams, class diagrams, ER diagrams, state diagrams, and more.","https:\u002F\u002Fgithub.com\u002FSyukPublic\u002Fai-dev-toolkit\u002Fblob\u002Fmain\u002Fplugins\u002Fsdd-engineering\u002Fskills\u002Fmermaid-diagram\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":19},"01M7A05NQ6QV259QFW1XWVH5GG","engineering-insights","Capture durable engineering insights into the host project's insights file (default docs\u002Fengineering-insights.md), and prune that log. Use during any session when a non-obvious discovery is confirmed — a gotcha, a fix's root cause, a why-it's-like-this decision, an antipattern, or a tool\u002Flibrary quirk — and at session wrap-up to sweep for learnings. Also use to review, dedup, or declutter the insights file. Trigger terms: insight, learning, gotcha, engineering insights, lesson learned, wrap-up, retrospective, prune insights.","https:\u002F\u002Fgithub.com\u002FSyukPublic\u002Fai-dev-toolkit\u002Fblob\u002Fmain\u002Fplugins\u002Fsdd-engineering\u002Fskills\u002Fengineering-insights\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":19},"01M7A05ER6QKT6X84TCV09KBSC","typescript-expert","TypeScript and JavaScript expert with deep knowledge of type-level programming, performance optimization, monorepo management, migration strategies, and modern tooling.","https:\u002F\u002Fgithub.com\u002FSyukPublic\u002Fai-dev-toolkit\u002Fblob\u002Fmain\u002Fplugins\u002Fengineering-paved-path\u002Fskills\u002Ftypescript-expert\u002FSKILL.md",[],[]]