2FA setup required: review fixes (SR-1 to SR-9)
SR-1: /api/ipal/admin-icon sends the upload security headers (sandbox policy, nosniff) with the bytes: an SVG is shown, never run. fetchPublicImage stops reading at the size limit. SR-2: requireSetup.exempt exempts only on exactly true; an async function, and a windowHours that is not a number or false, stop the start. SR-3: on Postgres / SQLite the missing column makes every login fail: the log says so, the docs call the migration a required step of the same deploy, and ipal-doctor reports a SQL project without it. SR-4: an admin's reset also ends the account's sessions. SR-5: the reset needs a session that entered its own TOTP code by default. SR-6: the doctor's import-map rule covers TwoFactorStatusField and TwoFactorAlert. SR-7: building blocks exported; dashboard notice, status field, setup notice and the server-side image fetch can be switched off one by one. SR-8: totpSetupFrom is on the 2FA collection whenever 2FA is on. SR-9: both ways out of "every administrator is blocked" in security.md. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
9d2ab43438
commit
75a6f5209e
@@ -161,9 +161,14 @@ export function buildUploadSecurityHeaders({ collections = ['media'] }: { collec
|
||||
headers: SecurityHeader[]
|
||||
source: string
|
||||
}[] {
|
||||
const headers: SecurityHeader[] = [
|
||||
{ key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox" },
|
||||
{ key: 'X-Content-Type-Options', value: 'nosniff' },
|
||||
]
|
||||
return collections.map((slug) => ({ headers, source: `/api/${slug}/file/:path*` }))
|
||||
return collections.map((slug) => ({ headers: [...UPLOAD_SECURITY_HEADERS], source: `/api/${slug}/file/:path*` }))
|
||||
}
|
||||
|
||||
/**
|
||||
* The headers themselves: for any response that carries the bytes of an uploaded file from the
|
||||
* site's own origin (the upload routes above; the plugin's `/api/ipal/admin-icon`; a route of yours).
|
||||
*/
|
||||
export const UPLOAD_SECURITY_HEADERS: readonly SecurityHeader[] = [
|
||||
{ key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox" },
|
||||
{ key: 'X-Content-Type-Options', value: 'nosniff' },
|
||||
]
|
||||
|
||||
@@ -8,7 +8,7 @@ export {
|
||||
DEFAULT_CSP_REPORT_GROUP,
|
||||
} from './buildCsp.js'
|
||||
export type { BuildAdminCspArgs, BuildCspArgs, CspDirective, CspSources } from './buildCsp.js'
|
||||
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './buildSecurityHeaders.js'
|
||||
export { buildSecurityHeaders, buildUploadSecurityHeaders, UPLOAD_SECURITY_HEADERS } from './buildSecurityHeaders.js'
|
||||
export type { BuildSecurityHeadersArgs, SecurityHeader } from './buildSecurityHeaders.js'
|
||||
export { createCspReportRoute, parseCspReports } from './createCspReportRoute.js'
|
||||
export type { CreateCspReportRouteArgs, CspViolation } from './createCspReportRoute.js'
|
||||
|
||||
@@ -74,7 +74,11 @@ export const SETUP_FROM_FIELD = 'totpSetupFrom'
|
||||
*/
|
||||
export type TwoFactorSetupState = 'closed' | 'exempt' | 'not-applicable' | 'open' | 'set-up'
|
||||
|
||||
/** The moment setup closes for this account, or null (no window, or no start recorded yet). */
|
||||
/**
|
||||
* The moment setup closes for this account, or null (no window, or no start recorded yet).
|
||||
* A start that is missing or unreadable counts as "no deadline yet" (the account can still only
|
||||
* set TOTP up): only server code writes the field, and the start-up step fills in a missing one.
|
||||
*/
|
||||
export function twoFactorSetupDeadline({ payload, user }: MaybeReq): Date | null {
|
||||
const guard = guardConfig(payload)
|
||||
const from = (user as null | Record<string, unknown> | undefined)?.[SETUP_FROM_FIELD]
|
||||
@@ -89,7 +93,7 @@ export function twoFactorSetupState({ payload, user }: MaybeReq, now: number = D
|
||||
const u = user as { collection?: unknown; hasTotp?: unknown }
|
||||
if (u.collection !== guard.collection) {return 'not-applicable'}
|
||||
if (u.hasTotp !== false || (user as { totpSecret?: unknown }).totpSecret) {return 'set-up'}
|
||||
if (!guard.requireSetup || guard.exempt?.({ user: user as Record<string, unknown> })) {return 'exempt'}
|
||||
if (!guard.requireSetup || guard.exempt?.({ user: user as Record<string, unknown> }) === true) {return 'exempt'}
|
||||
const deadline = twoFactorSetupDeadline({ payload, user })
|
||||
return deadline && deadline.getTime() < now ? 'closed' : 'open'
|
||||
}
|
||||
@@ -124,7 +128,8 @@ export function secondFactorPassed({ payload, user }: MaybeReq): boolean {
|
||||
// came with the account's own record) then still says the account has TOTP: refused.
|
||||
if (u.hasTotp !== false || (user as { totpSecret?: unknown }).totpSecret) {return false}
|
||||
// TOTP not set up: only when setup is not required, or for an account the project exempts
|
||||
return !guard.requireSetup || Boolean(guard.exempt?.({ user: user as Record<string, unknown> }))
|
||||
// Exactly `true`: a Promise or any other truthy answer must never let an account in.
|
||||
return !guard.requireSetup || guard.exempt?.({ user: user as Record<string, unknown> }) === true
|
||||
}
|
||||
|
||||
const GUARDED = Symbol.for('ipal.secondFactorGuard')
|
||||
|
||||
@@ -20,12 +20,22 @@ import { secondFactorPassed, SETUP_FROM_FIELD } from './secondFactor.js'
|
||||
*/
|
||||
|
||||
export type RequireSetupOptions = {
|
||||
/** The notice for administrators on the dashboard (accounts without 2FA, how many are blocked). `false` = none. */
|
||||
dashboardNotice?: false
|
||||
/**
|
||||
* Accounts that may work without TOTP on purpose — a service account that
|
||||
* logs in with a password. Return true to exempt. (An API key needs no
|
||||
* exemption: it passes by itself.) `({ user }) => user.email === '[email protected]'`
|
||||
* logs in with a password. Return **exactly `true`** to exempt, and return it
|
||||
* at once: the function is called in access checks, which cannot wait. An
|
||||
* `async` function stops the site at start; any other answer than `true`
|
||||
* (a Promise, a string, an error thrown) exempts nobody and is logged.
|
||||
* (An API key needs no exemption: it passes by itself.)
|
||||
* `({ user }) => user.email === '[email protected]'`
|
||||
*/
|
||||
exempt?: (args: { user: Record<string, unknown> }) => boolean
|
||||
/** The notice on the setup screen (until when; or that the time has passed). `false` = none. */
|
||||
setupNotice?: false
|
||||
/** The "Two-step verification" status and reset control on the account in the panel. `false` = none (the reset endpoint stays). */
|
||||
statusField?: false
|
||||
/**
|
||||
* Hours an account has to set TOTP up, counted from its creation or from the
|
||||
* last reset by an admin. After that it is blocked until an admin reopens
|
||||
@@ -44,17 +54,76 @@ export function resolveRequireSetup(option: false | RequireSetupOptions | undefi
|
||||
setupWindowMs: number
|
||||
} {
|
||||
if (option === false) {return { requireSetup: false, setupWindowMs: 0 }}
|
||||
const hours = option?.windowHours === false ? 0 : (option?.windowHours ?? DEFAULT_SETUP_WINDOW_HOURS)
|
||||
// A typo must not loosen the rule: '24', -1 or NaN used to mean "no limit".
|
||||
const given = option?.windowHours
|
||||
if (given !== undefined && given !== false && (typeof given !== 'number' || !Number.isFinite(given) || given < 0)) {
|
||||
throw new Error(
|
||||
`[ipal] twoFactor.requireSetup.windowHours must be a number of hours (0 or more) or false, got ${JSON.stringify(given) ?? String(given)}. ` +
|
||||
'Use 72 (the default), another number, or false / 0 for no time limit.',
|
||||
)
|
||||
}
|
||||
const hours = given === false ? 0 : (given ?? DEFAULT_SETUP_WINDOW_HOURS)
|
||||
return {
|
||||
...(option?.exempt ? { exempt: option.exempt } : {}),
|
||||
...(option?.exempt !== undefined ? { exempt: strictExempt(option.exempt) } : {}),
|
||||
requireSetup: true,
|
||||
setupWindowMs: Number.isFinite(hours) && hours > 0 ? hours * 60 * 60 * 1000 : 0,
|
||||
setupWindowMs: hours > 0 ? hours * 60 * 60 * 1000 : 0,
|
||||
}
|
||||
}
|
||||
|
||||
/** The two fields for the 2FA collection: the window start (data) and its status / reset control (panel). */
|
||||
export function buildSetupFields(): Field[] {
|
||||
return [
|
||||
/** What was already said about a wrong `exempt` answer: each kind is logged once per process. */
|
||||
const exemptComplaints = new Set<string>()
|
||||
|
||||
/**
|
||||
* The project's `exempt`, made safe to call from an access check: only an answer of exactly
|
||||
* `true` exempts. An async function is refused at start (its Promise would be truthy for every
|
||||
* account — everyone let in on a password); any other answer, or an error, exempts nobody and
|
||||
* is logged (once per kind of wrong answer).
|
||||
*/
|
||||
export function strictExempt(exempt: unknown): NonNullable<RequireSetupOptions['exempt']> {
|
||||
if (typeof exempt !== 'function') {
|
||||
throw new Error('[ipal] twoFactor.requireSetup.exempt must be a function: ({ user }) => boolean.')
|
||||
}
|
||||
if (exempt.constructor?.name === 'AsyncFunction') {
|
||||
throw new Error(
|
||||
'[ipal] twoFactor.requireSetup.exempt must not be async: it is called in access checks, which cannot wait, and a Promise ' +
|
||||
'would count as "exempt" for every account. Return true or false at once (decide from the fields on `user`).',
|
||||
)
|
||||
}
|
||||
const complain = (what: string) => {
|
||||
const kind = what.replace(/\(.*\)$/, '')
|
||||
if (exemptComplaints.has(kind)) {return}
|
||||
exemptComplaints.add(kind)
|
||||
console.error(`[ipal] twoFactor.requireSetup.exempt ${what}; it must return true or false at once. The account is NOT exempt.`)
|
||||
}
|
||||
return (args) => {
|
||||
let answer: unknown
|
||||
try {
|
||||
answer = (exempt as (a: typeof args) => unknown)(args)
|
||||
} catch (err) {
|
||||
complain(`threw (${err instanceof Error ? err.message : String(err)})`)
|
||||
return false
|
||||
}
|
||||
if (answer === true) {return true}
|
||||
if (answer !== false && answer !== undefined && answer !== null) {
|
||||
// a Promise that rejects later must not become an unhandled rejection
|
||||
if (typeof (answer as { then?: unknown }).then === 'function') {void (answer as Promise<unknown>).then(undefined, () => undefined)}
|
||||
complain(`returned ${typeof (answer as { then?: unknown }).then === 'function' ? 'a Promise' : `a ${typeof answer}`}`)
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The fields for the 2FA collection: the window start (data) and, unless `statusField: false`,
|
||||
* its status / reset control (panel).
|
||||
*
|
||||
* ipalKit adds the data field **whenever 2FA is on**, also with `requireSetup: false` or
|
||||
* `guard: false`: the collection's schema then does not depend on those switches — on Postgres /
|
||||
* SQLite switching the mode off would otherwise drop the column with the next migration, and
|
||||
* switching it on again would hand every account without TOTP a new window.
|
||||
*/
|
||||
export function buildSetupFields({ statusField = true }: { statusField?: boolean } = {}): Field[] {
|
||||
const fields: Field[] = [
|
||||
{
|
||||
name: SETUP_FROM_FIELD,
|
||||
type: 'date',
|
||||
@@ -67,7 +136,9 @@ export function buildSetupFields(): Field[] {
|
||||
admin: { disableBulkEdit: true, disableListColumn: true, disableListFilter: true, hidden: true },
|
||||
label: { en: 'Two-step verification: setup open since', pl: 'Weryfikacja dwuetapowa: konfiguracja otwarta od' },
|
||||
},
|
||||
{
|
||||
]
|
||||
if (statusField) {
|
||||
fields.push({
|
||||
name: 'totpSetupStatus',
|
||||
type: 'ui',
|
||||
admin: {
|
||||
@@ -75,8 +146,9 @@ export function buildSetupFields(): Field[] {
|
||||
disableListColumn: true,
|
||||
position: 'sidebar',
|
||||
},
|
||||
},
|
||||
]
|
||||
})
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -122,21 +194,46 @@ export async function backfillSetupFrom(payload: BasePayload, collection: string
|
||||
}
|
||||
return totalDocs
|
||||
} catch (err) {
|
||||
payload.logger.warn(`[ipal] 2FA: could not start the setup window for existing accounts (${err instanceof Error ? err.message : String(err)}). On Postgres / SQLite run the migration that adds "${SETUP_FROM_FIELD}".`)
|
||||
const reason = err instanceof Error ? err.message : String(err)
|
||||
// On Postgres / SQLite this is the missing column — and then it is not only this step that fails:
|
||||
// every query on the collection selects the column, so EVERY login answers 500 until it exists.
|
||||
const adapter = (payload.db as { name?: unknown } | undefined)?.name
|
||||
if (/postgres|sqlite/i.test(typeof adapter === 'string' ? adapter : '') || /column|no such/i.test(reason)) {
|
||||
payload.logger.error(
|
||||
`[ipal] 2FA: the column for "${SETUP_FROM_FIELD}" is missing on "${collection}" (${reason}). NOBODY CAN LOG IN to the panel until the ` +
|
||||
'migration that adds it has run — administrators with 2FA included. Run `pnpm payload migrate:create`, commit the migration and ' +
|
||||
'run it (`pnpm payload migrate`) before this version serves requests (docs/security.md "Setup required" → Data).',
|
||||
)
|
||||
} else {
|
||||
payload.logger.warn(`[ipal] 2FA: could not start the setup window for existing accounts (${reason}).`)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
export type TwoFactorResetOptions = {
|
||||
/** Who may reset another account's TOTP. Default: a staff admin (`userMeetsRole(req, 'admin')`). The second factor is always required. */
|
||||
/**
|
||||
* Who may reset another account's TOTP. Default: a staff admin whose session has **entered its
|
||||
* TOTP code** (`_strategy: 'totp'`) — not an API key, and not an account `requireSetup.exempt`
|
||||
* lets work on its password. With your own function the session must still not owe a second
|
||||
* factor (`secondFactorPassed`), and the rest is yours: an API-key or exempt admin passes only
|
||||
* if you return true for it (`req.user._strategy` tells them apart).
|
||||
*/
|
||||
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/ipal/two-factor/reset `{ userId }` — clears that account's TOTP
|
||||
* secret. The account must set TOTP up again, and its setup window starts
|
||||
* anew. For a lost phone, and to reopen setup for an account whose window has
|
||||
* passed. Admins only, and only after their own second factor.
|
||||
* secret **and its sessions**. The account must log in and set TOTP up again,
|
||||
* and its setup window starts anew. For a lost phone, and to reopen setup for
|
||||
* an account whose window has passed. Admins only, and only after their own
|
||||
* TOTP code.
|
||||
*
|
||||
* The sessions go because a reset is also what an administrator presses for an
|
||||
* account that may be in someone else's hands: a session that had passed 2FA
|
||||
* would otherwise be a password-less way to enrol a new authenticator
|
||||
* (`/api/setup-totp` asks for no password). With `auth.useSessions: false`
|
||||
* there is nothing to clear — tokens then live until they expire.
|
||||
*/
|
||||
export function buildTwoFactorResetEndpoint(collection: string, options: TwoFactorResetOptions = {}): Endpoint {
|
||||
return {
|
||||
@@ -146,7 +243,9 @@ export function buildTwoFactorResetEndpoint(collection: string, options: TwoFact
|
||||
Boolean(req.user) &&
|
||||
secondFactorPassed(req) &&
|
||||
(req.user as { collection?: unknown }).collection === collection &&
|
||||
(options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'admin'))
|
||||
(options.access
|
||||
? (await options.access({ req })) === true
|
||||
: (req.user as { _strategy?: unknown })._strategy === 'totp' && userMeetsRole(req, 'admin'))
|
||||
if (!allowed) {return Response.json({ message: serverText(i18n, 'twoFactorResetForbidden'), ok: false }, { status: 403 })}
|
||||
let body: unknown
|
||||
try {
|
||||
@@ -159,7 +258,9 @@ export function buildTwoFactorResetEndpoint(collection: string, options: TwoFact
|
||||
return Response.json({ message: serverText(i18n, 'twoFactorResetFailed'), ok: false }, { status: 400 })
|
||||
}
|
||||
try {
|
||||
await req.payload.update({ id: userId, collection: collection as never, data: { [SETUP_FROM_FIELD]: new Date().toISOString(), totpSecret: null } as never, overrideAccess: true, req })
|
||||
const useSessions = (req.payload.collections as Record<string, { config?: { auth?: { useSessions?: boolean } } }>)[collection]?.config?.auth?.useSessions !== false
|
||||
const data = { [SETUP_FROM_FIELD]: new Date().toISOString(), totpSecret: null, ...(useSessions ? { sessions: [] } : {}) }
|
||||
await req.payload.update({ id: userId, collection: collection as never, data: data as never, overrideAccess: true, req })
|
||||
} catch (err) {
|
||||
req.payload.logger.error(`[ipal] 2FA reset failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
return Response.json({ message: serverText(i18n, 'twoFactorResetFailed'), ok: false }, { status: 400 })
|
||||
|
||||
Reference in New Issue
Block a user