@oxyhq/core 20.1.0 → 21.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 (70) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/boot/sessionColdBoot.js +107 -8
  3. package/dist/cjs/i18n/locales/en-US.json +19 -2
  4. package/dist/cjs/i18n/locales/es-ES.json +19 -2
  5. package/dist/cjs/i18n/locales/locales/en-US.json +19 -2
  6. package/dist/cjs/i18n/locales/locales/es-ES.json +19 -2
  7. package/dist/cjs/index.js +50 -16
  8. package/dist/cjs/mixins/OxyServices.auth.js +27 -3
  9. package/dist/cjs/session/SessionClient.js +361 -1
  10. package/dist/cjs/session/accountDialogController.js +121 -147
  11. package/dist/cjs/session/accountSwitchTargets.js +75 -0
  12. package/dist/cjs/session/deviceDirectory.js +143 -0
  13. package/dist/cjs/session/deviceSwitcherRows.js +76 -0
  14. package/dist/cjs/session/projectSessionState.js +8 -1
  15. package/dist/cjs/session/sharedDeviceCredential.js +247 -0
  16. package/dist/esm/.tsbuildinfo +1 -1
  17. package/dist/esm/boot/sessionColdBoot.js +107 -8
  18. package/dist/esm/i18n/locales/en-US.json +19 -2
  19. package/dist/esm/i18n/locales/es-ES.json +19 -2
  20. package/dist/esm/i18n/locales/locales/en-US.json +19 -2
  21. package/dist/esm/i18n/locales/locales/es-ES.json +19 -2
  22. package/dist/esm/index.js +32 -10
  23. package/dist/esm/mixins/OxyServices.auth.js +27 -3
  24. package/dist/esm/session/SessionClient.js +362 -2
  25. package/dist/esm/session/accountDialogController.js +121 -147
  26. package/dist/esm/session/accountSwitchTargets.js +71 -0
  27. package/dist/esm/session/deviceDirectory.js +135 -0
  28. package/dist/esm/session/deviceSwitcherRows.js +72 -0
  29. package/dist/esm/session/projectSessionState.js +8 -2
  30. package/dist/esm/session/sharedDeviceCredential.js +239 -0
  31. package/dist/types/.tsbuildinfo +1 -1
  32. package/dist/types/boot/sessionColdBoot.d.ts +24 -4
  33. package/dist/types/index.d.ts +8 -3
  34. package/dist/types/mixins/OxyServices.auth.d.ts +75 -3
  35. package/dist/types/models/session.d.ts +11 -0
  36. package/dist/types/session/SessionClient.d.ts +202 -1
  37. package/dist/types/session/accountDialogController.d.ts +76 -64
  38. package/dist/types/session/accountSwitchTargets.d.ts +64 -0
  39. package/dist/types/session/deviceDirectory.d.ts +182 -0
  40. package/dist/types/session/deviceSwitcherRows.d.ts +92 -0
  41. package/dist/types/session/projectSessionState.d.ts +29 -0
  42. package/dist/types/session/sharedDeviceCredential.d.ts +202 -0
  43. package/package.json +3 -3
  44. package/src/boot/__tests__/sessionColdBoot.sharedDevice.test.ts +325 -0
  45. package/src/boot/sessionColdBoot.ts +133 -9
  46. package/src/i18n/locales/en-US.json +19 -2
  47. package/src/i18n/locales/es-ES.json +19 -2
  48. package/src/index.ts +75 -18
  49. package/src/mixins/OxyServices.auth.ts +67 -5
  50. package/src/mixins/__tests__/preSessionSkipAuth.test.ts +54 -1
  51. package/src/models/session.ts +11 -0
  52. package/src/session/SessionClient.ts +386 -1
  53. package/src/session/__tests__/SessionClient.directory.test.ts +688 -0
  54. package/src/session/__tests__/accountDialogController.test.ts +411 -278
  55. package/src/session/__tests__/accountSwitchTargets.test.ts +132 -0
  56. package/src/session/__tests__/deviceDirectory.test.ts +422 -0
  57. package/src/session/__tests__/deviceSwitcherRows.test.ts +223 -0
  58. package/src/session/__tests__/projectSessionState.test.ts +17 -0
  59. package/src/session/__tests__/sharedDeviceCredential.test.ts +300 -0
  60. package/src/session/accountDialogController.ts +141 -179
  61. package/src/session/accountSwitchTargets.ts +87 -0
  62. package/src/session/deviceDirectory.ts +269 -0
  63. package/src/session/deviceSwitcherRows.ts +145 -0
  64. package/src/session/projectSessionState.ts +9 -3
  65. package/src/session/sharedDeviceCredential.ts +349 -0
  66. package/dist/cjs/session/accountProjection.js +0 -213
  67. package/dist/esm/session/accountProjection.js +0 -207
  68. package/dist/types/session/accountProjection.d.ts +0 -198
  69. package/src/session/__tests__/accountProjection.test.ts +0 -447
  70. package/src/session/accountProjection.ts +0 -354
@@ -0,0 +1,688 @@
1
+ /**
2
+ * `SessionClient` on the device DIRECTORY (issue #937, ADR 0002).
3
+ *
4
+ * The four properties the account lane already holds are re-asserted here for
5
+ * the context lane, because none of them transfers for free:
6
+ * 1. last-writer-wins is `deviceId`-SCOPED, not global;
7
+ * 2. the bearer for the new context is committed BEFORE any subscriber is
8
+ * notified;
9
+ * 3. an identity-pinned client tracks the device truthfully and never adopts
10
+ * a foreign bearer;
11
+ * 4. an idempotent activation moves nothing, so it reconciles nothing and
12
+ * wakes nobody — the client-side reading of the server's `changed: false`.
13
+ */
14
+ import type { DeviceDirectory, DeviceSessionState } from '@oxyhq/contracts';
15
+ import { SessionClient, type SessionClientHost } from '../SessionClient';
16
+ import { resolveDeviceContext } from '../deviceDirectory';
17
+ import { computeIdentityTag } from '../../utils/cacheKey';
18
+
19
+ /** A minimal jwt-decode-able token whose `userId` claim is `accountId`. */
20
+ function jwtFor(accountId: string): string {
21
+ const payload = Buffer.from(JSON.stringify({ userId: accountId })).toString('base64url');
22
+ return `h.${payload}.s`;
23
+ }
24
+
25
+ /**
26
+ * Nate (personal) plus `org`, reached through Nate. `activeContextId` picks
27
+ * which one is live.
28
+ */
29
+ function directoryAt(
30
+ revision: number,
31
+ activeContextId: string | null,
32
+ deviceId = 'd1',
33
+ ): DeviceDirectory {
34
+ return {
35
+ deviceId,
36
+ revision,
37
+ activeContextId,
38
+ updatedAt: 1_720_000_000_000,
39
+ principals: [
40
+ {
41
+ id: 'p-nate',
42
+ userId: 'nate',
43
+ authuser: 0,
44
+ user: { id: 'nate', username: 'nate' },
45
+ contexts: [
46
+ {
47
+ id: 'ctx-nate',
48
+ accountId: 'nate',
49
+ kind: 'personal',
50
+ relationship: 'self',
51
+ account: { id: 'nate', username: 'nate' },
52
+ onDevice: true,
53
+ available: true,
54
+ active: activeContextId === 'ctx-nate',
55
+ lastUsedAt: null,
56
+ },
57
+ {
58
+ id: 'ctx-org',
59
+ accountId: 'org',
60
+ kind: 'organization',
61
+ relationship: 'owner',
62
+ account: { id: 'org', username: 'oxy' },
63
+ onDevice: true,
64
+ available: true,
65
+ active: activeContextId === 'ctx-org',
66
+ lastUsedAt: null,
67
+ },
68
+ ],
69
+ },
70
+ ],
71
+ };
72
+ }
73
+
74
+ function stateAt(revision: number, activeAccountId: string, deviceId = 'd1'): DeviceSessionState {
75
+ return {
76
+ deviceId,
77
+ accounts: [
78
+ { accountId: 'nate', sessionId: 's-nate', authuser: 0 },
79
+ { accountId: 'org', sessionId: 's-org', authuser: 1, operatedByUserId: 'nate' },
80
+ ],
81
+ activeAccountId,
82
+ revision,
83
+ updatedAt: 1_720_000_000_000,
84
+ };
85
+ }
86
+
87
+ type Route = () => unknown;
88
+
89
+ interface TestHost extends SessionClientHost {
90
+ urls: string[];
91
+ bodies: unknown[];
92
+ planted(): string | null;
93
+ }
94
+
95
+ function makeHost(routes: Record<string, Route>, initialToken: string | null): TestHost {
96
+ const urls: string[] = [];
97
+ const bodies: unknown[] = [];
98
+ let planted = initialToken;
99
+ return {
100
+ makeRequest: jest.fn(async (_method: string, url: string, data?: unknown) => {
101
+ urls.push(url);
102
+ bodies.push(data);
103
+ const route = routes[url];
104
+ if (!route) {
105
+ throw new Error(`unexpected request: ${url}`);
106
+ }
107
+ return route();
108
+ }),
109
+ getBaseURL: () => 'http://test.invalid',
110
+ getAccessToken: () => planted,
111
+ getDeviceCredential: () => null,
112
+ onTokensChanged: () => () => undefined,
113
+ setTokens: (token: string) => {
114
+ planted = token;
115
+ },
116
+ getCurrentAccountId: () => null,
117
+ urls,
118
+ bodies,
119
+ planted: () => planted,
120
+ };
121
+ }
122
+
123
+ /** `applyState` is protected; a tiny subclass exposes it for the unit tests. */
124
+ class TestClient extends SessionClient {
125
+ public apply(raw: unknown): boolean {
126
+ return this.applyState(raw);
127
+ }
128
+ }
129
+
130
+ const countOf = (urls: string[], url: string): number => urls.filter((seen) => seen === url).length;
131
+
132
+ /**
133
+ * A recording stand-in for `BroadcastChannel`.
134
+ *
135
+ * Node's real one is ref'd and would keep the Jest event loop alive forever, but
136
+ * simply feature-detecting it away would ALSO make the cross-tab wake
137
+ * unobservable — and "an idempotent activation wakes nobody" is one of the
138
+ * properties under test, so it has to be a fake rather than an absence.
139
+ */
140
+ const posted: unknown[] = [];
141
+ class RecordingBroadcastChannel {
142
+ onmessage: ((event: { data: unknown }) => void) | null = null;
143
+ postMessage(message: unknown): void {
144
+ posted.push(message);
145
+ }
146
+ close(): void {
147
+ /* nothing to release */
148
+ }
149
+ }
150
+
151
+ describe('SessionClient — device directory', () => {
152
+ const realBroadcastChannel = (globalThis as { BroadcastChannel?: unknown }).BroadcastChannel;
153
+ beforeAll(() => {
154
+ (globalThis as { BroadcastChannel?: unknown }).BroadcastChannel = RecordingBroadcastChannel;
155
+ });
156
+ afterAll(() => {
157
+ (globalThis as { BroadcastChannel?: unknown }).BroadcastChannel = realBroadcastChannel;
158
+ });
159
+ beforeEach(() => {
160
+ posted.length = 0;
161
+ });
162
+
163
+ it('holds no directory until one is read', () => {
164
+ const client = new SessionClient(makeHost({}, jwtFor('nate')));
165
+
166
+ expect(client.getDirectory()).toBeNull();
167
+ expect(client.getActiveContext()).toBeNull();
168
+ });
169
+
170
+ it('refreshDirectory GETs the directory, applies it and notifies', async () => {
171
+ const host = makeHost(
172
+ { '/session/device/directory': () => directoryAt(3, 'ctx-org') },
173
+ jwtFor('nate'),
174
+ );
175
+ const client = new SessionClient(host);
176
+ const seen: Array<DeviceDirectory | null> = [];
177
+ client.subscribeDirectory((directory) => seen.push(directory));
178
+
179
+ await client.refreshDirectory();
180
+
181
+ expect(host.makeRequest).toHaveBeenCalledWith('GET', '/session/device/directory', undefined, { cache: false });
182
+ expect(client.getDirectory()?.revision).toBe(3);
183
+ expect(client.getActiveContext()?.subject.accountId).toBe('org');
184
+ expect(client.getActiveContext()?.actor.userId).toBe('nate');
185
+ expect(seen.at(-1)?.revision).toBe(3);
186
+ });
187
+
188
+ it('rejects a STRICTLY LOWER revision from the same device', async () => {
189
+ let next = directoryAt(5, 'ctx-nate');
190
+ const host = makeHost({ '/session/device/directory': () => next }, jwtFor('nate'));
191
+ const client = new SessionClient(host);
192
+
193
+ await client.refreshDirectory();
194
+
195
+ // Two GETs racing: the older response landing second must not win.
196
+ next = directoryAt(4, 'ctx-org');
197
+ await client.refreshDirectory();
198
+ expect(client.getActiveContext()?.subject.accountId).toBe('nate');
199
+
200
+ next = directoryAt(6, 'ctx-org');
201
+ await client.refreshDirectory();
202
+ expect(client.getActiveContext()?.subject.accountId).toBe('org');
203
+ });
204
+
205
+ /**
206
+ * The equal-revision read is NOT redundant, and rejecting it was a bug.
207
+ *
208
+ * The directory carries rows projected from the account graph, and the server
209
+ * materializes a context for every account a principal may act as WITHOUT
210
+ * bumping `revision` — deliberately, because `revision` tracks what the DEVICE
211
+ * holds and must never advance on a read. So a removed-then-rematerialized
212
+ * context comes back under a NEW id at an unchanged revision, as does a
213
+ * newly-granted `account:act_as`. Under a `<=` guard neither would ever be
214
+ * seen until some unrelated device mutation happened to move the number.
215
+ */
216
+ it('applies a re-read at the SAME revision, so a rematerialized context id lands', async () => {
217
+ const withOrgContextId = (contextId: string): DeviceDirectory => {
218
+ const base = directoryAt(5, 'ctx-nate');
219
+ const principal = base.principals[0];
220
+ return {
221
+ ...base,
222
+ principals: [
223
+ {
224
+ ...principal,
225
+ contexts: principal.contexts.map((context) =>
226
+ context.accountId === 'org' ? { ...context, id: contextId, onDevice: false } : context,
227
+ ),
228
+ },
229
+ ],
230
+ };
231
+ };
232
+
233
+ let next = withOrgContextId('ctx-org-first');
234
+ const host = makeHost({ '/session/device/directory': () => next }, jwtFor('nate'));
235
+ const client = new SessionClient(host);
236
+ await client.refreshDirectory();
237
+ expect(resolveDeviceContext(client.getDirectory(), 'ctx-org-first')).not.toBeNull();
238
+
239
+ // Same device, same revision — the pair is back under a fresh id.
240
+ next = withOrgContextId('ctx-org-rematerialized');
241
+ await client.refreshDirectory();
242
+
243
+ expect(resolveDeviceContext(client.getDirectory(), 'ctx-org-rematerialized')).not.toBeNull();
244
+ // And the id that is gone stays gone: it must read as absent, not as an
245
+ // error, and nothing may still be holding it.
246
+ expect(resolveDeviceContext(client.getDirectory(), 'ctx-org-first')).toBeNull();
247
+ });
248
+
249
+ it('accepts a LOWER-revision directory from a DIFFERENT device', async () => {
250
+ let next = directoryAt(10, 'ctx-nate', 'A');
251
+ const host = makeHost({ '/session/device/directory': () => next }, jwtFor('nate'));
252
+ const client = new SessionClient(host);
253
+
254
+ await client.refreshDirectory();
255
+ expect(client.getDirectory()?.deviceId).toBe('A');
256
+
257
+ // Device B is freshly converged at revision 1. The revision is monotone only
258
+ // WITHIN a device, so B must win over A's stale-but-higher number.
259
+ next = directoryAt(1, 'ctx-org', 'B');
260
+ await client.refreshDirectory();
261
+ expect(client.getDirectory()?.deviceId).toBe('B');
262
+ expect(client.getDirectory()?.revision).toBe(1);
263
+ });
264
+
265
+ it('discards an invalid directory and keeps the one it holds', async () => {
266
+ let next: unknown = directoryAt(2, 'ctx-nate');
267
+ const host = makeHost({ '/session/device/directory': () => next }, jwtFor('nate'));
268
+ const client = new SessionClient(host);
269
+
270
+ await client.refreshDirectory();
271
+ next = { deviceId: 'd1', revision: 9, principals: 'nope' };
272
+ await client.refreshDirectory();
273
+
274
+ expect(client.getDirectory()?.revision).toBe(2);
275
+ });
276
+
277
+ it('never fetches a directory for a client that has not asked for one', () => {
278
+ const host = makeHost({}, jwtFor('nate'));
279
+ const client = new TestClient(host);
280
+
281
+ client.apply(stateAt(1, 'nate'));
282
+ client.apply(stateAt(2, 'org'));
283
+
284
+ expect(countOf(host.urls, '/session/device/directory')).toBe(0);
285
+ });
286
+
287
+ it('re-reads the directory BEFORE notifying once the flat state moves past it', async () => {
288
+ let releaseDirectory: (() => void) | null = null;
289
+ const host = makeHost(
290
+ {
291
+ '/session/device/directory': () => {
292
+ if (releaseDirectory === null) {
293
+ return directoryAt(2, 'ctx-nate');
294
+ }
295
+ return new Promise((resolve) => {
296
+ releaseDirectory = () => resolve(directoryAt(3, 'ctx-org'));
297
+ });
298
+ },
299
+ },
300
+ jwtFor('nate'),
301
+ );
302
+ const client = new TestClient(host);
303
+ await client.refreshDirectory();
304
+
305
+ // Positive control for the previous test: this client HAS a directory, so
306
+ // an advancing state does fetch one.
307
+ const observed: Array<number | undefined> = [];
308
+ client.subscribe(() => observed.push(client.getDirectory()?.revision));
309
+ releaseDirectory = () => undefined;
310
+
311
+ client.apply(stateAt(3, 'org'));
312
+ // The directory is still at 2 and the fetch is in flight — nobody has been
313
+ // told about revision 3 yet.
314
+ expect(observed).toEqual([]);
315
+ expect(countOf(host.urls, '/session/device/directory')).toBe(2);
316
+
317
+ releaseDirectory();
318
+ for (let i = 0; i < 5; i++) {
319
+ await Promise.resolve();
320
+ }
321
+
322
+ // The one notify observed BOTH halves at revision 3.
323
+ expect(observed).toEqual([3]);
324
+ expect(client.getActiveContext()?.subject.accountId).toBe('org');
325
+ });
326
+
327
+ it('activateContext POSTs { contextId } and nothing else', async () => {
328
+ const host = makeHost(
329
+ {
330
+ '/session/device/activate': () => ({
331
+ directory: directoryAt(4, 'ctx-org'),
332
+ activeToken: { accessToken: jwtFor('org'), expiresAt: 'x' },
333
+ }),
334
+ '/session/device/state': () => ({ state: stateAt(4, 'org'), activeToken: null }),
335
+ },
336
+ jwtFor('nate'),
337
+ );
338
+ const client = new SessionClient(host);
339
+
340
+ await client.activateContext('ctx-org');
341
+
342
+ expect(host.makeRequest).toHaveBeenCalledWith('POST', '/session/device/activate', { contextId: 'ctx-org' }, { cache: false });
343
+ expect(client.getActiveContext()?.contextId).toBe('ctx-org');
344
+ });
345
+
346
+ it('commits the new context bearer BEFORE any subscriber observes the new subject', async () => {
347
+ const host = makeHost(
348
+ {
349
+ '/session/device/activate': () => ({
350
+ directory: directoryAt(4, 'ctx-org'),
351
+ activeToken: { accessToken: jwtFor('org'), expiresAt: 'x' },
352
+ }),
353
+ '/session/device/state': () => ({ state: stateAt(4, 'org'), activeToken: null }),
354
+ },
355
+ jwtFor('nate'),
356
+ );
357
+ const client = new SessionClient(host);
358
+
359
+ const observations: Array<{ subject: string | null; bearer: string }> = [];
360
+ client.subscribeDirectory((directory) => {
361
+ observations.push({
362
+ subject: directory?.activeContextId === 'ctx-org' ? 'org' : 'nate',
363
+ bearer: computeIdentityTag(host.getAccessToken()),
364
+ });
365
+ });
366
+
367
+ await client.activateContext('ctx-org');
368
+
369
+ expect(observations.length).toBeGreaterThan(0);
370
+ for (const observation of observations) {
371
+ expect(observation.bearer).toBe(observation.subject);
372
+ }
373
+ });
374
+
375
+ it('reconciles the flat projection so it cannot lag the directory', async () => {
376
+ const host = makeHost(
377
+ {
378
+ '/session/device/activate': () => ({
379
+ directory: directoryAt(4, 'ctx-org'),
380
+ activeToken: { accessToken: jwtFor('org'), expiresAt: 'x' },
381
+ }),
382
+ '/session/device/state': () => ({ state: stateAt(4, 'org'), activeToken: null }),
383
+ },
384
+ jwtFor('nate'),
385
+ );
386
+ const client = new TestClient(host);
387
+ client.apply(stateAt(3, 'nate'));
388
+
389
+ await client.activateContext('ctx-org');
390
+
391
+ expect(countOf(host.urls, '/session/device/state')).toBe(1);
392
+ expect(client.getState()?.activeAccountId).toBe('org');
393
+ expect(client.getState()?.revision).toBe(4);
394
+ });
395
+
396
+ it('an idempotent activation reconciles nothing and wakes nobody', async () => {
397
+ let directory = directoryAt(4, 'ctx-org');
398
+ const host = makeHost(
399
+ {
400
+ '/session/device/activate': () => ({
401
+ directory,
402
+ activeToken: { accessToken: jwtFor('org'), expiresAt: 'x' },
403
+ }),
404
+ '/session/device/state': () => ({ state: stateAt(directory.revision, 'org'), activeToken: null }),
405
+ },
406
+ jwtFor('nate'),
407
+ );
408
+ const client = new TestClient(host);
409
+ client.apply(stateAt(4, 'org'));
410
+ await client.activateContext('ctx-org');
411
+
412
+ const before = host.urls.length;
413
+ // The server answers the SAME revision: nothing was written, nothing
414
+ // broadcast. The client must read that off the revision, not re-fetch —
415
+ // and must not wake the origin's other tabs to converge on a change that
416
+ // did not happen.
417
+ await client.activateContext('ctx-org');
418
+ expect(host.urls.slice(before)).toEqual(['/session/device/activate']);
419
+ expect(posted).toEqual([]);
420
+
421
+ // Vacuity floor: a real transition from the same starting point DOES
422
+ // reconcile and DOES wake the siblings, so the assertions above are
423
+ // measuring idempotence and not a client that simply never does either.
424
+ directory = directoryAt(5, 'ctx-nate');
425
+ const beforeReal = host.urls.length;
426
+ await client.activateContext('ctx-nate');
427
+ expect(host.urls.slice(beforeReal)).toEqual(['/session/device/activate', '/session/device/state']);
428
+ expect(posted).toEqual([{ type: 'commit', at: expect.any(Number) }]);
429
+ });
430
+
431
+ it('discards an invalid activation response without touching the directory', async () => {
432
+ const host = makeHost(
433
+ {
434
+ '/session/device/directory': () => directoryAt(4, 'ctx-nate'),
435
+ '/session/device/activate': () => ({ directory: { deviceId: 'd1' }, activeToken: null }),
436
+ },
437
+ jwtFor('nate'),
438
+ );
439
+ const client = new SessionClient(host);
440
+ await client.refreshDirectory();
441
+
442
+ await client.activateContext('ctx-org');
443
+
444
+ expect(client.getActiveContext()?.contextId).toBe('ctx-nate');
445
+ expect(countOf(host.urls, '/session/device/state')).toBe(0);
446
+ });
447
+
448
+ describe('context-aware removals', () => {
449
+ const removalResponse = (revision: number, activeContextId: string | null) => ({
450
+ directory: directoryAt(revision, activeContextId),
451
+ state: stateAt(revision, activeContextId === 'ctx-org' ? 'org' : 'nate'),
452
+ activeToken: { accessToken: jwtFor(activeContextId === 'ctx-org' ? 'org' : 'nate'), expiresAt: 'x' },
453
+ });
454
+
455
+ it('signOutContext POSTs { contextId } and applies BOTH halves from one response', async () => {
456
+ const host = makeHost(
457
+ { '/session/device/signout': () => removalResponse(6, 'ctx-nate') },
458
+ jwtFor('org'),
459
+ );
460
+ const client = new TestClient(host);
461
+ client.apply(stateAt(5, 'org'));
462
+
463
+ await client.signOutContext('ctx-org');
464
+
465
+ expect(host.makeRequest).toHaveBeenCalledWith('POST', '/session/device/signout', { contextId: 'ctx-org' }, { cache: false });
466
+ expect(client.getActiveContext()?.contextId).toBe('ctx-nate');
467
+ expect(client.getState()?.activeAccountId).toBe('nate');
468
+ expect(client.getState()?.revision).toBe(6);
469
+ // Both halves arrived together, so nothing had to be fetched back.
470
+ expect(countOf(host.urls, '/session/device/state')).toBe(0);
471
+ expect(countOf(host.urls, '/session/device/directory')).toBe(0);
472
+ });
473
+
474
+ it('signOutPrincipal POSTs { principalId }', async () => {
475
+ const host = makeHost(
476
+ { '/session/device/signout': () => removalResponse(7, 'ctx-nate') },
477
+ jwtFor('nate'),
478
+ );
479
+ const client = new SessionClient(host);
480
+
481
+ await client.signOutPrincipal('p-alice');
482
+
483
+ expect(host.makeRequest).toHaveBeenCalledWith('POST', '/session/device/signout', { principalId: 'p-alice' }, { cache: false });
484
+ });
485
+
486
+ it('commits the replacement context bearer before any subscriber observes it', async () => {
487
+ const host = makeHost(
488
+ { '/session/device/signout': () => removalResponse(6, 'ctx-nate') },
489
+ jwtFor('org'),
490
+ );
491
+ const client = new TestClient(host);
492
+ client.apply(stateAt(5, 'org'));
493
+
494
+ const observations: Array<{ active: string | null; bearer: string }> = [];
495
+ client.subscribe((state) => {
496
+ observations.push({
497
+ active: state?.activeAccountId ?? null,
498
+ bearer: computeIdentityTag(host.getAccessToken()),
499
+ });
500
+ });
501
+
502
+ await client.signOutContext('ctx-org');
503
+
504
+ expect(observations.length).toBeGreaterThan(0);
505
+ for (const observation of observations) {
506
+ expect(observation.bearer).toBe(observation.active);
507
+ }
508
+ });
509
+
510
+ /**
511
+ * The removal response is `{directory, state, activeToken}` and must never
512
+ * be routed through the flat parser, which would strip the directory. The
513
+ * client-side half of that rule is that a directory-LESS payload on this
514
+ * lane is refused outright rather than half-applied.
515
+ */
516
+ it('discards a response missing the directory instead of applying the flat half', async () => {
517
+ const host = makeHost(
518
+ {
519
+ '/session/device/signout': () => ({
520
+ state: stateAt(6, 'nate'),
521
+ activeToken: { accessToken: jwtFor('nate'), expiresAt: 'x' },
522
+ }),
523
+ },
524
+ jwtFor('org'),
525
+ );
526
+ const client = new TestClient(host);
527
+ client.apply(stateAt(5, 'org'));
528
+
529
+ await client.signOutContext('ctx-org');
530
+
531
+ expect(client.getState()?.revision).toBe(5);
532
+ expect(client.getState()?.activeAccountId).toBe('org');
533
+ });
534
+
535
+ it('reports a device emptied by the removal as an authoritative sign-out', async () => {
536
+ const origins: string[] = [];
537
+ const host = makeHost(
538
+ {
539
+ '/session/device/signout': () => ({
540
+ directory: {
541
+ ...directoryAt(6, null),
542
+ principals: [],
543
+ },
544
+ state: { ...stateAt(6, 'nate'), accounts: [], activeAccountId: null },
545
+ activeToken: null,
546
+ }),
547
+ },
548
+ jwtFor('nate'),
549
+ );
550
+ const client = new TestClient(host, { onUnauthenticated: (origin) => origins.push(origin) });
551
+ client.apply(stateAt(5, 'nate'));
552
+
553
+ await client.signOutPrincipal('p-nate');
554
+
555
+ // `request` origin, not `push`: a REST removal this client asked for is
556
+ // authoritative enough to erase the durable device credential.
557
+ expect(origins).toEqual(['request']);
558
+ expect(client.getActiveContext()).toBeNull();
559
+ });
560
+
561
+ /**
562
+ * A socket push already applied this revision, so the flat half no-ops and
563
+ * publishes nothing. The directory half still moved — the push carries no
564
+ * directory — and without its own publish the switcher would keep rendering
565
+ * a context the removal deleted.
566
+ */
567
+ it('publishes the directory when only the directory half moved', async () => {
568
+ const host = makeHost(
569
+ { '/session/device/signout': () => removalResponse(6, 'ctx-nate') },
570
+ jwtFor('nate'),
571
+ );
572
+ const client = new TestClient(host);
573
+ // The push landed first: the flat state is already at revision 6.
574
+ client.apply(stateAt(6, 'nate'));
575
+
576
+ const seen: Array<string | null | undefined> = [];
577
+ client.subscribeDirectory((directory) => seen.push(directory?.activeContextId));
578
+
579
+ await client.signOutContext('ctx-org');
580
+
581
+ expect(seen).toEqual(['ctx-nate']);
582
+ expect(client.getActiveContext()?.contextId).toBe('ctx-nate');
583
+ });
584
+
585
+ it('leaves signOut({accountId}) on the flat lane untouched', async () => {
586
+ const host = makeHost(
587
+ {
588
+ '/session/device/signout': () => ({
589
+ state: stateAt(6, 'nate'),
590
+ activeToken: { accessToken: jwtFor('nate'), expiresAt: 'x' },
591
+ }),
592
+ },
593
+ jwtFor('org'),
594
+ );
595
+ const client = new TestClient(host);
596
+ client.apply(stateAt(5, 'org'));
597
+
598
+ await client.signOut({ accountId: 'org' });
599
+
600
+ // The flat response has no directory and is still accepted here.
601
+ expect(client.getState()?.revision).toBe(6);
602
+ expect(client.getState()?.activeAccountId).toBe('nate');
603
+ });
604
+ });
605
+
606
+ describe('under an identity pin', () => {
607
+ it('tracks an activation truthfully but never adopts the foreign bearer', async () => {
608
+ const host = makeHost(
609
+ {
610
+ '/session/device/activate': () => ({
611
+ directory: directoryAt(4, 'ctx-org'),
612
+ activeToken: { accessToken: jwtFor('org'), expiresAt: 'x' },
613
+ }),
614
+ '/session/device/state': () => ({ state: stateAt(4, 'org'), activeToken: null }),
615
+ },
616
+ jwtFor('nate'),
617
+ );
618
+ const client = new SessionClient(host, { getPinnedAccountId: () => 'nate' });
619
+
620
+ await client.activateContext('ctx-org');
621
+
622
+ expect(client.getActiveContext()?.subject.accountId).toBe('org');
623
+ expect(host.planted()).toBe(jwtFor('nate'));
624
+ });
625
+
626
+ it('DOES adopt the bearer when the new subject IS the pinned account', async () => {
627
+ const host = makeHost(
628
+ {
629
+ '/session/device/activate': () => ({
630
+ directory: directoryAt(4, 'ctx-nate'),
631
+ activeToken: { accessToken: jwtFor('nate'), expiresAt: 'x' },
632
+ }),
633
+ '/session/device/state': () => ({ state: stateAt(4, 'nate'), activeToken: null }),
634
+ },
635
+ null,
636
+ );
637
+ const client = new SessionClient(host, { getPinnedAccountId: () => 'nate' });
638
+
639
+ await client.activateContext('ctx-nate');
640
+
641
+ expect(host.planted()).toBe(jwtFor('nate'));
642
+ });
643
+ });
644
+ });
645
+
646
+ describe('SessionClient — the directory does not outlive the device', () => {
647
+ it('drops the held directory when the device empties', async () => {
648
+ const host = makeHost(
649
+ { '/session/device/directory': () => directoryAt(3, 'ctx-nate') },
650
+ jwtFor('nate'),
651
+ );
652
+ const client = new TestClient(host);
653
+ await client.refreshDirectory();
654
+ expect(client.getDirectory()?.revision).toBe(3);
655
+
656
+ // A sign-out: the device reports zero accounts.
657
+ client.apply({
658
+ deviceId: 'd1',
659
+ accounts: [],
660
+ activeAccountId: null,
661
+ revision: 4,
662
+ updatedAt: 1_720_000_000_100,
663
+ });
664
+
665
+ // The directory is bearer-read, and a sign-out leaves no bearer to re-read
666
+ // it with — so nothing downstream could ever correct a stale one. Without
667
+ // this, a directory-rendering switcher goes on showing the people who were
668
+ // signed in here.
669
+ expect(client.getDirectory()).toBeNull();
670
+ expect(client.getActiveContext()).toBeNull();
671
+ });
672
+
673
+ it('keeps the directory across an ordinary state change that still has accounts', async () => {
674
+ const host = makeHost(
675
+ {
676
+ '/session/device/directory': () => directoryAt(5, 'ctx-nate'),
677
+ },
678
+ jwtFor('nate'),
679
+ );
680
+ const client = new TestClient(host);
681
+ await client.refreshDirectory();
682
+
683
+ // A switch, not a sign-out: the directory stays and settles on its own.
684
+ client.apply(stateAt(5, 'org'));
685
+
686
+ expect(client.getDirectory()?.revision).toBe(5);
687
+ });
688
+ });