Security audit 2026-12, F0: inside an account's setup window its password alone enrolled an authenticator of the caller's choosing; the owner was locked out. - /setup-totp for an account without a factor: IAPL checks the code, keeps the secret pending (payload-kv), mails a single-use 30-min link to the account and ties it to the enrolling browser; the package's handler (and its -totp cookie) is never used for a first enrolment - GET /api/iapl/two-factor/confirm = a page with one button; POST confirms (own origin, same browser), ends the account's sessions, signs nobody in - notice mails on every enrolment, change, removal / reset (any path) - mail not working: link to the server log, admin confirms on the account page (POST /api/iapl/two-factor/confirm-pending), doctor rule 2fa-enrolment-mail - options and opt-out (confirmByEmail: false), building blocks exported - tests: HTTP suite on SQLite, MongoDB, Postgres; built-site spec in e2e:built; closed doors and judged routes; docs, AGENT.md, skills, changelog Co-Authored-By: Claude Opus 5.5 <[email protected]>
135 lines
6.8 KiB
TypeScript
135 lines
6.8 KiB
TypeScript
import type { AdminViewServerProps } from 'payload'
|
|
import type React from 'react'
|
|
|
|
import { RenderServerComponent } from '@payloadcms/ui/elements/RenderServerComponent'
|
|
import { getFromImportMap } from 'payload/shared'
|
|
|
|
import type { SignInLookProps } from '../../branding/signIn/brand.js'
|
|
|
|
import { iaplT } from '../../admin-i18n/t.js'
|
|
import { securityTexts } from '../../admin-i18n/texts/security.js'
|
|
import { signInProviderActive } from '../../branding/signIn/brand.js'
|
|
import { SignInPanel } from '../../branding/signIn/SignInPanel.js'
|
|
import { CodeInputNames } from './CodeInputNames.js'
|
|
import { maskAddress, pendingEnrolmentInfo } from './enrolmentConfirm.js'
|
|
import { safeAdminBack, type SafeBackRule, type TotpViewComponent, totpViewImportKey } from './safeBack.js'
|
|
|
|
export type SafeTotpViewProps = {
|
|
/**
|
|
* `whiteLabel.signIn`, set by the plugin: the sign-in panel is printed in front of the 2FA screen when the
|
|
* provider (`SignInLook`) does not print it. Not set: the screen as the package draws it.
|
|
*/
|
|
iaplSignIn?: SignInLookProps
|
|
/** `twoFactor.safeBack` as a function: replaces the default rule. */
|
|
ipalSafeBack?: SafeBackRule
|
|
/** `clientProps` of the view's own registration; passed on to it. */
|
|
ipalTotpClientProps?: Record<string, unknown>
|
|
/** The view to render, as registered: `'@clocklimited/payload-2fa/rsc#TOTPVerify'` or `{ path, exportName }`. */
|
|
ipalTotpView: TotpViewComponent
|
|
} & AdminViewServerProps
|
|
|
|
const originOf = (serverURL: unknown): string | undefined => {
|
|
if (typeof serverURL !== 'string' || !serverURL) {return undefined}
|
|
try {
|
|
return new URL(serverURL).origin
|
|
} catch {
|
|
return undefined
|
|
}
|
|
}
|
|
|
|
/** What Payload itself hands a client view (AdminViewClientProps): all serializable. */
|
|
const CLIENT_PROPS = ['browseByFolderSlugs', 'clientConfig', 'collectionSlug', 'docID', 'documentSubViewType', 'folderID', 'globalSlug', 'viewType'] as const
|
|
|
|
/**
|
|
* In front of the 2FA package's setup and verify views: replaces the `back` query value with a
|
|
* checked one (safeBack.ts) and renders the view with it. The package's form sends the browser
|
|
* to `back` after a valid code, so what it receives must be safe to navigate to.
|
|
*
|
|
* The view is rendered the way Payload renders any view: a server component gets every server
|
|
* prop, with `searchParams.back` checked; a client component (a project's own screen set through
|
|
* the wrapped factory) gets only what can cross to the browser — Payload's client props, its own
|
|
* `clientProps`, `searchParams` and `back`, both checked.
|
|
*
|
|
* iapl registers it (twoFactor.safeBack, on by default). A project that registers 2FA views
|
|
* itself can use it too: `wrapTotpViews`, or give it `ipalTotpView` and list that path in
|
|
* `admin.dependencies`.
|
|
*/
|
|
export function SafeTotpView(props: SafeTotpViewProps): React.ReactNode {
|
|
const { iaplSignIn, ipalSafeBack, ipalTotpClientProps, ipalTotpView, ...rest } = props
|
|
const config = props.initPageResult?.req?.payload?.config ?? props.payload?.config
|
|
const query = (props.searchParams ?? {}) as Record<string, unknown>
|
|
const back = (ipalSafeBack ?? safeAdminBack)(typeof query.back === 'string' ? query.back : undefined, {
|
|
adminRoute: config?.routes?.admin ?? '/admin',
|
|
origin: originOf(config?.serverURL),
|
|
})
|
|
const searchParams = { ...query, back }
|
|
|
|
if (!getFromImportMap({ importMap: props.importMap, PayloadComponent: ipalTotpView, schemaPath: '', silent: true })) {
|
|
throw new Error(
|
|
`[iapl] The admin import map has no "${totpViewImportKey(ipalTotpView)}" (the 2FA screen IAPL puts its back-link check in front of). ` +
|
|
'Run `pnpm payload generate:importmap` and commit the result.',
|
|
)
|
|
}
|
|
const clientProps: Record<string, unknown> = { ...ipalTotpClientProps, back, searchParams }
|
|
for (const key of CLIENT_PROPS) {
|
|
if (key in rest) {clientProps[key] = (rest as Record<string, unknown>)[key]}
|
|
}
|
|
const view = RenderServerComponent({
|
|
clientProps,
|
|
Component: ipalTotpView,
|
|
importMap: props.importMap,
|
|
serverProps: { ...rest, searchParams },
|
|
})
|
|
const req = props.initPageResult?.req
|
|
const payload = req?.payload ?? props.payload
|
|
const i18n = (req?.i18n ?? props.i18n) as { language?: string; t: (key: never, vars?: Record<string, unknown>) => string } | undefined
|
|
// A set-up waiting for its e-mail link (twoFactor.confirmByEmail): say where the link went, above the setup screen.
|
|
// (its own async server component: SafeTotpView stays a plain function for projects that call it)
|
|
const shown = pendingNoticeWanted(payload, totpViewImportKey(ipalTotpView)) ? (
|
|
<>
|
|
<PendingEnrolmentNotice i18n={i18n} payload={payload} user={(req?.user ?? props.user) as never} />
|
|
{view}
|
|
</>
|
|
) : view
|
|
// The look only: the panel is a sibling in front of the screen, the screen itself is rendered as above.
|
|
if (!iaplSignIn) {return shown}
|
|
const digit = i18n ? iaplT(i18n.t, 'twoFactorCodeDigit', { n: '%n', total: '%t' }) : securityTexts.en.twoFactorCodeDigit.replace('{{n}}', '%n').replace('{{total}}', '%t')
|
|
return (
|
|
<>
|
|
{signInProviderActive(payload) ? null : (
|
|
<SignInPanel
|
|
i18n={i18n as never}
|
|
locale={(props.initPageResult?.locale ?? props.locale) as never}
|
|
look={iaplSignIn}
|
|
payload={payload}
|
|
user={(req?.user ?? props.user) as never}
|
|
/>
|
|
)}
|
|
{shown}
|
|
<CodeInputNames label={digit} />
|
|
</>
|
|
)
|
|
}
|
|
|
|
const pendingNoticeWanted = (payload: SafeTotpViewProps['payload'] | undefined, viewKey: string) =>
|
|
Boolean((payload?.config?.custom as { iapl?: { twoFactorConfirmByEmail?: unknown } } | undefined)?.iapl?.twoFactorConfirmByEmail) && /setup/i.test(viewKey)
|
|
|
|
/** The notice on the setup screen while the account's first set-up waits for its e-mail link; nothing otherwise. */
|
|
async function PendingEnrolmentNotice({ i18n, payload, user }: {
|
|
i18n: { language?: string; t: (key: never, vars?: Record<string, unknown>) => string } | undefined
|
|
payload: SafeTotpViewProps['payload'] | undefined
|
|
user: ({ collection?: string; email?: string; id?: number | string } & Record<string, unknown>) | null | undefined
|
|
}): Promise<React.ReactNode> {
|
|
if (!payload || !user?.id || typeof user.collection !== 'string') {return null}
|
|
const pending = await pendingEnrolmentInfo(payload, user.collection, user.id).catch(() => null)
|
|
if (!pending) {return null}
|
|
const time = pending.createdAt.toLocaleTimeString(i18n?.language === 'pl' ? 'pl-PL' : 'en-GB', { hour: '2-digit', minute: '2-digit' })
|
|
const vars = { email: maskAddress(typeof user.email === 'string' ? user.email : ''), time }
|
|
const text = i18n ? iaplT(i18n.t, 'twoFactorEnrolPendingNotice', vars) : securityTexts.en.twoFactorEnrolPendingNotice.replace('{{email}}', vars.email).replace('{{time}}', time)
|
|
return (
|
|
<div className="banner banner--type-info" data-iapl="two-factor-pending" role="status" style={{ margin: '0 auto 1rem', maxWidth: '36rem' }}>
|
|
{text}
|
|
</div>
|
|
)
|
|
}
|