@givolt/i3-composer-agent 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/.agents/plugins/marketplace.json +23 -0
  2. package/.claude/commands/build.md +44 -0
  3. package/.claude/commands/code-simplify.md +22 -0
  4. package/.claude/commands/constraints.md +32 -0
  5. package/.claude/commands/plan.md +18 -0
  6. package/.claude/commands/review.md +16 -0
  7. package/.claude/commands/ship.md +72 -0
  8. package/.claude/commands/spec.md +17 -0
  9. package/.claude/commands/test.md +19 -0
  10. package/.claude/commands/webperf.md +32 -0
  11. package/.claude-plugin/marketplace.json +27 -0
  12. package/.claude-plugin/plugin.json +19 -0
  13. package/.codex-plugin/plugin.json +28 -0
  14. package/.gemini/commands/build.toml +43 -0
  15. package/.gemini/commands/code-simplify.toml +22 -0
  16. package/.gemini/commands/constraints.toml +32 -0
  17. package/.gemini/commands/planning.toml +18 -0
  18. package/.gemini/commands/review.toml +16 -0
  19. package/.gemini/commands/ship.toml +72 -0
  20. package/.gemini/commands/spec.toml +17 -0
  21. package/.gemini/commands/test.toml +19 -0
  22. package/.gemini/commands/webperf.toml +32 -0
  23. package/CHANGELOG.md +23 -0
  24. package/LICENSE +21 -0
  25. package/NOTICE.md +9 -0
  26. package/README.md +117 -2
  27. package/agents/code-reviewer.md +102 -0
  28. package/agents/security-auditor.md +112 -0
  29. package/agents/test-engineer.md +95 -0
  30. package/agents/web-performance-auditor.md +184 -0
  31. package/bin/i3-composer-agent.cjs +122 -0
  32. package/commands/build.toml +43 -0
  33. package/commands/code-simplify.toml +22 -0
  34. package/commands/constraints.toml +32 -0
  35. package/commands/planning.toml +18 -0
  36. package/commands/review.toml +16 -0
  37. package/commands/ship.toml +72 -0
  38. package/commands/spec.toml +17 -0
  39. package/commands/test.toml +19 -0
  40. package/commands/webperf.toml +32 -0
  41. package/docs/adoption-guide.md +129 -0
  42. package/docs/advanced-per-agent-configuration.md +70 -0
  43. package/docs/agents.md +123 -0
  44. package/docs/antigravity-setup.md +128 -0
  45. package/docs/codebuddy-setup.md +41 -0
  46. package/docs/codex-setup.md +34 -0
  47. package/docs/commandcode-setup.md +69 -0
  48. package/docs/comparison.md +131 -0
  49. package/docs/copilot-cli-setup.md +64 -0
  50. package/docs/copilot-setup.md +162 -0
  51. package/docs/cursor-setup.md +225 -0
  52. package/docs/developer-onboarding.md +116 -0
  53. package/docs/gemini-cli-setup.md +133 -0
  54. package/docs/getting-started.md +208 -0
  55. package/docs/opencode-setup.md +259 -0
  56. package/docs/other-hosts.md +7 -0
  57. package/docs/skill-anatomy.md +203 -0
  58. package/docs/windsurf-setup.md +48 -0
  59. package/evals/README.md +101 -0
  60. package/evals/cases/api-and-interface-design.json +45 -0
  61. package/evals/cases/browser-testing-with-devtools.json +44 -0
  62. package/evals/cases/ci-cd-and-automation.json +45 -0
  63. package/evals/cases/code-review-and-quality.json +49 -0
  64. package/evals/cases/code-simplification.json +45 -0
  65. package/evals/cases/constraint-driven-development.json +79 -0
  66. package/evals/cases/context-engineering.json +44 -0
  67. package/evals/cases/debugging-and-error-recovery.json +58 -0
  68. package/evals/cases/deprecation-and-migration.json +52 -0
  69. package/evals/cases/documentation-and-adrs.json +44 -0
  70. package/evals/cases/doubt-driven-development.json +43 -0
  71. package/evals/cases/frontend-ui-engineering.json +52 -0
  72. package/evals/cases/git-workflow-and-versioning.json +47 -0
  73. package/evals/cases/idea-refine.json +43 -0
  74. package/evals/cases/incremental-implementation.json +57 -0
  75. package/evals/cases/interview-me.json +42 -0
  76. package/evals/cases/observability-and-instrumentation.json +44 -0
  77. package/evals/cases/performance-optimization.json +53 -0
  78. package/evals/cases/planning-and-task-breakdown.json +45 -0
  79. package/evals/cases/security-and-hardening.json +53 -0
  80. package/evals/cases/shipping-and-launch.json +56 -0
  81. package/evals/cases/source-driven-development.json +44 -0
  82. package/evals/cases/spec-driven-development.json +72 -0
  83. package/evals/cases/test-driven-development.json +73 -0
  84. package/evals/cases/using-agent-skills.json +44 -0
  85. package/evals/fixtures/api-and-interface-design/service-brief.md +19 -0
  86. package/evals/fixtures/browser-testing-with-devtools/README.md +5 -0
  87. package/evals/fixtures/browser-testing-with-devtools/index.html +24 -0
  88. package/evals/fixtures/browser-testing-with-devtools/server.js +15 -0
  89. package/evals/fixtures/ci-cd-and-automation/package.json +8 -0
  90. package/evals/fixtures/ci-cd-and-automation/src/slug.js +3 -0
  91. package/evals/fixtures/ci-cd-and-automation/test/slug.test.js +9 -0
  92. package/evals/fixtures/code-review-and-quality/user-search.diff +16 -0
  93. package/evals/fixtures/code-simplification/config-parser.js +46 -0
  94. package/evals/fixtures/code-simplification/config-parser.test.js +15 -0
  95. package/evals/fixtures/context-engineering/context-audit.md +15 -0
  96. package/evals/fixtures/debugging-and-error-recovery/pagination.js +8 -0
  97. package/evals/fixtures/debugging-and-error-recovery/pagination.test.js +9 -0
  98. package/evals/fixtures/debugging-and-error-recovery/time-pressure.md +6 -0
  99. package/evals/fixtures/deprecation-and-migration/api-inventory.md +9 -0
  100. package/evals/fixtures/documentation-and-adrs/decision-context.md +16 -0
  101. package/evals/fixtures/doubt-driven-development/migration-plan.md +19 -0
  102. package/evals/fixtures/frontend-ui-engineering/Button.tsx +7 -0
  103. package/evals/fixtures/frontend-ui-engineering/design-system.md +11 -0
  104. package/evals/fixtures/git-workflow-and-versioning/.eval/working-tree.patch +21 -0
  105. package/evals/fixtures/git-workflow-and-versioning/app.js +7 -0
  106. package/evals/fixtures/git-workflow-and-versioning/app.test.js +9 -0
  107. package/evals/fixtures/incremental-implementation/reports.js +7 -0
  108. package/evals/fixtures/incremental-implementation/reports.test.js +12 -0
  109. package/evals/fixtures/incremental-implementation/tasks/plan.md +8 -0
  110. package/evals/fixtures/incremental-implementation-pressure/draft-export.js +17 -0
  111. package/evals/fixtures/incremental-implementation-pressure/scenario.md +9 -0
  112. package/evals/fixtures/observability-and-instrumentation/operations.md +11 -0
  113. package/evals/fixtures/observability-and-instrumentation/payment-retry.js +14 -0
  114. package/evals/fixtures/performance-optimization/benchmark.js +15 -0
  115. package/evals/fixtures/performance-optimization/products.js +14 -0
  116. package/evals/fixtures/planning-and-task-breakdown/notifications-spec.md +18 -0
  117. package/evals/fixtures/security-and-hardening/webhook.js +11 -0
  118. package/evals/fixtures/security-and-hardening/webhook.test.js +13 -0
  119. package/evals/fixtures/shipping-and-launch/authority-pressure.md +6 -0
  120. package/evals/fixtures/shipping-and-launch/launch-status.md +11 -0
  121. package/evals/fixtures/source-driven-development/framework-task.md +10 -0
  122. package/evals/fixtures/spec-driven-development/billing-brief.md +16 -0
  123. package/evals/fixtures/spec-driven-development-decomposition/portal-brief.md +22 -0
  124. package/evals/fixtures/test-driven-development/BUG.md +10 -0
  125. package/evals/fixtures/test-driven-development/README.md +28 -0
  126. package/evals/fixtures/test-driven-development/package.json +9 -0
  127. package/evals/fixtures/test-driven-development/src/split.js +8 -0
  128. package/evals/fixtures/test-driven-development/test/split.test.js +13 -0
  129. package/evals/fixtures/test-driven-development-ecosystem/README.md +9 -0
  130. package/evals/fixtures/test-driven-development-ecosystem/ledger.py +15 -0
  131. package/evals/fixtures/test-driven-development-ecosystem/test_ledger.py +19 -0
  132. package/evals/fixtures/using-agent-skills/incident.md +6 -0
  133. package/evals/plugin/code-review-fires/graders/off-by-one.md +7 -0
  134. package/evals/plugin/code-review-fires/graders/severity-labels.md +4 -0
  135. package/evals/plugin/code-review-fires/graders/skill-fired.md +5 -0
  136. package/evals/plugin/code-review-fires/prompt.md +31 -0
  137. package/evals/plugin/code-review-stays-quiet/graders/not-fired.md +8 -0
  138. package/evals/plugin/code-review-stays-quiet/graders/tdd-fired.md +6 -0
  139. package/evals/plugin/code-review-stays-quiet/prompt.md +8 -0
  140. package/evals/plugin/code-review-stays-quiet-on-commit-message/graders/not-fired.md +8 -0
  141. package/evals/plugin/code-review-stays-quiet-on-commit-message/prompt.md +25 -0
  142. package/evals/skill-impact.md +6 -0
  143. package/hooks/SDD-CACHE.md +167 -0
  144. package/hooks/SIMPLIFY-IGNORE.md +91 -0
  145. package/hooks/sdd-cache-post.sh +135 -0
  146. package/hooks/sdd-cache-pre.sh +106 -0
  147. package/hooks/sdd-cache-test.sh +246 -0
  148. package/hooks/session-start-test.sh +47 -0
  149. package/hooks/session-start.sh +33 -0
  150. package/hooks/simplify-ignore-test.sh +476 -0
  151. package/hooks/simplify-ignore.sh +352 -0
  152. package/package.json +89 -4
  153. package/plugin.json +7 -0
  154. package/rebrand/MAINTENANCE.md +112 -0
  155. package/rebrand/NOTICE.md +9 -0
  156. package/rebrand/PR-WORKFLOW.md +34 -0
  157. package/rebrand/UNIFICATION-SPEC.md +33 -0
  158. package/rebrand/VALIDATION.md +28 -0
  159. package/rebrand/VERSIONING.md +32 -0
  160. package/rebrand/apply.cjs +194 -0
  161. package/rebrand/brand.json +13 -0
  162. package/rebrand/catalog.cjs +56 -0
  163. package/rebrand/fork-patches.json +12 -0
  164. package/rebrand/overlay/.github/workflows/test-plugin-install.yml +177 -0
  165. package/rebrand/overlay/CHANGELOG.md +23 -0
  166. package/rebrand/overlay/bin/i3-composer-agent.cjs +122 -0
  167. package/rebrand/overlay/scripts/validate-brand.cjs +44 -0
  168. package/rebrand/overlay/tests/bundle.test.cjs +85 -0
  169. package/rebrand/package.template.json +82 -0
  170. package/rebrand/rebrand.sh +4 -0
  171. package/rebrand/record-upstream.cjs +37 -0
  172. package/rebrand/templates/README.md +86 -0
  173. package/rebrand/templates/codebuddy-setup.md +41 -0
  174. package/rebrand/templates/codex-setup.md +34 -0
  175. package/rebrand/tests/pipeline.test.cjs +185 -0
  176. package/rebrand/upstream.json +171 -0
  177. package/references/accessibility-checklist.md +160 -0
  178. package/references/definition-of-done.md +67 -0
  179. package/references/observability-checklist.md +92 -0
  180. package/references/orchestration-patterns.md +370 -0
  181. package/references/performance-checklist.md +236 -0
  182. package/references/security-checklist.md +248 -0
  183. package/references/testing-patterns.md +235 -0
  184. package/scripts/floor-guard-reference-test.js +291 -0
  185. package/scripts/lib/skill-lint-test.js +650 -0
  186. package/scripts/lib/skill-lint.js +584 -0
  187. package/scripts/run-evals-test.js +623 -0
  188. package/scripts/run-evals.js +638 -0
  189. package/scripts/validate-artifact-paths-test.js +179 -0
  190. package/scripts/validate-artifact-paths.js +128 -0
  191. package/scripts/validate-brand.cjs +44 -0
  192. package/scripts/validate-commands-test.js +216 -0
  193. package/scripts/validate-commands.js +222 -0
  194. package/scripts/validate-reference-links-test.js +495 -0
  195. package/scripts/validate-reference-links.js +187 -0
  196. package/scripts/validate-skills.js +69 -0
  197. package/scripts/validate-versions-test.js +32 -0
  198. package/scripts/validate-versions.js +35 -0
  199. package/skills/api-and-interface-design/SKILL.md +367 -0
  200. package/skills/browser-testing-with-devtools/SKILL.md +317 -0
  201. package/skills/ci-cd-and-automation/SKILL.md +390 -0
  202. package/skills/code-review-and-quality/SKILL.md +398 -0
  203. package/skills/code-simplification/SKILL.md +331 -0
  204. package/skills/constraint-driven-development/SKILL.md +311 -0
  205. package/skills/constraint-driven-development/references/floor-guard.md +182 -0
  206. package/skills/context-engineering/SKILL.md +353 -0
  207. package/skills/debugging-and-error-recovery/SKILL.md +300 -0
  208. package/skills/deprecation-and-migration/SKILL.md +247 -0
  209. package/skills/documentation-and-adrs/SKILL.md +288 -0
  210. package/skills/doubt-driven-development/SKILL.md +243 -0
  211. package/skills/frontend-ui-engineering/SKILL.md +340 -0
  212. package/skills/git-workflow-and-versioning/SKILL.md +355 -0
  213. package/skills/idea-refine/SKILL.md +178 -0
  214. package/skills/idea-refine/examples.md +238 -0
  215. package/skills/idea-refine/frameworks.md +99 -0
  216. package/skills/idea-refine/refinement-criteria.md +113 -0
  217. package/skills/idea-refine/scripts/idea-refine.sh +15 -0
  218. package/skills/incremental-implementation/SKILL.md +249 -0
  219. package/skills/interview-me/SKILL.md +235 -0
  220. package/skills/observability-and-instrumentation/SKILL.md +238 -0
  221. package/skills/performance-optimization/SKILL.md +267 -0
  222. package/skills/performance-optimization/references/optimization-patterns.md +250 -0
  223. package/skills/planning-and-task-breakdown/SKILL.md +257 -0
  224. package/skills/security-and-hardening/SKILL.md +216 -0
  225. package/skills/security-and-hardening/references/hardening-patterns.md +324 -0
  226. package/skills/shipping-and-launch/SKILL.md +330 -0
  227. package/skills/source-driven-development/SKILL.md +216 -0
  228. package/skills/spec-driven-development/SKILL.md +259 -0
  229. package/skills/test-driven-development/SKILL.md +398 -0
  230. package/skills/using-agent-skills/SKILL.md +192 -0
  231. package/tests/bundle.test.cjs +85 -0
@@ -0,0 +1,216 @@
1
+ ---
2
+ name: security-and-hardening
3
+ description: 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.
4
+ ---
5
+
6
+ # Security and Hardening
7
+
8
+ ## Overview
9
+
10
+ Security-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.
11
+
12
+ ## When to Use
13
+
14
+ - Building anything that accepts user input
15
+ - Implementing authentication or authorization
16
+ - Storing or transmitting sensitive data
17
+ - Integrating with external APIs or services
18
+ - Adding file uploads, webhooks, or callbacks
19
+ - Handling payment or PII data
20
+
21
+ ## Process: Threat Model First
22
+
23
+ Controls bolted on without a threat model are guesses. Before hardening, spend five minutes thinking like an attacker:
24
+
25
+ 1. **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.
26
+ 2. **Name the assets.** What's worth stealing or breaking? Credentials, PII, payment data, admin actions, money movement.
27
+ 3. **Run STRIDE over each boundary** — a quick lens, not a ceremony:
28
+
29
+ | Threat | Ask | Typical mitigation |
30
+ |---|---|---|
31
+ | **S**poofing | Can someone impersonate a user/service? | Authentication, signature verification |
32
+ | **T**ampering | Can data be altered in transit or at rest? | Integrity checks, parameterized queries, HTTPS |
33
+ | **R**epudiation | Can an action be denied later? | Audit logging of security events |
34
+ | **I**nformation disclosure | Can data leak? | Encryption, field allowlists, generic errors |
35
+ | **D**enial of service | Can it be overwhelmed? | Rate limiting, input size caps, timeouts |
36
+ | **E**levation of privilege | Can a user gain rights they shouldn't? | Authorization checks, least privilege |
37
+
38
+ 4. **Write abuse cases next to use cases.** For each feature, ask "how would I misuse this?" — then make that your first test.
39
+
40
+ If 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.
41
+
42
+ ## The Three-Tier Boundary System
43
+
44
+ ### Always Do (No Exceptions)
45
+
46
+ - **Validate all external input** at the system boundary (API routes, form handlers)
47
+ - **Parameterize all database queries** — never concatenate user input into SQL
48
+ - **Encode output** to prevent XSS (use framework auto-escaping, don't bypass it)
49
+ - **Use HTTPS** for all external communication
50
+ - **Hash passwords** with bcrypt/scrypt/argon2 (never store plaintext)
51
+ - **Set security headers** (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)
52
+ - **Use httpOnly, secure, sameSite cookies** for sessions
53
+ - **Run the detected package manager's native audit** against the committed lockfile before every release
54
+
55
+ ### Ask First (Requires Human Approval)
56
+
57
+ - Adding new authentication flows or changing auth logic
58
+ - Storing new categories of sensitive data (PII, payment info)
59
+ - Adding new external service integrations
60
+ - Changing CORS configuration
61
+ - Adding file upload handlers
62
+ - Modifying rate limiting or throttling
63
+ - Granting elevated permissions or roles
64
+
65
+ ### Never Do
66
+
67
+ - **Never commit secrets** to version control (API keys, passwords, tokens)
68
+ - **Never log sensitive data** (passwords, tokens, full credit card numbers)
69
+ - **Never trust client-side validation** as a security boundary
70
+ - **Never disable security headers** for convenience
71
+ - **Never use `eval()` or `innerHTML`** with user-provided data
72
+ - **Never store sessions in client-accessible storage** (localStorage for auth tokens)
73
+ - **Never expose stack traces** or internal error details to users
74
+
75
+ ## Hardening Controls
76
+
77
+ The rules below are the workflow; a concrete implementation of each lives in [references/hardening-patterns.md](references/hardening-patterns.md). Open the section you need when you reach that code, not before.
78
+
79
+ ### Injection, XSS, and access control
80
+
81
+ - Parameterize every query. Never build SQL, NoSQL, or shell commands from input strings.
82
+ - Encode output through the framework's auto-escaping. If raw HTML is unavoidable, sanitize with an allowlist sanitizer first.
83
+ - Check **authorization** on every request, not just authentication: the authenticated user must own, or be permitted on, the specific resource (A01, IDOR).
84
+
85
+ Patterns: [Injection](references/hardening-patterns.md#injection), [XSS](references/hardening-patterns.md#cross-site-scripting-xss), [Access control](references/hardening-patterns.md#broken-access-control).
86
+
87
+ ### Authentication and sessions
88
+
89
+ - Hash passwords with bcrypt (≥12 rounds), scrypt, or argon2. The session secret comes from the environment, never from code.
90
+ - 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`.
91
+
92
+ Pattern: [Authentication](references/hardening-patterns.md#broken-authentication).
93
+
94
+ ### Headers, CORS, and responses
95
+
96
+ - Security headers on every response (helmet or the framework equivalent); CSP starts from `default-src 'self'` and is tightened, not loosened.
97
+ - CORS restricted to an explicit origin list from configuration. Never `*` with credentials.
98
+ - Strip sensitive fields (`passwordHash`, reset tokens) before any response. Error bodies are generic; internals go to server logs only.
99
+
100
+ Patterns: [Misconfiguration](references/hardening-patterns.md#security-misconfiguration), [Sensitive data exposure](references/hardening-patterns.md#sensitive-data-exposure).
101
+
102
+ ### Input validation and uploads
103
+
104
+ - 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.
105
+ - Uploads: allowlist MIME types, cap size, verify content (magic bytes) when it matters. The extension proves nothing.
106
+
107
+ Patterns: [Schema validation](references/hardening-patterns.md#schema-validation-at-boundaries), [File upload](references/hardening-patterns.md#file-upload-safety).
108
+
109
+ ### Server-side fetches (SSRF)
110
+
111
+ Any 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.
112
+
113
+ Pattern: [SSRF](references/hardening-patterns.md#server-side-request-forgery-ssrf).
114
+
115
+ ### Destructive operations on derived paths
116
+
117
+ A 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.
118
+
119
+ Why the check is weaker than it reads (marker self-attestation, check/use races): [Destructive paths](references/hardening-patterns.md#destructive-operations-on-derived-paths). Worked code: `../../references/security-checklist.md`.
120
+
121
+ ### Rate limiting
122
+
123
+ Limit 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.
124
+
125
+ Pattern: [Rate limiting](references/hardening-patterns.md#rate-limiting).
126
+
127
+ ### Secrets
128
+
129
+ Secrets 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.**
130
+
131
+ Pattern: [Secrets management](references/hardening-patterns.md#secrets-management).
132
+
133
+ ### Dependencies and supply chain
134
+
135
+ 1. **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.
136
+ 2. **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/immutable install. Never blanket-approve.
137
+ 3. **Run the native audit against the committed lockfile before every release.** Triage critical/high 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.
138
+ 4. **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).
139
+
140
+ Triage decision tree: [Dependency audit triage](references/hardening-patterns.md#dependency-audit-triage). Manager matrix and install-script gate: `../../references/security-checklist.md`.
141
+
142
+ ### Personal data and privacy
143
+
144
+ Hardening 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.
145
+
146
+ - **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.
147
+ - **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).
148
+ - **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.
149
+ - **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.
150
+ - **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.
151
+
152
+ Classification table: [Data classification](references/hardening-patterns.md#data-classification). A privacy incident starts the breach-notification clock; run the postmortem with the `debugging-and-error-recovery` skill.
153
+
154
+ ### AI / LLM features
155
+
156
+ Calling an LLM — chatbots, summarizers, agents, RAG — adds a new attack surface; map it to the [OWASP Top 10 for LLM Applications (2025)](https://genai.owasp.org/llm-top-10/):
157
+
158
+ - **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.
159
+ - **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.
160
+ - **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).
161
+
162
+ Pattern: [LLM output handling](references/hardening-patterns.md#llm-output-handling).
163
+
164
+ ## Review Checklist
165
+
166
+ Before sign-off, walk `../../references/security-checklist.md`: it covers authentication, authorization, input, data protection and privacy, headers and CORS, dependencies and supply chain, AI/LLM, and error handling, plus the OWASP quick-reference tables.
167
+
168
+ ## Common Rationalizations
169
+
170
+ | Rationalization | Reality |
171
+ |---|---|
172
+ | "This is an internal tool, security doesn't matter" | Internal tools get compromised. Attackers target the weakest link. |
173
+ | "We'll add security later" | Security retrofitting is 10x harder than building it in. Add it now. |
174
+ | "No one would try to exploit this" | Automated scanners will find it. Security by obscurity is not security. |
175
+ | "The framework handles security" | Frameworks provide tools, not guarantees. You still need to use them correctly. |
176
+ | "It's just a prototype" | Prototypes become production. Security habits from day one. |
177
+ | "Threat modeling is overkill here" | Five minutes of "how would I attack this?" prevents the design flaws no control can patch later. |
178
+ | "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. |
179
+ | "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. |
180
+ | "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. |
181
+ | "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. |
182
+ | "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. |
183
+
184
+ ## Red Flags
185
+
186
+ - User input passed directly to database queries, shell commands, or HTML rendering
187
+ - 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
188
+ - Secrets in source code or commit history
189
+ - API endpoints without authentication or authorization checks
190
+ - Missing CORS configuration or wildcard (`*`) origins
191
+ - No rate limiting on authentication endpoints, or an in-memory limiter in front of more than one instance
192
+ - Stack traces or internal errors exposed to users
193
+ - Dependencies with known critical vulnerabilities, competing lockfiles at one installation boundary, non-reproducible installs, or blanket-approved scripts
194
+ - Server fetches user-supplied URLs without an allowlist (SSRF)
195
+ - LLM/model output passed into a query, the DOM, a shell, or `eval`
196
+ - Secrets, PII, or the full system prompt placed inside an LLM context window
197
+ - Personal data collected with no stated purpose, retention limit, or deletion path
198
+ - PII sent to analytics/ad/LLM vendors with no consent or data-processing agreement
199
+ - "Delete my account" that only flips a flag while the personal data lingers in stores and backups
200
+
201
+ ## Verification
202
+
203
+ After implementing security-relevant code:
204
+
205
+ - [ ] The native audit has no unmitigated reachable critical/high findings; CI preserves the authoritative lockfile and blocks unreviewed dependency scripts
206
+ - [ ] No secrets in source code or git history
207
+ - [ ] All user input validated at system boundaries
208
+ - [ ] Destructive filesystem operations resolve symlinks, then verify allowlisted root, minimum depth, and ownership before running
209
+ - [ ] Authentication and authorization checked on every protected endpoint
210
+ - [ ] Security headers present in response (check with browser DevTools)
211
+ - [ ] Error responses don't expose internal details
212
+ - [ ] Rate limiting active on auth endpoints, backed by a shared store when more than one instance serves traffic
213
+ - [ ] Server-side URL fetches validated against an allowlist (no SSRF)
214
+ - [ ] LLM/model output validated and encoded before use (if AI features present)
215
+ - [ ] Personal data is classified, minimized to a stated purpose, and has a retention limit
216
+ - [ ] Deletion and export requests work end-to-end (including backups, caches, and analytics copies)
@@ -0,0 +1,324 @@
1
+ # Hardening Patterns
2
+
3
+ Code patterns and decision aids for the `security-and-hardening` skill. The skill states each rule; this file shows one concrete implementation of it. Open the section you need when you reach that code — it is not meant to be read top to bottom.
4
+
5
+ Shared checklists (threat modeling, pre-commit checks, security headers, CORS, the package-manager matrix, install-script gate, and the OWASP quick-reference tables) live in `../../../references/security-checklist.md`.
6
+
7
+ ## OWASP Top 10 Prevention Patterns
8
+
9
+ These are prevention patterns, not a ranking. For the 2021 ordering, see the quick-reference table in `../../../references/security-checklist.md#owasp-top-10-quick-reference`.
10
+
11
+ ### Injection
12
+
13
+ ```typescript
14
+ // BAD: SQL injection via string concatenation
15
+ const query = `SELECT * FROM users WHERE id = '${userId}'`;
16
+
17
+ // GOOD: Parameterized query
18
+ const user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
19
+
20
+ // GOOD: ORM with parameterized input
21
+ const user = await prisma.user.findUnique({ where: { id: userId } });
22
+ ```
23
+
24
+ ### Broken Authentication
25
+
26
+ ```typescript
27
+ // Password hashing
28
+ import { hash, compare } from 'bcrypt';
29
+
30
+ const SALT_ROUNDS = 12;
31
+ const hashedPassword = await hash(plaintext, SALT_ROUNDS);
32
+ const isValid = await compare(plaintext, hashedPassword);
33
+
34
+ // Session management
35
+ app.use(session({
36
+ secret: process.env.SESSION_SECRET, // From environment, not code
37
+ resave: false,
38
+ saveUninitialized: false,
39
+ cookie: {
40
+ httpOnly: true, // Not accessible via JavaScript
41
+ secure: true, // HTTPS only
42
+ sameSite: 'lax', // CSRF protection
43
+ maxAge: 24 * 60 * 60 * 1000, // 24 hours
44
+ },
45
+ }));
46
+ ```
47
+
48
+ ### Cross-Site Scripting (XSS)
49
+
50
+ ```typescript
51
+ // BAD: Rendering user input as HTML
52
+ element.innerHTML = userInput;
53
+
54
+ // GOOD: Use framework auto-escaping (React does this by default)
55
+ return <div>{userInput}</div>;
56
+
57
+ // If you MUST render HTML, sanitize first
58
+ import DOMPurify from 'dompurify';
59
+ const clean = DOMPurify.sanitize(userInput);
60
+ ```
61
+
62
+ ### Broken Access Control
63
+
64
+ ```typescript
65
+ // Always check authorization, not just authentication
66
+ app.patch('/api/tasks/:id', authenticate, async (req, res) => {
67
+ const task = await taskService.findById(req.params.id);
68
+
69
+ // Check that the authenticated user owns this resource
70
+ if (task.ownerId !== req.user.id) {
71
+ return res.status(403).json({
72
+ error: { code: 'FORBIDDEN', message: 'Not authorized to modify this task' }
73
+ });
74
+ }
75
+
76
+ // Proceed with update
77
+ const updated = await taskService.update(req.params.id, req.body);
78
+ return res.json(updated);
79
+ });
80
+ ```
81
+
82
+ ### Security Misconfiguration
83
+
84
+ ```typescript
85
+ // Security headers (use helmet for Express)
86
+ import helmet from 'helmet';
87
+ app.use(helmet());
88
+
89
+ // Content Security Policy
90
+ app.use(helmet.contentSecurityPolicy({
91
+ directives: {
92
+ defaultSrc: ["'self'"],
93
+ scriptSrc: ["'self'"],
94
+ styleSrc: ["'self'", "'unsafe-inline'"], // Tighten if possible
95
+ imgSrc: ["'self'", 'data:', 'https:'],
96
+ connectSrc: ["'self'"],
97
+ },
98
+ }));
99
+
100
+ // CORS — restrict to known origins
101
+ app.use(cors({
102
+ origin: process.env.ALLOWED_ORIGINS?.split(',') || 'http://localhost:3000',
103
+ credentials: true,
104
+ }));
105
+ ```
106
+
107
+ ### Sensitive Data Exposure
108
+
109
+ ```typescript
110
+ // Never return sensitive fields in API responses
111
+ function sanitizeUser(user: UserRecord): PublicUser {
112
+ const { passwordHash, resetToken, ...publicFields } = user;
113
+ return publicFields;
114
+ }
115
+
116
+ // Use environment variables for secrets
117
+ const API_KEY = process.env.STRIPE_API_KEY;
118
+ if (!API_KEY) throw new Error('STRIPE_API_KEY not configured');
119
+ ```
120
+
121
+ ### Server-Side Request Forgery (SSRF)
122
+
123
+ Any time the server fetches a URL the user influenced — webhooks, "import from URL", image proxies, link previews — an attacker can aim it at internal services (cloud metadata, `localhost`, private IPs).
124
+
125
+ ```typescript
126
+ // BAD: fetch whatever the user gives you
127
+ await fetch(req.body.webhookUrl);
128
+
129
+ // GOOD: allowlist scheme + host, reject if ANY resolved IP is private, forbid redirects
130
+ import { lookup } from 'node:dns/promises';
131
+ import ipaddr from 'ipaddr.js';
132
+
133
+ const ALLOWED_HOSTS = new Set(['hooks.example.com']);
134
+
135
+ async function assertSafeUrl(raw: string): Promise<URL> {
136
+ const url = new URL(raw);
137
+ if (url.protocol !== 'https:') throw new Error('https only');
138
+ if (!ALLOWED_HOSTS.has(url.hostname)) throw new Error('host not allowed');
139
+ // Resolve ALL records; a single private/reserved address fails the check.
140
+ const addrs = await lookup(url.hostname, { all: true });
141
+ if (addrs.some((a) => ipaddr.parse(a.address).range() !== 'unicast')) {
142
+ throw new Error('private/reserved IP');
143
+ }
144
+ return url;
145
+ }
146
+
147
+ await fetch(await assertSafeUrl(req.body.webhookUrl), { redirect: 'error' });
148
+ ```
149
+
150
+ The `range() !== 'unicast'` check covers loopback, link-local `169.254.169.254` (cloud metadata, the #1 SSRF target), private, and unique-local ranges across IPv4 and IPv6.
151
+
152
+ **Caveat — this still has a TOCTOU gap.** `fetch` resolves DNS again after the check, so an attacker using a short-TTL record can rebind to an internal IP between validation and connection. For high-risk surfaces, resolve once and connect to the pinned IP, or put a filtering agent in front (`request-filtering-agent` / `ssrf-req-filter`).
153
+
154
+ ## Input Validation Patterns
155
+
156
+ ### Schema Validation at Boundaries
157
+
158
+ ```typescript
159
+ import { z } from 'zod';
160
+
161
+ const CreateTaskSchema = z.object({
162
+ title: z.string().min(1).max(200).trim(),
163
+ description: z.string().max(2000).optional(),
164
+ priority: z.enum(['low', 'medium', 'high']).default('medium'),
165
+ dueDate: z.string().datetime().optional(),
166
+ });
167
+
168
+ // Validate at the route handler
169
+ app.post('/api/tasks', async (req, res) => {
170
+ const result = CreateTaskSchema.safeParse(req.body);
171
+ if (!result.success) {
172
+ return res.status(422).json({
173
+ error: {
174
+ code: 'VALIDATION_ERROR',
175
+ message: 'Invalid input',
176
+ details: result.error.flatten(),
177
+ },
178
+ });
179
+ }
180
+ // result.data is now typed and validated
181
+ const task = await taskService.create(result.data);
182
+ return res.status(201).json(task);
183
+ });
184
+ ```
185
+
186
+ ### File Upload Safety
187
+
188
+ ```typescript
189
+ // Restrict file types and sizes
190
+ const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
191
+ const MAX_SIZE = 5 * 1024 * 1024; // 5MB
192
+
193
+ function validateUpload(file: UploadedFile) {
194
+ if (!ALLOWED_TYPES.includes(file.mimetype)) {
195
+ throw new ValidationError('File type not allowed');
196
+ }
197
+ if (file.size > MAX_SIZE) {
198
+ throw new ValidationError('File too large (max 5MB)');
199
+ }
200
+ // Don't trust the file extension — check magic bytes if critical
201
+ }
202
+ ```
203
+
204
+ ### Destructive Operations on Derived Paths
205
+
206
+ A delete, move, or overwrite is only as safe as the value that names its target. Reading that value from the kernel, a job payload, or a sibling service proves where it *arrived from*, not who *wrote* it — another process's command line is as attacker-controlled as a form field. A shape check ("absolute path, at least one directory deep") proves well-formedness and gets mistaken for authorization; that is how a cleanup routine deletes the root instead of the leaf.
207
+
208
+ Before a destructive call, require all three: the resolved target sits under an **allowlisted root** (compare after resolving symlinks, never on the raw string); it is at least one level **below** that root, so a root is never itself the target; and it carries **evidence that it is yours**, read *before* the operation and before any teardown that removes it — otherwise "absent" and "not mine" are indistinguishable. On refusal, log the rejected target and stop: a cleanup that falls back to a broader default path is the failure this guards against. Worked example in `../../../references/security-checklist.md#destructive-path-operations`.
209
+
210
+ Two limits, because the check reads stronger than it is. A marker inside the tree is self-attestation — anything that can write there can write the marker — so the expected owner has to come from authenticated state, and the marker needs integrity protection (restrictive ownership, or a MAC) before it counts as authorization. And resolving a path and then operating on the *name* is a check/use race wherever an untrusted process can swap an ancestor: on a shared volume, hold the target by descriptor and use no-follow, beneath-the-root operations, or make sure the hierarchy cannot change for the duration.
211
+
212
+ ## Dependency Audit Triage
213
+
214
+ Package-manager audits report known advisories; they do not prove a package is trustworthy or that vulnerable code is reachable. Use this decision tree:
215
+
216
+ ```
217
+ The native package-manager audit reports a vulnerability
218
+ ├── Severity: critical or high
219
+ │ ├── Is the vulnerable code reachable in runtime, build, test, or deployment paths?
220
+ │ │ ├── YES --> Fix immediately (update, patch, or replace the dependency)
221
+ │ │ └── NO (confirmed unused across those paths) --> Fix soon, but not a blocker
222
+ │ └── Is a fix available?
223
+ │ ├── YES --> Update to the patched version
224
+ │ └── NO --> Check for workarounds, consider replacing the dependency, or add to allowlist with a review date
225
+ ├── Severity: moderate
226
+ │ ├── Reachable in production? --> Fix in the next release cycle
227
+ │ └── Dev-only? --> Fix when convenient, track in backlog
228
+ └── Severity: low
229
+ └── Track and fix during regular dependency updates
230
+ ```
231
+
232
+ **Key questions:**
233
+ - Is the vulnerable function actually called in your code path?
234
+ - Is the dependency a runtime dependency or dev-only?
235
+ - Is the vulnerability exploitable given your deployment context (e.g., a server-side vulnerability in a client-only app)?
236
+
237
+ When you defer a fix, document the reason and set a review date.
238
+
239
+ ## Rate Limiting
240
+
241
+ ```typescript
242
+ import rateLimit from 'express-rate-limit';
243
+
244
+ // General API rate limit
245
+ app.use('/api/', rateLimit({
246
+ windowMs: 15 * 60 * 1000, // 15 minutes
247
+ max: 100, // 100 requests per window
248
+ standardHeaders: true,
249
+ legacyHeaders: false,
250
+ }));
251
+
252
+ // Stricter limit for auth endpoints
253
+ app.use('/api/auth/', rateLimit({
254
+ windowMs: 15 * 60 * 1000,
255
+ max: 10, // 10 attempts per 15 minutes
256
+ }));
257
+ ```
258
+
259
+ **Count in a shared store once there is more than one process.** `express-rate-limit` keeps its counters in process memory by default. Behind a load balancer each instance holds its own count, so the effective limit is `max × instances`; on serverless or edge runtimes a fresh invocation starts from zero, so the auth limit above may never fire. Pass a shared `store` (Redis via `rate-limit-redis`), or use an HTTP-based limiter that works where a long-lived TCP connection does not (for example `@upstash/ratelimit`):
260
+
261
+ ```typescript
262
+ import { Ratelimit } from '@upstash/ratelimit';
263
+ import { Redis } from '@upstash/redis';
264
+
265
+ const authLimiter = new Ratelimit({
266
+ redis: Redis.fromEnv(), // UPSTASH_REDIS_REST_URL + _TOKEN
267
+ limiter: Ratelimit.slidingWindow(10, '15 m'), // 10 attempts per 15 minutes, across all instances
268
+ });
269
+ const { success } = await authLimiter.limit(`login:${req.ip}`);
270
+ if (!success) return res.status(429).end();
271
+ ```
272
+
273
+ ## Secrets Management
274
+
275
+ ```
276
+ .env files:
277
+ ├── .env.example → Committed (template with placeholder values)
278
+ ├── .env → NOT committed (contains real secrets)
279
+ └── .env.local → NOT committed (local overrides)
280
+
281
+ .gitignore must include:
282
+ .env
283
+ .env.local
284
+ .env.*.local
285
+ *.pem
286
+ *.key
287
+ ```
288
+
289
+ **Always check before committing:**
290
+ ```bash
291
+ # Check for accidentally staged secrets
292
+ git diff --cached | grep -i "password\|secret\|api_key\|token"
293
+ ```
294
+
295
+ **If a secret is ever committed, rotate it.** Deleting the line or rewriting history is not enough — assume it's compromised the moment it reaches a remote. Revoke and reissue the key first, then purge it from history.
296
+
297
+ ## Data Classification
298
+
299
+ Classify personal data as you add fields, so export and deletion requests can find it later:
300
+
301
+ | Class | Examples | Handling |
302
+ |---|---|---|
303
+ | **Non-personal** | Aggregates, anonymized counts | Normal handling |
304
+ | **Personal (PII)** | Name, email, IP, device/user IDs | Minimize, access-control, include in export/delete |
305
+ | **Sensitive** | Health, finance, location, biometrics, gov IDs, anything about minors | Extra basis to collect, stricter access, often encryption + audit logging |
306
+
307
+ ## LLM Output Handling
308
+
309
+ ```typescript
310
+ // BAD: trusting model output as a command or as markup
311
+ const sql = await llm.generate(`Write SQL for: ${userQuestion}`);
312
+ await db.query(sql); // arbitrary query execution
313
+ container.innerHTML = await llm.reply(userMessage); // stored XSS, via the model
314
+
315
+ // GOOD: model output is data — parse defensively, then validate, then encode
316
+ let intent;
317
+ try {
318
+ intent = CommandSchema.parse(JSON.parse(await llm.replyJson(userMessage)));
319
+ } catch {
320
+ throw new ValidationError('unexpected model output'); // JSON.parse or schema failed
321
+ }
322
+ await runAllowlistedAction(intent.action, intent.params);
323
+ container.textContent = await llm.reply(userMessage);
324
+ ```