Skip to content

Commit c1ec627

Browse files
fix(auth): a TOTP code is accepted once (#34617)
Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:`/two-factor/verify-totp` 收下的每个 TOTP 验证码按「用户 + 密钥」记住它所在的时间步,在验证窗口内同一码再出现即拒收;时间步不晚于最近一次收下的码也拒收。拒收答复与错码完全相同(`401 INVALID_CODE`,同样计入挑战次数与账户锁定)。 - **为什么改**:规则是「TOTP 码只收一次」(RFC 6238 §5.2),跨登录挑战、跨客户端、跨节点、会话通道都成立。 - **风险与回滚**:同一 30 秒内用 TOTP 登录两次的客户端,第二次要用下一时间步的码;记账写 `sys_verification`,写失败则本次验证失败(不放行)。回滚即还原本 PR:接线只有 `auth-manager-auth-instance.ts` 一行,余为新模块。 - **先看**:`packages/plugins/plugin-auth/src/totp-code-single-use.ts` 的 `refuseSpentTotpStep`(预占与回填);`auth-manager-auth-instance.ts` 的接线行;`packages/qa/dogfood/test/totp.ts` 的 `freshTotp`。 - **两分钟验证**:依赖构建后跑 `pnpm --filter @objectstack/plugin-auth exec vitest run src/totp-code-single-use.test.ts`,预期 15 个用例全部通过。 - **需要你做的**:无,席位落地。 ## What changes **Rule: a TOTP code is accepted once.** A code that `/two-factor/verify-totp` accepts is remembered for its user and secret for as long as the verifier's window could still accept it. Any later presentation is refused, on another sign-in challenge, from another client, on another node and on the session lane (RFC 6238 §5.2). A code from a time step at or before the last accepted step is refused too. The refusal is the answer a wrong code gets, and it counts toward the challenge's attempt budget and the account lockout the same way. A code from a later step is accepted. - `packages/plugins/plugin-auth/src/totp-code-single-use.ts` (new): one before-hook on the two-factor plugin, matched on `/two-factor/verify-totp`, the one route that takes a TOTP code. It covers the enrolment confirmation, the sign-in challenge and the session-lane check. It resolves the user in the vendor's own order (session, then the pending challenge), finds the step the code belongs to inside the vendor's window, and reserves that step in `sys_verification` through better-auth's own single-use reservation (`internalAdapter.reserveVerificationValue`, a primary key derived from user, secret digest and step). It also reserves the earlier steps of the window. When a step is already held, the vendor is handed a code that cannot verify, so its own wrong-code path answers. The build fails when the two-factor plugin serves routes but none at `/two-factor/verify-totp`. - `packages/plugins/plugin-auth/src/auth-manager-auth-instance.ts`: one line wires the hook onto the plugin list the instance is built from. - `packages/plugins/plugin-auth/src/totp-code-single-use.test.ts` (new): the door pins and the seam pins below. - `packages/qa/dogfood/test/totp.ts`: `freshTotp()`, which hands out a code from a later step than the last one it handed out for the secret, and waits for the clock when that step is not inside the window yet. `two-factor-lockout.dogfood.test.ts` signs in with it, so its cases that need a later step carry longer timeouts. - `.changeset/totp-code-accepted-once.md`: `@objectstack/plugin-auth` patch. No spec, schema, exported signature or route change. None of the files the open draft PR #34333 holds is touched. ## Tests `src/totp-code-single-use.test.ts`, real stack: `AuthManager` over `ObjectQL` + `@objectstack/driver-sql` on better-sqlite3 `:memory:`, requests through `AuthManager.handleRequest`, the clock pinned (`Date` only) inside a step. Door pins (8): 1. a code accepted at one sign-in challenge is refused at another client's challenge (`401 INVALID_CODE`, no session cookie, no session row); 2. a code spent confirming the enrolment is refused at the sign-in challenge; 3. a code accepted on the session lane is refused on the session lane again; 4. a code from a step before the last accepted step is refused; 5. a code from a later step is accepted, at the challenge that refused a spent code; 6. a spent code gets the answer, and the failure count, a wrong code gets; 7. two presentations of one code that arrive together admit exactly one; 8. the vendor accepts no step outside the window whose steps are reserved. Seam pins (7): HOTP equals the RFC 4226 Appendix D values; the matched step is the newest step of the window; a step is reserved per user and per secret; the build refuses a two-factor plugin whose routes leave out the door; one before-hook is appended, matched on the door, once; a two-factor plugin that serves no route gets no hook; a list with no two-factor plugin is untouched. Ablation (the wiring line replaced on disk through `scripts/ablation-replace.mjs`): door pins 7 of 8 red, then restored (blob equal to `HEAD`, `git diff HEAD` empty). Pin 8 stays green by design: it pins the vendor's window. ## Acceptance notes - `/two-factor/enable`, `/two-factor/disable` and `/two-factor/get-totp-uri` take a password, and `/two-factor/verify-otp` and `/two-factor/verify-backup-code` take codes that are not TOTP codes. `auth-route-ledger.ts` pins the published route set, so a new code-taking route is a reviewed ledger change. - A reservation is keyed by user and a truncated SHA-256 digest of the secret, so a re-enrolled secret's first code may share a step with the old secret's last one. - `auth-manager.test.ts` mocks the two-factor plugin with no routes. The build accepts a plugin object that serves no route (it takes no code), so that file needed no edit. - The reservation conflict is logged by the SQL engine at `warn` (`Insert operation failed`), as for every better-auth reservation. ## Verification Head at opening: `3f95e6b9e5`. The branch merged `main` once (`c173ccc489`). Every run below went through `scripts/pm/os-verify-lock.sh`, and each names the commit it was taken at. <details><summary>Door and seam pins</summary> - `vitest run src/totp-code-single-use.test.ts` at `e63319413e`: `Tests 14 passed (14)`, VERDICT command-exit 0. - `vitest run src/totp-code-single-use.test.ts src/auth-manager.test.ts` at `dbdfc4dd0e` (the 15th pin added): `Test Files 2 passed (2)`, `Tests 352 passed (352)`, VERDICT command-exit 0. </details> <details><summary>Ablation</summary> At `e63319413e`, through `scripts/ablation-replace.mjs` with an EXIT/INT/TERM restore trap: the wiring line in `auth-manager-auth-instance.ts` replaced on disk (anchor 1 to 0, blob changed). Door pins: 7 of 8 red (pin 8 pins the vendor's window and stays green by design), seam pins green. Then restored: blob equal to `HEAD`, `git diff HEAD` empty. </details> <details><summary>plugin-auth full suite, build, typecheck</summary> - Full suite at `e63319413e`: `Test Files 280 passed`, 1 failed: `auth-manager.test.ts` (10 cases), whose two-factor mock serves no route. `dbdfc4dd0e` builds such a plugin object as it is, and that file is green above. - `turbo run build --filter=@objectstack/plugin-auth...` then `pnpm --filter @objectstack/plugin-auth typecheck` at `c173ccc489`: VERDICT command-exit 0 (`tsc --noEmit`, the examples project, and `check:test-typecheck` OK). </details> <details><summary>Derived gates</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` at `c173ccc489`: 73 commands, each run with its exit code captured before any pipe; `--ran` reconciliation: 73 accounted, 71 run, 2 NOT MEASURED. - 71 exit 0. `check:dispatcher-error-vocabulary` read the forced body field as an error-code stamp at `c173ccc489` (exit 1); `3f95e6b9e5` names the field, and the gate exits 0 there. - NOT MEASURED (exit 3, prerequisite): `check:dual-build-cjs-loads` (needs every workspace package built) and `check:type-check-debt` (its re-measure build never got the lock). Both run in CI. </details> <details><summary>Not measured here</summary> - The plugin-auth full suite at the final head, and the two-factor dogfood files (`two-factor-lockout`, `two-factor-backup-code-reveal`): the verify lock was held by another worktree's full dogfood battery for over 55 minutes, and these runs were still queued at opening. `Test Core` and the queue's dogfood shards run them. - `freshTotp()` step choice was checked by a scratch simulation under a fake clock (8 uses: every code from a later step than the last, inside the verifier's window when handed out and 5 s later; waits of 0, 0, 0, 12, 28, 28, 28, 28 s). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 6302c2c commit c1ec627

6 files changed

Lines changed: 746 additions & 14 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(auth): a TOTP code is accepted once
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A TOTP code that `/api/v1/auth/two-factor/verify-totp` accepts is remembered for its user and secret for as long as the verifier's window could still accept it. Any later presentation of that code is refused, whether it arrives on another sign-in challenge, from another client, on another server node or on the session lane (RFC 6238 §5.2). A code from a time step at or before the last accepted step for that user and secret is refused too. A refused code gets the answer a wrong code gets (`401 INVALID_CODE`) and counts toward the challenge's attempt budget and the account lockout in the same way. The same rule covers the code that confirms an enrolment, and every later code. A code from a later time step is accepted as before.
11+
12+
The spent steps are kept as short-lived `sys_verification` rows, one per step, reserved under a primary key derived from the user, the secret and the step. Two presentations of one code that arrive together therefore admit exactly one, across processes and nodes. A store error while recording a step fails that verification. A client that signs in with TOTP more than once inside the same 30-second step needs the code of a later step for its second sign-in.

‎packages/plugins/plugin-auth/src/auth-manager-auth-instance.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ import { createBetterAuthLogSink } from './sso-oidc-refusal-cause.js';
8080
import { withSystemReadContext } from './objectql-adapter.js';
8181
import { refuseSsoAccountOutsideProvenDomain, refuseSsoAccountWithoutAddress } from './sso-account-at-proven-domain.js';
8282
import { refuseSamlAccountKeyContradiction } from './sso-saml-account-key.js';
83+
import { acceptEachTotpCodeOnce } from './totp-code-single-use.js';
8384

8485
/** The path better-auth declares for the email sign-up endpoint. */
8586
const SIGN_UP_EMAIL_PATH = '/sign-up/email';
@@ -196,7 +197,10 @@ export interface AuthInstanceHost {
196197
export async function createAuthInstance(this: AuthInstanceHost): Promise<Auth<any>> {
197198
const { betterAuth } = await import('better-auth');
198199
const { createAuthMiddleware, setShouldSkipSessionRefresh } = await import('better-auth/api');
199-
const plugins = await this.buildPluginList();
200+
// A TOTP code the two-factor plugin accepts is accepted once (RFC 6238
201+
// §5.2): a before-hook on its `/two-factor/verify-totp`, appended to the
202+
// plugin object in place. See `totp-code-single-use.ts`.
203+
const plugins = await acceptEachTotpCodeOnce(await this.buildPluginList());
200204
// ADR-0069 D2: the verifier refuses a locked account by better-auth's own
201205
// wrong-password path; the WebContainer hasher, when there is one, is the
202206
// pair it wraps (`sign-in-lockout-refusal.ts`).

0 commit comments

Comments
 (0)