2FA setup required: an account without TOTP reaches only setup, within a 72 h window

twoFactor.requireSetup (on by default with 2FA): an account of the 2FA
collection that has not set TOTP up is refused by ipal-kit's second-factor
check on every collection, global and plugin endpoint; the setup screen and
/api/setup-totp are all it reaches. It has 72 hours from its creation or
from an admin's reset (field totpSetupFrom, stamped by a hook); after that
setup is refused too until an admin reopens it.

Accounts that existed before get their window at the first start after the
upgrade (backfill in onInit), so nobody is blocked when a site upgrades.

Admin side: status and reset / 'Reopen setup' button on the account page
(TwoFactorStatusField), POST /api/ipal/two-factor/reset, a dashboard notice
(TwoFactorAlert), a notice on the setup screen; texts in English and Polish.
ipal-doctor reports blocked accounts and a switched-off mode.

Overridable: requireSetup false, windowHours (false / 0 = none), exempt for
a service account, resetAccess; the per-entity second-factor opt-out applies.
API keys, seeds, bearer-token routes and sites with twoFactor false are not
affected.

HTTP tests (REST, GraphQL, first admin on an empty database) run on SQLite,
Postgres and MongoDB; a browser test on the reference site covers the first
admin, a new editor and the admin's reset. Docs, guide, skills, changelog.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 18:46:32 +01:00
co-authored by Claude Fable 5.2
parent 45d52c4690
commit 2aaaaa115a
43 changed files with 1234 additions and 63 deletions
+3
View File
@@ -22,6 +22,9 @@ export { SafeTotpView } from '../modules/security/totp/SafeTotpView.js'
export type { SafeTotpViewProps } from '../modules/security/totp/SafeTotpView.js'
export { TotpRedirectProvider } from '../modules/security/totp/TotpRedirectProvider.js'
export type { TotpRedirectProviderProps } from '../modules/security/totp/TotpRedirectProvider.js'
export { TwoFactorAlert } from '../modules/security/totp/TwoFactorAlert.js'
export { TwoFactorResetButton } from '../modules/security/totp/TwoFactorResetButton.js'
export { TwoFactorStatusField } from '../modules/security/totp/TwoFactorStatusField.js'
export { FaviconCheck } from '../modules/seo/FaviconCheck.js'
export type { FaviconCheckProps } from '../modules/seo/FaviconCheck.js'
export { MetaDescriptionCheck } from '../modules/seo/MetaDescriptionCheck.js'
+3 -1
View File
@@ -330,7 +330,9 @@ export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/securit
export { findImportMapFile, missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
export { changedViewKeys, copyViews, SAFE_TOTP_VIEW, safeAdminBack, totpViewImportKey, wrapTotpViews } from './modules/security/totp/safeBack.js'
export type { SafeBackContext, SafeBackRule, TotpViewComponent } from './modules/security/totp/safeBack.js'
export { requireSecondFactor, secondFactorPassed } from './modules/security/totp/secondFactor.js'
export { requireSecondFactor, secondFactorPassed, twoFactorSetupDeadline, twoFactorSetupState } from './modules/security/totp/secondFactor.js'
export type { TwoFactorSetupState } from './modules/security/totp/secondFactor.js'
export type { RequireSetupOptions } from './modules/security/totp/setupRequired.js'
export { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
export type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
export type { OgImage } from './modules/seo/buildMetadata.js'
+38
View File
@@ -3,9 +3,47 @@ import { defineTexts } from '../define.js'
/** Admin component texts — two-step verification (2FA). Placeholders use Payload's {{name}} syntax. */
export const securityTexts = defineTexts({
en: {
twoFactorAlertBlocked: 'Blocked because the time for setup has passed: {{count}}. Open the account in the user list and choose "Reopen setup".',
twoFactorAlertLink: 'Open the user list',
twoFactorAlertPending: 'Accounts without two-step verification: {{count}}. Until it is set up, such an account cannot use the panel.',
twoFactorAlertTitle: 'Two-step verification',
twoFactorReopen: 'Reopen setup',
twoFactorReset: 'Reset two-step verification',
twoFactorResetConfirm: 'This account will have to set up two-step verification again before it can use the panel. Continue?',
twoFactorResetDone: 'Done. The account can set up two-step verification now.',
twoFactorResetFailed: 'Could not reset two-step verification. Try again.',
twoFactorResetForbidden: 'Only an administrator who is fully logged in can do this.',
twoFactorSetupClosed: 'The time to set up two-step verification has passed, so this account is blocked. Ask an administrator to reopen setup for it.',
twoFactorSetupDeadline: 'Set up two-step verification by {{date}}. Until then you cannot use the panel.',
twoFactorSetupRequired: 'Set up two-step verification to use the panel.',
twoFactorStatusClosed: 'Not set up. The time for it passed on {{date}}, so the account is blocked.',
twoFactorStatusExempt: 'Not set up. This account is exempt in the site configuration.',
twoFactorStatusLabel: 'Two-step verification',
twoFactorStatusOn: 'Set up.',
twoFactorStatusOpen: 'Not set up. The account can set it up until {{date}}.',
twoFactorStatusOpenNoLimit: 'Not set up yet. The account cannot use the panel until it is.',
twoFactorTooManyAttempts: 'Too many codes were tried for this account. Wait {{minutes}} min, then enter the current code from your app.',
},
pl: {
twoFactorAlertBlocked: 'Zablokowane, bo minął czas na konfigurację: {{count}}. Otwórz konto na liście użytkowników i wybierz „Otwórz konfigurację ponownie”.',
twoFactorAlertLink: 'Otwórz listę użytkowników',
twoFactorAlertPending: 'Konta bez weryfikacji dwuetapowej: {{count}}. Dopóki nie zostanie ustawiona, takie konto nie może korzystać z panelu.',
twoFactorAlertTitle: 'Weryfikacja dwuetapowa',
twoFactorReopen: 'Otwórz konfigurację ponownie',
twoFactorReset: 'Zresetuj weryfikację dwuetapową',
twoFactorResetConfirm: 'To konto będzie musiało ponownie ustawić weryfikację dwuetapową, zanim skorzysta z panelu. Kontynuować?',
twoFactorResetDone: 'Gotowe. Konto może teraz ustawić weryfikację dwuetapową.',
twoFactorResetFailed: 'Nie udało się zresetować weryfikacji dwuetapowej. Spróbuj ponownie.',
twoFactorResetForbidden: 'Może to zrobić tylko w pełni zalogowany administrator.',
twoFactorSetupClosed: 'Czas na ustawienie weryfikacji dwuetapowej minął, więc to konto jest zablokowane. Poproś administratora o ponowne otwarcie konfiguracji.',
twoFactorSetupDeadline: 'Ustaw weryfikację dwuetapową do {{date}}. Do tego czasu nie możesz korzystać z panelu.',
twoFactorSetupRequired: 'Ustaw weryfikację dwuetapową, aby korzystać z panelu.',
twoFactorStatusClosed: 'Nieustawiona. Czas na konfigurację minął {{date}}, więc konto jest zablokowane.',
twoFactorStatusExempt: 'Nieustawiona. To konto jest zwolnione w konfiguracji strony.',
twoFactorStatusLabel: 'Weryfikacja dwuetapowa',
twoFactorStatusOn: 'Ustawiona.',
twoFactorStatusOpen: 'Nieustawiona. Konto może ją ustawić do {{date}}.',
twoFactorStatusOpenNoLimit: 'Jeszcze nieustawiona. Do tego czasu konto nie może korzystać z panelu.',
twoFactorTooManyAttempts: 'Dla tego konta wpisano zbyt wiele kodów. Odczekaj {{minutes}} min, a potem wpisz aktualny kod z aplikacji.',
},
})
+12 -1
View File
@@ -106,7 +106,18 @@ export const securityRules: DoctorRule[] = [
if (/\?\s*false\b|:\s*false\b|&&/.test(twoFactor) && /payloadTotp/.test(twoFactor)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor: { issuer, plugin: payloadTotp } without a switch', message: '2FA can be turned off at runtime (a condition on twoFactor)', severity: 'warning' })}
if (!/twoFactor\s*:[^\n]*payloadTotp|twoFactor\s*:\s*\{[\s\S]*?plugin\s*:\s*payloadTotp/.test(code)) {out.push({ file: configFile(ctx) ?? 'payload.config.ts', fix: "ipalKit({ twoFactor: { issuer: '<site>', plugin: payloadTotp } })", message: '2FA is not on (twoFactor with plugin: payloadTotp)', severity: 'error' })}
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 (ctx.deep?.usersWithout2fa) {out.push({ fix: 'each of them signs in and sets up TOTP (forceSetup)', message: `${ctx.deep.usersWithout2fa} panel user(s) without TOTP`, 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' })}
if (ctx.deep?.usersWithout2fa) {
const closed = ctx.deep.usersSetupClosed ?? 0
out.push({
fix: closed
? 'each of them signs in and sets up TOTP; for the blocked ones an admin opens the account in the panel → "Reopen setup" (or removes the account)'
: 'each of them signs in and sets up TOTP now; remove accounts nobody uses',
message: `${ctx.deep.usersWithout2fa} panel user(s) without TOTP${closed ? ` (${closed} blocked: the setup window has passed)` : ''}`,
severity: 'error',
})
}
return out
},
docs: 'docs/security.md#2fa-totp--enforced-for-every-user',
+8 -2
View File
@@ -7,7 +7,8 @@ import type { DoctorStatus } from './types.js'
import { countPendingCookies } from '../consent/scanner/approval.js'
import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js'
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
/** The plugin's own version (package.json next to dist/ and src/). */
@@ -30,15 +31,20 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
const authSlug = payload.config.admin?.user
const auth = collections.find((c) => c.slug === authSlug)
let usersWithout2fa: null | number = null
let usersSetupClosed: null | number = null
// payload-2fa stores `totpSecret` (`hasTotp` is virtual and cannot be queried); counted, never read.
if (auth?.fields?.some((f) => f.name === 'totpSecret')) {
const collection = auth.slug as never
const all = (await payload.count({ collection, overrideAccess: true })).totalDocs
const withTotp = (await payload.count({ collection, overrideAccess: true, where: { and: [{ totpSecret: { exists: true } }, { totpSecret: { not_equals: '' } }] } })).totalDocs
usersWithout2fa = Math.max(0, all - withTotp)
const windowMs = (payload.config.custom as { ipal?: { twoFactor?: { setupWindowMs?: number } } } | undefined)?.ipal?.twoFactor?.setupWindowMs
if (usersWithout2fa && windowMs && auth.fields.some((f) => f.name === SETUP_FROM_FIELD)) {
usersSetupClosed = (await countAccountsWithoutTotp(payload, auth.slug, windowMs)).blocked
}
}
const pendingCookies = collections.some((c) => c.slug === COOKIE_REVIEW_SLUG) ? await countPendingCookies(payload) : null
return { node: process.version, pendingCookies, plugin: pluginVersion(), usersWithout2fa }
return { node: process.version, pendingCookies, plugin: pluginVersion(), usersSetupClosed, usersWithout2fa }
}
export type DoctorEndpointOptions = {
+2
View File
@@ -63,6 +63,8 @@ export type DoctorStatus = {
node?: string
pendingCookies?: null | number
plugin?: string
/** Of `usersWithout2fa`: accounts whose setup window has passed (blocked until an admin reopens setup). */
usersSetupClosed?: null | number
usersWithout2fa?: null | number
}
@@ -8,12 +8,17 @@ import { useEffect } from 'react'
import type { TotpUser } from './totpRedirect.js'
import { totpRedirectTarget } from './totpRedirect.js'
import { formatDateTime, ipalT } from '../../admin-i18n/t.js'
import { totpAdminPath, totpRedirectTarget } from './totpRedirect.js'
export type TotpRedirectProviderProps = {
children?: ReactNode
/** pluginOptions.forceSetup — set by the plugin (true: 2FA is enforced). */
forceSetup?: boolean
/** `twoFactor.requireSetup` is on: say so on the setup screen. Set by the plugin. */
requireSetup?: boolean
/** Hours an account has for setup (0 = no limit). Set by the plugin. */
setupWindowHours?: number
/**
* Set by the plugin when the admin import map on disk lacks the 2FA view wrapper
* (importMapCheck.ts). The 2FA screens are then probably empty, so a notice says what is
@@ -42,9 +47,9 @@ const STALE_TEXT = {
* Renders nothing while a redirect is pending, so the panel does not flash.
* Swap it with `twoFactor.provider`.
*/
export function TotpRedirectProvider({ children, forceSetup = true, staleImportMap = false }: TotpRedirectProviderProps) {
export function TotpRedirectProvider({ children, forceSetup = true, requireSetup = false, setupWindowHours = 0, staleImportMap = false }: TotpRedirectProviderProps) {
const { i18n, t } = useTranslation()
const { user } = useAuth()
const { i18n } = useTranslation()
const { config } = useConfig()
const pathname = usePathname()
const router = useRouter()
@@ -62,19 +67,61 @@ export function TotpRedirectProvider({ children, forceSetup = true, staleImportM
}, [router, target])
if (target) {return null}
if (staleImportMap && user && /\/(?:setup|verify)-totp\/?$/.test(pathname ?? '')) {
// Both notices stand ABOVE the screen and never replace it: the code form must stay on the page whatever they say.
const adminRoute = config.routes?.admin ?? '/admin'
const here = (pathname ?? '').replace(/\/+$/, '')
const onSetup = here === totpAdminPath(adminRoute, '/setup-totp')
const onVerify = here === totpAdminPath(adminRoute, '/verify-totp')
// The admin import map on disk may be older than the config (importMapCheck.ts): a guess, hence only a notice.
let stale: ReactNode = null
if (staleImportMap && user && (onSetup || onVerify)) {
const text = STALE_TEXT[i18n.language?.toLowerCase().startsWith('pl') ? 'pl' : 'en']
return (
<>
<div role="alert" style={{ margin: '2rem auto 0', maxWidth: '36rem', padding: '0 1.5rem' }}>
<p style={{ fontWeight: 600, marginBottom: '0.5rem' }}>{text.title}</p>
<p>{text.body}</p>
</div>
{children}
</>
stale = (
<div role="alert" style={{ margin: '2rem auto 0', maxWidth: '36rem', padding: '0 1.5rem' }}>
<p style={{ fontWeight: 600, marginBottom: '0.5rem' }}>{text.title}</p>
<p>{text.body}</p>
</div>
)
}
return children
// On the setup screen: what the account is waiting for — or that its time has passed.
let setup: ReactNode = null
const account = user as ({ totpSetupFrom?: null | string } & TotpUser) | null
if (requireSetup && onSetup && account && account.hasTotp === false) {
const start = account.totpSetupFrom ? new Date(account.totpSetupFrom).getTime() : NaN
const deadline = setupWindowHours > 0 && Number.isFinite(start) ? start + setupWindowHours * 3_600_000 : null
const closed = deadline !== null && deadline < Date.now()
const notice = closed
? ipalT(t as never, 'twoFactorSetupClosed')
: deadline !== null
? ipalT(t as never, 'twoFactorSetupDeadline', { date: formatDateTime(new Date(deadline).toISOString(), i18n.language) })
: ipalT(t as never, 'twoFactorSetupRequired')
setup = (
<div
id="ipal-two-factor-notice"
role={closed ? 'alert' : 'status'}
style={{
background: closed ? 'var(--theme-error-100, #fdecea)' : 'var(--theme-elevation-100, #f3f3f3)',
borderBottom: `1px solid ${closed ? 'var(--theme-error-500, #b00020)' : 'var(--theme-elevation-200, #ddd)'}`,
padding: '.75rem 1rem',
textAlign: 'center',
}}
>
{notice}
</div>
)
}
if (!stale && !setup) {return children}
return (
<>
{setup}
{stale}
{children}
</>
)
}
export default TotpRedirectProvider
@@ -0,0 +1,47 @@
import type { BasePayload } from 'payload'
import { userMeetsRole } from '../../access/predicates.js'
import { serverText } from '../../integrations/texts.js'
import { countAccountsWithoutTotp } from './setupRequired.js'
type Props = {
/** Admin route, for the link. Default '/admin'. */
adminRoute?: string
i18n?: { language?: string; t?: (key: never, vars?: Record<string, unknown>) => string }
payload?: BasePayload
user?: null | Record<string, unknown>
}
/**
* Dashboard notice for administrators (admin.components.beforeDashboard):
* how many accounts have not set up two-step verification, and how many of
* them are blocked because the time for setup has passed. Renders nothing when
* every account has it, for non-admins, and when anything fails.
*/
export async function TwoFactorAlert({ adminRoute = '/admin', i18n, payload, user }: Props) {
if (!payload || !user || !userMeetsRole({ payload, user }, 'admin')) {return null}
const guard = (payload.config.custom as { ipal?: { twoFactor?: { collection?: string; setupWindowMs?: number } } } | undefined)?.ipal?.twoFactor
if (!guard?.collection) {return null}
let counts: { blocked: number; without: number }
try {
counts = await countAccountsWithoutTotp(payload, guard.collection, guard.setupWindowMs)
} catch {
return null
}
if (!counts.without) {return null}
const base = adminRoute === '/' ? '' : adminRoute.replace(/\/$/, '')
return (
<div
role="status"
style={{ background: 'var(--theme-warning-100, #fff8e1)', border: '1px solid var(--theme-warning-500, #f0b400)', borderRadius: 4, marginBottom: '1.5rem', padding: '1rem 1.25rem' }}
>
<strong>{serverText(i18n, 'twoFactorAlertTitle')}</strong>
<p style={{ margin: '.35rem 0 0' }}>{serverText(i18n, 'twoFactorAlertPending', { count: counts.without })}</p>
{counts.blocked > 0 && <p style={{ margin: '.35rem 0 0' }}>{serverText(i18n, 'twoFactorAlertBlocked', { count: counts.blocked })}</p>}
<p style={{ margin: '.35rem 0 0' }}>
<a href={`${base}/collections/${guard.collection}`}>{serverText(i18n, 'twoFactorAlertLink')}</a>
</p>
</div>
)
}
@@ -0,0 +1,52 @@
'use client'
import { toast, useConfig, useTranslation } from '@payloadcms/ui'
import { useState } from 'react'
import { ipalT } from '../../admin-i18n/t.js'
type Props = {
/** `reopen`: the account has no TOTP (window passed or still open). `reset`: it has one (lost phone). */
kind: 'reopen' | 'reset'
userId: number | string
}
/** The admin's button on an account: clears its TOTP so it can (or must) set it up again. */
export function TwoFactorResetButton({ kind, userId }: Props) {
const { t } = useTranslation()
const text = (key: Parameters<typeof ipalT>[1]) => ipalT(t as never, key)
const { config } = useConfig()
const [busy, setBusy] = useState(false)
const run = async () => {
if (kind === 'reset' && !window.confirm(text('twoFactorResetConfirm'))) {return}
setBusy(true)
try {
const res = await fetch(`${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/two-factor/reset`, {
body: JSON.stringify({ userId }),
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
})
const data = (await res.json()) as { message?: string; ok?: boolean }
if (data.ok) {
toast.success(data.message ?? text('twoFactorResetDone'))
// The status next to this button is rendered on the server with the document: load it again.
// (router.refresh() does not re-render a document's field components.)
window.location.reload()
} else {
toast.error(data.message ?? text('twoFactorResetFailed'))
}
} catch {
toast.error(text('twoFactorResetFailed'))
} finally {
setBusy(false)
}
}
return (
<button className="btn btn--style-secondary btn--size-small" disabled={busy} onClick={run} style={{ marginTop: '.5rem' }} type="button">
{text(kind === 'reopen' ? 'twoFactorReopen' : 'twoFactorReset')}
</button>
)
}
@@ -0,0 +1,64 @@
import type { BasePayload } from 'payload'
import { userMeetsRole } from '../../access/predicates.js'
import { formatDateTime } from '../../admin-i18n/t.js'
import { serverText } from '../../integrations/texts.js'
import { twoFactorSetupDeadline, twoFactorSetupState } from './secondFactor.js'
import { TwoFactorResetButton } from './TwoFactorResetButton.js'
type Props = {
/** The account being shown. Injected by Payload into field server components. */
data?: { id?: number | string } & Record<string, unknown>
i18n?: { language?: string; t?: (key: never, vars?: Record<string, unknown>) => string }
payload?: BasePayload
/** The account looking at it. */
user?: ({ id?: number | string } & Record<string, unknown>) | null
}
/**
* On an account in the panel (sidebar): where it stands with two-step
* verification — set up, open until a date, or blocked because the time for
* setup has passed — and, for an administrator looking at someone else's
* account, the button that resets it / reopens setup.
*/
export async function TwoFactorStatusField({ data, i18n, payload, user }: Props) {
if (!payload || !data?.id) {return null}
const collection = (payload.config.custom as { ipal?: { twoFactor?: { collection?: string } } } | undefined)?.ipal?.twoFactor?.collection
if (!collection) {return null}
// The document data the panel passes hides `hasTotp` from everyone but the account itself (the 2FA
// package's field access), so an admin would always read "set up". Ask the database: the secret is
// only tested for presence, never shown.
let stored: { totpSecret?: null | string; totpSetupFrom?: null | string }
try {
stored = (await payload.findByID({
id: data.id,
collection: collection as never,
depth: 0,
overrideAccess: true,
select: { totpSecret: true, totpSetupFrom: true } as never,
showHiddenFields: true,
})) as typeof stored
} catch {
return null
}
const account = { id: data.id, collection, email: data.email, hasTotp: Boolean(stored.totpSecret), totpSetupFrom: stored.totpSetupFrom }
const state = twoFactorSetupState({ payload, user: account })
if (state === 'not-applicable') {return null}
const deadline = twoFactorSetupDeadline({ payload, user: account })
const date = deadline ? formatDateTime(deadline.toISOString(), i18n?.language ?? 'en') : ''
const status =
state === 'set-up' ? serverText(i18n, 'twoFactorStatusOn')
: state === 'exempt' ? serverText(i18n, 'twoFactorStatusExempt')
: state === 'closed' ? serverText(i18n, 'twoFactorStatusClosed', { date })
: deadline ? serverText(i18n, 'twoFactorStatusOpen', { date })
: serverText(i18n, 'twoFactorStatusOpenNoLimit')
const canReset = Boolean(user && user.id !== data.id && userMeetsRole({ payload, user }, 'admin'))
return (
<div className="field-type" id="ipal-two-factor-status">
<span className="field-label">{serverText(i18n, 'twoFactorStatusLabel')}</span>
<p style={{ margin: 0, ...(state === 'closed' ? { color: 'var(--theme-error-500, #b00020)' } : {}) }}>{status}</p>
{canReset && state !== 'exempt' && <TwoFactorResetButton kind={state === 'set-up' ? 'reset' : 'reopen'} userId={data.id} />}
</div>
)
}
+69 -11
View File
@@ -21,7 +21,9 @@ import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payloa
* logs a warning at start);
* 4. `_strategy === 'totp'` → set by the package's strategy after password and code;
* 5. `_strategy === 'api-key'` → an API key is its own credential (the package's rule);
* 6. `hasTotp === false` → TOTP not set up yet (the setup screen needs the session);
* 6. `hasTotp === false` (TOTP not set up yet) → only when setup is not required
* (`twoFactor.requireSetup: false`) or the project's `exempt` says so for that account;
* by default such an account is refused like one that owes its code;
* 7. per-entity opt-out in the project's config (`custom.totp.disableAccessWrapper`,
* `custom.ipal.secondFactor`), or the package's global `disableAccessWrapper`;
* 8. `access.admin` (may this account open the panel) is not wrapped: the code is
@@ -36,14 +38,61 @@ import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payloa
* It fails closed. An account of the 2FA collection passes only when
* - it came through the package's `totp` strategy (password AND code), or
* - it authenticated with an API key (the package's own rule), or
* - TOTP is not set up on it yet (`hasTotp === false`) — the setup screen
* needs that, and the package lets such an account through as well.
* Anything else — code not entered, or a user object this check does not
* understand (a renamed strategy, no `hasTotp`) — is refused.
* - TOTP is not set up on it yet AND setup is not required
* (`twoFactor.requireSetup: false`), or the project exempts the account.
* Anything else — code not entered, TOTP not set up yet, or a user object this
* check does not understand (a renamed strategy, no `hasTotp`) — is refused.
*
* "Setup required" (the default): an account without TOTP reaches nothing at
* the access level. It does not need to: the setup screen is rendered from the
* session, and `/api/setup-totp` is an endpoint that writes with
* `overrideAccess`. It is the same state an account is in between its password
* and its code. The package alone only redirects such an account in the panel.
*/
/** What ipalKit records in `config.custom.ipal.twoFactor` when 2FA is on and the guard is not switched off. */
export type TwoFactorGuardConfig = { collection: string }
export type TwoFactorGuardConfig = {
collection: string
/** The project's exemption for accounts that never set TOTP up (a service account logging in with a password). */
exempt?: (args: { user: Record<string, unknown> }) => boolean
/** An account without TOTP is refused everything until it is set up. */
requireSetup?: boolean
/** How long after `totpSetupFrom` setup stays possible, in ms. 0 / undefined = no limit. */
setupWindowMs?: number
}
/** Field on the 2FA collection: when the current setup window opened (account created, or an admin reset). */
export const SETUP_FROM_FIELD = 'totpSetupFrom'
/**
* Where an account stands with TOTP setup:
* - `not-applicable`: no user, another collection, 2FA or the guard off;
* - `set-up`: TOTP is set up;
* - `exempt`: not set up, and the project exempts it (or setup is not required);
* - `open`: not set up, may set it up now;
* - `closed`: not set up and the setup window has passed — blocked until an admin reopens it.
*/
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). */
export function twoFactorSetupDeadline({ payload, user }: MaybeReq): Date | null {
const guard = guardConfig(payload)
const from = (user as null | Record<string, unknown> | undefined)?.[SETUP_FROM_FIELD]
if (!guard?.setupWindowMs || (typeof from !== 'string' && !(from instanceof Date))) {return null}
const start = new Date(from).getTime()
return Number.isFinite(start) ? new Date(start + guard.setupWindowMs) : null
}
export function twoFactorSetupState({ payload, user }: MaybeReq, now: number = Date.now()): TwoFactorSetupState {
const guard = guardConfig(payload)
if (!guard || !user || typeof user !== 'object') {return 'not-applicable'}
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'}
const deadline = twoFactorSetupDeadline({ payload, user })
return deadline && deadline.getTime() < now ? 'closed' : 'open'
}
type MaybeReq = { payload?: Pick<BasePayload, 'config'>; user?: unknown }
@@ -51,10 +100,11 @@ const guardConfig = (payload: MaybeReq['payload']): TwoFactorGuardConfig | undef
(payload?.config?.custom as { ipal?: { twoFactor?: TwoFactorGuardConfig } } | undefined)?.ipal?.twoFactor
/**
* False only for an account that still owes the second factor: it belongs to
* the 2FA collection, has TOTP set up and has not entered the code in this
* session. True for everyone else — no user (the access function decides),
* accounts of other auth collections, 2FA off (`twoFactor: false`).
* False for an account that still owes the second factor: it belongs to the
* 2FA collection and either has TOTP set up and has not entered the code in
* this session, or has not set TOTP up at all (unless setup is not required
* or the project exempts it). True for everyone else — no user (the access
* function decides), accounts of other auth collections, 2FA off (`twoFactor: false`).
*
* Pass `req`. Use it in your own endpoints and access functions:
* if (!secondFactorPassed(req)) return Response.json({ ok: false }, { status: 403 })
@@ -72,7 +122,9 @@ export function secondFactorPassed({ payload, user }: MaybeReq): boolean {
// "Not set up yet" only when nothing says otherwise. The package computes `hasTotp` with a second
// database read and answers false when that read fails; the secret on the user object itself (it
// came with the account's own record) then still says the account has TOTP: refused.
return u.hasTotp === false && !(user as { totpSecret?: unknown }).totpSecret
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> }))
}
const GUARDED = Symbol.for('ipal.secondFactorGuard')
@@ -321,6 +373,8 @@ export type TotpEndpointGuards = {
* it. Return a Response to refuse (too many attempts), null to let it through.
*/
limitVerify?: (req: never) => null | Promise<null | Response> | Response
/** The answer for an account whose setup window has passed (in the caller's language). Default: a plain 403. */
onSetupClosed?: (req: never) => Response
}
export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collection: string, guards: TotpEndpointGuards = {}): T {
@@ -332,6 +386,10 @@ export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collectio
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()}
// Setup after the window: blocked until an admin reopens it.
if (user && endpoint.path === '/setup-totp' && twoFactorSetupState(req) === 'closed') {
return guards.onSetupClosed ? guards.onSetupClosed(req as never) : refused()
}
// The code has about three right answers in a million and the package never counts tries.
if (user && endpoint.path === '/verify-totp' && guards.limitVerify) {
const limited = await guards.limitVerify(req as never)
+184
View File
@@ -0,0 +1,184 @@
import type { BasePayload, CollectionBeforeChangeHook, Endpoint, Field, PayloadRequest } from 'payload'
import { isAdmin, userMeetsRole } from '../../access/predicates.js'
import { serverText } from '../../integrations/texts.js'
import { secondFactorPassed, SETUP_FROM_FIELD } from './secondFactor.js'
/**
* "2FA setup required": the pieces ipalKit adds to the 2FA collection and the
* config when the mode is on (the default with `twoFactor`).
*
* - the date field `totpSetupFrom` — when the current setup window opened;
* - a hook that stamps it when an account is created and whenever its TOTP
* secret is cleared (an admin reset, a removal);
* - a backfill for accounts that existed before the mode (onInit);
* - POST /api/ipal/two-factor/reset — an admin clears an account's TOTP, which
* reopens its setup window;
* - the status / reset field shown on the account in the panel.
*
* The rule itself (who is refused) lives in secondFactor.ts.
*/
export type RequireSetupOptions = {
/**
* 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]'`
*/
exempt?: (args: { user: Record<string, unknown> }) => boolean
/**
* 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
* setup. Default 72. `false` or `0` = no limit (still nothing but setup until it is done).
*/
windowHours?: false | number
}
export const DEFAULT_SETUP_WINDOW_HOURS = 72
export const TWO_FACTOR_RESET_PATH = '/ipal/two-factor/reset'
/** `twoFactor.requireSetup` → what the guard reads. */
export function resolveRequireSetup(option: false | RequireSetupOptions | undefined): {
exempt?: RequireSetupOptions['exempt']
requireSetup: boolean
setupWindowMs: number
} {
if (option === false) {return { requireSetup: false, setupWindowMs: 0 }}
const hours = option?.windowHours === false ? 0 : (option?.windowHours ?? DEFAULT_SETUP_WINDOW_HOURS)
return {
...(option?.exempt ? { exempt: option.exempt } : {}),
requireSetup: true,
setupWindowMs: Number.isFinite(hours) && 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 [
{
name: SETUP_FROM_FIELD,
type: 'date',
access: {
// Written by the hook below only — never through the API.
create: () => false,
read: ({ data, doc, req }) => isAdmin(req.user, req.payload) || Boolean(req.user && ((doc ?? data) as { id?: unknown } | undefined)?.id === req.user.id),
update: () => false,
},
admin: { disableBulkEdit: true, disableListColumn: true, disableListFilter: true, hidden: true },
label: { en: 'Two-step verification: setup open since', pl: 'Weryfikacja dwuetapowa: konfiguracja otwarta od' },
},
{
name: 'totpSetupStatus',
type: 'ui',
admin: {
components: { Field: '@intecion/ipal-kit/admin#TwoFactorStatusField' },
disableListColumn: true,
position: 'sidebar',
},
},
]
}
/**
* Stamps `totpSetupFrom`: on create, and when an account that had TOTP loses
* its secret (the 2FA package's own remove / admin endpoints). The reset
* endpoint below writes the date itself, so it also reopens the window of an
* account that never had TOTP. Neither field can be written through the API
* (field access), so only server code gets here with them.
*/
export const stampSetupFrom: CollectionBeforeChangeHook = ({ data, operation, originalDoc }) => {
if (!data) {return data}
const hadTotp = Boolean((originalDoc as { totpSecret?: unknown } | undefined)?.totpSecret)
if (operation === 'create' ? !data[SETUP_FROM_FIELD] : hadTotp && 'totpSecret' in data && !data.totpSecret) {
data[SETUP_FROM_FIELD] = new Date().toISOString()
}
return data
}
/**
* Accounts that existed before the mode have no `totpSetupFrom`. Their window
* starts now — at the first start after the upgrade — so nobody is blocked the
* moment a site upgrades: each such account gets the full window to set TOTP
* up. Runs on every start; after the first there is nothing left to do.
* Returns how many accounts it stamped; never throws (a database that has not
* been migrated yet must not stop the site).
*/
export async function backfillSetupFrom(payload: BasePayload, collection: string): Promise<number> {
try {
const where = {
and: [
{ or: [{ totpSecret: { exists: false } }, { totpSecret: { equals: '' } }] },
{ [SETUP_FROM_FIELD]: { exists: false } },
],
}
const { totalDocs } = await payload.count({ collection: collection as never, overrideAccess: true, where: where as never })
if (!totalDocs) {return 0}
const data = { [SETUP_FROM_FIELD]: new Date().toISOString() }
// One query where the adapter has it (Payload 3.9x); the Local API otherwise. Hooks have nothing to add here.
if (typeof payload.db.updateMany === 'function') {
await payload.db.updateMany({ collection: collection as never, data: data as never, where: where as never })
} else {
await payload.update({ collection: collection as never, data: data as never, overrideAccess: true, where: where as never })
}
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}".`)
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. */
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.
*/
export function buildTwoFactorResetEndpoint(collection: string, options: TwoFactorResetOptions = {}): Endpoint {
return {
handler: async (req) => {
const i18n = req.i18n as Parameters<typeof serverText>[0]
const allowed =
Boolean(req.user) &&
secondFactorPassed(req) &&
(req.user as { collection?: unknown }).collection === collection &&
(options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'admin'))
if (!allowed) {return Response.json({ message: serverText(i18n, 'twoFactorResetForbidden'), ok: false }, { status: 403 })}
let body: unknown
try {
body = await req.json?.()
} catch {
body = undefined
}
const userId = (body as { userId?: unknown } | undefined)?.userId
if (typeof userId !== 'string' && typeof userId !== 'number') {
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 })
} 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 })
}
const actor = (req.user as { email?: string; id?: unknown }).email ?? String((req.user as { id?: unknown }).id)
req.payload.logger.info(`[ipal] 2FA reset for ${collection} ${String(userId)} by ${actor}.`)
return Response.json({ message: serverText(i18n, 'twoFactorResetDone'), ok: true })
},
method: 'post',
path: TWO_FACTOR_RESET_PATH,
}
}
/** Accounts of the 2FA collection without TOTP, and how many of those are past their setup window. */
export async function countAccountsWithoutTotp(payload: BasePayload, collection: string, setupWindowMs = 0): Promise<{ blocked: number; without: number }> {
const none = { or: [{ totpSecret: { exists: false } }, { totpSecret: { equals: '' } }] }
const without = (await payload.count({ collection: collection as never, overrideAccess: true, where: none as never })).totalDocs
if (!without || !setupWindowMs) {return { blocked: 0, without }}
const limit = new Date(Date.now() - setupWindowMs).toISOString()
const blocked = (await payload.count({ collection: collection as never, overrideAccess: true, where: { and: [none, { [SETUP_FROM_FIELD]: { less_than: limit } }] } as never })).totalDocs
return { blocked, without }
}
+46 -3
View File
@@ -32,6 +32,7 @@ import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.js'
import { withFillLocales } from './modules/hooks/fillEmptyLocales.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { serverText } from './modules/integrations/texts.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js'
@@ -45,6 +46,7 @@ import {
passOptOutsToPackage,
watchPayloadConfig,
} from './modules/security/totp/secondFactor.js'
import { backfillSetupFrom, buildSetupFields, buildTwoFactorResetEndpoint, resolveRequireSetup, stampSetupFrom } from './modules/security/totp/setupRequired.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'
@@ -189,6 +191,9 @@ export const ipalKit = (options: IpalOptions): Plugin => {
const late = ensurePayloadGuarded(payload)
if (late?.length) {payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`)}
}
/** 2FA collection when "setup required" is on — its existing accounts get their setup window in onInit. */
let setupRequiredFor: null | string = null
let setupWindowHours = 0
if (options.twoFactor !== false) {
const tf = options.twoFactor
if (!tf?.issuer) {
@@ -257,7 +262,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// Only accounts of the 2FA collection may use them (guardTotpEndpoint) —
// whatever the package registered, also paths a later version adds.
const limitVerify = tf.verifyLimit === false ? undefined : buildVerifyLimit(target, tf.verifyLimit)
const guards = limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}
const guards = {
...(limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}),
onSetupClosed: (req: PayloadRequest) =>
Response.json({ message: serverText(req.i18n as never, 'twoFactorSetupClosed'), ok: false }, { status: 403 }),
}
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)
@@ -286,7 +295,31 @@ export const ipalKit = (options: IpalOptions): Plugin => {
)
}
secondFactorGuard = true
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, twoFactor: { collection: target } } }
// "Setup required" (default): an account without TOTP reaches nothing but the setup
// screen, and only within the window; requireSetup: false = the package's rule.
const setup = resolveRequireSetup(tf.requireSetup)
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, twoFactor: { collection: target, ...setup } } }
if (setup.requireSetup) {
setupRequiredFor = target
setupWindowHours = setup.setupWindowMs / 3_600_000
config.collections = (config.collections ?? []).map((c) =>
c.slug === target
? { ...c, fields: [...c.fields, ...buildSetupFields()], hooks: { ...c.hooks, beforeChange: [...(c.hooks?.beforeChange ?? []), stampSetupFrom] } }
: c,
)
config.admin = {
...config.admin,
components: {
...config.admin?.components,
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
{ path: '@intecion/ipal-kit/admin#TwoFactorAlert', serverProps: { adminRoute: options.adminRoute ?? '/admin' } },
],
},
}
}
// An admin resets an account's TOTP (lost phone) / reopens its setup window.
config.endpoints = [...(config.endpoints ?? []), buildTwoFactorResetEndpoint(target, { access: tf.resetAccess })]
// 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(adoptConfig)
@@ -342,7 +375,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
p && (typeof p === 'string' ? p : p.path) === TOTP_PACKAGE_PROVIDER
? {
...ours,
clientProps: { forceSetup: true, ...ours.clientProps },
clientProps: { forceSetup: true, ...(setupRequiredFor ? { requireSetup: true, setupWindowHours } : {}), ...ours.clientProps },
serverProps: { ...(typeof p === 'object' ? p.serverProps : {}), ...ours.serverProps },
}
: p,
@@ -779,6 +812,16 @@ export const ipalKit = (options: IpalOptions): Plugin => {
)
}
}
// Accounts from before "setup required": their window starts now, not at their creation date.
if (setupRequiredFor) {
const started = await backfillSetupFrom(payload, setupRequiredFor)
if (started) {
payload.logger.warn(
`[ipal] 2FA: ${started} existing account(s) without two-step verification. ` +
(setupWindowHours ? `They have ${setupWindowHours} h from now to set it up; after that an administrator must reopen setup.` : 'They cannot use the panel until they set it up.'),
)
}
}
await migrateCookieSettingsSaveButton(payload)
await migrateTitleSeparator(payload, settingsSlug)
if (adminMeta) {await syncAdminMeta(payload, adminMeta, { nameField: brandFields.nameField, settingsSlug })}
+18 -1
View File
@@ -1,4 +1,4 @@
import type { CollectionSlug, Field, PayloadComponent, Plugin } from 'payload'
import type { CollectionSlug, Field, PayloadComponent, PayloadRequest, Plugin } from 'payload'
/**
* Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected
@@ -24,6 +24,7 @@ import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js'
import type { I18nConfig } from './modules/i18n/types.js'
import type { PagesOption } from './modules/pages/types.js'
import type { SafeBackRule } from './modules/security/totp/safeBack.js'
import type { RequireSetupOptions } from './modules/security/totp/setupRequired.js'
import type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
import type { SeoOption } from './modules/seo/types.js'
import type { StatsOptions } from './modules/stats/collection.js'
@@ -275,6 +276,22 @@ export type IpalOptions = {
* (then set `x-pathname` on /admin yourself). Run generate:importmap.
*/
provider?: false | PayloadComponent
/**
* "Setup required", on by default: an account that has not set TOTP up
* reaches nothing at the access level (REST, GraphQL, the panel's data) —
* only the setup screen and its endpoint. It has `windowHours` (default 72)
* from its creation, or from a reset by an admin, to set TOTP up; after that
* it is blocked until an admin reopens setup (the account's page in the
* panel, or POST /api/ipal/two-factor/reset). Accounts that existed before
* the mode get the full window from the first start after the upgrade.
* `{ windowHours: false }` = no time limit; `{ exempt: ({ user }) => … }` =
* accounts that may work without TOTP on purpose (a service account);
* `false` = the 2FA package's rule (the panel redirects, the API is open
* until setup). Needs `guard` on. docs/security.md.
*/
requireSetup?: false | RequireSetupOptions
/** Who may reset another account's TOTP / reopen its setup. Default: a staff admin. The second factor is always required. */
resetAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
/**
* Check on the `back` query value of the 2FA setup and verify screens. The
* 2FA package sends the browser there after a valid code without looking at