Files
ipal-kit/src/modules/security/routeCheck.ts
T

90 lines
5.1 KiB
TypeScript

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
}