Security review fixes: staff collection first everywhere, 2FA package endpoints guarded, per-entity opt-out, hot reload

F1: roles count only for accounts of a staff collection, in every exported
predicate and access builder (isAdmin, isEditor, hasMinimumRole, adminOnly,
adminOrEditor, requireRole, adminOrSelf, adminOrSelfIn, the Field variants,
the roles field) and first in userMeetsRole. An account of another auth
collection with its own roles: ['admin'] gets nothing. Staff collections:
admin.user, access.authCollection, access.staffCollections. Predicates take
req.payload as an optional last argument and otherwise use the staff
collections of the config ipalKit built in this process.

F2: every endpoint @clocklimited/payload-2fa registers answers accounts of
the 2FA collection only (setup-totp wrote the secret into the 2FA collection
under the caller's id, whatever collection the caller came from); remove and
the admin reset/remove endpoints also need the second factor.

F3: per-entity opt-out honoured, operation by operation: the package's
custom.totp.disableAccessWrapper and ipal-kit's custom.ipal.secondFactor
(passed on to the package); the package's global disableAccessWrapper too.

F4: a no-user auth strategy on the 2FA collection guards the live config at
the start of each request, so entities from plugins listed after ipalKit
stay guarded after a dev hot reload and with disableOnInit.

Tests through HTTP for all four; the 2FA tests now run on payload-2fa
3.0.0-beta.7 (what client sites use), a second file on beta.1 (alias), and
the HTTP files can run against Postgres (IPAL_TEST_POSTGRES_URI). Docs,
agent guide, skills and changelog updated; the not-yet-enrolled limitation
is stated plainly.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 01:02:34 +01:00
co-authored by Claude Fable 5.2
parent 97ee1289aa
commit 32faaa5e30
30 changed files with 836 additions and 187 deletions
+133 -18
View File
@@ -74,47 +74,162 @@ const COLLECTION_OPERATIONS = ['create', 'delete', 'read', 'readVersions', 'unlo
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
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
/**
* 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 }
}
/** 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,
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,
),
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. Called from ipalKit's onInit; returns the slugs it had to guard.
* added. Returns the slugs it had to guard.
*/
export function guardPayloadAccess(payload: BasePayload): string[] {
export function guardPayloadAccess(payload: Pick<BasePayload, 'config'>): string[] {
if (wrapperDisabled(payload.config.custom)) {return []}
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}
const sweep = (entity: GuardedEntity, operations: readonly string[]) => {
const todo = unguarded(entity, operations)
if (!todo.length) {return}
late.push(entity.slug)
entity.access = guardAccessMap(access, operations)
const access: AccessMap = { ...(entity.access as AccessMap | undefined) }
for (const op of todo) {access[op] = requireSecondFactor(access[op])}
entity.access = access
}
// 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)}
if (!c.slug.startsWith('payload-')) {sweep(c as GuardedEntity, COLLECTION_OPERATIONS)}
}
for (const g of payload.config.globals ?? []) {sweep(g, GLOBAL_OPERATIONS)}
for (const g of payload.config.globals ?? []) {sweep(g as GuardedEntity, GLOBAL_OPERATIONS)}
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 (empty when already done). */
export function ensurePayloadGuarded(payload: Pick<BasePayload, 'config'>): string[] {
const config = payload?.config
if (!config || swept.has(config)) {return []}
swept.add(config)
return guardPayloadAccess(payload)
}
/** 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(onLate?: (payload: BasePayload, slugs: string[]) => void) {
return {
name: GUARD_STRATEGY_NAME,
authenticate: ({ payload }: { payload: BasePayload }) => {
const late = ensurePayloadGuarded(payload)
if (late.length) {onLate?.(payload, late)}
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 function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collection: string): 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: ((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()}
return handler(req)
}) as unknown as T['handler'],
}
}
/**
* 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