Job queue (R3-1): only a rule that exists is wrapped. At config time that is what the project wrote; Payload fills in the rest when it builds the config (3.94.1: run, queue and cancel are all defaultAccess, a logged-in user) and the sweep of the running config wraps those. No default is invented, so a request without a user gets what Payload itself answers. hasTotp false while the account's record carries a TOTP secret (the 2FA package's own lookup failed, R3-4): the account owes its code, not 'not set up yet'. Docs: the two-configs-in-one-process case for calls without a source, and that a half-logged-in editor's browser is refused media files. Co-Authored-By: Claude Fable 5.2 <[email protected]>
381 lines
19 KiB
TypeScript
381 lines
19 KiB
TypeScript
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 (the setup screen needs the session);
|
|
* 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 (`hasTotp === false`) — the setup screen
|
|
* needs that, and the package lets such an account through as well.
|
|
* Anything else — code not entered, or a user object this check does not
|
|
* understand (a renamed strategy, no `hasTotp`) — is refused.
|
|
*/
|
|
|
|
/** What ipalKit records in `config.custom.ipal.twoFactor` when 2FA is on and the guard is not switched off. */
|
|
export type TwoFactorGuardConfig = { collection: string }
|
|
|
|
type MaybeReq = { payload?: Pick<BasePayload, 'config'>; user?: unknown }
|
|
|
|
const guardConfig = (payload: MaybeReq['payload']): TwoFactorGuardConfig | undefined =>
|
|
(payload?.config?.custom as { ipal?: { twoFactor?: TwoFactorGuardConfig } } | undefined)?.ipal?.twoFactor
|
|
|
|
/**
|
|
* False only for an account that still owes the second factor: it belongs to
|
|
* the 2FA collection, has TOTP set up and has not entered the code in this
|
|
* session. 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.
|
|
return u.hasTotp === false && !(user as { totpSecret?: unknown }).totpSecret
|
|
}
|
|
|
|
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<T extends AnyAccess>(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<string, AnyAccess | undefined>
|
|
type GuardedEntity = { access?: unknown; custom?: Record<string, unknown>; 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.<operation>: 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 `{ <operation>: false }`.
|
|
*/
|
|
function optedOut(entity: GuardedEntity, operation: string): boolean {
|
|
const custom = entity.custom as
|
|
| { ipal?: { secondFactor?: false | Record<string, boolean> }; totp?: { disableAccessWrapper?: Record<string, boolean> } }
|
|
| 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 = <T extends GuardedEntity>(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<string, boolean> }
|
|
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<T extends GuardedEntity>(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<T extends JobsLike>(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<BasePayload, 'config'>): 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<object>()
|
|
|
|
/**
|
|
* 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<BasePayload, 'config'>): 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> | 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<null | Response> | Response
|
|
}
|
|
|
|
export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collection: string, guards: TotpEndpointGuards = {}): T {
|
|
const handler = endpoint.handler as (req: MaybeReq) => Promise<Response> | 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()}
|
|
// 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<T extends { endpoints?: unknown; slug: string }>(
|
|
entities: T[] | undefined,
|
|
before: Map<string, Set<unknown>>,
|
|
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
|
|
}
|