@ultimat3/testing 30.8.0 → 31.0.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 (159) hide show
  1. package/CLAUDE.md +49 -62
  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 +41 -11
  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-input.ts +22 -9
  55. package/src/exercise-override-line.ts +98 -0
  56. package/src/exercise-report.ts +30 -51
  57. package/src/exercise-sweeps.ts +3 -1
  58. package/src/exercise.ts +38 -19
  59. package/src/factories.ts +192 -179
  60. package/src/factory-api.ts +131 -0
  61. package/src/factory-associations.ts +67 -0
  62. package/src/factory-errors.ts +38 -0
  63. package/src/factory-lint.ts +92 -0
  64. package/src/factory-persist.ts +74 -16
  65. package/src/factory-pipeline.ts +191 -0
  66. package/src/factory-registry.ts +2 -1
  67. package/src/factory-types.ts +131 -0
  68. package/src/failure-store-conformance.ts +137 -0
  69. package/src/fixture-jobs.ts +50 -15
  70. package/src/fixture-mail.ts +7 -7
  71. package/src/fixture-seed.ts +111 -0
  72. package/src/fixture-statements.ts +68 -52
  73. package/src/framework-fixtures.ts +1 -1
  74. package/src/idempotency-store-conformance.ts +186 -0
  75. package/src/idempotency-store-replay-conformance.ts +140 -0
  76. package/src/idempotency-store-tx-conformance.ts +132 -0
  77. package/src/idempotency-store-world-conformance.ts +82 -0
  78. package/src/identity-provider-conformance.ts +144 -0
  79. package/src/image-transform-conformance.ts +89 -0
  80. package/src/index.ts +68 -157
  81. package/src/isr-store-conformance.ts +113 -0
  82. package/src/job-sim-effects.ts +19 -31
  83. package/src/job-sim-world.ts +6 -15
  84. package/src/lease-store-conformance.ts +195 -0
  85. package/src/mail-driver-conformance.ts +108 -0
  86. package/src/matcher-doubles.ts +104 -0
  87. package/src/matcher-stub.ts +78 -0
  88. package/src/matcher-surface.ts +21 -0
  89. package/src/matchers.ts +19 -1
  90. package/src/mcp-confirmation-store-conformance.ts +262 -0
  91. package/src/meter-store-conformance.ts +135 -0
  92. package/src/notify-digest-conformance.ts +133 -0
  93. package/src/notify-inbox-conformance.ts +130 -0
  94. package/src/notify-ledger-conformance.ts +134 -0
  95. package/src/notify-preference-conformance.ts +49 -0
  96. package/src/notify-stores-conformance.ts +73 -0
  97. package/src/outbox-store-conformance-claims.ts +112 -0
  98. package/src/outbox-store-conformance-subject.ts +65 -0
  99. package/src/outbox-store-conformance.ts +71 -0
  100. package/src/per-test-reset.ts +55 -20
  101. package/src/plan-oracle.ts +10 -3
  102. package/src/plan-sweep.ts +37 -12
  103. package/src/preload.ts +4 -2
  104. package/src/purge-conformance.ts +79 -0
  105. package/src/push-device-conformance.ts +124 -0
  106. package/src/push-subscription-conformance.ts +123 -0
  107. package/src/quiet-logs.ts +4 -4
  108. package/src/rate-limit-store-conformance.ts +178 -0
  109. package/src/registry-leak-error.ts +8 -1
  110. package/src/scale-sweep-run.ts +3 -1
  111. package/src/scrape-driver-conformance-frame-checks.ts +97 -0
  112. package/src/scrape-driver-conformance-page-checks.ts +114 -0
  113. package/src/scrape-driver-conformance-site.ts +84 -0
  114. package/src/scrape-driver-conformance.ts +34 -0
  115. package/src/sealed-dns-resolver.ts +56 -0
  116. package/src/sealed-dns.ts +63 -64
  117. package/src/sealed-network.ts +13 -12
  118. package/src/sealed-node-sockets.ts +63 -0
  119. package/src/sealed-sockets.ts +13 -8
  120. package/src/sealed-udp.ts +118 -0
  121. package/src/search-index-conformance-list.ts +76 -0
  122. package/src/search-index-conformance-support.ts +69 -0
  123. package/src/search-index-conformance-versions.ts +66 -0
  124. package/src/search-index-conformance.ts +126 -0
  125. package/src/secret-source-conformance.ts +91 -0
  126. package/src/seed-factories.ts +57 -0
  127. package/src/seed-writer.ts +8 -19
  128. package/src/semantic-cache-factory-conformance.ts +86 -0
  129. package/src/sms-transport-conformance.ts +102 -0
  130. package/src/step-store-conformance.ts +171 -0
  131. package/src/storage-conformance-read-checks.ts +132 -0
  132. package/src/storage-conformance-shape.ts +121 -0
  133. package/src/storage-conformance-stream-checks.ts +226 -0
  134. package/src/storage-conformance.ts +34 -0
  135. package/src/stub-action.ts +24 -0
  136. package/src/stub-errors.ts +86 -0
  137. package/src/stub-job.ts +30 -0
  138. package/src/stub-query.ts +25 -0
  139. package/src/stub-script.ts +76 -0
  140. package/src/stub-stack.ts +29 -0
  141. package/src/stub.ts +73 -0
  142. package/src/swap-adapter.ts +135 -0
  143. package/src/test-scope.ts +96 -0
  144. package/src/test-types.ts +1 -1
  145. package/src/totp-replay-guard-conformance.ts +76 -0
  146. package/src/transport-conformance.ts +179 -0
  147. package/src/upload-scanner-conformance.ts +112 -0
  148. package/src/vector-store-conformance-checks.ts +174 -0
  149. package/src/vector-store-conformance.ts +21 -0
  150. package/src/cdp-connection.ts +0 -291
  151. package/src/cdp-errors.ts +0 -179
  152. package/src/cdp-launch-attempt.ts +0 -224
  153. package/src/cdp-launch-candidates.ts +0 -62
  154. package/src/cdp-launch-profile.ts +0 -106
  155. package/src/cdp-launch-reap.ts +0 -68
  156. package/src/cdp-launch-wire.ts +0 -171
  157. package/src/cdp-launch.ts +0 -175
  158. package/src/cdp-pipe.ts +0 -77
  159. package/src/cdp-wire-watch.ts +0 -113
@@ -0,0 +1,224 @@
1
+ // The `AuthLimiterFactory` contract of `@ultimat3/auth` as shared examples: `behavesLike(
2
+ // authLimiterFactoryConformance, () => ({ factory, clock }))`. Time is the frozen clock the limiters
3
+ // read, never a sleep. Every limiter RESERVES: an attempt counts in the step that admits it, so a
4
+ // concurrent burst spends the allowance before any guess reaches the KDF.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { AuthLimiter, AuthLimiterFactory, AuthRateLimitPolicy } from '@ultimat3/auth/adapter';
8
+ import type { FrozenClock } from '@ultimat3/core';
9
+ import { isUltimateError } from '@ultimat3/core';
10
+ import type { SharedExamples } from './shared-examples';
11
+ import { sharedExamples } from './shared-examples';
12
+
13
+ /** The factory under test, and the clock every limiter it builds reads. */
14
+ export interface AuthLimiterSubject {
15
+ readonly factory: AuthLimiterFactory;
16
+ readonly clock: FrozenClock;
17
+ }
18
+
19
+ export interface AuthLimiterCheck {
20
+ readonly name: string;
21
+ run(subject: AuthLimiterSubject): Promise<void>;
22
+ }
23
+
24
+ const POLICY: AuthRateLimitPolicy = {
25
+ maxAttempts: 3,
26
+ windowMs: 60_000,
27
+ lockoutMs: 300_000,
28
+ scope: 'process',
29
+ };
30
+ const BURST = 20;
31
+
32
+ /** A key no other check, run or process shares — a shared table holds every run's keys. */
33
+ const keyOf = (label: string): string => `account:conformance-${label}-${crypto.randomUUID()}`;
34
+
35
+ /** The code a call refused with, or `admitted`. */
36
+ const outcome = async (call: Promise<unknown>): Promise<string> => {
37
+ try {
38
+ await call;
39
+ } catch (error) {
40
+ return isUltimateError(error) ? error.code : 'not-an-UltimateError';
41
+ }
42
+ return 'admitted';
43
+ };
44
+
45
+ const reserveTimes = async (limiter: AuthLimiter, key: string, n: number): Promise<void> => {
46
+ for (let index = 0; index < n; index += 1) await limiter.reserve(key);
47
+ };
48
+
49
+ const build = ({ factory }: AuthLimiterSubject): AuthLimiter => factory(POLICY);
50
+
51
+ export const AUTH_LIMITER_CHECKS: readonly AuthLimiterCheck[] = [
52
+ {
53
+ name: 'reports the limits it was built with, and where it counts',
54
+ async run(subject) {
55
+ const { policy } = build(subject);
56
+ expect([policy.maxAttempts, policy.windowMs, policy.lockoutMs]).toEqual([3, 60_000, 300_000]);
57
+ expect(['process', 'shared']).toContain(policy.scope);
58
+ },
59
+ },
60
+ {
61
+ name: 'the attempt that fills the window is admitted and starts the lockout; the next is refused',
62
+ async run(subject) {
63
+ const limiter = build(subject);
64
+ const key = keyOf('fill');
65
+ await reserveTimes(limiter, key, 2);
66
+ expect(await limiter.lockedUntil(key)).toBeNull();
67
+ expect(await outcome(limiter.reserve(key))).toBe('admitted');
68
+ const until = subject.clock.now().getTime() + POLICY.lockoutMs;
69
+ expect((await limiter.lockedUntil(key))?.getTime()).toBe(until);
70
+ expect(await outcome(limiter.reserve(key))).toBe('X_ACCOUNT_LOCKED');
71
+ },
72
+ },
73
+ {
74
+ name: 'attempts that slid out of the window do not add up to a lockout',
75
+ async run(subject) {
76
+ const limiter = build(subject);
77
+ const key = keyOf('slide');
78
+ await reserveTimes(limiter, key, 2);
79
+ subject.clock.advance(POLICY.windowMs + 1);
80
+ await limiter.reserve(key);
81
+ expect(await limiter.lockedUntil(key)).toBeNull();
82
+ },
83
+ },
84
+ {
85
+ name: 'recordSuccess clears the window and a lockout with it',
86
+ async run(subject) {
87
+ const limiter = build(subject);
88
+ const key = keyOf('success');
89
+ await reserveTimes(limiter, key, 3);
90
+ await limiter.recordSuccess(key);
91
+ expect(await limiter.lockedUntil(key)).toBeNull();
92
+ await reserveTimes(limiter, key, 2);
93
+ expect(await limiter.lockedUntil(key)).toBeNull();
94
+ },
95
+ },
96
+ {
97
+ name: 'a refused reservation counts nothing and never moves a live lockout',
98
+ async run(subject) {
99
+ const limiter = build(subject);
100
+ const key = keyOf('refused');
101
+ await reserveTimes(limiter, key, 3);
102
+ const first = (await limiter.lockedUntil(key))?.getTime();
103
+ subject.clock.advance(1_000);
104
+ expect(await outcome(limiter.reserve(key))).toBe('X_ACCOUNT_LOCKED');
105
+ expect((await limiter.lockedUntil(key))?.getTime()).toBe(first);
106
+ },
107
+ },
108
+ {
109
+ name: 'an expired lockout answers exactly as a missing one',
110
+ async run(subject) {
111
+ const limiter = build(subject);
112
+ const key = keyOf('expired');
113
+ await reserveTimes(limiter, key, 3);
114
+ subject.clock.advance(POLICY.lockoutMs + 1);
115
+ expect(await limiter.lockedUntil(key)).toBeNull();
116
+ expect(await outcome(limiter.reserve(key))).toBe('admitted');
117
+ expect(await limiter.lockedUntil(key)).toBeNull();
118
+ },
119
+ },
120
+ {
121
+ name: 'a refund gives one attempt back and lifts the lockout that attempt started',
122
+ async run(subject) {
123
+ const limiter = build(subject);
124
+ const key = keyOf('refund');
125
+ await reserveTimes(limiter, key, 2);
126
+ const third = await limiter.reserve(key);
127
+ expect(await limiter.lockedUntil(key)).not.toBeNull();
128
+ await limiter.refund(third);
129
+ expect(await limiter.lockedUntil(key)).toBeNull();
130
+ // Two are still counted: the next one fills the window again.
131
+ await limiter.reserve(key);
132
+ expect(await limiter.lockedUntil(key)).not.toBeNull();
133
+ },
134
+ },
135
+ {
136
+ name: 'reservations at one instant are refunded one at a time',
137
+ async run(subject) {
138
+ const limiter = build(subject);
139
+ const key = keyOf('same-ms');
140
+ const first = await limiter.reserve(key);
141
+ await limiter.reserve(key);
142
+ await limiter.refund(first);
143
+ // A reservation this limiter never handed out gives nothing back.
144
+ await limiter.refund({ key, atMs: first.atMs - 1 });
145
+ await limiter.reserve(key);
146
+ expect(await limiter.lockedUntil(key)).toBeNull();
147
+ await limiter.reserve(key);
148
+ expect(await limiter.lockedUntil(key)).not.toBeNull();
149
+ },
150
+ },
151
+ {
152
+ name: `a concurrent burst of ${BURST} is admitted maxAttempts times`,
153
+ async run(subject) {
154
+ const limiter = build(subject);
155
+ const key = keyOf('burst');
156
+ const codes = await Promise.all(
157
+ Array.from({ length: BURST }, () => outcome(limiter.reserve(key))),
158
+ );
159
+ expect(codes.filter((code) => code === 'admitted')).toHaveLength(POLICY.maxAttempts);
160
+ expect(codes.filter((code) => code === 'X_ACCOUNT_LOCKED')).toHaveLength(
161
+ BURST - POLICY.maxAttempts,
162
+ );
163
+ },
164
+ },
165
+ {
166
+ name: 'two limiters from one factory count one key together',
167
+ async run(subject) {
168
+ const [podA, podB] = [build(subject), build(subject)];
169
+ const key = keyOf('fleet');
170
+ await podA.reserve(key);
171
+ await podB.reserve(key);
172
+ await podA.reserve(key);
173
+ // A per-process limiter keeps its own count and is honest about it.
174
+ const shared = podB.policy.scope === 'shared';
175
+ expect(await outcome(podB.reserve(key))).toBe(shared ? 'X_ACCOUNT_LOCKED' : 'admitted');
176
+ },
177
+ },
178
+ {
179
+ name: 'one key locked is no other key locked',
180
+ async run(subject) {
181
+ const limiter = build(subject);
182
+ const [locked, other] = [keyOf('locked'), keyOf('other')];
183
+ await reserveTimes(limiter, locked, 3);
184
+ expect(await limiter.lockedUntil(other)).toBeNull();
185
+ expect(await outcome(limiter.reserve(other))).toBe('admitted');
186
+ },
187
+ },
188
+ {
189
+ name: 'reset forgets every key',
190
+ async run(subject) {
191
+ const limiter = build(subject);
192
+ const key = keyOf('reset');
193
+ await reserveTimes(limiter, key, 3);
194
+ await limiter.reset();
195
+ expect(await limiter.lockedUntil(key)).toBeNull();
196
+ await reserveTimes(limiter, key, 2);
197
+ expect(await limiter.lockedUntil(key)).toBeNull();
198
+ },
199
+ },
200
+ {
201
+ name: 'purgeExpired, when declared, keeps a live lockout and drops a dead one',
202
+ async run(subject) {
203
+ const limiter = build(subject);
204
+ if (limiter.purgeExpired === undefined) return;
205
+ const key = keyOf('purge');
206
+ await reserveTimes(limiter, key, 3);
207
+ await limiter.purgeExpired();
208
+ expect(await limiter.lockedUntil(key)).not.toBeNull();
209
+ subject.clock.advance(POLICY.lockoutMs + 1);
210
+ expect(await limiter.purgeExpired()).toBeGreaterThanOrEqual(1);
211
+ expect(await outcome(limiter.reserve(key))).toBe('admitted');
212
+ },
213
+ },
214
+ ];
215
+
216
+ export const authLimiterFactoryConformance: SharedExamples<
217
+ AuthLimiterSubject | Promise<AuthLimiterSubject>
218
+ > = sharedExamples('an auth limiter factory', (subject) => {
219
+ for (const check of AUTH_LIMITER_CHECKS) {
220
+ test(check.name, async () => {
221
+ await check.run(await subject());
222
+ });
223
+ }
224
+ });
@@ -0,0 +1,69 @@
1
+ // The records `authServerStoreConformance` writes, each under ids a check minted for itself — a
2
+ // shared table holds every check's and every run's rows, so no check may read a neighbour's.
3
+
4
+ import type {
5
+ AuthCodeRecord,
6
+ AuthGrantRecord,
7
+ AuthTokenRecord,
8
+ DeviceCodeRecord,
9
+ } from '@ultimat3/auth/adapter';
10
+
11
+ const T0 = Date.parse('2026-11-06T09:00:00.000Z');
12
+
13
+ /** `T0` plus `seconds`: every instant a check passes is one of these. */
14
+ export const at = (seconds: number): Date => new Date(T0 + seconds * 1000);
15
+
16
+ /** An id no other check, run or process shares. */
17
+ export const idOf = (label: string): string => `conformance-${label}-${crypto.randomUUID()}`;
18
+
19
+ export const codeRecord = (codeHash: string, grantId: string): AuthCodeRecord => ({
20
+ codeHash,
21
+ grantId,
22
+ clientId: 'c1',
23
+ subject: 'u1',
24
+ scopes: ['read', 'write'],
25
+ resource: 'https://as.test/mcp',
26
+ redirectUri: 'https://app.test/cb',
27
+ codeChallenge: 'x'.repeat(43),
28
+ expiresAt: at(120),
29
+ usedAt: null,
30
+ });
31
+
32
+ export const tokenRecord = (
33
+ tokenHash: string,
34
+ grantId: string,
35
+ kind: AuthTokenRecord['kind'] = 'refresh',
36
+ ): AuthTokenRecord => ({
37
+ tokenHash,
38
+ kind,
39
+ grantId,
40
+ createdAt: at(0),
41
+ expiresAt: at(3600),
42
+ retiredAt: null,
43
+ });
44
+
45
+ export const grantRecord = (id: string, subject: string, clientId = 'c1'): AuthGrantRecord => ({
46
+ id,
47
+ clientId,
48
+ subject,
49
+ scopes: ['read'],
50
+ resource: null,
51
+ createdAt: at(0),
52
+ refreshedAt: at(0),
53
+ revokedAt: null,
54
+ });
55
+
56
+ export const deviceRecord = (deviceCodeHash: string, userCodeHash: string): DeviceCodeRecord => ({
57
+ deviceCodeHash,
58
+ userCodeHash,
59
+ clientId: 'c1',
60
+ scopes: ['read'],
61
+ resource: null,
62
+ status: 'pending',
63
+ subject: null,
64
+ grantedScopes: null,
65
+ intervalSeconds: 5,
66
+ lastPolledAt: null,
67
+ createdAt: at(0),
68
+ expiresAt: at(600),
69
+ });
@@ -0,0 +1,208 @@
1
+ // The `AuthServerStore` contract of `@ultimat3/auth` as shared examples, for a store of your own:
2
+ // `behavesLike(authServerStoreConformance, () => store)`. Every single-use rule of an authorization
3
+ // server is a STORAGE guarantee — a code taken once, a refresh token rotated once, a device code
4
+ // consumed once — so each is asserted as a race, through the port, never as a read then a write.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { AuthServerStore } from '@ultimat3/auth/adapter';
8
+ import {
9
+ at,
10
+ codeRecord,
11
+ deviceRecord,
12
+ grantRecord,
13
+ idOf,
14
+ tokenRecord,
15
+ } from './auth-server-store-conformance-records';
16
+ import type { SharedExamples } from './shared-examples';
17
+ import { sharedExamples } from './shared-examples';
18
+
19
+ export interface AuthServerStoreCheck {
20
+ readonly name: string;
21
+ run(store: AuthServerStore): Promise<void>;
22
+ }
23
+
24
+ const RACERS = 8;
25
+
26
+ export const AUTH_SERVER_STORE_CHECKS: readonly AuthServerStoreCheck[] = [
27
+ {
28
+ name: 'a client round-trips intact, and an unknown one is null',
29
+ async run(store) {
30
+ const client = {
31
+ clientId: idOf('client'),
32
+ name: 'App',
33
+ secretHash: null,
34
+ authMethod: 'none' as const,
35
+ redirectUris: ['https://app.test/cb', 'http://localhost:4000/cb'],
36
+ grantTypes: ['authorization_code' as const, 'refresh_token' as const],
37
+ scopes: ['read'],
38
+ resources: ['https://as.test/mcp'],
39
+ createdAt: at(0),
40
+ };
41
+ await store.putClient(client);
42
+ expect(await store.getClient(client.clientId)).toEqual(client);
43
+ expect(await store.getClient(idOf('nobody'))).toBeNull();
44
+ },
45
+ },
46
+ {
47
+ name: 'a code is taken fresh once; every later take is a replay',
48
+ async run(store) {
49
+ const [hash, grant] = [idOf('code'), idOf('grant')];
50
+ await store.putCode(codeRecord(hash, grant));
51
+ const first = await store.takeCode(hash, at(1));
52
+ expect([first?.fresh, first?.code.scopes, first?.code.grantId]).toEqual([
53
+ true,
54
+ ['read', 'write'],
55
+ grant,
56
+ ]);
57
+ expect((await store.takeCode(hash, at(2)))?.fresh).toBe(false);
58
+ expect(await store.takeCode(idOf('none'), at(2))).toBeNull();
59
+ },
60
+ },
61
+ {
62
+ name: 'reading a code spends nothing; the take stamps usedAt',
63
+ async run(store) {
64
+ const hash = idOf('peek');
65
+ await store.putCode(codeRecord(hash, idOf('grant')));
66
+ expect(await store.getCode(hash)).toMatchObject({ clientId: 'c1', usedAt: null });
67
+ expect(await store.getCode(idOf('none'))).toBeNull();
68
+ expect((await store.takeCode(hash, at(1)))?.fresh).toBe(true);
69
+ expect((await store.getCode(hash))?.usedAt?.getTime()).toBe(at(1).getTime());
70
+ },
71
+ },
72
+ {
73
+ name: `${RACERS} racing takes of one code spend it exactly once`,
74
+ async run(store) {
75
+ const hash = idOf('race');
76
+ await store.putCode(codeRecord(hash, idOf('grant')));
77
+ const takes = await Promise.all(
78
+ Array.from({ length: RACERS }, () => store.takeCode(hash, at(1))),
79
+ );
80
+ expect(takes.filter((take) => take?.fresh === true)).toHaveLength(1);
81
+ },
82
+ },
83
+ {
84
+ name: 'a refresh token rotates once; the retired one is a replay naming its grant',
85
+ async run(store) {
86
+ const [grant, first, second] = [idOf('grant'), idOf('r1'), idOf('r2')];
87
+ await store.putToken(tokenRecord(first, grant));
88
+ expect(await store.rotateRefresh(first, tokenRecord(second, grant), at(1))).toEqual({
89
+ outcome: 'rotated',
90
+ grantId: grant,
91
+ });
92
+ expect((await store.getToken(first))?.retiredAt?.getTime()).toBe(at(1).getTime());
93
+ expect((await store.getToken(second))?.retiredAt).toBeNull();
94
+ expect(await store.rotateRefresh(first, tokenRecord(idOf('r3'), grant), at(2))).toEqual({
95
+ outcome: 'replayed',
96
+ grantId: grant,
97
+ });
98
+ expect(await store.rotateRefresh(idOf('zz'), tokenRecord(idOf('r4'), grant), at(2))).toEqual({
99
+ outcome: 'unknown',
100
+ });
101
+ },
102
+ },
103
+ {
104
+ name: 'racing rotations of one refresh token rotate it once',
105
+ async run(store) {
106
+ const [grant, live] = [idOf('grant'), idOf('live')];
107
+ await store.putToken(tokenRecord(live, grant));
108
+ const raced = await Promise.all(
109
+ Array.from({ length: RACERS / 2 }, () =>
110
+ store.rotateRefresh(live, tokenRecord(idOf('next'), grant), at(3)),
111
+ ),
112
+ );
113
+ expect(raced.filter((rotation) => rotation.outcome === 'rotated')).toHaveLength(1);
114
+ },
115
+ },
116
+ {
117
+ name: 'a grant revokes by id and by subject, one client or all, and counts only live ones',
118
+ async run(store) {
119
+ const subject = idOf('subject');
120
+ const [g1, g2, g3] = [idOf('g1'), idOf('g2'), idOf('g3')];
121
+ await store.putGrant(grantRecord(g1, subject));
122
+ await store.putGrant(grantRecord(g2, subject, 'c2'));
123
+ await store.putGrant(grantRecord(g3, subject, 'c3'));
124
+ await store.revokeGrant(g1, at(1));
125
+ expect((await store.getGrant(g1))?.revokedAt?.getTime()).toBe(at(1).getTime());
126
+ expect(await store.revokeGrants({ subject, clientId: 'c2' }, at(2))).toBe(1);
127
+ expect(await store.revokeGrants({ subject }, at(3))).toBe(1);
128
+ expect(await store.revokeGrants({ subject }, at(4))).toBe(0);
129
+ expect((await store.getGrant(g1))?.revokedAt?.getTime()).toBe(at(1).getTime());
130
+ },
131
+ },
132
+ {
133
+ name: 'touchGrant restarts the idle window',
134
+ async run(store) {
135
+ const id = idOf('touch');
136
+ await store.putGrant(grantRecord(id, idOf('subject')));
137
+ await store.touchGrant(id, at(50));
138
+ expect((await store.getGrant(id))?.refreshedAt.getTime()).toBe(at(50).getTime());
139
+ },
140
+ },
141
+ {
142
+ name: "a device poll answers the row before its stamp, and another client's poll is null",
143
+ async run(store) {
144
+ const device = idOf('device');
145
+ await store.putDevice(deviceRecord(device, idOf('user-code')));
146
+ expect((await store.pollDevice(device, 'c1', at(1)))?.lastPolledAt).toBeNull();
147
+ expect(await store.pollDevice(device, 'c2', at(4))).toBeNull();
148
+ expect((await store.pollDevice(device, 'c1', at(6)))?.lastPolledAt?.getTime()).toBe(
149
+ at(1).getTime(),
150
+ );
151
+ },
152
+ },
153
+ {
154
+ name: 'a device code is decided once and consumed once, under a race',
155
+ async run(store) {
156
+ const [device, userCode] = [idOf('device'), idOf('user-code')];
157
+ await store.putDevice(deviceRecord(device, userCode));
158
+ expect((await store.deviceByUserCode(userCode))?.deviceCodeHash).toBe(device);
159
+ const decided = await store.decideDevice(
160
+ userCode,
161
+ { status: 'approved', subject: 'u1', scopes: ['read'] },
162
+ at(7),
163
+ );
164
+ expect(decided).toMatchObject({ status: 'approved', subject: 'u1', grantedScopes: ['read'] });
165
+ expect(await store.decideDevice(userCode, { status: 'denied' }, at(8))).toBeNull();
166
+ const consumed = await Promise.all(
167
+ Array.from({ length: RACERS }, () => store.consumeDevice(device, at(9))),
168
+ );
169
+ expect(consumed.filter(Boolean)).toHaveLength(1);
170
+ },
171
+ },
172
+ {
173
+ name: 'an expired device code cannot be decided',
174
+ async run(store) {
175
+ const userCode = idOf('user-code');
176
+ await store.putDevice(deviceRecord(idOf('device'), userCode));
177
+ expect(await store.decideDevice(userCode, { status: 'denied' }, at(600))).toBeNull();
178
+ },
179
+ },
180
+ {
181
+ name: 'purge removes what expired and what sat idle, and keeps what is live',
182
+ async run(store) {
183
+ const [code, token, idle, live] = [idOf('old'), idOf('t-old'), idOf('idle'), idOf('live')];
184
+ await store.putCode(codeRecord(code, idOf('grant')));
185
+ await store.putToken(tokenRecord(token, idOf('grant'), 'access'));
186
+ await store.putGrant(grantRecord(idle, idOf('subject')));
187
+ await store.putGrant({ ...grantRecord(live, idOf('subject')), refreshedAt: at(5000) });
188
+ expect(await store.purge(at(200), at(-1))).toBeGreaterThanOrEqual(1);
189
+ expect([await store.getCode(code), (await store.getToken(token))?.tokenHash]).toEqual([
190
+ null,
191
+ token,
192
+ ]);
193
+ expect(await store.purge(at(4000), at(1))).toBeGreaterThanOrEqual(2);
194
+ expect([await store.getToken(token), await store.getGrant(idle)]).toEqual([null, null]);
195
+ expect((await store.getGrant(live))?.id).toBe(live);
196
+ },
197
+ },
198
+ ];
199
+
200
+ export const authServerStoreConformance: SharedExamples<
201
+ AuthServerStore | Promise<AuthServerStore>
202
+ > = sharedExamples('an authorization-server store', (subject) => {
203
+ for (const check of AUTH_SERVER_STORE_CHECKS) {
204
+ test(check.name, async () => {
205
+ await check.run(await subject());
206
+ });
207
+ }
208
+ });
@@ -0,0 +1,142 @@
1
+ // The `CacheTier` contract, check by check: what every rung — the request memo, the LRU, Redis and
2
+ // yours — answers through the port alone. Lifted from `cache/src/tier-parity.test.ts` and
3
+ // `tier-value-shape.test.ts`; a semantic one rung holds is a stack whose hits depend on the rung.
4
+
5
+ import { expect } from 'bun:test';
6
+ import type { CacheTier } from '@ultimat3/cache';
7
+ import { tag } from '@ultimat3/cache';
8
+ import { isUltimateError } from '@ultimat3/core';
9
+
10
+ export interface CacheTierCheck {
11
+ readonly name: string;
12
+ run(tier: CacheTier): Promise<void>;
13
+ }
14
+
15
+ /** An entity and a key prefix per check, so one shared Redis serves two runs and a dead one. */
16
+ const scopeOf = () => {
17
+ const id = crypto.randomUUID().replaceAll('-', '');
18
+ return { entity: `e${id.slice(0, 12)}`, key: (name: string) => `conformance:${id}:${name}` };
19
+ };
20
+
21
+ async function refusalOf(call: () => Promise<unknown>): Promise<string> {
22
+ try {
23
+ await call();
24
+ } catch (caught) {
25
+ return isUltimateError(caught) ? caught.code : `not-a-coded-error: ${String(caught)}`;
26
+ }
27
+ return 'resolved';
28
+ }
29
+
30
+ /** One row, its neighbour, and a list: the three keys every bust is judged on. */
31
+ const seeded = async (tier: CacheTier) => {
32
+ const scope = scopeOf();
33
+ const [one, two, feed] = [scope.key('row-1'), scope.key('row-2'), scope.key('feed')];
34
+ await tier.set(one, 'one', { ttlMs: 60_000, tags: [tag(scope.entity, '1')] });
35
+ await tier.set(two, 'two', { ttlMs: 60_000, tags: [tag(scope.entity, '2')] });
36
+ await tier.set(feed, 'list', { ttlMs: 60_000, tags: [tag(scope.entity)] });
37
+ const survivors = async (): Promise<readonly string[]> => {
38
+ const found: string[] = [];
39
+ for (const key of [one, two, feed]) if ((await tier.get(key)) !== undefined) found.push(key);
40
+ return found;
41
+ };
42
+ return { entity: scope.entity, one, two, feed, survivors };
43
+ };
44
+
45
+ const SAMPLE = {
46
+ at: new Date('2026-10-07T12:00:00.000Z'),
47
+ total: 9_007_199_254_740_993n,
48
+ byId: new Map([['a', 1]]),
49
+ seen: new Set(['x', 'y']),
50
+ rows: [{ id: 'a', seenAt: new Date('2026-01-01T00:00:00.000Z') }],
51
+ nothing: null,
52
+ };
53
+
54
+ export const CACHE_TIER_CHECKS: readonly CacheTierCheck[] = [
55
+ {
56
+ name: 'a set value is a hit carrying its tags, a del makes it a miss, an unknown key misses',
57
+ async run(tier) {
58
+ const scope = scopeOf();
59
+ const key = scope.key('k');
60
+ await tier.set(key, 'v', { ttlMs: 60_000, tags: [tag(scope.entity, '1')] });
61
+ const hit = await tier.get<string>(key);
62
+ expect([hit?.value, hit?.tags]).toEqual(['v', [tag(scope.entity, '1')]]);
63
+ await tier.del(key);
64
+ expect(await tier.get(key)).toBeUndefined();
65
+ expect(await tier.get(scope.key('never'))).toBeUndefined();
66
+ },
67
+ },
68
+ {
69
+ name: 'a Date, a bigint, a Map and a Set come back as themselves',
70
+ async run(tier) {
71
+ const key = scopeOf().key('shape');
72
+ await tier.set(key, SAMPLE, { ttlMs: 60_000 });
73
+ const value = (await tier.get<typeof SAMPLE>(key))?.value;
74
+ expect(value).toEqual(SAMPLE);
75
+ expect([value?.at, value?.rows[0]?.seenAt].every((at) => at instanceof Date)).toBe(true);
76
+ expect([typeof value?.total, value?.byId instanceof Map, value?.seen instanceof Set]).toEqual(
77
+ ['bigint', true, true],
78
+ );
79
+ },
80
+ },
81
+ {
82
+ name: 'mutating the written object, or a hit, never reaches the next reader',
83
+ async run(tier) {
84
+ const key = scopeOf().key('shared');
85
+ const written = { count: 1, tags: ['a'] };
86
+ await tier.set(key, written, { ttlMs: 60_000 });
87
+ written.count = 99;
88
+ const first = await tier.get<typeof written>(key);
89
+ expect(first?.value.count).toBe(1);
90
+ first?.value.tags.push('leaked');
91
+ expect((await tier.get<typeof written>(key))?.value.tags).toEqual(['a']);
92
+ },
93
+ },
94
+ {
95
+ name: 'a ROW bust takes the row and its collection, and spares the other rows',
96
+ async run(tier) {
97
+ const { entity, one, two, feed, survivors } = await seeded(tier);
98
+ const report = await tier.invalidateTags([tag(entity, '1')]);
99
+ expect([...report.keys].sort()).toEqual([feed, one].sort());
100
+ expect(await survivors()).toEqual([two]);
101
+ },
102
+ },
103
+ {
104
+ name: 'a COLLECTION bust takes every row of its entity as well as the list',
105
+ async run(tier) {
106
+ const { entity, survivors } = await seeded(tier);
107
+ await tier.invalidateTags([tag(entity)]);
108
+ expect(await survivors()).toEqual([]);
109
+ },
110
+ },
111
+ {
112
+ name: 'a bust of no tags, or of another entity, clears nothing',
113
+ async run(tier) {
114
+ const { two, one, feed, survivors } = await seeded(tier);
115
+ expect((await tier.invalidateTags([])).keys).toEqual([]);
116
+ await tier.invalidateTags([tag(scopeOf().entity)]);
117
+ expect(await survivors()).toEqual([one, two, feed]);
118
+ },
119
+ },
120
+ {
121
+ name: 'a ttlMs that is not positive and finite is X_CACHE_TTL_INVALID, and holds nothing',
122
+ async run(tier) {
123
+ const key = scopeOf().key('ttl');
124
+ for (const ttlMs of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
125
+ expect(await refusalOf(() => tier.set(key, 'v', { ttlMs }))).toBe('X_CACHE_TTL_INVALID');
126
+ }
127
+ expect(await tier.get(key)).toBeUndefined();
128
+ },
129
+ },
130
+ {
131
+ name: 'a value no tier can encode is X_CACHE_VALUE_UNENCODABLE, never a bare TypeError',
132
+ async run(tier) {
133
+ const cyclic: { self?: unknown } = {};
134
+ cyclic.self = cyclic;
135
+ const key = scopeOf().key('cycle');
136
+ expect(await refusalOf(() => tier.set(key, cyclic, { ttlMs: 60_000 }))).toBe(
137
+ 'X_CACHE_VALUE_UNENCODABLE',
138
+ );
139
+ expect(await tier.get(key)).toBeUndefined();
140
+ },
141
+ },
142
+ ];
@@ -0,0 +1,24 @@
1
+ // The `CacheTier` contract as shared examples: `behavesLike(cacheTierConformance, () => tier)` runs
2
+ // every check against a tier of your own, one test per check, each inside a request — the memo tier
3
+ // holds nothing outside one, and every other tier must not care which side it is called from.
4
+
5
+ import { test } from 'bun:test';
6
+ import type { CacheTier } from '@ultimat3/cache';
7
+ import { ctxOf, runWithContext } from '@ultimat3/core';
8
+ import { CACHE_TIER_CHECKS } from './cache-tier-conformance-checks';
9
+ import type { SharedExamples } from './shared-examples';
10
+ import { sharedExamples } from './shared-examples';
11
+
12
+ export type { CacheTierCheck } from './cache-tier-conformance-checks';
13
+ export { CACHE_TIER_CHECKS } from './cache-tier-conformance-checks';
14
+
15
+ export const cacheTierConformance: SharedExamples<CacheTier | Promise<CacheTier>> = sharedExamples(
16
+ 'a cache tier',
17
+ (subject) => {
18
+ for (const check of CACHE_TIER_CHECKS) {
19
+ test(check.name, async () => {
20
+ await runWithContext(ctxOf(), async () => check.run(await subject()));
21
+ });
22
+ }
23
+ },
24
+ );