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:
co-authored by
Claude Fable 5.2
parent
45d52c4690
commit
2aaaaa115a
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user