import type { BasePayload, Endpoint, PayloadRequest } from 'payload' import { timingSafeEqual } from 'node:crypto' import type { DoctorStatus } from './types.js' import { PLUGIN_VERSION } from '../../version.js' import { openSignUpCollections, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers } from '../access/selfRegistration.js' import { countPendingCookies } from '../consent/scanner/approval.js' import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js' import { graphAvailable } from '../email/mailAdapter.js' import { mailPanelState } from '../email/relay/panel.js' import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js' import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js' import { accessAllowed } from '../shared/accessAnswer.js' import { readEnv } from '../shared/envName.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { turnstileSecretFromEnv } from '../turnstile/config.js' import { visitorWritableEntities } from './visitorWrites.js' /** The plugin's own version — a constant (src/version.ts), never a file read at run time. */ export function pluginVersion(): string { return PLUGIN_VERSION } type CollectionLike = { fields?: Array<{ name?: string }>; slug: string } /** * Read-only counts for iapl-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 { 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 let usersSetupClosed: 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 windowMs = (payload.config.custom as { ipal?: { twoFactor?: { setupWindowMs?: number } } } | undefined)?.ipal?.twoFactor?.setupWindowMs if (usersWithout2fa && windowMs && auth.fields.some((f) => f.name === SETUP_FROM_FIELD)) { usersSetupClosed = (await countAccountsWithoutTotp(payload, auth.slug, windowMs)).blocked } } const pendingCookies = collections.some((c) => c.slug === COOKIE_REVIEW_SLUG) ? await countPendingCookies(payload) : null // Turnstile: the recorded state and where the secret comes from — never the keys themselves. let turnstile: DoctorStatus['turnstile'] = null let secretFromEnv: boolean | null = null if ((payload.config.globals ?? []).some((g) => g.slug === 'site-integrations')) { try { const integrations = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0, overrideAccess: true })) as unknown as { turnstileSecretKey?: null | string turnstileStatus?: { code?: null | string; since?: null | string; state?: null | string } | null } const status = integrations.turnstileStatus turnstile = status?.state ? { code: status.code ?? null, since: status.since ?? null, state: status.state } : null secretFromEnv = turnstileSecretFromEnv(integrations) } catch { /* the global cannot be read: unknown */ } } // E-mail: the transport in effect and the state with the mail service — read from the store, nothing is asked. let mail: DoctorStatus['mail'] = null if ((payload.config.globals ?? []).some((g) => g.slug === 'site-integrations')) { try { const state = await mailPanelState({ payload }, undefined) const integrations = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0, overrideAccess: true })) as unknown as { emailStatus?: { code?: null | string; since?: null | string; state?: null | string } | null } mail = { graphEnv: graphAvailable(), ...(state.nonPublic ? { nonPublic: true, ...(state.nonPublicBy ? { nonPublicBy: state.nonPublicBy } : {}), ...(state.nonPublicPattern ? { nonPublicPattern: state.nonPublicPattern } : {}) } : {}), ...(state.otherHostEntries ? { otherHostEntries: true } : {}), methodChosen: state.methodChosen, ...(state.methodColumnMissing ? { methodColumnMissing: true } : {}), relay: state.relay ? { connected: state.relay.connected, disconnected: state.relay.disconnected, nameReplaced: Boolean(state.relay.nameReplaced), ...(state.relay.refusal ? { refusal: state.relay.refusal.code, ...(state.relay.refusal.reason ? { reason: state.relay.refusal.reason } : {}) } : {}), ...(state.relay.state ? { state: state.relay.state } : {}), } : null, replyAddress: Boolean(state.replyAddress), status: integrations.emailStatus?.state ? { code: integrations.emailStatus.code ?? null, since: integrations.emailStatus.since ?? null, state: integrations.emailStatus.state } : null, ...(state.methodProblem ? { methodProblem: state.methodProblem } : {}), transport: state.transport, } } catch { /* the global cannot be read: unknown */ } } let openSignUp: null | string[] = null try { openSignUp = await openSignUpCollections(payload as never) } catch { openSignUp = null } let staffOpenToOthers: null | string[] = null try { staffOpenToOthers = await staffCollectionsOpenToOthers(payload as never) } catch { staffOpenToOthers = null } let staffOnOwnRoles: null | string[] = null try { staffOnOwnRoles = staffCollectionsOnOwnRoles(payload as never) } catch { staffOnOwnRoles = null } let visitorWrites: null | string[] = null try { visitorWrites = await visitorWritableEntities(payload as never) } catch { visitorWrites = null } const { csrf, serverURL } = payload.config as { csrf?: unknown; serverURL?: unknown } const originKnown = (typeof serverURL === 'string' && serverURL.trim() !== '') || (Array.isArray(csrf) && csrf.some((o) => typeof o === 'string' && o.trim() !== '')) return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa, visitorWrites } } export type DoctorEndpointOptions = { /** Who may read the status besides a valid token, e.g. `({ req }) => isAdmin(req.user, req.payload)` (a staff admin; the second factor is checked for you). */ access?: (args: { req: PayloadRequest }) => boolean | Promise /** Env variable that holds the token (≥ 32 characters). Default IAPL_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 `iapl-doctor --url`. Off (404) until the token variable * holds at least 32 characters; then `Authorization: Bearer ` (or `access`) is required. * Rate-limited per client IP. `iapl({ doctor: false })` removes the endpoint. */ export function buildDoctorEndpoint(options: DoctorEndpointOptions = {}): Endpoint { const tokenVar = options.tokenVar ?? 'IAPL_DOCTOR_TOKEN' return { handler: async (req: PayloadRequest) => { 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' })} const given = (req.headers.get('authorization') ?? '').replace(/^Bearer\s+/i, '').trim() const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && accessAllowed('doctor.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', } }