@oxyhq/core 18.0.0 → 19.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 (43) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/i18n/locales/en-US.json +48 -5
  3. package/dist/cjs/i18n/locales/es-ES.json +48 -5
  4. package/dist/cjs/i18n/locales/locales/en-US.json +48 -5
  5. package/dist/cjs/i18n/locales/locales/es-ES.json +48 -5
  6. package/dist/cjs/index.js +10 -6
  7. package/dist/cjs/mixins/OxyServices.accounts.js +27 -2
  8. package/dist/cjs/mixins/OxyServices.user.js +14 -20
  9. package/dist/cjs/server/index.js +8 -2
  10. package/dist/cjs/server/userInvalidation.js +6 -28
  11. package/dist/cjs/utils/identityCacheSweep.js +97 -0
  12. package/dist/esm/.tsbuildinfo +1 -1
  13. package/dist/esm/i18n/locales/en-US.json +48 -5
  14. package/dist/esm/i18n/locales/es-ES.json +48 -5
  15. package/dist/esm/i18n/locales/locales/en-US.json +48 -5
  16. package/dist/esm/i18n/locales/locales/es-ES.json +48 -5
  17. package/dist/esm/index.js +1 -1
  18. package/dist/esm/mixins/OxyServices.accounts.js +22 -1
  19. package/dist/esm/mixins/OxyServices.user.js +14 -20
  20. package/dist/esm/server/index.js +5 -1
  21. package/dist/esm/server/userInvalidation.js +5 -26
  22. package/dist/esm/utils/identityCacheSweep.js +92 -0
  23. package/dist/types/.tsbuildinfo +1 -1
  24. package/dist/types/index.d.ts +2 -2
  25. package/dist/types/mixins/OxyServices.accounts.d.ts +39 -7
  26. package/dist/types/mixins/OxyServices.user.d.ts +9 -7
  27. package/dist/types/models/interfaces.d.ts +11 -3
  28. package/dist/types/server/index.d.ts +4 -2
  29. package/dist/types/server/userInvalidation.d.ts +5 -24
  30. package/dist/types/utils/identityCacheSweep.d.ts +80 -0
  31. package/package.json +2 -2
  32. package/src/i18n/locales/en-US.json +48 -5
  33. package/src/i18n/locales/es-ES.json +48 -5
  34. package/src/index.ts +8 -2
  35. package/src/mixins/OxyServices.accounts.ts +58 -7
  36. package/src/mixins/OxyServices.user.ts +14 -20
  37. package/src/mixins/__tests__/identityWriteCacheInvalidation.test.ts +370 -0
  38. package/src/models/interfaces.ts +11 -3
  39. package/src/server/__tests__/userInvalidation.test.ts +3 -20
  40. package/src/server/index.ts +5 -2
  41. package/src/server/userInvalidation.ts +8 -36
  42. package/src/utils/__tests__/identityCacheSweep.test.ts +151 -0
  43. package/src/utils/identityCacheSweep.ts +104 -0
@@ -0,0 +1,370 @@
1
+ /**
2
+ * Identity-cache invalidation for the profile WRITERS, against the REAL
3
+ * response cache.
4
+ *
5
+ * An account IS a user, and a profile screen never reads `/accounts/<id>` — it
6
+ * reads `GET /users/<id>` and `GET /profiles/username/<handle>`, both cached for
7
+ * five minutes in the caller's own process. `updateAccount` used to bust only
8
+ * the account-graph keys, so for up to five minutes after an edit a refetch
9
+ * handed back the PRE-EDIT profile from the client's own cache, with a
10
+ * perfectly healthy server ("I changed my channel's picture and it doesn't
11
+ * update until I reload the page").
12
+ *
13
+ * These tests drive the real `HttpService` cache over a mocked `fetch` rather
14
+ * than spying on `clearCacheEntry` / `clearCacheByPrefix`, because a spy proves
15
+ * only that SOME string was passed — not that the entry a read actually lands
16
+ * under was evicted. The load-bearing case is the RENAME: an implementation
17
+ * that busts the exact key for the handle in the write RESPONSE passes every
18
+ * assertion about the new handle while leaving the OLD handle's entry serving
19
+ * the pre-rename profile until its TTL. Both handles are warmed here so the two
20
+ * implementations disagree.
21
+ *
22
+ * `updateProfile` is covered here too, because it carried a SECOND, drifted
23
+ * hand-written copy of the same key list — it swept four of the six keys,
24
+ * missing `GET:/auth/lookup/` and `GET:/profiles/resolve`. Both writers now
25
+ * share one enumeration (`utils/identityCacheSweep`), and this is where that is
26
+ * asserted from the outside.
27
+ */
28
+
29
+ import { OxyServices } from '../../OxyServices';
30
+ import type { AccountNode } from '../OxyServices.accounts';
31
+
32
+ /**
33
+ * A non-verified JWT whose payload decodes to the given claims — enough for the
34
+ * cache's identity tag and the bearer preflight (`jwtDecode` never checks a
35
+ * signature).
36
+ */
37
+ function makeJwt(payload: Record<string, unknown>): string {
38
+ const b64url = (obj: Record<string, unknown>): string =>
39
+ Buffer.from(JSON.stringify(obj)).toString('base64url');
40
+ return `${b64url({ alg: 'none', typ: 'JWT' })}.${b64url({
41
+ exp: Math.floor(Date.now() / 1000) + 3600,
42
+ ...payload,
43
+ })}.sig`;
44
+ }
45
+
46
+ /** A JSON `Response` in the API's `{ data: ... }` success envelope. */
47
+ function jsonResponse(data: unknown): Response {
48
+ return new Response(JSON.stringify({ data }), {
49
+ status: 200,
50
+ headers: { 'content-type': 'application/json' },
51
+ });
52
+ }
53
+
54
+ const ACCOUNT_ID = 'acc1';
55
+ const PARENT_ID = 'root1';
56
+ const OLD_USERNAME = 'oldhandle';
57
+ const NEW_USERNAME = 'newhandle';
58
+
59
+ /** The write response: the account after a rename + a new picture. */
60
+ const renamedNode: AccountNode = {
61
+ accountId: ACCOUNT_ID,
62
+ kind: 'channel',
63
+ parentAccountId: PARENT_ID,
64
+ account: {
65
+ id: ACCOUNT_ID,
66
+ publicKey: 'pk-acc1',
67
+ username: NEW_USERNAME,
68
+ name: { displayName: 'Renamed Channel' },
69
+ avatar: 'file_new',
70
+ },
71
+ relationship: 'owner',
72
+ callerMembership: null,
73
+ };
74
+
75
+ describe('updateAccount identity-cache invalidation (real cache)', () => {
76
+ let originalFetch: typeof globalThis.fetch;
77
+ let fetchMock: jest.Mock<Promise<Response>, [RequestInfo | URL, RequestInit?]>;
78
+ let oxy: OxyServices;
79
+
80
+ beforeEach(() => {
81
+ originalFetch = globalThis.fetch;
82
+ fetchMock = jest.fn();
83
+ globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch;
84
+
85
+ oxy = new OxyServices({
86
+ baseURL: 'http://test.invalid',
87
+ enableRetry: false,
88
+ requestTimeout: 1000,
89
+ });
90
+ oxy.httpService.setTokens(makeJwt({ userId: 'operator-1' }));
91
+ });
92
+
93
+ afterEach(() => {
94
+ globalThis.fetch = originalFetch;
95
+ jest.clearAllMocks();
96
+ });
97
+
98
+ /**
99
+ * Warm every cache entry an account can be served under, plus one unrelated
100
+ * entry that must SURVIVE. Returns the number of network calls made, so each
101
+ * assertion below can be expressed as "did this read hit the network again".
102
+ */
103
+ async function warmCaches(): Promise<number> {
104
+ // The profile screen's two reads, under the handle it had BEFORE the edit
105
+ // and under the id.
106
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, username: OLD_USERNAME }));
107
+ await oxy.getProfileByUsername(OLD_USERNAME);
108
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, username: OLD_USERNAME }));
109
+ await oxy.getUserById(ACCOUNT_ID);
110
+
111
+ // The handle the account is ABOUT to be renamed to may already be warm (a
112
+ // 404-shaped read, a previous holder, a same-session preview). Warming it
113
+ // is what makes the old-handle assertion below non-vacuous: an
114
+ // implementation that busts only the response's handle passes for this one.
115
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, username: NEW_USERNAME }));
116
+ await oxy.getProfileByUsername(NEW_USERNAME);
117
+
118
+ // The pre-session login lookup (carries avatar + display name) and handle
119
+ // resolution — two keys the SDK's own profile-write sweep had drifted away
120
+ // from, and which no test previously covered from a write.
121
+ fetchMock.mockResolvedValueOnce(jsonResponse({ exists: true, username: OLD_USERNAME }));
122
+ await oxy.lookupUsername(OLD_USERNAME);
123
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, username: OLD_USERNAME }));
124
+ await oxy.resolveProfile(`@${OLD_USERNAME}@test.invalid`);
125
+
126
+ // The account-graph reads.
127
+ fetchMock.mockResolvedValueOnce(jsonResponse({ account: renamedNode }));
128
+ await oxy.getAccount(ACCOUNT_ID);
129
+ fetchMock.mockResolvedValueOnce(jsonResponse({ accounts: [renamedNode] }));
130
+ await oxy.listAccounts();
131
+ fetchMock.mockResolvedValueOnce(jsonResponse({ accounts: [renamedNode] }));
132
+ await oxy.listChildAccounts(PARENT_ID);
133
+
134
+ // An unrelated cached read. It must survive — the vacuity floor that tells
135
+ // a targeted sweep from a blanket `clearCache()`.
136
+ fetchMock.mockResolvedValueOnce(jsonResponse({ count: 3 }));
137
+ await oxy.httpService.get('/notifications/unread-count', { cache: true });
138
+
139
+ return fetchMock.mock.calls.length;
140
+ }
141
+
142
+ /** Perform the rename + picture change. */
143
+ async function performUpdate(): Promise<void> {
144
+ fetchMock.mockResolvedValueOnce(jsonResponse({ account: renamedNode }));
145
+ await oxy.updateAccount(ACCOUNT_ID, {
146
+ username: NEW_USERNAME,
147
+ avatar: 'file_new',
148
+ });
149
+ }
150
+
151
+ it('warms every read it later asserts on (control: all are cache hits before the write)', async () => {
152
+ const warmed = await warmCaches();
153
+
154
+ // Re-issue every read with no queued response. A cache MISS would call
155
+ // `fetch`, which now resolves `undefined` and throws — so a green run here
156
+ // is proof that each entry really is resident, and that the assertions
157
+ // below are measuring eviction rather than a cache that was never warm.
158
+ await oxy.getProfileByUsername(OLD_USERNAME);
159
+ await oxy.getProfileByUsername(NEW_USERNAME);
160
+ await oxy.getUserById(ACCOUNT_ID);
161
+ await oxy.lookupUsername(OLD_USERNAME);
162
+ await oxy.resolveProfile(`@${OLD_USERNAME}@test.invalid`);
163
+ await oxy.getAccount(ACCOUNT_ID);
164
+ await oxy.listAccounts();
165
+ await oxy.listChildAccounts(PARENT_ID);
166
+ await oxy.httpService.get('/notifications/unread-count', { cache: true });
167
+
168
+ expect(fetchMock).toHaveBeenCalledTimes(warmed);
169
+ });
170
+
171
+ it('evicts the OLD handle, not just the handle in the write response', async () => {
172
+ await warmCaches();
173
+ await performUpdate();
174
+ const afterWrite = fetchMock.mock.calls.length;
175
+
176
+ // THE assertion. `updateAccount` cannot know the pre-rename handle — it is
177
+ // in neither the request nor the response — so only a PREFIX sweep of
178
+ // `GET:/profiles/username/` reaches it. A targeted `clearCacheEntry` for
179
+ // the response's handle leaves this entry serving the pre-rename profile.
180
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, username: NEW_USERNAME }));
181
+ const refetched = await oxy.getProfileByUsername(OLD_USERNAME);
182
+
183
+ expect(fetchMock).toHaveBeenCalledTimes(afterWrite + 1);
184
+ expect(refetched.username).toBe(NEW_USERNAME);
185
+ });
186
+
187
+ it('evicts the by-id profile read the account detail page uses', async () => {
188
+ await warmCaches();
189
+ await performUpdate();
190
+ const afterWrite = fetchMock.mock.calls.length;
191
+
192
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, avatar: 'file_new' }));
193
+ const refetched = await oxy.getUserById(ACCOUNT_ID);
194
+
195
+ expect(fetchMock).toHaveBeenCalledTimes(afterWrite + 1);
196
+ expect(refetched.avatar).toBe('file_new');
197
+ });
198
+
199
+ it('evicts the new handle, the login lookup, and handle resolution', async () => {
200
+ await warmCaches();
201
+ await performUpdate();
202
+ let calls = fetchMock.mock.calls.length;
203
+
204
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, username: NEW_USERNAME }));
205
+ await oxy.getProfileByUsername(NEW_USERNAME);
206
+ expect(fetchMock).toHaveBeenCalledTimes(++calls);
207
+
208
+ fetchMock.mockResolvedValueOnce(jsonResponse({ exists: false, username: OLD_USERNAME }));
209
+ await oxy.lookupUsername(OLD_USERNAME);
210
+ expect(fetchMock).toHaveBeenCalledTimes(++calls);
211
+
212
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, username: NEW_USERNAME }));
213
+ await oxy.resolveProfile(`@${OLD_USERNAME}@test.invalid`);
214
+ expect(fetchMock).toHaveBeenCalledTimes(++calls);
215
+ });
216
+
217
+ it('evicts the account detail, the account lists, and the PARENT children list', async () => {
218
+ await warmCaches();
219
+ await performUpdate();
220
+ let calls = fetchMock.mock.calls.length;
221
+
222
+ fetchMock.mockResolvedValueOnce(jsonResponse({ account: renamedNode }));
223
+ await oxy.getAccount(ACCOUNT_ID);
224
+ expect(fetchMock).toHaveBeenCalledTimes(++calls);
225
+
226
+ fetchMock.mockResolvedValueOnce(jsonResponse({ accounts: [renamedNode] }));
227
+ await oxy.listAccounts();
228
+ expect(fetchMock).toHaveBeenCalledTimes(++calls);
229
+
230
+ // Keyed by the PARENT id, which is reachable only from the response node —
231
+ // the child's own id does not build this key.
232
+ fetchMock.mockResolvedValueOnce(jsonResponse({ accounts: [renamedNode] }));
233
+ await oxy.listChildAccounts(PARENT_ID);
234
+ expect(fetchMock).toHaveBeenCalledTimes(++calls);
235
+ });
236
+
237
+ it('leaves unrelated cached reads alone (it is a sweep, not a cache wipe)', async () => {
238
+ await warmCaches();
239
+ await performUpdate();
240
+ const afterWrite = fetchMock.mock.calls.length;
241
+
242
+ // No queued response: a miss would call `fetch` and throw.
243
+ const cached = await oxy.httpService.get<{ count: number }>(
244
+ '/notifications/unread-count',
245
+ { cache: true },
246
+ );
247
+
248
+ expect(fetchMock).toHaveBeenCalledTimes(afterWrite);
249
+ expect(cached.count).toBe(3);
250
+ });
251
+
252
+ it('does not sweep when the write fails', async () => {
253
+ await warmCaches();
254
+ const warmed = fetchMock.mock.calls.length;
255
+
256
+ fetchMock.mockResolvedValueOnce(
257
+ new Response(JSON.stringify({ message: 'forbidden' }), {
258
+ status: 403,
259
+ headers: { 'content-type': 'application/json' },
260
+ }),
261
+ );
262
+ await expect(
263
+ oxy.updateAccount(ACCOUNT_ID, { avatar: 'file_new' }),
264
+ ).rejects.toThrow();
265
+
266
+ // The failed PATCH is one call; every read below must still be a cache hit.
267
+ await oxy.getProfileByUsername(OLD_USERNAME);
268
+ await oxy.getUserById(ACCOUNT_ID);
269
+ await oxy.getAccount(ACCOUNT_ID);
270
+
271
+ expect(fetchMock).toHaveBeenCalledTimes(warmed + 1);
272
+ });
273
+
274
+ it('still sweeps the identity keys when the response carries no parent', async () => {
275
+ await warmCaches();
276
+ const rootNode: AccountNode = { ...renamedNode, parentAccountId: null };
277
+ fetchMock.mockResolvedValueOnce(jsonResponse({ account: rootNode }));
278
+ await oxy.updateAccount(ACCOUNT_ID, { avatar: 'file_new' });
279
+ const afterWrite = fetchMock.mock.calls.length;
280
+
281
+ // A root account has no children list to bust, but its identity keys go
282
+ // stale exactly the same way — the `parentAccountId` guard must not gate
283
+ // the identity sweep.
284
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: ACCOUNT_ID, avatar: 'file_new' }));
285
+ await oxy.getUserById(ACCOUNT_ID);
286
+
287
+ expect(fetchMock).toHaveBeenCalledTimes(afterWrite + 1);
288
+ });
289
+ });
290
+
291
+ describe('updateProfile identity-cache invalidation (real cache)', () => {
292
+ let originalFetch: typeof globalThis.fetch;
293
+ let fetchMock: jest.Mock<Promise<Response>, [RequestInfo | URL, RequestInit?]>;
294
+ let oxy: OxyServices;
295
+
296
+ const SELF_ID = 'me-1';
297
+
298
+ beforeEach(() => {
299
+ originalFetch = globalThis.fetch;
300
+ fetchMock = jest.fn();
301
+ globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch;
302
+ oxy = new OxyServices({
303
+ baseURL: 'http://test.invalid',
304
+ enableRetry: false,
305
+ requestTimeout: 1000,
306
+ });
307
+ oxy.httpService.setTokens(makeJwt({ userId: SELF_ID }));
308
+ });
309
+
310
+ afterEach(() => {
311
+ globalThis.fetch = originalFetch;
312
+ jest.clearAllMocks();
313
+ });
314
+
315
+ /**
316
+ * The two keys `updateProfile`'s own hand-written sweep MISSED. They are the
317
+ * whole point of this block — a test that only re-checked `GET:/users/me` and
318
+ * `GET:/profiles/username/` would have passed against the drifted version.
319
+ */
320
+ it('evicts the login lookup and handle resolution, not just the keys it used to know', async () => {
321
+ fetchMock.mockResolvedValueOnce(jsonResponse({ exists: true, username: 'alice', avatar: 'old' }));
322
+ await oxy.lookupUsername('alice');
323
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'old' }));
324
+ await oxy.resolveProfile('@alice@test.invalid');
325
+
326
+ // Control: both are warm (a miss would call the un-queued mock and throw).
327
+ await oxy.lookupUsername('alice');
328
+ await oxy.resolveProfile('@alice@test.invalid');
329
+ expect(fetchMock).toHaveBeenCalledTimes(2);
330
+
331
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'new' }));
332
+ await oxy.updateProfile({ avatar: 'new' });
333
+ expect(fetchMock).toHaveBeenCalledTimes(3);
334
+
335
+ fetchMock.mockResolvedValueOnce(jsonResponse({ exists: true, username: 'alice', avatar: 'new' }));
336
+ await oxy.lookupUsername('alice');
337
+ expect(fetchMock).toHaveBeenCalledTimes(4);
338
+
339
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'new' }));
340
+ await oxy.resolveProfile('@alice@test.invalid');
341
+ expect(fetchMock).toHaveBeenCalledTimes(5);
342
+ });
343
+
344
+ it('still evicts the self, by-id and handle reads it always did', async () => {
345
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'old' }));
346
+ await oxy.getCurrentUser();
347
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'old' }));
348
+ await oxy.getUserById(SELF_ID);
349
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'old' }));
350
+ await oxy.getProfileByUsername('alice');
351
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'old' }));
352
+ await oxy.getUserBySession('sess-1');
353
+ expect(fetchMock).toHaveBeenCalledTimes(4);
354
+
355
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'new' }));
356
+ await oxy.updateProfile({ avatar: 'new' });
357
+
358
+ let calls = 5;
359
+ for (const read of [
360
+ () => oxy.getCurrentUser(),
361
+ () => oxy.getUserById(SELF_ID),
362
+ () => oxy.getProfileByUsername('alice'),
363
+ () => oxy.getUserBySession('sess-1'),
364
+ ]) {
365
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: SELF_ID, avatar: 'new' }));
366
+ await read();
367
+ expect(fetchMock).toHaveBeenCalledTimes(++calls);
368
+ }
369
+ });
370
+ });
@@ -1,6 +1,6 @@
1
1
  import type {
2
2
  AccountKind,
3
- OrganizationCategory,
3
+ AccountCategoryId,
4
4
  UserNameResponse,
5
5
  UserRelationship,
6
6
  ThemePreference,
@@ -170,8 +170,16 @@ export interface User {
170
170
  // Managed account fields
171
171
  isManagedAccount?: boolean;
172
172
  managedBy?: string;
173
- /** Real-estate taxonomy when this user is a `kind: 'organization'` account. */
174
- organizationCategory?: OrganizationCategory;
173
+ /**
174
+ * What this account is about, for any NON-personal account. ORDERED — the
175
+ * first element is the primary category, and nothing may reorder it.
176
+ *
177
+ * Stable ids, not labels: render each through the
178
+ * `accounts.accountCategory.<id>` translation key so the reader sees their own
179
+ * language rather than the language of whoever chose it. Absent when the
180
+ * account has none.
181
+ */
182
+ accountCategories?: AccountCategoryId[];
175
183
  /**
176
184
  * The account's languages as full BCP-47 locales (`language-REGION`, e.g.
177
185
  * `en-US`, `es-MX`, `pt-BR`), ordered with the PRIMARY (UI) locale first.
@@ -2,10 +2,11 @@ import { OXY_USER_INVALIDATION_CHANNEL } from '@oxyhq/contracts';
2
2
 
3
3
  import {
4
4
  createOxyUserInvalidationHandler,
5
- evictOxyIdentityCache,
6
5
  publishOxyUserInvalidation,
7
- type OxyIdentityCacheEvictor,
8
6
  } from '../userInvalidation';
7
+ // The key enumeration this subscriber sweeps is platform-neutral and shared
8
+ // with the client mixins — see `utils/identityCacheSweep` and its own suite.
9
+ import type { OxyIdentityCacheEvictor } from '../../utils/identityCacheSweep';
9
10
 
10
11
  function makePublisher() {
11
12
  const calls: Array<{ channel: string; message: string }> = [];
@@ -200,21 +201,3 @@ describe('@oxyhq/core/server createOxyUserInvalidationHandler', () => {
200
201
  expect(() => createOxyUserInvalidationHandler()(validMessage)).not.toThrow();
201
202
  });
202
203
  });
203
-
204
- describe('@oxyhq/core/server evictOxyIdentityCache', () => {
205
- it('clears the exact by-id entry and the handle-keyed prefixes', () => {
206
- // The by-id key is exact. The handle-keyed ones cannot be derived from an
207
- // id without the lookup being invalidated, so they are swept by prefix.
208
- const { evictor, entries, prefixes } = makeEvictor();
209
- evictOxyIdentityCache(evictor, 'abc123');
210
-
211
- expect(entries).toEqual(['GET:/users/abc123']);
212
- expect(prefixes).toEqual([
213
- 'GET:/session/user/',
214
- 'GET:/users/me',
215
- 'GET:/auth/lookup/',
216
- 'GET:/profiles/username/',
217
- 'GET:/profiles/resolve',
218
- ]);
219
- });
220
- });
@@ -86,14 +86,17 @@ export { verifySecret } from './verifySecret';
86
86
  // changes, every consuming backend sweeps its caches instead of waiting out a TTL.
87
87
  export {
88
88
  createOxyUserInvalidationHandler,
89
- evictOxyIdentityCache,
90
89
  publishOxyUserInvalidation,
91
90
  } from './userInvalidation';
92
91
  export type {
93
- OxyIdentityCacheEvictor,
94
92
  OxyInvalidationPublisher,
95
93
  OxyUserInvalidationHandlerOptions,
96
94
  } from './userInvalidation';
95
+ // The identity-key enumeration itself is platform-neutral (`src/utils/`) so the
96
+ // client mixins and this Node-only subscriber sweep the SAME list — a second
97
+ // copy is what let `updateAccount` and `updateProfile` drift apart.
98
+ export { evictOxyIdentityCache, oxyUserByIdCacheKey, OXY_IDENTITY_CACHE_PREFIXES } from '../utils/identityCacheSweep';
99
+ export type { OxyIdentityCacheEvictor } from '../utils/identityCacheSweep';
97
100
 
98
101
  // Registrable-apex (eTLD+1) derivation via the Public Suffix List — the SINGLE
99
102
  // SOURCE OF TRUTH shared with the IdP worker and the client FAPI auto-detect.
@@ -6,10 +6,10 @@
6
6
  * Every Oxy backend caches Oxy identity, and none of them find out when it
7
7
  * changes. The `OxyServices` GET response cache holds `GET /users/:id` and
8
8
  * `GET /profiles/username/:name` for five minutes; it is swept when THIS process
9
- * writes the profile (see the `clearCacheEntry` calls in the user mixin) and
10
- * never when somebody else does — which is the normal case, since profiles are
11
- * edited in Oxy's own apps. So an avatar or display-name change is invisible to
12
- * every consuming backend for up to five minutes, per process.
9
+ * writes the profile (the `evictOxyIdentityCache` calls in the user and accounts
10
+ * mixins) and never when somebody else does — which is the normal case, since
11
+ * profiles are edited in Oxy's own apps. So an avatar or display-name change is
12
+ * invisible to every consuming backend for up to five minutes, per process.
13
13
  *
14
14
  * oxy-api broadcasts {@link OXY_USER_INVALIDATION_CHANNEL} on the shared Valkey
15
15
  * when a user's identity changes. This module is the consumer half: it parses
@@ -58,6 +58,10 @@ import {
58
58
  type OxyUserChangeReason,
59
59
  type OxyUserInvalidationEvent,
60
60
  } from '@oxyhq/contracts';
61
+ import {
62
+ evictOxyIdentityCache,
63
+ type OxyIdentityCacheEvictor,
64
+ } from '../utils/identityCacheSweep';
61
65
 
62
66
  /**
63
67
  * The publish surface of a Redis client. Both `ioredis` and `node-redis`
@@ -67,15 +71,6 @@ export interface OxyInvalidationPublisher {
67
71
  publish(channel: string, message: string): unknown;
68
72
  }
69
73
 
70
- /**
71
- * The cache-eviction surface of an {@link OxyServices} instance. Declared
72
- * structurally so this Node-only module does not pull in the client.
73
- */
74
- export interface OxyIdentityCacheEvictor {
75
- clearCacheEntry(key: string): void;
76
- clearCacheByPrefix(prefix: string): number;
77
- }
78
-
79
74
  /**
80
75
  * Broadcast that an Oxy user's record changed.
81
76
  *
@@ -202,26 +197,3 @@ export function createOxyUserInvalidationHandler(
202
197
  }
203
198
  };
204
199
  }
205
-
206
- /**
207
- * Sweep an `OxyServices` GET response cache of everything that could carry the
208
- * given user's identity.
209
- *
210
- * The by-id entry is exact. The by-username and resolve entries are keyed by
211
- * HANDLE, which cannot be derived from an id without the very lookup we are
212
- * invalidating, so those are swept by prefix — the same imprecision the SDK
213
- * already accepts when it sweeps its own cache after a local profile write, and
214
- * bounded by the fact that over-eviction costs a refetch and can never serve
215
- * wrong data.
216
- */
217
- export function evictOxyIdentityCache(oxy: OxyIdentityCacheEvictor, userId: string): void {
218
- // Match the sweep the user mixin runs after a local profile write — session-
219
- // bound and /users/me entries are keyed without the user id, so they must be
220
- // prefix-swept on cross-service invalidation too.
221
- oxy.clearCacheByPrefix('GET:/session/user/');
222
- oxy.clearCacheByPrefix('GET:/users/me');
223
- oxy.clearCacheByPrefix('GET:/auth/lookup/');
224
- oxy.clearCacheEntry(`GET:/users/${userId}`);
225
- oxy.clearCacheByPrefix('GET:/profiles/username/');
226
- oxy.clearCacheByPrefix('GET:/profiles/resolve');
227
- }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * The identity cache-key enumeration, checked against the keys REAL reads
3
+ * produce.
4
+ *
5
+ * A list-equality assertion on `OXY_IDENTITY_CACHE_PREFIXES` alone would be
6
+ * satisfied forever by a typo (`GET:/profile/username/`) — it pins the list's
7
+ * shape, not its correctness. So the load-bearing test here drives each prefix
8
+ * from the SDK method that actually reads under it, over the real
9
+ * `HttpService` cache, and asserts the sweep evicts every one. A prefix that
10
+ * stops matching its read fails here rather than in production.
11
+ *
12
+ * The list is shared by every profile writer (`updateProfile`,
13
+ * `updatePrivacySettings`, `updateAccount`) and by the Node-only
14
+ * `oxy:user:invalidate` subscriber in `@oxyhq/core/server`, precisely because
15
+ * two hand-written copies of it had already drifted apart.
16
+ */
17
+
18
+ import { OxyServices } from '../../OxyServices';
19
+ import {
20
+ OXY_IDENTITY_CACHE_PREFIXES,
21
+ evictOxyIdentityCache,
22
+ oxyUserByIdCacheKey,
23
+ type OxyIdentityCacheEvictor,
24
+ } from '../identityCacheSweep';
25
+
26
+ function makeJwt(payload: Record<string, unknown>): string {
27
+ const b64url = (obj: Record<string, unknown>): string =>
28
+ Buffer.from(JSON.stringify(obj)).toString('base64url');
29
+ return `${b64url({ alg: 'none', typ: 'JWT' })}.${b64url({
30
+ exp: Math.floor(Date.now() / 1000) + 3600,
31
+ ...payload,
32
+ })}.sig`;
33
+ }
34
+
35
+ function jsonResponse(data: unknown): Response {
36
+ return new Response(JSON.stringify({ data }), {
37
+ status: 200,
38
+ headers: { 'content-type': 'application/json' },
39
+ });
40
+ }
41
+
42
+ function makeRecordingEvictor() {
43
+ const entries: string[] = [];
44
+ const prefixes: string[] = [];
45
+ const evictor: OxyIdentityCacheEvictor = {
46
+ clearCacheEntry: (key) => {
47
+ entries.push(key);
48
+ },
49
+ clearCacheByPrefix: (prefix) => {
50
+ prefixes.push(prefix);
51
+ return 0;
52
+ },
53
+ };
54
+ return { evictor, entries, prefixes };
55
+ }
56
+
57
+ describe('evictOxyIdentityCache — the key list', () => {
58
+ it('sweeps every identity prefix and the exact by-id entry', () => {
59
+ const { evictor, entries, prefixes } = makeRecordingEvictor();
60
+ evictOxyIdentityCache(evictor, 'abc123');
61
+
62
+ expect(prefixes).toEqual([
63
+ 'GET:/session/user/',
64
+ 'GET:/users/me',
65
+ 'GET:/auth/lookup/',
66
+ 'GET:/profiles/username/',
67
+ 'GET:/profiles/resolve',
68
+ ]);
69
+ expect(prefixes).toEqual([...OXY_IDENTITY_CACHE_PREFIXES]);
70
+ expect(entries).toEqual([oxyUserByIdCacheKey('abc123')]);
71
+ });
72
+
73
+ it('sweeps the prefixes but writes no by-id entry when the id is unknown', () => {
74
+ const { evictor, entries, prefixes } = makeRecordingEvictor();
75
+ evictOxyIdentityCache(evictor);
76
+
77
+ expect(prefixes).toEqual([...OXY_IDENTITY_CACHE_PREFIXES]);
78
+ expect(entries).toEqual([]);
79
+ });
80
+
81
+ it('treats an empty-string id as unknown rather than building `GET:/users/`', () => {
82
+ // `GET:/users/` would be a prefix-shaped key handed to an EXACT-match
83
+ // deleter, so it evicts nothing while looking like it evicted something.
84
+ const { evictor, entries } = makeRecordingEvictor();
85
+ evictOxyIdentityCache(evictor, '');
86
+ expect(entries).toEqual([]);
87
+ });
88
+ });
89
+
90
+ describe('evictOxyIdentityCache — every prefix matches a real read', () => {
91
+ let originalFetch: typeof globalThis.fetch;
92
+ let fetchMock: jest.Mock<Promise<Response>, [RequestInfo | URL, RequestInit?]>;
93
+ let oxy: OxyServices;
94
+
95
+ const USER_ID = 'user-77';
96
+
97
+ beforeEach(() => {
98
+ originalFetch = globalThis.fetch;
99
+ fetchMock = jest.fn();
100
+ globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch;
101
+ oxy = new OxyServices({
102
+ baseURL: 'http://test.invalid',
103
+ enableRetry: false,
104
+ requestTimeout: 1000,
105
+ });
106
+ oxy.httpService.setTokens(makeJwt({ userId: USER_ID }));
107
+ });
108
+
109
+ afterEach(() => {
110
+ globalThis.fetch = originalFetch;
111
+ jest.clearAllMocks();
112
+ });
113
+
114
+ /** One real read per swept key, each warmed into the real response cache. */
115
+ const reads: ReadonlyArray<{
116
+ key: string;
117
+ warm: (client: OxyServices) => Promise<unknown>;
118
+ }> = [
119
+ { key: 'GET:/session/user/', warm: (c) => c.getUserBySession('sess-1') },
120
+ { key: 'GET:/users/me', warm: (c) => c.getCurrentUser() },
121
+ { key: 'GET:/auth/lookup/', warm: (c) => c.lookupUsername('alice') },
122
+ { key: 'GET:/profiles/username/', warm: (c) => c.getProfileByUsername('alice') },
123
+ { key: 'GET:/profiles/resolve', warm: (c) => c.resolveProfile('@alice@test.invalid') },
124
+ { key: 'GET:/users/<id>', warm: (c) => c.getUserById(USER_ID) },
125
+ ];
126
+
127
+ it('covers every prefix in the list with a read (no prefix goes unexercised)', () => {
128
+ // Vacuity floor: adding a prefix to the list without adding the read that
129
+ // exercises it fails HERE, rather than silently shrinking the test below.
130
+ expect(reads).toHaveLength(OXY_IDENTITY_CACHE_PREFIXES.length + 1);
131
+ for (const prefix of OXY_IDENTITY_CACHE_PREFIXES) {
132
+ expect(reads.some((read) => read.key === prefix)).toBe(true);
133
+ }
134
+ });
135
+
136
+ it.each(reads)('evicts the entry warmed by $key', async ({ warm }) => {
137
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: USER_ID, username: 'alice' }));
138
+ await warm(oxy);
139
+ expect(fetchMock).toHaveBeenCalledTimes(1);
140
+
141
+ // Control: the entry really is warm (a miss would call the un-queued mock).
142
+ await warm(oxy);
143
+ expect(fetchMock).toHaveBeenCalledTimes(1);
144
+
145
+ evictOxyIdentityCache(oxy, USER_ID);
146
+
147
+ fetchMock.mockResolvedValueOnce(jsonResponse({ id: USER_ID, username: 'alice-2' }));
148
+ await warm(oxy);
149
+ expect(fetchMock).toHaveBeenCalledTimes(2);
150
+ });
151
+ });