import type { BasePayload, CollectionBeforeChangeHook, Endpoint, Field, PayloadRequest } from 'payload' import { isAdmin, userMeetsRole } from '../../access/predicates.js' import { serverText } from '../../integrations/texts.js' import { secondFactorPassed, SETUP_FROM_FIELD } from './secondFactor.js' /** * "2FA setup required": the pieces iapl adds to the 2FA collection and the * config when the mode is on (the default with `twoFactor`). * * - the date field `totpSetupFrom` — when the current setup window opened; * - a hook that stamps it when an account is created and whenever its TOTP * secret is cleared (an admin reset, a removal); * - a backfill for accounts that existed before the mode (onInit); * - POST /api/ipal/two-factor/reset — an admin clears an account's TOTP, which * reopens its setup window; * - the status / reset field shown on the account in the panel. * * The rule itself (who is refused) lives in secondFactor.ts. */ export type RequireSetupOptions = { /** The notice for administrators on the dashboard (accounts without 2FA, how many are blocked). `false` = none. */ dashboardNotice?: false /** * Accounts that may work without TOTP on purpose — a service account that * logs in with a password. Return **exactly `true`** to exempt, and return it * at once: the function is called in access checks, which cannot wait. An * `async` function stops the site at start; any other answer than `true` * (a Promise, a string, an error thrown) exempts nobody and is logged. * (An API key needs no exemption: it passes by itself.) * `({ user }) => user.email === 'bot@acme.pl'` */ exempt?: (args: { user: Record }) => boolean /** The notice on the setup screen (until when; or that the time has passed). `false` = none. */ setupNotice?: false /** The "Two-step verification" status and reset control on the account in the panel. `false` = none (the reset endpoint stays). */ statusField?: false /** * Hours an account has to set TOTP up, counted from its creation or from the * last reset by an admin. After that it is blocked until an admin reopens * setup. Default 72. `false` or `0` = no limit (still nothing but setup until it is done). */ windowHours?: false | number } export const DEFAULT_SETUP_WINDOW_HOURS = 72 export const TWO_FACTOR_RESET_PATH = '/ipal/two-factor/reset' /** `twoFactor.requireSetup` → what the guard reads. */ export function resolveRequireSetup(option: false | RequireSetupOptions | undefined): { exempt?: RequireSetupOptions['exempt'] requireSetup: boolean setupWindowMs: number } { if (option === false) {return { requireSetup: false, setupWindowMs: 0 }} // A typo must not loosen the rule: '24', -1 or NaN used to mean "no limit". const given = option?.windowHours if (given !== undefined && given !== false && (typeof given !== 'number' || !Number.isFinite(given) || given < 0)) { throw new Error( `[iapl] twoFactor.requireSetup.windowHours must be a number of hours (0 or more) or false, got ${JSON.stringify(given) ?? String(given)}. ` + 'Use 72 (the default), another number, or false / 0 for no time limit.', ) } const hours = given === false ? 0 : (given ?? DEFAULT_SETUP_WINDOW_HOURS) return { ...(option?.exempt !== undefined ? { exempt: strictExempt(option.exempt) } : {}), requireSetup: true, setupWindowMs: hours > 0 ? hours * 60 * 60 * 1000 : 0, } } /** What was already said about a wrong `exempt` answer: each kind is logged once per process. */ const exemptComplaints = new Set() /** The constructor of async functions (there is no global for it). */ const ASYNC_FUNCTION: unknown = (async () => {}).constructor /** * The project's `exempt`, made safe to call from an access check: only an answer of exactly * `true` exempts. An async function is refused at start (its Promise would be truthy for every * account — everyone let in on a password); any other answer, or an error, exempts nobody and * is logged (once per kind of wrong answer). */ export function strictExempt(exempt: unknown): NonNullable { if (typeof exempt !== 'function') { throw new Error('[iapl] twoFactor.requireSetup.exempt must be a function: ({ user }) => boolean.') } // by the constructor itself, not by its name if (exempt.constructor === ASYNC_FUNCTION) { throw new Error( '[iapl] twoFactor.requireSetup.exempt must not be async: it is called in access checks, which cannot wait, and a Promise ' + 'would count as "exempt" for every account. Return true or false at once (decide from the fields on `user`).', ) } const complain = (what: string) => { const kind = what.replace(/\(.*\)$/, '') if (exemptComplaints.has(kind)) {return} exemptComplaints.add(kind) console.error(`[iapl] twoFactor.requireSetup.exempt ${what}; it must return true or false at once. The account is NOT exempt.`) } return (args) => { let answer: unknown try { answer = (exempt as (a: typeof args) => unknown)(args) } catch (err) { complain(`threw (${err instanceof Error ? err.message : String(err)})`) return false } if (answer === true) {return true} if (answer !== false && answer !== undefined && answer !== null) { // a Promise that rejects later must not become an unhandled rejection if (typeof (answer as { then?: unknown }).then === 'function') {void (answer as Promise).then(undefined, () => undefined)} complain(`returned ${typeof (answer as { then?: unknown }).then === 'function' ? 'a Promise' : `a ${typeof answer}`}`) } return false } } /** * The fields for the 2FA collection: the window start (data) and, unless `statusField: false`, * its status / reset control (panel). * * iapl adds the data field **whenever 2FA is on**, also with `requireSetup: false` or * `guard: false`: the collection's schema then does not depend on those switches — on Postgres / * SQLite switching the mode off would otherwise drop the column with the next migration, and * switching it on again would hand every account without TOTP a new window. */ export function buildSetupFields({ statusField = true }: { statusField?: boolean } = {}): Field[] { const fields: Field[] = [ { name: SETUP_FROM_FIELD, type: 'date', access: { // Written by the hook below only — never through the API. create: () => false, read: ({ data, doc, req }) => isAdmin(req.user, req.payload) || Boolean(req.user && ((doc ?? data) as { id?: unknown } | undefined)?.id === req.user.id), update: () => false, }, admin: { disableBulkEdit: true, disableListColumn: true, disableListFilter: true, hidden: true }, label: { en: 'Two-step verification: setup open since', pl: 'Weryfikacja dwuetapowa: konfiguracja otwarta od' }, }, ] if (statusField) { fields.push({ name: 'totpSetupStatus', type: 'ui', admin: { components: { Field: '@intecion/ipal-kit/admin#TwoFactorStatusField' }, disableListColumn: true, position: 'sidebar', }, }) } return fields } /** * Stamps `totpSetupFrom`: on create, and when an account that had TOTP loses * its secret (the 2FA package's own remove / admin endpoints). The reset * endpoint below writes the date itself, so it also reopens the window of an * account that never had TOTP. Neither field can be written through the API * (field access), so only server code gets here with them. */ export const stampSetupFrom: CollectionBeforeChangeHook = ({ data, operation, originalDoc }) => { if (!data) {return data} const hadTotp = Boolean((originalDoc as { totpSecret?: unknown } | undefined)?.totpSecret) if (operation === 'create' ? !data[SETUP_FROM_FIELD] : hadTotp && 'totpSecret' in data && !data.totpSecret) { data[SETUP_FROM_FIELD] = new Date().toISOString() } return data } /** * Accounts that existed before the mode have no `totpSetupFrom`. Their window * starts now — at the first start after the upgrade — so nobody is blocked the * moment a site upgrades: each such account gets the full window to set TOTP * up. Runs on every start; after the first there is nothing left to do. * Returns how many accounts it stamped; never throws (a database that has not * been migrated yet must not stop the site). */ export async function backfillSetupFrom(payload: BasePayload, collection: string): Promise { try { const where = { and: [ { or: [{ totpSecret: { exists: false } }, { totpSecret: { equals: '' } }] }, { [SETUP_FROM_FIELD]: { exists: false } }, ], } const { totalDocs } = await payload.count({ collection: collection as never, overrideAccess: true, where: where as never }) if (!totalDocs) {return 0} const data = { [SETUP_FROM_FIELD]: new Date().toISOString() } // One query where the adapter has it (Payload 3.9x); the Local API otherwise. Hooks have nothing to add here. if (typeof payload.db.updateMany === 'function') { await payload.db.updateMany({ collection: collection as never, data: data as never, where: where as never }) } else { await payload.update({ collection: collection as never, data: data as never, overrideAccess: true, where: where as never }) } return totalDocs } catch (err) { // The whole chain: Drizzle's own message is "Failed query: …", and what the database said // ("column … does not exist", "no such column") is in `cause`. const reason = errorChain(err) // On Postgres / SQLite without the migration the column is missing — and then it is not only this step // that fails: every query on the collection selects the column, so EVERY login answers 500 until it exists. // Only the missing column gets this message — a database that cannot be reached is another problem. if (/column .+ does not exist|no such column|unknown column|has no column/i.test(reason)) { payload.logger.error( `[iapl] 2FA: the column for "${SETUP_FROM_FIELD}" is missing on "${collection}" (${reason}). NOBODY CAN LOG IN to the panel until the ` + 'migration that adds it has run — administrators with 2FA included. Run `pnpm payload migrate:create`, commit the migration, and ' + 'have it applied when the new container starts (`prodMigrations` in the database adapter, or `pnpm payload migrate && pnpm start`) — ' + 'not in a pre-deployment command, which runs in the old container (docs/deployment.md §4.3, docs/security.md "Setup required" → Data).', ) } else { payload.logger.warn(`[iapl] 2FA: could not start the setup window for existing accounts (${reason}).`) } return 0 } } /** The messages of an error and of everything in its `cause` chain, outermost first. */ export function errorChain(err: unknown): string { const parts: string[] = [] const seen = new Set() for (let current: unknown = err; current !== undefined && current !== null && !seen.has(current) && parts.length < 6; current = (current as { cause?: unknown }).cause) { seen.add(current) const message = current instanceof Error || typeof (current as { message?: unknown }).message === 'string' ? String((current as { message: unknown }).message) : typeof current === 'string' ? current : '' if (message && !parts.includes(message)) {parts.push(message)} if (typeof current !== 'object') {break} } return parts.join(' — ') || String(err) } export type TwoFactorResetOptions = { /** * Who may reset another account's TOTP. Default: a staff admin whose session has **entered its * TOTP code** (`_strategy: 'totp'`) — not an API key, and not an account `requireSetup.exempt` * lets work on its password. With your own function the session must still not owe a second * factor (`secondFactorPassed`), and the rest is yours: an API-key or exempt admin passes only * if you return true for it (`req.user._strategy` tells them apart). */ access?: (args: { req: PayloadRequest }) => boolean | Promise /** * Whether the request may come from where the browser says it comes from (sameOrigin.ts). False = * refused (403) before anything is read or changed. The plugin passes the `twoFactor.sameOrigin` rule * (on by default; `sameOrigin: false` leaves it out). Without it the endpoint takes a cross-origin * `text/plain` POST — no CORS preflight — so a page on a sibling subdomain, which the browser sends the * admin's `SameSite=Lax` cookie to, could reset any account's TOTP and end its sessions. */ ownOrigin?: (req: PayloadRequest) => boolean } /** * POST /api/ipal/two-factor/reset `{ userId }` — clears that account's TOTP * secret **and its sessions**. The account must log in and set TOTP up again, * and its setup window starts anew. For a lost phone, and to reopen setup for * an account whose window has passed. Admins only, and only after their own * TOTP code. * * The sessions go because a reset is also what an administrator presses for an * account that may be in someone else's hands: a session that had passed 2FA * would otherwise be a password-less way to enrol a new authenticator * (`/api/setup-totp` asks for no password). With `auth.useSessions: false` * there is nothing to clear — tokens then live until they expire. */ export function buildTwoFactorResetEndpoint(collection: string, options: TwoFactorResetOptions = {}): Endpoint { return { handler: async (req) => { const i18n = req.i18n as Parameters[0] const allowed = Boolean(req.user) && secondFactorPassed(req) && (req.user as { collection?: unknown }).collection === collection && (options.access ? (await options.access({ req })) === true : (req.user as { _strategy?: unknown })._strategy === 'totp' && userMeetsRole(req, 'admin')) if (!allowed) {return Response.json({ message: serverText(i18n, 'twoFactorResetForbidden'), ok: false }, { status: 403 })} if (options.ownOrigin && !options.ownOrigin(req)) {return Response.json({ message: 'Not allowed from this origin.', ok: false }, { status: 403 })} let body: unknown try { body = await req.json?.() } catch { body = undefined } const userId = (body as { userId?: unknown } | undefined)?.userId if (typeof userId !== 'string' && typeof userId !== 'number') { return Response.json({ message: serverText(i18n, 'twoFactorResetFailed'), ok: false }, { status: 400 }) } try { const useSessions = (req.payload.collections as Record)[collection]?.config?.auth?.useSessions !== false const data = { [SETUP_FROM_FIELD]: new Date().toISOString(), totpSecret: null, ...(useSessions ? { sessions: [] } : {}) } await req.payload.update({ id: userId, collection: collection as never, data: data as never, overrideAccess: true, req }) } catch (err) { req.payload.logger.error(`[iapl] 2FA reset failed: ${err instanceof Error ? err.message : String(err)}`) return Response.json({ message: serverText(i18n, 'twoFactorResetFailed'), ok: false }, { status: 400 }) } const actor = (req.user as { email?: string; id?: unknown }).email ?? String((req.user as { id?: unknown }).id) req.payload.logger.info(`[iapl] 2FA reset for ${collection} ${String(userId)} by ${actor}.`) return Response.json({ message: serverText(i18n, 'twoFactorResetDone'), ok: true }) }, method: 'post', path: TWO_FACTOR_RESET_PATH, } } /** Accounts of the 2FA collection without TOTP, and how many of those are past their setup window. */ export async function countAccountsWithoutTotp(payload: BasePayload, collection: string, setupWindowMs = 0): Promise<{ blocked: number; without: number }> { const none = { or: [{ totpSecret: { exists: false } }, { totpSecret: { equals: '' } }] } const without = (await payload.count({ collection: collection as never, overrideAccess: true, where: none as never })).totalDocs if (!without || !setupWindowMs) {return { blocked: 0, without }} const limit = new Date(Date.now() - setupWindowMs).toISOString() const blocked = (await payload.count({ collection: collection as never, overrideAccess: true, where: { and: [none, { [SETUP_FROM_FIELD]: { less_than: limit } }] } as never })).totalDocs return { blocked, without } }