Skip to content

Commit ea1edf9

Browse files
fix(plugin-auth): a single-use auth value is redeemed at most once, even across processes sharing a database (#34511)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9CEjuTu4HVEtNH1742UngyH)_ Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:认证适配器兑现一次性认证值(邮箱验证、重置密码、魔法链接、一次性验证码等)时,只把值交给自己的删除确实删掉那一行的那次调用,其余调用一律得到 `null`。 - **为什么改**:规则是「一次性认证值至多兑现一次,即使多个进程共享同一个数据库」,也是 better-auth `consumeOne` 契约的要求。 - **风险与回滚**:单次兑现行为不变;数据引擎的删除若既不答「删没删」也不答「删了几行」,兑现会报错而不是放行。回滚即还原本 PR,改动只在一个源文件。 - **先看**:`packages/plugins/plugin-auth/src/objectql-adapter.ts` 的 `consumeOne` 与新函数 `removedByThisDelete`;再看 `objectql-adapter.test.ts` 末尾新增的 describe。 - **两分钟验证**:依赖构建后跑 `pnpm --filter @objectstack/plugin-auth exec vitest run src/objectql-adapter.test.ts -t 'redeemed at most once'`,预期 4 个用例全部通过。 - **需要你做的**:无,席位落地。 ## What changes **Rule: a single-use auth value is redeemed at most once, even across processes sharing a database.** - `packages/plugins/plugin-auth/src/objectql-adapter.ts`: `consumeOne` hands the stored row back only when this call's own by-id delete removed it, and answers `null` otherwise, as better-auth's `consumeOne` contract requires. The new `removedByThisDelete` reads the data engine's delete answer: `true` (or a count of 1) is this call's removal; `false`, a count of 0, or the engine's `RECORD_NOT_FOUND` mean the row is gone and was not removed by this call; any other answer is refused by name rather than read as either. - `packages/plugins/plugin-auth/src/objectql-adapter.test.ts`: one new top-level `describe` with 4 pins over the real stack (two `ObjectQL` engines, each with its own `@objectstack/driver-sql` connection to one SQLite file, each with its own factory-wrapped adapter). - `.changeset/auth-single-use-redeemed-once.md`: `@objectstack/plugin-auth` patch, rule only. No engine, driver, spec or exported signature changes. ## Tests The new `describe` ("a single-use auth value is redeemed at most once, even across processes sharing a database"), 4 pins: 1. of two concurrent redemptions on two engines over one database, exactly one receives the value (the other gets `null`); 2. a redemption of a value already redeemed elsewhere receives `null`; 3. a single redemption receives the value and removes it (a second redemption gets `null`); 4. redeeming a value that does not exist receives `null` and removes nothing. Ablation (the decision line replaced by the behaviour before this PR, on disk, through `scripts/ablation-replace.mjs`): 2 of 4 pins red; restored: 4 of 4 green, `git diff HEAD` empty. ## Acceptance notes - Read from code, not measured: every driver in `packages/drivers` answers its by-id delete from the store's own removal result, which is what the engine passes through and this adapter now reads. Measured: the SQL driver over SQLite (the pins above). - The pins drive the adapter's `consumeOne` directly, the method better-auth calls for each single-use value. ## Verification All readings are at head `a3aa7c8f`. The branch merged `main` once (at `3bf9c5c4`, merge commit `2e4eed29`). Before the fix, on `origin/main` `bf769229`, the same 4 pins read 2 red and 2 green. <details><summary>plugin-auth vitest (full package)</summary> `vitest run --maxWorkers=2` in `packages/plugins/plugin-auth` under `scripts/pm/os-verify-lock.sh`, at `HEAD=a3aa7c8f`: `Test Files 280 passed (280)` · `Tests 5767 passed | 10 skipped (5777)` · `VERDICT command-exit 0`. </details> <details><summary>plugin-auth typecheck</summary> `pnpm --filter @objectstack/plugin-auth typecheck` (tsc, the examples project and `check:test-typecheck`) under `scripts/pm/os-verify-lock.sh`: `VERDICT command-exit 0`. `check:test-typecheck: OK — @objectstack/plugin-auth's test layer compiles under packages/plugins/plugin-auth/tsconfig.test.json; 10 file(s) / 71 error(s) / 23 pinned signature(s) held in test-typecheck-debt.json` (the existing ledger, unchanged). </details> <details><summary>Gates derived by dispatch-gates.mjs --commands</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 69 families from the 3 changed paths; all 69 run at `a3aa7c8f`, each exit code captured before any pipe. `--ran` reconciliation: `69 derived, 69 run, 0 NOT-MEASURED, 0 UNRUN` (a derived zero: every row recorded an exit code). - `node scripts/check-adr-0087-registration.mjs --base origin/main` :: exit 0 - `node scripts/check-adr-0087-registration.mjs --self-test` :: exit 0 - `node scripts/check-changeset-no-major.mjs --base origin/main` :: exit 0 - `node scripts/check-closing-keyword-parity.mjs` :: exit 0 - `node scripts/check-closing-keyword-parity.mjs --self-test` :: exit 0 - `node scripts/check-comment-mask-adoption.mjs` :: exit 0 - `node scripts/check-comment-mask-adoption.mjs --self-test` :: exit 0 - `node scripts/check-comment-mask-corpus.mjs` :: exit 0 - `node scripts/check-dev-prereqs.mjs --self-test` :: exit 0 - `node scripts/check-dts-emitted.mjs --self-test` :: exit 0 - `node scripts/check-empty-changeset.mjs --base origin/main` :: exit 0 - `node scripts/check-empty-changeset.mjs --self-test` :: exit 0 - `node scripts/check-issue-citations.mjs` :: exit 0 - `node scripts/check-plugin-teardown-shape.mjs` :: exit 0 - `node scripts/check-plugin-teardown-shape.mjs --self-test` :: exit 0 - `node scripts/check-tenant-audit-census.mjs` :: exit 0 - `node scripts/check-tenant-audit-census.mjs --self-test` :: exit 0 - `node scripts/ci/assert-turbo-remote-cache.mjs --self-test` :: exit 0 - `node scripts/ci/plan-test-core-shards.mjs --self-test` :: exit 0 - `node scripts/ci/prune-turbo-cache.mjs --self-test` :: exit 0 - `node scripts/ci/snapshot-next.mjs --self-test` :: exit 0 - `node scripts/docs-audit/check-affected-docs.mjs` :: exit 0 - `node scripts/docs-audit/check-drift-comment.mjs` :: exit 0 - `node scripts/pm/check-governed-queue-guard.mjs --self-test` :: exit 0 - `node scripts/pm/release-rehearsal-clone.mjs --self-test` :: exit 0 - `node scripts/release-pending-publish.mjs --self-test` :: exit 0 - `pnpm --filter @objectstack/spec run check:duration-unit-keys` :: exit 0 - `pnpm --filter @objectstack/spec run check:error-code-provenance` :: exit 0 - `pnpm check:adr-anchors` :: exit 0 - `pnpm check:adr-symbol-anchors` :: exit 0 - `pnpm check:changeset-gate-self-tests` :: exit 0 - `pnpm check:ci-filter-parity` :: exit 0 - `pnpm check:closed-ceremony-text` :: exit 0 - `pnpm check:cross-package-test-inputs` :: exit 0 - `pnpm check:dispatcher-error-vocabulary` :: exit 0 - `pnpm check:doc-authoring` :: exit 0 - `pnpm check:driver-memory-census` :: exit 0 - `pnpm check:dts-closure` :: exit 0 - `pnpm check:dual-build-cjs-loads` :: exit 0 - `pnpm check:engine-double-contract` :: exit 0 - `pnpm check:gitlink-declared` :: exit 0 - `pnpm check:issue-citations` :: exit 0 - `pnpm check:keyed-text-bounds` :: exit 0 - `pnpm check:lean-entry-closure` :: exit 0 - `pnpm check:logger-receiver-detach` :: exit 0 - `pnpm check:nul-bytes` :: exit 0 - `pnpm check:object-def-param-keys` :: exit 0 - `pnpm check:objectql-double-limit` :: exit 0 - `pnpm check:optional-error-sink` :: exit 0 - `pnpm check:org-identifier` :: exit 0 - `pnpm check:page-declaration-shape` :: exit 0 - `pnpm check:platform-object-tenancy-census` :: exit 0 - `pnpm check:published-files` :: exit 0 - `pnpm check:query-options-erasure` :: exit 0 - `pnpm check:refd-timer-probe` :: exit 0 - `pnpm check:registry-log-declared` :: exit 0 - `pnpm check:rest-log-spy-declared` :: exit 0 - `pnpm check:slot-lookup` :: exit 0 - `pnpm check:sourcemap-no-sources-content` :: exit 0 - `pnpm check:system-context-census` :: exit 0 - `pnpm check:test-source-alias` :: exit 0 - `pnpm check:tier-file-adoption` :: exit 0 - `pnpm check:type-check-coverage` :: exit 0 - `pnpm check:type-check-debt` :: exit 0 - `pnpm check:undeclared-dep-imports` :: exit 0 - `pnpm check:vouch-for-reference-callers` :: exit 0 - `pnpm check:watch-hint-literal` :: exit 0 - `pnpm check:where-matcher` :: exit 0 - `pnpm check:wildcard-fallthrough` :: exit 0 </details> <details><summary>Ablation</summary> `node scripts/ablation-replace.mjs` on `packages/plugins/plugin-auth/src/objectql-adapter.ts`: the decision line replaced by a bare `await deletion;` (anchor 1 to 0, blob `6902c52d6194` to `02672d5b7d47`), then `vitest run src/objectql-adapter.test.ts -t 'redeemed at most once'` under the verify lock: `Tests 2 failed | 2 passed`, `VERDICT command-exit 1`. Restored: blob equals HEAD (`6902c52d6194`), `git diff HEAD` empty; the whole file then reads `Tests 51 passed (51)`, `VERDICT command-exit 0`. The subject is imported from source (`./objectql-adapter`), so no build sits between the mutation and the run. </details> <!-- signed: security#1 · os-steve · session_01ADHkmRiaNzHVY81pCjZrpv --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 23a07c8 commit ea1edf9

3 files changed

Lines changed: 202 additions & 5 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth): a single-use auth value is redeemed at most once, even across processes sharing a database
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
better-auth redeems its single-use values (email verification, password reset, magic-link and one-time codes, and the other values it keeps in `sys_verification`) through the storage adapter's `consumeOne`. The ObjectQL adapter now hands a redeemed value back only to the call whose own delete removed the stored row, and answers `null` to every other call, as better-auth's `consumeOne` contract requires. This holds for any number of server processes on one database.
11+
12+
A value that was already redeemed answers `null`, which better-auth refuses as an invalid or expired value. A single redemption is unchanged: it receives the value and removes it.
13+
14+
The adapter reads the data engine's delete answer to decide. A data engine whose delete answers neither whether nor how many rows it removed (`IDataEngine.delete` declares `boolean | number`) now fails the redemption with an error naming that answer, rather than handing the value back.

‎packages/plugins/plugin-auth/src/objectql-adapter.test.ts‎

Lines changed: 147 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

3-
import { describe, it, expect, vi, beforeEach } from 'vitest';
3+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
4+
import { mkdtempSync, rmSync } from 'node:fs';
5+
import { tmpdir } from 'node:os';
6+
import { join } from 'node:path';
7+
import { ObjectQL } from '@objectstack/objectql';
8+
import { SqlDriver } from '@objectstack/driver-sql';
9+
import { authIdentityObjects } from './manifest.js';
410
import {
511
createObjectQLAdapter,
612
createObjectQLAdapterFactory,
@@ -753,3 +759,143 @@ describe('an unbounded ssoProvider read reads every row (the 100-row factory def
753759
]);
754760
});
755761
});
762+
763+
describe('a single-use auth value is redeemed at most once, even across processes sharing a database', () => {
764+
// Each "process" is its own ObjectQL engine with its own SQL driver
765+
// connection, both opened on ONE SQLite file, and its own factory-wrapped
766+
// adapter: nothing in memory is shared between the two, only the database.
767+
const VERIFICATION = 'sys_verification';
768+
type Adapter = {
769+
create(a: { model: string; data: Record<string, unknown> }): Promise<Record<string, unknown>>;
770+
consumeOne(a: { model: string; where: Array<Record<string, unknown>> }): Promise<Record<string, unknown> | null>;
771+
};
772+
/** A pause point: every caller waits until `parties` callers have arrived. */
773+
type Gate = () => Promise<void>;
774+
const gate = (parties: number): Gate => {
775+
let arrived = 0;
776+
let open!: () => void;
777+
const opened = new Promise<void>((resolve) => { open = resolve; });
778+
return async () => {
779+
if (++arrived === parties) open();
780+
await opened;
781+
};
782+
};
783+
784+
const dirs: string[] = [];
785+
const engines: ObjectQL[] = [];
786+
afterEach(async () => {
787+
while (engines.length) {
788+
try { await engines.pop()!.destroy(); } catch { /* noop */ }
789+
}
790+
while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true });
791+
});
792+
793+
/**
794+
* One replica over `file`. `atRead` runs once, after its adapter's first
795+
* read of a verification row; `atDelete` before each of its driver's
796+
* verification deletes. Both default to no pause.
797+
*/
798+
const replica = async (
799+
file: string,
800+
pauses: { atRead?: () => Promise<void>; atDelete?: () => Promise<void> } = {},
801+
): Promise<{ adapter: Adapter; driver: SqlDriver }> => {
802+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: file }, useNullAsDefault: true });
803+
const engine = new ObjectQL();
804+
engines.push(engine);
805+
engine.registerDriver(driver, true);
806+
await engine.init();
807+
for (const object of authIdentityObjects) engine.registry.registerObject(object as never, '@objectstack/plugin-auth');
808+
await engine.syncSchemas();
809+
810+
const driverDelete = driver.delete.bind(driver);
811+
driver.delete = (async (object: string, id: string | number, options?: unknown) => {
812+
if (object === VERIFICATION) await pauses.atDelete?.();
813+
return driverDelete(object, id, options as never);
814+
}) as typeof driver.delete;
815+
816+
let read = false;
817+
const seen = new Proxy(engine, {
818+
get(target, prop) {
819+
const member = Reflect.get(target, prop, target);
820+
if (prop !== 'findOne') return typeof member === 'function' ? member.bind(target) : member;
821+
return async (object: string, ...rest: unknown[]) => {
822+
const row = await (member as (...a: unknown[]) => Promise<unknown>).call(target, object, ...rest);
823+
if (object === VERIFICATION && !read) {
824+
read = true;
825+
await pauses.atRead?.();
826+
}
827+
return row;
828+
};
829+
},
830+
});
831+
const adapter = (createObjectQLAdapterFactory(seen as unknown as IDataEngine) as unknown as (o: unknown) => Adapter)({});
832+
return { adapter, driver };
833+
};
834+
835+
const sharedFile = () => {
836+
const dir = mkdtempSync(join(tmpdir(), 'os-auth-single-use-'));
837+
dirs.push(dir);
838+
return join(dir, 'auth.db');
839+
};
840+
841+
const issue = (adapter: Adapter, identifier: string) =>
842+
adapter.create({
843+
model: 'verification',
844+
data: { identifier, value: `value-of-${identifier}`, expiresAt: new Date(Date.now() + 5 * 60_000) },
845+
});
846+
847+
const redeem = (adapter: Adapter, id: unknown) =>
848+
adapter.consumeOne({ model: 'verification', where: [{ field: 'id', value: id, operator: 'eq', connector: 'AND' }] });
849+
850+
const stored = async (driver: SqlDriver, identifier: string) =>
851+
(await driver.find(VERIFICATION, { object: VERIFICATION, where: { identifier } } as never)) as unknown[];
852+
853+
it('of two concurrent redemptions on two engines over one database, exactly one receives the value', async () => {
854+
const file = sharedFile();
855+
const atRead = gate(2);
856+
const atDelete = gate(2);
857+
const a = await replica(file, { atRead, atDelete });
858+
const b = await replica(file, { atRead, atDelete });
859+
const row = await issue(a.adapter, 'race-both-paused');
860+
861+
const answers = await Promise.all([redeem(a.adapter, row.id), redeem(b.adapter, row.id)]);
862+
863+
expect(answers.filter((r) => r !== null), 'redemptions that received the value').toHaveLength(1);
864+
expect(answers.filter((r) => r === null), 'redemptions answered null').toHaveLength(1);
865+
expect(answers.find((r) => r !== null)).toMatchObject({ id: row.id, value: 'value-of-race-both-paused' });
866+
expect(await stored(a.driver, 'race-both-paused')).toHaveLength(0);
867+
});
868+
869+
it('a redemption of a value already redeemed elsewhere receives null', async () => {
870+
const file = sharedFile();
871+
const bothRead = gate(2);
872+
let aDone!: Promise<unknown>;
873+
const a = await replica(file, { atRead: bothRead });
874+
const b = await replica(file, { atRead: async () => { await bothRead(); await aDone; } });
875+
const row = await issue(a.adapter, 'race-late-delete');
876+
877+
aDone = redeem(a.adapter, row.id);
878+
const [first, second] = await Promise.all([aDone, redeem(b.adapter, row.id)]);
879+
880+
expect(first).toMatchObject({ id: row.id, value: 'value-of-race-late-delete' });
881+
expect(second).toBeNull();
882+
expect(await stored(b.driver, 'race-late-delete')).toHaveLength(0);
883+
});
884+
885+
it('a single redemption receives the value and removes it', async () => {
886+
const { adapter, driver } = await replica(sharedFile());
887+
const row = await issue(adapter, 'single');
888+
889+
expect(await redeem(adapter, row.id)).toMatchObject({ id: row.id, identifier: 'single', value: 'value-of-single' });
890+
expect(await stored(driver, 'single')).toHaveLength(0);
891+
expect(await redeem(adapter, row.id), 'the same value a second time').toBeNull();
892+
});
893+
894+
it('redeeming a value that does not exist receives null and removes nothing', async () => {
895+
const { adapter, driver } = await replica(sharedFile());
896+
await issue(adapter, 'bystander');
897+
898+
expect(await redeem(adapter, 'no-such-value')).toBeNull();
899+
expect(await stored(driver, 'bystander')).toHaveLength(1);
900+
});
901+
});

‎packages/plugins/plugin-auth/src/objectql-adapter.ts‎

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1218,9 +1218,12 @@ export function createObjectQLAdapterFactory(
12181218
return records.length;
12191219
},
12201220

1221-
// Atomic single-row consume (better-auth 1.7+). ObjectQL has no native
1222-
// `DELETE ... RETURNING`, so we find the single guarded row, delete it,
1223-
// and return the consumed record — a find-then-write mirror of `delete`.
1221+
// Single-row consume (better-auth 1.7+): find the guarded row, delete it
1222+
// by id, and return it. A single-use auth value is redeemed at most
1223+
// once, even across processes sharing a database — the row goes back
1224+
// only to the call whose own delete removed it (`removedByThisDelete`),
1225+
// and every other call is answered `null`, as better-auth's `consumeOne`
1226+
// contract requires.
12241227
consumeOne: async <T>(
12251228
{ model, where }: { model: string; where: CleanedWhere[] },
12261229
): Promise<T | null> => {
@@ -1237,7 +1240,8 @@ export function createObjectQLAdapterFactory(
12371240
// privileged accessor reads the stored row, and after the delete
12381241
// there is none.
12391242
await reattachInternalFieldsOnRead(internalFieldEngine, objectName, record);
1240-
await dataEngine.delete(objectName, { where: { id: record.id } });
1243+
const deletion = dataEngine.delete(objectName, { where: { id: record.id } });
1244+
if (!(await removedByThisDelete(deletion, objectName))) return null;
12411245
const norm = normaliseLegacyDates(model, record);
12421246
return (bridged ? remapKeys(norm, snakeToCamel) : norm) as T;
12431247
},
@@ -1290,6 +1294,39 @@ export function createObjectQLAdapterFactory(
12901294
};
12911295
}
12921296

1297+
/**
1298+
* Answer whether a by-id delete of one `objectName` row (`deletion`, already
1299+
* issued) removed it for THIS call — the fact a single-use redemption
1300+
* (`consumeOne`) is decided on.
1301+
*
1302+
* The engine's by-id delete answers it one of three ways (`IDataEngine.delete`;
1303+
* `packages/objectql/src/engine-delete-and-aggregate.ts`): `true` when its
1304+
* driver removed the row; `false` when its driver removed nothing, the row
1305+
* being gone already; and a thrown `RECORD_NOT_FOUND` (`recordNotFoundError`,
1306+
* `@objectstack/core`) when its own read of the row before the delete found
1307+
* none. The last two are one fact — the row was removed, but not by this call
1308+
* — and both answer `false`. A count of 1 or 0 reads as `true` or `false`.
1309+
*
1310+
* Any other answer does not say who removed the row, so it is refused by name
1311+
* rather than read as either: a redemption the adapter cannot attribute to
1312+
* this call is never handed to its caller.
1313+
*/
1314+
async function removedByThisDelete(deletion: Promise<unknown>, objectName: string): Promise<boolean> {
1315+
let answer: unknown;
1316+
try {
1317+
answer = await deletion;
1318+
} catch (error) {
1319+
if ((error as { code?: unknown } | null)?.code === 'RECORD_NOT_FOUND') return false;
1320+
throw error;
1321+
}
1322+
if (answer === true || answer === 1) return true;
1323+
if (answer === false || answer === 0) return false;
1324+
throw new Error(
1325+
`[objectql-adapter] consumeOne: the delete of a ${objectName} row answered ${String(answer)}, ` +
1326+
'not whether this call removed it, so the value is not redeemed',
1327+
);
1328+
}
1329+
12931330
/**
12941331
* The SSO provider table is read WHOLE when its caller asks for no limit.
12951332
*

0 commit comments

Comments
 (0)