bin ipal-doctor + @intecion/ipal-kit/doctor: static rules (versions, Node 22, AGENT.md §3 layout and naming, database names, env rules, headers, X-Powered-By, CSP, 2FA, cookie scanner, adminMeta, AGENTS.md, skills, seeds, block library via blockLibraryManifest, ipal-audit --quick), registry rules (latest plugin, pnpm audit --prod), live rules (--url, ipal-seo-check), deep rules (--deep via payload run; GET /api/ipal/doctor, off until IPAL_DOCTOR_TOKEN). Human / JSON output, --strict, exit codes 0/1/2/3, --sites drift table, ipal-doctor.json with reasons, until, files, seen. Fixes found on the way: sitemap leaves out the System pages 404 page; ipal-audit finds array labels after fields, any form seed, runs grep in UTF-8; ipal-seo-check counts duplicate titles per language. Reference site at zero findings (static), CI steps on. Co-Authored-By: Claude Opus 5.5 <[email protected]>
206 lines
10 KiB
TypeScript
206 lines
10 KiB
TypeScript
import { existsSync, writeFileSync } from 'node:fs'
|
|
import { join, resolve } from 'node:path'
|
|
import { pathToFileURL } from 'node:url'
|
|
|
|
import type { DoctorConfig, DoctorFinding, DoctorReport, DoctorRule, DoctorSeverity, DoctorStatus, RuleFinding } from './types.js'
|
|
|
|
import { createDoctorContext, type DoctorContext, loadDoctorConfig } from './project.js'
|
|
import { agentRules } from './rules/agents.js'
|
|
import { blockRules } from './rules/blocks.js'
|
|
import { envRules } from './rules/env.js'
|
|
import { layoutRules } from './rules/layout.js'
|
|
import { createLiveFetcher, liveRules } from './rules/live.js'
|
|
import { securityRules } from './rules/security.js'
|
|
import { seedRules } from './rules/seeds.js'
|
|
import { toolingRules } from './rules/tooling.js'
|
|
import { versionRules } from './rules/versions.js'
|
|
import { run } from './util.js'
|
|
|
|
const deepRules: DoctorRule[] = [
|
|
{
|
|
id: 'deep-status',
|
|
check: (ctx) => (ctx.deep?.error ? [{ fix: 'check DATABASE_URI / PAYLOAD_SECRET and that the database is up', message: `the deep check could not finish: ${ctx.deep.error}`, severity: 'error' }] : []),
|
|
group: 'deep',
|
|
source: 'deep',
|
|
},
|
|
]
|
|
|
|
/** Every built-in rule, in report order. Exported so a project can wrap, filter or extend them. */
|
|
export const doctorRules: DoctorRule[] = [
|
|
...versionRules,
|
|
...layoutRules,
|
|
...envRules,
|
|
...securityRules,
|
|
...agentRules,
|
|
...seedRules,
|
|
...blockRules,
|
|
...toolingRules,
|
|
...liveRules,
|
|
...deepRules,
|
|
]
|
|
|
|
/** `ipal-audit-skip` keys (AGENTS.md) → doctor rules they silence (the audit script honours the rest itself). */
|
|
export const AUDIT_SKIP_RULES: Record<string, string[]> = {
|
|
csp: ['csp'],
|
|
twofactor: ['2fa'],
|
|
}
|
|
|
|
export type RunDoctorOptions = {
|
|
adminRoute?: string
|
|
config?: DoctorConfig
|
|
/** Run the deep rules: `payload run` in the project (read-only). */
|
|
deep?: boolean
|
|
/** Status already collected (tests, or another source). */
|
|
deepStatus?: DoctorStatus | null
|
|
/** A production env export: its DATABASE_URI must name <domain>_prod. */
|
|
envFile?: string
|
|
offline?: boolean
|
|
/** Rule ids or groups to run (default all). */
|
|
only?: string[]
|
|
/** The doctor's package root (bin/, docs/, dist/). */
|
|
packageRoot: string
|
|
root: string
|
|
/** Extra rules (a project's own, `extraRules` in ipal-doctor.json are added too). */
|
|
rules?: DoctorRule[]
|
|
skip?: string[]
|
|
staging?: boolean
|
|
today?: string
|
|
/** Live site; with IPAL_DOCTOR_TOKEN set (and no --deep) the deep rules read GET /api/ipal/doctor. */
|
|
url?: string
|
|
/** Store first-seen dates (CSP report-only) in ipal-doctor.json. Default: only outside CI. */
|
|
writeSeen?: boolean
|
|
}
|
|
|
|
/** `payload run` of the probe inside the project; null when it cannot start. */
|
|
export function runDeepProbe(ctx: DoctorContext): DoctorStatus {
|
|
const probe = join(ctx.packageRoot, 'dist/modules/doctor/probe.js')
|
|
if (!existsSync(probe)) {return { error: `the probe is missing (${probe}) — build the plugin` }}
|
|
const res = run('pnpm', ['exec', 'payload', 'run', probe], ctx.root, 300_000)
|
|
const line = res.stdout.split('\n').find((l) => l.startsWith('IPAL_DOCTOR_STATUS '))
|
|
if (!line) {return { error: `payload run gave no status (exit ${res.code}): ${(res.stderr || res.stdout).trim().split('\n').slice(-1)[0] ?? ''}` }}
|
|
try {
|
|
return JSON.parse(line.slice('IPAL_DOCTOR_STATUS '.length)) as DoctorStatus
|
|
} catch {
|
|
return { error: 'payload run printed an unreadable status' }
|
|
}
|
|
}
|
|
|
|
async function fetchDeepStatus(url: string, token: string): Promise<DoctorStatus> {
|
|
try {
|
|
const res = await fetch(`${url.replace(/\/+$/, '')}/api/ipal/doctor`, { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(20_000) })
|
|
if (!res.ok) {return { error: `GET /api/ipal/doctor → ${res.status}` }}
|
|
return (await res.json()) as DoctorStatus
|
|
} catch (err) {
|
|
return { error: `GET /api/ipal/doctor failed: ${err instanceof Error ? err.message : String(err)}` }
|
|
}
|
|
}
|
|
|
|
const SEVERITIES: DoctorSeverity[] = ['error', 'warning', 'info']
|
|
|
|
/** `src/components/design/**` → a RegExp over project-relative paths. */
|
|
export function globToRegExp(glob: string): RegExp {
|
|
const body = glob.replace(/^\.\//, '').split('**').map((part) => part.split('*').map((p) => p.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('[^/]*')).join('.*')
|
|
return new RegExp(`^${body}$`)
|
|
}
|
|
|
|
const inFiles = (file: string | undefined, globs: string[] | undefined) => !globs?.length || (!!file && globs.some((g) => globToRegExp(g).test(file)))
|
|
|
|
/** Applies ipal-doctor.json `rules` and `ipal-audit-skip` lines: off (silenced, kept in JSON), severity, until. */
|
|
export function applySettings(findings: DoctorFinding[], ctx: DoctorContext): DoctorFinding[] {
|
|
const settings = ctx.config.rules ?? {}
|
|
const out: DoctorFinding[] = []
|
|
for (const [id, s] of Object.entries(settings)) {
|
|
if (!s || typeof s !== 'object') {continue}
|
|
if (!s.reason?.trim()) {out.push({ fix: 'add "reason": "<why>" — an entry without one is ignored', message: `ipal-doctor.json: rule "${id}" has no reason, so it is ignored`, rule: 'doctor-config', severity: 'error', source: 'static' })}
|
|
else if (s.severity && !SEVERITIES.includes(s.severity)) {out.push({ message: `ipal-doctor.json: rule "${id}" has an unknown severity "${s.severity}"`, rule: 'doctor-config', severity: 'error', source: 'static' })}
|
|
else if (s.until && ctx.today > s.until) {out.push({ fix: 'fix the finding, or extend "until" with a new reason', message: `ipal-doctor.json: the setting for "${id}" expired on ${s.until}`, rule: 'doctor-config', severity: 'warning', source: 'static' })}
|
|
}
|
|
const skips = new Map<string, string>()
|
|
for (const [key, reason] of ctx.auditSkips) {
|
|
for (const id of AUDIT_SKIP_RULES[key] ?? []) {skips.set(id, reason || `ipal-audit-skip: ${key}`)}
|
|
}
|
|
for (const f of findings) {
|
|
const s = settings[f.rule] ?? settings[f.rule.split(':')[0]]
|
|
const valid = s?.reason?.trim() && !(s.until && ctx.today > s.until) && inFiles(f.file, s.files)
|
|
if (valid && s.off) {out.push({ ...f, reason: s.reason, silenced: true })}
|
|
else if (valid && s.severity && SEVERITIES.includes(s.severity)) {out.push({ ...f, reason: s.reason, severity: s.severity })}
|
|
else if (!valid && skips.has(f.rule)) {out.push({ ...f, reason: skips.get(f.rule), silenced: true })}
|
|
else {out.push(f)}
|
|
}
|
|
return out
|
|
}
|
|
|
|
const RANK: Record<DoctorSeverity, number> = { error: 0, info: 2, warning: 1 }
|
|
|
|
async function loadExtraRules(ctx: DoctorContext): Promise<{ errors: DoctorFinding[]; rules: DoctorRule[] }> {
|
|
const rules: DoctorRule[] = []
|
|
const errors: DoctorFinding[] = []
|
|
for (const file of ctx.config.extraRules ?? []) {
|
|
try {
|
|
const mod = (await import(pathToFileURL(resolve(ctx.root, file)).href)) as { default?: DoctorRule[]; rules?: DoctorRule[] }
|
|
rules.push(...(mod.rules ?? mod.default ?? []))
|
|
} catch (err) {
|
|
errors.push({ message: `extra rules ${file} could not be loaded: ${err instanceof Error ? err.message : String(err)}`, rule: 'doctor-config', severity: 'error', source: 'static' })
|
|
}
|
|
}
|
|
return { errors, rules }
|
|
}
|
|
|
|
/** Runs the doctor on one project folder. Never throws for a failing rule (it becomes a `doctor-crash` finding). */
|
|
export async function runDoctor(options: RunDoctorOptions): Promise<DoctorReport> {
|
|
const root = resolve(options.root)
|
|
const live = options.url ? createLiveFetcher(options.url, { adminRoute: options.adminRoute, staging: options.staging }) : null
|
|
const ctx = createDoctorContext({ config: options.config, envFile: options.envFile, live, offline: options.offline, packageRoot: options.packageRoot, root, today: options.today })
|
|
|
|
// Deep status: the probe (--deep), the endpoint (--url + IPAL_DOCTOR_TOKEN), or none.
|
|
const token = process.env.IPAL_DOCTOR_TOKEN?.trim()
|
|
if (options.deepStatus !== undefined) {ctx.deep = options.deepStatus}
|
|
else if (options.deep) {ctx.deep = runDeepProbe({ ...ctx, root })}
|
|
else if (options.url && token && token.length >= 32) {ctx.deep = await fetchDeepStatus(options.url, token)}
|
|
|
|
const extra = await loadExtraRules(ctx)
|
|
const all = [...doctorRules, ...(options.rules ?? []), ...extra.rules]
|
|
const wanted = (r: DoctorRule) =>
|
|
(!options.only?.length || options.only.some((o) => o === r.id || o === r.group)) && !options.skip?.some((o) => o === r.id || o === r.group)
|
|
|
|
const findings: DoctorFinding[] = [...extra.errors]
|
|
if (ctx.configError) {findings.push({ message: ctx.configError, rule: 'doctor-config', severity: 'error', source: 'static' })}
|
|
const skipped: string[] = []
|
|
for (const rule of all.filter(wanted)) {
|
|
if ((rule.source === 'registry' && ctx.offline) || (rule.source === 'live' && !ctx.live) || (rule.source === 'deep' && !ctx.deep)) {
|
|
skipped.push(rule.id)
|
|
continue
|
|
}
|
|
let raw: RuleFinding[]
|
|
try {
|
|
raw = await rule.check(ctx)
|
|
} catch (err) {
|
|
raw = [{ message: `rule crashed: ${err instanceof Error ? err.message : String(err)}`, rule: 'doctor-crash', severity: 'error' }]
|
|
}
|
|
for (const f of raw) {findings.push({ docs: rule.docs, ...f, rule: f.rule ?? rule.id, source: f.rule === 'doctor-crash' ? 'static' : rule.source })}
|
|
}
|
|
|
|
// First-seen dates (CSP report-only → warning after 4 weeks): stored outside CI when the file exists.
|
|
const writeSeen = options.writeSeen ?? !process.env.CI
|
|
if (writeSeen && findings.some((f) => f.rule === 'csp' && /report-only/.test(f.message)) && !ctx.config.seen?.['csp-report-only'] && existsSync(join(root, 'ipal-doctor.json'))) {
|
|
const current = loadDoctorConfig(root).config
|
|
writeFileSync(join(root, 'ipal-doctor.json'), `${JSON.stringify({ ...current, seen: { ...current.seen, 'csp-report-only': ctx.today } }, null, 2)}\n`)
|
|
}
|
|
|
|
const final = applySettings(findings, ctx).sort((a, b) => Number(!!a.silenced) - Number(!!b.silenced) || RANK[a.severity] - RANK[b.severity])
|
|
const active = final.filter((f) => !f.silenced)
|
|
return {
|
|
findings: final,
|
|
rulesVersion: ctx.rulesVersion,
|
|
schema: 1,
|
|
site: { domain: ctx.domain, path: root, plugin: ctx.pluginVersion },
|
|
skipped,
|
|
summary: {
|
|
error: active.filter((f) => f.severity === 'error').length,
|
|
info: active.filter((f) => f.severity === 'info').length,
|
|
silenced: final.length - active.length,
|
|
warning: active.filter((f) => f.severity === 'warning').length,
|
|
},
|
|
}
|
|
}
|