diff --git a/bin/iapl-skills.mjs b/bin/iapl-skills.mjs index 9c59b82..ab98dbf 100755 --- a/bin/iapl-skills.mjs +++ b/bin/iapl-skills.mjs @@ -16,8 +16,8 @@ // text between the markers is ever rewritten; the project's own content stays as it is. import { createHash } from 'node:crypto' -import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs' -import { dirname, join, relative, resolve } from 'node:path' +import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs' +import { basename, dirname, join, relative, resolve, sep } from 'node:path' import { fileURLToPath } from 'node:url' const args = process.argv.slice(2) @@ -39,8 +39,22 @@ if (!destValue || destValue.startsWith('-')) { process.exit(1) } const dest = resolve(process.cwd(), destValue) -if (dest === resolve(process.cwd())) { - console.error('iapl-skills: --dest must be a subdirectory, not the project root') +// Compared AFTER resolving links: `--dest root-link` (a link to `.`), `..` or `/` would otherwise pass and lose +// the iapl-* folders of the project root, its parent or the filesystem root. A folder that does not exist yet is +// resolved through its nearest existing parent. +const real = (path) => { + const rest = [] + let at = path + while (!existsSync(at) && dirname(at) !== at) { + rest.unshift(basename(at)) + at = dirname(at) + } + return join(realpathSync(at), ...rest) +} +const realDest = real(dest) +const realRoot = real(resolve(process.cwd())) +if (realDest === realRoot || realRoot.startsWith(realDest.endsWith(sep) ? realDest : `${realDest}${sep}`)) { + console.error(`iapl-skills: --dest must be a folder inside the project or elsewhere, not the project root or a folder that holds it (${destValue} is ${realDest})`) process.exit(1) } 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 6d979a5..4089a4a 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -528,7 +528,7 @@ No abbreviations (`HeroSection`, not `HeroSec`). Do not create `lib/pages.ts`, 1. **`proxy.ts`, never `middleware.ts`.** middleware.ts exists → delete it. Proxy: `export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true })`, the matcher - as an **inline literal** (`['/((?!api|admin|_next|.*\\..*).*)']`), not an import. + as an **inline literal** (`['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)']`), not an import. 2. **No explicit `` in the layout.** It pushes metadata into ``. `` in `` (React 19 hoists it). 3. **ISR:** `export const revalidate = 3600` in `page.tsx`. Refresh after save: @@ -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/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md index b2e4881..6f7e685 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -265,7 +265,7 @@ import { i18nConfig } from '@/i18n.config' export const proxy = createProxy(i18nConfig, { markdown: true, NextResponse }) // Inline LITERAL — Next reads the matcher statically (importing DEFAULT_PROXY_MATCHER breaks /admin) -export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } ``` ## Collections and globals @@ -1164,6 +1164,8 @@ Rules: AGENT.md §8a. | File | What it shows | |---|---| +| `e2e/closed-doors.spec.ts` | closed doors from outside (run by `pnpm e2e:built` in both bundlers): every door of e2e/closed-doors.ts asked on the production build as an anonymous visitor, a customer (the fixture's `e2e-visitors`) and an editor; doors still open while the owner decides are asserted open (`test.fail`) | +| `e2e/closed-doors.ts` | the doors that must stay closed, who each is closed for and how a closed answer looks; a project adds its own (security.md "Closed doors from outside") | | `e2e/create-test-admin.ts` | two test admins with a known TOTP secret (the specs share out the five 2FA verify attempts per account), their stored verify counts cleared, and e-mail sending pointed at the tests' mail sink (local / CI database only) | | `e2e/global-setup.ts` | Playwright global setup: resets the test admins and clears their stored 2FA attempt counts before every run, so specs do not depend on run order (below) | | `e2e/late-staff-fixture.ts` | test fixture, on only with E2E_LATE_STAFF=1: one plugin before iapl (staff collections of the config: roles with one more value, the plugin's roles, roles of the project's own) and one after it (a staff collection without rules, one whose roles field is text, copies of staff collections under new slugs — plain, with rules of their own, one rule used for another operation, other role values, the opt-out, not staff — and a visitor collection with open sign-up) | @@ -1171,9 +1173,11 @@ Rules: AGENT.md §8a. | `e2e/mail-relay-fixture.ts` | test fixture, on only with E2E_MAIL_RELAY_URL: points the mail service's client at the stand-in the spec starts; never in a real site (a real site names no address) (below) | | `e2e/mail-relay-setup.ts` | for the mail-service spec: empties the SMTP fields and the stored token, so the next e-mail enrols and goes through the mail service (local database only) (below) | | `e2e/mail-relay.spec.ts` | the mail service on a built site: the state block in the panel, the first e-mail through the public confirm route, no token in anything the browser receives | +| `e2e/routes.snapshot.json` | every public route of the site (REST, GraphQL, Next route files) with one line saying who may use it and why — the judged list `routes:check` compares with | +| `e2e/routes.ts` | `routes:check`: the site's public routes against e2e/routes.snapshot.json (`pnpm payload run e2e/routes.ts [update]`; from the repository `pnpm routes:check`) (below) | | `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA | | `e2e/smtp-sink.ts` | a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments) | -| `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test, and the address of the second test admin (below) | +| `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test, and the addresses of the second test admin and the test editor (below) | | `e2e/two-factor-back.spec.ts` | browser test of the 2FA screens' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed | | `e2e/two-factor-setup.spec.ts` | browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator's reset on the account page | @@ -1249,6 +1253,23 @@ console.log('[e2e] no SMTP server and no mail-service token: the next e-mail enr process.exit(0) ``` +### `e2e/routes.ts` + +```ts +/** + * 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') })) +``` + ### `e2e/totp.ts` ```ts @@ -1270,4 +1291,7 @@ 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/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-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index aa08390..500b89e 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -865,6 +865,10 @@ Bin: `iapl-doctor` (`pnpm exec iapl-doctor [dir] [--json] [--md] [--strict] [--f | `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. | | `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. | | `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IAPL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `iapl` unless `doctor: false`. | +| `runRouteCheck({ config, appDir?, snapshot?, update?, graphql?, cwd?, log? })` | `@intecion/ipal-kit/doctor` | `routes:check`: every public route (REST, GraphQL, Next route files) against the judged snapshot (default `e2e/routes.snapshot.json`); returns 1 on a route nobody judged or an entry without a reason; `update` writes new routes with an empty reason. Template: `iapl-audit/resources/routes.template.ts` (security.md "Routes nobody has judged"). Type `RunRouteCheckOptions`. | +| `listPublicRoutes(config, { graphqlSchema?, routeFiles? })` | `@intecion/ipal-kit` | Stable ids of every door a built config opens: `GET /api/users/me`, `graphql mutation loginUser`, `next GET /sitemap.xml`. From the config only (same on every database). Types `RouteInventoryOptions`, `GraphqlSchemaLike` (`getQueryType` / `getMutationType`). | +| `listNextRouteFiles(files, read)` | `@intecion/ipal-kit` | Next route handlers of an app directory (`route.ts` with the methods it exports, `robots.ts`, `sitemap.ts`, `manifest.ts`; route groups left out). | +| `compareRouteSnapshot(current, snapshot)` / `updateRouteSnapshot(current, snapshot)` | `@intecion/ipal-kit` | `{ unjudged, unexplained, gone }` against a `RouteSnapshot` (route id → reason); the snapshot after `--update` (new routes with `''`, gone ones dropped). Type `RouteSnapshotDiff`. | **Types:** `DoctorRule`, `DoctorFinding`, `RuleFinding`, `DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`, `DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`, `FrontendLayout`. diff --git a/docs/agent/skills/iapl-setup/SKILL.md b/docs/agent/skills/iapl-setup/SKILL.md index 0d19ced..78453e9 100644 --- a/docs/agent/skills/iapl-setup/SKILL.md +++ b/docs/agent/skills/iapl-setup/SKILL.md @@ -401,7 +401,7 @@ import { createProxy } from '@intecion/ipal-kit' import { i18nConfig } from '@/i18n.config' export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true }) // Inline LITERAL (importing DEFAULT_PROXY_MATCHER = 500 on /admin); with adminRoute '/its' write `its` instead of `admin` -export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } ``` `src/lib/content.ts` = PROGRAMISTA §2.7 1:1: `createContentHelpers({ config, content: contentConfig, i18n: i18nConfig, baseUrl: process.env.NEXT_PUBLIC_SERVER_URL, markdownAlternate: true, summaryField: 'aiSummary', mcp: { serverName: diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 8e2e432..4bd9e93 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/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index 5003745..d3b1365 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -245,7 +245,7 @@ import { i18nConfig } from '@/i18n.config' export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true }) // Inline literal — Next analyzes it statically; importing a variable = proxy on /admin → 500 -export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } ``` Sets `x-locale` / `x-pathname`, the language cookie with consent, redirects `/`. The headers are for dynamic routes (API, route handlers) — in SSG/ISR pages, diff --git a/docs/doctor.md b/docs/doctor.md index 9448041..3f11bec 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -101,6 +101,7 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE | | `env-live` | error | (deep) the project's env rules pass in the real environment | | security | `security-headers` | error | `buildSecurityHeaders`; live: HSTS, nosniff, Referrer-Policy, Permissions-Policy, frame protection | | | `powered-by` | error | `withSecurityConfig`; live: no `X-Powered-By` on `/` and the admin | +| | `proxy-matcher` | warning | `src/proxy.ts`: a matcher that skips `api`, `admin` or `_next` without ending them at "/" (`(?!api|admin|…)`) also skips every page whose first segment only starts with them (`/administracja`): no locale redirect, no proxy CSP. Fix: the literal in i18n.md (1.17.1) | | | `client-hints` | info | `withSecurityConfig` is the outer wrapper (`withSecurityConfig(withPayload(…))`), so Payload's colour-scheme client hints go to the admin only; live: `/` sends no `Critical-CH: Sec-CH-Prefers-Color-Scheme`. Not reported with `adminClientHints: false` | | | `csp` | warning / info | CSP on the site and the admin; report-only is info, a warning after 4 weeks (`seen`) | | | `2fa` | error | `twoFactor: { plugin: payloadTotp }` + the package; deep: 0 users without TOTP (the message says how many of them are blocked because their setup window has passed); error: a Postgres / SQLite project whose migrations do not mention the 2FA column `totp_setup_from` (every login would answer 500; a warning when there is no migrations folder — the doctor cannot see a schema that gets there another way); warning: `twoFactor.requireSetup: false`; info: no setup window (`windowHours: false`) | diff --git a/docs/i18n.md b/docs/i18n.md index b684438..6fcbb3d 100644 --- a/docs/i18n.md +++ b/docs/i18n.md @@ -132,7 +132,7 @@ See [proxy in this section](#proxy-formerly-middleware) below. > import { createProxy } from '@intecion/ipal-kit' > import { i18nConfig } from '@/i18n.config' > export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true }) // markdown: GEO, content.md -> export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +> export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } > ``` > Use the manual variant below only when you need your own logic in the proxy. @@ -171,7 +171,7 @@ export function proxy(req) { return res } -export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } // = DEFAULT_MIDDLEWARE_MATCHER, inline +export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } // = DEFAULT_MIDDLEWARE_MATCHER, inline ``` Behavior: @@ -182,7 +182,7 @@ Behavior: `DEFAULT_MIDDLEWARE_MATCHER` excludes `api`, `admin`, `_next`, static files. The `admin` prefix is hard-coded — with a custom `adminRoute` (e.g. `/its`) add -it to the matcher (`'/((?!api|its|_next|.*\\..*).*)'`), otherwise the proxy redirects the admin panel +it to the matcher (`'/((?!(?:api|its|_next)(?:/|$)|.*\\..*).*)'`), otherwise the proxy redirects the admin panel to `/pl/its`. ## Locale cookie and consent (GDPR) @@ -398,7 +398,7 @@ in the proxy/middleware file, not an import/variable. Even though the plugin exp ```ts // proxy.ts — matcher INLINE (not an import) -export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } ``` Use `DEFAULT_PROXY_MATCHER` as a reference value, but if Next complains diff --git a/docs/security.md b/docs/security.md index 5a09063..fafb3de 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1106,6 +1106,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 7bea0ea..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", @@ -204,6 +205,9 @@ "registry": "https://git.intecion.net/api/packages/IntecionSoftware/npm/" }, "pnpm": { + "ignoredBuiltDependencies": [ + "@swc/core" + ], "onlyBuiltDependencies": [ "sharp", "esbuild", 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-reference/resources/api.md b/reference/.agents/skills/iapl-reference/resources/api.md index 1791160..182ce98 100644 --- a/reference/.agents/skills/iapl-reference/resources/api.md +++ b/reference/.agents/skills/iapl-reference/resources/api.md @@ -865,6 +865,10 @@ Bin: `iapl-doctor` (`pnpm exec iapl-doctor [dir] [--json] [--md] [--strict] [--f | `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. | | `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. | | `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IAPL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `iapl` unless `doctor: false`. | +| `runRouteCheck({ config, appDir?, snapshot?, update?, graphql?, cwd?, log? })` | `@intecion/ipal-kit/doctor` | `routes:check`: every public route (REST, GraphQL, Next route files) against the judged snapshot (default `e2e/routes.snapshot.json`); returns 1 on a route nobody judged or an entry without a reason; `update` writes new routes with an empty reason. Template: `iapl-audit/resources/routes.template.ts` (security.md "Routes nobody has judged"). Type `RunRouteCheckOptions`. | +| `listPublicRoutes(config, { graphqlSchema?, routeFiles? })` | `@intecion/ipal-kit` | Stable ids of every door a built config opens: `GET /api/users/me`, `graphql mutation loginUser`, `next GET /sitemap.xml`. From the config only (same on every database). Types `RouteInventoryOptions`, `GraphqlSchemaLike` (`getQueryType` / `getMutationType`). | +| `listNextRouteFiles(files, read)` | `@intecion/ipal-kit` | Next route handlers of an app directory (`route.ts` with the methods it exports, `robots.ts`, `sitemap.ts`, `manifest.ts`; route groups left out). | +| `compareRouteSnapshot(current, snapshot)` / `updateRouteSnapshot(current, snapshot)` | `@intecion/ipal-kit` | `{ unjudged, unexplained, gone }` against a `RouteSnapshot` (route id → reason); the snapshot after `--update` (new routes with `''`, gone ones dropped). Type `RouteSnapshotDiff`. | **Types:** `DoctorRule`, `DoctorFinding`, `RuleFinding`, `DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`, `DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`, `FrontendLayout`. diff --git a/reference/.agents/skills/iapl-setup/SKILL.md b/reference/.agents/skills/iapl-setup/SKILL.md index 6e48a13..8857e7c 100644 --- a/reference/.agents/skills/iapl-setup/SKILL.md +++ b/reference/.agents/skills/iapl-setup/SKILL.md @@ -399,7 +399,7 @@ import { createProxy } from '@intecion/ipal-kit' import { i18nConfig } from '@/i18n.config' export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true }) // Inline LITERAL (importing DEFAULT_PROXY_MATCHER = 500 on /admin); with adminRoute '/its' write `its` instead of `admin` -export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } ``` `src/lib/content.ts` = PROGRAMISTA §2.7 1:1: `createContentHelpers({ config, content: contentConfig, i18n: i18nConfig, baseUrl: process.env.NEXT_PUBLIC_SERVER_URL, markdownAlternate: true, summaryField: 'aiSummary', mcp: { serverName: 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/reference/src/proxy.ts b/reference/src/proxy.ts index ae749be..bd288ce 100644 --- a/reference/src/proxy.ts +++ b/reference/src/proxy.ts @@ -7,4 +7,4 @@ import { i18nConfig } from '@/i18n.config' export const proxy = createProxy(i18nConfig, { markdown: true, NextResponse }) // Inline LITERAL — Next reads the matcher statically (importing DEFAULT_PROXY_MATCHER breaks /admin) -export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } 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/reference-index.mjs b/scripts/reference-index.mjs index 70d1123..5a1e053 100644 --- a/scripts/reference-index.mjs +++ b/scripts/reference-index.mjs @@ -61,6 +61,8 @@ export const DESCRIPTIONS = { 'docs/DEPLOY.md': 'the Coolify runbook: local check, app settings, MongoDB resource, env, targeted seeds, DNS, rollback', 'e2e/create-test-admin.ts': 'two test admins with a known TOTP secret (the specs share out the five 2FA verify attempts per account), their stored verify counts cleared, and e-mail sending pointed at the tests\' mail sink (local / CI database only)', 'e2e/late-staff-fixture.ts': 'test fixture, on only with E2E_LATE_STAFF=1: one plugin before iapl (staff collections of the config: roles with one more value, the plugin\'s roles, roles of the project\'s own) and one after it (a staff collection without rules, one whose roles field is text, copies of staff collections under new slugs — plain, with rules of their own, one rule used for another operation, other role values, the opt-out, not staff — and a visitor collection with open sign-up)', + 'e2e/closed-doors.spec.ts': 'closed doors from outside (run by `pnpm e2e:built` in both bundlers): every door of e2e/closed-doors.ts asked on the production build as an anonymous visitor, a customer (the fixture\'s `e2e-visitors`) and an editor; doors still open while the owner decides are asserted open (`test.fail`)', + 'e2e/closed-doors.ts': 'the doors that must stay closed, who each is closed for and how a closed answer looks; a project adds its own (security.md "Closed doors from outside")', 'e2e/late-staff.spec.ts': 'the account rules on a BUILT site (run by `pnpm e2e:built` after a webpack and a Turbopack build): a staff collection a later plugin adds, staff collections whose accounts can hold `admin`, and copies of staff collections — a visitor account gets nothing, nobody raises its own role or makes an admin, a copy is never wider than the plugin\'s rule', 'e2e/global-setup.ts': 'Playwright global setup: resets the test admins and clears their stored 2FA attempt counts before every run, so specs do not depend on run order', 'e2e/two-factor-setup.spec.ts': 'browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator\'s reset on the account page', @@ -70,7 +72,9 @@ export const DESCRIPTIONS = { 'e2e/mail-relay.spec.ts': 'the mail service on a built site: the state block in the panel, the first e-mail through the public confirm route, no token in anything the browser receives', 'e2e/smtp-sink.ts': 'a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments)', 'e2e/two-factor-back.spec.ts': 'browser test of the 2FA screens\' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed', - 'e2e/totp.ts': 'RFC 6238 code generator for the 2FA sign-in in the smoke test, and the address of the second test admin', + 'e2e/routes.snapshot.json': 'every public route of the site (REST, GraphQL, Next route files) with one line saying who may use it and why — the judged list `routes:check` compares with', + 'e2e/routes.ts': '`routes:check`: the site\'s public routes against e2e/routes.snapshot.json (`pnpm payload run e2e/routes.ts [update]`; from the repository `pnpm routes:check`)', + 'e2e/totp.ts': 'RFC 6238 code generator for the 2FA sign-in in the smoke test, and the addresses of the second test admin and the test editor', 'iapl-doctor.json': 'the production domain and launch state for iapl-doctor', 'next.config.ts': 'security headers, enforced CSP, admin CSP, upload headers, images, no X-Powered-By', 'package.json': 'scripts (build, start, seed, tokens, generate), pinned Payload versions and overrides', 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..5e12cde 100644 --- a/src/exports/doctor.ts +++ b/src/exports/doctor.ts @@ -29,3 +29,6 @@ export type { DoctorStatus, RuleFinding, } from '../modules/doctor/types.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' 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/doctor/rules/security.ts b/src/modules/doctor/rules/security.ts index b5cc8c6..358e874 100644 --- a/src/modules/doctor/rules/security.ts +++ b/src/modules/doctor/rules/security.ts @@ -60,6 +60,27 @@ export const securityRules: DoctorRule[] = [ group: 'security', source: 'static', }, + { + // A matcher whose lookahead names api / admin / _next without ending them at "/" also skips every page whose + // first segment merely STARTS with those letters (/administracja, /apis): no locale redirect, and no CSP from the + // proxy on a single-locale site (IAWL idea 36, fixed in the documented literal in 1.17.1). + id: 'proxy-matcher', + check: (ctx) => { + const file = `${ctx.src}proxy.ts` + const code = stripComments(ctx.read(file)) + const loose = [...code.matchAll(/\(\?!((?:[\w-]+\|)*[\w-]+)\|/g)].map((m) => m[1].split('|')).find((names) => names.some((n) => ['_next', 'admin', 'api'].includes(n))) + if (!loose) {return []} + return [{ + file, + fix: "matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\\\..*).*)'] (i18n.md → Next matcher)", + message: `the proxy matcher skips every path that starts with ${loose.map((n) => `"${n}"`).join(', ')} (e.g. /${loose.includes('admin') ? 'administracja' : `${loose[0]}s`}), not only those folders: no locale redirect, no proxy CSP there`, + severity: 'warning', + }] + }, + docs: 'docs/i18n.md', + group: 'security', + source: 'static', + }, { id: 'client-hints', check: async (ctx) => { diff --git a/src/modules/forms/attachments/fileChecks.ts b/src/modules/forms/attachments/fileChecks.ts index d81026e..b214bb1 100644 --- a/src/modules/forms/attachments/fileChecks.ts +++ b/src/modules/forms/attachments/fileChecks.ts @@ -106,7 +106,10 @@ const REQUIRED_ENTRIES: Record = { xlsx: ['[Content_Types].xml', 'xl/workbook.xml'], } -const RISKY_ENTRY = /\.(?:bat|cmd|com|dll|exe|hta|jar|js|lnk|msi|ps1|scr|sh|vbs)$/i +// Trailing dots and spaces count as the end of the name: Windows drops them when it writes the file, so an entry +// `setup.exe.` or `setup.exe ` becomes `setup.exe` once extracted. +const RISKY_ENTRY = /\.(?:bat|cmd|com|dll|exe|hta|jar|js|lnk|msi|ps1|scr|sh|vbs)[.\s]*$/i +const MACRO_ENTRY = /vbaProject\.bin[.\s]*$/i const indexOfBytes = (bytes: Uint8Array, needle: readonly number[]) => { outer: for (let i = 0; i <= bytes.length - needle.length; i++) { @@ -188,7 +191,7 @@ export async function checkFileContent( if (!entries) {return 'signature'} const names = new Set(entries.map((e) => e.name)) if (required.some((name) => !names.has(name))) {return 'signature'} - if (entries.some((e) => e.encrypted || /vbaProject\.bin$/i.test(e.name) || RISKY_ENTRY.test(e.name))) {return 'content'} + if (entries.some((e) => e.encrypted || MACRO_ENTRY.test(e.name) || RISKY_ENTRY.test(e.name))) {return 'content'} } if ((key === 'doc' || key === 'xls') && oleHasMacros(bytes)) {return 'content'} if (key === 'pdf' && strictPdf && pdfHasActiveContent(bytes)) {return 'content'} diff --git a/src/modules/i18n/createProxy.ts b/src/modules/i18n/createProxy.ts index fa85f28..72e6f4d 100644 --- a/src/modules/i18n/createProxy.ts +++ b/src/modules/i18n/createProxy.ts @@ -81,7 +81,7 @@ type CreateProxyOptions = { * import { createProxy, DEFAULT_PROXY_MATCHER } from '@intecion/ipal-kit' * import { i18nConfig } from '@/i18n.config' * export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true }) - * export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } // inline literal + * export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] } // inline literal */ export function createProxy( config: I18nConfig, diff --git a/src/modules/i18n/localeMiddleware.ts b/src/modules/i18n/localeMiddleware.ts index 94b4627..0b9fafe 100644 --- a/src/modules/i18n/localeMiddleware.ts +++ b/src/modules/i18n/localeMiddleware.ts @@ -164,5 +164,8 @@ export function createLocaleMiddleware({ /** * Default Next.js middleware matcher: run on everything except API routes, the * admin panel, Next internals, and files with an extension (static assets). + * `api`, `admin` and `_next` are skipped only as a WHOLE first segment (`/api`, `/api/…`): before 1.17.1 the + * lookahead did not end at "/", so `/administracja` or `/apis` skipped the proxy too (no locale redirect, no + * proxy CSP). The doctor's `proxy-matcher` rule reports the old literal. */ -export const DEFAULT_MIDDLEWARE_MATCHER = ['/((?!api|admin|_next|.*\\..*).*)'] +export const DEFAULT_MIDDLEWARE_MATCHER = ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] diff --git a/src/modules/security/routeCheck.ts b/src/modules/security/routeCheck.ts new file mode 100644 index 0000000..d4ba0c5 --- /dev/null +++ b/src/modules/security/routeCheck.ts @@ -0,0 +1,89 @@ +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() + // eslint-disable-next-line no-console -- a command-line check prints its report + 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..1290aba --- /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 = { + /** Routes the snapshot has and the config no longer opens (not a failure; `--update` drops them). */ + gone: string[] + /** Entries whose reason is empty or still says TODO. */ + unexplained: string[] + /** Routes the config has and the snapshot does not. */ + unjudged: 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/src/modules/starter/bundle.ts b/src/modules/starter/bundle.ts index e904fa4..f22ce74 100644 --- a/src/modules/starter/bundle.ts +++ b/src/modules/starter/bundle.ts @@ -4,7 +4,7 @@ * (`pnpm build:starter`); a checkout of the repo can read `reference/` directly instead. */ import { execFileSync } from 'node:child_process' -import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs' +import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs' import { join, relative, sep } from 'node:path' import { gunzipSync, gzipSync } from 'node:zlib' @@ -32,7 +32,8 @@ function walk(dir: string, root: string, out: string[]) { const rel = relative(root, full).split(sep).join('/') // never descend into installed or built trees if (name === 'node_modules' || name === '.next' || name === '.git') {continue} - if (statSync(full).isDirectory()) {walk(full, root, out)} + // lstat: a link is listed as itself (and refused below), never followed into its target + if (lstatSync(full).isDirectory()) {walk(full, root, out)} else {out.push(rel)} } } @@ -42,7 +43,7 @@ function listFiles(dir: string): string[] { try { const out = execFileSync('git', ['ls-files', '-z', '--cached', '--', '.'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }) const tracked = out.split('\0').filter(Boolean) - if (tracked.length) {return tracked.filter((path) => existsSync(join(dir, path)))} + if (tracked.length) {return tracked.filter((path) => existsSync(join(dir, path)) || lstatSync(join(dir, path), { throwIfNoEntry: false })?.isSymbolicLink())} } catch { // not a Git checkout (e.g. an unpacked tarball) — fall back to the folder } @@ -70,6 +71,11 @@ export function collectBundle(referenceDir: string): StarterBundle { if (path === MANIFEST || path === LOCKFILE) {continue} const role = fileRole(path, manifest) if (role === 'drop') {continue} + // A link would be read through: its TARGET (a key, another project's .env) would ship in the published bundle. + if (lstatSync(join(referenceDir, path)).isSymbolicLink()) { + problems.push(`${path}: symbolic link — commit the file itself, or drop it in the manifest`) + continue + } const content = readFileSync(join(referenceDir, path)) if (!isText(content)) { problems.push(`${path}: binary file — drop it in the manifest`) diff --git a/src/modules/starter/cli.ts b/src/modules/starter/cli.ts index f2f7b6d..777a823 100644 --- a/src/modules/starter/cli.ts +++ b/src/modules/starter/cli.ts @@ -5,7 +5,7 @@ import { spawnSync } from 'node:child_process' import { createHash, randomBytes } from 'node:crypto' import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' -import { dirname, join, relative, resolve } from 'node:path' +import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { domainToASCII, fileURLToPath } from 'node:url' import type { SiteContext } from './generate.js' @@ -118,7 +118,17 @@ function run(log: Log, cwd: string, command: string, args: string[], env: Record return result.status === 0 } -function writeFiles(dir: string, files: Record) { +/** + * The new site's files, each under `dir`. A path that is absolute or climbs out with `..` stops the run before + * anything is written (the bundle is built from this repository's tracked files, so none does; a damaged or + * altered bundle must not write outside the new folder). + */ +export function writeFiles(dir: string, files: Record) { + const outside = Object.keys(files).filter((path) => { + const target = resolve(dir, path) + return isAbsolute(path) || (target !== dir && !target.startsWith(`${resolve(dir)}${sep}`)) + }) + if (outside.length) {throw new Error(`the starter bundle names files outside the new folder: ${outside.join(', ')} — nothing was written`)} for (const [path, content] of Object.entries(files)) { const target = join(dir, path) mkdirSync(dirname(target), { recursive: true }) @@ -208,7 +218,12 @@ export async function runCreateCli(args: string[], log: Log = (line) => process. return 0 } - writeFiles(dir, files) + try { + writeFiles(dir, files) + } catch (error) { + log(`iapl create: ${(error as Error).message}`) + return 1 + } writeFileSync(join(dir, '.env'), localEnv(files['.env.example'] ?? '')) log(`Wrote ${Object.keys(files).length} files to ${relative(cwd, dir) || '.'}`) diff --git a/test/doctor.test.ts b/test/doctor.test.ts index 171aa52..9d72c1d 100644 --- a/test/doctor.test.ts +++ b/test/doctor.test.ts @@ -493,6 +493,14 @@ describe('security and deep status', () => { expect(rules(await doctor(root, ['security']))).toContain('csp:info') expect(rules(await doctor(root, ['csp'], { config: { seen: { 'csp-report-only': '2026-09-01' } } }))).toEqual(['csp:warning']) }) + test('proxy-matcher: a lookahead that does not end api / admin / _next at "/" is a warning; the 1.17.1 literal is not', async () => { + const proxy = (matcher: string) => project({ ...base(), 'src/proxy.ts': `export const config = { matcher: ['${matcher}'] }` }) + expect(rules(await doctor(proxy('/((?!api|admin|_next|.*\\\\..*).*)'), ['proxy-matcher']))).toEqual(['proxy-matcher:warning']) + expect(rules(await doctor(proxy('/((?!api|cms|_next|.*\\\\..*).*)'), ['proxy-matcher']))).toEqual(['proxy-matcher:warning']) + expect(rules(await doctor(proxy('/((?!(?:api|admin|_next)(?:/|$)|.*\\\\..*).*)'), ['proxy-matcher']))).toEqual([]) + expect(rules(await doctor(project(base()), ['proxy-matcher']))).toEqual([]) + }) + test('client-hints: withSecurityConfig inside withPayload is reported (info); outside, or kept on purpose, is not', async () => { const inner = project(next('export default withPayload(\n withSecurityConfig(nextConfig))')) expect(rules(await doctor(inner, ['client-hints']))).toEqual(['client-hints:info']) diff --git a/test/formAttachments.test.ts b/test/formAttachments.test.ts index 3b76025..415201e 100644 --- a/test/formAttachments.test.ts +++ b/test/formAttachments.test.ts @@ -367,6 +367,13 @@ describe('3 · refused files leave no submission and send no e-mail', () => { await refused([{ name: 'cv.docx', data: ARCHIVE }], notAcceptable('cv.docx')) // a ZIP that is not a Word file }) + test('a program inside an Office file is found also with trailing dots or spaces (Windows drops them)', async () => { + for (const entry of ['word/setup.exe', 'word/setup.exe.', 'word/setup.exe ', 'word/setup.EXE. .', 'word/vbaProject.bin.']) { + const data = zip({ '[Content_Types].xml': '', [entry]: 'x', 'word/document.xml': '' }) + await refused([{ name: 'cv.docx', data }], notAcceptable('cv.docx')) + } + }) + test('extra files: more than the field allows, a file under a key that is no File field', async () => { await refused( [{ name: 'a.pdf', data: PDF }, { name: 'b.pdf', data: PDF }], diff --git a/test/iaplSkillsDest.test.ts b/test/iaplSkillsDest.test.ts new file mode 100644 index 0000000..8837eb6 --- /dev/null +++ b/test/iaplSkillsDest.test.ts @@ -0,0 +1,60 @@ +/** + * `iapl-skills --dest`: the "not the project root" rule is checked on RESOLVED paths. Before 1.17.1 the check + * compared the paths as typed, so `--dest root-link` (a link to `.`), `--dest ..` or `--dest /` passed it, and the + * run removed the `iapl-*` folders of the project root, its parent or the filesystem root (IAWL idea 13). + */ +import { spawnSync } from 'node:child_process' +import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { afterAll, describe, expect, test } from 'vitest' + +const bin = path.resolve(import.meta.dirname, '../bin/iapl-skills.mjs') +const made: string[] = [] +afterAll(() => { + for (const dir of made) {rmSync(dir, { force: true, recursive: true })} +}) + +/** A throw-away project: a parent folder holding `project/` with an `iapl-mine` folder in its root. */ +function project() { + const parent = realpathSync(mkdtempSync(path.join(tmpdir(), 'iapl-skills-dest-'))) + made.push(parent) + const dir = path.join(parent, 'project') + mkdirSync(path.join(dir, 'iapl-mine'), { recursive: true }) + writeFileSync(path.join(dir, 'iapl-mine', 'keep.txt'), 'the project root holds this folder') + mkdirSync(path.join(parent, 'iapl-next-door')) + return { dir, parent } +} + +const run = (cwd: string, dest: string) => + spawnSync(process.execPath, [bin, '--dest', dest, '--no-pointer'], { cwd, encoding: 'utf8' }) + +describe('iapl-skills --dest is judged after the path is resolved', () => { + test('a link to the project root is refused and the root keeps its iapl-* folders', () => { + const { dir } = project() + symlinkSync('.', path.join(dir, 'root-link')) + const result = run(dir, 'root-link') + expect(result.status, result.stdout).toBe(1) + expect(result.stderr).toMatch(/not the project root/) + expect(existsSync(path.join(dir, 'iapl-mine', 'keep.txt'))).toBe(true) + }) + + test('a folder that holds the project (the parent, the filesystem root) is refused', () => { + const { dir, parent } = project() + for (const dest of ['..', '/', parent]) { + const result = run(dir, dest) + expect([dest, result.status]).toEqual([dest, 1]) + } + expect(existsSync(path.join(parent, 'iapl-next-door'))).toBe(true) + }) + + test('a folder inside the project, a new one, or one elsewhere still works', () => { + const { dir, parent } = project() + expect(run(dir, '.agents/skills').status).toBe(0) + expect(existsSync(path.join(dir, '.agents/skills/iapl-setup/SKILL.md'))).toBe(true) + const shared = path.join(parent, 'shared-skills') + expect(run(dir, shared).status).toBe(0) + expect(existsSync(path.join(shared, 'iapl-setup/SKILL.md'))).toBe(true) + expect(existsSync(path.join(dir, 'iapl-mine', 'keep.txt'))).toBe(true) + }) +}) diff --git a/test/proxyMatcher.test.ts b/test/proxyMatcher.test.ts new file mode 100644 index 0000000..0407a7b --- /dev/null +++ b/test/proxyMatcher.test.ts @@ -0,0 +1,38 @@ +/** + * The documented proxy matcher, compiled by Next's own code (the function `next build` uses for `config.matcher`): + * `api`, `admin` and `_next` are skipped only as a whole first segment. Before 1.17.1 `/administracja`, `/admin-guide` + * or `/apis` skipped the proxy as well (IAWL idea 36: a deny rule by name must end at "/"). + */ +import { readFileSync, realpathSync } from 'node:fs' +import { createRequire } from 'node:module' +import path from 'node:path' +import { describe, expect, test } from 'vitest' + +import { DEFAULT_PROXY_MATCHER } from '../src/modules/i18n/createProxy.js' + +const root = path.resolve(import.meta.dirname, '..') +const next = realpathSync(path.join(root, 'node_modules/next')) +const { getMiddlewareMatchers } = createRequire(import.meta.url)(path.join(next, 'dist/build/analysis/get-page-static-info.js')) as { + getMiddlewareMatchers: (matchers: string[], nextConfig: object) => { regexp: string }[] +} +const runs = (matcher: string) => { + const re = new RegExp(getMiddlewareMatchers([matcher], {})[0].regexp) + return (pathname: string) => re.test(pathname) +} + +describe('the proxy matcher', () => { + test('skips /api, /admin and /_next as whole segments and files; runs on pages that only START with those letters', () => { + const proxy = runs(DEFAULT_PROXY_MATCHER[0]) + for (const skipped of ['/api', '/api/users', '/api/ipal/hit', '/admin', '/admin/', '/admin/collections/users', '/_next/static/chunk.js', '/robots.txt', '/sitemap.xml']) { + expect([skipped, proxy(skipped)]).toEqual([skipped, false]) + } + for (const page of ['/', '/o-nas', '/pl/o-nas', '/administracja', '/admin-guide', '/apis', '/api-docs', '/_nextish', '/md/pl/o-nas']) { + expect([page, proxy(page)]).toEqual([page, true]) + } + }) + + test('the reference site uses the same literal (Next reads it statically, it cannot be imported)', () => { + const proxyFile = readFileSync(path.join(root, 'reference/src/proxy.ts'), 'utf8') + expect(proxyFile).toContain(`matcher: ['${DEFAULT_PROXY_MATCHER[0].replace(/\\/g, '\\\\')}']`) + }) +}) diff --git a/test/routeInventory.test.ts b/test/routeInventory.test.ts new file mode 100644 index 0000000..17d7cc3 --- /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 { compareRouteSnapshot, listNextRouteFiles, listPublicRoutes, updateRouteSnapshot } from '../src/modules/security/routeInventory.js' +import { iapl } from '../src/plugin.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 = { + '(frontend)/[locale]/page.tsx': 'export default function Page() {}', + '(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', + } + 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']) + }) +}) diff --git a/test/starter.test.ts b/test/starter.test.ts index 228f41e..eca523a 100644 --- a/test/starter.test.ts +++ b/test/starter.test.ts @@ -1,4 +1,5 @@ -import { existsSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' import path from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -29,7 +30,7 @@ import { unpackBundle, validateAnswers, } from '../src/exports/starter.js' -import { externalSkillNames, resolveExternal } from '../src/modules/starter/cli.js' +import { externalSkillNames, resolveExternal, writeFiles } from '../src/modules/starter/cli.js' const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') const reference = path.join(root, 'reference') @@ -257,3 +258,49 @@ describe.runIf(existsSync(path.join(reference, 'starter.manifest.json')))('start expect(files['src/instrumentation.ts']).not.toContain('cookieCrawl') }) }) + +describe('starter: links and paths (IAWL ideas 12, 13)', () => { + const site = () => { + const dir = mkdtempSync(path.join(tmpdir(), 'iapl-starter-links-')) + const manifest: StarterManifest = { drop: [], keep: ['**'], placeholders: {}, schema: 1, template: [] } + writeFileSync(path.join(dir, 'starter.manifest.json'), JSON.stringify(manifest)) + writeFileSync(path.join(dir, 'pnpm-lock.yaml'), "lockfileVersion: '9.0'\n") + writeFileSync(path.join(dir, 'kept.ts'), 'export const a = 1\n') + return dir + } + + it('a symbolic link is refused: its target is never read into the published bundle', () => { + const dir = site() + const secret = path.join(dir, '..', `${path.basename(dir)}-secret.txt`) + writeFileSync(secret, 'PRIVATE KEY OF SOMEBODY ELSE') + symlinkSync(secret, path.join(dir, 'leak.txt')) + mkdirSync(path.join(dir, 'outside')) + symlinkSync(path.dirname(secret), path.join(dir, 'outside', 'up')) + try { + expect(() => collectBundle(dir)).toThrow(/leak\.txt: symbolic link/) + rmSync(path.join(dir, 'leak.txt')) + // a link to a folder is not walked into either + expect(() => collectBundle(dir)).toThrow(/outside\/up: symbolic link/) + rmSync(path.join(dir, 'outside'), { force: true, recursive: true }) + expect(Object.keys(collectBundle(dir).files)).toEqual(['kept.ts']) + } finally { + rmSync(dir, { force: true, recursive: true }) + rmSync(secret, { force: true }) + } + }) + + it('a bundle path outside the new folder stops the run before anything is written', () => { + const parent = mkdtempSync(path.join(tmpdir(), 'iapl-starter-paths-')) + const dir = path.join(parent, 'site') + try { + for (const bad of ['../escaped.txt', 'a/../../escaped.txt', path.join(parent, 'abs.txt')]) { + expect(() => writeFiles(dir, { [bad]: 'no', 'ok.txt': 'fine' }), bad).toThrow(/outside the new folder/) + } + expect(readdirSync(parent)).toEqual([]) + writeFiles(dir, { 'ok.txt': 'fine', 'src/a/b.ts': 'x' }) + expect(readdirSync(dir).sort()).toEqual(['ok.txt', 'src']) + } finally { + rmSync(parent, { force: true, recursive: true }) + } + }) +})