Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/plugin-auth-locked-account-every-sign-in-door.md
Original file line number Diff line number Diff line change
@@ -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

<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export or type changes. What moves is which answer a locked account gets at the sign-in doors, the existing lockout refusal, so there is nothing for a migration to rewrite and no tombstone. -->

**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.
9 changes: 6 additions & 3 deletions content/docs/kernel/runtime-services/audit-service.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions content/docs/permissions/authentication.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
25 changes: 17 additions & 8 deletions packages/plugins/plugin-auth/src/auth-manager-after-hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
33 changes: 22 additions & 11 deletions packages/plugins/plugin-auth/src/auth-manager-before-hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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`).
Expand Down Expand Up @@ -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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading