@ericrisco/rsc 4.0.5 → 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.
- package/README.md +4 -4
- package/manifest.json +78 -84
- package/package.json +1 -1
- package/scripts/lib/default-skill-floor.js +5 -1
- package/scripts/lib/domains.js +1 -1
- package/scripts/lib/recommend.js +1 -1
- package/scripts/lib/retired-skills.js +4 -0
- package/scripts/skill-migration-brief.md +1 -1
- package/skills/accessibility/evals/README.md +1 -1
- package/skills/accessibility/evals/cases.yaml +1 -1
- package/skills/agent-safety/SKILL.md +2 -2
- package/skills/agent-safety/evals/README.md +1 -1
- package/skills/agent-safety/evals/cases.yaml +1 -1
- package/skills/analyze/evals/README.md +1 -1
- package/skills/analyze/evals/cases.yaml +2 -2
- package/skills/angular/SKILL.md +1 -1
- package/skills/api-connector-builder/SKILL.md +1 -1
- package/skills/api-design/SKILL.md +3 -3
- package/skills/api-design/evals/cases.yaml +1 -1
- package/skills/automation-strategy/SKILL.md +1 -1
- package/skills/automation-strategy/evals/README.md +1 -1
- package/skills/automation-strategy/evals/cases.yaml +2 -2
- package/skills/automation-strategy/references/orchestration-and-antipatterns.md +1 -1
- package/skills/aws-essentials/SKILL.md +3 -3
- package/skills/aws-essentials/evals/cases.yaml +2 -2
- package/skills/backups/SKILL.md +2 -2
- package/skills/backups/evals/cases.yaml +2 -2
- package/skills/bash-scripting/SKILL.md +1 -1
- package/skills/building-agents/SKILL.md +2 -2
- package/skills/building-agents/evals/cases.yaml +2 -2
- package/skills/chrome-extension/SKILL.md +1 -1
- package/skills/cloudflare/SKILL.md +1 -1
- package/skills/code-review/SKILL.md +2 -2
- package/skills/code-review/evals/cases.yaml +2 -2
- package/skills/compliance/SKILL.md +3 -3
- package/skills/compliance/evals/cases.yaml +1 -1
- package/skills/constitution/SKILL.md +2 -2
- package/skills/constitution/evals/README.md +2 -2
- package/skills/constitution/evals/cases.yaml +2 -2
- package/skills/constitution/references/constitution-template.md +1 -1
- package/skills/cpp/SKILL.md +2 -2
- package/skills/cpp/evals/README.md +1 -1
- package/skills/cpp/evals/cases.yaml +2 -2
- package/skills/csharp-dotnet/SKILL.md +3 -3
- package/skills/csharp-dotnet/evals/cases.yaml +1 -1
- package/skills/csharp-dotnet/references/aspnetcore.md +1 -1
- package/skills/data-policy/SKILL.md +2 -2
- package/skills/data-policy/evals/README.md +1 -1
- package/skills/data-policy/evals/cases.yaml +1 -1
- package/skills/debug/SKILL.md +1 -1
- package/skills/debug/evals/README.md +1 -1
- package/skills/decision-challenge/SKILL.md +2 -2
- package/skills/decision-challenge/evals/cases.yaml +1 -1
- package/skills/deployment/SKILL.md +2 -2
- package/skills/deployment/evals/README.md +1 -1
- package/skills/deployment/evals/cases.yaml +2 -2
- package/skills/django/SKILL.md +2 -2
- package/skills/django/evals/README.md +1 -1
- package/skills/django/evals/cases.yaml +1 -1
- package/skills/django/references/security.md +1 -1
- package/skills/docker/SKILL.md +3 -3
- package/skills/docker/evals/cases.yaml +1 -1
- package/skills/dynamodb/SKILL.md +2 -2
- package/skills/electron/SKILL.md +1 -1
- package/skills/electron/references/packaging-and-updates.md +1 -1
- package/skills/email-connector/SKILL.md +2 -2
- package/skills/email-deliverability/SKILL.md +1 -1
- package/skills/error-handling/SKILL.md +1 -1
- package/skills/expo/SKILL.md +2 -2
- package/skills/fastapi/SKILL.md +4 -4
- package/skills/fastapi/evals/README.md +2 -2
- package/skills/fastapi/evals/cases.yaml +2 -2
- package/skills/fastapi/references/security.md +2 -2
- package/skills/firebase/SKILL.md +1 -1
- package/skills/flutter/SKILL.md +1 -1
- package/skills/flutter/evals/cases.yaml +2 -2
- package/skills/fly-io/SKILL.md +1 -1
- package/skills/gamedev-multiplayer/SKILL.md +1 -1
- package/skills/gamedev-multiplayer/evals/README.md +1 -1
- package/skills/gamedev-multiplayer/evals/cases.yaml +2 -2
- package/skills/gamedev-shipping/SKILL.md +1 -1
- package/skills/gcp-essentials/SKILL.md +2 -2
- package/skills/gcp-essentials/evals/README.md +1 -1
- package/skills/gcp-essentials/evals/cases.yaml +2 -2
- package/skills/gdpr-privacy/SKILL.md +2 -2
- package/skills/gdpr-privacy/evals/cases.yaml +1 -1
- package/skills/github-actions/SKILL.md +2 -2
- package/skills/go/SKILL.md +4 -4
- package/skills/go/evals/README.md +1 -1
- package/skills/go/evals/cases.yaml +2 -2
- package/skills/google-workspace/SKILL.md +2 -2
- package/skills/hetzner/SKILL.md +1 -1
- package/skills/htmx/SKILL.md +4 -4
- package/skills/htmx/evals/cases.yaml +2 -2
- package/skills/implement/SKILL.md +1 -1
- package/skills/init/SKILL.md +2 -2
- package/skills/init/evals/cases.yaml +2 -2
- package/skills/init/references/discovery.md +1 -1
- package/skills/init/references/recommend-skills.md +5 -5
- package/skills/java/SKILL.md +3 -3
- package/skills/java/evals/README.md +1 -1
- package/skills/java/evals/cases.yaml +2 -2
- package/skills/laravel/SKILL.md +3 -3
- package/skills/laravel/evals/README.md +1 -1
- package/skills/laravel/evals/cases.yaml +1 -1
- package/skills/marketing/evals/README.md +1 -1
- package/skills/marketing/evals/cases.yaml +1 -1
- package/skills/mongodb/SKILL.md +2 -2
- package/skills/mongodb/evals/README.md +1 -1
- package/skills/mongodb/evals/cases.yaml +2 -2
- package/skills/nextjs/SKILL.md +3 -3
- package/skills/nextjs/evals/cases.yaml +2 -2
- package/skills/nextjs/references/security.md +2 -2
- package/skills/notion-connector/SKILL.md +3 -3
- package/skills/notion-connector/evals/README.md +1 -1
- package/skills/notion-connector/evals/cases.yaml +2 -2
- package/skills/php/SKILL.md +4 -4
- package/skills/php/evals/README.md +1 -1
- package/skills/php/evals/cases.yaml +1 -1
- package/skills/plan/evals/README.md +1 -1
- package/skills/postgresdb/SKILL.md +1 -1
- package/skills/postgresdb/evals/README.md +1 -1
- package/skills/postgresdb/evals/cases.yaml +2 -2
- package/skills/presentations/evals/README.md +1 -1
- package/skills/python/SKILL.md +3 -3
- package/skills/python/evals/README.md +1 -1
- package/skills/python/evals/cases.yaml +2 -2
- package/skills/rag/scripts/verify.sh +1 -1
- package/skills/review/SKILL.md +2 -2
- package/skills/review/evals/cases.yaml +3 -3
- package/skills/ruby/SKILL.md +1 -1
- package/skills/rust/SKILL.md +2 -2
- package/skills/rust/evals/README.md +1 -1
- package/skills/rust/evals/cases.yaml +2 -2
- package/skills/security-audit/SKILL.md +186 -0
- package/skills/security-audit/evals/cases.yaml +95 -0
- package/skills/security-audit/references/auditor-safety.md +69 -0
- package/skills/security-audit/references/classes/README.md +225 -0
- package/skills/security-audit/references/classes/ai-and-llm.md +247 -0
- package/skills/security-audit/references/classes/client-side.md +181 -0
- package/skills/security-audit/references/classes/cloud-and-deployment.md +167 -0
- package/skills/security-audit/references/classes/data-isolation.md +161 -0
- package/skills/security-audit/references/classes/desktop-mobile-ipc.md +167 -0
- package/skills/security-audit/references/classes/memory-and-binary.md +230 -0
- package/skills/security-audit/references/classes/protocols-and-messaging.md +151 -0
- package/skills/security-audit/references/classes/resource-exhaustion.md +141 -0
- package/skills/security-audit/references/classes/supply-chain.md +147 -0
- package/skills/security-audit/references/classes/web-and-auth.md +238 -0
- package/skills/security-audit/references/coverage-ledger.md +172 -0
- package/skills/security-audit/references/fixes-by-stack.md +972 -0
- package/skills/security-audit/references/fixing.md +200 -0
- package/skills/security-audit/references/hunting.md +146 -0
- package/skills/security-audit/references/isolated-execution.md +85 -0
- package/skills/security-audit/references/platforms.md +650 -0
- package/skills/security-audit/references/reconnaissance.md +73 -0
- package/skills/security-audit/references/resuming.md +55 -0
- package/skills/security-audit/references/scanners.md +347 -0
- package/skills/{secure-coding → security-audit}/references/secrets-and-supply-chain.md +78 -34
- package/skills/security-audit/references/secrets-discipline.md +173 -0
- package/skills/{secure-coding → security-audit}/references/threat-modeling.md +80 -32
- package/skills/security-audit/references/verification.md +118 -0
- package/skills/security-audit/schema/findings.schema.json +178 -0
- package/skills/security-audit/scripts/render-report.mjs +311 -0
- package/skills/security-audit/scripts/validate-findings.mjs +508 -0
- package/skills/skill-scout/scripts/verify.sh +1 -1
- package/skills/source-grounded-development/evals/cases.yaml +1 -1
- package/skills/specify/evals/README.md +1 -1
- package/skills/spring-boot/SKILL.md +3 -3
- package/skills/spring-boot/evals/README.md +1 -1
- package/skills/spring-boot/evals/cases.yaml +1 -1
- package/skills/spring-boot/references/security.md +1 -1
- package/skills/stripe/SKILL.md +2 -2
- package/skills/suggest/evals/cases.yaml +2 -2
- package/skills/supabase/SKILL.md +1 -1
- package/skills/tauri/SKILL.md +2 -2
- package/skills/testing-go/SKILL.md +1 -1
- package/skills/typescript/SKILL.md +2 -2
- package/skills/verify/SKILL.md +3 -3
- package/skills/verify/evals/README.md +2 -2
- package/skills/verify/evals/cases.yaml +2 -2
- package/skills/vue-nuxt/SKILL.md +2 -2
- package/skills/webhooks/SKILL.md +2 -2
- package/skills/wordpress/SKILL.md +2 -2
- package/skills/wordpress/evals/README.md +1 -1
- package/skills/wordpress/evals/cases.yaml +1 -1
- package/skills/worktrees/evals/README.md +1 -1
- package/targets/clone-bootstrap.mjs +1 -1
- package/targets/commands.js +1 -1
- package/skills/secure-coding/SKILL.md +0 -336
- package/skills/secure-coding/evals/README.md +0 -68
- package/skills/secure-coding/evals/cases.yaml +0 -55
- package/skills/secure-coding/references/authn-authz.md +0 -249
- package/skills/secure-coding/references/owasp-by-stack.md +0 -574
- package/skills/secure-coding/scripts/verify.sh +0 -208
- package/skills/security-scan/SKILL.md +0 -219
- package/skills/security-scan/evals/README.md +0 -14
- package/skills/security-scan/evals/cases.yaml +0 -50
- package/skills/security-scan/references/tools.md +0 -97
- package/skills/security-scan/references/triage.md +0 -92
- package/skills/security-scan/scripts/verify.sh +0 -108
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
skill: secure-coding
|
|
2
|
-
|
|
3
|
-
should_trigger:
|
|
4
|
-
- prompt: "Can you do a security review of this diff before I merge? It adds a /documents/{id} GET endpoint in our FastAPI app."
|
|
5
|
-
why: "Explicit security review of a diff touching an endpoint that returns an object by id — A01/IDOR territory, the skill's flagship. Pre-merge security pass is a core Use-when trigger."
|
|
6
|
-
- prompt: "We're about to add a feature where users can paste a URL and our backend fetches it to generate a preview. What could go wrong?"
|
|
7
|
-
why: "User-supplied URL into an outbound fetch is the SSRF (A10) trust-boundary crossing. 'What could go wrong' before coding is a threat-model request even though the user never says 'security' or 'SSRF'."
|
|
8
|
-
- prompt: "Our login endpoint stores password hashes with SHA-256 and we generate reset tokens with Python's random module. Is that okay?"
|
|
9
|
-
why: "Cryptographic failures (A02): fast hash for passwords + non-CSPRNG tokens. Asking 'is that okay' about auth crypto is a hardening request the skill owns (Argon2id + secrets)."
|
|
10
|
-
- prompt: "Marketing wants me to add allow_origins=['*'] with credentials so the widget works everywhere. Set that up?"
|
|
11
|
-
why: "CORS misconfiguration (A05) — wildcard origin with credentials. The user is asking to implement an insecure config; the skill must intercept and correct it rather than comply."
|
|
12
|
-
- prompt: "Before we ship the avatar upload, I want to make sure someone can't upload a malicious file. It currently checks file.type and saves into /public."
|
|
13
|
-
why: "Upload-to-disk boundary: trusting client content-type and storing in the web root. Non-obvious phrasing ('make sure someone can't upload a malicious file') but squarely the upload-validation guidance (magic-byte sniff, store outside web root)."
|
|
14
|
-
- prompt: "I think we accidentally committed an API key to git last week. What's the right way to handle this?"
|
|
15
|
-
why: "Secret exposure in repo — the skill's secrets/supply-chain runbook (rotate first, then scrub history, confirm with gitleaks). User doesn't name OWASP or 'security' but it's exactly the secrets concern."
|
|
16
|
-
- prompt: "Can you threat-model the new payments flow? Users will be able to retry a charge if it times out."
|
|
17
|
-
why: "Explicit threat-model request before code; replayable payment is insecure design (A04 — idempotency-key UNIQUE constraint). Money + design-time modeling are both Use-when triggers."
|
|
18
|
-
|
|
19
|
-
should_not_trigger:
|
|
20
|
-
- prompt: "My Next.js Server Action returns the wrong data on the second render and the UI flickers. How do I fix the re-render?"
|
|
21
|
-
route_to: "nextjs"
|
|
22
|
-
why: "A rendering/state bug with no security boundary, sink, or auth concern. Belongs to the Next.js framework skill, not a security pass."
|
|
23
|
-
- prompt: "Write me a Postgres query that returns the top 5 customers by total order value per month."
|
|
24
|
-
route_to: "postgresdb"
|
|
25
|
-
why: "Pure SQL authoring task — no untrusted input, no injection sink, no authz decision. This is query design, owned by the postgresdb skill."
|
|
26
|
-
- prompt: "My MCP server keeps leaking the system prompt and an attacker could prompt-inject my agent tools. How do I sandbox the hooks?"
|
|
27
|
-
route_to: "building-agents"
|
|
28
|
-
why: "Agent / Claude-Code config security (.claude/, hooks, MCP, prompt injection, sandboxing) is explicitly OUT of scope per 'When NOT to use'. Routes to building-agents."
|
|
29
|
-
- prompt: "The firewall on our VPS is blocking port 5432 and I can't reach Postgres from the app server. How do I open it?"
|
|
30
|
-
route_to: "deployment"
|
|
31
|
-
why: "Pure infra/network firewalling with no application code change — the skill defers this. Network/host config belongs to deployment."
|
|
32
|
-
- prompt: "Rename this Go function and extract the duplicated formatting logic into a helper — no behavior change."
|
|
33
|
-
route_to: "go"
|
|
34
|
-
why: "Trivial non-security refactor with no security-relevant sink; the skill says don't gate these through verify.sh. Plain Go refactor, route to the go skill."
|
|
35
|
-
- prompt: "Can you pentest this competitor's API and find me a working exploit PoC?"
|
|
36
|
-
route_to: "none"
|
|
37
|
-
why: "Offensive testing against a third party is explicitly out of scope (legal); the skill defends code, it does not attack external targets. No sibling fits — decline."
|
|
38
|
-
|
|
39
|
-
capability:
|
|
40
|
-
- scenario: "Review this FastAPI endpoint before merge: @router.get('/documents/{doc_id}') def get_doc(doc_id: int, db: Session = Depends(get_db)): return db.get(Document, doc_id). It's behind auth so any logged-in user hits it."
|
|
41
|
-
must_include:
|
|
42
|
-
- "Identifies Broken Access Control / IDOR (OWASP A01) as the primary finding: authenticated does not mean authorized."
|
|
43
|
-
- "Provides a fixed diff with an ownership-scoped query (WHERE id == doc_id AND owner_id == user.id) using injected current_user."
|
|
44
|
-
- "Returns 404 (not 403) on miss to avoid leaking object existence / enumeration."
|
|
45
|
-
- "Adds an output schema (e.g. DocumentOut.model_validate) instead of returning the raw ORM object, to avoid over-exposing fields."
|
|
46
|
-
- "Ranks by exploitability and ships the fix as code, not a vague 'consider authorizing' note."
|
|
47
|
-
- "Optionally notes running scripts/verify.sh and resolving high/critical before merge."
|
|
48
|
-
- scenario: "We let users submit a webhook URL and our server POSTs to it. Make this safe."
|
|
49
|
-
must_include:
|
|
50
|
-
- "Names SSRF (OWASP A10) as the threat: user-controlled URL into an outbound fetch crossing into the trusted network."
|
|
51
|
-
- "Enforces https-only scheme and an explicit host allowlist (or rejects non-allowlisted hosts)."
|
|
52
|
-
- "Blocks private / link-local / loopback IP ranges (169.254.169.254, 10/8, 172.16/12, 192.168/16, 127/8, ::1, fc00::/7, fe80::/10)."
|
|
53
|
-
- "Resolves the hostname and pins/validates the dialed IP to defeat DNS rebinding (validate the IP actually connected to, not just the string)."
|
|
54
|
-
- "Calls out the metadata-endpoint / internal-service risk (cloud metadata, RDS) rather than treating internal URLs as safe."
|
|
55
|
-
- "Ships the defense as stack-correct code, not a checklist."
|
|
@@ -1,249 +0,0 @@
|
|
|
1
|
-
# Authentication & authorization
|
|
2
|
-
|
|
3
|
-
Pick the session model, verify tokens correctly, authorize per-object, hash
|
|
4
|
-
with Argon2id, and store tokens where XSS can't reach them. Versions: FastAPI
|
|
5
|
-
≥0.115 / Python 3.12+, Auth.js v5 (`next-auth@5`) on Next.js 15, Go 1.22+,
|
|
6
|
-
Dart 3 / Flutter stable. (Auth.js moved under the Better Auth team in late 2025
|
|
7
|
-
and is still patched; the `auth()` patterns below remain valid — for *new*
|
|
8
|
-
projects, weigh Better Auth too. The controls here are library-agnostic.)
|
|
9
|
-
|
|
10
|
-
## Sessions vs JWT — pick this when
|
|
11
|
-
|
|
12
|
-
| Dimension | Server-side session | JWT (access + refresh) |
|
|
13
|
-
|---|---|---|
|
|
14
|
-
| Revocation | Instant — delete the server row | Needs a denylist; access token valid until `exp` |
|
|
15
|
-
| Scale | Shared store (Redis) or sticky | Stateless; nothing to look up |
|
|
16
|
-
| Mobile / native | Cookie handling is awkward | Natural — send as a bearer header |
|
|
17
|
-
| XSS exposure | `HttpOnly` cookie is unreadable by JS | `localStorage` is stealable by any XSS |
|
|
18
|
-
| CSRF | Needs a CSRF token (cookie auto-sent) | Bearer header is immune (not auto-sent) |
|
|
19
|
-
|
|
20
|
-
Bottom line: **server-side session is the default for first-party web.** Use
|
|
21
|
-
JWT for stateless/native clients — short access (5–15 min) + rotating refresh
|
|
22
|
-
with reuse detection + a revocation story.
|
|
23
|
-
|
|
24
|
-
## OAuth2 / OIDC
|
|
25
|
-
|
|
26
|
-
Use the authorization-code flow **with PKCE** (the code challenge defeats
|
|
27
|
-
interception of the authorization code). FastAPI as a **resource server**
|
|
28
|
-
verifies the access token: fetch and cache the JWKS, check `aud`/`iss`/`exp`,
|
|
29
|
-
and **pin the algorithm** — reject `alg:none` and reject HS256 when you expect
|
|
30
|
-
RS256 (an attacker who knows your public key could forge HS256 otherwise).
|
|
31
|
-
|
|
32
|
-
```python
|
|
33
|
-
# GOOD — verify with explicit algorithms, audience, issuer (PyJWT).
|
|
34
|
-
import jwt
|
|
35
|
-
from jwt import PyJWKClient
|
|
36
|
-
from fastapi import Depends, HTTPException, Request
|
|
37
|
-
|
|
38
|
-
_jwks = PyJWKClient("https://issuer.example.com/.well-known/jwks.json")
|
|
39
|
-
|
|
40
|
-
def get_current_user(request: Request) -> User:
|
|
41
|
-
token = request.headers.get("authorization", "").removeprefix("Bearer ").strip()
|
|
42
|
-
try:
|
|
43
|
-
signing_key = _jwks.get_signing_key_from_jwt(token)
|
|
44
|
-
claims = jwt.decode(
|
|
45
|
-
token,
|
|
46
|
-
signing_key.key,
|
|
47
|
-
algorithms=["RS256"], # pinned; rejects alg:none + HS*
|
|
48
|
-
audience="api://my-service",
|
|
49
|
-
issuer="https://issuer.example.com/",
|
|
50
|
-
options={"require": ["exp", "iat", "aud", "iss"]},
|
|
51
|
-
)
|
|
52
|
-
except jwt.InvalidTokenError:
|
|
53
|
-
raise HTTPException(status_code=401, detail="invalid token")
|
|
54
|
-
return load_user(claims["sub"])
|
|
55
|
-
```
|
|
56
|
-
|
|
57
|
-
```ts
|
|
58
|
-
// GOOD (Next.js 15, Auth.js v5) — server-side session guard in a Route Handler.
|
|
59
|
-
import { auth } from "@/auth";
|
|
60
|
-
|
|
61
|
-
export async function GET() {
|
|
62
|
-
const session = await auth();
|
|
63
|
-
if (!session) return new Response("unauthorized", { status: 401 });
|
|
64
|
-
return Response.json({ user: session.user.id });
|
|
65
|
-
}
|
|
66
|
-
```
|
|
67
|
-
|
|
68
|
-
## RBAC vs ABAC
|
|
69
|
-
|
|
70
|
-
RBAC checks a **role** ("is admin"); ABAC checks an **attribute/policy** ("is
|
|
71
|
-
the owner of this object", "is in the same org and the resource is not
|
|
72
|
-
locked"). Use RBAC for coarse function-level gates, ABAC for per-object access.
|
|
73
|
-
|
|
74
|
-
```python
|
|
75
|
-
# GOOD — RBAC dependency (function-level) raises 403 on role mismatch.
|
|
76
|
-
from fastapi import Depends, HTTPException
|
|
77
|
-
|
|
78
|
-
def require_role(role: str):
|
|
79
|
-
def dep(user: User = Depends(get_current_user)) -> User:
|
|
80
|
-
if role not in user.roles:
|
|
81
|
-
raise HTTPException(status_code=403, detail="forbidden")
|
|
82
|
-
return user
|
|
83
|
-
return dep
|
|
84
|
-
|
|
85
|
-
@router.delete("/users/{uid}")
|
|
86
|
-
def delete_user(uid: int, _: User = Depends(require_role("admin"))) -> None:
|
|
87
|
-
db.execute(delete(User).where(User.id == uid))
|
|
88
|
-
|
|
89
|
-
# GOOD — ABAC per-object check (ownership / attribute policy).
|
|
90
|
-
def can_edit(user: User, doc: Document) -> bool:
|
|
91
|
-
return doc.owner_id == user.id or (
|
|
92
|
-
"editor" in user.roles and doc.org_id == user.org_id and not doc.locked
|
|
93
|
-
)
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
```go
|
|
97
|
-
// GOOD — Go middleware reads the role from the authenticated context.
|
|
98
|
-
func RequireRole(role string, next http.Handler) http.Handler {
|
|
99
|
-
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
100
|
-
roles, _ := r.Context().Value(rolesKey).([]string)
|
|
101
|
-
if !slices.Contains(roles, role) {
|
|
102
|
-
http.Error(w, "forbidden", http.StatusForbidden)
|
|
103
|
-
return
|
|
104
|
-
}
|
|
105
|
-
next.ServeHTTP(w, r)
|
|
106
|
-
})
|
|
107
|
-
}
|
|
108
|
-
```
|
|
109
|
-
|
|
110
|
-
## Token lifetimes & refresh rotation
|
|
111
|
-
|
|
112
|
-
Short access tokens (5–15 min). Rotating refresh tokens: each refresh issues a
|
|
113
|
-
new refresh token and invalidates the old one. **Reuse detection**: if an
|
|
114
|
-
already-rotated refresh token is presented again, it was replayed — revoke the
|
|
115
|
-
entire token family and force re-login. Logout invalidates the refresh token.
|
|
116
|
-
|
|
117
|
-
```python
|
|
118
|
-
# GOOD — rotate + detect reuse (server-side refresh store).
|
|
119
|
-
def refresh(presented_jti: str, family_id: str) -> Tokens:
|
|
120
|
-
rec = store.get(presented_jti)
|
|
121
|
-
if rec is None or rec.revoked:
|
|
122
|
-
# Replay of a rotated/revoked token -> kill the whole family.
|
|
123
|
-
store.revoke_family(family_id)
|
|
124
|
-
raise HTTPException(status_code=401, detail="reuse detected")
|
|
125
|
-
store.revoke(presented_jti) # old token is now spent
|
|
126
|
-
new_refresh = store.issue(family_id=family_id) # rotate
|
|
127
|
-
return Tokens(access=mint_access(rec.user_id), refresh=new_refresh)
|
|
128
|
-
```
|
|
129
|
-
|
|
130
|
-
## Cookies done right
|
|
131
|
-
|
|
132
|
-
Canonical flags: `HttpOnly; Secure; SameSite=Lax` (use `Strict` for sensitive
|
|
133
|
-
actions), the `__Host-` prefix (forces `Secure`, `Path=/`, and no `Domain` —
|
|
134
|
-
locks the cookie to the exact host), scoped `Path=/`, no `Domain` attribute.
|
|
135
|
-
|
|
136
|
-
```python
|
|
137
|
-
# FastAPI
|
|
138
|
-
response.set_cookie(
|
|
139
|
-
key="__Host-session", value=sid,
|
|
140
|
-
httponly=True, secure=True, samesite="lax", path="/",
|
|
141
|
-
)
|
|
142
|
-
```
|
|
143
|
-
|
|
144
|
-
```ts
|
|
145
|
-
// Next.js 15 — Route Handler or Server Action.
|
|
146
|
-
import { cookies } from "next/headers";
|
|
147
|
-
(await cookies()).set("__Host-session", sid, {
|
|
148
|
-
httpOnly: true, secure: true, sameSite: "lax", path: "/",
|
|
149
|
-
});
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
```go
|
|
153
|
-
// Go
|
|
154
|
-
http.SetCookie(w, &http.Cookie{
|
|
155
|
-
Name: "__Host-session", Value: sid,
|
|
156
|
-
HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, Path: "/",
|
|
157
|
-
})
|
|
158
|
-
```
|
|
159
|
-
|
|
160
|
-
BAD: storing the token in `localStorage` — readable by any XSS payload.
|
|
161
|
-
|
|
162
|
-
## CSRF defense
|
|
163
|
-
|
|
164
|
-
Needed for **cookie-authenticated, state-changing** requests (the browser sends
|
|
165
|
-
the cookie automatically). Use a double-submit token plus an Origin/Referer
|
|
166
|
-
check. SameSite is defense-in-depth, **not** sufficient alone. Bearer-token APIs
|
|
167
|
-
don't need CSRF tokens — **but must not also accept the auth cookie**, or
|
|
168
|
-
they're back in scope.
|
|
169
|
-
|
|
170
|
-
```python
|
|
171
|
-
# GOOD — double-submit: cookie value must equal the X-CSRF-Token header.
|
|
172
|
-
import hmac
|
|
173
|
-
def verify_csrf(request: Request):
|
|
174
|
-
cookie = request.cookies.get("csrf")
|
|
175
|
-
header = request.headers.get("x-csrf-token", "")
|
|
176
|
-
if not cookie or not hmac.compare_digest(cookie, header):
|
|
177
|
-
raise HTTPException(status_code=403, detail="csrf")
|
|
178
|
-
origin = request.headers.get("origin", "")
|
|
179
|
-
if origin and origin not in settings.allowed_origins:
|
|
180
|
-
raise HTTPException(status_code=403, detail="bad origin")
|
|
181
|
-
```
|
|
182
|
-
|
|
183
|
-
## Password hashing — Argon2id
|
|
184
|
-
|
|
185
|
-
Concrete params (tune `memory_cost` up until a hash takes ~0.5s on prod
|
|
186
|
-
hardware): `time_cost=3, memory_cost=65536 (64 MiB), parallelism=4`. These sit
|
|
187
|
-
above the OWASP Password Storage minimums (`m=19456, t=2, p=1` **or** `m=47104,
|
|
188
|
-
t=1, p=1`) — meet or exceed the floor on every axis. Verify on login and rehash
|
|
189
|
-
transparently when params change. bcrypt with `cost>=12` is an acceptable
|
|
190
|
-
fallback. Never SHA-256/MD5.
|
|
191
|
-
|
|
192
|
-
```python
|
|
193
|
-
# GOOD — argon2-cffi: hash, verify, transparent rehash.
|
|
194
|
-
from argon2 import PasswordHasher
|
|
195
|
-
from argon2.exceptions import VerifyMismatchError
|
|
196
|
-
|
|
197
|
-
ph = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=4)
|
|
198
|
-
|
|
199
|
-
def verify_login(stored_hash: str, password: str) -> bool:
|
|
200
|
-
try:
|
|
201
|
-
ph.verify(stored_hash, password)
|
|
202
|
-
except VerifyMismatchError:
|
|
203
|
-
return False
|
|
204
|
-
if ph.check_needs_rehash(stored_hash):
|
|
205
|
-
save_new_hash(ph.hash(password)) # upgrade params on successful login
|
|
206
|
-
return True
|
|
207
|
-
```
|
|
208
|
-
|
|
209
|
-
Go note: `argon2.IDKey(password, salt, 3, 64*1024, 4, 32)` from
|
|
210
|
-
`golang.org/x/crypto/argon2` produces the equivalent Argon2id key.
|
|
211
|
-
|
|
212
|
-
## MFA
|
|
213
|
-
|
|
214
|
-
TOTP enrollment + verification with `pyotp`; store recovery codes **hashed**
|
|
215
|
-
(same as passwords); require step-up auth (re-verify the second factor) for
|
|
216
|
-
sensitive actions like changing email or disabling MFA.
|
|
217
|
-
|
|
218
|
-
```python
|
|
219
|
-
# GOOD — TOTP enroll + verify (pyotp).
|
|
220
|
-
import pyotp
|
|
221
|
-
secret = pyotp.random_base32() # store encrypted per user
|
|
222
|
-
uri = pyotp.totp.TOTP(secret).provisioning_uri(name=user.email, issuer_name="MyApp")
|
|
223
|
-
# verify with a small window to tolerate clock drift:
|
|
224
|
-
ok = pyotp.TOTP(secret).verify(submitted_code, valid_window=1)
|
|
225
|
-
```
|
|
226
|
-
|
|
227
|
-
## Flutter / Dart 3 note
|
|
228
|
-
|
|
229
|
-
Store tokens in `flutter_secure_storage` (backed by iOS Keychain / Android
|
|
230
|
-
Keystore) — **never** `SharedPreferences`, which is plaintext on disk.
|
|
231
|
-
|
|
232
|
-
```dart
|
|
233
|
-
// GOOD — secure storage, not SharedPreferences.
|
|
234
|
-
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
235
|
-
|
|
236
|
-
final _storage = const FlutterSecureStorage();
|
|
237
|
-
Future<void> saveToken(String token) =>
|
|
238
|
-
_storage.write(key: 'refresh_token', value: token);
|
|
239
|
-
Future<String?> readToken() => _storage.read(key: 'refresh_token');
|
|
240
|
-
```
|
|
241
|
-
|
|
242
|
-
For high-value apps, add TLS certificate pinning (e.g. via a pinned
|
|
243
|
-
`SecurityContext` / `badCertificateCallback` on the HTTP client).
|
|
244
|
-
|
|
245
|
-
---
|
|
246
|
-
|
|
247
|
-
See `owasp-by-stack.md` (A01 access control, A07 auth failures) for the
|
|
248
|
-
vulnerable→fixed handler code, and `secrets-and-supply-chain.md` for where
|
|
249
|
-
signing keys and session secrets are stored.
|