diff --git a/.changeset/plugin-auth-locked-account-every-sign-in-door.md b/.changeset/plugin-auth-locked-account-every-sign-in-door.md new file mode 100644 index 00000000000..dc34f732152 --- /dev/null +++ b/.changeset/plugin-auth-locked-account-every-sign-in-door.md @@ -0,0 +1,18 @@ +--- +'@objectstack/plugin-auth': patch +'@objectstack/runtime': patch +--- + +fix(plugin-auth)!: a locked account is refused on every door that ends in a session for it + +Clause-②: no (narrowing) — while an account's lock holds (ADR-0069 D2, `lockoutThreshold` on), every door that ends in a session for that account refuses it with the answer password sign-in gives under the deployment's `lockoutRefusal`, and every password door counts its refused attempts toward that one lock and checks it before the password. No request, response or metadata shape is added, removed or re-shaped; an unlocked account, an expired lock and a deployment with the lockout off sign in exactly as before. +Metadata-protocol: none + + + +**BREAKING** sign-in narrowing for locked accounts (`@objectstack/plugin-auth`): a locked account is refused on every door that ends in a session for it, with the answer password sign-in gives. + +- **Now.** While the lock holds, every door that ends in a new session for the account issues none and answers as `POST /sign-in/email` does: `403 ACCOUNT_LOCKED` under `lockoutRefusal: 'explicit'`, `401 INVALID_EMAIL_OR_PASSWORD` otherwise. That is `POST /phone-number/verify`; `GET /magic-link/verify` (JSON and `callbackURL` lanes); `GET /verify-email` when it signs the caller in, an address-change confirmation opened without a session included; the second-factor step (`/two-factor/verify-totp`, `/two-factor/verify-otp`, `/two-factor/verify-backup-code`); sign-in through an identity provider (social and generic-OAuth callbacks and the ID-token sign-in, enterprise SSO over OIDC and SAML); and the device grant (`POST /device/token`). `POST /sign-in/phone-number` checks the lock before the password and answers a locked account the same whatever password it is sent: `403 ACCOUNT_LOCKED` under `'explicit'`, that door's own wrong-password answer (`401 INVALID_PHONE_NUMBER_OR_PASSWORD`) otherwise. Its wrong passwords count toward the account's one lock and a correct one resets the count, as at `/sign-in/email`. Each refused attempt writes its `login_failed` row with the reason `ACCOUNT_LOCKED`. Not sign-ins, and unchanged: an administrator's impersonation, a new session for the account whose live session of record made the request (enrolling a second factor, a password change that ends the other sessions), and the server's in-process principal session. A session for a locked account made any other way is refused. +- **Who moves.** A client that signs an account in through a one-time code, a sign-in link, an address-change confirmation without a session, the second-factor step, an identity provider, the device grant or the phone-number password door: while the account is locked it now receives the lockout refusal. That includes accounts with no password at all, which the lock now reaches on doors that never asked for one, and phone-number password failures now lock the account after `lockoutThreshold` attempts. An administrator clears a lock early with the **Unlock** action, as before. + +`@objectstack/runtime`: the dispatcher error-vocabulary ledger classifies the `INVALID_EMAIL_OR_PASSWORD` stamp in `@objectstack/plugin-auth` as better-auth's own vocabulary; no behaviour changes. diff --git a/content/docs/kernel/runtime-services/audit-service.mdx b/content/docs/kernel/runtime-services/audit-service.mdx index f8480f654ec..56fcf631d41 100644 --- a/content/docs/kernel/runtime-services/audit-service.mdx +++ b/content/docs/kernel/runtime-services/audit-service.mdx @@ -47,9 +47,12 @@ services.audit.recordAuthEvent(event: { - `login` / `logout` are **session events**: a sign-in that minted a session, and a sign-out. - `login_failed` / `account_locked` are **account events**: a refused sign-in — a - password sign-in that named an existing account, or any `/sign-in/*` request the IP - allow-list refused (ADR-0069 D5) — and the refused sign-in that stamped the account - lockout (`lockoutThreshold`, ADR-0069 D2). They exist without any session. + password sign-in (email or phone number) that named an existing account, a sign-in + the account lockout refused at any other door that ends in a session (a one-time + code, a sign-in link, the second-factor step, an identity provider's callback, the + device grant; `reason: 'ACCOUNT_LOCKED'`), or any `/sign-in/*` request the IP + allow-list refused (ADR-0069 D5) — and the refused password sign-in that stamped the + account lockout (`lockoutThreshold`, ADR-0069 D2). They exist without any session. - **`userId`** must be a real `sys_user` id when given — it lands on the strict `user_id` lookup. On an account event it is the account the sign-in named. Every event names one except a `login_failed` refused before any account could be resolved: the deployment's diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index 0ec63634653..639ecceefd2 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -633,6 +633,13 @@ credential check resolves the address to. So every refused sign-in on that accou counts toward its one lock, whichever spelling of the address it used. A lock refuses every sign-in that resolves to the account, the correct password included, and a successful sign-in under any spelling clears the counter. +Every password sign-in door (email and password, phone number and password) counts +toward that one lock and checks it before the password, and a locked account is +refused, with the answer password sign-in gives, on every door that ends in a session +for it: one-time codes, sign-in links, an address-change confirmation opened without a +session, the second-factor step, sign-in through an identity provider (social, generic +OAuth, enterprise SSO) and the device grant, so the lock also reaches an account that +has no password. Setting `lockout_threshold` to `0` disables the **password-stage** lockout only. Two-factor verification keeps a built-in limit of 10 attempts per 15 minutes, diff --git a/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts index 05e698a873c..75555575c32 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts @@ -43,7 +43,8 @@ import { codeSelfServiceRefusal } from './account-self-service-refusal-code.js'; import { BANNED_USER_CODE, causeBannedUserRefusal } from './banned-user-refusal-cause.js'; import type { AuthManager } from './auth-manager.js'; -import { refusalCodeOf, SIGN_IN_EMAIL_PATH } from './auth-session-audit.js'; +import { refusalCodeOf } from './auth-session-audit.js'; +import { passwordSignInDoorOf } from './auth-manager-sign-in-lockout.js'; import { narrowDirectoryForExternalCaller } from './external-directory-door.js'; import { SESSION_SCOPING_REFUSAL } from './organization-access-policy.js'; import { refuseIntrospectionForBannedSubject } from './oauth-token-read-ban-refusal.js'; @@ -235,6 +236,7 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) { if (ctx?.path === '/sso/register' || ctx?.path === '/sso/update-provider') await this.settleSsoSignOutOfIdp(ctx); // ── ADR-0069 D2: account lockout (counter) ────────────────── + // On every password door (`/sign-in/email`, `/sign-in/phone-number`). // better-auth catches an INVALID_EMAIL_OR_PASSWORD APIError and runs // the after-hook with it on `ctx.context.returned`; a success leaves // the session payload there. The gate stamped this attempt as a @@ -243,8 +245,9 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) { // names is neither: the password passed and a policy then refused the // sign-in, so the stamp is handed back and the counter is left as it // stood. Its `login_failed` row is still written below. - if (ctx?.path === SIGN_IN_EMAIL_PATH) { - const email = typeof ctx?.body?.email === 'string' ? ctx.body.email : ''; + const passwordDoor = passwordSignInDoorOf(ctx); + if (passwordDoor) { + const { door, identifier: email } = passwordDoor; if (email) { let succeeded = true; try { @@ -260,14 +263,17 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) { : await refusedAfterTheCredential(ctx?.context?.returned) ? 'refused-after-credential' : 'refused', + door, ); // A refused sign-in writes `login_failed`, and the one that // stamped the lockout also writes `account_locked`. A successful // one is recorded as `login` by the session hook, unchanged. A // sign-in refused because the account is locked had its row // written by the gate, with the lock as its reason. - if (!succeeded && !settlement.refusedByLock) await this.auditRefusedSignIn(ctx, email, settlement); - if (succeeded) { + if (!succeeded && !settlement.refusedByLock) await this.auditRefusedSignIn(ctx, email, settlement, door); + // The session controls and the last-login stamp below are the email + // door's, as before. + if (succeeded && door === 'email') { const uid = ctx?.context?.returned?.user?.id; // [ADR-0069 TL;DR 6] The cap of the organization the new session // was scoped to at creation (ADR-0093 D9), never above the @@ -297,9 +303,12 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) { // `details.cause: 'scim_deactivated'`; an administrator's ban is // answered as before. See `banned-user-refusal-cause.ts`. It throws // on a match, so it stays after the settlement and the refusal's - // `login_failed` row above. - await causeBannedUserRefusal(ctx); - return; + // `login_failed` row above. The phone door goes on to the hooks below, + // as before. + if (door === 'email') { + await causeBannedUserRefusal(ctx); + return; + } } // ── ADR-0069 D1: on a successful change/reset — stamp diff --git a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts index 169dbb80e0f..63354f85784 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts @@ -20,8 +20,8 @@ * the same cloud-as-IdP authorization gate, the same break-glass * last-local-credential refusal, the same audience posture and uniqueness * refusal on password sign-up, the same cloud-managed invite-member refusal, - * the same account lockout gate, and the same first-user `disableSignUp` flip - * — in the same order. + * the same account lockout gate (on every password door), and the same + * first-user `disableSignUp` flip — in the same order. * * ## How the moved body reaches the class * @@ -62,7 +62,7 @@ import { isCloudManaged } from '@objectstack/core'; import { VENDOR_ROLE_SCALAR_ADMIN_PATHS } from './admin-impersonate-endpoint.js'; import { setAuthActorResolver } from './auth-actor-attribution.js'; import { AuthManager } from './auth-manager.js'; -import { SIGN_IN_EMAIL_PATH } from './auth-session-audit.js'; +import { passwordSignInDoorOf, recordLockoutRequest } from './auth-manager-sign-in-lockout.js'; import { CLOUD_MANAGED_REFUSAL_CODE, CLOUD_MANAGED_REFUSAL_MESSAGES } from './cloud-managed.js'; import { isLastLocalCredentialHolder, @@ -214,6 +214,16 @@ export async function globalBeforeHook( // states the rule and how each credential is read. await refuseRequestNamingDifferentAccounts(ctx); + // ── ADR-0069 D2: what this request is, for the lock at session creation ── + // Its path, and the session of record it presents, read from the store + // before the endpoint runs (and before it can replace that row), so the + // lock's refusal at session creation tells a sign-in from a new session for + // an account the caller is already signed in as by the session of record, + // never by the request's own view of it, and judges the same request where + // the endpoint context does not reach the database hooks. Lockout on only; + // see `auth-manager-sign-in-lockout.ts`. + await recordLockoutRequest.call(this, ctx); + // ── [#33203] Cloud-managed: no reset door sets a local password ── // A hosted environment sets no local password for anyone, a platform // administrator included (ruling 10 of cloud#4465, `cloud-managed.ts`). @@ -856,17 +866,18 @@ export async function globalBeforeHook( }); // ── ADR-0069 D2: account lockout (gate) ───────────────────── + // On every password door (`/sign-in/email`, `/sign-in/phone-number`), // BEFORE better-auth checks the password: the attempt is stamped as a // failure (settled by the after-hook once the check answers), and a // locked identity is refused — a lock must hold even against the - // correct password. The refusal is the one a wrong password gets, made - // by better-auth's own credential check (`sign-in-lockout-refusal.ts`), - // unless the deployment opted into `403 ACCOUNT_LOCKED`. It is a - // refused sign-in, so it writes its `login_failed` row - // (`auth-session-audit.ts`, account events). - if (ctx?.path === SIGN_IN_EMAIL_PATH) { - const email = typeof ctx?.body?.email === 'string' ? ctx.body.email : ''; - if (email) await this.admitSignInAttempt(email, ctx); + // correct password. The refusal is the one a wrong password gets at that + // door, made by better-auth's own credential check + // (`sign-in-lockout-refusal.ts`), unless the deployment opted into `403 + // ACCOUNT_LOCKED`. It is a refused sign-in, so it writes its + // `login_failed` row (`auth-session-audit.ts`, account events). + const passwordDoor = passwordSignInDoorOf(ctx); + if (passwordDoor) { + if (passwordDoor.identifier) await this.admitSignInAttempt(passwordDoor.identifier, ctx, passwordDoor.door); return; } diff --git a/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts b/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts index d1a4ae5b605..3dc563d6cf0 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts @@ -64,6 +64,7 @@ import { readRequestClientAddress } from './request-client-address.js'; import { SESSION_SCOPING_REFUSAL } from './organization-access-policy.js'; import { readSessionUserRow, refuseAgentAccountCredential } from './service-account-identity.js'; import { refuseInactiveUserSession, SESSION_ADMISSION_ROW_FIELDS } from './user-session-admission.js'; +import { LOCKED_ACCOUNT_ROW_FIELDS, refuseLockedAccountSession } from './auth-manager-sign-in-lockout.js'; import { PLATFORM_IDP_PROVIDER_ID } from './implicit-account-linking.js'; import { PENDING_SSO_SOURCE } from './pending-sso-marker.js'; @@ -362,17 +363,22 @@ export function composeDatabaseHooks( // before the host's hook and every step below, so no sign-in method, // impersonation or minted session gets a session for one, whatever runs // after it. See service-account-identity.ts. + const SESSION_USER_ROW_FIELDS = [...SESSION_ADMISSION_ROW_FIELDS, ...LOCKED_ACCOUNT_ROW_FIELDS]; const sessionBefore = async (session: any, ctx: any) => { // [#33181] The same one read of the row carries the columns the next // refusal judges: a pending person holds no session but the platform // sign-in's, and a ban holds on a kernel without the vendor admin plugin // (whose own hook enforces it where it is mounted). See // user-session-admission.ts. - const userRow = await readSessionUserRow(this.config.dataEngine, session, SESSION_ADMISSION_ROW_FIELDS); + const userRow = await readSessionUserRow(this.config.dataEngine, session, SESSION_USER_ROW_FIELDS); await refuseInactiveUserSession(this.config.dataEngine, session, { row: userRow, enforceBan: async () => !(await this.isAdminPluginMounted()), }); + // ADR-0069 D2: a locked account is refused on every door that ends in a + // session for that account, with the answer password sign-in gives. See + // auth-manager-sign-in-lockout.ts. + await refuseLockedAccountSession.call(this, session, ctx, userRow); const captured = await captureSessionAddress(session); const result = sessionActiveOrgBefore ? await sessionActiveOrgBefore(captured, ctx) : undefined; if (result === false) return false; diff --git a/packages/plugins/plugin-auth/src/auth-manager-sign-in-lockout.ts b/packages/plugins/plugin-auth/src/auth-manager-sign-in-lockout.ts index edbcb61a155..313e1e99bab 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-sign-in-lockout.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-sign-in-lockout.ts @@ -25,6 +25,12 @@ * - a completed password reset clears the counter and the lock * ({@link clearSignInLockout}). * + * The gate and the counter hold every password door — `/sign-in/email` and + * `/sign-in/phone-number` ({@link passwordSignInDoorOf}), each naming the + * account its own credential check names — and a locked account is refused on + * every other door that ends in a session for it, at session creation + * ({@link refuseLockedAccountSession}). + * * ## How the moved bodies reach the class * * The shape #23050 set for `rest-server.ts` (its `data-action-routes.ts` @@ -61,8 +67,13 @@ import { } from './auth-session-audit.js'; import { canonicalClientAddress } from './client-address-canonical.js'; import { readRequestClientAddress } from './request-client-address.js'; +import { PRINCIPAL_SESSION_TOKEN_PREFIX } from './principal-session-mint.js'; +import { IMPERSONATE_USER_PATH } from './impersonation-bearer-rotation.js'; import { + lockedAccountRefusal, + readLockoutRequestState, readSignInAttempt, + recordLockoutRequestState, recordSignInAttempt, type SignInAttempt, type SignInLockStamp, @@ -96,6 +107,67 @@ const LOCKOUT_SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] }; */ const RESERVATION_ROUNDS = 32; +/** + * A password door the lock gate and the counter hold: `/sign-in/email`, whose + * identifier is the address, and `/sign-in/phone-number`, whose identifier is + * the phone number. Every password door counts its refused attempts toward + * the one lock and checks that lock before its credential (ADR-0069 D2). + */ +export type PasswordSignInDoor = 'email' | 'phone'; + +/** better-auth's phone-number password door. */ +export const SIGN_IN_PHONE_NUMBER_PATH = '/sign-in/phone-number'; + +/** Each password door's path, as its account events record it. */ +const PASSWORD_DOOR_PATHS: Readonly> = Object.freeze({ + email: SIGN_IN_EMAIL_PATH, + phone: SIGN_IN_PHONE_NUMBER_PATH, +}); + +/** + * The password door this request is, with the identifier its body carries + * (`''` when it carries none), or `undefined` for any other path. + */ +export function passwordSignInDoorOf(ctx: any): { door: PasswordSignInDoor; identifier: string } | undefined { + if (ctx?.path === SIGN_IN_EMAIL_PATH) { + return { door: 'email', identifier: typeof ctx?.body?.email === 'string' ? ctx.body.email : '' }; + } + if (ctx?.path === SIGN_IN_PHONE_NUMBER_PATH) { + return { door: 'phone', identifier: typeof ctx?.body?.phoneNumber === 'string' ? ctx.body.phoneNumber : '' }; + } + return undefined; +} + +/** + * The account `/sign-in/phone-number`'s credential check names: the + * `sys_user` row whose `phone_number` equals the number exactly, as better-auth + * looks it up (1.7.12 `plugins/phone-number/routes.mjs`, an equality match on + * the number the body carries), with `fields` (plus `id`). + */ +export async function findPhoneSignInAccount( + engine: IDataEngine, + phoneNumber: string, + fields: readonly string[], +): Promise<({ id: string } & Record) | undefined> { + const query: EngineQueryOptions = { + where: { phone_number: phoneNumber }, + fields: ['id', ...fields], + context: { isSystem: true, positions: [], permissions: [] }, + }; + const row = await engine.findOne('sys_user', query); + return row && typeof row.id === 'string' && row.id + ? (row as { id: string } & Record) + : undefined; +} + +/** The account question of `door`: the manager's own for the address, the phone number's for the phone door. */ +function accountFinderFor( + host: Pick, + door: PasswordSignInDoor, +): SignInLockoutHost['findSignInAccount'] { + return door === 'phone' ? findPhoneSignInAccount : host.findSignInAccount; +} + /** Whether a stored `locked_until` is still in the future at `now` (epoch ms). */ function lockHolds(lockedUntil: unknown, now: number): boolean { if (lockedUntil === null || lockedUntil === undefined || lockedUntil === '') return false; @@ -218,6 +290,7 @@ export async function admitSignInAttempt( this: Pick, email: string, ctx?: any, + door: PasswordSignInDoor = 'email', ): Promise { const threshold = Number(this.config.lockoutThreshold) || 0; const engine = threshold > 0 ? this.getDataEngine() : undefined; @@ -230,7 +303,7 @@ export async function admitSignInAttempt( try { attempt = await reserveSignInAttempt( engine, - this.findSignInAccount, + accountFinderFor(this, door), email, threshold, Number(this.config.lockoutDurationMinutes) || 15, @@ -263,7 +336,7 @@ export async function admitSignInAttempt( await emitAuthSessionAuditEvent( this.config.getAuditSink?.(), signInFailureEventFor(attempt.userId, { - path: SIGN_IN_EMAIL_PATH, + path: PASSWORD_DOOR_PATHS[door], reason: 'ACCOUNT_LOCKED', fingerprint: signInClientFingerprint(ctx, await readRequestClientAddress()), }), @@ -289,13 +362,7 @@ export async function admitSignInAttempt( { object: 'sys_user', threshold }, ); } - const { APIError } = await import('better-auth/api'); - throw new APIError('FORBIDDEN', { - message: - 'This account is temporarily locked after too many failed sign-in ' + - 'attempts. Try again later or ask an administrator to unlock it.', - code: 'ACCOUNT_LOCKED', - }); + throw await lockedAccountRefusal('explicit'); } /** How a `/sign-in/email` ended, as the after-hook judged it. */ @@ -325,6 +392,7 @@ export async function settleSignInAttempt( this: Pick, email: string, outcome: SignInOutcome, + door: PasswordSignInDoor = 'email', ): Promise { const recorded = await readSignInAttempt(); // A verdict recorded for another identifier belongs to another call. @@ -343,7 +411,7 @@ export async function settleSignInAttempt( if (outcome === 'succeeded') { try { - const u = await this.findSignInAccount(engine, email, ['failed_login_count', 'locked_until']); + const u = await accountFinderFor(this, door)(engine, email, ['failed_login_count', 'locked_until']); if (u && ((Number(u.failed_login_count) || 0) !== 0 || u.locked_until)) await writeLockoutCleared(engine, u.id); } catch (e) { this.logDurabilityDegradation( @@ -438,17 +506,18 @@ export async function auditRefusedSignIn( ctx: any, email: string, settlement: SignInSettlement, + door: PasswordSignInDoor = 'email', ): Promise { const sink = this.config.getAuditSink?.(); if (!sink) return; const lockStamped = settlement.lockStamped; - const userId = lockStamped?.userId ?? settlement.userId ?? (await this.resolveSignInAccountId(email)); + const userId = lockStamped?.userId ?? settlement.userId ?? (await this.resolveSignInAccountId(email, door)); if (!userId) return; const fingerprint = signInClientFingerprint(ctx, await readRequestClientAddress()); await emitAuthSessionAuditEvent( sink, signInFailureEventFor(userId, { - path: SIGN_IN_EMAIL_PATH, + path: PASSWORD_DOOR_PATHS[door], reason: refusalCodeOf(ctx?.context?.returned), fingerprint, }), @@ -457,7 +526,7 @@ export async function auditRefusedSignIn( await emitAuthSessionAuditEvent( sink, accountLockedEventFor(lockStamped.userId, { - path: SIGN_IN_EMAIL_PATH, + path: PASSWORD_DOOR_PATHS[door], lockedUntil: lockStamped.lockedUntil, threshold: lockStamped.threshold, fingerprint, @@ -467,11 +536,15 @@ export async function auditRefusedSignIn( } /** The body of `AuthManager#resolveSignInAccountId`; the method's docblock there is its contract. */ -export async function resolveSignInAccountId(this: Pick, email: string): Promise { +export async function resolveSignInAccountId( + this: Pick, + email: string, + door: PasswordSignInDoor = 'email', +): Promise { const engine = this.getDataEngine(); if (!engine) return undefined; try { - return (await this.findSignInAccount(engine, email, []))?.id; + return (await accountFinderFor(this, door)(engine, email, []))?.id; } catch (e) { // The refusal stands either way; what is lost is its ledger row. this.logDurabilityDegradation( @@ -503,6 +576,154 @@ export async function findSignInAccount( : undefined; } +/** The `sys_user` column {@link refuseLockedAccountSession} reads, beside the other session refusals' columns. */ +export const LOCKED_ACCOUNT_ROW_FIELDS = ['locked_until'] as const; + +/** + * Record, before the endpoint runs, what the request is for + * {@link refuseLockedAccountSession}: its endpoint path, and the account + * whose live session of record it presents — the stored `sys_session` row its + * session token names, unexpired. Read from the store, never from a session + * cache or the request's own view, and BEFORE the endpoint can replace that + * row (a password change that ends the other sessions deletes it first). + * + * Kept in the request state, which reaches the database hooks in every + * supported runtime, including the one whose endpoint context does not reach + * them (WebContainer: the request-state polyfill in `auth-manager.ts`). + * + * Only while the lockout is on. The first record in a request state stands: a + * nested call never replaces the outer call's. No holder is recorded when the + * request presents no token, the token names no live row, or the read fails, + * and no holder exempts nothing. Never throws. + */ +export async function recordLockoutRequest( + this: Pick, + ctx: any, +): Promise { + if ((Number(this.config.lockoutThreshold) || 0) <= 0) return; + if (typeof ctx?.path !== 'string' || ctx.path === '') return; + if (await readLockoutRequestState()) return; + let holder: string | undefined; + try { + const token = await presentedSessionToken(ctx); + if (token && typeof ctx?.context?.adapter?.findOne === 'function') { + const row: any = await ctx.context.adapter.findOne({ model: 'session', where: [{ field: 'token', value: token }] }); + const userId = row?.userId ?? row?.user_id; + const expiresAt = row?.expiresAt ?? row?.expires_at; + if (typeof userId === 'string' && userId !== '' && expiresAt && new Date(expiresAt).getTime() > Date.now()) { + holder = userId; + } + } + } catch { + holder = undefined; + } + await recordLockoutRequestState({ path: ctx.path, ...(holder ? { holder } : {}) }); +} + +/** + * The session token the request presents: the bearer credential, or the + * session cookie whose signature verifies. The stored token is the unsigned + * value; a bearer may carry the signed `TOKEN.SIGNATURE` spelling. + */ +async function presentedSessionToken(ctx: any): Promise { + const header = (name: string): string => + String(ctx?.headers?.get?.(name) ?? ctx?.request?.headers?.get?.(name) ?? ''); + const bearer = /^Bearer\s+(.+)$/i.exec(header('authorization'))?.[1]?.trim(); + if (bearer) return bearer.split('.')[0] || undefined; + const name = ctx?.context?.authCookies?.sessionToken?.name; + if (typeof name !== 'string' || typeof ctx?.getSignedCookie !== 'function') return undefined; + const signed = await ctx.getSignedCookie(name, ctx.context.secret); + return typeof signed === 'string' && signed !== '' ? signed : undefined; +} + +/** + * Whether a new session for `session.userId` is NOT a sign-in, judged + * fail-closed on the request `path` and `holder` the before-hook recorded: + * each exemption holds only when its condition is established, and a + * condition that cannot be established is a sign-in. + * + * - The server's in-process principal session: made outside any request, and + * carrying the token prefix only the mint writes + * (`principal-session-mint.ts`). A session made outside any request + * without that prefix is judged a sign-in. + * - An administrator's impersonation session: made on the administrator-gated + * impersonation route, naming as `impersonatedBy` the account whose live + * session of record made the request, which is not the account itself. + * - A new session for the account whose live session of record made the + * request (enrolling a second factor, a password change that ends the + * other sessions, an impersonating administrator's own rotation). + */ +function isNotASignIn(session: any, path: string | undefined, holder: string | undefined): boolean { + if (!path) { + return typeof session?.token === 'string' && session.token.startsWith(PRINCIPAL_SESSION_TOKEN_PREFIX); + } + if (typeof holder !== 'string' || holder === '') return false; + if (holder === session?.userId) return true; + return path === IMPERSONATE_USER_PATH && session?.impersonatedBy === holder; +} + +/** + * ADR-0069 D2 — a locked account is refused on every door that ends in a + * session for that account, with the answer password sign-in gives under the + * deployment's `lockoutRefusal` ({@link lockedAccountRefusal}). Composed into + * `session.create.before`, the one write every sign-in door ends in, so a door + * is held by the lock whichever credential it checks, or none. + * + * The lock is the one password sign-in reads: `locked_until` still in the + * future while `lockoutThreshold` is on. An expired lock admits, and with the + * threshold off no lock is read, as at `/sign-in/email`. + * + * The request is judged by its endpoint context when that reaches the hook, + * and otherwise by what the before-hook recorded in the request state + * ({@link recordLockoutRequest}); with neither, the session was made outside + * any request. + * + * A password door ({@link PASSWORD_DOOR_PATHS}) is held by its own gate, + * before its credential is checked ({@link admitSignInAttempt}), which also + * settles its counter and writes its row; here it is admitted only on that + * gate's recorded `admitted` verdict for this account in this request (and + * this identifier, where the endpoint context names one), and refused when + * that verdict is absent. Any other door refuses a sign-in + * ({@link isNotASignIn}) and writes the account's `login_failed` row with the + * lock as its reason, as password sign-in does. The counter is not moved. + * + * @param row the `sys_user` row the session refusals composed before this one + * read, with {@link LOCKED_ACCOUNT_ROW_FIELDS} among its columns. + */ +export async function refuseLockedAccountSession( + this: Pick, + session: any, + ctx: any, + row: Record | undefined, +): Promise { + const threshold = Number(this.config.lockoutThreshold) || 0; + if (threshold <= 0 || !row || !lockHolds(row.locked_until, Date.now())) return; + const userId = session?.userId; + if (typeof userId !== 'string' || userId === '') return; + const recorded = await readLockoutRequestState(); + const path = typeof ctx?.path === 'string' && ctx.path !== '' ? ctx.path : recorded?.path; + if (path && Object.values(PASSWORD_DOOR_PATHS).includes(path)) { + const attempt = await readSignInAttempt(); + const named = passwordSignInDoorOf(ctx)?.identifier; + if ( + attempt?.verdict === 'admitted' + && attempt.userId === userId + && (named === undefined || attempt.identifier === named.toLowerCase()) + ) return; + throw await lockedAccountRefusal(this.config.lockoutRefusal); + } + if (isNotASignIn(session, path, recorded?.holder)) return; + await emitAuthSessionAuditEvent( + this.config.getAuditSink?.(), + signInFailureEventFor(userId, { + path: path ?? '', + reason: 'ACCOUNT_LOCKED', + fingerprint: signInClientFingerprint(ctx, await readRequestClientAddress()), + }), + ); + throw await lockedAccountRefusal(this.config.lockoutRefusal); +} + /** The body of `AuthManager#resolveTwoFactorAccountLockout`; the method's docblock there is its contract. */ export function resolveTwoFactorAccountLockout(this: Pick): { enabled: boolean; maxFailedAttempts: number; durationSeconds: number } | undefined { const threshold = Number(this.config.lockoutThreshold) || 0; diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index 9affdd9d3aa..9076e2b2d05 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -169,6 +169,7 @@ import { resolveTwoFactorAccountLockout, settleSignInAttempt, stampLastLogin, + type PasswordSignInDoor, type SignInLockoutHost, type SignInOutcome, type SignInSettlement, @@ -7157,7 +7158,7 @@ export class AuthManager { * resolves the identifier to ({@link findSignInAccount}), so they hold for * every spelling of the address that signs in to that account. */ - private admitSignInAttempt(email: string, ctx?: unknown): Promise { + private admitSignInAttempt(email: string, ctx?: unknown, door?: PasswordSignInDoor): Promise { // [#25224 cut 2] The body moved to `auth-manager-sign-in-lockout.ts` (see `SignInLockoutHost`). const readConfig = () => this.config; const host: Pick = { @@ -7166,7 +7167,7 @@ export class AuthManager { getDataEngine: (...a) => this.getDataEngine(...a), logDurabilityDegradation: (...a) => this.logDurabilityDegradation(...a), }; - return admitSignInAttempt.call(host, email, ctx); + return admitSignInAttempt.call(host, email, ctx, door); } /** @@ -7193,7 +7194,7 @@ export class AuthManager { * transition the `account_locked` row records, so a lock that was never * written is never reported as one. */ - private settleSignInAttempt(email: string, outcome: SignInOutcome): Promise { + private settleSignInAttempt(email: string, outcome: SignInOutcome, door?: PasswordSignInDoor): Promise { // [#25224 cut 2] The body moved to `auth-manager-sign-in-lockout.ts` (see `SignInLockoutHost`). const readConfig = () => this.config; const host: Pick = { @@ -7202,7 +7203,7 @@ export class AuthManager { getDataEngine: (...a) => this.getDataEngine(...a), logDurabilityDegradation: (...a) => this.logDurabilityDegradation(...a), }; - return settleSignInAttempt.call(host, email, outcome); + return settleSignInAttempt.call(host, email, outcome, door); } /** @@ -7241,6 +7242,7 @@ export class AuthManager { ctx: any, email: string, settlement: SignInSettlement, + door?: PasswordSignInDoor, ): Promise { // [#25224 cut 2] The body moved to `auth-manager-sign-in-lockout.ts` (see `SignInLockoutHost`). const readConfig = () => this.config; @@ -7248,7 +7250,7 @@ export class AuthManager { get config() { return readConfig(); }, resolveSignInAccountId: (...a) => this.resolveSignInAccountId(...a), }; - return auditRefusedSignIn.call(host, ctx, email, settlement); + return auditRefusedSignIn.call(host, ctx, email, settlement, door); } /** @@ -7257,14 +7259,14 @@ export class AuthManager { * row names the account the credential check actually judged and the lock * gate and counter hold. */ - private resolveSignInAccountId(email: string): Promise { + private resolveSignInAccountId(email: string, door?: PasswordSignInDoor): Promise { // [#25224 cut 2] The body moved to `auth-manager-sign-in-lockout.ts` (see `SignInLockoutHost`). const host: Pick = { findSignInAccount: (...a) => this.findSignInAccount(...a), getDataEngine: (...a) => this.getDataEngine(...a), logDurabilityDegradation: (...a) => this.logDurabilityDegradation(...a), }; - return resolveSignInAccountId.call(host, email); + return resolveSignInAccountId.call(host, email, door); } /** diff --git a/packages/plugins/plugin-auth/src/locked-account-every-sign-in-door.test.ts b/packages/plugins/plugin-auth/src/locked-account-every-sign-in-door.test.ts new file mode 100644 index 00000000000..6221ebe69c2 --- /dev/null +++ b/packages/plugins/plugin-auth/src/locked-account-every-sign-in-door.test.ts @@ -0,0 +1,961 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// ADR-0069 D2 — the rule under test: a locked account is refused on every +// door that ends in a session for that account, with the answer password +// sign-in gives under the deployment's `lockoutRefusal`. Every password door +// counts its refused attempts toward the lock and checks the lock before its +// credential, so its answer for a locked account is the same whichever +// password it is sent. +// +// Real better-auth pipeline throughout: requests go in as `Request` objects +// through `AuthManager.handleRequest`, the codes and links are the ones the +// running plugins minted and handed to the SMS and email services, the lock is +// the account's own `locked_until`, and "was a session issued" is read from the +// `sys_session` rows themselves. +// +// The reference answer is always measured, never restated: the answer +// `/sign-in/email` gives the same locked account in the same deployment. + +import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest'; +import { createHmac } from 'node:crypto'; +import { ADMIN_FULL_ACCESS } from '@objectstack/spec/identity'; +import { AuthManager } from './auth-manager'; +import { createMemoryEngine } from './impersonation-bearer-rotation.test'; +import { memoizeScrypt } from './__tests__/scrypt-memo.testkit'; +import { inviteForAudienceGate } from './audience-gate-test-support'; +import type { AuthSessionAuditEventInput } from './auth-session-audit'; +import { PLATFORM_IDP_PROVIDER_ID } from './implicit-account-linking'; +import { refuseLockedAccountSession } from './auth-manager-sign-in-lockout'; +// Vendor modules paid at module load, never inside a clocked case. +import 'better-auth'; +import 'better-auth/api'; +import 'better-auth/plugins'; +import 'better-auth/plugins/bearer'; +import 'better-auth/plugins/two-factor'; +import 'better-auth/plugins/phone-number'; +import 'better-auth/plugins/magic-link'; +import 'better-auth/plugins/admin'; +import '@better-auth/core/context'; +import '@better-auth/core/error'; + +const SECRET = 'test-secret-at-least-32-chars-long!!'; +const PASSWORD = 'S3cure!Passw0rd-locked-doors'; +const WRONG_PASSWORD = 'Wr0ng!Guess-Zebra-7731'; +const ORIGIN = 'http://localhost:3000'; +const BASE = `${ORIGIN}/api/v1/auth`; +const THRESHOLD = 3; +const PLAIN = { email: 'plain@example.com', phone: '+15550143' }; +const ENROLLED = { email: 'enrolled@example.com', phone: '+15550142' }; +const ADMIN = { email: 'admin@example.com', phone: '+15550144' }; +const PS_ADMIN = 'ps_admin_full_access'; + +type Refusal = 'uniform' | 'explicit'; + +// ── RFC 6238 TOTP (the vendor defaults: SHA-1, 6 digits, 30 s) ──────────── +function base32Decode(input: string): Buffer { + const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; + let bits = 0; + let value = 0; + const out: number[] = []; + for (const char of input.replace(/=+$/, '').toUpperCase()) { + value = (value << 5) | ALPHABET.indexOf(char); + bits += 5; + if (bits >= 8) { + out.push((value >>> (bits - 8)) & 0xff); + bits -= 8; + } + } + return Buffer.from(out); +} + +function totp(secret: Buffer): string { + const buf = Buffer.alloc(8); + buf.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 30_000))); + const digest = createHmac('sha1', secret).update(buf).digest(); + const offset = digest[digest.length - 1] & 0x0f; + const code = + ((digest[offset] & 0x7f) << 24) | + ((digest[offset + 1] & 0xff) << 16) | + ((digest[offset + 2] & 0xff) << 8) | + (digest[offset + 3] & 0xff); + return String(code % 1_000_000).padStart(6, '0'); +} + +/** The unsigned value of the response cookie whose name ends with `suffix`. */ +const cookieValue = (res: Response, suffix: string): string | undefined => { + const pair = (res.headers.getSetCookie?.() ?? []) + .map((c) => c.split(';')[0]) + .find((p) => p.split('=')[0].endsWith(suffix)); + if (!pair) return undefined; + const raw = decodeURIComponent(pair.split('=').slice(1).join('=')); + return raw.slice(0, raw.lastIndexOf('.')); +}; + +/** A response's Set-Cookie values as one request Cookie header (expired ones dropped). */ +const cookieHeader = (res: Response): string => + (res.headers.getSetCookie?.() ?? []) + .filter((c) => !/max-age=0/i.test(c)) + .map((c) => c.split(';')[0]) + .join('; '); + +type Rig = Awaited>; + +const arrange = async (lockoutRefusal: Refusal = 'uniform', options: { lockoutThreshold?: number } = {}) => { + const engine: any = createMemoryEngine(); + const texts: { to: string; body: string }[] = []; + const mails: any[] = []; + const events: AuthSessionAuditEventInput[] = []; + const manager = new AuthManager({ + secret: SECRET, + baseUrl: ORIGIN, + dataEngine: engine, + lockoutThreshold: options.lockoutThreshold ?? THRESHOLD, + lockoutDurationMinutes: 15, + lockoutRefusal, + plugins: { twoFactor: true, phoneNumber: true, magicLink: true, admin: true, deviceAuthorization: true }, + emailVerification: { autoSignInAfterVerification: true }, + getAuditSink: () => ({ + recordAuthEvent: async (event: AuthSessionAuditEventInput) => { + events.push(event); + }, + }), + smsService: { + async send(input: any) { + texts.push({ to: String(input?.to ?? ''), body: String(input?.body ?? input?.text ?? '') }); + return { id: 'sms_test', status: 'sent' }; + }, + isConfigured: () => true, + }, + emailService: { + async sendTemplate(input: any) { + mails.push(input); + return { id: 'mail_test', status: 'sent' }; + }, + async send(input: any) { + mails.push(input); + return { id: 'mail_test', status: 'sent' }; + }, + isConfigured: () => true, + }, + } as any); + + const post = (path: string, body: unknown, headers: Record = {}) => + manager.handleRequest( + new Request(`${BASE}${path}`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: ORIGIN, ...headers }, + body: JSON.stringify(body ?? {}), + }), + ); + const get = (url: string, headers: Record = {}) => + manager.handleRequest( + new Request(url.startsWith('http') ? url : `${BASE}${url}`, { method: 'GET', headers: { origin: ORIGIN, ...headers } }), + ); + + const userRow = (email: string) => { + const row = ((engine.tables.get('sys_user') ?? []) as any[]).find((r) => r.email === email); + if (!row) throw new Error(`no sys_user row for ${email}`); + return row; + }; + + const signUp = async ({ email, phone }: { email: string; phone: string }) => { + const invitationId = await inviteForAudienceGate(manager, email); + const res = await post('/sign-up/email', { email, password: PASSWORD, name: email.split('@')[0], invitationId }); + expect(res.status, `sign-up/email: ${await res.clone().text()}`).toBe(200); + // A verified phone and address: an account in ordinary use. + const row = userRow(email); + row.phone_number = phone; + row.phone_number_verified = true; + row.email_verified = true; + return { cookie: cookieHeader(res), userId: String(row.id) }; + }; + + const plain = await signUp(PLAIN); + const enrolled = await signUp(ENROLLED); + const admin = await signUp(ADMIN); + + // The ENROLLED account: TOTP enabled and confirmed. + const enabled = await post('/two-factor/enable', { password: PASSWORD }, { cookie: enrolled.cookie }); + expect(enabled.status, `two-factor/enable: ${await enabled.clone().text()}`).toBe(200); + const { totpURI, backupCodes } = (await enabled.json()) as { totpURI: string; backupCodes: string[] }; + const secret = base32Decode(String(new URL(totpURI.replace('otpauth://', 'https://')).searchParams.get('secret'))); + const confirmed = await post('/two-factor/verify-totp', { code: totp(secret) }, { cookie: enrolled.cookie }); + expect(confirmed.status, `verify-totp (enrolment): ${await confirmed.clone().text()}`).toBe(200); + + const sessionRows = (userId: string) => + ((engine.tables.get('sys_session') ?? []) as any[]).filter((r) => String(r.user_id ?? r.userId) === userId).length; + + /** Lock the account the way a run of wrong passwords leaves it. */ + const lock = (email: string, minutes = 10) => { + const row = userRow(email); + row.failed_login_count = THRESHOLD; + row.locked_until = new Date(Date.now() + minutes * 60_000); + }; + + return { + engine, + manager, + post, + get, + texts, + mails, + events, + userRow, + sessionRows, + lock, + secret, + backupCodes, + plainId: plain.userId, + plainCookie: plain.cookie, + enrolledId: enrolled.userId, + adminId: admin.userId, + }; +}; + +/** The refusal's envelope: status, machine code and sentence. */ +const answerOf = async (res: Response) => { + const text = await res.clone().text(); + let body: { code?: unknown; message?: unknown } = {}; + try { + body = JSON.parse(text); + } catch { + /* not JSON */ + } + return { status: res.status, code: body.code, message: body.message }; +}; + +/** What `/sign-in/email` answers this locked account with the correct password: the reference. */ +const passwordSignInAnswer = async (rig: Rig, email: string) => + answerOf(await rig.post('/sign-in/email', { email, password: PASSWORD })); + +/** + * Stage the second factor's one-time code for a pending challenge exactly as + * the vendor stores it (`2fa-otp-` + the challenge cookie's value, `CODE:0`, + * kept in plain): this deployment wires no sender for that code. + */ +const stageSecondFactorOtp = async (rig: Rig, challenged: Response, code: string) => { + const key = cookieValue(challenged, 'two_factor'); + expect(key, 'the challenge set its two-factor cookie').toBeTruthy(); + const auth: any = await rig.manager.getAuthContext(); + await auth.internalAdapter.createVerificationValue({ + identifier: `2fa-otp-${key}`, + value: `${code}:0`, + expiresAt: new Date(Date.now() + 5 * 60_000), + }); +}; + +const EXPECTED_CODE: Record = { + explicit: 'ACCOUNT_LOCKED', + uniform: 'INVALID_EMAIL_OR_PASSWORD', +}; +const EXPECTED_STATUS: Record = { explicit: 403, uniform: 401 }; + +// ── The code and link doors ─────────────────────────────────────────────── + +interface Door { + path: string; + label: string; + pass(rig: Rig, who: { email: string; phone: string }): Promise; +} + +const smsCode = async (rig: Rig, phone: string): Promise => { + const sent = await rig.post('/phone-number/send-otp', { phoneNumber: phone }); + expect(sent.status, `send-otp: ${await sent.clone().text()}`).toBe(200); + const code = rig.texts.at(-1)?.body.match(/\b(\d{6})\b/)?.[1]; + expect(code, 'the SMS carried a code').toBeTruthy(); + return code!; +}; + +const magicLinkUrl = async (rig: Rig, email: string, callbackURL?: string): Promise => { + const before = rig.mails.length; + const sent = await rig.post('/sign-in/magic-link', { email, ...(callbackURL ? { callbackURL } : {}) }); + expect(sent.status, `sign-in/magic-link: ${await sent.clone().text()}`).toBe(200); + const mail = rig.mails.slice(before).find((m) => m?.data?.magicLinkUrl); + expect(mail, 'the sign-in link was mailed').toBeDefined(); + return new URL(String(mail.data.magicLinkUrl)); +}; + +const DOORS: Door[] = [ + { + path: '/phone-number/verify', + label: 'the SMS one-time code', + async pass(rig, who) { + const code = await smsCode(rig, who.phone); + return rig.post('/phone-number/verify', { phoneNumber: who.phone, code }); + }, + }, + { + path: '/magic-link/verify', + label: 'the emailed sign-in link, JSON lane', + async pass(rig, who) { + const url = await magicLinkUrl(rig, who.email); + url.searchParams.delete('callbackURL'); + return rig.get(url.toString()); + }, + }, + { + path: '/magic-link/verify', + label: 'the emailed sign-in link, callbackURL lane', + async pass(rig, who) { + return rig.get((await magicLinkUrl(rig, who.email, '/after-sign-in')).toString()); + }, + }, + { + path: '/verify-email', + label: 'the verification link that signs the caller in', + async pass(rig, who) { + rig.userRow(who.email).email_verified = false; + const { createEmailVerificationToken } = await import('better-auth/api'); + return rig.get(`/verify-email?token=${await createEmailVerificationToken(SECRET, who.email)}`); + }, + }, +]; + +beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); + vi.spyOn(console, 'info').mockImplementation(() => {}); +}); +afterEach(() => vi.restoreAllMocks()); + +const scrypt = memoizeScrypt(); +afterAll(scrypt.restore); + +describe.each(['explicit', 'uniform'] as const)( + 'a locked account is refused on every door that ends in a session for it (lockoutRefusal: %s)', + (refusal) => { + it.each(DOORS.map((door) => [door.label, door] as const))( + '%s: no session, and the answer password sign-in gives', + async (_label, door) => { + const rig = await arrange(refusal); + rig.lock(PLAIN.email); + const reference = await passwordSignInAnswer(rig, PLAIN.email); + expect(reference.status).toBe(EXPECTED_STATUS[refusal]); + expect(reference.code).toBe(EXPECTED_CODE[refusal]); + const rowsBefore = rig.sessionRows(rig.plainId); + + const res = await door.pass(rig, PLAIN); + + expect(await answerOf(res)).toEqual(reference); + expect(rig.sessionRows(rig.plainId), 'no session row was written').toBe(rowsBefore); + }, + 60_000, + ); + + it.each(DOORS.map((door) => [door.label, door] as const))( + '%s: the refused attempt writes its login_failed row, as password sign-in does', + async (_label, door) => { + const rig = await arrange(refusal); + rig.lock(PLAIN.email); + + await door.pass(rig, PLAIN); + + const rows = rig.events.filter((e: any) => e?.action === 'login_failed' && e.userId === rig.plainId); + expect(rows.map((e: any) => e.context)).toEqual([{ endpoint: door.path, reason: 'ACCOUNT_LOCKED' }]); + }, + 60_000, + ); + + it('/two-factor/verify-totp: an enrolled account locked after its challenge gets no session', async () => { + const rig = await arrange(refusal); + const challenged = await rig.post('/sign-in/email', { email: ENROLLED.email, password: PASSWORD }); + expect(((await challenged.clone().json()) as any).twoFactorRedirect).toBe(true); + rig.lock(ENROLLED.email); + const reference = await passwordSignInAnswer(rig, ENROLLED.email); + const rowsBefore = rig.sessionRows(rig.enrolledId); + + const res = await rig.post('/two-factor/verify-totp', { code: totp(rig.secret) }, { cookie: cookieHeader(challenged) }); + + expect(await answerOf(res)).toEqual(reference); + expect(rig.sessionRows(rig.enrolledId), 'no session row was written').toBe(rowsBefore); + }, 60_000); + + it('/two-factor/verify-backup-code: an enrolled account locked after its challenge gets no session', async () => { + const rig = await arrange(refusal); + const challenged = await rig.post('/sign-in/email', { email: ENROLLED.email, password: PASSWORD }); + expect(((await challenged.clone().json()) as any).twoFactorRedirect).toBe(true); + rig.lock(ENROLLED.email); + const reference = await passwordSignInAnswer(rig, ENROLLED.email); + const rowsBefore = rig.sessionRows(rig.enrolledId); + + const res = await rig.post('/two-factor/verify-backup-code', { code: rig.backupCodes[0] }, { cookie: cookieHeader(challenged) }); + + expect(await answerOf(res)).toEqual(reference); + expect(rig.sessionRows(rig.enrolledId), 'no session row was written').toBe(rowsBefore); + }, 60_000); + + it('/two-factor/verify-otp: an enrolled account locked after its challenge gets no session', async () => { + const rig = await arrange(refusal); + const challenged = await rig.post('/sign-in/email', { email: ENROLLED.email, password: PASSWORD }); + expect(((await challenged.clone().json()) as any).twoFactorRedirect).toBe(true); + await stageSecondFactorOtp(rig, challenged, '424242'); + rig.lock(ENROLLED.email); + const reference = await passwordSignInAnswer(rig, ENROLLED.email); + const rowsBefore = rig.sessionRows(rig.enrolledId); + + const res = await rig.post('/two-factor/verify-otp', { code: '424242' }, { cookie: cookieHeader(challenged) }); + + expect(await answerOf(res)).toEqual(reference); + expect(rig.sessionRows(rig.enrolledId), 'no session row was written').toBe(rowsBefore); + }, 60_000); + + it('a code door gives an enrolled locked account no second-factor challenge, and no session', async () => { + const rig = await arrange(refusal); + rig.lock(ENROLLED.email); + const reference = await passwordSignInAnswer(rig, ENROLLED.email); + const rowsBefore = rig.sessionRows(rig.enrolledId); + + const res = await DOORS[0].pass(rig, ENROLLED); + + expect(await answerOf(res)).toEqual(reference); + expect(rig.sessionRows(rig.enrolledId)).toBe(rowsBefore); + }, 60_000); + + it('/sign-in/phone-number: a locked account gets one answer whatever the password, and no session', async () => { + const rig = await arrange(refusal); + rig.lock(PLAIN.email); + const rowsBefore = rig.sessionRows(rig.plainId); + + const correct = await answerOf(await rig.post('/sign-in/phone-number', { phoneNumber: PLAIN.phone, password: PASSWORD })); + const wrong = await answerOf(await rig.post('/sign-in/phone-number', { phoneNumber: PLAIN.phone, password: WRONG_PASSWORD })); + + expect(correct).toEqual(wrong); + // `uniform` is that door's own wrong-password answer; `explicit` is the + // `403 ACCOUNT_LOCKED` password sign-in gives. + expect(correct.status).toBe(EXPECTED_STATUS[refusal]); + expect(correct.code).toBe(refusal === 'explicit' ? 'ACCOUNT_LOCKED' : 'INVALID_PHONE_NUMBER_OR_PASSWORD'); + expect(rig.sessionRows(rig.plainId), 'no session row was written').toBe(rowsBefore); + const rows = rig.events.filter((e: any) => e?.action === 'login_failed' && e.userId === rig.plainId); + expect(rows.map((e: any) => e.context?.endpoint)).toEqual(['/sign-in/phone-number', '/sign-in/phone-number']); + }, 60_000); + + it('CONTROL: password sign-in is unchanged — refused, one login_failed row, no session', async () => { + const rig = await arrange(refusal); + rig.lock(PLAIN.email); + const rowsBefore = rig.sessionRows(rig.plainId); + + const answer = await passwordSignInAnswer(rig, PLAIN.email); + + expect(answer.status).toBe(EXPECTED_STATUS[refusal]); + expect(answer.code).toBe(EXPECTED_CODE[refusal]); + expect(rig.sessionRows(rig.plainId)).toBe(rowsBefore); + const rows = rig.events.filter((e: any) => e?.action === 'login_failed' && e.userId === rig.plainId); + expect(rows.map((e: any) => e.context)).toEqual([{ endpoint: '/sign-in/email', reason: 'ACCOUNT_LOCKED' }]); + }, 60_000); + }, +); + +describe('an unlocked account, and a lock that has run out, still sign in at every door', () => { + it.each(DOORS.map((door) => [door.label, door] as const))('%s: an unlocked account gets its session', async (_label, door) => { + const rig = await arrange(); + const rowsBefore = rig.sessionRows(rig.plainId); + + const res = await door.pass(rig, PLAIN); + + expect(res.status, await res.clone().text()).toBeLessThan(400); + expect(rig.sessionRows(rig.plainId)).toBe(rowsBefore + 1); + }, 60_000); + + it.each(DOORS.map((door) => [door.label, door] as const))('%s: an expired lock admits', async (_label, door) => { + const rig = await arrange(); + rig.lock(PLAIN.email, -1); + const rowsBefore = rig.sessionRows(rig.plainId); + + const res = await door.pass(rig, PLAIN); + + expect(res.status, await res.clone().text()).toBeLessThan(400); + expect(rig.sessionRows(rig.plainId)).toBe(rowsBefore + 1); + }, 60_000); + + it('with the lockout off, a stored lock is not read, as at /sign-in/email', async () => { + const rig = await arrange('explicit', { lockoutThreshold: 0 }); + rig.lock(PLAIN.email); + const rowsBefore = rig.sessionRows(rig.plainId); + + const res = await DOORS[0].pass(rig, PLAIN); + + expect(res.status, await res.clone().text()).toBe(200); + expect(rig.sessionRows(rig.plainId)).toBe(rowsBefore + 1); + }, 60_000); + + it('/sign-in/phone-number: an unlocked account signs in', async () => { + const rig = await arrange(); + const res = await rig.post('/sign-in/phone-number', { phoneNumber: PLAIN.phone, password: PASSWORD }); + expect(res.status, await res.clone().text()).toBe(200); + }, 60_000); + + it('CONTROL: /two-factor/verify-otp completes the challenge for an unlocked enrolled account', async () => { + const rig = await arrange(); + const challenged = await rig.post('/sign-in/email', { email: ENROLLED.email, password: PASSWORD }); + await stageSecondFactorOtp(rig, challenged, '424242'); + const rowsBefore = rig.sessionRows(rig.enrolledId); + + const res = await rig.post('/two-factor/verify-otp', { code: '424242' }, { cookie: cookieHeader(challenged) }); + + expect(res.status, await res.clone().text()).toBe(200); + expect(rig.sessionRows(rig.enrolledId)).toBe(rowsBefore + 1); + }, 60_000); + + it('CONTROL: the second-factor challenge is unchanged for an unlocked enrolled account', async () => { + const rig = await arrange(); + const challenged = await DOORS[0].pass(rig, ENROLLED); + expect(((await challenged.clone().json()) as any).twoFactorRedirect).toBe(true); + + const verified = await rig.post('/two-factor/verify-totp', { code: totp(rig.secret) }, { cookie: cookieHeader(challenged) }); + + expect(verified.status, await verified.clone().text()).toBe(200); + }, 60_000); +}); + +describe('every password door counts its refused attempts toward the lock', () => { + it(`${THRESHOLD} wrong passwords at /sign-in/phone-number lock the account`, async () => { + const rig = await arrange('explicit'); + for (let i = 0; i < THRESHOLD; i++) { + const res = await rig.post('/sign-in/phone-number', { phoneNumber: PLAIN.phone, password: WRONG_PASSWORD }); + expect(res.status).toBe(401); + } + + expect(rig.userRow(PLAIN.email).failed_login_count).toBe(THRESHOLD); + expect(new Date(rig.userRow(PLAIN.email).locked_until).getTime()).toBeGreaterThan(Date.now()); + const after = await answerOf(await rig.post('/sign-in/phone-number', { phoneNumber: PLAIN.phone, password: PASSWORD })); + expect(after.code).toBe('ACCOUNT_LOCKED'); + expect(rig.events.some((e: any) => e?.action === 'account_locked' && e.userId === rig.plainId && e.context?.endpoint === '/sign-in/phone-number')).toBe(true); + }, 60_000); + + it('a correct password at /sign-in/phone-number resets the count, as at /sign-in/email', async () => { + const rig = await arrange(); + for (let i = 0; i < THRESHOLD - 1; i++) { + await rig.post('/sign-in/phone-number', { phoneNumber: PLAIN.phone, password: WRONG_PASSWORD }); + } + expect(rig.userRow(PLAIN.email).failed_login_count).toBe(THRESHOLD - 1); + + const res = await rig.post('/sign-in/phone-number', { phoneNumber: PLAIN.phone, password: PASSWORD }); + + expect(res.status, await res.clone().text()).toBe(200); + expect(Number(rig.userRow(PLAIN.email).failed_login_count) || 0).toBe(0); + }, 60_000); + + it('CONTROL: /sign-in/email counts and resets as before', async () => { + const rig = await arrange('explicit'); + for (let i = 0; i < THRESHOLD - 1; i++) { + await rig.post('/sign-in/email', { email: PLAIN.email, password: WRONG_PASSWORD }); + } + expect(rig.userRow(PLAIN.email).failed_login_count).toBe(THRESHOLD - 1); + expect((await rig.post('/sign-in/email', { email: PLAIN.email, password: PASSWORD })).status).toBe(200); + expect(Number(rig.userRow(PLAIN.email).failed_login_count) || 0).toBe(0); + + for (let i = 0; i < THRESHOLD; i++) { + await rig.post('/sign-in/email', { email: PLAIN.email, password: WRONG_PASSWORD }); + } + expect(new Date(rig.userRow(PLAIN.email).locked_until).getTime()).toBeGreaterThan(Date.now()); + }, 60_000); +}); + +describe('CONTROL: administrative sessions for a locked account keep working', () => { + /** Grant platform admin the ADR-0068 D2 way and sign the admin in; resolves its bearer. */ + const platformAdminBearer = async (rig: Rig): Promise => { + if (!(rig.engine.tables.get('sys_permission_set') ?? []).some((r: any) => r.id === PS_ADMIN)) { + await rig.engine.insert('sys_permission_set', { id: PS_ADMIN, name: ADMIN_FULL_ACCESS }); + } + let org = (rig.engine.tables.get('sys_organization') ?? []).find((r: any) => r.slug === 'default'); + if (!org) { + await rig.engine.insert('sys_organization', { id: 'org_default', name: 'Default Organization', slug: 'default' }); + org = { id: 'org_default' }; + } + await rig.engine.insert('sys_user_permission_set', { + user_id: rig.adminId, + permission_set_id: PS_ADMIN, + permission_set: 'admin_full_access', + organization_id: String(org.id), + }); + const signedIn = await rig.post('/sign-in/email', { email: ADMIN.email, password: PASSWORD }); + expect(signedIn.status, await signedIn.clone().text()).toBe(200); + return String(signedIn.headers.get('set-auth-token')); + }; + + it('an administrator impersonates a locked account', async () => { + const rig = await arrange('explicit'); + const bearer = await platformAdminBearer(rig); + rig.lock(PLAIN.email); + const rowsBefore = rig.sessionRows(rig.plainId); + + const res = await rig.post('/admin/impersonate-user', { userId: rig.plainId }, { authorization: `Bearer ${bearer}` }); + + expect(res.status, await res.clone().text()).toBe(200); + expect(rig.sessionRows(rig.plainId)).toBe(rowsBefore + 1); + }, 60_000); + + it("a locked administrator's own session is still rotated when impersonating", async () => { + const rig = await arrange('explicit'); + const bearer = await platformAdminBearer(rig); + rig.lock(ADMIN.email); + + const res = await rig.post('/admin/impersonate-user', { userId: rig.plainId }, { authorization: `Bearer ${bearer}` }); + + expect(res.status, await res.clone().text()).toBe(200); + }, 60_000); + + it('a locked, signed-in account changes its password and ends its other sessions', async () => { + const rig = await arrange('explicit'); + rig.lock(PLAIN.email); + + const res = await rig.post( + '/change-password', + { currentPassword: PASSWORD, newPassword: 'N3w!Passw0rd-locked-Q9', revokeOtherSessions: true }, + { cookie: rig.plainCookie }, + ); + + expect(res.status, await res.clone().text()).toBe(200); + expect(rig.sessionRows(rig.plainId)).toBe(1); + }, 60_000); + + it('the in-process principal session is minted for a locked account', async () => { + const rig = await arrange('explicit'); + rig.lock(PLAIN.email); + + const minted = await rig.manager.mintPrincipalSession({ userId: rig.plainId, principalKind: 'human' } as any, { ttlSeconds: 60 }); + + expect(typeof minted.token).toBe('string'); + }, 60_000); +}); + +describe('the device grant: a locked account is not signed in on a device', () => { + /** Start a device sign-in, approve it as the account, and poll for the device's session. */ + const deviceSignIn = async (rig: Rig, approverCookie: string) => { + const started = await rig.post('/device/code', { client_id: 'locked-door-cli' }); + expect(started.status, await started.clone().text()).toBe(200); + const { device_code, user_code } = (await started.json()) as { device_code: string; user_code: string }; + // The signed-in account claims the code before approving it, as the + // verification page does. + const claimed = await rig.get(`/device?user_code=${encodeURIComponent(user_code)}`, { cookie: approverCookie }); + expect(claimed.status, await claimed.clone().text()).toBe(200); + const approved = await rig.post('/device/approve', { userCode: user_code }, { cookie: approverCookie }); + expect(approved.status, await approved.clone().text()).toBe(200); + return rig.post('/device/token', { + grant_type: 'urn:ietf:params:oauth:grant-type:device_code', + device_code, + client_id: 'locked-door-cli', + }); + }; + + it.each(['explicit', 'uniform'] as const)('a locked account gets no device session (lockoutRefusal: %s)', async (refusal) => { + const rig = await arrange(refusal); + rig.lock(PLAIN.email); + const reference = await passwordSignInAnswer(rig, PLAIN.email); + const rowsBefore = rig.sessionRows(rig.plainId); + + const res = await deviceSignIn(rig, rig.plainCookie); + + expect(await answerOf(res)).toEqual(reference); + expect(rig.sessionRows(rig.plainId), 'no session row was written').toBe(rowsBefore); + const rows = rig.events.filter( + (e: any) => e?.action === 'login_failed' && e.userId === rig.plainId && e.context?.endpoint !== '/sign-in/email', + ); + expect(rows.map((e: any) => e.context)).toEqual([{ endpoint: '/device/token', reason: 'ACCOUNT_LOCKED' }]); + }, 60_000); + + it('CONTROL: an unlocked account gets its device session', async () => { + const rig = await arrange(); + const rowsBefore = rig.sessionRows(rig.plainId); + + const res = await deviceSignIn(rig, rig.plainCookie); + + expect(res.status, await res.clone().text()).toBe(200); + expect(typeof ((await res.json()) as any).access_token).toBe('string'); + expect(rig.sessionRows(rig.plainId)).toBe(rowsBefore + 1); + }, 60_000); +}); + +describe('external-identity sign-in: a locked account is not signed in through its identity provider', () => { + const IDP = 'https://idp.locked-door.test'; + const IDP_EMAIL = 'idp-person@example.test'; + const realFetch = globalThis.fetch; + + beforeEach(() => { + vi.stubGlobal('fetch', async (input: any, init?: any) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + if (!url.startsWith(IDP)) return realFetch(input, init); + if (url.endsWith('/token')) { + return new Response(JSON.stringify({ access_token: 'at-idp', token_type: 'Bearer', expires_in: 3600 }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + } + if (url.endsWith('/userinfo')) { + return new Response( + JSON.stringify({ sub: 'idp-sub-1', id: 'idp-sub-1', email: IDP_EMAIL, email_verified: true, name: 'IdP Person' }), + { status: 200, headers: { 'Content-Type': 'application/json' } }, + ); + } + return new Response('not found', { status: 404 }); + }); + }); + afterEach(() => vi.unstubAllGlobals()); + + const idpDeployment = (lockoutRefusal: Refusal) => { + const engine: any = createMemoryEngine(); + const events: AuthSessionAuditEventInput[] = []; + const manager = new AuthManager({ + secret: SECRET, + baseUrl: ORIGIN, + dataEngine: engine, + lockoutThreshold: THRESHOLD, + lockoutDurationMinutes: 15, + lockoutRefusal, + oidcProviders: [ + { + providerId: PLATFORM_IDP_PROVIDER_ID, + clientId: 'idp-client', + clientSecret: 'idp-secret', + authorizationUrl: `${IDP}/authorize`, + tokenUrl: `${IDP}/token`, + userInfoUrl: `${IDP}/userinfo`, + pkce: false, + }, + ], + getAuditSink: () => ({ + recordAuthEvent: async (event: AuthSessionAuditEventInput) => { + events.push(event); + }, + }), + } as any); + const signInWithIdp = async (): Promise => { + const begin = await manager.handleRequest( + new Request(`${BASE}/sign-in/social`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: ORIGIN }, + body: JSON.stringify({ provider: PLATFORM_IDP_PROVIDER_ID, callbackURL: `${ORIGIN}/after-sign-in`, disableRedirect: true }), + }), + ); + expect(begin.status, await begin.clone().text()).toBe(200); + const state = new URL(((await begin.json()) as { url: string }).url).searchParams.get('state'); + return manager.handleRequest( + new Request(`${BASE}/callback/${PLATFORM_IDP_PROVIDER_ID}?code=code-1&state=${encodeURIComponent(String(state))}`, { + headers: { cookie: cookieHeader(begin) }, + }), + ); + }; + const userRow = () => ((engine.tables.get('sys_user') ?? []) as any[]).find((r) => r.email === IDP_EMAIL); + const sessionRows = () => + ((engine.tables.get('sys_session') ?? []) as any[]).filter((r) => String(r.user_id ?? r.userId) === String(userRow()?.id)).length; + return { manager, events, signInWithIdp, userRow, sessionRows }; + }; + + it.each(['explicit', 'uniform'] as const)('a locked account gets no session from its identity provider (lockoutRefusal: %s)', async (refusal) => { + const d = idpDeployment(refusal); + const first = await d.signInWithIdp(); + expect(first.status, await first.clone().text()).toBe(302); + expect(d.userRow(), 'the first sign-in made the account').toBeDefined(); + const row = d.userRow(); + row.locked_until = new Date(Date.now() + 10 * 60_000); + const rowsBefore = d.sessionRows(); + + const res = await d.signInWithIdp(); + + // The callback is a browser redirect: its refusal rides the provider + // door's error redirect, carrying the code password sign-in gives. + expect(res.status).toBe(302); + const location = new URL(String(res.headers.get('location')), ORIGIN); + expect(location.pathname).not.toBe('/after-sign-in'); + expect(location.searchParams.get('error')).toBe(EXPECTED_CODE[refusal]); + expect(d.sessionRows(), 'no session row was written').toBe(rowsBefore); + const rows = d.events.filter((e: any) => e?.action === 'login_failed' && e.userId === row.id); + expect(rows.map((e: any) => e.context)).toEqual([{ endpoint: '/callback/:id', reason: 'ACCOUNT_LOCKED' }]); + }, 60_000); + + it('CONTROL: an unlocked account signs in through its identity provider', async () => { + const d = idpDeployment('explicit'); + await d.signInWithIdp(); + const rowsBefore = d.sessionRows(); + + const res = await d.signInWithIdp(); + + expect(res.status, await res.clone().text()).toBe(302); + expect(new URL(String(res.headers.get('location')), ORIGIN).pathname).toBe('/after-sign-in'); + expect(d.sessionRows()).toBe(rowsBefore + 1); + }, 60_000); +}); + +describe("a password door's session is admitted only on its own gate's verdict", () => { + it.each(['explicit', 'uniform'] as const)( + 'with no gate verdict recorded, a locked account gets no session at /sign-in/email (lockoutRefusal: %s)', + async (refusal) => { + const rig = await arrange(refusal); + vi.spyOn(rig.manager as any, 'admitSignInAttempt').mockResolvedValue(undefined); + rig.lock(PLAIN.email); + const rowsBefore = rig.sessionRows(rig.plainId); + + const res = await rig.post('/sign-in/email', { email: PLAIN.email, password: PASSWORD }); + + expect(res.status).toBe(EXPECTED_STATUS[refusal]); + expect((await answerOf(res)).code).toBe(EXPECTED_CODE[refusal]); + expect(rig.sessionRows(rig.plainId), 'no session row was written').toBe(rowsBefore); + }, + 60_000, + ); + + it('CONTROL: with no gate verdict recorded, an unlocked account still signs in', async () => { + const rig = await arrange(); + vi.spyOn(rig.manager as any, 'admitSignInAttempt').mockResolvedValue(undefined); + + const res = await rig.post('/sign-in/email', { email: PLAIN.email, password: PASSWORD }); + + expect(res.status, await res.clone().text()).toBe(200); + }, 60_000); +}); + +describe('every exemption holds only when its condition is established (fail closed)', () => { + const config = { lockoutThreshold: THRESHOLD, lockoutRefusal: 'explicit' } as any; + const lockedRow = { locked_until: new Date(Date.now() + 10 * 60_000) }; + const refusalOf = async (session: any, ctx: any) => { + try { + await refuseLockedAccountSession.call({ config }, session, ctx, lockedRow); + return 'admitted'; + } catch (e: any) { + return e?.body?.code ?? e?.code ?? 'threw'; + } + }; + + it('a session made outside an endpoint call is refused unless it carries the principal mint token', async () => { + expect(await refusalOf({ userId: 'u1', token: 'plainToken123' }, undefined)).toBe('ACCOUNT_LOCKED'); + expect(await refusalOf({ userId: 'u1' }, null)).toBe('ACCOUNT_LOCKED'); + }); + + it('an impersonation mark without a live session of record for the administrator is refused', async () => { + expect(await refusalOf({ userId: 'u1', impersonatedBy: 'admin1' }, { path: '/admin/impersonate-user' })).toBe('ACCOUNT_LOCKED'); + expect(await refusalOf({ userId: 'u1', impersonatedBy: 'admin1' }, { path: '/magic-link/verify' })).toBe('ACCOUNT_LOCKED'); + }); + + it("the request's own view of a session for the same account is not a session of record", async () => { + const ctx = { path: '/verify-email', context: { session: { user: { id: 'u1' }, session: { userId: 'u1' } } } }; + expect(await refusalOf({ userId: 'u1' }, ctx)).toBe('ACCOUNT_LOCKED'); + }); + + it('a password door with no gate verdict is refused', async () => { + expect(await refusalOf({ userId: 'u1' }, { path: '/sign-in/phone-number', body: { phoneNumber: '+15550143' } })).toBe('ACCOUNT_LOCKED'); + }); + + it('CONTROL: an unlocked account is never refused', async () => { + await expect( + refuseLockedAccountSession.call({ config }, { userId: 'u1' }, { path: '/magic-link/verify' }, { locked_until: null }), + ).resolves.toBeUndefined(); + }); +}); + +describe('CONTROL: a session presented that is no longer of record exempts nothing', () => { + it('an expired session of the same account does not stand in for a sign-in at a code door', async () => { + const rig = await arrange('explicit'); + for (const row of (rig.engine.tables.get('sys_session') ?? []) as any[]) { + if (String(row.user_id ?? row.userId) === rig.plainId) { + row.expires_at = new Date(Date.now() - 60_000); + row.expiresAt = row.expires_at; + } + } + rig.lock(PLAIN.email); + const code = await smsCode(rig, PLAIN.phone); + const liveRows = () => + ((rig.engine.tables.get('sys_session') ?? []) as any[]).filter( + (r) => String(r.user_id ?? r.userId) === rig.plainId && new Date(r.expires_at ?? r.expiresAt).getTime() > Date.now(), + ).length; + expect(liveRows()).toBe(0); + + const res = await rig.post('/phone-number/verify', { phoneNumber: PLAIN.phone, code }, { cookie: rig.plainCookie }); + + expect((await answerOf(res)).code).toBe('ACCOUNT_LOCKED'); + expect(liveRows(), 'no live session was issued').toBe(0); + }, 60_000); +}); + +describe('where the endpoint context does not reach the database hooks (the WebContainer runtime), the request state judges the request', () => { + // WebContainer's `node:async_hooks` does not carry better-auth's endpoint + // context across `await`, so the session hooks run without it there, while + // the request state rides `auth-manager.ts`'s polyfill. Stood up here by + // emptying the endpoint-context store for the request under test only. + const withoutEndpointContext = async (run: () => Promise): Promise => { + const global = (globalThis as any)[Symbol.for('better-auth:global')]; + const saved = global.context.endpointContextAsyncStorage; + global.context.endpointContextAsyncStorage = { run: (_store: unknown, fn: () => unknown) => fn(), getStore: () => undefined }; + try { + return await run(); + } finally { + global.context.endpointContextAsyncStorage = saved; + } + }; + + it.each([ + ['/sign-in/email', (rig: Rig) => rig.post('/sign-in/email', { email: PLAIN.email, password: PASSWORD })], + ['/sign-in/phone-number', (rig: Rig) => rig.post('/sign-in/phone-number', { phoneNumber: PLAIN.phone, password: PASSWORD })], + ] as const)('%s: the correct password on the attempt that reaches the threshold signs in, and clears the count', async (_door, signIn) => { + const rig = await arrange('explicit'); + rig.userRow(PLAIN.email).failed_login_count = THRESHOLD - 1; + const rowsBefore = rig.sessionRows(rig.plainId); + + const res = await withoutEndpointContext(() => signIn(rig)); + + expect(res.status, await res.clone().text()).toBe(200); + expect(rig.sessionRows(rig.plainId)).toBe(rowsBefore + 1); + expect(Number(rig.userRow(PLAIN.email).failed_login_count) || 0).toBe(0); + }, 60_000); + + it('a locked, signed-in account changes its password and ends its other sessions', async () => { + const rig = await arrange('explicit'); + rig.lock(PLAIN.email); + + const res = await withoutEndpointContext(() => + rig.post( + '/change-password', + { currentPassword: PASSWORD, newPassword: 'N3w!Passw0rd-locked-Q9', revokeOtherSessions: true }, + { cookie: rig.plainCookie }, + ), + ); + + expect(res.status, await res.clone().text()).toBe(200); + expect(rig.sessionRows(rig.plainId)).toBe(1); + }, 60_000); + + it.each(['explicit', 'uniform'] as const)('a code door still refuses a locked account (lockoutRefusal: %s)', async (refusal) => { + const rig = await arrange(refusal); + rig.lock(PLAIN.email); + const reference = await passwordSignInAnswer(rig, PLAIN.email); + const code = await smsCode(rig, PLAIN.phone); + const rowsBefore = rig.sessionRows(rig.plainId); + + const res = await withoutEndpointContext(() => rig.post('/phone-number/verify', { phoneNumber: PLAIN.phone, code })); + + expect(await answerOf(res)).toEqual(reference); + expect(rig.sessionRows(rig.plainId), 'no session row was written').toBe(rowsBefore); + }, 60_000); +}); + +describe('the address-change confirmation opened without a session', () => { + const confirmationUrl = async () => { + const { createEmailVerificationToken } = await import('better-auth/api'); + const token = await createEmailVerificationToken(SECRET, PLAIN.email, 'plain-moved@example.com', 3600, { + requestType: 'change-email-verification', + }); + return `/verify-email?token=${token}`; + }; + + it.each(['explicit', 'uniform'] as const)('a locked account gets no session, and its address is not moved (lockoutRefusal: %s)', async (refusal) => { + const rig = await arrange(refusal); + rig.lock(PLAIN.email); + const reference = await passwordSignInAnswer(rig, PLAIN.email); + const rowsBefore = rig.sessionRows(rig.plainId); + + const res = await rig.get(await confirmationUrl()); + + expect(await answerOf(res)).toEqual(reference); + expect(rig.sessionRows(rig.plainId), 'no session row was written').toBe(rowsBefore); + expect(rig.userRow(PLAIN.email).email).toBe(PLAIN.email); + }, 60_000); + + it('CONTROL: an unlocked account confirms the change and is signed in', async () => { + const rig = await arrange(); + const rowsBefore = rig.sessionRows(rig.plainId); + + const res = await rig.get(await confirmationUrl()); + + expect(res.status, await res.clone().text()).toBe(200); + expect(rig.sessionRows(rig.plainId)).toBe(rowsBefore + 1); + }, 60_000); +}); diff --git a/packages/plugins/plugin-auth/src/sign-in-lockout-refusal.ts b/packages/plugins/plugin-auth/src/sign-in-lockout-refusal.ts index a7bd389050a..cdf7367aaa2 100644 --- a/packages/plugins/plugin-auth/src/sign-in-lockout-refusal.ts +++ b/packages/plugins/plugin-auth/src/sign-in-lockout-refusal.ts @@ -84,6 +84,66 @@ export interface SignInAttempt { const signInAttemptState = defineRequestState(() => undefined); +/** The sentence the explicit `403 ACCOUNT_LOCKED` carries. */ +export const ACCOUNT_LOCKED_MESSAGE = + 'This account is temporarily locked after too many failed sign-in ' + + 'attempts. Try again later or ask an administrator to unlock it.'; + +/** + * The answer password sign-in gives a locked account under the deployment's + * `lockoutRefusal`, as an error to throw: `'explicit'` is `403 + * ACCOUNT_LOCKED`; anything else is the answer a wrong password gets at + * `/sign-in/email`, better-auth's own `401 INVALID_EMAIL_OR_PASSWORD`. Its + * sentence is read off the vendor's constant, and its code is the vendor's + * spelling, which `locked-account-every-sign-in-door.test.ts` holds equal to + * the answer `/sign-in/email` itself gives, so the two never part. + */ +export async function lockedAccountRefusal(lockoutRefusal: unknown): Promise { + const { APIError } = await import('better-auth/api'); + if (lockoutRefusal === 'explicit') { + return new APIError('FORBIDDEN', { message: ACCOUNT_LOCKED_MESSAGE, code: 'ACCOUNT_LOCKED' }); + } + const { BASE_ERROR_CODES } = await import('@better-auth/core/error'); + return new APIError('UNAUTHORIZED', { + message: BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD.message, + code: 'INVALID_EMAIL_OR_PASSWORD', + }); +} + +/** + * What the running request is, as the global before-hook read it before the + * endpoint ran (`auth-manager-sign-in-lockout.ts`, `recordLockoutRequest`): + * its endpoint `path`, and `holder`, the account whose live session of record + * (its stored `sys_session` row, unexpired) the request presented, when it + * presented one that could be read. The session-creation refusal reads this + * record, so it judges the same request where the endpoint context does not + * reach the database hooks. + */ +export interface LockoutRequest { + readonly path: string; + readonly holder?: string; +} + +const lockoutRequestState = defineRequestState(() => undefined); + +/** Record what the running request is. Never throws. */ +export async function recordLockoutRequestState(request: LockoutRequest): Promise { + try { + await lockoutRequestState.set(request); + } catch { + /* no request state is open: nothing is recorded, so nothing is exempted */ + } +} + +/** What the running request is, if the before-hook recorded it. Never throws. */ +export async function readLockoutRequestState(): Promise { + try { + return await lockoutRequestState.get(); + } catch { + return undefined; + } +} + /** * Record the gate's verdict for the request that is running (`undefined`: this * attempt has none, whatever an earlier call recorded). `false` when no request diff --git a/packages/runtime/src/dispatcher-error-vocabulary.ts b/packages/runtime/src/dispatcher-error-vocabulary.ts index b64488b7ec1..af90a87ddb0 100644 --- a/packages/runtime/src/dispatcher-error-vocabulary.ts +++ b/packages/runtime/src/dispatcher-error-vocabulary.ts @@ -546,6 +546,24 @@ export const UNREGISTERED_CODE_SITES: readonly UnregisteredCodeSite[] = [ "into a code this repo owns by accident: it is still the vendor's string on the vendor's " + 'wire, and a vendor rename turns the pin red rather than silently minting a local code.', }, + { + code: 'INVALID_EMAIL_OR_PASSWORD', + file: 'packages/plugins/plugin-auth/src/sign-in-lockout-refusal.ts', + shape: 'objlit', + door: 'none', + verdict: 'foreign-vocabulary', + why: + "better-auth 1.7.12's BASE_ERROR_CODES member, the answer its own `/sign-in/email` gives a " + + "wrong password (`dist/api/routes/sign-in.mjs`, `APIError.from('UNAUTHORIZED', " + + "BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD)`). ADR-0069 D2's `lockoutRefusal: 'uniform'` " + + 'answers a locked account at every other door that ends in a session with exactly that ' + + "answer: the sentence is read off the vendor's constant, the code is the vendor's spelling, " + + 'and `locked-account-every-sign-in-door.test.ts` holds the whole answer equal to the one ' + + "`/sign-in/email` gives, so a vendor rename turns that pin red rather than minting a local " + + "code. Raised inside a better-auth endpoint, it leaves as the vendor's own `Response`. " + + 'Registering it would promote a vendor spelling into the platform vocabulary, for the ' + + 'reason the section note above gives.', + }, { code: 'EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION', file: 'packages/plugins/plugin-auth/src/list-user-invitations-verification.ts',