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,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',
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user