@baukit/suite-client 0.0.0-stage → 0.10.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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +73 -2
  3. package/dist/api.d.ts +103 -0
  4. package/dist/api.d.ts.map +1 -0
  5. package/dist/api.js +67 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/authorize.d.ts +48 -0
  8. package/dist/authorize.d.ts.map +1 -0
  9. package/dist/authorize.js +123 -0
  10. package/dist/authorize.js.map +1 -0
  11. package/dist/cjs/package.json +1 -0
  12. package/dist/cjs/peers.d.ts +14 -0
  13. package/dist/cjs/peers.d.ts.map +1 -0
  14. package/dist/cjs/peers.js +63 -0
  15. package/dist/cjs/peers.js.map +1 -0
  16. package/dist/connected.d.ts +29 -0
  17. package/dist/connected.d.ts.map +1 -0
  18. package/dist/connected.js +51 -0
  19. package/dist/connected.js.map +1 -0
  20. package/dist/index.d.ts +9 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +9 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/linked.d.ts +28 -0
  25. package/dist/linked.d.ts.map +1 -0
  26. package/dist/linked.js +50 -0
  27. package/dist/linked.js.map +1 -0
  28. package/dist/messages.d.ts +455 -0
  29. package/dist/messages.d.ts.map +1 -0
  30. package/dist/messages.js +279 -0
  31. package/dist/messages.js.map +1 -0
  32. package/dist/navigation.d.ts +24 -0
  33. package/dist/navigation.d.ts.map +1 -0
  34. package/dist/navigation.js +80 -0
  35. package/dist/navigation.js.map +1 -0
  36. package/dist/peers.d.ts +14 -0
  37. package/dist/peers.d.ts.map +1 -0
  38. package/dist/peers.js +59 -0
  39. package/dist/peers.js.map +1 -0
  40. package/dist/session.d.ts +26 -0
  41. package/dist/session.d.ts.map +1 -0
  42. package/dist/session.js +88 -0
  43. package/dist/session.js.map +1 -0
  44. package/dist/urls.d.ts +17 -0
  45. package/dist/urls.d.ts.map +1 -0
  46. package/dist/urls.js +46 -0
  47. package/dist/urls.js.map +1 -0
  48. package/package.json +61 -4
  49. package/src/api.ts +139 -0
  50. package/src/authorize.ts +141 -0
  51. package/src/client.test.ts +575 -0
  52. package/src/connected.ts +54 -0
  53. package/src/index.ts +8 -0
  54. package/src/linked.ts +56 -0
  55. package/src/messages.ts +365 -0
  56. package/src/navigation.test.ts +99 -0
  57. package/src/navigation.ts +94 -0
  58. package/src/peers.test.ts +85 -0
  59. package/src/peers.ts +77 -0
  60. package/src/session.ts +88 -0
  61. package/src/urls.ts +58 -0
@@ -0,0 +1,575 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { compareCatalogKeys } from '@baukit/localization-core';
3
+ import { type OAuthInFlightSession, type OAuthSessionResult } from '@baukit/integrations-client';
4
+ import {
5
+ SuiteClient,
6
+ SuiteFlowError,
7
+ SuiteSession,
8
+ SuiteAuthorizeMachine,
9
+ SuiteLinkedMachine,
10
+ ConnectedApps,
11
+ suiteReturnValidator,
12
+ createSuiteNativeIntentValidator,
13
+ openSuitePeer,
14
+ suiteConnectionState,
15
+ parseSuiteAuthorizeQuery,
16
+ switchSuiteAccount,
17
+ createSuiteNavigationStore,
18
+ suiteMessages,
19
+ type SuiteLink,
20
+ type SuiteTransport,
21
+ type AuthorizationPreview,
22
+ } from './index.js';
23
+
24
+ const link: SuiteLink = {
25
+ id: 'link',
26
+ peerApp: 'beta',
27
+ role: 'initiator',
28
+ remoteLinkId: 'remote',
29
+ remoteDisplayName: 'User',
30
+ status: 'active',
31
+ sends: ['alpha.activity.completed'],
32
+ receives: ['beta.activity.completed'],
33
+ shareXp: true,
34
+ rewardMode: 'native',
35
+ deliveryHealth: 'healthy',
36
+ consecutiveFailures: 0,
37
+ lastDeliveryAt: null,
38
+ lastFailureAt: null,
39
+ lastFailureCode: null,
40
+ lastReceivedAt: null,
41
+ replayEarliest: '2025-10-07',
42
+ createdAt: '2026-10-07T00:00:00Z',
43
+ updatedAt: '2026-10-07T00:00:00Z',
44
+ };
45
+ const preview: AuthorizationPreview = {
46
+ peer: 'Beta',
47
+ authorizerSends: ['beta.activity.completed'],
48
+ initiatorSends: ['alpha.activity.completed'],
49
+ existingLink: false,
50
+ autoApprove: false,
51
+ hintMismatch: false,
52
+ };
53
+ const input = {
54
+ client: 'alpha',
55
+ state: 'state',
56
+ codeChallenge: 'challenge',
57
+ hint: 'hint',
58
+ hintDomain: 'shared',
59
+ };
60
+ function apiFixture() {
61
+ const request = vi.fn<(method: string, path: string, body?: unknown) => Promise<unknown>>(
62
+ (_method, path) => {
63
+ if (path.includes('/preview?')) return Promise.resolve(preview);
64
+ if (path === '/suite/links' && _method === 'POST')
65
+ return Promise.resolve({
66
+ requestId: 'request',
67
+ authorizeUrl: 'https://beta.example/suite/authorize',
68
+ });
69
+ if (path === '/suite/peers' || (path === '/suite/links' && _method === 'GET'))
70
+ return Promise.resolve([]);
71
+ if (path.endsWith('/complete')) return Promise.resolve(link);
72
+ return Promise.resolve({ redirectUrl: 'https://alpha.example/suite/links/callback' });
73
+ },
74
+ );
75
+ const transport: SuiteTransport = {
76
+ async request<T>(
77
+ method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
78
+ path: string,
79
+ body?: unknown,
80
+ ): Promise<T> {
81
+ return (await request(method, path, body)) as T;
82
+ },
83
+ };
84
+ return { client: new SuiteClient(transport), request };
85
+ }
86
+ function sessionFixture(platform: 'web' | 'native' = 'native') {
87
+ const api = apiFixture();
88
+ let stored: OAuthInFlightSession | null = null;
89
+ const storage = {
90
+ load: () => Promise.resolve(stored),
91
+ save: (value: OAuthInFlightSession) => {
92
+ stored = value;
93
+ return Promise.resolve();
94
+ },
95
+ clear: () => {
96
+ stored = null;
97
+ return Promise.resolve();
98
+ },
99
+ };
100
+ const callback =
101
+ platform === 'web'
102
+ ? 'https://alpha.example/suite/linked?state=nonce&request=request&code=code'
103
+ : 'alpha://suite/linked?state=nonce&request=request&code=code';
104
+ const run = vi.fn<() => Promise<OAuthSessionResult>>(() =>
105
+ Promise.resolve({ type: 'success', returnUrl: callback }),
106
+ );
107
+ const cancel = vi.fn();
108
+ const timers = new Map<number, () => void>();
109
+ let next = 0;
110
+ const session = new SuiteSession({
111
+ client: api.client,
112
+ platform,
113
+ origin: platform === 'web' ? 'https://alpha.example' : 'alpha://suite',
114
+ coordinator: {
115
+ storage,
116
+ createStateNonce: () => 'nonce',
117
+ clock: {
118
+ now: () => 100,
119
+ setTimeout: (callback) => {
120
+ timers.set(++next, callback);
121
+ return next;
122
+ },
123
+ clearTimeout: (handle) => {
124
+ if (typeof handle === 'number') timers.delete(handle);
125
+ },
126
+ },
127
+ native: { run, cancel },
128
+ redirect: { authorize: run },
129
+ },
130
+ });
131
+ return { ...api, session, storage, callback, run, cancel, timers };
132
+ }
133
+
134
+ describe('suite API', () => {
135
+ it('uses all authenticated route shapes and encodes path and query values', async () => {
136
+ const { client, request } = apiFixture();
137
+ await client.peers();
138
+ await client.list();
139
+ await client.get('a/b');
140
+ await client.preview('a&b', 'x+y', 'd e');
141
+ await client.authorize(input);
142
+ await client.deny({ client: 'alpha', state: 'state' });
143
+ await client.update('a/b', { shareXp: false, rewardMode: 'off' });
144
+ await client.disconnect('a/b');
145
+ await client.test('a/b');
146
+ await client.reenable('a/b');
147
+ await client.replay('a/b', '2026-01-01');
148
+ await client.deliveries('a/b');
149
+ expect(request.mock.calls).toEqual([
150
+ ['GET', '/suite/peers', undefined],
151
+ ['GET', '/suite/links', undefined],
152
+ ['GET', '/suite/links/a%2Fb', undefined],
153
+ ['GET', '/suite/authorizations/preview?client=a%26b&hint=x%2By&hint_domain=d+e', undefined],
154
+ ['POST', '/suite/authorizations', input],
155
+ ['POST', '/suite/authorizations/deny', { client: 'alpha', state: 'state' }],
156
+ ['PATCH', '/suite/links/a%2Fb', { shareXp: false, rewardMode: 'off' }],
157
+ ['DELETE', '/suite/links/a%2Fb', undefined],
158
+ ['POST', '/suite/links/a%2Fb/test', undefined],
159
+ ['POST', '/suite/links/a%2Fb/reenable', undefined],
160
+ ['POST', '/suite/links/a%2Fb/replay', { since: '2026-01-01' }],
161
+ ['GET', '/suite/links/a%2Fb/deliveries', undefined],
162
+ ]);
163
+ });
164
+ });
165
+ describe('return URLs and peer links', () => {
166
+ it('validates exact web and native endpoints', () => {
167
+ const web = suiteReturnValidator({ platform: 'web', origin: 'https://alpha.example' });
168
+ const native = suiteReturnValidator({ platform: 'native', origin: 'alpha://suite' });
169
+ expect(web('https://alpha.example/suite/linked?code=x')).toBe(true);
170
+ expect(native('alpha://suite/linked?state=x')).toBe(true);
171
+ for (const url of [
172
+ 'https://evil.example/suite/linked',
173
+ 'https://alpha.example.evil/suite/linked',
174
+ 'https://user@alpha.example/suite/linked',
175
+ 'https://alpha.example/suite/linked/extra',
176
+ 'http://alpha.example/suite/linked',
177
+ ])
178
+ expect(web(url)).toBe(false);
179
+ for (const url of [
180
+ 'alpha://auth/callback',
181
+ 'alpha://suite/linked/extra',
182
+ 'alpha:///suite/linked',
183
+ 'beta://suite/linked',
184
+ 'alpha://suite.evil/linked',
185
+ ])
186
+ expect(native(url)).toBe(false);
187
+ });
188
+ it('allows only suite native pages and retains their queries', () => {
189
+ const validate = createSuiteNativeIntentValidator('alpha-app');
190
+ for (const url of [
191
+ 'alpha-app://suite/linked?code=x',
192
+ 'alpha-app:///suite/authorize?client=x',
193
+ '/suite/linked',
194
+ ])
195
+ expect(validate(url)).toBe(true);
196
+ for (const url of [
197
+ 'beta://suite/linked',
198
+ '/suite/linked/extra',
199
+ 'alpha-app://suite/%6cinked',
200
+ '/auth/callback',
201
+ ])
202
+ expect(validate(url)).toBe(false);
203
+ expect(() => createSuiteNativeIntentValidator('javascript:')).toThrow(TypeError);
204
+ });
205
+ it('opens the configured web origin on web', async () => {
206
+ const openUrl = vi.fn(() => Promise.resolve());
207
+ await openSuitePeer(
208
+ { scheme: 'beta', webUrl: 'https://beta.example' },
209
+ { platform: 'web', openUrl },
210
+ );
211
+ expect(openUrl.mock.calls).toEqual([['https://beta.example']]);
212
+ });
213
+ it('opens the native app and falls back to web only on failure', async () => {
214
+ const openUrl = vi
215
+ .fn<(url: string) => Promise<void>>()
216
+ .mockRejectedValueOnce(new Error('absent'))
217
+ .mockResolvedValueOnce(undefined);
218
+ await openSuitePeer(
219
+ { scheme: 'beta.app+native', webUrl: 'https://beta.example' },
220
+ { platform: 'native', openUrl },
221
+ );
222
+ expect(openUrl.mock.calls).toEqual([['beta.app+native://'], ['https://beta.example']]);
223
+ openUrl.mockReset().mockResolvedValue(undefined);
224
+ await openSuitePeer(
225
+ { scheme: 'beta', webUrl: 'https://beta.example' },
226
+ { platform: 'native', openUrl },
227
+ );
228
+ expect(openUrl).toHaveBeenCalledTimes(1);
229
+ });
230
+ it('propagates failure when neither native nor web can open', async () => {
231
+ const openUrl = vi.fn(() => Promise.reject(new Error('unavailable')));
232
+ await expect(
233
+ openSuitePeer(
234
+ { scheme: 'beta', webUrl: 'https://beta.example' },
235
+ { platform: 'native', openUrl },
236
+ ),
237
+ ).rejects.toThrow('unavailable');
238
+ expect(openUrl).toHaveBeenCalledTimes(2);
239
+ });
240
+ it('requires explicit loopback HTTP and rejects unsafe URLs on web too', async () => {
241
+ const openUrl = vi.fn(() => Promise.resolve());
242
+ for (const webUrl of [
243
+ 'javascript:alert(1)',
244
+ 'http://beta.example',
245
+ 'https://user:pass@beta.example',
246
+ ])
247
+ await expect(
248
+ openSuitePeer({ scheme: 'beta', webUrl }, { platform: 'web', openUrl }),
249
+ ).rejects.toThrow(TypeError);
250
+ expect(openUrl).not.toHaveBeenCalled();
251
+ await openSuitePeer(
252
+ { scheme: 'beta', webUrl: 'http://localhost:1234' },
253
+ { platform: 'web', openUrl, allowLoopback: true },
254
+ );
255
+ expect(openUrl).toHaveBeenCalledWith('http://localhost:1234');
256
+ });
257
+ });
258
+ describe('OAuth session glue', () => {
259
+ it('opens a shared native session and redeems the validated code once', async () => {
260
+ const f = sessionFixture();
261
+ const result = f.session.connect('beta');
262
+ expect(f.session.handleRedirect(f.callback)).toBe(result);
263
+ expect(await result).toEqual({ type: 'connected', requestId: 'request', link });
264
+ expect(await f.session.handleRedirect(f.callback)).toEqual(await result);
265
+ expect(f.request.mock.calls).toEqual([
266
+ [
267
+ 'POST',
268
+ '/suite/links',
269
+ { peerApp: 'beta', returnUrl: 'alpha://suite/linked', stateNonce: 'nonce' },
270
+ ],
271
+ ['POST', '/suite/links/requests/request/complete', { code: 'code' }],
272
+ ]);
273
+ expect(f.run).toHaveBeenCalledTimes(1);
274
+ });
275
+ it('treats dismiss as cancellation', async () => {
276
+ const f = sessionFixture();
277
+ f.run.mockResolvedValue({ type: 'cancelled' });
278
+ expect(await f.session.connect('beta')).toEqual({ type: 'cancelled' });
279
+ expect(await f.storage.load()).toBeNull();
280
+ expect(f.request).toHaveBeenCalledTimes(1);
281
+ });
282
+ it.each(['native', 'web'] as const)(
283
+ 'resumes a %s callback after a cold launch',
284
+ async (platform) => {
285
+ const f = sessionFixture(platform);
286
+ await f.storage.save({
287
+ stateNonce: 'nonce',
288
+ returnUrl: f.callback.split('?')[0] ?? '',
289
+ createdAt: 100,
290
+ });
291
+ expect(await f.session.handleRedirect(f.callback)).toEqual({
292
+ type: 'connected',
293
+ requestId: 'request',
294
+ link,
295
+ });
296
+ expect(f.run).not.toHaveBeenCalled();
297
+ },
298
+ );
299
+ it('uses the current web tab adapter and persists state before navigation', async () => {
300
+ const f = sessionFixture('web');
301
+ f.run.mockImplementation(async () => {
302
+ expect((await f.storage.load())?.stateNonce).toBe('nonce');
303
+ return { type: 'success', returnUrl: f.callback };
304
+ });
305
+ expect((await f.session.connect('beta')).type).toBe('connected');
306
+ expect(f.run).toHaveBeenCalledTimes(1);
307
+ });
308
+ it.each([
309
+ 'status=denied',
310
+ 'status=failed&code=suite_peer_unreachable',
311
+ 'status=other',
312
+ 'request=request',
313
+ 'request=request&code=code&state=duplicate',
314
+ ])('handles %s without redeeming an untrusted code', async (query) => {
315
+ const f = sessionFixture();
316
+ f.run.mockResolvedValue({
317
+ type: 'success',
318
+ returnUrl: `alpha://suite/linked?state=nonce&${query}`,
319
+ });
320
+ if (query === 'status=denied')
321
+ expect(await f.session.connect('beta')).toEqual({ type: 'denied' });
322
+ else await expect(f.session.connect('beta')).rejects.toBeInstanceOf(SuiteFlowError);
323
+ expect(f.request).toHaveBeenCalledTimes(1);
324
+ });
325
+ it('rejects a return with the wrong nonce or origin', async () => {
326
+ for (const returnUrl of [
327
+ 'alpha://suite/linked?state=wrong&request=r&code=c',
328
+ 'beta://suite/linked?state=nonce&request=r&code=c',
329
+ ]) {
330
+ const f = sessionFixture();
331
+ f.run.mockResolvedValue({ type: 'success', returnUrl });
332
+ await expect(f.session.connect('beta')).rejects.toMatchObject({ code: 'suite_code_invalid' });
333
+ expect(f.request).toHaveBeenCalledTimes(1);
334
+ }
335
+ });
336
+ });
337
+ describe('authorize state', () => {
338
+ it('previews both directions with the identity domain then posts consent', async () => {
339
+ const f = apiFixture();
340
+ const machine = new SuiteAuthorizeMachine(f.client, input, {
341
+ web: true,
342
+ framed: false,
343
+ signedIn: true,
344
+ });
345
+ expect(await machine.load()).toEqual({ type: 'consent', preview });
346
+ expect(await machine.approve()).toEqual({
347
+ type: 'redirect',
348
+ url: 'https://alpha.example/suite/links/callback',
349
+ });
350
+ expect(f.request.mock.calls[0]).toEqual([
351
+ 'GET',
352
+ '/suite/authorizations/preview?client=alpha&hint=hint&hint_domain=shared',
353
+ undefined,
354
+ ]);
355
+ expect(f.request.mock.calls[1]).toEqual([
356
+ 'POST',
357
+ '/suite/authorizations',
358
+ { client: 'alpha', state: 'state', codeChallenge: 'challenge', hint: 'hint' },
359
+ ]);
360
+ });
361
+ it('auto-approves once', async () => {
362
+ const f = apiFixture();
363
+ f.request.mockResolvedValueOnce({ ...preview, autoApprove: true });
364
+ const machine = new SuiteAuthorizeMachine(f.client, input, {
365
+ web: true,
366
+ framed: false,
367
+ signedIn: true,
368
+ });
369
+ expect((await machine.load()).type).toBe('redirect');
370
+ await machine.load();
371
+ await machine.approve();
372
+ expect(f.request).toHaveBeenCalledTimes(2);
373
+ });
374
+ it('denies consent and follows the API redirect', async () => {
375
+ const f = apiFixture();
376
+ const machine = new SuiteAuthorizeMachine(f.client, input, {
377
+ web: true,
378
+ framed: false,
379
+ signedIn: true,
380
+ });
381
+ await machine.load();
382
+ expect((await machine.deny()).type).toBe('redirect');
383
+ expect(f.request.mock.calls[1]).toEqual([
384
+ 'POST',
385
+ '/suite/authorizations/deny',
386
+ { client: 'alpha', state: 'state' },
387
+ ]);
388
+ });
389
+ it('blocks consent and auto-approve on a hint mismatch', async () => {
390
+ const f = apiFixture();
391
+ f.request.mockResolvedValueOnce({ ...preview, autoApprove: true, hintMismatch: true });
392
+ const machine = new SuiteAuthorizeMachine(f.client, input, {
393
+ web: true,
394
+ framed: false,
395
+ signedIn: true,
396
+ });
397
+ expect((await machine.load()).type).toBe('hint_mismatch');
398
+ await machine.approve();
399
+ expect(f.request).toHaveBeenCalledTimes(1);
400
+ expect((await machine.deny()).type).toBe('redirect');
401
+ });
402
+ it('waits for logout before starting account-switch login and retains the query', async () => {
403
+ const order: string[] = [];
404
+ const logout = vi.fn((path: string) => {
405
+ order.push('logout');
406
+ expect(new URL(path, 'https://alpha.example').searchParams.get('hint_domain')).toBe('shared');
407
+ return Promise.resolve();
408
+ });
409
+ const login = vi.fn(() => {
410
+ expect(order).toEqual(['logout']);
411
+ order.push('login');
412
+ return Promise.resolve();
413
+ });
414
+ await switchSuiteAccount(input, { logout, login });
415
+ expect(order).toEqual(['logout', 'login']);
416
+ });
417
+ it.each([
418
+ { web: true, framed: true, signedIn: true, type: 'framed' },
419
+ { web: false, framed: false, signedIn: true, type: 'web_required' },
420
+ { web: true, framed: false, signedIn: false, type: 'login' },
421
+ ])('refuses authorization in $type state', async ({ type, ...environment }) => {
422
+ const f = apiFixture();
423
+ const machine = new SuiteAuthorizeMachine(f.client, input, environment);
424
+ expect((await machine.load()).type).toBe(type);
425
+ await machine.approve();
426
+ await machine.deny();
427
+ expect(f.request).not.toHaveBeenCalled();
428
+ });
429
+ it('rejects invalid and duplicate query values', () => {
430
+ for (const query of [
431
+ '',
432
+ 'client=a&state=s',
433
+ 'client=a&state=s&code_challenge=c&hint=a&hint=b',
434
+ 'client=a&client=b&state=s&code_challenge=c',
435
+ ])
436
+ expect(parseSuiteAuthorizeQuery(new URLSearchParams(query))).toBeNull();
437
+ expect(
438
+ parseSuiteAuthorizeQuery(
439
+ new URLSearchParams(
440
+ 'client=alpha&state=state&code_challenge=challenge&hint=hint&hint_domain=shared',
441
+ ),
442
+ ),
443
+ ).toEqual(input);
444
+ });
445
+ it('keeps consent available after coded authorization failure', async () => {
446
+ const f = apiFixture();
447
+ const machine = new SuiteAuthorizeMachine(f.client, input, {
448
+ web: true,
449
+ framed: false,
450
+ signedIn: true,
451
+ });
452
+ await machine.load();
453
+ f.request.mockRejectedValueOnce(new SuiteFlowError('suite_link_account_mismatch'));
454
+ expect(await machine.approve()).toEqual({
455
+ type: 'failed',
456
+ code: 'suite_link_account_mismatch',
457
+ });
458
+ expect((await machine.approve()).type).toBe('redirect');
459
+ });
460
+ });
461
+ describe('connected apps and linked page', () => {
462
+ it('waits for restoration, scrubs history, completes and refetches before navigating', async () => {
463
+ const f = sessionFixture('web');
464
+ await f.storage.save({
465
+ stateNonce: 'nonce',
466
+ returnUrl: 'https://alpha.example/suite/linked',
467
+ createdAt: 100,
468
+ });
469
+ const refresh = vi.fn(() => Promise.resolve());
470
+ const scrubHistory = vi.fn();
471
+ const machine = new SuiteLinkedMachine({
472
+ originalUrl: f.callback,
473
+ session: f.session,
474
+ navigation: createSuiteNavigationStore(() => 'notice'),
475
+ refresh,
476
+ scrubHistory,
477
+ });
478
+ expect(scrubHistory).toHaveBeenCalledWith('/suite/linked');
479
+ expect(await machine.restore(true, true)).toEqual({ type: 'restoring' });
480
+ expect(f.request).not.toHaveBeenCalled();
481
+ expect(await machine.restore(false, true)).toEqual({
482
+ type: 'connected_apps',
483
+ noticeToken: 'notice',
484
+ });
485
+ await machine.restore(false, true);
486
+ expect(f.request).toHaveBeenCalledTimes(1);
487
+ expect(refresh).toHaveBeenCalledTimes(1);
488
+ });
489
+ it('requires login before redeeming a return and retains its query', async () => {
490
+ const f = sessionFixture('web');
491
+ const machine = new SuiteLinkedMachine({
492
+ originalUrl: f.callback,
493
+ session: f.session,
494
+ navigation: createSuiteNavigationStore(() => 'notice'),
495
+ refresh: () => Promise.resolve(),
496
+ scrubHistory: () => undefined,
497
+ });
498
+ expect(await machine.restore(false, false)).toEqual({
499
+ type: 'login',
500
+ returnPath: '/suite/linked?state=nonce&request=request&code=code',
501
+ });
502
+ expect(f.request).not.toHaveBeenCalled();
503
+ });
504
+ it('returns coded failure through a one-shot notice', async () => {
505
+ const f = sessionFixture();
506
+ const navigation = createSuiteNavigationStore(() => 'notice');
507
+ const machine = new SuiteLinkedMachine({
508
+ originalUrl: f.callback,
509
+ session: f.session,
510
+ navigation,
511
+ refresh: () => Promise.resolve(),
512
+ scrubHistory: () => undefined,
513
+ });
514
+ expect(await machine.restore(false, true)).toEqual({
515
+ type: 'connected_apps',
516
+ noticeToken: 'notice',
517
+ });
518
+ expect(navigation.consumeSuiteNotice('notice')?.notice.errorCode).toBe('suite_code_invalid');
519
+ });
520
+ it('loads peers and links and handles denied, failed and reconnect flows', async () => {
521
+ const f = sessionFixture();
522
+ const connected = new ConnectedApps(f.client, f.session);
523
+ expect(await connected.load()).toEqual({ type: 'ready', peers: [], links: [] });
524
+ f.run.mockResolvedValueOnce({
525
+ type: 'success',
526
+ returnUrl: 'alpha://suite/linked?state=nonce&status=denied',
527
+ });
528
+ expect(await connected.connect('beta')).toEqual({ type: 'denied' });
529
+ f.run.mockResolvedValueOnce({
530
+ type: 'success',
531
+ returnUrl: 'alpha://suite/linked?state=nonce&status=failed&code=suite_peer_unreachable',
532
+ });
533
+ expect(await connected.connect('beta')).toEqual({
534
+ type: 'failed',
535
+ code: 'suite_peer_unreachable',
536
+ });
537
+ expect((await connected.connect('beta')).type).toBe('ready');
538
+ expect(suiteConnectionState(undefined)).toBe('not_connected');
539
+ expect(suiteConnectionState(link)).toBe('connected');
540
+ expect(
541
+ suiteConnectionState({ ...link, status: 'needs_attention', deliveryHealth: 'healthy' }),
542
+ ).toBe('needs_attention');
543
+ expect(suiteConnectionState({ ...link, deliveryHealth: 'needs_attention' })).toBe(
544
+ 'needs_attention',
545
+ );
546
+ expect(suiteConnectionState({ ...link, deliveryHealth: 'disabled' })).toBe('disabled');
547
+ expect(suiteConnectionState({ ...link, status: 'revoked' })).toBe('not_connected');
548
+ });
549
+ it('preserves API transport error codes and maps uncoded errors to unavailable', async () => {
550
+ const f = sessionFixture();
551
+ const connected = new ConnectedApps(f.client, f.session);
552
+ f.request.mockRejectedValueOnce(
553
+ Object.assign(new Error('Account mismatch'), { code: 'suite_link_account_mismatch' }),
554
+ );
555
+ expect(await connected.load()).toEqual({
556
+ type: 'failed',
557
+ code: 'suite_link_account_mismatch',
558
+ });
559
+ f.request.mockRejectedValueOnce(new Error('Network failure'));
560
+ expect(await connected.load()).toEqual({ type: 'failed', code: 'suite_unavailable' });
561
+ });
562
+ });
563
+ it('keeps all locales and interpolation parameters in parity', () => {
564
+ for (const locale of ['de', 'es'] as const) {
565
+ expect(compareCatalogKeys(suiteMessages.en, suiteMessages[locale])).toEqual({
566
+ missing: [],
567
+ extra: [],
568
+ });
569
+ for (const key of Object.keys(suiteMessages.en) as (keyof typeof suiteMessages.en)[]) {
570
+ const placeholders = (text: string) =>
571
+ [...text.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]).sort();
572
+ expect(placeholders(suiteMessages[locale][key])).toEqual(placeholders(suiteMessages.en[key]));
573
+ }
574
+ }
575
+ });
@@ -0,0 +1,54 @@
1
+ import { SuiteClient, suiteErrorCode, type SuiteLink, type SuitePeer } from './api.js';
2
+ import { SuiteSession } from './session.js';
3
+ export type ConnectedAppsState =
4
+ | { readonly type: 'loading' }
5
+ | {
6
+ readonly type: 'ready';
7
+ readonly peers: readonly SuitePeer[];
8
+ readonly links: readonly SuiteLink[];
9
+ }
10
+ | { readonly type: 'connecting'; readonly peerApp: string }
11
+ | { readonly type: 'denied' | 'cancelled' }
12
+ | { readonly type: 'failed'; readonly code: string };
13
+ export function suiteConnectionState(
14
+ link: SuiteLink | undefined,
15
+ ): 'not_connected' | 'connected' | 'needs_attention' | 'disabled' {
16
+ if (link === undefined || link.status === 'revoked') return 'not_connected';
17
+ if (link.status === 'needs_attention') return 'needs_attention';
18
+ if (link.deliveryHealth === 'needs_attention' || link.deliveryHealth === 'disabled')
19
+ return link.deliveryHealth;
20
+ return 'connected';
21
+ }
22
+ export class ConnectedApps {
23
+ #state: ConnectedAppsState = { type: 'loading' };
24
+ public constructor(
25
+ private readonly client: SuiteClient,
26
+ private readonly session: SuiteSession,
27
+ ) {}
28
+ public get state(): ConnectedAppsState {
29
+ return this.#state;
30
+ }
31
+ public async load(): Promise<ConnectedAppsState> {
32
+ this.#state = { type: 'loading' };
33
+ try {
34
+ const [peers, links] = await Promise.all([this.client.peers(), this.client.list()]);
35
+ this.#state = { type: 'ready', peers, links };
36
+ } catch (error) {
37
+ this.#state = { type: 'failed', code: suiteErrorCode(error) };
38
+ }
39
+ return this.#state;
40
+ }
41
+ /** Connecting an already linked peer uses the same flow and replaces both links. */
42
+ public async connect(peerApp: string): Promise<ConnectedAppsState> {
43
+ if (this.#state.type === 'connecting') return this.#state;
44
+ this.#state = { type: 'connecting', peerApp };
45
+ try {
46
+ const result = await this.session.connect(peerApp);
47
+ if (result.type === 'connected') return await this.load();
48
+ this.#state = { type: result.type };
49
+ } catch (error) {
50
+ this.#state = { type: 'failed', code: suiteErrorCode(error) };
51
+ }
52
+ return this.#state;
53
+ }
54
+ }
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ export * from './api.js';
2
+ export * from './urls.js';
3
+ export * from './session.js';
4
+ export * from './authorize.js';
5
+ export * from './connected.js';
6
+ export * from './messages.js';
7
+ export * from './navigation.js';
8
+ export * from './linked.js';
package/src/linked.ts ADDED
@@ -0,0 +1,56 @@
1
+ import { suiteErrorCode } from './api.js';
2
+ import { SuiteSession } from './session.js';
3
+ import { type SuiteNavigationStore } from './navigation.js';
4
+ export type LinkedState =
5
+ | { readonly type: 'restoring' | 'completing' }
6
+ | { readonly type: 'login'; readonly returnPath: string }
7
+ | { readonly type: 'connected_apps'; readonly noticeToken?: string };
8
+ export interface SuiteLinkedOptions {
9
+ readonly originalUrl: string;
10
+ readonly session: SuiteSession;
11
+ readonly navigation: SuiteNavigationStore;
12
+ readonly scrubHistory: (path: string) => void;
13
+ readonly refresh: () => Promise<void>;
14
+ }
15
+ /** Retains the callback in memory while removing codes from browser history. */
16
+ export class SuiteLinkedMachine {
17
+ #state: LinkedState = { type: 'restoring' };
18
+ #operation: Promise<LinkedState> | undefined;
19
+ public constructor(private readonly options: SuiteLinkedOptions) {
20
+ options.scrubHistory('/suite/linked');
21
+ }
22
+ public get state(): LinkedState {
23
+ return this.#state;
24
+ }
25
+ public async restore(restoring: boolean, signedIn: boolean): Promise<LinkedState> {
26
+ if (restoring) return this.#state;
27
+ if (!signedIn) {
28
+ this.#state = {
29
+ type: 'login',
30
+ returnPath: `/suite/linked${new URL(this.options.originalUrl).search}`,
31
+ };
32
+ return this.#state;
33
+ }
34
+ this.#operation ??= this.complete();
35
+ return this.#operation;
36
+ }
37
+ private async complete(): Promise<LinkedState> {
38
+ this.#state = { type: 'completing' };
39
+ try {
40
+ const result = await this.options.session.handleRedirect(this.options.originalUrl);
41
+ await this.options.refresh();
42
+ this.#state = {
43
+ type: 'connected_apps',
44
+ ...(result.type === 'connected'
45
+ ? { noticeToken: this.options.navigation.createSuiteConnectionNotice(result.requestId) }
46
+ : {}),
47
+ };
48
+ } catch (error) {
49
+ this.#state = {
50
+ type: 'connected_apps',
51
+ noticeToken: this.options.navigation.createSuiteErrorNotice(suiteErrorCode(error)),
52
+ };
53
+ }
54
+ return this.#state;
55
+ }
56
+ }