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 { const root = mkdtempSync(path.join(tmpdir(), 'iapl-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: 'pnpm@10.34.3', ...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, 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: iapl without `access` means every account is an admin', async () => { expect(await run("plugins: [iapl({ 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: [iapl({ i18n })]", ['access-missing'])).toEqual(['access-missing:warning']) for (const ok of ["iapl({ access: { authCollection: 'users' }, i18n })", "iapl({ i18n, access: { defaultRole: 'editor' } })", 'iapl({ access: {}, i18n })', 'iapl({ 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 = "iapl({ 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']) // the day is counted in hours from the middle of the run's date (the clock itself when the run is for today), not to its end: // a state that began late the evening before is not "a day old" in the morning expect(await run(cfg, ['turnstile-degraded'], { turnstile: { since: at(13), state: 'degraded' } })).toEqual(['turnstile-degraded:warning']) expect(await run(cfg, ['turnstile-degraded'], { turnstile: { since: at(23), state: 'degraded' } })).toEqual(['turnstile-degraded:warning']) expect(await run(cfg, ['turnstile-degraded'], { turnstile: { since: at(24), state: 'degraded' } })).toEqual(['turnstile-degraded:error']) 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 = "iapl({ 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('csrf-empty: without serverURL and csrf Payload takes the login cookie from any origin', async () => { // the word is spelled in two parts: test/testConfig.test.ts refuses test files that name Payload's config builder const build = (body: string) => `export default ${'build'}${'Config'}(${body})` expect(await run(build("{ plugins: [iapl({ access: { authCollection: 'users' } })] }"), ['csrf-empty'])).toEqual(['csrf-empty:warning']) expect(await run(build('{ serverURL: process.env.NEXT_PUBLIC_SERVER_URL, plugins: [] }'), ['csrf-empty'])).toEqual([]) expect(await run(build("{ csrf: ['https://site.example'], plugins: [] }"), ['csrf-empty'])).toEqual([]) expect(await run('// not a Payload config', ['csrf-empty'])).toEqual([]) }) test('open-signup: an auth collection anyone can register in is said, as info', async () => { const cfg = "iapl({ access: { authCollection: 'users' } })" expect(await run(cfg, ['open-signup'], { openSignUp: ['customers', 'members'] })).toEqual(['open-signup:info', 'open-signup:info']) expect(await run(cfg, ['open-signup'], { openSignUp: [] })).toEqual([]) expect(await run(cfg, ['open-signup'], { openSignUp: null })).toEqual([]) expect(await run(cfg, ['open-signup'])).toEqual([]) }) test('staff-accounts-open: a staff collection an account of another collection may write to is an error', async () => { const cfg = "iapl({ access: { authCollection: 'users' } })" expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:delete', 'agents:update', 'users:create'] })).toEqual(['staff-accounts-open:error', 'staff-accounts-open:error', 'staff-accounts-open:error']) expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:read', 'agents:unlock'] })).toEqual(expect.arrayContaining(['staff-accounts-open:warning', 'staff-accounts-open:error'])) expect(await run(cfg, ['staff-own-roles'], { staffOnOwnRoles: ['crew'] })).toEqual(['staff-own-roles:warning']) expect(await run(cfg, ['staff-own-roles'], { staffOnOwnRoles: [] })).toEqual([]) expect(await run(cfg, ['staff-own-roles'])).toEqual([]) expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: [] })).toEqual([]) expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: null })).toEqual([]) expect(await run(cfg, ['staff-accounts-open'])).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('- iapl-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('iapl-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('iapl-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 next@16.4.6 eslint-config-next@16.4.6') 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 mongoose@8.24.1: 8.24.1\n\npackages:\n\n happy-dom@${happyDom}:\n resolution: {integrity: x}\n\n mongoose-paginate-v2@1.9.4:\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/mongoose@8.24.1_socks@2.8.7/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('_dev passes', async () => { expect(rules(await doctor(project({ ...env('examplepl_dev'), 'iapl-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'), 'iapl-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, extra: Record = {}) { const files: Record = { ...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- iapl-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': 'IAPL_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', // IAPL_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 = '\n## IAPL 1.14.6 — agent guide\n' 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\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 iapl-* 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('proxy-matcher: a lookahead that does not end api / admin / _next at "/" is a warning; the 1.17.1 literal is not', async () => { const proxy = (matcher: string) => project({ ...base(), 'src/proxy.ts': `export const config = { matcher: ['${matcher}'] }` }) expect(rules(await doctor(proxy('/((?!api|admin|_next|.*\\\\..*).*)'), ['proxy-matcher']))).toEqual(['proxy-matcher:warning']) expect(rules(await doctor(proxy('/((?!api|cms|_next|.*\\\\..*).*)'), ['proxy-matcher']))).toEqual(['proxy-matcher:warning']) expect(rules(await doctor(proxy('/((?!(?:api|admin|_next)(?:/|$)|.*\\\\..*).*)'), ['proxy-matcher']))).toEqual([]) expect(rules(await doctor(project(base()), ['proxy-matcher']))).toEqual([]) }) test('client-hints: withSecurityConfig inside withPayload is reported (info); outside, or kept on purpose, is not', async () => { const inner = project(next('export default withPayload(\n withSecurityConfig(nextConfig))')) expect(rules(await doctor(inner, ['client-hints']))).toEqual(['client-hints:info']) expect(rules(await doctor(project(next('export default withSecurityConfig(withPayload(nextConfig))')), ['client-hints']))).toEqual([]) expect(rules(await doctor(project(next('export default withPayload(withSecurityConfig(nextConfig, { adminClientHints: false }))')), ['client-hints']))).toEqual([]) }) 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(['mail', 'node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa']) expect(status.usersSetupClosed).toBeNull() // no setup window in this config expect(status.mail).toBeNull() // no Site integrations global 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 expect((await call()).status).toBe(404) vi.stubEnv('IAPL_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 (iapl-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, iapl-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': '- iapl-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 = {} let home = 'ok' 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(''); return} res.writeHead(200, headers).end(home) }) await new Promise((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((resolve) => server.close(() => resolve()))) test('X-Powered-By, missing headers, noindex on production', async () => { headers = { 'x-content-type-options': 'nosniff' } home = '' 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('live (--url): client hints', () => { let server: Server let url = '' let headers: Record = {} beforeAll(async () => { server = createServer((_req, res) => res.writeHead(200, headers).end('ok')) await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) url = `http://127.0.0.1:${(server.address() as { port: number }).port}` }) afterAll(() => new Promise((resolve) => server.close(() => resolve()))) test('a public page that sends Critical-CH for the colour scheme is reported; without it, or kept on purpose, not', async () => { const outer = { ...base(), 'next.config.ts': 'export default withSecurityConfig(withPayload(nextConfig))' } headers = { 'Accept-CH': 'Sec-CH-Prefers-Color-Scheme', 'Critical-CH': 'Sec-CH-Prefers-Color-Scheme' } expect((await doctor(project(outer), ['client-hints'], { url })).findings.map((f) => `${f.severity}: ${f.message}`)).toEqual([ 'info: live / sends Critical-CH: Sec-CH-Prefers-Color-Scheme (only the admin needs it)', ]) const kept = { ...base(), 'next.config.ts': 'export default withSecurityConfig(withPayload(nextConfig), { adminClientHints: false })' } expect((await doctor(project(kept), ['client-hints'], { url })).findings).toEqual([]) headers = {} expect((await doctor(project(outer), ['client-hints'], { url })).findings).toEqual([]) }) }) describe('CLI', () => { const clean = () => project({ ...base(), 'AGENTS.md': '## Project decisions\n- x\n\n## IAPL 1.14.6 — agent guide\n', '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(), 'iapl-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/iapl-doctor.json silences only with reasons', () => { const config = JSON.parse(readFileSync(path.join(packageRoot, 'reference/iapl-doctor.json'), 'utf8')) as DoctorConfig for (const setting of Object.values(config.rules ?? {})) {expect(setting.reason?.trim()).toBeTruthy()} }) }) describe('iapl-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) }) }) describe('e-mail: transport, the mail service, Graph, the confirm route', () => { const ids = ['mail-transport', 'mail-method', 'mail-non-public', 'mail-relay-state', 'mail-reply-address', 'mail-graph-deprecated', 'mail-relay-route'] const relay = (extra: object = {}) => ({ connected: true, disconnected: false, nameReplaced: false, state: 'active', ...extra }) const mail = (extra: object = {}) => ({ graphEnv: false, relay: relay(), replyAddress: true, status: null, transport: 'relay', ...extra }) const run = async (deep: null | object, files: Record = {}) => rules(await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })', ...files }), ids, deep ? { deepStatus: { mail: deep } } : {})) test('a healthy site on the mail service, a site on SMTP, and a run without the deep status report nothing', async () => { expect(await run(mail())).toEqual([]) expect(await run(mail({ relay: relay({ connected: false, state: undefined }), replyAddress: false, transport: 'smtp' }))).toEqual([]) expect(await run(null)).toEqual([]) }) test('mail-transport: nothing set up is an error; failing sends are a warning, an error after a day', async () => { expect(await run(mail({ relay: null, transport: 'none' }))).toEqual(['mail-transport:error']) const failing = (since: string) => mail({ status: { code: 'relay-quota', since, state: 'degraded' } }) expect(await run(failing(`${TODAY}T09:00:00.000Z`))).toEqual(['mail-transport:warning']) expect(await run(failing('2026-10-27T09:00:00.000Z'))).toEqual(['mail-transport:error']) }) test('mail-relay-state: disconnected, suspended, pending, refused, not enrolled yet, a replaced sender name', async () => { expect(await run(mail({ relay: relay({ connected: false, disconnected: true }) }))).toEqual(['mail-relay-state:error']) expect(await run(mail({ relay: relay({ state: 'suspended' }) }))).toEqual(['mail-relay-state:error']) expect(await run(mail({ relay: relay({ state: 'pending' }) }))).toEqual(['mail-relay-state:warning']) expect(await run(mail({ relay: relay({ connected: false, reason: 'redirect', refusal: 'callback-failed', state: undefined }) }))).toEqual(['mail-relay-state:warning']) expect(await run(mail({ relay: relay({ connected: false, state: undefined }) }))).toEqual(['mail-relay-state:info']) // a copy of another site's database: it does not connect by itself, and the finding says what to do const copy = await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail({ relay: relay({ connected: false, reason: 'client.pl', refusal: 'client-other-host', state: undefined }) }) } }) expect(rules(copy)).toEqual(['mail-relay-state:warning']) expect(copy.findings[0].message).toContain('client.pl') expect(copy.findings[0].fix).toContain('Connect again') // the same for a copy that has a token of its own (production's data copied back onto the development address) expect(await run(mail({ nonPublic: true, nonPublicBy: 'noindex', relay: relay({ reason: 'client.pl', refusal: 'client-other-host' }) }))).toEqual(['mail-relay-state:warning', 'mail-non-public:info']) // a PUBLIC site whose database knows another host: the site after its launch — or a copy that forgot IAPL_NOINDEX const launched = await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail({ otherHostEntries: true }) } }) expect(rules(launched)).toEqual(['mail-relay-state:info']) expect(launched.findings[0].message).toContain('copy') expect(launched.findings[0].fix).toContain('IAPL_NOINDEX=1') expect(launched.findings[0].fix).toContain('otherHosts') expect(await run(mail({ nonPublic: true, nonPublicBy: 'noindex', otherHostEntries: true }))).toEqual(['mail-non-public:info']) }) test('mail-method: a chosen method that cannot be used is an error; nothing chosen yet is information', async () => { const find = async (deep: object) => (await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail(deep) } })).findings.filter((f) => f.rule === 'mail-method') const smtp = await find({ methodChosen: true, methodProblem: 'smtp-incomplete', relay: relay({ connected: false, state: undefined }), replyAddress: false, transport: 'smtp' }) expect(smtp.map((f) => f.severity)).toEqual(['error']) expect(smtp[0].message).toContain('e-mails are not sent') expect(smtp[0].fix).toContain('server, user name and password') const graph = await find({ methodChosen: true, methodProblem: 'graph-not-set-up', relay: relay({ connected: false, state: undefined }), replyAddress: false, transport: 'graph' }) expect(graph.map((f) => f.severity)).toEqual(['error']) expect(graph[0].message).toContain('GRAPH_*') const open = await find({ methodChosen: false }) expect(open.map((f) => f.severity)).toEqual(['info']) expect(open[0].message).toContain('the built-in service') expect(open[0].message).toContain('the way it did before the upgrade') expect(open[0].fix).toContain('nothing to do') expect(await find({ methodChosen: true })).toEqual([]) // Postgres / SQLite whose 1.17.1 migration has not run const column = await find({ methodChosen: false, methodColumnMissing: true }) expect(column.map((f) => f.severity)).toEqual(['error']) expect(column[0].message).toContain('no column for "Sending method"') expect(column[0].fix).toContain('migrate:create') expect(await find({ methodChosen: false, relay: null, transport: 'none' })).toEqual([]) // that is mail-transport's error }) test('mail-non-public: says which signal makes the site a non-public copy — the development pattern, or IAPL_NOINDEX', async () => { const find = async (deep: object) => (await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })' }), ids, { deepStatus: { mail: mail(deep) } })).findings const byHost = await find({ nonPublic: true, nonPublicBy: 'development-host', nonPublicPattern: '*.dev.netscale.pl' }) expect(byHost.map((f) => `${f.rule}:${f.severity}`)).toEqual(['mail-non-public:info']) expect(byHost[0].message).toContain('its host matches the development pattern "*.dev.netscale.pl"') expect(byHost[0].fix).toContain('developmentHosts') const byEnv = await find({ nonPublic: true, nonPublicBy: 'noindex' }) expect(byEnv[0].message).toContain('IAPL_NOINDEX is set') expect(byEnv[0].fix).toContain('remove IAPL_NOINDEX') // the copy warning names the same signal const held = await find({ nonPublic: true, nonPublicBy: 'development-host', nonPublicPattern: '*.dev.netscale.pl', relay: relay({ reason: 'client.pl', refusal: 'client-other-host' }) }) expect(held.map((f) => `${f.rule}:${f.severity}`)).toEqual(['mail-relay-state:warning', 'mail-non-public:info']) expect(held[0].message).toContain('"*.dev.netscale.pl"') // a public site, a site on SMTP: nothing expect(await run(mail({}))).toEqual([]) expect(await run(mail({ nonPublic: true, nonPublicBy: 'noindex', relay: relay({ connected: false, state: undefined }), replyAddress: false, transport: 'smtp' }))).toEqual([]) expect(await run(mail({ relay: relay({ nameReplaced: true }) }))).toEqual(['mail-relay-state:warning']) }) test('mail-reply-address: on the mail service without a "Sender address"', async () => { expect(await run(mail({ replyAddress: false }))).toEqual(['mail-reply-address:warning']) }) test('mail-graph-deprecated: the variables, the transport in use, or graphAdapter in the config', async () => { expect(await run(mail({ graphEnv: true, relay: relay({ connected: false, state: undefined }), transport: 'graph' }))).toEqual(['mail-graph-deprecated:warning']) expect(await run(mail({ graphEnv: true, transport: 'smtp' }))).toEqual(['mail-graph-deprecated:warning']) expect(await run(null, { 'src/payload.config.ts': 'email: graphAdapter()' })).toEqual(['mail-graph-deprecated:warning']) }) test('mail-relay-route: trailing slashes or another API route keep the service from confirming the site — unless the relay is off', async () => { expect(await run(null, { 'next.config.ts': 'export default { trailingSlash: true }' })).toEqual(['mail-relay-route:warning']) expect(await run(null, { 'src/payload.config.ts': "export default { plugins: [iapl({})], routes: { api: '/cms-api' } }" })).toEqual(['mail-relay-route:warning']) expect(await run(null, { 'next.config.ts': 'export default { trailingSlash: true }', 'src/payload.config.ts': 'iapl({ mail: { relay: false } })' })).toEqual([]) }) test('every rule is listed and documented in doctor.md', () => { const doc = readFileSync(path.join(packageRoot, 'docs/doctor.md'), 'utf8') for (const id of ids) { expect(doctorRules.some((r) => r.id === id)).toBe(true) expect(doc).toContain(`\`${id}\``) } }) })