IAPL rename: the old names keep working, and a second cookie name and counter key for new sites
- exports: ipalKit, IpalOptions, ipalEnvRules, IpalEnvFeatures, ipalT, ipalVar, IPAL_TOKENS, IPAL_BREAKPOINTS, IpalTokenName, IpalGlobalSlug are aliases of the iapl names - env: IAPL_* is read first, IPAL_* as fallback (readEnv; EnvRule.aliases for assertEnv); the crawler service reads IPAL_CRAWLER_SITES too - doctor: reads ipal-doctor.json when it is the only one, the old pointer block, ipal-audit-skip and old skill folders; new rule legacy-names (info) and storage-names (warning) - iapl-skills: installs iapl-*, removes the 16 old folders by exact name, rewrites the old pointer block in place; a project's own ipal-* skill stays - storageNames: 'ipal' (default) | 'iapl': the cookie the scanner declares and the 2FA counter's kv prefix; <PageStats visitorCookie>, IAPL_VISITOR_COOKIE, verifyLimit.keyPrefix - test/legacyNames.test.ts: 24 tests for all of the above Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
0a4f001797
commit
425fac14fb
@@ -14,6 +14,7 @@ import { pathToFileURL } from 'node:url'
|
||||
|
||||
import type { DoctorStatus } from './types.js'
|
||||
|
||||
import { readEnv } from '../shared/envName.js'
|
||||
import { collectDoctorStatus, pluginVersion } from './status.js'
|
||||
|
||||
const root = process.cwd()
|
||||
@@ -47,7 +48,7 @@ async function main() {
|
||||
Object.assign(status, await collectDoctorStatus(payload))
|
||||
|
||||
// The doctor passes the committed import map it found (relative to the project root).
|
||||
const committed = config.admin?.importMap?.importMapFile ?? (process.env.IAPL_DOCTOR_IMPORT_MAP ? join(root, process.env.IAPL_DOCTOR_IMPORT_MAP) : '')
|
||||
const committed = config.admin?.importMap?.importMapFile ?? (readEnv('IAPL_DOCTOR_IMPORT_MAP') ? join(root, readEnv('IAPL_DOCTOR_IMPORT_MAP')!) : '')
|
||||
if (committed && existsSync(committed)) {
|
||||
const temp = join(dirname(committed), 'importMap.iapl-doctor.tmp.js')
|
||||
try {
|
||||
|
||||
@@ -75,11 +75,11 @@ export function bareHost(value: string): string {
|
||||
|
||||
const isLocalHost = (host: string) => /^(?:localhost|127\.0\.0\.1|\[?::1\]?|0\.0\.0\.0)$|^[^.]+$/.test(host)
|
||||
|
||||
/** Reads `iapl-audit-skip: a, b — reason` lines (AGENT.md §0b). */
|
||||
/** Reads `iapl-audit-skip: a, b — reason` lines (AGENT.md §0b); the spelling before 1.17.0, `ipal-audit-skip`, is read too. */
|
||||
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(/^[-* ]*iapl-audit-skip:(.*)$/i)
|
||||
const m = line.match(/^[-* ]*(?:iapl|ipal)-audit-skip:(.*)$/i)
|
||||
if (!m) {continue}
|
||||
const [keys = '', ...rest] = m[1].trim().split(/\s+—\s+|\s+-\s+/)
|
||||
const reason = rest.join(' — ').trim()
|
||||
@@ -88,15 +88,24 @@ export function readAuditSkips(agents: string): Map<string, string> {
|
||||
return out
|
||||
}
|
||||
|
||||
/** The doctor's file in a project, and its name before 1.17.0. The first one that exists is read and written. */
|
||||
export const DOCTOR_CONFIG_FILES = ['iapl-doctor.json', 'ipal-doctor.json'] as const
|
||||
|
||||
/** Name of the project's doctor file: `iapl-doctor.json`, or `ipal-doctor.json` when only that one exists. */
|
||||
export function doctorConfigFile(root: string): string {
|
||||
return DOCTOR_CONFIG_FILES.find((name) => existsSync(join(root, name))) ?? DOCTOR_CONFIG_FILES[0]
|
||||
}
|
||||
|
||||
export function loadDoctorConfig(root: string): { config: DoctorConfig; error: null | string } {
|
||||
const file = join(root, 'iapl-doctor.json')
|
||||
const name = doctorConfigFile(root)
|
||||
const file = join(root, name)
|
||||
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: 'iapl-doctor.json must hold an object' }}
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {return { config: {}, error: `${name} must hold an object` }}
|
||||
return { config: parsed as DoctorConfig, error: null }
|
||||
} catch (err) {
|
||||
return { config: {}, error: `iapl-doctor.json is not valid JSON (${err instanceof Error ? err.message : String(err)})` }
|
||||
return { config: {}, error: `${name} is not valid JSON (${err instanceof Error ? err.message : String(err)})` }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,11 +19,14 @@ export function hashDir(dir: string): string {
|
||||
return hash.digest('hex')
|
||||
}
|
||||
|
||||
/** The pointer block `iapl-skills` keeps in AGENTS.md; the block written before 1.17.0 (`ipal-kit:start`, "## ipal-kit <version>") is read too. */
|
||||
export const POINTER_BLOCK = /<!-- (?:iapl|ipal-kit):start -->[\s\S]*?## (?:IAPL|ipal-kit) ([\w.-]+) — agent guide[\s\S]*?<!-- (?:iapl|ipal-kit):end -->/
|
||||
|
||||
/** What `iapl-skills` would change in a skills folder: missing, stale (different content) and retired skills. */
|
||||
export function planSkills({ dest, source }: { dest: string; source: string }): { missing: string[]; retired: string[]; stale: string[] } {
|
||||
const ls = (d: string) => {
|
||||
try {
|
||||
return readdirSync(d).filter((n) => n.startsWith('ipal-') && statSync(join(d, n)).isDirectory())
|
||||
return readdirSync(d).filter((n) => /^(?:iapl|ipal)-/.test(n) && statSync(join(d, n)).isDirectory())
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
@@ -50,12 +53,12 @@ export const agentRules: DoctorRule[] = [
|
||||
const body = parts[1].split(/^## /m)[0].replace(/<!--[\s\S]*?-->/g, '')
|
||||
if (!/^\s*[-*] +\S/m.test(body)) {out.push({ file: 'AGENTS.md', message: '"## Project decisions" is empty', severity: 'warning' })}
|
||||
}
|
||||
const pointer = agents.match(/<!-- iapl:start -->[\s\S]*?## IAPL ([\w.-]+) — agent guide[\s\S]*?<!-- iapl:end -->/)
|
||||
const pointer = agents.match(POINTER_BLOCK)
|
||||
if (!pointer) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec iapl-skills', message: 'no IAPL pointer block in AGENTS.md', severity: 'warning' })}
|
||||
else if (ctx.pluginVersion && pointer[1] !== ctx.pluginVersion) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec iapl-skills', message: `the pointer block names IAPL ${pointer[1]}, installed ${ctx.pluginVersion}`, severity: 'warning' })}
|
||||
const claude = ctx.read('CLAUDE.md')
|
||||
if (!claude) {out.push({ fix: 'pnpm exec iapl-skills (creates CLAUDE.md with @AGENTS.md)', message: 'no CLAUDE.md', severity: 'warning' })}
|
||||
else if (!/^@AGENTS\.md\s*$/m.test(claude) && !claude.includes('<!-- iapl:start -->')) {out.push({ file: 'CLAUDE.md', fix: 'add a line @AGENTS.md', message: 'CLAUDE.md neither imports AGENTS.md nor has the pointer block', severity: 'warning' })}
|
||||
else if (!/^@AGENTS\.md\s*$/m.test(claude) && !/<!-- (?:iapl|ipal-kit):start -->/.test(claude)) {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',
|
||||
@@ -65,7 +68,7 @@ export const agentRules: DoctorRule[] = [
|
||||
{
|
||||
id: 'skills-current',
|
||||
check: (ctx) => {
|
||||
const dest = ['.agents/skills', '.claude/skills'].find((d) => ctx.list(d).some((n) => n.startsWith('ipal-')))
|
||||
const dest = ['.agents/skills', '.claude/skills'].find((d) => ctx.list(d).some((n) => /^(?:iapl|ipal)-/.test(n)))
|
||||
if (!dest) {return [{ fix: 'pnpm exec iapl-skills', message: 'no iapl-* skills in .agents/skills or .claude/skills', severity: 'error' }]}
|
||||
// Compare with the skills the project's installed plugin ships (what `pnpm exec iapl-skills` copies).
|
||||
const installedSkills = join(ctx.root, 'node_modules/@intecion/ipal-kit/docs/agent/skills')
|
||||
|
||||
@@ -54,7 +54,7 @@ export const envRules: DoctorRule[] = [
|
||||
return [{ file, fix: "register(): assertEnv(iaplEnvRules({ storage: true, ipHeader: true })) from '@intecion/ipal-kit/env'", message: 'instrumentation.ts does not call assertEnv(iaplEnvRules(…))', severity: 'error' }]
|
||||
}
|
||||
const out: RuleFinding[] = []
|
||||
if (!/iaplEnvRules\s*\(/.test(code)) {out.push({ file, message: 'assertEnv without iaplEnvRules — the plugin variables are not checked', severity: 'warning' })}
|
||||
if (!/\b(?:iaplEnvRules|ipalEnvRules)\s*\(/.test(code)) {out.push({ file, message: 'assertEnv without iaplEnvRules — the plugin variables are not checked', severity: 'warning' })}
|
||||
if (/from\s+['"]@intecion\/ipal-kit['"]/.test(code)) {out.push({ file, fix: "import from '@intecion/ipal-kit/env'", message: 'instrumentation.ts imports the package root (Edge build breaks)', severity: 'error' })}
|
||||
const cfg = stripComments(ctx.read(configFile(ctx) ?? ''))
|
||||
const flag = (name: string) => new RegExp(`\\b${name}\\s*:`).test(code)
|
||||
|
||||
@@ -243,7 +243,7 @@ export const layoutRules: DoctorRule[] = [
|
||||
{
|
||||
id: 'tsconfig-skills',
|
||||
check: (ctx) => {
|
||||
const dirs = ['.agents', '.claude'].filter((d) => ctx.list(`${d}/skills`).some((n) => n.startsWith('ipal-')))
|
||||
const dirs = ['.agents', '.claude'].filter((d) => ctx.list(`${d}/skills`).some((n) => /^(?:iapl|ipal)-/.test(n)))
|
||||
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))
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import type { DoctorRule, RuleFinding } from '../types.js'
|
||||
|
||||
import { legacyEnvName } from '../../shared/envName.js'
|
||||
import { configFile, DOCTOR_CONFIG_FILES } from '../project.js'
|
||||
import { stripComments } from '../util.js'
|
||||
|
||||
/** The 16 skills shipped as `ipal-<name>` before 1.17.0 (now `iapl-<name>`). `iapl-skills` removes exactly these. */
|
||||
export const LEGACY_SKILL_NAMES = [
|
||||
'audit', 'block', 'collection', 'consent-check', 'debug', 'doctor', 'form', 'locale-add',
|
||||
'migrate-fields', 'nav', 'plugin-gap', 'reference', 'seo-check', 'setup', 'site', 'upgrade',
|
||||
].map((name) => `ipal-${name}`)
|
||||
|
||||
/** Exported names before 1.17.0 → the names since. Both work through 1.x. */
|
||||
export const LEGACY_EXPORTS: Record<string, string> = {
|
||||
IPAL_BREAKPOINTS: 'IAPL_BREAKPOINTS',
|
||||
IPAL_TOKENS: 'IAPL_TOKENS',
|
||||
IpalEnvFeatures: 'IaplEnvFeatures',
|
||||
ipalEnvRules: 'iaplEnvRules',
|
||||
IpalGlobalSlug: 'IaplGlobalSlug',
|
||||
ipalKit: 'iapl',
|
||||
IpalOptions: 'IaplOptions',
|
||||
ipalT: 'iaplT',
|
||||
IpalTokenName: 'IaplTokenName',
|
||||
ipalVar: 'iaplVar',
|
||||
}
|
||||
|
||||
/** Commands before 1.17.0 → the commands since. */
|
||||
export const LEGACY_COMMANDS: Record<string, string> = {
|
||||
'ipal-blocks': 'iapl-blocks',
|
||||
'ipal-doctor': 'iapl-doctor',
|
||||
'ipal-kit': 'iapl',
|
||||
'ipal-skills': 'iapl-skills',
|
||||
'ipal-tokens': 'iapl-tokens',
|
||||
}
|
||||
|
||||
/** The plugin's runtime variables: `IAPL_<NAME>`, read as `IPAL_<NAME>` too. */
|
||||
export const PLUGIN_ENV_NAMES = [
|
||||
'IAPL_COOKIE_SCAN_TOKEN', 'IAPL_COOKIE_SCAN_URL', 'IAPL_DOCTOR_IMPORT_MAP', 'IAPL_DOCTOR_TOKEN',
|
||||
'IAPL_IP_HEADER', 'IAPL_NOINDEX', 'IAPL_SEED_ALLOW_FULL', 'IAPL_SEED_ALLOW_PROD_UPDATE',
|
||||
]
|
||||
|
||||
/**
|
||||
* `legacy-names`: names from before the rename to IAPL (1.17.0) that the project still uses.
|
||||
* Every one of them keeps working through 1.x, so this is information, not a defect: the project
|
||||
* moves when its owner asks (the iapl-upgrade skill, "→ 1.17.0"). The two cases that are more
|
||||
* than information are a warning: both doctor files present, and one variable set under both
|
||||
* spellings with different values (the new spelling is the one read).
|
||||
*/
|
||||
export const legacyRules: DoctorRule[] = [
|
||||
{
|
||||
id: 'legacy-names',
|
||||
check: (ctx) => {
|
||||
const out: RuleFinding[] = []
|
||||
const info = (message: string, fix: string, file?: string) => out.push({ ...(file ? { file } : {}), fix, message, severity: 'info' })
|
||||
|
||||
if (DOCTOR_CONFIG_FILES.every((name) => ctx.exists(name))) {
|
||||
out.push({ fix: 'merge ipal-doctor.json into iapl-doctor.json and delete it', message: 'both iapl-doctor.json and ipal-doctor.json exist — only iapl-doctor.json is read', severity: 'warning' })
|
||||
} else if (ctx.exists('ipal-doctor.json')) {
|
||||
info('the doctor file has its name from before 1.17.0', 'optional: rename ipal-doctor.json to iapl-doctor.json', 'ipal-doctor.json')
|
||||
}
|
||||
|
||||
for (const file of [configFile(ctx), ctx.exists(`${ctx.src}instrumentation.ts`) ? `${ctx.src}instrumentation.ts` : 'instrumentation.ts']) {
|
||||
const code = file ? stripComments(ctx.read(file)) : ''
|
||||
const used = Object.keys(LEGACY_EXPORTS).filter((name) => new RegExp(`\\b${name}\\b`).test(code))
|
||||
if (used.length) {info(`uses ${used.join(', ')}`, `optional: ${used.map((name) => `${name} → ${LEGACY_EXPORTS[name]}`).join(', ')}`, file!)}
|
||||
}
|
||||
|
||||
const scripts = Object.entries((ctx.pkg.scripts ?? {}))
|
||||
const commands = Object.keys(LEGACY_COMMANDS).filter((name) => scripts.some(([, command]) => new RegExp(`(?<![\\w@/.-])${name}(?![\\w/-])`).test(command)))
|
||||
if (commands.length) {info(`package.json scripts call ${commands.join(', ')}`, `optional: ${commands.map((name) => `${name} → ${LEGACY_COMMANDS[name]}`).join(', ')}`, 'package.json')}
|
||||
|
||||
for (const [label, env] of [['.env.example', ctx.env.example], ['.env', ctx.env.local], ['--env-file', ctx.env.prod]] as const) {
|
||||
if (!env) {continue}
|
||||
const old = PLUGIN_ENV_NAMES.filter((name) => env[legacyEnvName(name)!] !== undefined)
|
||||
const clash = old.filter((name) => env[name] !== undefined && env[name] !== env[legacyEnvName(name)!])
|
||||
if (clash.length) {out.push({ fix: `keep ${clash.join(', ')} and remove the IPAL_ spelling`, message: `${label}: ${clash.map((name) => `${name} and ${legacyEnvName(name)}`).join('; ')} are both set, with different values — the IAPL_ one is read`, severity: 'warning' })}
|
||||
const only = old.filter((name) => !clash.includes(name) && env[name] === undefined)
|
||||
if (only.length) {info(`${label} sets ${only.map((name) => legacyEnvName(name)).join(', ')}`, `optional: ${only.map((name) => `${legacyEnvName(name)} → ${name}`).join(', ')}`)}
|
||||
}
|
||||
|
||||
const agents = `${ctx.read('AGENTS.md')}\n${ctx.read('CLAUDE.md')}`
|
||||
if (/<!-- ipal-kit:start -->/.test(agents)) {info('the agent pointer block is the one from before 1.17.0', 'pnpm exec iapl-skills (rewrites the block in place)', 'AGENTS.md')}
|
||||
if (/^[-* ]*ipal-audit-skip:/im.test(agents)) {info('ipal-audit-skip lines', 'optional: ipal-audit-skip → iapl-audit-skip', 'AGENTS.md')}
|
||||
|
||||
for (const dir of ['.agents/skills', '.claude/skills']) {
|
||||
const old = ctx.list(dir).filter((name) => LEGACY_SKILL_NAMES.includes(name))
|
||||
if (old.length) {info(`${old.length} skill folder(s) named ipal-* (from before 1.17.0)`, 'pnpm exec iapl-skills (installs iapl-*, removes these) and commit', dir)}
|
||||
}
|
||||
return out
|
||||
},
|
||||
docs: 'docs/agent/AGENT.md#names-iapl-and-ipal-kit',
|
||||
group: 'agents',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// The cookie the layout sets and the cookie the scanner declares must be the same one.
|
||||
id: 'storage-names',
|
||||
check: (ctx) => {
|
||||
const cfg = stripComments(ctx.read(configFile(ctx) ?? ''))
|
||||
const declared = /\bstorageNames\s*:\s*['"]iapl['"]/.test(cfg) ? 'iapl_vid' : 'ipal_vid'
|
||||
const files: string[] = []
|
||||
const walk = (dir: string, depth: number) => {
|
||||
for (const name of ctx.list(dir)) {
|
||||
if (files.length >= 600 || name === 'node_modules' || name.startsWith('.')) {continue}
|
||||
if (/\.tsx$/.test(name)) {files.push(`${dir}/${name}`)}
|
||||
else if (!name.includes('.') || /^\(.*\)$|^\[.*\]$/.test(name)) {if (depth < 8) {walk(`${dir}/${name}`, depth + 1)}}
|
||||
}
|
||||
}
|
||||
walk(`${ctx.src}app`, 0)
|
||||
walk(`${ctx.src}components`, 0)
|
||||
const out: RuleFinding[] = []
|
||||
for (const file of files) {
|
||||
const code = stripComments(ctx.read(file))
|
||||
if (!/<PageStats\b|<SiteProviders\s[^>]*\bstats\b/.test(code)) {continue}
|
||||
const set = /\bIAPL_VISITOR_COOKIE\b|['"]iapl_vid['"]/.test(code) ? 'iapl_vid' : /\bvisitorCookie\b/.test(code) ? null : 'ipal_vid'
|
||||
if (set && set !== declared) {
|
||||
out.push({
|
||||
file,
|
||||
fix: declared === 'iapl_vid'
|
||||
? "pass visitorCookie={IAPL_VISITOR_COOKIE} (from '@intecion/ipal-kit/client') to <PageStats> / <SiteProviders stats={{ … }}>"
|
||||
: "set iapl({ storageNames: 'iapl' }) in the config, or drop visitorCookie — one name per site (docs/stats.md)",
|
||||
message: `the page sets the visitor cookie ${set}, the cookie scanner declares ${declared}`,
|
||||
severity: 'warning',
|
||||
})
|
||||
}
|
||||
}
|
||||
return out
|
||||
},
|
||||
docs: 'docs/stats.md',
|
||||
group: 'security',
|
||||
source: 'static',
|
||||
},
|
||||
]
|
||||
@@ -146,7 +146,7 @@ export const securityRules: DoctorRule[] = [
|
||||
id: 'access-missing',
|
||||
check: (ctx) => {
|
||||
const code = cfg(ctx)
|
||||
if (!/iapl\s*\(/.test(code)) {return []}
|
||||
if (!/\b(?:iapl|ipalKit)\s*\(/.test(code)) {return []}
|
||||
// `access: { authCollection | defaultRole | … }`, an empty `access: {}`, or a variable whose name says so
|
||||
const set = /\baccess\s*:\s*\{\}/.test(code.replace(/\s+/g, '')) || /\baccess\s*:\s*\{[^{}]*\b(?:authCollection|defaultRole|authAccess|firstUserAdmin|staffCollections|panelRole|selfRegistration|password)\b/.test(code) || /\baccess\s*:\s*\w*[aA]ccess\w*\s*[,}]/.test(code)
|
||||
return set
|
||||
|
||||
@@ -4,11 +4,13 @@ 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 { readEnv } from '../shared/envName.js'
|
||||
import { createDoctorContext, doctorConfigFile, 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 { legacyRules } from './rules/legacy.js'
|
||||
import { createLiveFetcher, liveRules } from './rules/live.js'
|
||||
import { securityRules } from './rules/security.js'
|
||||
import { seedRules } from './rules/seeds.js'
|
||||
@@ -32,6 +34,7 @@ export const doctorRules: DoctorRule[] = [
|
||||
...envRules,
|
||||
...securityRules,
|
||||
...agentRules,
|
||||
...legacyRules,
|
||||
...seedRules,
|
||||
...blockRules,
|
||||
...toolingRules,
|
||||
@@ -111,9 +114,9 @@ export function applySettings(findings: DoctorFinding[], ctx: DoctorContext): Do
|
||||
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: `iapl-doctor.json: rule "${id}" has no reason, so it is ignored`, rule: 'doctor-config', severity: 'error', source: 'static' })}
|
||||
else if (s.severity && !SEVERITIES.includes(s.severity)) {out.push({ message: `iapl-doctor.json: rule "${id}" has an unknown severity "${s.severity}"`, rule: 'doctor-config', severity: 'error', source: 'static' })}
|
||||
else if (s.until && ctx.today > s.until) {out.push({ fix: 'fix the finding, or extend "until" with a new reason', message: `iapl-doctor.json: the setting for "${id}" expired on ${s.until}`, rule: 'doctor-config', severity: 'warning', source: 'static' })}
|
||||
if (!s.reason?.trim()) {out.push({ fix: 'add "reason": "<why>" — an entry without one is ignored', message: `${doctorConfigFile(ctx.root)}: 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: `${doctorConfigFile(ctx.root)}: 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: `${doctorConfigFile(ctx.root)}: 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) {
|
||||
@@ -153,7 +156,7 @@ export async function runDoctor(options: RunDoctorOptions): Promise<DoctorReport
|
||||
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 + IAPL_DOCTOR_TOKEN), or none.
|
||||
const token = process.env.IAPL_DOCTOR_TOKEN?.trim()
|
||||
const token = readEnv('IAPL_DOCTOR_TOKEN')?.trim()
|
||||
if (options.deepStatus !== undefined) {ctx.deep = options.deepStatus}
|
||||
else if (options.deep) {ctx.deep = runDeepProbe({ ...ctx, root })}
|
||||
else if (options.url && token && token.length >= 32) {ctx.deep = await fetchDeepStatus(options.url, token)}
|
||||
@@ -182,9 +185,9 @@ export async function runDoctor(options: RunDoctorOptions): Promise<DoctorReport
|
||||
|
||||
// First-seen dates (CSP report-only → warning after 4 weeks): stored outside CI when the file exists.
|
||||
const writeSeen = options.writeSeen ?? !process.env.CI
|
||||
if (writeSeen && findings.some((f) => f.rule === 'csp' && /report-only/.test(f.message)) && !ctx.config.seen?.['csp-report-only'] && existsSync(join(root, 'iapl-doctor.json'))) {
|
||||
if (writeSeen && findings.some((f) => f.rule === 'csp' && /report-only/.test(f.message)) && !ctx.config.seen?.['csp-report-only'] && existsSync(join(root, doctorConfigFile(root)))) {
|
||||
const current = loadDoctorConfig(root).config
|
||||
writeFileSync(join(root, 'iapl-doctor.json'), `${JSON.stringify({ ...current, seen: { ...current.seen, 'csp-report-only': ctx.today } }, null, 2)}\n`)
|
||||
writeFileSync(join(root, doctorConfigFile(root)), `${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])
|
||||
|
||||
@@ -10,6 +10,7 @@ import { countPendingCookies } from '../consent/scanner/approval.js'
|
||||
import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js'
|
||||
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
|
||||
import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js'
|
||||
import { readEnv } from '../shared/envName.js'
|
||||
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
|
||||
import { turnstileSecretFromEnv } from '../turnstile/config.js'
|
||||
|
||||
@@ -101,7 +102,7 @@ export function buildDoctorEndpoint(options: DoctorEndpointOptions = {}): Endpoi
|
||||
const tokenVar = options.tokenVar ?? 'IAPL_DOCTOR_TOKEN'
|
||||
return {
|
||||
handler: async (req: PayloadRequest) => {
|
||||
const token = process.env[tokenVar]?.trim() ?? ''
|
||||
const token = (options.tokenVar ? process.env[tokenVar] : readEnv(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: 'iapl-doctor', windowMs: 60_000 })
|
||||
if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests' })}
|
||||
|
||||
Reference in New Issue
Block a user