Security review round 2: no exception by name, staff list fails closed, verify limit

R2-1: the sweep skipped every collection whose slug starts with payload-,
so a plugin's payload-... collection added after ipalKit was never guarded.
There is no exception by name or prefix now: every collection and global
is guarded, Payload's own included, and the job queue's run / queue /
cancel rules too.

R2-2: role predicates called without a source fail closed where the staff
collections are not known (browser bundle, middleware, edge): nobody is
staff. They accept req.payload, a config (also the client config) or
{ staffCollections } as the source.

R2-3: the staff list is filed per config / Payload instance; a call without
a source gets only what every config in the process calls staff.

R2-4: payload.config is watched on the instance, so a config swapped in by
a dev reload is guarded before any request or Local API call.

R2-5: verify attempts are limited per account (default 5 in 10 minutes,
twoFactor.verifyLimit), counted in memory, never skipped.

R2-6: a user object without collection owes the second factor; endpoints
the 2FA package may add on collections or globals are guarded too; a
warning names staff collections that 2FA does not cover; docs state what
is not covered, fix the one-argument examples and the doctor example.

HTTP tests for each on payload-2fa beta.7, run on SQLite, Postgres and
MongoDB (test adapter added).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 01:46:25 +01:00
co-authored by Claude Fable 5.2
parent 32faaa5e30
commit c56f0d41b8
34 changed files with 871 additions and 108 deletions
+55 -15
View File
@@ -1,4 +1,4 @@
import type { Config, Plugin } from 'payload'
import type { BasePayload, Config, PayloadRequest, Plugin } from 'payload'
import { deepMergeSimple } from 'payload/shared'
@@ -33,8 +33,18 @@ import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.j
import { withFillLocales } from './modules/hooks/fillEmptyLocales.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { buildGuardStrategy, ensurePayloadGuarded, guardConfigAccess, guardTotpEndpoint, missingTotpParts, passOptOutsToPackage } from './modules/security/totp/secondFactor.js'
import {
buildGuardStrategy,
ensurePayloadGuarded,
guardConfigAccess,
guardNewEntityEndpoints,
guardTotpEndpoint,
missingTotpParts,
passOptOutsToPackage,
watchPayloadConfig,
} from './modules/security/totp/secondFactor.js'
import { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
import { buildVerifyLimit } from './modules/security/totp/verifyLimit.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
import { buildIndexNowHook } from './modules/seo/indexNow.js'
import { searchSettingsFields } from './modules/seo/searchSettings.js'
@@ -158,6 +168,21 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// ipal-kit's own second-factor check (secondFactor.ts) covers what the 2FA
// package cannot: everything added to the config after the package ran.
let secondFactorGuard = false
/** The 2FA collection, when 2FA is on. */
let twoFactorCollection: null | string = null
/** This config's entry in the staff registry until a Payload instance takes it over. */
const staffToken = {}
/**
* A config has gone live on this instance (start, or a dev hot reload): guard what plugins
* listed after ipalKit added, and file its staff collections under the instance.
*/
const adoptConfig = (payload: BasePayload) => {
const token = (payload.config.custom as { ipal?: { staffToken?: object } } | undefined)?.ipal?.staffToken
registerStaffCollections(payload, staffCollectionSlugs(payload), token)
if (!secondFactorGuard) {return}
const late = ensurePayloadGuarded(payload)
if (late?.length) {payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`)}
}
if (options.twoFactor !== false) {
const tf = options.twoFactor
if (!tf?.issuer) {
@@ -204,6 +229,9 @@ export const ipalKit = (options: IpalOptions): Plugin => {
)
}
const endpointsBefore = new Set(config.endpoints ?? [])
const entityEndpointsBefore = new Map<string, Set<unknown>>(
[...(config.collections ?? []), ...(config.globals ?? [])].map((e) => [e.slug, new Set<unknown>(Array.isArray(e.endpoints) ? e.endpoints : [])]),
)
// custom.ipal.secondFactor (ipal-kit's per-entity opt-out) → the package's own key
config = passOptOutsToPackage(config)
config = await totp({
@@ -216,7 +244,13 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// `req.user` from ANY auth collection and act on the 2FA collection by id.
// Only accounts of the 2FA collection may use them (guardTotpEndpoint) —
// whatever the package registered, also paths a later version adds.
config.endpoints = (config.endpoints ?? []).map((e) => (endpointsBefore.has(e) ? e : guardTotpEndpoint(e, target)))
const limitVerify = tf.verifyLimit === false ? undefined : buildVerifyLimit(target, tf.verifyLimit)
const guards = limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}
config.endpoints = (config.endpoints ?? []).map((e) => (endpointsBefore.has(e) ? e : guardTotpEndpoint(e, target, guards as never)))
// …and the same for endpoints it may put on a collection or a global.
config.collections = guardNewEntityEndpoints(config.collections, entityEndpointsBefore, target, guards as never)
config.globals = guardNewEntityEndpoints(config.globals, entityEndpointsBefore, target, guards as never)
twoFactorCollection = target
// The package wraps only what is in the config right now. ipal-kit's own
// globals and collections come later, so they get ipal-kit's guard at the
@@ -238,9 +272,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, twoFactor: { collection: target } } }
// Called by Payload on every request before any access function: guards whatever
// the live config has that was added after ipalKit (start, dev hot reload).
const sweep = buildGuardStrategy((payload, late) =>
payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`),
)
const sweep = buildGuardStrategy(adoptConfig)
config.collections = (config.collections ?? []).map((c) =>
c.slug === target && typeof c.auth === 'object'
? { ...c, auth: { ...c.auth, strategies: [sweep as never, ...(c.auth.strategies ?? [])] } } // first: a strategy that finds a user ends the round
@@ -406,11 +438,13 @@ export const ipalKit = (options: IpalOptions): Plugin => {
const staff = [...new Set([options.access.authCollection, ...(options.access.staffCollections ?? [])])]
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, staffCollections: staff } }
}
// For predicates called without `req.payload` (isAdmin(req.user) in a hook): what this
// config says now; onInit repeats it with the sanitized config (admin.user as Payload resolved it).
// For predicates called without `req.payload` (isAdmin(req.user) in a hook): what this config
// says now, under a token; the Payload instance takes the entry over when the config goes live
// (adoptConfig), with `admin.user` as Payload resolved it.
{
const panel = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
registerStaffCollections(staffCollectionSlugs({ config: { admin: { user: panel }, custom: config.custom } } as never))
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, staffToken } }
registerStaffCollections(staffToken, staffCollectionSlugs({ admin: { user: panel }, custom: config.custom }))
}
// --- seo: apply @payloadcms/plugin-seo directly ---
@@ -663,12 +697,18 @@ export const ipalKit = (options: IpalOptions): Plugin => {
const incomingOnInit = config.onInit
config.onInit = async (payload) => {
if (incomingOnInit) {await incomingOnInit(payload)}
registerStaffCollections(staffCollectionSlugs(payload))
// …and on what plugins listed after ipalKit added: they did not exist above.
// (The guard strategy does the same on the first request — after a hot reload too.)
if (secondFactorGuard) {
const late = ensurePayloadGuarded(payload)
if (late.length) {payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`)}
adoptConfig(payload)
// Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once.
watchPayloadConfig(payload, adoptConfig)
// Staff whose collection is not the 2FA collection log in without a second factor: say so.
if (twoFactorCollection) {
const uncovered = staffCollectionSlugs(payload).filter((slug) => slug !== twoFactorCollection)
if (uncovered.length) {
payload.logger.warn(
`[ipal] 2FA covers "${twoFactorCollection}" only. Staff accounts of ${uncovered.map((s) => `"${s}"`).join(', ')} ` +
'pass the staff checks with a password alone (docs/access.md "Who is staff").',
)
}
}
await migrateCookieSettingsSaveButton(payload)
await migrateTitleSeparator(payload, settingsSlug)