[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M74G0EB19WBE6T2FSGPH1ATC":3,"skill-same:01M74G0EB19WBE6T2FSGPH1ATC":52},{"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":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M74G0EB19WBE6T2FSGPH1ATC","security-and-hardening",null,"Hardens code against vulnerabilities. Use when auditing an input handler for vulnerabilities, when handling user input, authentication, data storage, or external integrations, or when checking a login flow is safe against the OWASP Top Ten. Use when building any feature that accepts untrusted data, manages user sessions, or interacts with third-party services. Use when auditing dependencies for known vulnerabilities, triaging package-manager audit findings, or assessing supply-chain risk in a new package. Use when personal data or privacy compliance (GDPR, CCPA) is involved.","casualjim\u002Fpi-mimir","casualjim","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F456109?v=4","01M74FWNWVYZQ29YNASRYNTCG4","Ivan Porto Carrero","01M74FWNXE5R8481XV0Q8Q7EY0",16,"MIT","https:\u002F\u002Fgithub.com\u002Fcasualjim\u002Fpi-mimir\u002Fblob\u002Fmain\u002Fpackages\u002Fpi-addy-skills\u002Fskills\u002Fsecurity-and-hardening\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: security-and-hardening\ndescription: Hardens code against vulnerabilities. Use when auditing an input handler for vulnerabilities, when handling user input, authentication, data storage, or external integrations, or when checking a login flow is safe against the OWASP Top Ten. Use when building any feature that accepts untrusted data, manages user sessions, or interacts with third-party services. Use when auditing dependencies for known vulnerabilities, triaging package-manager audit findings, or assessing supply-chain risk in a new package. Use when personal data or privacy compliance (GDPR, CCPA) is involved.\n---\n\n# Security and Hardening\n\n## Overview\n\nSecurity-first development practices for web applications. Treat every external input as hostile, every secret as sacred, and every authorization check as mandatory. Security isn't a phase — it's a constraint on every line of code that touches user data, authentication, or external systems.\n\n## When to Use\n\n- Building anything that accepts user input\n- Implementing authentication or authorization\n- Storing or transmitting sensitive data\n- Integrating with external APIs or services\n- Adding file uploads, webhooks, or callbacks\n- Handling payment or PII data\n\n## Process: Threat Model First\n\nControls bolted on without a threat model are guesses. Before hardening, spend five minutes thinking like an attacker:\n\n1. **Map the trust boundaries.** Where does untrusted data cross into your system? HTTP requests, form fields, file uploads, webhooks, third-party APIs, message queues, and **LLM output** — plus the local values that look internal because the OS handed them to you: another process's command line or environment, filenames on a shared volume, a path in a job payload. Trust follows who *wrote* a value, not which channel delivered it. Every boundary is attack surface.\n2. **Name the assets.** What's worth stealing or breaking? Credentials, PII, payment data, admin actions, money movement.\n3. **Run STRIDE over each boundary** — a quick lens, not a ceremony:\n\n| Threat | Ask | Typical mitigation |\n|---|---|---|\n| **S**poofing | Can someone impersonate a user\u002Fservice? | Authentication, signature verification |\n| **T**ampering | Can data be altered in transit or at rest? | Integrity checks, parameterized queries, HTTPS |\n| **R**epudiation | Can an action be denied later? | Audit logging of security events |\n| **I**nformation disclosure | Can data leak? | Encryption, field allowlists, generic errors |\n| **D**enial of service | Can it be overwhelmed? | Rate limiting, input size caps, timeouts |\n| **E**levation of privilege | Can a user gain rights they shouldn't? | Authorization checks, least privilege |\n\n4. **Write abuse cases next to use cases.** For each feature, ask \"how would I misuse this?\" — then make that your first test.\n\nIf you can't name the trust boundaries for a feature, you're not ready to secure it. This is OWASP **A04: Insecure Design** — most breaches begin in design, not code.\n\n## The Three-Tier Boundary System\n\n### Always Do (No Exceptions)\n\n- **Validate all external input** at the system boundary (API routes, form handlers)\n- **Parameterize all database queries** — never concatenate user input into SQL\n- **Encode output** to prevent XSS (use framework auto-escaping, don't bypass it)\n- **Use HTTPS** for all external communication\n- **Hash passwords** with bcrypt\u002Fscrypt\u002Fargon2 (never store plaintext)\n- **Set security headers** (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)\n- **Use httpOnly, secure, sameSite cookies** for sessions\n- **Run the detected package manager's native audit** against the committed lockfile before every release\n\n### Ask First (Requires Human Approval)\n\n- Adding new authentication flows or changing auth logic\n- Storing new categories of sensitive data (PII, payment info)\n- Adding new external service integrations\n- Changing CORS configuration\n- Adding file upload handlers\n- Modifying rate limiting or throttling\n- Granting elevated permissions or roles\n\n### Never Do\n\n- **Never commit secrets** to version control (API keys, passwords, tokens)\n- **Never log sensitive data** (passwords, tokens, full credit card numbers)\n- **Never trust client-side validation** as a security boundary\n- **Never disable security headers** for convenience\n- **Never use `eval()` or `innerHTML`** with user-provided data\n- **Never store sessions in client-accessible storage** (localStorage for auth tokens)\n- **Never expose stack traces** or internal error details to users\n\n## Hardening Controls\n\nThe rules below are the workflow; a concrete implementation of each lives in [references\u002Fhardening-patterns.md](references\u002Fhardening-patterns.md). Open the section you need when you reach that code, not before.\n\n### Injection, XSS, and access control\n\n- Parameterize every query. Never build SQL, NoSQL, or shell commands from input strings.\n- Encode output through the framework's auto-escaping. If raw HTML is unavoidable, sanitize with an allowlist sanitizer first.\n- Check **authorization** on every request, not just authentication: the authenticated user must own, or be permitted on, the specific resource (A01, IDOR).\n\nPatterns: [Injection](references\u002Fhardening-patterns.md#injection), [XSS](references\u002Fhardening-patterns.md#cross-site-scripting-xss), [Access control](references\u002Fhardening-patterns.md#broken-access-control).\n\n### Authentication and sessions\n\n- Hash passwords with bcrypt (≥12 rounds), scrypt, or argon2. The session secret comes from the environment, never from code.\n- Session cookies are `httpOnly`, `secure`, and `sameSite: 'lax'` or `'strict'` (the CSRF defense; `'none'` sends the cookie on cross-site requests), with a bounded `maxAge`.\n\nPattern: [Authentication](references\u002Fhardening-patterns.md#broken-authentication).\n\n### Headers, CORS, and responses\n\n- Security headers on every response (helmet or the framework equivalent); CSP starts from `default-src 'self'` and is tightened, not loosened.\n- CORS restricted to an explicit origin list from configuration. Never `*` with credentials.\n- Strip sensitive fields (`passwordHash`, reset tokens) before any response. Error bodies are generic; internals go to server logs only.\n\nPatterns: [Misconfiguration](references\u002Fhardening-patterns.md#security-misconfiguration), [Sensitive data exposure](references\u002Fhardening-patterns.md#sensitive-data-exposure).\n\n### Input validation and uploads\n\n- Validate at the boundary with a schema: allowlisted shape, lengths, enums, formats. Reject with 422 and structured details; downstream code uses only the parsed, typed value.\n- Uploads: allowlist MIME types, cap size, verify content (magic bytes) when it matters. The extension proves nothing.\n\nPatterns: [Schema validation](references\u002Fhardening-patterns.md#schema-validation-at-boundaries), [File upload](references\u002Fhardening-patterns.md#file-upload-safety).\n\n### Server-side fetches (SSRF)\n\nAny URL the user influences — webhooks, import-from-URL, image proxies, link previews — can be aimed at internal services. Allowlist scheme and host, resolve **all** DNS records and reject any private or reserved address (loopback, link-local `169.254.169.254`, private, unique-local, for IPv4 and IPv6), and forbid redirects. That check still has a DNS-rebinding TOCTOU gap: for high-risk surfaces, pin the resolved IP or put a filtering agent in front.\n\nPattern: [SSRF](references\u002Fhardening-patterns.md#server-side-request-forgery-ssrf).\n\n### Destructive operations on derived paths\n\nA delete, move, or overwrite is only as safe as the value naming its target, and trust follows who *wrote* that value, not which channel delivered it: another process's command line is as attacker-controlled as a form field. A shape check proves well-formedness, not authorization. Before the call, require all three: the resolved target (symlinks resolved) sits under an **allowlisted root**; it is at least one level **below** that root; and it carries **ownership evidence read before the operation**. On refusal, log the rejected target and stop; never fall back to a broader default path.\n\nWhy the check is weaker than it reads (marker self-attestation, check\u002Fuse races): [Destructive paths](references\u002Fhardening-patterns.md#destructive-operations-on-derived-paths). Worked code: `..\u002F..\u002Freferences\u002Fsecurity-checklist.md`.\n\n### Rate limiting\n\nLimit the API generally and auth endpoints strictly (about 10 attempts per 15 minutes). Once more than one process serves traffic, in-memory counters silently become `max × instances`, or never fire on serverless: back the limiter with a shared store.\n\nPattern: [Rate limiting](references\u002Fhardening-patterns.md#rate-limiting).\n\n### Secrets\n\nSecrets come from the environment. `.env.example` is committed with placeholders; real `.env*` files and key material are gitignored; grep the staged diff before committing. **A secret that reaches a remote is compromised the moment it lands: rotate it first, then purge history.**\n\nPattern: [Secrets management](references\u002Fhardening-patterns.md#secrets-management).\n\n### Dependencies and supply chain\n\n1. **Find the installation boundary and manager.** Use the workspace root that owns the lockfile, or an independent nested project only when it is outside that workspace. Corroborate `packageManager` (when present), the lockfile, and CI; stop on disagreement or competing lockfiles. Pin the manager version.\n2. **Block dependency scripts before first execution.** Bootstrap with scripts disabled or a documented fail-closed policy, inspect the pending script source, approve only the minimum, commit the policy, then verify with a clean frozen\u002Fimmutable install. Never blanket-approve.\n3. **Run the native audit against the committed lockfile before every release.** Triage critical\u002Fhigh by **reachability** (runtime, build, test, deploy paths) and fix availability. Never apply forced remediation (`npm audit fix --force` or equivalent) automatically, since forced fixes may cross declared dependency ranges; preview, read changelogs, test each upgrade. Document every deferral with a reason and a review date.\n4. **Audits only match known advisories.** They do not catch a newly malicious or typosquatted package (`cross-env` vs `crossenv`). Review new dependencies, lockfile diffs, and script-policy changes together: ownership, maintenance, release age, provenance, transitive graph. Verify registry signatures where supported (`npm audit signatures`, `pnpm audit signatures`) and treat their absence as a signal to investigate, not automatic proof of compromise (A06, LLM03).\n\nTriage decision tree: [Dependency audit triage](references\u002Fhardening-patterns.md#dependency-audit-triage). Manager matrix and install-script gate: `..\u002F..\u002Freferences\u002Fsecurity-checklist.md`.\n\n### Personal data and privacy\n\nHardening asks \"can an attacker read it?\" Privacy asks \"should *we* hold it at all, and for how long?\" The cheapest data to protect, breach, and comply over is the data you never collected; treat personal data as a liability to minimize.\n\n- **Classify fields as you add them** (non-personal, PII, sensitive) and handle each class accordingly. You cannot protect, or honor a deletion request for, data you cannot find.\n- **Collect only against a stated purpose.** \"Might be useful later\" is latent breach scope, not a purpose. Keep PII out of telemetry (the `observability-and-instrumentation` skill makes the same point from the ops side).\n- **Set retention up front, then actually delete.** Every personal-data store needs a TTL and a working deletion path, including backups, caches, search indexes, and analytics copies.\n- **Support the data-subject rights your jurisdiction requires** (GDPR, CCPA, and kin): export, correct, delete. Design the schema so a user's data is findable and erasable, not smeared irreversibly across systems.\n- **Consent gates collection and third-party sharing, and is auditable.** Sending PII to an analytics, ad, or LLM vendor is sharing; the vendor needs a data-processing agreement. Make region a configurable policy, not a hardcoded assumption.\n\nClassification table: [Data classification](references\u002Fhardening-patterns.md#data-classification). A privacy incident starts the breach-notification clock; run the postmortem with the `debugging-and-error-recovery` skill.\n\n### AI \u002F LLM features\n\nCalling an LLM — chatbots, summarizers, agents, RAG — adds a new attack surface; map it to the [OWASP Top 10 for LLM Applications (2025)](https:\u002F\u002Fgenai.owasp.org\u002Fllm-top-10\u002F):\n\n- **Model output is untrusted input** (LLM05). Never into `eval`, SQL, a shell, `innerHTML`, or a file path; parse defensively, validate against a schema, then encode.\n- **Prompts can be hijacked** (LLM01). Untrusted text in the context — a user message, a fetched page, a PDF — can carry instructions. The system prompt is not a security boundary; enforce permissions in code.\n- **Keep secrets, other tenants' data, and the full system prompt out of the context window** (LLM02, LLM07); scope tool permissions, validate every tool argument, and confirm destructive actions (LLM06); cap tokens, request rate, and recursion depth (LLM10); partition RAG embeddings per tenant and validate documents before indexing (LLM08).\n\nPattern: [LLM output handling](references\u002Fhardening-patterns.md#llm-output-handling).\n\n## Review Checklist\n\nBefore sign-off, walk `..\u002F..\u002Freferences\u002Fsecurity-checklist.md`: it covers authentication, authorization, input, data protection and privacy, headers and CORS, dependencies and supply chain, AI\u002FLLM, and error handling, plus the OWASP quick-reference tables.\n\n## Common Rationalizations\n\n| Rationalization | Reality |\n|---|---|\n| \"This is an internal tool, security doesn't matter\" | Internal tools get compromised. Attackers target the weakest link. |\n| \"We'll add security later\" | Security retrofitting is 10x harder than building it in. Add it now. |\n| \"No one would try to exploit this\" | Automated scanners will find it. Security by obscurity is not security. |\n| \"The framework handles security\" | Frameworks provide tools, not guarantees. You still need to use them correctly. |\n| \"It's just a prototype\" | Prototypes become production. Security habits from day one. |\n| \"Threat modeling is overkill here\" | Five minutes of \"how would I attack this?\" prevents the design flaws no control can patch later. |\n| \"It's just LLM output, it's only text\" | That \"text\" can be a SQL statement, a script tag, or a shell command. Treat it like any untrusted input. |\n| \"The audit passed, so the dependency is safe\" | Audits match known advisories. They do not detect a newly malicious package or make unreviewed install scripts safe to execute. |\n| \"Collect it now, we might need it later\" | Data you don't hold can't be breached, subpoenaed, or mis-deleted. \"Might need it\" is breach scope, not a purpose. |\n| \"We'll handle deletion requests manually\" | Manual erasure misses backups, caches, and analytics copies. If the schema can't find a user's data, you can't honor the request — design for it. |\n| \"Compliance is legal's problem, not ours\" | Export, deletion, retention, and consent are schema and code. Legal can't bolt them on after you've smeared PII across ten systems. |\n\n## Red Flags\n\n- User input passed directly to database queries, shell commands, or HTML rendering\n- A delete, move, or overwrite whose target comes from a payload, a config value, or another process's command line, guarded only by a shape check on the path\n- Secrets in source code or commit history\n- API endpoints without authentication or authorization checks\n- Missing CORS configuration or wildcard (`*`) origins\n- No rate limiting on authentication endpoints, or an in-memory limiter in front of more than one instance\n- Stack traces or internal errors exposed to users\n- Dependencies with known critical vulnerabilities, competing lockfiles at one installation boundary, non-reproducible installs, or blanket-approved scripts\n- Server fetches user-supplied URLs without an allowlist (SSRF)\n- LLM\u002Fmodel output passed into a query, the DOM, a shell, or `eval`\n- Secrets, PII, or the full system prompt placed inside an LLM context window\n- Personal data collected with no stated purpose, retention limit, or deletion path\n- PII sent to analytics\u002Fad\u002FLLM vendors with no consent or data-processing agreement\n- \"Delete my account\" that only flips a flag while the personal data lingers in stores and backups\n\n## Verification\n\nAfter implementing security-relevant code:\n\n- [ ] The native audit has no unmitigated reachable critical\u002Fhigh findings; CI preserves the authoritative lockfile and blocks unreviewed dependency scripts\n- [ ] No secrets in source code or git history\n- [ ] All user input validated at system boundaries\n- [ ] Destructive filesystem operations resolve symlinks, then verify allowlisted root, minimum depth, and ownership before running\n- [ ] Authentication and authorization checked on every protected endpoint\n- [ ] Security headers present in response (check with browser DevTools)\n- [ ] Error responses don't expose internal details\n- [ ] Rate limiting active on auth endpoints, backed by a shared store when more than one instance serves traffic\n- [ ] Server-side URL fetches validated against an allowlist (no SSRF)\n- [ ] LLM\u002Fmodel output validated and encoded before use (if AI features present)\n- [ ] Personal data is classified, minimized to a stated purpose, and has a retention limit\n- [ ] Deletion and export requests work end-to-end (including backups, caches, and analytics copies)\n\n## omp tooling\n\n- Run `xd:\u002F\u002Fsecurity_scan` for repo-native and cloud scans; read existing findings through `security:\u002F\u002Fscans` before starting a manual pass.\n- Delegate deep review to `task` with `agent: \"security-reviewer\"` (read-only, evidence-backed findings).\n- Sweep for secrets with `grep` patterns over tracked files; never print or copy full credential values into context.\n- `bash` runs inside the heimdall sandbox; a sandbox denial is not evidence about the real environment.\n","# Security and Hardening\n\n## Overview\n\nSecurity-first development practices for web applications. Treat every external input as hostile, every secret as sacred, and every authorization check as mandatory. Security isn't a phase — it's a constraint on every line of code that touches user data, authentication, or external systems.\n\n## When to Use\n\n- Building anything that accepts user input\n- Implementing authentication or authorization\n- Storing or transmitting sensitive data\n- Integrating with external APIs or services\n- Adding file uploads, webhooks, or callbacks\n- Handling payment or PII data\n\n## Process: Threat Model First\n\nControls bolted on without a threat model are guesses. Before hardening, spend five minutes thinking like an attacker:\n\n1. **Map the trust boundaries.** Where does untrusted data cross into your system? HTTP requests, form fields, file uploads, webhooks, third-party APIs, message queues, and **LLM output** — plus the local values that look internal because the OS handed them to you: another process's command line or environment, filenames on a shared volume, a path in a job payload. Trust follows who *wrote* a value, not which channel delivered it. Every boundary is attack surface.\n2. **Name the assets.** What's worth stealing or breaking? Credentials, PII, payment data, admin actions, money movement.\n3. **Run STRIDE over each boundary** — a quick lens, not a ceremony:\n\n| Threat | Ask | Typical mitigation |\n|---|---|---|\n| **S**poofing | Can someone impersonate a user\u002Fservice? | Authentication, signature verification |\n| **T**ampering | Can data be altered in transit or at rest? | Integrity checks, parameterized queries, HTTPS |\n| **R**epudiation | Can an action be denied later? | Audit logging of security events |\n| **I**nformation disclosure | Can data leak? | Encryption, field allowlists, generic errors |\n| **D**enial of service | Can it be overwhelmed? | Rate limiting, input size caps, timeouts |\n| **E**levation of privilege | Can a user gain rights they shouldn't? | Authorization checks, least privilege |\n\n4. **Write abuse cases next to use cases.** For each feature, ask \"how would I misuse this?\" — then make that your first test.\n\nIf you can't name the trust boundaries for a feature, you're not ready to secure it. This is OWASP **A04: Insecure Design** — most breaches begin in design, not code.\n\n## The Three-Tier Boundary System\n\n### Always Do (No Exceptions)\n\n- **Validate all external input** at the system boundary (API routes, form handlers)\n- **Parameterize all database queries** — never concatenate user input into SQL\n- **Encode output** to prevent XSS (use framework auto-escaping, don't bypass it)\n- **Use HTTPS** for all external communication\n- **Hash passwords** with bcrypt\u002Fscrypt\u002Fargon2 (never store plaintext)\n- **Set security headers** (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)\n- **Use httpOnly, secure, sameSite cookies** for sessions\n- **Run the detected package manager's native audit** against the committed lockfile before every release\n\n### Ask First (Requires Human Approval)\n\n- Adding new authentication flows or changing auth logic\n- Storing new categories of sensitive data (PII, payment info)\n- Adding new external service integrations\n- Changing CORS configuration\n- Adding file upload handlers\n- Modifying rate limiting or throttling\n- Granting elevated permissions or roles\n\n### Never Do\n\n- **Never commit secrets** to version control (API keys, passwords, tokens)\n- **Never log sensitive data** (passwords, tokens, full credit card numbers)\n- **Never trust client-side validation** as a security boundary\n- **Never disable security headers** for convenience\n- **Never use `eval()` or `innerHTML`** with user-provided data\n- **Never store sessions in client-accessible storage** (localStorage for auth tokens)\n- **Never expose stack traces** or internal error details to users\n\n## Hardening Controls\n\nThe rules below are the workflow; a concrete implementation of each lives in [references\u002Fhardening-patterns.md](references\u002Fhardening-patterns.md). Open the section you need when you reach that code, not before.\n\n### Injection, XSS, and access control\n\n- Parameterize every query. Never build SQL, NoSQL, or shell commands from input strings.\n- Encode output through the framework's auto-escaping. If raw HTML is unavoidable, sanitize with an allowlist sanitizer first.\n- Check **authorization** on every request, not just authentication: the authenticated user must own, or be permitted on, the specific resource (A01, IDOR).\n\nPatterns: [Injection](references\u002Fhardening-patterns.md#injection), [XSS](references\u002Fhardening-patterns.md#cross-site-scripting-xss), [Access control](references\u002Fhardening-patterns.md#broken-access-control).\n\n### Authentication and sessions\n\n- Hash passwords with bcrypt (≥12 rounds), scrypt, or argon2. The session secret comes from the environment, never from code.\n- Session cookies are `httpOnly`, `secure`, and `sameSite: 'lax'` or `'strict'` (the CSRF defense; `'none'` sends the cookie on cross-site requests), with a bounded `maxAge`.\n\nPattern: [Authentication](references\u002Fhardening-patterns.md#broken-authentication).\n\n### Headers, CORS, and responses\n\n- Security headers on every response (helmet or the framework equivalent); CSP starts from `default-src 'self'` and is tightened, not loosened.\n- CORS restricted to an explicit origin list from configuration. Never `*` with credentials.\n- Strip sensitive fields (`passwordHash`, reset tokens) before any response. Error bodies are generic; internals go to server logs only.\n\nPatterns: [Misconfiguration](references\u002Fhardening-patterns.md#security-misconfiguration), [Sensitive data exposure](references\u002Fhardening-patterns.md#sensitive-data-exposure).\n\n### Input validation and uploads\n\n- Validate at the boundary with a schema: allowlisted shape, lengths, enums, formats. Reject with 422 and structured details; downstream code uses only the parsed, typed value.\n- Uploads: allowlist MIME types, cap size, verify content (magic bytes) when it matters. The extension proves nothing.\n\nPatterns: [Schema validation](references\u002Fhardening-patterns.md#schema-validation-at-boundaries), [File upload](references\u002Fhardening-patterns.md#file-upload-safety).\n\n### Server-side fetches (SSRF)\n\nAny URL the user influences — webhooks, import-from-URL, image proxies, link previews — can be aimed at internal services. Allowlist scheme and host, resolve **all** DNS records and reject any private or reserved address (loopback, link-local `169.254.169.254`, private, unique-local, for IPv4 and IPv6), and forbid redirects. That check still has a DNS-rebinding TOCTOU gap: for high-risk surfaces, pin the resolved IP or put a filtering agent in front.\n\nPattern: [SSRF](references\u002Fhardening-patterns.md#server-side-request-forgery-ssrf).\n\n### Destructive operations on derived paths\n\nA delete, move, or overwrite is only as safe as the value naming its target, and trust follows who *wrote* that value, not which channel delivered it: another process's command line is as attacker-controlled as a form field. A shape check proves well-formedness, not authorization. Before the call, require all three: the resolved target (symlinks resolved) sits under an **allowlisted root**; it is at least one level **below** that root; and it carries **ownership evidence read before the operation**. On refusal, log the rejected target and stop; never fall back to a broader default path.\n\nWhy the check is weaker than it reads (marker self-attestation, check\u002Fuse races): [Destructive paths](references\u002Fhardening-patterns.md#destructive-operations-on-derived-paths). Worked code: `..\u002F..\u002Freferences\u002Fsecurity-checklist.md`.\n\n### Rate limiting\n\nLimit the API generally and auth endpoints strictly (about 10 attempts per 15 minutes). Once more than one process serves traffic, in-memory counters silently become `max × instances`, or never fire on serverless: back the limiter with a shared store.\n\nPattern: [Rate limiting](references\u002Fhardening-patterns.md#rate-limiting).\n\n### Secrets\n\nSecrets come from the environment. `.env.example` is committed with placeholders; real `.env*` files and key material are gitignored; grep the staged diff before committing. **A secret that reaches a remote is compromised the moment it lands: rotate it first, then purge history.**\n\nPattern: [Secrets management](references\u002Fhardening-patterns.md#secrets-management).\n\n### Dependencies and supply chain\n\n1. **Find the installation boundary and manager.** Use the workspace root that owns the lockfile, or an independent nested project only when it is outside that workspace. Corroborate `packageManager` (when present), the lockfile, and CI; stop on disagreement or competing lockfiles. Pin the manager version.\n2. **Block dependency scripts before first execution.** Bootstrap with scripts disabled or a documented fail-closed policy, inspect the pending script source, approve only the minimum, commit the policy, then verify with a clean frozen\u002Fimmutable install. Never blanket-approve.\n3. **Run the native audit against the committed lockfile before every release.** Triage critical\u002Fhigh by **reachability** (runtime, build, test, deploy paths) and fix availability. Never apply forced remediation (`npm audit fix --force` or equivalent) automatically, since forced fixes may cross declared dependency ranges; preview, read changelogs, test each upgrade. Document every deferral with a reason and a review date.\n4. **Audits only match known advisories.** They do not catch a newly malicious or typosquatted package (`cross-env` vs `crossenv`). Review new dependencies, lockfile diffs, and script-policy changes together: ownership, maintenance, release age, provenance, transitive graph. Verify registry signatures where supported (`npm audit signatures`, `pnpm audit signatures`) and treat their absence as a signal to investigate, not automatic proof of compromise (A06, LLM03).\n\nTriage decision tree: [Dependency audit triage](references\u002Fhardening-patterns.md#dependency-audit-triage). Manager matrix and install-script gate: `..\u002F..\u002Freferences\u002Fsecurity-checklist.md`.\n\n### Personal data and privacy\n\nHardening asks \"can an attacker read it?\" Privacy asks \"should *we* hold it at all, and for how long?\" The cheapest data to protect, breach, and comply over is the data you never collected; treat personal data as a liability to minimize.\n\n- **Classify fields as you add them** (non-personal, PII, sensitive) and handle each class accordingly. You cannot protect, or honor a deletion request for, data you cannot find.\n- **Collect only against a stated purpose.** \"Might be useful later\" is latent breach scope, not a purpose. Keep PII out of telemetry (the `observability-and-instrumentation` skill makes the same point from the ops side).\n- **Set retention up front, then actually delete.** Every personal-data store needs a TTL and a working deletion path, including backups, caches, search indexes, and analytics copies.\n- **Support the data-subject rights your jurisdiction requires** (GDPR, CCPA, and kin): export, correct, delete. Design the schema so a user's data is findable and erasable, not smeared irreversibly across systems.\n- **Consent gates collection and third-party sharing, and is auditable.** Sending PII to an analytics, ad, or LLM vendor is sharing; the vendor needs a data-processing agreement. Make region a configurable policy, not a hardcoded assumption.\n\nClassification table: [Data classification](references\u002Fhardening-patterns.md#data-classification). A privacy incident starts the breach-notification clock; run the postmortem with the `debugging-and-error-recovery` skill.\n\n### AI \u002F LLM features\n\nCalling an LLM — chatbots, summarizers, agents, RAG — adds a new attack surface; map it to the [OWASP Top 10 for LLM Applications (2025)](https:\u002F\u002Fgenai.owasp.org\u002Fllm-top-10\u002F):\n\n- **Model output is untrusted input** (LLM05). Never into `eval`, SQL, a shell, `innerHTML`, or a file path; parse defensively, validate against a schema, then encode.\n- **Prompts can be hijacked** (LLM01). Untrusted text in the context — a user message, a fetched page, a PDF — can carry instructions. The system prompt is not a security boundary; enforce permissions in code.\n- **Keep secrets, other tenants' data, and the full system prompt out of the context window** (LLM02, LLM07); scope tool permissions, validate every tool argument, and confirm destructive actions (LLM06); cap tokens, request rate, and recursion depth (LLM10); partition RAG embeddings per tenant and validate documents before indexing (LLM08).\n\nPattern: [LLM output handling](references\u002Fhardening-patterns.md#llm-output-handling).\n\n## Review Checklist\n\nBefore sign-off, walk `..\u002F..\u002Freferences\u002Fsecurity-checklist.md`: it covers authentication, authorization, input, data protection and privacy, headers and CORS, dependencies and supply chain, AI\u002FLLM, and error handling, plus the OWASP quick-reference tables.\n\n## Common Rationalizations\n\n| Rationalization | Reality |\n|---|---|\n| \"This is an internal tool, security doesn't matter\" | Internal tools get compromised. Attackers target the weakest link. |\n| \"We'll add security later\" | Security retrofitting is 10x harder than building it in. Add it now. |\n| \"No one would try to exploit this\" | Automated scanners will find it. Security by obscurity is not security. |\n| \"The framework handles security\" | Frameworks provide tools, not guarantees. You still need to use them correctly. |\n| \"It's just a prototype\" | Prototypes become production. Security habits from day one. |\n| \"Threat modeling is overkill here\" | Five minutes of \"how would I attack this?\" prevents the design flaws no control can patch later. |\n| \"It's just LLM output, it's only text\" | That \"text\" can be a SQL statement, a script tag, or a shell command. Treat it like any untrusted input. |\n| \"The audit passed, so the dependency is safe\" | Audits match known advisories. They do not detect a newly malicious package or make unreviewed install scripts safe to execute. |\n| \"Collect it now, we might need it later\" | Data you don't hold can't be breached, subpoenaed, or mis-deleted. \"Might need it\" is breach scope, not a purpose. |\n| \"We'll handle deletion requests manually\" | Manual erasure misses backups, caches, and analytics copies. If the schema can't find a user's data, you can't honor the request — design for it. |\n| \"Compliance is legal's problem, not ours\" | Export, deletion, retention, and consent are schema and code. Legal can't bolt them on after you've smeared PII across ten systems. |\n\n## Red Flags\n\n- User input passed directly to database queries, shell commands, or HTML rendering\n- A delete, move, or overwrite whose target comes from a payload, a config value, or another process's command line, guarded only by a shape check on the path\n- Secrets in source code or commit history\n- API endpoints without authentication or authorization checks\n- Missing CORS configuration or wildcard (`*`) origins\n- No rate limiting on authentication endpoints, or an in-memory limiter in front of more than one instance\n- Stack traces or internal errors exposed to users\n- Dependencies with known critical vulnerabilities, competing lockfiles at one installation boundary, non-reproducible installs, or blanket-approved scripts\n- Server fetches user-supplied URLs without an allowlist (SSRF)\n- LLM\u002Fmodel output passed into a query, the DOM, a shell, or `eval`\n- Secrets, PII, or the full system prompt placed inside an LLM context window\n- Personal data collected with no stated purpose, retention limit, or deletion path\n- PII sent to analytics\u002Fad\u002FLLM vendors with no consent or data-processing agreement\n- \"Delete my account\" that only flips a flag while the personal data lingers in stores and backups\n\n## Verification\n\nAfter implementing security-relevant code:\n\n- [ ] The native audit has no unmitigated reachable critical\u002Fhigh findings; CI preserves the authoritative lockfile and blocks unreviewed dependency scripts\n- [ ] No secrets in source code or git history\n- [ ] All user input validated at system boundaries\n- [ ] Destructive filesystem operations resolve symlinks, then verify allowlisted root, minimum depth, and ownership before running\n- [ ] Authentication and authorization checked on every protected endpoint\n- [ ] Security headers present in response (check with browser DevTools)\n- [ ] Error responses don't expose internal details\n- [ ] Rate limiting active on auth endpoints, backed by a shared store when more than one instance serves traffic\n- [ ] Server-side URL fetches validated against an allowlist (no SSRF)\n- [ ] LLM\u002Fmodel output validated and encoded before use (if AI features present)\n- [ ] Personal data is classified, minimized to a stated purpose, and has a retention limit\n- [ ] Deletion and export requests work end-to-end (including backups, caches, and analytics copies)\n\n## omp tooling\n\n- Run `xd:\u002F\u002Fsecurity_scan` for repo-native and cloud scans; read existing findings through `security:\u002F\u002Fscans` before starting a manual pass.\n- Delegate deep review to `task` with `agent: \"security-reviewer\"` (read-only, evidence-backed findings).\n- Sweep for secrets with `grep` patterns over tracked files; never print or copy full credential values into context.\n- `bash` runs inside the heimdall sandbox; a sandbox denial is not evidence about the real environment.\n",{"name":5,"description":7},"main","86a206d111fba4ffc9c47c363486479262e63513","packages\u002Fpi-addy-skills\u002Fskills\u002Fsecurity-and-hardening",9,"https:\u002F\u002Fgithub.com\u002Fcasualjim\u002Fpi-mimir","https:\u002F\u002Fgithub.com\u002Fcasualjim","http:\u002F\u002Fflanders.co.nz","2026-11-10 15:32:15",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add casualjim\u002Fpi-mimir --skill security-and-hardening",{"tool":38,"command":39},"bunx","bunx skills add casualjim\u002Fpi-mimir --skill security-and-hardening",{"tool":41,"command":42},"pnpm","pnpm dlx skills add casualjim\u002Fpi-mimir --skill security-and-hardening","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fcasualjim\u002Fpi-mimir\u002Fblob\u002Fmain\u002Fpackages\u002Fpi-addy-skills\u002Fskills\u002Fsecurity-and-hardening\u002FSKILL.md",true,[46],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},"references\u002Fhardening-patterns.md","REFERENCE","参考文档",13036,"https:\u002F\u002Fgithub.com\u002Fcasualjim\u002Fpi-mimir\u002Fblob\u002Fmain\u002Fpackages\u002Fpi-addy-skills\u002Fskills\u002Fsecurity-and-hardening\u002Freferences\u002Fhardening-patterns.md",[53,60,67,74,81,88],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M74GK3CG2X0988XMHBKNC0HG","why","Use for 'why does X work this way', 'why we picked Y', design rationale, regressions, postmortems, or data-backed thresholds. Discovers available MCPs and queries each evidence category (source control, issue tracker, long-form docs, real-time chat, infrastructure observability, error tracking, product analytics warehouse) in parallel, then returns a cited read on decisions and tradeoffs. Use how for runtime behavior.","https:\u002F\u002Fgithub.com\u002Fcasualjim\u002Fpi-mimir\u002Fblob\u002Fmain\u002Fpackages\u002Fpi-pstack\u002Fskills\u002Fwhy\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M74GK2A4034JSAN8BCGBEPVB","unslop","Cut AI tells from any writing.","https:\u002F\u002Fgithub.com\u002Fcasualjim\u002Fpi-mimir\u002Fblob\u002Fmain\u002Fpackages\u002Fpi-pstack\u002Fskills\u002Funslop\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M74GK13302GXTR58TM47BQY1","typescript-best-practices","TypeScript best practices. Use when reading or editing any .ts or .tsx file.","https:\u002F\u002Fgithub.com\u002Fcasualjim\u002Fpi-mimir\u002Fblob\u002Fmain\u002Fpackages\u002Fpi-pstack\u002Fskills\u002Ftypescript-best-practices\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M74GJYB1DJCA4AQH22MWYM9J","technical-writing","Layered technical-writing standard: Diátaxis structure, Google developer style sentences, STE instruction rules, Global English syntax. Use for \u002Fskill:technical-writing or when writing or reviewing docs, RFCs, readmes, PR descriptions, or commit messages.","https:\u002F\u002Fgithub.com\u002Fcasualjim\u002Fpi-mimir\u002Fblob\u002Fmain\u002Fpackages\u002Fpi-pstack\u002Fskills\u002Ftechnical-writing\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M74GJW7794XM60AKH76941T0","teach","Explain a body of work plainly so a person actually understands it. Runs the `how` and `why` skills and weaves what they find into one clear explanation. Use for 'teach me this', 'help me really understand X', 'explain this change or subsystem to me'.","https:\u002F\u002Fgithub.com\u002Fcasualjim\u002Fpi-mimir\u002Fblob\u002Fmain\u002Fpackages\u002Fpi-pstack\u002Fskills\u002Fteach\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M74GJPQN3RW4FN7G78W2NFR1","tdd","Use only when the user explicitly asks for TDD, a failing test, or a regression test, OR when the bug has an obvious cheap local test target. Skip when the test path is unclear, expensive, integration-heavy, or not requested.","https:\u002F\u002Fgithub.com\u002Fcasualjim\u002Fpi-mimir\u002Fblob\u002Fmain\u002Fpackages\u002Fpi-pstack\u002Fskills\u002Ftdd\u002FSKILL.md",[],[]]