Outside-in tests (IAWL ideas 33, 34): closed doors on the built site as anonymous, customer and editor; every public route judged

- reference/e2e/closed-doors.ts + closed-doors.spec.ts: one table of doors, asked by pnpm e2e:built in both bundlers;
  doors still open while the owner decides are asserted open (test.fail) with their question
- listPublicRoutes / listNextRouteFiles / compareRouteSnapshot / updateRouteSnapshot (main entry), runRouteCheck (/doctor)
- reference/e2e/routes.ts + routes.snapshot.json (395 routes, one reason each); pnpm routes:check [--update], first step of e2e:built
- create-test-admin.ts makes an editor test account
- docs: security.md sections, AGENT.md 8a, iapl-audit templates, iapl-upgrade 1.17.1, changelog draft

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 20:26:30 +01:00
co-authored by Claude Opus 5.5
parent 498b3dbf38
commit 2468390538
25 changed files with 1384 additions and 6 deletions
+3
View File
@@ -17,6 +17,9 @@ export { AUDIT_RULE_MAP, parseToolOutput } from '../modules/doctor/rules/tooling
export { applySettings, AUDIT_SKIP_RULES, doctorRules, globToRegExp, runDeepProbe, runDoctor } from '../modules/doctor/run.js'
export type { RunDoctorOptions } from '../modules/doctor/run.js'
export { buildDoctorEndpoint, collectDoctorStatus } from '../modules/doctor/status.js'
// routes:check — the site's public routes against the judged snapshot (docs/security.md "Routes nobody has judged")
export { runRouteCheck } from '../modules/security/routeCheck.js'
export type { RunRouteCheckOptions } from '../modules/security/routeCheck.js'
export type { DoctorEndpointOptions } from '../modules/doctor/status.js'
export type {
DoctorConfig,
+3
View File
@@ -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'
+88
View File
@@ -0,0 +1,88 @@
import type { SanitizedConfig } from 'payload'
import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { join, relative, sep } from 'node:path'
import { pathToFileURL } from 'node:url'
import type { GraphqlSchemaLike, RouteSnapshot } from './routeInventory.js'
import { compareRouteSnapshot, listNextRouteFiles, listPublicRoutes, updateRouteSnapshot } from './routeInventory.js'
export type RunRouteCheckOptions = {
/** The Next app directory, relative to `cwd`. Default `src/app`. */
appDir?: string
/** The project's config (`await config` from `@payload-config`). */
config: SanitizedConfig
cwd?: string
/** Set false when the project has no `/api/graphql` route (no GraphQL operation is then listed). Default true. */
graphql?: boolean
log?: (line: string) => void
/** The judged list, relative to `cwd`. Default `e2e/routes.snapshot.json`. */
snapshot?: string
/** Write new routes (with an empty reason) and drop gone ones, instead of only checking. */
update?: boolean
}
type SnapshotFile = { $comment?: string; routes: RouteSnapshot }
const COMMENT =
'Every public door of this site: REST routes, GraphQL operations, Next route files. One line per entry: who may use it and why it is open (or that it is closed and to whom). A new route fails `routes:check` until somebody judges it here. `--update` adds new routes with an empty reason and drops gone ones. docs/security.md "Routes nobody has judged".'
/** `@payloadcms/graphql`, the copy next to the project's `@payloadcms/next` (the one `/api/graphql` uses). */
async function loadSchema(config: SanitizedConfig, cwd: string): Promise<GraphqlSchemaLike> {
// @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<number> {
const cwd = options.cwd ?? process.cwd()
const log = options.log ?? ((line: string) => console.log(line))
const appDir = join(cwd, options.appDir ?? 'src/app')
const snapshotFile = join(cwd, options.snapshot ?? 'e2e/routes.snapshot.json')
const routeFiles = listNextRouteFiles(walk(appDir).map((file) => relative(appDir, file).split(sep).join('/')), (file) => readFileSync(join(appDir, file), 'utf8'))
const current = listPublicRoutes(options.config, {
graphqlSchema: options.graphql === false ? undefined : await loadSchema(options.config, cwd),
routeFiles,
})
const saved: SnapshotFile = existsSync(snapshotFile) ? (JSON.parse(readFileSync(snapshotFile, 'utf8')) as SnapshotFile) : { routes: {} }
if (options.update) {
const routes = updateRouteSnapshot(current, saved.routes ?? {})
writeFileSync(snapshotFile, `${JSON.stringify({ $comment: saved.$comment ?? COMMENT, routes }, null, 2)}\n`)
const diff = compareRouteSnapshot(current, routes)
log(`[routes] wrote ${relative(cwd, snapshotFile)}: ${current.length} routes, ${diff.unexplained.length} without a reason`)
return diff.unexplained.length ? 1 : 0
}
const diff = compareRouteSnapshot(current, saved.routes ?? {})
for (const id of diff.unjudged) {log(` ✗ not judged: ${id}`)}
for (const id of diff.unexplained) {log(` ✗ no reason: ${id}`)}
for (const id of diff.gone) {log(` · gone (drop it with --update): ${id}`)}
if (diff.unjudged.length || diff.unexplained.length) {
log(`[routes] ✗ ${diff.unjudged.length} route(s) nobody has judged, ${diff.unexplained.length} without a reason — judge them in ${relative(cwd, snapshotFile)} (\`--update\` adds them with an empty reason)`)
return 1
}
log(`[routes] ✓ ${current.length} public routes, every one judged${diff.gone.length ? ` (${diff.gone.length} gone)` : ''}`)
return 0
}
+125
View File
@@ -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<string, unknown> } | null | undefined
getQueryType: () => { getFields: () => Record<string, unknown> } | 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<string>()
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<string, string> = { 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<string, string>
export type RouteSnapshotDiff = {
/** Entries whose reason is empty or still says TODO. */
unexplained: string[]
/** Routes the config has and the snapshot does not. */
unjudged: string[]
/** Routes the snapshot has and the config no longer opens (not a failure; `--update` drops them). */
gone: string[]
}
export function compareRouteSnapshot(current: string[], snapshot: RouteSnapshot): RouteSnapshotDiff {
const judged = new Set(Object.keys(snapshot))
const now = new Set(current)
return {
gone: [...judged].filter((id) => !now.has(id)).sort(),
unexplained: [...judged].filter((id) => now.has(id) && (!snapshot[id]?.trim() || /^TODO\b/i.test(snapshot[id]!.trim()))).sort(),
unjudged: current.filter((id) => !judged.has(id)),
}
}
/** The snapshot after `--update`: new routes added with an empty reason (still a failure), gone ones dropped. */
export function updateRouteSnapshot(current: string[], snapshot: RouteSnapshot): RouteSnapshot {
const next: RouteSnapshot = {}
for (const id of current) {next[id] = snapshot[id] ?? ''}
return next
}