@oxyhq/core 1.11.23 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +5 -6
  2. package/dist/cjs/.tsbuildinfo +1 -1
  3. package/dist/cjs/AuthManager.js +678 -4
  4. package/dist/cjs/AuthManagerTypes.js +13 -0
  5. package/dist/cjs/CrossDomainAuth.js +45 -3
  6. package/dist/cjs/OxyServices.base.js +16 -0
  7. package/dist/cjs/i18n/locales/ar-SA.json +83 -0
  8. package/dist/cjs/i18n/locales/ca-ES.json +83 -0
  9. package/dist/cjs/i18n/locales/de-DE.json +83 -0
  10. package/dist/cjs/i18n/locales/en-US.json +83 -0
  11. package/dist/cjs/i18n/locales/es-ES.json +99 -4
  12. package/dist/cjs/i18n/locales/fr-FR.json +83 -0
  13. package/dist/cjs/i18n/locales/it-IT.json +83 -0
  14. package/dist/cjs/i18n/locales/ja-JP.json +83 -0
  15. package/dist/cjs/i18n/locales/ko-KR.json +83 -0
  16. package/dist/cjs/i18n/locales/locales/ar-SA.json +83 -1
  17. package/dist/cjs/i18n/locales/locales/ca-ES.json +83 -1
  18. package/dist/cjs/i18n/locales/locales/de-DE.json +83 -1
  19. package/dist/cjs/i18n/locales/locales/en-US.json +83 -0
  20. package/dist/cjs/i18n/locales/locales/es-ES.json +99 -4
  21. package/dist/cjs/i18n/locales/locales/fr-FR.json +83 -1
  22. package/dist/cjs/i18n/locales/locales/it-IT.json +83 -1
  23. package/dist/cjs/i18n/locales/locales/ja-JP.json +200 -117
  24. package/dist/cjs/i18n/locales/locales/ko-KR.json +83 -1
  25. package/dist/cjs/i18n/locales/locales/pt-PT.json +83 -1
  26. package/dist/cjs/i18n/locales/locales/zh-CN.json +83 -1
  27. package/dist/cjs/i18n/locales/pt-PT.json +83 -0
  28. package/dist/cjs/i18n/locales/zh-CN.json +83 -0
  29. package/dist/cjs/index.js +114 -57
  30. package/dist/cjs/mixins/OxyServices.auth.js +235 -0
  31. package/dist/cjs/mixins/OxyServices.fedcm.js +205 -73
  32. package/dist/cjs/mixins/OxyServices.popup.js +61 -1
  33. package/dist/cjs/mixins/OxyServices.user.js +18 -0
  34. package/dist/cjs/utils/accountUtils.js +64 -1
  35. package/dist/esm/.tsbuildinfo +1 -1
  36. package/dist/esm/AuthManager.js +678 -4
  37. package/dist/esm/AuthManagerTypes.js +12 -0
  38. package/dist/esm/CrossDomainAuth.js +45 -3
  39. package/dist/esm/OxyServices.base.js +16 -0
  40. package/dist/esm/i18n/locales/ar-SA.json +83 -0
  41. package/dist/esm/i18n/locales/ca-ES.json +83 -0
  42. package/dist/esm/i18n/locales/de-DE.json +83 -0
  43. package/dist/esm/i18n/locales/en-US.json +83 -0
  44. package/dist/esm/i18n/locales/es-ES.json +99 -4
  45. package/dist/esm/i18n/locales/fr-FR.json +83 -0
  46. package/dist/esm/i18n/locales/it-IT.json +83 -0
  47. package/dist/esm/i18n/locales/ja-JP.json +83 -0
  48. package/dist/esm/i18n/locales/ko-KR.json +83 -0
  49. package/dist/esm/i18n/locales/locales/ar-SA.json +83 -1
  50. package/dist/esm/i18n/locales/locales/ca-ES.json +83 -1
  51. package/dist/esm/i18n/locales/locales/de-DE.json +83 -1
  52. package/dist/esm/i18n/locales/locales/en-US.json +83 -0
  53. package/dist/esm/i18n/locales/locales/es-ES.json +99 -4
  54. package/dist/esm/i18n/locales/locales/fr-FR.json +83 -1
  55. package/dist/esm/i18n/locales/locales/it-IT.json +83 -1
  56. package/dist/esm/i18n/locales/locales/ja-JP.json +200 -117
  57. package/dist/esm/i18n/locales/locales/ko-KR.json +83 -1
  58. package/dist/esm/i18n/locales/locales/pt-PT.json +83 -1
  59. package/dist/esm/i18n/locales/locales/zh-CN.json +83 -1
  60. package/dist/esm/i18n/locales/pt-PT.json +83 -0
  61. package/dist/esm/i18n/locales/zh-CN.json +83 -0
  62. package/dist/esm/index.js +69 -26
  63. package/dist/esm/mixins/OxyServices.auth.js +235 -0
  64. package/dist/esm/mixins/OxyServices.fedcm.js +205 -73
  65. package/dist/esm/mixins/OxyServices.popup.js +61 -1
  66. package/dist/esm/mixins/OxyServices.user.js +18 -0
  67. package/dist/esm/utils/accountUtils.js +61 -0
  68. package/dist/types/.tsbuildinfo +1 -1
  69. package/dist/types/AuthManager.d.ts +243 -3
  70. package/dist/types/AuthManagerTypes.d.ts +68 -0
  71. package/dist/types/CrossDomainAuth.d.ts +23 -0
  72. package/dist/types/OxyServices.base.d.ts +14 -0
  73. package/dist/types/OxyServices.d.ts +16 -0
  74. package/dist/types/index.d.ts +28 -17
  75. package/dist/types/mixins/OxyServices.analytics.d.ts +1 -0
  76. package/dist/types/mixins/OxyServices.appData.d.ts +1 -0
  77. package/dist/types/mixins/OxyServices.assets.d.ts +4 -1
  78. package/dist/types/mixins/OxyServices.auth.d.ts +73 -1
  79. package/dist/types/mixins/OxyServices.contacts.d.ts +1 -0
  80. package/dist/types/mixins/OxyServices.developer.d.ts +1 -0
  81. package/dist/types/mixins/OxyServices.devices.d.ts +1 -0
  82. package/dist/types/mixins/OxyServices.features.d.ts +2 -5
  83. package/dist/types/mixins/OxyServices.fedcm.d.ts +53 -1
  84. package/dist/types/mixins/OxyServices.karma.d.ts +1 -0
  85. package/dist/types/mixins/OxyServices.language.d.ts +1 -0
  86. package/dist/types/mixins/OxyServices.location.d.ts +1 -0
  87. package/dist/types/mixins/OxyServices.managedAccounts.d.ts +1 -0
  88. package/dist/types/mixins/OxyServices.payment.d.ts +1 -0
  89. package/dist/types/mixins/OxyServices.popup.d.ts +40 -0
  90. package/dist/types/mixins/OxyServices.privacy.d.ts +1 -0
  91. package/dist/types/mixins/OxyServices.redirect.d.ts +1 -0
  92. package/dist/types/mixins/OxyServices.security.d.ts +1 -0
  93. package/dist/types/mixins/OxyServices.topics.d.ts +1 -0
  94. package/dist/types/mixins/OxyServices.user.d.ts +16 -1
  95. package/dist/types/mixins/OxyServices.utility.d.ts +1 -0
  96. package/dist/types/models/interfaces.d.ts +98 -0
  97. package/dist/types/models/session.d.ts +8 -0
  98. package/dist/types/utils/accountUtils.d.ts +33 -0
  99. package/package.json +9 -18
  100. package/src/AuthManager.ts +776 -7
  101. package/src/AuthManagerTypes.ts +72 -0
  102. package/src/CrossDomainAuth.ts +54 -3
  103. package/src/OxyServices.base.ts +17 -0
  104. package/src/OxyServices.ts +17 -0
  105. package/src/__tests__/authManager.cookiePath.test.ts +339 -0
  106. package/src/__tests__/authManager.security.test.ts +342 -0
  107. package/src/__tests__/crossDomainAuth.test.ts +191 -0
  108. package/src/i18n/locales/ar-SA.json +83 -1
  109. package/src/i18n/locales/ca-ES.json +83 -1
  110. package/src/i18n/locales/de-DE.json +83 -1
  111. package/src/i18n/locales/en-US.json +83 -0
  112. package/src/i18n/locales/es-ES.json +99 -4
  113. package/src/i18n/locales/fr-FR.json +83 -1
  114. package/src/i18n/locales/it-IT.json +83 -1
  115. package/src/i18n/locales/ja-JP.json +200 -117
  116. package/src/i18n/locales/ko-KR.json +83 -1
  117. package/src/i18n/locales/pt-PT.json +83 -1
  118. package/src/i18n/locales/zh-CN.json +83 -1
  119. package/src/index.ts +295 -112
  120. package/src/mixins/OxyServices.auth.ts +268 -1
  121. package/src/mixins/OxyServices.fedcm.ts +250 -78
  122. package/src/mixins/OxyServices.popup.ts +79 -1
  123. package/src/mixins/OxyServices.user.ts +33 -1
  124. package/src/mixins/__tests__/fedcm.test.ts +231 -0
  125. package/src/mixins/__tests__/popup.test.ts +307 -0
  126. package/src/mixins/__tests__/sessionBaseUrl.test.ts +61 -0
  127. package/src/models/interfaces.ts +116 -0
  128. package/src/models/session.ts +8 -0
  129. package/src/utils/accountUtils.ts +84 -0
  130. package/dist/cjs/crypto/index.js +0 -22
  131. package/dist/cjs/shared/index.js +0 -70
  132. package/dist/cjs/utils/index.js +0 -26
  133. package/dist/esm/crypto/index.js +0 -13
  134. package/dist/esm/shared/index.js +0 -31
  135. package/dist/esm/utils/index.js +0 -7
  136. package/dist/types/crypto/index.d.ts +0 -11
  137. package/dist/types/shared/index.d.ts +0 -28
  138. package/dist/types/utils/index.d.ts +0 -6
  139. package/src/crypto/index.ts +0 -30
  140. package/src/shared/index.ts +0 -82
  141. package/src/utils/index.ts +0 -21
@@ -385,6 +385,241 @@ function OxyServicesAuthMixin(Base) {
385
385
  throw this.handleError(error);
386
386
  }
387
387
  }
388
+ /**
389
+ * Refresh every device-local refresh-cookie slot in a single round trip
390
+ * (Google-style multi-account rebuild).
391
+ *
392
+ * Calls `POST {sessionBaseUrl}/auth/refresh-all` with `credentials: 'include'`
393
+ * and NO bearer. The browser attaches every `oxy_rt*` cookie it has; the
394
+ * server rotates each in parallel and returns one entry per VALID account.
395
+ *
396
+ * Failure handling:
397
+ * - 401 → no signed-in accounts on this device → returns `{ accounts: [] }`
398
+ * (NOT an error; this is the cold-boot "not signed in" path).
399
+ * - 404 → server is older than the multi-account endpoint. We fall back to
400
+ * `POST /auth/refresh` (single-slot) and wrap its response in the
401
+ * refresh-all shape so callers can treat the two paths uniformly. The
402
+ * fallback entry has `authuser: 0` (the legacy slot maps to slot 0 by
403
+ * convention) and a minimal `user` shape — consumers needing the full
404
+ * user must fetch it separately. Always exactly one account in this
405
+ * shape.
406
+ * - Any other non-2xx → throws via `handleError`.
407
+ *
408
+ * The refresh cookie itself never enters JS — only the rotated access
409
+ * tokens do. Each access token still needs to be planted via
410
+ * `setTokens(...)` (or per-account in-memory storage) at the consumer.
411
+ */
412
+ async refreshAllSessions() {
413
+ const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/auth/refresh-all`;
414
+ let response;
415
+ try {
416
+ response = await fetch(url, {
417
+ method: 'POST',
418
+ credentials: 'include',
419
+ headers: { Accept: 'application/json' },
420
+ });
421
+ }
422
+ catch (error) {
423
+ throw this.handleError(error);
424
+ }
425
+ if (response.status === 401) {
426
+ return { accounts: [] };
427
+ }
428
+ if (response.status === 404) {
429
+ // Legacy single-account refresh fallback. Wrap the response so the
430
+ // caller can treat both paths identically.
431
+ const legacy = await this._refreshCookieRaw();
432
+ if (!legacy) {
433
+ return { accounts: [] };
434
+ }
435
+ const fallbackAccount = {
436
+ authuser: 0,
437
+ accessToken: legacy.accessToken,
438
+ expiresAt: legacy.expiresAt,
439
+ sessionId: this._decodeSessionIdFromAccessToken(legacy.accessToken) ?? '',
440
+ // Legacy /auth/refresh does NOT project the user shape; the caller
441
+ // (AuthManager) is expected to hydrate via /users/me after planting.
442
+ user: null,
443
+ };
444
+ return { accounts: [fallbackAccount] };
445
+ }
446
+ if (!response.ok) {
447
+ throw this.handleError(new Error(`Refresh-all failed with HTTP ${response.status}`));
448
+ }
449
+ const payload = (await response.json());
450
+ const raw = Array.isArray(payload.accounts) ? payload.accounts : [];
451
+ const accounts = [];
452
+ for (const entry of raw) {
453
+ if (entry === null || typeof entry !== 'object') {
454
+ continue;
455
+ }
456
+ const e = entry;
457
+ if (!e.accessToken || !e.expiresAt || !e.sessionId || !e.user) {
458
+ continue;
459
+ }
460
+ const userId = e.user.id ?? e.user._id;
461
+ if (!userId || !e.user.username) {
462
+ continue;
463
+ }
464
+ // Normalise the legacy un-suffixed cookie (`authuser: null` on the
465
+ // wire) to slot 0. The SDK surface always operates on numeric indices.
466
+ const authuser = typeof e.authuser === 'number' ? e.authuser : 0;
467
+ accounts.push({
468
+ authuser,
469
+ accessToken: e.accessToken,
470
+ expiresAt: e.expiresAt,
471
+ sessionId: e.sessionId,
472
+ user: {
473
+ id: userId,
474
+ username: e.user.username,
475
+ name: e.user.name,
476
+ avatar: e.user.avatar ?? null,
477
+ email: e.user.email,
478
+ color: e.user.color ?? null,
479
+ },
480
+ });
481
+ }
482
+ return { accounts };
483
+ }
484
+ /**
485
+ * Rotate a single refresh-cookie slot and return the fresh access token.
486
+ *
487
+ * When `authuser` is provided, the server rotates ONLY that slot
488
+ * (`oxy_rt_${authuser}`) — sibling accounts on the same device stay
489
+ * untouched. When omitted, the server picks the lowest indexed slot
490
+ * present (legacy fallback applies). The refresh cookie itself never
491
+ * enters JS.
492
+ *
493
+ * Returns `null` on 401 (no cookie / expired / reused) so the caller can
494
+ * fall through cleanly to the unauthenticated path.
495
+ */
496
+ async refreshTokenViaCookie(opts = {}) {
497
+ const result = await this._refreshCookieRaw(opts.authuser);
498
+ return result;
499
+ }
500
+ /**
501
+ * Sign out a single device-local account by its authuser slot index.
502
+ *
503
+ * Revokes that slot's refresh-token family and deactivates its session;
504
+ * sibling indexed slots stay signed in. The browser-side `oxy_rt_${n}`
505
+ * cookie is cleared by the server's `Set-Cookie` response header.
506
+ */
507
+ async logoutSessionByAuthuser(authuser) {
508
+ const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/auth/logout?authuser=${encodeURIComponent(String(authuser))}`;
509
+ try {
510
+ const response = await fetch(url, {
511
+ method: 'POST',
512
+ credentials: 'include',
513
+ headers: { Accept: 'application/json' },
514
+ });
515
+ if (!response.ok && response.status !== 401) {
516
+ throw new Error(`Logout (authuser=${authuser}) failed with HTTP ${response.status}`);
517
+ }
518
+ }
519
+ catch (error) {
520
+ throw this.handleError(error);
521
+ }
522
+ }
523
+ /**
524
+ * Sign out EVERY device-local account on this device by clearing every
525
+ * presented refresh-cookie slot at once. Revokes every family + clears
526
+ * every slot. Always succeeds (idempotent on unknown/garbage tokens).
527
+ */
528
+ async logoutAllSessionsViaCookie() {
529
+ const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/auth/logout`;
530
+ try {
531
+ const response = await fetch(url, {
532
+ method: 'POST',
533
+ credentials: 'include',
534
+ headers: { Accept: 'application/json' },
535
+ });
536
+ if (!response.ok && response.status !== 401) {
537
+ throw new Error(`Logout-all failed with HTTP ${response.status}`);
538
+ }
539
+ }
540
+ catch (error) {
541
+ throw this.handleError(error);
542
+ }
543
+ }
544
+ /**
545
+ * Internal: raw `POST /auth/refresh[?authuser=N]` call returning the
546
+ * minted access token. Returns `null` on 401 / non-2xx. Used as both the
547
+ * implementation of `refreshTokenViaCookie` and the legacy fallback for
548
+ * `refreshAllSessions` against older servers.
549
+ *
550
+ * @internal
551
+ */
552
+ async _refreshCookieRaw(authuser) {
553
+ const base = this.getSessionBaseUrl().replace(/\/$/, '');
554
+ const url = typeof authuser === 'number'
555
+ ? `${base}/auth/refresh?authuser=${encodeURIComponent(String(authuser))}`
556
+ : `${base}/auth/refresh`;
557
+ let response;
558
+ try {
559
+ response = await fetch(url, {
560
+ method: 'POST',
561
+ credentials: 'include',
562
+ headers: { Accept: 'application/json' },
563
+ });
564
+ }
565
+ catch (error) {
566
+ throw this.handleError(error);
567
+ }
568
+ if (!response.ok) {
569
+ return null;
570
+ }
571
+ const payload = (await response.json());
572
+ if (typeof payload.accessToken !== 'string' || !payload.accessToken) {
573
+ return null;
574
+ }
575
+ const expiresAt = typeof payload.expiresAt === 'string' ? payload.expiresAt : '';
576
+ const respAuthuser = typeof payload.authuser === 'number' ? payload.authuser : null;
577
+ return {
578
+ accessToken: payload.accessToken,
579
+ expiresAt,
580
+ authuser: respAuthuser,
581
+ };
582
+ }
583
+ /**
584
+ * Internal: decode (without verifying) the `sessionId` claim from a
585
+ * server-signed access token. The server already verified the signature;
586
+ * the client only reads the claim to drive multi-session state.
587
+ *
588
+ * @internal
589
+ */
590
+ _decodeSessionIdFromAccessToken(token) {
591
+ if (!token || typeof token !== 'string') {
592
+ return null;
593
+ }
594
+ const segments = token.split('.');
595
+ if (segments.length !== 3) {
596
+ return null;
597
+ }
598
+ const payloadSegment = segments[1];
599
+ if (!payloadSegment) {
600
+ return null;
601
+ }
602
+ try {
603
+ const base64 = payloadSegment.replace(/-/g, '+').replace(/_/g, '/');
604
+ const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), '=');
605
+ if (typeof atob !== 'function') {
606
+ return null;
607
+ }
608
+ const json = decodeURIComponent(atob(padded)
609
+ .split('')
610
+ .map((char) => `%${`00${char.charCodeAt(0).toString(16)}`.slice(-2)}`)
611
+ .join(''));
612
+ const parsed = JSON.parse(json);
613
+ if (parsed === null || typeof parsed !== 'object') {
614
+ return null;
615
+ }
616
+ const claims = parsed;
617
+ return typeof claims.sessionId === 'string' ? claims.sessionId : null;
618
+ }
619
+ catch {
620
+ return null;
621
+ }
622
+ }
388
623
  /**
389
624
  * Get sessions by session ID
390
625
  */
@@ -37,12 +37,44 @@ function isUnknownModeEnumError(error) {
37
37
  ((message.includes('active') || message.includes('passive')) &&
38
38
  (message.includes('enum') || message.includes('not a valid'))));
39
39
  }
40
+ /**
41
+ * Detect a `navigator.credentials.get` rejection that is consistent with
42
+ * "the supplied loginHint matched no account at the IdP".
43
+ *
44
+ * When an RP passes a `loginHint` and the IdP returns accounts but NONE of them
45
+ * declare that hint in their `login_hints`, Chrome filters every account out,
46
+ * greys it in the chooser ("You can't sign in using this account"), logs
47
+ * "Accounts were received, but none matched the login hint…", and ultimately
48
+ * rejects the credential request — surfacing as a `NotAllowedError` /
49
+ * `AbortError` (the same shape as a user-cancelled or timed-out request). A
50
+ * stale hint left over from a previously-signed-in/test account therefore hard
51
+ * -blocks sign-in.
52
+ *
53
+ * We can only safely apply the clear-and-retry recovery when a `loginHint` was
54
+ * actually supplied; without one this is just a normal cancel/timeout and must
55
+ * NOT be retried. Callers gate on `hadLoginHint` before calling this.
56
+ */
57
+ function isPossibleHintMismatchError(error) {
58
+ if (!(error instanceof Error))
59
+ return false;
60
+ // FedCM surfaces a filtered-out / no-eligible-account outcome as
61
+ // NotAllowedError (current Chrome) or AbortError (our own timeout abort while
62
+ // the chooser had no selectable account). Both are indistinguishable from a
63
+ // genuine user cancel at the API level, so the gate on "a hint was supplied"
64
+ // (in the caller) is what makes the retry safe and targeted.
65
+ return error.name === 'NotAllowedError' || error.name === 'AbortError';
66
+ }
40
67
  const FEDCM_LOGIN_HINT_KEY = 'oxy_fedcm_login_hint';
41
68
  // Global lock to prevent concurrent FedCM requests
42
69
  // FedCM only allows one navigator.credentials.get request at a time
43
70
  let fedCMRequestInProgress = false;
44
71
  let fedCMRequestPromise = null;
45
72
  let currentMediationMode = null;
73
+ // AbortController of the in-flight request, exposed at module scope so an
74
+ // arriving INTERACTIVE request can abort a slow/hung SILENT one instead of
75
+ // blocking on it (see requestIdentityCredential). Set when a request starts,
76
+ // cleared in that request's `finally`.
77
+ let fedCMActiveController = null;
46
78
  /**
47
79
  * Federated Credential Management (FedCM) Authentication Mixin
48
80
  *
@@ -71,9 +103,12 @@ function OxyServicesFedCMMixin(Base) {
71
103
  super(...args);
72
104
  }
73
105
  resolveFedcmConfigUrl() {
106
+ // `DEFAULT_CONFIG_URL` is a static on the composed class; read it off the
107
+ // most-derived constructor through a typed cast (not `any`).
108
+ const configCtor = this.constructor;
74
109
  return this.config.authWebUrl
75
110
  ? `${this.config.authWebUrl}/fedcm.json`
76
- : this.constructor.DEFAULT_CONFIG_URL;
111
+ : configCtor.DEFAULT_CONFIG_URL;
77
112
  }
78
113
  /**
79
114
  * Check if FedCM is supported in the current browser
@@ -117,67 +152,104 @@ function OxyServicesFedCMMixin(Base) {
117
152
  if (!this.isFedCMSupported()) {
118
153
  throw new OxyServices_errors_1.OxyAuthenticationError('FedCM not supported in this browser. Please update your browser or use an alternative sign-in method.');
119
154
  }
155
+ // Use provided loginHint, or fall back to stored last-used account ID.
156
+ const initialLoginHint = options.loginHint || this.getStoredLoginHint();
120
157
  try {
121
- // Prefer a server-minted, origin-bound nonce so the downstream
122
- // `/fedcm/exchange` can validate it. A caller-supplied nonce is
123
- // respected as-is for advanced use cases.
124
- const nonce = options.nonce || (await this.getFedcmNonce());
125
- const clientId = this.getClientId();
126
- // Use provided loginHint, or fall back to stored last-used account ID
127
- const loginHint = options.loginHint || this.getStoredLoginHint();
128
- debug.log('Interactive sign-in: Requesting credential for', clientId, loginHint ? `(hint: ${loginHint})` : '');
129
- // Request credential from browser's native identity flow.
130
- // mode: 'active' signals this is a user-gesture-initiated (button) flow.
131
- // 'active' is the current W3C spec value; requestIdentityCredential
132
- // transparently retries with the legacy 'button' value for Chrome 125–131.
133
- const credential = await this.requestIdentityCredential({
134
- configURL: this.resolveFedcmConfigUrl(),
135
- clientId,
136
- nonce,
137
- context: options.context,
138
- loginHint,
139
- mode: 'active',
140
- });
141
- if (!credential || !credential.token) {
142
- throw new OxyServices_errors_1.OxyAuthenticationError('No credential received from browser');
143
- }
144
- debug.log('Interactive sign-in: Got credential, exchanging for session');
145
- // Exchange FedCM ID token for Oxy session
146
- const session = await this.exchangeIdTokenForSession(credential.token);
147
- // Store access token in HttpService. `accessToken`/`refreshToken` are
148
- // declared optional on SessionLoginResponse; default the refresh token to
149
- // an empty string when the exchange did not return one.
150
- if (session?.accessToken) {
151
- this.httpService.setTokens(session.accessToken, session.refreshToken ?? '');
152
- }
153
- // Store the user ID as loginHint for future FedCM requests
154
- if (session?.user?.id) {
155
- this.storeLoginHint(session.user.id);
156
- }
157
- debug.log('Interactive sign-in: Success!', { userId: session?.user?.id });
158
- return session;
158
+ return await this.attemptInteractiveSignIn(options, initialLoginHint);
159
159
  }
160
160
  catch (error) {
161
- debug.log('Interactive sign-in failed:', error);
162
- const errorMessage = error instanceof Error ? error.message : String(error);
163
- // FedCM aborts/network failures surface as DOMException/Error instances,
164
- // both of which carry a `name`. Anything else has no meaningful name.
165
- const errorName = error instanceof Error ? error.name : '';
166
- if (errorName === 'AbortError') {
167
- throw new OxyServices_errors_1.OxyAuthenticationError('Sign-in was cancelled by user');
168
- }
169
- if (errorName === 'NetworkError') {
170
- throw new OxyServices_errors_1.OxyAuthenticationError('Network error during sign-in. Please check your connection.');
161
+ // A STALE loginHint (e.g. left over from a previously-signed-in or test
162
+ // account) that matches no account at the IdP makes Chrome filter out
163
+ // every account and reject the request — indistinguishable from a user
164
+ // cancel. When that happens AND we supplied a hint, clear the bad hint
165
+ // and retry the credential request ONCE with no hint, which lets the
166
+ // chooser surface the genuinely available account(s). We only do this for
167
+ // a hint we pulled from storage (not a caller-supplied one), and only
168
+ // once, so a real cancel never loops.
169
+ const usedStoredHint = !!initialLoginHint && !options.loginHint;
170
+ if (usedStoredHint && isPossibleHintMismatchError(error)) {
171
+ debug.log('Interactive sign-in: stored loginHint matched no account; clearing it and retrying without a hint');
172
+ this.clearLoginHint();
173
+ return await this.attemptInteractiveSignIn(options, undefined);
171
174
  }
172
- if (errorMessage.includes('multiple accounts')) {
173
- throw new OxyServices_errors_1.OxyAuthenticationError('Please sign out and sign in again to use FedCM with a single account');
174
- }
175
- if (errorMessage.includes('retrieving a token') || errorMessage.includes('Error retrieving')) {
176
- debug.error('FedCM token retrieval error - this may be a browser or IdP configuration issue');
177
- throw new OxyServices_errors_1.OxyAuthenticationError('Authentication failed. Please try again or use an alternative sign-in method.');
178
- }
179
- throw error;
175
+ throw this.normalizeInteractiveSignInError(error);
176
+ }
177
+ }
178
+ /**
179
+ * Run a single interactive FedCM credential request + token exchange for the
180
+ * given (possibly undefined) loginHint. A successful exchange plants the
181
+ * access token and persists the user id as the future loginHint — the hint is
182
+ * therefore only ever stored after a GENUINELY successful sign-in, never
183
+ * speculatively.
184
+ *
185
+ * @private
186
+ */
187
+ async attemptInteractiveSignIn(options, loginHint) {
188
+ // Prefer a server-minted, origin-bound nonce so the downstream
189
+ // `/fedcm/exchange` can validate it. A caller-supplied nonce is
190
+ // respected as-is for advanced use cases.
191
+ const nonce = options.nonce || (await this.getFedcmNonce());
192
+ const clientId = this.getClientId();
193
+ debug.log('Interactive sign-in: Requesting credential for', clientId, loginHint ? `(hint: ${loginHint})` : '');
194
+ // Request credential from browser's native identity flow.
195
+ // mode: 'active' signals this is a user-gesture-initiated (button) flow.
196
+ // 'active' is the current W3C spec value; requestIdentityCredential
197
+ // transparently retries with the legacy 'button' value for Chrome 125–131.
198
+ const credential = await this.requestIdentityCredential({
199
+ configURL: this.resolveFedcmConfigUrl(),
200
+ clientId,
201
+ nonce,
202
+ context: options.context,
203
+ loginHint,
204
+ mode: 'active',
205
+ });
206
+ if (!credential || !credential.token) {
207
+ throw new OxyServices_errors_1.OxyAuthenticationError('No credential received from browser');
208
+ }
209
+ debug.log('Interactive sign-in: Got credential, exchanging for session');
210
+ // Exchange FedCM ID token for Oxy session
211
+ const session = await this.exchangeIdTokenForSession(credential.token);
212
+ // Store access token in HttpService. `accessToken`/`refreshToken` are
213
+ // declared optional on SessionLoginResponse; default the refresh token to
214
+ // an empty string when the exchange did not return one.
215
+ if (session?.accessToken) {
216
+ this.httpService.setTokens(session.accessToken, session.refreshToken ?? '');
180
217
  }
218
+ // Store the user ID as loginHint for future FedCM requests — only now, after
219
+ // a real successful exchange, so we never persist a hint that cannot resolve.
220
+ if (session?.user?.id) {
221
+ this.storeLoginHint(session.user.id);
222
+ }
223
+ debug.log('Interactive sign-in: Success!', { userId: session?.user?.id });
224
+ return session;
225
+ }
226
+ /**
227
+ * Map a raw FedCM/exchange failure to a user-facing {@link OxyAuthenticationError}
228
+ * (or pass it through). Extracted so the clear-and-retry path can reuse the
229
+ * exact same error normalisation as the first attempt.
230
+ *
231
+ * @private
232
+ */
233
+ normalizeInteractiveSignInError(error) {
234
+ debug.log('Interactive sign-in failed:', error);
235
+ const errorMessage = error instanceof Error ? error.message : String(error);
236
+ // FedCM aborts/network failures surface as DOMException/Error instances,
237
+ // both of which carry a `name`. Anything else has no meaningful name.
238
+ const errorName = error instanceof Error ? error.name : '';
239
+ if (errorName === 'AbortError') {
240
+ return new OxyServices_errors_1.OxyAuthenticationError('Sign-in was cancelled by user');
241
+ }
242
+ if (errorName === 'NetworkError') {
243
+ return new OxyServices_errors_1.OxyAuthenticationError('Network error during sign-in. Please check your connection.');
244
+ }
245
+ if (errorMessage.includes('multiple accounts')) {
246
+ return new OxyServices_errors_1.OxyAuthenticationError('Please sign out and sign in again to use FedCM with a single account');
247
+ }
248
+ if (errorMessage.includes('retrieving a token') || errorMessage.includes('Error retrieving')) {
249
+ debug.error('FedCM token retrieval error - this may be a browser or IdP configuration issue');
250
+ return new OxyServices_errors_1.OxyAuthenticationError('Authentication failed. Please try again or use an alternative sign-in method.');
251
+ }
252
+ return error;
181
253
  }
182
254
  /**
183
255
  * Silent sign-in using FedCM
@@ -319,16 +391,20 @@ function OxyServicesFedCMMixin(Base) {
319
391
  // If a request is already in progress...
320
392
  if (fedCMRequestInProgress && fedCMRequestPromise) {
321
393
  debug.log('Request already in progress, waiting...');
322
- // If current request is silent and new request is interactive,
323
- // wait for silent to finish, then make the interactive request
394
+ // If the in-flight request is SILENT and this new one is INTERACTIVE,
395
+ // abort the silent and proceed immediately. The silent round-trip can be
396
+ // slow (it runs on page load and may stall in the browser), and a user who
397
+ // just clicked "Sign In" must never be made to wait on — or be blocked by —
398
+ // it. Awaiting the silent here is what previously let a hung silent
399
+ // request deadlock the sign-in button, so we deliberately do NOT await it:
400
+ // we abort it (its own `finally` resets the lock as it settles) and fall
401
+ // through to start the interactive request synchronously below.
324
402
  if (currentMediationMode === 'silent' && isInteractive) {
325
- try {
326
- await fedCMRequestPromise;
327
- }
328
- catch {
329
- // Ignore silent request errors
330
- }
331
- // Now fall through to make the interactive request
403
+ debug.log('Aborting in-flight silent request to make way for interactive request');
404
+ fedCMActiveController?.abort();
405
+ // Fall through. The interactive request synchronously overwrites the
406
+ // lock globals (below); the aborted silent's `finally` uses identity
407
+ // guards so it cannot later clobber this interactive request's state.
332
408
  }
333
409
  else {
334
410
  // Same type of request - wait for the existing one
@@ -343,10 +419,14 @@ function OxyServicesFedCMMixin(Base) {
343
419
  fedCMRequestInProgress = true;
344
420
  currentMediationMode = requestedMediation;
345
421
  const controller = new AbortController();
346
- // Use shorter timeout for silent mediation since it should be quick
422
+ fedCMActiveController = controller;
423
+ // Use shorter timeout for silent mediation since it should be quick.
424
+ // The timeout constants are static on the composed class; read them off the
425
+ // most-derived constructor through a typed cast (not `any`).
426
+ const timeoutCtor = this.constructor;
347
427
  const timeoutMs = requestedMediation === 'silent'
348
- ? this.constructor.FEDCM_SILENT_TIMEOUT
349
- : this.constructor.FEDCM_TIMEOUT;
428
+ ? timeoutCtor.FEDCM_SILENT_TIMEOUT
429
+ : timeoutCtor.FEDCM_TIMEOUT;
350
430
  const timeout = setTimeout(() => {
351
431
  debug.log('Request timed out after', timeoutMs, 'ms (mediation:', requestedMediation + ')');
352
432
  controller.abort();
@@ -423,9 +503,20 @@ function OxyServicesFedCMMixin(Base) {
423
503
  }
424
504
  finally {
425
505
  clearTimeout(timeout);
426
- fedCMRequestInProgress = false;
427
- fedCMRequestPromise = null;
428
- currentMediationMode = null;
506
+ // Only reset the shared lock if it still belongs to THIS request. When an
507
+ // interactive request aborts a slow silent one, the silent settles (and
508
+ // runs this `finally`) AFTER the interactive has already taken over the
509
+ // lock and installed its own controller/promise. Guarding on identity
510
+ // (`fedCMActiveController === controller`) ensures the settling silent
511
+ // cannot null out the interactive request's in-progress state. The
512
+ // request that still owns the lock clears it; the superseded one is a
513
+ // no-op here.
514
+ if (fedCMActiveController === controller) {
515
+ fedCMRequestInProgress = false;
516
+ fedCMRequestPromise = null;
517
+ currentMediationMode = null;
518
+ fedCMActiveController = null;
519
+ }
429
520
  }
430
521
  })();
431
522
  return fedCMRequestPromise;
@@ -610,11 +701,52 @@ function OxyServicesFedCMMixin(Base) {
610
701
  // Storage blocked
611
702
  }
612
703
  }
704
+ /**
705
+ * List the authenticated user's authorized RP apps.
706
+ *
707
+ * Returns the intersection of the user's FedCM grants and the currently-
708
+ * approved RP catalog — what powers the "Connected apps" management UI in
709
+ * @oxyhq/services. Requires a real user session; service tokens are
710
+ * rejected by the underlying endpoint.
711
+ */
712
+ async listAuthorizedApps() {
713
+ try {
714
+ const response = await this.makeRequest('GET', '/fedcm/me/authorized-apps', undefined, {
715
+ cache: true,
716
+ cacheTTL: 30 * 1000, // 30 second cache — short, this drives a manageable UI
717
+ });
718
+ return response.apps ?? [];
719
+ }
720
+ catch (error) {
721
+ throw this.handleError(error);
722
+ }
723
+ }
724
+ /**
725
+ * Revoke the authenticated user's authorization for a specific RP origin.
726
+ *
727
+ * The next FedCM sign-in from that origin will require explicit re-consent.
728
+ * The corresponding cache entry is invalidated so a subsequent
729
+ * `listAuthorizedApps()` call sees fresh data.
730
+ */
731
+ async revokeAuthorizedApp(origin) {
732
+ try {
733
+ await this.makeRequest('DELETE', `/fedcm/me/authorized-apps/${encodeURIComponent(origin)}`, undefined, { cache: false });
734
+ this.clearCacheEntry('GET:/fedcm/me/authorized-apps');
735
+ }
736
+ catch (error) {
737
+ throw this.handleError(error);
738
+ }
739
+ }
613
740
  },
614
741
  _a.DEFAULT_CONFIG_URL = 'https://auth.oxy.so/fedcm.json',
615
742
  _a.FEDCM_TIMEOUT = 15000 // 15 seconds for interactive
616
743
  ,
617
- _a.FEDCM_SILENT_TIMEOUT = 3000 // 3 seconds for silent mediation
744
+ // Silent mediation runs on page load (e.g. re-signing-in a user whose stored
745
+ // session was cleared after a cold-boot token fetch 401'd). The real silent
746
+ // round-trip — mint nonce → navigator.credentials.get → /fedcm/exchange — was
747
+ // measured to take more than 3s for live users, so a 3s budget timed out and
748
+ // left them signed out on reload. 10s gives ample margin while staying bounded.
749
+ _a.FEDCM_SILENT_TIMEOUT = 10000 // 10 seconds for silent mediation
618
750
  ,
619
751
  _a;
620
752
  }