@oxyhq/core 1.11.22 → 1.11.24

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 (41) hide show
  1. package/README.md +2 -2
  2. package/dist/cjs/.tsbuildinfo +1 -1
  3. package/dist/cjs/HttpService.js +52 -0
  4. package/dist/cjs/OxyServices.base.js +16 -0
  5. package/dist/cjs/mixins/OxyServices.fedcm.js +169 -73
  6. package/dist/esm/.tsbuildinfo +1 -1
  7. package/dist/esm/HttpService.js +52 -0
  8. package/dist/esm/OxyServices.base.js +16 -0
  9. package/dist/esm/mixins/OxyServices.fedcm.js +169 -73
  10. package/dist/types/.tsbuildinfo +1 -1
  11. package/dist/types/HttpService.d.ts +31 -0
  12. package/dist/types/OxyServices.base.d.ts +14 -0
  13. package/dist/types/OxyServices.d.ts +9 -0
  14. package/dist/types/mixins/OxyServices.analytics.d.ts +1 -0
  15. package/dist/types/mixins/OxyServices.appData.d.ts +1 -0
  16. package/dist/types/mixins/OxyServices.assets.d.ts +1 -0
  17. package/dist/types/mixins/OxyServices.auth.d.ts +1 -0
  18. package/dist/types/mixins/OxyServices.contacts.d.ts +1 -0
  19. package/dist/types/mixins/OxyServices.developer.d.ts +1 -0
  20. package/dist/types/mixins/OxyServices.devices.d.ts +1 -0
  21. package/dist/types/mixins/OxyServices.features.d.ts +6 -1
  22. package/dist/types/mixins/OxyServices.fedcm.d.ts +20 -1
  23. package/dist/types/mixins/OxyServices.karma.d.ts +1 -0
  24. package/dist/types/mixins/OxyServices.language.d.ts +1 -0
  25. package/dist/types/mixins/OxyServices.location.d.ts +1 -0
  26. package/dist/types/mixins/OxyServices.managedAccounts.d.ts +1 -0
  27. package/dist/types/mixins/OxyServices.payment.d.ts +1 -0
  28. package/dist/types/mixins/OxyServices.popup.d.ts +1 -0
  29. package/dist/types/mixins/OxyServices.privacy.d.ts +1 -0
  30. package/dist/types/mixins/OxyServices.redirect.d.ts +1 -0
  31. package/dist/types/mixins/OxyServices.security.d.ts +1 -0
  32. package/dist/types/mixins/OxyServices.topics.d.ts +1 -0
  33. package/dist/types/mixins/OxyServices.user.d.ts +1 -0
  34. package/dist/types/mixins/OxyServices.utility.d.ts +1 -0
  35. package/package.json +1 -1
  36. package/src/HttpService.ts +53 -0
  37. package/src/OxyServices.base.ts +17 -0
  38. package/src/OxyServices.ts +10 -0
  39. package/src/mixins/OxyServices.fedcm.ts +187 -78
  40. package/src/mixins/__tests__/fedcm.test.ts +231 -0
  41. package/src/mixins/__tests__/onTokensChanged.test.ts +130 -0
@@ -66,6 +66,33 @@ function isUnknownModeEnumError(error: unknown): boolean {
66
66
  );
67
67
  }
68
68
 
69
+ /**
70
+ * Detect a `navigator.credentials.get` rejection that is consistent with
71
+ * "the supplied loginHint matched no account at the IdP".
72
+ *
73
+ * When an RP passes a `loginHint` and the IdP returns accounts but NONE of them
74
+ * declare that hint in their `login_hints`, Chrome filters every account out,
75
+ * greys it in the chooser ("You can't sign in using this account"), logs
76
+ * "Accounts were received, but none matched the login hint…", and ultimately
77
+ * rejects the credential request — surfacing as a `NotAllowedError` /
78
+ * `AbortError` (the same shape as a user-cancelled or timed-out request). A
79
+ * stale hint left over from a previously-signed-in/test account therefore hard
80
+ * -blocks sign-in.
81
+ *
82
+ * We can only safely apply the clear-and-retry recovery when a `loginHint` was
83
+ * actually supplied; without one this is just a normal cancel/timeout and must
84
+ * NOT be retried. Callers gate on `hadLoginHint` before calling this.
85
+ */
86
+ function isPossibleHintMismatchError(error: unknown): boolean {
87
+ if (!(error instanceof Error)) return false;
88
+ // FedCM surfaces a filtered-out / no-eligible-account outcome as
89
+ // NotAllowedError (current Chrome) or AbortError (our own timeout abort while
90
+ // the chooser had no selectable account). Both are indistinguishable from a
91
+ // genuine user cancel at the API level, so the gate on "a hint was supplied"
92
+ // (in the caller) is what makes the retry safe and targeted.
93
+ return error.name === 'NotAllowedError' || error.name === 'AbortError';
94
+ }
95
+
69
96
  // Minimal structural types for the FedCM `navigator.credentials.get` surface.
70
97
  // The DOM lib does not ship these in every TypeScript version we build against,
71
98
  // so we model only the fields this mixin reads/writes. This lets the FedCM code
@@ -129,6 +156,11 @@ const FEDCM_LOGIN_HINT_KEY = 'oxy_fedcm_login_hint';
129
156
  let fedCMRequestInProgress = false;
130
157
  let fedCMRequestPromise: Promise<FedCMTokenResult | null> | null = null;
131
158
  let currentMediationMode: string | null = null;
159
+ // AbortController of the in-flight request, exposed at module scope so an
160
+ // arriving INTERACTIVE request can abort a slow/hung SILENT one instead of
161
+ // blocking on it (see requestIdentityCredential). Set when a request starts,
162
+ // cleared in that request's `finally`.
163
+ let fedCMActiveController: AbortController | null = null;
132
164
 
133
165
  /**
134
166
  * Federated Credential Management (FedCM) Authentication Mixin
@@ -159,13 +191,23 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
159
191
  public static readonly DEFAULT_CONFIG_URL = 'https://auth.oxy.so/fedcm.json';
160
192
 
161
193
  public resolveFedcmConfigUrl(): string {
194
+ // `DEFAULT_CONFIG_URL` is a static on the composed class; read it off the
195
+ // most-derived constructor through a typed cast (not `any`).
196
+ const configCtor = this.constructor as typeof OxyServicesBase & {
197
+ DEFAULT_CONFIG_URL: string;
198
+ };
162
199
  return this.config.authWebUrl
163
200
  ? `${this.config.authWebUrl}/fedcm.json`
164
- : (this.constructor as any).DEFAULT_CONFIG_URL;
201
+ : configCtor.DEFAULT_CONFIG_URL;
165
202
  }
166
203
 
167
204
  public static readonly FEDCM_TIMEOUT = 15000; // 15 seconds for interactive
168
- public static readonly FEDCM_SILENT_TIMEOUT = 3000; // 3 seconds for silent mediation
205
+ // Silent mediation runs on page load (e.g. re-signing-in a user whose stored
206
+ // session was cleared after a cold-boot token fetch 401'd). The real silent
207
+ // round-trip — mint nonce → navigator.credentials.get → /fedcm/exchange — was
208
+ // measured to take more than 3s for live users, so a 3s budget timed out and
209
+ // left them signed out on reload. 10s gives ample margin while staying bounded.
210
+ public static readonly FEDCM_SILENT_TIMEOUT = 10000; // 10 seconds for silent mediation
169
211
 
170
212
  /**
171
213
  * Check if FedCM is supported in the current browser
@@ -213,77 +255,121 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
213
255
  );
214
256
  }
215
257
 
216
- try {
217
- // Prefer a server-minted, origin-bound nonce so the downstream
218
- // `/fedcm/exchange` can validate it. A caller-supplied nonce is
219
- // respected as-is for advanced use cases.
220
- const nonce = options.nonce || (await this.getFedcmNonce());
221
- const clientId = this.getClientId();
222
-
223
- // Use provided loginHint, or fall back to stored last-used account ID
224
- const loginHint = options.loginHint || this.getStoredLoginHint();
225
-
226
- debug.log('Interactive sign-in: Requesting credential for', clientId, loginHint ? `(hint: ${loginHint})` : '');
227
-
228
- // Request credential from browser's native identity flow.
229
- // mode: 'active' signals this is a user-gesture-initiated (button) flow.
230
- // 'active' is the current W3C spec value; requestIdentityCredential
231
- // transparently retries with the legacy 'button' value for Chrome 125–131.
232
- const credential = await this.requestIdentityCredential({
233
- configURL: this.resolveFedcmConfigUrl(),
234
- clientId,
235
- nonce,
236
- context: options.context,
237
- loginHint,
238
- mode: 'active',
239
- });
258
+ // Use provided loginHint, or fall back to stored last-used account ID.
259
+ const initialLoginHint = options.loginHint || this.getStoredLoginHint();
240
260
 
241
- if (!credential || !credential.token) {
242
- throw new OxyAuthenticationError('No credential received from browser');
261
+ try {
262
+ return await this.attemptInteractiveSignIn(options, initialLoginHint);
263
+ } catch (error) {
264
+ // A STALE loginHint (e.g. left over from a previously-signed-in or test
265
+ // account) that matches no account at the IdP makes Chrome filter out
266
+ // every account and reject the request — indistinguishable from a user
267
+ // cancel. When that happens AND we supplied a hint, clear the bad hint
268
+ // and retry the credential request ONCE with no hint, which lets the
269
+ // chooser surface the genuinely available account(s). We only do this for
270
+ // a hint we pulled from storage (not a caller-supplied one), and only
271
+ // once, so a real cancel never loops.
272
+ const usedStoredHint = !!initialLoginHint && !options.loginHint;
273
+ if (usedStoredHint && isPossibleHintMismatchError(error)) {
274
+ debug.log(
275
+ 'Interactive sign-in: stored loginHint matched no account; clearing it and retrying without a hint'
276
+ );
277
+ this.clearLoginHint();
278
+ return await this.attemptInteractiveSignIn(options, undefined);
243
279
  }
280
+ throw this.normalizeInteractiveSignInError(error);
281
+ }
282
+ }
244
283
 
245
- debug.log('Interactive sign-in: Got credential, exchanging for session');
284
+ /**
285
+ * Run a single interactive FedCM credential request + token exchange for the
286
+ * given (possibly undefined) loginHint. A successful exchange plants the
287
+ * access token and persists the user id as the future loginHint — the hint is
288
+ * therefore only ever stored after a GENUINELY successful sign-in, never
289
+ * speculatively.
290
+ *
291
+ * @private
292
+ */
293
+ public async attemptInteractiveSignIn(
294
+ options: FedCMAuthOptions,
295
+ loginHint: string | undefined
296
+ ): Promise<SessionLoginResponse> {
297
+ // Prefer a server-minted, origin-bound nonce so the downstream
298
+ // `/fedcm/exchange` can validate it. A caller-supplied nonce is
299
+ // respected as-is for advanced use cases.
300
+ const nonce = options.nonce || (await this.getFedcmNonce());
301
+ const clientId = this.getClientId();
246
302
 
247
- // Exchange FedCM ID token for Oxy session
248
- const session = await this.exchangeIdTokenForSession(credential.token);
303
+ debug.log('Interactive sign-in: Requesting credential for', clientId, loginHint ? `(hint: ${loginHint})` : '');
249
304
 
250
- // Store access token in HttpService. `accessToken`/`refreshToken` are
251
- // declared optional on SessionLoginResponse; default the refresh token to
252
- // an empty string when the exchange did not return one.
253
- if (session?.accessToken) {
254
- this.httpService.setTokens(session.accessToken, session.refreshToken ?? '');
255
- }
305
+ // Request credential from browser's native identity flow.
306
+ // mode: 'active' signals this is a user-gesture-initiated (button) flow.
307
+ // 'active' is the current W3C spec value; requestIdentityCredential
308
+ // transparently retries with the legacy 'button' value for Chrome 125–131.
309
+ const credential = await this.requestIdentityCredential({
310
+ configURL: this.resolveFedcmConfigUrl(),
311
+ clientId,
312
+ nonce,
313
+ context: options.context,
314
+ loginHint,
315
+ mode: 'active',
316
+ });
256
317
 
257
- // Store the user ID as loginHint for future FedCM requests
258
- if (session?.user?.id) {
259
- this.storeLoginHint(session.user.id);
260
- }
318
+ if (!credential || !credential.token) {
319
+ throw new OxyAuthenticationError('No credential received from browser');
320
+ }
261
321
 
262
- debug.log('Interactive sign-in: Success!', { userId: session?.user?.id });
322
+ debug.log('Interactive sign-in: Got credential, exchanging for session');
263
323
 
264
- return session;
265
- } catch (error) {
266
- debug.log('Interactive sign-in failed:', error);
267
- const errorMessage = error instanceof Error ? error.message : String(error);
268
- // FedCM aborts/network failures surface as DOMException/Error instances,
269
- // both of which carry a `name`. Anything else has no meaningful name.
270
- const errorName = error instanceof Error ? error.name : '';
271
-
272
- if (errorName === 'AbortError') {
273
- throw new OxyAuthenticationError('Sign-in was cancelled by user');
274
- }
275
- if (errorName === 'NetworkError') {
276
- throw new OxyAuthenticationError('Network error during sign-in. Please check your connection.');
277
- }
278
- if (errorMessage.includes('multiple accounts')) {
279
- throw new OxyAuthenticationError('Please sign out and sign in again to use FedCM with a single account');
280
- }
281
- if (errorMessage.includes('retrieving a token') || errorMessage.includes('Error retrieving')) {
282
- debug.error('FedCM token retrieval error - this may be a browser or IdP configuration issue');
283
- throw new OxyAuthenticationError('Authentication failed. Please try again or use an alternative sign-in method.');
284
- }
285
- throw error;
324
+ // Exchange FedCM ID token for Oxy session
325
+ const session = await this.exchangeIdTokenForSession(credential.token);
326
+
327
+ // Store access token in HttpService. `accessToken`/`refreshToken` are
328
+ // declared optional on SessionLoginResponse; default the refresh token to
329
+ // an empty string when the exchange did not return one.
330
+ if (session?.accessToken) {
331
+ this.httpService.setTokens(session.accessToken, session.refreshToken ?? '');
286
332
  }
333
+
334
+ // Store the user ID as loginHint for future FedCM requests — only now, after
335
+ // a real successful exchange, so we never persist a hint that cannot resolve.
336
+ if (session?.user?.id) {
337
+ this.storeLoginHint(session.user.id);
338
+ }
339
+
340
+ debug.log('Interactive sign-in: Success!', { userId: session?.user?.id });
341
+
342
+ return session;
343
+ }
344
+
345
+ /**
346
+ * Map a raw FedCM/exchange failure to a user-facing {@link OxyAuthenticationError}
347
+ * (or pass it through). Extracted so the clear-and-retry path can reuse the
348
+ * exact same error normalisation as the first attempt.
349
+ *
350
+ * @private
351
+ */
352
+ public normalizeInteractiveSignInError(error: unknown): unknown {
353
+ debug.log('Interactive sign-in failed:', error);
354
+ const errorMessage = error instanceof Error ? error.message : String(error);
355
+ // FedCM aborts/network failures surface as DOMException/Error instances,
356
+ // both of which carry a `name`. Anything else has no meaningful name.
357
+ const errorName = error instanceof Error ? error.name : '';
358
+
359
+ if (errorName === 'AbortError') {
360
+ return new OxyAuthenticationError('Sign-in was cancelled by user');
361
+ }
362
+ if (errorName === 'NetworkError') {
363
+ return new OxyAuthenticationError('Network error during sign-in. Please check your connection.');
364
+ }
365
+ if (errorMessage.includes('multiple accounts')) {
366
+ return new OxyAuthenticationError('Please sign out and sign in again to use FedCM with a single account');
367
+ }
368
+ if (errorMessage.includes('retrieving a token') || errorMessage.includes('Error retrieving')) {
369
+ debug.error('FedCM token retrieval error - this may be a browser or IdP configuration issue');
370
+ return new OxyAuthenticationError('Authentication failed. Please try again or use an alternative sign-in method.');
371
+ }
372
+ return error;
287
373
  }
288
374
 
289
375
  /**
@@ -457,15 +543,20 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
457
543
  // If a request is already in progress...
458
544
  if (fedCMRequestInProgress && fedCMRequestPromise) {
459
545
  debug.log('Request already in progress, waiting...');
460
- // If current request is silent and new request is interactive,
461
- // wait for silent to finish, then make the interactive request
546
+ // If the in-flight request is SILENT and this new one is INTERACTIVE,
547
+ // abort the silent and proceed immediately. The silent round-trip can be
548
+ // slow (it runs on page load and may stall in the browser), and a user who
549
+ // just clicked "Sign In" must never be made to wait on — or be blocked by —
550
+ // it. Awaiting the silent here is what previously let a hung silent
551
+ // request deadlock the sign-in button, so we deliberately do NOT await it:
552
+ // we abort it (its own `finally` resets the lock as it settles) and fall
553
+ // through to start the interactive request synchronously below.
462
554
  if (currentMediationMode === 'silent' && isInteractive) {
463
- try {
464
- await fedCMRequestPromise;
465
- } catch {
466
- // Ignore silent request errors
467
- }
468
- // Now fall through to make the interactive request
555
+ debug.log('Aborting in-flight silent request to make way for interactive request');
556
+ fedCMActiveController?.abort();
557
+ // Fall through. The interactive request synchronously overwrites the
558
+ // lock globals (below); the aborted silent's `finally` uses identity
559
+ // guards so it cannot later clobber this interactive request's state.
469
560
  } else {
470
561
  // Same type of request - wait for the existing one
471
562
  try {
@@ -479,10 +570,17 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
479
570
  fedCMRequestInProgress = true;
480
571
  currentMediationMode = requestedMediation;
481
572
  const controller = new AbortController();
482
- // Use shorter timeout for silent mediation since it should be quick
573
+ fedCMActiveController = controller;
574
+ // Use shorter timeout for silent mediation since it should be quick.
575
+ // The timeout constants are static on the composed class; read them off the
576
+ // most-derived constructor through a typed cast (not `any`).
577
+ const timeoutCtor = this.constructor as typeof OxyServicesBase & {
578
+ FEDCM_SILENT_TIMEOUT: number;
579
+ FEDCM_TIMEOUT: number;
580
+ };
483
581
  const timeoutMs = requestedMediation === 'silent'
484
- ? (this.constructor as any).FEDCM_SILENT_TIMEOUT
485
- : (this.constructor as any).FEDCM_TIMEOUT;
582
+ ? timeoutCtor.FEDCM_SILENT_TIMEOUT
583
+ : timeoutCtor.FEDCM_TIMEOUT;
486
584
  const timeout = setTimeout(() => {
487
585
  debug.log('Request timed out after', timeoutMs, 'ms (mediation:', requestedMediation + ')');
488
586
  controller.abort();
@@ -562,9 +660,20 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
562
660
  throw error;
563
661
  } finally {
564
662
  clearTimeout(timeout);
565
- fedCMRequestInProgress = false;
566
- fedCMRequestPromise = null;
567
- currentMediationMode = null;
663
+ // Only reset the shared lock if it still belongs to THIS request. When an
664
+ // interactive request aborts a slow silent one, the silent settles (and
665
+ // runs this `finally`) AFTER the interactive has already taken over the
666
+ // lock and installed its own controller/promise. Guarding on identity
667
+ // (`fedCMActiveController === controller`) ensures the settling silent
668
+ // cannot null out the interactive request's in-progress state. The
669
+ // request that still owns the lock clears it; the superseded one is a
670
+ // no-op here.
671
+ if (fedCMActiveController === controller) {
672
+ fedCMRequestInProgress = false;
673
+ fedCMRequestPromise = null;
674
+ currentMediationMode = null;
675
+ fedCMActiveController = null;
676
+ }
568
677
  }
569
678
  })();
570
679
 
@@ -321,3 +321,234 @@ describe('OxyServices FedCM mode enum (active/passive)', () => {
321
321
  expect(call.identity.mode).toBeUndefined();
322
322
  });
323
323
  });
324
+
325
+ /**
326
+ * Stale-loginHint clear-and-retry regression tests.
327
+ *
328
+ * A loginHint left over from a previously-signed-in/test account (persisted in
329
+ * `oxy_fedcm_login_hint`) that matches NO account at the IdP makes Chrome
330
+ * filter out every account, grey it in the chooser, and reject
331
+ * `navigator.credentials.get` — indistinguishable from a user cancel. The
332
+ * interactive flow must recover by clearing the bad hint and retrying ONCE with
333
+ * no hint, so the genuinely available account becomes selectable again. These
334
+ * tests lock that behaviour in.
335
+ */
336
+ describe('OxyServices FedCM stale loginHint clear-and-retry', () => {
337
+ afterEach(() => {
338
+ clearBrowserGlobals();
339
+ jest.restoreAllMocks();
340
+ });
341
+
342
+ it('clears a stale stored hint and retries the get() once with no hint, then succeeds', async () => {
343
+ const hintsSeen: Array<string | undefined> = [];
344
+ installBrowserGlobals({
345
+ credentialsGet: async (opts) => {
346
+ const hint = opts.identity.providers[0].loginHint;
347
+ hintsSeen.push(hint);
348
+ if (hint) {
349
+ // First attempt carries the stale stored hint → Chrome filtered out
350
+ // every account and rejected the request (NotAllowedError).
351
+ const err = new Error('Accounts were received, but none matched the login hint.');
352
+ err.name = 'NotAllowedError';
353
+ throw err;
354
+ }
355
+ // Retry with NO hint → the available account resolves.
356
+ return { type: 'identity', token: 'recovered-id-token', isAutoSelected: false };
357
+ },
358
+ });
359
+
360
+ const oxy = new OxyServices({ baseURL: 'https://api.oxy.so' });
361
+ // Seed a stale hint in localStorage (a previously-signed-in/test account).
362
+ localStorage.setItem('oxy_fedcm_login_hint', 'stale-user-id');
363
+
364
+ const exchanged: string[] = [];
365
+ mintAndExchange(oxy, exchanged);
366
+
367
+ const session = await oxy.signInWithFedCM();
368
+
369
+ // The first get() saw the stale hint; the second saw none.
370
+ expect(hintsSeen).toEqual(['stale-user-id', undefined]);
371
+ // The token from the hint-less retry was exchanged for a session.
372
+ expect(session.sessionId).toBe('sess_mode');
373
+ expect(exchanged).toEqual(['recovered-id-token']);
374
+ // The stale hint was cleared and replaced with the freshly signed-in id.
375
+ expect(localStorage.getItem('oxy_fedcm_login_hint')).toBe('user_mode');
376
+ });
377
+
378
+ it('does NOT retry when there was no stored hint (a genuine cancel surfaces)', async () => {
379
+ let callCount = 0;
380
+ installBrowserGlobals({
381
+ credentialsGet: async () => {
382
+ callCount += 1;
383
+ const err = new Error('User cancelled the sign-in.');
384
+ err.name = 'NotAllowedError';
385
+ throw err;
386
+ },
387
+ });
388
+
389
+ const oxy = new OxyServices({ baseURL: 'https://api.oxy.so' });
390
+ // No hint in storage → a NotAllowedError is a real cancel, not a mismatch,
391
+ // so the error must surface (no clear-and-retry).
392
+ jest.spyOn(oxy, 'makeRequest').mockImplementation(async (_method: string, url: string) => {
393
+ if (url === '/fedcm/nonce') {
394
+ return { nonce: 'n', expiresAt: new Date(Date.now() + 60000).toISOString() } as never;
395
+ }
396
+ throw new Error(`unexpected request to ${url}`);
397
+ });
398
+
399
+ await expect(oxy.signInWithFedCM()).rejects.toThrow('User cancelled the sign-in.');
400
+ // Exactly one attempt — no clear-and-retry without a stored hint.
401
+ expect(callCount).toBe(1);
402
+ });
403
+
404
+ it('does NOT clear or retry a caller-supplied loginHint (only stored hints are cleared)', async () => {
405
+ let callCount = 0;
406
+ installBrowserGlobals({
407
+ credentialsGet: async () => {
408
+ callCount += 1;
409
+ const err = new Error('Accounts were received, but none matched the login hint.');
410
+ err.name = 'NotAllowedError';
411
+ throw err;
412
+ },
413
+ });
414
+
415
+ const oxy = new OxyServices({ baseURL: 'https://api.oxy.so' });
416
+ // A leftover stored hint must be untouched: the caller explicitly chose the
417
+ // hint, so we must not silently discard it nor retry behind their back.
418
+ localStorage.setItem('oxy_fedcm_login_hint', 'persisted-hint');
419
+ jest.spyOn(oxy, 'makeRequest').mockImplementation(async (_method: string, url: string) => {
420
+ if (url === '/fedcm/nonce') {
421
+ return { nonce: 'n', expiresAt: new Date(Date.now() + 60000).toISOString() } as never;
422
+ }
423
+ throw new Error(`unexpected request to ${url}`);
424
+ });
425
+
426
+ await expect(oxy.signInWithFedCM({ loginHint: 'caller-hint' })).rejects.toBeTruthy();
427
+ // Exactly one attempt — caller-supplied hints are never auto-cleared/retried.
428
+ expect(callCount).toBe(1);
429
+ // The stored hint was left intact.
430
+ expect(localStorage.getItem('oxy_fedcm_login_hint')).toBe('persisted-hint');
431
+ });
432
+ });
433
+
434
+ /**
435
+ * FedCM single-flight lock: interactive-aborts-silent regression tests.
436
+ *
437
+ * FedCM only allows one `navigator.credentials.get` at a time. Silent SSO runs
438
+ * on page load and the real round-trip can be slow (or stall in the browser).
439
+ * If an INTERACTIVE request (the user clicked "Sign In") arrives while a SILENT
440
+ * one is still in flight, it must NOT wait on the silent — awaiting a hung
441
+ * silent request previously deadlocked the sign-in button. Instead it aborts the
442
+ * in-flight silent and proceeds immediately. These tests lock that in, and pin
443
+ * the silent timeout so the on-load silent round-trip has enough budget.
444
+ */
445
+
446
+ // `navigator.credentials.get` receives an AbortSignal we want to observe in the
447
+ // lock tests, which the shared `CredentialGetCall` shape omits. Model it here.
448
+ interface CredentialGetCallWithSignal {
449
+ identity: { providers: Array<{ loginHint?: string }>; mode?: string };
450
+ mediation: string;
451
+ signal?: AbortSignal;
452
+ }
453
+
454
+ describe('OxyServices FedCM single-flight lock (interactive aborts silent)', () => {
455
+ afterEach(() => {
456
+ clearBrowserGlobals();
457
+ jest.restoreAllMocks();
458
+ });
459
+
460
+ it('aborts an in-progress silent request and proceeds with the interactive one', async () => {
461
+ let silentSignal: AbortSignal | undefined;
462
+ let silentAborted = false;
463
+ let interactiveRan = false;
464
+
465
+ const store = new Map<string, string>();
466
+ const localStorageStub = {
467
+ getItem: (k: string) => (store.has(k) ? (store.get(k) as string) : null),
468
+ setItem: (k: string, v: string) => { store.set(k, v); },
469
+ removeItem: (k: string) => { store.delete(k); },
470
+ };
471
+
472
+ const credentialsGet = (opts: CredentialGetCallWithSignal): Promise<unknown> => {
473
+ if (opts.mediation === 'silent') {
474
+ // The silent request HANGS: it only settles when its signal is aborted,
475
+ // exactly like a real slow/stalled silent round-trip. This is what must
476
+ // NOT block the interactive request.
477
+ silentSignal = opts.signal;
478
+ return new Promise((_resolve, reject) => {
479
+ const signal = opts.signal;
480
+ if (!signal) return; // never settles without a signal (shouldn't happen)
481
+ signal.addEventListener('abort', () => {
482
+ silentAborted = true;
483
+ const err = new Error('The operation was aborted.');
484
+ err.name = 'AbortError';
485
+ reject(err);
486
+ });
487
+ });
488
+ }
489
+ // Interactive request resolves immediately with a usable credential.
490
+ interactiveRan = true;
491
+ return Promise.resolve({ type: 'identity', token: 'interactive-token', isAutoSelected: false });
492
+ };
493
+
494
+ const nav = { credentials: { get: (opts: CredentialGetCallWithSignal) => credentialsGet(opts) } };
495
+ const win = {
496
+ location: { origin: ORIGIN, hostname: 'accounts.oxy.so' },
497
+ IdentityCredential: function IdentityCredential() {},
498
+ navigator: nav,
499
+ localStorage: localStorageStub,
500
+ };
501
+ (globalThis as unknown as { window: unknown }).window = win;
502
+ (globalThis as unknown as { navigator: unknown }).navigator = nav;
503
+ (globalThis as unknown as { localStorage: unknown }).localStorage = localStorageStub;
504
+ (globalThis as unknown as { IdentityCredential: unknown }).IdentityCredential = win.IdentityCredential;
505
+
506
+ const oxy = new OxyServices({ baseURL: 'https://api.oxy.so' });
507
+ const exchanged: string[] = [];
508
+ jest
509
+ .spyOn(oxy, 'makeRequest')
510
+ .mockImplementation(async (_method: string, url: string, data?: unknown) => {
511
+ if (url === '/fedcm/nonce') {
512
+ return { nonce: 'server-nonce', expiresAt: new Date(Date.now() + 60000).toISOString() } as never;
513
+ }
514
+ if (url === '/fedcm/exchange') {
515
+ exchanged.push((data as { id_token: string }).id_token);
516
+ return {
517
+ sessionId: 'sess_lock',
518
+ deviceId: 'dev_lock',
519
+ expiresAt: new Date(Date.now() + 60000).toISOString(),
520
+ accessToken: 'access_lock',
521
+ user: { id: 'user_lock', username: 'tester' },
522
+ } as never;
523
+ }
524
+ throw new Error(`unexpected request to ${url}`);
525
+ });
526
+
527
+ // Kick off the silent request (it will hang) WITHOUT awaiting it.
528
+ const silentPromise = oxy.silentSignInWithFedCM();
529
+ // Let the silent request reach navigator.credentials.get and register its
530
+ // abort listener (it awaits the nonce mint first).
531
+ await new Promise((resolve) => setTimeout(resolve, 0));
532
+ expect(silentSignal).toBeDefined();
533
+ expect(silentAborted).toBe(false);
534
+
535
+ // Now the user clicks "Sign In": the interactive request must abort the
536
+ // hung silent one and complete on its own — never block on it.
537
+ const session = await oxy.signInWithFedCM();
538
+
539
+ expect(silentAborted).toBe(true);
540
+ expect(interactiveRan).toBe(true);
541
+ expect(session.sessionId).toBe('sess_lock');
542
+ expect(exchanged).toEqual(['interactive-token']);
543
+
544
+ // The aborted silent resolves cleanly to null (its own error path), never
545
+ // throwing and never leaving the lock stuck.
546
+ await expect(silentPromise).resolves.toBeNull();
547
+ });
548
+ });
549
+
550
+ describe('OxyServices FedCM silent timeout', () => {
551
+ it('uses a 10s silent timeout (enough budget for the real on-load round-trip)', () => {
552
+ expect(OxyServices.FEDCM_SILENT_TIMEOUT).toBe(10000);
553
+ });
554
+ });