Security: staff checks only for staff collections; 2FA covers what the plugin adds

Staff check (userMeetsRole): the 'no roles field = every account passes'
rule applied to the account's own collection, so an account of a second
auth collection (customers) passed every staff check. It now applies only
to staff collections: the panel's login collection plus the new
access.staffCollections. The injected auth collection uses the new
adminOrSelfIn(slug), so an account of another collection with the same
numeric id is not 'self'.

2FA: @clocklimited/payload-2fa wraps the collections and globals present
when it runs; ipalKit's own globals and collections were added later and
stayed unwrapped, so a password without the TOTP code opened them over
REST and GraphQL. ipal-kit now has its own second-factor check
(secondFactorPassed / requireSecondFactor): applied to every collection
and global at the end of ipalKit, again in onInit for entities added by
plugins listed after it, and inside userMeetsRole and the endpoints that
take a project access function. It fails closed: an unrecognised user
shape is refused, and startup stops when the injected 2FA plugin lacks
the parts the check reads (twoFactor.guard: false opts out).

Tests through real HTTP requests (REST and GraphQL) against Payload's
route handlers, plus the reference smoke test. Docs, agent guide, skills
and the reference skills copy updated; changelog entry without a version.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 00:31:55 +01:00
co-authored by Claude Fable 5.2
parent bc1045a5b7
commit 0c61ac231b
40 changed files with 1224 additions and 63 deletions
+134
View File
@@ -0,0 +1,134 @@
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.
*
* 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 }
if (u.collection !== guard.collection) {return true}
if (u._strategy === 'totp' || u._strategy === 'api-key') {return true}
return u.hasTotp === false
}
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)) }
*/
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>
function guardAccessMap(access: AccessMap | undefined, operations: readonly string[]): AccessMap {
const out: AccessMap = { ...access }
for (const op of operations) {out[op] = requireSecondFactor(out[op])}
return out
}
/** Every collection and global of a (not yet sanitized) config, guarded. Returns a new config. */
export function guardConfigAccess(config: Config): Config {
return {
...config,
collections: (config.collections ?? []).map(
(c) => ({ ...c, access: guardAccessMap(c.access as AccessMap | undefined, COLLECTION_OPERATIONS) }) as CollectionConfig,
),
globals: (config.globals ?? []).map(
(g) => ({ ...g, access: guardAccessMap(g.access as AccessMap | undefined, GLOBAL_OPERATIONS) }) as GlobalConfig,
),
}
}
/**
* The same for a running Payload, in place: what plugins listed after ipalKit
* added. Called from ipalKit's onInit; returns the slugs it had to guard.
*/
export function guardPayloadAccess(payload: BasePayload): string[] {
const late: string[] = []
const sweep = (entity: { access?: unknown; slug: string }, operations: readonly string[]) => {
const access = (entity.access ?? {}) as AccessMap
if (operations.every((op) => (access[op] as Guarded | undefined)?.[GUARDED])) {return}
late.push(entity.slug)
entity.access = guardAccessMap(access, operations)
}
// Payload's own collections (payload-preferences, payload-locked-documents, …) keep their rules:
// the panel uses them before the code is entered, and the package leaves them alone too.
for (const c of payload.config.collections ?? []) {
if (!c.slug.startsWith('payload-')) {sweep(c, COLLECTION_OPERATIONS)}
}
for (const g of payload.config.globals ?? []) {sweep(g, GLOBAL_OPERATIONS)}
return late
}
/**
* 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
}