Skip to content

Commit 852270a

Browse files
fix(plugin-auth): a guarded increment is one atomic conditional write (#36139)
Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户无感:登录与组织功能的表现不变,只是认证存储层的一种计数写入在多实例同时调用时也守住了它的前置条件。 - 安全席位派发的加固单,替认证插件补齐其所依赖的认证库对这类写入的约定。 - 出错的话,相关写入会报错而非静默放行;可随整个变更直接撤回,不涉及数据迁移。 - 无。 ## What changes Hardening rule: **a guarded increment is one atomic conditional write.** - `packages/plugins/plugin-auth/src/objectql-adapter.ts`, the factory adapter's `incrementOne`: each attempt reads the guarded row, computes the new values, and writes them with ONE predicate update (`multi: true`) whose condition is the caller's `where` (selector and guard), the row id, and every incremented counter at the value read. The affected count decides: `1` is this call's write; `0` re-reads (the guard no longer matching answers `null`; an unguarded counter is recomputed from the new value); anything else is refused by name; contention outlasting 5 attempts throws. This is better-auth's stated contract for the method. Answer shapes are unchanged (the updated row, or `null`). The native `incrementOne` / `consumeOne` stay, with a note on why they must. - Five in-package engine doubles (`impersonation-bearer-rotation`, `accept-invitation-adopt-membership`, `list-user-invitations-verification`, `org-create-posture-gate`, `remove-user-atomicity` tests) now serve the engine's predicate update path behind the producer's own `assertEngineUpdateDispatch`, and their matchers take `$and`. They only ever served by-id updates; the real engine serves both. - `scripts/engine-double-contract.pinned.json` / `.baseline.json`: the org-create posture double's `update` now opens with the producer's dispatch predicate, so it moves from the shrink-only DEBT ledger to the pinned ledger (`--write`, plus the stale DEBT row removed). - `.changeset/sec2-4ghv.md`: `patch` for `@objectstack/plugin-auth`. No engine or driver change was needed: the engine's predicate path already lowers to one `UPDATE … WHERE …` statement and answers its affected count. ## Why better-auth states the contract for `incrementOne`: the `where` clause is both selector and guard, and the conditional write must be atomic. The adapter now enforces exactly that rule. ## Tests New top-level suite in `src/objectql-adapter.test.ts`: two ObjectQL engines, each with its own SQL driver connection to ONE SQLite file, both paused after their first guarded read so both see the guard hold before either writes. Three concurrency pins (one per guard shape better-auth issues against the method), a sequential control, and a null-counter case. <details><summary>Red on base, green after, ablations (SQLite, the committed pins)</summary> - Base (`objectql-adapter.ts` at `db9e34ad`, new pins in place): 3 failed | 2 passed — all three concurrency pins red, the sequential control and the null-counter case green. - Fix (`e986331f`): 5 passed. - Ablation A — the counters-as-read terms dropped from the conditional write's predicate: 1 failed (the unguarded-increment pin). Restored, blob equal to HEAD. - Ablation B — the caller's guard dropped from the conditional write's predicate: 1 failed (the guard-on-a-stored-value pin). Restored, blob equal to HEAD. - Ablation C — an affected count of 0 read as written: 3 failed (all three concurrency pins). Restored, blob equal to HEAD. - The guard-on-the-counter pin is held by either term (guard and counter-as-read), so only C turns it red alone. </details> <details><summary>Package suite and typecheck</summary> - `@objectstack/plugin-auth` full suite at `4f58e2fc`: Test Files 291 passed (291), Tests 6189 passed, 10 skipped. Later commits change one return-type annotation in five test doubles and two gate ledgers. - `pnpm --filter @objectstack/plugin-auth typecheck` at `3ab85b9e`: exit 0 (`check:test-typecheck: OK`, ledger unchanged). - Before the doubles were taught the predicate path, the first full run had 41 failures in 12 files, every one in a fake engine that served only by-id updates (the same 12 files pass 305/305 on base and 305/305 after the double fix). </details> ## Acceptance notes - The committed pins run on SQLite (the package's test setup). The same five cases were also measured once against a local PostgreSQL 16 (two engines, two connection pools, one database per case): red 3/5 on base, green 5/5 with the fix. Not committed, because this package's CI job provisions no Postgres and a cell nobody provisions would only ever skip. - The pins call the factory-wrapped adapter with the exact call shapes the vendor issues; they do not drive the HTTP routes end to end across two processes. ## Verification Two-minute check: `pnpm --filter @objectstack/plugin-auth exec vitest run --maxWorkers=2 src/objectql-adapter.test.ts -t "a guarded increment is one atomic"` — expect 5 passed. Revert `objectql-adapter.ts` to `main` and the three concurrency cases go red. Read first: `objectql-adapter.ts` `incrementOne` (the conditional write and the attempt loop), then the new suite at the end of `objectql-adapter.test.ts`, then one of the doubles (`impersonation-bearer-rotation.test.ts` `update`). L2: the contract-tier review is owed to the security seat (not requested here). 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_017xRBcU63t9HUySVRZqa3bk --- _Generated by [Claude Code](https://claude.ai/code/session_017xRBcU63t9HUySVRZqa3bk)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d953558 commit 852270a

11 files changed

Lines changed: 353 additions & 44 deletions

‎.changeset/sec2-4ghv.md‎

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(plugin-auth): a guarded increment is one atomic conditional write
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The auth adapter's `incrementOne` now honours better-auth's contract for that method under concurrency: its `where` clause is both the selector and the guard, and the guarded write is one conditional update judged by the database. Each attempt reads the guarded row and writes the new values with a single predicate update whose condition is the caller's guard, the row id and every incremented counter at the value read; the affected count decides. A guard that no longer holds answers `null`, an unguarded counter is retried from the new value, and contention that outlasts the bounded attempts throws rather than answering `null`.
11+
12+
The answer shapes are unchanged: the updated row, or `null` when the guard matches no row. The native `incrementOne` and `consumeOne` stay in place, so better-auth's own fallbacks are not used.

‎packages/plugins/plugin-auth/src/accept-invitation-adopt-membership.test.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
// that index and throws in SQLite's own words. That is what makes the ablation
2121
// (revert the fix → these tests go red) mean anything.
2222

23+
// Pays the first load of the egress module at collection, not inside a clocked test.
24+
import '@objectstack/core/egress';
2325
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2426
import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/objectql';
2527
import { AuthManager } from './auth-manager';
@@ -47,8 +49,10 @@ const createMemoryEngine = () => {
4749
a instanceof Date || b instanceof Date
4850
? new Date(a as any).getTime() === new Date(b as any).getTime()
4951
: a === b;
50-
const matches = (row: any, where: Record<string, any> = {}) =>
52+
const matches = (row: any, where: Record<string, any> = {}): boolean =>
5153
Object.entries(where).every(([k, v]) => {
54+
// A conjunction of conditions, as the engine's predicate path takes one.
55+
if (k === '$and' && Array.isArray(v)) return v.every((w) => matches(row, w));
5256
if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`);
5357
const actual = row[k];
5458
if (v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date)) {
@@ -117,7 +121,15 @@ const createMemoryEngine = () => {
117121
// `delete` below is: this fake carries the ADOPTION write, so a fake looser
118122
// than the real engine would let a by-id update that ObjectQL refuses look
119123
// like a working adoption. `adopt-membership.ts` dispatches by scalar id.
120-
assertEngineUpdateDispatch(patch, options);
124+
const dispatch = assertEngineUpdateDispatch(patch, options);
125+
// The predicate path (`multi: true`, a `where` and no id in the payload)
126+
// writes every matching row and answers how many it wrote.
127+
if (dispatch.kind === 'multi') {
128+
const targets = rows(name).filter((r) => matches(r, options?.where));
129+
for (const target of targets) assertMemberUnique(name, { ...target, ...patch }, target.id);
130+
for (const target of targets) Object.assign(target, patch);
131+
return targets.length;
132+
}
121133
const row = rows(name).find((r) => r.id === patch.id);
122134
if (!row) return null;
123135
assertMemberUnique(name, { ...row, ...patch }, row.id);

‎packages/plugins/plugin-auth/src/idp-group-mapping-match.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,9 @@
2424
* platform-admin door's save). `roles.map` is not enough: the vendor calls it
2525
* only for a group that has members, so an empty group's rename would never
2626
* reach it. Every one of those writes goes through the ObjectQL engine (the
27-
* better-auth adapter's `create` / `update` / `incrementOne` / `delete` all
28-
* end in an engine call by id), so after-hooks on `sys_scim_group` and on
27+
* better-auth adapter's `create` / `update` / `delete` end in an engine call
28+
* by id, and its `incrementOne` in a one-row predicate update, whose per-row
29+
* after-hooks fire the same way), so after-hooks on `sys_scim_group` and on
2930
* `sys_idp_group_mapping` see each of them, the same seam
3031
* `membership-ended-session.ts` measured for `sys_member`. A raw driver write
3132
* below the engine is not seen; the boot sweep ({@link refreshAllMappingMatches})

‎packages/plugins/plugin-auth/src/impersonation-bearer-rotation.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
// that is literally what `runtime/src/security/resolve-session-principal.ts`
2525
// calls.
2626

27+
// Pays the first load of the egress module at collection, not inside a clocked test.
28+
import '@objectstack/core/egress';
2729
import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
2830
import { fileURLToPath } from 'node:url';
2931
import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/objectql';
@@ -56,8 +58,10 @@ export const createMemoryEngine = () => {
5658
a instanceof Date || b instanceof Date
5759
? new Date(a as any).getTime() === new Date(b as any).getTime()
5860
: a === b;
59-
const matches = (row: any, where: Record<string, any> = {}) =>
61+
const matches = (row: any, where: Record<string, any> = {}): boolean =>
6062
Object.entries(where).every(([k, v]) => {
63+
// A conjunction of conditions, as the engine's predicate path takes one.
64+
if (k === '$and' && Array.isArray(v)) return v.every((w) => matches(row, w));
6165
if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`);
6266
const actual = row[k];
6367
if (v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date)) {

‎packages/plugins/plugin-auth/src/list-user-invitations-verification.test.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
// it as B's (it strengthens the own-email pin) and excludes it only where an
2525
// exact id set is compared.
2626

27+
// Pays the first load of the egress module at collection, not inside a clocked test.
28+
import '@objectstack/core/egress';
2729
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2830
import { readFileSync, existsSync } from 'node:fs';
2931
import { createRequire } from 'node:module';
@@ -56,8 +58,10 @@ const createMemoryEngine = () => {
5658
a instanceof Date || b instanceof Date
5759
? new Date(a as any).getTime() === new Date(b as any).getTime()
5860
: a === b;
59-
const matches = (row: any, where: Record<string, any> = {}) =>
61+
const matches = (row: any, where: Record<string, any> = {}): boolean =>
6062
Object.entries(where).every(([k, v]) => {
63+
// A conjunction of conditions, as the engine's predicate path takes one.
64+
if (k === '$and' && Array.isArray(v)) return v.every((w) => matches(row, w));
6165
if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`);
6266
const actual = row[k];
6367
if (v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date)) {
@@ -103,7 +107,14 @@ const createMemoryEngine = () => {
103107
return rows(name).filter((r) => matches(r, q.where)).length;
104108
},
105109
async update(name: string, patch: any, options?: any) {
106-
assertEngineUpdateDispatch(patch, options);
110+
const dispatch = assertEngineUpdateDispatch(patch, options);
111+
// The predicate path (`multi: true`, a `where` and no id in the payload)
112+
// writes every matching row and answers how many it wrote.
113+
if (dispatch.kind === 'multi') {
114+
const targets = rows(name).filter((r) => matches(r, options?.where));
115+
for (const target of targets) Object.assign(target, patch);
116+
return targets.length;
117+
}
107118
const row = rows(name).find((r) => r.id === patch.id);
108119
if (!row) return null;
109120
Object.assign(row, patch);

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

Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

3+
// Pays the first load of the egress module at collection, not inside a clocked test.
4+
import '@objectstack/core/egress';
35
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
46
import { mkdtempSync, rmSync } from 'node:fs';
57
import { tmpdir } from 'node:os';
@@ -34,6 +36,8 @@ import {
3436
import { SystemObjectName } from '@objectstack/spec/system';
3537
import type { IDataEngine } from '@objectstack/core';
3638
import { sso } from '@better-auth/sso';
39+
import { twoFactor } from 'better-auth/plugins/two-factor';
40+
import { organization } from 'better-auth/plugins/organization';
3741
import { AuthManager } from './auth-manager';
3842
import { createMemoryEngine } from './impersonation-bearer-rotation.test';
3943

@@ -899,3 +903,199 @@ describe('a single-use auth value is redeemed at most once, even across processe
899903
expect(await stored(driver, 'bystander')).toHaveLength(1);
900904
});
901905
});
906+
907+
describe('a guarded increment is one atomic conditional write, even across processes sharing a database', () => {
908+
// The same two-replica shape as the single-use suite above: two ObjectQL
909+
// engines, each with its own SQL driver connection to ONE SQLite file and
910+
// its own factory-wrapped adapter. Each replica pauses once, right after its
911+
// first read of a guarded row, until both replicas have read — so both
912+
// calls see the guard pass before either one writes. The three call shapes
913+
// are ones better-auth 1.7.12 itself issues against `incrementOne`.
914+
const GUARDED = new Set(['sys_two_factor', 'sys_team']);
915+
type Where = { field: string; value: unknown; operator?: string; connector?: string };
916+
type Adapter = {
917+
create(a: { model: string; data: Record<string, unknown> }): Promise<Record<string, unknown>>;
918+
findOne(a: { model: string; where: Where[] }): Promise<Record<string, unknown> | null>;
919+
incrementOne(a: {
920+
model: string; where: Where[]; increment: Record<string, number>; set?: Record<string, unknown>;
921+
}): Promise<Record<string, unknown> | null>;
922+
};
923+
const gate = (parties: number) => {
924+
let arrived = 0;
925+
let open!: () => void;
926+
const opened = new Promise<void>((resolve) => { open = resolve; });
927+
return async () => {
928+
if (++arrived === parties) open();
929+
await opened;
930+
};
931+
};
932+
933+
const dirs: string[] = [];
934+
const engines: ObjectQL[] = [];
935+
afterEach(async () => {
936+
while (engines.length) {
937+
try { await engines.pop()!.destroy(); } catch { /* noop */ }
938+
}
939+
while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true });
940+
});
941+
942+
const replica = async (file: string, atRead?: () => Promise<void>): Promise<{ adapter: Adapter; driver: SqlDriver }> => {
943+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: file }, useNullAsDefault: true });
944+
const engine = new ObjectQL();
945+
engines.push(engine);
946+
engine.registerDriver(driver, true);
947+
await engine.init();
948+
for (const object of authIdentityObjects) engine.registry.registerObject(object as never, '@objectstack/plugin-auth');
949+
await engine.syncSchemas();
950+
951+
let read = false;
952+
const seen = new Proxy(engine, {
953+
get(target, prop) {
954+
const member = Reflect.get(target, prop, target);
955+
if (prop !== 'findOne') return typeof member === 'function' ? member.bind(target) : member;
956+
return async (object: string, ...rest: unknown[]) => {
957+
const row = await (member as (...a: unknown[]) => Promise<unknown>).call(target, object, ...rest);
958+
if (GUARDED.has(object) && !read) {
959+
read = true;
960+
await atRead?.();
961+
}
962+
return row;
963+
};
964+
},
965+
});
966+
const options = {
967+
plugins: [
968+
twoFactor({ schema: buildTwoFactorPluginSchema() }),
969+
organization({ schema: buildOrganizationPluginSchema(), teams: { enabled: true } }),
970+
],
971+
};
972+
const adapter = (createObjectQLAdapterFactory(seen as unknown as IDataEngine) as unknown as (o: unknown) => Adapter)(options);
973+
return { adapter, driver };
974+
};
975+
976+
/** Two replicas over one fresh file, both paused at their first guarded read. */
977+
const twoReplicas = async () => {
978+
const dir = mkdtempSync(join(tmpdir(), 'os-auth-guarded-increment-'));
979+
dirs.push(dir);
980+
const file = join(dir, 'auth.db');
981+
const bothRead = gate(2);
982+
return [await replica(file, bothRead), await replica(file, bothRead)] as const;
983+
};
984+
/** One replica, no pause: the sequential control. */
985+
const oneReplica = async () => {
986+
const dir = mkdtempSync(join(tmpdir(), 'os-auth-guarded-increment-'));
987+
dirs.push(dir);
988+
return replica(join(dir, 'auth.db'));
989+
};
990+
991+
const eq = (field: string, value: unknown): Where => ({ field, value, operator: 'eq', connector: 'AND' });
992+
const stored = async (driver: SqlDriver, object: string, id: unknown) =>
993+
((await driver.find(object, { object, where: { id } } as never)) as Array<Record<string, unknown>>)[0];
994+
995+
const twoFactorRow = async (adapter: Adapter, backupCodes = 'codes-v1') => {
996+
const user = await adapter.create({ model: 'user', data: { email: `u${Math.random()}@example.com`, name: 'U', emailVerified: false } });
997+
return adapter.create({ model: 'twoFactor', data: { userId: user.id, secret: 'totp-secret', backupCodes } });
998+
};
999+
const teamRow = async (adapter: Adapter) => {
1000+
const org = await adapter.create({ model: 'organization', data: { name: 'Org', slug: `org-${Math.random()}`.replace('.', '') } });
1001+
return adapter.create({ model: 'team', data: { name: 'Team', organizationId: org.id, memberCount: 0 } });
1002+
};
1003+
1004+
// A guard on a stored value, and an absolute `set` that moves it.
1005+
const swapGuardedValue = (adapter: Adapter, id: unknown, from: string, to: string) =>
1006+
adapter.incrementOne({ model: 'twoFactor', where: [eq('id', id), eq('backupCodes', from)], increment: {}, set: { backupCodes: to } });
1007+
// No guard beyond the row: +1.
1008+
const incrementUnguarded = (adapter: Adapter, id: unknown) =>
1009+
adapter.incrementOne({ model: 'twoFactor', where: [eq('id', id)], increment: { failedVerificationCount: 1 } });
1010+
// A guard on the counter itself (below a bound), +1.
1011+
const incrementBelowBound = (adapter: Adapter, id: unknown, maximum: number) =>
1012+
adapter.incrementOne({
1013+
model: 'team',
1014+
where: [eq('id', id), { field: 'memberCount', value: maximum, operator: 'lt', connector: 'AND' }],
1015+
increment: { memberCount: 1 },
1016+
});
1017+
1018+
it('a guard on a stored value admits exactly one of two concurrent conditional writes on two engines over one database', async () => {
1019+
const [a, b] = await twoReplicas();
1020+
const row = await twoFactorRow(a.adapter);
1021+
1022+
const answers = await Promise.all([
1023+
swapGuardedValue(a.adapter, row.id, 'codes-v1', 'codes-v2-by-a'),
1024+
swapGuardedValue(b.adapter, row.id, 'codes-v1', 'codes-v2-by-b'),
1025+
]);
1026+
1027+
expect(answers.filter((r) => r !== null), 'conditional writes applied').toHaveLength(1);
1028+
const accepted = answers.find((r) => r !== null)!;
1029+
expect((await stored(a.driver, 'sys_two_factor', row.id)).backup_codes).toBe(accepted.backupCodes);
1030+
});
1031+
1032+
it('two concurrent unguarded increments on two engines over one database are both applied', async () => {
1033+
const [a, b] = await twoReplicas();
1034+
const row = await twoFactorRow(a.adapter);
1035+
1036+
const answers = await Promise.all([incrementUnguarded(a.adapter, row.id), incrementUnguarded(b.adapter, row.id)]);
1037+
1038+
expect(answers.map((r) => r?.failedVerificationCount).sort()).toEqual([1, 2]);
1039+
expect((await stored(a.driver, 'sys_two_factor', row.id)).failed_verification_count).toBe(2);
1040+
});
1041+
1042+
it('a guard on the counter admits exactly one of two concurrent increments up to its bound on two engines over one database', async () => {
1043+
const [a, b] = await twoReplicas();
1044+
const team = await teamRow(a.adapter);
1045+
1046+
const answers = await Promise.all([incrementBelowBound(a.adapter, team.id, 1), incrementBelowBound(b.adapter, team.id, 1)]);
1047+
1048+
expect(answers.filter((r) => r !== null), 'increments applied').toHaveLength(1);
1049+
expect(answers.find((r) => r !== null)).toMatchObject({ id: team.id, memberCount: 1 });
1050+
expect((await stored(a.driver, 'sys_team', team.id)).member_count).toBe(1);
1051+
});
1052+
1053+
it('one caller at a time: each guarded increment applies, and a guard that no longer holds changes nothing', async () => {
1054+
const { adapter, driver } = await oneReplica();
1055+
const row = await twoFactorRow(adapter);
1056+
const team = await teamRow(adapter);
1057+
1058+
expect(await swapGuardedValue(adapter, row.id, 'codes-v1', 'codes-v2')).toMatchObject({ id: row.id, backupCodes: 'codes-v2' });
1059+
expect(await swapGuardedValue(adapter, row.id, 'codes-v1', 'codes-v3'), 'the same guard a second time').toBeNull();
1060+
expect((await stored(driver, 'sys_two_factor', row.id)).backup_codes).toBe('codes-v2');
1061+
1062+
expect((await incrementUnguarded(adapter, row.id))?.failedVerificationCount).toBe(1);
1063+
expect((await incrementUnguarded(adapter, row.id))?.failedVerificationCount).toBe(2);
1064+
1065+
expect(await incrementBelowBound(adapter, team.id, 2)).toMatchObject({ memberCount: 1 });
1066+
expect(await incrementBelowBound(adapter, team.id, 2)).toMatchObject({ memberCount: 2 });
1067+
expect(await incrementBelowBound(adapter, team.id, 2), 'the bound is reached').toBeNull();
1068+
expect((await stored(driver, 'sys_team', team.id)).member_count).toBe(2);
1069+
1070+
expect(await incrementUnguarded(adapter, 'no-such-row'), 'a row that does not exist').toBeNull();
1071+
});
1072+
1073+
it('the row a guarded increment answers carries the fields a read of that row carries, internal columns included', async () => {
1074+
const { adapter } = await oneReplica();
1075+
const row = await twoFactorRow(adapter);
1076+
const team = await teamRow(adapter);
1077+
const fieldsOf = (r: Record<string, unknown> | null) => Object.keys(r ?? {}).sort();
1078+
const read = (model: string, id: unknown) => adapter.findOne({ model, where: [eq('id', id)] });
1079+
1080+
const counted = await incrementUnguarded(adapter, row.id);
1081+
expect(counted).toMatchObject({ id: row.id, secret: 'totp-secret', backupCodes: 'codes-v1', failedVerificationCount: 1 });
1082+
expect(fieldsOf(counted)).toEqual(fieldsOf(await read('twoFactor', row.id)));
1083+
1084+
const swapped = await swapGuardedValue(adapter, row.id, 'codes-v1', 'codes-v2');
1085+
expect(swapped).toMatchObject({ id: row.id, secret: 'totp-secret', backupCodes: 'codes-v2' });
1086+
expect(fieldsOf(swapped)).toEqual(fieldsOf(await read('twoFactor', row.id)));
1087+
1088+
const reserved = await incrementBelowBound(adapter, team.id, 5);
1089+
expect(reserved).toMatchObject({ id: team.id, memberCount: 1 });
1090+
expect(fieldsOf(reserved)).toEqual(fieldsOf(await read('team', team.id)));
1091+
});
1092+
1093+
it('a counter stored as null counts from zero', async () => {
1094+
const { adapter, driver } = await oneReplica();
1095+
const row = await twoFactorRow(adapter);
1096+
await driver.update('sys_two_factor', row.id as string, { failed_verification_count: null });
1097+
1098+
expect((await incrementUnguarded(adapter, row.id))?.failedVerificationCount).toBe(1);
1099+
expect((await stored(driver, 'sys_two_factor', row.id)).failed_verification_count).toBe(1);
1100+
});
1101+
});

0 commit comments

Comments
 (0)