@ericrisco/rsc 4.0.4 → 4.1.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 (202) hide show
  1. package/README.md +4 -4
  2. package/manifest.json +78 -84
  3. package/package.json +1 -1
  4. package/scripts/lib/default-skill-floor.js +5 -1
  5. package/scripts/lib/domains.js +1 -1
  6. package/scripts/lib/recommend.js +1 -1
  7. package/scripts/lib/retired-skills.js +4 -0
  8. package/scripts/skill-migration-brief.md +1 -1
  9. package/skills/accessibility/evals/README.md +1 -1
  10. package/skills/accessibility/evals/cases.yaml +1 -1
  11. package/skills/agent-safety/SKILL.md +2 -2
  12. package/skills/agent-safety/evals/README.md +1 -1
  13. package/skills/agent-safety/evals/cases.yaml +1 -1
  14. package/skills/analyze/evals/README.md +1 -1
  15. package/skills/analyze/evals/cases.yaml +2 -2
  16. package/skills/angular/SKILL.md +1 -1
  17. package/skills/api-connector-builder/SKILL.md +1 -1
  18. package/skills/api-design/SKILL.md +3 -3
  19. package/skills/api-design/evals/cases.yaml +1 -1
  20. package/skills/asdd/SKILL.md +3 -1
  21. package/skills/automation-strategy/SKILL.md +1 -1
  22. package/skills/automation-strategy/evals/README.md +1 -1
  23. package/skills/automation-strategy/evals/cases.yaml +2 -2
  24. package/skills/automation-strategy/references/orchestration-and-antipatterns.md +1 -1
  25. package/skills/aws-essentials/SKILL.md +3 -3
  26. package/skills/aws-essentials/evals/cases.yaml +2 -2
  27. package/skills/backups/SKILL.md +2 -2
  28. package/skills/backups/evals/cases.yaml +2 -2
  29. package/skills/bash-scripting/SKILL.md +1 -1
  30. package/skills/building-agents/SKILL.md +2 -2
  31. package/skills/building-agents/evals/cases.yaml +2 -2
  32. package/skills/chrome-extension/SKILL.md +1 -1
  33. package/skills/cloudflare/SKILL.md +1 -1
  34. package/skills/code-review/SKILL.md +2 -2
  35. package/skills/code-review/evals/cases.yaml +2 -2
  36. package/skills/compliance/SKILL.md +3 -3
  37. package/skills/compliance/evals/cases.yaml +1 -1
  38. package/skills/constitution/SKILL.md +2 -2
  39. package/skills/constitution/evals/README.md +2 -2
  40. package/skills/constitution/evals/cases.yaml +2 -2
  41. package/skills/constitution/references/constitution-template.md +1 -1
  42. package/skills/cpp/SKILL.md +2 -2
  43. package/skills/cpp/evals/README.md +1 -1
  44. package/skills/cpp/evals/cases.yaml +2 -2
  45. package/skills/csharp-dotnet/SKILL.md +3 -3
  46. package/skills/csharp-dotnet/evals/cases.yaml +1 -1
  47. package/skills/csharp-dotnet/references/aspnetcore.md +1 -1
  48. package/skills/data-policy/SKILL.md +2 -2
  49. package/skills/data-policy/evals/README.md +1 -1
  50. package/skills/data-policy/evals/cases.yaml +1 -1
  51. package/skills/debug/SKILL.md +1 -1
  52. package/skills/debug/evals/README.md +1 -1
  53. package/skills/decision-challenge/SKILL.md +2 -2
  54. package/skills/decision-challenge/evals/cases.yaml +1 -1
  55. package/skills/deployment/SKILL.md +2 -2
  56. package/skills/deployment/evals/README.md +1 -1
  57. package/skills/deployment/evals/cases.yaml +2 -2
  58. package/skills/django/SKILL.md +2 -2
  59. package/skills/django/evals/README.md +1 -1
  60. package/skills/django/evals/cases.yaml +1 -1
  61. package/skills/django/references/security.md +1 -1
  62. package/skills/docker/SKILL.md +3 -3
  63. package/skills/docker/evals/cases.yaml +1 -1
  64. package/skills/dynamodb/SKILL.md +2 -2
  65. package/skills/electron/SKILL.md +1 -1
  66. package/skills/electron/references/packaging-and-updates.md +1 -1
  67. package/skills/email-connector/SKILL.md +2 -2
  68. package/skills/email-deliverability/SKILL.md +1 -1
  69. package/skills/error-handling/SKILL.md +1 -1
  70. package/skills/expo/SKILL.md +2 -2
  71. package/skills/fastapi/SKILL.md +4 -4
  72. package/skills/fastapi/evals/README.md +2 -2
  73. package/skills/fastapi/evals/cases.yaml +2 -2
  74. package/skills/fastapi/references/security.md +2 -2
  75. package/skills/firebase/SKILL.md +1 -1
  76. package/skills/flutter/SKILL.md +1 -1
  77. package/skills/flutter/evals/cases.yaml +2 -2
  78. package/skills/fly-io/SKILL.md +1 -1
  79. package/skills/gamedev-multiplayer/SKILL.md +1 -1
  80. package/skills/gamedev-multiplayer/evals/README.md +1 -1
  81. package/skills/gamedev-multiplayer/evals/cases.yaml +2 -2
  82. package/skills/gamedev-shipping/SKILL.md +1 -1
  83. package/skills/gcp-essentials/SKILL.md +2 -2
  84. package/skills/gcp-essentials/evals/README.md +1 -1
  85. package/skills/gcp-essentials/evals/cases.yaml +2 -2
  86. package/skills/gdpr-privacy/SKILL.md +2 -2
  87. package/skills/gdpr-privacy/evals/cases.yaml +1 -1
  88. package/skills/github-actions/SKILL.md +2 -2
  89. package/skills/go/SKILL.md +4 -4
  90. package/skills/go/evals/README.md +1 -1
  91. package/skills/go/evals/cases.yaml +2 -2
  92. package/skills/google-workspace/SKILL.md +2 -2
  93. package/skills/hetzner/SKILL.md +1 -1
  94. package/skills/htmx/SKILL.md +4 -4
  95. package/skills/htmx/evals/cases.yaml +2 -2
  96. package/skills/implement/SKILL.md +2 -2
  97. package/skills/init/SKILL.md +2 -2
  98. package/skills/init/evals/cases.yaml +2 -2
  99. package/skills/init/references/discovery.md +1 -1
  100. package/skills/init/references/recommend-skills.md +5 -5
  101. package/skills/java/SKILL.md +3 -3
  102. package/skills/java/evals/README.md +1 -1
  103. package/skills/java/evals/cases.yaml +2 -2
  104. package/skills/laravel/SKILL.md +3 -3
  105. package/skills/laravel/evals/README.md +1 -1
  106. package/skills/laravel/evals/cases.yaml +1 -1
  107. package/skills/marketing/evals/README.md +1 -1
  108. package/skills/marketing/evals/cases.yaml +1 -1
  109. package/skills/mongodb/SKILL.md +2 -2
  110. package/skills/mongodb/evals/README.md +1 -1
  111. package/skills/mongodb/evals/cases.yaml +2 -2
  112. package/skills/nextjs/SKILL.md +3 -3
  113. package/skills/nextjs/evals/cases.yaml +2 -2
  114. package/skills/nextjs/references/security.md +2 -2
  115. package/skills/notion-connector/SKILL.md +3 -3
  116. package/skills/notion-connector/evals/README.md +1 -1
  117. package/skills/notion-connector/evals/cases.yaml +2 -2
  118. package/skills/php/SKILL.md +4 -4
  119. package/skills/php/evals/README.md +1 -1
  120. package/skills/php/evals/cases.yaml +1 -1
  121. package/skills/plan/evals/README.md +1 -1
  122. package/skills/postgresdb/SKILL.md +1 -1
  123. package/skills/postgresdb/evals/README.md +1 -1
  124. package/skills/postgresdb/evals/cases.yaml +2 -2
  125. package/skills/presentations/evals/README.md +1 -1
  126. package/skills/python/SKILL.md +3 -3
  127. package/skills/python/evals/README.md +1 -1
  128. package/skills/python/evals/cases.yaml +2 -2
  129. package/skills/rag/scripts/verify.sh +1 -1
  130. package/skills/review/SKILL.md +2 -2
  131. package/skills/review/evals/cases.yaml +3 -3
  132. package/skills/ruby/SKILL.md +1 -1
  133. package/skills/rust/SKILL.md +2 -2
  134. package/skills/rust/evals/README.md +1 -1
  135. package/skills/rust/evals/cases.yaml +2 -2
  136. package/skills/security-audit/SKILL.md +186 -0
  137. package/skills/security-audit/evals/cases.yaml +95 -0
  138. package/skills/security-audit/references/auditor-safety.md +69 -0
  139. package/skills/security-audit/references/classes/README.md +225 -0
  140. package/skills/security-audit/references/classes/ai-and-llm.md +247 -0
  141. package/skills/security-audit/references/classes/client-side.md +181 -0
  142. package/skills/security-audit/references/classes/cloud-and-deployment.md +167 -0
  143. package/skills/security-audit/references/classes/data-isolation.md +161 -0
  144. package/skills/security-audit/references/classes/desktop-mobile-ipc.md +167 -0
  145. package/skills/security-audit/references/classes/memory-and-binary.md +230 -0
  146. package/skills/security-audit/references/classes/protocols-and-messaging.md +151 -0
  147. package/skills/security-audit/references/classes/resource-exhaustion.md +141 -0
  148. package/skills/security-audit/references/classes/supply-chain.md +147 -0
  149. package/skills/security-audit/references/classes/web-and-auth.md +238 -0
  150. package/skills/security-audit/references/coverage-ledger.md +172 -0
  151. package/skills/security-audit/references/fixes-by-stack.md +972 -0
  152. package/skills/security-audit/references/fixing.md +200 -0
  153. package/skills/security-audit/references/hunting.md +146 -0
  154. package/skills/security-audit/references/isolated-execution.md +85 -0
  155. package/skills/security-audit/references/platforms.md +650 -0
  156. package/skills/security-audit/references/reconnaissance.md +73 -0
  157. package/skills/security-audit/references/resuming.md +55 -0
  158. package/skills/security-audit/references/scanners.md +347 -0
  159. package/skills/{secure-coding → security-audit}/references/secrets-and-supply-chain.md +78 -34
  160. package/skills/security-audit/references/secrets-discipline.md +173 -0
  161. package/skills/{secure-coding → security-audit}/references/threat-modeling.md +80 -32
  162. package/skills/security-audit/references/verification.md +118 -0
  163. package/skills/security-audit/schema/findings.schema.json +178 -0
  164. package/skills/security-audit/scripts/render-report.mjs +311 -0
  165. package/skills/security-audit/scripts/validate-findings.mjs +508 -0
  166. package/skills/skill-scout/scripts/verify.sh +1 -1
  167. package/skills/source-grounded-development/evals/cases.yaml +1 -1
  168. package/skills/specify/evals/README.md +1 -1
  169. package/skills/spring-boot/SKILL.md +3 -3
  170. package/skills/spring-boot/evals/README.md +1 -1
  171. package/skills/spring-boot/evals/cases.yaml +1 -1
  172. package/skills/spring-boot/references/security.md +1 -1
  173. package/skills/stripe/SKILL.md +2 -2
  174. package/skills/suggest/evals/cases.yaml +2 -2
  175. package/skills/supabase/SKILL.md +1 -1
  176. package/skills/tauri/SKILL.md +2 -2
  177. package/skills/testing-go/SKILL.md +1 -1
  178. package/skills/typescript/SKILL.md +2 -2
  179. package/skills/verify/SKILL.md +3 -3
  180. package/skills/verify/evals/README.md +2 -2
  181. package/skills/verify/evals/cases.yaml +2 -2
  182. package/skills/vue-nuxt/SKILL.md +2 -2
  183. package/skills/webhooks/SKILL.md +2 -2
  184. package/skills/wordpress/SKILL.md +2 -2
  185. package/skills/wordpress/evals/README.md +1 -1
  186. package/skills/wordpress/evals/cases.yaml +1 -1
  187. package/skills/worktrees/evals/README.md +1 -1
  188. package/targets/claude.js +23 -1
  189. package/targets/clone-bootstrap.mjs +1 -1
  190. package/targets/commands.js +1 -1
  191. package/skills/secure-coding/SKILL.md +0 -336
  192. package/skills/secure-coding/evals/README.md +0 -68
  193. package/skills/secure-coding/evals/cases.yaml +0 -55
  194. package/skills/secure-coding/references/authn-authz.md +0 -249
  195. package/skills/secure-coding/references/owasp-by-stack.md +0 -574
  196. package/skills/secure-coding/scripts/verify.sh +0 -208
  197. package/skills/security-scan/SKILL.md +0 -219
  198. package/skills/security-scan/evals/README.md +0 -14
  199. package/skills/security-scan/evals/cases.yaml +0 -50
  200. package/skills/security-scan/references/tools.md +0 -97
  201. package/skills/security-scan/references/triage.md +0 -92
  202. package/skills/security-scan/scripts/verify.sh +0 -108
@@ -1,574 +0,0 @@
1
- # OWASP Top 10 (2021) — vulnerable→fixed per stack
2
-
3
- Each category opens with a 2-line "what / why exploitable", then Bad/Good
4
- pairs. Where a category is most acute in one language we lead with that one but
5
- always give at least Python + one other. A01, A03, and A10 get all three
6
- (Python / Go / TS) because they are the highest-paying, most stack-agnostic
7
- classes. Versions assumed: Python 3.12+, Pydantic v2, SQLAlchemy 2.0,
8
- FastAPI ≥0.115, Next.js 15 App Router / React 19, Zod ≥3.23, Go 1.22+
9
- (`http.ServeMux`, `log/slog`), PostgreSQL 16.
10
-
11
- ## Contents
12
-
13
- - [A01 — Broken Access Control / IDOR](#a01--broken-access-control--idor)
14
- - [A02 — Cryptographic Failures](#a02--cryptographic-failures)
15
- - [A03 — Injection](#a03--injection)
16
- - [A04 — Insecure Design](#a04--insecure-design)
17
- - [A05 — Security Misconfiguration](#a05--security-misconfiguration)
18
- - [A06 — Vulnerable & Outdated Components](#a06--vulnerable--outdated-components)
19
- - [A07 — Identification & Authentication Failures](#a07--identification--authentication-failures)
20
- - [A08 — Software & Data Integrity (supply chain)](#a08--software--data-integrity-supply-chain)
21
- - [A09 — Logging & Monitoring Failures](#a09--logging--monitoring-failures)
22
- - [A10 — SSRF (Server-Side Request Forgery)](#a10--ssrf-server-side-request-forgery)
23
- - [Index — category → fastest fix](#index--category--fastest-fix)
24
-
25
- ## A01 — Broken Access Control / IDOR
26
-
27
- What: a row or function is reachable by a caller who should not see it.
28
- Why exploitable: the id is in the URL/body and the server trusts authentication
29
- ("they're logged in") instead of checking authorization ("do they own *this*").
30
-
31
- ### Python (FastAPI + SQLAlchemy 2.0)
32
-
33
- ```python
34
- # BAD — any authenticated user can read any document by id.
35
- @router.get("/documents/{doc_id}")
36
- def get_doc(doc_id: int, db: Session = Depends(get_db)):
37
- return db.get(Document, doc_id)
38
-
39
- # GOOD — ownership-scoped query; 404 (not 403) on miss to prevent enumeration.
40
- from fastapi import Depends, HTTPException
41
- from sqlalchemy import select
42
-
43
- @router.get("/documents/{doc_id}")
44
- def get_doc(
45
- doc_id: int,
46
- db: Session = Depends(get_db),
47
- user: User = Depends(get_current_user),
48
- ) -> DocumentOut:
49
- doc = db.execute(
50
- select(Document).where(
51
- Document.id == doc_id,
52
- Document.owner_id == user.id,
53
- )
54
- ).scalar_one_or_none()
55
- if doc is None:
56
- raise HTTPException(status_code=404, detail="Not found")
57
- return DocumentOut.model_validate(doc)
58
- ```
59
-
60
- ### Go (1.22 `ServeMux`, `slog`)
61
-
62
- ```go
63
- // BAD — path id goes straight to the query; no ownership check.
64
- mux.HandleFunc("GET /documents/{id}", func(w http.ResponseWriter, r *http.Request) {
65
- id := r.PathValue("id")
66
- var body string
67
- _ = db.QueryRowContext(r.Context(), "SELECT body FROM documents WHERE id=$1", id).Scan(&body)
68
- _, _ = w.Write([]byte(body)) // returned to ANY caller
69
- })
70
-
71
- // GOOD — userID from the authenticated context; scoped query; 404 on miss.
72
- mux.HandleFunc("GET /documents/{id}", func(w http.ResponseWriter, r *http.Request) {
73
- userID, ok := r.Context().Value(userKey).(int64)
74
- if !ok {
75
- http.Error(w, "unauthorized", http.StatusUnauthorized)
76
- return
77
- }
78
- id := r.PathValue("id")
79
- var body string
80
- err := db.QueryRowContext(r.Context(),
81
- "SELECT body FROM documents WHERE id=$1 AND owner_id=$2", id, userID,
82
- ).Scan(&body)
83
- if err == sql.ErrNoRows {
84
- slog.Warn("authz_miss", "user", userID, "doc", id)
85
- http.Error(w, "not found", http.StatusNotFound)
86
- return
87
- }
88
- if err != nil {
89
- http.Error(w, "internal error", http.StatusInternalServerError)
90
- return
91
- }
92
- _, _ = w.Write([]byte(body))
93
- })
94
- ```
95
-
96
- ### TS (Next.js 15 App Router — Route Handler / Server Action)
97
-
98
- ```ts
99
- // BAD — returns the row from the id, assuming a session exists.
100
- // Next.js 15: params is a Promise — await it (sync access is a removed-shim path).
101
- export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
102
- const { id } = await params;
103
- const doc = await db.document.findUnique({ where: { id } });
104
- return Response.json(doc);
105
- }
106
-
107
- // GOOD — auth() guard + ownership scope + notFound() on miss.
108
- import { auth } from "@/auth";
109
- import { notFound } from "next/navigation";
110
-
111
- export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
112
- const { id } = await params;
113
- const session = await auth();
114
- if (!session) notFound();
115
- const doc = await db.document.findFirst({
116
- where: { id, ownerId: session.user.id },
117
- });
118
- if (!doc) notFound();
119
- return Response.json(doc);
120
- }
121
- ```
122
-
123
- > **Server Actions are public POST endpoints.** Re-authorize inside the action
124
- > body on every call. Conditionally rendering the button or hiding the form is
125
- > UX only — an attacker calls the action directly.
126
-
127
- ### Mass-assignment guard
128
-
129
- ```python
130
- # Pydantic v2 — reject unknown fields; never bind owner_id/role from the body.
131
- from pydantic import BaseModel, ConfigDict
132
-
133
- class DocumentCreate(BaseModel):
134
- model_config = ConfigDict(extra="forbid")
135
- title: str
136
- body: str
137
- # owner_id is set from current_user server-side, never from the request.
138
- ```
139
-
140
- ```go
141
- // Go — decode into an allowlist struct that has no owner_id / role field.
142
- type docCreate struct {
143
- Title string `json:"title"`
144
- Body string `json:"body"`
145
- }
146
- dec := json.NewDecoder(r.Body)
147
- dec.DisallowUnknownFields()
148
- var in docCreate
149
- if err := dec.Decode(&in); err != nil { /* 400 */ }
150
- ```
151
-
152
- ```ts
153
- // Zod — .strict() rejects extra keys; map only the allowed ones.
154
- const DocCreate = z.object({ title: z.string(), body: z.string() }).strict();
155
- const data = DocCreate.parse(await req.json());
156
- await db.document.create({ data: { ...data, ownerId: session.user.id } });
157
- ```
158
-
159
- ## A02 — Cryptographic Failures
160
-
161
- What: passwords or data at rest protected with fast/broken primitives or
162
- predictable randomness. Why exploitable: MD5/SHA-1 hashes crack offline at
163
- billions/sec; `random`/`Math.random` tokens are guessable.
164
-
165
- ```python
166
- # BAD — fast hash, trivially brute-forced; predictable token.
167
- import hashlib, random
168
- pw_hash = hashlib.sha256(password.encode()).hexdigest()
169
- token = str(random.randint(0, 10**9))
170
-
171
- # GOOD — Argon2id for passwords; CSPRNG for tokens.
172
- from argon2 import PasswordHasher
173
- import secrets
174
-
175
- ph = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=4) # 64 MiB
176
- pw_hash = ph.hash(password)
177
- token = secrets.token_urlsafe(32)
178
- ```
179
-
180
- ```go
181
- // GOOD (Go) — Argon2id and crypto/rand; never math/rand for secrets.
182
- import ("crypto/rand"; "golang.org/x/crypto/argon2")
183
- salt := make([]byte, 16); _, _ = rand.Read(salt)
184
- key := argon2.IDKey([]byte(password), salt, 3, 64*1024, 4, 32)
185
- ```
186
-
187
- ```ts
188
- // GOOD (TS) — crypto.randomBytes, never Math.random for tokens.
189
- import { randomBytes } from "node:crypto";
190
- const token = randomBytes(32).toString("base64url");
191
- ```
192
-
193
- Data at rest: AES-GCM (an AEAD with integrity), e.g. `cryptography`'s
194
- `AESGCM`/`Fernet`. Enforce TLS everywhere; never MD5/SHA-1 for passwords.
195
-
196
- ## A03 — Injection
197
-
198
- What: user input is concatenated into a query, shell command, or path. Why
199
- exploitable: the parser can't tell data from code — `'; DROP TABLE` /
200
- `$(rm -rf)` / `../../etc/passwd` all execute.
201
-
202
- ### SQL — parameterize, never interpolate
203
-
204
- ```python
205
- # BAD — f-string SQL is injectable.
206
- db.execute(text(f"SELECT * FROM users WHERE email = '{email}'"))
207
- # GOOD — SQLAlchemy 2.0 bound parameters.
208
- from sqlalchemy import select
209
- db.execute(select(User).where(User.email == email))
210
- ```
211
-
212
- ```go
213
- // BAD — Sprintf into the query string.
214
- db.QueryContext(ctx, fmt.Sprintf("SELECT id FROM users WHERE email='%s'", email))
215
- // GOOD — placeholders; the driver binds values.
216
- db.QueryContext(ctx, "SELECT id FROM users WHERE email=$1", email)
217
- ```
218
-
219
- ```ts
220
- // BAD — string concatenation in raw SQL.
221
- sql.unsafe(`SELECT * FROM users WHERE email = '${email}'`);
222
- // GOOD — postgres.js tagged template parameterizes interpolations.
223
- await sql`SELECT * FROM users WHERE email = ${email}`;
224
- // (Prisma client methods are parameterized; avoid $queryRawUnsafe.)
225
- ```
226
-
227
- ### Command injection — no shell, pass args as a list
228
-
229
- ```python
230
- # BAD — shell=True with interpolation runs arbitrary commands.
231
- subprocess.run(f"convert {infile} {outfile}", shell=True)
232
- # GOOD — argument vector, no shell.
233
- subprocess.run(["convert", infile, outfile], shell=False, check=True)
234
- ```
235
-
236
- ```go
237
- // BAD — sh -c with a concatenated string.
238
- exec.CommandContext(ctx, "sh", "-c", "convert "+infile+" "+outfile)
239
- // GOOD — program + explicit args, no shell.
240
- exec.CommandContext(ctx, "convert", infile, outfile)
241
- ```
242
-
243
- Never build a shell string from user input.
244
-
245
- ### Path traversal — canonicalize + require base-dir containment
246
-
247
- ```python
248
- # BAD — user name escapes the base dir via ../.
249
- open(base_dir + "/" + user_name)
250
- # GOOD — resolve and require containment in base.
251
- from pathlib import Path
252
- base = Path(base_dir).resolve()
253
- target = (base / user_name).resolve()
254
- if not target.is_relative_to(base):
255
- raise ValueError("path traversal")
256
- target.open("rb")
257
- ```
258
-
259
- ```go
260
- // GOOD (Go) — Clean + prefix check against the resolved base.
261
- clean := filepath.Join(base, name) // Join already applies filepath.Clean
262
- if !strings.HasPrefix(clean, filepath.Clean(base)+string(os.PathSeparator)) {
263
- http.Error(w, "bad path", http.StatusBadRequest)
264
- return
265
- }
266
- // CAVEAT: filepath.Clean is purely lexical — a symlink inside base can still
267
- // point outside it. If the tree may contain attacker-controlled symlinks,
268
- // resolve them too: real, err := filepath.EvalSymlinks(clean); then re-run the
269
- // prefix check on `real` against an EvalSymlinks'd base. On Go 1.24+,
270
- // os.Root / os.OpenRoot confines opens to the directory and refuses escapes.
271
- ```
272
-
273
- ### NoSQL / operator injection (Mongo-style)
274
-
275
- ```ts
276
- // BAD — { email: req.body.email } where email is { "$ne": null } returns all.
277
- // GOOD — reject object-typed values and $-prefixed keys before querying.
278
- function assertScalar(v: unknown): asserts v is string | number {
279
- if (typeof v === "object" || v === null) throw new Error("bad filter value");
280
- }
281
- ```
282
-
283
- ## A04 — Insecure Design
284
-
285
- What: the feature is missing a control by design, not by bug. Why exploitable:
286
- brute force, double-charge replays, and id enumeration need no "vulnerability",
287
- just usage. Controls: rate-limit + lockout on auth (A07); idempotency keys on
288
- payment writes (a `UNIQUE` constraint on `idempotency_key` turns a replayed POST
289
- into a no-op); signed/expiring URLs instead of guessable sequential ids.
290
-
291
- **Password reset done right** (the flagship): single-use, store the **hash** of
292
- the token, short TTL, link built from a configured base URL.
293
-
294
- ```python
295
- # GOOD — issue: store only the hash; email a link from a configured base URL.
296
- import hashlib, secrets
297
- from datetime import datetime, timedelta, timezone
298
-
299
- raw = secrets.token_urlsafe(32)
300
- db.add(PasswordReset(
301
- user_id=user.id,
302
- token_hash=hashlib.sha256(raw.encode()).hexdigest(),
303
- expires_at=datetime.now(timezone.utc) + timedelta(minutes=15),
304
- used=False,
305
- ))
306
- db.commit()
307
- link = f"{settings.public_base_url}/reset?token={raw}" # NOT request.headers["host"]
308
- send_email(user.email, link)
309
- # On redeem: look up by sha256(token), require not used and not expired,
310
- # set used=True in the same transaction, then invalidate the user's sessions.
311
- ```
312
-
313
- ## A05 — Security Misconfiguration
314
-
315
- What: debug mode, verbose errors, default creds, or permissive CORS shipped to
316
- prod. Why exploitable: stack traces leak internals; `*`+credentials and open
317
- admin panels hand attackers a foothold.
318
-
319
- ```python
320
- # GOOD — app config and a panic-equivalent: never leak internals to the client.
321
- app = FastAPI(debug=False) # no --reload in prod
322
-
323
- @app.exception_handler(Exception)
324
- async def unhandled(request, exc):
325
- logger.exception("unhandled", path=request.url.path) # detail to logs
326
- return JSONResponse(status_code=500, content={"detail": "Internal error"})
327
- ```
328
-
329
- ```go
330
- // GOOD — recover from panics; log detail, return a generic 500.
331
- defer func() {
332
- if rec := recover(); rec != nil {
333
- slog.Error("panic", "err", rec)
334
- http.Error(w, "internal error", http.StatusInternalServerError)
335
- }
336
- }()
337
- ```
338
-
339
- Also: `NODE_ENV=production`; CORS allowlist (never `*` with credentials);
340
- directory listing off; no default creds; security headers present (see the
341
- headers block in `SKILL.md`).
342
-
343
- ## A06 — Vulnerable & Outdated Components
344
-
345
- What: a dependency (often transitive) has a known CVE. Why exploitable: the
346
- vulnerable code ships in your bundle whether you call it directly or not.
347
-
348
- ```bash
349
- # Per ecosystem. Read each line as package@version -> advisory id + fixed-in;
350
- # fix = upgrade to fixed-in, or override/replace if it's transitive.
351
- pip-audit
352
- npm audit --omit=dev --audit-level=high
353
- osv-scanner scan source -L pnpm-lock.yaml # v2 CLI; lockfile-aware, multi-ecosystem
354
- govulncheck ./... # reports ONLY vulns your code actually calls (reachability)
355
- ```
356
-
357
- Override a vulnerable **transitive** dependency: npm `"overrides": {"lib":"1.2.4"}`
358
- in `package.json`; pip a `constraints.txt` pin (`pip install -r req.txt -c
359
- constraints.txt`); Go `replace lib v1.2.3 => lib v1.2.4` in `go.mod`. Full
360
- commands, "how to read", and SBOM/provenance live in
361
- `secrets-and-supply-chain.md`.
362
-
363
- ## A07 — Identification & Authentication Failures
364
-
365
- What: weak login flow — no brute-force defense, session id not rotated, error
366
- messages reveal which accounts exist. Why exploitable: credential stuffing and
367
- session fixation need only a login form.
368
-
369
- - **Brute-force/credential-stuffing defense:** per-IP + per-identity rate limit,
370
- lockout after N failures, generic `"invalid credentials"` (no user
371
- enumeration — same message and timing whether or not the email exists).
372
- - **Session fixation:** regenerate the session id on login and on any privilege
373
- change, so a pre-auth id an attacker planted can't be reused.
374
-
375
- ```python
376
- # GOOD (FastAPI + starsessions/itsdangerous-style store): rotate on login.
377
- async def login(request: Request, creds: LoginIn) -> None:
378
- user = authenticate(creds.email, creds.password) # raises 401 on mismatch
379
- await request.session.regenerate_id() # new server-side session id
380
- request.session["uid"] = user.id
381
- ```
382
-
383
- ```go
384
- // GOOD (Go, gorilla/sessions): rotate the session id at login.
385
- session.Options.MaxAge = 0 // expire the old id
386
- _ = session.Save(r, w) // issue a fresh id, then set uid
387
- session.Values["uid"] = userID
388
- _ = session.Save(r, w)
389
- ```
390
-
391
- MFA enrollment/verification lives in `authn-authz.md`.
392
-
393
- ## A08 — Software & Data Integrity (supply chain)
394
-
395
- What: code or data is trusted without verifying its origin. Why exploitable: a
396
- poisoned dependency, unsigned binary, or CDN compromise runs in your context.
397
-
398
- - **Lockfile integrity:** `npm ci` / `pnpm i --frozen-lockfile`; `go mod verify`
399
- confirms module checksums against `go.sum`.
400
- - **No `curl … | bash`:** download, `sha256sum -c`, then run. SRI for any
401
- third-party `<script>` so the browser refuses a tampered file.
402
-
403
- ```html
404
- <!-- GOOD — Subresource Integrity pins the exact file hash. -->
405
- <script src="https://cdn.example.com/lib.js"
406
- integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
407
- crossorigin="anonymous"></script>
408
- ```
409
-
410
- ## A09 — Logging & Monitoring Failures
411
-
412
- What: security events aren't logged, or logs leak PII/secrets. Why exploitable:
413
- breaches go undetected, and the logs themselves become the leak.
414
-
415
- ```python
416
- # GOOD (structlog) — log the event keyed on user_id; redact secrets; no bodies.
417
- import structlog
418
- log = structlog.get_logger()
419
- log.warning("authz_miss", user_id=user.id, object="document", object_id=doc_id)
420
- log.info("login_fail", user_id=user.id) # never log password or full email
421
- ```
422
-
423
- ```go
424
- // GOOD (slog) — structured fields, user_id not PII.
425
- slog.Warn("authz_miss", "user_id", userID, "object", "document", "id", id)
426
- ```
427
-
428
- Log auth events + authz failures with `user_id` (not PII); never log auth-route
429
- bodies; alert on spikes of `authz_miss` / `login_fail`.
430
-
431
- ## A10 — SSRF (Server-Side Request Forgery)
432
-
433
- What: the server fetches a user-supplied URL. Why exploitable: the attacker
434
- points it at internal services or the cloud metadata endpoint to steal
435
- credentials. Highest-value modern category — block by IP, not just hostname.
436
- Forbidden ranges: `169.254.169.254` (metadata), `10.0.0.0/8`, `172.16.0.0/12`,
437
- `192.168.0.0/16`, `127.0.0.0/8`, `::1`, `fc00::/7`, `fe80::/10`.
438
-
439
- ### Python (`httpx`)
440
-
441
- ```python
442
- # BAD — fetches whatever URL the user gave us: r = httpx.get(user_url)
443
- # GOOD — https-only, resolve DNS, reject EVERY returned IP, then DIAL the
444
- # validated IP literal so DNS cannot rebind between check and connect.
445
- # `sni_hostname` keeps TLS/SNI + certificate validation bound to the real host.
446
- import ipaddress, socket, httpx
447
- from urllib.parse import urlparse
448
-
449
- def _blocked(ip) -> bool: # ip: IPv4Address | IPv6Address
450
- return (ip.is_private or ip.is_loopback or ip.is_link_local
451
- or ip.is_reserved or ip.is_multicast or ip.is_unspecified)
452
-
453
- def safe_get(user_url: str) -> httpx.Response:
454
- u = urlparse(user_url)
455
- if u.scheme != "https" or not u.hostname:
456
- raise ValueError("https URL required")
457
- port = u.port or 443
458
- # Resolve once and validate ALL returned addresses (a multi-record answer
459
- # can pair a safe first record with a private second one).
460
- infos = socket.getaddrinfo(u.hostname, port, proto=socket.IPPROTO_TCP)
461
- addrs = [ipaddress.ip_address(info[4][0]) for info in infos]
462
- if not addrs or any(_blocked(ip) for ip in addrs):
463
- raise ValueError("blocked address")
464
- pinned = addrs[0] # a validated address from the set we just checked
465
- bracket = f"[{pinned}]" if pinned.version == 6 else str(pinned)
466
- with httpx.Client(timeout=5.0, follow_redirects=False) as c:
467
- # Connect to the validated IP literal; pin SNI + Host to the real
468
- # hostname so certificate verification is performed against it.
469
- return c.get(
470
- f"https://{bracket}:{port}{u.path or '/'}",
471
- headers={"Host": u.hostname},
472
- extensions={"sni_hostname": u.hostname},
473
- )
474
- ```
475
-
476
- ### Go (`http.Client`)
477
-
478
- ```go
479
- // GOOD — DialContext re-checks the IP actually dialed; redirects blocked; timeout.
480
- func blockPrivate(ip net.IP) bool {
481
- return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() ||
482
- ip.Equal(net.ParseIP("169.254.169.254"))
483
- }
484
- client := &http.Client{
485
- Timeout: 5 * time.Second,
486
- CheckRedirect: func(*http.Request, []*http.Request) error {
487
- return http.ErrUseLastResponse // do not follow redirects
488
- },
489
- Transport: &http.Transport{
490
- DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
491
- host, port, _ := net.SplitHostPort(addr)
492
- ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host)
493
- if err != nil { return nil, err }
494
- for _, ip := range ips {
495
- if blockPrivate(ip) { return nil, fmt.Errorf("blocked address") }
496
- }
497
- return (&net.Dialer{}).DialContext(ctx, network, net.JoinHostPort(ips[0].String(), port))
498
- },
499
- },
500
- }
501
- ```
502
-
503
- ### TS (Route Handler `fetch`)
504
-
505
- ```ts
506
- // GOOD — https-only allowlist, no redirects, hard timeout.
507
- import { lookup } from "node:dns/promises";
508
- import net from "node:net";
509
-
510
- const ALLOWED_HOSTS = new Set(["api.partner.com"]);
511
-
512
- // Reject loopback, RFC1918 private, link-local (incl. 169.254.169.254 metadata),
513
- // IPv6 loopback/ULA/link-local. Normalize IPv4-mapped IPv6 (::ffff:a.b.c.d) so a
514
- // mapped private address cannot slip through the IPv4 ranges below.
515
- function isPrivate(address: string): boolean {
516
- let addr = address;
517
- const mapped = addr.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i); // IPv4-mapped
518
- if (mapped) addr = mapped[1];
519
-
520
- if (net.isIPv4(addr)) {
521
- const o = addr.split(".").map(Number); // [a, b, c, d]
522
- return (
523
- o[0] === 10 || // 10.0.0.0/8
524
- (o[0] === 172 && o[1] >= 16 && o[1] <= 31) || // 172.16.0.0/12
525
- (o[0] === 192 && o[1] === 168) || // 192.168.0.0/16
526
- o[0] === 127 || // 127.0.0.0/8 loopback
527
- (o[0] === 169 && o[1] === 254) // 169.254.0.0/16 link-local + metadata
528
- );
529
- }
530
-
531
- const ip = addr.toLowerCase().split("%")[0]; // drop zone id (fe80::1%eth0)
532
- if (ip === "::1") return true; // IPv6 loopback
533
- if (ip.startsWith("fc") || ip.startsWith("fd")) return true; // fc00::/7 ULA
534
- if (ip.startsWith("fe8") || ip.startsWith("fe9") ||
535
- ip.startsWith("fea") || ip.startsWith("feb")) return true; // fe80::/10 link-local
536
- return false;
537
- }
538
-
539
- export async function fetchUserUrl(raw: string): Promise<Response> {
540
- const u = new URL(raw); // throws on malformed input
541
- if (u.protocol !== "https:") throw new Error("https required");
542
- if (!ALLOWED_HOSTS.has(u.hostname)) throw new Error("host not allowed");
543
- // Validate EVERY resolved address, not just the first record.
544
- const addrs = await lookup(u.hostname, { all: true });
545
- if (addrs.length === 0) throw new Error("no address");
546
- for (const { address } of addrs) {
547
- if (net.isIP(address) && isPrivate(address)) throw new Error("blocked address");
548
- }
549
- // NOTE: undici/fetch re-resolves DNS at connect time, so this check is
550
- // TOCTOU-racy on its own. For untrusted hosts, pin via a custom undici
551
- // Agent whose `connect` re-validates the dialed IP (mirror the Go dialer).
552
- return fetch(u, { redirect: "error", signal: AbortSignal.timeout(5000) });
553
- }
554
- ```
555
-
556
- **DNS-rebinding caveat:** validating the pre-resolution IP is not enough — the
557
- hostname can resolve to a safe IP at check time and a private IP at connect
558
- time. Validate the IP you actually **dial**: the Python example connects to the
559
- validated IP literal (with `sni_hostname` so TLS still verifies the real host),
560
- and the Go example re-checks every IP inside `DialContext`. The TS `fetch`
561
- example checks all records but cannot pin the dialed IP without a custom undici
562
- `Agent` — for untrusted hosts, supply one whose `connect` re-validates the IP,
563
- mirroring the Go dialer.
564
-
565
- ---
566
-
567
- ## Index — category → fastest fix
568
-
569
- A01 ownership-scoped query + 404 · A02 Argon2id + CSPRNG · A03 parameterize /
570
- arg-list / canonicalize · A04 idempotency key + rate limit · A05 `debug=False`
571
- + CORS allowlist · A06 audit + override transitive · A07 lockout + rotate
572
- session id · A08 `npm ci`/`go mod verify` + SRI · A09 structured log on
573
- `user_id` · A10 https-only + IP allowlist + pin dialed IP. The "fastest fix per
574
- category" table and the flagship Good/Bad blocks live in `SKILL.md`.