[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77JK6Y36CEWWZASZ4PBF2CY":3,"skill-same:01M77JK6Y36CEWWZASZ4PBF2CY":56},{"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":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":20,"linkOnly":21,"markdownContent":22,"markdownBody":23,"frontMatter":24,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":14,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M77JK6Y36CEWWZASZ4PBF2CY","VibeSec-Skill",null,"This skill helps Claude write secure web applications. Use this when working on any web application or when a user requests a scan or audit to ensure security best practices are followed.","hillzeealex\u002Fskills","hillzeealex","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F36928534?v=4","01M77JEXSA3WQRD0YGSB3MXNM5","Alexander HILLS","01M77JEXTGRW0E3KC02SZNX6DR",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fhillzeealex\u002Fskills\u002Fblob\u002Fmaster\u002Fsecurity\u002Fvibesec\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhillzeealex\u002Fskills\u002Fblob\u002Fmaster\u002Fsecurity\u002Fvibesec\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: VibeSec-Skill\ndescription: This skill helps Claude write secure web applications. Use this when working on any web application or when a user requests a scan or audit to ensure security best practices are followed.\n---\n\n# Secure Coding Guide for Web Applications\n\n## Overview\n\nThis guide provides comprehensive secure coding practices for web applications. As an AI assistant, your role is to approach code from a **bug hunter's perspective** and make applications **as secure as possible** without breaking functionality.\n\n**Key Principles:**\n- Defense in depth: Never rely on a single security control\n- Fail securely: When something fails, fail closed (deny access)\n- Least privilege: Grant minimum permissions necessary\n- Input validation: Never trust user input, validate everything server-side\n- Output encoding: Encode data appropriately for the context it's rendered in\n\n---\n\n## Access Control Issues\n\nAccess control vulnerabilities occur when users can access resources or perform actions beyond their intended permissions.\n\n### Core Requirements\n\nFor **every data point and action** that requires authentication:\n\n1. **User-Level Authorization**\n   - Each user must only access\u002Fmodify their own data\n   - No user should access data from other users or organizations\n   - Always verify ownership at the data layer, not just the route level\n\n2. **Use UUIDs Instead of Sequential IDs**\n   - Use UUIDv4 or similar non-guessable identifiers\n   - Exception: Only use sequential IDs if explicitly requested by user\n\n3. **Account Lifecycle Handling**\n   - When a user is removed from an organization: immediately revoke all access tokens and sessions\n   - When an account is deleted\u002Fdeactivated: invalidate all active sessions and API keys\n   - Implement token revocation lists or short-lived tokens with refresh mechanisms\n\n### Authorization Checks Checklist\n\n- [ ] Verify user owns the resource on every request (don't trust client-side data)\n- [ ] Check organization membership for multi-tenant apps\n- [ ] Validate role permissions for role-based actions\n- [ ] Re-validate permissions after any privilege change\n- [ ] Check parent resource ownership (e.g., if accessing a comment, verify user owns the parent post)\n\n### Common Pitfalls to Avoid\n\n- **IDOR (Insecure Direct Object Reference)**: Always verify the requesting user has permission to access the requested resource ID\n- **Privilege Escalation**: Validate role changes server-side; never trust role info from client\n- **Horizontal Access**: User A accessing User B's resources with the same privilege level\n- **Vertical Access**: Regular user accessing admin functionality\n- **Mass Assignment**: Filter which fields users can update; don't blindly accept all request body fields\n\n### Implementation Pattern\n\n```\n# Pseudocode for secure resource access\nfunction getResource(resourceId, currentUser):\n    resource = database.find(resourceId)\n    \n    if resource is null:\n        return 404  # Don't reveal if resource exists\n    \n    if resource.ownerId != currentUser.id:\n        if not currentUser.hasOrgAccess(resource.orgId):\n            return 404  # Return 404, not 403, to prevent enumeration\n    \n    return resource\n```\n\n---\n\n## Client-Side Bugs\n\n### Cross-Site Scripting (XSS)\n\nEvery input controllable by the user—whether directly or indirectly—must be sanitized against XSS.\n\n#### Input Sources to Protect\n\n**Direct Inputs:**\n- Form fields (email, name, bio, comments, etc.)\n- Search queries\n- File names during upload\n- Rich text editors \u002F WYSIWYG content\n\n**Indirect Inputs:**\n- URL parameters and query strings\n- URL fragments (hash values)\n- HTTP headers used in the application (Referer, User-Agent if displayed)\n- Data from third-party APIs displayed to users\n- WebSocket messages\n- postMessage data from iframes\n- LocalStorage\u002FSessionStorage values if rendered\n\n**Often Overlooked:**\n- Error messages that reflect user input\n- PDF\u002Fdocument generators that accept HTML\n- Email templates with user data\n- Log viewers in admin panels\n- JSON responses rendered as HTML\n- SVG file uploads (can contain JavaScript)\n- Markdown rendering (if allowing HTML)\n\n#### Protection Strategies\n\n1. **Output Encoding** (Context-Specific)\n   - HTML context: HTML entity encode (`\u003C` → `&lt;`)\n   - JavaScript context: JavaScript escape\n   - URL context: URL encode\n   - CSS context: CSS escape\n   - Use framework's built-in escaping (React's JSX, Vue's {{ }}, etc.)\n\n2. **Content Security Policy (CSP)**\n   ```\n   Content-Security-Policy: \n     default-src 'self';\n     script-src 'self';\n     style-src 'self' 'unsafe-inline';\n     img-src 'self' data: https:;\n     font-src 'self';\n     connect-src 'self' https:\u002F\u002Fapi.yourdomain.com;\n     frame-ancestors 'none';\n     base-uri 'self';\n     form-action 'self';\n   ```\n   - Avoid `'unsafe-inline'` and `'unsafe-eval'` for scripts\n   - Use nonces or hashes for inline scripts when necessary\n   - Report violations: `report-uri \u002Fcsp-report`\n\n3. **Input Sanitization**\n   - Use established libraries (DOMPurify for HTML)\n   - Whitelist allowed tags\u002Fattributes for rich text\n   - Strip or encode dangerous patterns\n\n4. **Additional Headers**\n   - `X-Content-Type-Options: nosniff`\n   - `X-Frame-Options: DENY` (or use CSP frame-ancestors)\n\n---\n\n### Cross-Site Request Forgery (CSRF)\n\nEvery state-changing endpoint must be protected against CSRF attacks.\n\n#### Endpoints Requiring CSRF Protection\n\n**Authenticated Actions:**\n- All POST, PUT, PATCH, DELETE requests\n- Any GET request that changes state (fix these to use proper HTTP methods)\n- File uploads\n- Settings changes\n- Payment\u002Ftransaction endpoints\n\n**Pre-Authentication Actions:**\n- Login endpoints (prevent login CSRF)\n- Signup endpoints\n- Password reset request endpoints\n- Password change endpoints\n- Email\u002Fphone verification endpoints\n- OAuth callback endpoints\n\n#### Protection Mechanisms\n\n1. **CSRF Tokens**\n   - Generate cryptographically random tokens\n   - Tie token to user session\n   - Validate on every state-changing request\n   - Regenerate after login (prevent session fixation combo)\n\n2. **SameSite Cookies**\n   ```\n   Set-Cookie: session=abc123; SameSite=Strict; Secure; HttpOnly\n   ```\n   - `Strict`: Cookie never sent cross-site (best security)\n   - `Lax`: Cookie sent on top-level navigations (good balance)\n   - Always combine with CSRF tokens for defense in depth\n\n3. **Double Submit Cookie Pattern**\n   - Send CSRF token in both cookie and request body\u002Fheader\n   - Server validates they match\n\n#### Edge Cases and Common Mistakes\n\n- **Token presence check**: CSRF validation must NOT depend on whether the token is present, always require it\n- **Token per form**: Consider unique tokens per form for sensitive operations\n- **JSON APIs**: Don't assume JSON content-type prevents CSRF; validate Origin\u002FReferer headers AND use tokens\n- **CORS misconfiguration**: Overly permissive CORS can bypass SameSite cookies\n- **Subdomains**: CSRF tokens should be scoped because subdomain takeover can lead to CSRF\n- **Flash\u002FPDF uploads**: Legacy browser plugins could bypass SameSite\n- **GET requests with side effects**: Never perform state changes on GET\n- **Token leakage**: Don't include CSRF tokens in URLs\n- **Token in URL vs Header**: Prefer custom headers (X-CSRF-Token) over URL parameters\n\n\n#### Verification Checklist\n\n- [ ] Token is cryptographically random (use secure random generator)\n- [ ] Token is tied to user session\n- [ ] Token is validated server-side on all state-changing requests\n- [ ] Missing token = rejected request\n- [ ] Token regenerated on authentication state change\n- [ ] SameSite cookie attribute is set\n- [ ] Secure and HttpOnly flags on session cookies\n\n---\n\n### Secret Keys and Sensitive Data Exposure\n\nNo secrets or sensitive information should be accessible to client-side code.\n\n#### Never Expose in Client-Side Code\n\n**API Keys and Secrets:**\n- Third-party API keys (Stripe, AWS, etc.)\n- Database connection strings\n- JWT signing secrets\n- Encryption keys\n- OAuth client secrets\n- Internal service URLs\u002Fcredentials\n\n**Sensitive User Data:**\n- Full credit card numbers\n- Social Security Numbers\n- Passwords (even hashed)\n- Security questions\u002Fanswers\n- Full phone numbers (mask them: ***-***-1234)\n- Sensitive PII that isn't needed for display\n\n**Infrastructure Details:**\n- Internal IP addresses\n- Database schemas\n- Debug information\n- Stack traces in production\n- Server software versions\n\n#### Where Secrets Hide (Check These!)\n\n- JavaScript bundles (including source maps)\n- HTML comments\n- Hidden form fields\n- Data attributes\n- LocalStorage\u002FSessionStorage\n- Initial state\u002Fhydration data in SSR apps\n- Environment variables exposed via build tools (NEXT_PUBLIC_*, REACT_APP_*)\n\n#### Best Practices\n\n1. **Environment Variables**: Store secrets in `.env` files\n2. **Server-Side Only**: Make API calls requiring secrets from backend only\n\n---\n\n## Open Redirect\n\nAny endpoint accepting a URL for redirection must be protected against open redirect attacks.\n\n### Protection Strategies\n\n1. **Allowlist Validation**\n   ```\n   allowed_domains = ['yourdomain.com', 'app.yourdomain.com']\n   \n   function isValidRedirect(url):\n       parsed = parseUrl(url)\n       return parsed.hostname in allowed_domains\n   ```\n\n2. **Relative URLs Only**\n   - Only accept paths (e.g., `\u002Fdashboard`) not full URLs\n   - Validate the path starts with `\u002F` and doesn't contain `\u002F\u002F`\n\n3. **Indirect References**\n   - Use a mapping instead of raw URLs: `?redirect=dashboard` → lookup to `\u002Fdashboard`\n\n### Bypass Techniques to Block\n\n| Technique | Example | Why It Works |\n|-----------|---------|--------------|\n| @ symbol | `https:\u002F\u002Flegit.com@evil.com` | Browser navigates to evil.com with legit.com as username |\n| Subdomain abuse | `https:\u002F\u002Flegit.com.evil.com` | evil.com owns the subdomain |\n| Protocol tricks | `javascript:alert(1)` | XSS via redirect |\n| Double URL encoding | `%252f%252fevil.com` | Decodes to `\u002F\u002Fevil.com` after double decode |\n| Backslash | `https:\u002F\u002Flegit.com\\@evil.com` | Some parsers normalize `\\` to `\u002F` |\n| Null byte | `https:\u002F\u002Flegit.com%00.evil.com` | Some parsers truncate at null |\n| Tab\u002Fnewline | `https:\u002F\u002Flegit.com%09.evil.com` | Whitespace confusion |\n| Unicode normalization | `https:\u002F\u002Flegіt.com` (Cyrillic і) | IDN homograph attack |\n| Data URLs | `data:text\u002Fhtml,\u003Cscript>...` | Direct payload execution |\n| Protocol-relative | `\u002F\u002Fevil.com` | Uses current page's protocol |\n| Fragment abuse | `https:\u002F\u002Flegit.com#@evil.com` | Parsed differently by different libraries |\n\n### IDN Homograph Attack Protection\n\n- Convert URLs to Punycode before validation\n- Consider blocking non-ASCII domains entirely for sensitive redirects\n\n\n---\n\n### Password Security\n\n#### Password Requirements\n\n- Minimum 8 characters (12+ recommended)\n- No maximum length (or very high, e.g., 128 chars)\n- Allow all characters including special chars\n- Don't require specific character types (let users choose strong passwords)\n\n#### Storage\n\n- Use Argon2id, bcrypt, or scrypt\n- Never MD5, SHA1, or plain SHA256\n\n---\n\n## Server-Side Bugs\n\n### Server-Side Request Forgery (SSRF)\n\nAny functionality where the server makes requests to URLs provided or influenced by users must be protected.\n\n#### Potential Vulnerable Features\n\n- Webhooks (user provides callback URL)\n- URL previews\n- PDF generators from URLs\n- Image\u002Ffile fetching from URLs\n- Import from URL features\n- RSS\u002Ffeed readers\n- API integrations with user-provided endpoints\n- Proxy functionality\n- HTML to PDF\u002Fimage converters\n\n#### Protection Strategies\n\n1. **Allowlist Approach** (Preferred)\n   - Only allow requests to pre-approved domains\n   - Maintain a strict allowlist for integrations\n\n2. **Network Segmentation**\n   - Run URL-fetching services in isolated network\n   - Block access to internal network, cloud metadata\n\n#### IP and DNS Bypass Techniques to Block\n\n| Technique | Example | Description |\n|-----------|---------|-------------|\n| Decimal IP | `http:\u002F\u002F2130706433` | 127.0.0.1 as decimal |\n| Octal IP | `http:\u002F\u002F0177.0.0.1` | Octal representation |\n| Hex IP | `http:\u002F\u002F0x7f.0x0.0x0.0x1` | Hexadecimal |\n| IPv6 localhost | `http:\u002F\u002F[::1]` | IPv6 loopback |\n| IPv6 mapped IPv4 | `http:\u002F\u002F[::ffff:127.0.0.1]` | IPv4-mapped IPv6 |\n| Short IPv6 | `http:\u002F\u002F[::]` | All zeros |\n| DNS rebinding | Attacker's DNS returns internal IP | First request resolves to external IP, second to internal |\n| CNAME to internal | Attacker domain CNAMEs to internal | DNS points to internal hostname |\n| URL parser confusion | `http:\u002F\u002Fattacker.com#@internal` | Different parsing behaviors |\n| Redirect chains | External URL redirects to internal | Follow redirects carefully |\n| IPv6 scope ID | `http:\u002F\u002F[fe80::1%25eth0]` | Interface-scoped IPv6 |\n| Rare IP formats | `http:\u002F\u002F127.1` | Shortened IP notation |\n\n#### DNS Rebinding Prevention\n\n1. Resolve DNS before making request\n2. Validate resolved IP is not internal\n3. Pin the resolved IP for the request (don't re-resolve)\n4. Or: Resolve twice with delay, ensure both resolve to same external IP\n\n#### Cloud Metadata Protection\n\nBlock access to cloud metadata endpoints:\n- AWS: `169.254.169.254`\n- GCP: `metadata.google.internal`, `169.254.169.254`, `http:\u002F\u002Fmetadata`\n- Azure: `169.254.169.254`\n- DigitalOcean: `169.254.169.254`\n\n#### Implementation Checklist\n\n- [ ] Validate URL scheme is HTTP\u002FHTTPS only\n- [ ] Resolve DNS and validate IP is not private\u002Finternal\n- [ ] Block cloud metadata IPs explicitly\n- [ ] Limit or disable redirect following\n- [ ] If following redirects, validate each hop\n- [ ] Set timeout on requests\n- [ ] Limit response size\n- [ ] Use network isolation where possible\n\n---\n\n### Insecure File Upload\n\nFile uploads must validate type, content, and size to prevent various attacks.\n\n#### Validation Requirements\n\n**1. File Type Validation**\n- Check file extension against allowlist\n- Validate magic bytes\u002Ffile signature match expected type\n- Never rely on just one check\n\n**2. File Content Validation**\n- Read and verify magic bytes\n- For images: attempt to process with image library (detects malformed files)\n- For documents: scan for macros, embedded objects\n- Check for polyglot files (files valid as multiple types)\n\n**3. File Size Limits**\n- Set maximum file size server-side\n- Configure web server\u002Fproxy limits as well\n- Consider per-file-type limits (images smaller than videos)\n\n#### Common Bypasses and Attacks\n\n| Attack | Description | Prevention |\n|--------|-------------|------------|\n| Extension bypass | `shell.php.jpg` | Check full extension, use allowlist |\n| Null byte | `shell.php%00.jpg` | Sanitize filename, check for null bytes |\n| Double extension | `shell.jpg.php` | Only allow single extension |\n| MIME type spoofing | Set Content-Type to image\u002Fjpeg | Validate magic bytes |\n| Magic byte injection | Prepend valid magic bytes to malicious file | Check entire file structure, not just header |\n| Polyglot files | File valid as both JPEG and JavaScript | Parse file as expected type, reject if invalid |\n| SVG with JavaScript | `\u003Csvg onload=\"alert(1)\">` | Sanitize SVG or disallow entirely |\n| XXE via file upload | Malicious DOCX, XLSX (which are XML) | Disable external entities in parser |\n| ZIP slip | `..\u002F..\u002F..\u002Fetc\u002Fpasswd` in archive | Validate extracted paths |\n| ImageMagick exploits | Specially crafted images | Keep ImageMagick updated, use policy.xml |\n| Filename injection | `; rm -rf \u002F` in filename | Sanitize filenames, use random names |\n| Content-type confusion | Browser MIME sniffing | Set `X-Content-Type-Options: nosniff` |\n\n#### Magic Bytes Reference\n\n| Type | Magic Bytes (hex) |\n|------|-------------------|\n| JPEG | `FF D8 FF` |\n| PNG | `89 50 4E 47 0D 0A 1A 0A` |\n| GIF | `47 49 46 38` |\n| PDF | `25 50 44 46` |\n| ZIP | `50 4B 03 04` |\n| DOCX\u002FXLSX | `50 4B 03 04` (ZIP-based) |\n\n#### Secure Upload Handling\n\n1. **Rename files**: Use random UUID names, discard original\n2. **Store outside webroot**: Or use separate domain for uploads\n3. **Serve with correct headers**:\n   - `Content-Disposition: attachment` (forces download)\n   - `X-Content-Type-Options: nosniff`\n   - `Content-Type` matching actual file type\n4. **Use CDN\u002Fseparate domain**: Isolate uploaded content from main app\n5. **Set restrictive permissions**: Uploaded files should not be executable\n\n---\n\n### SQL Injection\n\nSQL injection occurs when user input is incorporated into SQL queries without proper handling.\n\n#### Prevention Methods\n\n**1. Parameterized Queries (Prepared Statements)** — PRIMARY DEFENSE\n```sql\n-- VULNERABLE\nquery = \"SELECT * FROM users WHERE id = \" + userId\n\n-- SECURE\nquery = \"SELECT * FROM users WHERE id = ?\"\nexecute(query, [userId])\n```\n\n**2. ORM Usage**\n- Use ORM methods that automatically parameterize\n- Be cautious with raw query methods in ORMs\n- Watch for ORM-specific injection points\n\n**3. Input Validation**\n- Validate data types (integer should be integer)\n- Whitelist allowed values where applicable\n- This is defense-in-depth, not primary defense\n\n#### Injection Points to Watch\n\n- WHERE clauses\n- ORDER BY clauses (often overlooked—can't use parameters, must whitelist)\n- LIMIT\u002FOFFSET values\n- Table and column names (can't parameterize—must whitelist)\n- INSERT values\n- UPDATE SET values\n- IN clauses with dynamic lists\n- LIKE patterns (also escape wildcards: %, _)\n\n#### Additional Defenses\n\n- **Least privilege**: Database user should have minimum required permissions\n- **Disable dangerous functions**: Like `xp_cmdshell` in SQL Server\n- **Error handling**: Never expose SQL errors to users\n\n---\n\n### XML External Entity (XXE)\n\nXXE vulnerabilities occur when XML parsers process external entity references in user-supplied XML.\n\n#### Vulnerable Scenarios\n\n**Direct XML Input:**\n- SOAP APIs\n- XML-RPC\n- XML file uploads\n- Configuration file parsing\n- RSS\u002FAtom feed processing\n\n**Indirect XML:**\n- JSON\u002Fother format converted to XML server-side\n- Office documents (DOCX, XLSX, PPTX are ZIP with XML)\n- SVG files (XML-based)\n- SAML assertions\n- PDF with XFA forms\n\n\n#### Prevention by Language\u002FParser\n\n**Java:**\n```java\nDocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\ndbf.setFeature(\"http:\u002F\u002Fapache.org\u002Fxml\u002Ffeatures\u002Fdisallow-doctype-decl\", true);\ndbf.setFeature(\"http:\u002F\u002Fxml.org\u002Fsax\u002Ffeatures\u002Fexternal-general-entities\", false);\ndbf.setFeature(\"http:\u002F\u002Fxml.org\u002Fsax\u002Ffeatures\u002Fexternal-parameter-entities\", false);\ndbf.setExpandEntityReferences(false);\n```\n\n**Python (lxml):**\n```python\nfrom lxml import etree\nparser = etree.XMLParser(resolve_entities=False, no_network=True)\n# Or use defusedxml library\n```\n\n**PHP:**\n```php\nlibxml_disable_entity_loader(true);\n\u002F\u002F Or use XMLReader with proper settings\n```\n\n**Node.js:**\n```javascript\n\u002F\u002F Use libraries that disable DTD processing by default\n\u002F\u002F If using libxmljs, set { noent: false, dtdload: false }\n```\n\n**.NET:**\n```csharp\nXmlReaderSettings settings = new XmlReaderSettings();\nsettings.DtdProcessing = DtdProcessing.Prohibit;\nsettings.XmlResolver = null;\n```\n\n#### XXE Prevention Checklist\n\n- [ ] Disable DTD processing entirely if possible\n- [ ] Disable external entity resolution\n- [ ] Disable external DTD loading\n- [ ] Disable XInclude processing\n- [ ] Use latest patched XML parser versions\n- [ ] Validate\u002Fsanitize XML before parsing if DTD needed\n- [ ] Consider using JSON instead of XML where possible\n\n---\n\n### Path Traversal\n\nPath traversal vulnerabilities occur when user input controls file paths, allowing access to files outside intended directories.\n\n#### Vulnerable Patterns\n\n```python\n# VULNERABLE\nfile_path = \"\u002Fuploads\u002F\" + user_input\nfile_path = base_dir + request.params['file']\ntemplate = \"templates\u002F\" + user_provided_template\n```\n\n#### Prevention Strategies\n\n**1. Avoid User Input in Paths**\n```python\n# Instead of using user input directly\n# Use indirect references\nfiles = {'report': '\u002Freports\u002Fq1.pdf', 'invoice': '\u002Finvoices\u002F2024.pdf'}\nfile_path = files.get(user_input)  # Returns None if invalid\n```\n\n**2. Canonicalization and Validation**\n\n```python\nimport os\n\ndef safe_join(base_directory, user_path):\n    # Ensure base is absolute and normalized\n    base = os.path.abspath(os.path.realpath(base_directory))\n    \n    # Join and then resolve the result\n    target = os.path.abspath(os.path.realpath(os.path.join(base, user_path)))\n    \n    # Ensure the commonpath is the base directory\n    if os.path.commonpath([base, target]) != base:\n        raise ValueError(\"Error!\")\n    \n    return target\n```\n\n**3. Input Sanitization**\n- Remove or reject `..` sequences\n- Remove or reject absolute path indicators (`\u002F`, `C:`)\n- Whitelist allowed characters (alphanumeric, dash, underscore)\n- Validate file extension if applicable\n\n\n#### Path Traversal Checklist\n\n- [ ] Never use user input directly in file paths\n- [ ] Canonicalize paths and validate against base directory\n- [ ] Restrict file extensions if applicable\n- [ ] Test with various encoding and bypass techniques\n\n---\n\n## Security Headers Checklist\n\nInclude these headers in all responses:\n\n```\nStrict-Transport-Security: max-age=31536000; includeSubDomains; preload\nContent-Security-Policy: [see XSS section]\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\nReferrer-Policy: strict-origin-when-cross-origin\nCache-Control: no-store (for sensitive pages)\n```\n\n---\n\n## JWT Security\n\nJWT misconfigurations can lead to full authentication bypass and token forgery.\n\n### Vulnerabilities\n\n| Vulnerability | Prevention |\n|---------------|------------|\n| `alg: none` attack | Always verify algorithm server-side, reject `none` |\n| Algorithm confusion | Explicitly specify expected algorithm, never derive from token |\n| Weak HMAC secrets | Use 256+ bit cryptographically random secrets |\n| Missing expiration | Always set `exp` claim |\n| Token in localStorage | Store in httpOnly, Secure, SameSite=Strict cookies, never localStorage |\n\n\n### Secure Implementation\n\n```javascript\n\u002F\u002F 1. SIGNING\n\u002F\u002F Always use environment variables for secrets\nconst secret = process.env.JWT_SECRET; \n\nconst token = jwt.sign({\n  sub: userId,\n  iat: Math.floor(Date.now() \u002F 1000),\n  exp: Math.floor(Date.now() \u002F 1000) + (15 * 60), \u002F\u002F 15 mins (Short-lived)\n  jti: crypto.randomUUID() \u002F\u002F Unique ID for revocation\u002Fblacklisting\n}, secret, { \n  algorithm: 'HS256' \n});\n\n\u002F\u002F 2. SENDING (Cookie Best Practices)\n\u002F\u002F Protect against XSS and CSRF\nres.cookie('token', token, {\n  httpOnly: true, \n  secure: true,    \n  sameSite: 'strict'\n});\n\n\u002F\u002F 3. VERIFYING\n\u002F\u002F CRITICAL: Whitelist the allowed algorithm\njwt.verify(token, secret, { algorithms: ['HS256'] }, (err, decoded) => {\n  if (err) {\n    \u002F\u002F Handle invalid token\n  }\n  \u002F\u002F Trust the payload\n});\n```\n\n### JWT Checklist\n\n- [ ] Algorithm explicitly specified on verification (never trust token header)\n- [ ] `alg: none` rejected\n- [ ] Secret is 256+ bits of random data (not a password or phrase)\n- [ ] `exp` claim always set and validated\n- [ ] Tokens stored in httpOnly cookies (not localStorage\u002FsessionStorage)\n- [ ] Refresh token rotation implemented (old refresh token invalidated on use)\n\n---\n\n## API Security\n\n### Mass Assignment\n\nAccepting unfiltered request bodies can lead to privilege escalation.\n\n```javascript\n\u002F\u002F VULNERABLE — user can set { role: \"admin\" } in request body\nUser.update(req.body)\n\n\u002F\u002F SECURE — whitelist allowed fields\nconst allowed = ['name', 'email', 'avatar']\nconst updates = pick(req.body, allowed)\nUser.update(updates)\n```\n\nThis applies to any ORM\u002Fframework — always explicitly define which fields a request can modify.\n\n### GraphQL\n\n| Vulnerability | Prevention |\n| :--- | :--- |\n| Introspection in production | Disable introspection in production environments. |\n| Query depth attack | Implement query depth limiting (e.g., maximum of 10 levels). |\n| Query complexity attack | Calculate and enforce strict query cost limits. |\n| Batching attack | Limit the number of operations allowed per single request. |\n\n\n```javascript\nconst server = new ApolloServer({\n  introspection: process.env.NODE_ENV !== 'production',\n  validationRules: [\n    depthLimit(10),\n    costAnalysis({ maximumCost: 1000 })\n  ]\n})\n```\n\n---\n\n## General Security Principles\n\nWhen generating code, always:\n\n1. **Validate all input server-side** — Never trust client-side validation alone\n2. **Use parameterized queries** — Never concatenate user input into queries\n3. **Encode output contextually** — HTML, JS, URL, CSS contexts need different encoding\n4. **Apply authentication checks** — On every endpoint, not just at routing\n5. **Apply authorization checks** — Verify the user can access the specific resource\n6. **Use secure defaults**\n7. **Handle errors securely** — Don't leak stack traces or internal details to users\n8. **Keep dependencies updated** — Use tools to track vulnerable dependencies\n\nWhen unsure, choose the more restrictive\u002Fsecure option and document the security consideration in comments.\n","# Secure Coding Guide for Web Applications\n\n## Overview\n\nThis guide provides comprehensive secure coding practices for web applications. As an AI assistant, your role is to approach code from a **bug hunter's perspective** and make applications **as secure as possible** without breaking functionality.\n\n**Key Principles:**\n- Defense in depth: Never rely on a single security control\n- Fail securely: When something fails, fail closed (deny access)\n- Least privilege: Grant minimum permissions necessary\n- Input validation: Never trust user input, validate everything server-side\n- Output encoding: Encode data appropriately for the context it's rendered in\n\n---\n\n## Access Control Issues\n\nAccess control vulnerabilities occur when users can access resources or perform actions beyond their intended permissions.\n\n### Core Requirements\n\nFor **every data point and action** that requires authentication:\n\n1. **User-Level Authorization**\n   - Each user must only access\u002Fmodify their own data\n   - No user should access data from other users or organizations\n   - Always verify ownership at the data layer, not just the route level\n\n2. **Use UUIDs Instead of Sequential IDs**\n   - Use UUIDv4 or similar non-guessable identifiers\n   - Exception: Only use sequential IDs if explicitly requested by user\n\n3. **Account Lifecycle Handling**\n   - When a user is removed from an organization: immediately revoke all access tokens and sessions\n   - When an account is deleted\u002Fdeactivated: invalidate all active sessions and API keys\n   - Implement token revocation lists or short-lived tokens with refresh mechanisms\n\n### Authorization Checks Checklist\n\n- [ ] Verify user owns the resource on every request (don't trust client-side data)\n- [ ] Check organization membership for multi-tenant apps\n- [ ] Validate role permissions for role-based actions\n- [ ] Re-validate permissions after any privilege change\n- [ ] Check parent resource ownership (e.g., if accessing a comment, verify user owns the parent post)\n\n### Common Pitfalls to Avoid\n\n- **IDOR (Insecure Direct Object Reference)**: Always verify the requesting user has permission to access the requested resource ID\n- **Privilege Escalation**: Validate role changes server-side; never trust role info from client\n- **Horizontal Access**: User A accessing User B's resources with the same privilege level\n- **Vertical Access**: Regular user accessing admin functionality\n- **Mass Assignment**: Filter which fields users can update; don't blindly accept all request body fields\n\n### Implementation Pattern\n\n```\n# Pseudocode for secure resource access\nfunction getResource(resourceId, currentUser):\n    resource = database.find(resourceId)\n    \n    if resource is null:\n        return 404  # Don't reveal if resource exists\n    \n    if resource.ownerId != currentUser.id:\n        if not currentUser.hasOrgAccess(resource.orgId):\n            return 404  # Return 404, not 403, to prevent enumeration\n    \n    return resource\n```\n\n---\n\n## Client-Side Bugs\n\n### Cross-Site Scripting (XSS)\n\nEvery input controllable by the user—whether directly or indirectly—must be sanitized against XSS.\n\n#### Input Sources to Protect\n\n**Direct Inputs:**\n- Form fields (email, name, bio, comments, etc.)\n- Search queries\n- File names during upload\n- Rich text editors \u002F WYSIWYG content\n\n**Indirect Inputs:**\n- URL parameters and query strings\n- URL fragments (hash values)\n- HTTP headers used in the application (Referer, User-Agent if displayed)\n- Data from third-party APIs displayed to users\n- WebSocket messages\n- postMessage data from iframes\n- LocalStorage\u002FSessionStorage values if rendered\n\n**Often Overlooked:**\n- Error messages that reflect user input\n- PDF\u002Fdocument generators that accept HTML\n- Email templates with user data\n- Log viewers in admin panels\n- JSON responses rendered as HTML\n- SVG file uploads (can contain JavaScript)\n- Markdown rendering (if allowing HTML)\n\n#### Protection Strategies\n\n1. **Output Encoding** (Context-Specific)\n   - HTML context: HTML entity encode (`\u003C` → `&lt;`)\n   - JavaScript context: JavaScript escape\n   - URL context: URL encode\n   - CSS context: CSS escape\n   - Use framework's built-in escaping (React's JSX, Vue's {{ }}, etc.)\n\n2. **Content Security Policy (CSP)**\n   ```\n   Content-Security-Policy: \n     default-src 'self';\n     script-src 'self';\n     style-src 'self' 'unsafe-inline';\n     img-src 'self' data: https:;\n     font-src 'self';\n     connect-src 'self' https:\u002F\u002Fapi.yourdomain.com;\n     frame-ancestors 'none';\n     base-uri 'self';\n     form-action 'self';\n   ```\n   - Avoid `'unsafe-inline'` and `'unsafe-eval'` for scripts\n   - Use nonces or hashes for inline scripts when necessary\n   - Report violations: `report-uri \u002Fcsp-report`\n\n3. **Input Sanitization**\n   - Use established libraries (DOMPurify for HTML)\n   - Whitelist allowed tags\u002Fattributes for rich text\n   - Strip or encode dangerous patterns\n\n4. **Additional Headers**\n   - `X-Content-Type-Options: nosniff`\n   - `X-Frame-Options: DENY` (or use CSP frame-ancestors)\n\n---\n\n### Cross-Site Request Forgery (CSRF)\n\nEvery state-changing endpoint must be protected against CSRF attacks.\n\n#### Endpoints Requiring CSRF Protection\n\n**Authenticated Actions:**\n- All POST, PUT, PATCH, DELETE requests\n- Any GET request that changes state (fix these to use proper HTTP methods)\n- File uploads\n- Settings changes\n- Payment\u002Ftransaction endpoints\n\n**Pre-Authentication Actions:**\n- Login endpoints (prevent login CSRF)\n- Signup endpoints\n- Password reset request endpoints\n- Password change endpoints\n- Email\u002Fphone verification endpoints\n- OAuth callback endpoints\n\n#### Protection Mechanisms\n\n1. **CSRF Tokens**\n   - Generate cryptographically random tokens\n   - Tie token to user session\n   - Validate on every state-changing request\n   - Regenerate after login (prevent session fixation combo)\n\n2. **SameSite Cookies**\n   ```\n   Set-Cookie: session=abc123; SameSite=Strict; Secure; HttpOnly\n   ```\n   - `Strict`: Cookie never sent cross-site (best security)\n   - `Lax`: Cookie sent on top-level navigations (good balance)\n   - Always combine with CSRF tokens for defense in depth\n\n3. **Double Submit Cookie Pattern**\n   - Send CSRF token in both cookie and request body\u002Fheader\n   - Server validates they match\n\n#### Edge Cases and Common Mistakes\n\n- **Token presence check**: CSRF validation must NOT depend on whether the token is present, always require it\n- **Token per form**: Consider unique tokens per form for sensitive operations\n- **JSON APIs**: Don't assume JSON content-type prevents CSRF; validate Origin\u002FReferer headers AND use tokens\n- **CORS misconfiguration**: Overly permissive CORS can bypass SameSite cookies\n- **Subdomains**: CSRF tokens should be scoped because subdomain takeover can lead to CSRF\n- **Flash\u002FPDF uploads**: Legacy browser plugins could bypass SameSite\n- **GET requests with side effects**: Never perform state changes on GET\n- **Token leakage**: Don't include CSRF tokens in URLs\n- **Token in URL vs Header**: Prefer custom headers (X-CSRF-Token) over URL parameters\n\n\n#### Verification Checklist\n\n- [ ] Token is cryptographically random (use secure random generator)\n- [ ] Token is tied to user session\n- [ ] Token is validated server-side on all state-changing requests\n- [ ] Missing token = rejected request\n- [ ] Token regenerated on authentication state change\n- [ ] SameSite cookie attribute is set\n- [ ] Secure and HttpOnly flags on session cookies\n\n---\n\n### Secret Keys and Sensitive Data Exposure\n\nNo secrets or sensitive information should be accessible to client-side code.\n\n#### Never Expose in Client-Side Code\n\n**API Keys and Secrets:**\n- Third-party API keys (Stripe, AWS, etc.)\n- Database connection strings\n- JWT signing secrets\n- Encryption keys\n- OAuth client secrets\n- Internal service URLs\u002Fcredentials\n\n**Sensitive User Data:**\n- Full credit card numbers\n- Social Security Numbers\n- Passwords (even hashed)\n- Security questions\u002Fanswers\n- Full phone numbers (mask them: ***-***-1234)\n- Sensitive PII that isn't needed for display\n\n**Infrastructure Details:**\n- Internal IP addresses\n- Database schemas\n- Debug information\n- Stack traces in production\n- Server software versions\n\n#### Where Secrets Hide (Check These!)\n\n- JavaScript bundles (including source maps)\n- HTML comments\n- Hidden form fields\n- Data attributes\n- LocalStorage\u002FSessionStorage\n- Initial state\u002Fhydration data in SSR apps\n- Environment variables exposed via build tools (NEXT_PUBLIC_*, REACT_APP_*)\n\n#### Best Practices\n\n1. **Environment Variables**: Store secrets in `.env` files\n2. **Server-Side Only**: Make API calls requiring secrets from backend only\n\n---\n\n## Open Redirect\n\nAny endpoint accepting a URL for redirection must be protected against open redirect attacks.\n\n### Protection Strategies\n\n1. **Allowlist Validation**\n   ```\n   allowed_domains = ['yourdomain.com', 'app.yourdomain.com']\n   \n   function isValidRedirect(url):\n       parsed = parseUrl(url)\n       return parsed.hostname in allowed_domains\n   ```\n\n2. **Relative URLs Only**\n   - Only accept paths (e.g., `\u002Fdashboard`) not full URLs\n   - Validate the path starts with `\u002F` and doesn't contain `\u002F\u002F`\n\n3. **Indirect References**\n   - Use a mapping instead of raw URLs: `?redirect=dashboard` → lookup to `\u002Fdashboard`\n\n### Bypass Techniques to Block\n\n| Technique | Example | Why It Works |\n|-----------|---------|--------------|\n| @ symbol | `https:\u002F\u002Flegit.com@evil.com` | Browser navigates to evil.com with legit.com as username |\n| Subdomain abuse | `https:\u002F\u002Flegit.com.evil.com` | evil.com owns the subdomain |\n| Protocol tricks | `javascript:alert(1)` | XSS via redirect |\n| Double URL encoding | `%252f%252fevil.com` | Decodes to `\u002F\u002Fevil.com` after double decode |\n| Backslash | `https:\u002F\u002Flegit.com\\@evil.com` | Some parsers normalize `\\` to `\u002F` |\n| Null byte | `https:\u002F\u002Flegit.com%00.evil.com` | Some parsers truncate at null |\n| Tab\u002Fnewline | `https:\u002F\u002Flegit.com%09.evil.com` | Whitespace confusion |\n| Unicode normalization | `https:\u002F\u002Flegіt.com` (Cyrillic і) | IDN homograph attack |\n| Data URLs | `data:text\u002Fhtml,\u003Cscript>...` | Direct payload execution |\n| Protocol-relative | `\u002F\u002Fevil.com` | Uses current page's protocol |\n| Fragment abuse | `https:\u002F\u002Flegit.com#@evil.com` | Parsed differently by different libraries |\n\n### IDN Homograph Attack Protection\n\n- Convert URLs to Punycode before validation\n- Consider blocking non-ASCII domains entirely for sensitive redirects\n\n\n---\n\n### Password Security\n\n#### Password Requirements\n\n- Minimum 8 characters (12+ recommended)\n- No maximum length (or very high, e.g., 128 chars)\n- Allow all characters including special chars\n- Don't require specific character types (let users choose strong passwords)\n\n#### Storage\n\n- Use Argon2id, bcrypt, or scrypt\n- Never MD5, SHA1, or plain SHA256\n\n---\n\n## Server-Side Bugs\n\n### Server-Side Request Forgery (SSRF)\n\nAny functionality where the server makes requests to URLs provided or influenced by users must be protected.\n\n#### Potential Vulnerable Features\n\n- Webhooks (user provides callback URL)\n- URL previews\n- PDF generators from URLs\n- Image\u002Ffile fetching from URLs\n- Import from URL features\n- RSS\u002Ffeed readers\n- API integrations with user-provided endpoints\n- Proxy functionality\n- HTML to PDF\u002Fimage converters\n\n#### Protection Strategies\n\n1. **Allowlist Approach** (Preferred)\n   - Only allow requests to pre-approved domains\n   - Maintain a strict allowlist for integrations\n\n2. **Network Segmentation**\n   - Run URL-fetching services in isolated network\n   - Block access to internal network, cloud metadata\n\n#### IP and DNS Bypass Techniques to Block\n\n| Technique | Example | Description |\n|-----------|---------|-------------|\n| Decimal IP | `http:\u002F\u002F2130706433` | 127.0.0.1 as decimal |\n| Octal IP | `http:\u002F\u002F0177.0.0.1` | Octal representation |\n| Hex IP | `http:\u002F\u002F0x7f.0x0.0x0.0x1` | Hexadecimal |\n| IPv6 localhost | `http:\u002F\u002F[::1]` | IPv6 loopback |\n| IPv6 mapped IPv4 | `http:\u002F\u002F[::ffff:127.0.0.1]` | IPv4-mapped IPv6 |\n| Short IPv6 | `http:\u002F\u002F[::]` | All zeros |\n| DNS rebinding | Attacker's DNS returns internal IP | First request resolves to external IP, second to internal |\n| CNAME to internal | Attacker domain CNAMEs to internal | DNS points to internal hostname |\n| URL parser confusion | `http:\u002F\u002Fattacker.com#@internal` | Different parsing behaviors |\n| Redirect chains | External URL redirects to internal | Follow redirects carefully |\n| IPv6 scope ID | `http:\u002F\u002F[fe80::1%25eth0]` | Interface-scoped IPv6 |\n| Rare IP formats | `http:\u002F\u002F127.1` | Shortened IP notation |\n\n#### DNS Rebinding Prevention\n\n1. Resolve DNS before making request\n2. Validate resolved IP is not internal\n3. Pin the resolved IP for the request (don't re-resolve)\n4. Or: Resolve twice with delay, ensure both resolve to same external IP\n\n#### Cloud Metadata Protection\n\nBlock access to cloud metadata endpoints:\n- AWS: `169.254.169.254`\n- GCP: `metadata.google.internal`, `169.254.169.254`, `http:\u002F\u002Fmetadata`\n- Azure: `169.254.169.254`\n- DigitalOcean: `169.254.169.254`\n\n#### Implementation Checklist\n\n- [ ] Validate URL scheme is HTTP\u002FHTTPS only\n- [ ] Resolve DNS and validate IP is not private\u002Finternal\n- [ ] Block cloud metadata IPs explicitly\n- [ ] Limit or disable redirect following\n- [ ] If following redirects, validate each hop\n- [ ] Set timeout on requests\n- [ ] Limit response size\n- [ ] Use network isolation where possible\n\n---\n\n### Insecure File Upload\n\nFile uploads must validate type, content, and size to prevent various attacks.\n\n#### Validation Requirements\n\n**1. File Type Validation**\n- Check file extension against allowlist\n- Validate magic bytes\u002Ffile signature match expected type\n- Never rely on just one check\n\n**2. File Content Validation**\n- Read and verify magic bytes\n- For images: attempt to process with image library (detects malformed files)\n- For documents: scan for macros, embedded objects\n- Check for polyglot files (files valid as multiple types)\n\n**3. File Size Limits**\n- Set maximum file size server-side\n- Configure web server\u002Fproxy limits as well\n- Consider per-file-type limits (images smaller than videos)\n\n#### Common Bypasses and Attacks\n\n| Attack | Description | Prevention |\n|--------|-------------|------------|\n| Extension bypass | `shell.php.jpg` | Check full extension, use allowlist |\n| Null byte | `shell.php%00.jpg` | Sanitize filename, check for null bytes |\n| Double extension | `shell.jpg.php` | Only allow single extension |\n| MIME type spoofing | Set Content-Type to image\u002Fjpeg | Validate magic bytes |\n| Magic byte injection | Prepend valid magic bytes to malicious file | Check entire file structure, not just header |\n| Polyglot files | File valid as both JPEG and JavaScript | Parse file as expected type, reject if invalid |\n| SVG with JavaScript | `\u003Csvg onload=\"alert(1)\">` | Sanitize SVG or disallow entirely |\n| XXE via file upload | Malicious DOCX, XLSX (which are XML) | Disable external entities in parser |\n| ZIP slip | `..\u002F..\u002F..\u002Fetc\u002Fpasswd` in archive | Validate extracted paths |\n| ImageMagick exploits | Specially crafted images | Keep ImageMagick updated, use policy.xml |\n| Filename injection | `; rm -rf \u002F` in filename | Sanitize filenames, use random names |\n| Content-type confusion | Browser MIME sniffing | Set `X-Content-Type-Options: nosniff` |\n\n#### Magic Bytes Reference\n\n| Type | Magic Bytes (hex) |\n|------|-------------------|\n| JPEG | `FF D8 FF` |\n| PNG | `89 50 4E 47 0D 0A 1A 0A` |\n| GIF | `47 49 46 38` |\n| PDF | `25 50 44 46` |\n| ZIP | `50 4B 03 04` |\n| DOCX\u002FXLSX | `50 4B 03 04` (ZIP-based) |\n\n#### Secure Upload Handling\n\n1. **Rename files**: Use random UUID names, discard original\n2. **Store outside webroot**: Or use separate domain for uploads\n3. **Serve with correct headers**:\n   - `Content-Disposition: attachment` (forces download)\n   - `X-Content-Type-Options: nosniff`\n   - `Content-Type` matching actual file type\n4. **Use CDN\u002Fseparate domain**: Isolate uploaded content from main app\n5. **Set restrictive permissions**: Uploaded files should not be executable\n\n---\n\n### SQL Injection\n\nSQL injection occurs when user input is incorporated into SQL queries without proper handling.\n\n#### Prevention Methods\n\n**1. Parameterized Queries (Prepared Statements)** — PRIMARY DEFENSE\n```sql\n-- VULNERABLE\nquery = \"SELECT * FROM users WHERE id = \" + userId\n\n-- SECURE\nquery = \"SELECT * FROM users WHERE id = ?\"\nexecute(query, [userId])\n```\n\n**2. ORM Usage**\n- Use ORM methods that automatically parameterize\n- Be cautious with raw query methods in ORMs\n- Watch for ORM-specific injection points\n\n**3. Input Validation**\n- Validate data types (integer should be integer)\n- Whitelist allowed values where applicable\n- This is defense-in-depth, not primary defense\n\n#### Injection Points to Watch\n\n- WHERE clauses\n- ORDER BY clauses (often overlooked—can't use parameters, must whitelist)\n- LIMIT\u002FOFFSET values\n- Table and column names (can't parameterize—must whitelist)\n- INSERT values\n- UPDATE SET values\n- IN clauses with dynamic lists\n- LIKE patterns (also escape wildcards: %, _)\n\n#### Additional Defenses\n\n- **Least privilege**: Database user should have minimum required permissions\n- **Disable dangerous functions**: Like `xp_cmdshell` in SQL Server\n- **Error handling**: Never expose SQL errors to users\n\n---\n\n### XML External Entity (XXE)\n\nXXE vulnerabilities occur when XML parsers process external entity references in user-supplied XML.\n\n#### Vulnerable Scenarios\n\n**Direct XML Input:**\n- SOAP APIs\n- XML-RPC\n- XML file uploads\n- Configuration file parsing\n- RSS\u002FAtom feed processing\n\n**Indirect XML:**\n- JSON\u002Fother format converted to XML server-side\n- Office documents (DOCX, XLSX, PPTX are ZIP with XML)\n- SVG files (XML-based)\n- SAML assertions\n- PDF with XFA forms\n\n\n#### Prevention by Language\u002FParser\n\n**Java:**\n```java\nDocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\ndbf.setFeature(\"http:\u002F\u002Fapache.org\u002Fxml\u002Ffeatures\u002Fdisallow-doctype-decl\", true);\ndbf.setFeature(\"http:\u002F\u002Fxml.org\u002Fsax\u002Ffeatures\u002Fexternal-general-entities\", false);\ndbf.setFeature(\"http:\u002F\u002Fxml.org\u002Fsax\u002Ffeatures\u002Fexternal-parameter-entities\", false);\ndbf.setExpandEntityReferences(false);\n```\n\n**Python (lxml):**\n```python\nfrom lxml import etree\nparser = etree.XMLParser(resolve_entities=False, no_network=True)\n# Or use defusedxml library\n```\n\n**PHP:**\n```php\nlibxml_disable_entity_loader(true);\n\u002F\u002F Or use XMLReader with proper settings\n```\n\n**Node.js:**\n```javascript\n\u002F\u002F Use libraries that disable DTD processing by default\n\u002F\u002F If using libxmljs, set { noent: false, dtdload: false }\n```\n\n**.NET:**\n```csharp\nXmlReaderSettings settings = new XmlReaderSettings();\nsettings.DtdProcessing = DtdProcessing.Prohibit;\nsettings.XmlResolver = null;\n```\n\n#### XXE Prevention Checklist\n\n- [ ] Disable DTD processing entirely if possible\n- [ ] Disable external entity resolution\n- [ ] Disable external DTD loading\n- [ ] Disable XInclude processing\n- [ ] Use latest patched XML parser versions\n- [ ] Validate\u002Fsanitize XML before parsing if DTD needed\n- [ ] Consider using JSON instead of XML where possible\n\n---\n\n### Path Traversal\n\nPath traversal vulnerabilities occur when user input controls file paths, allowing access to files outside intended directories.\n\n#### Vulnerable Patterns\n\n```python\n# VULNERABLE\nfile_path = \"\u002Fuploads\u002F\" + user_input\nfile_path = base_dir + request.params['file']\ntemplate = \"templates\u002F\" + user_provided_template\n```\n\n#### Prevention Strategies\n\n**1. Avoid User Input in Paths**\n```python\n# Instead of using user input directly\n# Use indirect references\nfiles = {'report': '\u002Freports\u002Fq1.pdf', 'invoice': '\u002Finvoices\u002F2024.pdf'}\nfile_path = files.get(user_input)  # Returns None if invalid\n```\n\n**2. Canonicalization and Validation**\n\n```python\nimport os\n\ndef safe_join(base_directory, user_path):\n    # Ensure base is absolute and normalized\n    base = os.path.abspath(os.path.realpath(base_directory))\n    \n    # Join and then resolve the result\n    target = os.path.abspath(os.path.realpath(os.path.join(base, user_path)))\n    \n    # Ensure the commonpath is the base directory\n    if os.path.commonpath([base, target]) != base:\n        raise ValueError(\"Error!\")\n    \n    return target\n```\n\n**3. Input Sanitization**\n- Remove or reject `..` sequences\n- Remove or reject absolute path indicators (`\u002F`, `C:`)\n- Whitelist allowed characters (alphanumeric, dash, underscore)\n- Validate file extension if applicable\n\n\n#### Path Traversal Checklist\n\n- [ ] Never use user input directly in file paths\n- [ ] Canonicalize paths and validate against base directory\n- [ ] Restrict file extensions if applicable\n- [ ] Test with various encoding and bypass techniques\n\n---\n\n## Security Headers Checklist\n\nInclude these headers in all responses:\n\n```\nStrict-Transport-Security: max-age=31536000; includeSubDomains; preload\nContent-Security-Policy: [see XSS section]\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\nReferrer-Policy: strict-origin-when-cross-origin\nCache-Control: no-store (for sensitive pages)\n```\n\n---\n\n## JWT Security\n\nJWT misconfigurations can lead to full authentication bypass and token forgery.\n\n### Vulnerabilities\n\n| Vulnerability | Prevention |\n|---------------|------------|\n| `alg: none` attack | Always verify algorithm server-side, reject `none` |\n| Algorithm confusion | Explicitly specify expected algorithm, never derive from token |\n| Weak HMAC secrets | Use 256+ bit cryptographically random secrets |\n| Missing expiration | Always set `exp` claim |\n| Token in localStorage | Store in httpOnly, Secure, SameSite=Strict cookies, never localStorage |\n\n\n### Secure Implementation\n\n```javascript\n\u002F\u002F 1. SIGNING\n\u002F\u002F Always use environment variables for secrets\nconst secret = process.env.JWT_SECRET; \n\nconst token = jwt.sign({\n  sub: userId,\n  iat: Math.floor(Date.now() \u002F 1000),\n  exp: Math.floor(Date.now() \u002F 1000) + (15 * 60), \u002F\u002F 15 mins (Short-lived)\n  jti: crypto.randomUUID() \u002F\u002F Unique ID for revocation\u002Fblacklisting\n}, secret, { \n  algorithm: 'HS256' \n});\n\n\u002F\u002F 2. SENDING (Cookie Best Practices)\n\u002F\u002F Protect against XSS and CSRF\nres.cookie('token', token, {\n  httpOnly: true, \n  secure: true,    \n  sameSite: 'strict'\n});\n\n\u002F\u002F 3. VERIFYING\n\u002F\u002F CRITICAL: Whitelist the allowed algorithm\njwt.verify(token, secret, { algorithms: ['HS256'] }, (err, decoded) => {\n  if (err) {\n    \u002F\u002F Handle invalid token\n  }\n  \u002F\u002F Trust the payload\n});\n```\n\n### JWT Checklist\n\n- [ ] Algorithm explicitly specified on verification (never trust token header)\n- [ ] `alg: none` rejected\n- [ ] Secret is 256+ bits of random data (not a password or phrase)\n- [ ] `exp` claim always set and validated\n- [ ] Tokens stored in httpOnly cookies (not localStorage\u002FsessionStorage)\n- [ ] Refresh token rotation implemented (old refresh token invalidated on use)\n\n---\n\n## API Security\n\n### Mass Assignment\n\nAccepting unfiltered request bodies can lead to privilege escalation.\n\n```javascript\n\u002F\u002F VULNERABLE — user can set { role: \"admin\" } in request body\nUser.update(req.body)\n\n\u002F\u002F SECURE — whitelist allowed fields\nconst allowed = ['name', 'email', 'avatar']\nconst updates = pick(req.body, allowed)\nUser.update(updates)\n```\n\nThis applies to any ORM\u002Fframework — always explicitly define which fields a request can modify.\n\n### GraphQL\n\n| Vulnerability | Prevention |\n| :--- | :--- |\n| Introspection in production | Disable introspection in production environments. |\n| Query depth attack | Implement query depth limiting (e.g., maximum of 10 levels). |\n| Query complexity attack | Calculate and enforce strict query cost limits. |\n| Batching attack | Limit the number of operations allowed per single request. |\n\n\n```javascript\nconst server = new ApolloServer({\n  introspection: process.env.NODE_ENV !== 'production',\n  validationRules: [\n    depthLimit(10),\n    costAnalysis({ maximumCost: 1000 })\n  ]\n})\n```\n\n---\n\n## General Security Principles\n\nWhen generating code, always:\n\n1. **Validate all input server-side** — Never trust client-side validation alone\n2. **Use parameterized queries** — Never concatenate user input into queries\n3. **Encode output contextually** — HTML, JS, URL, CSS contexts need different encoding\n4. **Apply authentication checks** — On every endpoint, not just at routing\n5. **Apply authorization checks** — Verify the user can access the specific resource\n6. **Use secure defaults**\n7. **Handle errors securely** — Don't leak stack traces or internal details to users\n8. **Keep dependencies updated** — Use tools to track vulnerable dependencies\n\nWhen unsure, choose the more restrictive\u002Fsecure option and document the security consideration in comments.\n",{"name":5,"description":7},"master","6c848afa5711ab2dcc21c03262db6a1d113ce090","security\u002Fvibesec","https:\u002F\u002Fgithub.com\u002Fhillzeealex\u002Fskills","https:\u002F\u002Fgithub.com\u002Fhillzeealex","I turn ideas into products that scale · Agentic AI, custom agent harnesses, MCP · DevOps & CI\u002FCD · Swiss & EU, nLPD\u002FGDPR","2026-07-06 20:37:55",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add hillzeealex\u002Fskills --skill VibeSec-Skill",{"tool":38,"command":39},"bunx","bunx skills add hillzeealex\u002Fskills --skill VibeSec-Skill",{"tool":41,"command":42},"pnpm","pnpm dlx skills add hillzeealex\u002Fskills --skill VibeSec-Skill","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhillzeealex\u002Fskills\u002Fblob\u002Fmaster\u002Fsecurity\u002Fvibesec\u002FSKILL.md",true,[46,50],{"path":47,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":16},"LICENSE","许可证",11357,{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"README.md","REFERENCE","参考文档",4310,"https:\u002F\u002Fgithub.com\u002Fhillzeealex\u002Fskills\u002Fblob\u002Fmaster\u002Fsecurity\u002Fvibesec\u002FREADME.md",[57],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":61,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":20},"01M77JG71Y3VV8EMWAG0TR8ZHT","karpathy-guidelines","Behavioral guidelines to reduce common LLM coding mistakes. Use when writing, reviewing, or refactoring code to avoid overcomplication, make surgical changes, surface assumptions, and define verifiable success criteria.","MIT","https:\u002F\u002Fgithub.com\u002Fhillzeealex\u002Fskills\u002Fblob\u002Fmaster\u002Fengineering\u002Fkarpathy-guidelines\u002FSKILL.md",[],[]]