diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index ccf49bb..e3a51a7 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -51,8 +51,8 @@ jobs: - run: pnpm --dir reference generate:importmap && git diff --exit-code reference/src/app - run: pnpm --dir reference generate:types && git diff --exit-code reference/src/payload-types.ts - run: pnpm --dir reference typecheck - # Doctor (static) — turn on when ipal-doctor ships (docs/dev/ipal-doctor-proposal.md): - # - run: node bin/ipal-doctor.mjs reference --strict --offline --json > doctor-static.json + # ipal-doctor (static, docs/doctor.md): the reference site is the zero-findings example — any unsilenced finding fails + - run: node bin/ipal-doctor.mjs reference --strict --offline # Full run on main (and before a release): MongoDB, seed, production build, smoke tests. reference-full: @@ -69,6 +69,9 @@ jobs: PAYLOAD_SECRET: ci-reference-secret-0123456789abcdef NEXT_PUBLIC_SERVER_URL: http://localhost:3100 IPAL_IP_HEADER: x-forwarded-for + # cookieScanner.crawl → ipalEnvRules({ cookieCrawl }) requires both in production; CI never starts a crawl + IPAL_COOKIE_SCAN_URL: http://127.0.0.1:9/crawl + IPAL_COOKIE_SCAN_TOKEN: ci-cookie-scan-token-0123456789 NEXT_PUBLIC_TURNSTILE_SITE_KEY: 1x00000000000000000000AA TURNSTILE_SECRET_KEY: 1x0000000000000000000000000000000AA ALLOW_LOCAL_MEDIA: '1' @@ -95,5 +98,8 @@ jobs: - run: pnpm --dir reference build - run: pnpm --dir reference exec playwright install --with-deps chromium - run: pnpm --dir reference test:e2e - # Doctor (deep + HTTP) — turn on when ipal-doctor ships: - # - run: node bin/ipal-doctor.mjs reference --strict --offline --deep --url http://localhost:3100 + # ipal-doctor (deep + HTTP): read-only database counts, the import map, the env rules, and the running site + - run: | + PORT=3100 pnpm --dir reference start & + for i in $(seq 1 60); do curl -sf http://localhost:3100/api/health >/dev/null && break; sleep 2; done + node bin/ipal-doctor.mjs reference --strict --offline --deep --url http://localhost:3100 diff --git a/bin/ipal-doctor.mjs b/bin/ipal-doctor.mjs new file mode 100755 index 0000000..80a19bc --- /dev/null +++ b/bin/ipal-doctor.mjs @@ -0,0 +1,17 @@ +#!/usr/bin/env node +// ipal-doctor — checks a site against the ipal-kit team rules and lists every gap with a fix hint +// (docs/doctor.md). Static by default: reads files, writes nothing (except a first-seen date in +// ipal-doctor.json outside CI). +// 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 +// pnpm exec ipal-doctor --json > doctor.json +// pnpm dlx --package=@intecion/ipal-kit@latest ipal-doctor → the newest rules +// Exit: 0 ok · 1 findings · 2 could not run · 3 a rule crashed. + +import { dirname, join } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' + +const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..') +const { runDoctorCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'doctor', 'cli.js')).href) +process.exit(await runDoctorCli(process.argv.slice(2), { packageRoot: pkgRoot })) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 52a3584..c8e6c23 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -14,6 +14,17 @@ Database names follow one rule, and seeding a live site touches only the records fifteen ready page sections and ten page templates. ### New +- **`ipal-doctor`** ([doctor.md](./doctor.md)): one command, run in a site, that checks it against the team rules and + lists every gap with a fix hint — plugin/Next/sharp/Node versions, the AGENT.md §3 layout and naming, database names, + env rules, security headers, X-Powered-By, CSP, 2FA, the cookie scanner, adminMeta, AGENTS.md "Project decisions", + current skills, seeds (`createSeeder`, no deletes, guard on), the block library (`blockLibraryManifest`), `pnpm audit + --prod`, hardcoded texts (it runs `ipal-audit --quick`). `--url` checks the running site (and runs `ipal-seo-check`), + `--deep` reads the database read-only through `payload run`. Human or `--json` output, `--strict`, exit codes 0/1/2/3, + `--sites '../*-web'` for a read-only drift table. `ipal-doctor.json` silences, lowers or raises a rule with a reason + (`until`, `files`). New bin `ipal-doctor`, new entry `@intecion/ipal-kit/doctor`, new skill **ipal-doctor**. +- **`GET /api/ipal/doctor`**: read-only counts for the doctor (users without TOTP, cookies waiting for approval, + versions). 404 until `IPAL_DOCTOR_TOKEN` (≥ 32 characters) is set; Bearer token, rate-limited. `ipalKit({ doctor: false })` + removes it. - **Design-token standard** ([design-tokens.md](./design-tokens.md)): one set of `--ipal-*` names for every site, only the values differ per brand. `@intecion/ipal-kit/tokens.css` (neutral defaults, light/dark on `data-theme`, `[data-surface="inverse"]` scope, reduced motion), `@intecion/ipal-kit/tailwind.css` (Tailwind 4 preset: `bg-surface`, @@ -50,6 +61,12 @@ fifteen ready page sections and ten page templates. plugin repo (`reference/`, not shipped) and is built, seeded and smoke-tested in the plugin's CI. ### Changed +- **Sitemap:** the page assigned as the 404 in *Site settings → System pages* is left out whatever its slug (only + the slugs `404`, `500`, `error`, `not-found` were left out; a 404 page called `nie-znaleziono` was listed and answered 404). +- **ipal-seo-check:** duplicate titles are counted per language (the same word in two languages is not a duplicate). +- **ipal-audit:** array `labels` / `rowLabel` after the `fields` key are found (were reported missing); a form seeded + from any seed file (`src/seed/forms.ts`, `upsertBy('forms', …)`) counts as a form seed; the script runs grep in UTF-8 + (in the C locale an en dash matched the Polish-letter check). - **Cookie banner / button colours** read the single token names (`--ipal-surface`, `--ipal-text` …) instead of `dark:` + `--ipal-*-dark`. With `tokens.css` they switch with the theme. Without it, the built-in fallback follows the page's `color-scheme` (`light-dark()`): a site without a dark theme no longer gets a dark banner on a dark-mode diff --git a/docs/README.md b/docs/README.md index e09e576..80bbf0e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -54,6 +54,7 @@ API details — one file per module: | Design tokens (`--ipal-*`, `tokens.css`, `tailwind.css`, `ipal-tokens`, DESIGN.md) | [design-tokens.md](./design-tokens.md) | | R2, `buildImagesConfig`, `MediaPreconnect`, `YouTubeEmbed` | [storage.md](./storage.md) | | Turnstile | [turnstile.md](./turnstile.md) | +| ipal-doctor (the site against the team standard, `ipal-doctor.json`) | [doctor.md](./doctor.md) | | Admin panel white-label | [white-label.md](./white-label.md) | Maintenance rule: a module's API changes → update its file in the same commit. New working rules → diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 323d6a5..74500d5 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1244,9 +1244,12 @@ Record the key project decisions (stack, decisions, page modes) in the project's ## 11. BEFORE YOU SAY "DONE" **Run, do not guess** — `ipal-audit` (the §0b set + the rules below) and `ipal-seo-check` -(GEO and SEO on the built site) instead of manual greps: +(GEO and SEO on the built site) instead of manual greps; then `ipal-doctor` for the whole site against the team +standard (versions, Node 22, layout, database names, env, headers, 2FA, cookie scanner, AGENTS.md, skills, seeds, +block library — [doctor.md](../doctor.md)): ```bash bash .agents/skills/ipal-audit/scripts/audit.sh +pnpm exec ipal-doctor # + --deep --url http://localhost:3000 on the built site node .agents/skills/ipal-seo-check/scripts/seo-check.mjs http://localhost:3000 pnpm generate:types && pnpm tsc --noEmit pnpm build # --webpack in the script; locally, not only dev @@ -1318,6 +1321,7 @@ Anything that needs a developer → move it to the panel. | Seeds on production: create-only, dry run, backup, update guard | [seeding.md](../seeding.md) | | Meta Pixel / GA4 via GTM | [gtm-meta-pixel.md](../gtm-meta-pixel.md) | | Turnstile | [turnstile.md](../turnstile.md) | +| ipal-doctor: the site against the team standard, `ipal-doctor.json`, `/api/ipal/doctor` | [doctor.md](../doctor.md) | | Panel white-label | [white-label.md](../white-label.md) | --- @@ -1388,9 +1392,10 @@ the task matches — manually: `/`. | `ipal-audit` | before every "done" — the §0b set + the §11 checks + panel (§6.5a) + hardcoding in JSX + tsc + build | | `ipal-seo-check` | the running site through the eyes of Googlebot and AI agents (head, canonical, hreflang, sitemap, 404, JSON-LD, llms, Markdown, MCP) | | `ipal-consent-check` | browser: no tracking pixels or cookies before consent; the Google tag may load before consent only in Consent Mode `advanced` (all signals `denied`) — a client who wants zero requests gets `consentMode: 'basic'` | +| `ipal-doctor` | the whole site against the team standard in one command (`pnpm exec ipal-doctor`): versions, Node 22, layout, database names, env, headers, CSP, 2FA, cookie scanner, adminMeta, AGENTS.md, skills, seeds, block library, pnpm audit; `--url` / `--deep` for the running site and the database; `--strict` in the CI of a new site | | `ipal-plugin-gap` | ipal-kit has a bug or is missing a feature — report to the owner, wait for the decision; a marked workaround only after approval | -Run the scripts in the skills, do not read them (the output is enough): `ipal-audit/scripts/audit.sh`, +Run the scripts in the skills, do not read them (the output is enough): `ipal-audit/scripts/audit.sh`, `pnpm exec ipal-doctor`, `ipal-seo-check/scripts/seo-check.mjs`, `ipal-consent-check/scripts/consent-check.mjs`, `ipal-locale-add/scripts/locale-coverage.ts`; templates to copy are in `resources/`. diff --git a/docs/agent/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md index a1a8c3f..938d1fb 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -63,7 +63,20 @@ legacy-peer-deps=true ```json { "domain": "example-studio.pl", - "launched": false + "launched": false, + "rules": { + "audit:collections-present": { + "off": true, + "reason": "Project decisions: posts and caseStudies with archive pages; entryFields.ts is their shared field helper, not a collection" + }, + "i18n-literals": { + "off": true, + "files": [ + "src/components/design/**" + ], + "reason": "Approved exception (AGENTS.md → Project decisions): the /design styleguide has its labels in code" + } + } } ``` @@ -242,10 +255,11 @@ export function register() { if (process.env.NEXT_RUNTIME !== 'nodejs') {return} // storage: R2 is required in production. ALLOW_LOCAL_MEDIA=1 lets a production build run on local disk for // local checks and CI only — never set it in Coolify. + // cookieCrawl: IPAL_COOKIE_SCAN_URL / IPAL_COOKIE_SCAN_TOKEN in production (cookieScanner.crawl, the shared service). // databaseName: DATABASE_URI must name example-studiopl_dev / example-studiopl_prod (databaseNamesFor). // R2_PUBLIC_URL optional: media are served through the app by default (storage.md, env.md). assertEnv( - ipalEnvRules({ databaseName: { domain: 'example-studio.pl' }, ipHeader: true, storage: process.env.ALLOW_LOCAL_MEDIA !== '1' }).map((rule) => + ipalEnvRules({ cookieCrawl: true, databaseName: { domain: 'example-studio.pl' }, ipHeader: true, storage: process.env.ALLOW_LOCAL_MEDIA !== '1' }).map((rule) => rule.name === 'R2_PUBLIC_URL' ? { ...rule, required: false } : rule, ), ) @@ -348,6 +362,7 @@ import { buildRevalidateHook, buildSlugField, buildSummaryField, + rowLabel, trackSlugHistoryHook, } from '@intecion/ipal-kit' import { revalidatePath } from 'next/cache' @@ -367,7 +382,7 @@ export const Pages: CollectionConfig = { { name: 'layout', type: 'blocks', blocks: pageBlocks, minRows: 1 }, buildSummaryField(), // aiSummary — GEO (llms.txt, MCP) buildNoindexField(), - { name: 'slugHistory', type: 'array', admin: { readOnly: true }, fields: [{ name: 'slug', type: 'text' }] }, + { name: 'slugHistory', type: 'array', admin: { components: rowLabel('slug', 'Old address'), readOnly: true }, fields: [{ name: 'slug', type: 'text' }], labels: { plural: 'Old addresses', singular: 'Old address' } }, ], hooks: { afterChange: [revalidate.afterChange], @@ -434,7 +449,7 @@ export const entryFields: Field[] = [ ```ts import type { GlobalConfig } from 'payload' -import { buildGlobalRevalidateHook } from '@intecion/ipal-kit' +import { buildGlobalRevalidateHook, rowLabel } from '@intecion/ipal-kit' import { revalidatePath } from 'next/cache' /** Company data for a PL market site: footer, contact block details, LocalBusiness JSON-LD. */ @@ -445,6 +460,7 @@ export const Company: GlobalConfig = { { name: 'name', type: 'text', required: true }, { name: 'legalName', type: 'text' }, { name: 'taxId', type: 'text', label: 'NIP' }, + { name: 'taxIdLabel', type: 'text', admin: { description: 'Shown before the tax ID in the footer.' }, defaultValue: 'NIP', label: 'Tax ID label', localized: true }, { name: 'address', type: 'group', @@ -461,6 +477,8 @@ export const Company: GlobalConfig = { { name: 'socials', type: 'array', + admin: { components: rowLabel('label', 'Profile'), initCollapsed: true }, + labels: { plural: 'Profiles', singular: 'Profile' }, fields: [ { name: 'label', type: 'text', required: true }, { name: 'url', type: 'text', required: true }, diff --git a/docs/agent/skills/ipal-audit/SKILL.md b/docs/agent/skills/ipal-audit/SKILL.md index 2498a0a..0d4f4fc 100644 --- a/docs/agent/skills/ipal-audit/SKILL.md +++ b/docs/agent/skills/ipal-audit/SKILL.md @@ -36,6 +36,13 @@ classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warnin next/font in `--font-body` with the preset (warning), and with `src/design/tokens.ts`: no `DESIGN.md` (warning) and `ipal-tokens --check` — a stale `src/design/tokens.css` or a WCAG AA contrast failure is an error. +## ipal-audit and ipal-doctor +`ipal-audit` checks the **code** inside the edit loop (and tsc + build). `pnpm exec ipal-doctor` checks the **site** +against the team standard: it runs this script (`--quick`) from the installed package, reports its findings under its +own rule ids (`i18n-literals`, `blocks-tokens`, `audit:`, one per file), and adds versions, Node, layout, database +names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` — the running site and the database +(the `ipal-doctor` skill, docs/doctor.md). An approved exception for the doctor goes into `ipal-doctor.json` with a reason. + ## What the script does not check (do it by hand) - **Editor test** (AGENT.md §11): every text, image, button, section, diff --git a/docs/agent/skills/ipal-audit/scripts/audit.sh b/docs/agent/skills/ipal-audit/scripts/audit.sh index 0aa5888..7225b75 100644 --- a/docs/agent/skills/ipal-audit/scripts/audit.sh +++ b/docs/agent/skills/ipal-audit/scripts/audit.sh @@ -7,6 +7,8 @@ # Exit code: 0 = no errors (warnings allowed), 1 = at least one error. set -u +# UTF-8 for grep: in the C locale a multibyte class like [ąę…] matches single bytes (an en dash hit "Polish"). +export LC_ALL="${LC_ALL:-C.UTF-8}" QUICK=0 for arg in "$@"; do @@ -322,8 +324,10 @@ if [ -n "$CFG" ]; then report WARNING "robots blocks AI bots" "§0b.8 — only with the client's decision in AGENTS.md" \ "$(skipped aibots || g "aiBots: *'(disallow|block-training)'" src --include=*.ts)" fi -if [ -n "$CFG" ] && grep -qE 'forms *:' "$CFG" 2>/dev/null && ! ls scripts/seed-form* >/dev/null 2>&1 && ! skipped forms-seed; then - report WARNING "no form seed" "ipal-form §5 — every form from scripts/seed-form-*.ts (notification + sender confirmation, all languages)" "scripts/seed-form-*.ts" +# A form seed: scripts/seed-form-*.ts, or a seed file (src/seed, scripts) that seeds the forms collection. +FORM_SEED=$(ls scripts/seed-form* 2>/dev/null; grep -rlE "collection: *['\"]forms['\"]|upsertBy\( *['\"]forms['\"]|seed\.form\(|\.forms?\(" $(dirs src/seed scripts) 2>/dev/null) +if [ -n "$CFG" ] && grep -qE 'forms *:' "$CFG" 2>/dev/null && [ -z "$FORM_SEED" ] && ! skipped forms-seed; then + report WARNING "no form seed" "ipal-form §5 — every form from a seed (scripts/seed-form-*.ts or src/seed/forms.ts: notification + sender confirmation, all languages)" "scripts/seed-form-*.ts" fi need WARNING r2 "R2 env in .env.example" ".env.example lists R2_BUCKET, R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_PUBLIC_URL" 'R2_BUCKET' .env.example need WARNING '' "IPAL_IP_HEADER in .env.example" "header the rate limit trusts, e.g. cf-connecting-ip (forms.md)" 'IPAL_IP_HEADER' .env.example diff --git a/docs/agent/skills/ipal-audit/scripts/panel-check.mjs b/docs/agent/skills/ipal-audit/scripts/panel-check.mjs index cacf2e5..bfe6021 100644 --- a/docs/agent/skills/ipal-audit/scripts/panel-check.mjs +++ b/docs/agent/skills/ipal-audit/scripts/panel-check.mjs @@ -18,6 +18,31 @@ const lineOf = (src, i) => src.slice(0, i).split('\n').length const out = (level, rule, file, src, i, detail) => console.log(`${level}|${rule}|${file}:${lineOf(src, i)}: ${detail}`) const strip = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/(^|[^:])\/\/.*$/gm, (m, p) => p + ' '.repeat(m.length - p.length)) +// The text of the object literal around index i, without the contents of its nested `fields: [...]`. +function ownObject(src, i) { + let start = i + for (let depth = 0; start > 0; start--) { + const ch = src[start - 1] + if (ch === '}') depth++ + else if (ch === '{') { if (depth === 0) { start--; break } depth-- } + } + let end = i + for (let depth = 0; end < src.length; end++) { + const ch = src[end] + if (ch === '{') depth++ + else if (ch === '}') { if (depth === 0) break; depth-- } + } + const obj = src.slice(start, end + 1) + const at = obj.search(/\bfields\s*:\s*\[/) + if (at < 0) return obj + let j = obj.indexOf('[', at) + for (let depth = 0; j < obj.length; j++) { + if (obj[j] === '[') depth++ + else if (obj[j] === ']' && --depth === 0) break + } + return obj.slice(0, at) + obj.slice(j + 1) +} + for (const file of files) { const src = strip(readFileSync(file, 'utf8')) @@ -35,15 +60,13 @@ for (const file of files) { else if (m[1] === 'description' && text.length > 120) out('WARNING', 'description over 120 chars — one short sentence: what it does / where it shows', file, src, m.index, `${text.length} chars`) } - // arrays: labels (→ "Add Feature" button) + rowLabel (→ readable rows) + // arrays: labels (→ "Add Feature" button) + rowLabel (→ readable rows) — anywhere in the array's own + // object (before or after its `fields`), not inside the nested fields for (const m of src.matchAll(/type:\s*['"]array['"]/g)) { - const before = src.slice(0, m.index) - const start = Math.max(before.lastIndexOf('name:'), before.lastIndexOf('{')) - const fieldsAt = src.indexOf('fields:', m.index) - const head = src.slice(start < 0 ? m.index : start, fieldsAt < 0 ? m.index + 400 : fieldsAt) - const name = head.match(/name:\s*['"](\w+)['"]/)?.[1] ?? '?' - if (!/\blabels\s*:/.test(head)) out('WARNING', 'array without labels {singular, plural} — panel shows "Add Row"', file, src, m.index, name) - if (!/rowLabel|RowLabel/.test(head)) out('WARNING', 'array without rowLabel() — rows read "Item 01" instead of their content', file, src, m.index, name) + const own = ownObject(src, m.index) + const name = own.match(/name:\s*['"](\w+)['"]/)?.[1] ?? '?' + if (!/\blabels\s*:/.test(own)) out('WARNING', 'array without labels {singular, plural} — panel shows "Add Row"', file, src, m.index, name) + if (!/rowLabel|RowLabel/.test(own)) out('WARNING', 'array without rowLabel() — rows read "Item 01" instead of their content', file, src, m.index, name) } // too many fields in one block config → tabs / condition / arrays / variant diff --git a/docs/agent/skills/ipal-doctor/SKILL.md b/docs/agent/skills/ipal-doctor/SKILL.md new file mode 100644 index 0000000..2f424b4 --- /dev/null +++ b/docs/agent/skills/ipal-doctor/SKILL.md @@ -0,0 +1,70 @@ +--- +name: ipal-doctor +description: Checks the whole site against the ipal-kit team standard with one command (`pnpm exec ipal-doctor`) — plugin, Next, sharp and Node versions, the AGENT.md §3 folder layout and naming, database names (<domain>_dev/_prod), env rules, security headers, X-Powered-By, CSP, 2FA, the cookie scanner, adminMeta/agency, AGENTS.md "Project decisions", current ipal-* skills, seeds (createSeeder, SEED_ONLY, no deletes), the block library, pnpm audit, hardcoded texts, and with --url / --deep the running site and the database. Use after setting up a site, after an ipal-kit upgrade, before a deploy, in CI of a new site, and when asked whether a site follows the team rules. +--- + +# ipal-doctor + +Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`. + +## Steps + +1. From the project root (after `pnpm install`, `pnpm payload generate:importmap`, `pnpm exec ipal-skills`): + ```bash + pnpm exec ipal-doctor # static: files only, no build, no database + pnpm exec ipal-doctor --offline # without the registry (latest plugin, pnpm audit) + ``` + Running site and database (read-only): + ```bash + pnpm build && pnpm start # or the deployed URL + pnpm exec ipal-doctor --deep --url http://localhost:3000 + ``` +2. Show the user the **full output**. Every finding names its rule, the file, a fix and a doc. +3. Fix every `error`. A `warning` is drift — fix it or tell the user why not. `info` is a note. +4. A deliberate exception (the owner's decision) goes into `ipal-doctor.json` **with a reason** — the same reason as in + AGENTS.md "Project decisions". Never silence a rule just to make the run pass: + ```json + { "rules": { "i18n-literals": { "off": true, "files": ["src/components/design/**"], "reason": "approved exception: styleguide labels" } } } + ``` + Keys: `off`, `severity`, `reason` (required), `until` (ISO date), `files` (globs). Top level: `domain`, `launched`, + `layout.allow`, `seen` (written by the doctor), `extraRules`. +5. Run again until it reports what the project expects (a new site: `--strict` → `0 error(s), 0 warning(s), 0 info`). + +## Options and exit codes + +`[dir]` · `--json` (schema 1) · `--md` · `--strict` (= `--fail-on info`) · `--fail-on error|warning|info` · `--offline` · +`--url <url>` · `--staging` (must be noindex) · `--admin-route <path>` · `--deep` · `--env-file <prod export>` (checks +`<domain>_prod`) · `--only` / `--skip <ids,groups>` · `--sites '../*-web'` (a read-only rule × site table, exit 0). + +Exit `0` ok · `1` findings at or above `--fail-on` · `2` could not run · `3` a rule crashed. + +## CI of a new site (starter, reference site) + +```bash +pnpm exec ipal-doctor --strict --offline # after install +pnpm exec ipal-doctor --strict --offline --deep --url http://localhost:3000 # after build + start +``` +Existing client sites are not gated on it; run it there as a report only. + +## The status endpoint + +`GET /api/ipal/doctor` is added by `ipalKit` and answers 404 until the site has `IPAL_DOCTOR_TOKEN` (≥ 32 characters). +Then `Authorization: Bearer <token>`; counts only (`usersWithout2fa`, `pendingCookies`, `plugin`, `node`). With the same +`IPAL_DOCTOR_TOKEN` in the doctor's environment, `--url` reads it. Off: `ipalKit({ doctor: false })`; adapt: +`ipalKit({ doctor: { tokenVar, access } })`. + +## Env the doctor reads + +`IPAL_DOCTOR_TOKEN` (endpoint), `CI` (set → never writes `seen`), `NO_COLOR` (plain output), `PAYLOAD_CONFIG_PATH` +(`--deep` loads that config), `IPAL_DOCTOR_IMPORT_MAP` (internal: passed to the probe). + +## Building blocks + +`@intecion/ipal-kit/doctor`: `runDoctor`, `doctorRules`, `formatReport`, … (docs/doctor.md → Building blocks) — wrap, +filter or add rules (`extraRules` in `ipal-doctor.json`, each module exports `rules: DoctorRule[]`). + +## Relation to the other checks + +`ipal-audit` stays the check inside the edit loop (plus tsc and build); the doctor runs `ipal-audit --quick` from the +installed package, `ipal-seo-check` with `--url`, and adds versions, env, database, admin, seeds, skills and the live +headers. `ipal-consent-check` (browser) is not part of it. diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index 15c5e0b..93d7475 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -70,6 +70,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins | | `consentLog` | off | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min) | `true` / `{ retentionDays }` (default 1095) | | `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === 'dpo@acme.pl' } }` — narrows who reads records in a project without roles | +| `doctor` | on (404 until `IPAL_DOCTOR_TOKEN` is set) | `GET /api/ipal/doctor` — read-only counts for `ipal-doctor --url` (users without TOTP, cookies waiting for approval, versions); Bearer token ≥ 32 characters, rate-limited, never names or values | `false` = no endpoint; `{ tokenVar, access }` (doctor.md) | | `cookieScanner` | off | `cookie-review` collection, "Scan cookies" box above its list (`CookieScanButton`), `GET`/`POST /api/ipal/cookie-scan`, and (unless `approval: false`) the *Approve cookies* view `/admin/cookie-approval` (`CookieApprovalView`) + `GET`/`POST /api/ipal/cookie-approval` + the dashboard reminder; a scan lists the cookies of the integrations switched on + names looked up in the bundled Open Cookie Database; one **Approve and add** puts the ticked cookies into Cookies → Cookie list (so `<CookieTable>` and the detailed window); never deletes, never overwrites edited text, never duplicates, nothing reaches the banner before approval | `true` / object; after switching on: `pnpm generate:importmap` + `migrate:create`. Check: *Privacy → Cookie review* → **Scan cookies** → "Waiting for approval: N" → **Review and approve** → **Approve and add** → the cookies are in Cookies → Cookie list (cookie-scanner.md) | | `cookieScanner.adminLayout` | `'combined'` | one *Cookies* entry: *Review and approve* and (with `crawl`) *Site check* tabs on the `cookie-settings` global (`ui` fields, `CookieReviewTab` / `CookieSiteCheckTab`); `cookie-review` and `cookie-crawl` get `admin.group: false` (out of the nav, pages and API kept) | `'separate'`; no migration, `generate:importmap` | | `fillEmptyLocales` | on | afterChange hooks: text saved in one language fills the empty languages of `cookie-settings` `cookies.purpose` / `cookies.duration` and `cookie-review` `purpose` / `retention`; never overwrites a language's own text | `false`; `{ 'cookie-settings': [...], 'cookie-review': [...] }` (`[]` = off); check: add a cookie in Polish, switch the locale to English → same purpose | @@ -142,7 +143,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip ## 3. What the project wires itself -Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ipal-seo-check**. +Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ipal-seo-check**, **ipal-doctor** (`pnpm exec ipal-doctor` — the whole site against the team standard; `ipal-doctor.json` silences a rule with a reason, docs/doctor.md). `$U` = `NEXT_PUBLIC_SERVER_URL` (e.g. `http://localhost:3000`). | element | file | minimal example | how to check | details | @@ -236,6 +237,7 @@ and what throws without `i18n`: frontend.md. `SiteProviders` props: `shell`, `ba | `INDEXNOW_KEY` | no | key from Site integrations → IndexNow (generated) | env or panel | | `IPAL_IP_HEADER` | `ipHeader: true` + production | rate limit trusts any IP header (spoofing) + warning in prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) | | `IPAL_COOKIE_SCAN_URL`, `IPAL_COOKIE_SCAN_TOKEN` | `cookieScanner.crawl` (`ipalEnvRules({ cookieCrawl: true })` requires both in production; token ≥ 16 chars) | **Check site** disabled, the box names the missing variable | env; the token also goes into the scanner service's `IPAL_CRAWLER_SITES` as `host=token` | +| `IPAL_DOCTOR_TOKEN` | no; ≥ 32 characters | `GET /api/ipal/doctor` answers 404; with it the endpoint answers a Bearer token, and `ipal-doctor --url` with the same variable reads the deep counts | env (Coolify) and the doctor's shell; also read by the doctor: `CI`, `NO_COLOR`, `PAYLOAD_CONFIG_PATH` (`--deep`), `IPAL_DOCTOR_IMPORT_MAP` (internal) — doctor.md | | `IPAL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only** | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing) | staging env | | `NEXT_PHASE` | set by Next | only tells `next build` from runtime: during the build an unreachable database gives an empty sitemap; at runtime the sitemap throws (route → 503) | do not set by hand | | `NEXT_RUNTIME` | set by Next | `instrumentation.ts` checks for `nodejs`; missing (scripts, seed) → `buildRevalidateHook` does not revalidate | do not set by hand | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index eb08043..7c087f6 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -1,7 +1,7 @@ # ipal-kit — export index Every public export of `@intecion/ipal-kit` (all entries: root, `/client`, `/rsc`, -`/server`, `/seed`, `/next/middleware`, `/admin`, `/env`, `/blocks`, `/blocks/rsc`, `/templates`, `/tokens`), grouped by module. Search with grep +`/server`, `/seed`, `/next/middleware`, `/admin`, `/env`, `/blocks`, `/blocks/rsc`, `/templates`, `/tokens`, `/doctor`), grouped by module. Search with grep (`grep -n "name" .agents/skills/ipal-reference/resources/api.md`) before you write anything yourself. "Import from" column — the first entry is preferred. Plugin options, env, routes and what the project wires: `../SKILL.md`. Module details: `node_modules/@intecion/ipal-kit/docs/<page>.md`. @@ -763,6 +763,30 @@ CSS: `@intecion/ipal-kit/tokens.css` (neutral `--ipal-*` defaults, light/dark, ` **Types:** `TokensInput`, `IpalTokenName` (root, `/tokens`), `ColorInput`, `ColorRole`, `ContrastRow`, `FluidRange`, `RemValue` (`/tokens`). +## ipal-doctor (`doctor`) — details: `node_modules/@intecion/ipal-kit/docs/doctor.md` + +Bin: `ipal-doctor` (`pnpm exec ipal-doctor [dir] [--json] [--md] [--strict] [--fail-on] [--offline] [--url] [--staging] +[--admin-route] [--deep] [--env-file] [--only] [--skip] [--sites]`). `@intecion/ipal-kit/doctor` is Node only. + +| Export | Import from | What it does / when | +|---|---|---| +| `runDoctor(options)` | `@intecion/ipal-kit/doctor` | Runs every rule on one project folder → `DoctorReport` (schema 1). Options: `root`, `packageRoot`, `offline`, `url`, `staging`, `adminRoute`, `deep`, `deepStatus`, `envFile`, `only`, `skip`, `rules`, `config`, `today`, `writeSeen`. Never throws for a failing rule. | +| `runDoctorCli(argv, { packageRoot, cwd?, log? })` | `@intecion/ipal-kit/doctor` | The command; returns the exit code (0 / 1 / 2 / 3). `parseDoctorArgs`, `expandSites` (`'../*-web'`), `DOCTOR_USAGE`. | +| `doctorRules` | `@intecion/ipal-kit/doctor` | Every built-in rule (`DoctorRule`: `id`, `group`, `source`, `docs`, `check(ctx)`) — filter, wrap or extend; own rules through `extraRules` in `ipal-doctor.json`. | +| `applySettings(findings, ctx)`, `globToRegExp(glob)`, `AUDIT_SKIP_RULES` | `@intecion/ipal-kit/doctor` | `ipal-doctor.json` `rules` (`off`, `severity`, `reason`, `until`, `files`) and `ipal-audit-skip` lines applied to findings. | +| `createDoctorContext(options)`, `loadDoctorConfig(root)`, `parseEnvFile(text)`, `readAuditSkips(agentsMd)`, `bareHost(url)` | `@intecion/ipal-kit/doctor` | What a rule reads about the project (files only, values never leave it). | +| `formatReport(report, { color })`, `formatDriftTable(reports)` | `@intecion/ipal-kit/doctor` | Human report; the rule × site Markdown table. | +| `planSkills({ dest, source })` | `@intecion/ipal-kit/doctor` | What `ipal-skills` would change: `missing`, `stale`, `retired` ipal-* folders. | +| `parseToolOutput(text)`, `AUDIT_RULE_MAP` | `@intecion/ipal-kit/doctor` | Reads `[ERROR] title (n) — rule` output of `audit.sh` / `seo-check.mjs`; audit titles that are a doctor rule. | +| `DEFAULT_SRC_ALLOW` | `@intecion/ipal-kit/doctor` | Top-level `src/` entries the convention allows (`layout.allow` extends it). | +| `createLiveFetcher(url, { adminRoute, staging })` | `@intecion/ipal-kit/doctor` | Cached GET-only fetcher for the live rules. | +| `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. | +| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. | +| `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IPAL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `ipalKit` unless `doctor: false`. | + +**Types:** `DoctorRule`, `DoctorFinding`, `RuleFinding`, `DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`, +`DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`. + ## Turnstile (`turnstile`) — details: `node_modules/@intecion/ipal-kit/docs/turnstile.md` | Export | Import from | What it does / when | diff --git a/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs b/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs index 5514ea8..56cec8a 100644 --- a/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs +++ b/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs @@ -136,7 +136,9 @@ for (const url of sample) { if (!title) issues.title.push(url) else { if (title.length > 65) issues.longTitle.push(`${url} (${title.length} chars)`) - titles.set(title, [...(titles.get(title) ?? []), url]) + // per language: the same word in two languages ("Blog" in pl and en) is not a duplicate + const key = `${multiLocale ? localeOf(url) : ''}\u0000${title}` + titles.set(key, [...(titles.get(key) ?? []), url]) } const desc = tags(head, /<meta[^>]+name="description"[^>]*>/gi).map((t) => attr(t, 'content'))[0]?.trim() if (!desc) issues.desc.push(url) @@ -196,7 +198,7 @@ for (const url of sample) { } } -const dupTitles = [...titles.entries()].filter(([, us]) => us.length > 1).map(([t, us]) => `"${t}" × ${us.length}`) +const dupTitles = [...titles.entries()].filter(([, us]) => us.length > 1).map(([k, us]) => `"${k.split('\u0000')[1]}" × ${us.length}`) const dupDescs = [...descriptions.entries()].filter(([, us]) => us.length > 1).map(([d, us]) => `"${d.slice(0, 60)}…" × ${us.length}`) if (issues.status.length) report('ERROR', 'sitemap URLs not 200 (redirect / error)', 'sitemap must list final, live URLs', issues.status) if (issues.noHead.length) report('ERROR', 'no </head> in HTML', 'broken document', issues.noHead) diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index 35fde74..3f9ba30 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -537,6 +537,7 @@ bash .agents/skills/ipal-audit/scripts/audit.sh # full: §0b "missing pnpm build && pnpm start node .agents/skills/ipal-seo-check/scripts/seo-check.mjs http://localhost:3000 # 0 errors node .agents/skills/ipal-consent-check/scripts/consent-check.mjs http://localhost:3000/pl +pnpm exec ipal-doctor --strict --offline --deep --url http://localhost:3000 # the team standard (skill ipal-doctor) ``` The §0b list with its checks: proxy + catch-all + 404 (stage 6) · meta, sitemap, robots, manifest (7) · JSON-LD (6, 10) · llms, llms-full, Markdown, MCP, AI bots, IndexNow (8) · Media/R2 (3–4) · seeded forms (9) · Turnstile (9) · diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/ipal-upgrade/SKILL.md index 8b477c6..022b0d8 100644 --- a/docs/agent/skills/ipal-upgrade/SKILL.md +++ b/docs/agent/skills/ipal-upgrade/SKILL.md @@ -217,4 +217,8 @@ need a **data migration before** the old fields are removed — ask the user whether the project already has content. ## 4. Finish -A full **ipal-audit** with no errors + a list of things to check in the admin panel. +A full **ipal-audit** with no errors, then `pnpm exec ipal-doctor` (after `pnpm exec ipal-skills` and +`pnpm payload generate:importmap`): no new errors against the report before the upgrade (skill **ipal-doctor**; +new rules come with new versions — read each finding, fix or record the owner's decision in `ipal-doctor.json` with a +reason). Before the upgrade, `pnpm dlx --package=@intecion/ipal-kit@latest ipal-doctor --offline` shows what the newest +rules will report. Then the list of things to check in the admin panel. diff --git a/docs/dev/ipal-doctor-proposal.md b/docs/dev/ipal-doctor-proposal.md index ce92fa7..59621a4 100644 --- a/docs/dev/ipal-doctor-proposal.md +++ b/docs/dev/ipal-doctor-proposal.md @@ -1,9 +1,7 @@ # ipal-doctor — proposal -Status: **design approved 2026-10-29** (all of D1–D9, with the adjustments in §6). Build approved in this order: -design tokens and the block library, then the reference site, then the doctor and the starter. Not started — the -doctor waits for the coordinator's start signal. -Date: 2026-10-29 · plugin version at the time: 1.14.6. +Status: **built** (branch `claude/ipal-doctor-build`). The user guide is [docs/doctor.md](../doctor.md); this file +keeps the design and the decisions (§6). Where the two differ, doctor.md describes what shipped. ## 1. What it is @@ -132,7 +130,7 @@ Live checks are GET only, no login, a doctor user agent, at most ~20 requests. ` ### 3.1 Shipping — a bin in the plugin `bin/ipal-doctor.mjs` next to `bin/ipal-skills.mjs`, zero dependencies, Node built-ins and `fetch`. The rules -sit in `bin/doctor/rules/*.mjs`, one module per group, each exporting +sit in `src/modules/doctor/rules/*.ts` (built to `dist/`, the bin imports them), one module per group, each exporting `{ id, group, severity, source, docs, check(ctx) }`. Why in the plugin and not a separate package: the rules change with the plugin (a new required import-map entry, @@ -158,7 +156,7 @@ run anywhere and does not touch the network except `plugin-latest` and `deps-aud Some rules need the real data: users without TOTP, cookies waiting for approval, the exact import map, the real environment. Two ways, decision D3: -- **A. `ipal-doctor --deep`** runs `pnpm payload run node_modules/@intecion/ipal-kit/bin/doctor/deep.ts`: the Local +- **A. `ipal-doctor --deep`** runs `pnpm payload run node_modules/@intecion/ipal-kit/dist/modules/doctor/probe.js`: the Local API, read-only queries (`count`), locally with the dev database (sites are built and checked locally), or in the Coolify app container's terminal against the MongoDB container. No new route. - **B. A status endpoint** `GET /api/ipal/doctor`, **off unless `IPAL_DOCTOR_TOKEN` is set** (≥ 32 chars, bearer, diff --git a/docs/doctor.md b/docs/doctor.md new file mode 100644 index 0000000..2e2128b --- /dev/null +++ b/docs/doctor.md @@ -0,0 +1,225 @@ +# 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", "usersWithout2fa": 0 } +``` + +Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'MY_TOKEN', access: ({ req }) => … } })` +(`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.1; `eslint-config-next` on the same minor (warning) | +| | `sharp-min` | error | `sharp` ≥ 0.35.5 | +| | `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, `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, R2, cookie scanner, `adminMeta`), names no export the plugin no longer has; with `--deep`, equals a fresh one | +| | `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 | +| | `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 | +| | `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"] }, + "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 | +| `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`, `createLiveFetcher`, `buildDoctorEndpoint`, `collectDoctorStatus`, `globToRegExp`, `parseEnvFile`, +`readAuditSkips`, `bareHost`, `expandSites`, `parseDoctorArgs`, `DOCTOR_USAGE`; types `DoctorRule`, `DoctorFinding`, +`DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`, `DoctorSource`, `DoctorStatus`, `DoctorContext`, +`RuleFinding`, `RunDoctorOptions`, `DoctorEndpointOptions`. + +## 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 | diff --git a/docs/env.md b/docs/env.md index 236e31a..1de840d 100644 --- a/docs/env.md +++ b/docs/env.md @@ -91,7 +91,8 @@ from the panel first (Site integrations) and env is only a fallback — turn it in env. The plugin also reads (outside the preset — add your own rules if you want to validate them): -`INDEXNOW_KEY` (seo.md), `IPAL_NOINDEX` (`1`/`true`/`yes` — staging, seo.md). Full table: +`INDEXNOW_KEY` (seo.md), `IPAL_NOINDEX` (`1`/`true`/`yes` — staging, seo.md), `IPAL_DOCTOR_TOKEN` (≥ 32 characters — +turns `GET /api/ipal/doctor` on, doctor.md). Full table: [deployment.md](./deployment.md). Extending with your own variables — spread: diff --git a/package.json b/package.json index 2159b65..3bb4f64 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,11 @@ "types": "./dist/exports/env.d.ts", "default": "./dist/exports/env.js" }, + "./doctor": { + "import": "./dist/exports/doctor.js", + "types": "./dist/exports/doctor.d.ts", + "default": "./dist/exports/doctor.js" + }, "./tokens": { "import": "./dist/exports/tokens.js", "types": "./dist/exports/tokens.d.ts", @@ -80,7 +85,8 @@ "bin": { "ipal-skills": "bin/ipal-skills.mjs", "ipal-blocks": "bin/ipal-blocks.mjs", - "ipal-tokens": "bin/ipal-tokens.mjs" + "ipal-tokens": "bin/ipal-tokens.mjs", + "ipal-doctor": "bin/ipal-doctor.mjs" }, "files": [ "dist", diff --git a/reference/.agents/skills/ipal-audit/SKILL.md b/reference/.agents/skills/ipal-audit/SKILL.md index 2498a0a..0d4f4fc 100644 --- a/reference/.agents/skills/ipal-audit/SKILL.md +++ b/reference/.agents/skills/ipal-audit/SKILL.md @@ -36,6 +36,13 @@ classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warnin next/font in `--font-body` with the preset (warning), and with `src/design/tokens.ts`: no `DESIGN.md` (warning) and `ipal-tokens --check` — a stale `src/design/tokens.css` or a WCAG AA contrast failure is an error. +## ipal-audit and ipal-doctor +`ipal-audit` checks the **code** inside the edit loop (and tsc + build). `pnpm exec ipal-doctor` checks the **site** +against the team standard: it runs this script (`--quick`) from the installed package, reports its findings under its +own rule ids (`i18n-literals`, `blocks-tokens`, `audit:<title>`, one per file), and adds versions, Node, layout, database +names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` — the running site and the database +(the `ipal-doctor` skill, docs/doctor.md). An approved exception for the doctor goes into `ipal-doctor.json` with a reason. + ## What the script does not check (do it by hand) - **Editor test** (AGENT.md §11): every text, image, button, section, diff --git a/reference/.agents/skills/ipal-audit/scripts/audit.sh b/reference/.agents/skills/ipal-audit/scripts/audit.sh index 0aa5888..7225b75 100644 --- a/reference/.agents/skills/ipal-audit/scripts/audit.sh +++ b/reference/.agents/skills/ipal-audit/scripts/audit.sh @@ -7,6 +7,8 @@ # Exit code: 0 = no errors (warnings allowed), 1 = at least one error. set -u +# UTF-8 for grep: in the C locale a multibyte class like [ąę…] matches single bytes (an en dash hit "Polish"). +export LC_ALL="${LC_ALL:-C.UTF-8}" QUICK=0 for arg in "$@"; do @@ -322,8 +324,10 @@ if [ -n "$CFG" ]; then report WARNING "robots blocks AI bots" "§0b.8 — only with the client's decision in AGENTS.md" \ "$(skipped aibots || g "aiBots: *'(disallow|block-training)'" src --include=*.ts)" fi -if [ -n "$CFG" ] && grep -qE 'forms *:' "$CFG" 2>/dev/null && ! ls scripts/seed-form* >/dev/null 2>&1 && ! skipped forms-seed; then - report WARNING "no form seed" "ipal-form §5 — every form from scripts/seed-form-*.ts (notification + sender confirmation, all languages)" "scripts/seed-form-*.ts" +# A form seed: scripts/seed-form-*.ts, or a seed file (src/seed, scripts) that seeds the forms collection. +FORM_SEED=$(ls scripts/seed-form* 2>/dev/null; grep -rlE "collection: *['\"]forms['\"]|upsertBy\( *['\"]forms['\"]|seed\.form\(|\.forms?\(" $(dirs src/seed scripts) 2>/dev/null) +if [ -n "$CFG" ] && grep -qE 'forms *:' "$CFG" 2>/dev/null && [ -z "$FORM_SEED" ] && ! skipped forms-seed; then + report WARNING "no form seed" "ipal-form §5 — every form from a seed (scripts/seed-form-*.ts or src/seed/forms.ts: notification + sender confirmation, all languages)" "scripts/seed-form-*.ts" fi need WARNING r2 "R2 env in .env.example" ".env.example lists R2_BUCKET, R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_PUBLIC_URL" 'R2_BUCKET' .env.example need WARNING '' "IPAL_IP_HEADER in .env.example" "header the rate limit trusts, e.g. cf-connecting-ip (forms.md)" 'IPAL_IP_HEADER' .env.example diff --git a/reference/.agents/skills/ipal-audit/scripts/panel-check.mjs b/reference/.agents/skills/ipal-audit/scripts/panel-check.mjs index cacf2e5..bfe6021 100644 --- a/reference/.agents/skills/ipal-audit/scripts/panel-check.mjs +++ b/reference/.agents/skills/ipal-audit/scripts/panel-check.mjs @@ -18,6 +18,31 @@ const lineOf = (src, i) => src.slice(0, i).split('\n').length const out = (level, rule, file, src, i, detail) => console.log(`${level}|${rule}|${file}:${lineOf(src, i)}: ${detail}`) const strip = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/(^|[^:])\/\/.*$/gm, (m, p) => p + ' '.repeat(m.length - p.length)) +// The text of the object literal around index i, without the contents of its nested `fields: [...]`. +function ownObject(src, i) { + let start = i + for (let depth = 0; start > 0; start--) { + const ch = src[start - 1] + if (ch === '}') depth++ + else if (ch === '{') { if (depth === 0) { start--; break } depth-- } + } + let end = i + for (let depth = 0; end < src.length; end++) { + const ch = src[end] + if (ch === '{') depth++ + else if (ch === '}') { if (depth === 0) break; depth-- } + } + const obj = src.slice(start, end + 1) + const at = obj.search(/\bfields\s*:\s*\[/) + if (at < 0) return obj + let j = obj.indexOf('[', at) + for (let depth = 0; j < obj.length; j++) { + if (obj[j] === '[') depth++ + else if (obj[j] === ']' && --depth === 0) break + } + return obj.slice(0, at) + obj.slice(j + 1) +} + for (const file of files) { const src = strip(readFileSync(file, 'utf8')) @@ -35,15 +60,13 @@ for (const file of files) { else if (m[1] === 'description' && text.length > 120) out('WARNING', 'description over 120 chars — one short sentence: what it does / where it shows', file, src, m.index, `${text.length} chars`) } - // arrays: labels (→ "Add Feature" button) + rowLabel (→ readable rows) + // arrays: labels (→ "Add Feature" button) + rowLabel (→ readable rows) — anywhere in the array's own + // object (before or after its `fields`), not inside the nested fields for (const m of src.matchAll(/type:\s*['"]array['"]/g)) { - const before = src.slice(0, m.index) - const start = Math.max(before.lastIndexOf('name:'), before.lastIndexOf('{')) - const fieldsAt = src.indexOf('fields:', m.index) - const head = src.slice(start < 0 ? m.index : start, fieldsAt < 0 ? m.index + 400 : fieldsAt) - const name = head.match(/name:\s*['"](\w+)['"]/)?.[1] ?? '?' - if (!/\blabels\s*:/.test(head)) out('WARNING', 'array without labels {singular, plural} — panel shows "Add Row"', file, src, m.index, name) - if (!/rowLabel|RowLabel/.test(head)) out('WARNING', 'array without rowLabel() — rows read "Item 01" instead of their content', file, src, m.index, name) + const own = ownObject(src, m.index) + const name = own.match(/name:\s*['"](\w+)['"]/)?.[1] ?? '?' + if (!/\blabels\s*:/.test(own)) out('WARNING', 'array without labels {singular, plural} — panel shows "Add Row"', file, src, m.index, name) + if (!/rowLabel|RowLabel/.test(own)) out('WARNING', 'array without rowLabel() — rows read "Item 01" instead of their content', file, src, m.index, name) } // too many fields in one block config → tabs / condition / arrays / variant diff --git a/reference/.agents/skills/ipal-block/SKILL.md b/reference/.agents/skills/ipal-block/SKILL.md index 91c9329..087eb45 100644 --- a/reference/.agents/skills/ipal-block/SKILL.md +++ b/reference/.agents/skills/ipal-block/SKILL.md @@ -14,6 +14,8 @@ One section per use of this skill. Details and ready code: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6. ## 0. Library block first (docs/block-library.md) +See every block and variant rendered (also on `muted` and `inverted`) on the reference site's Blocks page — seed +`src/seed/showcase.ts` in `docs/agent/reference-site/INDEX.md`; wiring: `src/blocks/configs.ts`, `src/blocks/registry.ts` there. The plugin ships 15 blocks: `hero`, `textMedia`, `featureGrid`, `cta`, `richText`, `faq`, `contact`, `gallery`, `testimonials`, `stats`, `steps`, `logos`, `team`, `pricing`, `entryList` (variants: `blockLibraryManifest`). 1. Does a library block or one of its variants fit the section? → turn it on in `src/blocks/configs.ts` diff --git a/reference/.agents/skills/ipal-doctor/SKILL.md b/reference/.agents/skills/ipal-doctor/SKILL.md new file mode 100644 index 0000000..2f424b4 --- /dev/null +++ b/reference/.agents/skills/ipal-doctor/SKILL.md @@ -0,0 +1,70 @@ +--- +name: ipal-doctor +description: Checks the whole site against the ipal-kit team standard with one command (`pnpm exec ipal-doctor`) — plugin, Next, sharp and Node versions, the AGENT.md §3 folder layout and naming, database names (<domain>_dev/_prod), env rules, security headers, X-Powered-By, CSP, 2FA, the cookie scanner, adminMeta/agency, AGENTS.md "Project decisions", current ipal-* skills, seeds (createSeeder, SEED_ONLY, no deletes), the block library, pnpm audit, hardcoded texts, and with --url / --deep the running site and the database. Use after setting up a site, after an ipal-kit upgrade, before a deploy, in CI of a new site, and when asked whether a site follows the team rules. +--- + +# ipal-doctor + +Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`. + +## Steps + +1. From the project root (after `pnpm install`, `pnpm payload generate:importmap`, `pnpm exec ipal-skills`): + ```bash + pnpm exec ipal-doctor # static: files only, no build, no database + pnpm exec ipal-doctor --offline # without the registry (latest plugin, pnpm audit) + ``` + Running site and database (read-only): + ```bash + pnpm build && pnpm start # or the deployed URL + pnpm exec ipal-doctor --deep --url http://localhost:3000 + ``` +2. Show the user the **full output**. Every finding names its rule, the file, a fix and a doc. +3. Fix every `error`. A `warning` is drift — fix it or tell the user why not. `info` is a note. +4. A deliberate exception (the owner's decision) goes into `ipal-doctor.json` **with a reason** — the same reason as in + AGENTS.md "Project decisions". Never silence a rule just to make the run pass: + ```json + { "rules": { "i18n-literals": { "off": true, "files": ["src/components/design/**"], "reason": "approved exception: styleguide labels" } } } + ``` + Keys: `off`, `severity`, `reason` (required), `until` (ISO date), `files` (globs). Top level: `domain`, `launched`, + `layout.allow`, `seen` (written by the doctor), `extraRules`. +5. Run again until it reports what the project expects (a new site: `--strict` → `0 error(s), 0 warning(s), 0 info`). + +## Options and exit codes + +`[dir]` · `--json` (schema 1) · `--md` · `--strict` (= `--fail-on info`) · `--fail-on error|warning|info` · `--offline` · +`--url <url>` · `--staging` (must be noindex) · `--admin-route <path>` · `--deep` · `--env-file <prod export>` (checks +`<domain>_prod`) · `--only` / `--skip <ids,groups>` · `--sites '../*-web'` (a read-only rule × site table, exit 0). + +Exit `0` ok · `1` findings at or above `--fail-on` · `2` could not run · `3` a rule crashed. + +## CI of a new site (starter, reference site) + +```bash +pnpm exec ipal-doctor --strict --offline # after install +pnpm exec ipal-doctor --strict --offline --deep --url http://localhost:3000 # after build + start +``` +Existing client sites are not gated on it; run it there as a report only. + +## The status endpoint + +`GET /api/ipal/doctor` is added by `ipalKit` and answers 404 until the site has `IPAL_DOCTOR_TOKEN` (≥ 32 characters). +Then `Authorization: Bearer <token>`; counts only (`usersWithout2fa`, `pendingCookies`, `plugin`, `node`). With the same +`IPAL_DOCTOR_TOKEN` in the doctor's environment, `--url` reads it. Off: `ipalKit({ doctor: false })`; adapt: +`ipalKit({ doctor: { tokenVar, access } })`. + +## Env the doctor reads + +`IPAL_DOCTOR_TOKEN` (endpoint), `CI` (set → never writes `seen`), `NO_COLOR` (plain output), `PAYLOAD_CONFIG_PATH` +(`--deep` loads that config), `IPAL_DOCTOR_IMPORT_MAP` (internal: passed to the probe). + +## Building blocks + +`@intecion/ipal-kit/doctor`: `runDoctor`, `doctorRules`, `formatReport`, … (docs/doctor.md → Building blocks) — wrap, +filter or add rules (`extraRules` in `ipal-doctor.json`, each module exports `rules: DoctorRule[]`). + +## Relation to the other checks + +`ipal-audit` stays the check inside the edit loop (plus tsc and build); the doctor runs `ipal-audit --quick` from the +installed package, `ipal-seo-check` with `--url`, and adds versions, env, database, admin, seeds, skills and the live +headers. `ipal-consent-check` (browser) is not part of it. diff --git a/reference/.agents/skills/ipal-form/resources/formClasses.ts b/reference/.agents/skills/ipal-form/resources/formClasses.ts index f0c18a8..4bc645c 100644 --- a/reference/.agents/skills/ipal-form/resources/formClasses.ts +++ b/reference/.agents/skills/ipal-form/resources/formClasses.ts @@ -1,29 +1,36 @@ // src/components/forms/formClasses.ts — the ONLY place forms are styled. Every -// panel form (RenderForm / BuilderForm) uses it. Values = the project's design -// tokens (DESIGN.md); the plugin ships no styles. Delete keys you don't need. +// panel form (RenderForm / BuilderForm) uses it. Design-token utilities only +// (node_modules/@intecion/ipal-kit/docs/design-tokens.md): a brand changes +// src/design/tokens.ts, never this file. Delete keys you don't need. import type { BuilderFormClassNames } from '@intecion/ipal-kit/client' +import { buttonClass } from '@intecion/ipal-kit/blocks/rsc' + +const control = + 'w-full rounded-control border border-border-strong bg-surface px-3 py-2 text-fg placeholder:text-fg-muted ' + + 'transition-colors duration-fast ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus ' + + 'aria-invalid:border-danger' export const formClasses: BuilderFormClassNames = { form: 'grid gap-6', - progress: 'text-sm text-muted', // "Step 1 of 3" + progress: 'text-sm text-fg-muted', // "Step 1 of 3" step: 'grid gap-4', - stepTitle: 'text-h3 font-semibold', - stepDescription: 'text-muted', + stepTitle: 'text-h4', + stepDescription: 'text-fg-muted', fields: 'grid grid-cols-12 gap-4', field: 'col-span-12', fieldHalf: 'md:col-span-6', // width ≤ 50 in the panel - label: 'mb-1 block font-medium', - input: 'w-full rounded-md border border-border px-3 py-2', - textarea: 'w-full rounded-md border border-border px-3 py-2', - select: 'w-full rounded-md border border-border px-3 py-2', + label: 'mb-1 block font-medium text-fg-strong', + input: control, + textarea: control, + select: control, checkboxLabel: 'flex items-start gap-2', choices: 'grid gap-2', // radio / checkbox group <fieldset> - legend: 'mb-1 font-medium', + legend: 'mb-1 font-medium text-fg-strong', choice: 'flex items-center gap-2', error: 'mt-1 text-sm text-danger', - formError: 'text-danger', - actions: 'flex gap-3', - back: 'btn btn-secondary', // same classes as Button.tsx variants - submit: 'btn btn-primary', - success: 'rounded-md bg-surface p-6', + formError: 'rounded-control bg-danger-surface p-4 text-danger', + actions: 'flex flex-wrap gap-3', + back: buttonClass('secondary'), // the same looks as the section buttons + submit: buttonClass('primary'), + success: 'rounded-card bg-success-surface p-6 text-success', } diff --git a/reference/.agents/skills/ipal-reference/SKILL.md b/reference/.agents/skills/ipal-reference/SKILL.md index 0a9bf7c..93d7475 100644 --- a/reference/.agents/skills/ipal-reference/SKILL.md +++ b/reference/.agents/skills/ipal-reference/SKILL.md @@ -6,6 +6,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip # ipal-reference ## How to use +- **A working example of every row** is in the reference site: `docs/agent/reference-site/INDEX.md` (file → what it + shows; wiring files in full). - **Look here first**, then at the code. Looking for a function → `grep -n "<word>" resources/api.md` (`resources/api.md` — every export: import, what it does). Module description: `node_modules/@intecion/ipal-kit/docs/<page>.md` (the "details" column). @@ -68,6 +70,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins | | `consentLog` | off | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min) | `true` / `{ retentionDays }` (default 1095) | | `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === 'dpo@acme.pl' } }` — narrows who reads records in a project without roles | +| `doctor` | on (404 until `IPAL_DOCTOR_TOKEN` is set) | `GET /api/ipal/doctor` — read-only counts for `ipal-doctor --url` (users without TOTP, cookies waiting for approval, versions); Bearer token ≥ 32 characters, rate-limited, never names or values | `false` = no endpoint; `{ tokenVar, access }` (doctor.md) | | `cookieScanner` | off | `cookie-review` collection, "Scan cookies" box above its list (`CookieScanButton`), `GET`/`POST /api/ipal/cookie-scan`, and (unless `approval: false`) the *Approve cookies* view `/admin/cookie-approval` (`CookieApprovalView`) + `GET`/`POST /api/ipal/cookie-approval` + the dashboard reminder; a scan lists the cookies of the integrations switched on + names looked up in the bundled Open Cookie Database; one **Approve and add** puts the ticked cookies into Cookies → Cookie list (so `<CookieTable>` and the detailed window); never deletes, never overwrites edited text, never duplicates, nothing reaches the banner before approval | `true` / object; after switching on: `pnpm generate:importmap` + `migrate:create`. Check: *Privacy → Cookie review* → **Scan cookies** → "Waiting for approval: N" → **Review and approve** → **Approve and add** → the cookies are in Cookies → Cookie list (cookie-scanner.md) | | `cookieScanner.adminLayout` | `'combined'` | one *Cookies* entry: *Review and approve* and (with `crawl`) *Site check* tabs on the `cookie-settings` global (`ui` fields, `CookieReviewTab` / `CookieSiteCheckTab`); `cookie-review` and `cookie-crawl` get `admin.group: false` (out of the nav, pages and API kept) | `'separate'`; no migration, `generate:importmap` | | `fillEmptyLocales` | on | afterChange hooks: text saved in one language fills the empty languages of `cookie-settings` `cookies.purpose` / `cookies.duration` and `cookie-review` `purpose` / `retention`; never overwrites a language's own text | `false`; `{ 'cookie-settings': [...], 'cookie-review': [...] }` (`[]` = off); check: add a cookie in Polish, switch the locale to English → same purpose | @@ -140,7 +143,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip ## 3. What the project wires itself -Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ipal-seo-check**. +Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ipal-seo-check**, **ipal-doctor** (`pnpm exec ipal-doctor` — the whole site against the team standard; `ipal-doctor.json` silences a rule with a reason, docs/doctor.md). `$U` = `NEXT_PUBLIC_SERVER_URL` (e.g. `http://localhost:3000`). | element | file | minimal example | how to check | details | @@ -234,6 +237,7 @@ and what throws without `i18n`: frontend.md. `SiteProviders` props: `shell`, `ba | `INDEXNOW_KEY` | no | key from Site integrations → IndexNow (generated) | env or panel | | `IPAL_IP_HEADER` | `ipHeader: true` + production | rate limit trusts any IP header (spoofing) + warning in prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) | | `IPAL_COOKIE_SCAN_URL`, `IPAL_COOKIE_SCAN_TOKEN` | `cookieScanner.crawl` (`ipalEnvRules({ cookieCrawl: true })` requires both in production; token ≥ 16 chars) | **Check site** disabled, the box names the missing variable | env; the token also goes into the scanner service's `IPAL_CRAWLER_SITES` as `host=token` | +| `IPAL_DOCTOR_TOKEN` | no; ≥ 32 characters | `GET /api/ipal/doctor` answers 404; with it the endpoint answers a Bearer token, and `ipal-doctor --url` with the same variable reads the deep counts | env (Coolify) and the doctor's shell; also read by the doctor: `CI`, `NO_COLOR`, `PAYLOAD_CONFIG_PATH` (`--deep`), `IPAL_DOCTOR_IMPORT_MAP` (internal) — doctor.md | | `IPAL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only** | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`, IndexNow sends nothing) | staging env | | `NEXT_PHASE` | set by Next | only tells `next build` from runtime: during the build an unreachable database gives an empty sitemap; at runtime the sitemap throws (route → 503) | do not set by hand | | `NEXT_RUNTIME` | set by Next | `instrumentation.ts` checks for `nodejs`; missing (scripts, seed) → `buildRevalidateHook` does not revalidate | do not set by hand | diff --git a/reference/.agents/skills/ipal-reference/resources/api.md b/reference/.agents/skills/ipal-reference/resources/api.md index fe2efea..7c087f6 100644 --- a/reference/.agents/skills/ipal-reference/resources/api.md +++ b/reference/.agents/skills/ipal-reference/resources/api.md @@ -1,7 +1,7 @@ # ipal-kit — export index Every public export of `@intecion/ipal-kit` (all entries: root, `/client`, `/rsc`, -`/server`, `/seed`, `/next/middleware`, `/admin`, `/env`, `/blocks`, `/blocks/rsc`, `/templates`, `/tokens`), grouped by module. Search with grep +`/server`, `/seed`, `/next/middleware`, `/admin`, `/env`, `/blocks`, `/blocks/rsc`, `/templates`, `/tokens`, `/doctor`), grouped by module. Search with grep (`grep -n "name" .agents/skills/ipal-reference/resources/api.md`) before you write anything yourself. "Import from" column — the first entry is preferred. Plugin options, env, routes and what the project wires: `../SKILL.md`. Module details: `node_modules/@intecion/ipal-kit/docs/<page>.md`. @@ -759,10 +759,34 @@ CSS: `@intecion/ipal-kit/tokens.css` (neutral `--ipal-*` defaults, light/dark, ` | `ipalVar(name, fallback?)` | `@intecion/ipal-kit/tokens`, `@intecion/ipal-kit` | `var(--ipal-<name>[, fallback])`. | | `IPAL_BREAKPOINTS` | `@intecion/ipal-kit/tokens`, `@intecion/ipal-kit` | `{ sm: 40, md: 48, lg: 64, xl: 80, '2xl': 96 }` (rem) — for `sizes=` / `matchMedia`. | | `COLOR_DEFAULTS`, `STATIC_DEFAULTS`, `FLUID_TOKENS`, `INVERSE_SCOPE`, `LEGACY_DARK_ROLES` | `@intecion/ipal-kit/tokens` | The catalogue: colour defaults per theme, theme-independent defaults, fluid names, inverse re-map, the old `-dark` twins. | -| `DARK_SELECTOR`, `INVERSE_SELECTOR` | `@intecion/ipal-kit/tokens` | `:root[data-theme="dark"]`, `[data-surface="inverse"]`. | +| `LIGHT_SELECTOR`, `DARK_SELECTOR`, `INVERSE_SELECTOR` | `@intecion/ipal-kit/tokens` | `:root, [data-theme="light"]`, `:root[data-theme="dark"], [data-theme="dark"]` (a theme on any element), `[data-surface="inverse"]`. | **Types:** `TokensInput`, `IpalTokenName` (root, `/tokens`), `ColorInput`, `ColorRole`, `ContrastRow`, `FluidRange`, `RemValue` (`/tokens`). +## ipal-doctor (`doctor`) — details: `node_modules/@intecion/ipal-kit/docs/doctor.md` + +Bin: `ipal-doctor` (`pnpm exec ipal-doctor [dir] [--json] [--md] [--strict] [--fail-on] [--offline] [--url] [--staging] +[--admin-route] [--deep] [--env-file] [--only] [--skip] [--sites]`). `@intecion/ipal-kit/doctor` is Node only. + +| Export | Import from | What it does / when | +|---|---|---| +| `runDoctor(options)` | `@intecion/ipal-kit/doctor` | Runs every rule on one project folder → `DoctorReport` (schema 1). Options: `root`, `packageRoot`, `offline`, `url`, `staging`, `adminRoute`, `deep`, `deepStatus`, `envFile`, `only`, `skip`, `rules`, `config`, `today`, `writeSeen`. Never throws for a failing rule. | +| `runDoctorCli(argv, { packageRoot, cwd?, log? })` | `@intecion/ipal-kit/doctor` | The command; returns the exit code (0 / 1 / 2 / 3). `parseDoctorArgs`, `expandSites` (`'../*-web'`), `DOCTOR_USAGE`. | +| `doctorRules` | `@intecion/ipal-kit/doctor` | Every built-in rule (`DoctorRule`: `id`, `group`, `source`, `docs`, `check(ctx)`) — filter, wrap or extend; own rules through `extraRules` in `ipal-doctor.json`. | +| `applySettings(findings, ctx)`, `globToRegExp(glob)`, `AUDIT_SKIP_RULES` | `@intecion/ipal-kit/doctor` | `ipal-doctor.json` `rules` (`off`, `severity`, `reason`, `until`, `files`) and `ipal-audit-skip` lines applied to findings. | +| `createDoctorContext(options)`, `loadDoctorConfig(root)`, `parseEnvFile(text)`, `readAuditSkips(agentsMd)`, `bareHost(url)` | `@intecion/ipal-kit/doctor` | What a rule reads about the project (files only, values never leave it). | +| `formatReport(report, { color })`, `formatDriftTable(reports)` | `@intecion/ipal-kit/doctor` | Human report; the rule × site Markdown table. | +| `planSkills({ dest, source })` | `@intecion/ipal-kit/doctor` | What `ipal-skills` would change: `missing`, `stale`, `retired` ipal-* folders. | +| `parseToolOutput(text)`, `AUDIT_RULE_MAP` | `@intecion/ipal-kit/doctor` | Reads `[ERROR] title (n) — rule` output of `audit.sh` / `seo-check.mjs`; audit titles that are a doctor rule. | +| `DEFAULT_SRC_ALLOW` | `@intecion/ipal-kit/doctor` | Top-level `src/` entries the convention allows (`layout.allow` extends it). | +| `createLiveFetcher(url, { adminRoute, staging })` | `@intecion/ipal-kit/doctor` | Cached GET-only fetcher for the live rules. | +| `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. | +| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. | +| `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IPAL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `ipalKit` unless `doctor: false`. | + +**Types:** `DoctorRule`, `DoctorFinding`, `RuleFinding`, `DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`, +`DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`. + ## Turnstile (`turnstile`) — details: `node_modules/@intecion/ipal-kit/docs/turnstile.md` | Export | Import from | What it does / when | diff --git a/reference/.agents/skills/ipal-seo-check/scripts/seo-check.mjs b/reference/.agents/skills/ipal-seo-check/scripts/seo-check.mjs index 5514ea8..56cec8a 100644 --- a/reference/.agents/skills/ipal-seo-check/scripts/seo-check.mjs +++ b/reference/.agents/skills/ipal-seo-check/scripts/seo-check.mjs @@ -136,7 +136,9 @@ for (const url of sample) { if (!title) issues.title.push(url) else { if (title.length > 65) issues.longTitle.push(`${url} (${title.length} chars)`) - titles.set(title, [...(titles.get(title) ?? []), url]) + // per language: the same word in two languages ("Blog" in pl and en) is not a duplicate + const key = `${multiLocale ? localeOf(url) : ''}\u0000${title}` + titles.set(key, [...(titles.get(key) ?? []), url]) } const desc = tags(head, /<meta[^>]+name="description"[^>]*>/gi).map((t) => attr(t, 'content'))[0]?.trim() if (!desc) issues.desc.push(url) @@ -196,7 +198,7 @@ for (const url of sample) { } } -const dupTitles = [...titles.entries()].filter(([, us]) => us.length > 1).map(([t, us]) => `"${t}" × ${us.length}`) +const dupTitles = [...titles.entries()].filter(([, us]) => us.length > 1).map(([k, us]) => `"${k.split('\u0000')[1]}" × ${us.length}`) const dupDescs = [...descriptions.entries()].filter(([, us]) => us.length > 1).map(([d, us]) => `"${d.slice(0, 60)}…" × ${us.length}`) if (issues.status.length) report('ERROR', 'sitemap URLs not 200 (redirect / error)', 'sitemap must list final, live URLs', issues.status) if (issues.noHead.length) report('ERROR', 'no </head> in HTML', 'broken document', issues.noHead) diff --git a/reference/.agents/skills/ipal-setup/SKILL.md b/reference/.agents/skills/ipal-setup/SKILL.md index ecbf46f..3f9ba30 100644 --- a/reference/.agents/skills/ipal-setup/SKILL.md +++ b/reference/.agents/skills/ipal-setup/SKILL.md @@ -8,6 +8,10 @@ description: Complete start-to-finish install of @intecion/ipal-kit in a Payload **Goal: the MANDATORY SET from AGENT.md §0b (18 items), with nothing left "to discover".** Stage 11 checks everything; you do not finish with gaps (exception: an `ipal-audit-skip:` line from a client decision, AGENT.md §0b). +**Canonical code:** every stage's files exist, wired and tested, in the reference site — +`node_modules/@intecion/ipal-kit/docs/agent/reference-site/INDEX.md` (AGENT.md "Reference site"). When a snippet here +and the reference site differ, the reference site is the current one (and the difference is a plugin bug to report). + **Stage 0 first: ask the architecture questions and wait for the answers** (below). After that: **one stage = one commit** (`git commit -m "ipal-setup <N>: <stage>"`), no waiting for an OK between stages (AGENT.md §0a). Missing *content data* (keys, IDs, company data) does not block you: wire the code, the value goes into `.env`/the panel @@ -533,6 +537,7 @@ bash .agents/skills/ipal-audit/scripts/audit.sh # full: §0b "missing pnpm build && pnpm start node .agents/skills/ipal-seo-check/scripts/seo-check.mjs http://localhost:3000 # 0 errors node .agents/skills/ipal-consent-check/scripts/consent-check.mjs http://localhost:3000/pl +pnpm exec ipal-doctor --strict --offline --deep --url http://localhost:3000 # the team standard (skill ipal-doctor) ``` The §0b list with its checks: proxy + catch-all + 404 (stage 6) · meta, sitemap, robots, manifest (7) · JSON-LD (6, 10) · llms, llms-full, Markdown, MCP, AI bots, IndexNow (8) · Media/R2 (3–4) · seeded forms (9) · Turnstile (9) · diff --git a/reference/.agents/skills/ipal-site/SKILL.md b/reference/.agents/skills/ipal-site/SKILL.md index f8a832f..b56f016 100644 --- a/reference/.agents/skills/ipal-site/SKILL.md +++ b/reference/.agents/skills/ipal-site/SKILL.md @@ -45,7 +45,9 @@ decision on that part; no hand-built replacement, no silent workaround. **Code r decision (AGENT §0a) and on a plugin gap (ipal-plugin-gap — report, wait for the owner). ## Phase 1 — Foundation -- New project → **ipal-setup** (all of it, with `ipal-skills`, `AGENTS.md`). +- New project → **ipal-setup** (all of it, with `ipal-skills`, `AGENTS.md`). Every file you wire has its canonical + version in the reference site: `node_modules/@intecion/ipal-kit/docs/agent/reference-site/INDEX.md` (AGENT.md + "Reference site") — copy the pattern, change only the content. - Existing project on an older ipal-kit → **ipal-upgrade** before anything else. - Exit: `pnpm build` passes, `/admin` works, `ipal-audit --quick` = 0 errors — **including zero "missing: …"**, i.e. the full AGENT.md §0b set (SEO, GEO, R2, Turnstile, @@ -66,6 +68,8 @@ decision on that part; no hand-built replacement, no silent workaround. **Code r ## Phase 3 — Navigation and company data → **ipal-nav** ## Phase 4 — Sections → **ipal-block** for every block +The reference site's Blocks page (`/pl/bloki` on the reference site, seed `src/seed/showcase.ts` in the index) shows +every library block in every variant, also on the inverted background — pick the closest block × variant there. Library blocks need no code: `libraryBlocks(blockOptions)` in the Pages layout and `createBlockRegistry(content, { Image, Link, sendForm })` in `src/blocks/registry.ts` (docs/block-library.md "Setup"). Change looks through `classNames` / `ui`, never by copying a block; own it completely only with `ipal-blocks eject <block>`. @@ -116,6 +120,8 @@ title/description of every page (≤ 60 / ≤ 155 characters, unique); `aiSummar keep the auto-fill or fix it when the summary is weak. ## Phase 8 — Design +The reference site's `/design` page (`src/components/design/TokenPanel.tsx` in the index) is the styleguide to reproduce: +every token from `IPAL_TOKENS`, light and dark, the inverse scope. The design-token standard (AGENT.md §6.11, `design-tokens.md`): `DESIGN.md` exists → its values go into `src/design/tokens.ts` (template `.agents/skills/ipal-setup/resources/tokens.ts`) → `pnpm exec ipal-tokens` (no ✗ contrast rows). None → copy the `DESIGN.md` template, keep the neutral defaults + the brand primary, and recommend diff --git a/reference/.agents/skills/ipal-upgrade/SKILL.md b/reference/.agents/skills/ipal-upgrade/SKILL.md index d7ab9ee..022b0d8 100644 --- a/reference/.agents/skills/ipal-upgrade/SKILL.md +++ b/reference/.agents/skills/ipal-upgrade/SKILL.md @@ -197,6 +197,9 @@ and the browser tab shows the same separator. consent: `pnpm exec ipal-skills --external`. ## 2. Inventory (no code changes) +**What changed for projects** between your old and new plugin version is exactly the reference site's diff — +`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files): +every file a project must touch, already done once and tested in the plugin's CI. For **every** item in the PROGRAMISTA §6 table show evidence (grep / file) of whether it applies to the project. Run the **ipal-audit** skill (`--quick`) and attach the result. Result: a prioritised to-do list — carry it out right away. Stop @@ -214,4 +217,8 @@ need a **data migration before** the old fields are removed — ask the user whether the project already has content. ## 4. Finish -A full **ipal-audit** with no errors + a list of things to check in the admin panel. +A full **ipal-audit** with no errors, then `pnpm exec ipal-doctor` (after `pnpm exec ipal-skills` and +`pnpm payload generate:importmap`): no new errors against the report before the upgrade (skill **ipal-doctor**; +new rules come with new versions — read each finding, fix or record the owner's decision in `ipal-doctor.json` with a +reason). Before the upgrade, `pnpm dlx --package=@intecion/ipal-kit@latest ipal-doctor --offline` shows what the newest +rules will report. Then the list of things to check in the admin panel. diff --git a/reference/ipal-doctor.json b/reference/ipal-doctor.json index e2ba037..9569ca2 100644 --- a/reference/ipal-doctor.json +++ b/reference/ipal-doctor.json @@ -1,4 +1,17 @@ { "domain": "example-studio.pl", - "launched": false + "launched": false, + "rules": { + "audit:collections-present": { + "off": true, + "reason": "Project decisions: posts and caseStudies with archive pages; entryFields.ts is their shared field helper, not a collection" + }, + "i18n-literals": { + "off": true, + "files": [ + "src/components/design/**" + ], + "reason": "Approved exception (AGENTS.md → Project decisions): the /design styleguide has its labels in code" + } + } } diff --git a/reference/package.json b/reference/package.json index 16941c8..515f4d7 100644 --- a/reference/package.json +++ b/reference/package.json @@ -7,6 +7,7 @@ "engines": { "node": ">=22 <23" }, + "packageManager": "pnpm@10.34.3", "scripts": { "dev": "next dev", "build": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" next build --webpack", diff --git a/reference/src/collections/Pages.ts b/reference/src/collections/Pages.ts index cd8879b..eaa4e04 100644 --- a/reference/src/collections/Pages.ts +++ b/reference/src/collections/Pages.ts @@ -6,6 +6,7 @@ import { buildRevalidateHook, buildSlugField, buildSummaryField, + rowLabel, trackSlugHistoryHook, } from '@intecion/ipal-kit' import { revalidatePath } from 'next/cache' @@ -25,7 +26,7 @@ export const Pages: CollectionConfig = { { name: 'layout', type: 'blocks', blocks: pageBlocks, minRows: 1 }, buildSummaryField(), // aiSummary — GEO (llms.txt, MCP) buildNoindexField(), - { name: 'slugHistory', type: 'array', admin: { readOnly: true }, fields: [{ name: 'slug', type: 'text' }] }, + { name: 'slugHistory', type: 'array', admin: { components: rowLabel('slug', 'Old address'), readOnly: true }, fields: [{ name: 'slug', type: 'text' }], labels: { plural: 'Old addresses', singular: 'Old address' } }, ], hooks: { afterChange: [revalidate.afterChange], diff --git a/reference/src/components/layout/Footer.tsx b/reference/src/components/layout/Footer.tsx index 3508fa2..727a3ee 100644 --- a/reference/src/components/layout/Footer.tsx +++ b/reference/src/components/layout/Footer.tsx @@ -24,7 +24,7 @@ export async function Footer({ company, footer, locale }: Props) { {address ? <p className="text-fg-muted">{address}</p> : null} {company.phone ? <a className="text-link hover:text-link-hover" href={`tel:${company.phone.replace(/[^\d+]/g, '')}`}>{company.phone}</a> : null} {company.email ? <a className="text-link hover:text-link-hover" href={`mailto:${company.email}`}>{company.email}</a> : null} - {company.taxId ? <p className="text-sm text-fg-muted">NIP {company.taxId}</p> : null} + {company.taxId ? <p className="text-sm text-fg-muted">{[company.taxIdLabel, company.taxId].filter(Boolean).join(' ')}</p> : null} </div> {columns.map((column) => ( <nav aria-label={column.heading ?? undefined} className="grid content-start gap-2" key={column.id}> diff --git a/reference/src/globals/Company.ts b/reference/src/globals/Company.ts index 42b2b0f..59f22a5 100644 --- a/reference/src/globals/Company.ts +++ b/reference/src/globals/Company.ts @@ -1,6 +1,6 @@ import type { GlobalConfig } from 'payload' -import { buildGlobalRevalidateHook } from '@intecion/ipal-kit' +import { buildGlobalRevalidateHook, rowLabel } from '@intecion/ipal-kit' import { revalidatePath } from 'next/cache' /** Company data for a PL market site: footer, contact block details, LocalBusiness JSON-LD. */ @@ -11,6 +11,7 @@ export const Company: GlobalConfig = { { name: 'name', type: 'text', required: true }, { name: 'legalName', type: 'text' }, { name: 'taxId', type: 'text', label: 'NIP' }, + { name: 'taxIdLabel', type: 'text', admin: { description: 'Shown before the tax ID in the footer.' }, defaultValue: 'NIP', label: 'Tax ID label', localized: true }, { name: 'address', type: 'group', @@ -27,6 +28,8 @@ export const Company: GlobalConfig = { { name: 'socials', type: 'array', + admin: { components: rowLabel('label', 'Profile'), initCollapsed: true }, + labels: { plural: 'Profiles', singular: 'Profile' }, fields: [ { name: 'label', type: 'text', required: true }, { name: 'url', type: 'text', required: true }, diff --git a/reference/src/instrumentation.ts b/reference/src/instrumentation.ts index 6836eb0..9b38734 100644 --- a/reference/src/instrumentation.ts +++ b/reference/src/instrumentation.ts @@ -4,10 +4,11 @@ export function register() { if (process.env.NEXT_RUNTIME !== 'nodejs') {return} // storage: R2 is required in production. ALLOW_LOCAL_MEDIA=1 lets a production build run on local disk for // local checks and CI only — never set it in Coolify. + // cookieCrawl: IPAL_COOKIE_SCAN_URL / IPAL_COOKIE_SCAN_TOKEN in production (cookieScanner.crawl, the shared service). // databaseName: DATABASE_URI must name example-studiopl_dev / example-studiopl_prod (databaseNamesFor). // R2_PUBLIC_URL optional: media are served through the app by default (storage.md, env.md). assertEnv( - ipalEnvRules({ databaseName: { domain: 'example-studio.pl' }, ipHeader: true, storage: process.env.ALLOW_LOCAL_MEDIA !== '1' }).map((rule) => + ipalEnvRules({ cookieCrawl: true, databaseName: { domain: 'example-studio.pl' }, ipHeader: true, storage: process.env.ALLOW_LOCAL_MEDIA !== '1' }).map((rule) => rule.name === 'R2_PUBLIC_URL' ? { ...rule, required: false } : rule, ), ) diff --git a/reference/src/payload-types.ts b/reference/src/payload-types.ts index 3e75de0..583c493 100644 --- a/reference/src/payload-types.ts +++ b/reference/src/payload-types.ts @@ -2486,6 +2486,10 @@ export interface Company { name: string; legalName?: string | null; taxId?: string | null; + /** + * Shown before the tax ID in the footer. + */ + taxIdLabel?: string | null; address?: { street?: string | null; postalCode?: string | null; @@ -2986,6 +2990,7 @@ export interface CompanySelect<T extends boolean = true> { name?: T; legalName?: T; taxId?: T; + taxIdLabel?: T; address?: | T | { diff --git a/src/exports/doctor.ts b/src/exports/doctor.ts new file mode 100644 index 0000000..f07fd38 --- /dev/null +++ b/src/exports/doctor.ts @@ -0,0 +1,30 @@ +/** + * Entry point: @intecion/ipal-kit/doctor + * + * ipal-doctor's building blocks — the rules, the runner, the formatters and the status + * collector — for a project that wants to wrap, filter or extend the checks (docs/doctor.md). + * Node only (reads files, runs commands). The command itself: `pnpm exec ipal-doctor`. + */ +export { DOCTOR_USAGE, expandSites, parseDoctorArgs, runDoctorCli } from '../modules/doctor/cli.js' +export { formatDriftTable, formatReport } from '../modules/doctor/format.js' +export { bareHost, createDoctorContext, loadDoctorConfig, parseEnvFile, readAuditSkips } from '../modules/doctor/project.js' +export type { DoctorContext } from '../modules/doctor/project.js' +export { planSkills } from '../modules/doctor/rules/agents.js' +export { DEFAULT_SRC_ALLOW } from '../modules/doctor/rules/layout.js' +export { createLiveFetcher } from '../modules/doctor/rules/live.js' +export { AUDIT_RULE_MAP, parseToolOutput } from '../modules/doctor/rules/tooling.js' +export { applySettings, AUDIT_SKIP_RULES, doctorRules, globToRegExp, runDeepProbe, runDoctor } from '../modules/doctor/run.js' +export type { RunDoctorOptions } from '../modules/doctor/run.js' +export { buildDoctorEndpoint, collectDoctorStatus } from '../modules/doctor/status.js' +export type { DoctorEndpointOptions } from '../modules/doctor/status.js' +export type { + DoctorConfig, + DoctorFinding, + DoctorReport, + DoctorRule, + DoctorRuleSetting, + DoctorSeverity, + DoctorSource, + DoctorStatus, + RuleFinding, +} from '../modules/doctor/types.js' diff --git a/src/modules/doctor/cli.ts b/src/modules/doctor/cli.ts new file mode 100644 index 0000000..34983e9 --- /dev/null +++ b/src/modules/doctor/cli.ts @@ -0,0 +1,148 @@ +import { existsSync, readdirSync, statSync } from 'node:fs' +import { basename, dirname, join, resolve } from 'node:path' + +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. + + --json machine-readable report (schema 1) + --md Markdown table (with --sites: rule × site) + --strict any unsilenced finding fails (= --fail-on info) + --fail-on <level> error (default) | warning | info + --offline skip the registry rules (latest plugin, pnpm audit) + --url <url> also check the running site (headers, robots, sitemap, admin, noindex, SEO) + --staging with --url: the site is a staging copy and must be noindex + --admin-route <path> with --url: the panel path (default /admin) + --deep read-only database checks through \`pnpm exec payload run\` (needs DATABASE_URI) + --env-file <file> a production env export: its DATABASE_URI must name <domain>_prod + --only <ids,groups> run only these rules or groups + --skip <ids,groups> leave these out + --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` + +const RANK: Record<DoctorSeverity, number> = { error: 3, info: 1, warning: 2 } + +type Args = { + adminRoute?: string + deep: boolean + dir: string + envFile?: string + failOn: DoctorSeverity + json: boolean + md: boolean + offline: boolean + only?: string[] + sites?: string + skip?: string[] + staging: boolean + url?: string +} + +export function parseDoctorArgs(argv: string[]): Args | string { + const args: Args = { deep: false, dir: '.', failOn: 'error', json: false, md: false, offline: false, staging: false } + const value = (i: number, name: string) => { + const v = argv[i + 1] + if (!v || v.startsWith('--')) {throw new Error(`${name} needs a value`)} + return v + } + try { + for (let i = 0; i < argv.length; i++) { + const a = argv[i] + switch (a) { + case '--admin-route': args.adminRoute = value(i++, a); break + case '--deep': args.deep = true; break + case '--env-file': args.envFile = value(i++, a); break + case '--fail-on': { + const level = value(i++, a) + if (!(level in RANK)) {return `--fail-on takes error, warning or info (got "${level}")`} + args.failOn = level as DoctorSeverity + break + } + case '--json': args.json = true; break + case '--md': args.md = true; break + case '--offline': args.offline = true; break + case '--only': args.only = value(i++, a).split(','); break + case '--sites': args.sites = value(i++, a); break + case '--skip': args.skip = value(i++, a).split(','); break + case '--staging': args.staging = true; break + case '--strict': args.failOn = 'info'; break + case '--url': args.url = value(i++, a); break + default: + if (a.startsWith('-')) {return `unknown option ${a}`} + args.dir = a + } + } + } catch (err) { + return err instanceof Error ? err.message : String(err) + } + return args +} + +/** `../*-web` → the matching folders (one `*` in the last segment). */ +export function expandSites(pattern: string, cwd: string): string[] { + const full = resolve(cwd, pattern) + const base = basename(full) + if (!base.includes('*')) {return existsSync(full) ? [full] : []} + const dir = dirname(full) + const re = new RegExp(`^${base.split('*').map((p) => p.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`) + return readdirSync(dir).filter((n) => re.test(n) && statSync(join(dir, n)).isDirectory()).sort().map((n) => join(dir, n)) +} + +const failed = (r: DoctorReport, failOn: DoctorSeverity) => + r.findings.some((f) => !f.silenced && RANK[f.severity] >= RANK[failOn]) + +/** The whole command; returns the exit code. */ +export async function runDoctorCli(argv: string[], { cwd = process.cwd(), log = (line: string) => process.stdout.write(`${line}\n`), packageRoot }: { cwd?: string; log?: (s: string) => void; packageRoot: string }): Promise<number> { + if (argv.includes('--help') || argv.includes('-h')) { + log(DOCTOR_USAGE) + return 0 + } + const args = parseDoctorArgs(argv) + if (typeof args === 'string') { + console.error(`ipal-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}`) + 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)`) + if (!args.sites) {return 2} + continue + } + reports.push( + await runDoctor({ + adminRoute: args.adminRoute, + deep: args.deep, + envFile: args.envFile ? resolve(cwd, args.envFile) : undefined, + offline: args.offline, + only: args.only, + packageRoot, + root: dir, + skip: args.skip, + staging: args.staging, + url: args.sites ? undefined : args.url, + writeSeen: !args.sites && !args.json, + }), + ) + } + if (args.json) {log(JSON.stringify(args.sites ? reports : reports[0], null, 2))} + else if (args.md || args.sites) {log(formatDriftTable(reports))} + else {log(formatReport(reports[0], { color: !!process.stdout.isTTY && !process.env.NO_COLOR }))} + + if (args.sites) {return 0} // a report, never a gate (D7) + const report = reports[0] + if (report.findings.some((f) => f.rule === 'doctor-crash')) {return 3} + if (report.findings.some((f) => f.rule === 'doctor-config' && f.severity === 'error' && /not valid JSON|must hold an object/.test(f.message))) {return 2} + return failed(report, args.failOn) ? 1 : 0 +} diff --git a/src/modules/doctor/format.ts b/src/modules/doctor/format.ts new file mode 100644 index 0000000..06bf319 --- /dev/null +++ b/src/modules/doctor/format.ts @@ -0,0 +1,46 @@ +import type { DoctorReport, DoctorSeverity } from './types.js' + +const MARK: Record<DoctorSeverity, string> = { error: '✗', info: 'i', warning: '!' } +const COLOR: Record<DoctorSeverity, string> = { error: '\x1b[31m', info: '\x1b[36m', warning: '\x1b[33m' } + +const summaryLine = (r: DoctorReport) => + `${r.summary.error} error(s), ${r.summary.warning} warning(s), ${r.summary.info} info${r.summary.silenced ? ` (${r.summary.silenced} silenced)` : ''}` + +/** 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 active = report.findings.filter((f) => !f.silenced) + if (!active.length) {lines.push('No findings.')} + for (const f of active) { + lines.push(c(f.severity, `${MARK[f.severity]} [${f.severity}] ${f.rule}: ${f.message}`)) + if (f.file) {lines.push(` file: ${f.file}`)} + if (f.fix) {lines.push(` fix: ${f.fix}`)} + if (f.docs) {lines.push(` docs: node_modules/@intecion/ipal-kit/${f.docs}`)} + } + const silenced = report.findings.filter((f) => f.silenced) + if (silenced.length) { + lines.push('', 'Silenced:') + 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)}`) + return lines.join('\n') +} + +const cell = (report: DoctorReport, rule: string) => { + const hits = report.findings.filter((f) => !f.silenced && (f.rule === rule || f.rule.startsWith(`${rule}:`))) + if (!hits.length) {return report.findings.some((f) => f.silenced && f.rule === rule) ? 'silenced' : '✅'} + const worst = hits.some((f) => f.severity === 'error') ? '❌' : hits.some((f) => f.severity === 'warning') ? '⚠️' : 'ℹ️' + return `${worst} ${hits.length > 1 ? hits.length : ''}`.trim() +} + +/** One Markdown table: rule × site (the drift sweep, `--sites … --md`). */ +export function formatDriftTable(reports: DoctorReport[]): string { + const name = (r: DoctorReport) => r.site.path.split('/').filter(Boolean).at(-1) ?? r.site.path + const rules = [...new Set(reports.flatMap((r) => r.findings.map((f) => f.rule.split(':')[0])))].sort() + const head = `| Rule | ${reports.map(name).join(' | ')} |` + const sep = `|---|${reports.map(() => '---').join('|')}|` + const totals = `| **errors / warnings / info** | ${reports.map((r) => `${r.summary.error} / ${r.summary.warning} / ${r.summary.info}`).join(' | ')} |` + return [head, sep, totals, ...rules.map((rule) => `| \`${rule}\` | ${reports.map((r) => cell(r, rule)).join(' | ')} |`)].join('\n') +} diff --git a/src/modules/doctor/probe.ts b/src/modules/doctor/probe.ts new file mode 100644 index 0000000..55188d9 --- /dev/null +++ b/src/modules/doctor/probe.ts @@ -0,0 +1,71 @@ +import type { SanitizedConfig } from 'payload' + +/** + * ipal-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. + * + * 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. + */ +import { existsSync, readFileSync, rmSync } from 'node:fs' +import { dirname, join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' + +import type { DoctorStatus } from './types.js' + +import { collectDoctorStatus, pluginVersion } from './status.js' + +const root = process.cwd() +const status: DoctorStatus = { node: process.version, plugin: pluginVersion() } +const normalize = (text: string) => text.replace(/\s+/g, ' ').trim() + +async function main() { + const configPath = resolve(root, process.env.PAYLOAD_CONFIG_PATH ?? (existsSync(join(root, 'src/payload.config.ts')) ? 'src/payload.config.ts' : 'payload.config.ts')) + + // The project's env rules first: they are what production would refuse to start with. + const instrumentation = ['src/instrumentation.ts', 'instrumentation.ts'].map((f) => join(root, f)).find((f) => existsSync(f)) + if (instrumentation) { + const before = process.env.NEXT_RUNTIME + process.env.NEXT_RUNTIME = 'nodejs' + try { + const mod = (await import(pathToFileURL(instrumentation).href)) as { register?: () => unknown } + await mod.register?.() + status.envProblems = [] + } catch (err) { + const message = err instanceof Error ? err.message : String(err) + status.envProblems = message.split('\n').map((l) => l.match(/^\s*•\s*([A-Z][A-Z0-9_]+)/)?.[1]).filter((n): n is string => !!n) + if (!status.envProblems.length) {status.envProblems = [message.split('\n')[0] ?? 'env check failed']} + } finally { + process.env.NEXT_RUNTIME = before + } + } + + const { generateImportMap, getPayload } = await import('payload') + const config = await (await import(pathToFileURL(configPath).href) as { default: Promise<SanitizedConfig> }).default + const payload = await getPayload({ config }) + 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) : '') + if (committed && existsSync(committed)) { + const temp = join(dirname(committed), 'importMap.ipal-doctor.tmp.js') + try { + const copy = { ...config, admin: { ...config.admin, importMap: { ...config.admin.importMap, importMapFile: temp } } } + await generateImportMap(copy, { force: true, log: false }) + status.importMapCurrent = normalize(readFileSync(temp, 'utf8')) === normalize(readFileSync(committed, 'utf8')) + } catch { + status.importMapCurrent = null + } finally { + rmSync(temp, { force: true }) + } + } +} + +try { + await main() +} 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.exit(0) diff --git a/src/modules/doctor/project.ts b/src/modules/doctor/project.ts new file mode 100644 index 0000000..d340a01 --- /dev/null +++ b/src/modules/doctor/project.ts @@ -0,0 +1,195 @@ +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs' +import { basename, join, relative } from 'node:path' + +import type { DoctorConfig, DoctorLive, DoctorStatus } from './types.js' + +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. */ + auditSkips: Map<string, string> + config: DoctorConfig + configError: null | string + /** Status from the deep check (payload run or the endpoint), or null. */ + deep: DoctorStatus | null + deps: Record<string, string> + /** Site domain without protocol and `www.` (dots kept), or null. */ + domain: null | string + /** Parsed `.env` / `.env.example` (null when the file is missing). Values never leave the doctor. */ + env: { example: null | Record<string, string>; local: null | Record<string, string>; prod: null | Record<string, string> } + exists: (rel: string) => boolean + /** The project's import map, relative path, or null. */ + importMap: null | string + /** Installed version of a package in the project's node_modules, or null. */ + installed: (name: string) => null | string + launched: boolean + list: (rel: string) => string[] + live: DoctorLive | null + offline: boolean + /** The doctor's own package root (bin, docs, dist). */ + packageRoot: string + pkg: { engines?: Record<string, string>; packageManager?: string; scripts?: Record<string, string> } & Record<string, unknown> + pluginVersion: null | string + read: (rel: string) => string + root: string + rulesVersion: string + /** 'src/' when the project uses a src folder, else ''. */ + src: string + /** Today's date (ISO, yyyy-mm-dd) — injectable for tests. */ + today: string +} + +export type ProjectOptions = { + config?: DoctorConfig + deep?: DoctorStatus | null + /** A production env export (--env-file), absolute path. */ + envFile?: string + live?: DoctorLive | null + offline?: boolean + packageRoot: string + root: string + today?: string +} + +/** KEY=value lines; quotes stripped, comments and blanks skipped. */ +export function parseEnvFile(text: string): Record<string, string> { + const out: Record<string, string> = {} + for (const line of text.split(/\r?\n/)) { + const m = line.trim().match(/^(?:export\s+)?([A-Z_]\w*)\s*=(.*)$/i) + if (!m) {continue} + out[m[1]] = m[2].trim().replace(/^(['"])(.*)\1$/, '$2') + } + return out +} + +/** Bare host of a domain or URL: `https://www.Example.pl/` → `example.pl`. */ +export function bareHost(value: string): string { + return value.trim().toLowerCase().replace(/^[a-z][a-z\d+.-]*:\/\//, '').replace(/[/:?#].*$/, '').replace(/^www\./, '') +} + +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). */ +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) + if (!m) {continue} + const [keys = '', ...rest] = m[1].trim().split(/\s+—\s+|\s+-\s+/) + const reason = rest.join(' — ').trim() + for (const key of keys.split(',').map((k) => k.trim()).filter(Boolean)) {out.set(key, reason)} + } + return out +} + +export function loadDoctorConfig(root: string): { config: DoctorConfig; error: null | string } { + const file = join(root, 'ipal-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' }} + 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)})` } + } +} + +export function createDoctorContext(options: ProjectOptions): DoctorContext { + const { packageRoot, root } = options + const abs = (rel: string) => join(root, rel) + const exists = (rel: string) => existsSync(abs(rel)) + const read = (rel: string) => { + try { + return statSync(abs(rel)).isFile() ? readFileSync(abs(rel), 'utf8') : '' + } catch { + return '' + } + } + const list = (rel: string) => { + try { + return readdirSync(abs(rel)).filter((n) => n !== '.DS_Store') + } catch { + return [] + } + } + const installed = (name: string) => { + try { + return (JSON.parse(readFileSync(abs(join('node_modules', name, 'package.json')), 'utf8')) as { version?: string }).version ?? null + } catch { + return null + } + } + + let pkg: DoctorContext['pkg'] = {} + try { + pkg = JSON.parse(read('package.json') || '{}') as DoctorContext['pkg'] + } catch { + pkg = {} + } + const deps = { ...(pkg.dependencies as Record<string, string> | undefined), ...(pkg.devDependencies as Record<string, string> | undefined) } + const loaded = options.config ? { config: options.config, error: null } : loadDoctorConfig(root) + const config = loaded.config + const env = { + example: exists('.env.example') ? parseEnvFile(read('.env.example')) : null, + local: exists('.env') ? parseEnvFile(read('.env')) : null, + prod: options.envFile && existsSync(options.envFile) ? parseEnvFile(readFileSync(options.envFile, 'utf8')) : null, + } + const src = exists('src') ? 'src/' : '' + + // Domain: ipal-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$/, '') + const domain = config.domain ? bareHost(config.domain) : (urls.find((h) => !isLocalHost(h)) ?? (fromDir.includes('.') ? fromDir : null)) + + const agents = read('AGENTS.md') + const launchedInAgents = /^[-* ][^\n]*?launch(?:ed)?[^\n]*?\d{4}-\d{2}-\d{2}/im.test(agents.split(/^## Project decisions\s*$/m)[1] ?? '') + + const adminDir = list(`${src}app/(payload)`).find((d) => exists(`${src}app/(payload)/${d}/importMap.js`)) + const rulesVersion = (() => { + try { + return (JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')) as { version: string }).version + } catch { + return '0.0.0' + } + })() + + return { + auditSkips: readAuditSkips(agents), + config, + configError: loaded.error, + deep: options.deep ?? null, + deps, + domain, + env, + exists, + importMap: adminDir ? `${src}app/(payload)/${adminDir}/importMap.js` : null, + installed, + launched: config.launched ?? launchedInAgents, + list, + live: options.live ?? null, + offline: options.offline ?? false, + packageRoot, + pkg, + pluginVersion: installed('@intecion/ipal-kit'), + read, + root, + rulesVersion, + src, + today: options.today ?? new Date().toISOString().slice(0, 10), + } +} + +/** First file of the list that exists, or null. */ +export function firstExisting(ctx: DoctorContext, files: string[]): null | string { + return files.find((f) => ctx.exists(f)) ?? null +} + +export const configFile = (ctx: DoctorContext) => firstExisting(ctx, [`${ctx.src}payload.config.ts`, 'payload.config.ts']) +export const nextConfigFile = (ctx: DoctorContext) => firstExisting(ctx, ['next.config.ts', 'next.config.mjs', 'next.config.js']) + +/** The database name in a `.env` value, never the rest of the URI. */ +export const databaseOf = (uri: string | undefined) => databaseNameFromUri(uri) + +/** Relative path for messages. */ +export const rel = (ctx: DoctorContext, path: string) => relative(ctx.root, path) || '.' diff --git a/src/modules/doctor/rules/agents.ts b/src/modules/doctor/rules/agents.ts new file mode 100644 index 0000000..a78ab0e --- /dev/null +++ b/src/modules/doctor/rules/agents.ts @@ -0,0 +1,85 @@ +import { createHash } from 'node:crypto' +import { readdirSync, readFileSync, statSync } from 'node:fs' +import { join } from 'node:path' + +import type { DoctorRule, RuleFinding } from '../types.js' + +/** Content hash of a folder (names + bytes), so two copies of a skill compare equal. */ +export function hashDir(dir: string): string { + const hash = createHash('sha256') + const walk = (d: string, prefix: string) => { + for (const name of readdirSync(d).sort()) { + if (name === '.DS_Store') {continue} + const path = join(d, name) + if (statSync(path).isDirectory()) {walk(path, `${prefix}${name}/`)} + else {hash.update(`${prefix}${name}\0`).update(readFileSync(path))} + } + } + walk(dir, '') + return hash.digest('hex') +} + +/** What `ipal-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 { + return readdirSync(d).filter((n) => n.startsWith('ipal-') && statSync(join(d, n)).isDirectory()) + } catch { + return [] + } + } + const shipped = ls(source) + const have = ls(dest) + return { + missing: shipped.filter((n) => !have.includes(n)), + retired: have.filter((n) => !shipped.includes(n)), + stale: shipped.filter((n) => have.includes(n) && hashDir(join(dest, n)) !== hashDir(join(source, n))), + } +} + +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' }]} + 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' })} + else { + 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 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' })} + return out + }, + docs: 'docs/agent/AGENT.md#13-agentsmd-template-for-a-project', + group: 'agents', + source: 'static', + }, + { + 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). + 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 }) + const parts = [ + plan.stale.length ? `${plan.stale.length} outdated (${plan.stale.join(', ')})` : '', + 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' }] : [] + }, + docs: 'docs/agent/AGENT.md#14-skills-antigravity-claude-code-cursor', + group: 'agents', + source: 'static', + }, +] diff --git a/src/modules/doctor/rules/blocks.ts b/src/modules/doctor/rules/blocks.ts new file mode 100644 index 0000000..dde993b --- /dev/null +++ b/src/modules/doctor/rules/blocks.ts @@ -0,0 +1,137 @@ +import type { DoctorContext } from '../project.js' +import type { DoctorRule, RuleFinding } from '../types.js' + +import { stripComments } from '../util.js' +import { usesBlockRegistry } from './layout.js' + +type Manifest = { blocks: Array<{ interfaceName: string; slug: string }>; fieldBuilders: string[]; primitives: string[] } + +/** The five primitives a project without the library registry writes itself (AGENT.md §6.3). */ +const OWN_PRIMITIVES = ['Section', 'SectionHeader', 'Media', 'CMSLink', 'Button'] +/** Helpers the plugin exports that projects used to copy (not field builders, so not in the manifest). */ +const OTHER_HELPERS = ['ctaHref', 'buildActionButtonsField'] + +let manifest: Manifest | null | undefined +/** blockLibraryManifest from the plugin (plain data); null when it cannot be loaded. */ +export async function loadBlockManifest(): Promise<Manifest | null> { + if (manifest !== undefined) {return manifest} + try { + manifest = (await import('../../block-library/manifest.js')).blockLibraryManifest as Manifest + } catch { + manifest = null + } + return manifest +} + +/** Every .ts/.tsx file under a project folder (relative paths). */ +export function sourceFiles(ctx: DoctorContext, dir: string): string[] { + return ctx.list(dir).flatMap((name) => { + const path = `${dir}/${name}` + if (/\.tsx?$/.test(name)) {return [path]} + if (name.includes('.') || name === 'node_modules') {return []} + return sourceFiles(ctx, path) + }) +} + +const registry = (ctx: DoctorContext) => stripComments(ctx.read(`${ctx.src}blocks/registry.ts`)) + +/** Keys of an object literal passed as `<option>: { … }` in the registry (`ui`, `components`). */ +function optionKeys(code: string, option: string): string[] { + const body = code.match(new RegExp(`\\b${option}\\s*:\\s*\\{([^}]*)\\}`))?.[1] ?? '' + return [...body.matchAll(/(?:^|[,{\s])([A-Z_$][\w$]*)\s*(?=[:,}]|$)/gi)].map((m) => m[1]) +} + +export const blockRules: DoctorRule[] = [ + { + id: 'blocks-registry', + check: (ctx) => { + const file = `${ctx.src}blocks/registry.ts` + if (!ctx.exists(file)) {return []} // layout-required reports the missing file + const code = registry(ctx) + if (/createBlockRegistry\s*\(/.test(code) || /RenderBlocks/.test(code)) {return []} + return [{ file, fix: 'export const blockRegistry = createBlockRegistry(content, { … }) from @intecion/ipal-kit/blocks/rsc', message: 'blocks/registry.ts uses neither createBlockRegistry nor RenderBlocks', severity: 'error' }] + }, + docs: 'docs/blocks.md', + group: 'blocks', + source: 'static', + }, + { + id: 'blocks-ui-required', + check: (ctx) => { + if (usesBlockRegistry(ctx)) {return []} + const have = ctx.list(`${ctx.src}components/ui`).map((n) => n.replace(/\.tsx?$/, '')) + const missing = OWN_PRIMITIVES.filter((p) => !have.includes(p)) + return missing.length + ? [{ fix: 'use createBlockRegistry (primitives from the plugin) or write them (AGENT.md §6.3)', message: `without createBlockRegistry, components/ui/ needs ${missing.join(', ')}`, severity: 'error' }] + : [] + }, + docs: 'docs/agent/AGENT.md#63-layer-2--ui-primitives', + group: 'blocks', + source: 'static', + }, + { + id: 'blocks-ui-override', + check: async (ctx) => { + if (!usesBlockRegistry(ctx)) {return []} + const m = await loadBlockManifest() + const primitives = m?.primitives ?? OWN_PRIMITIVES + const passed = optionKeys(registry(ctx), 'ui') + const own = ctx.list(`${ctx.src}components/ui`).map((n) => n.replace(/\.tsx?$/, '')).filter((n) => primitives.includes(n)) + const loose = own.filter((n) => !passed.includes(n)) + return loose.length + ? [{ file: `${ctx.src}blocks/registry.ts`, fix: `createBlockRegistry(content, { ui: { ${loose.join(', ')} } })`, message: `components/ui/ overrides ${loose.join(', ')} but the registry does not pass them — library blocks keep the plugin's look`, severity: 'warning' }] + : [] + }, + docs: 'docs/blocks.md', + group: 'blocks', + source: 'static', + }, + { + id: 'blocks-duplicate', + check: async (ctx) => { + const m = await loadBlockManifest() + if (!m) {return []} + const out: RuleFinding[] = [] + const code = sourceFiles(ctx, `${ctx.src.replace(/\/$/, '') || '.'}`) + .filter((f) => !f.includes('payload-types')) + .map((f) => stripComments(ctx.read(f))) + .join('\n') + // A library block renamed through its slug option (testimonials → reviews) is still the library block. + const renamed = [...code.matchAll(/build\w+Block\s*\(\s*\{[^}]*\bslug\s*:\s*['"]([\w-]+)['"]/g)].map((x) => x[1]) + const librarySlugs = new Set([...m.blocks.map((b) => b.slug), ...renamed]) + const libraryInterfaces = new Set(m.blocks.map((b) => b.interfaceName).filter(Boolean)) + const overrides = new Set(optionKeys(registry(ctx), 'components')) + for (const folder of ctx.list(`${ctx.src}blocks`).filter((n) => !n.includes('.'))) { + const file = `${ctx.src}blocks/${folder}/config.ts` + const config = stripComments(ctx.read(file)) + const slug = config.match(/\bslug\s*:\s*['"]([\w-]+)['"]/)?.[1] + 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' }) + } + } + return out + }, + docs: 'docs/blocks.md', + group: 'blocks', + source: 'static', + }, + { + id: 'blocks-helper-copy', + check: async (ctx) => { + const m = await loadBlockManifest() + const names = [...(m?.fieldBuilders ?? []), ...OTHER_HELPERS] + const out: RuleFinding[] = [] + for (const file of sourceFiles(ctx, ctx.src.replace(/\/$/, '') || '.')) { + const code = stripComments(ctx.read(file)) + const copies = names.filter((n) => new RegExp(`(?:function\\s+${n}\\b|(?:const|let)\\s+${n}\\s*=)`).test(code)) + if (copies.length) {out.push({ file, fix: `import { ${copies.join(', ')} } from the plugin`, message: `local copy of ${copies.join(', ')}`, severity: 'warning' })} + } + return out + }, + docs: 'docs/blocks.md', + group: 'blocks', + source: 'static', + }, +] diff --git a/src/modules/doctor/rules/env.ts b/src/modules/doctor/rules/env.ts new file mode 100644 index 0000000..d594398 --- /dev/null +++ b/src/modules/doctor/rules/env.ts @@ -0,0 +1,105 @@ +import type { DoctorRule, RuleFinding } from '../types.js' + +import { databaseNameFromUri, databaseNamesFor } from '../../env/databaseName.js' +import { configFile } from '../project.js' +import { stripComments } from '../util.js' + +/** The database name of a URI; also for placeholder URIs (`HOST:PORT`) that `new URL` rejects. */ +const dbName = (uri: string | undefined) => databaseNameFromUri(uri) ?? (uri?.match(/^[a-z+]+:\/\/[^/]*\/([^/?#]+)/i)?.[1] ?? null) + +/** Placeholder hosts, users or names in .env.example — fine, they carry no secret. */ +const PLACEHOLDER = /[<>]|\b(?:HOST|PORT|USER|PASS(?:WORD)?|DATABASE|example)\b|\$\{/i + +export const envRules: DoctorRule[] = [ + { + id: 'db-name', + 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' }] + } + const { dev, prod } = databaseNamesFor(ctx.domain) + for (const [file, env] of [['.env', ctx.env.local], ['.env.example', ctx.env.example]] as const) { + if (!env) {continue} + const uri = env.DATABASE_URI + if (!uri) { + if (file === '.env.example') {out.push({ file, fix: `DATABASE_URI=mongodb://USER:PASS@HOST:PORT/${dev}?authSource=admin`, message: `${file} has no DATABASE_URI`, severity: 'warning' })} + continue + } + if (/^file:/i.test(uri)) { + out.push({ file, fix: `a MongoDB database named ${dev}`, message: `${file}: SQLite file — the team standard is a database named ${dev}`, severity: 'warning' }) + continue + } + const name = dbName(uri) + if (name === prod) { + out.push({ file, fix: `point it at ${dev}`, message: `${file} points at the production database ${prod} — a local run or seed writes to production`, severity: 'error' }) + } else if (name !== dev) { + out.push({ file, fix: `rename the database to ${dev} (production: ${prod}) — deployment.md backup + restore`, message: `${file}: database "${name ?? '(none)'}", expected ${dev}`, severity: 'error' }) + } + } + const prodName = ctx.env.prod ? dbName(ctx.env.prod.DATABASE_URI) : undefined + if (ctx.env.prod && prodName !== prod) {out.push({ fix: `name the production database ${prod}`, message: `--env-file: database "${prodName ?? '(none)'}", expected ${prod}`, severity: 'error' })} + return out + }, + docs: 'docs/deployment.md', + group: 'env', + source: 'static', + }, + { + id: 'env-rules', + check: (ctx) => { + 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' }] + } + const out: RuleFinding[] = [] + if (!/ipalEnvRules\s*\(/.test(code)) {out.push({ file, message: 'assertEnv without ipalEnvRules — 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' })} + return out + }, + docs: 'docs/env.md', + group: 'env', + source: 'static', + }, + { + id: 'env-example', + check: (ctx) => { + 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'] + 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')} + 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']) { + 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' })} + } + return out + }, + docs: 'docs/env.md', + group: 'env', + source: 'static', + }, + { + id: 'env-live', + check: (ctx) => + ctx.deep?.envProblems?.length + ? [{ fix: 'set the variable (Coolify → Environment Variables, or .env) and redeploy', message: `the project's env rules fail: ${ctx.deep.envProblems.join(', ')}`, severity: 'error' }] + : [], + docs: 'docs/env.md', + group: 'env', + source: 'deep', + }, +] diff --git a/src/modules/doctor/rules/layout.ts b/src/modules/doctor/rules/layout.ts new file mode 100644 index 0000000..ef1e926 --- /dev/null +++ b/src/modules/doctor/rules/layout.ts @@ -0,0 +1,188 @@ +import type { DoctorContext } from '../project.js' +import type { DoctorRule, RuleFinding } from '../types.js' + +import { configFile } from '../project.js' +import { lt, stripComments } from '../util.js' + +/** Top-level entries of src/ the convention allows (AGENT.md §3 + the starter, reference site and token drafts). */ +export const DEFAULT_SRC_ALLOW = [ + 'access', + 'app', + 'blocks', + 'collections', + 'components', + 'content.config.ts', + 'db.ts', + 'design', + 'env.rules.ts', + 'fields', + 'fonts', + 'globals', + 'hooks', + 'i18n.config.ts', + 'instrumentation.ts', + 'lib', + 'migrations', + 'payload-types.ts', + 'payload.config.ts', + 'proxy.ts', + 'seed', + 'utilities', +] + +/** The project renders blocks through the library registry — then components/ui/ only holds overrides. */ +export const usesBlockRegistry = (ctx: DoctorContext) => /createBlockRegistry\s*\(/.test(stripComments(ctx.read(`${ctx.src}blocks/registry.ts`))) + +/** Files AGENT.md §3 expects, with the `ipal-audit-skip` key that drops each one. */ +function requiredFiles(ctx: DoctorContext): Array<[string, string?]> { + const multi = ctx.exists(`${ctx.src}app/(frontend)/[locale]`) + const fe = multi ? 'app/(frontend)/[locale]' : 'app/(frontend)' + return [ + ['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', 'llms'], + ['app/llms-full.txt/route.ts', 'llms-full'], + [multi ? 'app/md/[locale]/[[...slug]]/route.ts' : 'app/md/[[...slug]]/route.ts', 'markdown'], + ['app/api/mcp/route.ts', 'mcp'], + ['app/api/health/route.ts'], + ['app/indexnow-key.txt/route.ts', 'indexnow'], + [`${fe}/layout.tsx`], + [`${fe}/actions.ts`], + [`${fe}/not-found.tsx`], + [`${fe}/notFoundView.ts`], + [`${fe}/[[...slug]]/page.tsx`], + ['blocks/registry.ts'], + ['collections/Pages.ts'], + ['collections/Media.ts'], + ['components/layout'], + ['components/forms/formClasses.ts'], + // components/ui/: blocks-ui-required (only without createBlockRegistry) + ] +} + +const PASCAL = /^[A-Z][A-Za-z0-9]*$/ +const KEBAB = /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\.[a-z0-9]+)*$/ + +export const layoutRules: DoctorRule[] = [ + { + id: 'layout-required', + check: (ctx) => { + if (!ctx.src) {return [{ message: 'no src/ folder (AGENT.md §3)', severity: 'error' }]} + const missing = requiredFiles(ctx).filter(([file, key]) => !(key && ctx.auditSkips.has(key)) && !ctx.exists(`${ctx.src}${file}`)) + return missing.length + ? [{ fix: 'the ipal-setup skill (stage named by the file)', message: `missing: ${missing.map(([f]) => `${ctx.src}${f}`).join(', ')}`, severity: 'error' }] + : [] + }, + docs: 'docs/agent/AGENT.md#3-project-structure-and-naming', + group: 'layout', + source: 'static', + }, + { + id: 'layout-forbidden', + check: (ctx) => { + const files = ['middleware.ts', `${ctx.src}middleware.ts`, ...['lib/pages.ts', 'lib/locales.ts', 'lib/navigation.ts', 'fields/link.ts', 'fields/sectionHeader.ts', 'fields/sectionSettings.ts'].map((f) => `${ctx.src}${f}`)] + const found = [...new Set(files)].filter((f) => ctx.exists(f)) + return found.length + ? [{ fix: 'delete — Next 16 uses proxy.ts; the plugin has resolveRoute, getConfiguredLocales, resolveNav, buildLinkField and the section fields', message: `files the plugin replaces: ${found.join(', ')}`, severity: 'error' }] + : [] + }, + docs: 'docs/agent/AGENT.md#3-project-structure-and-naming', + group: 'layout', + source: 'static', + }, + { + id: 'layout-extra', + check: (ctx) => { + if (!ctx.src) {return []} + 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' }] + : [] + }, + docs: 'docs/agent/AGENT.md#3-project-structure-and-naming', + group: 'layout', + source: 'static', + }, + { + id: 'naming', + check: (ctx) => { + const out: RuleFinding[] = [] + const bad: string[] = [] + // Block folders PascalCase; files in blocks/ (registry.ts, configs.ts) are helpers — camelCase is fine. + for (const name of ctx.list(`${ctx.src}blocks`)) { + if (!name.includes('.') && !PASCAL.test(name)) {bad.push(`blocks/${name}`)} + } + // A collection / global file (it has a slug) PascalCase; helper files next to them camelCase. + for (const dir of ['collections', 'globals']) { + for (const name of ctx.list(`${ctx.src}${dir}`)) { + const file = `${ctx.src}${dir}/${name}` + if (!/\.tsx?$/.test(name)) {continue} + const isConfig = /\bslug\s*:/.test(ctx.read(file)) && /(?:CollectionConfig|GlobalConfig)\b/.test(ctx.read(file)) + if (isConfig && !PASCAL.test(name.replace(/\.tsx?$/, ''))) {bad.push(`${dir}/${name}`)} + } + } + for (const name of ctx.list('scripts')) { + if (/\.[cm]?[jt]s$/.test(name) && !KEBAB.test(name)) {bad.push(`scripts/${name}`)} + } + if (bad.length) {out.push({ fix: 'rename (blocks, collections, globals: PascalCase; scripts: kebab-case)', message: `names off the convention: ${bad.join(', ')}`, severity: 'warning' })} + const barrels = ['blocks', 'components'].flatMap((d) => (ctx.exists(`${ctx.src}${d}/index.ts`) ? [`${ctx.src}${d}/index.ts`] : [])) + if (barrels.length) {out.push({ fix: 'delete — import files directly (§6.12)', message: `barrel files: ${barrels.join(', ')}`, severity: 'warning' })} + return out + }, + docs: 'docs/agent/AGENT.md#3-project-structure-and-naming', + group: 'layout', + source: 'static', + }, + { + id: 'importmap', + check: (ctx) => { + if (!ctx.importMap) {return [{ fix: 'pnpm payload generate:importmap', message: 'no importMap.js under app/(payload)/<admin>/', severity: 'error' }]} + const out: RuleFinding[] = [] + const im = ctx.read(ctx.importMap) + const cfg = stripComments(ctx.read(configFile(ctx) ?? '')) + const v = ctx.pluginVersion + const need: string[] = [] + if (/payloadTotp/.test(cfg)) { + need.push('@clocklimited/payload-2fa/rsc#TOTPSetup') + if (!lt(v, '1.14.2')) {need.push('@intecion/ipal-kit/admin#TotpRedirectProvider')} + } + if (/buildR2Storage/.test(cfg)) {need.push('S3ClientUploadHandler')} + if (/cookieScanner\s*:\s*(?!false)/.test(cfg) && !lt(v, '1.14.4')) {need.push('@intecion/ipal-kit/admin#CookieReviewTab')} + if (!lt(v, '1.14.5') && !/adminMeta\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#AdminIcon')} + const missing = need.filter((n) => !im.includes(n)) + if (missing.length) {out.push({ file: ctx.importMap, fix: 'pnpm payload generate:importmap and commit', message: `import map lacks ${missing.join(', ')}`, severity: 'error' })} + // Entries that name exports the installed plugin no longer has (a removed admin component → blank admin). + const adminIndex = ctx.read('node_modules/@intecion/ipal-kit/dist/exports/admin.js') + if (adminIndex) { + const names = [...new Set([...im.matchAll(/['"]@intecion\/ipal-kit\/admin#(\w+)['"]/g)].map((m) => m[1]))] + const gone = names.filter((n) => !new RegExp(`\\b${n}\\b`).test(adminIndex)) + if (gone.length) {out.push({ file: ctx.importMap, fix: 'pnpm payload generate:importmap and commit', message: `import map names exports the installed plugin no longer has: ${gone.join(', ')}`, severity: 'error' })} + } + 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', + group: 'layout', + source: 'static', + }, + { + id: 'tsconfig-skills', + check: (ctx) => { + const dirs = ['.agents', '.claude'].filter((d) => ctx.list(`${d}/skills`).some((n) => n.startsWith('ipal-'))) + if (!dirs.length || !ctx.exists('tsconfig.json')) {return []} + const exclude = ctx.read('tsconfig.json').replace(/\s/g, '').match(/"exclude":\[([^\]]*)\]/)?.[1] ?? '' + const missing = dirs.filter((d) => !new RegExp(`"(?:\\./)?${d.replace('.', '\\.')}(?:/[^"]*)?"`).test(exclude)) + return missing.length ? [{ file: 'tsconfig.json', fix: `"exclude": ["node_modules", "${missing.join('", "')}"]`, message: `tsconfig.json does not exclude ${missing.join(', ')} — skill templates break tsc / next build`, severity: 'error' }] : [] + }, + docs: 'docs/agent/AGENT.md#14-skills-antigravity-claude-code-cursor', + group: 'layout', + source: 'static', + }, +] diff --git a/src/modules/doctor/rules/live.ts b/src/modules/doctor/rules/live.ts new file mode 100644 index 0000000..ff99b86 --- /dev/null +++ b/src/modules/doctor/rules/live.ts @@ -0,0 +1,94 @@ +import { existsSync } from 'node:fs' +import { join } from 'node:path' + +import type { DoctorLive, DoctorRule, LiveResponse, RuleFinding } from '../types.js' + +import { run } from '../util.js' +import { noindex } from './security.js' +import { parseToolOutput, titleSlug } from './tooling.js' + +/** GET-only fetcher with a cache (each path is requested once per run) and a doctor user agent. */ +export function createLiveFetcher(url: string, options: { adminRoute?: string; staging?: boolean } = {}): DoctorLive { + const base = url.replace(/\/+$/, '') + const cache = new Map<string, Promise<LiveResponse>>() + const fetchOnce = (path: string, init: { redirect?: 'follow' | 'manual' } = {}) => { + const key = `${init.redirect ?? 'follow'} ${path}` + if (!cache.has(key)) { + cache.set( + key, + (async () => { + try { + const res = await fetch(base + path, { + headers: { 'user-agent': 'ipal-doctor (+https://intecion.com; read-only)' }, + redirect: init.redirect ?? 'follow', + signal: AbortSignal.timeout(20_000), + }) + return { headers: res.headers, status: res.status, text: await res.text() } + } catch (err) { + const e = err as { cause?: { code?: string }; message?: string } + return { error: e.cause?.code ?? e.message ?? 'unreachable', headers: new Headers(), status: 0, text: '' } + } + })(), + ) + } + return cache.get(key)! + } + return { adminRoute: options.adminRoute ?? '/admin', fetch: fetchOnce, staging: options.staging ?? false, url: base } +} + +export const liveRules: DoctorRule[] = [ + { + id: 'live-reachable', + check: async (ctx) => { + const home = await ctx.live!.fetch('/', { redirect: 'manual' }) + return home.status ? [] : [{ message: `${ctx.live!.url} is unreachable (${home.error})`, severity: 'error' }] + }, + group: 'live', + source: 'live', + }, + { + id: 'live-health', + check: async (ctx) => { + const res = await ctx.live!.fetch('/api/health') + return res.status === 200 ? [] : [{ fix: 'src/app/api/health/route.ts → healthRoute (Coolify health check)', message: `/api/health → ${res.status || res.error}`, severity: 'error' }] + }, + docs: 'docs/deployment.md', + group: 'live', + source: 'live', + }, + { + id: 'live-noindex', + check: async (ctx) => { + 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' }] : [] + }, + docs: 'docs/seo.md', + group: 'live', + source: 'live', + }, + { + 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' }]} + 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) + const out: RuleFinding[] = [] + // INFO lines are notes (e.g. "no verification meta" with DNS verification) — not findings. + for (const line of parseToolOutput(res.stdout).filter((l) => l.level !== 'info')) { + 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' })} + return out + }, + docs: 'docs/agent/skills/ipal-seo-check/SKILL.md', + group: 'live', + source: 'live', + }, +] diff --git a/src/modules/doctor/rules/security.ts b/src/modules/doctor/rules/security.ts new file mode 100644 index 0000000..73ddb28 --- /dev/null +++ b/src/modules/doctor/rules/security.ts @@ -0,0 +1,162 @@ +import type { DoctorContext } from '../project.js' +import type { DoctorRule, RuleFinding } from '../types.js' + +import { configFile, nextConfigFile } from '../project.js' +import { lt, stripComments } from '../util.js' + +const next = (ctx: DoctorContext) => stripComments(ctx.read(nextConfigFile(ctx) ?? '')) +const cfg = (ctx: DoctorContext) => stripComments(ctx.read(configFile(ctx) ?? '')) +const isLocal = (url: string) => /^https?:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::|\/|$)/i.test(url) +const noindex = (html: string, robotsHeader: null | string) => + /<meta[^>]+name=["']robots["'][^>]*content=["'][^"']*noindex/i.test(html) || /<meta[^>]+content=["'][^"']*noindex[^>]+name=["']robots["']/i.test(html) || /noindex/i.test(robotsHeader ?? '') + +/** Days between two ISO dates. */ +const daysBetween = (from: string, to: string) => Math.floor((Date.parse(to) - Date.parse(from)) / 86_400_000) + +export const securityRules: DoctorRule[] = [ + { + id: 'security-headers', + check: async (ctx) => { + const out: RuleFinding[] = [] + const file = nextConfigFile(ctx) + if (!/buildSecurityHeaders\s*\(/.test(next(ctx))) {out.push({ file: file ?? 'next.config.ts', fix: 'headers(): [{ source: "/:path*", headers: buildSecurityHeaders({ csp }) }]', message: 'next.config does not use buildSecurityHeaders', severity: 'error' })} + if (ctx.live) { + const home = await ctx.live.fetch('/') + if (home.status) { + const h = home.headers + const missing = [ + ...(isLocal(ctx.live.url) || h.get('strict-transport-security') ? [] : ['Strict-Transport-Security']), + ...(h.get('x-content-type-options') ? [] : ['X-Content-Type-Options']), + ...(h.get('referrer-policy') ? [] : ['Referrer-Policy']), + ...(h.get('permissions-policy') ? [] : ['Permissions-Policy']), + ...(h.get('x-frame-options') || /frame-ancestors/.test(h.get('content-security-policy') ?? '') ? [] : ['X-Frame-Options / frame-ancestors']), + ] + if (missing.length) {out.push({ fix: 'buildSecurityHeaders on /:path* (security.md)', message: `live / lacks ${missing.join(', ')}`, severity: 'error' })} + } + } + return out + }, + docs: 'docs/security.md', + group: 'security', + source: 'static', + }, + { + id: 'powered-by', + check: async (ctx) => { + const out: RuleFinding[] = [] + if (!/withSecurityConfig\s*\(|poweredByHeader\s*:\s*false/.test(next(ctx))) { + out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: 'export default withPayload(withSecurityConfig(nextConfig))', message: 'X-Powered-By is not hidden (withSecurityConfig)', severity: 'error' }) + } + if (ctx.live) { + for (const path of ['/', `${ctx.live.adminRoute}/login`]) { + const res = await ctx.live.fetch(path) + const value = res.headers.get('x-powered-by') + if (value) {out.push({ fix: 'withSecurityConfig (security.md → X-Powered-By)', message: `live ${path} sends X-Powered-By: ${value}`, severity: 'error' })} + } + } + return out + }, + docs: 'docs/security.md', + group: 'security', + source: 'static', + }, + { + id: 'csp', + check: async (ctx) => { + const code = next(ctx) + stripComments(ctx.read(`${ctx.src}proxy.ts`)) + if (!/\bcsp\s*[:,}]|buildCsp|Content-Security-Policy/i.test(code)) { + return [{ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: "buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report' } }) + buildAdminCspHeaders on /admin/:path*", message: 'no Content-Security-Policy', severity: 'warning' }] + } + const out: RuleFinding[] = [] + if (!/buildAdminCspHeaders\s*\(/.test(code)) {out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: "{ source: '/admin/:path*', headers: buildAdminCspHeaders(csp) }", message: 'no CSP for the admin (buildAdminCspHeaders)', severity: 'warning' })} + let reportOnly = /mode\s*:\s*['"]report-only['"]/.test(code) || !/mode\s*:\s*['"]enforce['"]/.test(code) + if (ctx.live) { + for (const path of ['/', `${ctx.live.adminRoute}/login`]) { + const h = (await ctx.live.fetch(path)).headers + if (h.get('content-security-policy')) { + if (path === '/') {reportOnly = false} + } else if (h.get('content-security-policy-report-only')) { + reportOnly = true + } else { + out.push({ fix: 'security.md → ROLL OUT CSP', message: `live ${path} has no CSP header`, severity: 'warning' }) + } + } + } + if (reportOnly) { + const seen = ctx.config.seen?.['csp-report-only'] ?? ctx.today + const days = daysBetween(seen, ctx.today) + out.push({ + fix: "switch to mode: 'enforce' once the reports are clean (security.md → ROLL OUT CSP)", + message: `CSP is report-only (since ${seen}${days ? `, ${days} days` : ''})`, + severity: days >= 28 ? 'warning' : 'info', + }) + } + return out + }, + docs: 'docs/security.md', + group: 'security', + source: 'static', + }, + { + id: '2fa', + check: (ctx) => { + const out: RuleFinding[] = [] + if (!/twoFactor\s*:\s*\{[\s\S]*?plugin\s*:\s*payloadTotp/.test(cfg(ctx))) {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' })} + 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 (ctx.deep?.usersWithout2fa) {out.push({ fix: 'each of them signs in and sets up TOTP (forceSetup)', message: `${ctx.deep.usersWithout2fa} panel user(s) without TOTP`, severity: 'error' })} + return out + }, + docs: 'docs/security.md#2fa-totp--enforced-for-every-user', + group: 'security', + source: 'static', + }, + { + id: 'cookie-scanner', + 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' }] + } + 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' })} + if (ctx.deep?.pendingCookies) {out.push({ fix: 'Privacy → Cookies → Review and approve → Approve and add', message: `${ctx.deep.pendingCookies} cookie(s) wait for approval`, severity: 'warning' })} + return out + }, + docs: 'docs/cookie-scanner.md', + group: 'security', + source: 'static', + }, + { + id: 'admin-meta', + 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 (/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) { + const res = await ctx.live.fetch(`${ctx.live.adminRoute}/login`) + if (res.status && res.status < 400 && !/\/api\/ipal\/admin-og/.test(res.text)) {out.push({ fix: 'adminMeta on (default) and generate:importmap', message: 'the live admin has no ipal link preview (og:image /api/ipal/admin-og)', severity: 'warning' })} + } + return out + }, + docs: 'docs/white-label.md', + group: 'admin', + source: 'static', + }, + { + id: 'admin-noindex', + check: async (ctx) => { + if (!ctx.live) {return []} + const path = `${ctx.live.adminRoute}/login` + const res = await ctx.live.fetch(path) + if (!res.status || res.status >= 400) {return [{ message: `live ${path} → ${res.status || res.error}`, severity: 'warning' }]} + return noindex(res.text, res.headers.get('x-robots-tag')) ? [] : [{ fix: 'adminMeta robots (default noindex, nofollow)', message: `live ${path} is not noindex`, severity: 'error' }] + }, + docs: 'docs/white-label.md', + group: 'admin', + source: 'live', + }, +] + +export { noindex } diff --git a/src/modules/doctor/rules/seeds.ts b/src/modules/doctor/rules/seeds.ts new file mode 100644 index 0000000..66811ae --- /dev/null +++ b/src/modules/doctor/rules/seeds.ts @@ -0,0 +1,56 @@ +import { dirname, join, normalize } from 'node:path' + +import type { DoctorContext } from '../project.js' +import type { DoctorRule, RuleFinding } from '../types.js' + +import { stripComments } from '../util.js' + +/** The seed entry file and the project files it imports (relative imports, two levels deep). */ +function seedFiles(ctx: DoctorContext, entry: string): string[] { + const seen = new Set<string>() + const visit = (file: string, depth: number) => { + if (seen.has(file) || !ctx.exists(file)) {return} + seen.add(file) + if (depth >= 2) {return} + for (const m of ctx.read(file).matchAll(/from\s+['"](\.{1,2}\/[^'"]+)['"]/g)) { + const base = normalize(join(dirname(file), m[1])).replace(/\.js$/, '') + const hit = ['.ts', '.tsx', '.mjs', '.js', '/index.ts'].map((ext) => base + ext).find((f) => ctx.exists(f)) + if (hit) {visit(hit, depth + 1)} + } + } + visit(entry, 0) + return [...seen] +} + +const DELETES = /payload\s*\.\s*delete\s*\(|\.deleteMany\s*\(|dropDatabase|SEED_FRESH|--fresh\b/ + +export const seedRules: DoctorRule[] = [ + { + id: 'seed-named', + check: (ctx) => { + const out: RuleFinding[] = [] + 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' })} + 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' })} + 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 (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' })} + } + return out + }, + docs: 'docs/seeding.md', + group: 'seeds', + source: 'static', + }, +] diff --git a/src/modules/doctor/rules/tooling.ts b/src/modules/doctor/rules/tooling.ts new file mode 100644 index 0000000..c69d9f0 --- /dev/null +++ b/src/modules/doctor/rules/tooling.ts @@ -0,0 +1,83 @@ +import { existsSync } from 'node:fs' +import { join } from 'node:path' + +import type { DoctorRule, DoctorSeverity, RuleFinding } from '../types.js' + +import { run } from '../util.js' + +export type ToolLine = { items: string[]; level: DoctorSeverity; rule: string; title: string } + +/** `[ERROR] title (n) — rule` blocks with their indented items (the output of audit.sh and seo-check.mjs). */ +export function parseToolOutput(text: string): ToolLine[] { + const out: ToolLine[] = [] + for (const line of text.split('\n')) { + const head = line.match(/^\[(ERROR|WARNING|INFO)\] (.+?)(?: \(\d+\))? — (.*)$/) + if (head) { + out.push({ items: [], level: head[1] === 'ERROR' ? 'error' : head[1] === 'WARNING' ? 'warning' : 'info', rule: head[3], title: head[2] }) + continue + } + const item = line.match(/^ {2}(\S.*)$/) + if (item && out.length) {out.at(-1)!.items.push(item[1])} + } + return out +} + +/** + * ipal-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]> = [ + [/^missing: security headers$/, 'security-headers'], + [/^missing: X-Powered-By hidden$/, 'powered-by'], + [/^missing: Content-Security-Policy$/, 'csp'], + [/^missing: 2FA$/, '2fa'], + [/^missing: env validation$/, 'env-rules'], + [/^import map without the R2 upload handler$/, 'importmap'], + [/^tsconfig\.json does not exclude \.agents$/, 'tsconfig-skills'], + [/^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'], + [/^own block renderer switch$/, 'blocks-registry'], +] + +/** Rules the doctor already reports itself — the audit copy is dropped instead of reported twice. */ +const AUDIT_DUPLICATES = new Set(['2fa', 'csp', 'env-rules', 'importmap', 'layout-forbidden', 'naming', 'powered-by', 'security-headers', 'tsconfig-skills']) + +/** `duplicate titles` → `duplicate-titles` (the id part of `audit:<slug>` / `live-seo:<slug>`). */ +export const titleSlug = (title: string) => title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') + +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' }]} + 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' }]} + const out: RuleFinding[] = [] + for (const line of parseToolOutput(res.stdout)) { + const mapped = AUDIT_RULE_MAP.find(([re]) => re.test(line.title))?.[1] + if (mapped && AUDIT_DUPLICATES.has(mapped)) {continue} + const rule = mapped ?? `audit:${titleSlug(line.title)}` + // One finding per file (`file:line: text` items), so a silenced file does not hide the others. + const byFile = new Map<string, string[]>() + for (const item of line.items) { + const file = item.match(/^([\w@()[\].\-/]+\.[a-z]+):\d+:/)?.[1] ?? '' + byFile.set(file, [...(byFile.get(file) ?? []), item]) + } + if (!byFile.size) {byFile.set('', [])} + for (const [file, items] of byFile) { + const list = items.length ? `: ${items.slice(0, 5).join('; ')}${items.length > 5 ? ` … +${items.length - 5}` : ''}` : '' + out.push({ file: file || undefined, fix: line.rule, message: `${line.title}${list}`, rule, severity: line.level }) + } + } + return out + }, + docs: 'docs/agent/skills/ipal-audit/SKILL.md', + group: 'audit', + source: 'static', + }, +] diff --git a/src/modules/doctor/rules/versions.ts b/src/modules/doctor/rules/versions.ts new file mode 100644 index 0000000..1a6a087 --- /dev/null +++ b/src/modules/doctor/rules/versions.ts @@ -0,0 +1,125 @@ +import type { DoctorRule, RuleFinding } from '../types.js' + +import { compareVersions, isSemverSpec, lt, parseVersion, run } from '../util.js' + +const PKG = '@intecion/ipal-kit' + +export const versionRules: DoctorRule[] = [ + { + id: 'plugin-installed', + check: (ctx) => { + const spec = ctx.deps[PKG] + if (!spec) {return [{ fix: `pnpm add ${PKG}`, message: `${PKG} is not a dependency`, severity: 'error' }]} + if (!ctx.pluginVersion) {return [{ fix: 'pnpm install', message: `${PKG} is not installed (no node_modules/${PKG})`, severity: 'error' }]} + if (isSemverSpec(spec) && lt(ctx.pluginVersion, spec)) { + return [{ file: 'package.json', fix: 'pnpm install', message: `package.json asks ${spec}, node_modules has ${ctx.pluginVersion}`, severity: 'error' }] + } + return [] + }, + docs: 'docs/agent/skills/ipal-upgrade/SKILL.md', + group: 'versions', + source: 'static', + }, + { + id: 'next-min', + check: (ctx) => { + const out: RuleFinding[] = [] + const next = ctx.installed('next') + if (!next) {return [{ fix: 'pnpm install', message: 'next is not installed', severity: 'error' }]} + if (lt(next, '16.4.1')) {out.push({ fix: 'pnpm add next@16.4 eslint-config-next@16.4', message: `next ${next} < 16.4.1 (RCE and DoS advisories)`, severity: 'error' })} + const eslint = ctx.installed('eslint-config-next') + if (eslint && parseVersion(eslint)?.slice(0, 2).join('.') !== parseVersion(next)?.slice(0, 2).join('.')) { + out.push({ fix: `pnpm add -D eslint-config-next@${next}`, message: `eslint-config-next ${eslint} is not on next's ${next}`, severity: 'warning' }) + } + return out + }, + docs: 'docs/agent/AGENT.md#4-next-16--rendering-seo-build', + group: 'versions', + source: 'static', + }, + { + id: 'sharp-min', + check: (ctx) => { + const sharp = ctx.installed('sharp') + if (!sharp) {return [{ fix: 'pnpm add sharp@^0.35.5', message: 'sharp is not installed (next/image and Payload need it)', severity: 'error' }]} + return lt(sharp, '0.35.5') ? [{ fix: 'pnpm add sharp@^0.35.5 (or a pnpm.overrides entry)', message: `sharp ${sharp} < 0.35.5`, severity: 'error' }] : [] + }, + docs: 'docs/agent/AGENT.md#4-next-16--rendering-seo-build', + group: 'versions', + source: 'static', + }, + { + id: 'node-22', + check: (ctx) => { + const out: RuleFinding[] = [] + const engines = ctx.pkg.engines?.node?.trim() + // Only 22: a lower bound of 22 and an upper bound below 23 (or a 22.x / ^22 / ~22 range). + const only22 = !!engines && (/^(?:\^|~)?22(?:\.\d+){0,2}(?:\.x)?$/.test(engines) || /^>=\s*22(?:\.\d+){0,2}\s+<\s*23(?:\.0){0,2}$/.test(engines)) + if (!only22) {out.push({ file: 'package.json', fix: 'set "engines": { "node": ">=22 <23" }', message: `engines.node is ${engines ? `"${engines}"` : 'missing'} — want ">=22 <23"`, severity: 'warning' })} + for (const file of ['.nvmrc', '.node-version']) { + const v = ctx.read(file).trim() + if (v && !/^v?22(?:\.|$)/.test(v)) {out.push({ file, fix: `write 22 to ${file}`, message: `${file} says ${v}`, severity: 'warning' })} + } + if (!ctx.exists('.nvmrc') && !ctx.exists('.node-version')) {out.push({ fix: 'echo 22 > .nvmrc', message: 'no .nvmrc (Nixpacks and nvm pick Node from it)', severity: 'warning' })} + if (ctx.deep?.node && !/^v?22\./.test(ctx.deep.node)) {out.push({ message: `the site runs on Node ${ctx.deep.node}`, severity: 'warning' })} + return out + }, + docs: 'docs/deployment.md', + group: 'versions', + source: 'static', + }, + { + id: 'pnpm-pinned', + check: (ctx) => (ctx.pkg.packageManager ? [] : [{ file: 'package.json', fix: 'corepack use pnpm@10', message: 'no packageManager — builds may use another pnpm', severity: 'info' }]), + group: 'versions', + source: 'static', + }, + { + id: 'plugin-latest', + check: (ctx) => { + if (!ctx.pluginVersion) {return []} + const res = run('pnpm', ['view', PKG, 'version', '--json'], ctx.root, 30_000) + let latest: null | string = null + try { + const parsed = JSON.parse(res.stdout) as string | string[] + latest = Array.isArray(parsed) ? (parsed.at(-1) ?? null) : parsed + } catch { + latest = null + } + if (!latest) {return [{ message: `could not read the latest ${PKG} from the registry (${res.stderr.trim().split('\n')[0] || 'no answer'}) — use --offline`, severity: 'info' }]} + if (compareVersions(ctx.pluginVersion, latest) >= 0) {return []} + 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`, + message: `${PKG} ${ctx.pluginVersion} installed, ${latest} is out`, + severity: minorsBehind >= 2 ? 'error' : 'warning', + }] + }, + docs: 'docs/agent/skills/ipal-upgrade/SKILL.md', + group: 'versions', + source: 'registry', + }, + { + id: 'deps-audit', + check: (ctx) => { + const res = run('pnpm', ['audit', '--prod', '--json', '--ignore-workspace'], ctx.root, 120_000) + let v: Record<string, number> | undefined + try { + v = (JSON.parse(res.stdout) as { metadata?: { vulnerabilities?: Record<string, number> } }).metadata?.vulnerabilities + } catch { + v = undefined + } + if (!v) {return [{ message: `pnpm audit --prod gave no result (${res.stderr.trim().split('\n')[0] || 'no output'}) — use --offline`, severity: 'info' }]} + const high = (v.critical ?? 0) + (v.high ?? 0) + if (high) { + return [{ fix: 'pnpm up <package>, upgrade the plugin, or a pnpm.overrides entry (AGENT.md §4 item 12)', message: `pnpm audit --prod: ${v.critical ?? 0} critical, ${v.high ?? 0} high`, severity: 'error' }] + } + const low = (v.moderate ?? 0) + (v.low ?? 0) + return low ? [{ message: `pnpm audit --prod: ${v.moderate ?? 0} moderate, ${v.low ?? 0} low`, severity: 'info' }] : [] + }, + docs: 'docs/agent/AGENT.md#4-next-16--rendering-seo-build', + group: 'versions', + source: 'registry', + }, +] diff --git a/src/modules/doctor/run.ts b/src/modules/doctor/run.ts new file mode 100644 index 0000000..abd706f --- /dev/null +++ b/src/modules/doctor/run.ts @@ -0,0 +1,205 @@ +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, + }, + } +} diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts new file mode 100644 index 0000000..07808f8 --- /dev/null +++ b/src/modules/doctor/status.ts @@ -0,0 +1,78 @@ +import type { BasePayload, Endpoint, PayloadRequest } from 'payload' + +import { timingSafeEqual } from 'node:crypto' +import { readFileSync } from 'node:fs' + +import type { DoctorStatus } from './types.js' + +import { countPendingCookies } from '../consent/scanner/approval.js' +import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js' +import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' + +/** The plugin's own version (package.json next to dist/ and src/). */ +export function pluginVersion(): string { + try { + return (JSON.parse(readFileSync(new URL('../../../package.json', import.meta.url), 'utf8')) as { version: string }).version + } catch { + return 'unknown' + } +} + +type CollectionLike = { fields?: Array<{ name?: string }>; slug: string } + +/** + * Read-only counts for ipal-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> { + const collections = (payload.config.collections ?? []) as unknown as CollectionLike[] + const authSlug = payload.config.admin?.user + const auth = collections.find((c) => c.slug === authSlug) + let usersWithout2fa: null | number = null + // payload-2fa stores `totpSecret` (`hasTotp` is virtual and cannot be queried); counted, never read. + if (auth?.fields?.some((f) => f.name === 'totpSecret')) { + const collection = auth.slug as never + const all = (await payload.count({ collection, overrideAccess: true })).totalDocs + const withTotp = (await payload.count({ collection, overrideAccess: true, where: { and: [{ totpSecret: { exists: true } }, { totpSecret: { not_equals: '' } }] } })).totalDocs + usersWithout2fa = Math.max(0, all - withTotp) + } + const pendingCookies = collections.some((c) => c.slug === COOKIE_REVIEW_SLUG) ? await countPendingCookies(payload) : null + return { node: process.version, pendingCookies, plugin: pluginVersion(), usersWithout2fa } +} + +export type DoctorEndpointOptions = { + /** Who may read the status besides a valid token, e.g. `({ req }) => req.user?.roles?.includes('admin')`. */ + access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean> + /** Env variable that holds the token (≥ 32 characters). Default IPAL_DOCTOR_TOKEN. */ + tokenVar?: string +} + +const sameToken = (given: string, expected: string) => { + const a = Buffer.from(given) + const b = Buffer.from(expected) + return a.length === b.length && timingSafeEqual(a, b) +} + +/** + * GET /api/ipal/doctor — the deep status for `ipal-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. + */ +export function buildDoctorEndpoint(options: DoctorEndpointOptions = {}): Endpoint { + const tokenVar = options.tokenVar ?? 'IPAL_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 }) + 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 ? await options.access({ req }) : false) + if (!allowed) {return Response.json({ error: 'Unauthorized' }, { status: 401 })} + const status = await collectDoctorStatus(req.payload) + return Response.json(status, { headers: { 'cache-control': 'no-store' } }) + }, + method: 'get', + path: '/ipal/doctor', + } +} diff --git a/src/modules/doctor/types.ts b/src/modules/doctor/types.ts new file mode 100644 index 0000000..7089f3a --- /dev/null +++ b/src/modules/doctor/types.ts @@ -0,0 +1,92 @@ +import type { DoctorContext } from './project.js' + +/** How bad a finding is: error fails CI, warning is drift to fix, info is worth knowing. */ +export type DoctorSeverity = 'error' | 'info' | 'warning' + +/** Where a rule looks: files only, the package registry, the running site, or the database. */ +export type DoctorSource = 'deep' | 'live' | 'registry' | 'static' + +export type DoctorFinding = { + docs?: string + /** The project file the finding is about, relative to the project root. */ + file?: string + fix?: string + message: string + /** Why the project silenced it (from ipal-doctor.json or an `ipal-audit-skip` line). */ + reason?: string + rule: string + severity: DoctorSeverity + silenced?: boolean + source: DoctorSource +} + +/** 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. */ +export type DoctorRuleSetting = { + /** Only findings in these files (globs: `*` within a folder, `**` across folders), e.g. an approved exception. */ + files?: string[] + off?: boolean + reason?: string + severity?: DoctorSeverity + /** ISO date; after it the entry no longer applies. */ + until?: string +} + +/** ipal-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 + /** Paths of extra rule modules (relative to the project), each exporting `rules: DoctorRule[]`. */ + extraRules?: string[] + /** true once the site is live: seeds must then name their records. */ + launched?: boolean + layout?: { allow?: string[] } + rules?: Record<string, DoctorRuleSetting> + /** First time a condition was seen (ISO date), e.g. `{ "csp-report-only": "2026-10-29" }`. */ + seen?: Record<string, string> +} + +/** The read-only status a deep check collects (payload run or GET /api/ipal/doctor). */ +export type DoctorStatus = { + /** Variables the project's own env rules report missing or invalid (names only). */ + envProblems?: string[] + /** Why the deep check could not finish (first line). */ + error?: string + /** null = not compared (the endpoint cannot read files). */ + importMapCurrent?: boolean | null + node?: string + pendingCookies?: null | number + plugin?: string + usersWithout2fa?: null | number +} + +export type DoctorLive = { + /** Path of the admin panel, default /admin. */ + adminRoute: string + fetch: (path: string, init?: { redirect?: 'follow' | 'manual' }) => Promise<LiveResponse> + /** Site is a staging copy: must be noindex. */ + staging: boolean + url: string +} + +export type LiveResponse = { error?: string; headers: Headers; status: number; text: string } + +export type DoctorRule = { + check: (ctx: DoctorContext) => Promise<RuleFinding[]> | RuleFinding[] + docs?: string + group: string + id: string + source: DoctorSource +} + +export type DoctorReport = { + findings: DoctorFinding[] + rulesVersion: string + schema: 1 + site: { domain: null | string; path: string; plugin: null | string } + /** Rules that did not run (offline, no --url, no --deep) — never counted. */ + skipped: string[] + summary: { error: number; info: number; silenced: number; warning: number } +} diff --git a/src/modules/doctor/util.ts b/src/modules/doctor/util.ts new file mode 100644 index 0000000..364200e --- /dev/null +++ b/src/modules/doctor/util.ts @@ -0,0 +1,36 @@ +import { spawnSync } from 'node:child_process' + +/** [major, minor, patch] of a version or the lowest version in a range (`^1.2.3` → [1, 2, 3]). */ +export function parseVersion(value: null | string | undefined): [number, number, number] | null { + const m = (value ?? '').match(/(\d+)(?:\.(\d+))?(?:\.(\d+))?/) + return m ? [Number(m[1]), Number(m[2] ?? 0), Number(m[3] ?? 0)] : null +} + +/** -1 / 0 / 1; a missing version sorts first. */ +export function compareVersions(a: null | string | undefined, b: null | string | undefined): number { + const x = parseVersion(a) + const y = parseVersion(b) + if (!x || !y) {return x ? 1 : y ? -1 : 0} + for (let i = 0; i < 3; i++) { + if (x[i] !== y[i]) {return x[i] < y[i] ? -1 : 1} + } + return 0 +} + +export const lt = (a: null | string | undefined, b: string) => compareVersions(a, b) < 0 + +/** A range that names a registry version (not file:, link:, workspace:, git, a URL or a tag). */ +export const isSemverSpec = (spec: string | undefined) => !!spec && /^[\^~>=<\s]*\d/.test(spec.trim()) + +/** Runs a command; never throws. */ +export function run(command: string, args: string[], cwd: string, timeoutMs = 120_000): { code: number; stderr: string; stdout: string } { + const res = spawnSync(command, args, { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: timeoutMs }) + return { code: res.status ?? (res.error ? 127 : 1), stderr: res.stderr ?? String(res.error?.message ?? ''), stdout: res.stdout ?? '' } +} + +/** Strips // and /* *\/ comments so a commented-out line does not count as wired. */ +export function stripComments(code: string): string { + return code.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:'"`\\])\/\/.*$/gm, '$1') +} + +export const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}` diff --git a/src/modules/seo/buildSitemapEntries.ts b/src/modules/seo/buildSitemapEntries.ts index 888104c..6886d12 100644 --- a/src/modules/seo/buildSitemapEntries.ts +++ b/src/modules/seo/buildSitemapEntries.ts @@ -253,6 +253,11 @@ export async function buildSitemapEntries({ extractSlugInLocale(settings.homepage, defaultLocale) ?? 'home' + // The page assigned as the 404 in System pages renders with status 404 — never a sitemap URL, + // whatever its slug (the slug list above only catches '404', 'not-found' …). + const notFound = settings.notFound as { id?: number | string } | null | number | string | undefined + const notFoundId = notFound && typeof notFound === 'object' ? notFound.id : notFound + // Which collections to walk: pages (no prefix) + each content collection with // its archive-page slugs as the localized prefix. const collections: CollectionEntry[] = [{ slug: pagesSlug }] @@ -272,6 +277,7 @@ export async function buildSitemapEntries({ // loads every block of every post into memory at once. for await (const raw of readAll(payload, collection.slug, select)) { if (!isIndexable(raw)) {continue} + if (collection.slug === pagesSlug && notFoundId != null && String(raw.id) === String(notFoundId)) {continue} const images = [...new Set(imagesOf(raw).map(absolute).filter((u): u is string => Boolean(u)))] // Emit a separate <url> for EACH locale. Google's sitemap spec for diff --git a/src/plugin.ts b/src/plugin.ts index 376ef01..708a41b 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -23,6 +23,7 @@ import { buildCookieScanEndpoints } from './modules/consent/scanner/endpoint.js' import { mergeCookieScanLabels } from './modules/consent/scanner/labels.js' import { buildConstructionFields } from './modules/construction/fields.js' import { buildArchiveFields } from './modules/content/index.js' +import { buildDoctorEndpoint } from './modules/doctor/status.js' import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js' import { emailSettingsFields } from './modules/forms/emailLayout.js' import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js' @@ -413,6 +414,11 @@ export const ipalKit = (options: IpalOptions): Plugin => { config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint] + // --- ipal-doctor status (404 until IPAL_DOCTOR_TOKEN is set; docs/doctor.md) --- + if (options.doctor !== false) { + config.endpoints = [...(config.endpoints ?? []), buildDoctorEndpoint(options.doctor ?? {})] + } + // --- consent log: proof of consent (opt-in) --- if (options.consentLog) { const logOptions = options.consentLog === true ? {} : options.consentLog diff --git a/src/types.ts b/src/types.ts index d9c4c57..e2e50ff 100644 --- a/src/types.ts +++ b/src/types.ts @@ -18,6 +18,7 @@ import type { AdminMetaOptions, AgencyOption } from './modules/branding/adminMet import type { ConsentLogOptions } from './modules/consent/consentLog.js' import type { CookieScannerOptions } from './modules/consent/scanner/types.js' import type { ContentOption } from './modules/content/types.js' +import type { DoctorEndpointOptions } from './modules/doctor/status.js' import type { FormsOption } from './modules/forms/types.js' import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js' import type { I18nConfig } from './modules/i18n/types.js' @@ -92,6 +93,14 @@ export type IpalOptions = { */ cookieScanner?: boolean | CookieScannerOptions + /** + * GET /api/ipal/doctor — read-only counts for `ipal-doctor --url` (users without 2FA, cookies + * waiting for approval, versions). Answers 404 until IPAL_DOCTOR_TOKEN (≥ 32 characters) is set; + * then a `Bearer` token is required. `false` = no endpoint; `{ tokenVar, access }` to adapt it. + * docs/doctor.md. + */ + doctor?: DoctorEndpointOptions | false + /** * `false` = plugin off without uninstalling: its collections, globals and * fields stay (DB schema and migrations unchanged), but it adds no endpoints, diff --git a/test/docsConsistency.test.ts b/test/docsConsistency.test.ts index 2224780..e3c731f 100644 --- a/test/docsConsistency.test.ts +++ b/test/docsConsistency.test.ts @@ -19,6 +19,7 @@ const ENTRIES: Record<string, string> = { '/blocks': 'src/exports/blocks.ts', '/blocks/rsc': 'src/exports/blocks-rsc.ts', '/client': 'src/exports/client.ts', + '/doctor': 'src/exports/doctor.ts', '/env': 'src/exports/env.ts', '/next/middleware': 'src/exports/next-middleware.ts', '/rsc': 'src/exports/rsc.ts', diff --git a/test/doctor.test.ts b/test/doctor.test.ts new file mode 100644 index 0000000..e6b5f91 --- /dev/null +++ b/test/doctor.test.ts @@ -0,0 +1,346 @@ +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.3', sharp: '0.35.5' }, engines: { node: '>=22 <23' }, packageManager: 'pnpm@10.34.3', ...extra }) +const installed = (name: string, version: string) => ({ [`node_modules/${name}/package.json`]: { name, version } }) +const base = () => ({ + ...installed('@intecion/ipal-kit', '1.14.6'), + ...installed('next', '16.4.3'), + ...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('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('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']) + }) +}) + +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('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()} + }) +}) diff --git a/test/seoSearch.test.ts b/test/seoSearch.test.ts index a1ac4ad..e1b5a28 100644 --- a/test/seoSearch.test.ts +++ b/test/seoSearch.test.ts @@ -170,6 +170,14 @@ describe('buildSitemapEntries at scale', () => { expect(args.select).toEqual({ slug: true, _status: true, meta: true, noindex: true, updatedAt: true }) }) + test('the page assigned as the 404 in System pages is left out, whatever its slug', async () => { + const payload = fakePayload({ pages: pages.slice(0, 3) }) + payload.findGlobal.mockImplementation(async () => ({ notFound: { id: 1 } })) + const entries = await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, payload: payload as never }) + expect(entries.map((e) => e.url).some((u) => /\/s1$|\/p1$/.test(u))).toBe(false) + expect(entries).toHaveLength(2 * 2) + }) + test('custom images → whole documents (no select)', async () => { const payload = fakePayload({ pages: pages.slice(0, 2) }) await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, images: () => [], payload: payload as never })