Files
ipal-kit/test/doctor.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 ab51027617 Payload 3.94.1, dependency updates, overrides re-checked
- payload and every @payloadcms/* 3.94.1 in the plugin's dev dependencies, the
  reference site and the starter (peer range unchanged: ^3.90.2); react/react-dom
  19.3.1; reference engines node >=22.23.5 <23 (Payload 3.94's minimum).
- Overrides re-checked: dompurify and happy-dom still needed; mongoose (3.90–3.93)
  and undici (3.90–3.91) only on an older Payload; graphql-scalars no longer needed
  (GHSA-x8rm-f576-gq67 covers 1.24.1–2.0.0; Payload pins 1.22.2). Reference keeps
  dompurify + happy-dom; plugin root drops graphql-scalars.
- ipal-doctor transitive-min: the mongoose fix names the Payload upgrade first.
- nodemailer 10.6.1; dev: playwright 1.65.1, vitest 5.1.1, prettier 3.10.1,
  @swc/cli 0.8, rimraf 6 (clean uses --glob), cross-env 10, open 11,
  sort-package-json 4, @swc-node/register 1.12.1, vite-tsconfig-paths 6.1.1;
  reference tailwind 4.3.5, postcss 8.5.33.
- Kept back: typescript 7, eslint 10, graphql 17, @types/node 26, lucide-react 1.x.
- AGENT.md §4 item 12, ipal-setup, ipal-upgrade, README, PROGRAMISTA §1, forms.md,
  doctor.md; reference skills copy; CHANGELOG Unreleased.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 15:18:58 +01:00

455 lines
30 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 } 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('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', 'usersWithout2fa'])
})
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()}
})
})