Skip to content

Commit 9728ab1

Browse files
fix(plugin-auth): answer a locked account like a wrong password, clear the lock on reset, count attempts atomically (#31419)
<!-- claude-projects-attribution: {"github_login":"os-zhuang"} --> _Requested by **Sam** · [project thread](https://claude.ai/code/project/chan_01GsBogozeZG5sdpAARrN7HP?thread=cmsg_01GsBogozeZG5sdpAARrN7HPWpc3NTXt4TesUX4RAeTzBw)_ Closes #28381 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 改了什么:被锁定的账号用密码登录时,得到的回答与密码错误完全相同(状态码、正文、耗时一致);完成密码重置会清除锁定;每次尝试在校验密码之前就原子计数,并发尝试越不过阈值;控制台的登录错误文案说明「多次失败会暂停一段时间,重置密码可立即登录」(全部 11 种控制台语言)。 - 为什么改:原来的 `403 ACCOUNT_LOCKED` 只有真实存在的账号才会出现,等于告诉任何人某个邮箱是否注册过;重置密码后锁还在,用户换了密码仍登不进;并发尝试能越过阈值。 - 风险与回滚:登录路径的行为变化,默认对锁定账号不再给出专门的提示;想保留原来 403 的部署设 `lockoutRefusal: 'explicit'` 即可;绕过 better-auth 端点管道的调用无法给出统一回答,会得到 403 并记一条降级日志。无数据迁移,回滚 = revert 本 PR。cloud 目前在两个平面上自行改写这个回答,本 PR 不动 cloud,改写由 cloud 在之后的 pin 轮次里撤掉。 - 先看:`packages/plugins/plugin-auth/src/auth-manager-sign-in-lockout.ts`(计数与上锁的原子写入、成功清零、密码通过后的拒绝退回计数)、`packages/plugins/plugin-auth/src/sign-in-lockout-refusal.ts`(锁定账号如何得到与密码错误相同的回答)、`packages/plugins/plugin-auth/src/auth-manager-auth-instance.ts`(重置清锁的接线)。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run --maxWorkers=2 src/account-lockout-resolved-account.test.ts src/password-reset-ends-sessions.test.ts`,预期两个文件全部通过。 - 需要你做的:无,席位落地。 ## What changes - **A locked account is answered like a wrong password.** A password sign-in for an account the ADR-0069 D2 lockout holds is now refused `401 INVALID_EMAIL_OR_PASSWORD`, with the same body and the same password-check cost a wrong password gets. The lock still holds against the correct password, and the account's `login_failed` audit row still records the reason `ACCOUNT_LOCKED`. A deployment that wants the explicit answer sets the new `AuthManagerOptions.lockoutRefusal: 'explicit'` (default `'uniform'`) and is answered `403 ACCOUNT_LOCKED` as before. A sign-in that runs outside better-auth's endpoint pipeline cannot be answered uniformly; it is refused `403 ACCOUNT_LOCKED` and logged as a degradation, so the lock still holds. - **A completed password reset clears the lock.** A reset through the emailed link or the phone code clears `failed_login_count` and `locked_until`, so the new password signs in at once. An incomplete reset clears nothing. The second factor's own lock is not cleared by a reset; the administrator's Unlock action still clears both. - **Concurrent attempts cannot exceed the threshold.** Each attempt is counted before its password is checked, in one atomic write that also stamps the lock when the count reaches the threshold. A successful sign-in still clears the count, and a refusal that comes after the password passed (an organization's IP list, a ban, an unverified address) still neither counts nor clears. - **The console names the pause.** `auth.login.errors.invalidCredentials` now says repeated failures pause sign-in for a while and that resetting the password signs in right away, in all 11 console locales (`en`, `zh-Hans`, `zh-Hant`, `ja`, `ar`, `de`, `es`, `fr`, `ko`, `pt-BR`, `ru`), so `check:i18n-drift` holds. **Clause-② for the opt-in key.** `lockoutRefusal` is a new optional key on `AuthManagerOptions`, the constructor options of the published `@objectstack/plugin-auth`. It widens what that package accepts, so the line reads `yes (widening)`. It is not a settings key and nothing in `packages/spec` changes, so `Metadata-protocol` stays `none` and the changeset is `patch`. ## Tests - `account-lockout-resolved-account.test.ts` (real sign-in endpoint): a locked account answers exactly what a wrong password answers, the correct password included (status, body, and one password derivation each, counted with the scrypt testkit for an open account's wrong password, a locked account's correct and wrong password, and an unknown account); input refusals match too; a locked refusal opens no session and writes the `ACCOUNT_LOCKED` audit row; `lockoutRefusal: 'explicit'` answers `403 ACCOUNT_LOCKED`; of 30 concurrent wrong passwords, exactly the threshold reach the password check, the rest meet the lock, one `account_locked` row is written, and the lock then holds against the correct password. - `password-reset-ends-sessions.test.ts` (real ObjectQL + sqlite): a reset by emailed link and by phone code each clear the lock and the new password signs in at once; an incomplete reset leaves the lock. - `auth-manager.test.ts`: the lockout unit block, rewritten for the new gate (no-op at threshold 0, the uniform and explicit refusals, the refusal and its log line outside the pipeline, a locked attempt counted without moving its expiry, the compare-and-set write below and at the threshold, a re-read after a lost write, success clearing). Its fake engine now opens `update` with `assertEngineUpdateDispatch`, so every write the block makes is one the real engine accepts. - `auth-account-event-audit.test.ts` and `durability-swallow-repair.test.ts`: updated to the uniform answer and the renamed gate. - NULL counter (seat review): `password-reset-ends-sessions.test.ts` › "ADR-0069 D2: an account whose failed_login_count is NULL is counted and cleared through ObjectQL + SqlDriver" (better-sqlite3; the column is read back as NULL first) and `account-lockout-resolved-account.test.ts` › "ADR-0069 D2: an account whose failed_login_count is NULL or absent is counted and cleared like one at 0" (in-memory, NULL and absent): the correct password signs in and clears the counter to 0; a wrong password counts to 1 and the correct one still signs in after it. The compare-and-set matches a NULL counter on both engines, so no normalisation was needed. SqlDriver compiles every dialect through one filter compiler; only sqlite was run. Reverse verification: with the implementation committed, the plugin-auth source files were restored from `eff90af6` and the two endpoint-level files run against them: 10 failed and 25 passed (the uniform answer under every spelling and input, the reset clearing in all three cases, and the concurrency pin). `git checkout HEAD -- …` restored the implementation, with `git diff HEAD` empty, and both files are green again. ## Acceptance notes - **The opt-in is config-only.** `lockoutRefusal` is read from the constructor options; there is no settings key and no UI for it. - **cloud is untouched.** cloud rewrites this answer on both planes today; dropping that rewrite is a cloud card after a pin round carries this change. - **Where the concurrency pin runs.** The 30-attempt pin runs on the in-memory engine, whose `update` honours `where` + `multi` and returns the row count; the reset pins run on real ObjectQL + sqlite. - **Files outside `plugin-auth/**` and the console copy.** Three generated or ratchet files move with this diff, each written by its own tool: `content/docs/permissions/tenant-audit-census.mdx` and `docs/audits/2026-08-tenant-audit-write-call-sites.counts.md` (`node scripts/tenant-audit-census.mjs --write`; two `sys_user` write sites now read as a typed engine receiver, so the page's two hand-written erased-receiver figures go from 64 to 62, with the total unchanged at 270), and `scripts/engine-double-contract.pinned.json` (`check-engine-double-contract.mjs --write`; one more pinned fake in `auth-manager.test.ts`). The seat agreed to the census page before it was written. - **Test-typecheck debt shrank.** Typing the lockout block's engine mock removed 16 recorded test type errors in `auth-manager.test.ts`; `test-typecheck-debt.json` was re-recorded downward with the package's own `gen:test-typecheck-debt`. - **The wrong-password code is not in the ADR-0112 ledger.** `INVALID_EMAIL_OR_PASSWORD` is better-auth's code and reaches the wire unregistered. Stamping it from plugin-auth would need a ledger row in `packages/spec`, which this card does not touch, so the one path that would have stamped it (outside the endpoint pipeline) uses the registered `ACCOUNT_LOCKED` instead. Registering the code would let that path answer uniformly too; left for the seat to schedule. - **Body order.** The two attribution lines the session adds sit above `Closes #28381`. ## Verification The readings below were taken at head `42421e44`. At head `00c88e7e` (NULL-counter tests and the 7 locale packs), under the lock: plugin-auth typecheck OK and 240/240 files, 4267 tests; ui i18n, console auth, `check-i18n-call-site-keys` and `check-i18n-en-drift`: 115/115 files, 2094 tests; the changeset, engine-double, NUL and i18n-drift gates green. Wall-clock figures come from a shared box. <details><summary>plugin-auth build, typecheck and full suite; console copy tests</summary> `bash scripts/pm/os-verify-lock.sh -c 'pnpm --filter @objectstack/plugin-auth build && pnpm --filter @objectstack/plugin-auth typecheck && pnpm --filter @objectstack/plugin-auth exec vitest run --maxWorkers=2 && cd ui && npx vitest run --maxWorkers=2 packages/i18n/ packages/app-shell/src/console/auth/ scripts/__tests__/check-i18n-call-site-keys.test.ts --testTimeout=120000'` ``` check:test-typecheck: OK — 10 file(s) / 72 error(s) / 23 pinned signature(s) held in test-typecheck-debt.json Test Files 240 passed (240) Tests 4261 passed | 10 skipped (4271) Test Files 114 passed (114) Tests 2029 passed | 13 skipped (2042) os-verify-lock: VERDICT command-exit 0 ``` </details> <details><summary>Derived gates</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 116 commands for this change set. They ran with 4 more whose rosters sit beside touched paths (`check:changeset-fixed`, `check:error-code-casing`, `check:filter-alias-parity`, `check:error-status-conformance`), and each exit code was captured before any pipe. - 119 of 120 exited 0. - `pnpm --dir ui exec vitest run scripts/` exited 1 because four tests in `check-i18n-call-site-keys.test.ts` and `check-vi-mock-specifiers.test.ts` each hit "Test timed out in 15000ms" while three gates ran at once. Run under the lock with `--testTimeout=180000`, those two files pass 187/187. - `node scripts/pm/dispatch-gates.mjs --ran`: 116 derived families accounted for, 0 not measured. - `node scripts/check-nul-bytes.mjs`: OK. Five gates needed a change on this branch. `check:test-typecheck`: debt re-recorded downward. `check:tenant-audit-census`: page regenerated. `check:engine-double-contract`: the ledger records one more pinned fake. `check:dispatcher-error-vocabulary` and `check:query-options-erasure`: code fixed, no ledger touched. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QUs3BtDNDGBRyYSpvMa9Qi)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QUs3BtDNDGBRyYSpvMa9Qi <!-- signed: repo:cloud#3 · os-zhuang · session_01QUs3BvRcDHXqRU4TSVE4u6 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent b6e6545 commit 9728ab1

28 files changed

Lines changed: 1099 additions & 206 deletions
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
'@object-ui/i18n': patch
4+
'@object-ui/app-shell': patch
5+
---
6+
7+
fix(plugin-auth): a locked account is answered like a wrong password, a password reset clears the lock, and attempts are counted before they are checked
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: none
11+
12+
- **A locked account answers like a wrong password.** A password sign-in for an account the ADR-0069 D2 lockout holds was refused `403 ACCOUNT_LOCKED`. Only an account that exists can be locked, so that answer told anyone who typed an address whether it has an account. It is now refused exactly as a wrong password is: `401 INVALID_EMAIL_OR_PASSWORD`, the same body, and the same password check before the answer. The lock still holds against the correct password, and the account's `login_failed` audit row still records the reason `ACCOUNT_LOCKED`. A deployment that wants the explicit answer sets the new `AuthManagerOptions.lockoutRefusal: 'explicit'` (default `'uniform'`), and is answered `403 ACCOUNT_LOCKED` as before. A sign-in reached outside better-auth's endpoint pipeline cannot be answered uniformly; it is refused `403 ACCOUNT_LOCKED` and logged as a degradation.
13+
- **A completed password reset clears the lock.** A reset through the emailed link or the phone code now clears `failed_login_count` and `locked_until`, so the new password signs in at once. Before, the lock stayed until it ran out or an administrator unlocked it. The second factor's own lock is not cleared by a reset; the administrator's Unlock action still clears both.
14+
- **Attempts that arrive together cannot outrun the lock.** Each attempt is now counted before its password is checked, in one atomic write that also sets the lock when the count reaches the threshold, so at most the threshold's number of attempts reach the password check before the lock holds. A successful sign-in still clears the count, and a refusal that comes after the password passed (an organization's IP list, a ban, an unverified address) still neither counts nor clears. Attempts on a locked account are now counted too; the lock's expiry does not move.
15+
- **The console names the pause.** The sign-in refusal copy (`auth.login.errors.invalidCredentials`) now says that repeated failures pause sign-in for a while and that resetting the password signs in right away, in all 11 console locales (`en`, `zh-Hans`, `zh-Hant`, `ja`, `ar`, `de`, `es`, `fr`, `ko`, `pt-BR`, `ru`).

‎content/docs/permissions/tenant-audit-census.mdx‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ what moved this page's population from 225 to 227; nothing about the two sites
9393
changed, only whether this instrument could see them.
9494

9595
**The expensive failure direction is a keyword.** Sites whose receiver the author
96-
typed `any` have no type to read, and there are 64 of them — just over a fifth
96+
typed `any` have no type to read, and there are 62 of them — just over a fifth
9797
of the population, concentrated in exactly the seed and bootstrap paths this
9898
control exists for. Scoring an unreadable receiver as "not an engine" would have
9999
dropped every one of them silently, with a clean exit and a smaller number that
@@ -210,7 +210,7 @@ be stated is what this instrument counts, which is written above and re-runnable
210210
at any commit.
211211

212212
Two structural facts do plausibly widen this reading against any hand or regex
213-
one, and both are counted in the generated tables below: the 64 sites reached
213+
one, and both are counted in the generated tables below: the 62 sites reached
214214
through an erased (`any`) receiver, and the 69 that name their object through a
215215
`const` rather than inline. An instrument that read either the way a person does
216216
would report a smaller number and would not say so.
@@ -249,8 +249,8 @@ cannot read, and they are neither in nor out.
249249

250250
| how the instrument reached the site | count |
251251
| :--- | ---: |
252-
| receiver carried a readable engine type | 206 |
253-
| receiver erased, placed by the object NAME | 54 |
252+
| receiver carried a readable engine type | 208 |
253+
| receiver erased, placed by the object NAME | 52 |
254254
| receiver erased, placed by an `object: string` PARAMETER | 5 |
255255
| receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 |
256256

@@ -307,13 +307,13 @@ holds still. They are required to be HERE and to say WHEN they were true;
307307
their values are not compared. The reasoning, and the measurement behind it,
308308
are in `scripts/check-tenant-audit-census.mjs`.
309309

310-
Measured on 2026-11-07 at `9dd4abeaa`.
310+
Measured on 2026-11-08 at `759f4daa0`.
311311

312312
| corpus scale (not enforced) | count |
313313
| :--- | ---: |
314-
| tracked non-test sources scanned | 1057 |
315-
| engine-shaped types recognised | 113 |
314+
| tracked non-test sources scanned | 1060 |
315+
| engine-shaped types recognised | 114 |
316316
| declared objects in the registry | 131 |
317-
| same-named calls subtracted as non-engine | 239 |
317+
| same-named calls subtracted as non-engine | 243 |
318318

319319
{/* END GENERATED: tenant-audit-census */}

‎docs/audits/2026-08-tenant-audit-write-call-sites.counts.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,14 +90,14 @@ holds still. They are required to be HERE and to say WHEN they were true;
9090
their values are not compared. The reasoning, and the measurement behind it,
9191
are in `scripts/check-tenant-audit-census.mjs`.
9292

93-
Measured on 2026-11-07 at `9dd4abeaa`.
93+
Measured on 2026-11-08 at `759f4daa0`.
9494

9595
| corpus scale (not enforced) | count |
9696
| :--- | ---: |
97-
| tracked non-test sources scanned | 1057 |
98-
| engine-shaped types recognised | 113 |
97+
| tracked non-test sources scanned | 1060 |
98+
| engine-shaped types recognised | 114 |
9999
| declared objects in the registry | 131 |
100-
| same-named calls subtracted as non-engine | 239 |
100+
| same-named calls subtracted as non-engine | 243 |
101101

102102
## Every site
103103

‎packages/plugins/plugin-auth/src/account-lockout-resolved-account.test.ts‎

Lines changed: 161 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,15 @@ async function outcome(res: Response): Promise<{ status: number; code: string |
107107
}
108108

109109
const REFUSED = { status: 401, code: 'INVALID_EMAIL_OR_PASSWORD' };
110-
const LOCKED = { status: 403, code: 'ACCOUNT_LOCKED' };
110+
/**
111+
* A locked account's refusal: the wrong-password answer itself (ADR-0069 D2,
112+
* `sign-in-lockout-refusal.ts`). The cases below tell a lock from a wrong
113+
* password by submitting the CORRECT password, and by the reason the account's
114+
* `login_failed` row carries.
115+
*/
116+
const LOCKED = REFUSED;
117+
/** The explicit refusal a deployment opts into with `lockoutRefusal: 'explicit'`. */
118+
const LOCKED_EXPLICIT = { status: 403, code: 'ACCOUNT_LOCKED' };
111119

112120
function accountRow(engine: any): any {
113121
const row = ((engine.tables.get('sys_user') ?? []) as any[]).find((r) => r.email === EMAIL);
@@ -359,3 +367,155 @@ describe('ADR-0069 D2: a correct password refused for a ban or an unverified add
359367
expect(isLocked(accountRow(engine))).toBe(true);
360368
});
361369
});
370+
371+
/** Status, headers that describe the body, and the body itself, byte for byte. */
372+
async function wholeAnswer(res: Response): Promise<{ status: number; contentType: string | null; body: string }> {
373+
return { status: res.status, contentType: res.headers.get('content-type'), body: await res.clone().text() };
374+
}
375+
376+
/** The answer to `send`, and how many password derivations it ran (the work behind the answer). */
377+
async function measured(send: () => Promise<Response>) {
378+
const before = scrypt.counts();
379+
const answer = await wholeAnswer(await send());
380+
const after = scrypt.counts();
381+
return { answer, derivations: after.derived + after.answered - before.derived - before.answered };
382+
}
383+
384+
describe('ADR-0069 D2: a locked account is answered exactly as a wrong password is', () => {
385+
it('the same status and body, after the same one password check, whatever password it is sent', async () => {
386+
const { engine, manager } = deployment();
387+
await signUp(manager);
388+
const wrongWhileOpen = await measured(() => signIn(manager, EMAIL, WRONG_PASSWORD));
389+
const unknown = await measured(() => signIn(manager, 'nobody.lockout-account@example.com', WRONG_PASSWORD));
390+
for (let i = 1; i < THRESHOLD; i++) await signIn(manager, EMAIL, WRONG_PASSWORD);
391+
expect(isLocked(accountRow(engine))).toBe(true);
392+
393+
const correctWhileLocked = await measured(() => signIn(manager, EMAIL, PASSWORD));
394+
const wrongWhileLocked = await measured(() => signIn(manager, EMAIL, WRONG_PASSWORD));
395+
396+
expect(wrongWhileOpen.answer.status).toBe(401);
397+
expect(JSON.parse(wrongWhileOpen.answer.body)).toMatchObject({ code: 'INVALID_EMAIL_OR_PASSWORD' });
398+
for (const locked of [correctWhileLocked, wrongWhileLocked]) {
399+
expect(locked.answer).toEqual(wrongWhileOpen.answer);
400+
expect(locked.derivations).toBe(wrongWhileOpen.derivations);
401+
}
402+
// …and the same as an address that names no account at all.
403+
expect(unknown.answer).toEqual(wrongWhileOpen.answer);
404+
expect(unknown.derivations).toBe(wrongWhileOpen.derivations);
405+
expect(wrongWhileOpen.derivations).toBe(1);
406+
});
407+
408+
it('a request the endpoint refuses before any password check is refused the same way for a locked account', async () => {
409+
const { engine, manager } = deployment();
410+
await signUp(manager);
411+
const malformed = [
412+
{ email: EMAIL, password: 'x'.repeat(4096) },
413+
{ email: EMAIL },
414+
];
415+
const open = [];
416+
for (const body of malformed) open.push(await wholeAnswer(await post(manager, '/sign-in/email', body)));
417+
// Those refusals counted as attempts; reset the count before locking.
418+
accountRow(engine).failed_login_count = 0;
419+
for (let i = 0; i < THRESHOLD; i++) await signIn(manager, EMAIL, WRONG_PASSWORD);
420+
expect(isLocked(accountRow(engine))).toBe(true);
421+
422+
for (const [i, body] of malformed.entries()) {
423+
const answer = await wholeAnswer(await post(manager, '/sign-in/email', body));
424+
expect(answer.status, JSON.stringify(Object.keys(body))).toBeGreaterThanOrEqual(400);
425+
expect(answer, JSON.stringify(Object.keys(body))).toEqual(open[i]);
426+
}
427+
});
428+
429+
it('no session is issued and the account records the lock as the reason', async () => {
430+
const { engine, manager, events } = deployment();
431+
await signUp(manager);
432+
for (let i = 0; i < THRESHOLD; i++) await signIn(manager, EMAIL, WRONG_PASSWORD);
433+
events.length = 0;
434+
435+
const res = await signIn(manager, EMAIL, PASSWORD);
436+
expect(await outcome(res)).toEqual(REFUSED);
437+
expect(res.headers.getSetCookie?.() ?? []).toEqual([]);
438+
expect(events.some((e) => e.action === 'login')).toBe(false);
439+
expect(accountEvents(events)).toEqual([
440+
expect.objectContaining({
441+
action: 'login_failed',
442+
userId: String(accountRow(engine).id),
443+
context: { endpoint: '/sign-in/email', reason: 'ACCOUNT_LOCKED' },
444+
}),
445+
]);
446+
});
447+
});
448+
449+
describe("ADR-0069 D2: a deployment that opts in answers a locked account 403 ACCOUNT_LOCKED", () => {
450+
it('the correct password is refused with the explicit code, and the account records the lock', async () => {
451+
const { engine, manager, events } = deployment({ lockoutRefusal: 'explicit' });
452+
await signUp(manager);
453+
for (let i = 0; i < THRESHOLD; i++) {
454+
expect(await outcome(await signIn(manager, EMAIL, WRONG_PASSWORD))).toEqual(REFUSED);
455+
}
456+
expect(isLocked(accountRow(engine))).toBe(true);
457+
const lockedUntil = new Date(accountRow(engine).locked_until).getTime();
458+
events.length = 0;
459+
460+
expect(await outcome(await signIn(manager, EMAIL, PASSWORD))).toEqual(LOCKED_EXPLICIT);
461+
expect(await outcome(await signIn(manager, SPELLINGS[0], WRONG_PASSWORD))).toEqual(LOCKED_EXPLICIT);
462+
expect(events.some((e) => e.action === 'login')).toBe(false);
463+
expect(accountEvents(events).map((e) => e.context?.reason)).toEqual(['ACCOUNT_LOCKED', 'ACCOUNT_LOCKED']);
464+
expect(new Date(accountRow(engine).locked_until).getTime()).toBe(lockedUntil);
465+
// An address that names no account is still a wrong password.
466+
expect(await outcome(await signIn(manager, 'nobody.lockout-account@example.com', PASSWORD))).toEqual(REFUSED);
467+
});
468+
});
469+
470+
describe('ADR-0069 D2: attempts that arrive together reach the credential check at most threshold times', () => {
471+
it('of many concurrent wrong passwords, exactly the threshold are checked and the rest meet the lock', async () => {
472+
const { engine, manager, events } = deployment();
473+
await signUp(manager);
474+
events.length = 0;
475+
const CONCURRENT = 30;
476+
477+
const answers = await Promise.all(
478+
Array.from({ length: CONCURRENT }, () => signIn(manager, EMAIL, WRONG_PASSWORD).then(outcome)),
479+
);
480+
481+
expect(answers).toEqual(answers.map(() => REFUSED));
482+
expect(isLocked(accountRow(engine))).toBe(true);
483+
expect(Number(accountRow(engine).failed_login_count)).toBeGreaterThanOrEqual(THRESHOLD);
484+
const failed = accountEvents(events).filter((e) => e.action === 'login_failed');
485+
expect(failed.filter((e) => e.context?.reason === 'INVALID_EMAIL_OR_PASSWORD')).toHaveLength(THRESHOLD);
486+
expect(failed.filter((e) => e.context?.reason === 'ACCOUNT_LOCKED')).toHaveLength(CONCURRENT - THRESHOLD);
487+
expect(accountEvents(events).filter((e) => e.action === 'account_locked')).toHaveLength(1);
488+
// The lock holds against the correct password.
489+
expect(await outcome(await signIn(manager, EMAIL, PASSWORD))).toEqual(LOCKED);
490+
});
491+
});
492+
493+
describe('ADR-0069 D2: an account whose failed_login_count is NULL or absent is counted and cleared like one at 0', () => {
494+
const blank: Array<[string, (row: any) => void]> = [
495+
['NULL', (row) => { row.failed_login_count = null; }],
496+
['absent', (row) => { delete row.failed_login_count; }],
497+
];
498+
for (const [label, clearCounter] of blank) {
499+
it(`${label}: the correct password signs in, and the counter is cleared to 0`, async () => {
500+
const { engine, manager } = deployment();
501+
await signUp(manager);
502+
clearCounter(accountRow(engine));
503+
const res = await signIn(manager, EMAIL, PASSWORD);
504+
expect(res.status, await res.clone().text()).toBe(200);
505+
expect(accountRow(engine).failed_login_count).toBe(0);
506+
expect(isLocked(accountRow(engine))).toBe(false);
507+
});
508+
509+
it(`${label}: a wrong password counts to 1, and the correct one still signs in after it`, async () => {
510+
const { engine, manager } = deployment();
511+
await signUp(manager);
512+
clearCounter(accountRow(engine));
513+
expect(await outcome(await signIn(manager, EMAIL, WRONG_PASSWORD))).toEqual(REFUSED);
514+
expect(accountRow(engine).failed_login_count).toBe(1);
515+
expect(isLocked(accountRow(engine))).toBe(false);
516+
const res = await signIn(manager, EMAIL, PASSWORD);
517+
expect(res.status, await res.clone().text()).toBe(200);
518+
expect(accountRow(engine).failed_login_count).toBe(0);
519+
});
520+
}
521+
});

‎packages/plugins/plugin-auth/src/auth-account-event-audit.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -225,9 +225,10 @@ describe('reaching the lockout threshold records one account_locked event', () =
225225
for (let i = 0; i < 3; i++) await signIn(manager, EMAIL, WRONG_PASSWORD);
226226
events.length = 0;
227227

228-
// Refused by the lock even with the right password.
228+
// Refused by the lock even with the right password — with the answer a
229+
// wrong password gets; the ledger row still names the lock.
229230
const res = await signIn(manager, EMAIL, PASSWORD);
230-
expect(res.status).toBe(403);
231+
expect(res.status).toBe(401);
231232

232233
expect(accountEvents(events)).toEqual([
233234
{

‎packages/plugins/plugin-auth/src/auth-manager-after-hook.ts‎

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,9 @@ export interface AfterHookHost {
6868
externalDirectoryDoorDeps: AuthManager['externalDirectoryDoorDeps'];
6969
isEmailDeliveryLive: AuthManager['isEmailDeliveryLive'];
7070
recordPasswordHistory: AuthManager['recordPasswordHistory'];
71-
recordSignInOutcome: AuthManager['recordSignInOutcome'];
7271
roleChangeGrantDeps: AuthManager['roleChangeGrantDeps'];
7372
sendChangeEmailNotice: AuthManager['sendChangeEmailNotice'];
73+
settleSignInAttempt: AuthManager['settleSignInAttempt'];
7474
stampLastLogin: AuthManager['stampLastLogin'];
7575
stampPasswordChangedAt: AuthManager['stampPasswordChangedAt'];
7676
}
@@ -191,10 +191,12 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) {
191191
// ── ADR-0069 D2: account lockout (counter) ──────────────────
192192
// better-auth catches an INVALID_EMAIL_OR_PASSWORD APIError and runs
193193
// the after-hook with it on `ctx.context.returned`; a success leaves
194-
// the session payload there. Count failures, reset on success.
195-
// A refusal `refusedAfterTheCredential` names is neither: the password
196-
// passed and a policy then refused the sign-in, so the counter is left
197-
// as it stands. Its `login_failed` row is still written below.
194+
// the session payload there. The gate stamped this attempt as a
195+
// failure before the check; settle that stamp now: a success clears
196+
// the counter, a failure keeps it. A refusal `refusedAfterTheCredential`
197+
// names is neither: the password passed and a policy then refused the
198+
// sign-in, so the stamp is handed back and the counter is left as it
199+
// stood. Its `login_failed` row is still written below.
198200
if (ctx?.path === SIGN_IN_EMAIL_PATH) {
199201
const email = typeof ctx?.body?.email === 'string' ? ctx.body.email : '';
200202
if (email) {
@@ -205,13 +207,20 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) {
205207
} catch {
206208
succeeded = !(ctx?.context?.returned instanceof Error);
207209
}
208-
const lockStamped = !succeeded && await refusedAfterTheCredential(ctx?.context?.returned)
209-
? undefined
210-
: await this.recordSignInOutcome(email, succeeded);
210+
const settlement = await this.settleSignInAttempt(
211+
email,
212+
succeeded
213+
? 'succeeded'
214+
: await refusedAfterTheCredential(ctx?.context?.returned)
215+
? 'refused-after-credential'
216+
: 'refused',
217+
);
211218
// A refused sign-in writes `login_failed`, and the one that
212219
// stamped the lockout also writes `account_locked`. A successful
213-
// one is recorded as `login` by the session hook, unchanged.
214-
if (!succeeded) await this.auditRefusedSignIn(ctx, email, lockStamped);
220+
// one is recorded as `login` by the session hook, unchanged. A
221+
// sign-in refused because the account is locked had its row
222+
// written by the gate, with the lock as its reason.
223+
if (!succeeded && !settlement.refusedByLock) await this.auditRefusedSignIn(ctx, email, settlement);
215224
if (succeeded) {
216225
const uid = ctx?.context?.returned?.user?.id;
217226
// [ADR-0069 TL;DR 6] The cap of the organization the new session
@@ -227,7 +236,7 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) {
227236
);
228237
}
229238
// ADR-0069 D7 — login audit: stamp last_login_at/ip on success.
230-
// Independent of lockout config (recordSignInOutcome no-ops when
239+
// Independent of lockout config (settleSignInAttempt no-ops when
231240
// lockout is off). The IP is the address `handleRequest`
232241
// established for this request by the client-address trust rule,
233242
// the same address the D5 allow-list judged; none when it was

0 commit comments

Comments
 (0)