diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index e78a8b1..4348444 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -9,6 +9,42 @@ versions at once, go through every "Requires project changes" section in order, version you have. A new release = a new section at the top; we remove the oldest ones only once there are more than 20. +## 1.17.1 — DRAFT (security group C: files, jobs, outside-in tests; not released) + +> Draft lines from the IAWL-ideas session C (branch `claude/security-c-files-jobs-tests-cfba70`); the integration +> session merges them with A and B. No option, schema, migration or import-map change. Nothing locks anybody out. + +### Security +- **The proxy matcher skipped pages that only start with `api`, `admin` or `_next`.** The documented literal + `'/((?!api|admin|_next|.*\\..*).*)'` did not end those names at "/", so `/administracja`, `/admin-guide` or `/apis` + skipped the proxy: no locale redirect, and on a single-locale site with `createProxy({ csp })` no CSP. The + literal is now `'/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'` (`DEFAULT_PROXY_MATCHER`, the reference site, the + starter, the docs). **Requires a project change:** Next reads the matcher from each site's `proxy.ts`, so paste + the new literal there; `iapl-doctor` reports the old one (`proxy-matcher`, warning). +- **Form files: a program inside a DOCX / XLSX named `setup.exe.` or `setup.exe ` passed** (Windows drops the + trailing dot or space when the file is extracted). Trailing dots and spaces are ignored now. +- **`iapl-skills --dest` compared the paths before resolving links**: `--dest `, `..` or `/` passed + the "not the project root" rule and lost the `iapl-*` folders there. The paths are resolved first; a folder that + is the project root or holds it is refused. A folder elsewhere (shared skills) still works. +- **The starter bundle followed symbolic links**: a link committed under `reference/` would have shipped its + target's content in the published bundle (none existed). Links are refused; `iapl create` also refuses a bundle + path that leaves the new folder. + +### Added +- **`routes:check`** — every public route (REST, GraphQL, Next route files) against a committed snapshot with one + reason per entry; fails on a route nobody has judged. `listPublicRoutes`, `listNextRouteFiles`, + `compareRouteSnapshot`, `updateRouteSnapshot` (`@intecion/ipal-kit`), `runRouteCheck` (`@intecion/ipal-kit/doctor`); + a template in the `iapl-audit` skill (security.md "Routes nobody has judged"). +- **Closed doors from outside** — a Playwright template that asks every door that must stay closed as an anonymous + visitor, a customer and an editor on a production build (security.md "Closed doors from outside"); in this + repository part of `pnpm e2e:built`, in both bundlers. +- `iapl-doctor` rule **`proxy-matcher`** (above). + +### Changed +- The plugin's own `package.json` declares `@swc/core` in `pnpm.ignoredBuiltDependencies`: its install script only + checks the native binary, which the build already has. pnpm no longer asks about it (repository only; no effect on + projects). + ## 1.17.0 — the plugin is called IAPL; mail works with no setup > **Read before upgrading.** In this order: the security follow-ups prepared as 1.16.8 (never released on their diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 02a1c5b..6a7fe18 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1411,6 +1411,8 @@ its own tests). Order from the cheapest: | Build | `pnpm build` — page routes `●` (SSG), not `ƒ` | before every "done" | | Smoke (Playwright) | `iapl-audit/resources/smoke.spec.template.ts` → `tests/smoke.spec.ts`: all URLs from the sitemap 200 + title + one h1, 404, GEO routes, banner, form end-to-end | before handover and after every IAPL update | | 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 | | 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/skills/iapl-audit/SKILL.md b/docs/agent/skills/iapl-audit/SKILL.md index f4eef8c..21d0ea5 100644 --- a/docs/agent/skills/iapl-audit/SKILL.md +++ b/docs/agent/skills/iapl-audit/SKILL.md @@ -51,6 +51,13 @@ names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` — ## What the script does not check (do it by hand) +- **Closed doors and judged routes** (security.md "Closed doors from outside", "Routes nobody has judged"): + `resources/closed-doors.spec.template.ts` → `tests/closed-doors.spec.ts` (add the project's own doors; run on a + production build as anonymous, customer and editor) and `resources/routes.template.ts` → `tests/routes.ts` + (`pnpm payload run tests/routes.ts update` once, write a reason per route, commit the snapshot; then + `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. + - **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/closed-doors.spec.template.ts b/docs/agent/skills/iapl-audit/resources/closed-doors.spec.template.ts new file mode 100644 index 0000000..816abbf --- /dev/null +++ b/docs/agent/skills/iapl-audit/resources/closed-doors.spec.template.ts @@ -0,0 +1,105 @@ +/** + * Closed doors from outside — every door of the site that must stay CLOSED, asked on a PRODUCTION build (`pnpm build + * && pnpm start`: Payload's GraphQL playground and introspection, among others, behave differently outside + * production) as an anonymous visitor, a customer and an editor (IAPL docs/security.md "Closed doors from outside"). + * Copy to tests/closed-doors.spec.ts and run: + * + * BASE_URL=http://localhost:3000 pnpm exec playwright test tests/closed-doors.spec.ts + * + * Callers (each is skipped when its variables are missing): + * anonymous always; + * customer a site with a visitor login collection: E2E_CUSTOMER_COLLECTION (its slug), E2E_CUSTOMER_EMAIL, + * E2E_CUSTOMER_PASSWORD — an existing test account of that collection; + * editor E2E_EDITOR_EMAIL, E2E_EDITOR_PASSWORD, E2E_EDITOR_TOTP_SECRET — a staff test account with the role + * `editor` and a known 2FA secret, on a LOCAL or staging database only (never production accounts). + * Add the project's own doors to DOORS (a custom endpoint, a collection only staff may read, a global with secrets). + * A write door is asked with a body that changes nothing when the door is open (an id that does not exist, `{}`). + */ +import { type APIRequestContext, expect, test } from '@playwright/test' +import { createHmac } from 'node:crypto' + +type Caller = 'anonymous' | 'customer' | 'editor' +type Answer = { body: unknown; status: number } +type Door = { body?: unknown; closed?: (a: Answer) => boolean; closedFor: Caller[]; graphql?: string; method?: 'DELETE' | 'GET' | 'PATCH' | 'POST'; name: string; path?: string } + +const BASE = (process.env.BASE_URL ?? 'http://localhost:3000').replace(/\/$/, '') +const ALL: Caller[] = ['anonymous', 'customer', 'editor'] +const OUTSIDERS: Caller[] = ['anonymous', 'customer'] +const NO_ID = '000000000000000000000000' // MongoDB; use 999999999 on Postgres / SQLite +const refused = ({ status }: Answer) => [401, 403, 404].includes(status) +const status = (code: number) => (a: Answer) => a.status === code +const noData = (field: string) => ({ body, status: s }: Answer) => { + const b = body as { data?: Record | null; errors?: unknown[] } | null + return s >= 400 || Boolean(b?.errors?.length) || b?.data?.[field] == null +} + +const DOORS: Door[] = [ + // the plugin's own — keep them + { closedFor: ALL, name: 'Site integrations cannot be read', path: '/api/globals/site-integrations' }, + { body: {}, closedFor: ALL, method: 'POST', name: 'Site integrations cannot be saved', path: '/api/globals/site-integrations' }, + { closedFor: ALL, graphql: '{ SiteIntegration { smtpHost } }', closed: noData('SiteIntegration'), name: 'Site integrations over GraphQL' }, + { closedFor: ALL, name: 'the key-value store (2FA counts, the mail-service token)', path: '/api/payload-kv' }, + { closedFor: ALL, name: 'the consent log', path: '/api/consent-records' }, + { closedFor: ALL, name: 'the deep doctor status without its token', path: '/api/ipal/doctor', closed: status(404) }, + { closedFor: ALL, method: 'POST', name: 'a test e-mail', path: '/api/ipal/test-email', body: { to: 'nobody@example.com' } }, + { closedFor: ALL, name: 'the mail-service status', path: '/api/iapl/mail-relay/status' }, + { closedFor: ALL, method: 'POST', name: 'the crawler\'s call-back without its token', path: '/api/ipal/cookie-crawl/results', body: { jobId: 'x', ok: true } }, + { closedFor: OUTSIDERS, method: 'POST', name: 'a crawl without the schedule\'s token', path: '/api/ipal/cookie-crawl' }, + { closedFor: OUTSIDERS, name: 'form submissions', path: '/api/form-submissions' }, + { body: { email: 'door@example.com', password: 'Door-Password-1234', roles: ['admin'] }, closedFor: ALL, method: 'POST', name: 'nobody creates a staff account', path: '/api/users', closed: status(403) }, + { body: { email: 'first@example.com', password: 'Door-Password-1234' }, closedFor: ALL, method: 'POST', name: 'the first-user route once an account exists', path: '/api/users/first-register', closed: status(403) }, + { body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'Site settings cannot be saved', path: '/api/globals/site-settings', closed: status(403) }, + { closedFor: ALL, name: 'the GraphQL playground (production)', path: '/api/graphql-playground', closed: status(404) }, + { closedFor: ALL, graphql: '{ __schema { queryType { name } } }', closed: ({ body }) => Boolean((body as { errors?: unknown[] })?.errors?.length), name: 'GraphQL introspection (production)' }, + { closedFor: ALL, name: 'Payload\'s job queue (a site without jobs)', path: '/api/payload-jobs/run', closed: status(404) }, + // the project's own doors: add them here + // { closedFor: OUTSIDERS, body: {}, method: 'PATCH', name: 'pages cannot be changed', path: `/api/pages/${NO_ID}`, closed: status(403) }, +] + +/** RFC 6238 TOTP (SHA-1, 6 digits, 30 s) for a base32 secret. */ +function totp(secret: string): string { + const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' + let bits = '' + for (const ch of secret.replace(/=+$/, '').toUpperCase()) {bits += alphabet.indexOf(ch).toString(2).padStart(5, '0')} + const key = Buffer.from((bits.match(/.{8}/g) ?? []).map((b) => parseInt(b, 2))) + const counter = Buffer.alloc(8) + counter.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 30_000))) + const h = createHmac('sha1', key).update(counter).digest() + return (((h.readUInt32BE(h[h.length - 1]! & 0xf) & 0x7fffffff) % 1_000_000).toString().padStart(6, '0')) +} + +async function signIn(caller: Caller, playwright: { request: { newContext: (o: object) => Promise } }): Promise { + const api = await playwright.request.newContext({ baseURL: BASE, extraHTTPHeaders: { origin: BASE } }) + const env = process.env + if (caller === 'customer') { + if (!env.E2E_CUSTOMER_COLLECTION || !env.E2E_CUSTOMER_EMAIL || !env.E2E_CUSTOMER_PASSWORD) {return null} + expect((await api.post(`/api/${env.E2E_CUSTOMER_COLLECTION}/login`, { data: { email: env.E2E_CUSTOMER_EMAIL, password: env.E2E_CUSTOMER_PASSWORD } })).status()).toBe(200) + } + if (caller === 'editor') { + if (!env.E2E_EDITOR_EMAIL || !env.E2E_EDITOR_PASSWORD || !env.E2E_EDITOR_TOTP_SECRET) {return null} + expect((await api.post('/api/users/login', { data: { email: env.E2E_EDITOR_EMAIL, password: env.E2E_EDITOR_PASSWORD } })).status()).toBe(200) + expect((await (await api.post('/api/verify-totp', { data: { token: totp(env.E2E_EDITOR_TOTP_SECRET) } })).json()).ok).toBe(true) + } + return api +} + +for (const caller of ALL) { + test.describe(`closed doors as ${caller}`, () => { + let api: APIRequestContext | null = null + test.beforeAll(async ({ playwright }) => { + api = await signIn(caller, playwright) + }) + for (const door of DOORS.filter((d) => d.closedFor.includes(caller))) { + test(door.name, async () => { + test.skip(!api, `no ${caller} test account configured`) + const res = door.graphql + ? await api!.post('/api/graphql', { data: { query: door.graphql } }) + : await api!.fetch(door.path!, { data: door.body, maxRedirects: 0, method: door.method ?? 'GET' }) + const text = await res.text() + let body: unknown = text + try { body = JSON.parse(text) } catch { /* not JSON */ } + expect((door.closed ?? refused)({ body, status: res.status() }), `${door.graphql ?? door.path} → ${res.status()} ${text.slice(0, 200)}`).toBe(true) + }) + } + }) +} diff --git a/docs/agent/skills/iapl-audit/resources/routes.template.ts b/docs/agent/skills/iapl-audit/resources/routes.template.ts new file mode 100644 index 0000000..80f6819 --- /dev/null +++ b/docs/agent/skills/iapl-audit/resources/routes.template.ts @@ -0,0 +1,24 @@ +/** + * Routes nobody has judged — every public route of this site (REST, GraphQL, Next route files) against the judged + * list in tests/routes.snapshot.json (IAPL docs/security.md "Routes nobody has judged"). Reads the config, never the + * database: the same on MongoDB, Postgres and SQLite. Copy to tests/routes.ts, then: + * + * pnpm payload run tests/routes.ts update → writes tests/routes.snapshot.json, every route with an EMPTY reason + * (write one line per route: who may use it and why it is open, or that it is closed and to whom) + * pnpm payload run tests/routes.ts → fails on a route nobody has judged or an entry without a reason + * + * Run it in CI and after every Payload / IAPL / plugin upgrade; an upgrade that adds a route fails here until somebody + * judges it (`update` adds it with an empty reason; review the diff). `payload run` drops `--flags`: the word is `update`. + */ +import config from '@payload-config' +import { runRouteCheck } from '@intecion/ipal-kit/doctor' + +process.exit( + await runRouteCheck({ + config: await config, + snapshot: 'tests/routes.snapshot.json', + // appDir: 'src/app', // where the Next routes live + // graphql: false, // a site that deleted app/(payload)/api/graphql + update: process.argv.slice(2).includes('update'), + }), +) diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 0e52b53..53fe0a2 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -25,6 +25,14 @@ the MANDATORY SET (GEO: llms-full, Markdown, MCP; R2; Turnstile through `getTurnstileConfig`…). Wire each one according to PROGRAMISTA §2 — it is part of the update, not an extra. Skip one only with a client decision in `AGENTS.md` (`iapl-audit-skip:`). +**→ 1.17.1:** (1) `src/proxy.ts`: replace the matcher literal with +`['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)']` (i18n.md "Next matcher"; `iapl-doctor` rule `proxy-matcher`). +The old one skipped every page whose first segment only starts with `api`, `admin` or `_next` (`/administracja`): +no locale redirect, no proxy CSP there. Verify on a build: `curl -sI localhost:3000/administracja` → 307 to +`/pl/administracja`; `/admin` and `/api/health` unchanged. (2) If the project has `tests/routes.ts`: run +`pnpm payload run tests/routes.ts update`, judge the new entries, commit (after EVERY Payload / IAPL upgrade). New +projects: add the closed-doors spec and the route check (iapl-audit "What the script does not check"). + **1.8.x → 1.9.0 (PROGRAMISTA §6, items 17–21):** `twoFactor.plugin` required; `getTurnstileConfig` instead of `turnstileSiteKey` (with both keys set the token is required — check that every form has the widget); `clientIp(await headers())` in diff --git a/docs/security.md b/docs/security.md index 05e6a40..3cdd189 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1078,6 +1078,54 @@ loosens it. **`'all'` checks nothing** — no role and no second factor: whoever the full text, as before. The components take the same as props (`details`, `audience`). +## Closed doors from outside (`closed-doors.spec`) + +Access rules are tested from OUTSIDE, on a **production build** (`pnpm build && pnpm start`): some doors behave +differently outside production (Payload's GraphQL playground and introspection), and a bundler renames every +function (a rule told apart by its name was skipped there in 1.16.7). The test asks every door that must stay closed +as three callers and fails when one opens: + +- **anonymous** — no session; +- **customer** — an account of a visitor login collection (a shop, a member zone), if the site has one; +- **editor** — a staff account with the role `editor`, signed in with the second factor. + +**In a project:** copy `.agents/skills/iapl-audit/resources/closed-doors.spec.template.ts` to +`tests/closed-doors.spec.ts`, set the test accounts' variables (the file's header: `E2E_CUSTOMER_*`, `E2E_EDITOR_*`, +local or staging database only) and add the project's own doors to `DOORS`: each names who it is closed for and, +where 401 / 403 / 404 is not the whole story, what a closed answer looks like. A write door is asked with a body +that changes nothing when it is open (a document id that does not exist, `{}`): an open door then answers 404 or +400 instead of 403. Run it before every release and after every Payload / IAPL upgrade. Verify: the run lists one +test per door and caller; temporarily set a collection's `read: () => true` where a door says closed and the test +fails. + +**In the plugin repository** it is `reference/e2e/closed-doors.ts` (the doors) and `closed-doors.spec.ts`, run by +`pnpm e2e:built` after a webpack and a Turbopack build; the customer is the late-staff fixture's self-signing-up +`e2e-visitors` collection, the editor `e2e/create-test-admin.ts`'s `…-editor@` account. A door that is still open +for a caller while the owner decides is listed under `openFor` and asserted OPEN (`test.fail`): the day somebody +closes it, the run says "passed unexpectedly" and the entry moves to `closedFor`. + +## Routes nobody has judged (`routes:check`) + +A Payload, plugin or project change can add a public route without anybody noticing (IAWL idea 34). `routes:check` +lists every door a built config opens — each REST route of every collection, global and root endpoint (Payload's +own and the plugin's), each GraphQL query and mutation, each Next route file with its methods — and compares the list +with a committed snapshot in which **every entry carries one line saying who may use it and why**. It fails on a +route that is not in the snapshot and on an entry without a reason (or one that still says `TODO`); routes that went +away are listed, not failed. The list comes from the config only, never from the database, so it is the same on +MongoDB, Postgres and SQLite. + +**In a project:** copy `.agents/skills/iapl-audit/resources/routes.template.ts` to `tests/routes.ts`; `pnpm payload +run tests/routes.ts update` writes `tests/routes.snapshot.json` with an empty reason per route; write the reasons +(the reference site's `e2e/routes.snapshot.json` in the plugin repository shows the style), commit, and run +`pnpm payload run tests/routes.ts` in CI. After an upgrade: `update` again, judge the new entries, review the diff. +(`payload run` drops `--flags`, so the word is `update`.) Building blocks, for a test of your own: +`listPublicRoutes(config, { graphqlSchema, routeFiles })`, `listNextRouteFiles`, `compareRouteSnapshot`, +`updateRouteSnapshot` (`@intecion/ipal-kit`) and `runRouteCheck` (`@intecion/ipal-kit/doctor`, Node only). Verify: add +a root endpoint to the config and the check names it as "not judged". + +**In the plugin repository:** `pnpm routes:check` (`--update` after a Payload upgrade) on the reference site, also +the first step of `pnpm e2e:built`; the test fixtures are switched off for it. + ## Turn off, override, extend - **Stored secrets:** `secrets: { writeOnly: false }`, `secrets: { reenterOnChange: false }`; `writeOnlySecret` / diff --git a/package.json b/package.json index 46b378b..91d421c 100644 --- a/package.json +++ b/package.json @@ -129,6 +129,7 @@ "prepare": "pnpm build", "prepublishOnly": "pnpm clean && pnpm build && pnpm build:starter && pnpm test:int && pnpm starter:gate", "reference:index": "node scripts/reference-index.mjs", + "routes:check": "node scripts/routes-check.mjs", "starter:gate": "node scripts/starter-gate.mjs", "test": "pnpm test:int && pnpm test:e2e", "test:e2e": "playwright test", diff --git a/reference/.agents/skills/iapl-audit/SKILL.md b/reference/.agents/skills/iapl-audit/SKILL.md index f4eef8c..21d0ea5 100644 --- a/reference/.agents/skills/iapl-audit/SKILL.md +++ b/reference/.agents/skills/iapl-audit/SKILL.md @@ -51,6 +51,13 @@ names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` — ## What the script does not check (do it by hand) +- **Closed doors and judged routes** (security.md "Closed doors from outside", "Routes nobody has judged"): + `resources/closed-doors.spec.template.ts` → `tests/closed-doors.spec.ts` (add the project's own doors; run on a + production build as anonymous, customer and editor) and `resources/routes.template.ts` → `tests/routes.ts` + (`pnpm payload run tests/routes.ts update` once, write a reason per route, commit the snapshot; then + `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. + - **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/reference/.agents/skills/iapl-audit/resources/closed-doors.spec.template.ts b/reference/.agents/skills/iapl-audit/resources/closed-doors.spec.template.ts new file mode 100644 index 0000000..816abbf --- /dev/null +++ b/reference/.agents/skills/iapl-audit/resources/closed-doors.spec.template.ts @@ -0,0 +1,105 @@ +/** + * Closed doors from outside — every door of the site that must stay CLOSED, asked on a PRODUCTION build (`pnpm build + * && pnpm start`: Payload's GraphQL playground and introspection, among others, behave differently outside + * production) as an anonymous visitor, a customer and an editor (IAPL docs/security.md "Closed doors from outside"). + * Copy to tests/closed-doors.spec.ts and run: + * + * BASE_URL=http://localhost:3000 pnpm exec playwright test tests/closed-doors.spec.ts + * + * Callers (each is skipped when its variables are missing): + * anonymous always; + * customer a site with a visitor login collection: E2E_CUSTOMER_COLLECTION (its slug), E2E_CUSTOMER_EMAIL, + * E2E_CUSTOMER_PASSWORD — an existing test account of that collection; + * editor E2E_EDITOR_EMAIL, E2E_EDITOR_PASSWORD, E2E_EDITOR_TOTP_SECRET — a staff test account with the role + * `editor` and a known 2FA secret, on a LOCAL or staging database only (never production accounts). + * Add the project's own doors to DOORS (a custom endpoint, a collection only staff may read, a global with secrets). + * A write door is asked with a body that changes nothing when the door is open (an id that does not exist, `{}`). + */ +import { type APIRequestContext, expect, test } from '@playwright/test' +import { createHmac } from 'node:crypto' + +type Caller = 'anonymous' | 'customer' | 'editor' +type Answer = { body: unknown; status: number } +type Door = { body?: unknown; closed?: (a: Answer) => boolean; closedFor: Caller[]; graphql?: string; method?: 'DELETE' | 'GET' | 'PATCH' | 'POST'; name: string; path?: string } + +const BASE = (process.env.BASE_URL ?? 'http://localhost:3000').replace(/\/$/, '') +const ALL: Caller[] = ['anonymous', 'customer', 'editor'] +const OUTSIDERS: Caller[] = ['anonymous', 'customer'] +const NO_ID = '000000000000000000000000' // MongoDB; use 999999999 on Postgres / SQLite +const refused = ({ status }: Answer) => [401, 403, 404].includes(status) +const status = (code: number) => (a: Answer) => a.status === code +const noData = (field: string) => ({ body, status: s }: Answer) => { + const b = body as { data?: Record | null; errors?: unknown[] } | null + return s >= 400 || Boolean(b?.errors?.length) || b?.data?.[field] == null +} + +const DOORS: Door[] = [ + // the plugin's own — keep them + { closedFor: ALL, name: 'Site integrations cannot be read', path: '/api/globals/site-integrations' }, + { body: {}, closedFor: ALL, method: 'POST', name: 'Site integrations cannot be saved', path: '/api/globals/site-integrations' }, + { closedFor: ALL, graphql: '{ SiteIntegration { smtpHost } }', closed: noData('SiteIntegration'), name: 'Site integrations over GraphQL' }, + { closedFor: ALL, name: 'the key-value store (2FA counts, the mail-service token)', path: '/api/payload-kv' }, + { closedFor: ALL, name: 'the consent log', path: '/api/consent-records' }, + { closedFor: ALL, name: 'the deep doctor status without its token', path: '/api/ipal/doctor', closed: status(404) }, + { closedFor: ALL, method: 'POST', name: 'a test e-mail', path: '/api/ipal/test-email', body: { to: 'nobody@example.com' } }, + { closedFor: ALL, name: 'the mail-service status', path: '/api/iapl/mail-relay/status' }, + { closedFor: ALL, method: 'POST', name: 'the crawler\'s call-back without its token', path: '/api/ipal/cookie-crawl/results', body: { jobId: 'x', ok: true } }, + { closedFor: OUTSIDERS, method: 'POST', name: 'a crawl without the schedule\'s token', path: '/api/ipal/cookie-crawl' }, + { closedFor: OUTSIDERS, name: 'form submissions', path: '/api/form-submissions' }, + { body: { email: 'door@example.com', password: 'Door-Password-1234', roles: ['admin'] }, closedFor: ALL, method: 'POST', name: 'nobody creates a staff account', path: '/api/users', closed: status(403) }, + { body: { email: 'first@example.com', password: 'Door-Password-1234' }, closedFor: ALL, method: 'POST', name: 'the first-user route once an account exists', path: '/api/users/first-register', closed: status(403) }, + { body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'Site settings cannot be saved', path: '/api/globals/site-settings', closed: status(403) }, + { closedFor: ALL, name: 'the GraphQL playground (production)', path: '/api/graphql-playground', closed: status(404) }, + { closedFor: ALL, graphql: '{ __schema { queryType { name } } }', closed: ({ body }) => Boolean((body as { errors?: unknown[] })?.errors?.length), name: 'GraphQL introspection (production)' }, + { closedFor: ALL, name: 'Payload\'s job queue (a site without jobs)', path: '/api/payload-jobs/run', closed: status(404) }, + // the project's own doors: add them here + // { closedFor: OUTSIDERS, body: {}, method: 'PATCH', name: 'pages cannot be changed', path: `/api/pages/${NO_ID}`, closed: status(403) }, +] + +/** RFC 6238 TOTP (SHA-1, 6 digits, 30 s) for a base32 secret. */ +function totp(secret: string): string { + const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' + let bits = '' + for (const ch of secret.replace(/=+$/, '').toUpperCase()) {bits += alphabet.indexOf(ch).toString(2).padStart(5, '0')} + const key = Buffer.from((bits.match(/.{8}/g) ?? []).map((b) => parseInt(b, 2))) + const counter = Buffer.alloc(8) + counter.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 30_000))) + const h = createHmac('sha1', key).update(counter).digest() + return (((h.readUInt32BE(h[h.length - 1]! & 0xf) & 0x7fffffff) % 1_000_000).toString().padStart(6, '0')) +} + +async function signIn(caller: Caller, playwright: { request: { newContext: (o: object) => Promise } }): Promise { + const api = await playwright.request.newContext({ baseURL: BASE, extraHTTPHeaders: { origin: BASE } }) + const env = process.env + if (caller === 'customer') { + if (!env.E2E_CUSTOMER_COLLECTION || !env.E2E_CUSTOMER_EMAIL || !env.E2E_CUSTOMER_PASSWORD) {return null} + expect((await api.post(`/api/${env.E2E_CUSTOMER_COLLECTION}/login`, { data: { email: env.E2E_CUSTOMER_EMAIL, password: env.E2E_CUSTOMER_PASSWORD } })).status()).toBe(200) + } + if (caller === 'editor') { + if (!env.E2E_EDITOR_EMAIL || !env.E2E_EDITOR_PASSWORD || !env.E2E_EDITOR_TOTP_SECRET) {return null} + expect((await api.post('/api/users/login', { data: { email: env.E2E_EDITOR_EMAIL, password: env.E2E_EDITOR_PASSWORD } })).status()).toBe(200) + expect((await (await api.post('/api/verify-totp', { data: { token: totp(env.E2E_EDITOR_TOTP_SECRET) } })).json()).ok).toBe(true) + } + return api +} + +for (const caller of ALL) { + test.describe(`closed doors as ${caller}`, () => { + let api: APIRequestContext | null = null + test.beforeAll(async ({ playwright }) => { + api = await signIn(caller, playwright) + }) + for (const door of DOORS.filter((d) => d.closedFor.includes(caller))) { + test(door.name, async () => { + test.skip(!api, `no ${caller} test account configured`) + const res = door.graphql + ? await api!.post('/api/graphql', { data: { query: door.graphql } }) + : await api!.fetch(door.path!, { data: door.body, maxRedirects: 0, method: door.method ?? 'GET' }) + const text = await res.text() + let body: unknown = text + try { body = JSON.parse(text) } catch { /* not JSON */ } + expect((door.closed ?? refused)({ body, status: res.status() }), `${door.graphql ?? door.path} → ${res.status()} ${text.slice(0, 200)}`).toBe(true) + }) + } + }) +} diff --git a/reference/.agents/skills/iapl-audit/resources/routes.template.ts b/reference/.agents/skills/iapl-audit/resources/routes.template.ts new file mode 100644 index 0000000..80f6819 --- /dev/null +++ b/reference/.agents/skills/iapl-audit/resources/routes.template.ts @@ -0,0 +1,24 @@ +/** + * Routes nobody has judged — every public route of this site (REST, GraphQL, Next route files) against the judged + * list in tests/routes.snapshot.json (IAPL docs/security.md "Routes nobody has judged"). Reads the config, never the + * database: the same on MongoDB, Postgres and SQLite. Copy to tests/routes.ts, then: + * + * pnpm payload run tests/routes.ts update → writes tests/routes.snapshot.json, every route with an EMPTY reason + * (write one line per route: who may use it and why it is open, or that it is closed and to whom) + * pnpm payload run tests/routes.ts → fails on a route nobody has judged or an entry without a reason + * + * Run it in CI and after every Payload / IAPL / plugin upgrade; an upgrade that adds a route fails here until somebody + * judges it (`update` adds it with an empty reason; review the diff). `payload run` drops `--flags`: the word is `update`. + */ +import config from '@payload-config' +import { runRouteCheck } from '@intecion/ipal-kit/doctor' + +process.exit( + await runRouteCheck({ + config: await config, + snapshot: 'tests/routes.snapshot.json', + // appDir: 'src/app', // where the Next routes live + // graphql: false, // a site that deleted app/(payload)/api/graphql + update: process.argv.slice(2).includes('update'), + }), +) diff --git a/reference/.agents/skills/iapl-upgrade/SKILL.md b/reference/.agents/skills/iapl-upgrade/SKILL.md index 0e52b53..53fe0a2 100644 --- a/reference/.agents/skills/iapl-upgrade/SKILL.md +++ b/reference/.agents/skills/iapl-upgrade/SKILL.md @@ -25,6 +25,14 @@ the MANDATORY SET (GEO: llms-full, Markdown, MCP; R2; Turnstile through `getTurnstileConfig`…). Wire each one according to PROGRAMISTA §2 — it is part of the update, not an extra. Skip one only with a client decision in `AGENTS.md` (`iapl-audit-skip:`). +**→ 1.17.1:** (1) `src/proxy.ts`: replace the matcher literal with +`['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)']` (i18n.md "Next matcher"; `iapl-doctor` rule `proxy-matcher`). +The old one skipped every page whose first segment only starts with `api`, `admin` or `_next` (`/administracja`): +no locale redirect, no proxy CSP there. Verify on a build: `curl -sI localhost:3000/administracja` → 307 to +`/pl/administracja`; `/admin` and `/api/health` unchanged. (2) If the project has `tests/routes.ts`: run +`pnpm payload run tests/routes.ts update`, judge the new entries, commit (after EVERY Payload / IAPL upgrade). New +projects: add the closed-doors spec and the route check (iapl-audit "What the script does not check"). + **1.8.x → 1.9.0 (PROGRAMISTA §6, items 17–21):** `twoFactor.plugin` required; `getTurnstileConfig` instead of `turnstileSiteKey` (with both keys set the token is required — check that every form has the widget); `clientIp(await headers())` in diff --git a/reference/e2e/closed-doors.spec.ts b/reference/e2e/closed-doors.spec.ts new file mode 100644 index 0000000..7a45c3a --- /dev/null +++ b/reference/e2e/closed-doors.spec.ts @@ -0,0 +1,86 @@ +import { type APIRequestContext, expect, test } from '@playwright/test' +import { randomUUID } from 'node:crypto' + +import { type Caller, DOORS, type DoorAnswer, refused } from './closed-doors' +import { editorTestAccount, totp } from './totp' + +/** + * Closed doors from outside (IAWL idea 33): every door of e2e/closed-doors.ts asked on the BUILT site in production + * mode — `pnpm e2e:built` runs it after a webpack and a Turbopack build — as an anonymous visitor, a customer and an + * editor. Some behaviour differs outside production (Payload's GraphQL playground and introspection), so this is not + * a unit test. The customer needs the late-staff fixture (E2E_LATE_STAFF=1, a self-signing-up `e2e-visitors` + * collection); the editor the E2E_* test admin values (e2e/create-test-admin.ts makes the editor account). + */ +const { E2E_ADMIN_EMAIL: adminEmail, E2E_ADMIN_PASSWORD: password, E2E_LATE_STAFF: lateStaff, E2E_TOTP_SECRET: secret } = process.env + +type Ctx = { api: APIRequestContext; email?: string } + +async function signIn(caller: Caller, baseURL: string, playwright: { request: { newContext: (o: object) => Promise } }): Promise { + const api = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL } }) + if (caller === 'anonymous') {return { api }} + if (caller === 'customer') { + if (lateStaff !== '1') {return null} + const email = `door-${randomUUID().slice(0, 8)}@example.com` + const pass = `D-${randomUUID()}` + expect((await api.post('/api/e2e-visitors', { data: { email, password: pass } })).status()).toBe(201) + expect((await api.post('/api/e2e-visitors/login', { data: { email, password: pass } })).status()).toBe(200) + return { api, email } + } + if (!adminEmail || !password || !secret) {return null} + const email = editorTestAccount(adminEmail) + expect((await api.post('/api/users/login', { data: { email, password } })).status()).toBe(200) + expect((await (await api.post('/api/verify-totp', { data: { token: totp(secret) } })).json()).ok).toBe(true) + return { api, email } +} + +async function ask(api: APIRequestContext, door: (typeof DOORS)[number]): Promise { + const res = door.graphql + ? await api.post('/api/graphql', { data: { query: door.graphql } }) + : await api.fetch(door.path!, { data: door.body, maxRedirects: 0, method: door.method ?? 'GET' }) + const text = await res.text() + let body: unknown = text + try { + body = JSON.parse(text) + } catch { + // not JSON + } + return { body, location: res.headers().location ?? null, status: res.status() } +} + +for (const caller of ['anonymous', 'customer', 'editor'] as const) { + test.describe(`closed doors as ${caller === 'anonymous' ? 'an anonymous visitor' : `a ${caller}`}`, () => { + let ctx: Ctx | null = null + test.beforeAll(async ({ baseURL, playwright }) => { + ctx = await signIn(caller, baseURL!, playwright) + }) + test.afterAll(async () => { + await ctx?.api.dispose() + }) + + for (const door of DOORS) { + const open = door.openFor?.callers.includes(caller) + if (!door.closedFor.includes(caller) && !open) {continue} + test(`${open ? '[open, waiting for the owner] ' : ''}${door.name}`, async () => { + test.skip(!ctx, caller === 'customer' ? 'E2E_LATE_STAFF=1 not set (the customer collection is the fixture\'s)' : 'E2E_* test admin not configured') + // still open while the owner decides: this asserts that it IS open; once closed, the test "passes unexpectedly" + if (open) {test.fail(true, door.openFor!.question)} + const answer = await ask(ctx!.api, door) + const closed = (door.closed ?? refused)(answer, { email: ctx!.email }) + expect(closed, `${door.graphql ?? `${door.method ?? 'GET'} ${door.path}`} → ${answer.status} ${JSON.stringify(answer.body).slice(0, 300)}`).toBe(true) + }) + } + }) +} + +test.describe('closed doors: the proxy skips /api, /admin and /_next as whole segments only (IAWL idea 36)', () => { + test('the admin and the API are not sent to a locale; a page that only starts with those letters is', async ({ request }) => { + for (const path of ['/admin', '/api/health']) { + const res = await request.get(path, { maxRedirects: 0 }) + expect([path, res.headers().location ?? '']).not.toEqual([path, expect.stringMatching(/^(?:https?:\/\/[^/]+)?\/(?:pl|en)\//)]) + } + for (const path of ['/administracja', '/apis']) { + const res = await request.get(path, { maxRedirects: 0 }) + expect([path, res.status(), new URL(res.headers().location ?? '/', 'http://x').pathname]).toEqual([path, 307, `/pl${path}`]) + } + }) +}) diff --git a/reference/e2e/closed-doors.ts b/reference/e2e/closed-doors.ts new file mode 100644 index 0000000..8a5b09f --- /dev/null +++ b/reference/e2e/closed-doors.ts @@ -0,0 +1,133 @@ +/** + * The doors of this site that must stay CLOSED, asked from outside on the built site in production mode by + * e2e/closed-doors.spec.ts (`pnpm e2e:built`, both bundlers) as three callers: + * anonymous — no session; + * customer — an account of a visitor collection that signs itself up (`e2e-visitors`, late-staff fixture, + * E2E_LATE_STAFF=1); stands for a shop's or a member zone's customers; + * editor — a staff account with the role `editor`, signed in with the second factor. + * A project adds its own doors here (docs/security.md "Closed doors from outside"). Every door says who it is + * closed for and how a closed answer looks; a caller not named may pass (an editor reads the submissions). + * + * A door that is still OPEN for a caller while the owner decides is listed under `openFor`, with the question: the + * spec asserts that it is open today (`test.fail` — when somebody closes it, the test reports "passed + * unexpectedly" and the entry moves to `closedFor`). A door that writes is asked with a body that cannot change + * anything when the door is open: a document id that does not exist, an empty update, a form id that does not exist. + */ +export type Caller = 'anonymous' | 'customer' | 'editor' + +export type DoorAnswer = { body: unknown; location: null | string; status: number } + +export type Door = { + /** GraphQL: the query, sent as POST /api/graphql. REST: the path. */ + body?: unknown + /** How a closed answer looks; default: status 401, 403 or 404. */ + closed?: (answer: DoorAnswer, ctx: { email?: string }) => boolean + closedFor: Caller[] + graphql?: string + method?: 'DELETE' | 'GET' | 'PATCH' | 'POST' + name: string + /** Open for these callers while the owner decides (the finding's question). */ + openFor?: { callers: Caller[]; question: string } + path?: string +} + +export const ALL: Caller[] = ['anonymous', 'customer', 'editor'] +export const OUTSIDERS: Caller[] = ['anonymous', 'customer'] +const NO_ID = '000000000000000000000000' + +export const refused = ({ status }: DoorAnswer) => [401, 403, 404].includes(status) +const refusedOrNotOk = (answer: DoorAnswer) => refused(answer) || (answer.body as { ok?: unknown } | null)?.ok === false +const forbidden = ({ status }: DoorAnswer) => status === 403 +const notFound = ({ status }: DoorAnswer) => status === 404 +/** A GraphQL answer that carries no data for the field: an error, or null. */ +const noData = (field: string) => ({ body, status }: DoorAnswer) => { + const b = body as { data?: Record | null; errors?: unknown[] } | null + return status >= 400 || Boolean(b?.errors?.length) || b?.data?.[field] == null +} + +export const DOORS: Door[] = [ + // ---- secrets and the system's own state ------------------------------------------------------------------ + { closedFor: ALL, name: 'Site integrations (SMTP password, keys) cannot be read', path: '/api/globals/site-integrations' }, + { body: {}, closedFor: ALL, method: 'POST', name: 'Site integrations cannot be saved', path: '/api/globals/site-integrations' }, + { closedFor: ALL, graphql: '{ SiteIntegration { smtpHost } }', closed: noData('SiteIntegration'), name: 'Site integrations over GraphQL' }, + { closedFor: ALL, name: 'Payload\'s key-value store (2FA counts, the mail-service token) cannot be listed', path: '/api/payload-kv' }, + { closedFor: ALL, graphql: '{ PayloadKvs { docs { key } } }', closed: noData('PayloadKvs'), name: 'the key-value store over GraphQL' }, + { closedFor: ALL, name: 'the consent log (admin only)', path: '/api/consent-records' }, + { closedFor: ALL, name: 'the deep doctor status answers 404 without its token', path: '/api/ipal/doctor', closed: notFound }, + + // ---- jobs, schedules and call-backs (IAWL idea 35) --------------------------------------------------------- + { closedFor: ALL, name: 'Payload\'s job queue has no run route (no jobs on this site)', path: '/api/payload-jobs/run', closed: notFound }, + { closedFor: ALL, method: 'POST', name: 'the crawler\'s call-back without its token', path: '/api/ipal/cookie-crawl/results', body: { jobId: 'x', ok: true } }, + { closedFor: OUTSIDERS, method: 'POST', name: 'a crawl cannot be started without the schedule\'s token', path: '/api/ipal/cookie-crawl' }, + { closedFor: OUTSIDERS, name: 'the crawl status', path: '/api/ipal/cookie-crawl' }, + { closedFor: OUTSIDERS, method: 'POST', name: 'a cookie scan cannot be run', path: '/api/ipal/cookie-scan' }, + { closedFor: OUTSIDERS, name: 'the cookie approval list', path: '/api/ipal/cookie-approval' }, + { closedFor: OUTSIDERS, body: { ids: [NO_ID] }, method: 'POST', name: 'cookies cannot be approved', path: '/api/ipal/cookie-approval' }, + { closedFor: OUTSIDERS, name: 'the cookie review entries', path: '/api/cookie-review' }, + { closedFor: OUTSIDERS, name: 'the crawl global', path: '/api/globals/cookie-crawl' }, + + // ---- admin actions --------------------------------------------------------------------------------------- + { body: { to: 'nobody@example.com' }, closedFor: ALL, method: 'POST', name: 'a test e-mail cannot be sent', path: '/api/ipal/test-email' }, + { closedFor: ALL, name: 'the mail-service status', path: '/api/iapl/mail-relay/status' }, + { body: { token: 'ims_x' }, closedFor: ALL, method: 'POST', name: 'the mail service cannot be connected', path: '/api/iapl/mail-relay/connect' }, + { closedFor: ALL, method: 'POST', name: 'the mail service cannot be disconnected', path: '/api/iapl/mail-relay/disconnect' }, + { closedFor: ALL, method: 'POST', name: 'the confirm route answers 404 without a nonce of this site', path: '/api/iapl/mail-relay/confirm', body: { nonce: 'n'.repeat(40), state: 'active', token: `ims_${'a'.repeat(43)}` }, closed: notFound }, + { body: { id: NO_ID }, closedFor: ALL, method: 'POST', name: 'another account\'s 2FA cannot be reset', path: '/api/ipal/two-factor/reset' }, + // payload-2fa refuses with HTTP 200 and `{ ok: false }` (its own convention), so the body is what is judged + { body: { id: NO_ID }, closedFor: ALL, method: 'POST', name: 'another account\'s 2FA cannot be removed (payload-2fa)', path: '/api/admin/remove-user-totp', closed: refusedOrNotOk }, + { body: { id: NO_ID }, closedFor: ALL, method: 'POST', name: 'another account\'s 2FA cannot be reset (payload-2fa)', path: '/api/admin/reset-user-totp', closed: refusedOrNotOk }, + + // ---- accounts -------------------------------------------------------------------------------------------- + { body: { email: 'door@example.com', password: 'Door-Password-1234', roles: ['admin'] }, closedFor: ALL, method: 'POST', name: 'nobody creates a staff account', path: '/api/users', closed: forbidden }, + { body: { email: 'first@example.com', password: 'Door-Password-1234' }, closedFor: ALL, method: 'POST', name: 'the first-user route is closed once an account exists', path: '/api/users/first-register', closed: forbidden }, + { body: { email: 'nobody@example.com' }, closedFor: ALL, method: 'POST', name: 'nobody unlocks an account', path: '/api/users/unlock', closed: forbidden }, + { body: { roles: ['admin'] }, closedFor: ALL, method: 'PATCH', name: 'nobody changes another account', path: `/api/users/${NO_ID}`, closed: forbidden }, + { + closedFor: ALL, + // an editor reads its own account only (adminOrSelfIn): one document, its own + closed: (answer, { email }) => refused(answer) || (Array.isArray((answer.body as { docs?: { email?: string }[] })?.docs) && (answer.body as { docs: { email?: string }[] }).docs.every((d) => d.email === email)), + name: 'the staff accounts cannot be listed (an editor sees its own only)', + path: '/api/users?limit=100', + }, + { closedFor: OUTSIDERS, graphql: '{ Users { docs { email } } }', closed: noData('Users'), name: 'the staff accounts over GraphQL' }, + + // ---- content and visitors' data -------------------------------------------------------------------------- + { closedFor: OUTSIDERS, name: 'form submissions (visitors\' personal data)', path: '/api/form-submissions' }, + { closedFor: OUTSIDERS, graphql: '{ FormSubmissions { docs { id } } }', closed: noData('FormSubmissions'), name: 'form submissions over GraphQL' }, + { + body: { form: NO_ID, submissionData: [] }, + closedFor: ['anonymous'], + method: 'POST', + name: 'a submission cannot be posted past submitForm (rate limit, Turnstile, consent, validation)', + openFor: { callers: ['customer'], question: 'Q1 (iawl-ideas-c-findings.md): any signed-in account may POST /api/form-submissions' }, + path: '/api/form-submissions', + closed: forbidden, + }, + { body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'Site settings cannot be saved', path: '/api/globals/site-settings', closed: forbidden }, + { body: {}, closedFor: OUTSIDERS, method: 'POST', name: 'Cookie settings (legal texts) cannot be saved', path: '/api/globals/cookie-settings', closed: forbidden }, + { + body: {}, + closedFor: ['anonymous'], + method: 'PATCH', + name: 'pages cannot be changed', + openFor: { callers: ['customer'], question: 'Q3: collections without their own write rules run on Payload\'s default (any signed-in account)' }, + path: `/api/pages/${NO_ID}`, + closed: forbidden, + }, + { + closedFor: ['anonymous'], + name: 'who edits what (Payload\'s document locks, with the editor\'s account)', + openFor: { callers: ['customer'], question: 'Q3: payload-locked-documents runs on Payload\'s default (any signed-in account)' }, + path: '/api/payload-locked-documents', + closed: forbidden, + }, + + // ---- what differs in production (IAWL idea 33) ------------------------------------------------------------ + { closedFor: ALL, name: 'the GraphQL playground is off in production', path: '/api/graphql-playground', closed: notFound }, + { + closedFor: ALL, + graphql: '{ __schema { queryType { name } } }', + closed: ({ body }) => Boolean((body as { errors?: unknown[] })?.errors?.length) && !(body as { data?: { __schema?: unknown } })?.data?.__schema, + name: 'GraphQL introspection is off in production', + }, +] diff --git a/reference/e2e/create-test-admin.ts b/reference/e2e/create-test-admin.ts index cceec85..fe39f83 100644 --- a/reference/e2e/create-test-admin.ts +++ b/reference/e2e/create-test-admin.ts @@ -10,7 +10,7 @@ import config from '@payload-config' import { verifyLimitKey } from '@intecion/ipal-kit' import { isLocalDatabase } from '@intecion/ipal-kit/seed' -import { secondTestAdmin } from './totp' +import { editorTestAccount, secondTestAdmin } from './totp' import { getPayload } from 'payload' const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: totpSecret } = process.env @@ -23,8 +23,9 @@ const payload = await getPayload({ config }) // 10 minutes and is stored in the database, so it survives a restart of the site: the smoke and back-link specs // sign in as the first account, the setup spec as the second, and this script clears both counts — run it again // before repeating the tests within ten minutes. -for (const address of [email, secondTestAdmin(email)]) { - const data = { email: address, hasTotp: true, password, roles: ['admin'], totpSecret } +// and an editor for the closed-doors spec (e2e/closed-doors.spec.ts), signed in through the same 2FA +for (const [address, role] of [[email, 'admin'], [secondTestAdmin(email), 'admin'], [editorTestAccount(email), 'editor']] as const) { + const data = { email: address, hasTotp: true, password, roles: [role], totpSecret } const found = await payload.find({ collection: 'users', limit: 1, overrideAccess: true, where: { email: { equals: address } } }) const doc = found.docs[0] ? await payload.update({ id: found.docs[0].id, collection: 'users', data: data as never, overrideAccess: true }) @@ -32,7 +33,7 @@ for (const address of [email, secondTestAdmin(email)]) { // this site counts under the `iapl` prefix (payload.config.ts: storageNames: 'iapl'); the old key too, for a database from before await payload.kv.delete(verifyLimitKey('users', String(doc.id), 'iapl')) await payload.kv.delete(verifyLimitKey('users', String(doc.id))) - console.log(`[e2e] test admin ready: ${address}`) + console.log(`[e2e] test ${role} ready: ${address}`) } // E-mail for the smoke tests goes to a local sink the test itself starts (e2e/smtp-sink.ts), so the test can diff --git a/reference/e2e/routes.snapshot.json b/reference/e2e/routes.snapshot.json new file mode 100644 index 0000000..a20d028 --- /dev/null +++ b/reference/e2e/routes.snapshot.json @@ -0,0 +1,400 @@ +{ + "$comment": "Every public door of this site: REST routes, GraphQL operations, Next route files. One line per entry: who may use it and why it is open (or that it is closed and to whom). A new route fails `routes:check` until somebody judges it here. `--update` adds new routes with an empty reason and drops gone ones. docs/security.md \"Routes nobody has judged\".", + "routes": { + "DELETE /api/caseStudies": "delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "DELETE /api/caseStudies/:id": "deleteByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "DELETE /api/consent-records": "delete: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", + "DELETE /api/consent-records/:id": "deleteByID: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", + "DELETE /api/cookie-review": "delete: create/update: editor+; delete: admin", + "DELETE /api/cookie-review/:id": "deleteByID: create/update: editor+; delete: admin", + "DELETE /api/form-submissions": "delete: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "DELETE /api/form-submissions/:id": "deleteByID: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "DELETE /api/forms": "delete: editor+ (staffAccess)", + "DELETE /api/forms/:id": "deleteByID: editor+ (staffAccess)", + "DELETE /api/media": "delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "DELETE /api/media/:id": "deleteByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "DELETE /api/pages": "delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "DELETE /api/pages/:id": "deleteByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "DELETE /api/payload-kv": "delete: nobody (every rule false)", + "DELETE /api/payload-kv/:id": "deleteByID: nobody (every rule false)", + "DELETE /api/payload-locked-documents": "delete: Payload default: any signed-in account (owner Q3)", + "DELETE /api/payload-locked-documents/:id": "deleteByID: Payload default: any signed-in account (owner Q3)", + "DELETE /api/payload-preferences": "delete: own preferences only (Payload)", + "DELETE /api/payload-preferences/:id": "deleteByID: own preferences only (Payload)", + "DELETE /api/payload-preferences/:key": "deleteByID: own preferences only (Payload)", + "DELETE /api/posts": "delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "DELETE /api/posts/:id": "deleteByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "DELETE /api/users": "delete: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", + "DELETE /api/users/:id": "deleteByID: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", + "GET /api/access": "Payload: the signed-in account's permissions (what the panel may show); anonymous gets an empty map", + "GET /api/caseStudies": "find: anyone (published content, no drafts)", + "GET /api/caseStudies/:id": "findByID: anyone (published content, no drafts)", + "GET /api/caseStudies/count": "count: anyone (published content, no drafts)", + "GET /api/caseStudies/versions": "versions: readVersions = read (anyone (published content, no drafts)); no version history kept here", + "GET /api/caseStudies/versions/:id": "versionByID: readVersions = read (anyone (published content, no drafts)); no version history kept here", + "GET /api/consent-records": "find: admin", + "GET /api/consent-records/:id": "findByID: admin", + "GET /api/consent-records/count": "count: admin", + "GET /api/consent-records/versions": "versions: readVersions = read (admin); no version history kept here", + "GET /api/consent-records/versions/:id": "versionByID: readVersions = read (admin); no version history kept here", + "GET /api/cookie-review": "find: editor+", + "GET /api/cookie-review/:id": "findByID: editor+", + "GET /api/cookie-review/count": "count: editor+", + "GET /api/cookie-review/versions": "versions: readVersions = read (editor+); no version history kept here", + "GET /api/cookie-review/versions/:id": "versionByID: readVersions = read (editor+); no version history kept here", + "GET /api/form-submissions": "find: editor+ (visitors' personal data)", + "GET /api/form-submissions/:id": "findByID: editor+ (visitors' personal data)", + "GET /api/form-submissions/count": "count: editor+ (visitors' personal data)", + "GET /api/form-submissions/versions": "versions: readVersions = read (editor+ (visitors' personal data)); no version history kept here", + "GET /api/form-submissions/versions/:id": "versionByID: readVersions = read (editor+ (visitors' personal data)); no version history kept here", + "GET /api/forms": "find: anyone (the form renders from it; the Emails tab is staff-only by field access)", + "GET /api/forms/:id": "findByID: anyone (the form renders from it; the Emails tab is staff-only by field access)", + "GET /api/forms/count": "count: anyone (the form renders from it; the Emails tab is staff-only by field access)", + "GET /api/forms/versions": "versions: readVersions = read (anyone (the form renders from it; the Emails tab is staff-only by field access)); no version history kept here", + "GET /api/forms/versions/:id": "versionByID: readVersions = read (anyone (the form renders from it; the Emails tab is staff-only by field access)); no version history kept here", + "GET /api/globals/company": "find: anyone (company data for JSON-LD / contact)", + "GET /api/globals/company/versions": "versions: readVersions = read (anyone (company data for JSON-LD / contact)); no version history kept here", + "GET /api/globals/company/versions/:id": "versionByID: readVersions = read (anyone (company data for JSON-LD / contact)); no version history kept here", + "GET /api/globals/cookie-crawl": "find: editor+", + "GET /api/globals/cookie-crawl/versions": "versions: readVersions = read (editor+); no version history kept here", + "GET /api/globals/cookie-crawl/versions/:id": "versionByID: readVersions = read (editor+); no version history kept here", + "GET /api/globals/cookie-settings": "find: anyone (banner texts, policy version)", + "GET /api/globals/cookie-settings/versions": "versions: readVersions = read (anyone (banner texts, policy version)); no version history kept here", + "GET /api/globals/cookie-settings/versions/:id": "versionByID: readVersions = read (anyone (banner texts, policy version)); no version history kept here", + "GET /api/globals/footer": "find: anyone (site footer)", + "GET /api/globals/footer/versions": "versions: readVersions = read (anyone (site footer)); no version history kept here", + "GET /api/globals/footer/versions/:id": "versionByID: readVersions = read (anyone (site footer)); no version history kept here", + "GET /api/globals/header": "find: anyone (site navigation)", + "GET /api/globals/header/versions": "versions: readVersions = read (anyone (site navigation)); no version history kept here", + "GET /api/globals/header/versions/:id": "versionByID: readVersions = read (anyone (site navigation)); no version history kept here", + "GET /api/globals/notifications": "find: anyone (public-facing texts)", + "GET /api/globals/notifications/versions": "versions: readVersions = read (anyone (public-facing texts)); no version history kept here", + "GET /api/globals/notifications/versions/:id": "versionByID: readVersions = read (anyone (public-facing texts)); no version history kept here", + "GET /api/globals/site-integrations": "find: admin (SMTP, keys, integrations)", + "GET /api/globals/site-integrations/versions": "versions: readVersions = read (admin (SMTP, keys, integrations)); no version history kept here", + "GET /api/globals/site-integrations/versions/:id": "versionByID: readVersions = read (admin (SMTP, keys, integrations)); no version history kept here", + "GET /api/globals/site-settings": "find: anyone (brand, homepage, construction mode)", + "GET /api/globals/site-settings/versions": "versions: readVersions = read (anyone (brand, homepage, construction mode)); no version history kept here", + "GET /api/globals/site-settings/versions/:id": "versionByID: readVersions = read (anyone (brand, homepage, construction mode)); no version history kept here", + "GET /api/iapl/mail-relay/status": "mail service status in the panel: admin", + "GET /api/ipal/admin-icon": "public by design: the panel's favicon (white-label)", + "GET /api/ipal/admin-og": "public by design: the panel's link-preview image", + "GET /api/ipal/cookie-approval": "cookie approval list: editor+ with the second factor (cookieScanner.access)", + "GET /api/ipal/cookie-crawl": "crawl status: editor+ with the second factor", + "GET /api/ipal/cookie-scan": "what a scan covers: editor+ with the second factor", + "GET /api/ipal/doctor": "404 until IAPL_DOCTOR_TOKEN (32+ chars) is set; then that bearer token (or doctor.access); 10 per minute per address", + "GET /api/media": "find: anyone (public files)", + "GET /api/media/:id": "findByID: anyone (public files)", + "GET /api/media/count": "count: anyone (public files)", + "GET /api/media/file/:filename": "serve a file: anyone (public files)", + "GET /api/media/paste-url/:id?": "Payload: the server fetches a URL into an upload; signed-in AND media create/update rule AND upload.pasteURL on (off here: 400); safeFetch refuses private addresses", + "GET /api/media/versions": "versions: readVersions = read (anyone (public files)); no version history kept here", + "GET /api/media/versions/:id": "versionByID: readVersions = read (anyone (public files)); no version history kept here", + "GET /api/pages": "find: anyone (published content, no drafts)", + "GET /api/pages/:id": "findByID: anyone (published content, no drafts)", + "GET /api/pages/count": "count: anyone (published content, no drafts)", + "GET /api/pages/versions": "versions: readVersions = read (anyone (published content, no drafts)); no version history kept here", + "GET /api/pages/versions/:id": "versionByID: readVersions = read (anyone (published content, no drafts)); no version history kept here", + "GET /api/payload-kv": "find: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)", + "GET /api/payload-kv/:id": "findByID: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)", + "GET /api/payload-kv/count": "count: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)", + "GET /api/payload-kv/versions": "versions: readVersions = read (nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)); no version history kept here", + "GET /api/payload-kv/versions/:id": "versionByID: readVersions = read (nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)); no version history kept here", + "GET /api/payload-locked-documents": "find: Payload default: any signed-in account (owner Q3)", + "GET /api/payload-locked-documents/:id": "findByID: Payload default: any signed-in account (owner Q3)", + "GET /api/payload-locked-documents/count": "count: Payload default: any signed-in account (owner Q3)", + "GET /api/payload-locked-documents/versions": "versions: readVersions = read (Payload default: any signed-in account (owner Q3)); no version history kept here", + "GET /api/payload-locked-documents/versions/:id": "versionByID: readVersions = read (Payload default: any signed-in account (owner Q3)); no version history kept here", + "GET /api/payload-preferences": "find: the signed-in account's own preferences only (Payload)", + "GET /api/payload-preferences/:id": "findByID: the signed-in account's own preferences only (Payload)", + "GET /api/payload-preferences/:key": "findByID: the signed-in account's own preferences only (Payload)", + "GET /api/payload-preferences/count": "count: the signed-in account's own preferences only (Payload)", + "GET /api/payload-preferences/versions": "versions: readVersions = read (the signed-in account's own preferences only (Payload)); no version history kept here", + "GET /api/payload-preferences/versions/:id": "versionByID: readVersions = read (the signed-in account's own preferences only (Payload)); no version history kept here", + "GET /api/posts": "find: anyone (published content, no drafts)", + "GET /api/posts/:id": "findByID: anyone (published content, no drafts)", + "GET /api/posts/count": "count: anyone (published content, no drafts)", + "GET /api/posts/versions": "versions: readVersions = read (anyone (published content, no drafts)); no version history kept here", + "GET /api/posts/versions/:id": "versionByID: readVersions = read (anyone (published content, no drafts)); no version history kept here", + "GET /api/users": "find: an admin, or the account itself (adminOrSelfIn users)", + "GET /api/users/:id": "findByID: an admin, or the account itself (adminOrSelfIn users)", + "GET /api/users/count": "count: an admin, or the account itself (adminOrSelfIn users)", + "GET /api/users/init": "Payload: whether a first account exists (true/false only)", + "GET /api/users/me": "Payload: the signed-in account itself, or null; no other account", + "GET /api/users/versions": "versions: readVersions = read (an admin, or the account itself (adminOrSelfIn users)); no version history kept here", + "GET /api/users/versions/:id": "versionByID: readVersions = read (an admin, or the account itself (adminOrSelfIn users)); no version history kept here", + "PATCH /api/caseStudies": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "PATCH /api/caseStudies/:id": "updateByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "PATCH /api/consent-records": "update: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", + "PATCH /api/consent-records/:id": "updateByID: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", + "PATCH /api/cookie-review": "update: create/update: editor+; delete: admin", + "PATCH /api/cookie-review/:id": "updateByID: create/update: editor+; delete: admin", + "PATCH /api/form-submissions": "update: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "PATCH /api/form-submissions/:id": "updateByID: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "PATCH /api/forms": "update: editor+ (staffAccess)", + "PATCH /api/forms/:id": "updateByID: editor+ (staffAccess)", + "PATCH /api/media": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "PATCH /api/media/:id": "updateByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "PATCH /api/pages": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "PATCH /api/pages/:id": "updateByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "PATCH /api/payload-kv": "update: nobody (every rule false)", + "PATCH /api/payload-kv/:id": "updateByID: nobody (every rule false)", + "PATCH /api/payload-locked-documents": "update: Payload default: any signed-in account (owner Q3)", + "PATCH /api/payload-locked-documents/:id": "updateByID: Payload default: any signed-in account (owner Q3)", + "PATCH /api/payload-preferences": "update: own preferences only (Payload)", + "PATCH /api/payload-preferences/:id": "updateByID: own preferences only (Payload)", + "PATCH /api/posts": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "PATCH /api/posts/:id": "updateByID: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "PATCH /api/users": "update: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", + "PATCH /api/users/:id": "updateByID: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", + "POST /api/admin/remove-user-totp": "2FA: an admin removes another account's second factor", + "POST /api/admin/reset-user-totp": "2FA: an admin resets another account's second factor", + "POST /api/caseStudies": "create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/caseStudies/:id/duplicate": "duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/caseStudies/access/:id?": "the signed-in account's own permissions on caseStudies", + "POST /api/caseStudies/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/consent-records": "create: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", + "POST /api/consent-records/:id/duplicate": "duplicate: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", + "POST /api/consent-records/access/:id?": "the signed-in account's own permissions on consent-records", + "POST /api/consent-records/versions/:id": "restore a version: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", + "POST /api/cookie-review": "create: create/update: editor+; delete: admin", + "POST /api/cookie-review/:id/duplicate": "duplicate: create/update: editor+; delete: admin", + "POST /api/cookie-review/access/:id?": "the signed-in account's own permissions on cookie-review", + "POST /api/cookie-review/versions/:id": "restore a version: create/update: editor+; delete: admin", + "POST /api/form-submissions": "create: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "POST /api/form-submissions/:id/duplicate": "duplicate: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "POST /api/form-submissions/access/:id?": "the signed-in account's own permissions on form-submissions", + "POST /api/form-submissions/versions/:id": "restore a version: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "POST /api/forms": "create: editor+ (staffAccess)", + "POST /api/forms/:id/duplicate": "duplicate: editor+ (staffAccess)", + "POST /api/forms/access/:id?": "the signed-in account's own permissions on forms", + "POST /api/forms/versions/:id": "restore a version: editor+ (staffAccess)", + "POST /api/globals/company": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/globals/company/access": "the signed-in account's own permissions on globals/company", + "POST /api/globals/company/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/globals/cookie-crawl": "update: admin; the crawl endpoints write it after their own checks", + "POST /api/globals/cookie-crawl/access": "the signed-in account's own permissions on globals/cookie-crawl", + "POST /api/globals/cookie-crawl/versions/:id": "restore a version: admin; the crawl endpoints write it after their own checks", + "POST /api/globals/cookie-settings": "update: editor+", + "POST /api/globals/cookie-settings/access": "the signed-in account's own permissions on globals/cookie-settings", + "POST /api/globals/cookie-settings/versions/:id": "restore a version: editor+", + "POST /api/globals/footer": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/globals/footer/access": "the signed-in account's own permissions on globals/footer", + "POST /api/globals/footer/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/globals/header": "update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/globals/header/access": "the signed-in account's own permissions on globals/header", + "POST /api/globals/header/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/globals/notifications": "update: editor+", + "POST /api/globals/notifications/access": "the signed-in account's own permissions on globals/notifications", + "POST /api/globals/notifications/versions/:id": "restore a version: editor+", + "POST /api/globals/site-integrations": "update: admin; secrets write-only", + "POST /api/globals/site-integrations/access": "the signed-in account's own permissions on globals/site-integrations", + "POST /api/globals/site-integrations/versions/:id": "restore a version: admin; secrets write-only", + "POST /api/globals/site-settings": "update: editor+", + "POST /api/globals/site-settings/access": "the signed-in account's own permissions on globals/site-settings", + "POST /api/globals/site-settings/versions/:id": "restore a version: editor+", + "POST /api/iapl/mail-relay/confirm": "public by design: the mail service's call-back; 404 unless it carries a nonce this site made in the last 5 min (single use)", + "POST /api/iapl/mail-relay/connect": "mail service, connect with a pasted token: admin", + "POST /api/iapl/mail-relay/disconnect": "mail service, disconnect: admin", + "POST /api/ipal/consent": "public by design: a visitor's own banner choice (random id, no personal data), body capped at 4 KiB", + "POST /api/ipal/cookie-approval": "approve cookies: editor+ with the second factor", + "POST /api/ipal/cookie-crawl": "start a crawl: editor+, or Bearer IAPL_COOKIE_SCAN_TOKEN (the schedule); only of the configured site URL", + "POST /api/ipal/cookie-crawl/results": "the crawler's call-back: Bearer IAPL_COOKIE_SCAN_TOKEN AND the jobId of the running crawl", + "POST /api/ipal/cookie-scan": "run a scan: editor+ with the second factor", + "POST /api/ipal/forms/submit": "public by design: a form with files; the submitForm pipeline (rate limit, Turnstile, consent, validation, file checks)", + "POST /api/ipal/test-email": "send a test e-mail: admin", + "POST /api/ipal/two-factor/reset": "reset another account's 2FA set-up window: admin signed in with the second factor", + "POST /api/media": "create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/media/:id/duplicate": "duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/media/access/:id?": "the signed-in account's own permissions on media", + "POST /api/media/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/pages": "create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/pages/:id/duplicate": "duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/pages/access/:id?": "the signed-in account's own permissions on pages", + "POST /api/pages/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/payload-kv": "create: nobody (every rule false)", + "POST /api/payload-kv/:id/duplicate": "duplicate: nobody (every rule false)", + "POST /api/payload-kv/access/:id?": "the signed-in account's own permissions on payload-kv", + "POST /api/payload-kv/versions/:id": "restore a version: nobody (every rule false)", + "POST /api/payload-locked-documents": "create: Payload default: any signed-in account (owner Q3)", + "POST /api/payload-locked-documents/:id/duplicate": "duplicate: Payload default: any signed-in account (owner Q3)", + "POST /api/payload-locked-documents/access/:id?": "the signed-in account's own permissions on payload-locked-documents", + "POST /api/payload-locked-documents/versions/:id": "restore a version: Payload default: any signed-in account (owner Q3)", + "POST /api/payload-preferences": "create: own preferences only (Payload)", + "POST /api/payload-preferences/:id/duplicate": "duplicate: own preferences only (Payload)", + "POST /api/payload-preferences/:key": "updateByID: own preferences only (Payload)", + "POST /api/payload-preferences/access/:id?": "the signed-in account's own permissions on payload-preferences", + "POST /api/payload-preferences/versions/:id": "restore a version: own preferences only (Payload)", + "POST /api/plugin-seo/generate-description": "SEO plugin (panel button): Payload default (signed-in account); text from the document, nothing stored", + "POST /api/plugin-seo/generate-image": "SEO plugin (panel button): Payload default (signed-in account); nothing stored", + "POST /api/plugin-seo/generate-title": "SEO plugin (panel button): Payload default (signed-in account); nothing stored", + "POST /api/plugin-seo/generate-url": "SEO plugin (panel button): Payload default (signed-in account); nothing stored", + "POST /api/posts": "create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/posts/:id/duplicate": "duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/posts/access/:id?": "the signed-in account's own permissions on posts", + "POST /api/posts/versions/:id": "restore a version: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "POST /api/remove-totp": "2FA: the signed-in account's own second factor, fully signed in", + "POST /api/setup-totp": "2FA: sets up the signed-in account's own authenticator; same-origin only", + "POST /api/users": "create: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", + "POST /api/users/access/:id?": "Payload: the signed-in account's permissions for one document", + "POST /api/users/first-register": "only while no account exists (the first becomes admin); 403 afterwards (accounts.firstUserRoute)", + "POST /api/users/forgot-password": "public by design: the same answer for a real and an invented address", + "POST /api/users/login": "public by design: sign-in; Payload's maxLoginAttempts, the 2FA step follows", + "POST /api/users/logout": "public by design: ends the caller's own session", + "POST /api/users/refresh-token": "the signed-in account's own token only", + "POST /api/users/reset-password": "public by design: needs the e-mailed reset token", + "POST /api/users/unlock": "admin with the second factor (accounts.adminOnlyWrite)", + "POST /api/users/verify/:id": "public by design: needs the e-mailed verification token (verify is off on users)", + "POST /api/users/versions/:id": "restore a version: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", + "POST /api/verify-totp": "2FA (payload-2fa): the signed-in account's own code; same-origin only, 5 tries per account in 10 min", + "graphql mutation createCaseStudy": "GraphQL create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation createConsentRecord": "GraphQL create: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", + "graphql mutation createCookieReview": "GraphQL create: create/update: editor+; delete: admin", + "graphql mutation createForm": "GraphQL create: editor+ (staffAccess)", + "graphql mutation createFormSubmission": "GraphQL create: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "graphql mutation createMedia": "GraphQL create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation createPage": "GraphQL create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation createPayloadKv": "GraphQL create: nobody (every rule false)", + "graphql mutation createPayloadLockedDocument": "GraphQL create: Payload default: any signed-in account (owner Q3)", + "graphql mutation createPayloadPreference": "GraphQL create: own preferences only (Payload)", + "graphql mutation createPost": "GraphQL create: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation createUser": "GraphQL create: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", + "graphql mutation deleteCaseStudy": "GraphQL delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation deleteConsentRecord": "GraphQL delete: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", + "graphql mutation deleteCookieReview": "GraphQL delete: create/update: editor+; delete: admin", + "graphql mutation deleteForm": "GraphQL delete: editor+ (staffAccess)", + "graphql mutation deleteFormSubmission": "GraphQL delete: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "graphql mutation deleteMedia": "GraphQL delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation deletePage": "GraphQL delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation deletePayloadKv": "GraphQL delete: nobody (every rule false)", + "graphql mutation deletePayloadLockedDocument": "GraphQL delete: Payload default: any signed-in account (owner Q3)", + "graphql mutation deletePayloadPreference": "GraphQL delete: own preferences only (Payload)", + "graphql mutation deletePost": "GraphQL delete: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation deleteUser": "GraphQL delete: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", + "graphql mutation duplicateCaseStudy": "GraphQL duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation duplicateConsentRecord": "GraphQL duplicate: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", + "graphql mutation duplicateCookieReview": "GraphQL duplicate: create/update: editor+; delete: admin", + "graphql mutation duplicateForm": "GraphQL duplicate: editor+ (staffAccess)", + "graphql mutation duplicateFormSubmission": "GraphQL duplicate: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "graphql mutation duplicateMedia": "GraphQL duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation duplicatePage": "GraphQL duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation duplicatePayloadKv": "GraphQL duplicate: nobody (every rule false)", + "graphql mutation duplicatePayloadLockedDocument": "GraphQL duplicate: Payload default: any signed-in account (owner Q3)", + "graphql mutation duplicatePayloadPreference": "GraphQL duplicate: own preferences only (Payload)", + "graphql mutation duplicatePost": "GraphQL duplicate: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation forgotPasswordUser": "public by design: the same answer for a real and an invented address", + "graphql mutation loginUser": "public by design: sign-in (as POST /api/users/login)", + "graphql mutation logoutUser": "public by design: ends the caller's own session", + "graphql mutation refreshTokenUser": "the signed-in account's own token only", + "graphql mutation resetPasswordUser": "public by design: needs the e-mailed reset token", + "graphql mutation unlockUser": "admin with the second factor (accounts.adminOnlyWrite)", + "graphql mutation updateCaseStudy": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation updateCompany": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation updateConsentRecord": "GraphQL update: nobody over the API (create/update false); delete: admin; visitors write through POST /api/ipal/consent", + "graphql mutation updateCookieCrawl": "GraphQL update: admin; the crawl endpoints write it after their own checks", + "graphql mutation updateCookieReview": "GraphQL update: create/update: editor+; delete: admin", + "graphql mutation updateCookieSetting": "GraphQL update: editor+", + "graphql mutation updateFooter": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation updateForm": "GraphQL update: editor+ (staffAccess)", + "graphql mutation updateFormSubmission": "GraphQL update: create: any signed-in account (owner Q1); update: Payload default; delete: admin", + "graphql mutation updateHeader": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation updateMedia": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation updateNotification": "GraphQL update: editor+", + "graphql mutation updatePage": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation updatePayloadKv": "GraphQL update: nobody (every rule false)", + "graphql mutation updatePayloadLockedDocument": "GraphQL update: Payload default: any signed-in account (owner Q3)", + "graphql mutation updatePayloadPreference": "GraphQL update: own preferences only (Payload)", + "graphql mutation updatePost": "GraphQL update: Payload default (any signed-in account; one login collection here, so staff only — a visitor collection would reach it: owner Q3)", + "graphql mutation updateSiteIntegration": "GraphQL update: admin; secrets write-only", + "graphql mutation updateSiteSetting": "GraphQL update: editor+", + "graphql mutation updateUser": "GraphQL update: create/delete/unlock: an admin with the second factor; update: admin or self; roles field: admin", + "graphql mutation verifyEmailUser": "public by design: needs the e-mailed verification token (verify is off on users)", + "graphql query Access": "Payload: the signed-in account's permissions; anonymous gets an empty map", + "graphql query CaseStudies": "GraphQL find: anyone (published content, no drafts)", + "graphql query CaseStudy": "GraphQL find: anyone (published content, no drafts)", + "graphql query Company": "GraphQL find: anyone (company data for JSON-LD / contact)", + "graphql query ConsentRecord": "GraphQL find: admin", + "graphql query ConsentRecords": "GraphQL find: admin", + "graphql query CookieCrawl": "GraphQL find: editor+", + "graphql query CookieReview": "GraphQL find: editor+", + "graphql query CookieReviews": "GraphQL find: editor+", + "graphql query CookieSetting": "GraphQL find: anyone (banner texts, policy version)", + "graphql query Footer": "GraphQL find: anyone (site footer)", + "graphql query Form": "GraphQL find: anyone (the form renders from it; the Emails tab is staff-only by field access)", + "graphql query FormSubmission": "GraphQL find: editor+ (visitors' personal data)", + "graphql query FormSubmissions": "GraphQL find: editor+ (visitors' personal data)", + "graphql query Forms": "GraphQL find: anyone (the form renders from it; the Emails tab is staff-only by field access)", + "graphql query Header": "GraphQL find: anyone (site navigation)", + "graphql query Media": "GraphQL find: anyone (public files)", + "graphql query Notification": "GraphQL find: anyone (public-facing texts)", + "graphql query Page": "GraphQL find: anyone (published content, no drafts)", + "graphql query Pages": "GraphQL find: anyone (published content, no drafts)", + "graphql query PayloadKv": "GraphQL find: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)", + "graphql query PayloadKvs": "GraphQL find: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)", + "graphql query PayloadLockedDocument": "GraphQL find: Payload default: any signed-in account (owner Q3)", + "graphql query PayloadLockedDocuments": "GraphQL find: Payload default: any signed-in account (owner Q3)", + "graphql query PayloadPreference": "GraphQL find: the signed-in account's own preferences only (Payload)", + "graphql query PayloadPreferences": "GraphQL find: the signed-in account's own preferences only (Payload)", + "graphql query Post": "GraphQL find: anyone (published content, no drafts)", + "graphql query Posts": "GraphQL find: anyone (published content, no drafts)", + "graphql query SiteIntegration": "GraphQL find: admin (SMTP, keys, integrations)", + "graphql query SiteSetting": "GraphQL find: anyone (brand, homepage, construction mode)", + "graphql query User": "GraphQL find: an admin, or the account itself (adminOrSelfIn users)", + "graphql query Users": "GraphQL find: an admin, or the account itself (adminOrSelfIn users)", + "graphql query allMedia": "GraphQL find: anyone (public files)", + "graphql query countCaseStudies": "GraphQL count: anyone (published content, no drafts)", + "graphql query countConsentRecords": "GraphQL count: admin", + "graphql query countCookieReviews": "GraphQL count: editor+", + "graphql query countFormSubmissions": "GraphQL count: editor+ (visitors' personal data)", + "graphql query countForms": "GraphQL count: anyone (the form renders from it; the Emails tab is staff-only by field access)", + "graphql query countPages": "GraphQL count: anyone (published content, no drafts)", + "graphql query countPayloadKvs": "GraphQL count: nobody (Payload: every rule false; the plugin keeps 2FA counts and the mail-service token here)", + "graphql query countPayloadLockedDocuments": "GraphQL count: Payload default: any signed-in account (owner Q3)", + "graphql query countPayloadPreferences": "GraphQL count: the signed-in account's own preferences only (Payload)", + "graphql query countPosts": "GraphQL count: anyone (published content, no drafts)", + "graphql query countUsers": "GraphQL count: an admin, or the account itself (adminOrSelfIn users)", + "graphql query countallMedia": "GraphQL count: anyone (public files)", + "graphql query docAccessCaseStudy": "GraphQL the signed-in account's own permissions on caseStudies", + "graphql query docAccessCompany": "GraphQL the signed-in account's own permissions on globals/company", + "graphql query docAccessConsentRecord": "GraphQL the signed-in account's own permissions on consent-records", + "graphql query docAccessCookieCrawl": "GraphQL the signed-in account's own permissions on globals/cookie-crawl", + "graphql query docAccessCookieReview": "GraphQL the signed-in account's own permissions on cookie-review", + "graphql query docAccessCookieSetting": "GraphQL the signed-in account's own permissions on globals/cookie-settings", + "graphql query docAccessFooter": "GraphQL the signed-in account's own permissions on globals/footer", + "graphql query docAccessForm": "GraphQL the signed-in account's own permissions on forms", + "graphql query docAccessFormSubmission": "GraphQL the signed-in account's own permissions on form-submissions", + "graphql query docAccessHeader": "GraphQL the signed-in account's own permissions on globals/header", + "graphql query docAccessMedia": "GraphQL the signed-in account's own permissions on media", + "graphql query docAccessNotification": "GraphQL the signed-in account's own permissions on globals/notifications", + "graphql query docAccessPage": "GraphQL the signed-in account's own permissions on pages", + "graphql query docAccessPayloadKv": "GraphQL the signed-in account's own permissions on payload-kv", + "graphql query docAccessPayloadLockedDocument": "GraphQL the signed-in account's own permissions on payload-locked-documents", + "graphql query docAccessPayloadPreference": "GraphQL the signed-in account's own permissions on payload-preferences", + "graphql query docAccessPost": "GraphQL the signed-in account's own permissions on posts", + "graphql query docAccessSiteIntegration": "GraphQL the signed-in account's own permissions on globals/site-integrations", + "graphql query docAccessSiteSetting": "GraphQL the signed-in account's own permissions on globals/site-settings", + "graphql query docAccessUser": "GraphQL the signed-in account's own permissions on users", + "graphql query initializedUser": "Payload: whether a first account exists (true/false only)", + "graphql query meUser": "Payload: the signed-in account itself, or null", + "next DELETE /api/[...slug]": "Payload's REST catch-all; each route behind it is listed above", + "next GET /api/[...slug]": "Payload's REST catch-all; each route behind it is listed above", + "next GET /api/graphql-playground": "Payload's GraphQL playground: 404 in production (closed-doors spec)", + "next GET /api/health": "public by design: liveness for Coolify (ok / database reachable, nothing else)", + "next GET /api/mcp": "public by design: read-only MCP server of published content (GEO)", + "next GET /indexnow-key.txt": "public by design: the IndexNow key file (proves the site owns the key)", + "next GET /llms-full.txt": "public by design: published content for AI assistants", + "next GET /llms.txt": "public by design: published content index for AI assistants", + "next GET /manifest.webmanifest": "public by design: web app manifest", + "next GET /md/[locale]/[[...slug]]": "public by design: Markdown copy of published pages (GEO)", + "next GET /robots.txt": "public by design: robots rules", + "next GET /sitemap.xml": "public by design: published pages only", + "next OPTIONS /api/[...slug]": "CORS preflight of the REST API (no data)", + "next OPTIONS /api/graphql": "CORS preflight of GraphQL (no data)", + "next PATCH /api/[...slug]": "Payload's REST catch-all; each route behind it is listed above", + "next POST /api/[...slug]": "Payload's REST catch-all; each route behind it is listed above", + "next POST /api/csp-report": "public by design: browsers post CSP violation reports; size-capped, logged only", + "next POST /api/graphql": "Payload's GraphQL; every operation is listed below with the same rules as REST", + "next POST /api/mcp": "public by design: read-only MCP server of published content (GEO); no write tool", + "next PUT /api/[...slug]": "Payload's REST catch-all (no Payload route answers PUT)" + } +} diff --git a/reference/e2e/routes.ts b/reference/e2e/routes.ts new file mode 100644 index 0000000..f662ad0 --- /dev/null +++ b/reference/e2e/routes.ts @@ -0,0 +1,12 @@ +/** + * routes:check — every public route of this site (REST, GraphQL, Next route files) against the judged list in + * e2e/routes.snapshot.json (docs/security.md "Routes nobody has judged"). Reads the config only, never the database. + * pnpm payload run e2e/routes.ts → fails on a route nobody has judged + * pnpm payload run e2e/routes.ts update → adds new routes with an empty reason (judge them), drops gone ones + * (`payload run` drops `--flags`, so the word is `update`.) From the plugin repository: pnpm routes:check [--update], + * also the first step of pnpm e2e:built. + */ +import config from '@payload-config' +import { runRouteCheck } from '@intecion/ipal-kit/doctor' + +process.exit(await runRouteCheck({ config: await config, update: process.argv.slice(2).includes('update') })) diff --git a/reference/e2e/totp.ts b/reference/e2e/totp.ts index 42cab42..30f27b7 100644 --- a/reference/e2e/totp.ts +++ b/reference/e2e/totp.ts @@ -16,3 +16,6 @@ export function totp(secret: string, now = Date.now()): string { /** The second smoke-test admin (create-test-admin.ts makes both): `e2e-admin@…` → `e2e-admin-2@…`. */ export const secondTestAdmin = (email: string): string => email.replace('@', '-2@') + +/** The smoke-test editor (create-test-admin.ts makes it): `e2e-admin@…` → `e2e-admin-editor@…`, role `editor`, the same password and secret. */ +export const editorTestAccount = (email: string): string => email.replace('@', '-editor@') diff --git a/scripts/e2e-built.mjs b/scripts/e2e-built.mjs index ca31359..9518fab 100644 --- a/scripts/e2e-built.mjs +++ b/scripts/e2e-built.mjs @@ -8,7 +8,9 @@ * once with Turbopack: * 1. production build with the late-staff fixture (E2E_LATE_STAFF=1, reference/e2e/late-staff-fixture.ts); * 2. no package manifest under .next/static (checked on disk, before anything is started); - * 3. Playwright against `next start`: e2e/late-staff.spec.ts, e2e/mail-relay.spec.ts (the mail service: the confirm + * 0. (once, before the builds) every public route is judged: `pnpm routes:check` (reference/e2e/routes.snapshot.json); + * 3. Playwright against `next start`: e2e/closed-doors.spec.ts (every door of e2e/closed-doors.ts asked as an anonymous + * visitor, a customer and an editor), e2e/late-staff.spec.ts, e2e/mail-relay.spec.ts (the mail service: the confirm * route under Next, the state block in the panel's production bundle) and the smoke tests "no package.json is published", * "client hints" (Payload's colour-scheme headers on the admin only; a public page is requested once) and every * "consent" test (banner at first paint, Global Privacy Control, equal prominence, withdrawal, the consent log). @@ -53,6 +55,9 @@ if (!args.includes('--skip-plugin-build')) { run('build the plugin', 'pnpm', ['build'], root) run('refresh the plugin copy in the reference site', 'pnpm', ['install', '--ignore-workspace'], site) } +// Every public route judged (IAWL idea 34): from the config only, without the test fixtures, before any build. +run('every public route of the reference site is judged (pnpm routes:check)', 'node', ['scripts/routes-check.mjs'], root) + // The run starts Payload with the fixture's collections, and Payload rewrites the site's generated types then. The // tree must be as it was after a required release step: the file is put back at the end — also when a step fails. const generated = ['src/payload-types.ts', 'src/app/(payload)/admin/importMap.js'].map((rel) => path.join(site, rel)).filter((file) => existsSync(file)).map((file) => ({ before: readFileSync(file), file })) @@ -83,7 +88,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, the published-files check, the client hints and consent`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'smoke', '--grep', 'late staff collection|the mail service|no package.json is published|client hints|consent'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' }) + run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints and consent`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', '--grep', 'late staff collection|the mail service|closed doors|no package.json is published|client hints|consent'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' }) passed.push(bundler) } console.log(`\n[e2e:built] passed: ${passed.join(' and ')}. (The reference site's .next now holds the ${passed.at(-1)} build WITH the fixture: rebuild with \`pnpm build\` there before other checks.)`) diff --git a/scripts/routes-check.mjs b/scripts/routes-check.mjs new file mode 100644 index 0000000..26bfcc4 --- /dev/null +++ b/scripts/routes-check.mjs @@ -0,0 +1,23 @@ +#!/usr/bin/env node +/** + * pnpm routes:check — every public route of the reference site (REST, GraphQL, Next route files) against the judged + * list reference/e2e/routes.snapshot.json (docs/security.md "Routes nobody has judged"). Fails on a route nobody + * has judged and on an entry without a reason; reads the config only, never the database. + * pnpm routes:check the check (also the first step of pnpm e2e:built) + * pnpm routes:check --update after a Payload or plugin upgrade: new routes are added with an EMPTY reason (the + * check fails until somebody writes one), gone ones dropped; review the diff + * Needs the reference site installed (pnpm install --ignore-workspace in reference/) with a current plugin copy + * (pnpm build first), and reference/.env (the config reads it; nothing connects). + * The test fixtures (E2E_LATE_STAFF, E2E_MAIL_RELAY_URL) are switched off: the list is the site's, not the tests'. + */ +import { spawnSync } from 'node:child_process' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const site = path.join(path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'), 'reference') +const update = process.argv.slice(2).includes('--update') +const env = { ...process.env } +for (const fixture of ['E2E_LATE_STAFF', 'E2E_MAIL_RELAY_URL', 'E2E_DEVELOPMENT_HOSTS']) {delete env[fixture]} +// `payload run` drops --flags (minimist), so the script takes the word `update` +const result = spawnSync('pnpm', ['payload', 'run', 'e2e/routes.ts', ...(update ? ['update'] : [])], { cwd: site, env, stdio: 'inherit' }) +process.exit(result.status ?? 1) diff --git a/src/exports/doctor.ts b/src/exports/doctor.ts index 73c7a6b..7d80aa6 100644 --- a/src/exports/doctor.ts +++ b/src/exports/doctor.ts @@ -17,6 +17,9 @@ export { AUDIT_RULE_MAP, parseToolOutput } from '../modules/doctor/rules/tooling export { applySettings, AUDIT_SKIP_RULES, doctorRules, globToRegExp, runDeepProbe, runDoctor } from '../modules/doctor/run.js' export type { RunDoctorOptions } from '../modules/doctor/run.js' export { buildDoctorEndpoint, collectDoctorStatus } from '../modules/doctor/status.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' export type { DoctorEndpointOptions } from '../modules/doctor/status.js' export type { DoctorConfig, diff --git a/src/index.ts b/src/index.ts index cfdf136..f63b78a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -457,6 +457,9 @@ export type { } from './modules/security/index.js' export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js' +// The doors a built config opens (REST, GraphQL, Next route files) and the judged snapshot they are checked against. +export { compareRouteSnapshot, listNextRouteFiles, listPublicRoutes, updateRouteSnapshot } from './modules/security/routeInventory.js' +export type { GraphqlSchemaLike, RouteInventoryOptions, RouteSnapshot, RouteSnapshotDiff } from './modules/security/routeInventory.js' export { findImportMapFile, missingImportMapEntries } from './modules/security/totp/importMapCheck.js' export { changedViewKeys, copyViews, SAFE_TOTP_VIEW, safeAdminBack, totpViewImportKey, wrapTotpViews } from './modules/security/totp/safeBack.js' export type { SafeBackContext, SafeBackRule, TotpViewComponent } from './modules/security/totp/safeBack.js' diff --git a/src/modules/security/routeCheck.ts b/src/modules/security/routeCheck.ts new file mode 100644 index 0000000..adcdcf6 --- /dev/null +++ b/src/modules/security/routeCheck.ts @@ -0,0 +1,88 @@ +import type { SanitizedConfig } from 'payload' + +import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { join, relative, sep } from 'node:path' +import { pathToFileURL } from 'node:url' + +import type { GraphqlSchemaLike, RouteSnapshot } from './routeInventory.js' + +import { compareRouteSnapshot, listNextRouteFiles, listPublicRoutes, updateRouteSnapshot } from './routeInventory.js' + +export type RunRouteCheckOptions = { + /** The Next app directory, relative to `cwd`. Default `src/app`. */ + appDir?: string + /** The project's config (`await config` from `@payload-config`). */ + config: SanitizedConfig + cwd?: string + /** Set false when the project has no `/api/graphql` route (no GraphQL operation is then listed). Default true. */ + graphql?: boolean + log?: (line: string) => void + /** The judged list, relative to `cwd`. Default `e2e/routes.snapshot.json`. */ + snapshot?: string + /** Write new routes (with an empty reason) and drop gone ones, instead of only checking. */ + update?: boolean +} + +type SnapshotFile = { $comment?: string; routes: RouteSnapshot } + +const COMMENT = + 'Every public door of this site: REST routes, GraphQL operations, Next route files. One line per entry: who may use it and why it is open (or that it is closed and to whom). A new route fails `routes:check` until somebody judges it here. `--update` adds new routes with an empty reason and drops gone ones. docs/security.md "Routes nobody has judged".' + +/** `@payloadcms/graphql`, the copy next to the project's `@payloadcms/next` (the one `/api/graphql` uses). */ +async function loadSchema(config: SanitizedConfig, cwd: string): Promise { + // @payloadcms/next exports no main entry: its folder is looked up along the module paths (the project's first) + const folders = [ + ...(createRequire(join(cwd, 'package.json')).resolve.paths('@payloadcms/next') ?? []), + ...(createRequire(import.meta.url).resolve.paths('@payloadcms/next') ?? []), + ] + const found = folders.map((dir) => join(dir, '@payloadcms', 'next')).find((dir) => existsSync(join(dir, 'package.json'))) + if (!found) {throw new Error('routes:check: @payloadcms/next not found (pass graphql: false for a site without /api/graphql)')} + const root = realpathSync(found) + const graphqlEntry = createRequire(join(root, 'package.json')).resolve('@payloadcms/graphql') + const mod = (await import(pathToFileURL(graphqlEntry).href)) as { configToSchema: (c: SanitizedConfig) => { schema: GraphqlSchemaLike } } + return mod.configToSchema(config).schema +} + +function walk(dir: string): string[] { + if (!existsSync(dir)) {return []} + return readdirSync(dir).flatMap((name) => { + const full = join(dir, name) + return statSync(full).isDirectory() ? walk(full) : [full] + }) +} + +/** + * `routes:check`: lists the site's public routes (listPublicRoutes + the Next route files) and compares them with the + * committed, judged snapshot. Returns the exit code: 0 all judged, 1 a route nobody judged or an entry without a reason. + * With `update`, writes the snapshot (new routes with an empty reason, so the check fails until somebody writes one). + */ +export async function runRouteCheck(options: RunRouteCheckOptions): Promise { + const cwd = options.cwd ?? process.cwd() + const log = options.log ?? ((line: string) => console.log(line)) + const appDir = join(cwd, options.appDir ?? 'src/app') + const snapshotFile = join(cwd, options.snapshot ?? 'e2e/routes.snapshot.json') + const routeFiles = listNextRouteFiles(walk(appDir).map((file) => relative(appDir, file).split(sep).join('/')), (file) => readFileSync(join(appDir, file), 'utf8')) + const current = listPublicRoutes(options.config, { + graphqlSchema: options.graphql === false ? undefined : await loadSchema(options.config, cwd), + routeFiles, + }) + const saved: SnapshotFile = existsSync(snapshotFile) ? (JSON.parse(readFileSync(snapshotFile, 'utf8')) as SnapshotFile) : { routes: {} } + if (options.update) { + const routes = updateRouteSnapshot(current, saved.routes ?? {}) + writeFileSync(snapshotFile, `${JSON.stringify({ $comment: saved.$comment ?? COMMENT, routes }, null, 2)}\n`) + const diff = compareRouteSnapshot(current, routes) + log(`[routes] wrote ${relative(cwd, snapshotFile)}: ${current.length} routes, ${diff.unexplained.length} without a reason`) + return diff.unexplained.length ? 1 : 0 + } + const diff = compareRouteSnapshot(current, saved.routes ?? {}) + for (const id of diff.unjudged) {log(` ✗ not judged: ${id}`)} + for (const id of diff.unexplained) {log(` ✗ no reason: ${id}`)} + for (const id of diff.gone) {log(` · gone (drop it with --update): ${id}`)} + if (diff.unjudged.length || diff.unexplained.length) { + log(`[routes] ✗ ${diff.unjudged.length} route(s) nobody has judged, ${diff.unexplained.length} without a reason — judge them in ${relative(cwd, snapshotFile)} (\`--update\` adds them with an empty reason)`) + return 1 + } + log(`[routes] ✓ ${current.length} public routes, every one judged${diff.gone.length ? ` (${diff.gone.length} gone)` : ''}`) + return 0 +} diff --git a/src/modules/security/routeInventory.ts b/src/modules/security/routeInventory.ts new file mode 100644 index 0000000..4a632d9 --- /dev/null +++ b/src/modules/security/routeInventory.ts @@ -0,0 +1,125 @@ +import type { SanitizedConfig } from 'payload' + +/** + * Every door a built Payload config opens to the web, as stable one-line ids — for a test that fails when a new + * Payload, a plugin or a project change adds a public route nobody has judged (IAWL idea 34). + * + * GET /api/users/me a REST endpoint of a collection (Payload's own or a custom one) + * POST /api/globals/header a REST endpoint of a global + * POST /api/ipal/hit a root endpoint (the plugin's own, a project's, Payload's) + * graphql query Users a GraphQL query / mutation (pass `graphqlSchema`) + * next GET /sitemap.xml a Next route handler of the project (pass `routeFiles`, see `listNextRouteFiles`) + * + * The list comes from the config alone, never from the database, so it is the same on MongoDB, Postgres and SQLite. + * Ids carry no ids or slugs of documents, only route patterns (`/:id`), so the list does not change with content. + */ +export type RouteInventoryOptions = { + /** + * The schema `/api/graphql` serves (`configToSchema(config).schema` from `@payloadcms/graphql`). Left out, no + * GraphQL operation is listed. The plugin does not import `@payloadcms/graphql` itself. + */ + graphqlSchema?: GraphqlSchemaLike + /** Next route handlers of the project, e.g. from `listNextRouteFiles` (`{ path: '/sitemap.xml', methods: ['GET'] }`). */ + routeFiles?: { methods: string[]; path: string }[] +} + +/** The two methods of a `graphql` GraphQLSchema that the inventory uses. */ +export type GraphqlSchemaLike = { + getMutationType: () => { getFields: () => Record } | null | undefined + getQueryType: () => { getFields: () => Record } | null | undefined +} + +type EndpointLike = { method?: string; path?: string } +type EntityLike = { endpoints?: EndpointLike[] | false; graphQL?: false | object; slug: string } + +const rest = (method: string | undefined, path: string) => `${(method ?? 'get').toUpperCase()} ${path}` +const join = (base: string, path: string | undefined) => `${base}${!path || path === '/' ? '' : path.startsWith('/') ? path : `/${path}`}` + +export function listPublicRoutes(config: SanitizedConfig, options: RouteInventoryOptions = {}): string[] { + const api = config.routes?.api ?? '/api' + const out = new Set() + for (const endpoint of Array.isArray(config.endpoints) ? (config.endpoints as EndpointLike[]) : []) { + out.add(rest(endpoint.method, join(api, endpoint.path))) + } + for (const collection of (config.collections ?? []) as unknown as EntityLike[]) { + for (const endpoint of Array.isArray(collection.endpoints) ? collection.endpoints : []) { + out.add(rest(endpoint.method, join(`${api}/${collection.slug}`, endpoint.path))) + } + } + for (const global of (config.globals ?? []) as unknown as EntityLike[]) { + for (const endpoint of Array.isArray(global.endpoints) ? global.endpoints : []) { + out.add(rest(endpoint.method, join(`${api}/globals/${global.slug}`, endpoint.path))) + } + } + const schema = options.graphqlSchema + if (schema) { + for (const name of Object.keys(schema.getQueryType()?.getFields() ?? {})) {out.add(`graphql query ${name}`)} + for (const name of Object.keys(schema.getMutationType()?.getFields() ?? {})) {out.add(`graphql mutation ${name}`)} + } + for (const file of options.routeFiles ?? []) { + for (const method of file.methods) {out.add(`next ${method.toUpperCase()} ${file.path}`)} + } + return [...out].sort() +} + +const ROUTE_METHODS = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT'] as const +/** Metadata files Next answers as routes (robots.txt, sitemap.xml, manifest.webmanifest). */ +const METADATA_ROUTES: Record = { manifest: '/manifest.webmanifest', robots: '/robots.txt', sitemap: '/sitemap.xml' } + +/** + * The route handlers of a Next app directory: every `route.ts|js` with the HTTP methods it exports, and the + * metadata routes (`robots.ts`, `sitemap.ts`, `manifest.ts`). `files` are paths relative to the app directory + * (`api/health/route.ts`); route groups `(name)` are left out of the path. `read(file)` returns a file's code (fs in + * a script, a map in a test). + */ +export function listNextRouteFiles( + files: string[], + read: (file: string) => string, +): { methods: string[]; path: string }[] { + const out: { methods: string[]; path: string }[] = [] + for (const file of files) { + const parts = file.split('/').filter((p) => p && !/^\(.*\)$/.test(p)) + const name = parts.pop() ?? '' + const base = name.replace(/\.(?:[cm]?[jt]sx?)$/, '') + const path = `/${parts.join('/')}` + if (base === 'route') { + const code = read(file) + const methods = ROUTE_METHODS.filter((m) => + new RegExp(`export\\s+(?:async\\s+)?(?:function|const|let|var)\\s+${m}\\b|export\\s*\\{[^}]*\\b(?:as\\s+)?${m}\\b[^}]*\\}`).test(code), + ) + if (methods.length) {out.push({ methods: [...methods], path })} + } else if (parts.length === 0 && METADATA_ROUTES[base]) { + out.push({ methods: ['GET'], path: METADATA_ROUTES[base] }) + } + } + return out.sort((a, b) => a.path.localeCompare(b.path)) +} + +/** A judged route list: route id → one line saying who may use it and why it is open (or closed). */ +export type RouteSnapshot = Record + +export type RouteSnapshotDiff = { + /** Entries whose reason is empty or still says TODO. */ + unexplained: string[] + /** Routes the config has and the snapshot does not. */ + unjudged: string[] + /** Routes the snapshot has and the config no longer opens (not a failure; `--update` drops them). */ + gone: string[] +} + +export function compareRouteSnapshot(current: string[], snapshot: RouteSnapshot): RouteSnapshotDiff { + const judged = new Set(Object.keys(snapshot)) + const now = new Set(current) + return { + gone: [...judged].filter((id) => !now.has(id)).sort(), + unexplained: [...judged].filter((id) => now.has(id) && (!snapshot[id]?.trim() || /^TODO\b/i.test(snapshot[id]!.trim()))).sort(), + unjudged: current.filter((id) => !judged.has(id)), + } +} + +/** The snapshot after `--update`: new routes added with an empty reason (still a failure), gone ones dropped. */ +export function updateRouteSnapshot(current: string[], snapshot: RouteSnapshot): RouteSnapshot { + const next: RouteSnapshot = {} + for (const id of current) {next[id] = snapshot[id] ?? ''} + return next +} diff --git a/test/routeInventory.test.ts b/test/routeInventory.test.ts new file mode 100644 index 0000000..67dba44 --- /dev/null +++ b/test/routeInventory.test.ts @@ -0,0 +1,121 @@ +/** + * The route inventory behind `pnpm routes:check` (IAWL idea 34): every REST route, GraphQL operation and Next route + * file of a built config, compared with a judged snapshot. The list is made from the config only, so the same + * config on MongoDB, Postgres and SQLite gives the same list (the check must not be flaky across databases). + */ +import type { Config, SanitizedConfig } from 'payload' + +import { mongooseAdapter } from '@payloadcms/db-mongodb' +import { postgresAdapter } from '@payloadcms/db-postgres' +import { sqliteAdapter } from '@payloadcms/db-sqlite' +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import { realpathSync } from 'node:fs' +import path from 'node:path' +import { pathToFileURL } from 'node:url' +import { describe, expect, test, vi } from 'vitest' + +import type { GraphqlSchemaLike } from '../src/modules/security/routeInventory.js' + +import { iapl } from '../src/plugin.js' +import { compareRouteSnapshot, listNextRouteFiles, listPublicRoutes, updateRouteSnapshot } from '../src/modules/security/routeInventory.js' +import { buildTestConfig } from './helpers.js' + +vi.mock('server-only', () => ({})) + +async function configToSchema(config: SanitizedConfig): Promise { + const next = realpathSync(path.resolve(import.meta.dirname, '../node_modules/@payloadcms/next')) + const graphql = realpathSync(path.join(next, '..', 'graphql')) + const mod = (await import(pathToFileURL(path.join(graphql, 'dist/index.js')).href)) as { configToSchema: (c: SanitizedConfig) => { schema: GraphqlSchemaLike } } + return mod.configToSchema(config).schema +} + +const adapters = { + mongodb: () => mongooseAdapter({ url: 'mongodb://127.0.0.1:1/never-connected' }), + postgres: () => postgresAdapter({ pool: { connectionString: 'postgres://nobody@127.0.0.1:1/never-connected' } }), + sqlite: () => sqliteAdapter({ client: { url: 'file::memory:' } }), +} + +const build = (db: Config['db']) => + buildTestConfig({ + collections: [ + { slug: 'users', auth: true, fields: [] }, + { slug: 'pages', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }], versions: { drafts: true } }, + { slug: 'media', fields: [], upload: true }, + ], + db, + editor: lexicalEditor(), + plugins: [ + iapl({ + access: { authCollection: 'users' }, + cookieScanner: { crawl: { serviceUrl: 'http://crawler.test', siteUrl: 'http://site.test', token: 'x' } }, + forms: { attachments: true, emailLayout: true }, + i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }, + pages: { slug: 'pages' }, + seo: { collections: ['pages'] }, + stats: true, + twoFactor: false, + } as never), + ], + secret: 'route-inventory-test', + telemetry: false, + } as unknown as Config) + +describe('listPublicRoutes', () => { + test('lists Payload\'s routes, the plugin\'s own and GraphQL; the same on MongoDB, Postgres and SQLite', async () => { + const lists: Record = {} + for (const [name, adapter] of Object.entries(adapters)) { + const config = await build(adapter()) + lists[name] = listPublicRoutes(config, { graphqlSchema: await configToSchema(config) }) + } + const sqlite = lists.sqlite! + expect(lists.mongodb).toEqual(sqlite) + expect(lists.postgres).toEqual(sqlite) + for (const id of [ + 'POST /api/users/login', + 'POST /api/users/first-register', + 'GET /api/pages/versions', + 'POST /api/ipal/forms/submit', + 'POST /api/ipal/hit', + 'POST /api/ipal/cookie-crawl/results', + 'POST /api/globals/site-integrations', + 'graphql query Users', + 'graphql mutation loginUser', + ]) { + expect(sqlite, id).toContain(id) + } + expect(sqlite).toEqual([...sqlite].sort()) + }, 60_000) + + test('Next route files: exported methods, route groups left out, metadata routes', () => { + const code: Record = { + '(payload)/api/[...slug]/route.ts': 'export const GET = a\nexport const POST = b\nexport const OPTIONS = c', + 'api/health/route.ts': 'export async function GET() {}', + 'api/mcp/route.ts': "export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'", + 'md/[locale]/[[...slug]]/route.ts': 'export const dynamic = "force-dynamic"\nexport function GET() {}', + 'robots.ts': 'export default function robots() {}', + 'sitemap.xml/route.ts': 'export const GET = handler', + '(frontend)/[locale]/page.tsx': 'export default function Page() {}', + } + expect(listNextRouteFiles(Object.keys(code), (f) => code[f]!)).toEqual([ + { methods: ['GET', 'OPTIONS', 'POST'], path: '/api/[...slug]' }, + { methods: ['GET'], path: '/api/health' }, + { methods: ['GET', 'POST'], path: '/api/mcp' }, + { methods: ['GET'], path: '/md/[locale]/[[...slug]]' }, + { methods: ['GET'], path: '/robots.txt' }, + { methods: ['GET'], path: '/sitemap.xml' }, + ]) + }) +}) + +describe('the judged snapshot', () => { + test('a new route, an empty or TODO reason fail; a gone route is listed', () => { + const diff = compareRouteSnapshot(['GET /a', 'GET /b', 'GET /new', 'GET /todo'], { 'GET /a': 'public: published pages', 'GET /b': ' ', 'GET /old': 'x', 'GET /todo': 'TODO judge' }) + expect(diff).toEqual({ gone: ['GET /old'], unexplained: ['GET /b', 'GET /todo'], unjudged: ['GET /new'] }) + }) + + test('--update adds new routes with an empty reason (still failing) and drops gone ones, keeping the reasons', () => { + const next = updateRouteSnapshot(['GET /a', 'GET /new'], { 'GET /a': 'kept reason', 'GET /old': 'x' }) + expect(next).toEqual({ 'GET /a': 'kept reason', 'GET /new': '' }) + expect(compareRouteSnapshot(['GET /a', 'GET /new'], next).unexplained).toEqual(['GET /new']) + }) +})