Security suites from the 2026-12 audit: static rules, attack probes, per-class tests, gate
- doctor: code-patterns (unescaped HTML/JSON-LD, eval, shell, NEXT_PUBLIC_ secrets, overrideAccess / Local API user, where from the request, redirects and fetches to a request address) and config-dangerous; live-probes runs the safe attack probes on --url - ATTACK_PROBES / runAttackProbes / createProbeContext exported from /doctor; the reference site runs all of them in pnpm e2e:built (both bundlers) plus CSRF and cookie flags; project template iapl-audit/resources/attack-probes.spec.template.ts - test/securityPatterns.test.ts gates every hit against test/security-patterns.allow.json; test/securityClasses.test.ts covers XSS, redirects, pollution, logs, DoS, cache poisoning - pnpm security:gate (pnpm audit --prod, the two suites, optional offline ZAP) in prepublishOnly - audit findings F1, F3, F4, F5 reproduced as expected-to-fail tests/probes; no fix built - docs: security.md threat list + Security suites, doctor.md, AGENT.md, CHANGELOG, skills Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a416411f01
commit
d2f19095dc
@@ -94,6 +94,22 @@ once there are more than 20.
|
||||
> gate template. **Recommended for projects:** `index: true` on `slugHistory.slug`; the heading font with
|
||||
> `preload: false` (the starter's default now); a placeholder of the 404 content's height.
|
||||
|
||||
### Security audit 2026-12: suites and fixes (docs/security.md)
|
||||
|
||||
> Nothing changes for a running site; nothing to wire. New checks a project can run on its own site:
|
||||
>
|
||||
> - **Static security rules** in the doctor: `iapl-doctor --only security` now also reads the project's own code
|
||||
> (`code-patterns`: unescaped HTML / JSON-LD, `overrideAccess: true` and a Local API `user` without
|
||||
> `overrideAccess: false` where a request reaches, a `where` from the request, `eval`, `NEXT_PUBLIC_` secrets,
|
||||
> redirects and fetches to an address from the request) and its configs (`config-dangerous`). A correct place is
|
||||
> marked `// iapl-security-ok: <why>`. Expect new warnings on an existing site the first time; judge each.
|
||||
> - **Attack probes**: `iapl-doctor --url https://<domain> --only live-probes` (requests that change nothing) and the
|
||||
> Playwright template `iapl-audit/resources/attack-probes.spec.template.ts`. Exported: `ATTACK_PROBES`,
|
||||
> `runAttackProbes`, `createProbeContext`, `scanCode`, `scanConfigs` (`@intecion/ipal-kit/doctor`).
|
||||
> - Known and reported by the probes until fixed (audit findings): the Markdown copy given at an HTML URL to
|
||||
> `Accept: text/markdown` can be cached as the page by a CDN that caches HTML (`markdown-vary`); public REST lists
|
||||
> take any `limit` (`unbounded-list`); an operator name in `?sort=` answers 500 on MongoDB (`sort-operator`).
|
||||
|
||||
## 1.17.2 — version history with readPublished, sign-in and panel actions, staff-only REST submissions and jobs, the cookie button
|
||||
|
||||
> **Read before upgrading.** No schema change, no migration on any database, no import-map change. What changes for
|
||||
|
||||
@@ -1462,6 +1462,9 @@ its own tests). Order from the cheapest:
|
||||
| Site in the browser | `iapl-seo-check`, `iapl-consent-check`, `cookie-scan` | before handover, after deploy |
|
||||
| Closed doors (Playwright) | `iapl-audit/resources/closed-doors.spec.template.ts` → `tests/closed-doors.spec.ts`: every door that must stay closed, asked on a production build as anonymous, customer and editor; add the project's own doors (security.md "Closed doors from outside") | before every release and after every IAPL / Payload update |
|
||||
| Routes judged | `iapl-audit/resources/routes.template.ts` → `tests/routes.ts`; `pnpm payload run tests/routes.ts` against the committed `tests/routes.snapshot.json`, one reason per route; `… update` after an upgrade (security.md "Routes nobody has judged") | in CI, and after every IAPL / Payload / plugin update |
|
||||
| Security, code | `pnpm exec iapl-doctor --only security`: headers, CSP, 2FA, account rules and the static rules over your code (`code-patterns`: unescaped HTML / JSON-LD, `overrideAccess: true` or a Local API `user` without `overrideAccess: false` where a request reaches, a `where` from the request, `eval`, `NEXT_PUBLIC_` secrets, redirects and fetches to an address from the request; `config-dangerous`). A correct place: `// iapl-security-ok: <why>` (security.md "Security suites") | before every "done", in CI |
|
||||
| Attack probes (Playwright / doctor) | `iapl-audit/resources/attack-probes.spec.template.ts` → `tests/attack-probes.spec.ts` on a production build or staging (secret files, bundle secrets, proxy bypass, open redirect, cache poisoning, NoSQL operators, anonymous where / draft / GraphQL reads, error leaks, unbounded lists, `/_next/image`, 8 MB bodies); add a probe per custom endpoint in `EXTRA`. On the live site: `pnpm exec iapl-doctor --url https://<domain> --only live-probes` (changes nothing) | before every release, after every IAPL / Payload / Next update, and after deploy (live) |
|
||||
| Dependencies | `pnpm audit --prod` (the doctor's `deps-audit`): no high or critical; see §4 for the minimum Next / sharp / Payload | before every deploy |
|
||||
| Project logic | vitest for your own functions (mapping company data to JSON-LD, helpers, hooks, migration scripts with `--dry-run`) | when you write logic the plugin does not have |
|
||||
| Panel | the editor test (§11) and the empty-block test (§6.5a) | every new block / global |
|
||||
|
||||
|
||||
@@ -1132,6 +1132,7 @@ Rules: AGENT.md §8a.
|
||||
|
||||
| File | What it shows |
|
||||
|---|---|
|
||||
| `e2e/attack-probes.spec.ts` | attack probes on the built site (run by `pnpm e2e:built` in both bundlers): every probe of the plugin's ATTACK_PROBES (security.md "Security suites") with this site's secret values for the bundle check, plus CSRF with the editor's cookie from another origin and the session cookie's flags; probes tied to an open audit finding are expected to fail (`test.fail`) |
|
||||
| `e2e/closed-doors.spec.ts` | closed doors from outside (run by `pnpm e2e:built` in both bundlers): every door of e2e/closed-doors.ts asked on the production build as an anonymous visitor, a customer (the fixture's `e2e-visitors`) and an editor; doors still open while the owner decides are asserted open (`test.fail`) |
|
||||
| `e2e/closed-doors.ts` | the doors that must stay closed, who each is closed for and how a closed answer looks; a project adds its own (security.md "Closed doors from outside") |
|
||||
| `e2e/create-test-admin.ts` | two test admins with a known TOTP secret (the specs share out the five 2FA verify attempts per account), their stored verify counts cleared, and e-mail sending pointed at the tests' mail sink (local / CI database only) |
|
||||
|
||||
@@ -65,6 +65,13 @@ names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` —
|
||||
`pnpm payload run tests/routes.ts` fails on a route nobody has judged). A new custom endpoint, collection or
|
||||
route file of the project = a new snapshot entry with its reason, and a door in `DOORS` if it must stay closed.
|
||||
|
||||
- **Attack probes and static security rules** (security.md "Security suites"): `resources/attack-probes.spec.template.ts`
|
||||
→ `tests/attack-probes.spec.ts`, run on a production build or staging (`BASE_URL=… PAGE=/pl pnpm exec playwright test
|
||||
tests/attack-probes.spec.ts`): the plugin's ATTACK_PROBES, plus the project's own in `EXTRA` for every custom
|
||||
endpoint. On the live site: `pnpm exec iapl-doctor --url https://<domain> --only live-probes`. The code side:
|
||||
`pnpm exec iapl-doctor --only security` (`code-patterns`, `config-dangerous`); a correct place gets
|
||||
`// iapl-security-ok: <why>`. Dependencies: `pnpm audit --prod` (the doctor's `deps-audit`) — no high or critical.
|
||||
|
||||
- **Editor test** (AGENT.md §11): every text, image, button, section,
|
||||
menu, footer and SEO field can be changed in the panel, in every language.
|
||||
- **Cookie consent:** in Network, before accepting, there are no requests to
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Attack probes from outside — the requests attackers send to Payload / Next.js sites, asked on a PRODUCTION build
|
||||
* (`pnpm build && pnpm start`) or a staging copy (IAPL docs/security.md "Security suites"). Copy to
|
||||
* tests/attack-probes.spec.ts and run:
|
||||
*
|
||||
* BASE_URL=http://localhost:3000 PAGE=/pl pnpm exec playwright test tests/attack-probes.spec.ts
|
||||
*
|
||||
* The probes come from the plugin (ATTACK_PROBES, @intecion/ipal-kit/doctor), so an IAPL upgrade brings new ones.
|
||||
* On a LIVE site use `pnpm exec iapl-doctor --url https://<domain> --only live-probes` instead: it runs only the
|
||||
* probes that change nothing (no 8 MB bodies). This spec runs all of them — local or staging only.
|
||||
* The bundle check looks for this site's own secret VALUES: they are read from the environment (.env of the local
|
||||
* build) and never printed. Add the project's own probes to EXTRA.
|
||||
*/
|
||||
import { ATTACK_PROBES, type AttackProbe, createProbeContext } from '@intecion/ipal-kit/doctor'
|
||||
import { expect, test } from '@playwright/test'
|
||||
|
||||
const BASE = (process.env.BASE_URL ?? 'http://localhost:3000').replace(/\/$/, '')
|
||||
const PAGE = process.env.PAGE ?? '/'
|
||||
const secrets = ['PAYLOAD_SECRET', 'CRON_SECRET', 'R2_SECRET_ACCESS_KEY', 'TURNSTILE_SECRET_KEY', 'IAPL_DOCTOR_TOKEN', 'IAPL_COOKIE_SCAN_TOKEN'].map((k) => process.env[k]).filter((v): v is string => !!v && v.length >= 8)
|
||||
|
||||
/** The project's own probes, e.g. a custom endpoint that must refuse an 8 MB body or an operator in its query. */
|
||||
const EXTRA: AttackProbe[] = []
|
||||
|
||||
for (const probe of [...ATTACK_PROBES, ...EXTRA]) {
|
||||
test(`${probe.class}: ${probe.title}`, async () => {
|
||||
const result = await probe.run(createProbeContext(BASE, { page: PAGE, secrets }))
|
||||
test.skip(!!result.skipped, result.skipped)
|
||||
expect(result.ok, result.detail).toBe(true)
|
||||
})
|
||||
}
|
||||
@@ -46,6 +46,16 @@ Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`.
|
||||
`--url <url>` · `--staging` (must be noindex) · `--admin-route <path>` · `--deep` · `--env-file <prod export>` (checks
|
||||
`<domain>_prod`) · `--only` / `--skip <ids,groups>` · `--sites '../*-web'` (a read-only rule × site table, exit 0).
|
||||
|
||||
**Security checks only** (security.md "Security suites"): `pnpm exec iapl-doctor --only security` — headers, CSP,
|
||||
2FA, account rules, plus the static rules over the project's own code (`code-patterns`: unescaped HTML / JSON-LD,
|
||||
`overrideAccess: true` or a Local API `user` without `overrideAccess: false` where a request reaches, a `where` from
|
||||
the request, `eval`, `NEXT_PUBLIC_` secrets, redirects and fetches to an address from the request) and its configs
|
||||
(`config-dangerous`). With `--url https://<domain>` also `live-probes`: the plugin's attack probes that change
|
||||
nothing, run against the real site (secret files, bundle secrets, proxy bypass, open redirects, cache poisoning,
|
||||
NoSQL operators, anonymous where / draft / GraphQL reads, error leaks, unbounded lists, `/_next/image`). Verify: on a
|
||||
fresh starter site the run lists no `code-*` finding; add `eval(x)` to a page and `code-eval` appears. A correct
|
||||
place is marked `// iapl-security-ok: <why>`.
|
||||
|
||||
Exit `0` ok · `1` findings at or above `--fail-on` · `2` could not run · `3` a rule crashed.
|
||||
|
||||
## CI of a new site (starter, reference site)
|
||||
|
||||
@@ -896,11 +896,13 @@ Bin: `iapl-doctor` (`pnpm exec iapl-doctor [dir] [--json] [--md] [--strict] [--f
|
||||
| `withJobsRunAccess(config, options \| false)` / `jobsRunNotice(config)` | `@intecion/ipal-kit` | The config with that rule (only when `jobs.access.run` is missing; marks `custom.iapl.jobsRunDefault`); the start-up line when the queue is on and the secret is missing (null otherwise). |
|
||||
| `cronSecretMatches(req, secret)`, `CRON_SECRET_ENV`, `CRON_SECRET_MIN_LENGTH` | `@intecion/ipal-kit` | `Authorization: Bearer <secret>` compared in constant time; an unset or shorter-than-16 secret never matches. Default variable `CRON_SECRET`. |
|
||||
| `runRouteCheck({ config, appDir?, snapshot?, update?, graphql?, cwd?, log? })` | `@intecion/ipal-kit/doctor` | `routes:check`: every public route (REST, GraphQL, Next route files) against the judged snapshot (default `e2e/routes.snapshot.json`); returns 1 on a route nobody judged or an entry without a reason; `update` writes new routes with an empty reason. Template: `iapl-audit/resources/routes.template.ts` (security.md "Routes nobody has judged"). Type `RunRouteCheckOptions`. |
|
||||
| `ATTACK_PROBES`, `runAttackProbes(ctx, probes?)`, `createProbeContext(base, { page?, secrets?, timeoutMs?, userAgent? })` | `@intecion/ipal-kit/doctor` | The HTTP attack probes (secret files, bundle secrets, proxy bypass, open redirect, host-header and negotiation cache poisoning, NoSQL operators in sign-in and sort, anonymous where / draft / GraphQL reads, error leaks, unbounded lists, `/_next/image`, headers, methods, 8 MB bodies). Each `{ id, class, title, live, finding?, run(ctx) → { ok, detail, skipped? } }`; `runAttackProbes` runs the `live` ones by default. The doctor's `live-probes` rule; the Playwright template `iapl-audit/resources/attack-probes.spec.template.ts`; your own probe = an object of the same shape (security.md "Security suites"). Types `AttackProbe`, `ProbeContext`, `ProbeAnswer`, `ProbeResult`. |
|
||||
| `scanCode(path, code)`, `listCodeFiles(root, start)`, `codeFindings(ctx)`, `scanConfigs(next, payload)`, `securityCodeRules`, `SECURITY_OK_MARKER`, `LIVE_PROBE_IDS` | `@intecion/ipal-kit/doctor` | The static security rules behind `code-patterns` and `config-dangerous`: every hit `{ rule, file, line, severity, message, text }` (types `CodeHit`, `CodePatternId`). A correct place is marked `// iapl-security-ok: <why>`. Use `scanCode` in a test of your own to keep a judged allow-list, as the plugin does (`test/security-patterns.allow.json`). |
|
||||
| `listPublicRoutes(config, { graphqlSchema?, routeFiles? })` | `@intecion/ipal-kit` | Stable ids of every door a built config opens: `GET /api/users/me`, `graphql mutation loginUser`, `next GET /sitemap.xml`. From the config only (same on every database). Types `RouteInventoryOptions`, `GraphqlSchemaLike` (`getQueryType` / `getMutationType`). |
|
||||
| `listNextRouteFiles(files, read)` | `@intecion/ipal-kit` | Next route handlers of an app directory (`route.ts` with the methods it exports, `robots.ts`, `sitemap.ts`, `manifest.ts`; route groups left out). |
|
||||
| `compareRouteSnapshot(current, snapshot)` / `updateRouteSnapshot(current, snapshot)` | `@intecion/ipal-kit` | `{ unjudged, unexplained, gone }` against a `RouteSnapshot` (route id → reason); the snapshot after `--update` (new routes with `''`, gone ones dropped). Type `RouteSnapshotDiff`. |
|
||||
|
||||
**Types:** `DoctorRule`, `DoctorFinding`, `RuleFinding`, `DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`,
|
||||
**Types:** `AttackProbe`, `ProbeContext`, `ProbeAnswer`, `ProbeResult`, `CodeHit`, `CodePatternId`, `DoctorRule`, `DoctorFinding`, `RuleFinding`, `DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`,
|
||||
`DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`, `FrontendLayout`.
|
||||
|
||||
## Turnstile (`turnstile`) — details: `node_modules/@intecion/ipal-kit/docs/turnstile.md`
|
||||
|
||||
@@ -123,6 +123,9 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE
|
||||
| | `staff-accounts-open` | error (warning for `read`, `readVersions`) | (deep) a staff collection that an account of another, non-staff auth collection may create in, read (also its versions), update, delete from or unlock — it can make itself staff, change a staff password, list the accounts or lift a login lock. The account rules are off (`accounts: false`, `adminOnlyCreate` / `adminOnlyWrite` / `staffOnlyRead: false`) or the project's own rule is wider. Asked with a made-up outside account; a rule that throws counts as closed |
|
||||
| | `turnstile-degraded` | warning / error | (deep) Turnstile is checking forms; while it is not (wrong or missing secret, Cloudflare down) a warning, an error once it has lasted 24 hours (counted from the recorded start to now) |
|
||||
| | `turnstile-env-key` | warning | (deep) the Turnstile secret key is in the panel, not in the deprecated `TURNSTILE_SECRET_KEY` environment variable |
|
||||
| | `code-patterns` | error / warning | the project's own code (`src/`, seeds, migrations, scripts and tests left out where the rule is about requests): `dangerouslySetInnerHTML` / `innerHTML` with a value no sanitizer passed, JSON in a `<script>` without escaping `<` (`code-inner-html`); `eval` / `new Function` / `vm` (`code-eval`); a shell command from a template string (`code-shell`); a `NEXT_PUBLIC_` secret, or a server secret read in a `'use client'` file (`code-public-secret`); `overrideAccess: true` where a request reaches (`code-override-access`); the Local API given a `user` without `overrideAccess: false` — Payload then ignores the user (`code-local-api-user`); a `where` taken from the request (`code-raw-where`); a redirect (`code-open-redirect`) or a server-side `fetch` (`code-ssrf`) to an address from the request. One finding per rule and file. A correct place: `// iapl-security-ok: <why>` on the line or the line above; a file or folder: `iapl-doctor.json` `rules: { "code-override-access": { "files": ["src/lib/admin/**"], "off": true, "reason": "…" } }` (security.md "Security suites") |
|
||||
| | `config-dangerous` | error / warning | `next.config`: `images.dangerouslyAllowSVG` without `images.contentSecurityPolicy` (error), `remotePatterns` hostname `**` / `*`, `serverActions.allowedOrigins` with `*` (error), `productionBrowserSourceMaps: true`; `payload.config`: `cors: '*'`, `debug: true`, GraphQL playground / introspection on in production, `maxDepth` above 20 |
|
||||
| | `live-probes` | error / warning | (live, `--url`) the plugin's attack probes that change nothing: source / env / git files, secrets in the page scripts and public source maps, `x-middleware-subrequest` proxy bypass, open redirects, `X-Forwarded-Host` in redirects and links, Markdown / RSC answers a cache could store as the page, `$ne` operators in a sign-in, anonymous `where` / draft / versions / GraphQL reads, stack traces, unbounded `limit`, `/_next/image` to inner hosts or SVG, headers on every kind of answer, odd methods and an unknown Server Action. Reported as `live-probes:<id>`; the 8 MB-body probe runs only in the Playwright spec (security.md "Security suites") |
|
||||
| | `storage-names` | warning | the visitor cookie the layout sets (`<PageStats visitorCookie>`, default `ipal_vid`) is the one the config makes the cookie scanner declare (`storageNames`, stats.md) |
|
||||
| | `cookie-scanner` | error / warning / info | `cookieScanner` on (with `crawl`, else info); deep: nothing waits for approval (warning) |
|
||||
| mail | `mail-method` | error / info | (deep) the chosen "Sending method" can be used — "Own SMTP server" with server, user name and password, "Microsoft Graph" with the `GRAPH_*` variables; otherwise e-mails are not sent and nothing is sent another way (error). On Postgres / SQLite: the column of `emailMethod` exists — the 1.17.1 migration has run (error). Nobody has chosen yet: the site picks a method from what is filled in until Site integrations is saved (info) |
|
||||
|
||||
@@ -1350,6 +1350,69 @@ once per option in the server log:
|
||||
`[iapl] cookieScanner.access returned an object, not true or false. It is still read as allowed; …`.
|
||||
Return a boolean: `({ req }) => Boolean(req.user)`, `({ req }) => isAdmin(req.user, req.payload)`. One function reads
|
||||
every answer: `accessAllowed(option, answer)` (exported). The second factor is checked before the callback, as before.
|
||||
## Threat list (security audit 2026-12)
|
||||
|
||||
What most often hits Payload / Next.js / Node sites, ranked by how often it appeared in the advisories of the last three
|
||||
years (Dec 2023 – Dec 2026: 71 for `next`, 9 for React Server Components, 58 for `payload` / `@payloadcms/*`, 147 in the
|
||||
usual transitive dependencies; GitHub Security Advisories, NVD) and by what it costs a client site. OWASP Top 10:2025
|
||||
and ASVS 5.0 name the categories. Each row says where IAPL covers it and which suite checks it.
|
||||
|
||||
| # | Class | Seen in | IAPL covers it with | Checked by |
|
||||
|---|---|---|---|---|
|
||||
| 1 | Denial of service (body size, ReDoS, Server Actions, image optimizer, unbounded lists, GraphQL) | 27 core + 46 deps; Next GHSA-p3m5-59mp-jv5r (Server Actions, Oct 2026) | body caps on every public plugin route (`readCappedBody`), MCP batch cap, rate limits; Payload `maxDepth`. **Lists are not capped** (audit F4) | probes `body-size`, `unbounded-list`; per-class tests |
|
||||
| 2 | Access control (REST / GraphQL / Local API `overrideAccess`, drafts, versions, field access) | 17 Payload (A01) | account rules, `readPublished`, 2FA wrapper, jobs rule, `visitor-writes` | closed-doors spec, `routes:check`, probes `rest-where`, `graphql`; rules `code-override-access`, `code-local-api-user` |
|
||||
| 3 | Cache poisoning and cross-user leaks (ISR, RSC, CDN, host headers) | 18 Next (CVE-2024-46982 …) | no host header read for URLs (`NEXT_PUBLIC_SERVER_URL`), `no-store` on personal answers. **Markdown negotiation at the HTML URL** (audit F3) | probes `host-header`, `markdown-vary`, `rsc-vary` |
|
||||
| 4 | Remote code execution (RSC Flight, `use cache`, image optimizer + libvips/librsvg) | 10 core (React2Shell CVE-2025-55182, GHSA-2464-fhr4-w9xw, GHSA-673q-mjm6-r5xr, GHSA-xqc2-xf4c-x3h3) | minimum Next / sharp in AGENT.md §4; no `eval` | `deps-audit`, `code-eval` |
|
||||
| 5 | Information disclosure (errors, source maps, secrets in bundles and files) | 14 core | no stack traces in plugin answers, write-only secrets, no manifest in `.next/static` | probes `error-leak`, `bundle-secrets`, `secret-files`; rule `code-public-secret` |
|
||||
| 6 | SSRF (Server Actions Host header, middleware redirects, image optimizer, URL uploads) | 9 core (CVE-2024-34351, CVE-2025-57822) | `buildImagesConfig` (listed hosts only), `safeFetch` for brand images, the crawl only of the site's own URL | probe `image-optimizer`; rule `code-ssrf` |
|
||||
| 7 | Authentication and session (JWT after logout, fixation, 2FA bypass, enumeration, CSRF) | 8 + 3 (CVE-2025-4643, CVE-2025-4644) | 2FA enforced and wrapped around plugin entities, own-origin checks, `serverURL` for Payload's CSRF list, verify limit | spec "attack probes with a session" (CSRF, cookie flags), 2FA specs |
|
||||
| 8 | XSS (rich text, links, JSON-LD, SVG uploads, `dangerouslySetInnerHTML`) | 7 core + 39 deps (dompurify, sanitize-html) | `RenderRichText` / `safeHref` drop `javascript:`, `JsonLdGraph` escapes `<`, upload CSP `sandbox`, CSP | per-class tests; rule `code-inner-html`; `config-dangerous` (`dangerouslyAllowSVG`) |
|
||||
| 9 | Middleware / proxy bypass (`x-middleware-subrequest`, path normalisation) | 7 Next (CVE-2025-29927) | the plugin makes NO access decision in the proxy (locale and CSP nonce only); matcher ends at `/` | probe `middleware-subrequest`; doctor `proxy-matcher` |
|
||||
| 10 | Injection (NoSQL operators, `$where`, SQL in raw queries, CRLF, logs) | 5 Payload + 16 deps (mongoose CVE-2024-53900, CVE-2025-23061) | no `where` from request input in plugin routes; typed values in queries. **Operator names in `sort`** reach MongoDB (audit F5); **CSP reports write raw text into the log** (audit F1) | probes `login-operators`, `sort-operator`; rule `code-raw-where`; per-class tests |
|
||||
| 11 | Supply chain (npm worms: Shai-Hulud 2025, chalk/debug 2025, Mini Shai-Hulud 2026) | 13 incidents | exact pins of the plugin's own deps, lockfile, `pnpm.overrides` advice (AGENT.md §4 item 12) | `deps-audit` (doctor), `pnpm security:gate` |
|
||||
| 12 | Open redirect | 1 Payload | `safeAdminBack`, `adminPathFromReferer`, locale redirect keeps the host | probe `open-redirect`; rule `code-open-redirect` |
|
||||
| 13 | Security headers and CSP | — (misconfiguration, A02) | `buildSecurityHeaders`, `buildCsp`, `withSecurityConfig` | probe `headers-everywhere`; doctor `security-headers`, `csp`, `config-dangerous` |
|
||||
|
||||
## Security suites
|
||||
|
||||
Four suites, each runnable by a project on its own site. The plugin repository runs all of them before a release.
|
||||
|
||||
| Suite | In a project | In the plugin repository |
|
||||
|---|---|---|
|
||||
| **Static rules** over the project's own code and config | `pnpm exec iapl-doctor --only security` (rules `code-patterns`, `config-dangerous`) | `test/securityPatterns.test.ts`: every hit in `src/`, `bin/`, `scripts/` and the reference site must be judged in `test/security-patterns.allow.json` (one reason per file and rule; a new place or a higher count fails) |
|
||||
| **Per-class tests** of the building blocks | — (the plugin's own) | `test/securityClasses.test.ts`: XSS payloads into JSON-LD, first-paint scripts, links, rich text, sitemap; open redirects; prototype pollution; log injection; body and batch caps; cache poisoning |
|
||||
| **HTTP attack probes** against a running site | live: `pnpm exec iapl-doctor --url https://<domain> --only live-probes` (changes nothing); local / staging: `.agents/skills/iapl-audit/resources/attack-probes.spec.template.ts` → `tests/attack-probes.spec.ts` | `reference/e2e/attack-probes.spec.ts` in `pnpm e2e:built`, after a webpack and a Turbopack production build, beside the closed-doors spec |
|
||||
| **Dependency audit** | the doctor's `deps-audit` (`pnpm audit --prod`, error on high / critical) | `pnpm security:gate` (also in `prepublishOnly`): `pnpm audit --prod` with no high / critical, then the two vitest suites; `--zap <url>` adds an OWASP ZAP baseline scan when the image `ghcr.io/zaproxy/zaproxy:stable` is already on the machine (offline; never pulled by the script) |
|
||||
|
||||
**Static rules** (`code-*`, one finding per rule and file, seeds / migrations / scripts / tests left out where the
|
||||
rule is about requests):
|
||||
|
||||
| Rule | Severity | Finds |
|
||||
|---|---|---|
|
||||
| `code-inner-html` | error | `dangerouslySetInnerHTML` / `innerHTML` / `insertAdjacentHTML` / `document.write` with a value no sanitizer passed; JSON in a `<script>` without `.replace(/</g, '\\u003c')` (use `JsonLdGraph`) |
|
||||
| `code-eval` | error | `eval`, `new Function`, `vm.run*`, `setTimeout("…")` |
|
||||
| `code-shell` | error (warning offline) | `exec` / `execSync` with a template string |
|
||||
| `code-public-secret` | error | a `NEXT_PUBLIC_…SECRET / PASSWORD / TOKEN / PRIVATE / DATABASE…` name; a server secret read in a `'use client'` file |
|
||||
| `code-override-access` | warning | `overrideAccess: true` in code a request reaches |
|
||||
| `code-local-api-user` | warning | `payload.find({ user })` without `overrideAccess: false` — Payload then IGNORES the user's rules |
|
||||
| `code-raw-where` | error | `where:` taken from `req.query`, a body, `searchParams` or `JSON.parse` |
|
||||
| `code-open-redirect` | warning | `redirect()` / `NextResponse.redirect()` to an address from the request (`?next=`, `?redirect=`) |
|
||||
| `code-ssrf` | warning | a server-side `fetch()` of an address from the request |
|
||||
| `config-dangerous` | error / warning | `dangerouslyAllowSVG` without `contentSecurityPolicy`, `remotePatterns` `**`, `serverActions.allowedOrigins` `*`, public source maps; `cors: '*'`, `debug: true`, GraphQL introspection or playground on in production, `maxDepth` above 20 |
|
||||
|
||||
A place that is correct on purpose: `// iapl-security-ok: <why>` on the same line or the line above. A whole file or
|
||||
folder: `iapl-doctor.json` → `"rules": { "code-override-access": { "files": ["src/lib/admin/**"], "off": true, "reason": "…" } }`.
|
||||
Verify: add `eval(x)` to a page and `pnpm exec iapl-doctor --only code-patterns` reports `code-eval` with the line.
|
||||
|
||||
**Attack probes** (`ATTACK_PROBES` in `@intecion/ipal-kit/doctor`; each answers on status codes and headers, a 500 is
|
||||
never "closed"): `secret-files`, `bundle-secrets` (with the spec: also the site's own secret values), `middleware-subrequest`,
|
||||
`open-redirect`, `host-header`, `markdown-vary`, `rsc-vary`, `login-operators`, `sort-operator`, `rest-where`, `graphql`,
|
||||
`error-leak`, `unbounded-list`, `image-optimizer`, `headers-everywhere`, `methods`, `body-size` (spec only: 8 MB
|
||||
bodies). The spec adds, with a signed-in editor: the session cookie is `HttpOnly` and `SameSite`, and from another
|
||||
origin the same cookie neither reads `/api/users/me`, writes a global, nor runs a GraphQL mutation. A probe tied to an
|
||||
open audit finding carries `finding` and is expected to fail (`test.fail`) until the fix lands. Your own probe: an
|
||||
object `{ id, class, title, live, run(ctx) }` in the template's `EXTRA`. Verify: run the doctor with `--url` against
|
||||
`pnpm start` of a fresh starter site — no `live-probes` finding except the open audit findings.
|
||||
|
||||
## Turn off, override, extend
|
||||
|
||||
@@ -1395,6 +1458,9 @@ every answer: `accessAllowed(option, answer)` (exported). The second factor is c
|
||||
`buildCsp` / `buildCspHeaders` / `buildReportingEndpoints` / `cspHeaderKey` /
|
||||
`parseCspReports` / `createCspNonce` (`CSP_NONCE_HEADER`, `DEFAULT_CSP_REPORT_GROUP`) for your own proxy
|
||||
or collector; `buildUploadSecurityHeaders({ collections })` for your own upload collections.
|
||||
- **Security suites:** `iapl-doctor --skip code-patterns,config-dangerous,live-probes`, or one rule per file / folder in
|
||||
`iapl-doctor.json`; the building blocks `ATTACK_PROBES`, `runAttackProbes`, `createProbeContext`, `scanCode`,
|
||||
`scanConfigs` (`@intecion/ipal-kit/doctor`) for your own CI.
|
||||
- **Check:** `curl -sI https://domain/pl | grep -iE "strict-transport|x-frame|referrer|permissions|cross-origin|content-security|x-powered-by"`
|
||||
(no `x-powered-by`; `content-security-policy-report-only` while rolling out);
|
||||
on staging also `x-robots-tag`; startup with a wrong `twoFactor.collectionSlug` fails with `[iapl] twoFactor…`.
|
||||
|
||||
+2
-1
@@ -134,9 +134,10 @@
|
||||
"lint:fix": "eslint ./src ./test --fix",
|
||||
"perf:measure": "node scripts/perf-measure.mjs",
|
||||
"prepare": "pnpm build",
|
||||
"prepublishOnly": "pnpm clean && pnpm build && pnpm build:starter && pnpm test:int && pnpm starter:gate",
|
||||
"prepublishOnly": "pnpm clean && pnpm build && pnpm build:starter && pnpm test:int && pnpm starter:gate && pnpm security:gate",
|
||||
"reference:index": "node scripts/reference-index.mjs",
|
||||
"routes:check": "node scripts/routes-check.mjs",
|
||||
"security:gate": "node scripts/security-gate.mjs",
|
||||
"starter:gate": "node scripts/starter-gate.mjs",
|
||||
"test": "pnpm test:int && pnpm test:e2e",
|
||||
"test:e2e": "playwright test",
|
||||
|
||||
@@ -65,6 +65,13 @@ names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` —
|
||||
`pnpm payload run tests/routes.ts` fails on a route nobody has judged). A new custom endpoint, collection or
|
||||
route file of the project = a new snapshot entry with its reason, and a door in `DOORS` if it must stay closed.
|
||||
|
||||
- **Attack probes and static security rules** (security.md "Security suites"): `resources/attack-probes.spec.template.ts`
|
||||
→ `tests/attack-probes.spec.ts`, run on a production build or staging (`BASE_URL=… PAGE=/pl pnpm exec playwright test
|
||||
tests/attack-probes.spec.ts`): the plugin's ATTACK_PROBES, plus the project's own in `EXTRA` for every custom
|
||||
endpoint. On the live site: `pnpm exec iapl-doctor --url https://<domain> --only live-probes`. The code side:
|
||||
`pnpm exec iapl-doctor --only security` (`code-patterns`, `config-dangerous`); a correct place gets
|
||||
`// iapl-security-ok: <why>`. Dependencies: `pnpm audit --prod` (the doctor's `deps-audit`) — no high or critical.
|
||||
|
||||
- **Editor test** (AGENT.md §11): every text, image, button, section,
|
||||
menu, footer and SEO field can be changed in the panel, in every language.
|
||||
- **Cookie consent:** in Network, before accepting, there are no requests to
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Attack probes from outside — the requests attackers send to Payload / Next.js sites, asked on a PRODUCTION build
|
||||
* (`pnpm build && pnpm start`) or a staging copy (IAPL docs/security.md "Security suites"). Copy to
|
||||
* tests/attack-probes.spec.ts and run:
|
||||
*
|
||||
* BASE_URL=http://localhost:3000 PAGE=/pl pnpm exec playwright test tests/attack-probes.spec.ts
|
||||
*
|
||||
* The probes come from the plugin (ATTACK_PROBES, @intecion/ipal-kit/doctor), so an IAPL upgrade brings new ones.
|
||||
* On a LIVE site use `pnpm exec iapl-doctor --url https://<domain> --only live-probes` instead: it runs only the
|
||||
* probes that change nothing (no 8 MB bodies). This spec runs all of them — local or staging only.
|
||||
* The bundle check looks for this site's own secret VALUES: they are read from the environment (.env of the local
|
||||
* build) and never printed. Add the project's own probes to EXTRA.
|
||||
*/
|
||||
import { ATTACK_PROBES, type AttackProbe, createProbeContext } from '@intecion/ipal-kit/doctor'
|
||||
import { expect, test } from '@playwright/test'
|
||||
|
||||
const BASE = (process.env.BASE_URL ?? 'http://localhost:3000').replace(/\/$/, '')
|
||||
const PAGE = process.env.PAGE ?? '/'
|
||||
const secrets = ['PAYLOAD_SECRET', 'CRON_SECRET', 'R2_SECRET_ACCESS_KEY', 'TURNSTILE_SECRET_KEY', 'IAPL_DOCTOR_TOKEN', 'IAPL_COOKIE_SCAN_TOKEN'].map((k) => process.env[k]).filter((v): v is string => !!v && v.length >= 8)
|
||||
|
||||
/** The project's own probes, e.g. a custom endpoint that must refuse an 8 MB body or an operator in its query. */
|
||||
const EXTRA: AttackProbe[] = []
|
||||
|
||||
for (const probe of [...ATTACK_PROBES, ...EXTRA]) {
|
||||
test(`${probe.class}: ${probe.title}`, async () => {
|
||||
const result = await probe.run(createProbeContext(BASE, { page: PAGE, secrets }))
|
||||
test.skip(!!result.skipped, result.skipped)
|
||||
expect(result.ok, result.detail).toBe(true)
|
||||
})
|
||||
}
|
||||
@@ -46,6 +46,16 @@ Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`.
|
||||
`--url <url>` · `--staging` (must be noindex) · `--admin-route <path>` · `--deep` · `--env-file <prod export>` (checks
|
||||
`<domain>_prod`) · `--only` / `--skip <ids,groups>` · `--sites '../*-web'` (a read-only rule × site table, exit 0).
|
||||
|
||||
**Security checks only** (security.md "Security suites"): `pnpm exec iapl-doctor --only security` — headers, CSP,
|
||||
2FA, account rules, plus the static rules over the project's own code (`code-patterns`: unescaped HTML / JSON-LD,
|
||||
`overrideAccess: true` or a Local API `user` without `overrideAccess: false` where a request reaches, a `where` from
|
||||
the request, `eval`, `NEXT_PUBLIC_` secrets, redirects and fetches to an address from the request) and its configs
|
||||
(`config-dangerous`). With `--url https://<domain>` also `live-probes`: the plugin's attack probes that change
|
||||
nothing, run against the real site (secret files, bundle secrets, proxy bypass, open redirects, cache poisoning,
|
||||
NoSQL operators, anonymous where / draft / GraphQL reads, error leaks, unbounded lists, `/_next/image`). Verify: on a
|
||||
fresh starter site the run lists no `code-*` finding; add `eval(x)` to a page and `code-eval` appears. A correct
|
||||
place is marked `// iapl-security-ok: <why>`.
|
||||
|
||||
Exit `0` ok · `1` findings at or above `--fail-on` · `2` could not run · `3` a rule crashed.
|
||||
|
||||
## CI of a new site (starter, reference site)
|
||||
|
||||
@@ -896,11 +896,13 @@ Bin: `iapl-doctor` (`pnpm exec iapl-doctor [dir] [--json] [--md] [--strict] [--f
|
||||
| `withJobsRunAccess(config, options \| false)` / `jobsRunNotice(config)` | `@intecion/ipal-kit` | The config with that rule (only when `jobs.access.run` is missing; marks `custom.iapl.jobsRunDefault`); the start-up line when the queue is on and the secret is missing (null otherwise). |
|
||||
| `cronSecretMatches(req, secret)`, `CRON_SECRET_ENV`, `CRON_SECRET_MIN_LENGTH` | `@intecion/ipal-kit` | `Authorization: Bearer <secret>` compared in constant time; an unset or shorter-than-16 secret never matches. Default variable `CRON_SECRET`. |
|
||||
| `runRouteCheck({ config, appDir?, snapshot?, update?, graphql?, cwd?, log? })` | `@intecion/ipal-kit/doctor` | `routes:check`: every public route (REST, GraphQL, Next route files) against the judged snapshot (default `e2e/routes.snapshot.json`); returns 1 on a route nobody judged or an entry without a reason; `update` writes new routes with an empty reason. Template: `iapl-audit/resources/routes.template.ts` (security.md "Routes nobody has judged"). Type `RunRouteCheckOptions`. |
|
||||
| `ATTACK_PROBES`, `runAttackProbes(ctx, probes?)`, `createProbeContext(base, { page?, secrets?, timeoutMs?, userAgent? })` | `@intecion/ipal-kit/doctor` | The HTTP attack probes (secret files, bundle secrets, proxy bypass, open redirect, host-header and negotiation cache poisoning, NoSQL operators in sign-in and sort, anonymous where / draft / GraphQL reads, error leaks, unbounded lists, `/_next/image`, headers, methods, 8 MB bodies). Each `{ id, class, title, live, finding?, run(ctx) → { ok, detail, skipped? } }`; `runAttackProbes` runs the `live` ones by default. The doctor's `live-probes` rule; the Playwright template `iapl-audit/resources/attack-probes.spec.template.ts`; your own probe = an object of the same shape (security.md "Security suites"). Types `AttackProbe`, `ProbeContext`, `ProbeAnswer`, `ProbeResult`. |
|
||||
| `scanCode(path, code)`, `listCodeFiles(root, start)`, `codeFindings(ctx)`, `scanConfigs(next, payload)`, `securityCodeRules`, `SECURITY_OK_MARKER`, `LIVE_PROBE_IDS` | `@intecion/ipal-kit/doctor` | The static security rules behind `code-patterns` and `config-dangerous`: every hit `{ rule, file, line, severity, message, text }` (types `CodeHit`, `CodePatternId`). A correct place is marked `// iapl-security-ok: <why>`. Use `scanCode` in a test of your own to keep a judged allow-list, as the plugin does (`test/security-patterns.allow.json`). |
|
||||
| `listPublicRoutes(config, { graphqlSchema?, routeFiles? })` | `@intecion/ipal-kit` | Stable ids of every door a built config opens: `GET /api/users/me`, `graphql mutation loginUser`, `next GET /sitemap.xml`. From the config only (same on every database). Types `RouteInventoryOptions`, `GraphqlSchemaLike` (`getQueryType` / `getMutationType`). |
|
||||
| `listNextRouteFiles(files, read)` | `@intecion/ipal-kit` | Next route handlers of an app directory (`route.ts` with the methods it exports, `robots.ts`, `sitemap.ts`, `manifest.ts`; route groups left out). |
|
||||
| `compareRouteSnapshot(current, snapshot)` / `updateRouteSnapshot(current, snapshot)` | `@intecion/ipal-kit` | `{ unjudged, unexplained, gone }` against a `RouteSnapshot` (route id → reason); the snapshot after `--update` (new routes with `''`, gone ones dropped). Type `RouteSnapshotDiff`. |
|
||||
|
||||
**Types:** `DoctorRule`, `DoctorFinding`, `RuleFinding`, `DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`,
|
||||
**Types:** `AttackProbe`, `ProbeContext`, `ProbeAnswer`, `ProbeResult`, `CodeHit`, `CodePatternId`, `DoctorRule`, `DoctorFinding`, `RuleFinding`, `DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`,
|
||||
`DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`, `FrontendLayout`.
|
||||
|
||||
## Turnstile (`turnstile`) — details: `node_modules/@intecion/ipal-kit/docs/turnstile.md`
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { ATTACK_PROBES, createProbeContext } from '@intecion/ipal-kit/doctor'
|
||||
import { expect, test } from '@playwright/test'
|
||||
|
||||
import { editorTestAccount, totp } from './totp'
|
||||
|
||||
/**
|
||||
* Attack probes on the BUILT site (security audit 2026-12; docs/security.md → "Security suites"): every probe of
|
||||
* the plugin's ATTACK_PROBES, the live-safe ones and those only for a local build (8 MB bodies), then what needs a
|
||||
* signed-in session: CSRF on the API and the session cookie's flags. `pnpm e2e:built` runs it after a webpack and a
|
||||
* Turbopack build. A probe tied to an open audit finding is expected to fail (test.fail) until the fix lands.
|
||||
*
|
||||
* The secrets the bundle check looks for are this site's own values from reference/.env.
|
||||
*/
|
||||
const env = process.env
|
||||
const dbPassword = (() => {
|
||||
try {
|
||||
return decodeURIComponent(new URL(env.DATABASE_URI ?? '').password)
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
})()
|
||||
const secrets = [env.PAYLOAD_SECRET, env.CRON_SECRET, env.IAPL_COOKIE_SCAN_TOKEN, env.IAPL_DOCTOR_TOKEN, env.R2_SECRET_ACCESS_KEY, env.E2E_ADMIN_PASSWORD, env.E2E_TOTP_SECRET, dbPassword].filter((s): s is string => !!s && s.length >= 8)
|
||||
|
||||
test.describe('attack probes', () => {
|
||||
for (const probe of ATTACK_PROBES) {
|
||||
test(`${probe.class}: ${probe.title}`, async ({ baseURL }) => {
|
||||
if (probe.finding) {test.fail(true, `audit finding ${probe.finding} is open (security-audit-2026-12-findings.md)`)}
|
||||
const { result } = { result: await probe.run(createProbeContext(baseURL!, { page: '/pl', secrets })) }
|
||||
test.skip(!!result.skipped, result.skipped)
|
||||
expect(result.ok, result.detail).toBe(true)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test.describe('attack probes with a session', () => {
|
||||
test('CSRF: the editor\'s cookie does not work from another origin (REST write, GraphQL mutation)', async ({ baseURL, playwright }) => {
|
||||
const { E2E_ADMIN_EMAIL: adminEmail, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: secret } = env
|
||||
test.skip(!adminEmail || !password || !secret, 'E2E_* test admin not configured')
|
||||
const api = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } })
|
||||
expect((await api.post('/api/users/login', { data: { email: editorTestAccount(adminEmail!), password } })).status()).toBe(200)
|
||||
expect((await (await api.post('/api/verify-totp', { data: { token: totp(secret!) } })).json()).ok).toBe(true)
|
||||
// the same session, same origin: the write is allowed (proves the cookie works), with a body that changes nothing
|
||||
const own = await api.get('/api/users/me')
|
||||
expect(((await own.json()) as { user?: unknown }).user).toBeTruthy()
|
||||
const foreign = { origin: 'https://evil.example', referer: 'https://evil.example/', 'sec-fetch-site': 'cross-site' }
|
||||
const me = await api.get('/api/users/me', { headers: foreign })
|
||||
expect([me.status(), ((await me.json()) as { user?: unknown }).user ?? null], 'a cross-site request must not be signed in').toEqual([200, null])
|
||||
const write = await api.post('/api/globals/header', { data: {}, headers: foreign })
|
||||
expect([401, 403]).toContain(write.status())
|
||||
const gql = await api.post('/api/graphql', { data: { query: 'mutation { updateHeader(data: {}) { id } }' }, headers: foreign })
|
||||
expect(gql.status()).toBeLessThan(500)
|
||||
expect(await gql.text()).not.toMatch(/"updateHeader"\s*:\s*\{/)
|
||||
await api.dispose()
|
||||
})
|
||||
|
||||
test('session cookie: HttpOnly and SameSite, never readable by script', async ({ baseURL, playwright }) => {
|
||||
const { E2E_ADMIN_EMAIL: adminEmail, E2E_ADMIN_PASSWORD: password } = env
|
||||
test.skip(!adminEmail || !password, 'E2E_* test admin not configured')
|
||||
const api = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } })
|
||||
const res = await api.post('/api/users/login', { data: { email: editorTestAccount(adminEmail!), password } })
|
||||
expect(res.status()).toBe(200)
|
||||
const cookie = res.headersArray().filter((h) => h.name.toLowerCase() === 'set-cookie').map((h) => h.value).find((v) => /-token=/.test(v))
|
||||
expect(cookie, 'the login sets the session cookie').toBeTruthy()
|
||||
expect(cookie).toMatch(/;\s*HttpOnly/i)
|
||||
expect(cookie).toMatch(/;\s*SameSite=(?:Lax|Strict)/i)
|
||||
await api.dispose()
|
||||
})
|
||||
})
|
||||
@@ -19,7 +19,10 @@
|
||||
* staff sign-in from another origin refused);
|
||||
* e2e/sign-in-answers.spec.ts (1.17.2: a locked staff account answers like a wrong password; the panel actions refuse
|
||||
* another origin), e2e/two-factor-enrolment.spec.ts (1.18.0: the first 2FA set-up waits for the e-mailed link,
|
||||
* read from the mail sink; the password alone no longer enrols a factor).
|
||||
* read from the mail sink; the password alone no longer enrols a factor), e2e/attack-probes.spec.ts (security audit
|
||||
* 2026-12: the plugin's ATTACK_PROBES — secret files, bundle secrets, proxy bypass, open redirect, host-header and
|
||||
* negotiation cache poisoning, NoSQL operators, where/draft/GraphQL access, error leaks, unbounded lists, the image
|
||||
* optimizer, headers, methods, 8 MB bodies — plus CSRF and the session cookie's flags).
|
||||
* 4. e2e/performance.spec.ts (1.18.0): the performance budgets — LCP, CLS, Total Blocking Time, the response to a tap,
|
||||
* JS / CSS / font bytes, requests, render-blocking resources and third parties before consent for every page type,
|
||||
* on a throttled phone and a desktop, and the MongoDB queries of one render (docs/performance.md).
|
||||
@@ -100,7 +103,7 @@ for (const bundler of bundlers) {
|
||||
process.exit(1)
|
||||
}
|
||||
console.log(`[e2e:built] ✓ ${bundler}: no package manifest among ${files.length} public files`)
|
||||
run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent, the sign-in look, the sign-in answers, the own account and the unused-files notice`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', 'sign-in-answers', 'own-account', 'two-factor-enrolment', 'unused-media', '--grep', 'unused-files notice|2FA enrolment|late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look|locked staff account|panel actions|own account|staff sign-in'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', CRON_SECRET: cronSecret, E2E_LATE_STAFF: '1' })
|
||||
run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the attack probes, the published-files check, the client hints, consent, the sign-in look, the sign-in answers, the own account and the unused-files notice`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'attack-probes', 'smoke', 'sign-in-look', 'sign-in-answers', 'own-account', 'two-factor-enrolment', 'unused-media', '--grep', 'unused-files notice|2FA enrolment|late staff collection|the mail service|closed doors|attack probes|no package.json is published|client hints|consent|sign-in look|locked staff account|panel actions|own account|staff sign-in'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', CRON_SECRET: cronSecret, E2E_LATE_STAFF: '1' })
|
||||
// the budgets are the built site's own numbers: they hold for each bundler (docs/performance.md, docs/dev/perf/)
|
||||
run(`${bundler}: performance budgets — every page type on a phone and a desktop, queries per render`, 'pnpm', ['exec', 'playwright', 'test', 'e2e/performance.spec'] /* a regex on the file path: a checkout path may hold "performance" */, site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' })
|
||||
passed.push(bundler)
|
||||
|
||||
@@ -63,6 +63,7 @@ export const DESCRIPTIONS = {
|
||||
'e2e/late-staff-fixture.ts': 'test fixture, on only with E2E_LATE_STAFF=1: one plugin before iapl (staff collections of the config: roles with one more value, the plugin\'s roles, roles of the project\'s own) and one after it (a staff collection without rules, one whose roles field is text, copies of staff collections under new slugs — plain, with rules of their own, one rule used for another operation, other role values, the opt-out, not staff — and a visitor collection with open sign-up)',
|
||||
'e2e/enrolment.ts': 'reads the two-step verification confirmation link (twoFactor.confirmByEmail, 1.18.0) from the mail sink: quoted-printable undone, the latest message to an address, waited for',
|
||||
'e2e/two-factor-enrolment.spec.ts': 'the first 2FA set-up confirmed by e-mail on the built site (run by `pnpm e2e:built` in both bundlers): the password alone no longer enrols an attacker\'s factor (the link goes to the owner and is refused in another browser), and the panel flow — code, notice, link from the mail sink, sign in again',
|
||||
'e2e/attack-probes.spec.ts': 'attack probes on the built site (run by `pnpm e2e:built` in both bundlers): every probe of the plugin\'s ATTACK_PROBES (security.md "Security suites") with this site\'s secret values for the bundle check, plus CSRF with the editor\'s cookie from another origin and the session cookie\'s flags; probes tied to an open audit finding are expected to fail (`test.fail`)',
|
||||
'e2e/closed-doors.spec.ts': 'closed doors from outside (run by `pnpm e2e:built` in both bundlers): every door of e2e/closed-doors.ts asked on the production build as an anonymous visitor, a customer (the fixture\'s `e2e-visitors`) and an editor; doors still open while the owner decides are asserted open (`test.fail`)',
|
||||
'e2e/closed-doors.ts': 'the doors that must stay closed, who each is closed for and how a closed answer looks; a project adds its own (security.md "Closed doors from outside")',
|
||||
'e2e/late-staff.spec.ts': 'the account rules on a BUILT site (run by `pnpm e2e:built` after a webpack and a Turbopack build): a staff collection a later plugin adds, staff collections whose accounts can hold `admin`, and copies of staff collections — a visitor account gets nothing, nobody raises its own role or makes an admin, a copy is never wider than the plugin\'s rule',
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* pnpm security:gate — the security suites that need no built site (docs/security.md → "Security suites"):
|
||||
* 1. dependency audit: `pnpm audit --prod` must show no high or critical advisory (the plugin's own production
|
||||
* dependency tree; dev tooling is reported, not failed);
|
||||
* 2. static rules over the plugin, its scripts and the reference site, every hit judged in
|
||||
* test/security-patterns.allow.json (test/securityPatterns.test.ts), and the per-class tests
|
||||
* (test/securityClasses.test.ts);
|
||||
* 3. optional, `--zap <url>`: an OWASP ZAP baseline scan (passive, spiders 1 minute) of a running site, ONLY when
|
||||
* the image `ghcr.io/zaproxy/zaproxy:stable` is already on this machine — the scan runs offline (`-I` keeps
|
||||
* warnings from failing; failures fail). Pull the image once yourself: `docker pull ghcr.io/zaproxy/zaproxy:stable`.
|
||||
* The built-site part (attack probes, closed doors) is `pnpm e2e:built`.
|
||||
* Options: --offline (skip the audit, it needs the registry), --zap <url>.
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const args = process.argv.slice(2)
|
||||
const zapAt = args.indexOf('--zap')
|
||||
const zapUrl = zapAt >= 0 ? args[zapAt + 1] : null
|
||||
const results = []
|
||||
|
||||
const step = (label, command, commandArgs, { allowFail = false } = {}) => {
|
||||
console.log(`\n[security:gate] ${label}`)
|
||||
const r = spawnSync(command, commandArgs, { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
|
||||
results.push({ label, ok: r.status === 0 || allowFail })
|
||||
return r
|
||||
}
|
||||
|
||||
if (!args.includes('--offline')) {
|
||||
const audit = step('dependency audit (pnpm audit --prod)', 'pnpm', ['audit', '--prod', '--json', '--ignore-workspace'], { allowFail: true })
|
||||
let v = null
|
||||
try {
|
||||
v = JSON.parse(audit.stdout).metadata?.vulnerabilities ?? null
|
||||
} catch {
|
||||
// no JSON: the registry did not answer
|
||||
}
|
||||
if (!v) {
|
||||
console.error(` pnpm audit gave no result: ${(audit.stderr || audit.stdout).trim().split('\n')[0]}`)
|
||||
results.at(-1).ok = false
|
||||
} else {
|
||||
console.log(` production tree: ${v.critical ?? 0} critical, ${v.high ?? 0} high, ${v.moderate ?? 0} moderate, ${v.low ?? 0} low`)
|
||||
results.at(-1).ok = !(v.critical || v.high)
|
||||
const dev = spawnSync('pnpm', ['audit', '--json', '--ignore-workspace'], { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
|
||||
try {
|
||||
const d = JSON.parse(dev.stdout).metadata?.vulnerabilities
|
||||
console.log(` with dev tooling (reported, not failed): ${d.critical ?? 0} critical, ${d.high ?? 0} high, ${d.moderate ?? 0} moderate, ${d.low ?? 0} low`)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const tests = step('static rules + per-class tests (vitest)', 'pnpm', ['exec', 'vitest', 'run', 'test/securityPatterns.test.ts', 'test/securityClasses.test.ts'])
|
||||
process.stdout.write(tests.stdout.split('\n').filter((l) => /Tests |✓|×|FAIL|NOT JUDGED|MORE THAN/.test(l)).join('\n') + '\n')
|
||||
if (tests.status !== 0) {process.stdout.write(tests.stdout.slice(-4000))}
|
||||
|
||||
if (zapUrl) {
|
||||
const image = 'ghcr.io/zaproxy/zaproxy:stable'
|
||||
const has = spawnSync('docker', ['image', 'inspect', image], { encoding: 'utf8' })
|
||||
if (has.status !== 0) {
|
||||
console.log(`\n[security:gate] ZAP baseline skipped: ${image} is not on this machine (docker pull it once)`)
|
||||
} else {
|
||||
const target = zapUrl.replace('localhost', 'host.docker.internal').replace('127.0.0.1', 'host.docker.internal')
|
||||
const zap = step(`OWASP ZAP baseline of ${zapUrl}`, 'docker', ['run', '--rm', '--add-host=host.docker.internal:host-gateway', image, 'zap-baseline.py', '-t', target, '-m', '1', '-I', '--autooff'])
|
||||
process.stdout.write(zap.stdout.split('\n').filter((l) => /^(?:FAIL|WARN|PASS):|FAIL-NEW|WARN-NEW/.test(l)).slice(0, 80).join('\n') + '\n')
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n[security:gate] ' + results.map((r) => `${r.ok ? '✓' : '✗'} ${r.label}`).join('\n[security:gate] '))
|
||||
process.exit(results.every((r) => r.ok) ? 0 : 1)
|
||||
@@ -18,6 +18,8 @@ export { DEFAULT_SRC_ALLOW, findFrontend } from '../modules/doctor/rules/layout.
|
||||
export type { FrontendLayout } from '../modules/doctor/rules/layout.js'
|
||||
export { createLiveFetcher } from '../modules/doctor/rules/live.js'
|
||||
export { performanceRules } from '../modules/doctor/rules/performance.js'
|
||||
export { codeFindings, listCodeFiles, LIVE_PROBE_IDS, scanCode, scanConfigs, SECURITY_OK_MARKER, securityCodeRules } from '../modules/doctor/rules/securityCode.js'
|
||||
export type { CodeHit, CodePatternId } from '../modules/doctor/rules/securityCode.js'
|
||||
export { AUDIT_RULE_MAP, parseToolOutput } from '../modules/doctor/rules/tooling.js'
|
||||
export { applySettings, AUDIT_SKIP_RULES, doctorRules, globToRegExp, runDeepProbe, runDoctor } from '../modules/doctor/run.js'
|
||||
export type { RunDoctorOptions } from '../modules/doctor/run.js'
|
||||
@@ -38,6 +40,9 @@ export type { GrowthThresholds } from '../modules/doctor/types.js'
|
||||
// Performance budgets (docs/performance.md): the defaults, a project's own on top, and the check the gate runs
|
||||
export { IMAGE_RULES, overBudget, PERF_BUDGETS, perfBudgets, SERVER_BUDGET } from '../modules/performance/budgets.js'
|
||||
export type { PerfBudget, PerfMeasurement, PerfProfile, ServerBudget } from '../modules/performance/budgets.js'
|
||||
// HTTP attack probes (docs/security.md "Security suites")
|
||||
export { ATTACK_PROBES, createProbeContext, runAttackProbes } from '../modules/security/attackProbes.js'
|
||||
export type { AttackProbe, ProbeAnswer, ProbeContext, ProbeResult } from '../modules/security/attackProbes.js'
|
||||
// routes:check — the site's public routes against the judged snapshot (docs/security.md "Routes nobody has judged")
|
||||
export { runRouteCheck } from '../modules/security/routeCheck.js'
|
||||
export type { RunRouteCheckOptions } from '../modules/security/routeCheck.js'
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
import { readdirSync, statSync } from 'node:fs'
|
||||
import { join, relative } from 'node:path'
|
||||
|
||||
import type { DoctorContext } from '../project.js'
|
||||
import type { DoctorRule, DoctorSeverity, RuleFinding } from '../types.js'
|
||||
|
||||
import { ATTACK_PROBES, createProbeContext, runAttackProbes } from '../../security/attackProbes.js'
|
||||
import { configFile, nextConfigFile } from '../project.js'
|
||||
import { stripComments } from '../util.js'
|
||||
|
||||
/**
|
||||
* Static security rules over the project's own code (security.md → "Security suites"). Each pattern is a class that
|
||||
* hits Payload / Next.js sites again and again: HTML or JSON printed into the page without escaping, the Local API
|
||||
* run with access switched off where a visitor reaches it, a query built from what the request sent, code built from
|
||||
* strings, secrets in the browser bundle, redirects and server-side fetches to an address the request chose.
|
||||
*
|
||||
* Patterns, not proof: a finding is a place to look. A place that is right on purpose carries a comment on the same
|
||||
* line or the line above — `// iapl-security-ok: <why>` — and the finding goes; a whole file or rule is silenced in
|
||||
* iapl-doctor.json (`rules: { "code-override-access": { files: ["src/lib/admin/**"], off: true, reason: "…" } }`).
|
||||
*/
|
||||
|
||||
/** The marker that accepts one place, with its reason: `// iapl-security-ok: the value is a number`. */
|
||||
export const SECURITY_OK_MARKER = 'iapl-security-ok'
|
||||
|
||||
const CODE_EXT = /\.[cm]?[jt]sx?$/
|
||||
/** Never scanned: generated, built or vendored code, and the project's tests. */
|
||||
const SKIP_DIR = new Set(['.agents', '.git', '.next', '.turbo', 'build', 'coverage', 'dist', 'node_modules', 'out'])
|
||||
const SKIP_FILE = /(?:^|\/)(?:payload-types\.ts|importMap\.js|next-env\.d\.ts)$|\.(?:test|spec)\.[cm]?[jt]sx?$|\.d\.ts$/
|
||||
/** Code no visitor reaches: seeds, migrations, scripts, tests. Rules about request input and access skip it. */
|
||||
const OFFLINE_PATH = /(?:^|\/)(?:seed|seeds|migrations|scripts|e2e|tests?|__tests__|fixtures)(?:\/|$)/
|
||||
|
||||
export type CodePatternId =
|
||||
| 'code-eval'
|
||||
| 'code-inner-html'
|
||||
| 'code-local-api-user'
|
||||
| 'code-open-redirect'
|
||||
| 'code-override-access'
|
||||
| 'code-public-secret'
|
||||
| 'code-raw-where'
|
||||
| 'code-shell'
|
||||
| 'code-ssrf'
|
||||
|
||||
export type CodeHit = { file: string; line: number; message: string; rule: CodePatternId; severity: DoctorSeverity; text: string }
|
||||
|
||||
/** Files to scan, relative to the project root: `src/` (or the root's app, lib, components… when there is none). */
|
||||
export function listCodeFiles(root: string, start: string): string[] {
|
||||
const out: string[] = []
|
||||
const walk = (dir: string) => {
|
||||
let names: string[]
|
||||
try {
|
||||
names = readdirSync(dir)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
for (const name of names) {
|
||||
if (SKIP_DIR.has(name)) {continue}
|
||||
const full = join(dir, name)
|
||||
let isDir = false
|
||||
try {
|
||||
isDir = statSync(full).isDirectory()
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
const rel = relative(root, full).split('\\').join('/')
|
||||
if (isDir) {walk(full)} else if (CODE_EXT.test(name) && !SKIP_FILE.test(rel)) {out.push(rel)}
|
||||
}
|
||||
}
|
||||
walk(join(root, start))
|
||||
return out.sort()
|
||||
}
|
||||
|
||||
/** The text of the `{ … }` (or `( … )`) that opens at `open`, up to `max` characters. */
|
||||
function balanced(code: string, open: number, max = 1500): string {
|
||||
const pairs: Record<string, string> = { '(': ')', '[': ']', '{': '}' }
|
||||
const stack: string[] = []
|
||||
let quote: null | string = null
|
||||
for (let i = open; i < code.length && i < open + max; i++) {
|
||||
const c = code[i]
|
||||
if (quote) {
|
||||
if (c === '\\') {i++; continue}
|
||||
if (c === quote) {quote = null}
|
||||
continue
|
||||
}
|
||||
if (c === '"' || c === "'" || c === '`') {quote = c; continue}
|
||||
if (pairs[c]) {stack.push(pairs[c])} else if (c === stack.at(-1)) {
|
||||
stack.pop()
|
||||
if (!stack.length) {return code.slice(open, i + 1)}
|
||||
}
|
||||
}
|
||||
return code.slice(open, open + max)
|
||||
}
|
||||
|
||||
const lineOf = (code: string, index: number) => code.slice(0, index).split('\n').length
|
||||
|
||||
/** True when the line, or the line above, carries `iapl-security-ok`. Read from the raw text (comments kept). */
|
||||
function accepted(raw: string[], line: number): boolean {
|
||||
return [raw[line - 1], raw[line - 2]].some((l) => l?.includes(SECURITY_OK_MARKER))
|
||||
}
|
||||
|
||||
/** What a request handed in: query, body, params, headers, search params. */
|
||||
const REQUEST_INPUT = String.raw`(?:req|request)\s*\.\s*(?:query|body|data|params|headers|json\s*\(|formData\s*\(|text\s*\()|searchParams\b|\bparams\s*\.|\bbody\s*\.|\bformData\s*\.\s*get\s*\(|nextUrl\s*\.\s*searchParams|routeParams\b`
|
||||
const FROM_REQUEST = new RegExp(REQUEST_INPUT)
|
||||
|
||||
/** __html values the plugin and common sanitizers make safe. */
|
||||
const SAFE_HTML = /\.replace\(\s*\/<\/g|sanitize|DOMPurify|xss\(|consentBannerScript|consentDecidedScript|themeScript|cookieButtonSpaceScript|jsonLdScript|serializeJsonLd|escapeHtml|escapeJson/
|
||||
|
||||
/** Secrets whose name says so; the public keys of browser tools are not secrets. */
|
||||
const SECRET_NAME = /NEXT_PUBLIC_[A-Z0-9_]*(?:SECRET|PASSWORD|PASSWD|PRIVATE|_TOKEN|DATABASE|DB_URI|MONGO|POSTGRES|SMTP_PASS|API_KEY_SECRET)[A-Z0-9_]*/g
|
||||
const SERVER_ONLY_ENV = /process\.env\.(?:PAYLOAD_SECRET|DATABASE_URI|DATABASE_URL|POSTGRES_URL|MONGODB_URI|R2_SECRET_ACCESS_KEY|R2_ACCESS_KEY_ID|TURNSTILE_SECRET_KEY|CRON_SECRET|IAPL_DOCTOR_TOKEN|IAPL_COOKIE_SCAN_TOKEN|SMTP_PASS(?:WORD)?|GRAPH_CLIENT_SECRET|RESEND_API_KEY)\b/g
|
||||
|
||||
/**
|
||||
* Every pattern hit in one file's code. `path` decides whether the file is reachable from the web (seeds, migrations,
|
||||
* scripts and tests are not). Exported for a project's own test or another scanner.
|
||||
*/
|
||||
export function scanCode(path: string, rawCode: string): CodeHit[] {
|
||||
const raw = rawCode.split('\n')
|
||||
// comments out, line count kept (block comments keep their newlines)
|
||||
const code = rawCode.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/(^|[^:'"`\\])\/\/.*$/gm, '$1')
|
||||
const web = !OFFLINE_PATH.test(path)
|
||||
const client = /^\s*['"]use client['"]/m.test(code)
|
||||
const hits: CodeHit[] = []
|
||||
const add = (rule: CodePatternId, index: number, severity: DoctorSeverity, message: string) => {
|
||||
const line = lineOf(code, index)
|
||||
if (accepted(raw, line)) {return}
|
||||
hits.push({ file: path, line, message, rule, severity, text: (raw[line - 1] ?? '').trim().slice(0, 160) })
|
||||
}
|
||||
|
||||
// 1. HTML into the page: dangerouslySetInnerHTML / innerHTML with a value nothing escaped
|
||||
for (const m of code.matchAll(/dangerouslySetInnerHTML\s*=\s*\{/g)) {
|
||||
const value = balanced(code, m.index + m[0].length - 1, 800)
|
||||
if (SAFE_HTML.test(value)) {continue}
|
||||
const json = /JSON\.stringify/.test(value)
|
||||
add('code-inner-html', m.index, 'error', json
|
||||
? 'JSON printed into a <script> without escaping "<": a value with </script> ends the script (JsonLdGraph, or .replace(/</g, "\\\\u003c"))'
|
||||
: 'dangerouslySetInnerHTML with a value that no sanitizer passed (RenderRichText, or a sanitizer such as DOMPurify)')
|
||||
}
|
||||
for (const m of code.matchAll(/\.(?:innerHTML|outerHTML)\s*=(?!=)|\.insertAdjacentHTML\s*\(|document\.write(?:ln)?\s*\(/g)) {
|
||||
const rest = code.slice(m.index, m.index + 300).split('\n')[0]
|
||||
if (SAFE_HTML.test(rest) || /=\s*(?:''|""|``)\s*;?$/.test(rest)) {continue}
|
||||
add('code-inner-html', m.index, 'error', 'HTML written into the DOM from a string (innerHTML / insertAdjacentHTML / document.write)')
|
||||
}
|
||||
|
||||
// 2. code built from strings
|
||||
for (const m of code.matchAll(/(?<![\w.])eval\s*\(|new\s+Function\s*\(|\bvm\s*\.\s*(?:runInNewContext|runInThisContext|runInContext|compileFunction)\s*\(|\bset(?:Timeout|Interval)\s*\(\s*['"`]/g)) {
|
||||
add('code-eval', m.index, 'error', 'code built from a string (eval / new Function / vm / setTimeout with a string)')
|
||||
}
|
||||
for (const m of code.matchAll(/\b(?:exec|execSync)\s*\(\s*`[^`]*\$\{/g)) {
|
||||
add('code-shell', m.index, web ? 'error' : 'warning', 'a shell command built from a template string: pass arguments with execFile / spawn instead')
|
||||
}
|
||||
|
||||
// 3. secrets that reach the browser
|
||||
for (const m of code.matchAll(SECRET_NAME)) {
|
||||
add('code-public-secret', m.index, 'error', `${m[0]}: a NEXT_PUBLIC_ variable is copied into the browser bundle; a secret must never have that prefix`)
|
||||
}
|
||||
if (client) {
|
||||
for (const m of code.matchAll(SERVER_ONLY_ENV)) {
|
||||
add('code-public-secret', m.index, 'error', `${m[0]} read in a 'use client' file: rendered on the server, the value can end up in the HTML`)
|
||||
}
|
||||
}
|
||||
|
||||
if (!web) {return hits}
|
||||
|
||||
// 4. the Local API with access off where a visitor reaches it
|
||||
for (const m of code.matchAll(/overrideAccess\s*:\s*true\b/g)) {
|
||||
add('code-override-access', m.index, 'warning', 'overrideAccess: true in code a request reaches: every access rule is skipped; pass the user and overrideAccess: false, or say why with iapl-security-ok')
|
||||
}
|
||||
for (const m of code.matchAll(/\bpayload\s*\.\s*(?:find|findByID|findGlobal|count|create|update|updateGlobal|delete|duplicate|findVersions|findVersionByID|findGlobalVersions)\s*\(\s*\{/g)) {
|
||||
const args = balanced(code, m.index + m[0].length - 1)
|
||||
if (/\buser\s*[:,}]/.test(args) && !/overrideAccess\s*:/.test(args)) {
|
||||
add('code-local-api-user', m.index, 'warning', "the Local API gets a user but no overrideAccess: false — Payload then IGNORES the user's rules (overrideAccess defaults to true)")
|
||||
}
|
||||
}
|
||||
|
||||
// 5. a query built from what the request sent (operators, other fields, other people's records)
|
||||
for (const m of code.matchAll(/\bwhere\s*:\s*/g)) {
|
||||
const start = m.index + m[0].length
|
||||
const value = code[start] === '{' ? balanced(code, start, 600) : code.slice(start, start + 200).split(/[,\n})]/)[0]
|
||||
const direct = code[start] !== '{'
|
||||
if ((direct && (FROM_REQUEST.test(value) || /^(?:JSON\.parse|qs\.parse|parse)\s*\(/.test(value))) || (!direct && /:\s*(?:req|request)\s*\.\s*(?:query|body)\s*(?:[,}\n]|\.where)/.test(value))) {
|
||||
add('code-raw-where', m.index, 'error', 'a where clause taken from the request: the visitor picks operators and fields ($ne, exists, other users\' records). Build it from checked values')
|
||||
}
|
||||
}
|
||||
|
||||
// 6. redirects and server-side fetches to an address the request chose
|
||||
for (const m of code.matchAll(/\b(?:redirect|permanentRedirect|NextResponse\s*\.\s*redirect|Response\s*\.\s*redirect)\s*\(/g)) {
|
||||
const args = balanced(code, m.index + m[0].length - 1, 300)
|
||||
if (FROM_REQUEST.test(args) || /\.get\(\s*['"](?:next|redirect|redirectTo|returnTo|return|back|url|to|callbackUrl)['"]\s*\)/.test(args)) {
|
||||
if (/safeAdminBack|safeRedirect|isSafe|startsWith\(\s*['"]\/['"]\s*\)/.test(args)) {continue}
|
||||
add('code-open-redirect', m.index, 'warning', 'a redirect to an address from the request: accept a path of this site only (one leading "/", not "//" or "/\\\\")')
|
||||
}
|
||||
}
|
||||
for (const m of code.matchAll(/\bfetch\s*\(/g)) {
|
||||
const args = balanced(code, m.index + m[0].length - 1, 300)
|
||||
const target = args.slice(1).split(/,(?![^(]*\))/)[0] ?? ''
|
||||
if (FROM_REQUEST.test(target) || /\b(?:body|data|input|args)\s*\.\s*(?:url|href|endpoint|webhook|callback)\b/.test(target)) {
|
||||
add('code-ssrf', m.index, 'warning', 'a server-side fetch of an address the request chose (SSRF): allow a fixed list of hosts, refuse private addresses')
|
||||
}
|
||||
}
|
||||
return hits
|
||||
}
|
||||
|
||||
/** next.config / payload.config settings that open a known door. */
|
||||
export function scanConfigs(next: { code: string; file: string } | null, payload: { code: string; file: string } | null): RuleFinding[] {
|
||||
const out: RuleFinding[] = []
|
||||
if (next) {
|
||||
const c = stripComments(next.code)
|
||||
if (/dangerouslyAllowSVG\s*:\s*true/.test(c) && !/contentSecurityPolicy\s*:/.test(c)) {
|
||||
out.push({ file: next.file, fix: "images.contentSecurityPolicy: \"default-src 'self'; script-src 'none'; sandbox;\" and contentDispositionType: 'attachment'", message: 'images.dangerouslyAllowSVG without images.contentSecurityPolicy: an uploaded SVG runs script on the site\'s domain through /_next/image', severity: 'error' })
|
||||
}
|
||||
if (/hostname\s*:\s*['"]\*\*?['"]/.test(c)) {
|
||||
out.push({ file: next.file, fix: 'list the media hosts (buildImagesConfig)', message: 'images.remotePatterns allows every host: /_next/image fetches and resizes any image on the internet for anyone (cost, SSRF to inner addresses on old Next)', severity: 'warning' })
|
||||
}
|
||||
if (/allowedOrigins\s*:\s*\[[^\]]*['"]\*['"]/.test(c)) {
|
||||
out.push({ file: next.file, fix: 'name the origins', message: 'serverActions.allowedOrigins contains "*": Server Actions accept posts from any site (CSRF)', severity: 'error' })
|
||||
}
|
||||
if (/productionBrowserSourceMaps\s*:\s*true/.test(c)) {
|
||||
out.push({ file: next.file, fix: 'productionBrowserSourceMaps: false (upload maps to the error tracker instead)', message: 'productionBrowserSourceMaps: true publishes the source of every client file', severity: 'warning' })
|
||||
}
|
||||
}
|
||||
if (payload) {
|
||||
const c = stripComments(payload.code)
|
||||
if (/\bcors\s*:\s*['"]\*['"]/.test(c)) {
|
||||
out.push({ file: payload.file, fix: 'cors: [process.env.NEXT_PUBLIC_SERVER_URL]', message: "cors: '*': any site may call the API from a visitor's browser", severity: 'warning' })
|
||||
}
|
||||
if (/\bdebug\s*:\s*true/.test(c)) {
|
||||
out.push({ file: payload.file, fix: 'debug: process.env.NODE_ENV !== "production"', message: 'debug: true: Payload answers errors with their stack traces', severity: 'warning' })
|
||||
}
|
||||
if (/disablePlaygroundInProduction\s*:\s*false|disableIntrospectionInProduction\s*:\s*false/.test(c)) {
|
||||
out.push({ file: payload.file, fix: 'leave the GraphQL defaults on', message: 'the GraphQL playground or introspection is switched on in production: the whole schema is public', severity: 'warning' })
|
||||
}
|
||||
if (/maxDepth\s*:\s*(?:[2-9]\d|\d{3,})/.test(c)) {
|
||||
out.push({ file: payload.file, fix: 'maxDepth: 10 or less', message: 'maxDepth above 20: one request can populate a very deep tree (memory, time)', severity: 'warning' })
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const RULE_TEXT: Record<CodePatternId, string> = {
|
||||
'code-eval': 'Code built from strings',
|
||||
'code-inner-html': 'HTML or JSON printed without escaping (XSS)',
|
||||
'code-local-api-user': 'Local API given a user without overrideAccess: false',
|
||||
'code-open-redirect': 'Redirect to an address from the request',
|
||||
'code-override-access': 'overrideAccess: true where a request reaches', // iapl-security-ok: the rule's own title
|
||||
'code-public-secret': 'A secret that can reach the browser',
|
||||
'code-raw-where': 'A query (where) taken from the request',
|
||||
'code-shell': 'A shell command built from a string',
|
||||
'code-ssrf': 'A server-side fetch of an address the request chose',
|
||||
}
|
||||
|
||||
/** Every hit of a project, grouped as doctor findings (one per rule and file). */
|
||||
export function codeFindings(ctx: Pick<DoctorContext, 'read' | 'root' | 'src'>): RuleFinding[] {
|
||||
const start = ctx.src ? ctx.src.replace(/\/$/, '') : '.'
|
||||
const files = listCodeFiles(ctx.root, start).filter((f) => ctx.src || /^(?:app|lib|components|blocks|collections|globals|hooks|endpoints|utilities|access|fields|plugins)\//.test(f) || /^(?:payload\.config|proxy|middleware)\.[cm]?[jt]s$/.test(f))
|
||||
const byKey = new Map<string, CodeHit[]>()
|
||||
for (const file of files) {
|
||||
for (const hit of scanCode(file, ctx.read(file))) {
|
||||
const key = `${hit.rule}\u0000${hit.file}`
|
||||
byKey.set(key, [...(byKey.get(key) ?? []), hit])
|
||||
}
|
||||
}
|
||||
return [...byKey.values()].map((hits) => ({
|
||||
file: hits[0].file,
|
||||
fix: `${RULE_TEXT[hits[0].rule]} — fix it, or mark a correct place with // ${SECURITY_OK_MARKER}: <why> (security.md → Security suites)`,
|
||||
message: `${hits[0].message}: ${hits.slice(0, 3).map((h) => `${h.file}:${h.line}`).join(', ')}${hits.length > 3 ? ` … +${hits.length - 3}` : ''}`,
|
||||
rule: hits[0].rule,
|
||||
severity: hits.some((h) => h.severity === 'error') ? 'error' : hits[0].severity,
|
||||
}))
|
||||
}
|
||||
|
||||
export const securityCodeRules: DoctorRule[] = [
|
||||
{
|
||||
id: 'code-patterns',
|
||||
check: (ctx) => codeFindings(ctx),
|
||||
docs: 'docs/security.md',
|
||||
group: 'security',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
id: 'config-dangerous',
|
||||
check: (ctx) => {
|
||||
const n = nextConfigFile(ctx)
|
||||
const p = configFile(ctx)
|
||||
return scanConfigs(n ? { code: ctx.read(n), file: n } : null, p ? { code: ctx.read(p), file: p } : null)
|
||||
},
|
||||
docs: 'docs/security.md',
|
||||
group: 'security',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// The HTTP attack probes safe on a live site (security/attackProbes.ts): `iapl-doctor --url https://site --only live-probes`
|
||||
id: 'live-probes',
|
||||
check: async (ctx) => {
|
||||
if (!ctx.live) {return []}
|
||||
const severe = new Set(['bundle-secrets', 'graphql', 'login-operators', 'middleware-subrequest', 'rest-where', 'secret-files'])
|
||||
const results = await runAttackProbes(createProbeContext(ctx.live.url))
|
||||
return results.filter(({ result }) => !result.ok).map(({ probe, result }) => ({
|
||||
fix: `${probe.title}${probe.finding ? ` (a known IAPL issue, ${probe.finding} of the 2026-12 audit: see the changelog)` : ''} — security.md → Security suites`,
|
||||
message: `${probe.class}: ${result.detail}`,
|
||||
rule: `live-probes:${probe.id}`,
|
||||
severity: severe.has(probe.id) ? 'error' : 'warning',
|
||||
}))
|
||||
},
|
||||
docs: 'docs/security.md',
|
||||
group: 'security',
|
||||
source: 'live',
|
||||
},
|
||||
]
|
||||
|
||||
/** Probe ids, for `--skip live-probes:<id>` style settings in iapl-doctor.json. */
|
||||
export const LIVE_PROBE_IDS = ATTACK_PROBES.filter((p) => p.live).map((p) => p.id)
|
||||
@@ -17,6 +17,7 @@ import { createLiveFetcher, liveRules } from './rules/live.js'
|
||||
import { mailRules } from './rules/mail.js'
|
||||
import { performanceRules } from './rules/performance.js'
|
||||
import { securityRules } from './rules/security.js'
|
||||
import { securityCodeRules } from './rules/securityCode.js'
|
||||
import { seedRules } from './rules/seeds.js'
|
||||
import { toolingRules } from './rules/tooling.js'
|
||||
import { versionRules } from './rules/versions.js'
|
||||
@@ -37,6 +38,7 @@ export const doctorRules: DoctorRule[] = [
|
||||
...layoutRules,
|
||||
...envRules,
|
||||
...securityRules,
|
||||
...securityCodeRules,
|
||||
...consentRules,
|
||||
...mailRules,
|
||||
...agentRules,
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
/**
|
||||
* HTTP attack probes (security audit 2026-12): the requests attackers send to Payload / Next.js sites, each with the
|
||||
* answer a safe site gives. One list, two users:
|
||||
* - `iapl-doctor --url https://site --only live-probes` runs the probes marked `live` against a project's own site:
|
||||
* GET requests, plus requests that change nothing (a refused sign-in with operators in it);
|
||||
* - the plugin's reference site runs every probe on a production build in both bundlers
|
||||
* (reference/e2e/attack-probes.spec.ts, part of `pnpm e2e:built`); a project copies
|
||||
* `.agents/skills/iapl-audit/resources/attack-probes.spec.template.ts`.
|
||||
* Exported (`@intecion/ipal-kit/doctor`) so a project adds its own probes or runs a subset in its CI.
|
||||
*
|
||||
* A probe answers on STATUS CODES and headers first: a 500 page is never counted as "closed" (a test that passes on
|
||||
* an error page proves nothing).
|
||||
*/
|
||||
|
||||
export type ProbeAnswer = { error?: string; headers: Headers; ms: number; status: number; text: string }
|
||||
|
||||
export type ProbeContext = {
|
||||
/** Site origin, no trailing slash. */
|
||||
base: string
|
||||
/** One request; never follows redirects unless asked. */
|
||||
fetch: (path: string, init?: { body?: string; follow?: boolean; headers?: Record<string, string>; method?: string }) => Promise<ProbeAnswer>
|
||||
/** A public page path of the site (default `/`), e.g. `/pl`. */
|
||||
page?: string
|
||||
/** Values that must never appear in a public file (the test knows the real secrets; a live run passes none). */
|
||||
secrets?: string[]
|
||||
}
|
||||
|
||||
export type ProbeResult = { detail: string; ok: boolean; skipped?: string }
|
||||
|
||||
export type AttackProbe = {
|
||||
/** The vulnerability class (security.md → "Threat list"). */
|
||||
class: string
|
||||
/** A finding of the audit that is not fixed yet (security-audit-2026-12-findings.md): expected to fail until it is. */
|
||||
finding?: string
|
||||
id: string
|
||||
/** Safe on a live site: reads only, or a request the site refuses without writing. */
|
||||
live: boolean
|
||||
run: (ctx: ProbeContext) => Promise<ProbeResult>
|
||||
title: string
|
||||
}
|
||||
|
||||
const ok = (detail = ''): ProbeResult => ({ detail, ok: true })
|
||||
const bad = (detail: string): ProbeResult => ({ detail, ok: false })
|
||||
const skip = (why: string): ProbeResult => ({ detail: '', ok: true, skipped: why })
|
||||
|
||||
/** A stack trace or a server path in an answer. */
|
||||
const LEAK = /\n\s+at [\w$.<>]+ \(|\bat (?:async )?[\w$.]+ \((?:\/|[A-Z]:\\|file:)|\/node_modules\/|webpack-internal:|\/\.next\/server\//
|
||||
/** What a secret looks like, without knowing it. */
|
||||
const SECRET_SHAPES: Array<[string, RegExp]> = [
|
||||
['a private key', /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/],
|
||||
['a database URL with a password', /\b(?:mongodb(?:\+srv)?|postgres(?:ql)?|mysql):\/\/[^\s"'`:@/]+:[^\s"'`@/]+@/],
|
||||
['a live Stripe key', /\bsk_live_[0-9a-zA-Z]{10,}/],
|
||||
['an AWS secret', /\baws_secret_access_key\b|\bAKIA[0-9A-Z]{16}\b/],
|
||||
['a variable assignment of a server secret', /\b(?:PAYLOAD_SECRET|DATABASE_URI|R2_SECRET_ACCESS_KEY|TURNSTILE_SECRET_KEY|CRON_SECRET|SMTP_PASS(?:WORD)?)\s*[=:]\s*["'`][^"'`]{8,}/],
|
||||
]
|
||||
const EVIL = 'evil.example'
|
||||
const sameHost = (location: null | string, base: string) => {
|
||||
if (!location) {return true}
|
||||
try {
|
||||
return new URL(location, base).host === new URL(base).host
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
const describe = (a: ProbeAnswer) => (a.error ? `no answer (${a.error})` : `${a.status}`)
|
||||
const scriptSrcs = (html: string) => [...html.matchAll(/<script[^>]+src="([^"]+)"/g)].map((m) => m[1].replace(/&/g, '&'))
|
||||
|
||||
export const ATTACK_PROBES: AttackProbe[] = [
|
||||
{
|
||||
id: 'secret-files',
|
||||
class: 'secrets in public files',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const paths = ['/.env', '/.env.local', '/.env.production', '/.git/config', '/.git/HEAD', '/package.json', '/pnpm-lock.yaml', '/next.config.ts', '/payload.config.ts', '/src/payload.config.ts', '/Dockerfile', '/docker-compose.yml', '/.DS_Store', '/api/media/file/..%2F..%2F.env', '/api/media/file/%2e%2e%2f%2e%2e%2fpackage.json', '/_next/static/..%2F..%2F.env', '/_next/../package.json']
|
||||
const open: string[] = []
|
||||
for (const path of paths) {
|
||||
const a = await fetch(path)
|
||||
if (a.status === 200 && /PAYLOAD_SECRET|DATABASE_URI|"dependencies"\s*:|\[core\]|^ref: refs\/|lockfileVersion|FROM node|buildConfig\(/m.test(a.text)) {open.push(path)}
|
||||
if (a.status >= 500) {open.push(`${path} → ${a.status}`)}
|
||||
}
|
||||
return open.length ? bad(`served: ${open.join(', ')}`) : ok(`${paths.length} paths refused`)
|
||||
},
|
||||
title: 'source, env and git files are not served (also through ../ in a file route)',
|
||||
},
|
||||
{
|
||||
id: 'bundle-secrets',
|
||||
class: 'secrets in client bundles',
|
||||
live: true,
|
||||
run: async ({ fetch, page = '/', secrets = [] }) => {
|
||||
const pages = [page, '/admin/login']
|
||||
const files = new Set<string>()
|
||||
for (const p of pages) {
|
||||
const a = await fetch(p, { follow: true })
|
||||
for (const src of scriptSrcs(a.text)) {if (src.startsWith('/') && !src.startsWith('//')) {files.add(src)}}
|
||||
}
|
||||
if (!files.size) {return skip('no script files found on the pages')}
|
||||
const found: string[] = []
|
||||
let maps = 0
|
||||
for (const file of files) {
|
||||
const a = await fetch(file)
|
||||
for (const [what, re] of SECRET_SHAPES) {if (re.test(a.text)) {found.push(`${file}: ${what}`)}}
|
||||
for (const s of secrets) {if (s && s.length >= 8 && a.text.includes(s)) {found.push(`${file}: a server secret's value`)}}
|
||||
if (maps < 3 && /\/_next\/static\/.+\.js$/.test(file)) {
|
||||
maps++
|
||||
const map = await fetch(`${file.split('?')[0]}.map`)
|
||||
if (map.status === 200 && /"sources"\s*:/.test(map.text)) {found.push(`${file}.map: source map is public (productionBrowserSourceMaps)`)}
|
||||
}
|
||||
}
|
||||
return found.length ? bad(found.join('; ')) : ok(`${files.size} script files clean`)
|
||||
},
|
||||
title: 'no secret (or a secret-shaped value) in the JavaScript the pages load; no public source maps',
|
||||
},
|
||||
{
|
||||
id: 'middleware-subrequest',
|
||||
class: 'middleware / proxy bypass',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const plain = await fetch('/')
|
||||
if (plain.status < 300 || plain.status >= 400) {return skip(`/ answers ${describe(plain)} without the proxy redirecting (single locale?): nothing to compare`)}
|
||||
const values = ['middleware:middleware:middleware:middleware:middleware', 'src/middleware:src/middleware:src/middleware:src/middleware:src/middleware', 'proxy:proxy:proxy:proxy:proxy', 'src/proxy:src/proxy:src/proxy:src/proxy:src/proxy', 'pages/_middleware']
|
||||
for (const v of values) {
|
||||
const a = await fetch('/', { headers: { 'x-middleware-subrequest': v } })
|
||||
if (a.status !== plain.status) {return bad(`x-middleware-subrequest: ${v} changed / from ${plain.status} to ${describe(a)}: the proxy was skipped (CVE-2025-29927 class — upgrade Next)`)}
|
||||
}
|
||||
return ok(`the proxy ran for all ${values.length} header values`)
|
||||
},
|
||||
title: 'x-middleware-subrequest does not skip the proxy (CVE-2025-29927 class)',
|
||||
},
|
||||
{
|
||||
id: 'open-redirect',
|
||||
class: 'open redirect',
|
||||
live: true,
|
||||
run: async ({ base, fetch }) => {
|
||||
const paths = [`//${EVIL}/`, `/%2F%2F${EVIL}`, `/\\${EVIL}`, `/%5C${EVIL}`, `/%09/${EVIL}`, `/admin/login?redirect=https://${EVIL}/`, `/admin?redirect=//${EVIL}`, `/api/ipal/admin-language?lng=en`]
|
||||
const away: string[] = []
|
||||
for (const path of paths) {
|
||||
const a = await fetch(path, { headers: path.includes('admin-language') ? { referer: `https://${EVIL}/admin` } : {} })
|
||||
const location = a.headers.get('location')
|
||||
if (a.status >= 300 && a.status < 400 && !sameHost(location, base)) {away.push(`${path} → ${location}`)}
|
||||
if (a.status >= 500) {away.push(`${path} → ${a.status}`)}
|
||||
}
|
||||
return away.length ? bad(away.join('; ')) : ok(`${paths.length} paths stay on the site`)
|
||||
},
|
||||
title: 'no path, parameter or Referer sends the browser to another host',
|
||||
},
|
||||
{
|
||||
id: 'host-header',
|
||||
class: 'cache poisoning (host headers)',
|
||||
live: true,
|
||||
run: async ({ fetch, page = '/' }) => {
|
||||
const headers = { forwarded: `host=${EVIL}`, 'x-forwarded-host': EVIL, 'x-host': EVIL, 'x-original-host': EVIL }
|
||||
const redirect = await fetch('/', { headers })
|
||||
const location = redirect.headers.get('location') ?? ''
|
||||
if (location.includes(EVIL)) {return bad(`/ redirects to ${location}: the redirect trusts X-Forwarded-Host`)}
|
||||
const html = await fetch(page, { follow: true, headers })
|
||||
if (html.text.includes(EVIL)) {return bad(`${page} prints ${EVIL} (canonical, og:url, hreflang or a link): a cached page would carry it for everyone`)}
|
||||
return ok('neither the redirect nor the page uses a host the request named')
|
||||
},
|
||||
title: 'X-Forwarded-Host / Forwarded do not reach redirects or links in the page',
|
||||
},
|
||||
{
|
||||
id: 'markdown-vary',
|
||||
class: 'cache poisoning (content negotiation)',
|
||||
finding: 'F3',
|
||||
live: true,
|
||||
run: async ({ fetch, page = '/' }) => {
|
||||
const a = await fetch(page, { follow: true, headers: { accept: 'text/markdown' } })
|
||||
if (!/text\/markdown/.test(a.headers.get('content-type') ?? '')) {return skip(`${page} with Accept: text/markdown answers ${a.headers.get('content-type') ?? describe(a)} (no Markdown negotiation)`)}
|
||||
const cc = a.headers.get('cache-control') ?? ''
|
||||
const shared = /s-maxage|public/.test(cc) && !/private|no-store/.test(cc)
|
||||
const vary = (a.headers.get('vary') ?? '').split(',').map((v) => v.trim().toLowerCase())
|
||||
if (shared && !vary.includes('accept') && !vary.includes('*')) {return bad(`${page} answers Markdown to Accept: text/markdown with "${cc}" and no Vary: Accept: a shared cache stores it under the HTML URL`)}
|
||||
return ok('the Markdown answer at the HTML URL varies by Accept or is not shared')
|
||||
},
|
||||
title: 'the Markdown copy at an HTML URL cannot be cached as the page',
|
||||
},
|
||||
{
|
||||
id: 'rsc-vary',
|
||||
class: 'cache poisoning (RSC)',
|
||||
live: true,
|
||||
run: async ({ fetch, page = '/' }) => {
|
||||
const a = await fetch(page, { follow: true, headers: { rsc: '1' } })
|
||||
if (!/text\/x-component/.test(a.headers.get('content-type') ?? '')) {return skip(`${page} with RSC: 1 is not a flight answer`)}
|
||||
return /\brsc\b/i.test(a.headers.get('vary') ?? '') ? ok() : bad(`the flight answer of ${page} has no Vary: RSC (vary: ${a.headers.get('vary') ?? 'none'})`)
|
||||
},
|
||||
title: 'the RSC (flight) answer of a page varies by the RSC header',
|
||||
},
|
||||
{
|
||||
id: 'login-operators',
|
||||
class: 'injection (NoSQL operators)',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const bodies = [{ email: { $ne: null }, password: { $ne: null } }, { email: { $gt: '' }, password: 'x' }, { email: '[email protected]', password: { $ne: 'x' } }]
|
||||
for (const body of bodies) {
|
||||
const a = await fetch('/api/users/login', { body: JSON.stringify(body), headers: { 'content-type': 'application/json' }, method: 'POST' })
|
||||
if (a.status === 200 || /"token"\s*:\s*"/.test(a.text)) {return bad(`login with ${JSON.stringify(body)} answered ${a.status} with a token`)}
|
||||
if (a.status >= 500) {return bad(`login with ${JSON.stringify(body)} answered ${a.status}`)}
|
||||
if (LEAK.test(a.text)) {return bad('the refused login answer carries a stack trace or a server path')}
|
||||
}
|
||||
return ok('operators in the e-mail or password are refused')
|
||||
},
|
||||
title: 'a sign-in with $ne / $gt in it is refused (no account, no 500)',
|
||||
},
|
||||
{
|
||||
id: 'rest-where',
|
||||
class: 'access control (REST where / drafts)',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const problems: string[] = []
|
||||
for (const path of ['/api/users?where[email][exists]=true&limit=1', '/api/users?where[password][exists]=true&limit=1', '/api/users?where[or][0][roles][equals]=admin&limit=1', '/api/form-submissions?limit=1', '/api/payload-preferences?limit=1', '/api/payload-kv?limit=1']) {
|
||||
const a = await fetch(path)
|
||||
if (a.status === 404) {continue}
|
||||
if (a.status >= 500) {problems.push(`${path} → ${a.status}`); continue}
|
||||
if (a.status === 200 && /"docs"\s*:\s*\[\s*\{/.test(a.text)) {problems.push(`${path} → 200 with documents`)}
|
||||
}
|
||||
const drafts = await fetch('/api/pages?draft=true&where[_status][equals]=draft&limit=5&depth=0')
|
||||
if (drafts.status === 200 && /"_status"\s*:\s*"draft"/.test(drafts.text)) {problems.push('/api/pages?draft=true returns drafts to an anonymous visitor')}
|
||||
if (drafts.status >= 500) {problems.push(`/api/pages?draft=true… → ${drafts.status}`)}
|
||||
const versions = await fetch('/api/pages/versions?limit=1&depth=0')
|
||||
if (versions.status === 200 && /"docs"\s*:\s*\[\s*\{/.test(versions.text)) {problems.push('/api/pages/versions lists versions to an anonymous visitor')}
|
||||
return problems.length ? bad(problems.join('; ')) : ok('accounts, submissions, preferences, drafts and versions stay closed to a where query')
|
||||
},
|
||||
title: 'an anonymous where / draft / versions query reads no accounts, submissions or drafts',
|
||||
},
|
||||
{
|
||||
id: 'graphql',
|
||||
class: 'access control (GraphQL)',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const post = (query: string) => fetch('/api/graphql', { body: JSON.stringify({ query }), headers: { 'content-type': 'application/json' }, method: 'POST' })
|
||||
const intro = await post('{ __schema { types { name } } }')
|
||||
if (intro.status === 404) {return skip('no GraphQL route')}
|
||||
if (intro.status === 200 && /"__schema"\s*:\s*\{/.test(intro.text)) {return bad('introspection answers in production: the whole schema is public')}
|
||||
const syntax = await post('{ Pages(where: { ')
|
||||
if (syntax.status >= 500 || LEAK.test(syntax.text)) {return bad(`a broken query answers ${syntax.status}${LEAK.test(syntax.text) ? ' with a stack trace' : ''}`)}
|
||||
const get = await fetch(`/api/graphql?query=${encodeURIComponent('mutation { __typename }')}`)
|
||||
if (get.status === 200 && /"data"\s*:\s*\{\s*"__typename"/.test(get.text)) {return bad('a mutation runs over GET (CSRF: a link or <img> can run it with the visitor\'s cookie)')}
|
||||
const users = await post('{ Users(limit: 1) { docs { email } } }')
|
||||
if (users.status === 200 && /"email"\s*:\s*"/.test(users.text)) {return bad('an anonymous GraphQL query lists account e-mails')}
|
||||
return ok('no introspection, no stack traces, no mutation over GET, no accounts')
|
||||
},
|
||||
title: 'GraphQL: no introspection in production, no mutation over GET, no accounts, no stack traces',
|
||||
},
|
||||
{
|
||||
id: 'error-leak',
|
||||
class: 'information disclosure (errors)',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const paths = ['/api/pages/%27%22%3C%3E', '/api/pages?where[id][equals]=not-an-id', '/api/pages?depth=abc&limit=-1', '/api/pages?where[title][like][$regex]=.*', '/api/users/me', '/api/globals/does-not-exist', '/does-not-exist-%00']
|
||||
const problems: string[] = []
|
||||
for (const path of paths) {
|
||||
const a = await fetch(path)
|
||||
if (a.status >= 500) {problems.push(`${path} → ${a.status}`)}
|
||||
if (LEAK.test(a.text)) {problems.push(`${path}: stack trace or server path in the answer`)}
|
||||
}
|
||||
return problems.length ? bad(problems.join('; ')) : ok(`${paths.length} malformed requests answered without a 500 or a stack trace`)
|
||||
},
|
||||
title: 'malformed ids, sorts, depths and operators give a 4xx without a stack trace',
|
||||
},
|
||||
{
|
||||
id: 'sort-operator',
|
||||
class: 'injection (operators in sort)',
|
||||
finding: 'F5',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const problems: string[] = []
|
||||
for (const sort of ['%24where', '-%24where', '%24natural', 'title.%24ne']) {
|
||||
const a = await fetch(`/api/pages?sort=${sort}&limit=1&depth=0`)
|
||||
if (a.status >= 500 || LEAK.test(a.text)) {problems.push(`sort=${decodeURIComponent(sort)} → ${a.status}`)}
|
||||
}
|
||||
return problems.length ? bad(`${problems.join('; ')}: an operator name reaches the database as a sort field (an error and a logged stack trace per request)`) : ok('operator names in sort are refused with a 4xx')
|
||||
},
|
||||
title: 'an operator name in ?sort= is refused, not passed to the database',
|
||||
},
|
||||
{
|
||||
id: 'unbounded-list',
|
||||
class: 'denial of service (unbounded queries)',
|
||||
finding: 'F4',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const a = await fetch('/api/pages?limit=100000&depth=50')
|
||||
if (a.status !== 200) {return skip(`/api/pages answers ${describe(a)}`)}
|
||||
let body: { limit?: number } = {}
|
||||
try {
|
||||
body = JSON.parse(a.text) as typeof body
|
||||
} catch {
|
||||
return skip('not JSON')
|
||||
}
|
||||
return (body.limit ?? 0) > 1000 ? bad(`/api/pages?limit=100000 is honoured (limit ${body.limit}, ${a.ms} ms, ${a.text.length} bytes): one anonymous request reads a whole collection`) : ok(`limit capped at ${body.limit}`)
|
||||
},
|
||||
title: 'a public list caps limit (and depth) so one request cannot read a whole collection',
|
||||
},
|
||||
{
|
||||
id: 'image-optimizer',
|
||||
class: 'SSRF / image optimizer',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const problems: string[] = []
|
||||
for (const url of ['http://169.254.169.254/latest/meta-data/', 'http://127.0.0.1:22/', `https://${EVIL}/x.png`, '//evil.example/x.png', '/api/media/file/x.svg']) {
|
||||
const a = await fetch(`/_next/image?url=${encodeURIComponent(url)}&w=64&q=75`)
|
||||
if (a.status === 200 && !/^image\/(?:png|jpe?g|webp|avif|gif)/.test(a.headers.get('content-type') ?? '')) {problems.push(`${url} → 200 ${a.headers.get('content-type')}`)}
|
||||
if (a.status === 200 && /169\.254|127\.0\.0\.1|evil\.example/.test(url)) {problems.push(`${url} → 200: the optimizer fetched it`)}
|
||||
// a missing local file is a 500 from Next's optimizer (it reports the upstream 404 so): not a door
|
||||
if (a.status >= 500 && !url.startsWith('/api/media/')) {problems.push(`${url} → ${a.status}`)}
|
||||
}
|
||||
return problems.length ? bad(problems.join('; ')) : ok('inner addresses, foreign hosts and SVG are refused')
|
||||
},
|
||||
title: '/_next/image refuses inner addresses, unlisted hosts and SVG',
|
||||
},
|
||||
{
|
||||
id: 'headers-everywhere',
|
||||
class: 'security headers',
|
||||
live: true,
|
||||
run: async ({ fetch, page = '/' }) => {
|
||||
const missing: string[] = []
|
||||
for (const path of [page, '/this-page-does-not-exist-iapl', '/api/health', '/api/pages?limit=1', '/admin/login']) {
|
||||
const a = await fetch(path, { follow: true })
|
||||
if (!a.status) {continue}
|
||||
const h = a.headers
|
||||
const lacks = [
|
||||
...(/nosniff/i.test(h.get('x-content-type-options') ?? '') ? [] : ['nosniff']),
|
||||
...(h.get('x-frame-options') || /frame-ancestors/.test(h.get('content-security-policy') ?? '') ? [] : ['frame protection']),
|
||||
...(h.get('x-powered-by') ? [`X-Powered-By: ${h.get('x-powered-by')}`] : []),
|
||||
]
|
||||
if (lacks.length) {missing.push(`${path}: ${lacks.join(', ')}`)}
|
||||
}
|
||||
return missing.length ? bad(missing.join('; ')) : ok()
|
||||
},
|
||||
title: 'pages, the 404 page, the API and the admin all carry nosniff and frame protection, no X-Powered-By',
|
||||
},
|
||||
{
|
||||
id: 'methods',
|
||||
class: 'unexpected methods',
|
||||
live: true,
|
||||
run: async ({ fetch, page = '/' }) => {
|
||||
const problems: string[] = []
|
||||
for (const method of ['TRACE', 'PUT', 'DELETE', 'PATCH']) {
|
||||
const a = await fetch(page, { method })
|
||||
if (a.status >= 500) {problems.push(`${method} ${page} → ${a.status}`)}
|
||||
if (method === 'TRACE' && a.status === 200 && /TRACE \//.test(a.text)) {problems.push('TRACE echoes the request')}
|
||||
}
|
||||
const action = await fetch(page, { body: '[]', headers: { 'content-type': 'text/plain;charset=UTF-8', 'next-action': '0'.repeat(42) }, method: 'POST' })
|
||||
if (action.status >= 500 || LEAK.test(action.text)) {problems.push(`an unknown Server Action id → ${action.status}`)}
|
||||
return problems.length ? bad(problems.join('; ')) : ok()
|
||||
},
|
||||
title: 'TRACE / PUT / DELETE on a page and an unknown Server Action id give no 500',
|
||||
},
|
||||
{
|
||||
id: 'body-size',
|
||||
class: 'denial of service (body size)',
|
||||
live: false,
|
||||
run: async ({ fetch }) => {
|
||||
const problems: string[] = []
|
||||
const big = JSON.stringify({ email: '[email protected]', pad: 'x'.repeat(8 * 1024 * 1024), password: 'x' })
|
||||
for (const path of ['/api/ipal/consent', '/api/csp-report', '/api/mcp', '/api/users/login', '/api/graphql']) {
|
||||
const a = await fetch(path, { body: big, headers: { 'content-type': 'application/json' }, method: 'POST' })
|
||||
if (a.status === 404 || a.status === 405) {continue}
|
||||
if (a.status >= 500 || a.status === 0) {problems.push(`${path} → ${describe(a)} after ${a.ms} ms`)}
|
||||
else if (a.ms > 5000) {problems.push(`${path} took ${a.ms} ms for an 8 MB body`)}
|
||||
}
|
||||
return problems.length ? bad(problems.join('; ')) : ok('8 MB bodies refused or answered quickly')
|
||||
},
|
||||
title: 'an 8 MB body to the public POST routes is refused quickly, never a 500',
|
||||
},
|
||||
]
|
||||
|
||||
/** Plain-fetch context for a site. */
|
||||
export function createProbeContext(base: string, options: { page?: string; secrets?: string[]; timeoutMs?: number; userAgent?: string } = {}): ProbeContext {
|
||||
const origin = base.replace(/\/+$/, '')
|
||||
return {
|
||||
base: origin,
|
||||
fetch: async (path, init = {}) => {
|
||||
const started = Date.now()
|
||||
try {
|
||||
const res = await fetch(origin + path, {
|
||||
body: init.body,
|
||||
headers: { 'user-agent': options.userAgent ?? 'iapl-doctor probes (read-only)', ...init.headers },
|
||||
method: init.method ?? 'GET',
|
||||
redirect: init.follow ? 'follow' : 'manual',
|
||||
signal: AbortSignal.timeout(options.timeoutMs ?? 20_000),
|
||||
})
|
||||
const text = init.method === 'HEAD' ? '' : await res.text()
|
||||
return { headers: res.headers, ms: Date.now() - started, status: res.status, text }
|
||||
} catch (err) {
|
||||
const e = err as { cause?: { code?: string }; message?: string }
|
||||
return { error: e.cause?.code ?? e.message ?? 'unreachable', headers: new Headers(), ms: Date.now() - started, status: 0, text: '' }
|
||||
}
|
||||
},
|
||||
page: options.page,
|
||||
secrets: options.secrets,
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the probes (default: those safe on a live site) and returns each result. */
|
||||
export async function runAttackProbes(ctx: ProbeContext, probes: AttackProbe[] = ATTACK_PROBES.filter((p) => p.live)): Promise<Array<{ probe: AttackProbe; result: ProbeResult }>> {
|
||||
const out: Array<{ probe: AttackProbe; result: ProbeResult }> = []
|
||||
for (const probe of probes) {
|
||||
let result: ProbeResult
|
||||
try {
|
||||
result = await probe.run(ctx)
|
||||
} catch (err) {
|
||||
result = bad(`probe crashed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
out.push({ probe, result })
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"$comment": "Places in the plugin and the reference site that match a static security rule (src/modules/doctor/rules/securityCode.ts) on purpose. Key: '<rule> <file>' → { count, reason }. test/securityPatterns.test.ts fails on a new place, a raised count or an empty reason; a lowered count is reported so the entry can shrink. Judge a new entry before adding it (security.md → Security suites).",
|
||||
"entries": {
|
||||
"code-override-access src/modules/access/panelRole.ts": { "count": 2, "reason": "counts staff accounts at start / in the doctor; no request data, counts only" },
|
||||
"code-override-access src/modules/access/passwordRule.ts": { "count": 1, "reason": "the password rule looks up the account being changed; the where is built from req.user's id or a string-checked reset token (typeof === 'string'), never an object from the body" },
|
||||
"code-override-access src/modules/access/rolesField.ts": { "count": 1, "reason": "first-account check (is the collection empty?): a count, no data returned" },
|
||||
"code-override-access src/modules/access/selfRegistration.ts": { "count": 3, "reason": "start-time inventory of auth collections (count / admin ids); never reached by a request" },
|
||||
"code-override-access src/modules/consent/consentLog.ts": { "count": 1, "reason": "POST /api/ipal/consent writes the visitor's own record: the collection's create is false over the API on purpose; body capped at 4 KiB, fields whitelisted" },
|
||||
"code-override-access src/modules/consent/scanner/approval.ts": { "count": 3, "reason": "cookie approval endpoint: runs after cookieScanner.access (editor+ with the second factor) has passed" },
|
||||
"code-override-access src/modules/consent/scanner/collection.ts": { "count": 2, "reason": "hooks of the cookie-review collection writing the scanner's own fields (context ipalCookieScan)" },
|
||||
"code-override-access src/modules/consent/scanner/crawl/endpoints.ts": { "count": 2, "reason": "crawl endpoints: after the editor+/second-factor check or the IAPL_COOKIE_SCAN_TOKEN + jobId check" },
|
||||
"code-override-access src/modules/consent/scanner/crawl/ingest.ts": { "count": 2, "reason": "crawler call-back ingest: only after the token and running jobId are checked" },
|
||||
"code-override-access src/modules/consent/scanner/scan.ts": { "count": 3, "reason": "cookie scan endpoint: after cookieScanner.access; writes the scanner's own collection" },
|
||||
"code-override-access src/modules/consent/scanner/sync.ts": { "count": 1, "reason": "copies approved cookies into Cookie settings after the approval check" },
|
||||
"code-override-access src/modules/doctor/status.ts": { "count": 4, "reason": "doctor status: counts and states only (no secrets returned); the endpoint needs IAPL_DOCTOR_TOKEN or doctor.access" },
|
||||
"code-override-access src/modules/email/method.ts": { "count": 1, "reason": "records the sending method chosen in the panel by an admin (the panel action checks the admin first)" },
|
||||
"code-override-access src/modules/email/relay/adapter.ts": { "count": 1, "reason": "reads the site name for the mail sender; no request data" },
|
||||
"code-override-access src/modules/forms/emailLayout.ts": { "count": 1, "reason": "reads the form's e-mail settings (staff-only fields) to send the notification of a submission; the visitor never sees them" },
|
||||
"code-override-access src/modules/hooks/fillEmptyLocales.ts": { "count": 1, "reason": "afterChange hook of a save the editor's own access already allowed; fills empty locales of the same document" },
|
||||
"code-override-access src/modules/security/totp/TwoFactorStatusField.tsx": { "count": 1, "reason": "admin field component: shows the 2FA state of an account the viewer may already open" },
|
||||
"code-override-access src/modules/security/totp/setupRequired.ts": { "count": 5, "reason": "2FA set-up window: start-time backfill, counts, and stamping the signed-in account's own record" },
|
||||
"code-override-access src/modules/stats/admin/loadStats.ts": { "count": 3, "reason": "the stats admin view, behind the stats access rule" },
|
||||
"code-override-access src/modules/stats/endpoint.ts": { "count": 3, "reason": "POST /api/ipal/hit (opt-in stats): writes the visit counters; body capped, fields parsed (stats/parse.ts)" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* Security audit 2026-12: one block per vulnerability class, each asking the plugin's own building blocks with the
|
||||
* payloads that class is known for (docs/security.md → "Security suites"). The HTTP side of the same classes runs
|
||||
* against a BUILT site in reference/e2e/attack-probes.spec.ts.
|
||||
*
|
||||
* A finding of the audit that is not fixed yet is an `it.fails` naming it (security-audit-2026-12-findings.md):
|
||||
* the test states the SAFE behaviour, so the day the fix lands vitest says the test "passed unexpectedly" and the
|
||||
* `.fails` goes. The same convention as `openFor` in the closed-doors spec.
|
||||
*/
|
||||
import { Script } from 'node:vm'
|
||||
import { createElement } from 'react'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { adminPathFromReferer } from '../src/modules/branding/signIn/languageEndpoint.js'
|
||||
import { consentDecidedScript } from '../src/modules/consent/firstPaint.js'
|
||||
import { parseConsent, readConsentRecord } from '../src/modules/consent/storage.js'
|
||||
import { markdownResponse } from '../src/modules/content/createMarkdownRenderer.js'
|
||||
import { createProxy } from '../src/modules/i18n/createProxy.js'
|
||||
import { safeHref } from '../src/modules/links/resolveLinkHref.js'
|
||||
import { createMcpRoute } from '../src/modules/mcp/createMcpRoute.js'
|
||||
import { sanitizeRichTextLinks } from '../src/modules/richtext/sanitizeLinks.js'
|
||||
import { createCspReportRoute } from '../src/modules/security/createCspReportRoute.js'
|
||||
import { safeAdminBack } from '../src/modules/security/totp/safeBack.js'
|
||||
import { buildSitemapXml } from '../src/modules/seo/buildSitemapXml.js'
|
||||
import { JsonLdGraph } from '../src/modules/seo/JsonLdGraph.js'
|
||||
import { themeScript } from '../src/modules/theme/theme.js'
|
||||
|
||||
/** Strings that end a script, open markup, or run as a URL — the XSS payloads used below. */
|
||||
const XSS = ['</script><script>alert(1)</script>', '<img src=x onerror=alert(1)>', '"><svg onload=alert(1)>', '
alert(1)//']
|
||||
const UNSAFE_URLS = ['javascript:alert(1)', 'JaVaScRiPt:alert(1)', ' javascript:alert(1)', 'java\tscript:alert(1)', 'java\nscript:alert(1)', 'data:text/html,<script>alert(1)</script>', 'vbscript:msgbox(1)', '//evil.example/x', '/\\evil.example', '\\\\evil.example']
|
||||
|
||||
const chunked = (text: string) => new Request('http://localhost/x', {
|
||||
body: new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode(text)); c.close() } }),
|
||||
// @ts-expect-error Node's fetch needs it for a stream body
|
||||
duplex: 'half',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
describe('XSS — output into HTML, scripts and URLs', () => {
|
||||
it('JSON-LD: no value can end the <script> (</script>, <!--, U+2028)', () => {
|
||||
const html = renderToStaticMarkup(createElement(JsonLdGraph, { schemas: XSS.map((name) => ({ name, '@type': 'Thing' })) as never }))
|
||||
expect(html.match(/<\/script>/gi)).toHaveLength(1)
|
||||
expect(html).not.toMatch(/<img|<svg|<!--/i)
|
||||
// what reaches the browser is still the same data
|
||||
const json = html.replace(/^<script[^>]*>/, '').replace(/<\/script>$/, '')
|
||||
expect(JSON.stringify(JSON.parse(json))).toContain('</script><script>alert(1)')
|
||||
})
|
||||
|
||||
it('first-paint scripts: a cookie name with </script> stays inside its string', () => {
|
||||
for (const cookieName of XSS) {
|
||||
const js = consentDecidedScript({ cookieName })
|
||||
expect(js).not.toMatch(/<\/script|<img|<svg/i)
|
||||
expect(() => new Script(js)).not.toThrow() // compiled, never run
|
||||
}
|
||||
})
|
||||
|
||||
// dev-config input only (the storage key is set in code, not by visitors): hardening, not a finding
|
||||
it('theme script: the storage key is a JSON string literal', () => {
|
||||
expect(() => new Script(themeScript({ allowToggle: true, defaultTheme: 'system', storageKey: 'a"b\\c' }))).not.toThrow()
|
||||
})
|
||||
|
||||
it('links: javascript:, data:, protocol-relative and control-character tricks never become an href', () => {
|
||||
// a link to another host is an editor's right (https://…); only schemes that run script are dropped
|
||||
for (const url of UNSAFE_URLS.filter((u) => !/^(?:\/\/|\/\\|\\\\)/.test(u))) {expect(safeHref(url), url).toBeNull()}
|
||||
for (const url of ['https://example.com', '/pl/o-nas', '#top', 'mailto:[email protected]', 'tel:+48123']) {expect(safeHref(url)).toBe(url)}
|
||||
})
|
||||
|
||||
it('rich text: a stored javascript: link loses its URL, keeps its text', () => {
|
||||
const data = { root: { type: 'root', children: [{ type: 'link', children: [{ type: 'text', text: 'click' }], fields: { linkType: 'custom', url: 'javascript:alert(1)' } }] } }
|
||||
expect(JSON.stringify(sanitizeRichTextLinks(data))).not.toContain('javascript:')
|
||||
expect(JSON.stringify(sanitizeRichTextLinks(data))).toContain('click')
|
||||
})
|
||||
|
||||
it('sitemap: a URL with markup is escaped in the XML', () => {
|
||||
const xml = buildSitemapXml([{ url: 'https://s.pl/a"><script>alert(1)</script>&' } as never])
|
||||
expect(xml).not.toContain('<script>')
|
||||
expect(xml).toContain('<script>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('open redirect and header injection', () => {
|
||||
it('2FA back link: only a path inside the panel', () => {
|
||||
for (const back of [...UNSAFE_URLS, 'https://evil.example/admin', '/admin/../../evil', 'https:evil.example']) {
|
||||
const to = safeAdminBack(back, { adminRoute: '/admin', origin: 'https://site.pl' })
|
||||
expect(to, back).toMatch(/^\/admin(?:\/|$)/)
|
||||
expect(to).not.toMatch(/^\/\/|\\/)
|
||||
}
|
||||
})
|
||||
|
||||
it('admin language link: the way back is a path of this panel, never a host; no CR/LF reaches Location', () => {
|
||||
for (const referer of ['https://evil.example/admin/x', 'https://site.pl//evil.example', 'https://site.pl/admin\\..\\x', 'https://site.pl/admin/%0d%0aSet-Cookie:x=1', 'not a url', 'javascript:alert(1)']) {
|
||||
const to = adminPathFromReferer(referer, '/admin')
|
||||
expect(to, referer).toMatch(/^\/admin(?:\/|$)/)
|
||||
expect(to).not.toMatch(/[\r\n\\]|^\/\//)
|
||||
}
|
||||
})
|
||||
|
||||
it('locale redirect: a path that looks like a host stays on this site', () => {
|
||||
const NextResponse = { next: () => ({ cookies: { set: () => {} }, headers: new Headers() }), redirect: (u: string | URL) => ({ cookies: { set: () => {} }, headers: new Headers({ location: String(u) }) }) }
|
||||
const proxy = createProxy({ defaultLocale: 'pl', locales: ['pl', 'en'] } as never, { NextResponse })
|
||||
for (const p of ['//evil.example', '/\\evil.example', '/%2F%2Fevil.example', '/.evil.example']) {
|
||||
const url = new URL(`https://site.pl${p}`)
|
||||
const res = proxy({ cookies: { get: () => undefined }, headers: new Headers(), nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: '' }, url: url.toString() }) as unknown as { headers: Headers }
|
||||
expect(new URL(res.headers.get('location')!).host, p).toBe('site.pl')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('injection — prototype pollution and operators in stored or sent JSON', () => {
|
||||
it('a consent cookie carrying __proto__ / constructor pollutes nothing', () => {
|
||||
const raw = encodeURIComponent('{"version":1,"__proto__":{"polluted":true},"constructor":{"prototype":{"polluted2":true}},"state":{"analytics":true,"__proto__":{"x":1}}}')
|
||||
const record = readConsentRecord(raw, 1)
|
||||
parseConsent(raw, 1)
|
||||
expect(({} as Record<string, unknown>).polluted).toBeUndefined()
|
||||
expect(({} as Record<string, unknown>).polluted2).toBeUndefined()
|
||||
expect(Object.getPrototypeOf(record)).toBe(Object.prototype)
|
||||
expect(record?.state.analytics).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('log injection', () => {
|
||||
// FINDING F1 (security-audit-2026-12-findings.md): the report's own strings go into the log line as they are.
|
||||
it.fails('F1: a CSP report cannot write a forged line into the server log', async () => {
|
||||
const lines: string[] = []
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation((...a: unknown[]) => {lines.push(a.join(' '))})
|
||||
try {
|
||||
const route = createCspReportRoute()
|
||||
await route(new Request('http://localhost/api/csp-report', { body: JSON.stringify({ 'csp-report': { 'blocked-uri': 'x\n[iapl] admin signed in: [email protected] from 10.0.0.1', 'document-uri': 'https://s.pl/', 'effective-directive': 'script-src' } }), method: 'POST' }))
|
||||
} finally {
|
||||
warn.mockRestore()
|
||||
}
|
||||
expect(lines.join('\n').split('\n')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('denial of service — bodies and batches', () => {
|
||||
it('CSP reports: a chunked body without content-length is cut at the cap (413)', async () => {
|
||||
const res = await createCspReportRoute({ maxBytes: 1024 })(chunked('x'.repeat(200_000)))
|
||||
expect(res.status).toBe(413)
|
||||
})
|
||||
|
||||
it('MCP: a body over the cap is 413 and a batch over the cap is refused before any database work', async () => {
|
||||
const getCachedPayload = vi.fn()
|
||||
const { POST } = createMcpRoute({ config: { defaultLocale: 'pl', locales: ['pl'] } as never, getCachedPayload, rateLimit: false } as never)
|
||||
expect((await POST(chunked(`[${'1,'.repeat(40_000)}1]`))).status).toBe(413)
|
||||
const batch = Array.from({ length: 11 }, (_, i) => ({ id: i, jsonrpc: '2.0', method: 'tools/list' }))
|
||||
expect((await POST(new Request('http://localhost/api/mcp', { body: JSON.stringify(batch), method: 'POST' }))).status).toBe(400)
|
||||
expect(getCachedPayload).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('cache poisoning — one URL, two bodies', () => {
|
||||
// FINDING F3: `Accept: text/markdown` on an HTML URL gets the Markdown copy at the SAME URL, cacheable by a shared
|
||||
// cache for an hour (a day stale) and with no Vary: a CDN that caches HTML can serve the Markdown to every visitor.
|
||||
it.fails('F3: the Markdown answer given at an HTML URL says it varies by Accept (or is not stored by shared caches)', () => {
|
||||
const rewrites: string[] = []
|
||||
const response = () => ({ cookies: { set: () => {} }, headers: new Headers() })
|
||||
const NextResponse = { next: response, redirect: response, rewrite: (u: string | URL) => {rewrites.push(String(u)); return response()} }
|
||||
const proxy = createProxy({ defaultLocale: 'pl', locales: ['pl', 'en'] } as never, { markdown: true, NextResponse })
|
||||
const url = new URL('https://site.pl/pl/o-nas')
|
||||
const res = proxy({ cookies: { get: () => undefined }, headers: new Headers({ accept: 'text/markdown' }), nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: '' }, url: url.toString() }) as unknown as { headers: Headers }
|
||||
expect(rewrites).toHaveLength(1)
|
||||
const md = markdownResponse('# x')
|
||||
const varies = /accept/i.test(res.headers.get('vary') ?? '') || /accept/i.test(md.headers.get('vary') ?? '')
|
||||
const private_ = /private|no-store/.test(md.headers.get('cache-control') ?? '')
|
||||
expect(varies || private_).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* Static security rules (src/modules/doctor/rules/securityCode.ts): each pattern found and not found, the
|
||||
* accept marker, the config checks, the doctor wiring — and the GATE: the plugin's own code and the reference site
|
||||
* hold no place that matches a rule unless test/security-patterns.allow.json judges it.
|
||||
*/
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterAll, describe, expect, test } from 'vitest'
|
||||
|
||||
import { listCodeFiles, scanCode, scanConfigs } from '../src/modules/doctor/rules/securityCode.js'
|
||||
import { runDoctor } from '../src/modules/doctor/run.js'
|
||||
|
||||
const root = path.resolve(import.meta.dirname, '..')
|
||||
const rules = (file: string, code: string) => scanCode(file, code).map((h) => h.rule)
|
||||
|
||||
describe('static security rules — each pattern', () => {
|
||||
test('HTML and JSON printed into the page', () => {
|
||||
expect(rules('src/a.tsx', '<div dangerouslySetInnerHTML={{ __html: post.body }} />')).toEqual(['code-inner-html'])
|
||||
expect(rules('src/a.tsx', '<script dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }} />')).toEqual(['code-inner-html'])
|
||||
expect(scanCode('src/a.tsx', '<script dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }} />')[0].message).toMatch(/<\/script>/)
|
||||
expect(rules('src/a.tsx', "<script dangerouslySetInnerHTML={{ __html: JSON.stringify(s).replace(/</g, '\\\\u003c') }} />")).toEqual([])
|
||||
expect(rules('src/a.tsx', '<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }} />')).toEqual([])
|
||||
expect(rules('src/a.ts', 'el.innerHTML = text')).toEqual(['code-inner-html'])
|
||||
expect(rules('src/a.ts', "el.innerHTML = ''")).toEqual([])
|
||||
expect(rules('src/a.ts', 'el.insertAdjacentHTML("beforeend", x)')).toEqual(['code-inner-html'])
|
||||
})
|
||||
|
||||
test('code from strings and shell commands', () => {
|
||||
expect(rules('src/a.ts', 'eval(code)')).toEqual(['code-eval'])
|
||||
expect(rules('src/a.ts', 'const f = new Function("a", body)')).toEqual(['code-eval'])
|
||||
expect(rules('src/a.ts', 'setTimeout("go()", 10)')).toEqual(['code-eval'])
|
||||
expect(rules('src/a.ts', 'setTimeout(() => go(), 10); retrieval(x)')).toEqual([])
|
||||
expect(rules('src/a.ts', 'execSync(`convert ${file} out.png`)')).toEqual(['code-shell'])
|
||||
expect(rules('src/a.ts', "execFileSync('convert', [file, 'out.png'])")).toEqual([])
|
||||
})
|
||||
|
||||
test('secrets that reach the browser', () => {
|
||||
expect(rules('src/a.ts', 'const k = process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY')).toEqual(['code-public-secret'])
|
||||
expect(rules('src/a.ts', 'const k = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY')).toEqual([])
|
||||
expect(rules('src/a.tsx', "'use client'\nconst s = process.env.PAYLOAD_SECRET")).toEqual(['code-public-secret'])
|
||||
expect(rules('src/a.tsx', 'const s = process.env.PAYLOAD_SECRET')).toEqual([])
|
||||
})
|
||||
|
||||
test('the Local API with access off where a request reaches it', () => {
|
||||
expect(rules('src/app/api/x/route.ts', "await payload.find({ collection: 'orders', overrideAccess: true })")).toEqual(['code-override-access'])
|
||||
expect(rules('src/seed/run.ts', "await payload.find({ collection: 'orders', overrideAccess: true })")).toEqual([])
|
||||
expect(rules('src/app/page.tsx', "await payload.find({ collection: 'orders', user: req.user })")).toEqual(['code-local-api-user'])
|
||||
expect(rules('src/app/page.tsx', "await payload.find({ collection: 'orders', user, overrideAccess: false })")).toEqual([])
|
||||
expect(rules('src/app/page.tsx', "await payload.find({ collection: 'pages', where: { slug: { equals: slug } } })")).toEqual([])
|
||||
})
|
||||
|
||||
test('a where clause from the request', () => {
|
||||
expect(rules('src/app/api/x/route.ts', "payload.find({ collection: 'pages', where: req.query.where })")).toEqual(['code-raw-where'])
|
||||
expect(rules('src/app/api/x/route.ts', "payload.find({ collection: 'pages', where: JSON.parse(searchParams.get('w')) })")).toEqual(['code-raw-where'])
|
||||
expect(rules('src/app/api/x/route.ts', "payload.find({ collection: 'pages', where: { slug: { equals: String(params.slug) } } })")).toEqual([])
|
||||
})
|
||||
|
||||
test('redirects and fetches to an address from the request', () => {
|
||||
expect(rules('src/app/x/page.tsx', "redirect(searchParams.get('next'))")).toEqual(['code-open-redirect'])
|
||||
expect(rules('src/app/x/route.ts', "return NextResponse.redirect(new URL(req.nextUrl.searchParams.get('to'), req.url))")).toEqual(['code-open-redirect'])
|
||||
expect(rules('src/app/x/page.tsx', "redirect('/pl')")).toEqual([])
|
||||
expect(rules('src/app/x/route.ts', 'const r = await fetch(body.url)')).toEqual(['code-ssrf'])
|
||||
expect(rules('src/app/x/route.ts', "const r = await fetch(searchParams.get('u'))")).toEqual(['code-ssrf'])
|
||||
expect(rules('src/app/x/route.ts', "const r = await fetch('https://api.example.com/x', { body: JSON.stringify(body) })")).toEqual([])
|
||||
})
|
||||
|
||||
test('a place accepted with its reason; comments do not count', () => {
|
||||
expect(rules('src/a.tsx', '// iapl-security-ok: escaped by toSafeHtml above\n<div dangerouslySetInnerHTML={{ __html: html }} />')).toEqual([])
|
||||
expect(rules('src/a.ts', 'eval(x) // iapl-security-ok: build-time only')).toEqual([])
|
||||
expect(rules('src/a.ts', '// eval(x) in a comment\n/* new Function() */')).toEqual([])
|
||||
})
|
||||
|
||||
test('config settings that open a door', () => {
|
||||
const next = (code: string) => scanConfigs({ code, file: 'next.config.ts' }, null).map((f) => f.severity)
|
||||
expect(next("images: { dangerouslyAllowSVG: true }")).toEqual(['error'])
|
||||
expect(next("images: { dangerouslyAllowSVG: true, contentSecurityPolicy: \"sandbox\" }")).toEqual([])
|
||||
expect(next("images: { remotePatterns: [{ hostname: '**' }] }")).toEqual(['warning'])
|
||||
expect(next("experimental: { serverActions: { allowedOrigins: ['*'] } }")).toEqual(['error'])
|
||||
const payload = (code: string) => scanConfigs(null, { code, file: 'src/payload.config.ts' }).length
|
||||
expect(payload("cors: '*', debug: true, graphQL: { disableIntrospectionInProduction: false }, maxDepth: 50")).toBe(4)
|
||||
expect(payload('cors: [process.env.NEXT_PUBLIC_SERVER_URL], maxDepth: 10')).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('static security rules — in the doctor', () => {
|
||||
const dirs: string[] = []
|
||||
afterAll(() => {for (const d of dirs) {rmSync(d, { force: true, recursive: true })}})
|
||||
|
||||
test('iapl-doctor --only security reports a project\'s own unsafe code, and an iapl-doctor.json entry silences one file', async () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), 'iapl-sec-'))
|
||||
dirs.push(dir)
|
||||
const files: Record<string, string> = {
|
||||
'package.json': JSON.stringify({ name: 'x', dependencies: {} }),
|
||||
'src/app/(frontend)/[locale]/page.tsx': '<div dangerouslySetInnerHTML={{ __html: page.html }} />',
|
||||
'src/app/api/orders/route.ts': "export const GET = async (req) => Response.json(await payload.find({ collection: 'orders', where: req.query.where, overrideAccess: true }))",
|
||||
'src/seed/index.ts': "await payload.find({ collection: 'orders', overrideAccess: true })",
|
||||
}
|
||||
for (const [rel, content] of Object.entries(files)) {
|
||||
mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true })
|
||||
writeFileSync(path.join(dir, rel), content)
|
||||
}
|
||||
const report = await runDoctor({ offline: true, only: ['code-patterns'], packageRoot: root, root: dir, writeSeen: false })
|
||||
const found = report.findings.filter((f) => !f.silenced).map((f) => `${f.rule} ${f.file}`).sort()
|
||||
expect(found).toEqual([
|
||||
'code-inner-html src/app/(frontend)/[locale]/page.tsx',
|
||||
'code-override-access src/app/api/orders/route.ts',
|
||||
'code-raw-where src/app/api/orders/route.ts',
|
||||
])
|
||||
const silenced = await runDoctor({
|
||||
config: { rules: { 'code-override-access': { files: ['src/app/api/**'], off: true, reason: 'orders are public in this shop' } } },
|
||||
offline: true, only: ['security'], packageRoot: root, root: dir, writeSeen: false,
|
||||
})
|
||||
expect(silenced.findings.find((f) => f.rule === 'code-override-access')?.silenced, JSON.stringify(silenced.findings.map((f) => [f.rule, f.message.slice(0, 80)]))).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GATE: the plugin and the reference site hold only judged places', () => {
|
||||
test('every hit is in test/security-patterns.allow.json with a reason, and no count grew', () => {
|
||||
const allow = (JSON.parse(readFileSync(path.join(root, 'test/security-patterns.allow.json'), 'utf8')) as { entries: Record<string, { count: number; reason: string }> }).entries
|
||||
const counts = new Map<string, number>()
|
||||
const where = new Map<string, string[]>()
|
||||
for (const [base, start, prefix] of [[root, 'src', ''], [path.join(root, 'reference'), 'src', 'reference/'], [root, 'bin', ''], [root, 'scripts', '']] as const) {
|
||||
for (const file of listCodeFiles(base, start)) {
|
||||
for (const hit of scanCode(file, readFileSync(path.join(base, file), 'utf8'))) {
|
||||
const key = `${hit.rule} ${prefix}${hit.file}`
|
||||
counts.set(key, (counts.get(key) ?? 0) + 1)
|
||||
where.set(key, [...(where.get(key) ?? []), `${prefix}${hit.file}:${hit.line} ${hit.text}`])
|
||||
}
|
||||
}
|
||||
}
|
||||
const problems: string[] = []
|
||||
for (const [key, n] of counts) {
|
||||
const entry = allow[key]
|
||||
if (!entry) {problems.push(`NOT JUDGED ${key} (${n}):\n ${where.get(key)!.join('\n ')}`)} else if (n > entry.count) {problems.push(`MORE THAN JUDGED ${key}: ${n} > ${entry.count}\n ${where.get(key)!.join('\n ')}`)}
|
||||
}
|
||||
for (const [key, entry] of Object.entries(allow)) {
|
||||
if (!entry.reason?.trim() || /TODO/i.test(entry.reason)) {problems.push(`no reason: ${key}`)}
|
||||
if ((counts.get(key) ?? 0) < entry.count) {console.warn(`[security-patterns] ${key}: ${counts.get(key) ?? 0} now, ${entry.count} judged — lower the count`)}
|
||||
}
|
||||
expect(problems, problems.join('\n')).toEqual([])
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user