ipal-doctor: one command that checks a site against the team rules
bin ipal-doctor + @intecion/ipal-kit/doctor: static rules (versions, Node 22, AGENT.md §3 layout and naming, database names, env rules, headers, X-Powered-By, CSP, 2FA, cookie scanner, adminMeta, AGENTS.md, skills, seeds, block library via blockLibraryManifest, ipal-audit --quick), registry rules (latest plugin, pnpm audit --prod), live rules (--url, ipal-seo-check), deep rules (--deep via payload run; GET /api/ipal/doctor, off until IPAL_DOCTOR_TOKEN). Human / JSON output, --strict, exit codes 0/1/2/3, --sites drift table, ipal-doctor.json with reasons, until, files, seen. Fixes found on the way: sitemap leaves out the System pages 404 page; ipal-audit finds array labels after fields, any form seed, runs grep in UTF-8; ipal-seo-check counts duplicate titles per language. Reference site at zero findings (static), CI steps on. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
0ab133fbd7
commit
a4e8cfeae8
@@ -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
|
||||
}
|
||||
@@ -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')
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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) || '.'
|
||||
@@ -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',
|
||||
},
|
||||
]
|
||||
@@ -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',
|
||||
},
|
||||
]
|
||||
@@ -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',
|
||||
},
|
||||
]
|
||||
@@ -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',
|
||||
},
|
||||
]
|
||||
@@ -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',
|
||||
},
|
||||
]
|
||||
@@ -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 }
|
||||
@@ -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',
|
||||
},
|
||||
]
|
||||
@@ -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',
|
||||
},
|
||||
]
|
||||
@@ -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 [email protected] [email protected]', 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',
|
||||
},
|
||||
]
|
||||
@@ -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,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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'}`
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user