2FA: the first set-up is confirmed by e-mail (twoFactor.confirmByEmail, 1.18.0)
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]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
84717804ae
commit
c9d1f4b340
@@ -15,6 +15,35 @@ export const securityTexts = defineTexts({
|
||||
twoFactorAlertTitle: 'Two-step verification',
|
||||
twoFactorBusy: 'Another code for this account is being checked right now. Try again in a moment.',
|
||||
twoFactorCodeDigit: 'Digit {{n}} of {{total}}',
|
||||
twoFactorConfirmPending: 'Confirm the waiting set-up',
|
||||
twoFactorConfirmPendingAsk: 'Confirm only after you have checked with this person, outside the panel (phone, in person), that they started the set-up themselves. Continue?',
|
||||
twoFactorConfirmPendingDone: 'Done. Two-step verification is on for this account; it signs in again with its password and code.',
|
||||
twoFactorConfirmPendingNone: 'There is no waiting set-up for this account (it was confirmed, it expired, or it never started).',
|
||||
twoFactorEnrolButton: 'Turn on two-step verification',
|
||||
twoFactorEnrolDone: 'Two-step verification is on. Sign in again with your password and the code from your app.',
|
||||
twoFactorEnrolInvalid: 'This link does not work any more: it was used, it expired, or a newer set-up was started. Scan the code on the set-up screen again to get a new one.',
|
||||
twoFactorEnrolLead: 'Turn on two-step verification for your account? Do it only if you scanned the code yourself a moment ago, in this browser.',
|
||||
twoFactorEnrolMailFailed: 'The confirmation e-mail could not be sent. Ask an administrator to confirm your set-up on your account page.',
|
||||
twoFactorEnrolMailFailedNoAdmin: 'The confirmation e-mail could not be sent. Ask the people who run the site: the confirmation link is in the server log.',
|
||||
twoFactorEnrolOtherBrowser: 'Open this link in the browser where you scanned the code. If that is not possible, scan the code there again to get a new link.',
|
||||
twoFactorEnrolPendingNotice: 'A link was sent to {{email}} at {{time}}. Open it in this browser. No e-mail? Scan the code again, or ask an administrator.',
|
||||
twoFactorEnrolSent: 'Almost done: we sent a link to {{email}}. Open it in this browser within {{minutes}} min, then sign in again.',
|
||||
twoFactorEnrolSignIn: 'Go to sign-in',
|
||||
twoFactorEnrolTitle: 'Two-step verification',
|
||||
twoFactorEnrolTooMany: 'Too many set-up attempts for this account. Try again in {{minutes}} min.',
|
||||
twoFactorMailBy: 'Done by: {{by}}.',
|
||||
twoFactorMailChangedBody: 'The authenticator app for your account was changed ({{when}}).',
|
||||
twoFactorMailChangedSubject: 'Your two-step verification was changed',
|
||||
twoFactorMailEnrolBody: 'Someone signed in with your password and set up an authenticator app. It works only after the link below is opened in the same browser within {{minutes}} min.',
|
||||
twoFactorMailEnrolButton: 'Turn on two-step verification',
|
||||
twoFactorMailEnrolFrom: 'Browser: {{agent}}. Address: {{ip}}.',
|
||||
twoFactorMailEnrolNotYou: 'If it was not you, do not open the link: someone knows your password. Change it now and tell your administrator.',
|
||||
twoFactorMailEnrolSubject: 'Confirm two-step verification for your account',
|
||||
twoFactorMailNotYou: 'If you did not expect this, tell your administrator at once and change your password.',
|
||||
twoFactorMailOffBody: 'Two-step verification was removed from your account ({{when}}). You will set it up again at your next sign-in.',
|
||||
twoFactorMailOffSubject: 'Two-step verification was removed from your account',
|
||||
twoFactorMailOnBody: 'Two-step verification was turned on for your account ({{when}}).',
|
||||
twoFactorMailOnSubject: 'Two-step verification is on for your account',
|
||||
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?',
|
||||
@@ -30,6 +59,7 @@ export const securityTexts = defineTexts({
|
||||
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.',
|
||||
twoFactorStatusPending: 'Not set up yet. A set-up started on {{date}} waits for confirmation by e-mail.',
|
||||
twoFactorTooManyAttempts: 'Too many codes were tried for this account. Wait {{minutes}} min, then enter the current code from your app.',
|
||||
},
|
||||
pl: {
|
||||
@@ -45,6 +75,35 @@ export const securityTexts = defineTexts({
|
||||
twoFactorAlertTitle: 'Weryfikacja dwuetapowa',
|
||||
twoFactorBusy: 'Właśnie sprawdzamy inny kod dla tego konta. Spróbuj ponownie za chwilę.',
|
||||
twoFactorCodeDigit: 'Cyfra {{n}} z {{total}}',
|
||||
twoFactorConfirmPending: 'Potwierdź oczekującą konfigurację',
|
||||
twoFactorConfirmPendingAsk: 'Potwierdź tylko wtedy, gdy poza panelem (telefonicznie, osobiście) upewnisz się, że ta osoba sama rozpoczęła konfigurację. Kontynuować?',
|
||||
twoFactorConfirmPendingDone: 'Gotowe. Weryfikacja dwuetapowa jest włączona dla tego konta; logowanie od nowa hasłem i kodem.',
|
||||
twoFactorConfirmPendingNone: 'To konto nie ma oczekującej konfiguracji (została potwierdzona, wygasła albo się nie zaczęła).',
|
||||
twoFactorEnrolButton: 'Włącz weryfikację dwuetapową',
|
||||
twoFactorEnrolDone: 'Weryfikacja dwuetapowa jest włączona. Zaloguj się ponownie hasłem i kodem z aplikacji.',
|
||||
twoFactorEnrolInvalid: 'Ten link już nie działa: został użyty, wygasł albo rozpoczęto nowszą konfigurację. Zeskanuj kod na ekranie konfiguracji ponownie, aby dostać nowy.',
|
||||
twoFactorEnrolLead: 'Włączyć weryfikację dwuetapową dla tego konta? Tylko jeśli kod został przed chwilą zeskanowany w tej przeglądarce.',
|
||||
twoFactorEnrolMailFailed: 'Nie udało się wysłać e-maila z potwierdzeniem. Poproś administratora o potwierdzenie konfiguracji na stronie Twojego konta.',
|
||||
twoFactorEnrolMailFailedNoAdmin: 'Nie udało się wysłać e-maila z potwierdzeniem. Zwróć się do osób prowadzących stronę: link potwierdzający jest w logu serwera.',
|
||||
twoFactorEnrolOtherBrowser: 'Otwórz ten link w przeglądarce, w której zeskanowano kod. Jeśli to niemożliwe, zeskanuj tam kod ponownie, aby dostać nowy link.',
|
||||
twoFactorEnrolPendingNotice: 'Link wysłano na {{email}} o {{time}}. Otwórz go w tej przeglądarce. Brak e-maila? Zeskanuj kod ponownie albo poproś administratora.',
|
||||
twoFactorEnrolSent: 'Prawie gotowe: link wysłano na {{email}}. Otwórz go w tej przeglądarce w ciągu {{minutes}} min, a potem zaloguj się ponownie.',
|
||||
twoFactorEnrolSignIn: 'Przejdź do logowania',
|
||||
twoFactorEnrolTitle: 'Weryfikacja dwuetapowa',
|
||||
twoFactorEnrolTooMany: 'Zbyt wiele prób konfiguracji dla tego konta. Spróbuj ponownie za {{minutes}} min.',
|
||||
twoFactorMailBy: 'Wykonał(a): {{by}}.',
|
||||
twoFactorMailChangedBody: 'Aplikacja uwierzytelniająca Twojego konta została zmieniona ({{when}}).',
|
||||
twoFactorMailChangedSubject: 'Twoja weryfikacja dwuetapowa została zmieniona',
|
||||
twoFactorMailEnrolBody: 'Ktoś zalogował się Twoim hasłem i ustawił aplikację uwierzytelniającą. Zadziała po otwarciu linku poniżej w tej samej przeglądarce w ciągu {{minutes}} min.',
|
||||
twoFactorMailEnrolButton: 'Włącz weryfikację dwuetapową',
|
||||
twoFactorMailEnrolFrom: 'Przeglądarka: {{agent}}. Adres: {{ip}}.',
|
||||
twoFactorMailEnrolNotYou: 'Jeśli to nie Ty, nie otwieraj linku: ktoś zna Twoje hasło. Zmień je od razu i powiadom administratora.',
|
||||
twoFactorMailEnrolSubject: 'Potwierdź weryfikację dwuetapową swojego konta',
|
||||
twoFactorMailNotYou: 'Jeśli się tego nie spodziewasz, od razu powiadom administratora i zmień hasło.',
|
||||
twoFactorMailOffBody: 'Weryfikacja dwuetapowa została usunięta z Twojego konta ({{when}}). Ustawisz ją ponownie przy następnym logowaniu.',
|
||||
twoFactorMailOffSubject: 'Weryfikacja dwuetapowa została usunięta z Twojego konta',
|
||||
twoFactorMailOnBody: 'Weryfikacja dwuetapowa została włączona dla Twojego konta ({{when}}).',
|
||||
twoFactorMailOnSubject: 'Weryfikacja dwuetapowa jest włączona dla Twojego konta',
|
||||
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ć?',
|
||||
@@ -60,6 +119,7 @@ export const securityTexts = defineTexts({
|
||||
twoFactorStatusOn: 'Ustawiona.',
|
||||
twoFactorStatusOpen: 'Nieustawiona. Konto może ją ustawić do {{date}}.',
|
||||
twoFactorStatusOpenNoLimit: 'Jeszcze nieustawiona. Do tego czasu konto nie może korzystać z panelu.',
|
||||
twoFactorStatusPending: 'Jeszcze nieustawiona. Konfiguracja rozpoczęta {{date}} czeka na potwierdzenie e-mailem.',
|
||||
twoFactorTooManyAttempts: 'Dla tego konta wpisano zbyt wiele kodów. Odczekaj {{minutes}} min, a potem wpisz aktualny kod z aplikacji.',
|
||||
},
|
||||
})
|
||||
|
||||
@@ -183,6 +183,35 @@ export const securityRules: DoctorRule[] = [
|
||||
group: 'security',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// twoFactor.confirmByEmail (1.18.0): the first enrolment waits for a link sent by e-mail. Without working mail
|
||||
// nobody finishes setting 2FA up on their own: the link is only in the server log, or an admin confirms it.
|
||||
id: '2fa-enrolment-mail',
|
||||
check: (ctx) => {
|
||||
const c = ctx.deep?.twoFactorConfirm
|
||||
if (!c?.on) {return []}
|
||||
const out: RuleFinding[] = []
|
||||
const broken = c.mailConfigured === false || Boolean(ctx.deep?.mail?.methodProblem) || ctx.deep?.mail?.transport === 'none'
|
||||
if (broken) {
|
||||
out.push({
|
||||
fix: 'set up e-mail (Site integrations → E-mail sending: the mail service or SMTP; docs/email.md), then "Send a test e-mail"',
|
||||
message: `e-mail is not working, so nobody can finish setting up two-step verification by themselves: the confirmation link goes only to the server log${c.adminConfirm ? ', or an administrator confirms each set-up on the account page' : ''}`,
|
||||
severity: 'error',
|
||||
})
|
||||
}
|
||||
if (c.pending) {
|
||||
out.push({
|
||||
fix: broken ? 'fix e-mail first; meanwhile an administrator confirms each waiting set-up (account page → "Confirm the waiting set-up") after checking with the person' : 'the people open the link they received; a link expires after its time and they scan the code again',
|
||||
message: `${c.pending} first set-up(s) of two-step verification wait for their e-mail link`,
|
||||
severity: broken ? 'error' : 'info',
|
||||
})
|
||||
}
|
||||
return out
|
||||
},
|
||||
docs: 'docs/security.md#set-up-confirmed-by-e-mail-twofactorconfirmbyemail-118',
|
||||
group: 'security',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// Without `access` the plugin adds no roles: every account that can log in to the panel is an admin.
|
||||
id: 'access-missing',
|
||||
|
||||
@@ -10,6 +10,7 @@ import { countPendingCookies } from '../consent/scanner/approval.js'
|
||||
import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js'
|
||||
import { graphAvailable } from '../email/mailAdapter.js'
|
||||
import { mailPanelState } from '../email/relay/panel.js'
|
||||
import { countPendingEnrolments, mailConfigured } from '../security/totp/enrolmentConfirm.js'
|
||||
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
|
||||
import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js'
|
||||
import { accessAllowed } from '../shared/accessAnswer.js'
|
||||
@@ -46,6 +47,14 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
usersSetupClosed = (await countAccountsWithoutTotp(payload, auth.slug, windowMs)).blocked
|
||||
}
|
||||
}
|
||||
// First enrolments waiting for their e-mail link, and whether mail can carry them (twoFactor.confirmByEmail).
|
||||
let twoFactorConfirm: DoctorStatus['twoFactorConfirm'] = null
|
||||
const confirmOn = (payload.config.custom as { iapl?: { twoFactorConfirmByEmail?: { adminConfirm?: boolean } | false } } | undefined)?.iapl?.twoFactorConfirmByEmail
|
||||
if (auth && confirmOn !== undefined) {
|
||||
twoFactorConfirm = confirmOn
|
||||
? { adminConfirm: confirmOn.adminConfirm !== false, mailConfigured: mailConfigured(payload), on: true, pending: await countPendingEnrolments(payload, auth.slug) }
|
||||
: { on: false }
|
||||
}
|
||||
const pendingCookies = collections.some((c) => c.slug === COOKIE_REVIEW_SLUG) ? await countPendingCookies(payload) : null
|
||||
// Turnstile: the recorded state and where the secret comes from — never the keys themselves.
|
||||
let turnstile: DoctorStatus['turnstile'] = null
|
||||
@@ -121,7 +130,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
}
|
||||
const { csrf, serverURL } = payload.config as { csrf?: unknown; serverURL?: unknown }
|
||||
const originKnown = (typeof serverURL === 'string' && serverURL.trim() !== '') || (Array.isArray(csrf) && csrf.some((o) => typeof o === 'string' && o.trim() !== ''))
|
||||
return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa, visitorWrites }
|
||||
return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, twoFactorConfirm, usersSetupClosed, usersWithout2fa, visitorWrites }
|
||||
}
|
||||
|
||||
export type DoctorEndpointOptions = {
|
||||
|
||||
@@ -120,6 +120,11 @@ export type DoctorStatus = {
|
||||
turnstile?: { code?: null | string; since?: null | string; state?: null | string } | null
|
||||
/** The Turnstile secret key in use comes from the environment (the panel field is empty). Deprecated. */
|
||||
turnstileSecretFromEnv?: boolean | null
|
||||
/**
|
||||
* twoFactor.confirmByEmail: on or off, first enrolments waiting for their e-mail link (null = could not be counted),
|
||||
* whether a mail transport is configured (Payload's console fallback = not), and whether an admin may confirm.
|
||||
*/
|
||||
twoFactorConfirm?: { adminConfirm?: boolean; mailConfigured?: boolean; on: boolean; pending?: null | number } | null
|
||||
/** Of `usersWithout2fa`: accounts whose setup window has passed (blocked until an admin reopens setup). */
|
||||
usersSetupClosed?: null | number
|
||||
usersWithout2fa?: null | number
|
||||
|
||||
@@ -11,6 +11,7 @@ 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 = {
|
||||
@@ -81,9 +82,17 @@ export function SafeTotpView(props: SafeTotpViewProps): React.ReactNode {
|
||||
})
|
||||
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 view}
|
||||
const i18n = (req?.i18n ?? props.i18n) as { t: (key: never, vars?: Record<string, unknown>) => string } | undefined
|
||||
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 (
|
||||
<>
|
||||
@@ -96,8 +105,30 @@ export function SafeTotpView(props: SafeTotpViewProps): React.ReactNode {
|
||||
user={(req?.user ?? props.user) as never}
|
||||
/>
|
||||
)}
|
||||
{view}
|
||||
{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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,8 +6,11 @@ import { useState } from 'react'
|
||||
import { iaplT } 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'
|
||||
/**
|
||||
* `reopen`: the account has no TOTP (window passed or still open). `reset`: it has one (lost phone).
|
||||
* `confirm`: it has a set-up waiting for its e-mail confirmation, and the administrator confirms it (twoFactor.confirmByEmail).
|
||||
*/
|
||||
kind: 'confirm' | 'reopen' | 'reset'
|
||||
userId: number | string
|
||||
}
|
||||
|
||||
@@ -20,9 +23,11 @@ export function TwoFactorResetButton({ kind, userId }: Props) {
|
||||
|
||||
const run = async () => {
|
||||
if (kind === 'reset' && !window.confirm(text('twoFactorResetConfirm'))) {return}
|
||||
if (kind === 'confirm' && !window.confirm(text('twoFactorConfirmPendingAsk'))) {return}
|
||||
setBusy(true)
|
||||
try {
|
||||
const res = await fetch(`${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/two-factor/reset`, {
|
||||
const path = kind === 'confirm' ? '/iapl/two-factor/confirm-pending' : '/ipal/two-factor/reset'
|
||||
const res = await fetch(`${config.serverURL ?? ''}${config.routes?.api ?? '/api'}${path}`, {
|
||||
body: JSON.stringify({ userId }),
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -30,7 +35,7 @@ export function TwoFactorResetButton({ kind, userId }: Props) {
|
||||
})
|
||||
const data = (await res.json()) as { message?: string; ok?: boolean }
|
||||
if (data.ok) {
|
||||
toast.success(data.message ?? text('twoFactorResetDone'))
|
||||
toast.success(data.message ?? text(kind === 'confirm' ? 'twoFactorConfirmPendingDone' : '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()
|
||||
@@ -46,7 +51,7 @@ export function TwoFactorResetButton({ kind, userId }: Props) {
|
||||
|
||||
return (
|
||||
<button className="btn btn--style-secondary btn--size-small" disabled={busy} onClick={run} style={{ marginTop: '.5rem' }} type="button">
|
||||
{text(kind === 'reopen' ? 'twoFactorReopen' : 'twoFactorReset')}
|
||||
{text(kind === 'confirm' ? 'twoFactorConfirmPending' : kind === 'reopen' ? 'twoFactorReopen' : 'twoFactorReset')}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ 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 { pendingEnrolmentInfo } from './enrolmentConfirm.js'
|
||||
import { twoFactorSetupDeadline, twoFactorSetupState } from './secondFactor.js'
|
||||
import { TwoFactorResetButton } from './TwoFactorResetButton.js'
|
||||
|
||||
@@ -46,8 +47,11 @@ export async function TwoFactorStatusField({ data, i18n, payload, user }: Props)
|
||||
if (state === 'not-applicable') {return null}
|
||||
const deadline = twoFactorSetupDeadline({ payload, user: account })
|
||||
const date = deadline ? formatDateTime(deadline.toISOString(), i18n?.language ?? 'en') : ''
|
||||
const confirmOn = (payload.config.custom as { iapl?: { twoFactorConfirmByEmail?: { adminConfirm?: boolean } | false } } | undefined)?.iapl?.twoFactorConfirmByEmail
|
||||
const pending = confirmOn && (state === 'open' || state === 'exempt') ? await pendingEnrolmentInfo(payload, collection, data.id) : null
|
||||
const status =
|
||||
state === 'set-up' ? serverText(i18n, 'twoFactorStatusOn')
|
||||
pending ? serverText(i18n, 'twoFactorStatusPending', { date: formatDateTime(pending.createdAt.toISOString(), i18n?.language ?? 'en') })
|
||||
: state === 'set-up' ? serverText(i18n, 'twoFactorStatusOn')
|
||||
: state === 'exempt' ? serverText(i18n, 'twoFactorStatusExempt')
|
||||
: state === 'closed' ? serverText(i18n, 'twoFactorStatusClosed', { date })
|
||||
: deadline ? serverText(i18n, 'twoFactorStatusOpen', { date })
|
||||
@@ -58,6 +62,7 @@ export async function TwoFactorStatusField({ data, i18n, payload, user }: Props)
|
||||
<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 && pending && confirmOn && confirmOn.adminConfirm && <TwoFactorResetButton kind="confirm" userId={data.id} />}
|
||||
{canReset && state !== 'exempt' && <TwoFactorResetButton kind={state === 'set-up' ? 'reset' : 'reopen'} userId={data.id} />}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,554 @@
|
||||
import type { BasePayload, CollectionAfterChangeHook, CollectionBeforeChangeHook, Endpoint, PayloadRequest } from 'payload'
|
||||
|
||||
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
|
||||
|
||||
import type { AdminTextKey } from '../../admin-i18n/texts/index.js'
|
||||
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { afterCommit } from '../../database/transactions.js'
|
||||
import { withMailKind } from '../../email/relay/kinds.js'
|
||||
import { serverText } from '../../integrations/texts.js'
|
||||
import { consumeRateLimit } from '../../shared/rateLimit.js'
|
||||
import { secondFactorPassed } from './secondFactor.js'
|
||||
|
||||
/**
|
||||
* Two-step verification set up by e-mail confirmation (`twoFactor.confirmByEmail`, on by default; security audit
|
||||
* 2026-12, finding F0).
|
||||
*
|
||||
* Without it, whoever has an account's password can enrol THEIR OWN authenticator while the account has none (its
|
||||
* setup window), and the owner is locked out. So the FIRST enrolment of a factor is only stored as pending:
|
||||
* 1. `POST /api/setup-totp` with a right code for the new secret → the secret is kept aside (payload-kv), a
|
||||
* single-use link goes to the account's own e-mail, and the browser that asked gets a random cookie;
|
||||
* 2. the link (`GET /api/iapl/two-factor/confirm`) shows a page with one button — a mail scanner that opens links
|
||||
* changes nothing; the button posts it back;
|
||||
* 3. the POST checks the link (hash, 30 min, single use), that the pending secret is the one the link was made
|
||||
* for, and — `sameBrowser`, on by default — that it comes from the browser that started the set-up: the owner
|
||||
* who receives a mail they did not ask for cannot turn on the attacker's factor by clicking it. Then the secret
|
||||
* is written, every session of the account ends, and nobody is signed in: the person signs in again with the
|
||||
* password and the code.
|
||||
* Until then the account stays in its setup state: no factor, nothing but the setup screen.
|
||||
*
|
||||
* Mail that cannot be sent (no mail set up, the mail service pending, SMTP incomplete) must not lock anybody out:
|
||||
* - the link is written to the server log (`logLinkWhenMailFails`, on by default — the logs are read by the team
|
||||
* that runs the site, never by the person at the keyboard), and
|
||||
* - an administrator who is fully signed in confirms the waiting set-up from the account page (`adminConfirm`),
|
||||
* after checking with the person outside the panel.
|
||||
* - the doctor reports it (rule `2fa-enrolment-mail`).
|
||||
* A notice goes to the account's address on every enrolment, change and removal / reset of its factor (`notices`).
|
||||
* Mails never carry the secret.
|
||||
*/
|
||||
|
||||
export type ConfirmByEmailOptions = {
|
||||
/** An administrator (fully signed in) may confirm another account's waiting set-up from the panel. Default true. */
|
||||
adminConfirm?: boolean
|
||||
/** How long the link works, in minutes. Default 30. */
|
||||
linkMinutes?: number
|
||||
/** When the mail cannot be sent, the link is written to the server log (one line). Default true. */
|
||||
logLinkWhenMailFails?: boolean
|
||||
/** Confirmation mails per account and hour (each set-up attempt sends one). Default 5. */
|
||||
maxMailsPerHour?: number
|
||||
/** A notice to the account's address on every enrolment, change and removal / reset. Default true. */
|
||||
notices?: boolean
|
||||
/** The link works only in the browser that started the set-up. Default true. */
|
||||
sameBrowser?: boolean
|
||||
}
|
||||
|
||||
export type ResolvedConfirmByEmail = Required<ConfirmByEmailOptions>
|
||||
|
||||
export const ENROL_CONFIRM_PATH = '/iapl/two-factor/confirm'
|
||||
export const ENROL_ADMIN_CONFIRM_PATH = '/iapl/two-factor/confirm-pending'
|
||||
/** The cookie that ties a waiting set-up to the browser that started it (`<cookiePrefix>-iapl-enrol`). */
|
||||
export const ENROL_COOKIE_SUFFIX = 'iapl-enrol'
|
||||
/** The mark a write carries when it is the confirmed enrolment (afterChange sends the "turned on" notice). */
|
||||
export const ENROL_CONFIRMED_CONTEXT = 'iaplEnrolmentConfirmed'
|
||||
|
||||
const DEFAULTS: ResolvedConfirmByEmail = { adminConfirm: true, linkMinutes: 30, logLinkWhenMailFails: true, maxMailsPerHour: 5, notices: true, sameBrowser: true }
|
||||
|
||||
/** `twoFactor.confirmByEmail` → the options, or null when switched off. A value that is not understood stops the start. */
|
||||
export function resolveConfirmByEmail(option: unknown): null | ResolvedConfirmByEmail {
|
||||
if (option === false) {return null}
|
||||
if (option === undefined || option === null || option === true) {return { ...DEFAULTS }}
|
||||
if (typeof option !== 'object' || Array.isArray(option)) {
|
||||
throw new Error(`[iapl] twoFactor.confirmByEmail must be false or an object, got ${JSON.stringify(option)}.`)
|
||||
}
|
||||
const o = option as Record<string, unknown>
|
||||
const out = { ...DEFAULTS }
|
||||
for (const key of ['adminConfirm', 'logLinkWhenMailFails', 'notices', 'sameBrowser'] as const) {
|
||||
if (o[key] === undefined) {continue}
|
||||
if (typeof o[key] !== 'boolean') {throw new Error(`[iapl] twoFactor.confirmByEmail.${key} must be true or false, got ${JSON.stringify(o[key])}.`)}
|
||||
out[key] = o[key]
|
||||
}
|
||||
for (const key of ['linkMinutes', 'maxMailsPerHour'] as const) {
|
||||
if (o[key] === undefined) {continue}
|
||||
const v = o[key]
|
||||
if (typeof v !== 'number' || !Number.isInteger(v) || v < 1 || (key === 'linkMinutes' && v > 24 * 60)) {
|
||||
throw new Error(`[iapl] twoFactor.confirmByEmail.${key} must be a whole number${key === 'linkMinutes' ? ' of minutes from 1 to 1440' : ' of 1 or more'}, got ${JSON.stringify(v)}.`)
|
||||
}
|
||||
out[key] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- the code check
|
||||
|
||||
const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
|
||||
|
||||
function base32Bytes(secret: string): Buffer | null {
|
||||
const clean = secret.replace(/=+$/, '').toUpperCase()
|
||||
if (!/^[A-Z2-7]+$/.test(clean)) {return null}
|
||||
let bits = ''
|
||||
for (const ch of clean) {bits += BASE32.indexOf(ch).toString(2).padStart(5, '0')}
|
||||
return Buffer.from((bits.match(/.{8}/g) ?? []).map((b) => parseInt(b, 2)))
|
||||
}
|
||||
|
||||
export type TotpParams = { algorithm?: string; digits?: number; period?: number }
|
||||
|
||||
/**
|
||||
* RFC 6238 check of `token` for `secret` (base32), one period either side — the same rule as the 2FA package
|
||||
* (`otpauth`'s `validate({ window: 1 })` with its options), so a code the package would accept is accepted here.
|
||||
*/
|
||||
export function verifyTotpCode(secret: string, token: string, { algorithm = 'SHA1', digits = 6, period = 30 }: TotpParams = {}, now = Date.now()): boolean {
|
||||
const key = base32Bytes(secret)
|
||||
if (!key || key.length < 10 || typeof token !== 'string' || !new RegExp(`^\\d{${digits}}$`).test(token.trim())) {return false}
|
||||
const hash = algorithm.toLowerCase().replace('-', '')
|
||||
const counter = Math.floor(now / 1000 / period)
|
||||
for (const step of [0, -1, 1]) {
|
||||
const buf = Buffer.alloc(8)
|
||||
buf.writeBigUInt64BE(BigInt(counter + step))
|
||||
const mac = createHmac(hash, key).update(buf).digest()
|
||||
const offset = mac[mac.length - 1] & 0xf
|
||||
const code = ((mac.readUInt32BE(offset) & 0x7fffffff) % 10 ** digits).toString().padStart(digits, '0')
|
||||
if (timingSafeEqual(Buffer.from(code), Buffer.from(token.trim()))) {return true}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- the waiting set-up
|
||||
|
||||
export type PendingEnrolment = {
|
||||
/** sha256 of the browser cookie (sameBrowser). */
|
||||
browser: string
|
||||
createdAt: number
|
||||
expiresAt: number
|
||||
/** The secret the person scanned. Stored like the 2FA package stores a confirmed one; never sent anywhere. */
|
||||
secret: string
|
||||
/** sha256 of the link's token. */
|
||||
token: string
|
||||
}
|
||||
|
||||
type KV = { delete?: (key: string) => Promise<void>; get: (key: string) => Promise<unknown>; keys?: () => Promise<string[]>; set: (key: string, value: object) => Promise<void> }
|
||||
const memory = new Map<string, PendingEnrolment>()
|
||||
let warnedMemory = false
|
||||
|
||||
/** Key of an account's waiting set-up in `payload.kv`. */
|
||||
export const pendingEnrolmentKey = (collection: string, id: number | string) => `iapl:2fa-enrol:${collection}:${String(id)}`
|
||||
const sha256 = (value: string) => createHash('sha256').update(value).digest('hex')
|
||||
const sameHash = (a: string, b: string) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b))
|
||||
|
||||
const kvOf = (payload: BasePayload): KV | null => {
|
||||
const kv = (payload as { kv?: KV }).kv
|
||||
return kv && typeof kv.get === 'function' && typeof kv.set === 'function' ? kv : null
|
||||
}
|
||||
|
||||
export async function readPendingEnrolment(payload: BasePayload, collection: string, id: number | string, now = Date.now()): Promise<null | PendingEnrolment> {
|
||||
const key = pendingEnrolmentKey(collection, id)
|
||||
const kv = kvOf(payload)
|
||||
let entry: unknown = memory.get(key) ?? null
|
||||
if (kv) {
|
||||
try {
|
||||
entry = await kv.get(key)
|
||||
} catch {
|
||||
// the memory copy, if any
|
||||
}
|
||||
}
|
||||
const p = entry as null | PendingEnrolment
|
||||
if (!p || typeof p.secret !== 'string' || typeof p.token !== 'string' || typeof p.expiresAt !== 'number') {return null}
|
||||
return p.expiresAt > now ? p : null
|
||||
}
|
||||
|
||||
async function writePending(payload: BasePayload, key: string, value: null | PendingEnrolment): Promise<void> {
|
||||
if (value) {memory.set(key, value)} else {memory.delete(key)}
|
||||
const kv = kvOf(payload)
|
||||
if (!kv) {
|
||||
if (!warnedMemory) {
|
||||
warnedMemory = true
|
||||
payload.logger.warn('[iapl] 2FA: payload-kv is not available; waiting set-ups are kept in this process only (several instances: a link may not work on another).')
|
||||
}
|
||||
return
|
||||
}
|
||||
try {
|
||||
if (value) {await kv.set(key, value)} else if (typeof kv.delete === 'function') {await kv.delete(key)} else {await kv.set(key, { removed: true })}
|
||||
} catch (err) {
|
||||
payload.logger.warn(`[iapl] 2FA: could not store a waiting set-up (${err instanceof Error ? err.message : String(err)}); kept in this process only.`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Ends an account's waiting set-up (a reset, a confirmed one). */
|
||||
export async function dropPendingEnrolment(payload: BasePayload, collection: string, id: number | string): Promise<void> {
|
||||
await writePending(payload, pendingEnrolmentKey(collection, id), null)
|
||||
}
|
||||
|
||||
/** How many accounts have a waiting set-up that has not expired (the doctor). Null when it cannot be told. */
|
||||
export async function countPendingEnrolments(payload: BasePayload, collection: string, now = Date.now()): Promise<null | number> {
|
||||
const kv = kvOf(payload)
|
||||
const prefix = `iapl:2fa-enrol:${collection}:`
|
||||
if (!kv || typeof kv.keys !== 'function') {return [...memory.entries()].filter(([k, v]) => k.startsWith(prefix) && v.expiresAt > now).length}
|
||||
try {
|
||||
const keys = (await kv.keys()).filter((k) => k.startsWith(prefix))
|
||||
let n = 0
|
||||
for (const key of keys) {
|
||||
const v = (await kv.get(key)) as null | Partial<PendingEnrolment>
|
||||
if (v && typeof v.expiresAt === 'number' && v.expiresAt > now && typeof v.secret === 'string') {n++}
|
||||
}
|
||||
return n
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- mail
|
||||
|
||||
type MailNoun = { email?: unknown; id?: unknown }
|
||||
type I18nLike = Parameters<typeof serverText>[0]
|
||||
|
||||
/** The language of mails sent without a request in hand: the panel's fallback language. */
|
||||
const fallbackI18n = (payload: BasePayload): I18nLike => ({ language: (payload.config.i18n as { fallbackLanguage?: string } | undefined)?.fallbackLanguage ?? 'en' }) as I18nLike
|
||||
|
||||
/** `[email protected]` → `j…@firma.pl` (the setup screen names where the link went without spelling it out). */
|
||||
export function maskAddress(address: string): string {
|
||||
const at = address.lastIndexOf('@')
|
||||
return at > 0 ? `${address[0]}…${address.slice(at)}` : '…'
|
||||
}
|
||||
|
||||
const escapeHtml = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||||
|
||||
/** Whether Payload has a real mail transport (its fallback only prints to the console). */
|
||||
export function mailConfigured(payload: BasePayload): boolean {
|
||||
const email = (payload as { email?: { name?: string } }).email
|
||||
return Boolean(email) && email?.name !== 'console'
|
||||
}
|
||||
|
||||
/** Sends one message; true when the transport took it. Never throws. */
|
||||
async function sendMail(payload: BasePayload, message: { html: string; subject: string; text: string; to: string }, kind: 'account' | 'security-alert'): Promise<boolean> {
|
||||
if (!mailConfigured(payload)) {return false}
|
||||
try {
|
||||
const result = (await payload.sendEmail(withMailKind(message, kind) as never)) as { sent?: boolean } | null | undefined
|
||||
return !(result && typeof result === 'object' && result.sent === false)
|
||||
} catch (err) {
|
||||
payload.logger.warn(`[iapl] 2FA: a mail to an account could not be sent (${err instanceof Error ? err.message : String(err)}).`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
const paragraph = (s: string) => `<p>${escapeHtml(s)}</p>`
|
||||
|
||||
/** A notice to the account: two-step verification was turned on, changed, or removed / reset. */
|
||||
export async function sendTwoFactorNotice(payload: BasePayload, account: MailNoun, change: 'changed' | 'off' | 'on', by?: string): Promise<boolean> {
|
||||
if (typeof account.email !== 'string' || !account.email) {return false}
|
||||
const i18n = fallbackI18n(payload)
|
||||
const t = (key: AdminTextKey, vars?: Record<string, unknown>) => serverText(i18n, key, vars)
|
||||
const subject = t(change === 'on' ? 'twoFactorMailOnSubject' : change === 'off' ? 'twoFactorMailOffSubject' : 'twoFactorMailChangedSubject')
|
||||
const when = new Date().toISOString().replace('T', ' ').slice(0, 16) + ' UTC'
|
||||
const lines = [
|
||||
t(change === 'on' ? 'twoFactorMailOnBody' : change === 'off' ? 'twoFactorMailOffBody' : 'twoFactorMailChangedBody', { when }),
|
||||
...(by ? [t('twoFactorMailBy', { by })] : []),
|
||||
t('twoFactorMailNotYou'),
|
||||
]
|
||||
const sent = await sendMail(payload, { html: lines.map(paragraph).join(''), subject, text: lines.join('\n\n'), to: account.email }, 'security-alert')
|
||||
if (!sent) {payload.logger.warn(`[iapl] 2FA: the notice "${change}" for ${account.email} was not sent (no working mail).`)}
|
||||
return sent
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- the set-up request
|
||||
|
||||
type SetupUser = { collection?: unknown; email?: unknown; id?: number | string }
|
||||
|
||||
/** What the plugin passes to the setup handler. */
|
||||
export type EnrolmentContext = {
|
||||
collection: string
|
||||
options: ResolvedConfirmByEmail
|
||||
/** The 2FA package's TOTP options (`totp: { algorithm, digits, period }`). */
|
||||
totp?: TotpParams
|
||||
}
|
||||
|
||||
const json = (body: Record<string, unknown>, status = 200, headers: Record<string, string> = {}) =>
|
||||
Response.json(body, { headers: { 'Cache-Control': 'no-store', ...headers }, status })
|
||||
|
||||
const secureRequest = (req: PayloadRequest) => (req.headers.get('x-forwarded-proto') ?? new URL(req.url ?? 'http://localhost').protocol.replace(':', '')) === 'https'
|
||||
|
||||
/** `<serverURL><api>/iapl/two-factor/confirm?u=…&t=…` — only from the configured serverURL, never from the request's Host. */
|
||||
function confirmLink(payload: BasePayload, id: number | string, token: string): null | string {
|
||||
const server = (payload.config.serverURL ?? '').replace(/\/+$/, '')
|
||||
if (!/^https?:\/\//i.test(server)) {return null}
|
||||
const api = payload.config.routes?.api ?? '/api'
|
||||
return `${server}${api}${ENROL_CONFIRM_PATH}?u=${encodeURIComponent(String(id))}&t=${encodeURIComponent(token)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST /api/setup-totp` for an account WITHOUT a factor, when confirmByEmail is on: checks the code like the 2FA
|
||||
* package, keeps the secret aside and mails the link. Answers `{ ok: false, pending: true, message }` (status 202):
|
||||
* the package's setup form shows the message and stays on the screen.
|
||||
*/
|
||||
export async function startEnrolment(req: PayloadRequest, ctx: EnrolmentContext): Promise<Response> {
|
||||
const user = req.user as null | SetupUser
|
||||
const i18n = req.i18n as I18nLike
|
||||
if (!user?.id) {return json({ message: 'Not allowed.', ok: false }, 403)}
|
||||
let body: unknown
|
||||
try {
|
||||
body = await req.json?.()
|
||||
} catch {
|
||||
body = undefined
|
||||
}
|
||||
const secret = typeof (body as { secret?: unknown })?.secret === 'string' ? (body as { secret: string }).secret.trim() : ''
|
||||
const token = typeof (body as { token?: unknown })?.token === 'string' ? (body as { token: string }).token : ''
|
||||
if (!secret || !token) {return json({ message: serverText(i18n, 'twoFactorResetFailed'), ok: false }, 400)}
|
||||
if (!verifyTotpCode(secret, token, ctx.totp)) {
|
||||
return json({ message: String(req.i18n?.t?.('totpPlugin:setup:incorrectCode' as never) ?? 'The code is not right.'), ok: false }, 400)
|
||||
}
|
||||
// Each attempt sends a mail: at most `maxMailsPerHour` per account (not per address: the attacker has the password).
|
||||
const limit = await consumeRateLimit({ key: `${ctx.collection}:${String(user.id)}`, max: ctx.options.maxMailsPerHour, scope: 'iapl-2fa-enrol', windowMs: 3_600_000 })
|
||||
if (!limit.ok) {
|
||||
return json({ message: serverText(i18n, 'twoFactorEnrolTooMany', { minutes: Math.ceil(limit.retryAfter / 60) }), ok: false }, 429, { 'Retry-After': String(limit.retryAfter) })
|
||||
}
|
||||
|
||||
const linkToken = randomBytes(32).toString('base64url')
|
||||
const browser = randomBytes(32).toString('base64url')
|
||||
const now = Date.now()
|
||||
const pending: PendingEnrolment = { browser: sha256(browser), createdAt: now, expiresAt: now + ctx.options.linkMinutes * 60_000, secret, token: sha256(linkToken) }
|
||||
// A newer set-up replaces a waiting one: its link stops working.
|
||||
await writePending(req.payload, pendingEnrolmentKey(ctx.collection, user.id), pending)
|
||||
|
||||
const address = typeof user.email === 'string' ? user.email : ''
|
||||
const link = confirmLink(req.payload, user.id, linkToken)
|
||||
const t = (key: AdminTextKey, vars?: Record<string, unknown>) => serverText(i18n, key, vars)
|
||||
let sent = false
|
||||
if (address && link) {
|
||||
const ip = req.headers.get('x-forwarded-for')?.split(',').pop()?.trim() || req.headers.get('x-real-ip') || ''
|
||||
const agent = (req.headers.get('user-agent') ?? '').slice(0, 160)
|
||||
const lines = [
|
||||
t('twoFactorMailEnrolBody', { minutes: ctx.options.linkMinutes }),
|
||||
t('twoFactorMailEnrolFrom', { agent: agent || '?', ip: ip || '?' }),
|
||||
t('twoFactorMailEnrolNotYou'),
|
||||
]
|
||||
sent = await sendMail(
|
||||
req.payload,
|
||||
{
|
||||
html: `${paragraph(lines[0])}<p><a href="${escapeHtml(link)}">${escapeHtml(t('twoFactorMailEnrolButton'))}</a></p>${lines.slice(1).map(paragraph).join('')}`,
|
||||
subject: t('twoFactorMailEnrolSubject'),
|
||||
text: `${lines[0]}\n\n${link}\n\n${lines.slice(1).join('\n\n')}`,
|
||||
to: address,
|
||||
},
|
||||
'account',
|
||||
)
|
||||
}
|
||||
if (!sent && link && ctx.options.logLinkWhenMailFails) {
|
||||
// For the team that runs the site (Coolify → Logs). Single use, short-lived, and with sameBrowser it works only
|
||||
// in the browser that started the set-up.
|
||||
req.payload.logger.warn(`[iapl] 2FA: the confirmation e-mail for ${address || String(user.id)} could not be sent (no working mail). Link (valid ${ctx.options.linkMinutes} min, single use): ${link}`)
|
||||
} else if (!link) {
|
||||
req.payload.logger.warn('[iapl] 2FA: no serverURL in the Payload config, so no confirmation link can be made (a link from the request\'s Host could point anywhere). Set serverURL (NEXT_PUBLIC_SERVER_URL).')
|
||||
}
|
||||
|
||||
const cookie = `${req.payload.config.cookiePrefix || 'payload'}-${ENROL_COOKIE_SUFFIX}=${browser}; Path=/; Max-Age=${ctx.options.linkMinutes * 60}; HttpOnly; SameSite=Lax${secureRequest(req) ? '; Secure' : ''}`
|
||||
const message = sent
|
||||
? t('twoFactorEnrolSent', { email: maskAddress(address), minutes: ctx.options.linkMinutes })
|
||||
: t(ctx.options.adminConfirm ? 'twoFactorEnrolMailFailed' : 'twoFactorEnrolMailFailedNoAdmin')
|
||||
return json({ mailed: sent, message, ok: false, pending: true }, 202, { 'Set-Cookie': cookie })
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- confirming
|
||||
|
||||
const page = (lang: string, title: string, body: string, status = 200) =>
|
||||
new Response(
|
||||
`<!doctype html><html lang="${lang === 'pl' ? 'pl' : 'en'}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>${escapeHtml(title)}</title>` +
|
||||
'<style>body{font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:10vh auto;padding:0 1rem;color:#171717;background:#fff}button,a.b{font:inherit;padding:.6rem 1.2rem;border-radius:6px;border:0;background:#171717;color:#fff;cursor:pointer;text-decoration:none;display:inline-block}@media (prefers-color-scheme:dark){body{background:#171717;color:#f5f5f5}button,a.b{background:#f5f5f5;color:#171717}}</style>' +
|
||||
`</head><body><h1>${escapeHtml(title)}</h1>${body}</body></html>`,
|
||||
{
|
||||
headers: {
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
|
||||
'Content-Type': 'text/html; charset=utf-8',
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
'X-Robots-Tag': 'noindex, nofollow',
|
||||
},
|
||||
status,
|
||||
},
|
||||
)
|
||||
|
||||
const languageOf = (req: PayloadRequest) => ((req.i18n as { language?: string } | undefined)?.language === 'pl' ? 'pl' : 'en')
|
||||
|
||||
function cookieValue(req: PayloadRequest, name: string): string {
|
||||
for (const part of (req.headers.get('cookie') ?? '').split(';')) {
|
||||
const i = part.indexOf('=')
|
||||
if (i > 0 && part.slice(0, i).trim() === name) {return part.slice(i + 1).trim()}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/** Writes the waiting secret: the confirmed enrolment. Ends every session; signs nobody in. */
|
||||
async function activate(req: PayloadRequest, collection: string, id: number | string, pending: PendingEnrolment, by?: string): Promise<boolean> {
|
||||
const useSessions = (req.payload.collections as Record<string, { config?: { auth?: { useSessions?: boolean } } }>)[collection]?.config?.auth?.useSessions !== false
|
||||
try {
|
||||
const current = (await req.payload.findByID({ id, collection: collection as never, depth: 0, overrideAccess: true, select: { totpSecret: true } as never, showHiddenFields: true })) as { totpSecret?: null | string }
|
||||
if (current.totpSecret) {return false} // set up in the meantime: nothing to confirm
|
||||
await req.payload.update({
|
||||
id,
|
||||
collection: collection as never,
|
||||
context: { [ENROL_CONFIRMED_CONTEXT]: by ?? true },
|
||||
data: { totpSecret: pending.secret, ...(useSessions ? { sessions: [] } : {}) } as never,
|
||||
overrideAccess: true,
|
||||
req,
|
||||
})
|
||||
} catch (err) {
|
||||
req.payload.logger.error(`[iapl] 2FA: confirming a set-up failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
return false
|
||||
}
|
||||
await dropPendingEnrolment(req.payload, collection, id)
|
||||
return true
|
||||
}
|
||||
|
||||
export type EnrolmentEndpointsOptions = {
|
||||
collection: string
|
||||
options: ResolvedConfirmByEmail
|
||||
/** The `twoFactor.sameOrigin` rule (the confirm POST and the admin action refuse other origins). */
|
||||
ownOrigin?: (req: PayloadRequest) => boolean
|
||||
/** Who may confirm another account's waiting set-up (default: like the 2FA reset — an admin who entered a code). */
|
||||
resetAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
|
||||
}
|
||||
|
||||
/** The link's page (GET), its button (POST), and the administrator's confirm (POST, JSON). */
|
||||
export function buildEnrolmentEndpoints({ collection, options, ownOrigin, resetAccess }: EnrolmentEndpointsOptions): Endpoint[] {
|
||||
const params = (req: PayloadRequest, form?: URLSearchParams) => {
|
||||
const url = new URL(req.url ?? 'http://localhost')
|
||||
const get = (k: string) => form?.get(k) ?? url.searchParams.get(k) ?? ''
|
||||
return { token: get('t'), userId: get('u') }
|
||||
}
|
||||
const invalid = (req: PayloadRequest, key: AdminTextKey = 'twoFactorEnrolInvalid', status = 400) => {
|
||||
const i18n = req.i18n as I18nLike
|
||||
return page(languageOf(req), serverText(i18n, 'twoFactorEnrolTitle'), paragraph(serverText(i18n, key)), status)
|
||||
}
|
||||
const endpoints: Endpoint[] = [
|
||||
{
|
||||
// Opening the link changes nothing (mail scanners open links): a page with one button.
|
||||
handler: async (req) => {
|
||||
const i18n = req.i18n as I18nLike
|
||||
const { token, userId } = params(req)
|
||||
if (!token || !userId) {return invalid(req)}
|
||||
const pending = await readPendingEnrolment(req.payload, collection, userId)
|
||||
if (!pending || !sameHash(pending.token, sha256(token))) {return invalid(req)}
|
||||
const action = `${req.payload.config.routes?.api ?? '/api'}${ENROL_CONFIRM_PATH}`
|
||||
return page(
|
||||
languageOf(req),
|
||||
serverText(i18n, 'twoFactorEnrolTitle'),
|
||||
paragraph(serverText(i18n, 'twoFactorEnrolLead')) +
|
||||
`<form method="post" action="${escapeHtml(action)}"><input type="hidden" name="u" value="${escapeHtml(userId)}"><input type="hidden" name="t" value="${escapeHtml(token)}"><button type="submit">${escapeHtml(serverText(i18n, 'twoFactorEnrolButton'))}</button></form>`,
|
||||
)
|
||||
},
|
||||
method: 'get',
|
||||
path: ENROL_CONFIRM_PATH,
|
||||
},
|
||||
{
|
||||
handler: async (req) => {
|
||||
const i18n = req.i18n as I18nLike
|
||||
if (ownOrigin && !ownOrigin(req)) {return invalid(req, 'twoFactorEnrolInvalid', 403)}
|
||||
let form: URLSearchParams
|
||||
try {
|
||||
form = new URLSearchParams((await req.text?.()) ?? '')
|
||||
} catch {
|
||||
return invalid(req)
|
||||
}
|
||||
const { token, userId } = params(req, form)
|
||||
if (!token || !userId) {return invalid(req)}
|
||||
const pending = await readPendingEnrolment(req.payload, collection, userId)
|
||||
if (!pending || !sameHash(pending.token, sha256(token))) {return invalid(req)}
|
||||
if (options.sameBrowser) {
|
||||
const browser = cookieValue(req, `${req.payload.config.cookiePrefix || 'payload'}-${ENROL_COOKIE_SUFFIX}`)
|
||||
if (!browser || !sameHash(pending.browser, sha256(browser))) {return invalid(req, 'twoFactorEnrolOtherBrowser', 403)}
|
||||
}
|
||||
if (!(await activate(req, collection, userId, pending))) {return invalid(req)}
|
||||
const admin = `${req.payload.config.routes?.admin ?? '/admin'}/login`
|
||||
const res = page(
|
||||
languageOf(req),
|
||||
serverText(i18n, 'twoFactorEnrolTitle'),
|
||||
paragraph(serverText(i18n, 'twoFactorEnrolDone')) + `<p><a class="b" href="${escapeHtml(admin)}">${escapeHtml(serverText(i18n, 'twoFactorEnrolSignIn'))}</a></p>`,
|
||||
)
|
||||
res.headers.append('Set-Cookie', `${req.payload.config.cookiePrefix || 'payload'}-${ENROL_COOKIE_SUFFIX}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax`)
|
||||
return res
|
||||
},
|
||||
method: 'post',
|
||||
path: ENROL_CONFIRM_PATH,
|
||||
},
|
||||
]
|
||||
if (options.adminConfirm) {
|
||||
endpoints.push({
|
||||
handler: async (req) => {
|
||||
const i18n = req.i18n as I18nLike
|
||||
const allowed =
|
||||
Boolean(req.user) &&
|
||||
secondFactorPassed(req) &&
|
||||
(req.user as { collection?: unknown }).collection === collection &&
|
||||
(resetAccess ? (await resetAccess({ req })) === true : (req.user as { _strategy?: unknown })._strategy === 'totp' && userMeetsRole(req, 'admin'))
|
||||
if (!allowed) {return json({ message: serverText(i18n, 'twoFactorResetForbidden'), ok: false }, 403)}
|
||||
if (ownOrigin && !ownOrigin(req)) {return json({ message: 'Not allowed from this origin.', ok: false }, 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') || String(userId) === String((req.user as { id?: unknown }).id)) {
|
||||
return json({ message: serverText(i18n, 'twoFactorConfirmPendingNone'), ok: false }, 400)
|
||||
}
|
||||
const pending = await readPendingEnrolment(req.payload, collection, userId)
|
||||
if (!pending) {return json({ message: serverText(i18n, 'twoFactorConfirmPendingNone'), ok: false }, 404)}
|
||||
const actor = (req.user as { email?: string; id?: unknown }).email ?? String((req.user as { id?: unknown }).id)
|
||||
if (!(await activate(req, collection, userId, pending, actor))) {return json({ message: serverText(i18n, 'twoFactorConfirmPendingNone'), ok: false }, 409)}
|
||||
req.payload.logger.info(`[iapl] 2FA: ${actor} confirmed the waiting set-up of ${collection} ${String(userId)}.`)
|
||||
return json({ message: serverText(i18n, 'twoFactorConfirmPendingDone'), ok: true })
|
||||
},
|
||||
method: 'post',
|
||||
path: ENROL_ADMIN_CONFIRM_PATH,
|
||||
})
|
||||
}
|
||||
return endpoints
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- notices
|
||||
|
||||
const CHANGE = 'iaplTotpChange'
|
||||
|
||||
/**
|
||||
* beforeChange + afterChange on the 2FA collection: a notice to the account whenever its factor is turned on,
|
||||
* changed or removed — through any path (setup, the package's remove / admin endpoints, IAPL's reset, the Local API).
|
||||
* A removal also ends a waiting set-up.
|
||||
*/
|
||||
export function buildTotpNoticeHooks(collection: string, { notices }: Pick<ResolvedConfirmByEmail, 'notices'>): { afterChange: CollectionAfterChangeHook; beforeChange: CollectionBeforeChangeHook } {
|
||||
return {
|
||||
afterChange: async ({ context, doc, req }) => {
|
||||
const change = context?.[CHANGE] as 'changed' | 'off' | 'on' | undefined
|
||||
if (!change || !doc) {return doc}
|
||||
if (change === 'off') {await dropPendingEnrolment(req.payload, collection, (doc as { id: number | string }).id)}
|
||||
if (!notices) {return doc}
|
||||
const actor = req.user && String((req.user as { id?: unknown }).id) !== String((doc as { id?: unknown }).id) ? ((req.user as { email?: string }).email ?? undefined) : undefined
|
||||
const by = typeof context?.[ENROL_CONFIRMED_CONTEXT] === 'string' ? (context[ENROL_CONFIRMED_CONTEXT]) : actor
|
||||
const send = () => sendTwoFactorNotice(req.payload, doc as MailNoun, change, by).then(() => undefined)
|
||||
if (!afterCommit(req, send)) {void send()}
|
||||
return doc
|
||||
},
|
||||
beforeChange: ({ context, data, operation, originalDoc }) => {
|
||||
if (!data || operation !== 'update' || !('totpSecret' in data)) {return data}
|
||||
const before = Boolean((originalDoc as { totpSecret?: unknown } | undefined)?.totpSecret)
|
||||
const after = Boolean(data.totpSecret)
|
||||
const change = !before && after ? 'on' : before && !after ? 'off' : before && after && data.totpSecret !== (originalDoc as { totpSecret?: unknown }).totpSecret ? 'changed' : null
|
||||
if (change && context) {context[CHANGE] = change}
|
||||
return data
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** For the setup screen and the account page: the waiting set-up of this account (when it started), or null. */
|
||||
export async function pendingEnrolmentInfo(payload: BasePayload, collection: string, id: number | string): Promise<{ createdAt: Date; expiresAt: Date } | null> {
|
||||
const p = await readPendingEnrolment(payload, collection, id)
|
||||
return p ? { createdAt: new Date(p.createdAt), expiresAt: new Date(p.expiresAt) } : null
|
||||
}
|
||||
@@ -377,6 +377,11 @@ type EndpointLike = { handler: (req: never) => Promise<Response> | Response; pat
|
||||
* so a password alone cannot reset or remove TOTP.
|
||||
*/
|
||||
export type TotpEndpointGuards = {
|
||||
/**
|
||||
* `/setup-totp` for an account WITHOUT a factor: when set, this answers instead of the package (the enrolment
|
||||
* waits for an e-mail confirmation, enrolmentConfirm.ts) — the package never writes the secret or its cookie.
|
||||
*/
|
||||
enrol?: (req: never) => Promise<Response> | Response
|
||||
/**
|
||||
* Called for a verify attempt of a logged-in account before the package sees
|
||||
* it. Return a Response to refuse (too many attempts), null to let it through.
|
||||
@@ -414,6 +419,11 @@ export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collectio
|
||||
if (user && (endpoint.path === '/verify-totp' || endpoint.path === '/setup-totp') && guards.ownOrigin && !guards.ownOrigin(req as never)) {
|
||||
return Response.json({ message: 'Not allowed from this origin.', ok: false }, { status: 403 })
|
||||
}
|
||||
// The first enrolment waits for the e-mail link (twoFactor.confirmByEmail): the package's handler is not called,
|
||||
// so it neither stores the secret nor sets its `-totp` cookie (which would turn valid once any secret is confirmed).
|
||||
if (user && endpoint.path === '/setup-totp' && guards.enrol && ['exempt', 'open'].includes(twoFactorSetupState(req))) {
|
||||
return guards.enrol(req as never)
|
||||
}
|
||||
// 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)
|
||||
|
||||
Reference in New Issue
Block a user