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
+14 -12
View File
@@ -8,17 +8,17 @@ import { hasMinimumRole, isAdmin } from './predicates.js'
* Collection-level access (returns boolean | Where).
* Use in collection `access.read/create/update/delete`.
*/
export const adminOnly: Access = ({ req: { user } }) => isAdmin(user)
export const adminOnly: Access = ({ req }) => isAdmin(req.user, req.payload)
export const adminOrEditor: Access = ({ req: { user } }) => hasMinimumRole(user, 'editor')
export const adminOrEditor: Access = ({ req }) => hasMinimumRole(req.user, 'editor', req.payload)
export const authenticated: Access = ({ req: { user } }) => Boolean(user)
/** Requires at least the given role. */
export const requireRole =
(minimum: Role): Access =>
({ req: { user } }) =>
hasMinimumRole(user, minimum)
({ req }) =>
hasMinimumRole(req.user, minimum, req.payload)
/**
* Admins see all; others are constrained to their own document.
@@ -28,8 +28,9 @@ export const requireRole =
* `adminOrSelfIn(slug)` instead: with numeric ids (Postgres, SQLite) customer
* no. 5 would otherwise match staff account no. 5.
*/
export const adminOrSelf: Access = ({ req: { user } }) => {
if (isAdmin(user)) {return true}
export const adminOrSelf: Access = ({ req }) => {
const { user } = req
if (isAdmin(user, req.payload)) {return true}
if (!user) {return false}
return { id: { equals: user.id } }
}
@@ -42,8 +43,9 @@ export const adminOrSelf: Access = ({ req: { user } }) => {
*/
export const adminOrSelfIn =
(slug: string): Access =>
({ req: { user } }) => {
if (isAdmin(user)) {return true}
({ req }) => {
const { user } = req
if (isAdmin(user, req.payload)) {return true}
if (!user || (user as { collection?: unknown }).collection !== slug) {return false}
return { id: { equals: user.id } }
}
@@ -52,12 +54,12 @@ export const adminOrSelfIn =
* Field-level access (returns boolean only — no Where support).
* Use in field `access.read/update`.
*/
export const adminOnlyField: FieldAccess = ({ req: { user } }) => isAdmin(user)
export const adminOnlyField: FieldAccess = ({ req }) => isAdmin(req.user, req.payload)
export const adminOrEditorField: FieldAccess = ({ req: { user } }) => hasMinimumRole(user, 'editor')
export const adminOrEditorField: FieldAccess = ({ req }) => hasMinimumRole(req.user, 'editor', req.payload)
/** Requires at least the given role, for field-level access. */
export const requireRoleField =
(minimum: Role): FieldAccess =>
({ req: { user } }) =>
hasMinimumRole(user, minimum)
({ req }) =>
hasMinimumRole(req.user, minimum, req.payload)
+1 -1
View File
@@ -10,7 +10,7 @@ export {
requireRoleField,
} from './access.js'
export { injectRoles } from './injectRoles.js'
export { hasMinimumRole, isAdmin, isEditor, staffCollectionSlugs, userMeetsRole } from './predicates.js'
export { hasMinimumRole, isAdmin, isEditor, registerStaffCollections, staffCollectionSlugs, userMeetsRole } from './predicates.js'
export { buildRolesField } from './rolesField.js'
export type { AccessOption, Role } from './types.js'
export { ROLE_HIERARCHY } from './types.js'
+72 -35
View File
@@ -13,6 +13,52 @@ import { ROLE_HIERARCHY } from './types.js'
*/
type MaybeUser = { roles?: null | Role[] } | null | Record<string, unknown> | undefined
/** `req.payload`, or anything with the sanitized config on it. */
type MaybePayload = null | Pick<BasePayload, 'config'> | undefined
/**
* The staff collections of the config ipalKit last built in this process —
* what the predicates fall back to when they get no `payload` (`isAdmin(req.user)`
* in a hook or an endpoint). `null` where ipalKit never ran: a browser bundle.
*/
let registeredStaff: null | string[] = null
/** Called by ipalKit (config time, then onInit with the sanitized config). Not for projects. */
export function registerStaffCollections(slugs: string[]): void {
registeredStaff = [...new Set(slugs.filter(Boolean))]
}
/**
* The auth collections whose accounts are staff: the one the admin panel logs
* in with (`admin.user`), the one that carries the plugin's roles
* (`access.authCollection`) and `access.staffCollections`. Accounts of any
* other auth collection — customers, members — are visitors to the plugin:
* no role and no staff check counts for them, whatever fields they have.
*/
export function staffCollectionSlugs(payload?: MaybePayload): string[] {
const config = payload?.config
if (!config) {return registeredStaff ?? []}
const extra = (config.custom as { ipal?: { staffCollections?: string[] } } | undefined)?.ipal?.staffCollections ?? []
return [...new Set([config.admin?.user, ...extra].filter((s): s is string => typeof s === 'string' && s !== ''))]
}
/**
* Whether this account's roles may count at all: it belongs to a staff
* collection. Checked before any role. An account without `collection` (a
* user object built by hand) does not count either — pass the user Payload
* authenticated, or add `collection` yourself in server code you trust.
*
* Only where no staff list is known (no `payload` given and ipalKit never ran
* in this bundle — client components) the roles are taken as they are; that is
* for showing or hiding things, never for access control.
*/
function isStaffAccount(user: MaybeUser, payload?: MaybePayload): boolean {
if (!user || typeof user !== 'object') {return false}
if (!payload?.config && registeredStaff === null) {return true}
const slug = (user as { collection?: unknown }).collection
return typeof slug === 'string' && staffCollectionSlugs(payload).includes(slug)
}
/** Safely extracts the roles array from a loosely-typed user. */
function getRoles(user: MaybeUser): Role[] {
if (!user || typeof user !== 'object') {return []}
@@ -29,60 +75,51 @@ function highestRoleIndex(user: MaybeUser): number {
}
/**
* True if the user holds at least the given role in the hierarchy.
* True if the user is a staff account and holds at least the given role.
* admin satisfies 'editor' and 'user'; editor satisfies 'user'.
*
* Pass `req.payload` as the third argument where you have it (access
* functions, hooks, endpoints); without it the staff collections of the
* config ipalKit built in this process are used.
*/
export function hasMinimumRole(user: MaybeUser, minimum: Role): boolean {
export function hasMinimumRole(user: MaybeUser, minimum: Role, payload?: MaybePayload): boolean {
if (!isStaffAccount(user, payload)) {return false}
return highestRoleIndex(user) >= ROLE_HIERARCHY.indexOf(minimum)
}
/** True if the user is an admin. */
export function isAdmin(user: MaybeUser): boolean {
return hasMinimumRole(user, 'admin')
/** True if the user is a staff account with the admin role. */
export function isAdmin(user: MaybeUser, payload?: MaybePayload): boolean {
return hasMinimumRole(user, 'admin', payload)
}
/** True if the user is an editor or higher (editor, admin). */
export function isEditor(user: MaybeUser): boolean {
return hasMinimumRole(user, 'editor')
}
/**
* The auth collections whose accounts are staff: the one the admin panel logs
* in with (`admin.user`) plus `access.staffCollections`. Accounts of any other
* auth collection — customers, members — are visitors to the plugin.
*/
export function staffCollectionSlugs(payload?: Pick<BasePayload, 'config'>): string[] {
const config = payload?.config
if (!config) {return []}
const extra = (config.custom as { ipal?: { staffCollections?: string[] } } | undefined)?.ipal?.staffCollections ?? []
return [...new Set([config.admin?.user, ...extra].filter((s): s is string => typeof s === 'string' && s !== ''))]
/** True if the user is a staff account with the editor role or higher. */
export function isEditor(user: MaybeUser, payload?: MaybePayload): boolean {
return hasMinimumRole(user, 'editor', payload)
}
/**
* Role check for the plugin's own staff features (Site Integrations, the
* e-mail test, stats, consent records, form submissions, the settings
* globals). True when the user holds at least `minimum`.
* globals). In this order:
*
* Without roles: when the user belongs to a STAFF collection (the panel's
* login collection, or one named in `access.staffCollections`) and that
* collection has no `roles` field (the project omitted `access`), every
* account of it passes — without roles all staff accounts are equal, as in
* Payload's own default. An account of any other auth collection (a
* `customers` collection has no `roles` field either) never passes this way.
* 1. The account must belong to a STAFF collection (staffCollectionSlugs).
* An account of any other auth collection never passes — also when its own
* collection has a `roles` field that says `admin`.
* 2. With 2FA on, an account that has TOTP set up must have entered the code
* in this session (secondFactorPassed).
* 3. It holds at least `minimum` — or its collection has no `roles` field at
* all (the project omitted `access`): then every account of that staff
* collection passes, as in Payload's own default.
*
* With 2FA on, an account that has TOTP set up and has not entered the code in
* this session never passes (secondFactorPassed).
*
* Pass `req` (it has `payload` and `user`). Without `payload` only a held role
* counts — the strict side. A project with its own role scheme in another
* field narrows access through globalOverrides / collection overrides.
* Pass `req` (it has `payload` and `user`). A project with its own role scheme
* in another field narrows access through globalOverrides / collection overrides.
*/
export function userMeetsRole({ payload, user }: { payload?: BasePayload; user?: unknown }, minimum: Role): boolean {
if (!user || typeof user !== 'object') {return false}
if (!secondFactorPassed({ payload, user })) {return false}
if (hasMinimumRole(user as MaybeUser, minimum)) {return true}
const slug = (user as { collection?: unknown }).collection
if (typeof slug !== 'string' || !staffCollectionSlugs(payload).includes(slug)) {return false}
if (!secondFactorPassed({ payload, user })) {return false}
if (highestRoleIndex(user as MaybeUser) >= ROLE_HIERARCHY.indexOf(minimum)) {return true}
const collection = payload?.collections?.[slug as never]?.config
const fields = (collection?.flattenedFields ?? collection?.fields) as Array<{ name?: string }> | undefined
if (!fields) {return false}
+3 -2
View File
@@ -34,8 +34,9 @@ export function buildRolesField(defaultRole: Role = 'user', { firstUserAdmin = t
type: 'select',
access: {
// Only admins may assign or change roles
create: ({ req: { user } }) => isAdmin(user),
update: ({ req: { user } }) => isAdmin(user),
// …of a staff collection: a role value on an account of another auth collection does not count
create: ({ req }) => isAdmin(req.user, req.payload),
update: ({ req }) => isAdmin(req.user, req.payload),
},
admin: {
description: {
+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