diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index aeb4d64..95f1348 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -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: `. Expect new warnings on an existing site the first time; judge each. +> - **Attack probes**: `iapl-doctor --url https:// --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 diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 203589b..c71ff17 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -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: ` (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:// --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 | diff --git a/docs/agent/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md index 1766d0a..efadd7c 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -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) | diff --git a/docs/agent/skills/iapl-audit/SKILL.md b/docs/agent/skills/iapl-audit/SKILL.md index e6aea47..65918cc 100644 --- a/docs/agent/skills/iapl-audit/SKILL.md +++ b/docs/agent/skills/iapl-audit/SKILL.md @@ -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:// --only live-probes`. The code side: + `pnpm exec iapl-doctor --only security` (`code-patterns`, `config-dangerous`); a correct place gets + `// iapl-security-ok: `. 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 diff --git a/docs/agent/skills/iapl-audit/resources/attack-probes.spec.template.ts b/docs/agent/skills/iapl-audit/resources/attack-probes.spec.template.ts new file mode 100644 index 0000000..6b46dd8 --- /dev/null +++ b/docs/agent/skills/iapl-audit/resources/attack-probes.spec.template.ts @@ -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:// --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) + }) +} diff --git a/docs/agent/skills/iapl-doctor/SKILL.md b/docs/agent/skills/iapl-doctor/SKILL.md index f2f6a05..4a7b6c0 100644 --- a/docs/agent/skills/iapl-doctor/SKILL.md +++ b/docs/agent/skills/iapl-doctor/SKILL.md @@ -46,6 +46,16 @@ Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`. `--url ` · `--staging` (must be noindex) · `--admin-route ` · `--deep` · `--env-file ` (checks `_prod`) · `--only` / `--skip ` · `--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://` 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: `. + 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) diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index 87cab14..2105fa5 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -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 ` 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: `. 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` diff --git a/docs/doctor.md b/docs/doctor.md index b49c4aa..86aeaaf 100644 --- a/docs/doctor.md +++ b/docs/doctor.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 ` ends the script (JsonLdGraph, or .replace(/ = { + '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): 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() + 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}: (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:` style settings in iapl-doctor.json. */ +export const LIVE_PROBE_IDS = ATTACK_PROBES.filter((p) => p.live).map((p) => p.id) diff --git a/src/modules/doctor/run.ts b/src/modules/doctor/run.ts index 2081504..10752a5 100644 --- a/src/modules/doctor/run.ts +++ b/src/modules/doctor/run.ts @@ -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, diff --git a/src/modules/security/attackProbes.ts b/src/modules/security/attackProbes.ts new file mode 100644 index 0000000..be6d6da --- /dev/null +++ b/src/modules/security/attackProbes.ts @@ -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; method?: string }) => Promise + /** 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 + 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(/]+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() + 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: 'a@b.pl', 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 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: 'a@b.pl', 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> { + 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 +} diff --git a/test/security-patterns.allow.json b/test/security-patterns.allow.json new file mode 100644 index 0000000..7bd8554 --- /dev/null +++ b/test/security-patterns.allow.json @@ -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: ' ' → { 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)" } + } +} diff --git a/test/securityClasses.test.ts b/test/securityClasses.test.ts new file mode 100644 index 0000000..923948c --- /dev/null +++ b/test/securityClasses.test.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 = ['', '', '">', '
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,', '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 ,