import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payload' /** * ipal-kit's own second-factor check, next to the access wrapper of * @clocklimited/payload-2fa. * * Why it exists: the package wraps the `access` functions of the collections * and globals that are in the config at the moment it runs. Whatever is added * afterwards — ipal-kit's globals and collections, a plugin listed after * ipalKit — was left unwrapped, so a staff password without the TOTP code * opened it over the API. This check does not depend on that order: ipalKit * applies it to everything in the config when it finishes, and again in onInit * to whatever other plugins added later; `userMeetsRole` asks it too. * * Every way past this check, and why it is safe — keep this list complete: * 1. no user → the access function itself decides (anonymous visitors); * 2. 2FA off or `twoFactor.guard: false` → there is no check (the project's choice); * 3. an account of another auth collection → 2FA is about ONE collection; such an * account is not staff unless the project names its collection in * `access.staffCollections` (then it is staff WITHOUT a second factor — ipalKit * logs a warning at start); * 4. `_strategy === 'totp'` → set by the package's strategy after password and code; * 5. `_strategy === 'api-key'` → an API key is its own credential (the package's rule); * 6. `hasTotp === false` (TOTP not set up yet) → only when setup is not required * (`twoFactor.requireSetup: false`) or the project's `exempt` says so for that account; * by default such an account is refused like one that owes its code; * 7. per-entity opt-out in the project's config (`custom.totp.disableAccessWrapper`, * `custom.ipal.secondFactor`), or the package's global `disableAccessWrapper`; * 8. `access.admin` (may this account open the panel) is not wrapped: the code is * entered inside the panel; * 9. endpoints are not access functions: the plugin's own check `userMeetsRole` / * `secondFactorPassed`, the 2FA package's are wrapped (guardTotpEndpoint), a * project's own must call `secondFactorPassed(req)`; * 10. the Local API with `overrideAccess: true` (server code). * There is no exception by slug, name or prefix, and a user object the check cannot * read (no `collection`, an unknown `_strategy`, no `hasTotp`) is refused. * * It fails closed. An account of the 2FA collection passes only when * - it came through the package's `totp` strategy (password AND code), or * - it authenticated with an API key (the package's own rule), or * - TOTP is not set up on it yet AND setup is not required * (`twoFactor.requireSetup: false`), or the project exempts the account. * Anything else — code not entered, TOTP not set up yet, or a user object this * check does not understand (a renamed strategy, no `hasTotp`) — is refused. * * "Setup required" (the default): an account without TOTP reaches nothing at * the access level. It does not need to: the setup screen is rendered from the * session, and `/api/setup-totp` is an endpoint that writes with * `overrideAccess`. It is the same state an account is in between its password * and its code. The package alone only redirects such an account in the panel. */ /** What ipalKit records in `config.custom.ipal.twoFactor` when 2FA is on and the guard is not switched off. */ export type TwoFactorGuardConfig = { collection: string /** The project's exemption for accounts that never set TOTP up (a service account logging in with a password). */ exempt?: (args: { user: Record }) => boolean /** An account without TOTP is refused everything until it is set up. */ requireSetup?: boolean /** How long after `totpSetupFrom` setup stays possible, in ms. 0 / undefined = no limit. */ setupWindowMs?: number } /** Field on the 2FA collection: when the current setup window opened (account created, or an admin reset). */ export const SETUP_FROM_FIELD = 'totpSetupFrom' /** * Where an account stands with TOTP setup: * - `not-applicable`: no user, another collection, 2FA or the guard off; * - `set-up`: TOTP is set up; * - `exempt`: not set up, and the project exempts it (or setup is not required); * - `open`: not set up, may set it up now; * - `closed`: not set up and the setup window has passed — blocked until an admin reopens it. */ export type TwoFactorSetupState = 'closed' | 'exempt' | 'not-applicable' | 'open' | 'set-up' /** * The moment setup closes for this account, or null (no window, or no start recorded yet). * A start that is missing or unreadable counts as "no deadline yet" (the account can still only * set TOTP up): only server code writes the field, and the start-up step fills in a missing one. */ export function twoFactorSetupDeadline({ payload, user }: MaybeReq): Date | null { const guard = guardConfig(payload) const from = (user as null | Record | undefined)?.[SETUP_FROM_FIELD] if (!guard?.setupWindowMs || (typeof from !== 'string' && !(from instanceof Date))) {return null} const start = new Date(from).getTime() return Number.isFinite(start) ? new Date(start + guard.setupWindowMs) : null } export function twoFactorSetupState({ payload, user }: MaybeReq, now: number = Date.now()): TwoFactorSetupState { const guard = guardConfig(payload) if (!guard || !user || typeof user !== 'object') {return 'not-applicable'} const u = user as { collection?: unknown; hasTotp?: unknown } if (u.collection !== guard.collection) {return 'not-applicable'} if (u.hasTotp !== false || (user as { totpSecret?: unknown }).totpSecret) {return 'set-up'} if (!guard.requireSetup || guard.exempt?.({ user: user as Record }) === true) {return 'exempt'} const deadline = twoFactorSetupDeadline({ payload, user }) return deadline && deadline.getTime() < now ? 'closed' : 'open' } type MaybeReq = { payload?: Pick; user?: unknown } const guardConfig = (payload: MaybeReq['payload']): TwoFactorGuardConfig | undefined => (payload?.config?.custom as { ipal?: { twoFactor?: TwoFactorGuardConfig } } | undefined)?.ipal?.twoFactor /** * False for an account that still owes the second factor: it belongs to the * 2FA collection and either has TOTP set up and has not entered the code in * this session, or has not set TOTP up at all (unless setup is not required * or the project exempts it). True for everyone else — no user (the access * function decides), accounts of other auth collections, 2FA off (`twoFactor: false`). * * Pass `req`. Use it in your own endpoints and access functions: * if (!secondFactorPassed(req)) return Response.json({ ok: false }, { status: 403 }) */ export function secondFactorPassed({ payload, user }: MaybeReq): boolean { if (!user || typeof user !== 'object') {return true} const guard = guardConfig(payload) if (!guard) {return true} const u = user as { _strategy?: unknown; collection?: unknown; hasTotp?: unknown } // A user object that does not say which collection it is from cannot be told apart from a // 2FA account: refused. (Payload's strategies and payload.auth() always set `collection`.) if (typeof u.collection !== 'string') {return false} if (u.collection !== guard.collection) {return true} if (u._strategy === 'totp' || u._strategy === 'api-key') {return true} // "Not set up yet" only when nothing says otherwise. The package computes `hasTotp` with a second // database read and answers false when that read fails; the secret on the user object itself (it // came with the account's own record) then still says the account has TOTP: refused. if (u.hasTotp !== false || (user as { totpSecret?: unknown }).totpSecret) {return false} // TOTP not set up: only when setup is not required, or for an account the project exempts // Exactly `true`: a Promise or any other truthy answer must never let an account in. return !guard.requireSetup || guard.exempt?.({ user: user as Record }) === true } const GUARDED = Symbol.for('ipal.secondFactorGuard') type AnyAccess = (args: never) => unknown type Guarded = { [GUARDED]?: true } & AnyAccess /** * Wraps one access function: refused while the second factor is owed, * otherwise the function itself (or Payload's default, "logged in", when there * is none). Wrapping twice is harmless — an already wrapped function is returned as is. * * access: { read: requireSecondFactor(({ req }) => isAdmin(req.user, req.payload)) } */ export function requireSecondFactor(access?: T): T { if (access && (access as Guarded)[GUARDED]) {return access} const wrapped = ((args: { req: MaybeReq }) => { if (!secondFactorPassed(args.req)) {return false} return access ? access(args as never) : Boolean(args.req?.user) }) as unknown as Guarded wrapped[GUARDED] = true return wrapped as unknown as T } /** `admin` (may this account open the panel) stays unwrapped: the code is entered inside the panel. */ const COLLECTION_OPERATIONS = ['create', 'delete', 'read', 'readVersions', 'unlock', 'update'] as const const GLOBAL_OPERATIONS = ['read', 'readDrafts', 'readVersions', 'update'] as const type AccessMap = Record type GuardedEntity = { access?: unknown; custom?: Record; slug: string } type ConfigCustom = { totp?: { pluginOptions?: { disableAccessWrapper?: boolean } } } | undefined /** * Per-entity opt-out, operation by operation — the project's decision that * this collection or global may be reached with the password alone: * - the 2FA package's own key: `custom.totp.disableAccessWrapper.: true` * (the package leaves that operation unwrapped; so does ipal-kit); * - ipal-kit's key, for entities the package never sees (added after it ran): * `custom.ipal.secondFactor: false` (every operation) or `{ : false }`. */ function optedOut(entity: GuardedEntity, operation: string): boolean { const custom = entity.custom as | { ipal?: { secondFactor?: false | Record }; totp?: { disableAccessWrapper?: Record } } | undefined if (custom?.totp?.disableAccessWrapper?.[operation]) {return true} const own = custom?.ipal?.secondFactor return own === false || (typeof own === 'object' && own?.[operation] === false) } /** * Before the 2FA package runs: ipal-kit's opt-out written in the package's own * key as well, so the package leaves those operations unwrapped too. */ export function passOptOutsToPackage(config: Config): Config { const translate = (entity: T, operations: readonly string[]): T => { const off = operations.filter((op) => optedOut(entity, op)) if (!off.length) {return entity} const totp = (entity.custom?.totp ?? {}) as { disableAccessWrapper?: Record } return { ...entity, custom: { ...entity.custom, totp: { ...totp, disableAccessWrapper: { ...totp.disableAccessWrapper, ...Object.fromEntries(off.map((op) => [op, true])) } } }, } } return { ...config, collections: (config.collections ?? []).map((c) => translate(c as GuardedEntity, COLLECTION_OPERATIONS) as CollectionConfig), globals: (config.globals ?? []).map((g) => translate(g as GuardedEntity, GLOBAL_OPERATIONS) as GlobalConfig), } } /** The package's global switch (`disableAccessWrapper: true` passed to its factory): no access wrapping at all. */ const wrapperDisabled = (custom: unknown): boolean => Boolean((custom as ConfigCustom)?.totp?.pluginOptions?.disableAccessWrapper) /** The operations of one entity that still need the guard. */ function unguarded(entity: GuardedEntity, operations: readonly string[]): string[] { const access = (entity.access ?? {}) as AccessMap return operations.filter((op) => !optedOut(entity, op) && !(access[op] as Guarded | undefined)?.[GUARDED]) } function guardEntity(entity: T, operations: readonly string[]): T { const todo = unguarded(entity, operations) if (!todo.length) {return entity} const access: AccessMap = { ...(entity.access as AccessMap | undefined) } for (const op of todo) {access[op] = requireSecondFactor(access[op])} return { ...entity, access } } /** * The job queue has its own rules outside any collection: `jobs.access.run / queue / cancel` * (POST /api/payload-jobs/run, `payload.jobs.queue()` / `.cancel()` with `overrideAccess: false`). * * Payload's defaults are kept exactly, by not inventing any: only a rule that EXISTS is wrapped * ("…and not while the second factor is owed"). At config time that is what the project wrote; * when Payload builds the config it fills the rest in itself (3.94.1, config/defaults.js: `run`, * `queue` and `cancel` are all `defaultAccess`, a logged-in user — the `?? (() => true)` in * queues/localAPI.js is never reached on a built config), and the sweep of the running config * wraps those. So a request without a user gets whatever Payload itself answers. */ const JOB_OPERATIONS = ['cancel', 'queue', 'run'] as const type JobsLike = { access?: AccessMap } | undefined function guardJobs(jobs: T): T { if (!jobs?.access) {return jobs} const access: AccessMap = { ...jobs.access } for (const op of JOB_OPERATIONS) { if (access[op]) {access[op] = requireSecondFactor(access[op])} } return { ...jobs, access } } /** Every collection and global of a (not yet sanitized) config, guarded. Returns a new config. */ export function guardConfigAccess(config: Config): Config { if (wrapperDisabled(config.custom)) {return config} return { ...config, ...(config.jobs ? { jobs: guardJobs(config.jobs as JobsLike) as Config['jobs'] } : {}), collections: (config.collections ?? []).map((c) => guardEntity(c as GuardedEntity, COLLECTION_OPERATIONS) as CollectionConfig), globals: (config.globals ?? []).map((g) => guardEntity(g as GuardedEntity, GLOBAL_OPERATIONS) as GlobalConfig), } } /** * The same for a running Payload, in place: what plugins listed after ipalKit * added, and what Payload itself adds when it sanitizes the config. Returns * the slugs it had to guard. * * EVERY collection and global is guarded — there is no exception by name or * prefix. That includes Payload's own collections (in 3.94.1: * payload-preferences, payload-locked-documents, payload-migrations, * payload-query-presets, payload-folders, payload-jobs, payload-kv and the * global payload-jobs-stats) and any a later Payload adds: an account that * still owes its code needs none of them — the verify and setup screens are * rendered from the session. A plugin that names its collection `payload-…` * (e.g. `payload-mcp-api-keys`) is therefore covered like any other. */ export function guardPayloadAccess(payload: Pick): string[] { if (wrapperDisabled(payload.config.custom)) {return []} const late: string[] = [] const sweep = (entity: GuardedEntity, operations: readonly string[]) => { const todo = unguarded(entity, operations) if (!todo.length) {return} late.push(entity.slug) const access: AccessMap = { ...(entity.access as AccessMap | undefined) } for (const op of todo) {access[op] = requireSecondFactor(access[op])} entity.access = access } for (const c of payload.config.collections ?? []) {sweep(c as GuardedEntity, COLLECTION_OPERATIONS)} for (const g of payload.config.globals ?? []) {sweep(g as GuardedEntity, GLOBAL_OPERATIONS)} const jobs = (payload.config as { jobs?: JobsLike }).jobs if (jobs?.access && JOB_OPERATIONS.some((op) => jobs.access?.[op] && !(jobs.access[op] as Guarded)[GUARDED])) { jobs.access = guardJobs(jobs).access late.push('jobs') } return late } /** Configs already swept — a new sanitized config (start, dev hot reload) is swept once. */ const swept = new WeakSet() /** * Sweeps `payload.config` once per config object. Returns the slugs guarded * now, or null when this config was swept before. */ export function ensurePayloadGuarded(payload: Pick): null | string[] { const config = payload?.config if (!config || swept.has(config)) {return null} swept.add(config) return guardPayloadAccess(payload) } /** * Makes `payload.config` an accessor on this instance, so the moment Payload * swaps the config (its dev `reload()` assigns `payload.config = …` and runs no * onInit) `onConfig` is called — before any request or Local API call can use * the new config. Without it the first HTTP request would do the same (the * guard strategy), but a Local API call made before that request would meet * unguarded entities from plugins listed after ipalKit. Never throws. */ export function watchPayloadConfig(payload: BasePayload, onConfig: (payload: BasePayload) => void): void { try { const own = Object.getOwnPropertyDescriptor(payload, 'config') if (!own || own.get || !own.configurable) {return} let current = own.value as BasePayload['config'] Object.defineProperty(payload, 'config', { configurable: true, enumerable: own.enumerable ?? true, get: () => current, set: (next: BasePayload['config']) => { current = next try { onConfig(payload) } catch { // the guard strategy repeats it on the next request } }, }) } catch { // an instance we cannot instrument: the guard strategy still covers HTTP } } /** Name of the auth strategy ipalKit adds to the 2FA collection (see buildGuardStrategy). */ export const GUARD_STRATEGY_NAME = 'ipal-second-factor-guard' /** * An auth strategy that authenticates nobody. Payload runs every strategy at * the start of every request, before any access function, so this is the one * place ipal-kit is called on each request with the config that is live right * now. It makes sure that config is guarded — also after a dev hot reload, * where Payload swaps in a freshly built config and does not run onInit, and * when Payload was started with `disableOnInit`. */ export function buildGuardStrategy(onConfig?: (payload: BasePayload) => void) { return { name: GUARD_STRATEGY_NAME, authenticate: ({ payload }: { payload: BasePayload }) => { if (onConfig) { onConfig(payload) } else { ensurePayloadGuarded(payload) } return { user: null } }, } } /** The 2FA package's endpoints an account uses BEFORE it has passed the second factor. */ const BEFORE_SECOND_FACTOR = new Set(['/setup-totp', '/verify-totp']) type EndpointLike = { handler: (req: never) => Promise | Response; path: string } /** * Guards one endpoint the 2FA package registered. The package trusts * `req.user` whatever collection it comes from: `/setup-totp` writes the TOTP * secret into the 2FA collection under the CALLER's id, so with numeric ids an * account of another auth collection could set the secret of the staff account * that has the same id. So: * - a logged-in account of another collection is refused on every endpoint * of the package (no user: the package answers as before); * - everything except setup and verify (remove, the admin reset / remove * endpoints, whatever a later version adds) also needs the second factor, * so a password alone cannot reset or remove TOTP. */ export type TotpEndpointGuards = { /** * Called for a verify attempt of a logged-in account before the package sees * it. Return a Response to refuse (too many attempts), null to let it through. */ limitVerify?: (req: never) => null | Promise | Response /** The answer for an account whose setup window has passed (in the caller's language). Default: a plain 403. */ onSetupClosed?: (req: never) => Response /** * Whether a verify / setup attempt may come from where the browser says it comes from * (sameOrigin.ts). False = refused, and NOT counted against the verify limit. */ ownOrigin?: (req: never) => boolean } export function guardTotpEndpoint(endpoint: T, collection: string, guards: TotpEndpointGuards = {}): T { const handler = endpoint.handler as (req: MaybeReq) => Promise | Response const refused = () => Response.json({ message: 'Not allowed.', ok: false }, { status: 403 }) return { ...endpoint, handler: (async (req: MaybeReq) => { const user = req.user as { collection?: unknown } | null | undefined if (user && user.collection !== collection) {return refused()} if (user && !BEFORE_SECOND_FACTOR.has(endpoint.path) && !secondFactorPassed(req)) {return refused()} // Setup after the window: blocked until an admin reopens it. if (user && endpoint.path === '/setup-totp' && twoFactorSetupState(req) === 'closed') { return guards.onSetupClosed ? guards.onSetupClosed(req as never) : refused() } // An attempt a browser marks as coming from another origin is refused before it is counted: // otherwise another page could burn the owner's attempts and lock them out, without the password. if (user && (endpoint.path === '/verify-totp' || endpoint.path === '/setup-totp') && guards.ownOrigin && !guards.ownOrigin(req as never)) { return Response.json({ message: 'Not allowed from this origin.', ok: false }, { status: 403 }) } // The code has about three right answers in a million and the package never counts tries. if (user && endpoint.path === '/verify-totp' && guards.limitVerify) { const limited = await guards.limitVerify(req as never) if (limited) {return limited} } return handler(req) }) as unknown as T['handler'], } } /** * The same for endpoints the package may register on a collection or a global * (none in the versions seen; a later one might): every endpoint that was not * there before the package ran gets `guardTotpEndpoint`. */ export function guardNewEntityEndpoints( entities: T[] | undefined, before: Map>, collection: string, guards?: TotpEndpointGuards, ): T[] { return (entities ?? []).map((entity) => { if (!Array.isArray(entity.endpoints)) {return entity} const known = before.get(entity.slug) ?? new Set() if (entity.endpoints.every((e) => known.has(e))) {return entity} return { ...entity, endpoints: entity.endpoints.map((e) => (known.has(e) ? e : guardTotpEndpoint(e as EndpointLike, collection, guards))) } }) } /** * The parts of @clocklimited/payload-2fa the guard relies on, checked right * after the injected factory ran. A missing part means a version this guard * was not written for: it would refuse every staff request, or — worse — the * package itself may no longer protect what it used to. Returns what is * missing; ipalKit refuses to start with it. */ export function missingTotpParts(config: Config, collection: string): string[] { const target = (config.collections ?? []).find((c) => c.slug === collection) const fields = (target?.fields ?? []) as Array<{ name?: string }> const strategies = typeof target?.auth === 'object' ? (target.auth.strategies ?? []) : [] const missing: string[] = [] if (!fields.some((f) => f.name === 'totpSecret')) {missing.push('the `totpSecret` field')} if (!fields.some((f) => f.name === 'hasTotp')) {missing.push('the `hasTotp` field')} if (!strategies.some((s) => s.name === 'totp')) {missing.push('the `totp` auth strategy')} return missing }