Files
ipal-kit/docs/doctor.md
T
Radosław SmolińskiandClaude Fable 5.2 75a6f5209e 2FA setup required: review fixes (SR-1 to SR-9)
SR-1: /api/ipal/admin-icon sends the upload security headers (sandbox policy,
nosniff) with the bytes: an SVG is shown, never run. fetchPublicImage stops
reading at the size limit.
SR-2: requireSetup.exempt exempts only on exactly true; an async function, and a
windowHours that is not a number or false, stop the start.
SR-3: on Postgres / SQLite the missing column makes every login fail: the log
says so, the docs call the migration a required step of the same deploy, and
ipal-doctor reports a SQL project without it.
SR-4: an admin's reset also ends the account's sessions.
SR-5: the reset needs a session that entered its own TOTP code by default.
SR-6: the doctor's import-map rule covers TwoFactorStatusField and TwoFactorAlert.
SR-7: building blocks exported; dashboard notice, status field, setup notice and
the server-side image fetch can be switched off one by one.
SR-8: totpSetupFrom is on the 2FA collection whenever 2FA is on.
SR-9: both ways out of "every administrator is blocked" in security.md.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 19:32:34 +01:00

228 lines
18 KiB
Markdown
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.
# ipal-doctor — one check for the whole site
`ipal-doctor` checks a site against the team's rules and lists every gap with a fix hint and a doc link. It covers
what drifts between sites: versions, Node, the folder layout, database names, env rules, security headers, 2FA, the
cookie scanner, the admin preview, the agent guide, seeds, the block library, and the running site.
Related: [AGENT.md §11](./agent/AGENT.md), the `ipal-doctor` skill, [deployment.md](./deployment.md),
[seeding.md](./seeding.md), [security.md](./security.md), [blocks.md](./blocks.md).
## Run it
```bash
pnpm exec ipal-doctor # this project, human-readable
pnpm exec ipal-doctor --strict --offline # CI on a new site: any finding fails
pnpm exec ipal-doctor --deep --url http://localhost:3000 # + database (read-only) and the running site
pnpm exec ipal-doctor --json > doctor.json # machine-readable
pnpm dlx --package=@intecion/ipal-kit@latest ipal-doctor # the newest rules, before an upgrade
```
`ipal-doctor` is a bin of the package (`bin/ipal-doctor.mjs`), like `ipal-skills`. `pnpm exec` uses the rules of
the version the site has installed — reproducible in CI. The report header names both: the rules version and the
site's ipal-kit.
| Option | What it does |
|---|---|
| `[dir]` | the project folder (default: the current one) |
| `--json` | the report as JSON (schema 1, below) |
| `--md` | a Markdown table |
| `--strict` | any finding that is not silenced fails (= `--fail-on info`) |
| `--fail-on error\|warning\|info` | the lowest severity that fails (default `error`) |
| `--offline` | skips the two rules that need the registry: `plugin-latest` (`pnpm view`) and `deps-audit` (`pnpm audit --prod`) |
| `--url <url>` | also checks the running site: headers, X-Powered-By, CSP, `/api/health`, admin noindex and link preview, production noindex, and `ipal-seo-check` (robots, sitemap, canonical, hreflang, JSON-LD, llms, MCP) |
| `--staging` | with `--url`: the site is a staging copy, so it must be noindex |
| `--admin-route <path>` | with `--url`: the panel path (default `/admin`) |
| `--deep` | read-only database checks through `pnpm exec payload run` (below) |
| `--env-file <file>` | a production env export (e.g. copied from Coolify): its `DATABASE_URI` must name `<domain>_prod` |
| `--only <ids,groups>`, `--skip <ids,groups>` | run or leave out rules or whole groups |
| `--sites <glob>` | many projects at once, e.g. `'../*-web'`: a rule × site table (always exit 0 — a report, never a gate) |
**Exit codes:** `0` nothing at or above `--fail-on` · `1` findings at or above it · `2` the doctor could not run (not
a project root, a broken `ipal-doctor.json`, a bad option) · `3` a rule crashed (the others still report).
**Severities:** `error` breaks a team rule or is a security or data risk; `warning` is drift to fix; `info` is
worth knowing. Without `--strict`, only errors fail.
## Static, live, deep
- **Static** (default): reads files only — `package.json`, the installed versions in `node_modules`, the config
files, `.env` / `.env.example` (only variable names and the database name ever reach the report, never values),
the import map, `AGENTS.md`, the skills folder. It also runs `ipal-audit --quick` from the installed package. No
build, no database, no server. It writes nothing, except one date in `ipal-doctor.json` (below) outside CI.
- **Live** (`--url`): GET requests only, no login, a doctor user agent, each path once per run. `localhost` is exempt
from the HSTS check (plain http).
- **Deep** (`--deep`): `pnpm exec payload run node_modules/@intecion/ipal-kit/dist/modules/doctor/probe.js` in the
project, with the project's `DATABASE_URI` and `PAYLOAD_SECRET`. Read-only counts: panel users without TOTP, cookies
waiting for approval; the project's own env rules (`register()` from `instrumentation.ts`); the committed import map
against a freshly generated one (written to a temporary file next to it and removed). Run it locally against the dev
database, or in the Coolify app container's terminal against the MongoDB container.
- **Deep through the site**: with `--url` (and no `--deep`), when `IPAL_DOCTOR_TOKEN` is set in the doctor's
environment, the doctor reads the same counts from `GET /api/ipal/doctor` of the running site.
### The status endpoint — `GET /api/ipal/doctor`
Added by `ipalKit` and **off until the site has `IPAL_DOCTOR_TOKEN`** (at least 32 characters): before that it answers
404. With the token set it needs `Authorization: Bearer <token>`, is rate-limited (10 a minute per client IP) and
returns counts only — never names, e-mails or values:
```json
{ "node": "v22.20.0", "pendingCookies": 0, "plugin": "1.15.0", "usersSetupClosed": 0, "usersWithout2fa": 0 }
```
Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'MY_TOKEN', access: ({ req }) => isAdmin(req.user, req.payload) } })` (a logged-in staff admin may read it too; the second factor is checked for you — never test `req.user.roles` by hand, an account of another collection can carry the same value)
(`access` lets a logged-in admin read it without the token). Building blocks: `buildDoctorEndpoint`,
`collectDoctorStatus` from `@intecion/ipal-kit/doctor`.
## The rules
| Group | Rule | Severity | Checks |
|---|---|---|---|
| versions | `plugin-installed` | error | `node_modules` has `@intecion/ipal-kit` and it satisfies `package.json` |
| | `plugin-latest` | warning; error two or more minors behind | the installed plugin is the newest on the team registry (registry) |
| | `next-min` | error | `next` ≥ 16.4.5 (below 16.4.1: RCE/DoS advisories; 16.3.0–16.4.4: GHSA-mfr8-8qww-v76h); `eslint-config-next` on the same minor (warning) |
| | `sharp-min` | error | `sharp` ≥ 0.35.5 |
| | `transitive-min` | error (`mongoose`), warning (`happy-dom`) | packages Payload pins below a security fix, in any depth of the tree (read from `pnpm-lock.yaml`, else `node_modules/.pnpm`): `mongoose` 8.x ≥ 8.24.7 (GHSA-pcrw-h46h-c93h and four more; Payload 3.90–3.93 pin 8.24.1, 3.94.0+ ship 8.24.7 — the fix it prints names the Payload upgrade first), `happy-dom` ≥ 21.0.4 (GHSA-c8p4-j97h-3vg8, GHSA-834v-8h66-3h79). The fix it prints is the `pnpm.overrides` line from AGENT.md §4 item 12 |
| | `node-22` | warning | `engines.node` only 22 (`">=22 <23"`), `.nvmrc` / `.node-version` = 22; with `--deep`, the running Node |
| | `pnpm-pinned` | info | `packageManager` is set |
| | `deps-audit` | error on critical/high, info on moderate/low | `pnpm audit --prod` (registry) |
| layout | `layout-required` | error | the AGENT.md §3 files (proxy, i18n config, instrumentation, `lib/content`, every route, the frontend files — `layout`, `actions`, `not-found`, `notFoundView` (`.ts` or `.tsx`), the catch-all page — in the route group found by structure: any `app/(<group>)` (or `app` itself) holding `[locale]/[[...slug]]/page.tsx` or `[[...slug]]/page.tsx`, a localized one first, `(frontend)` on a tie (two matches → a warning naming both); `layout.frontend` sets it, `blocks/registry.ts`, `collections/{Pages,Media}.ts`, `components/layout`, `components/forms/formClasses.ts`); an `ipal-audit-skip` key (`llms`, `llms-full`, `markdown`, `mcp`, `indexnow`) drops its file |
| | `layout-forbidden` | error | no `middleware.ts`, no `lib/{pages,locales,navigation}.ts`, `fields/{link,sectionHeader,sectionSettings}.ts` |
| | `layout-extra` | info | `src/` entries outside the allow list (AGENT.md §3 + `seed/`, `design/`, `db.ts`, `env.rules.ts`, `content.config.ts`; extend with `layout.allow`) |
| | `naming` | warning | block folders, collection and global files PascalCase, `scripts/*` kebab-case, no `index.ts` barrels |
| | `importmap` | error | the import map exists, holds the entries for what the config turns on (2FA incl. `SafeTotpView`, `TwoFactorStatusField`, `TwoFactorAlert`; R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one. Warning: the config uses the 2FA package's own setup / verify view as a view's `Component` (outside the `back` link check — security.md); not for that path as `ipalTotpView` of `SafeTotpView` or in `admin.dependencies` |
| | `tsconfig-skills` | error | `tsconfig.json` excludes the skills folder |
| env | `db-name` | error | `DATABASE_URI` in `.env` and `.env.example` names `<domain without dots>_dev`; a local `.env` on `_prod` is an error; `--env-file` checks `_prod` (`databaseNamesFor`) |
| | `env-rules` | error / warning | `instrumentation.ts` calls `assertEnv(ipalEnvRules(…))` from `/env`, with `storage` (R2), `cookieCrawl` (crawl), `ipHeader`; `databaseName` suggested (info) |
| | `env-example` | warning / error | `.env.example` lists the variables those rules name; no credentials or secret values in it |
| | `env-live` | error | (deep) the project's env rules pass in the real environment |
| security | `security-headers` | error | `buildSecurityHeaders`; live: HSTS, nosniff, Referrer-Policy, Permissions-Policy, frame protection |
| | `powered-by` | error | `withSecurityConfig`; live: no `X-Powered-By` on `/` and the admin |
| | `csp` | warning / info | CSP on the site and the admin; report-only is info, a warning after 4 weeks (`seen`) |
| | `2fa` | error | `twoFactor: { plugin: payloadTotp }` + the package; deep: 0 users without TOTP (the message says how many of them are blocked because their setup window has passed); error: a Postgres / SQLite project whose migrations do not mention the 2FA column `totp_setup_from` (every login would answer 500; a warning when there is no migrations folder — the doctor cannot see a schema that gets there another way); warning: `twoFactor.requireSetup: false`; info: no setup window (`windowHours: false`) |
| | `cookie-scanner` | error / warning / info | `cookieScanner` on (with `crawl`, else info); deep: nothing waits for approval (warning) |
| admin | `admin-meta` | warning | ipal-kit ≥ 1.14.5, no `adminMeta: false` / `agency: false`; live: the admin `og:image` is `/api/ipal/admin-og` |
| | `admin-noindex` | error | (live) the admin login page is noindex |
| agents | `agents-md` | error / warning | `AGENTS.md` with a non-empty `## Project decisions`, the `ipal-kit:start…end` pointer for the installed version, `CLAUDE.md` with `@AGENTS.md` |
| | `skills-current` | warning | `.agents/skills/ipal-*` equal the installed plugin's (`planSkills`, what `ipal-skills` would change) |
| seeds | `seed-named` | error / warning | every `seed*` script uses `createSeeder` (`only` / `SEED_ONLY`, the full-seed guard), deletes nothing, has no `fresh`/`reset` script, does not switch the guard off (`guard: false`, `allowFull: true`, `IPAL_SEED_ALLOW_FULL=1` in a script or committed env file); after launch a seed without an `only` list is a warning |
| blocks | `blocks-registry` | error | `blocks/registry.ts` uses `createBlockRegistry` or `RenderBlocks` (no `switch (blockType)`) |
| | `blocks-ui-required` | error | without `createBlockRegistry`, `components/ui/` has Section, SectionHeader, Media, CMSLink, Button |
| | `blocks-ui-override` | warning | a `components/ui/` file named like a library primitive is passed through `createBlockRegistry({ ui })` |
| | `blocks-duplicate` | warning | a project block whose `slug` (or `interfaceName`) matches a library block — also a slug renamed through the block's `slug` option — unless it is an override in `createBlockRegistry({ components })` |
| | `blocks-helper-copy` | warning | no local copy of a plugin field builder (`blockLibraryManifest.fieldBuilders`), `ctaHref`, `buildActionButtonsField` |
| | `blocks-tokens` | error / warning | from `ipal-audit`: hex colours, the token standard not wired, `ipal-tokens --check` |
| audit | `i18n-literals` | error / warning | from `ipal-audit`: hardcoded text in blocks (error) and components (warning), Polish literals in code (not the panel's `adminText()` / `{ en, pl }` labels in a schema file — the `ipal-audit` skill) |
| | `audit:<title>` | as reported | every other `ipal-audit --quick` finding, one per file |
| live | `live-reachable`, `live-health`, `live-noindex`, `live-seo` | error / warning | the URL answers; `/api/health` 200; production not noindex (staging must be); every `ipal-seo-check` error and warning |
| deep | `deep-status` | error | the deep check could not finish |
| — | `doctor-config` | error / warning | `ipal-doctor.json` problems: invalid JSON, an entry without a reason, an expired `until` |
| — | `doctor-crash` | error (exit 3) | a rule threw |
The block rules read `blockLibraryManifest` (`@intecion/ipal-kit/blocks`), so a new library block needs no doctor
change.
## Adapt it — `ipal-doctor.json`
Every rule can be silenced, lowered or raised — **with a reason** — in `ipal-doctor.json` in the project root:
```json
{
"domain": "example-studio.pl",
"launched": false,
"layout": { "allow": ["scripts"], "frontend": "src/app/(site)" },
"rules": {
"csp": { "off": true, "reason": "new site: report-only until the reports are clean", "until": "2026-12-01" },
"i18n-literals": { "off": true, "files": ["src/components/design/**"], "reason": "approved exception: the styleguide labels" },
"node-22": { "severity": "error", "reason": "we pin Node strictly" }
},
"seen": { "csp-report-only": "2026-10-29" },
"extraRules": ["./scripts/doctor-rules.mjs"]
}
```
| Key | Meaning |
|---|---|
| `domain` | the production domain (dots allowed) — the base of the database names. Without it: a non-local `NEXT_PUBLIC_SERVER_URL`, else the folder name minus `-web` |
| `launched` | the site is live: seeds must then name their records. Also true when "Project decisions" has a line with "launch" and a date |
| `layout.allow` | more top-level `src/` entries the convention allows |
| `layout.frontend` | the folder that holds the site's pages, e.g. `src/app/(site)` — only for a layout the doctor cannot tell (two route groups with pages); the route group's name is otherwise free |
| `rules.<id>` | `off` (silence), `severity` (`error` / `warning` / `info`), `reason` (**required** — an entry without one is ignored and reported), `until` (ISO date; after it the entry stops applying and the report says so), `files` (globs: only findings in those files). The id is the rule (`csp`) or an audit finding (`audit:collections-present`); `audit` covers all audit findings |
| `seen` | first-seen dates the doctor stores itself (`csp-report-only`, for the 4-week CSP rule). It writes this key only outside CI (`CI` unset), not with `--json`, and only when the file exists |
| `extraRules` | your own rule modules (paths relative to the project), each exporting `rules: DoctorRule[]` |
Silenced findings stay in the report: in JSON with `"silenced": true` and the reason, in the human output under
"Silenced", in the summary count. `--strict` does not fail on them.
`ipal-audit-skip: <keys> — <reason>` lines in `AGENTS.md` (a client decision, AGENT.md §0b) count too: the audit honours
its keys, and the doctor maps `twofactor` → `2fa`, `csp` → `csp`, and drops the files of `llms`, `llms-full`, `markdown`,
`mcp`, `indexnow` from `layout-required`.
## JSON (schema 1)
```json
{
"schema": 1,
"rulesVersion": "1.15.0",
"site": { "path": "/…/examplepl-web", "domain": "example.pl", "plugin": "1.15.0" },
"findings": [
{ "rule": "db-name", "severity": "error", "source": "static", "message": "…", "file": ".env", "fix": "…", "docs": "docs/deployment.md" }
],
"skipped": ["plugin-latest", "deps-audit", "live-health"],
"summary": { "error": 1, "warning": 0, "info": 0, "silenced": 0 }
}
```
`source` is `static`, `registry`, `live` or `deep`; `skipped` lists rules that did not run (offline, no `--url`, no
`--deep`); `reason` and `silenced` appear on silenced findings. With `--sites --json` the output is an array of reports.
## In CI
New sites only (the starter's and the reference site) gate on the doctor; existing client sites are not changed for it.
```yaml
- run: pnpm install --frozen-lockfile
- run: pnpm exec ipal-doctor --strict --offline # static, right after install
# … build, start the app on :3000 with the CI database …
- run: pnpm exec ipal-doctor --strict --offline --deep --url http://localhost:3000
```
The plugin's own CI does the same for `reference/` (`.gitea/workflows/ci.yml`).
## Building blocks — `@intecion/ipal-kit/doctor`
Node only. For a project that wraps, filters or extends the checks:
```ts
import { doctorRules, formatReport, runDoctor } from '@intecion/ipal-kit/doctor'
const report = await runDoctor({ root: process.cwd(), packageRoot: 'node_modules/@intecion/ipal-kit', offline: true })
console.log(formatReport(report))
```
`runDoctor`, `runDoctorCli`, `doctorRules`, `applySettings`, `runDeepProbe`, `createDoctorContext`, `loadDoctorConfig`,
`formatReport`, `formatDriftTable`, `planSkills`, `parseToolOutput`, `AUDIT_RULE_MAP`, `AUDIT_SKIP_RULES`,
`DEFAULT_SRC_ALLOW`, `findFrontend`, `createLiveFetcher`, `buildDoctorEndpoint`, `collectDoctorStatus`, `globToRegExp`, `parseEnvFile`,
`readAuditSkips`, `bareHost`, `expandSites`, `parseDoctorArgs`, `DOCTOR_USAGE`; types `DoctorRule`, `DoctorFinding`,
`DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`, `DoctorSource`, `DoctorStatus`, `DoctorContext`,
`RuleFinding`, `RunDoctorOptions`, `DoctorEndpointOptions`, `FrontendLayout`.
## Environment variables
| Variable | Where | Effect |
|---|---|---|
| `IPAL_DOCTOR_TOKEN` | the site (Coolify), ≥ 32 characters | turns `GET /api/ipal/doctor` on; in the doctor's environment, `--url` uses it to read the deep counts |
| `CI` | the doctor's environment | set → the doctor never writes `seen` into `ipal-doctor.json` |
| `NO_COLOR` | the doctor's environment | no colours in the human report |
| `PAYLOAD_CONFIG_PATH` | the project | `--deep` loads this config instead of `src/payload.config.ts` |
| `IPAL_DOCTOR_IMPORT_MAP` | internal | set by the doctor for the probe: the committed import map to compare |
## Relation to the other checks
| Tool | When |
|---|---|
| `ipal-audit` | inside the edit loop: is the code I just wrote built the ipal-kit way (+ tsc and build without `--quick`) |
| `ipal-seo-check` | what crawlers see on a running site |
| `ipal-consent-check` | tracking waits for consent (a real browser) — not run by the doctor |
| `ipal-skills` | copies the skills; the doctor's `skills-current` uses the same comparison (`planSkills`) |
| **`ipal-doctor`** | the whole site against the team standard: runs `ipal-audit --quick` and (with `--url`) `ipal-seo-check` from the installed package and adds everything they do not check |