@oxyhq/core 12.10.6 → 12.11.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 (126) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/boot/sessionColdBoot.js +142 -37
  3. package/dist/cjs/i18n/locales/ar-SA.json +13 -1
  4. package/dist/cjs/i18n/locales/ca-ES.json +13 -1
  5. package/dist/cjs/i18n/locales/de-DE.json +13 -1
  6. package/dist/cjs/i18n/locales/en-US.json +13 -4
  7. package/dist/cjs/i18n/locales/es-ES.json +13 -4
  8. package/dist/cjs/i18n/locales/fr-FR.json +13 -1
  9. package/dist/cjs/i18n/locales/it-IT.json +13 -1
  10. package/dist/cjs/i18n/locales/ja-JP.json +13 -1
  11. package/dist/cjs/i18n/locales/ko-KR.json +13 -1
  12. package/dist/cjs/i18n/locales/locales/ar-SA.json +13 -1
  13. package/dist/cjs/i18n/locales/locales/ca-ES.json +13 -1
  14. package/dist/cjs/i18n/locales/locales/de-DE.json +13 -1
  15. package/dist/cjs/i18n/locales/locales/en-US.json +13 -4
  16. package/dist/cjs/i18n/locales/locales/es-ES.json +13 -4
  17. package/dist/cjs/i18n/locales/locales/fr-FR.json +13 -1
  18. package/dist/cjs/i18n/locales/locales/it-IT.json +13 -1
  19. package/dist/cjs/i18n/locales/locales/ja-JP.json +13 -1
  20. package/dist/cjs/i18n/locales/locales/ko-KR.json +13 -1
  21. package/dist/cjs/i18n/locales/locales/pt-PT.json +13 -1
  22. package/dist/cjs/i18n/locales/locales/zh-CN.json +13 -1
  23. package/dist/cjs/i18n/locales/pt-PT.json +13 -1
  24. package/dist/cjs/i18n/locales/zh-CN.json +13 -1
  25. package/dist/cjs/index.js +31 -5
  26. package/dist/cjs/mixins/OxyServices.auth.js +257 -17
  27. package/dist/cjs/mixins/OxyServices.deviceBoot.js +54 -3
  28. package/dist/cjs/mixins/OxyServices.notifications.js +63 -0
  29. package/dist/cjs/mixins/index.js +5 -0
  30. package/dist/cjs/session/SessionClient.js +40 -4
  31. package/dist/cjs/session/accountDialogController.js +288 -41
  32. package/dist/cjs/session/identityPin.js +256 -0
  33. package/dist/cjs/session/identitySession.js +135 -0
  34. package/dist/cjs/session/projectSessionState.js +54 -15
  35. package/dist/cjs/session/refresh.js +73 -8
  36. package/dist/cjs/utils/commonsDelivery.js +59 -0
  37. package/dist/cjs/utils/oauthPkce.js +33 -3
  38. package/dist/esm/.tsbuildinfo +1 -1
  39. package/dist/esm/boot/sessionColdBoot.js +142 -37
  40. package/dist/esm/i18n/locales/ar-SA.json +13 -1
  41. package/dist/esm/i18n/locales/ca-ES.json +13 -1
  42. package/dist/esm/i18n/locales/de-DE.json +13 -1
  43. package/dist/esm/i18n/locales/en-US.json +13 -4
  44. package/dist/esm/i18n/locales/es-ES.json +13 -4
  45. package/dist/esm/i18n/locales/fr-FR.json +13 -1
  46. package/dist/esm/i18n/locales/it-IT.json +13 -1
  47. package/dist/esm/i18n/locales/ja-JP.json +13 -1
  48. package/dist/esm/i18n/locales/ko-KR.json +13 -1
  49. package/dist/esm/i18n/locales/locales/ar-SA.json +13 -1
  50. package/dist/esm/i18n/locales/locales/ca-ES.json +13 -1
  51. package/dist/esm/i18n/locales/locales/de-DE.json +13 -1
  52. package/dist/esm/i18n/locales/locales/en-US.json +13 -4
  53. package/dist/esm/i18n/locales/locales/es-ES.json +13 -4
  54. package/dist/esm/i18n/locales/locales/fr-FR.json +13 -1
  55. package/dist/esm/i18n/locales/locales/it-IT.json +13 -1
  56. package/dist/esm/i18n/locales/locales/ja-JP.json +13 -1
  57. package/dist/esm/i18n/locales/locales/ko-KR.json +13 -1
  58. package/dist/esm/i18n/locales/locales/pt-PT.json +13 -1
  59. package/dist/esm/i18n/locales/locales/zh-CN.json +13 -1
  60. package/dist/esm/i18n/locales/pt-PT.json +13 -1
  61. package/dist/esm/i18n/locales/zh-CN.json +13 -1
  62. package/dist/esm/index.js +14 -1
  63. package/dist/esm/mixins/OxyServices.auth.js +257 -17
  64. package/dist/esm/mixins/OxyServices.deviceBoot.js +52 -3
  65. package/dist/esm/mixins/OxyServices.notifications.js +60 -0
  66. package/dist/esm/mixins/index.js +5 -0
  67. package/dist/esm/session/SessionClient.js +40 -4
  68. package/dist/esm/session/accountDialogController.js +288 -41
  69. package/dist/esm/session/identityPin.js +249 -0
  70. package/dist/esm/session/identitySession.js +131 -0
  71. package/dist/esm/session/projectSessionState.js +54 -15
  72. package/dist/esm/session/refresh.js +73 -8
  73. package/dist/esm/utils/commonsDelivery.js +54 -0
  74. package/dist/esm/utils/oauthPkce.js +31 -2
  75. package/dist/types/.tsbuildinfo +1 -1
  76. package/dist/types/boot/sessionColdBoot.d.ts +38 -1
  77. package/dist/types/index.d.ts +12 -4
  78. package/dist/types/mixins/OxyServices.auth.d.ts +262 -11
  79. package/dist/types/mixins/OxyServices.deviceBoot.d.ts +31 -1
  80. package/dist/types/mixins/OxyServices.notifications.d.ts +143 -0
  81. package/dist/types/mixins/index.d.ts +2 -1
  82. package/dist/types/session/SessionClient.d.ts +28 -0
  83. package/dist/types/session/accountDialogController.d.ts +187 -9
  84. package/dist/types/session/identityPin.d.ts +87 -0
  85. package/dist/types/session/identitySession.d.ts +105 -0
  86. package/dist/types/session/projectSessionState.d.ts +21 -19
  87. package/dist/types/session/refresh.d.ts +32 -1
  88. package/dist/types/utils/commonsDelivery.d.ts +105 -0
  89. package/dist/types/utils/oauthPkce.d.ts +21 -1
  90. package/package.json +2 -2
  91. package/src/boot/__tests__/sessionColdBoot.identity.test.ts +393 -0
  92. package/src/boot/sessionColdBoot.ts +183 -37
  93. package/src/i18n/locales/ar-SA.json +13 -1
  94. package/src/i18n/locales/ca-ES.json +13 -1
  95. package/src/i18n/locales/de-DE.json +13 -1
  96. package/src/i18n/locales/en-US.json +13 -4
  97. package/src/i18n/locales/es-ES.json +13 -4
  98. package/src/i18n/locales/fr-FR.json +13 -1
  99. package/src/i18n/locales/it-IT.json +13 -1
  100. package/src/i18n/locales/ja-JP.json +13 -1
  101. package/src/i18n/locales/ko-KR.json +13 -1
  102. package/src/i18n/locales/pt-PT.json +13 -1
  103. package/src/i18n/locales/zh-CN.json +13 -1
  104. package/src/index.ts +49 -0
  105. package/src/mixins/OxyServices.auth.ts +464 -24
  106. package/src/mixins/OxyServices.deviceBoot.ts +54 -2
  107. package/src/mixins/OxyServices.notifications.ts +142 -0
  108. package/src/mixins/__tests__/commonsSignIn.test.ts +754 -2
  109. package/src/mixins/__tests__/deviceTokenMintPinned.test.ts +113 -0
  110. package/src/mixins/__tests__/preSessionSkipAuth.test.ts +18 -0
  111. package/src/mixins/index.ts +6 -0
  112. package/src/session/SessionClient.ts +57 -4
  113. package/src/session/__tests__/SessionClient.identityPin.test.ts +175 -0
  114. package/src/session/__tests__/accountDialogController.test.ts +812 -1
  115. package/src/session/__tests__/identityPin.test.ts +131 -0
  116. package/src/session/__tests__/identitySession.test.ts +194 -0
  117. package/src/session/__tests__/projectSessionState.test.ts +88 -0
  118. package/src/session/__tests__/refresh.identityPin.test.ts +306 -0
  119. package/src/session/accountDialogController.ts +435 -44
  120. package/src/session/identityPin.ts +310 -0
  121. package/src/session/identitySession.ts +206 -0
  122. package/src/session/projectSessionState.ts +61 -13
  123. package/src/session/refresh.ts +103 -9
  124. package/src/utils/__tests__/oauthPkce.test.ts +51 -0
  125. package/src/utils/commonsDelivery.ts +132 -0
  126. package/src/utils/oauthPkce.ts +56 -3
@@ -5,13 +5,20 @@
5
5
  * run with no network. We assert the exact request bodies the RP and the
6
6
  * approver send — these are the load-bearing coordination points with the C2
7
7
  * server endpoints — plus the native-vs-web behaviour of the shared-key SSO.
8
+ *
9
+ * Also covers Phase 4 (automatic delivery, issue #691): push-token
10
+ * registration, the bearer-authenticated `deliver` call, the un-authenticated
11
+ * `opened` progress signal, and the pure route selector — including the
12
+ * degrade-to-QR behaviour every ambiguous input must produce.
8
13
  */
9
14
 
10
15
  import type { SessionLoginResponse } from '../../models/session';
11
16
  import type { ChallengeResponse } from '../OxyServices.auth';
17
+ import type { CommonsDeliveryPlatform } from '../../utils/commonsDelivery';
12
18
  import { OxyServices } from '../../OxyServices';
13
19
  import { KeyManager } from '../../crypto/keyManager';
14
20
  import { SignatureService } from '../../crypto/signatureService';
21
+ import { selectCommonsDelivery, pushTargetsFromDelivery } from '../../utils/commonsDelivery';
15
22
 
16
23
  const challengeFixture: ChallengeResponse = {
17
24
  challenge: 'chal-xyz',
@@ -71,6 +78,86 @@ describe('OxyServices — "Sign in with Oxy" handoff', () => {
71
78
  expect(handle.qrPayload).not.toContain('secret-session-token');
72
79
  });
73
80
 
81
+ it('omits the oauth key entirely when no OAuth binding is given (body byte-identical to a plain device sign-in)', async () => {
82
+ jest.spyOn(Date, 'now').mockReturnValue(1700000000000);
83
+ jest.spyOn(SignatureService, 'generateChallenge').mockResolvedValue('tok');
84
+ makeRequestSpy.mockResolvedValue({
85
+ authorizeCode: 'code-1',
86
+ qrPayload: 'oxycommons://approve?v=1&code=code-1',
87
+ status: 'pending',
88
+ });
89
+
90
+ await oxy.startCommonsSignIn({ clientId: 'oxy_dk_test' });
91
+
92
+ // `toHaveBeenCalledWith` ignores explicitly-undefined keys, so assert the
93
+ // literal key set: the server decides the request's purpose from the
94
+ // PRESENCE of `oauth`, and an `oauth: undefined` key would still serialize
95
+ // differently from the body this endpoint has always received.
96
+ const body = makeRequestSpy.mock.calls[0][2];
97
+ expect(Object.keys(body)).toEqual(['sessionToken', 'expiresAt', 'clientId']);
98
+ });
99
+
100
+ it('sends the OAuth binding verbatim when provided', async () => {
101
+ jest.spyOn(Date, 'now').mockReturnValue(1700000000000);
102
+ jest.spyOn(SignatureService, 'generateChallenge').mockResolvedValue('secret-session-token');
103
+ makeRequestSpy.mockResolvedValue({
104
+ authorizeCode: 'code-oauth',
105
+ qrPayload: 'oxycommons://approve?v=1&code=code-oauth',
106
+ status: 'pending',
107
+ });
108
+
109
+ const oauth = {
110
+ redirectUri: 'https://mention.earth',
111
+ codeChallenge: 'chal-s256',
112
+ codeChallengeMethod: 'S256' as const,
113
+ scope: 'openid profile',
114
+ subjectAccountId: 'acct-org',
115
+ };
116
+
117
+ const handle = await oxy.startCommonsSignIn({ clientId: 'oxy_dk_test', oauth });
118
+
119
+ expect(makeRequestSpy).toHaveBeenCalledWith(
120
+ 'POST',
121
+ '/auth/session/create',
122
+ {
123
+ sessionToken: 'secret-session-token',
124
+ expiresAt: 1700000300000,
125
+ clientId: 'oxy_dk_test',
126
+ oauth,
127
+ },
128
+ expect.objectContaining({ cache: false, skipAuth: true }),
129
+ );
130
+ // The PKCE verifier and the secret token never leave the initiator, and
131
+ // the QR still only carries the public code.
132
+ expect(JSON.stringify(makeRequestSpy.mock.calls[0][2])).not.toContain('codeVerifier');
133
+ expect(handle.qrPayload).not.toContain('secret-session-token');
134
+ });
135
+
136
+ it('carries an OAuth binding without a scope or delegated account unchanged', async () => {
137
+ jest.spyOn(Date, 'now').mockReturnValue(1700000000000);
138
+ jest.spyOn(SignatureService, 'generateChallenge').mockResolvedValue('tok');
139
+ makeRequestSpy.mockResolvedValue({
140
+ authorizeCode: 'code-oauth',
141
+ qrPayload: 'oxycommons://approve?v=1&code=code-oauth',
142
+ status: 'pending',
143
+ });
144
+
145
+ await oxy.startCommonsSignIn({
146
+ clientId: 'oxy_dk_test',
147
+ oauth: {
148
+ redirectUri: 'https://mention.earth',
149
+ codeChallenge: 'chal-s256',
150
+ codeChallengeMethod: 'S256',
151
+ },
152
+ });
153
+
154
+ expect(makeRequestSpy.mock.calls[0][2].oauth).toEqual({
155
+ redirectUri: 'https://mention.earth',
156
+ codeChallenge: 'chal-s256',
157
+ codeChallengeMethod: 'S256',
158
+ });
159
+ });
160
+
74
161
  it('falls back to the client-proposed expiry when the server omits it', async () => {
75
162
  jest.spyOn(Date, 'now').mockReturnValue(1700000000000);
76
163
  jest.spyOn(SignatureService, 'generateChallenge').mockResolvedValue('tok');
@@ -91,7 +178,14 @@ describe('OxyServices — "Sign in with Oxy" handoff', () => {
91
178
 
92
179
  const result = await oxy.pollCommonsSignIn('secret-session-token');
93
180
 
94
- expect(result).toEqual({ authorized: true, sessionId: 's1' });
181
+ // Delivery progress degrades to null on a server that reports none.
182
+ expect(result).toEqual({
183
+ authorized: true,
184
+ sessionId: 's1',
185
+ purpose: 'device_sign_in',
186
+ pushSentAt: null,
187
+ openedAt: null,
188
+ });
95
189
  expect(makeRequestSpy).toHaveBeenCalledWith(
96
190
  'GET',
97
191
  '/auth/session/status/secret-session-token',
@@ -99,6 +193,319 @@ describe('OxyServices — "Sign in with Oxy" handoff', () => {
99
193
  expect.objectContaining({ cache: false, retry: false }),
100
194
  );
101
195
  });
196
+
197
+ it('carries delivery progress timestamps through unchanged', async () => {
198
+ makeRequestSpy.mockResolvedValue({
199
+ authorized: false,
200
+ status: 'pending',
201
+ pushSentAt: '2026-07-27T10:00:00.000Z',
202
+ openedAt: '2026-07-27T10:00:12.000Z',
203
+ });
204
+
205
+ const result = await oxy.pollCommonsSignIn('secret-session-token');
206
+
207
+ expect(result).toEqual({
208
+ authorized: false,
209
+ status: 'pending',
210
+ purpose: 'device_sign_in',
211
+ pushSentAt: '2026-07-27T10:00:00.000Z',
212
+ openedAt: '2026-07-27T10:00:12.000Z',
213
+ });
214
+ });
215
+
216
+ it('degrades safely when an older API omits the progress timestamps entirely', async () => {
217
+ makeRequestSpy.mockResolvedValue({ authorized: false, status: 'pending' });
218
+
219
+ const result = await oxy.pollCommonsSignIn('secret-session-token');
220
+
221
+ expect(result.pushSentAt).toBeNull();
222
+ expect(result.openedAt).toBeNull();
223
+ // The pre-existing contract is untouched by the addition.
224
+ expect(result.authorized).toBe(false);
225
+ expect(result.status).toBe('pending');
226
+ });
227
+
228
+ it.each([
229
+ ['an explicit null', null],
230
+ ['an empty string', ''],
231
+ ['an unparseable string', 'soon'],
232
+ ['a number (epoch ms, not the ISO contract)', 1700000000000],
233
+ ['an object', { at: '2026-07-27T10:00:00.000Z' }],
234
+ ['a boolean', true],
235
+ ])('drops %s progress timestamp rather than surfacing it', async (_label, value) => {
236
+ makeRequestSpy.mockResolvedValue({
237
+ authorized: false,
238
+ status: 'pending',
239
+ pushSentAt: value,
240
+ openedAt: value,
241
+ });
242
+
243
+ const result = await oxy.pollCommonsSignIn('secret-session-token');
244
+
245
+ expect(result.pushSentAt).toBeNull();
246
+ expect(result.openedAt).toBeNull();
247
+ });
248
+
249
+ it('parses each progress timestamp independently', async () => {
250
+ makeRequestSpy.mockResolvedValue({
251
+ authorized: false,
252
+ status: 'pending',
253
+ pushSentAt: '2026-07-27T10:00:00.000Z',
254
+ openedAt: 'not-a-date',
255
+ });
256
+
257
+ const result = await oxy.pollCommonsSignIn('secret-session-token');
258
+
259
+ expect(result.pushSentAt).toBe('2026-07-27T10:00:00.000Z');
260
+ expect(result.openedAt).toBeNull();
261
+ });
262
+
263
+ it('counts only a literal true as authorized and drops empty identifiers', async () => {
264
+ makeRequestSpy.mockResolvedValue({
265
+ authorized: 'yes',
266
+ sessionId: '',
267
+ publicKey: 42,
268
+ status: 'pending',
269
+ });
270
+
271
+ const result = await oxy.pollCommonsSignIn('secret-session-token');
272
+
273
+ expect(result).toEqual({
274
+ authorized: false,
275
+ status: 'pending',
276
+ purpose: 'device_sign_in',
277
+ pushSentAt: null,
278
+ openedAt: null,
279
+ });
280
+ });
281
+
282
+ it('parses purpose from the status response', async () => {
283
+ makeRequestSpy.mockResolvedValue({
284
+ authorized: false,
285
+ status: 'pending',
286
+ purpose: 'oauth_authorization',
287
+ });
288
+
289
+ const result = await oxy.pollCommonsSignIn('secret-session-token');
290
+
291
+ expect(result.purpose).toBe('oauth_authorization');
292
+ });
293
+
294
+ it.each([
295
+ ['a non-object body', 'pending'],
296
+ ['a null body', null],
297
+ ])('rejects %s rather than returning a half-parsed status', async (_label, value) => {
298
+ makeRequestSpy.mockResolvedValue(value);
299
+
300
+ await expect(oxy.pollCommonsSignIn('secret-session-token')).rejects.toThrow(
301
+ /unexpected response shape/,
302
+ );
303
+ });
304
+ });
305
+
306
+ describe('deliverCommonsSignIn (relying party)', () => {
307
+ it('POSTs the deliver path WITH a bearer (never skipAuth)', async () => {
308
+ makeRequestSpy.mockResolvedValue({ delivered: true, targets: 2 });
309
+
310
+ const result = await oxy.deliverCommonsSignIn('code with/slash');
311
+
312
+ expect(result).toEqual({ delivered: true, targets: 2 });
313
+ expect(makeRequestSpy).toHaveBeenCalledWith(
314
+ 'POST',
315
+ '/auth/session/deliver/code%20with%2Fslash',
316
+ undefined,
317
+ { cache: false },
318
+ );
319
+ // Delivery only happens for an identity Oxy already knows from a trusted
320
+ // authenticated context, so the bearer preflight must NOT be skipped.
321
+ expect(makeRequestSpy.mock.calls[0][3]).not.toHaveProperty('skipAuth');
322
+ });
323
+
324
+ it('treats zero targets as a normal outcome, not a failure', async () => {
325
+ makeRequestSpy.mockResolvedValue({ delivered: false, targets: 0 });
326
+
327
+ const result = await oxy.deliverCommonsSignIn('code-1');
328
+
329
+ // No throw, no coercion — the caller routes this to QR.
330
+ expect(result).toEqual({ delivered: false, targets: 0 });
331
+ expect(selectCommonsDelivery({
332
+ platform: 'desktop',
333
+ commonsAvailable: false,
334
+ pushTargets: pushTargetsFromDelivery(result),
335
+ })).toBe('qr');
336
+ });
337
+
338
+ it('routes a positive target count to the push wait', async () => {
339
+ makeRequestSpy.mockResolvedValue({ delivered: true, targets: 1 });
340
+
341
+ const result = await oxy.deliverCommonsSignIn('code-1');
342
+
343
+ expect(selectCommonsDelivery({
344
+ platform: 'desktop',
345
+ commonsAvailable: false,
346
+ pushTargets: pushTargetsFromDelivery(result),
347
+ })).toBe('await-push');
348
+ });
349
+
350
+ it('falls back to QR when delivery failed despite eligible targets', async () => {
351
+ makeRequestSpy.mockResolvedValue({ delivered: false, targets: 1 });
352
+
353
+ const result = await oxy.deliverCommonsSignIn('code-1');
354
+
355
+ expect(result).toEqual({ delivered: false, targets: 1 });
356
+ expect(selectCommonsDelivery({
357
+ platform: 'desktop',
358
+ commonsAvailable: false,
359
+ pushTargets: pushTargetsFromDelivery(result),
360
+ })).toBe('qr');
361
+ });
362
+
363
+ it.each([
364
+ ['a non-object body', 'delivered'],
365
+ ['a null body', null],
366
+ ])('rejects %s rather than returning it', async (_label, value) => {
367
+ makeRequestSpy.mockResolvedValue(value);
368
+
369
+ await expect(oxy.deliverCommonsSignIn('code-1')).rejects.toThrow(
370
+ /unexpected response shape/,
371
+ );
372
+ });
373
+
374
+ it.each([
375
+ ['a missing delivered', { targets: 1 }],
376
+ ['a non-boolean delivered', { delivered: 'true', targets: 1 }],
377
+ ['a missing targets', { delivered: true }],
378
+ ['a non-numeric targets', { delivered: true, targets: '1' }],
379
+ ['a fractional targets', { delivered: true, targets: 1.5 }],
380
+ ['a NaN targets', { delivered: true, targets: Number.NaN }],
381
+ ['a non-finite targets', { delivered: true, targets: Number.POSITIVE_INFINITY }],
382
+ ['a negative targets', { delivered: true, targets: -1 }],
383
+ ])('rejects %s rather than returning a half-parsed result', async (_label, value) => {
384
+ makeRequestSpy.mockResolvedValue(value);
385
+
386
+ await expect(oxy.deliverCommonsSignIn('code-1')).rejects.toThrow(
387
+ /incomplete delivery result/,
388
+ );
389
+ });
390
+
391
+ it('surfaces a server rejection through the shared error handler', async () => {
392
+ makeRequestSpy.mockRejectedValue(new Error('Invalid or expired sign-in request'));
393
+
394
+ await expect(oxy.deliverCommonsSignIn('code-1')).rejects.toThrow(
395
+ 'Invalid or expired sign-in request',
396
+ );
397
+ });
398
+ });
399
+
400
+ describe('markCommonsApprovalOpened (approver)', () => {
401
+ it('POSTs /auth/session/opened/:authorizeCode with NO bearer', async () => {
402
+ makeRequestSpy.mockResolvedValue(undefined);
403
+
404
+ await expect(oxy.markCommonsApprovalOpened('code-1')).resolves.toBeUndefined();
405
+
406
+ expect(makeRequestSpy).toHaveBeenCalledWith(
407
+ 'POST',
408
+ '/auth/session/opened/code-1',
409
+ undefined,
410
+ { cache: false, skipAuth: true },
411
+ );
412
+ });
413
+
414
+ it('encodes the public code in the path', async () => {
415
+ makeRequestSpy.mockResolvedValue(undefined);
416
+
417
+ await oxy.markCommonsApprovalOpened('code with/slash');
418
+
419
+ expect(makeRequestSpy.mock.calls[0][1]).toBe('/auth/session/opened/code%20with%2Fslash');
420
+ });
421
+
422
+ it('surfaces a server rejection through the shared error handler', async () => {
423
+ makeRequestSpy.mockRejectedValue(new Error('Sign-in request is not pending'));
424
+
425
+ await expect(oxy.markCommonsApprovalOpened('code-1')).rejects.toThrow(
426
+ 'Sign-in request is not pending',
427
+ );
428
+ });
429
+ });
430
+
431
+ describe('finalizeCommonsOAuth (relying party)', () => {
432
+ it('POSTs the finalize path with the SECRET sessionToken and no bearer', async () => {
433
+ makeRequestSpy.mockResolvedValue({
434
+ code: 'authcode-1',
435
+ redirectUri: 'https://mention.earth',
436
+ expiresIn: 60,
437
+ });
438
+
439
+ const result = await oxy.finalizeCommonsOAuth('secret session/token');
440
+
441
+ expect(makeRequestSpy).toHaveBeenCalledWith(
442
+ 'POST',
443
+ // The secret token is the credential in the path — encoded, never raw.
444
+ '/auth/session/finalize/secret%20session%2Ftoken',
445
+ undefined,
446
+ expect.objectContaining({ cache: false, skipAuth: true }),
447
+ );
448
+ // An authorization CODE, never a token: the caller still runs the PKCE
449
+ // exchange with the verifier it never sent.
450
+ expect(result).toEqual({
451
+ code: 'authcode-1',
452
+ redirectUri: 'https://mention.earth',
453
+ expiresIn: 60,
454
+ });
455
+ });
456
+
457
+ it('does not plant any token (finalization is not a session)', async () => {
458
+ makeRequestSpy.mockResolvedValue({
459
+ code: 'authcode-1',
460
+ redirectUri: 'https://mention.earth',
461
+ expiresIn: 60,
462
+ });
463
+
464
+ await oxy.finalizeCommonsOAuth('secret-session-token');
465
+
466
+ expect(oxy.getAccessToken()).toBeNull();
467
+ });
468
+
469
+ it.each([
470
+ ['a non-object body', 'authcode-1'],
471
+ ['a null body', null],
472
+ ])('rejects %s rather than returning it', async (_label, value) => {
473
+ makeRequestSpy.mockResolvedValue(value);
474
+
475
+ await expect(oxy.finalizeCommonsOAuth('secret-session-token')).rejects.toThrow(
476
+ /unexpected response shape/,
477
+ );
478
+ });
479
+
480
+ it.each([
481
+ ['a missing code', { redirectUri: 'https://mention.earth', expiresIn: 60 }],
482
+ ['an empty code', { code: '', redirectUri: 'https://mention.earth', expiresIn: 60 }],
483
+ ['a missing redirectUri', { code: 'authcode-1', expiresIn: 60 }],
484
+ ['an empty redirectUri', { code: 'authcode-1', redirectUri: '', expiresIn: 60 }],
485
+ ['a missing expiresIn', { code: 'authcode-1', redirectUri: 'https://mention.earth' }],
486
+ [
487
+ 'a non-numeric expiresIn',
488
+ { code: 'authcode-1', redirectUri: 'https://mention.earth', expiresIn: '60' },
489
+ ],
490
+ [
491
+ 'a non-finite expiresIn',
492
+ { code: 'authcode-1', redirectUri: 'https://mention.earth', expiresIn: Number.NaN },
493
+ ],
494
+ ])('rejects %s rather than returning a half-parsed result', async (_label, value) => {
495
+ makeRequestSpy.mockResolvedValue(value);
496
+
497
+ await expect(oxy.finalizeCommonsOAuth('secret-session-token')).rejects.toThrow(
498
+ /incomplete authorization code/,
499
+ );
500
+ });
501
+
502
+ it('surfaces a server rejection through the shared error handler', async () => {
503
+ makeRequestSpy.mockRejectedValue(new Error('Invalid or expired sign-in request'));
504
+
505
+ await expect(oxy.finalizeCommonsOAuth('secret-session-token')).rejects.toThrow(
506
+ 'Invalid or expired sign-in request',
507
+ );
508
+ });
102
509
  });
103
510
 
104
511
  describe('getCommonsApprovalInfo (approver)', () => {
@@ -122,7 +529,13 @@ describe('OxyServices — "Sign in with Oxy" handoff', () => {
122
529
 
123
530
  const result = await oxy.getCommonsApprovalInfo('code-1');
124
531
 
125
- expect(result).toEqual({ ...baseInfo, originVerified: true });
532
+ expect(result).toEqual({
533
+ ...baseInfo,
534
+ originVerified: true,
535
+ requesterLabel: null,
536
+ purpose: 'device_sign_in',
537
+ subjectAccount: null,
538
+ });
126
539
  expect(makeRequestSpy).toHaveBeenCalledWith(
127
540
  'GET',
128
541
  '/auth/session/approve-info/code-1',
@@ -139,6 +552,77 @@ describe('OxyServices — "Sign in with Oxy" handoff', () => {
139
552
  expect(result.originVerified).toBe(false);
140
553
  });
141
554
 
555
+ it('parses an OAuth-bound request with its delegated subject account', async () => {
556
+ makeRequestSpy.mockResolvedValue({
557
+ ...baseInfo,
558
+ originVerified: true,
559
+ purpose: 'oauth_authorization',
560
+ subjectAccount: { id: 'acct-org', username: 'oxy', displayName: 'The Oxy Collective' },
561
+ });
562
+
563
+ const result = await oxy.getCommonsApprovalInfo('code-1');
564
+
565
+ expect(result.purpose).toBe('oauth_authorization');
566
+ expect(result.subjectAccount).toEqual({
567
+ id: 'acct-org',
568
+ username: 'oxy',
569
+ displayName: 'The Oxy Collective',
570
+ });
571
+ });
572
+
573
+ it('keeps a delegated account without a displayName (omits the key rather than blanking it)', async () => {
574
+ makeRequestSpy.mockResolvedValue({
575
+ ...baseInfo,
576
+ subjectAccount: { id: 'acct-org', username: 'oxy' },
577
+ });
578
+
579
+ const result = await oxy.getCommonsApprovalInfo('code-1');
580
+
581
+ expect(result.subjectAccount).toEqual({ id: 'acct-org', username: 'oxy' });
582
+ });
583
+
584
+ it('degrades a server that omits purpose/subjectAccount to a plain device sign-in', async () => {
585
+ makeRequestSpy.mockResolvedValue(baseInfo);
586
+
587
+ const result = await oxy.getCommonsApprovalInfo('code-1');
588
+
589
+ expect(result.purpose).toBe('device_sign_in');
590
+ expect(result.subjectAccount).toBeNull();
591
+ });
592
+
593
+ it('coerces an unrecognized purpose to device_sign_in (never implies an OAuth grant)', async () => {
594
+ makeRequestSpy.mockResolvedValue({ ...baseInfo, purpose: 'something_else' });
595
+
596
+ const result = await oxy.getCommonsApprovalInfo('code-1');
597
+
598
+ expect(result.purpose).toBe('device_sign_in');
599
+ });
600
+
601
+ it.each([
602
+ ['a half-populated object', { id: 'acct-org' }],
603
+ ['a non-string id', { id: 7, username: 'oxy' }],
604
+ ['an empty username', { id: 'acct-org', username: '' }],
605
+ ['a non-object', 'acct-org'],
606
+ ['an explicit null', null],
607
+ ])('rejects %s subjectAccount whole (fail-safe to "no delegation")', async (_label, value) => {
608
+ makeRequestSpy.mockResolvedValue({ ...baseInfo, subjectAccount: value });
609
+
610
+ const result = await oxy.getCommonsApprovalInfo('code-1');
611
+
612
+ expect(result.subjectAccount).toBeNull();
613
+ });
614
+
615
+ it('drops a non-string displayName rather than rendering it', async () => {
616
+ makeRequestSpy.mockResolvedValue({
617
+ ...baseInfo,
618
+ subjectAccount: { id: 'acct-org', username: 'oxy', displayName: 42 },
619
+ });
620
+
621
+ const result = await oxy.getCommonsApprovalInfo('code-1');
622
+
623
+ expect(result.subjectAccount).toEqual({ id: 'acct-org', username: 'oxy' });
624
+ });
625
+
142
626
  it('coerces a non-boolean originVerified to false', async () => {
143
627
  makeRequestSpy.mockResolvedValue({ ...baseInfo, originVerified: 'yes' });
144
628
 
@@ -154,6 +638,50 @@ describe('OxyServices — "Sign in with Oxy" handoff', () => {
154
638
 
155
639
  expect(result.originVerified).toBe(false);
156
640
  });
641
+
642
+ it('carries the coarse requester label through verbatim', async () => {
643
+ makeRequestSpy.mockResolvedValue({ ...baseInfo, requesterLabel: 'Chrome on Windows' });
644
+
645
+ const result = await oxy.getCommonsApprovalInfo('code-1');
646
+
647
+ expect(result.requesterLabel).toBe('Chrome on Windows');
648
+ });
649
+
650
+ it('trims surrounding whitespace off the label', async () => {
651
+ makeRequestSpy.mockResolvedValue({ ...baseInfo, requesterLabel: ' Safari on iOS ' });
652
+
653
+ const result = await oxy.getCommonsApprovalInfo('code-1');
654
+
655
+ expect(result.requesterLabel).toBe('Safari on iOS');
656
+ });
657
+
658
+ it.each([
659
+ ['omitted (an API that predates the field)', undefined],
660
+ ['an explicit null (native requester)', null],
661
+ ['an empty string', ''],
662
+ ['whitespace only', ' '],
663
+ ['a non-string', 42],
664
+ ['an object', { browser: 'Chrome' }],
665
+ ])('degrades %s requesterLabel to null (the UI omits the line)', async (_label, value) => {
666
+ makeRequestSpy.mockResolvedValue({ ...baseInfo, requesterLabel: value });
667
+
668
+ const result = await oxy.getCommonsApprovalInfo('code-1');
669
+
670
+ expect(result.requesterLabel).toBeNull();
671
+ });
672
+
673
+ it('parses BOTH new fields fail-safe when the API omits them entirely', async () => {
674
+ // An older API sends neither `requesterLabel` nor the fields around it —
675
+ // the approval info must still resolve, never throw.
676
+ makeRequestSpy.mockResolvedValue(baseInfo);
677
+
678
+ const result = await oxy.getCommonsApprovalInfo('code-1');
679
+
680
+ expect(result.requesterLabel).toBeNull();
681
+ expect(result.originVerified).toBe(false);
682
+ expect(result.purpose).toBe('device_sign_in');
683
+ expect(result.subjectAccount).toBeNull();
684
+ });
157
685
  });
158
686
 
159
687
  describe('approveCommonsSignIn (approver)', () => {
@@ -240,6 +768,30 @@ describe('OxyServices — "Sign in with Oxy" handoff', () => {
240
768
  expect.objectContaining({ cache: false }),
241
769
  );
242
770
  });
771
+
772
+ it.each([['declined'], ['not_me']] as const)(
773
+ 'sends the closed-set reason %s in the body',
774
+ async (reason) => {
775
+ makeRequestSpy.mockResolvedValue({ success: true });
776
+
777
+ await oxy.denyCommonsSignIn('code-1', reason);
778
+
779
+ expect(makeRequestSpy).toHaveBeenCalledWith(
780
+ 'POST',
781
+ '/auth/session/deny/code-1',
782
+ { reason },
783
+ expect.objectContaining({ cache: false }),
784
+ );
785
+ },
786
+ );
787
+
788
+ it('sends no body at all when no reason is given (byte-identical to the old call)', async () => {
789
+ makeRequestSpy.mockResolvedValue({ success: true });
790
+
791
+ await oxy.denyCommonsSignIn('code-1');
792
+
793
+ expect(makeRequestSpy.mock.calls[0][2]).toBeUndefined();
794
+ });
243
795
  });
244
796
 
245
797
  describe('requestChallenge / verifyChallenge — requestOptions spread into makeRequest', () => {
@@ -382,4 +934,204 @@ describe('OxyServices — "Sign in with Oxy" handoff', () => {
382
934
  expect(verifyChallengeSpy).not.toHaveBeenCalled();
383
935
  });
384
936
  });
937
+
938
+ describe('registerPushToken / unregisterPushToken', () => {
939
+ const expoToken = 'ExponentPushToken[abc123XYZ]';
940
+
941
+ it('POSTs the Expo push token with a bearer', async () => {
942
+ makeRequestSpy.mockResolvedValue({ registered: true });
943
+
944
+ await expect(
945
+ oxy.registerPushToken({ expoPushToken: expoToken, platform: 'ios' }),
946
+ ).resolves.toBeUndefined();
947
+
948
+ expect(makeRequestSpy).toHaveBeenCalledWith(
949
+ 'POST',
950
+ '/notifications/push-token',
951
+ { token: expoToken, platform: 'ios' },
952
+ { cache: false },
953
+ );
954
+ // Push registration is per-identity — the bearer preflight must run.
955
+ expect(makeRequestSpy.mock.calls[0][3]).not.toHaveProperty('skipAuth');
956
+ });
957
+
958
+ it('omits deviceId/clientId entirely when not provided', async () => {
959
+ makeRequestSpy.mockResolvedValue({ registered: true });
960
+
961
+ await oxy.registerPushToken({ expoPushToken: expoToken, platform: 'android' });
962
+
963
+ // `toHaveBeenCalledWith` ignores explicitly-undefined keys, so assert the
964
+ // literal key set: the server reads PRESENCE of these optional fields.
965
+ expect(Object.keys(makeRequestSpy.mock.calls[0][2])).toEqual(['token', 'platform']);
966
+ });
967
+
968
+ it('sends deviceId and clientId when provided', async () => {
969
+ makeRequestSpy.mockResolvedValue({ registered: true });
970
+
971
+ await oxy.registerPushToken({
972
+ expoPushToken: expoToken,
973
+ platform: 'ios',
974
+ deviceId: 'dev-1',
975
+ clientId: 'oxy_dk_commons',
976
+ });
977
+
978
+ expect(makeRequestSpy.mock.calls[0][2]).toEqual({
979
+ token: expoToken,
980
+ platform: 'ios',
981
+ deviceId: 'dev-1',
982
+ clientId: 'oxy_dk_commons',
983
+ });
984
+ });
985
+
986
+ it('accepts the ExpoPushToken spelling as well', async () => {
987
+ makeRequestSpy.mockResolvedValue({ registered: true });
988
+
989
+ await oxy.registerPushToken({ expoPushToken: 'ExpoPushToken[abc123]', platform: 'web' });
990
+
991
+ expect(makeRequestSpy).toHaveBeenCalled();
992
+ });
993
+
994
+ it.each([
995
+ // The exact inbox hazard: getDevicePushTokenAsync's raw FCM/APNs token.
996
+ ['a raw FCM token', 'fMEP0vJqS0y5:APA91bH-longopaquestring'],
997
+ ['a raw APNs hex token', '740f4707bebcf74f9b7c25d48e3358945f6aa01da5ddb387462c7eaf61bb78ad'],
998
+ ['an empty string', ''],
999
+ ['a truncated wrapper', 'ExponentPushToken['],
1000
+ ['an empty wrapper', 'ExponentPushToken[]'],
1001
+ ['a token with whitespace inside', 'ExponentPushToken[abc 123]'],
1002
+ ['surrounding whitespace', ' ExponentPushToken[abc123] '],
1003
+ ])('rejects %s without sending a request', async (_label, token) => {
1004
+ await expect(
1005
+ oxy.registerPushToken({ expoPushToken: token, platform: 'ios' }),
1006
+ ).rejects.toThrow(/Expo push token/);
1007
+
1008
+ expect(makeRequestSpy).not.toHaveBeenCalled();
1009
+ });
1010
+
1011
+ it('DELETEs the token on unregister', async () => {
1012
+ makeRequestSpy.mockResolvedValue({ unregistered: true });
1013
+
1014
+ await expect(oxy.unregisterPushToken(expoToken)).resolves.toBeUndefined();
1015
+
1016
+ expect(makeRequestSpy).toHaveBeenCalledWith(
1017
+ 'DELETE',
1018
+ '/notifications/push-token',
1019
+ { token: expoToken },
1020
+ { cache: false },
1021
+ );
1022
+ });
1023
+
1024
+ it('surfaces a server rejection through the shared error handler', async () => {
1025
+ makeRequestSpy.mockRejectedValue(new Error('Unknown client'));
1026
+
1027
+ await expect(
1028
+ oxy.registerPushToken({ expoPushToken: expoToken, platform: 'ios' }),
1029
+ ).rejects.toThrow('Unknown client');
1030
+ });
1031
+ });
1032
+ });
1033
+
1034
+ describe('selectCommonsDelivery — automatic delivery selection', () => {
1035
+ const platforms: CommonsDeliveryPlatform[] = ['mobile', 'desktop', 'unknown'];
1036
+
1037
+ it('opens Commons on mobile when a verified Commons link is available', () => {
1038
+ expect(
1039
+ selectCommonsDelivery({ platform: 'mobile', commonsAvailable: true, pushTargets: 0 }),
1040
+ ).toBe('open-commons');
1041
+ });
1042
+
1043
+ it('prefers opening Commons over a push that also has targets', () => {
1044
+ // Rule 1 wins outright — the identity is already reachable on this device,
1045
+ // so nobody's other phone should ring.
1046
+ expect(
1047
+ selectCommonsDelivery({ platform: 'mobile', commonsAvailable: true, pushTargets: 3 }),
1048
+ ).toBe('open-commons');
1049
+ });
1050
+
1051
+ it('awaits the push on mobile without a verified Commons link', () => {
1052
+ expect(
1053
+ selectCommonsDelivery({ platform: 'mobile', commonsAvailable: false, pushTargets: 1 }),
1054
+ ).toBe('await-push');
1055
+ });
1056
+
1057
+ it('awaits the push on a desktop with a known Commons installation', () => {
1058
+ expect(
1059
+ selectCommonsDelivery({ platform: 'desktop', commonsAvailable: false, pushTargets: 2 }),
1060
+ ).toBe('await-push');
1061
+ });
1062
+
1063
+ it('shows the QR on an unknown desktop browser', () => {
1064
+ expect(
1065
+ selectCommonsDelivery({ platform: 'desktop', commonsAvailable: false, pushTargets: 0 }),
1066
+ ).toBe('qr');
1067
+ });
1068
+
1069
+ it('never deep-links from desktop even when a Commons link is claimed available', () => {
1070
+ // A custom-scheme navigation that does not resolve is a dead end, so a
1071
+ // desktop caller falls through to push/QR regardless.
1072
+ expect(
1073
+ selectCommonsDelivery({ platform: 'desktop', commonsAvailable: true, pushTargets: 0 }),
1074
+ ).toBe('qr');
1075
+ expect(
1076
+ selectCommonsDelivery({ platform: 'desktop', commonsAvailable: true, pushTargets: 1 }),
1077
+ ).toBe('await-push');
1078
+ });
1079
+
1080
+ it('never deep-links from an unknown platform (degrades to push, then QR)', () => {
1081
+ expect(
1082
+ selectCommonsDelivery({ platform: 'unknown', commonsAvailable: true, pushTargets: 0 }),
1083
+ ).toBe('qr');
1084
+ expect(
1085
+ selectCommonsDelivery({ platform: 'unknown', commonsAvailable: true, pushTargets: 1 }),
1086
+ ).toBe('await-push');
1087
+ expect(
1088
+ selectCommonsDelivery({ platform: 'unknown', commonsAvailable: false, pushTargets: 0 }),
1089
+ ).toBe('qr');
1090
+ });
1091
+
1092
+ it('treats zero targets as QR on every platform (a normal outcome, not an error)', () => {
1093
+ for (const platform of platforms) {
1094
+ expect(selectCommonsDelivery({ platform, commonsAvailable: false, pushTargets: 0 })).toBe(
1095
+ 'qr',
1096
+ );
1097
+ }
1098
+ });
1099
+
1100
+ it.each([
1101
+ ['a negative count', -1],
1102
+ ['a fractional count', 0.5],
1103
+ ['a fractional count above one', 1.5],
1104
+ ['NaN', Number.NaN],
1105
+ ['Infinity', Number.POSITIVE_INFINITY],
1106
+ ])('degrades %s to QR rather than a push nobody will answer', (_label, pushTargets) => {
1107
+ expect(selectCommonsDelivery({ platform: 'desktop', commonsAvailable: false, pushTargets })).toBe(
1108
+ 'qr',
1109
+ );
1110
+ });
1111
+
1112
+ it('is pure — the same facts always yield the same route', () => {
1113
+ const facts = {
1114
+ platform: 'desktop' as const,
1115
+ commonsAvailable: false,
1116
+ pushTargets: 1,
1117
+ };
1118
+
1119
+ expect(selectCommonsDelivery(facts)).toBe('await-push');
1120
+ expect(selectCommonsDelivery(facts)).toBe('await-push');
1121
+ // ...and it does not mutate the caller's facts.
1122
+ expect(facts).toEqual({ platform: 'desktop', commonsAvailable: false, pushTargets: 1 });
1123
+ });
1124
+
1125
+ it('covers every (platform × commonsAvailable × targets) combination with one route', () => {
1126
+ const routes = new Set<string>();
1127
+ for (const platform of platforms) {
1128
+ for (const commonsAvailable of [true, false]) {
1129
+ for (const pushTargets of [0, 1]) {
1130
+ routes.add(selectCommonsDelivery({ platform, commonsAvailable, pushTargets }));
1131
+ }
1132
+ }
1133
+ }
1134
+ // Exactly the three primary routes — no chained/compound outcome exists.
1135
+ expect([...routes].sort()).toEqual(['await-push', 'open-commons', 'qr']);
1136
+ });
385
1137
  });