@ultimat3/testing 30.9.0 → 31.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/CLAUDE.md +46 -55
  2. package/README.md +179 -39
  3. package/package.json +23 -17
  4. package/src/ai-conformance-answer.ts +67 -0
  5. package/src/ai-gateway-conformance.ts +105 -0
  6. package/src/ai-provider-conformance.ts +69 -0
  7. package/src/ai-provider-transport-conformance.ts +170 -0
  8. package/src/audit-sink-conformance.ts +204 -0
  9. package/src/auth-adapter-conformance-credentials.ts +124 -0
  10. package/src/auth-adapter-conformance-mfa.ts +70 -0
  11. package/src/auth-adapter-conformance-passkeys.ts +133 -0
  12. package/src/auth-adapter-conformance-sessions.ts +115 -0
  13. package/src/auth-adapter-conformance-support.ts +71 -0
  14. package/src/auth-adapter-conformance-users.ts +128 -0
  15. package/src/auth-adapter-conformance.ts +34 -0
  16. package/src/auth-limiter-factory-conformance.ts +224 -0
  17. package/src/auth-server-store-conformance-records.ts +69 -0
  18. package/src/auth-server-store-conformance.ts +208 -0
  19. package/src/cache-tier-conformance-checks.ts +142 -0
  20. package/src/cache-tier-conformance.ts +24 -0
  21. package/src/cassette-format.ts +8 -13
  22. package/src/cassette-record.ts +1 -1
  23. package/src/cdp-browser.ts +10 -11
  24. package/src/cdp-e2e-page.ts +2 -2
  25. package/src/cdp-e2e-session.ts +2 -2
  26. package/src/cdp-network-probe.ts +1 -1
  27. package/src/cdp-offline-script.ts +2 -2
  28. package/src/clock-conformance.ts +126 -0
  29. package/src/conformance.ts +239 -0
  30. package/src/e2e-browser-handle.ts +1 -2
  31. package/src/e2e-error-codes.ts +17 -16
  32. package/src/e2e-run.ts +4 -3
  33. package/src/embedder-conformance.ts +101 -0
  34. package/src/entity-conformance-aggregates.ts +210 -0
  35. package/src/entity-conformance-batches.ts +216 -0
  36. package/src/entity-conformance-bulk.ts +379 -0
  37. package/src/entity-conformance-checks.ts +27 -0
  38. package/src/entity-conformance-entities.ts +52 -0
  39. package/src/entity-conformance-locks.ts +286 -0
  40. package/src/entity-conformance-matrix.ts +397 -0
  41. package/src/entity-conformance-reads.ts +241 -0
  42. package/src/entity-conformance-support.ts +56 -0
  43. package/src/entity-conformance-tenancy.ts +296 -0
  44. package/src/entity-conformance-values.ts +305 -0
  45. package/src/entity-conformance-versions.ts +60 -0
  46. package/src/entity-conformance-writes.ts +348 -0
  47. package/src/entity-driver-conformance.ts +103 -0
  48. package/src/error-groups-store-conformance.ts +198 -0
  49. package/src/error-reporter-conformance.ts +119 -0
  50. package/src/errors.ts +20 -2
  51. package/src/event-bus-conformance.ts +161 -0
  52. package/src/exercise-drift-hint.ts +4 -1
  53. package/src/exercise-judge.ts +5 -3
  54. package/src/exercise-override-line.ts +98 -0
  55. package/src/exercise-report.ts +138 -115
  56. package/src/exercise-room-mail.ts +40 -0
  57. package/src/exercise.ts +33 -29
  58. package/src/factories.ts +192 -179
  59. package/src/factory-api.ts +131 -0
  60. package/src/factory-associations.ts +67 -0
  61. package/src/factory-errors.ts +38 -0
  62. package/src/factory-lint.ts +92 -0
  63. package/src/factory-persist.ts +74 -16
  64. package/src/factory-pipeline.ts +191 -0
  65. package/src/factory-registry.ts +2 -1
  66. package/src/factory-types.ts +131 -0
  67. package/src/failure-store-conformance.ts +137 -0
  68. package/src/fixture-jobs.ts +27 -11
  69. package/src/fixture-mail.ts +7 -7
  70. package/src/fixture-seed.ts +111 -0
  71. package/src/fixture-statements.ts +68 -52
  72. package/src/framework-fixtures.ts +1 -1
  73. package/src/idempotency-store-conformance.ts +186 -0
  74. package/src/idempotency-store-replay-conformance.ts +140 -0
  75. package/src/idempotency-store-tx-conformance.ts +132 -0
  76. package/src/idempotency-store-world-conformance.ts +82 -0
  77. package/src/identity-provider-conformance.ts +144 -0
  78. package/src/image-transform-conformance.ts +89 -0
  79. package/src/index.ts +68 -157
  80. package/src/isr-store-conformance.ts +113 -0
  81. package/src/job-sim-effects.ts +19 -31
  82. package/src/job-sim-world.ts +6 -15
  83. package/src/lease-store-conformance.ts +195 -0
  84. package/src/mail-driver-conformance.ts +108 -0
  85. package/src/matcher-doubles.ts +104 -0
  86. package/src/matcher-stub.ts +78 -0
  87. package/src/matcher-surface.ts +21 -0
  88. package/src/matchers.ts +19 -1
  89. package/src/mcp-confirmation-store-conformance.ts +262 -0
  90. package/src/meter-store-conformance.ts +135 -0
  91. package/src/notify-digest-conformance.ts +133 -0
  92. package/src/notify-inbox-conformance.ts +130 -0
  93. package/src/notify-ledger-conformance.ts +134 -0
  94. package/src/notify-preference-conformance.ts +49 -0
  95. package/src/notify-stores-conformance.ts +73 -0
  96. package/src/outbox-store-conformance-claims.ts +112 -0
  97. package/src/outbox-store-conformance-subject.ts +65 -0
  98. package/src/outbox-store-conformance.ts +71 -0
  99. package/src/per-test-reset.ts +55 -20
  100. package/src/preload.ts +4 -2
  101. package/src/purge-conformance.ts +79 -0
  102. package/src/push-device-conformance.ts +124 -0
  103. package/src/push-subscription-conformance.ts +123 -0
  104. package/src/quiet-logs.ts +4 -4
  105. package/src/rate-limit-store-conformance.ts +178 -0
  106. package/src/registry-leak-error.ts +8 -1
  107. package/src/scale-sweep-run.ts +6 -9
  108. package/src/scrape-driver-conformance-frame-checks.ts +97 -0
  109. package/src/scrape-driver-conformance-page-checks.ts +114 -0
  110. package/src/scrape-driver-conformance-site.ts +84 -0
  111. package/src/scrape-driver-conformance.ts +34 -0
  112. package/src/sealed-network.ts +20 -2
  113. package/src/search-index-conformance-list.ts +76 -0
  114. package/src/search-index-conformance-support.ts +69 -0
  115. package/src/search-index-conformance-versions.ts +66 -0
  116. package/src/search-index-conformance.ts +126 -0
  117. package/src/secret-source-conformance.ts +91 -0
  118. package/src/seed-factories.ts +57 -0
  119. package/src/seed-writer.ts +8 -19
  120. package/src/semantic-cache-factory-conformance.ts +86 -0
  121. package/src/sms-transport-conformance.ts +102 -0
  122. package/src/step-store-conformance.ts +171 -0
  123. package/src/storage-conformance-read-checks.ts +132 -0
  124. package/src/storage-conformance-shape.ts +121 -0
  125. package/src/storage-conformance-stream-checks.ts +226 -0
  126. package/src/storage-conformance.ts +34 -0
  127. package/src/stub-action.ts +24 -0
  128. package/src/stub-errors.ts +86 -0
  129. package/src/stub-job.ts +30 -0
  130. package/src/stub-query.ts +25 -0
  131. package/src/stub-script.ts +76 -0
  132. package/src/stub-stack.ts +29 -0
  133. package/src/stub.ts +73 -0
  134. package/src/swap-adapter.ts +135 -0
  135. package/src/test-scope.ts +96 -0
  136. package/src/test-types.ts +1 -1
  137. package/src/totp-replay-guard-conformance.ts +76 -0
  138. package/src/transport-conformance.ts +179 -0
  139. package/src/upload-scanner-conformance.ts +112 -0
  140. package/src/vector-store-conformance-checks.ts +174 -0
  141. package/src/vector-store-conformance.ts +21 -0
  142. package/src/cdp-connection.ts +0 -291
  143. package/src/cdp-errors.ts +0 -179
  144. package/src/cdp-launch-attempt.ts +0 -224
  145. package/src/cdp-launch-candidates.ts +0 -62
  146. package/src/cdp-launch-profile.ts +0 -106
  147. package/src/cdp-launch-reap.ts +0 -68
  148. package/src/cdp-launch-wire.ts +0 -171
  149. package/src/cdp-launch.ts +0 -175
  150. package/src/cdp-pipe.ts +0 -77
  151. package/src/cdp-wire-watch.ts +0 -113
@@ -0,0 +1,124 @@
1
+ // `VerificationStore`, `AccountStore` and `ApiKeyStore`, for `authAdapterConformance`: a token is
2
+ // consumed only on a hash match, in one step, stamped from the adapter's clock; a relinked
3
+ // provider account keeps its owner; api keys list newest first and revoke once.
4
+
5
+ import { expect } from 'bun:test';
6
+ import type { AuthAccount, AuthApiKeyRecord, AuthVerification } from '@ultimat3/auth';
7
+ import type { AuthAdapterCheck } from './auth-adapter-conformance-support';
8
+ import { emailOf, idOf, seedUser } from './auth-adapter-conformance-support';
9
+
10
+ const verification = (identifier: string, issuedAt: Date, tokenHash: string): AuthVerification => ({
11
+ id: idOf('verification'),
12
+ purpose: 'password-reset',
13
+ identifier,
14
+ tokenHash,
15
+ expiresAt: new Date(issuedAt.getTime() + 3_600_000),
16
+ consumedAt: null,
17
+ createdAt: issuedAt,
18
+ });
19
+
20
+ const apiKey = (id: string, owner: string, createdAt: string): AuthApiKeyRecord => ({
21
+ id,
22
+ prefix: `ult_dev_${id}`,
23
+ keyHash: 'hash',
24
+ userId: owner,
25
+ orgId: null,
26
+ scopes: [],
27
+ lastUsedAt: null,
28
+ expiresAt: null,
29
+ revokedAt: null,
30
+ createdAt: new Date(createdAt),
31
+ });
32
+
33
+ export const AUTH_ADAPTER_CREDENTIAL_CHECKS: readonly AuthAdapterCheck[] = [
34
+ {
35
+ name: 'a verification is consumed once, on a hash match only, stamped from the adapter’s clock',
36
+ async run({ adapter, clock }) {
37
+ const identifier = emailOf('reset');
38
+ // Issued an hour ago: the redemption stamp must be NOW, never the issue time.
39
+ const issuedAt = new Date(clock.now().getTime() - 3_600_000);
40
+ await adapter.putVerification(verification(identifier, issuedAt, 'digest'));
41
+ expect(await adapter.takeVerification('password-reset', identifier, 'wrong')).toBeNull();
42
+ const taken = await adapter.takeVerification('password-reset', identifier, 'digest');
43
+ expect([taken?.consumedAt?.getTime(), taken?.createdAt.getTime()]).toEqual([
44
+ clock.now().getTime(),
45
+ issuedAt.getTime(),
46
+ ]);
47
+ expect(await adapter.takeVerification('password-reset', identifier, 'digest')).toBeNull();
48
+ },
49
+ },
50
+ {
51
+ name: 'issuing a new token for one purpose and address invalidates the previous one',
52
+ async run({ adapter, clock }) {
53
+ const identifier = emailOf('reissue');
54
+ await adapter.putVerification(verification(identifier, clock.now(), 'first'));
55
+ await adapter.putVerification(verification(identifier, clock.now(), 'second'));
56
+ expect(await adapter.takeVerification('password-reset', identifier, 'first')).toBeNull();
57
+ expect(
58
+ (await adapter.takeVerification('password-reset', identifier, 'second'))?.tokenHash,
59
+ ).toBe('second');
60
+ },
61
+ },
62
+ {
63
+ name: 'relinking a linked provider account keeps its owner, id and age, and moves the tokens',
64
+ async run({ adapter }) {
65
+ const [owner, taker] = [await seedUser(adapter), await seedUser(adapter)];
66
+ const providerAccountId = idOf('gh');
67
+ const first: AuthAccount = {
68
+ id: crypto.randomUUID(),
69
+ userId: owner,
70
+ provider: 'github',
71
+ providerAccountId,
72
+ accessToken: 'gho_first',
73
+ refreshToken: null,
74
+ expiresAt: null,
75
+ createdAt: new Date('2026-08-09T12:00:00.000Z'),
76
+ };
77
+ await adapter.linkAccount(first);
78
+ const answered = await adapter.linkAccount({
79
+ ...first,
80
+ id: crypto.randomUUID(),
81
+ userId: taker,
82
+ accessToken: 'gho_second',
83
+ createdAt: new Date('2026-09-01T12:00:00.000Z'),
84
+ });
85
+ const stored = await adapter.findAccount('github', providerAccountId);
86
+ for (const account of [answered, stored]) {
87
+ expect([account?.id, account?.userId, account?.createdAt.getTime()]).toEqual([
88
+ first.id,
89
+ owner,
90
+ first.createdAt.getTime(),
91
+ ]);
92
+ expect(account?.accessToken).toBe('gho_second');
93
+ }
94
+ expect((await adapter.listAccounts(owner)).map((row) => row.id)).toEqual([first.id]);
95
+ expect(await adapter.listAccounts(taker)).toEqual([]);
96
+ },
97
+ },
98
+ {
99
+ name: 'listApiKeys answers newest first, then by id descending',
100
+ async run({ adapter }) {
101
+ const owner = crypto.randomUUID();
102
+ const [a1, b2, c3] = [idOf('a1'), idOf('b2'), idOf('c3')];
103
+ await adapter.putApiKey(apiKey(a1, owner, '2026-08-01T00:00:00.000Z'));
104
+ await adapter.putApiKey(apiKey(c3, owner, '2026-09-01T00:00:00.000Z'));
105
+ await adapter.putApiKey(apiKey(b2, owner, '2026-09-01T00:00:00.000Z'));
106
+ // `conformance-c3-…` sorts after `conformance-b2-…`: the tie on created_at is broken by id.
107
+ expect((await adapter.listApiKeys(owner)).map((key) => key.id)).toEqual([c3, b2, a1]);
108
+ },
109
+ },
110
+ {
111
+ name: 'an api key is found, touched, and revoked exactly once',
112
+ async run({ adapter, clock }) {
113
+ const id = idOf('key');
114
+ await adapter.putApiKey(apiKey(id, crypto.randomUUID(), '2026-08-01T00:00:00.000Z'));
115
+ await adapter.touchApiKey(id, clock.now());
116
+ expect((await adapter.findApiKeyById(id))?.lastUsedAt?.getTime()).toBe(clock.now().getTime());
117
+ expect(await adapter.revokeApiKey(id, clock.now())).toBe(true);
118
+ expect(await adapter.revokeApiKey(id, clock.now())).toBe(false);
119
+ expect((await adapter.findApiKeyById(id))?.revokedAt?.getTime()).toBe(clock.now().getTime());
120
+ expect(await adapter.findApiKeyById(idOf('nobody'))).toBeNull();
121
+ expect(await adapter.revokeApiKey(idOf('nobody'), clock.now())).toBe(false);
122
+ },
123
+ },
124
+ ];
@@ -0,0 +1,70 @@
1
+ // The members a second factor needs from `UserStore`, for `authAdapterConformance`: every stored
2
+ // secret enumerated as stored, a compare-and-set on it, and a recovery code consumed in ONE
3
+ // atomic step — two concurrent redemptions of one code must not both find it.
4
+
5
+ import { expect } from 'bun:test';
6
+ import type { AuthAdapterCheck } from './auth-adapter-conformance-support';
7
+ import { own, seedUser } from './auth-adapter-conformance-support';
8
+
9
+ const REDEEMERS = 10;
10
+
11
+ export const AUTH_ADAPTER_MFA_CHECKS: readonly AuthAdapterCheck[] = [
12
+ {
13
+ name: 'listUsersWithMfaSecret answers every enrolled user as stored, by id, and nobody else',
14
+ async run({ adapter }) {
15
+ const users = [await seedUser(adapter), await seedUser(adapter), await seedUser(adapter)];
16
+ const [first, second, unenrolled] = users as [string, string, string];
17
+ const enrolled = async () =>
18
+ own(await adapter.listUsersWithMfaSecret(), users, (row) => row.userId);
19
+ expect(await enrolled()).toEqual([]);
20
+ await adapter.updateUser(first, { mfaSecret: 'JBSWY3DPEHPK3PXP' });
21
+ await adapter.updateUser(second, { mfaSecret: 'x1.not-really.sealed.value' });
22
+ const expected = [
23
+ { userId: first, mfaSecret: 'JBSWY3DPEHPK3PXP' },
24
+ { userId: second, mfaSecret: 'x1.not-really.sealed.value' },
25
+ ].sort((a, b) => (a.userId < b.userId ? -1 : 1));
26
+ expect(await enrolled()).toEqual(expected);
27
+ expect(expected.map((row) => row.userId)).not.toContain(unenrolled);
28
+ },
29
+ },
30
+ {
31
+ name: 'replaceMfaSecret writes only while the row still holds what was read',
32
+ async run({ adapter }) {
33
+ const [ada, grace] = [await seedUser(adapter), await seedUser(adapter)];
34
+ await adapter.updateUser(ada, { mfaSecret: 'old' });
35
+ expect(await adapter.replaceMfaSecret(ada, 'not-what-is-there', 'next')).toBe(false);
36
+ expect(await adapter.replaceMfaSecret(grace, 'old', 'next')).toBe(false);
37
+ expect((await adapter.findUserById(ada))?.mfaSecret).toBe('old');
38
+ expect((await adapter.findUserById(grace))?.mfaSecret).toBeNull();
39
+ expect(await adapter.replaceMfaSecret(ada, 'old', 'next')).toBe(true);
40
+ expect(await adapter.replaceMfaSecret(ada, 'old', 'again')).toBe(false);
41
+ expect((await adapter.findUserById(ada))?.mfaSecret).toBe('next');
42
+ },
43
+ },
44
+ {
45
+ name: 'consumeRecoveryCode removes exactly the hash it was given, once, from that user',
46
+ async run({ adapter }) {
47
+ const [ada, grace] = [await seedUser(adapter), await seedUser(adapter)];
48
+ await adapter.updateUser(ada, { recoveryCodeHashes: ['h1', 'h2', 'h3'] });
49
+ await adapter.updateUser(grace, { recoveryCodeHashes: ['h2'] });
50
+ expect(await adapter.consumeRecoveryCode(ada, 'h2')).toBe(true);
51
+ expect(await adapter.consumeRecoveryCode(ada, 'h2')).toBe(false);
52
+ expect(await adapter.consumeRecoveryCode(ada, 'never-issued')).toBe(false);
53
+ expect(await adapter.consumeRecoveryCode(crypto.randomUUID(), 'h1')).toBe(false);
54
+ expect((await adapter.findUserById(ada))?.recoveryCodeHashes).toEqual(['h1', 'h3']);
55
+ expect((await adapter.findUserById(grace))?.recoveryCodeHashes).toEqual(['h2']);
56
+ },
57
+ },
58
+ {
59
+ name: `${REDEEMERS} concurrent redemptions of one recovery code: exactly one is true`,
60
+ async run({ adapter }) {
61
+ const ada = await seedUser(adapter);
62
+ await adapter.updateUser(ada, { recoveryCodeHashes: ['h1', 'h2'] });
63
+ const answers = await Promise.all(
64
+ Array.from({ length: REDEEMERS }, () => adapter.consumeRecoveryCode(ada, 'h1')),
65
+ );
66
+ expect(answers.filter(Boolean)).toHaveLength(1);
67
+ expect((await adapter.findUserById(ada))?.recoveryCodeHashes).toEqual(['h2']);
68
+ },
69
+ },
70
+ ];
@@ -0,0 +1,133 @@
1
+ // `PasskeyStore`, for `authAdapterConformance`: a credential id is globally unique, the counter
2
+ // advances by compare-and-set (two racing assertions must not both move it — the cloned-
3
+ // authenticator signal), a delete is the owner's, and a challenge is single-use for its ceremony.
4
+
5
+ import { expect } from 'bun:test';
6
+ import type { PasskeyChallengeRecord, PasskeyCredential, PasskeyEvidence } from '@ultimat3/auth';
7
+ import type { AuthAdapterCheck } from './auth-adapter-conformance-support';
8
+ import { idOf, refusal, seedUser } from './auth-adapter-conformance-support';
9
+
10
+ const NOW = new Date('2026-11-06T12:00:00.000Z');
11
+ const later = (ms: number): Date => new Date(NOW.getTime() + ms);
12
+ const ADVANCERS = 8;
13
+
14
+ const credential = (owner: string, signCount = 0, createdAt = NOW): PasskeyCredential => ({
15
+ id: idOf('cred'),
16
+ userId: owner,
17
+ publicKey: 'pQECAyYgASFYIA',
18
+ algorithm: -7,
19
+ signCount,
20
+ transports: ['internal'],
21
+ createdAt,
22
+ lastUsedAt: null,
23
+ });
24
+
25
+ const challenge = (expiresInMs: number, createdAt = NOW): PasskeyChallengeRecord => ({
26
+ id: idOf('challenge'),
27
+ ceremony: 'login',
28
+ userId: null,
29
+ digest: null,
30
+ nonce: null,
31
+ expiresAt: new Date(createdAt.getTime() + expiresInMs),
32
+ createdAt,
33
+ });
34
+
35
+ const evidence = (owner: string, digest: string, createdAt: Date): PasskeyEvidence => ({
36
+ id: idOf('evidence'),
37
+ userId: owner,
38
+ credentialId: idOf('cred'),
39
+ digest,
40
+ nonce: 'bm9uY2U',
41
+ authenticatorData: 'YXV0aA',
42
+ clientDataJSON: 'Y2xpZW50',
43
+ signature: 'c2ln',
44
+ publicKey: 'pQECAyYgASFYIA',
45
+ algorithm: -7,
46
+ createdAt,
47
+ });
48
+
49
+ export const AUTH_ADAPTER_PASSKEY_CHECKS: readonly AuthAdapterCheck[] = [
50
+ {
51
+ name: 'a passkey round-trips, lists oldest first, and a second at one id is refused',
52
+ async run({ adapter }) {
53
+ const [ada, grace] = [await seedUser(adapter), await seedUser(adapter)];
54
+ const [older, newer] = [credential(ada), credential(ada, 0, later(1))];
55
+ await adapter.putPasskey(newer);
56
+ await adapter.putPasskey(older);
57
+ expect((await adapter.listPasskeys(ada)).map((row) => row.id)).toEqual([older.id, newer.id]);
58
+ expect(await adapter.findPasskey(older.id)).toEqual(older);
59
+ expect(await refusal(adapter.putPasskey({ ...older, userId: grace }))).toStartWith(
60
+ 'X_AUTH_WRITE_FAILED',
61
+ );
62
+ expect((await adapter.findPasskey(older.id))?.userId).toBe(ada);
63
+ },
64
+ },
65
+ {
66
+ name: 'the counter advances only from the value it was read at, stamping its use',
67
+ async run({ adapter }) {
68
+ const row = credential(await seedUser(adapter), 4);
69
+ await adapter.putPasskey(row);
70
+ expect(await adapter.advancePasskeyCounter(row.id, 4, 5, later(5))).toBe(true);
71
+ expect(await adapter.advancePasskeyCounter(row.id, 4, 6, later(6))).toBe(false);
72
+ const stored = await adapter.findPasskey(row.id);
73
+ expect([stored?.signCount, stored?.lastUsedAt?.getTime()]).toEqual([5, later(5).getTime()]);
74
+ },
75
+ },
76
+ {
77
+ name: `${ADVANCERS} racing advances from one counter value: exactly one lands`,
78
+ async run({ adapter }) {
79
+ const row = credential(await seedUser(adapter), 1);
80
+ await adapter.putPasskey(row);
81
+ const answers = await Promise.all(
82
+ Array.from({ length: ADVANCERS }, (_, index) =>
83
+ adapter.advancePasskeyCounter(row.id, 1, 2 + index, NOW),
84
+ ),
85
+ );
86
+ expect(answers.filter(Boolean)).toHaveLength(1);
87
+ },
88
+ },
89
+ {
90
+ name: 'a passkey is deleted only by its owner',
91
+ async run({ adapter }) {
92
+ const [ada, grace] = [await seedUser(adapter), await seedUser(adapter)];
93
+ const row = credential(ada);
94
+ await adapter.putPasskey(row);
95
+ expect(await adapter.deletePasskey(grace, row.id)).toBe(false);
96
+ expect(await adapter.deletePasskey(ada, row.id)).toBe(true);
97
+ expect(await adapter.findPasskey(row.id)).toBeNull();
98
+ },
99
+ },
100
+ {
101
+ name: 'a challenge is taken once, and only for its own ceremony',
102
+ async run({ adapter }) {
103
+ const row = challenge(60_000);
104
+ await adapter.putPasskeyChallenge(row);
105
+ expect(await adapter.takePasskeyChallenge(row.id, 'step-up')).toBeNull();
106
+ expect((await adapter.takePasskeyChallenge(row.id, 'login'))?.id).toBe(row.id);
107
+ expect(await adapter.takePasskeyChallenge(row.id, 'login')).toBeNull();
108
+ },
109
+ },
110
+ {
111
+ name: 'issuing a challenge sweeps the ones already expired and keeps the live ones',
112
+ async run({ adapter }) {
113
+ const [stale, live] = [challenge(1_000), challenge(600_000)];
114
+ await adapter.putPasskeyChallenge(stale);
115
+ await adapter.putPasskeyChallenge(live);
116
+ await adapter.putPasskeyChallenge(challenge(60_000, later(5_000)));
117
+ expect(await adapter.takePasskeyChallenge(stale.id, 'login')).toBeNull();
118
+ expect((await adapter.takePasskeyChallenge(live.id, 'login'))?.id).toBe(live.id);
119
+ },
120
+ },
121
+ {
122
+ name: 'evidence lists every approval of one digest, oldest first, and no other digest',
123
+ async run({ adapter }) {
124
+ const owner = await seedUser(adapter);
125
+ const digest = idOf('digest');
126
+ const [first, second] = [evidence(owner, digest, NOW), evidence(owner, digest, later(1))];
127
+ await adapter.putPasskeyEvidence(second);
128
+ await adapter.putPasskeyEvidence(first);
129
+ await adapter.putPasskeyEvidence(evidence(owner, idOf('other'), NOW));
130
+ expect(await adapter.listPasskeyEvidence(digest)).toEqual([first, second]);
131
+ },
132
+ },
133
+ ];
@@ -0,0 +1,115 @@
1
+ // `SessionStore` and the org sweep, for `authAdapterConformance`: a delete answers whether THIS
2
+ // call removed the row (`rotateSession` claims the id with it), every revocation counts what it
3
+ // killed, and "before an instant" is strictly before.
4
+
5
+ import { expect } from 'bun:test';
6
+ import type { AuthSession } from '@ultimat3/auth';
7
+ import type { AuthAdapterCheck } from './auth-adapter-conformance-support';
8
+ import { idOf, seedUser } from './auth-adapter-conformance-support';
9
+
10
+ const T0 = Date.parse('2026-09-01T10:00:00.000Z');
11
+ const at = (seconds: number): Date => new Date(T0 + seconds * 1000);
12
+ const DELETERS = 8;
13
+
14
+ const session = (owner: string, createdAt = at(0), lastSeenAt = createdAt): AuthSession => ({
15
+ id: idOf('session'),
16
+ userId: owner,
17
+ tokenHash: 'digest-of-the-secret-half',
18
+ createdAt,
19
+ absoluteExpiresAt: at(86_400),
20
+ lastSeenAt,
21
+ ip: '203.0.113.7',
22
+ userAgent: 'conformance',
23
+ mfaSatisfied: false,
24
+ });
25
+
26
+ export const AUTH_ADAPTER_SESSION_CHECKS: readonly AuthAdapterCheck[] = [
27
+ {
28
+ name: 'a session round-trips, a patch moves only what it names, and nobody is null',
29
+ async run({ adapter }) {
30
+ const row = session(await seedUser(adapter));
31
+ await adapter.createSession(row);
32
+ expect(await adapter.getSession(row.id)).toEqual(row);
33
+ const patched = await adapter.updateSession(row.id, {
34
+ lastSeenAt: at(60),
35
+ mfaSatisfied: true,
36
+ ip: null,
37
+ });
38
+ expect(patched).toEqual({ ...row, lastSeenAt: at(60), mfaSatisfied: true, ip: null });
39
+ expect(await adapter.getSession(idOf('nobody'))).toBeNull();
40
+ expect(await adapter.updateSession(idOf('nobody'), { lastSeenAt: at(1) })).toBeNull();
41
+ },
42
+ },
43
+ {
44
+ name: `${DELETERS} concurrent deletes of one session: exactly one answers true`,
45
+ async run({ adapter }) {
46
+ const row = session(await seedUser(adapter));
47
+ await adapter.createSession(row);
48
+ const answers = await Promise.all(
49
+ Array.from({ length: DELETERS }, () => adapter.deleteSession(row.id)),
50
+ );
51
+ expect(answers.filter(Boolean)).toHaveLength(1);
52
+ expect(await adapter.getSession(row.id)).toBeNull();
53
+ },
54
+ },
55
+ {
56
+ name: 'listSessions answers one user’s sessions, most recently seen first',
57
+ async run({ adapter }) {
58
+ const [owner, other] = [await seedUser(adapter), await seedUser(adapter)];
59
+ const older = session(owner, at(0), at(10));
60
+ const newer = session(owner, at(0), at(20));
61
+ await adapter.createSession(older);
62
+ await adapter.createSession(newer);
63
+ await adapter.createSession(session(other));
64
+ expect((await adapter.listSessions(owner)).map((row) => row.id)).toEqual([
65
+ newer.id,
66
+ older.id,
67
+ ]);
68
+ },
69
+ },
70
+ {
71
+ name: 'deleteOtherSessions keeps the one named and counts the rest; ForUser takes them all',
72
+ async run({ adapter }) {
73
+ const [owner, other] = [await seedUser(adapter), await seedUser(adapter)];
74
+ const [keep, drop, untouched] = [session(owner), session(owner), session(other)];
75
+ for (const row of [keep, drop, untouched]) await adapter.createSession(row);
76
+ expect(await adapter.deleteOtherSessions(owner, keep.id)).toBe(1);
77
+ expect([await adapter.getSession(keep.id), await adapter.getSession(drop.id)]).toEqual([
78
+ keep,
79
+ null,
80
+ ]);
81
+ expect(await adapter.deleteSessionsForUser(owner)).toBe(1);
82
+ expect(await adapter.getSession(keep.id)).toBeNull();
83
+ expect(await adapter.getSession(untouched.id)).toEqual(untouched);
84
+ },
85
+ },
86
+ {
87
+ name: 'deleteSessionsForOrg takes every member’s sessions, through the user’s org',
88
+ async run({ adapter }) {
89
+ const orgId = crypto.randomUUID();
90
+ const [member, outsider] = [await seedUser(adapter, { orgId }), await seedUser(adapter)];
91
+ const [inside, outside] = [session(member), session(outsider)];
92
+ await adapter.createSession(inside);
93
+ await adapter.createSession(outside);
94
+ expect(await adapter.deleteSessionsForOrg(orgId)).toBe(1);
95
+ expect([await adapter.getSession(inside.id), await adapter.getSession(outside.id)]).toEqual([
96
+ null,
97
+ outside,
98
+ ]);
99
+ },
100
+ },
101
+ {
102
+ name: 'deleteSessionsCreatedBefore is strict: a session created at the instant survives',
103
+ async run({ adapter }) {
104
+ const owner = await seedUser(adapter);
105
+ const [before, exactly] = [session(owner, at(-1)), session(owner, at(0))];
106
+ await adapter.createSession(before);
107
+ await adapter.createSession(exactly);
108
+ expect(await adapter.deleteSessionsCreatedBefore(at(0))).toBeGreaterThanOrEqual(1);
109
+ expect([await adapter.getSession(before.id), await adapter.getSession(exactly.id)]).toEqual([
110
+ null,
111
+ exactly,
112
+ ]);
113
+ },
114
+ },
115
+ ];
@@ -0,0 +1,71 @@
1
+ // What every group of `authAdapterConformance` shares: the subject (an adapter and the frozen
2
+ // clock it stamps from), the check shape, and users minted under ids and addresses no other check
3
+ // or run holds — a shared database keeps every check's rows, so none may read a neighbour's.
4
+
5
+ import type { AuthAdapter, CreateUserInput } from '@ultimat3/auth';
6
+ import type { FrozenClock } from '@ultimat3/core';
7
+ import { isUltimateError } from '@ultimat3/core';
8
+
9
+ /** The adapter under test, and the clock it was built with — every instant it stamps is this one's. */
10
+ export interface AuthAdapterSubject {
11
+ readonly adapter: AuthAdapter;
12
+ readonly clock: FrozenClock;
13
+ }
14
+
15
+ export interface AuthAdapterCheck {
16
+ readonly name: string;
17
+ run(subject: AuthAdapterSubject): Promise<void>;
18
+ }
19
+
20
+ export const CREATED_AT = new Date('2026-08-09T12:00:00.000Z');
21
+
22
+ /** A user id: the Postgres column is `uuid`. */
23
+ export const userId = (): string => crypto.randomUUID();
24
+
25
+ /** An address unique to this call, its local part starting with `label` so order is the label's. */
26
+ export const emailOf = (label: string): string => `${label}-${crypto.randomUUID()}@example.com`;
27
+
28
+ /** A text id no other check, run or process shares. */
29
+ export const idOf = (label: string): string => `conformance-${label}-${crypto.randomUUID()}`;
30
+
31
+ export const userInput = (
32
+ id: string,
33
+ email: string,
34
+ extra: Partial<CreateUserInput> = {},
35
+ ): CreateUserInput => ({
36
+ id,
37
+ email,
38
+ passwordHash: null,
39
+ orgId: null,
40
+ roles: [],
41
+ createdAt: CREATED_AT,
42
+ ...extra,
43
+ });
44
+
45
+ /** Create a user and answer its id. */
46
+ export const seedUser = async (
47
+ adapter: AuthAdapter,
48
+ extra: Partial<CreateUserInput> = {},
49
+ ): Promise<string> => {
50
+ const id = userId();
51
+ await adapter.createUser(userInput(id, emailOf('user'), extra));
52
+ return id;
53
+ };
54
+
55
+ /** What a refused write answered: `<code> <meta.operation> <meta.column>`, or `did-not-throw`. */
56
+ export const refusal = async (attempt: Promise<unknown>): Promise<string> => {
57
+ try {
58
+ await attempt;
59
+ } catch (error) {
60
+ if (!isUltimateError(error)) return 'not-an-UltimateError';
61
+ return `${error.code} ${String(error.meta?.['operation'])} ${String(error.meta?.['column'])}`;
62
+ }
63
+ return 'did-not-throw';
64
+ };
65
+
66
+ /** Only the rows a check wrote, from a list a shared store fills with everyone's. */
67
+ export const own = <T>(
68
+ rows: readonly T[],
69
+ ids: readonly string[],
70
+ idOfRow: (row: T) => string,
71
+ ): readonly T[] => rows.filter((row) => ids.includes(idOfRow(row)));
@@ -0,0 +1,128 @@
1
+ // `UserStore`'s identity rules for `authAdapterConformance`: an address is looked up exactly as it
2
+ // is stored (normalisation is `normaliseEmail`'s, above the seam), and a duplicate id, email or
3
+ // external id is refused as `X_AUTH_WRITE_FAILED` — NULLS DISTINCT, as a Postgres unique index is.
4
+
5
+ import { expect } from 'bun:test';
6
+ import type { AuthAdapterCheck } from './auth-adapter-conformance-support';
7
+ import { emailOf, idOf, refusal, userId, userInput } from './auth-adapter-conformance-support';
8
+
9
+ const DISABLED_AT = new Date('2026-08-09T12:00:01.000Z');
10
+
11
+ export const AUTH_ADAPTER_USER_CHECKS: readonly AuthAdapterCheck[] = [
12
+ {
13
+ name: 'an address is stored as handed and looked up exactly, case and spaces included',
14
+ async run({ adapter }) {
15
+ const [id, padded] = [userId(), userId()];
16
+ const email = emailOf('ada');
17
+ await adapter.createUser(userInput(id, email));
18
+ expect((await adapter.findUserByEmail(email))?.id).toBe(id);
19
+ expect(await adapter.findUserByEmail(email.toUpperCase())).toBeNull();
20
+ const spaced = ` ${emailOf('Grace').toUpperCase()} `;
21
+ await adapter.createUser(userInput(padded, spaced));
22
+ expect((await adapter.findUserById(padded))?.email).toBe(spaced);
23
+ },
24
+ },
25
+ {
26
+ name: 'two spellings of one address are two accounts',
27
+ async run({ adapter }) {
28
+ const email = emailOf('ada');
29
+ await adapter.createUser(userInput(userId(), email));
30
+ const second = userId();
31
+ await adapter.createUser(userInput(second, email.toUpperCase()));
32
+ expect((await adapter.findUserByEmail(email.toUpperCase()))?.id).toBe(second);
33
+ },
34
+ },
35
+ {
36
+ name: 'a second account at one email is refused, and neither row moves',
37
+ async run({ adapter }) {
38
+ const [first, second] = [userId(), userId()];
39
+ const email = emailOf('dup');
40
+ await adapter.createUser(userInput(first, email, { passwordHash: 'hash' }));
41
+ expect(await refusal(adapter.createUser(userInput(second, email)))).toBe(
42
+ 'X_AUTH_WRITE_FAILED createUser email',
43
+ );
44
+ expect((await adapter.findUserById(first))?.passwordHash).toBe('hash');
45
+ expect(await adapter.findUserById(second)).toBeNull();
46
+ },
47
+ },
48
+ {
49
+ name: 'a second account at one id is refused, and the first keeps its address',
50
+ async run({ adapter }) {
51
+ const id = userId();
52
+ const email = emailOf('id');
53
+ await adapter.createUser(userInput(id, email));
54
+ expect(await refusal(adapter.createUser(userInput(id, emailOf('other'))))).toBe(
55
+ 'X_AUTH_WRITE_FAILED createUser id',
56
+ );
57
+ expect((await adapter.findUserById(id))?.email).toBe(email);
58
+ },
59
+ },
60
+ {
61
+ name: 'a second account at one external id is refused; any number may hold none',
62
+ async run({ adapter }) {
63
+ const externalId = idOf('okta');
64
+ const [first, second, third] = [userId(), userId(), userId()];
65
+ await adapter.createUser(userInput(first, emailOf('a'), { externalId }));
66
+ expect(
67
+ await refusal(adapter.createUser(userInput(second, emailOf('b'), { externalId }))),
68
+ ).toBe('X_AUTH_WRITE_FAILED createUser external_id');
69
+ await adapter.createUser(userInput(second, emailOf('b'), { externalId: null }));
70
+ await adapter.createUser(userInput(third, emailOf('c'), { externalId: null }));
71
+ expect((await adapter.findUserById(third))?.externalId).toBeNull();
72
+ expect((await adapter.findUserByExternalId(externalId))?.id).toBe(first);
73
+ expect(await adapter.findUserByExternalId(idOf('nobody'))).toBeNull();
74
+ },
75
+ },
76
+ {
77
+ name: "updateUser refuses another account's external id, and allows its own or none",
78
+ async run({ adapter }) {
79
+ const [ada, grace] = [userId(), userId()];
80
+ const [adaExternal, graceExternal] = [idOf('abc'), idOf('def')];
81
+ await adapter.createUser(userInput(ada, emailOf('a'), { externalId: adaExternal }));
82
+ await adapter.createUser(userInput(grace, emailOf('g'), { externalId: graceExternal }));
83
+ expect(await refusal(adapter.updateUser(grace, { externalId: adaExternal }))).toBe(
84
+ 'X_AUTH_WRITE_FAILED updateUser external_id',
85
+ );
86
+ expect((await adapter.findUserById(grace))?.externalId).toBe(graceExternal);
87
+ expect((await adapter.updateUser(ada, { externalId: adaExternal }))?.externalId).toBe(
88
+ adaExternal,
89
+ );
90
+ expect((await adapter.updateUser(ada, { externalId: null }))?.externalId).toBeNull();
91
+ expect((await adapter.updateUser(grace, { externalId: null }))?.externalId).toBeNull();
92
+ },
93
+ },
94
+ {
95
+ name: 'updateUser writes what the patch names, leaves the rest, and answers null for nobody',
96
+ async run({ adapter }) {
97
+ const id = userId();
98
+ await adapter.createUser(userInput(id, emailOf('patch'), { roles: ['editor'] }));
99
+ const updated = await adapter.updateUser(id, {
100
+ scopes: ['tenancy:cross'],
101
+ passwordHash: 'h',
102
+ });
103
+ expect([updated?.roles, updated?.scopes, updated?.passwordHash]).toEqual([
104
+ ['editor'],
105
+ ['tenancy:cross'],
106
+ 'h',
107
+ ]);
108
+ expect(await adapter.updateUser(userId(), { passwordHash: 'h' })).toBeNull();
109
+ },
110
+ },
111
+ {
112
+ name: 'listUsersByOrg orders by byte, leaves disabled members out unless asked, filters by role',
113
+ async run({ adapter }) {
114
+ const orgId = userId();
115
+ const [upper, lower, gone] = [userId(), userId(), userId()];
116
+ await adapter.createUser(userInput(lower, emailOf('ada'), { orgId, roles: ['editor'] }));
117
+ await adapter.createUser(userInput(upper, emailOf('Zed'), { orgId }));
118
+ await adapter.createUser(userInput(gone, emailOf('bob'), { orgId }));
119
+ await adapter.updateUser(gone, { disabledAt: DISABLED_AT });
120
+ const ids = async (query?: Parameters<typeof adapter.listUsersByOrg>[1]) =>
121
+ (await adapter.listUsersByOrg(orgId, query)).map((user) => user.id);
122
+ // `Z` (0x5A) sorts before `a` (0x61): a byte order, never a locale's.
123
+ expect(await ids()).toEqual([upper, lower]);
124
+ expect(await ids({ includeDisabled: true })).toEqual([upper, lower, gone]);
125
+ expect(await ids({ role: 'editor' })).toEqual([lower]);
126
+ },
127
+ },
128
+ ];
@@ -0,0 +1,34 @@
1
+ // The `AuthAdapter` contract of `@ultimat3/auth` as shared examples, for an identity backend of
2
+ // your own (Better Auth, a directory): `behavesLike(authAdapterConformance, () => ({ adapter,
3
+ // clock }))`. One suite over every sub-store — users, the second factor, sessions, credentials,
4
+ // passkeys — so the question two adapters must never answer differently is asked of both alike.
5
+
6
+ import { test } from 'bun:test';
7
+ import { AUTH_ADAPTER_CREDENTIAL_CHECKS } from './auth-adapter-conformance-credentials';
8
+ import { AUTH_ADAPTER_MFA_CHECKS } from './auth-adapter-conformance-mfa';
9
+ import { AUTH_ADAPTER_PASSKEY_CHECKS } from './auth-adapter-conformance-passkeys';
10
+ import { AUTH_ADAPTER_SESSION_CHECKS } from './auth-adapter-conformance-sessions';
11
+ import type { AuthAdapterCheck, AuthAdapterSubject } from './auth-adapter-conformance-support';
12
+ import { AUTH_ADAPTER_USER_CHECKS } from './auth-adapter-conformance-users';
13
+ import type { SharedExamples } from './shared-examples';
14
+ import { sharedExamples } from './shared-examples';
15
+
16
+ export type { AuthAdapterCheck, AuthAdapterSubject } from './auth-adapter-conformance-support';
17
+
18
+ export const AUTH_ADAPTER_CHECKS: readonly AuthAdapterCheck[] = [
19
+ ...AUTH_ADAPTER_USER_CHECKS,
20
+ ...AUTH_ADAPTER_MFA_CHECKS,
21
+ ...AUTH_ADAPTER_SESSION_CHECKS,
22
+ ...AUTH_ADAPTER_CREDENTIAL_CHECKS,
23
+ ...AUTH_ADAPTER_PASSKEY_CHECKS,
24
+ ];
25
+
26
+ export const authAdapterConformance: SharedExamples<
27
+ AuthAdapterSubject | Promise<AuthAdapterSubject>
28
+ > = sharedExamples('an auth adapter', (subject) => {
29
+ for (const check of AUTH_ADAPTER_CHECKS) {
30
+ test(check.name, async () => {
31
+ await check.run(await subject());
32
+ });
33
+ }
34
+ });