Files
ipal-kit/test/doctor.test.ts
T
Radosław SmolińskiandClaude Fable 5.2 42fdad8c2d M1 (2, 3): the Turnstile env secret is deprecated; doctor rules access-missing, turnstile-degraded, turnstile-env-key
(2) Stage one of the deprecation: TURNSTILE_SECRET_KEY from the environment still
works when the panel field is empty, logs once that it is deprecated, and the
doctor's deep status reports it (rule turnstile-env-key, warning). Nothing is
removed.
(3) access-missing (static, warning): ipalKit without `access` means every panel
account is an admin. turnstile-degraded (deep): Turnstile is not checking forms —
warning, error after a day. The deep status carries the recorded state and where
the secret comes from, never a key.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:12 +01:00

627 lines
43 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { createServer, type Server } from 'node:http'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
import type { DoctorConfig, DoctorReport } from '../src/modules/doctor/types.js'
import { expandSites, parseDoctorArgs, runDoctorCli, shouldWriteSeen } from '../src/modules/doctor/cli.js'
import { formatDriftTable, formatReport } from '../src/modules/doctor/format.js'
import { bareHost, parseEnvFile, readAuditSkips } from '../src/modules/doctor/project.js'
import { planSkills } from '../src/modules/doctor/rules/agents.js'
import { parseToolOutput } from '../src/modules/doctor/rules/tooling.js'
import { doctorRules, globToRegExp, runDoctor } from '../src/modules/doctor/run.js'
import { buildDoctorEndpoint, collectDoctorStatus } from '../src/modules/doctor/status.js'
import { compareVersions, stripComments } from '../src/modules/doctor/util.js'
const packageRoot = path.resolve(import.meta.dirname, '..')
const TODAY = '2026-10-29'
let dirs: string[] = []
/** A project folder from a { path: content } map; package.json objects are serialised. */
function project(files: Record<string, object | string>): string {
const root = mkdtempSync(path.join(tmpdir(), 'ipal-doctor-'))
dirs.push(root)
for (const [rel, content] of Object.entries(files)) {
const file = path.join(root, rel)
mkdirSync(path.dirname(file), { recursive: true })
writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content, null, 2))
}
return root
}
const pkgJson = (extra: object = {}) => ({ name: 'examplepl-web', dependencies: { '@intecion/ipal-kit': '^1.14.6', next: '16.4.6', sharp: '0.35.5' }, engines: { node: '>=22 <23' }, packageManager: '[email protected]', ...extra })
const installed = (name: string, version: string) => ({ [`node_modules/${name}/package.json`]: { name, version } })
const base = () => ({
...installed('@intecion/ipal-kit', '1.14.6'),
...installed('next', '16.4.6'),
...installed('sharp', '0.35.5'),
'.nvmrc': '22\n',
'package.json': pkgJson(),
})
const doctor = (root: string, only: string[], extra: { config?: DoctorConfig; deepStatus?: object; url?: string } = {}) =>
runDoctor({ offline: true, only, packageRoot, root, today: TODAY, writeSeen: false, ...extra })
const rules = (report: DoctorReport) => report.findings.filter((f) => !f.silenced).map((f) => `${f.rule}:${f.severity}`)
afterEach(() => {
for (const d of dirs) {rmSync(d, { force: true, recursive: true })}
dirs = []
vi.unstubAllEnvs()
})
describe('importmap rule and the 2FA back-link check', () => {
const MAP = 'src/app/(payload)/admin/importMap.js'
const entries = (...names: string[]) => `export const importMap = { ${names.map((n) => `"${n}": X`).join(', ')} }`
const withPlugin = (admin: string) => ({ ...base(), ...installed('@clocklimited/payload-2fa', '3.0.0'), 'node_modules/@intecion/ipal-kit/dist/exports/admin.js': admin })
const messages = (report: DoctorReport) => report.findings.filter((f) => f.rule === 'importmap').map((f) => `${f.severity}: ${f.message}`)
test('expects SafeTotpView when the installed plugin has it; not with safeBack: false; not for an older plugin', async () => {
const map = entries('@clocklimited/payload-2fa/rsc#TOTPSetup', '@intecion/ipal-kit/admin#TotpRedirectProvider')
const admin = 'export { SafeTotpView } from "./x.js"; export { TotpRedirectProvider } from "./y.js"'
const lacking = await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp }' }), ['importmap'])
expect(messages(lacking).join()).toContain('import map lacks @intecion/ipal-kit/admin#SafeTotpView')
const off = await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp, safeBack: false }' }), ['importmap'])
expect(messages(off).join()).not.toContain('SafeTotpView')
const older = await doctor(project({ ...withPlugin('export { TotpRedirectProvider } from "./y.js"'), [MAP]: map, 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp }' }), ['importmap'])
expect(messages(older).join()).not.toContain('SafeTotpView')
})
describe("the 2FA package's own view in the config", () => {
const map = entries('@clocklimited/payload-2fa/rsc#TOTPSetup', '@intecion/ipal-kit/admin#TotpRedirectProvider', '@intecion/ipal-kit/admin#SafeTotpView')
const admin = 'export { SafeTotpView } from "./x.js"; export { TotpRedirectProvider } from "./y.js"'
const NOTE = /^warning: the config registers the 2FA package's own setup \/ verify view/
const notes = async (config: string) =>
messages(await doctor(project({ ...withPlugin(admin), [MAP]: map, 'src/payload.config.ts': `twoFactor: { plugin: payloadTotp }, ${config}` }), ['importmap'])).filter((m) => NOTE.test(m))
const RAW = '@clocklimited/payload-2fa/rsc#TOTPVerify'
test.each([
['a string component', `admin: { components: { views: { Mine: { Component: '${RAW}', path: '/my-verify' } } } }`],
['an object component', `admin: { components: { views: { Mine: { Component: { path: "${RAW}", serverProps: { a: 1 } }, path: '/my-verify' } } } }`],
['an object component over several lines', `views: { Mine: { Component: {\n clientProps,\n path: \`${RAW}\`,\n}, path: '/my-verify' } }`],
['the setup view', "views: { Mine: { Component: '@clocklimited/payload-2fa/rsc#TOTPSetup', path: '/my-setup' } }"],
])('warns for %s', async (_name, config) => {
expect(await notes(config)).toHaveLength(1)
})
test.each([
['no such view', ''],
// the fix the warning itself suggests
['the wrapper with the raw path as ipalTotpView, and the path in admin.dependencies',
`admin: { components: { views: { Mine: { Component: { path: '@intecion/ipal-kit/admin#SafeTotpView', serverProps: { ipalTotpView: '${RAW}' } }, path: '/my-verify' } } }, dependencies: { 'my-verify': { path: '${RAW}', type: 'component' } } }`],
['the wrapper with serverProps written first', `views: { Mine: { Component: { serverProps: { ipalTotpView: '${RAW}' }, path: '@intecion/ipal-kit/admin#SafeTotpView' }, path: '/my-verify' } }`],
['a dependencies entry alone', `admin: { dependencies: { keep: { type: 'component', path: '${RAW}' } } }`],
['a comment', `// Component: '${RAW}'`],
])('does not warn for %s', async (_name, config) => {
expect(await notes(config)).toEqual([])
})
})
})
describe('2FA setup required: what a project must have', () => {
const MAP = 'src/app/(payload)/admin/importMap.js'
const NEW = ['@intecion/ipal-kit/admin#TwoFactorStatusField', '@intecion/ipal-kit/admin#TwoFactorAlert']
const OLD = ['@clocklimited/payload-2fa/rsc#TOTPSetup', '@intecion/ipal-kit/admin#TotpRedirectProvider', '@intecion/ipal-kit/admin#SafeTotpView']
const entries = (names: string[]) => `export const importMap = { ${names.map((n) => `"${n}": X`).join(', ')} }`
const plugin = {
...base(),
...installed('@clocklimited/payload-2fa', '3.0.0'),
'node_modules/@intecion/ipal-kit/dist/exports/admin.js': 'export { SafeTotpView, TotpRedirectProvider, TwoFactorAlert, TwoFactorStatusField }',
'node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js': "export const SETUP_FROM_FIELD = 'totpSetupFrom'",
}
const lacks = async (config: string, map: string[]) =>
(await doctor(project({ ...plugin, [MAP]: entries(map), 'src/payload.config.ts': config }), ['importmap'])).findings.filter((f) => /import map lacks/.test(f.message)).map((f) => f.message).join()
test('the import map must hold the status field and the dashboard notice', async () => {
const missing = await lacks('twoFactor: { plugin: payloadTotp }', OLD)
for (const name of NEW) {expect(missing).toContain(name)}
const complete = await lacks('twoFactor: { plugin: payloadTotp }', [...OLD, ...NEW])
for (const name of NEW) {expect(complete).not.toContain(name)}
})
test.each([
['requireSetup: false', []],
['guard: false', []],
['requireSetup: { statusField: false }', [NEW[1]]],
['requireSetup: { dashboardNotice: false }', [NEW[0]]],
])('%s: only what is still on is expected', async (option, expected) => {
const missing = await lacks(`twoFactor: { plugin: payloadTotp, ${option} }`, OLD)
for (const name of NEW) {expect([name, missing.includes(name)]).toEqual([name, expected.includes(name)])}
})
const migration = async (files: Record<string, object | string>, config = 'twoFactor: { plugin: payloadTotp }') =>
(await doctor(project({ ...plugin, [MAP]: entries([...OLD, ...NEW]), 'src/payload.config.ts': config, ...files }), ['2fa'])).findings.filter((f) => /totp_setup_from/.test(f.message)).map((f) => f.severity)
test('Postgres / SQLite: a migration must add the 2FA column, or nobody can log in', async () => {
const pg = installed('@payloadcms/db-postgres', '3.94.1')
expect(await migration({ ...pg, 'src/migrations/20260101_init.ts': 'await db.execute(sql`CREATE TABLE "users" ("id" serial)`)' })).toEqual(['error'])
expect(await migration({ ...pg, 'src/migrations/20260101_init.ts': 'x', 'src/migrations/20261124_totp.ts': 'ALTER TABLE "users" ADD COLUMN "totp_setup_from" timestamp' })).toEqual([])
expect(await migration({ ...pg, 'migrations/20261124_totp.json': '{ "columns": { "totpSetupFrom": {} } }' })).toEqual([])
expect(await migration(pg)).toEqual(['warning']) // no migrations folder: the doctor cannot see how the schema gets there
expect(await migration({ ...installed('@payloadcms/db-sqlite', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' })).toEqual(['error'])
})
test('MongoDB, 2FA off, or a plugin version without the column: nothing to report', async () => {
expect(await migration({ ...installed('@payloadcms/db-mongodb', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' })).toEqual([])
expect(await migration({ ...installed('@payloadcms/db-postgres', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' }, 'twoFactor: false')).toEqual([])
const older = { ...installed('@payloadcms/db-postgres', '3.94.1'), 'node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js': 'export {}', 'src/migrations/20260101_init.ts': 'x' }
expect(await migration(older)).toEqual([])
})
})
describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () => {
const run = async (config: string, only: string[], deepStatus?: object) =>
rules(await doctor(project({ ...base(), 'src/payload.config.ts': config }), only, deepStatus ? { deepStatus } : {}))
test('access-missing: ipalKit without `access` means every account is an admin', async () => {
expect(await run("plugins: [ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: payloadTotp } })]", ['access-missing'])).toEqual(['access-missing:warning'])
// a collection's own access rules are not the plugin option
expect(await run("collections: [{ slug: 'pages', access: { read: () => true } }], plugins: [ipalKit({ i18n })]", ['access-missing'])).toEqual(['access-missing:warning'])
for (const ok of ["ipalKit({ access: { authCollection: 'users' }, i18n })", "ipalKit({ i18n, access: { defaultRole: 'editor' } })", 'ipalKit({ access: {}, i18n })', 'ipalKit({ access: accessOptions, i18n })', '// no plugin here']) {
expect([ok, await run(`plugins: [${ok}]`, ['access-missing'])]).toEqual([ok, []])
}
})
test('turnstile-degraded: a warning, an error after a day', async () => {
const at = (hoursAgo: number) => new Date(Date.parse(`${TODAY}T12:00:00Z`) - hoursAgo * 3_600_000).toISOString()
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { code: 'invalid-input-secret', since: at(2), state: 'degraded' } })).toEqual(['turnstile-degraded:warning'])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { code: 'invalid-input-secret', since: at(48), state: 'degraded' } })).toEqual(['turnstile-degraded:error'])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { state: 'degraded' } })).toEqual(['turnstile-degraded:warning'])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { since: at(48), state: 'ok' } })).toEqual([])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: null })).toEqual([])
expect(await run(cfg, ['turnstile-degraded'])).toEqual([]) // no deep status: nothing to say
})
test('turnstile-env-key: the secret still comes from the environment', async () => {
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
expect(await run(cfg, ['turnstile-env-key'], { turnstileSecretFromEnv: true })).toEqual(['turnstile-env-key:warning'])
expect(await run(cfg, ['turnstile-env-key'], { turnstileSecretFromEnv: false })).toEqual([])
expect(await run(cfg, ['turnstile-env-key'])).toEqual([])
})
test('the deep status reports the state and where the secret comes from, never a key', async () => {
vi.stubEnv('TURNSTILE_SECRET_KEY', 'env-secret-value')
const fake = (integrations: object) => ({
config: { admin: { user: 'users' }, collections: [{ slug: 'users', fields: [] }], globals: [{ slug: 'site-integrations' }] },
findGlobal: async () => integrations,
})
const degraded = await collectDoctorStatus(fake({ turnstileSecretKey: 'panel-secret-value', turnstileStatus: { code: 'invalid-input-secret', message: 'x', since: '2026-10-28T10:00:00.000Z', state: 'degraded' } }) as never)
expect(degraded.turnstile).toEqual({ code: 'invalid-input-secret', since: '2026-10-28T10:00:00.000Z', state: 'degraded' })
expect(degraded.turnstileSecretFromEnv).toBe(false)
expect(JSON.stringify(degraded)).not.toMatch(/secret-value/)
const fromEnv = await collectDoctorStatus(fake({ turnstileSiteKey: 'site' }) as never)
expect(fromEnv.turnstile).toBeNull()
expect(fromEnv.turnstileSecretFromEnv).toBe(true)
expect(JSON.stringify(fromEnv)).not.toMatch(/secret-value/)
})
})
describe('helpers', () => {
test('parseEnvFile reads KEY=value, strips quotes, skips comments', () => {
expect(parseEnvFile('# c\nA=1\nexport B="two"\n C = \'3\'\nbad line')).toEqual({ A: '1', B: 'two', C: '3' })
})
test('readAuditSkips maps keys to the reason', () => {
const skips = readAuditSkips('- ipal-audit-skip: mcp, twofactor — client decision 2026-10-01\n')
expect(skips.get('mcp')).toBe('client decision 2026-10-01')
expect(skips.get('twofactor')).toBe('client decision 2026-10-01')
})
test('bareHost, compareVersions, stripComments, globToRegExp', () => {
expect(bareHost('https://www.Example.pl/path')).toBe('example.pl')
expect(compareVersions('1.14.6', '1.14.10')).toBe(-1)
expect(compareVersions('^1.15.0', '1.14.9')).toBe(1)
expect(stripComments("a // b\n/* c */ d 'http://x'")).toBe("a \n d 'http://x'")
expect(globToRegExp('src/components/design/**').test('src/components/design/TokenPanel.tsx')).toBe(true)
expect(globToRegExp('src/*.ts').test('src/a/b.ts')).toBe(false)
})
test('parseToolOutput reads the [LEVEL] title (n) — rule blocks of audit.sh and seo-check', () => {
const lines = parseToolOutput('ipal-audit\n\n[ERROR] hex colors in classes (2) — §6.11 tokens\n src/a.tsx:1: bg-[#fff]\n src/b.tsx:2: x\n[INFO] note — fine\n')
expect(lines).toEqual([
{ items: ['src/a.tsx:1: bg-[#fff]', 'src/b.tsx:2: x'], level: 'error', rule: '§6.11 tokens', title: 'hex colors in classes' },
{ items: [], level: 'info', rule: 'fine', title: 'note' },
])
})
test('every rule has a unique id, a group and a source', () => {
const ids = doctorRules.map((r) => r.id)
expect(new Set(ids).size).toBe(ids.length)
for (const r of doctorRules) {expect(r.group && r.source).toBeTruthy()}
})
})
describe('ipal-audit through the doctor', () => {
const site = (contentTs: string) =>
project({ ...base(), 'src/lib/content.ts': contentTs, 'src/payload.config.ts': "import { payloadTotp } from '@clocklimited/payload-2fa'\n" })
const aiBots = async (root: string) => (await doctor(root, ['audit'])).findings.filter((f) => f.rule === 'audit:robots-blocks-ai-bots')
test("a starter alternative line (//: …) with aiBots: 'block-training' is not a finding", async () => {
const root = site("export const content = createContentHelpers({\n // @starter:if aiBotsBlockTraining\n //: robots: { aiBots: 'block-training' },\n // @starter:endif\n})\n")
expect(await aiBots(root)).toEqual([])
})
test("a real robots: { aiBots: 'block-training' } line still is", async () => {
const root = site("export const content = createContentHelpers({\n robots: { aiBots: 'block-training' },\n})\n")
expect((await aiBots(root)).map((f) => f.severity)).toEqual(['warning'])
})
})
describe('versions', () => {
test('a current project passes', async () => {
expect(rules(await doctor(project(base()), ['versions']))).toEqual([])
})
test('old next and sharp, stale install, Node not pinned to 22', async () => {
const root = project({
...base(),
...installed('@intecion/ipal-kit', '1.14.4'),
...installed('next', '16.2.6'),
...installed('sharp', '0.34.2'),
'.nvmrc': '20\n',
'package.json': pkgJson({ engines: { node: '>=20.9.0' }, packageManager: undefined }),
})
expect(rules(await doctor(root, ['versions']))).toEqual([
'plugin-installed:error',
'next-min:error',
'sharp-min:error',
'node-22:warning',
'node-22:warning',
'pnpm-pinned:info',
])
})
test('next-min: 16.4.1–16.4.4 is an error (GHSA-mfr8-8qww-v76h), 16.4.5 passes, and the rule can be silenced', async () => {
const at = (version: string) => project({ ...base(), ...installed('next', version), ...installed('eslint-config-next', version) })
const old = await doctor(at('16.4.3'), ['next-min'])
expect(rules(old)).toEqual(['next-min:error'])
expect(old.findings[0].message).toContain('GHSA-mfr8-8qww-v76h')
expect(old.findings[0].fix).toBe('pnpm add [email protected] [email protected]')
expect(rules(await doctor(at('16.4.4'), ['next-min']))).toEqual(['next-min:error'])
expect((await doctor(at('16.4.0'), ['next-min'])).findings[0].message).toContain('RCE and DoS')
expect(rules(await doctor(at('16.4.5'), ['next-min']))).toEqual([])
expect(rules(await doctor(at('16.5.0'), ['next-min']))).toEqual([])
const silenced = await doctor(at('16.4.3'), ['next-min'], { config: { rules: { 'next-min': { off: true, reason: 'upgrade booked' } } } })
expect(silenced.summary).toMatchObject({ error: 0, silenced: 1 })
})
test('transitive-min: mongoose 8 below 8.24.7 (error) and happy-dom below 21.0.4 (warning), read from the lockfile', async () => {
const lock = (mongoose: string, happyDom: string) =>
`lockfileVersion: '9.0'\n\noverrides:\n [email protected]: 8.24.1\n\npackages:\n\n happy-dom@${happyDom}:\n resolution: {integrity: x}\n\n [email protected]:\n resolution: {integrity: x}\n\n mongoose@${mongoose}:\n resolution: {integrity: x}\n\nsnapshots:\n\n mongoose@${mongoose}:\n dependencies:\n mongodb: 6.20.0\n`
const at = (mongoose: string, happyDom: string) => project({ ...base(), 'pnpm-lock.yaml': lock(mongoose, happyDom) })
const old = await doctor(at('8.24.1', '20.14.6'), ['transitive-min'])
expect(rules(old)).toEqual(['transitive-min:error', 'transitive-min:warning'])
expect(old.findings[0].message).toContain('mongoose 8.24.1 < 8.24.7')
expect(old.findings[0].message).toContain('GHSA-pcrw-h46h-c93h')
expect(old.findings[0].fix).toContain('"mongoose@>=8 <8.24.7": "~8.24.10"')
expect(old.findings[0].fix).toMatch(/^upgrade payload and every @payloadcms\/\* to 3\.94\.1/)
expect(old.findings[1].fix).toMatch(/^add "happy-dom/)
expect(old.findings[1].message).toContain('happy-dom 20.14.6 < 21.0.4')
expect(old.findings[1].fix).toContain('"happy-dom@<21.0.4": "^21.0.4"')
// 8.24.3 fixes only the critical one
expect(rules(await doctor(at('8.24.6', '21.0.3'), ['transitive-min']))).toEqual(['transitive-min:error', 'transitive-min:warning'])
expect(rules(await doctor(at('8.24.7', '21.0.4'), ['transitive-min']))).toEqual([])
expect(rules(await doctor(at('8.24.10', '21.1.0'), ['transitive-min']))).toEqual([])
// another major line (Payload 4 uses mongoose 9) is not compared with the 8.x minimum
expect(rules(await doctor(at('9.11.4', '21.0.4'), ['transitive-min']))).toEqual([])
// no MongoDB adapter, no lexical: nothing to report
expect(rules(await doctor(project(base()), ['transitive-min']))).toEqual([])
const silenced = await doctor(at('8.24.1', '20.14.6'), ['transitive-min'], { config: { rules: { 'transitive-min': { off: true, reason: 'Payload upgrade booked' } } } })
expect(silenced.summary).toMatchObject({ error: 0, silenced: 2, warning: 0 })
})
test('transitive-min: without a pnpm lockfile it reads node_modules/.pnpm', async () => {
const root = project({ ...base(), 'node_modules/.pnpm/[email protected][email protected]/node_modules/mongoose/package.json': { name: 'mongoose', version: '8.24.1' } })
expect(rules(await doctor(root, ['transitive-min']))).toEqual(['transitive-min:error'])
})
test('file: / link: specs are not compared', async () => {
expect(rules(await doctor(project({ ...base(), 'package.json': pkgJson({ dependencies: { '@intecion/ipal-kit': 'file:..' } }) }), ['plugin-installed']))).toEqual([])
})
})
describe('db-name', () => {
const env = (dev: string, example = dev) => ({ ...base(), '.env': `DATABASE_URI=mongodb://127.0.0.1:27017/${dev}\n`, '.env.example': `DATABASE_URI=mongodb://USER:PASS@HOST:PORT/${example}?authSource=admin\n` })
test('<domain without dots>_dev passes', async () => {
expect(rules(await doctor(project({ ...env('examplepl_dev'), 'ipal-doctor.json': { domain: 'example.pl' } }), ['db-name']))).toEqual([])
})
test('a local .env on _prod is an error, another name too', async () => {
const report = await doctor(project({ ...env('examplepl_prod', 'dev'), 'ipal-doctor.json': { domain: 'example.pl' } }), ['db-name'])
expect(report.findings.map((f) => f.message)).toEqual([
'.env points at the production database examplepl_prod — a local run or seed writes to production',
'.env.example: database "dev", expected examplepl_dev',
])
})
test('the domain comes from NEXT_PUBLIC_SERVER_URL; a production export is checked with --env-file', async () => {
const root = project({ ...base(), '.env.example': 'NEXT_PUBLIC_SERVER_URL=https://www.acme.co.uk\nDATABASE_URI=mongodb://HOST/acmecouk_dev\n', 'prod.env': 'DATABASE_URI=mongodb://db/acme\n' })
const report = await runDoctor({ envFile: path.join(root, 'prod.env'), offline: true, only: ['db-name'], packageRoot, root, today: TODAY })
expect(report.site.domain).toBe('acme.co.uk')
expect(report.findings.map((f) => f.message)).toEqual(['--env-file: database "acme", expected acmecouk_prod'])
})
})
/** Every AGENT.md §3 file outside the frontend folder; `frontend` lists the files inside it. */
function layoutProject(group: string, frontend: Record<string, string>, extra: Record<string, object | string> = {}) {
const files: Record<string, object | string> = { ...base() }
for (const f of ['proxy.ts', 'i18n.config.ts', 'instrumentation.ts', 'payload.config.ts', 'lib/content.ts', 'app/manifest.ts', 'app/robots.ts', 'app/sitemap.xml/route.ts', 'app/llms.txt/route.ts', 'app/llms-full.txt/route.ts', 'app/md/[locale]/[[...slug]]/route.ts', 'app/api/mcp/route.ts', 'app/api/health/route.ts', 'app/indexnow-key.txt/route.ts', 'blocks/registry.ts', 'collections/Pages.ts', 'collections/Media.ts', 'components/layout/Header.tsx', 'components/forms/formClasses.ts']) {files[`src/${f}`] = ''}
for (const [f, content] of Object.entries(frontend)) {files[`src/app/${group}/${f}`] = content}
return project({ ...files, ...extra })
}
const localizedFrontend = { '[locale]/[[...slug]]/page.tsx': '', '[locale]/actions.ts': '', '[locale]/layout.tsx': '', '[locale]/not-found.tsx': '', '[locale]/notFoundView.tsx': '' }
describe('frontend route group (layout-required)', () => {
test('a (site) group with [locale] and notFoundView.tsx passes — the group name does not matter', async () => {
const report = await doctor(layoutProject('(site)', localizedFrontend), ['layout-required'])
expect(report.findings).toEqual([])
})
test('pages without a route group (app/[locale]) are found too', async () => {
expect((await doctor(layoutProject('', localizedFrontend), ['layout-required'])).findings).toEqual([])
})
test('layout.frontend wins; a folder that does not exist is reported', async () => {
const root = layoutProject('(web)', localizedFrontend, { 'src/app/(other)/[[...slug]]/page.tsx': '' })
expect((await doctor(root, ['layout-required'], { config: { layout: { frontend: 'src/app/(web)' } } })).findings).toEqual([])
const wrong = await doctor(root, ['layout-required'], { config: { layout: { frontend: 'src/app/(nope)' } } })
expect(wrong.findings.map((f) => f.message)[0]).toBe('layout.frontend "src/app/(nope)" does not exist')
})
test('two localized groups: the ambiguity is reported, (frontend) is checked', async () => {
const root = layoutProject('(site)', localizedFrontend, Object.fromEntries(Object.keys(localizedFrontend).map((f) => [`src/app/(frontend)/${f}`, ''])))
const report = await doctor(root, ['layout-required'])
expect(report.findings.map((f) => `${f.severity}: ${f.message}`)).toEqual([
'warning: several folders hold the site\'s pages: src/app/(frontend), src/app/(site) — checked src/app/(frontend)',
])
})
test('a localized group wins over a single-language one; a missing page names the group it checked', async () => {
const { '[locale]/actions.ts': _, ...withoutActions } = localizedFrontend
const root = layoutProject('(site)', withoutActions, { 'src/app/(landing)/[[...slug]]/page.tsx': '' })
const report = await doctor(root, ['layout-required'])
expect(report.findings.map((f) => f.message)).toEqual(['missing: src/app/(site)/[locale]/actions.ts'])
})
})
describe('layout, blocks, seeds, agents', () => {
test('missing convention files and forbidden copies', async () => {
const root = project({ ...base(), 'src/middleware.ts': '', 'src/payload.config.ts': '', 'src/scripts/x.ts': '' })
const report = await doctor(root, ['layout-required', 'layout-forbidden', 'layout-extra'])
expect(rules(report)).toEqual(['layout-required:error', 'layout-forbidden:error', 'layout-extra:info'])
expect(report.findings[0].message).toContain('src/proxy.ts')
})
test('layout.allow extends the src/ allow list; an audit skip drops its file', async () => {
const root = project({ ...base(), 'AGENTS.md': '## Project decisions\n- ipal-audit-skip: mcp — client decision\n', 'src/scripts/x.ts': '' })
const report = await doctor(root, ['layout-required', 'layout-extra'], { config: { layout: { allow: ['scripts'] } } })
expect(report.findings.map((f) => f.rule)).toEqual(['layout-required'])
expect(report.findings[0].message).not.toContain('api/mcp')
})
test('components/ui/ is required only without createBlockRegistry', async () => {
const own = project({ ...base(), 'src/blocks/registry.ts': 'export const r = RenderBlocks', 'src/components/ui/Button.tsx': '' })
expect((await doctor(own, ['blocks-ui-required'])).findings[0].message).toContain('Section, SectionHeader, Media, CMSLink')
const lib = project({ ...base(), 'src/blocks/registry.ts': "createBlockRegistry(content, { ui: { Card } })", 'src/components/ui/Button.tsx': '', 'src/components/ui/Card.tsx': '' })
const report = await doctor(lib, ['blocks-ui-required', 'blocks-ui-override', 'blocks-registry'])
expect(report.findings.map((f) => f.message)).toEqual(["components/ui/ overrides Button but the registry does not pass them — library blocks keep the plugin's look"])
})
test('an old-style blockType → component map passes blocks-registry; 2FA behind a switch is a warning', async () => {
const map = project({ ...base(), 'src/blocks/registry.ts': "export const blockRegistry: BlockComponentMap = { hero: Hero }" })
expect((await doctor(map, ['blocks-registry'])).findings).toEqual([])
const sw = project({ ...base(), ...installed('@clocklimited/payload-2fa', '3.0.0'), 'src/payload.config.ts': "twoFactor: process.env.X === 'true' ? false : { issuer: 'A', plugin: payloadTotp }," })
expect(rules(await doctor(sw, ['2fa']))).toEqual(['2fa:warning'])
})
test('the folder name gives the database base when there is no domain', async () => {
const parent = project({})
const root = path.join(parent, 'acmepl-web')
mkdirSync(root)
writeFileSync(path.join(root, '.env'), 'DATABASE_URI=mongodb://db/acme\n')
expect((await doctor(root, ['db-name'])).findings.map((f) => f.message)).toEqual(['.env: database "acme", expected acmepl_dev'])
})
test('a project block duplicating a library block (also by a renamed slug) and helper copies', async () => {
const root = project({
...base(),
'src/blocks/Faq/config.ts': "export const Faq = { slug: 'faq', fields: [] }",
'src/blocks/registry.ts': 'createBlockRegistry(content, {})',
'src/blocks/Reviews/config.ts': "export const R = { slug: 'reviews', fields: [] }",
'src/collections/Pages.ts': "buildTestimonialsBlock({ slug: 'reviews' })",
'src/fields/items.ts': 'export function buildItemsField() {}',
})
const report = await doctor(root, ['blocks-duplicate', 'blocks-helper-copy'])
expect(report.findings.map((f) => f.message)).toEqual([
'project block "faq" duplicates a library block',
'project block "reviews" duplicates a library block',
'local copy of buildItemsField',
])
const ejected = project({ ...base(), 'src/blocks/Faq/config.ts': "{ slug: 'faq' }", 'src/blocks/registry.ts': 'createBlockRegistry(content, { components: { faq: FaqBlock } })' })
expect((await doctor(ejected, ['blocks-duplicate'])).findings).toEqual([])
})
test('seeds: helper, no deletes, no fresh script, guard on; after launch a record list', async () => {
const files = {
...base(),
'package.json': pkgJson({ scripts: { seed: 'payload run src/seed/index.ts', 'seed:fresh': 'payload run src/seed/old.ts', 'seed:full': 'IPAL_SEED_ALLOW_FULL=1 payload run src/seed/index.ts' } }),
'src/seed/index.ts': "import { pages } from './pages'\nconst seed = createSeeder(payload)",
'src/seed/old.ts': 'await payload.delete({ collection: "pages" })',
'src/seed/pages.ts': 'export const pages = []',
}
expect(rules(await doctor(project(files), ['seed-named']))).toEqual([
'seed-named:error', // seed:fresh name
'seed-named:error', // old.ts deletes
'seed-named:error', // IPAL_SEED_ALLOW_FULL=1 in seed:full
'seed-named:warning', // old.ts without the helper (errors sort first)
])
const launched = await doctor(project({ ...files, 'package.json': pkgJson({ scripts: { seed: 'payload run src/seed/index.ts' } }) }), ['seed-named'], { config: { launched: true } })
expect(launched.findings.map((f) => f.message)).toEqual(['script "seed" has no record list — after launch every run needs SEED_ONLY'])
})
test('AGENTS.md needs a non-empty "Project decisions" and the pointer for the installed version', async () => {
const pointer = '<!-- ipal-kit:start -->\n## ipal-kit 1.14.6 — agent guide\n<!-- ipal-kit:end -->'
expect(rules(await doctor(project({ ...base(), 'AGENTS.md': `# x\n${pointer}`, 'CLAUDE.md': '@AGENTS.md\n' }), ['agents-md']))).toEqual(['agents-md:error'])
expect(rules(await doctor(project({ ...base(), 'AGENTS.md': `## Project decisions\n<!-- todo -->\n${pointer}`, 'CLAUDE.md': '@AGENTS.md\n' }), ['agents-md']))).toEqual(['agents-md:warning'])
expect(rules(await doctor(project({ ...base(), 'AGENTS.md': `## Project decisions\n- pl only\n${pointer}`, 'CLAUDE.md': '@AGENTS.md\n' }), ['agents-md']))).toEqual([])
})
test('planSkills: missing, stale and retired ipal-* folders', () => {
const source = project({ 'ipal-a/SKILL.md': 'a', 'ipal-b/SKILL.md': 'b' })
const dest = project({ 'ipal-b/SKILL.md': 'old', 'ipal-old/SKILL.md': 'x', 'mine/SKILL.md': 'own' })
expect(planSkills({ dest, source })).toEqual({ missing: ['ipal-a'], retired: ['ipal-old'], stale: ['ipal-b'] })
})
})
describe('security and deep status', () => {
const next = (body: string) => ({ ...base(), 'next.config.ts': body })
test('CSP report-only is info, a warning after 4 weeks (seen)', async () => {
const root = project(next("buildSecurityHeaders({ csp: { mode: 'report-only' } }); buildAdminCspHeaders(csp); withSecurityConfig(x)"))
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('deep status: users without TOTP, pending cookies, stale import map, env problems', async () => {
const root = project({ ...base(), 'src/app/(payload)/admin/importMap.js': '', 'src/payload.config.ts': 'twoFactor: { plugin: payloadTotp }, cookieScanner: { crawl: true }', ...installed('@clocklimited/payload-2fa', '3.0.0') })
const report = await doctor(root, ['2fa', 'cookie-scanner', 'importmap', 'env-live', 'deep-status'], {
deepStatus: { envProblems: ['R2_BUCKET'], error: 'db down', importMapCurrent: false, pendingCookies: 3, usersWithout2fa: 1 },
})
expect(report.findings.map((f) => f.message)).toEqual(
expect.arrayContaining([
'1 panel user(s) without TOTP',
'the committed import map differs from a freshly generated one',
"the project's env rules fail: R2_BUCKET",
'the deep check could not finish: db down',
'3 cookie(s) wait for approval',
]),
)
})
test('collectDoctorStatus counts only (no names)', async () => {
const payload = {
config: { admin: { user: 'users' }, collections: [{ slug: 'users', fields: [{ name: 'totpSecret' }, { name: 'hasTotp' }] }, { slug: 'cookie-review' }] },
count: vi.fn(async ({ collection, where }: { collection: string; where?: object }) => ({ totalDocs: collection === 'users' ? (where ? 3 : 5) : 4 })),
}
const status = await collectDoctorStatus(payload as never)
expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 })
expect(Object.keys(status).sort()).toEqual(['node', 'pendingCookies', 'plugin', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
})
test('collectDoctorStatus counts the accounts whose 2FA setup window has passed', async () => {
const payload = {
config: {
admin: { user: 'users' },
collections: [{ slug: 'users', fields: [{ name: 'totpSecret' }, { name: 'hasTotp' }, { name: 'totpSetupFrom' }] }],
custom: { ipal: { twoFactor: { collection: 'users', requireSetup: true, setupWindowMs: 72 * 3_600_000 } } },
},
// all 5; with TOTP 3; without 2; of those past the window 1 (the query with `less_than`)
count: vi.fn(async ({ where }: { where?: object }) => {
const q = JSON.stringify(where ?? {})
return { totalDocs: !where ? 5 : q.includes('less_than') ? 1 : q.includes('not_equals') ? 3 : 2 }
}),
}
expect(await collectDoctorStatus(payload as never)).toMatchObject({ usersSetupClosed: 1, usersWithout2fa: 2 })
})
test('GET /api/ipal/doctor: 404 without a token, 401 with a wrong one, counts with the right one', async () => {
const endpoint = buildDoctorEndpoint()
const payload = { config: { admin: { user: 'users' }, collections: [] }, count: vi.fn() }
const call = (auth?: string) => endpoint.handler({ headers: new Headers(auth ? { authorization: auth, 'x-forwarded-for': '1.2.3.4' } : {}), payload } as never) as Promise<Response>
expect((await call()).status).toBe(404)
vi.stubEnv('IPAL_DOCTOR_TOKEN', 'x'.repeat(40))
expect((await call('Bearer wrong')).status).toBe(401)
const ok = await call(`Bearer ${'x'.repeat(40)}`)
expect(ok.status).toBe(200)
expect(await ok.json()).toMatchObject({ pendingCookies: null, usersWithout2fa: null })
})
})
describe('silencing (ipal-doctor.json)', () => {
const noAgents = () => project(base())
test('off with a reason silences (kept in the report); without a reason it is ignored and reported', async () => {
const silenced = await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { off: true, reason: 'demo' } } } })
expect(silenced.summary).toMatchObject({ error: 0, silenced: 1 })
expect(silenced.findings[0]).toMatchObject({ reason: 'demo', silenced: true })
const noReason = await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { off: true } } } })
expect(rules(noReason)).toEqual(['doctor-config:error', 'agents-md:error'])
})
test('severity override, expired until, files filter, ipal-audit-skip', async () => {
expect(rules(await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { reason: 'r', severity: 'info' } } } }))).toEqual(['agents-md:info'])
expect(rules(await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { off: true, reason: 'r', until: '2026-10-01' } } } }))).toEqual(['agents-md:error', 'doctor-config:warning'])
expect(rules(await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { files: ['src/**'], off: true, reason: 'r' } } } }))).toEqual(['agents-md:error'])
const skip = project({ ...base(), 'AGENTS.md': '- ipal-audit-skip: twofactor — the client signs in with SSO\n', 'src/payload.config.ts': '' })
expect((await doctor(skip, ['2fa'])).findings[0]).toMatchObject({ reason: 'the client signs in with SSO', silenced: true })
})
})
describe('live (--url)', () => {
let server: Server
let url = ''
let headers: Record<string, string> = {}
let home = '<html><head></head><body>ok</body></html>'
beforeAll(async () => {
server = createServer((req, res) => {
if (req.url === '/api/health') {res.writeHead(200).end('{}'); return}
if (req.url?.startsWith('/admin')) {res.writeHead(200, { 'x-powered-by': 'Next.js, Payload' }).end('<meta name="robots" content="noindex, nofollow"><meta property="og:image" content="/api/ipal/admin-og">'); return}
res.writeHead(200, headers).end(home)
})
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
const address = server.address() as { port: number }
url = `http://127.0.0.1:${address.port}`
})
afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())))
test('X-Powered-By, missing headers, noindex on production', async () => {
headers = { 'x-content-type-options': 'nosniff' }
home = '<meta name="robots" content="noindex">'
const root = project({ ...base(), 'next.config.ts': 'buildSecurityHeaders(); withSecurityConfig(c); csp: {}; buildAdminCspHeaders(); mode: "enforce"' })
const report = await doctor(root, ['security-headers', 'powered-by', 'live-noindex', 'live-health', 'admin-noindex'], { url })
expect(report.findings.map((f) => f.message)).toEqual([
'live / lacks Referrer-Policy, Permissions-Policy, X-Frame-Options / frame-ancestors',
'live /admin/login sends X-Powered-By: Next.js, Payload',
'the production home page is noindex',
])
})
})
describe('CLI', () => {
const clean = () => project({ ...base(), 'AGENTS.md': '## Project decisions\n- x\n<!-- ipal-kit:start -->\n## ipal-kit 1.14.6 — agent guide\n<!-- ipal-kit:end -->', 'CLAUDE.md': '@AGENTS.md\n' })
const cli = async (args: string[], cwd: string) => {
const out: string[] = []
const code = await runDoctorCli(args, { cwd, log: (l) => out.push(l), packageRoot })
return { code, out: out.join('\n') }
}
test('args: --strict = --fail-on info; unknown option → usage error', () => {
expect(parseDoctorArgs(['ref', '--strict', '--offline'])).toMatchObject({ dir: 'ref', failOn: 'info', offline: true })
expect(parseDoctorArgs(['--nope'])).toBe('unknown option --nope')
expect(parseDoctorArgs(['--url'])).toBe('--url needs a value')
})
test('exit codes: 0 clean, 1 findings, --strict fails on info, 2 not a project / bad config', async () => {
const root = clean()
expect((await cli([root, '--offline', '--only', 'agents-md,versions'], root)).code).toBe(0)
const info = project({ ...base(), 'package.json': pkgJson({ packageManager: undefined }) })
expect((await cli([info, '--offline', '--only', 'versions'], info)).code).toBe(0)
expect((await cli([info, '--offline', '--only', 'versions', '--strict'], info)).code).toBe(1)
expect((await cli([project({ 'x.txt': '' })], packageRoot)).code).toBe(2)
const bad = project({ ...base(), 'ipal-doctor.json': '{ nope' })
expect((await cli([bad, '--offline', '--only', 'versions'], bad)).code).toBe(2)
})
test('--json is schema 1 with a summary; the human report lists fix and docs', async () => {
const root = project(base())
const { code, out } = await cli([root, '--offline', '--only', 'agents-md', '--json'], root)
const report = JSON.parse(out) as DoctorReport
expect(code).toBe(1)
expect(report).toMatchObject({ schema: 1, site: { plugin: '1.14.6' }, summary: { error: 1, info: 0, silenced: 0, warning: 0 } })
expect(formatReport(report)).toContain('fix: AGENT.md §13 template')
})
test('--sites: a read-only drift table, always exit 0', async () => {
const parent = mkdtempSync(path.join(tmpdir(), 'ipal-sites-'))
dirs.push(parent)
for (const name of ['a-web', 'b-web']) {
mkdirSync(path.join(parent, name))
writeFileSync(path.join(parent, name, 'package.json'), JSON.stringify(pkgJson()))
}
expect(expandSites('*-web', parent).map((d) => path.basename(d))).toEqual(['a-web', 'b-web'])
const { code, out } = await cli(['--sites', path.join(parent, '*-web'), '--offline', '--only', 'agents-md'], parent)
expect(code).toBe(0)
expect(out).toContain('| Rule | a-web | b-web |')
expect(out).toContain('| `agents-md` | ❌ | ❌ |')
})
test('formatDriftTable marks silenced cells', () => {
const r = (findings: DoctorReport['findings']): DoctorReport => ({ findings, rulesVersion: '1', schema: 1, site: { domain: null, path: '/x/s', plugin: null }, skipped: [], summary: { error: 0, info: 0, silenced: 0, warning: 0 } })
expect(formatDriftTable([r([{ message: 'm', rule: 'csp', severity: 'info', silenced: true, source: 'static' }])])).toContain('| `csp` | silenced |')
})
})
describe('the reference site', () => {
test('reference/ipal-doctor.json silences only with reasons', () => {
const config = JSON.parse(readFileSync(path.join(packageRoot, 'reference/ipal-doctor.json'), 'utf8')) as DoctorConfig
for (const setting of Object.values(config.rules ?? {})) {expect(setting.reason?.trim()).toBeTruthy()}
})
})
describe('ipal-doctor: first-seen dates', () => {
test('are written only outside CI, and never with --json or --sites', () => {
expect(shouldWriteSeen({}, {})).toBe(true)
expect(shouldWriteSeen({}, { CI: 'true' })).toBe(false)
expect(shouldWriteSeen({ json: true }, {})).toBe(false)
expect(shouldWriteSeen({ sites: 'clients/*' }, {})).toBe(false)
})
})