Security Lab Integration Guide
What is a security lab?
The lab teaches the instinct; the shipping defaults close the same classes in production — and the finding is only finished when it has a diff and an alert.
The Top 10:2025 keeps Broken Access Control at A01 (now including SSRF), makes Software Supply Chain Failures A03, and drops Injection to A05. Parameterisation is the reference fix, the same move as execFileSync(cmd, [args]). In production the framework is part of the attack surface: Next.js has shipped a security release every month since July 2026, and the floor today is next 16.4.1+ or 15.5.28+ after two critical RCEs on 2026-10-14. Six advisories since March 2025 bypassed middleware/proxy, so proxy.ts is UX and the route handler is the boundary. Ship a nonce CSP from proxy.ts (it forces dynamic rendering), run gitleaks v8.30.1 before every push, move to npm 12 (dependency install scripts blocked by default, git and tarball deps refused), verify with npm audit signatures, and publish via trusted publishing. Put BotID and a WAF rate limit on checkout, sign-up, OTP and every AI route. For agents, prompt injection cannot be filtered out, so limit what a hijacked model can do: tool allowlists, user-scoped credentials, schema-checked arguments, and human approval before money moves.
Seven things the lab teaches
Every offensive concept here exists to produce one defensive artefact: the diff that fixes it and the signal that catches it.
███████╗███████╗ ██████╗██╗ ██╗██████╗ ██╗████████╗██╗ ██╗
██╔════╝██╔════╝██╔════╝██║ ██║██╔══██╗██║╚══██╔══╝╚██╗ ██╔╝
███████╗█████╗ ██║ ██║ ██║██████╔╝██║ ██║ ╚████╔╝
╚════██║██╔══╝ ██║ ██║ ██║██╔══██╗██║ ██║ ╚██╔╝
███████║███████╗╚██████╗╚██████╔╝██║ ██║██║ ██║ ██║
╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝Security Lab Integration Guide
Focus: a defensive, offline lab of deliberately vulnerable targets you own, used to learn each attack class alongside the countermeasure that kills it and the signal that detects it, plus the production hardening that closes the same classes in codeAmani apps (Next.js patch floor, CSP and headers, secrets scanning, npm supply chain, bot and rate-limit controls, and prompt-injection defences for agents). It is never a playbook against real systems.
Legal & ethical scope
Read this before you install anything. Testing a computer system you do not own and are not authorised to test is a crime in essentially every jurisdiction codeAmani operates in. In the US that is the Computer Fraud and Abuse Act (18 U.S.C. § 1030) and state equivalents; in Kenya it is the Computer Misuse and Cybercrimes Act, 2018. "I was only learning" is not a defence, and neither is "the system was already broken." Intent does not create authorisation; a signed document does.
The rules this guide operates under, without exception:
- Own the target or hold written authorisation. Every host, app, container, and phone image in this lab is either something you installed on your own hardware or a purpose-built training platform whose terms of service explicitly invite testing (PortSwigger Web Security Academy, TryHackMe, Hack The Box, VulnHub images running locally). Nothing else. A public bug bounty programme's policy page is a form of authorisation: read it, and stay inside it.
- Written scope before any activity. A real engagement names the exact hosts, domains, IP ranges, and app versions in scope, and explicitly lists what is out of scope. Anything not named is out of scope. In your own lab, write the scope down anyway. It builds the habit, and it stops "I'll just check whether the router does that too."
- Rules of engagement. Agree the test window, the rate limits, a named emergency contact on both sides, what happens if you find live customer data (stop, do not exfiltrate, report immediately), and the fact that you will not test availability. Data you encounter is handled under the client's data-protection obligations, not yours.
- No spillover. The lab has no route to the internet and no route to production. Bind every target to
127.0.0.1or a host-only network. A misconfigureddocker run -p 3000:3000publishes a knowingly vulnerable app to your whole LAN, and on a laptop with a public IP or an open Wi-Fi network, to strangers. - Defence is the deliverable. A finding is not finished when you reproduce it. It is finished when you can state the root cause, the code-level fix, and the log line or rule that would have caught it. That is the entire point of this folder.
Out of scope for this guide, permanently: anything aimed at real or third-party systems, malware / ransomware / C2 development, denial-of-service techniques, detection or EDR evasion, credential attacks at scale, and jailbreak or prompt-injection payload collections aimed at third-party AI products. Where a topic is dual-use, only the lab-isolated defensive framing appears here.
Overview
The guide has two halves.
The lab is three things: targets (apps built to be broken), a proxy to watch traffic, and a notebook where each finding becomes a rule. It all runs in Docker on a laptop. The value is not the exploit. It is the loop: you see input reach a place it should never have reached, you find the line of code that let it, and you write the version that does not.
The shipping side (from Hardening what we ship onward) is where those lessons become defaults in every codeAmani app: the Next.js patch floor, a nonce CSP and security headers, gitleaks and npm supply-chain controls, BotID and rate limits, and the OWASP LLM and Agentic Top 10 for anything with a model in the loop.
Pick lab targets by what you want to learn:
| Platform | Runs | Best for | Cost |
|---|---|---|---|
| PortSwigger Web Security Academy | hosted, per-lab | the canonical, current explanation of every web class, free | free |
| OWASP Juice Shop (v20.3.0, 2026-10-11) | Docker / npm | a full modern JS SPA + API; realistic, gamified, ~100 challenges | free, self-hosted |
| DVWA (2.5) | Docker Compose | classic PHP app with a security level dial (low → impossible), the single best vulnerable-vs-safe code diff | free, self-hosted |
| OWASP WebGoat (v2026.5, 2026-10-12) | Docker | lesson-by-lesson teaching with explanation built in; ships WebWolf as the "attacker's own server" | free, self-hosted |
| TryHackMe | hosted VMs | guided rooms, gentle ramp, structured learning paths | freemium |
| Hack The Box | hosted VMs | unguided machines; closest to a real engagement's ambiguity | freemium |
| VulnHub | download → local VM | offline boot-to-root images you run on your own hypervisor | free |
| OWASP MASTG crackmes (MASTG v2.0.0, 2026-06-30) | Android / iOS | mobile reverse engineering and MASVS-RESILIENCE practice | free |
Official Documentation
Setup: build the lab
1. Start the targets
All three publish to 127.0.0.1 only. That prefix is not decoration. Drop it and you are hosting a known-vulnerable app on your network. These are the commands from each project's own README as of 2026-10-20.
# OWASP Juice Shop: modern SPA + REST API
docker run --rm -p 127.0.0.1:3000:3000 bkimminich/juice-shop
# OWASP WebGoat + WebWolf: guided lessons (set TZ to your timezone; some lessons need it)
docker run -it -p 127.0.0.1:8080:8080 -p 127.0.0.1:9090:9090 -e TZ=America/New_York webgoat/webgoat
# DVWA: classic PHP, with the security-level dial
git clone https://github.com/digininja/DVWA.git
cd DVWA
docker compose up -d
# → http://localhost:4280 (default creds admin / password, then "Create / Reset Database")Juice Shop lands on http://localhost:3000, WebGoat on http://localhost:8080/WebGoat/, WebWolf on http://localhost:9090/WebWolf/, DVWA on http://localhost:4280. For one file that boots all three on a no-egress network, see examples/lab-compose.yml.
2. Add an intercepting proxy
An intercepting proxy is a debugging tool first and a testing tool second. It is the same thing you reach for when a webhook body does not look like you expected.
# Burp Suite Community: https://portswigger.net/burp/communitydownload
# OWASP ZAP 2.17.0 (free, open source, scriptable, runs in CI).
# Its web UI listens on 8080 inside the container, so map it to 8081 on the host:
# WebGoat already owns 127.0.0.1:8080.
docker run --rm -u zap -p 127.0.0.1:8081:8080 -p 127.0.0.1:8090:8090 \
ghcr.io/zaproxy/zaproxy:stable zap-webswing.shPoint the browser at the proxy, and install its CA certificate in a throwaway browser profile only, never in your daily driver. If you proxy WebGoat through ZAP or Burp, you can no longer use localhost; WebGoat's README has you set WEBGOAT_HOST / WEBWOLF_HOST to custom host names instead.
3. Isolate the network
Isolation is the load-bearing control, and it has its own guides: sandbox/CLAUDE_CODE_INTEGRATION.md for VM and container isolation and networking/CLAUDE_CODE_INTEGRATION.md for addressing and routing. Minimum bar:
# A Docker network with no route off the host
docker network create --internal lab-net
# Verify a container on it genuinely cannot reach the internet
docker run --rm --network lab-net alpine sh -c "wget -qO- -T3 https://example.com || echo 'no egress, correct'"For VM-based targets (VulnHub images especially, which are untrusted third-party disk images), use a host-only adapter, snapshot before first boot, and revert after. Never bridge a VulnHub image to your LAN.
4. Lab configuration
The lab needs no secrets, which is the point. If you script against it, these are the only two settings, and neither is a secret:
| Setting | Lab value | Notes |
|---|---|---|
LAB_TARGET_URL | http://127.0.0.1:3000 | Juice Shop. Never a production or client host |
LAB_PROXY_URL | http://127.0.0.1:8090 | ZAP's proxy port as mapped above |
Never place a production URL, API key, or database connection string in a lab script. If a tool asks for a target and you have to think about whether the answer is allowed, the answer is no.
The attack classes and what kills them
The current web standard is the OWASP Top 10:2025 (the 8th edition, now served from top10.owasp.org). Two changes matter for how you plan a lab: SSRF was rolled into A01 Broken Access Control, and Software Supply Chain Failures (A03) is its own category. That is exactly why codeAmani's SLSA provenance policy exists (supply-chain/CLAUDE_CODE_INTEGRATION.md).
| # (2025) | Class | What goes wrong | Countermeasure | How you detect it |
|---|---|---|---|---|
| A01 | Broken Access Control (now includes SSRF) | The server trusts a client-supplied identifier: ?orderId=1002, a JWT claim, a hidden field, a URL it is asked to fetch | Deny by default; authorise server-side on every request against the session subject, never a request parameter. For SSRF: allowlist destination hosts and validate the resolved IP inside the connection's own DNS lookup (check-then-fetch leaves a DNS-rebinding gap; see networking/examples/safe-fetch.ts), refuse redirects, block 169.254.169.254 and RFC 1918 | Log (subject, object, decision) on every access check; alert on a spike of denies from one session, or on outbound requests to internal ranges |
| A02 | Security Misconfiguration | Debug mode in prod, default creds, permissive CORS, verbose stack traces, a public storage bucket, a dev server's endpoints reachable | Hardened build baseline in CI; explicit CORS origins; generic error responses; security headers (see Headers and CSP) | Config drift scanning; alert on Access-Control-Allow-Origin: * or a 500 that leaks a file path |
| A03 | Software Supply Chain Failures | A dependency, build system, or distribution channel is compromised, not just "old library" | Lockfiles + npm ci; npm 12's blocked install scripts; min-release-age; npm audit signatures; trusted publishing; SLSA Build L3 on anything shipped; GitHub Actions pinned to SHAs (see Supply chain) | Dependency review in CI; alert on a lockfile change in a PR that touches no source |
| A04 | Cryptographic Failures | Secrets at rest in plaintext, home-rolled crypto, weak hashing, TLS not enforced | Platform primitives only (argon2/bcrypt, AEAD ciphers); HSTS; secrets in a manager (Hazina), never in the repo | Secret scanning (gitleaks) as a pre-push gate; TLS posture monitoring |
| A05 | Injection (SQLi, command, XSS, template, LDAP) | User input crosses from data into a grammar: SQL, a shell command, HTML, a template | Parameterise. Prepared statements, execFileSync(cmd, [args]), contextual output encoding, DOMPurify for rendered HTML. Validate at the boundary as defence-in-depth, never as the primary control | WAF / CRS rules; DB error-rate spikes; alert on queries whose shape changes (normalised statement fingerprint) |
| A06 | Insecure Design | The feature is unsafe as specified: no rate limit on OTP, no re-auth before an email change | Threat-model at plan time; write abuse cases next to user stories | Business-logic anomaly detection: N password resets an hour, refunds exceeding charges |
| A07 | Authentication Failures | Credential stuffing survivable, no MFA, weak session lifecycle, tokens that never expire | MFA / passkeys; rate limits + BotID on credential routes; rotate session ID on privilege change; short-lived tokens | Alert on auth failure rate per account and per IP; impossible travel; new-device sign-in |
| A08 | Software or Data Integrity Failures | Unsigned updates, insecure deserialisation, CI that trusts an unpinned action | Signed artefacts + verification; never deserialise untrusted input into live objects; pin the pipeline | Verify signatures at install; alert on unexpected artefact digests |
| A09 | Security Logging and Alerting Failures | The attack happened and nothing recorded it, or it recorded and nobody was paged | Structured security events (authn, authz denials, admin actions, payment state changes) with a real alerting path | This is the detection layer. Test it: run a lab attack and confirm something fires |
| A10 | Mishandling of Exceptional Conditions | Errors leak internals, or a failure path silently falls open (catch {} → grant access) | Fail closed; generic client errors + detailed server-side logs; never swallow an exception on a security path | Alert on error-rate spikes on auth/payment paths and on any authorisation path reached via a catch block |
Practise each row against a target: A01 on Juice Shop's basket and order endpoints, A05 on DVWA (flip the security level to read the fix diff), A07 and A09 on WebGoat's lesson sequence, and the whole set on the Academy's per-topic labs. When you need a checklist rather than a risk list, use OWASP ASVS 5.0.0; the Top 10 is an awareness document, ASVS is the verification standard.
SQL injection in depth
SQL injection is the reference case because the mechanism generalises to every other injection class, and because the fix is one line.
The mechanism
A SQL statement has two things in it: grammar (SELECT, WHERE, ', --) and data (the phone number a user typed). String concatenation destroys that boundary, so the user's text is parsed as grammar. A single ' closes the string literal early, and everything after it is executed as SQL.
// ❌ VULNERABLE: the input becomes part of the query's grammar
const phone = req.query.phone as string;
const rows = await db.query(
`SELECT id, name, phone FROM riders WHERE phone = '${phone}'`
);With phone = 254712000000 the database parses ... WHERE phone = '254712000000'. With phone = ' OR '1'='1 it parses ... WHERE phone = '' OR '1'='1', a tautology, and the endpoint returns every rider. The attacker did not guess a password; they rewrote the query.
The fix: parameterise
A parameterised (prepared) statement sends the query text and the values to the database as separate things. The parser sees the statement first and finalises the grammar; values are then bound to placeholders. A ' inside a bound value is a ' character in a string. It can no longer become punctuation.
// ✅ SAFE: node-postgres / Neon: $1 placeholder, values in an array
const rows = await db.query(
"SELECT id, name, phone FROM riders WHERE phone = $1",
[phone]
);// ✅ SAFE: postgres.js tagged template: interpolations are parameterised, not concatenated
const rows = await sql`SELECT id, name, phone FROM riders WHERE phone = ${phone}`;// ✅ SAFE: Supabase / PostgREST: the filter builder parameterises for you
const { data, error } = await supabase
.from("riders")
.select("id, name, phone")
.eq("phone", phone);Escaping is not the fix. Hand-written quote doubling, blocklists of the word UNION, and "strip the apostrophes" all fail against numeric contexts, second-order injection (safe on write, concatenated on read), encoding tricks, and the next database driver you swap in. Parameterise.
The parameterisation footguns
Placeholders bind values, never identifiers or keywords. Anywhere the query shape is dynamic, you cannot parameterise, so you must map through an allowlist:
// ❌ VULNERABLE: sort column concatenated straight in
const rows = await db.query(`SELECT * FROM deliveries ORDER BY ${req.query.sort}`);
// ✅ SAFE: allowlist maps an opaque token to a literal you wrote
const SORTS = { newest: "created_at DESC", fare: "fare_kes DESC" } as const;
const orderBy = SORTS[req.query.sort as keyof typeof SORTS] ?? SORTS.newest;
const rows = await db.query(`SELECT * FROM deliveries ORDER BY ${orderBy}`);Every ORM keeps a raw escape hatch, and every one of them is where SQLi comes back: Prisma's $queryRawUnsafe, Drizzle's sql.raw(), Knex's knex.raw() with template interpolation, TypeORM's query(). Grep for them in review (PATTERNS.md has the gate). The safe raw form always takes values separately:
// ❌ prisma.$queryRawUnsafe(`SELECT * FROM riders WHERE phone = '${phone}'`)
// ✅ prisma.$queryRaw`SELECT * FROM riders WHERE phone = ${phone}` // tagged template = parameterisedThe layers behind it
Parameterisation is the control. These reduce the blast radius when something else slips through.
Least-privilege database user. The app's role should not be able to read tables it never touches, and should not be able to change schema. A read-only reporting path gets its own role.
-- The application role: exactly the verbs it needs, on exactly the tables it needs
REVOKE ALL ON SCHEMA public FROM PUBLIC;
CREATE ROLE app_rw LOGIN PASSWORD :'app_password';
GRANT USAGE ON SCHEMA public TO app_rw;
GRANT SELECT, INSERT, UPDATE ON deliveries, riders TO app_rw;
GRANT SELECT ON fare_rates TO app_rw;
-- deliberately absent: DROP, CREATE, TRUNCATE, and any grant on audit_log or webhook_jobsRow Level Security, on Supabase and on plain Postgres, turns "the query returned rows it should not have" into "the database refused." It is the last line that holds when application-layer authorisation has a bug, which is exactly the A01 failure mode.
ALTER TABLE deliveries ENABLE ROW LEVEL SECURITY;
CREATE POLICY rider_reads_own ON deliveries
FOR SELECT USING (rider_id = auth.uid());Input validation at the boundary. Validate shape, type, and range with a schema at the edge of the system: every form, API route, and webhook handler. It catches a large class of nonsense early and makes the intended domain explicit. It is defence-in-depth, never the primary control.
import { z } from "zod";
const RiderLookup = z.object({
// 254XXXXXXXXX: the M-Pesa phone format from CLAUDE.md
phone: z.string().regex(/^254\d{9}$/),
});
const parsed = RiderLookup.safeParse(await req.json());
if (!parsed.success) return Response.json({ error: "invalid request" }, { status: 400 });A WAF (Vercel WAF, Cloudflare's managed rules, or the OWASP Core Rule Set in front of your own origin) buys time against automated scanning and mass exploitation of a freshly published CVE. It is a speed bump on a determined, targeted attempt. Never let its presence justify a concatenated query.
Detecting it
- Application: log a structured security event on every rejected input at the boundary and every database error. A burst of syntax errors from one session is a scan in progress.
- Database: enable statement logging on the security-relevant paths and alert on statement-shape change: normalise the query text and flag fingerprints your app has never emitted.
- Edge: WAF / CRS rule hits, grouped by source. Rising hits on one path means someone found something interesting.
- Test the detection. Run the Juice Shop or DVWA SQLi challenge against a copy of your own logging stack. If nothing fires, you have A09:2025 and would not have known.
Hardening what we ship (2026)
Everything above is the lab. This half is the same classes closed in production code. Each subsection has a runnable file in examples/.
The Next.js patch floor
Next.js is now on a pre-announced monthly security release model (it started with the July 2026 release), with out-of-band releases for critical issues. Since the RSC remote-code-execution bug of December 2025 (CVE-2025-55182, "React2Shell"), the framework itself has been a regular source of critical advisories. Treat "which Next.js are we on" as a security question, and re-check this table every month.
| Date | Fixed in | What was fixed (headline) |
|---|---|---|
| 2025-03-21 | 15.2.3 / 14.2.25 / 13.5.9 / 12.3.5 | CVE-2025-29927, critical: middleware authorisation bypass via x-middleware-subrequest |
| 2025-12-03 | 16.0.7 / 15.5.7 (and each 15.x line) | CVE-2025-55182, critical: RCE in React Server Components |
| 2026-05-06 / 05-07 | 15.5.16 / 16.2.5, then 15.5.18 / 16.2.6 | Three middleware/proxy bypasses, WebSocket-upgrade SSRF, a CSP-nonce XSS (GHSA-ffhc-5mcf-pf4q), then the incomplete-fix follow-up GHSA-26hh-7cqf-hhc6 |
| 2026-07-21 | 15.5.21 / 16.2.11 | SSRF in Server Actions on custom servers and in rewrites; a proxy bypass with Turbopack + single locale |
| 2026-08-25 | 15.5.24 / 16.3.3 | Two critical unauthenticated RCEs (Image Optimization with AVIF; Windows-hosted servers) |
| 2026-09-22 | 15.5.26 / 16.3.6 | Critical RCE in next/og ImageResponse |
| 2026-09-30 | 15.5.27 / 16.3.8 | High SSRF in Image Optimization; several cache-poisoning and cache-leak issues |
| 2026-10-14 | 15.5.28 / 16.4.1 | Critical unauthenticated RCE in use cache functions returning typed arrays (GHSA-673q-mjm6-r5xr, 16.x); critical RCE in Image Optimization with SVG on glibc Linux (CVE-2026-96889, via sharp, fixed by sharp ≥ 0.35.5); high DoS in Server Actions (GHSA-p3m5-59mp-jv5r) |
Floor as of 2026-10-20: next ≥ 16.4.1 (Active LTS) or ≥ 15.5.28 (Maintenance LTS). The current latest tag is 16.4.2. The React side of the October fix is react-server-dom-* 19.0.9 / 19.1.10 / 19.2.9 / 19.3.1; upgrading next pulls the right one. Anything on 14.x or earlier 15.x lines is out of support for these fixes; upgrade rather than backport.
Three lessons that outlive the specific CVEs:
- Proxy (formerly middleware) is not an authorisation boundary. Six advisories since March 2025 are "middleware / proxy bypass" (CVE-2025-29927, three in May 2026, the GHSA-26hh follow-up, and a Turbopack single-locale bypass in July). Do the session check in
proxy.tsfor redirects and UX, then authorise again in the route handler, Server Action, or data layer, where the bypass cannot reach. Clerk's resource-levelauth.protect()and better-auth's server-side session read are the right shape (see those guides). - Server Actions and route handlers are public POST endpoints. Validate every argument with a schema and authorise inside the action. An action is reachable whether or not a button for it is rendered.
- Image Optimization is a server-side fetcher and a parser. It has produced SSRF, DoS and RCE advisories. Restrict
images.remotePatternsto the exact hosts you need, never a wildcard, and keepsharpcurrent.
Watch: https://github.com/vercel/next.js/security/advisories, and run npm audit in CI so a new advisory fails the build.
Headers and CSP
Two layers. next.config headers() for the static headers every route gets, and a nonce-based CSP set in proxy.ts, because a nonce must be fresh per request. The complete file is examples/proxy.ts; the shape, from the Next.js CSP guide (updated 2026-03-20):
// proxy.ts (Next 16: the file and the export are both named "proxy")
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
const csp = [
"default-src 'self'",
`script-src 'self' 'nonce-${nonce}' 'strict-dynamic'`,
`style-src 'self' 'nonce-${nonce}'`,
"img-src 'self' blob: data:",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
"upgrade-insecure-requests",
].join("; ");
// set it on BOTH the forwarded request headers (so Next can read the nonce
// and stamp it on its own scripts) and the responseWhat the docs make explicit, and what bites people:
- Nonces force dynamic rendering. Static generation, ISR and CDN caching of the HTML are off for those pages, and Partial Prerendering is incompatible with a nonce CSP. Await
connection()fromnext/serveron pages that would otherwise be static. - Development needs
'unsafe-eval'(React's debugging useseval); production does not. Gate it onNODE_ENV. - Want static pages and a strict CSP? Use the experimental hash-based route instead:
experimental.sri.algorithm(sha256/sha384/sha512) innext.config, App Router only. - Third-party scripts get the nonce via
(await headers()).get('x-nonce')and<Script nonce={nonce}>; add their origins toscript-src/connect-src. - Be on 15.5.16+ / 16.2.5+ before relying on nonces at all (GHSA-ffhc-5mcf-pf4q was an XSS in nonce handling).
Alongside the CSP, set on every response: Strict-Transport-Security: max-age=63072000; includeSubDomains; preload (only once every subdomain is HTTPS), X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin, Permissions-Policy denying what you do not use (camera=(), microphone=(), geolocation=()), and frame-ancestors 'none' in the CSP (the modern replacement for X-Frame-Options). Roll a new CSP out as Content-Security-Policy-Report-Only first.
Authentication and sessions
Auth providers have their own guides (clerk/, better-auth/, auth0/); the security floor across all of them:
- Authorise at the resource, not the route. Clerk's resource-level
auth.protect(), a better-auth session read in the handler, or an RLS policy. Never only inproxy.ts. - Patch the auth library like the framework. Current advisories: better-auth needs ≥ 1.7.7 (critical GHSA-965c-763c-88jm); Clerk-on-Next apps need Next ≥ 15.5.18 / ≥ 16.2.6 (GHSA-26hh-7cqf-hhc6), and now the higher floor above.
- Cookies:
HttpOnly; Secure; SameSite=Lax(orStrict) with a__Host-prefix for first-party session cookies. Rotate the session ID on login and on privilege change. - Credential routes (sign-in, sign-up, OTP, password reset) get BotID plus a per-account and per-IP rate limit, and the same response whether or not the account exists.
- Prefer passkeys for staff and admin accounts; they are phishing-resistant in a way that SMS and TOTP are not.
Webhooks are public, unauthenticated POSTs
Verify the signature against the raw body before parsing: stripe.webhooks.constructEvent (Stripe signing secret), Svix for Clerk (svix 2's verify() now returns undefined and throws on failure, so do not rely on its return value for the payload; parse the raw body yourself after it passes), and Daraja callback validation for Kenya-targeted projects. Then deduplicate on the provider's event ID. Full patterns live in webhooks/ and the repo-root SECURITY.md.
Secrets scanning: gitleaks
gitleaks v8.30.1 (2026-03-21) is the workspace gate. Since v8.19.0 the commands are git, dir and stdin; detect and protect still work but are hidden and deprecated.
# Whole history of the current repo (what CI runs)
gitleaks git -v .
# Just what you are about to commit (what a pre-commit hook runs)
gitleaks git --pre-commit --staged -v .
# A folder that is not a git repo (a downloaded export, a lab notes dir)
gitleaks dir -v ./notes
# Adopt on an old repo: record today's findings as a baseline, then fail only on new ones
gitleaks git --report-path gitleaks-baseline.json .
gitleaks git --baseline-path gitleaks-baseline.json --report-path findings.json .Config resolves from --config, then the GITLEAKS_CONFIG env var, then GITLEAKS_CONFIG_TOML, then .gitleaks.toml in the target. Suppress a known test value inline with a gitleaks:allow comment, or by fingerprint in .gitleaksignore. Pass --redact in CI so a finding does not print the secret into build logs.
In CI, prefer the binary or the official image (ghcr.io/gitleaks/gitleaks:v8.30.1) over gitleaks/gitleaks-action@v3. The Action requires a GITLEAKS_LICENSE for repos owned by an organisation (codeAmani-Labs is one); it is free, but the image needs no licence. See examples/security-ci.yml and examples/pre-commit-config.yaml.
A leaked secret is rotated, not deleted. Rewriting history does not un-leak a key that was pushed. Rotate it at the provider first, then clean up.
Supply chain: npm in 2026
The npm ecosystem changed more in the last twelve months than in the five before, mostly in response to self-propagating worms that stole publish tokens through postinstall scripts. The current state, from the npm docs and GitHub changelog:
| Control | What it is | Status (2026-10-20) |
|---|---|---|
| npm 12 blocks dependency lifecycle scripts by default | Install scripts in dependencies do not run unless the root package.json's allowScripts policy allows them. Approve with npm install-scripts approve, then npm rebuild | npm 12.0.0 (2026-07-08); current 12.2.0. Requires Node ^22.22.2 || ^24.15.0 || >=26.0.0 |
allow-git / allow-remote default to none | Git and tarball-URL dependencies are refused unless you opt in | npm 12.0.0 (flags arrived in 11.15.0 defaulting to all) |
min-release-age | Only install versions published more than N days ago; most worm payloads are caught and unpublished within days | npm config (complements --before); pnpm has minimumReleaseAge |
npm audit signatures | Verifies registry signatures and provenance attestations of what you installed | npm ≥ 8.15.0; run after npm ci |
| Trusted publishing (OIDC) | CI publishes with a short-lived OIDC token, no stored npm token; provenance is generated automatically | GA. Unvalidated configs expire after 48 hours (2026-10-02); issue_comment and pull_request_target events are rejected |
| Staged publishing | npm stage publish puts a version in a queue that a maintainer approves with 2FA before it can be installed; a trusted-publishing config can be stage-only | GA 2026-05-22 (npm 11.15.0+); can create new packages since 2026-10-02 |
| Classic tokens | Gone. Revoked 2025-12-09. Granular write tokens are capped at 90 days and enforce 2FA by default | Done |
The codeAmani baseline, as .npmrc plus CI:
# .npmrc (project root): non-secret policy only
min-release-age=3
allow-git=none
allow-remote=none
audit-level=highThen in CI: npm ci (never npm install), npm audit signatures, npm audit --audit-level=high, gitleaks, and all third-party Actions pinned to a full commit SHA. For publishing, trusted publishing + SLSA Build L3 per supply-chain/CLAUDE_CODE_INTEGRATION.md; for anything high-blast-radius, make the trusted-publishing config stage-only so a compromised workflow cannot ship without a human.
For local installs of a package you have not used before, Socket Firewall (npm i -g sfw, then sfw npm install <pkg>) blocks confirmed malware at the network layer, including transitive dependencies. The free tier needs no API key but sends anonymous telemetry (package names and versions) and only covers public registries. It does not see already-cached packages.
Rate limiting and bot protection
Bots go for the routes that cost you money or create accounts: checkout, sign-up, OTP, password reset, and anything that calls an LLM. Two Vercel-native controls, combined in examples/protected-route.ts:
- Vercel BotID (
botid1.5.11): an invisible challenge.initBotId({ protect: [...] })ininstrumentation-client.ts(Next 15.3+) attaches headers to the listed paths;checkBotId()frombotid/serverin the handler returns{ isBot }. Basic is free on all plans; Deep Analysis (Kasada) is $1 per 1,000checkBotId()calls on Pro, custom on Enterprise. As of mid-2026 Vercel routes the challenge traffic itself, so thewithBotId()wrapper innext.configis no longer needed; existing BotID rewrites can be removed. A path missing fromprotectmakescheckBotId()fail; local dev always returnsisBot: false; a directcurlto a protected route is blocked in production by design. - Vercel WAF rate limiting from code (
@vercel/firewall1.2.6): create a WAF rule whose condition is@vercel/firewallwith a rate-limit ID, thencheckRateLimit(id, { request, rateLimitKey })returns{ rateLimited }. The key defaults to client IP; passing a user ID replaces IP bucketing, so compose${userId}:${ip}if you want both. Counters are per region. 1.2.6 added atimeoutoption.
Off Vercel, Cloudflare WAF rate-limiting rules plus Turnstile are the equivalent pair (cloudflare/ guide), and @upstash/ratelimit works anywhere with a Redis (upstash/ guide).
LLM and agent security
Any feature where a model reads untrusted text and can take actions is its own threat model. Two OWASP lists define the vocabulary:
OWASP Top 10 for LLM Applications 2025 (current edition): LLM01 Prompt Injection · LLM02 Sensitive Information Disclosure · LLM03 Supply Chain · LLM04 Data and Model Poisoning · LLM05 Improper Output Handling · LLM06 Excessive Agency · LLM07 System Prompt Leakage · LLM08 Vector and Embedding Weaknesses · LLM09 Misinformation · LLM10 Unbounded Consumption.
OWASP Top 10 for Agentic Applications for 2026 (published 2025-12-09 by the OWASP GenAI Security Project): ASI01 Agent Goal Hijack · ASI02 Tool Misuse and Exploitation · ASI03 Identity and Privilege Abuse · ASI04 Agentic Supply Chain Vulnerabilities · ASI05 Unexpected Code Execution (RCE) · ASI06 Memory & Context Poisoning · ASI07 Insecure Inter-Agent Communication · ASI08 Cascading Failures · ASI09 Human-Agent Trust Exploitation · ASI10 Rogue Agents. The document places MCP tool poisoning (a falsified tool descriptor or schema) under ASI02, and a tool that is malicious at the source under ASI04.
Prompt injection cannot be fully filtered out, because instructions and data share one channel. So the defences are architectural, the same move as parameterisation: limit what a hijacked model can do, not what it can be told. examples/agent-tool-guard.ts implements the core of it:
- Least agency (LLM06, ASI02, ASI03). Each agent gets an explicit tool allowlist. Tools run with the user's scoped credentials, never a shared admin key. Read tools and write tools are separate.
- Human approval for consequential actions (ASI09). Sending money, sending messages to third parties, deleting data, and anything irreversible require an explicit confirmation step outside the model's control. An M-Pesa B2C or a Stripe refund is never one tool call away from a document the agent read.
- Validate tool arguments with a schema, then authorise them server-side, exactly like a Server Action. The model is an untrusted client.
- Mark untrusted content as data. Wrap fetched pages, emails, WhatsApp messages and RAG chunks in clearly delimited blocks and tell the model they are data. This reduces, but does not prevent, injection; the controls above are what hold.
- Treat model output as untrusted input (LLM05). Never pass it to
eval, a shell, raw SQL, ordangerouslySetInnerHTML. Sanitise rendered markdown, and strip or allowlist URLs and images, which are the standard exfiltration channel (). - Sandbox code execution (ASI05). Model-written code runs in an isolated sandbox with no secrets and no network by default (
sandbox/guide). - Cap consumption (LLM10). Per-user token and request budgets, max tool-loop iterations, and BotID on the public chat endpoint.
- Pin and review MCP servers and skills (ASI04). Treat a third-party MCP server like a dependency: pinned version, reviewed tool descriptions, least-privilege credentials.
The OWASP cheat sheets for this are LLM Prompt Injection Prevention, AI Agent Security, and MCP Security (links in RESOURCES.md).
Mobile: OWASP MASVS and MASTG
The mobile equivalent of the Top 10 is the OWASP Mobile Application Security project: MASVS (the requirements standard) and MASTG (the testing guide, plus the crackmes to practise on). The controls are organised into eight categories, each mapping to a decision you make while writing an app:
| MASVS category | The defensive question |
|---|---|
| MASVS-STORAGE | Is anything sensitive on disk, in a backup, in a log, or hardcoded in the package? |
| MASVS-CRYPTO | Are keys in the platform keystore, and is the crypto the platform's, not yours? |
| MASVS-AUTH | Is authorisation enforced server-side, with the device only presenting a credential? |
| MASVS-NETWORK | Is TLS enforced, with no user-added CA trust, and validation never disabled "for debugging"? |
| MASVS-PLATFORM | Are IPC surfaces (exported activities, intents, deep links, WebViews, pasteboard) locked down? |
| MASVS-CODE | Are dependencies current, is untrusted input validated, is debug tooling stripped from release? |
| MASVS-RESILIENCE | Does tampering and reverse engineering raise the cost, knowing it never makes the app safe? |
| MASVS-PRIVACY | Is data minimised, disclosed, and does the user actually have control? |
MASTG shipped v2.0.0 as a tagged release on 2026-06-30. v2 is built around MASWE weakness IDs (MASWE-0001 …) alongside MASTG-TEST-*, MASTG-DEMO-*, and MASTG-TOOL-* identifiers, with a demo per test so you see the finding reproduced and then fixed. Legacy v1 tests are still linked from the site, so search results mix the two schemes.
Practise on the official crackmes (https://mas.owasp.org/crackmes/) for Android and iOS, on an emulator or a dedicated wiped device. Never on a phone that holds real accounts.
The single most useful lesson the mobile lab teaches: the client is not a trust boundary. Anything the app can compute, an attacker with the binary can compute. Root and jailbreak detection, certificate pinning, and obfuscation (MASVS-RESILIENCE) raise cost; they do not create security. Every authorisation decision belongs on the server. It is the same rule as "proxy is a redirect optimisation, not an authorisation boundary," wearing different clothes.
Desktop and OS hardening
The lab teaches the app layer; the host layer is where a compromise becomes permanent. A defensible baseline per platform:
| Platform | Baseline that matters | Official reference |
|---|---|---|
| Windows | BitLocker on, Secure Boot + TPM, virtualisation-based security / Credential Guard, SmartScreen, Defender with tamper protection, standard (non-admin) daily account, Attack Surface Reduction rules | https://learn.microsoft.com/en-us/windows/security/ |
| macOS | FileVault, System Integrity Protection left on, Gatekeeper + notarisation enforced, firewall on, standard account for daily use, Lockdown Mode where the threat model warrants | https://support.apple.com/guide/security/welcome/web |
| Linux | Full-disk encryption, automatic security updates, keys-only SSH with root login disabled, host firewall default-deny inbound, SELinux/AppArmor enforcing, minimal installed surface | https://ubuntu.com/security |
| iOS | Current iOS, strong passcode + biometric, automatic updates, never install an unknown MDM/CA profile, Lockdown Mode for high-risk users | https://support.apple.com/guide/security/welcome/web |
| Android | Current Android + Play Protect, verified boot, sideloading off, per-app permission review, work profile to separate contexts, no root on a device holding real accounts | https://source.android.com/docs/security |
Cross-cutting, and worth more than any individual toggle: patch fast, run as a standard user, use a password manager plus phishing-resistant MFA (passkeys or hardware keys), full-disk encryption everywhere, and keep a restore-tested backup. Ransomware defence is backup and recovery, not a product.
For developer machines specifically: keep the lab off the machine that holds production credentials, and remember that a developer laptop is now a supply-chain target. A worm that runs in postinstall reads ~/.npmrc, cloud CLI credentials and .env files. npm 12's blocked install scripts, Hazina for secrets, and a separate lab VM are the three controls that matter. See sandbox/CLAUDE_CODE_INTEGRATION.md.
The loop: finding → fix → detection
Every lab session produces three artefacts, and stops being useful if it produces fewer:
- Root cause. The specific line or design decision, not the symptom. "The order endpoint reads
orderIdfrom the query string and never checks it against the session subject." - Countermeasure. The diff: parameterised query, server-side authorisation check, output encoding, signature verification. Written as code, not as advice.
- Detection. The log event and the alert that would have fired. If you cannot name it, you have found A09:2025 in your own stack.
Map the finding to MITRE ATT&CK (https://attack.mitre.org/) when it helps you talk to a security team, and score severity with CVSS (https://www.first.org/cvss/) when you need a shared vocabulary for prioritisation. Sigma (https://github.com/SigmaHQ/sigma) is a portable way to write the detection rule once. PATTERNS.md has the template.
codeAmani notes
This lab is where the CLAUDE.md security rules come from
Every rule in the workspace CLAUDE.md is the scar tissue of one of the classes above:
- "Always pass arguments as arrays using
execFileSync(cmd, [args]), never interpolate user input into shell strings." A05:2025 Injection with a shell instead of a database. The array form is parameterisation: the OS receives the program and its arguments as separate values, so a;in an argument is a semicolon character, not a command separator. - "Verify webhook signatures before processing payload." A webhook endpoint is a public, unauthenticated POST target. Without signature verification it is a "make my app believe anything" API: Stripe's signing secret against the raw body, Svix for Clerk, and Daraja callback validation for Kenya-targeted projects. See
SECURITY.mdandwebhooks/. - "Sanitise all user input at system boundaries." Boundary validation as defence-in-depth, with the real control at the point of use (parameterised query, encoded output).
- "Use DOMPurify for any HTML rendering from user content." Stored XSS survives longest because the payload lives in your database and fires for every subsequent viewer. The same rule now applies to model output: LLM-generated markdown is user content.
- RLS on Supabase. The database-level enforcement that holds when an application-layer authorisation check has a bug: A01:2025 insurance.
- SLSA Build L3 provenance (
supply-chain/CLAUDE_CODE_INTEGRATION.md). The Top 10:2025 promoted supply chain to A03, and codeAmani's answer already exists as policy. Provenance proves how and where an artefact was built, never that its source is benign.
Shipping defaults for every codeAmani app
- Next.js at or above the current patch floor (16.4.1 / 15.5.28 today), re-checked on each monthly Next.js security release. Dependabot or Renovate opens the PR; a human merges it the same week.
- Nonce CSP + security headers from
examples/proxy.tson any app that handles accounts or payments. Marketing-only static sites can use theexperimental.sriroute instead and keep static rendering. - gitleaks on pre-commit and in CI; npm 12 policy (
min-release-age, blocked scripts, no git/remote deps);npm audit signaturesin CI. All already standard in this repo; replicate them in each project scaffolded from_TEMPLATE-PROJECT/. - BotID + a rate limit on checkout, sign-up, OTP, and every AI endpoint. The AI route is the one that gets expensive fastest.
- Agents follow the eight rules above. Payments and outbound messages require human confirmation, and the Anthropic or OpenAI key never reaches the client (AI routing per
CLAUDE.md: Claude primary, OpenAI secondary). - Stripe is the default payment rail and its webhook route is the highest-value target in a US-first app; M-Pesa only on Kenya-targeted projects.
Secrets and the lab
- Nothing sensitive enters the lab. No production URLs, no API keys, no real customer data, not even a redacted export. If a lab script needs a credential, generate a throwaway.
- Run
gitleaksbefore every push. The workspace gate already exists. Lab notes are exactly where a copy-pasted token ends up. - Real secrets stay in Hazina (
packages/hazina) and never in a lab config, a screenshot, or a note file. - The proxy's CA certificate goes in a throwaway browser profile only. Installing it system-wide turns your daily browser into a permanent MITM target.
Kenya-targeted projects: the M-Pesa callback is hostile input
For boda-dispatch, duka-order-bot, and the other Kenya-targeted builds, the highest-value application of this guide is the Daraja callback path, because it combines three classes at once:
- A07 / A01. The callback URL is public and unauthenticated by construction. Validate that the request came from Safaricom (source validation plus your own stored
CheckoutRequestID), and treat every field as attacker-controlled until proven otherwise. - A08 (integrity) / replay. Store
CheckoutRequestIDimmediately on the STK Push response and deduplicate on the callback, perMPESA_PATTERNS.md. A replayed callback that credits an order twice is a business-logic failure with a direct cash cost. - Never trust the amount in the callback body. Reconcile it against the fare you quoted and stored. "The callback said 1 KES" is the injection-shaped bug of the payments world.
Three more that are genuinely regional: WhatsApp inbound messages are untrusted input in the same category as a form field, and when an agent reads them they are also a prompt-injection channel (ASI01), so a WhatsApp ordering bot must never be able to trigger a payout from message text alone. On low-bandwidth Android, a tight CSP plus a small JS bundle is both a performance win and a real XSS mitigation. And SIM-swap fraud makes SMS OTP weaker in this market than elsewhere; pair it with device binding or a PIN for anything that moves money.
Pair this guide with
sandbox/CLAUDE_CODE_INTEGRATION.md: isolation (containers, VMs, snapshot/revert, no-egress networks) and sandboxed agent code execution.networking/CLAUDE_CODE_INTEGRATION.md: addressing, routing, why-p 127.0.0.1:3000:3000differs from-p 3000:3000, and the DNS-rebinding-safe SSRF guard innetworking/examples/safe-fetch.ts.clerk/,better-auth/,auth0/: resource-level authorisation and each library's current advisory floor.webhooks/and the repo-rootSECURITY.md: webhook verification, RLS, and the pre-deploy checklist.supply-chain/CLAUDE_CODE_INTEGRATION.md: A03:2025 in practice.encryption/andsecrets/: A04:2025 in practice.
The one-line summary
You break a target you own so that you never ship the bug, and you ship on a framework version, a dependency policy and an agent design that assume the next bug is already out there.