Merge claude/security-c-files-jobs-tests-cfba70: resolved paths in the bins and starter, proxy matcher ends at /, closed doors on the built site, every public route judged

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 20:57:50 +01:00
co-authored by Claude Opus 5.5
47 changed files with 1675 additions and 34 deletions
+7
View File
@@ -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
@@ -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<string, unknown> | 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: '[email protected]' } },
{ 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: '[email protected]', password: 'Door-Password-1234', roles: ['admin'] }, closedFor: ALL, method: 'POST', name: 'nobody creates a staff account', path: '/api/users', closed: status(403) },
{ body: { email: '[email protected]', 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<APIRequestContext> } }): Promise<APIRequestContext | null> {
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)
})
}
})
}
@@ -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'),
}),
)
@@ -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`.
+1 -1
View File
@@ -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:
+8
View File
@@ -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