IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved

Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 17:24:21 +01:00
co-authored by Claude Fable 5.2
parent 414a4702df
commit 0a4f001797
262 changed files with 955 additions and 950 deletions
+7 -7
View File
@@ -6,8 +6,8 @@ import type { DoctorReport, DoctorSeverity } from './types.js'
import { formatDriftTable, formatReport } from './format.js'
import { runDoctor } from './run.js'
export const DOCTOR_USAGE = `Usage: ipal-doctor [dir] [options]
Checks a site against the ipal-kit team rules and lists every gap with a fix hint.
export const DOCTOR_USAGE = `Usage: iapl-doctor [dir] [options]
Checks a site against the IAPL team rules and lists every gap with a fix hint.
--json machine-readable report (schema 1)
--md Markdown table (with --sites: rule × site)
@@ -24,10 +24,10 @@ export const DOCTOR_USAGE = `Usage: ipal-doctor [dir] [options]
--sites <glob> many projects, e.g. '../*-web' (read-only report; never a gate)
Exit: 0 ok · 1 findings at or above --fail-on · 2 could not run · 3 a rule crashed
Silence a rule with a reason in ipal-doctor.json — docs/doctor.md`
Silence a rule with a reason in iapl-doctor.json — docs/doctor.md`
/**
* Whether this run stores first-seen dates in ipal-doctor.json: not with --sites or --json, and
* Whether this run stores first-seen dates in iapl-doctor.json: not with --sites or --json, and
* never when CI is set (a CI run must not change a tracked file).
*/
export function shouldWriteSeen(args: { json?: boolean; sites?: unknown }, env: Record<string, string | undefined> = process.env): boolean {
@@ -113,18 +113,18 @@ export async function runDoctorCli(argv: string[], { cwd = process.cwd(), log =
}
const args = parseDoctorArgs(argv)
if (typeof args === 'string') {
console.error(`ipal-doctor: ${args}\n\n${DOCTOR_USAGE}`)
console.error(`iapl-doctor: ${args}\n\n${DOCTOR_USAGE}`)
return 2
}
const dirs = args.sites ? expandSites(args.sites, cwd) : [resolve(cwd, args.dir)]
if (!dirs.length) {
console.error(`ipal-doctor: no folder matches ${args.sites}`)
console.error(`iapl-doctor: no folder matches ${args.sites}`)
return 2
}
const reports: DoctorReport[] = []
for (const dir of dirs) {
if (!existsSync(join(dir, 'package.json'))) {
console.error(`ipal-doctor: ${dir} is not a project root (no package.json)`)
console.error(`iapl-doctor: ${dir} is not a project root (no package.json)`)
if (!args.sites) {return 2}
continue
}
+2 -2
View File
@@ -9,7 +9,7 @@ const summaryLine = (r: DoctorReport) =>
/** Human-readable report: header, findings worst first with fix and doc link, summary. */
export function formatReport(report: DoctorReport, { color = false }: { color?: boolean } = {}): string {
const c = (sev: DoctorSeverity, text: string) => (color ? `${COLOR[sev]}${text}\x1b[0m` : text)
const lines = [`ipal-doctor ${report.rulesVersion} — ${report.site.path}`, `site: ${report.site.domain ?? '(no domain)'} · ipal-kit ${report.site.plugin ?? 'not installed'}`, '']
const lines = [`iapl-doctor ${report.rulesVersion} — ${report.site.path}`, `site: ${report.site.domain ?? '(no domain)'} · IAPL ${report.site.plugin ?? 'not installed'}`, '']
const active = report.findings.filter((f) => !f.silenced)
if (!active.length) {lines.push('No findings.')}
for (const f of active) {
@@ -24,7 +24,7 @@ export function formatReport(report: DoctorReport, { color = false }: { color?:
for (const f of silenced) {lines.push(` - ${f.rule}: ${f.message} — ${f.reason}`)}
}
if (report.skipped.length) {lines.push('', `Not run: ${report.skipped.join(', ')} (--url, --deep, or without --offline)`)}
lines.push('', `ipal-doctor: ${summaryLine(report)}`)
lines.push('', `iapl-doctor: ${summaryLine(report)}`)
return lines.join('\n')
}
+5 -5
View File
@@ -1,9 +1,9 @@
import type { SanitizedConfig } from 'payload'
/**
* ipal-doctor --deep: run inside the project by `pnpm exec payload run <this file>`.
* iapl-doctor --deep: run inside the project by `pnpm exec payload run <this file>`.
* Read-only Local API counts (collectDoctorStatus), an exact import-map comparison and the
* project's own env rules. Prints one line `IPAL_DOCTOR_STATUS <json>` and exits.
* project's own env rules. Prints one line `IAPL_DOCTOR_STATUS <json>` and exits.
*
* The import map is generated into a temporary file NEXT TO the committed one (the imports are
* relative to it), compared, then removed. Nothing else is written.
@@ -47,9 +47,9 @@ async function main() {
Object.assign(status, await collectDoctorStatus(payload))
// The doctor passes the committed import map it found (relative to the project root).
const committed = config.admin?.importMap?.importMapFile ?? (process.env.IPAL_DOCTOR_IMPORT_MAP ? join(root, process.env.IPAL_DOCTOR_IMPORT_MAP) : '')
const committed = config.admin?.importMap?.importMapFile ?? (process.env.IAPL_DOCTOR_IMPORT_MAP ? join(root, process.env.IAPL_DOCTOR_IMPORT_MAP) : '')
if (committed && existsSync(committed)) {
const temp = join(dirname(committed), 'importMap.ipal-doctor.tmp.js')
const temp = join(dirname(committed), 'importMap.iapl-doctor.tmp.js')
try {
const copy = { ...config, admin: { ...config.admin, importMap: { ...config.admin.importMap, importMapFile: temp } } }
await generateImportMap(copy, { force: true, log: false })
@@ -67,5 +67,5 @@ try {
} catch (err) {
status.error = err instanceof Error ? (err.message.split('\n')[0] ?? 'failed') : String(err)
}
process.stdout.write(`IPAL_DOCTOR_STATUS ${JSON.stringify(status)}\n`)
process.stdout.write(`IAPL_DOCTOR_STATUS ${JSON.stringify(status)}\n`)
process.exit(0)
+7 -7
View File
@@ -7,7 +7,7 @@ import { databaseNameFromUri } from '../env/databaseName.js'
/** Everything a rule may read about the project. Files only — nothing is written. */
export type DoctorContext = {
/** Keys from `ipal-audit-skip: <keys> — <reason>` lines in AGENTS.md, with the reason. */
/** Keys from `iapl-audit-skip: <keys> — <reason>` lines in AGENTS.md, with the reason. */
auditSkips: Map<string, string>
config: DoctorConfig
configError: null | string
@@ -75,11 +75,11 @@ export function bareHost(value: string): string {
const isLocalHost = (host: string) => /^(?:localhost|127\.0\.0\.1|\[?::1\]?|0\.0\.0\.0)$|^[^.]+$/.test(host)
/** Reads `ipal-audit-skip: a, b — reason` lines (AGENT.md §0b). */
/** Reads `iapl-audit-skip: a, b — reason` lines (AGENT.md §0b). */
export function readAuditSkips(agents: string): Map<string, string> {
const out = new Map<string, string>()
for (const line of agents.split('\n')) {
const m = line.match(/^[-* ]*ipal-audit-skip:(.*)$/i)
const m = line.match(/^[-* ]*iapl-audit-skip:(.*)$/i)
if (!m) {continue}
const [keys = '', ...rest] = m[1].trim().split(/\s+—\s+|\s+-\s+/)
const reason = rest.join(' — ').trim()
@@ -89,14 +89,14 @@ export function readAuditSkips(agents: string): Map<string, string> {
}
export function loadDoctorConfig(root: string): { config: DoctorConfig; error: null | string } {
const file = join(root, 'ipal-doctor.json')
const file = join(root, 'iapl-doctor.json')
if (!existsSync(file)) {return { config: {}, error: null }}
try {
const parsed = JSON.parse(readFileSync(file, 'utf8')) as unknown
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {return { config: {}, error: 'ipal-doctor.json must hold an object' }}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {return { config: {}, error: 'iapl-doctor.json must hold an object' }}
return { config: parsed as DoctorConfig, error: null }
} catch (err) {
return { config: {}, error: `ipal-doctor.json is not valid JSON (${err instanceof Error ? err.message : String(err)})` }
return { config: {}, error: `iapl-doctor.json is not valid JSON (${err instanceof Error ? err.message : String(err)})` }
}
}
@@ -161,7 +161,7 @@ export function createDoctorContext(options: ProjectOptions): DoctorContext {
}
const src = exists('src') ? 'src/' : ''
// Domain: ipal-doctor.json → a non-local NEXT_PUBLIC_SERVER_URL → the folder name minus -web (docs: D6).
// Domain: iapl-doctor.json → a non-local NEXT_PUBLIC_SERVER_URL → the folder name minus -web (docs: D6).
const urls = [env.local?.NEXT_PUBLIC_SERVER_URL, env.example?.NEXT_PUBLIC_SERVER_URL].filter(Boolean).map((u) => bareHost(u!))
const fromDir = basename(root).replace(/-web$/, '')
// The folder name (`intecioncom-web`) is already the domain without dots — enough for the database names.
+10 -10
View File
@@ -19,7 +19,7 @@ export function hashDir(dir: string): string {
return hash.digest('hex')
}
/** What `ipal-skills` would change in a skills folder: missing, stale (different content) and retired skills. */
/** What `iapl-skills` would change in a skills folder: missing, stale (different content) and retired skills. */
export function planSkills({ dest, source }: { dest: string; source: string }): { missing: string[]; retired: string[]; stale: string[] } {
const ls = (d: string) => {
try {
@@ -42,7 +42,7 @@ export const agentRules: DoctorRule[] = [
id: 'agents-md',
check: (ctx) => {
const agents = ctx.read('AGENTS.md')
if (!agents) {return [{ fix: 'AGENT.md §13 template, then pnpm exec ipal-skills', message: 'no AGENTS.md', severity: 'error' }]}
if (!agents) {return [{ fix: 'AGENT.md §13 template, then pnpm exec iapl-skills', message: 'no AGENTS.md', severity: 'error' }]}
const out: RuleFinding[] = []
const parts = agents.split(/^## Project decisions[ \t]*$/m)
if (parts.length < 2) {out.push({ file: 'AGENTS.md', fix: 'add "## Project decisions" with the architecture answers (AGENT.md "Ask before you build")', message: 'AGENTS.md has no "## Project decisions" section', severity: 'error' })}
@@ -50,12 +50,12 @@ export const agentRules: DoctorRule[] = [
const body = parts[1].split(/^## /m)[0].replace(/<!--[\s\S]*?-->/g, '')
if (!/^\s*[-*] +\S/m.test(body)) {out.push({ file: 'AGENTS.md', message: '"## Project decisions" is empty', severity: 'warning' })}
}
const pointer = agents.match(/<!-- ipal-kit:start -->[\s\S]*?## ipal-kit ([\w.-]+) — agent guide[\s\S]*?<!-- ipal-kit:end -->/)
if (!pointer) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec ipal-skills', message: 'no ipal-kit pointer block in AGENTS.md', severity: 'warning' })}
else if (ctx.pluginVersion && pointer[1] !== ctx.pluginVersion) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec ipal-skills', message: `the pointer block names ipal-kit ${pointer[1]}, installed ${ctx.pluginVersion}`, severity: 'warning' })}
const pointer = agents.match(/<!-- iapl:start -->[\s\S]*?## IAPL ([\w.-]+) — agent guide[\s\S]*?<!-- iapl:end -->/)
if (!pointer) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec iapl-skills', message: 'no IAPL pointer block in AGENTS.md', severity: 'warning' })}
else if (ctx.pluginVersion && pointer[1] !== ctx.pluginVersion) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec iapl-skills', message: `the pointer block names IAPL ${pointer[1]}, installed ${ctx.pluginVersion}`, severity: 'warning' })}
const claude = ctx.read('CLAUDE.md')
if (!claude) {out.push({ fix: 'pnpm exec ipal-skills (creates CLAUDE.md with @AGENTS.md)', message: 'no CLAUDE.md', severity: 'warning' })}
else if (!/^@AGENTS\.md\s*$/m.test(claude) && !claude.includes('<!-- ipal-kit:start -->')) {out.push({ file: 'CLAUDE.md', fix: 'add a line @AGENTS.md', message: 'CLAUDE.md neither imports AGENTS.md nor has the pointer block', severity: 'warning' })}
if (!claude) {out.push({ fix: 'pnpm exec iapl-skills (creates CLAUDE.md with @AGENTS.md)', message: 'no CLAUDE.md', severity: 'warning' })}
else if (!/^@AGENTS\.md\s*$/m.test(claude) && !claude.includes('<!-- iapl:start -->')) {out.push({ file: 'CLAUDE.md', fix: 'add a line @AGENTS.md', message: 'CLAUDE.md neither imports AGENTS.md nor has the pointer block', severity: 'warning' })}
return out
},
docs: 'docs/agent/AGENT.md#13-agentsmd-template-for-a-project',
@@ -66,8 +66,8 @@ export const agentRules: DoctorRule[] = [
id: 'skills-current',
check: (ctx) => {
const dest = ['.agents/skills', '.claude/skills'].find((d) => ctx.list(d).some((n) => n.startsWith('ipal-')))
if (!dest) {return [{ fix: 'pnpm exec ipal-skills', message: 'no ipal-* skills in .agents/skills or .claude/skills', severity: 'error' }]}
// Compare with the skills the project's installed plugin ships (what `pnpm exec ipal-skills` copies).
if (!dest) {return [{ fix: 'pnpm exec iapl-skills', message: 'no iapl-* skills in .agents/skills or .claude/skills', severity: 'error' }]}
// Compare with the skills the project's installed plugin ships (what `pnpm exec iapl-skills` copies).
const installedSkills = join(ctx.root, 'node_modules/@intecion/ipal-kit/docs/agent/skills')
const source = ctx.exists('node_modules/@intecion/ipal-kit/docs/agent/skills') ? installedSkills : join(ctx.packageRoot, 'docs/agent/skills')
const plan = planSkills({ dest: join(ctx.root, dest), source })
@@ -76,7 +76,7 @@ export const agentRules: DoctorRule[] = [
plan.missing.length ? `missing ${plan.missing.join(', ')}` : '',
plan.retired.length ? `retired ${plan.retired.join(', ')}` : '',
].filter(Boolean)
return parts.length ? [{ file: dest, fix: 'pnpm exec ipal-skills and commit', message: `skills differ from the installed ipal-kit: ${parts.join('; ')}`, severity: 'warning' }] : []
return parts.length ? [{ file: dest, fix: 'pnpm exec iapl-skills and commit', message: `skills differ from the installed ipal-kit: ${parts.join('; ')}`, severity: 'warning' }] : []
},
docs: 'docs/agent/AGENT.md#14-skills-antigravity-claude-code-cursor',
group: 'agents',
+1 -1
View File
@@ -109,7 +109,7 @@ export const blockRules: DoctorRule[] = [
const iface = config.match(/\binterfaceName\s*:\s*['"](\w+)['"]/)?.[1]
if (!slug) {continue}
if ((librarySlugs.has(slug) || (iface && libraryInterfaces.has(iface))) && !overrides.has(slug)) {
out.push({ file, fix: 'use the library block (+ variant), or eject it (pnpm exec ipal-blocks eject) and pass it in createBlockRegistry({ components })', message: `project block "${slug}" duplicates a library block`, severity: 'warning' })
out.push({ file, fix: 'use the library block (+ variant), or eject it (pnpm exec iapl-blocks eject) and pass it in createBlockRegistry({ components })', message: `project block "${slug}" duplicates a library block`, severity: 'warning' })
}
}
return out
+10 -10
View File
@@ -16,7 +16,7 @@ export const envRules: DoctorRule[] = [
check: (ctx) => {
const out: RuleFinding[] = []
if (!ctx.domain) {
return [{ fix: 'add "domain": "<site domain>" to ipal-doctor.json', message: 'no site domain (ipal-doctor.json "domain", or a non-local NEXT_PUBLIC_SERVER_URL) — database names not checked', severity: 'warning' }]
return [{ fix: 'add "domain": "<site domain>" to iapl-doctor.json', message: 'no site domain (iapl-doctor.json "domain", or a non-local NEXT_PUBLIC_SERVER_URL) — database names not checked', severity: 'warning' }]
}
const { dev, prod } = databaseNamesFor(ctx.domain)
for (const [file, env] of [['.env', ctx.env.local], ['.env.example', ctx.env.example]] as const) {
@@ -51,17 +51,17 @@ export const envRules: DoctorRule[] = [
const file = ctx.exists(`${ctx.src}instrumentation.ts`) ? `${ctx.src}instrumentation.ts` : 'instrumentation.ts'
const code = stripComments(ctx.read(file))
if (!/assertEnv\s*\(/.test(code)) {
return [{ file, fix: "register(): assertEnv(ipalEnvRules({ storage: true, ipHeader: true })) from '@intecion/ipal-kit/env'", message: 'instrumentation.ts does not call assertEnv(ipalEnvRules(…))', severity: 'error' }]
return [{ file, fix: "register(): assertEnv(iaplEnvRules({ storage: true, ipHeader: true })) from '@intecion/ipal-kit/env'", message: 'instrumentation.ts does not call assertEnv(iaplEnvRules(…))', severity: 'error' }]
}
const out: RuleFinding[] = []
if (!/ipalEnvRules\s*\(/.test(code)) {out.push({ file, message: 'assertEnv without ipalEnvRules — the plugin variables are not checked', severity: 'warning' })}
if (!/iaplEnvRules\s*\(/.test(code)) {out.push({ file, message: 'assertEnv without iaplEnvRules — the plugin variables are not checked', severity: 'warning' })}
if (/from\s+['"]@intecion\/ipal-kit['"]/.test(code)) {out.push({ file, fix: "import from '@intecion/ipal-kit/env'", message: 'instrumentation.ts imports the package root (Edge build breaks)', severity: 'error' })}
const cfg = stripComments(ctx.read(configFile(ctx) ?? ''))
const flag = (name: string) => new RegExp(`\\b${name}\\s*:`).test(code)
if (/buildR2Storage/.test(cfg) && !flag('storage')) {out.push({ file, fix: 'ipalEnvRules({ storage: true })', message: 'R2 is wired but ipalEnvRules has no storage flag', severity: 'warning' })}
if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg) && !flag('cookieCrawl')) {out.push({ file, fix: 'ipalEnvRules({ cookieCrawl: true })', message: 'cookieScanner.crawl is on but ipalEnvRules has no cookieCrawl flag', severity: 'warning' })}
if (!flag('ipHeader')) {out.push({ file, fix: 'ipalEnvRules({ ipHeader: true })', message: 'ipalEnvRules has no ipHeader flag — rate limits trust no client-IP header', severity: 'warning' })}
if (!flag('databaseName')) {out.push({ file, fix: "ipalEnvRules({ databaseName: { domain: '<domain>' } })", message: 'ipalEnvRules has no databaseName check', severity: 'info' })}
if (/buildR2Storage/.test(cfg) && !flag('storage')) {out.push({ file, fix: 'iaplEnvRules({ storage: true })', message: 'R2 is wired but iaplEnvRules has no storage flag', severity: 'warning' })}
if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg) && !flag('cookieCrawl')) {out.push({ file, fix: 'iaplEnvRules({ cookieCrawl: true })', message: 'cookieScanner.crawl is on but iaplEnvRules has no cookieCrawl flag', severity: 'warning' })}
if (!flag('ipHeader')) {out.push({ file, fix: 'iaplEnvRules({ ipHeader: true })', message: 'iaplEnvRules has no ipHeader flag — rate limits trust no client-IP header', severity: 'warning' })}
if (!flag('databaseName')) {out.push({ file, fix: "iaplEnvRules({ databaseName: { domain: '<domain>' } })", message: 'iaplEnvRules has no databaseName check', severity: 'info' })}
return out
},
docs: 'docs/env.md',
@@ -74,15 +74,15 @@ export const envRules: DoctorRule[] = [
if (!ctx.env.example) {return [{ fix: 'add .env.example (names, placeholder values)', message: 'no .env.example', severity: 'error' }]}
const out: RuleFinding[] = []
const cfg = stripComments(ctx.read(configFile(ctx) ?? ''))
const want = ['DATABASE_URI', 'PAYLOAD_SECRET', 'NEXT_PUBLIC_SERVER_URL', 'IPAL_IP_HEADER']
const want = ['DATABASE_URI', 'PAYLOAD_SECRET', 'NEXT_PUBLIC_SERVER_URL', 'IAPL_IP_HEADER']
if (/buildR2Storage/.test(cfg) && !ctx.auditSkips.has('r2')) {want.push('R2_BUCKET', 'R2_ENDPOINT', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_PUBLIC_URL')}
if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg)) {want.push('IPAL_COOKIE_SCAN_URL', 'IPAL_COOKIE_SCAN_TOKEN')}
if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg)) {want.push('IAPL_COOKIE_SCAN_URL', 'IAPL_COOKIE_SCAN_TOKEN')}
const missing = want.filter((v) => !(v in ctx.env.example!))
if (missing.length) {out.push({ file: '.env.example', fix: 'add the names (empty or placeholder values)', message: `.env.example lacks ${missing.join(', ')}`, severity: 'warning' })}
// A real-looking credential in a committed file.
const creds = (ctx.env.example.DATABASE_URI ?? '').match(/^[a-z+]+:\/\/([^@/]+)@/i)?.[1]
if (creds && !PLACEHOLDER.test(creds)) {out.push({ file: '.env.example', fix: 'replace with USER:PASS', message: 'DATABASE_URI in .env.example carries credentials', severity: 'error' })}
for (const key of ['PAYLOAD_SECRET', 'R2_SECRET_ACCESS_KEY', 'GRAPH_CLIENT_SECRET', 'IPAL_DOCTOR_TOKEN']) {
for (const key of ['PAYLOAD_SECRET', 'R2_SECRET_ACCESS_KEY', 'GRAPH_CLIENT_SECRET', 'IAPL_DOCTOR_TOKEN']) {
const value = ctx.env.example[key]
if (value && value.length >= 16 && !PLACEHOLDER.test(value)) {out.push({ file: '.env.example', fix: `leave ${key} empty`, message: `${key} in .env.example has a value`, severity: 'error' })}
}
+7 -7
View File
@@ -49,7 +49,7 @@ const has = (ctx: DoctorContext, dir: string, names: string[]) => names.some((n)
/**
* The frontend folder, found by structure rather than by name (a route group's name never reaches the URL):
* `ipal-doctor.json` `layout.frontend` wins; else every `app/(<group>)` except `(payload)`, and `app` itself,
* `iapl-doctor.json` `layout.frontend` wins; else every `app/(<group>)` except `(payload)`, and `app` itself,
* holding the catch-all page — one with a `[locale]` page first. No match → `app/(frontend)` (the convention).
*/
export function findFrontend(ctx: DoctorContext): FrontendLayout {
@@ -67,7 +67,7 @@ export function findFrontend(ctx: DoctorContext): FrontendLayout {
return { ambiguous: best.filter((g) => g !== dir), dir, multi: localized.length > 0 }
}
/** Files AGENT.md §3 expects — each as its accepted names — with the `ipal-audit-skip` key that drops it. */
/** Files AGENT.md §3 expects — each as its accepted names — with the `iapl-audit-skip` key that drops it. */
function requiredFiles(ctx: DoctorContext, frontend: FrontendLayout): Array<[string[], string?]> {
const fe = frontend.multi ? `${frontend.dir}/[locale]` : frontend.dir
const ts = (base: string) => [`${base}.ts`, `${base}.tsx`]
@@ -114,14 +114,14 @@ export const layoutRules: DoctorRule[] = [
const frontend = findFrontend(ctx)
const out: RuleFinding[] = []
if (frontend.missingOverride) {
out.push({ file: 'ipal-doctor.json', fix: 'point layout.frontend at the folder that holds the pages, e.g. "src/app/(site)"', message: `layout.frontend "${frontend.missingOverride}" does not exist`, severity: 'error' })
out.push({ file: 'iapl-doctor.json', fix: 'point layout.frontend at the folder that holds the pages, e.g. "src/app/(site)"', message: `layout.frontend "${frontend.missingOverride}" does not exist`, severity: 'error' })
}
if (frontend.ambiguous.length) {
out.push({ fix: `set "layout": { "frontend": "${ctx.src}${frontend.dir}" } in ipal-doctor.json (or the other one)`, message: `several folders hold the site's pages: ${[frontend.dir, ...frontend.ambiguous].map((d) => `${ctx.src}${d}`).join(', ')} — checked ${ctx.src}${frontend.dir}`, severity: 'warning' })
out.push({ fix: `set "layout": { "frontend": "${ctx.src}${frontend.dir}" } in iapl-doctor.json (or the other one)`, message: `several folders hold the site's pages: ${[frontend.dir, ...frontend.ambiguous].map((d) => `${ctx.src}${d}`).join(', ')} — checked ${ctx.src}${frontend.dir}`, severity: 'warning' })
}
const missing = requiredFiles(ctx, frontend).filter(([names, key]) => !(key && ctx.auditSkips.has(key)) && !names.some((n) => ctx.exists(`${ctx.src}${n}`)))
if (missing.length) {
out.push({ fix: 'the ipal-setup skill (stage named by the file)', message: `missing: ${missing.map(([names]) => `${ctx.src}${names[0]}`).join(', ')}`, severity: 'error' })
out.push({ fix: 'the iapl-setup skill (stage named by the file)', message: `missing: ${missing.map(([names]) => `${ctx.src}${names[0]}`).join(', ')}`, severity: 'error' })
}
return out
},
@@ -149,7 +149,7 @@ export const layoutRules: DoctorRule[] = [
const allow = new Set([...(ctx.config.layout?.allow ?? []), ...DEFAULT_SRC_ALLOW])
const extra = ctx.list('src').filter((n) => !allow.has(n) && !n.startsWith('.'))
return extra.length
? [{ fix: 'move into the convention, or add to ipal-doctor.json "layout": { "allow": [...] }', message: `src/ entries outside the convention: ${extra.join(', ')}`, severity: 'info' }]
? [{ fix: 'move into the convention, or add to iapl-doctor.json "layout": { "allow": [...] }', message: `src/ entries outside the convention: ${extra.join(', ')}`, severity: 'info' }]
: []
},
docs: 'docs/agent/AGENT.md#3-project-structure-and-naming',
@@ -236,7 +236,7 @@ export const layoutRules: DoctorRule[] = [
if (ctx.deep?.importMapCurrent === false) {out.push({ file: ctx.importMap, fix: 'pnpm payload generate:importmap and commit', message: 'the committed import map differs from a freshly generated one', severity: 'error' })}
return out
},
docs: 'docs/agent/skills/ipal-reference/SKILL.md',
docs: 'docs/agent/skills/iapl-reference/SKILL.md',
group: 'layout',
source: 'static',
},
+8 -8
View File
@@ -19,7 +19,7 @@ export function createLiveFetcher(url: string, options: { adminRoute?: string; s
(async () => {
try {
const res = await fetch(base + path, {
headers: { 'user-agent': 'ipal-doctor (+https://intecion.com; read-only)' },
headers: { 'user-agent': 'iapl-doctor (+https://intecion.com; read-only)' },
redirect: init.redirect ?? 'follow',
signal: AbortSignal.timeout(20_000),
})
@@ -62,8 +62,8 @@ export const liveRules: DoctorRule[] = [
const home = await ctx.live!.fetch('/')
if (!home.status) {return []}
const isNoindex = noindex(home.text, home.headers.get('x-robots-tag'))
if (ctx.live!.staging) {return isNoindex ? [] : [{ fix: 'IPAL_NOINDEX=1 on the staging app', message: 'the staging site is indexable', severity: 'error' }]}
return isNoindex ? [{ fix: 'unset IPAL_NOINDEX on production and redeploy', message: 'the production home page is noindex', severity: 'error' }] : []
if (ctx.live!.staging) {return isNoindex ? [] : [{ fix: 'IAPL_NOINDEX=1 on the staging app', message: 'the staging site is indexable', severity: 'error' }]}
return isNoindex ? [{ fix: 'unset IAPL_NOINDEX on production and redeploy', message: 'the production home page is noindex', severity: 'error' }] : []
},
docs: 'docs/seo.md',
group: 'live',
@@ -72,9 +72,9 @@ export const liveRules: DoctorRule[] = [
{
id: 'live-seo',
check: async (ctx) => {
// ipal-seo-check of the doctor's own version: robots, sitemap, canonical, hreflang, noindex, JSON-LD, llms, MCP.
const script = join(ctx.packageRoot, 'docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs')
if (!existsSync(script)) {return [{ message: 'ipal-seo-check not found', severity: 'warning' }]}
// iapl-seo-check of the doctor's own version: robots, sitemap, canonical, hreflang, noindex, JSON-LD, llms, MCP.
const script = join(ctx.packageRoot, 'docs/agent/skills/iapl-seo-check/scripts/seo-check.mjs')
if (!existsSync(script)) {return [{ message: 'iapl-seo-check not found', severity: 'warning' }]}
const home = await ctx.live!.fetch('/', { redirect: 'manual' })
if (!home.status) {return []}
const res = run(process.execPath, [script, ctx.live!.url, '--max', '10'], ctx.root, 300_000)
@@ -84,10 +84,10 @@ export const liveRules: DoctorRule[] = [
const items = line.items.length ? `: ${line.items.slice(0, 3).join('; ')}${line.items.length > 3 ? ` … +${line.items.length - 3}` : ''}` : ''
out.push({ fix: line.rule, message: `${line.title}${items}`, rule: `live-seo:${titleSlug(line.title.replace(/[\d/]+/g, ' '))}`, severity: line.level })
}
if (res.code === 2) {out.push({ message: `ipal-seo-check: ${res.stderr.trim()}`, severity: 'error' })}
if (res.code === 2) {out.push({ message: `iapl-seo-check: ${res.stderr.trim()}`, severity: 'error' })}
return out
},
docs: 'docs/agent/skills/ipal-seo-check/SKILL.md',
docs: 'docs/agent/skills/iapl-seo-check/SKILL.md',
group: 'live',
source: 'live',
},
+7 -7
View File
@@ -104,9 +104,9 @@ export const securityRules: DoctorRule[] = [
const code = cfg(ctx)
const twoFactor = code.match(/twoFactor\s*:([^\n]*)/)?.[1] ?? ''
if (/\?\s*false\b|:\s*false\b|&&/.test(twoFactor) && /payloadTotp/.test(twoFactor)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor: { issuer, plugin: payloadTotp } without a switch', message: '2FA can be turned off at runtime (a condition on twoFactor)', severity: 'warning' })}
if (!/twoFactor\s*:[^\n]*payloadTotp|twoFactor\s*:\s*\{[\s\S]*?plugin\s*:\s*payloadTotp/.test(code)) {out.push({ file: configFile(ctx) ?? 'payload.config.ts', fix: "ipalKit({ twoFactor: { issuer: '<site>', plugin: payloadTotp } })", message: '2FA is not on (twoFactor with plugin: payloadTotp)', severity: 'error' })}
if (!/twoFactor\s*:[^\n]*payloadTotp|twoFactor\s*:\s*\{[\s\S]*?plugin\s*:\s*payloadTotp/.test(code)) {out.push({ file: configFile(ctx) ?? 'payload.config.ts', fix: "iapl({ twoFactor: { issuer: '<site>', plugin: payloadTotp } })", message: '2FA is not on (twoFactor with plugin: payloadTotp)', severity: 'error' })}
else if (!ctx.installed('@clocklimited/payload-2fa')) {out.push({ fix: 'pnpm add @clocklimited/payload-2fa', message: '@clocklimited/payload-2fa is not installed', severity: 'error' })}
if (/requireSetup\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'remove twoFactor.requireSetup: false (or record the reason in ipal-doctor.json)', message: 'twoFactor.requireSetup is off: an account that has not set 2FA up opens everything with its password alone', severity: 'warning' })}
if (/requireSetup\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'remove twoFactor.requireSetup: false (or record the reason in iapl-doctor.json)', message: 'twoFactor.requireSetup is off: an account that has not set 2FA up opens everything with its password alone', severity: 'warning' })}
if (/windowHours\s*:\s*(?:false|0)\b/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor.requireSetup.windowHours: 72 (the default)', message: 'no time limit for 2FA setup: an account that never sets it up can be taken over with its password at any time', severity: 'info' })}
// Postgres / SQLite: the 2FA collection has the column `totp_setup_from` (whenever 2FA is on). Without a
// migration that adds it, every query on the collection fails in production — nobody can log in.
@@ -146,12 +146,12 @@ export const securityRules: DoctorRule[] = [
id: 'access-missing',
check: (ctx) => {
const code = cfg(ctx)
if (!/ipalKit\s*\(/.test(code)) {return []}
if (!/iapl\s*\(/.test(code)) {return []}
// `access: { authCollection | defaultRole | … }`, an empty `access: {}`, or a variable whose name says so
const set = /\baccess\s*:\s*\{\}/.test(code.replace(/\s+/g, '')) || /\baccess\s*:\s*\{[^{}]*\b(?:authCollection|defaultRole|authAccess|firstUserAdmin|staffCollections|panelRole|selfRegistration|password)\b/.test(code) || /\baccess\s*:\s*\w*[aA]ccess\w*\s*[,}]/.test(code)
return set
? []
: [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "ipalKit({ access: { authCollection: 'users' } }) — roles admin > editor > user; or record the reason in ipal-doctor.json", message: 'ipalKit has no `access` option: there are no roles, so every account that can log in to the panel is an admin', severity: 'warning' }]
: [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "iapl({ access: { authCollection: 'users' } }) — roles admin > editor > user; or record the reason in iapl-doctor.json", message: 'iapl has no `access` option: there are no roles, so every account that can log in to the panel is an admin', severity: 'warning' }]
},
docs: 'docs/access.md',
group: 'security',
@@ -175,7 +175,7 @@ export const securityRules: DoctorRule[] = [
id: 'open-signup',
check: (ctx) =>
(ctx.deep?.openSignUp ?? []).map((slug) => ({
fix: `intended (a customer zone)? silence it with a reason in ipal-doctor.json; otherwise give "${slug}" a create rule`,
fix: `intended (a customer zone)? silence it with a reason in iapl-doctor.json; otherwise give "${slug}" a create rule`,
message: `sign-up is open on "${slug}": an anonymous request can create an account there`,
severity: 'info' as const,
})),
@@ -261,7 +261,7 @@ export const securityRules: DoctorRule[] = [
check: (ctx) => {
const code = cfg(ctx)
if (!/cookieScanner\s*:/.test(code) || /cookieScanner\s*:\s*false/.test(code)) {
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix: 'ipalKit({ cookieScanner: { crawl: true } }) + generate:importmap', message: 'the cookie scanner is off', severity: 'error' }]
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix: 'iapl({ cookieScanner: { crawl: true } }) + generate:importmap', message: 'the cookie scanner is off', severity: 'error' }]
}
const out: RuleFinding[] = []
if (!/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(code)) {out.push({ fix: 'cookieScanner: { crawl: true } (shared cookie-crawler service)', message: 'cookie scanner without crawl — no scheduled site check', severity: 'info' })}
@@ -277,7 +277,7 @@ export const securityRules: DoctorRule[] = [
check: async (ctx) => {
const out: RuleFinding[] = []
const code = cfg(ctx)
if (lt(ctx.pluginVersion, '1.14.5')) {out.push({ message: `admin link previews (adminMeta) need ipal-kit ≥ 1.14.5 (installed ${ctx.pluginVersion ?? 'none'})`, severity: 'warning' })}
if (lt(ctx.pluginVersion, '1.14.5')) {out.push({ message: `admin link previews (adminMeta) need IAPL ≥ 1.14.5 (installed ${ctx.pluginVersion ?? 'none'})`, severity: 'warning' })}
if (/adminMeta\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, message: 'adminMeta: false — the panel has no link preview and no noindex from the plugin', severity: 'warning' })}
if (/agency\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, message: 'agency: false — no technology credit', severity: 'warning' })}
if (ctx.live && !out.length) {
+4 -4
View File
@@ -32,20 +32,20 @@ export const seedRules: DoctorRule[] = [
for (const [name, command] of Object.entries(ctx.pkg.scripts ?? {})) {
if (!/seed/i.test(name)) {continue}
if (/fresh|reset/i.test(name)) {out.push({ file: 'package.json', fix: 'remove it — seeds never delete (seeding.md)', message: `script "${name}" re-creates content from scratch`, severity: 'error' })}
if (/IPAL_SEED_ALLOW_FULL=1/.test(command)) {out.push({ file: 'package.json', fix: 'set IPAL_SEED_ALLOW_FULL=1 by hand for one run, only with the owner\'s OK', message: `script "${name}" switches the full-seed guard off`, severity: 'error' })}
if (/IAPL_SEED_ALLOW_FULL=1/.test(command)) {out.push({ file: 'package.json', fix: 'set IAPL_SEED_ALLOW_FULL=1 by hand for one run, only with the owner\'s OK', message: `script "${name}" switches the full-seed guard off`, severity: 'error' })}
const entry = command.match(/(?:^|\s)([\w./@-]+\.[cm]?[jt]s)(?:\s|$)/)?.[1]?.replace(/^\.\//, '')
if (!entry) {continue}
if (!ctx.exists(entry)) {out.push({ file: 'package.json', message: `script "${name}" runs ${entry}, which does not exist`, severity: 'warning' }); continue}
const files = seedFiles(ctx, entry)
const code = files.map((f) => stripComments(ctx.read(f))).join('\n')
if (!/createSeeder\s*\(/.test(code)) {out.push({ file: entry, fix: "createSeeder(payload) from '@intecion/ipal-kit/seed' (only / SEED_ONLY, full-seed guard)", message: `script "${name}" does not use the ipal-kit seed helper`, severity: 'warning' })}
if (!/createSeeder\s*\(/.test(code)) {out.push({ file: entry, fix: "createSeeder(payload) from '@intecion/ipal-kit/seed' (only / SEED_ONLY, full-seed guard)", message: `script "${name}" does not use the IAPL seed helper`, severity: 'warning' })}
const deleting = files.filter((f) => DELETES.test(stripComments(ctx.read(f))))
if (deleting.length) {out.push({ file: deleting[0], fix: 'seeds never delete — an editor removes records in the panel (seeding.md)', message: `script "${name}" deletes records (${deleting.join(', ')})`, severity: 'error' })}
if (/guard\s*:\s*false|allowFull\s*:\s*true/.test(code)) {out.push({ file: entry, fix: 'keep the guard; IPAL_SEED_ALLOW_FULL=1 for one run with the owner\'s OK', message: `script "${name}" turns the full-seed guard off in code`, severity: 'error' })}
if (/guard\s*:\s*false|allowFull\s*:\s*true/.test(code)) {out.push({ file: entry, fix: 'keep the guard; IAPL_SEED_ALLOW_FULL=1 for one run with the owner\'s OK', message: `script "${name}" turns the full-seed guard off in code`, severity: 'error' })}
if (ctx.launched && /createSeeder\s*\(/.test(code) && !/\bonly\s*:/.test(code)) {out.push({ file: entry, fix: 'run it with SEED_ONLY="pages:<slug>,global:<slug>" or pass only: [...] (seeding.md → after launch)', message: `script "${name}" has no record list — after launch every run needs SEED_ONLY`, severity: 'warning' })}
}
for (const file of ['.env.example', '.env.production']) {
if (/^\s*IPAL_SEED_ALLOW_FULL\s*=\s*1/m.test(ctx.read(file))) {out.push({ file, message: `${file} sets IPAL_SEED_ALLOW_FULL=1`, severity: 'error' })}
if (/^\s*IAPL_SEED_ALLOW_FULL\s*=\s*1/m.test(ctx.read(file))) {out.push({ file, message: `${file} sets IAPL_SEED_ALLOW_FULL=1`, severity: 'error' })}
}
return out
},
+6 -6
View File
@@ -23,7 +23,7 @@ export function parseToolOutput(text: string): ToolLine[] {
}
/**
* ipal-audit titles that are a doctor rule of their own — the finding is reported under that id
* iapl-audit titles that are a doctor rule of their own — the finding is reported under that id
* (one place per check: the audit script). Everything else lands under `audit`.
*/
export const AUDIT_RULE_MAP: Array<[RegExp, string]> = [
@@ -37,7 +37,7 @@ export const AUDIT_RULE_MAP: Array<[RegExp, string]> = [
[/^middleware\.ts exists$/, 'layout-forbidden'],
[/^barrel index\.ts$/, 'naming'],
[/^hardcoded text in (blocks|components\/layout)$|^hardcoded Polish text in code$/, 'i18n-literals'],
[/^hex colors in (classes|inline styles)$|^design-token standard not wired$|^ipal-tokens --check$/, 'blocks-tokens'],
[/^hex colors in (classes|inline styles)$|^design-token standard not wired$|^iapl-tokens --check$/, 'blocks-tokens'],
[/^own block renderer switch$/, 'blocks-registry'],
]
@@ -52,11 +52,11 @@ export const toolingRules: DoctorRule[] = [
id: 'audit',
check: (ctx) => {
// The audit script of the doctor's own version (the project's copy in .agents may be stale).
const script = join(ctx.packageRoot, 'docs/agent/skills/ipal-audit/scripts/audit.sh')
if (!existsSync(script)) {return [{ message: `ipal-audit not found (${script})`, severity: 'warning' }]}
const script = join(ctx.packageRoot, 'docs/agent/skills/iapl-audit/scripts/audit.sh')
if (!existsSync(script)) {return [{ message: `iapl-audit not found (${script})`, severity: 'warning' }]}
if (!ctx.src) {return []}
const res = run('bash', [script, '--quick'], ctx.root, 300_000)
if (res.code !== 0 && res.code !== 1) {return [{ message: `ipal-audit --quick could not run (exit ${res.code}): ${res.stderr.trim().split('\n')[0] ?? ''}`, severity: 'warning' }]}
if (res.code !== 0 && res.code !== 1) {return [{ message: `iapl-audit --quick could not run (exit ${res.code}): ${res.stderr.trim().split('\n')[0] ?? ''}`, severity: 'warning' }]}
const out: RuleFinding[] = []
for (const line of parseToolOutput(res.stdout)) {
const mapped = AUDIT_RULE_MAP.find(([re]) => re.test(line.title))?.[1]
@@ -76,7 +76,7 @@ export const toolingRules: DoctorRule[] = [
}
return out
},
docs: 'docs/agent/skills/ipal-audit/SKILL.md',
docs: 'docs/agent/skills/iapl-audit/SKILL.md',
group: 'audit',
source: 'static',
},
+3 -3
View File
@@ -43,7 +43,7 @@ export const versionRules: DoctorRule[] = [
}
return []
},
docs: 'docs/agent/skills/ipal-upgrade/SKILL.md',
docs: 'docs/agent/skills/iapl-upgrade/SKILL.md',
group: 'versions',
source: 'static',
},
@@ -145,12 +145,12 @@ export const versionRules: DoctorRule[] = [
const [a, b] = [parseVersion(ctx.pluginVersion)!, parseVersion(latest)!]
const minorsBehind = a[0] < b[0] ? 99 : b[1] - a[1]
return [{
fix: `pnpm add ${PKG}@${latest} — then the ipal-upgrade skill`,
fix: `pnpm add ${PKG}@${latest} — then the iapl-upgrade skill`,
message: `${PKG} ${ctx.pluginVersion} installed, ${latest} is out`,
severity: minorsBehind >= 2 ? 'error' : 'warning',
}]
},
docs: 'docs/agent/skills/ipal-upgrade/SKILL.md',
docs: 'docs/agent/skills/iapl-upgrade/SKILL.md',
group: 'versions',
source: 'registry',
},
+15 -15
View File
@@ -39,7 +39,7 @@ export const doctorRules: DoctorRule[] = [
...deepRules,
]
/** `ipal-audit-skip` keys (AGENTS.md) → doctor rules they silence (the audit script honours the rest itself). */
/** `iapl-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'],
@@ -60,14 +60,14 @@ export type RunDoctorOptions = {
/** 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). */
/** Extra rules (a project's own, `extraRules` in iapl-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. */
/** Live site; with IAPL_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. */
/** Store first-seen dates (CSP report-only) in iapl-doctor.json. Default: only outside CI. */
writeSeen?: boolean
}
@@ -76,10 +76,10 @@ 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 '))
const line = res.stdout.split('\n').find((l) => l.startsWith('IAPL_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
return JSON.parse(line.slice('IAPL_DOCTOR_STATUS '.length)) as DoctorStatus
} catch {
return { error: 'payload run printed an unreadable status' }
}
@@ -105,19 +105,19 @@ export function globToRegExp(glob: string): RegExp {
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. */
/** Applies iapl-doctor.json `rules` and `iapl-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' })}
if (!s.reason?.trim()) {out.push({ fix: 'add "reason": "<why>" — an entry without one is ignored', message: `iapl-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: `iapl-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: `iapl-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 id of AUDIT_SKIP_RULES[key] ?? []) {skips.set(id, reason || `iapl-audit-skip: ${key}`)}
}
for (const f of findings) {
const s = settings[f.rule] ?? settings[f.rule.split(':')[0]]
@@ -152,8 +152,8 @@ export async function runDoctor(options: RunDoctorOptions): Promise<DoctorReport
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()
// Deep status: the probe (--deep), the endpoint (--url + IAPL_DOCTOR_TOKEN), or none.
const token = process.env.IAPL_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)}
@@ -182,9 +182,9 @@ export async function runDoctor(options: RunDoctorOptions): Promise<DoctorReport
// 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'))) {
if (writeSeen && findings.some((f) => f.rule === 'csp' && /report-only/.test(f.message)) && !ctx.config.seen?.['csp-report-only'] && existsSync(join(root, 'iapl-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`)
writeFileSync(join(root, 'iapl-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])
+6 -6
View File
@@ -21,7 +21,7 @@ export function pluginVersion(): string {
type CollectionLike = { fields?: Array<{ name?: string }>; slug: string }
/**
* Read-only counts for ipal-doctor's deep rules: users without TOTP, cookies waiting for approval,
* Read-only counts for iapl-doctor's deep rules: users without TOTP, cookies waiting for approval,
* the versions. Counts and booleans only — never names, e-mails or values.
*/
export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorStatus> {
@@ -82,7 +82,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
export type DoctorEndpointOptions = {
/** Who may read the status besides a valid token, e.g. `({ req }) => isAdmin(req.user, req.payload)` (a staff admin; the second factor is checked for you). */
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
/** Env variable that holds the token (≥ 32 characters). Default IPAL_DOCTOR_TOKEN. */
/** Env variable that holds the token (≥ 32 characters). Default IAPL_DOCTOR_TOKEN. */
tokenVar?: string
}
@@ -93,17 +93,17 @@ const sameToken = (given: string, expected: string) => {
}
/**
* GET /api/ipal/doctor — the deep status for `ipal-doctor --url`. Off (404) until the token variable
* GET /api/ipal/doctor — the deep status for `iapl-doctor --url`. Off (404) until the token variable
* holds at least 32 characters; then `Authorization: Bearer <token>` (or `access`) is required.
* Rate-limited per client IP. `ipalKit({ doctor: false })` removes the endpoint.
* Rate-limited per client IP. `iapl({ doctor: false })` removes the endpoint.
*/
export function buildDoctorEndpoint(options: DoctorEndpointOptions = {}): Endpoint {
const tokenVar = options.tokenVar ?? 'IPAL_DOCTOR_TOKEN'
const tokenVar = options.tokenVar ?? 'IAPL_DOCTOR_TOKEN'
return {
handler: async (req: PayloadRequest) => {
const token = process.env[tokenVar]?.trim() ?? ''
if (token.length < 32) {return Response.json({ error: 'Not found' }, { status: 404 })}
const limit = await consumeRateLimit({ key: clientIp(req.headers), max: 10, scope: 'ipal-doctor', windowMs: 60_000 })
const limit = await consumeRateLimit({ key: clientIp(req.headers), max: 10, scope: 'iapl-doctor', windowMs: 60_000 })
if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests' })}
const given = (req.headers.get('authorization') ?? '').replace(/^Bearer\s+/i, '').trim()
const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && (await options.access({ req })) : false)
+3 -3
View File
@@ -12,7 +12,7 @@ export type DoctorFinding = {
file?: string
fix?: string
message: string
/** Why the project silenced it (from ipal-doctor.json or an `ipal-audit-skip` line). */
/** Why the project silenced it (from iapl-doctor.json or an `iapl-audit-skip` line). */
reason?: string
rule: string
severity: DoctorSeverity
@@ -23,7 +23,7 @@ export type DoctorFinding = {
/** What a rule returns — the runner adds rule, source and docs. */
export type RuleFinding = { rule?: string } & Omit<DoctorFinding, 'reason' | 'rule' | 'silenced' | 'source'>
/** One silencing / override entry in ipal-doctor.json. */
/** One silencing / override entry in iapl-doctor.json. */
export type DoctorRuleSetting = {
/** Only findings in these files (globs: `*` within a folder, `**` across folders), e.g. an approved exception. */
files?: string[]
@@ -34,7 +34,7 @@ export type DoctorRuleSetting = {
until?: string
}
/** ipal-doctor.json in the project root. Every key is optional. */
/** iapl-doctor.json in the project root. Every key is optional. */
export type DoctorConfig = {
/** The site's production domain (dots allowed) — the base of the database names. */
domain?: string