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:
Radosław Smoliński
2026-11-24 19:32:34 +01:00
co-authored by Claude Fable 5.2
parent 9d2ab43438
commit 75a6f5209e
34 changed files with 780 additions and 103 deletions
+3 -1
View File
@@ -27,6 +27,8 @@ import { publicImageDataUri, siteOrigin } from './publicImage.js'
type BrandingProps = {
/** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */
imageField?: string
/** `whiteLabel.inlineImages: false` — never fetch the image on the server for the 2FA screens. */
inlineImages?: false
/** Injected by Payload — current admin locale (object or code). */
locale?: { code?: string } | string
/** Field holding the site name. Default 'siteName'. */
@@ -78,7 +80,7 @@ async function loadBranding(
// other collection, so the browser would show a broken image on the verify / setup screens.
// Give it the picture itself, fetched as an anonymous visitor would get it; when that fails
// (media is not public), the site name is shown instead.
if (url && props.user && !secondFactorPassed({ payload, user: props.user })) {
if (url && props.inlineImages !== false && props.user && !secondFactorPassed({ payload, user: props.user })) {
return { name, url: await publicImageDataUri(url, siteOrigin(payload.config.serverURL)) }
}
return { name, url }
+12 -5
View File
@@ -2,6 +2,7 @@ import type { Endpoint, PayloadRequest } from 'payload'
import type { AgencyOption, ResolvedAdminMeta } from './adminMeta.js'
import { UPLOAD_SECURITY_HEADERS } from '../security/buildSecurityHeaders.js'
import { ADMIN_ICON_PATH, ADMIN_META_TEXTS, ADMIN_OG_PATH } from './adminMeta.js'
import { fetchPublicImage } from './publicImage.js'
@@ -14,13 +15,13 @@ import { fetchPublicImage } from './publicImage.js'
* the site name, then to initials.
*/
type Fields = { iconField?: string; logoField?: string; nameField?: string; settingsSlug?: string }
type Fields = { iconField?: string; logoField?: string; nameField?: string; serveIcon?: false; settingsSlug?: string }
type Branding = { icon: null | string; logo: null | string; name: string }
const CACHE = 'public, max-age=3600, s-maxage=3600'
async function loadBranding(req: PayloadRequest, f: Required<Fields>): Promise<Branding> {
async function loadBranding(req: PayloadRequest, f: Required<Omit<Fields, 'serveIcon'>>): Promise<Branding> {
try {
const locale = req.payload.config.localization ? req.payload.config.localization.defaultLocale : undefined
const s = (await req.payload.findGlobal({ slug: f.settingsSlug as never, depth: 1, ...(locale ? { locale: locale as never } : {}), req })) as Record<string, unknown>
@@ -63,7 +64,7 @@ const initials = (name: string) =>
.join('') || 'A'
export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fields = {}): Endpoint[] {
const f: Required<Fields> = {
const f: Required<Omit<Fields, 'serveIcon'>> = {
iconField: fields.iconField ?? 'favicon',
logoField: fields.logoField ?? 'logo',
nameField: fields.nameField ?? 'siteName',
@@ -110,8 +111,14 @@ export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fi
// media file: a panel session that still owes its 2FA code is refused that file (it is
// refused every collection), and a cached redirect would send it there anyway. The answer
// is the same for everyone, so it can be cached like the redirect was.
const image = await fetchPublicImage(absolute(brand.icon, req), null)
if (image) {return new Response(new Uint8Array(image.bytes), { headers: { 'Cache-Control': CACHE, 'Content-Type': image.type } })}
const image = fields.serveIcon === false ? null : await fetchPublicImage(absolute(brand.icon, req), null)
// An uploaded file from the site's own origin: the same headers as the upload routes
// (an SVG may be displayed, never run script — sandbox, no sniffing).
if (image) {
return new Response(new Uint8Array(image.bytes), {
headers: { 'Cache-Control': CACHE, 'Content-Type': image.type, ...Object.fromEntries(UPLOAD_SECURITY_HEADERS.map((h) => [h.key, h.value])) },
})
}
// Not fetchable from here (too large, or media is not public): let the browser try.
return new Response(null, { headers: { 'Cache-Control': CACHE, Location: absolute(brand.icon, req) }, status: 302 })
}
+6
View File
@@ -37,6 +37,12 @@ export type AdminMetaOptions = {
language?: 'en' | 'pl'
/** Robots meta. Default noindex, nofollow. `false` = none. */
robots?: { follow?: boolean; index?: boolean } | false
/**
* `/api/ipal/admin-icon` answers with the favicon's bytes (fetched as an anonymous visitor gets
* them, with the upload security headers), so it also loads for a session that still owes its
* 2FA code. `false` = a redirect to the media file instead, as before.
*/
serveIcon?: false
/** Browser-tab suffix; `{site}` is replaced. Default "— {site} | Panel". `false` = none. */
titleSuffix?: false | string
}
+29 -3
View File
@@ -6,7 +6,8 @@
* same file is public. Serving the bytes from here opens nothing: only what
* answers an anonymous request comes back, and only an image of a sane size.
*/
const MAX_BYTES = 512 * 1024
export const PUBLIC_IMAGE_MAX_BYTES = 512 * 1024
const MAX_BYTES = PUBLIC_IMAGE_MAX_BYTES
export async function fetchPublicImage(url: null | string | undefined, base: null | string | undefined): Promise<{ bytes: Buffer; type: string } | null> {
if (!url) {return null}
@@ -22,14 +23,39 @@ export async function fetchPublicImage(url: null | string | undefined, base: nul
if (!res.ok) {return null}
const type = (res.headers.get('content-type') ?? '').split(';')[0].trim()
if (!type.startsWith('image/')) {return null}
const bytes = Buffer.from(await res.arrayBuffer())
if (!bytes.length || bytes.length > MAX_BYTES) {return null}
// Too large is known before reading when the server says so; otherwise stop reading at the limit.
const declared = Number(res.headers.get('content-length'))
if (Number.isFinite(declared) && declared > MAX_BYTES) {
await res.body?.cancel().catch(() => undefined)
return null
}
const bytes = await readUpTo(res, MAX_BYTES)
if (!bytes?.length) {return null}
return { type, bytes }
} catch {
return null
}
}
/** The body, or null as soon as it grows past `limit` (the rest is not downloaded). */
async function readUpTo(res: Response, limit: number): Promise<Buffer | null> {
const reader = res.body?.getReader()
if (!reader) {return null}
const chunks: Uint8Array[] = []
let size = 0
for (;;) {
const { done, value } = await reader.read()
if (done) {break}
size += value.byteLength
if (size > limit) {
await reader.cancel().catch(() => undefined)
return null
}
chunks.push(value)
}
return Buffer.concat(chunks)
}
/** The same as a `data:` address for an `<img>`. */
export async function publicImageDataUri(url: null | string | undefined, base: null | string | undefined): Promise<null | string> {
const image = await fetchPublicImage(url, base)
+7
View File
@@ -198,6 +198,13 @@ export const layoutRules: DoctorRule[] = [
if (/payloadTotp/.test(cfg)) {
need.push('@clocklimited/payload-2fa/rsc#TOTPSetup')
if (!lt(v, '1.14.2')) {need.push('@intecion/ipal-kit/admin#TotpRedirectProvider')}
// "2FA setup required": the status / reset control on the account and the dashboard notice — when the
// installed plugin has them and the config does not switch them (or the mode) off. Without them the
// panel shows no "Reopen setup": the documented way out of a blocked account is missing.
const adminExports = ctx.read('node_modules/@intecion/ipal-kit/dist/exports/admin.js')
const modeOff = /requireSetup\s*:\s*false|guard\s*:\s*false/.test(cfg)
if (/\bTwoFactorStatusField\b/.test(adminExports) && !modeOff && !/statusField\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#TwoFactorStatusField')}
if (/\bTwoFactorAlert\b/.test(adminExports) && !modeOff && !/dashboardNotice\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#TwoFactorAlert')}
// the back-link check in front of the 2FA screens (twoFactor.safeBack) — when the installed plugin has it
if (/\bSafeTotpView\b/.test(ctx.read('node_modules/@intecion/ipal-kit/dist/exports/admin.js')) && !/safeBack\s*:\s*false/.test(cfg)) {
need.push('@intecion/ipal-kit/admin#SafeTotpView')
+17
View File
@@ -108,6 +108,23 @@ export const securityRules: DoctorRule[] = [
else if (!ctx.installed('@clocklimited/payload-2fa')) {out.push({ fix: 'pnpm add @clocklimited/payload-2fa', message: '@clocklimited/payload-2fa is not installed', severity: 'error' })}
if (/requireSetup\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'remove twoFactor.requireSetup: false (or record the reason in ipal-doctor.json)', message: 'twoFactor.requireSetup is off: an account that has not set 2FA up opens everything with its password alone', severity: 'warning' })}
if (/windowHours\s*:\s*(?:false|0)\b/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor.requireSetup.windowHours: 72 (the default)', message: 'no time limit for 2FA setup: an account that never sets it up can be taken over with its password at any time', severity: 'info' })}
// Postgres / SQLite: the 2FA collection has the column `totp_setup_from` (whenever 2FA is on). Without a
// migration that adds it, every query on the collection fails in production — nobody can log in.
const sqlAdapter = ['@payloadcms/db-postgres', '@payloadcms/db-vercel-postgres', '@payloadcms/db-sqlite', '@payloadcms/db-d1-sqlite'].some((name) => ctx.installed(name))
const pluginHasColumn = /totpSetupFrom/.test(ctx.read('node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js'))
if (sqlAdapter && pluginHasColumn && /payloadTotp/.test(code)) {
const dirs = [`${ctx.src}migrations`, 'migrations'].filter((dir) => ctx.exists(dir))
const files = dirs.flatMap((dir) => ctx.list(dir).filter((name) => /\.(?:ts|js|mjs|sql|json)$/.test(name)).map((name) => `${dir}/${name}`))
if (!files.some((file) => /totp_setup_from|totpSetupFrom/.test(ctx.read(file)))) {
out.push({
fix: 'pnpm payload migrate:create, commit the migration, and run it (pnpm payload migrate) in the same deploy, before the new version serves requests',
message: files.length
? 'no migration adds the 2FA column `totp_setup_from`: in production every login would answer 500 — nobody could sign in to the panel'
: 'a SQL database and no migrations folder: the 2FA column `totp_setup_from` must exist before this version runs in production (migrate:create), or nobody can sign in',
severity: files.length ? 'error' : 'warning',
})
}
}
if (ctx.deep?.usersWithout2fa) {
const closed = ctx.deep.usersSetupClosed ?? 0
out.push({
+10 -5
View File
@@ -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' },
]
+1 -1
View File
@@ -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'
+8 -3
View File
@@ -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')
+119 -18
View File
@@ -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 })