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
+3
View File
@@ -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'
+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'
+21
View File
@@ -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) => {
+5 -2
View File
@@ -106,7 +106,10 @@ const REQUIRED_ENTRIES: Record<string, string[]> = {
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'}
+1 -1
View File
@@ -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,
+4 -1
View File
@@ -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)(?:/|$)|.*\\..*).*)']
+89
View File
@@ -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<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()
// 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
}
+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 = {
/** 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
}
+9 -3
View File
@@ -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`)
+18 -3
View File
@@ -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<string, string>) {
/**
* 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<string, string>) {
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) || '.'}`)