@oxyhq/core 1.11.24 → 2.1.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 (150) 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 +121 -57
  30. package/dist/cjs/mixins/OxyServices.auth.js +235 -0
  31. package/dist/cjs/mixins/OxyServices.fedcm.js +36 -0
  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/cjs/utils/coldBoot.js +71 -0
  36. package/dist/cjs/utils/fapiAutoDetect.js +88 -0
  37. package/dist/esm/.tsbuildinfo +1 -1
  38. package/dist/esm/AuthManager.js +678 -4
  39. package/dist/esm/AuthManagerTypes.js +12 -0
  40. package/dist/esm/CrossDomainAuth.js +45 -3
  41. package/dist/esm/OxyServices.base.js +16 -0
  42. package/dist/esm/i18n/locales/ar-SA.json +83 -0
  43. package/dist/esm/i18n/locales/ca-ES.json +83 -0
  44. package/dist/esm/i18n/locales/de-DE.json +83 -0
  45. package/dist/esm/i18n/locales/en-US.json +83 -0
  46. package/dist/esm/i18n/locales/es-ES.json +99 -4
  47. package/dist/esm/i18n/locales/fr-FR.json +83 -0
  48. package/dist/esm/i18n/locales/it-IT.json +83 -0
  49. package/dist/esm/i18n/locales/ja-JP.json +83 -0
  50. package/dist/esm/i18n/locales/ko-KR.json +83 -0
  51. package/dist/esm/i18n/locales/locales/ar-SA.json +83 -1
  52. package/dist/esm/i18n/locales/locales/ca-ES.json +83 -1
  53. package/dist/esm/i18n/locales/locales/de-DE.json +83 -1
  54. package/dist/esm/i18n/locales/locales/en-US.json +83 -0
  55. package/dist/esm/i18n/locales/locales/es-ES.json +99 -4
  56. package/dist/esm/i18n/locales/locales/fr-FR.json +83 -1
  57. package/dist/esm/i18n/locales/locales/it-IT.json +83 -1
  58. package/dist/esm/i18n/locales/locales/ja-JP.json +200 -117
  59. package/dist/esm/i18n/locales/locales/ko-KR.json +83 -1
  60. package/dist/esm/i18n/locales/locales/pt-PT.json +83 -1
  61. package/dist/esm/i18n/locales/locales/zh-CN.json +83 -1
  62. package/dist/esm/i18n/locales/pt-PT.json +83 -0
  63. package/dist/esm/i18n/locales/zh-CN.json +83 -0
  64. package/dist/esm/index.js +74 -26
  65. package/dist/esm/mixins/OxyServices.auth.js +235 -0
  66. package/dist/esm/mixins/OxyServices.fedcm.js +36 -0
  67. package/dist/esm/mixins/OxyServices.popup.js +61 -1
  68. package/dist/esm/mixins/OxyServices.user.js +18 -0
  69. package/dist/esm/utils/accountUtils.js +61 -0
  70. package/dist/esm/utils/coldBoot.js +68 -0
  71. package/dist/esm/utils/fapiAutoDetect.js +85 -0
  72. package/dist/types/.tsbuildinfo +1 -1
  73. package/dist/types/AuthManager.d.ts +243 -3
  74. package/dist/types/AuthManagerTypes.d.ts +68 -0
  75. package/dist/types/CrossDomainAuth.d.ts +23 -0
  76. package/dist/types/OxyServices.base.d.ts +14 -0
  77. package/dist/types/OxyServices.d.ts +7 -0
  78. package/dist/types/index.d.ts +31 -17
  79. package/dist/types/mixins/OxyServices.analytics.d.ts +1 -0
  80. package/dist/types/mixins/OxyServices.appData.d.ts +1 -0
  81. package/dist/types/mixins/OxyServices.assets.d.ts +4 -1
  82. package/dist/types/mixins/OxyServices.auth.d.ts +73 -1
  83. package/dist/types/mixins/OxyServices.contacts.d.ts +1 -0
  84. package/dist/types/mixins/OxyServices.developer.d.ts +1 -0
  85. package/dist/types/mixins/OxyServices.devices.d.ts +1 -0
  86. package/dist/types/mixins/OxyServices.features.d.ts +2 -5
  87. package/dist/types/mixins/OxyServices.fedcm.d.ts +34 -0
  88. package/dist/types/mixins/OxyServices.karma.d.ts +1 -0
  89. package/dist/types/mixins/OxyServices.language.d.ts +1 -0
  90. package/dist/types/mixins/OxyServices.location.d.ts +1 -0
  91. package/dist/types/mixins/OxyServices.managedAccounts.d.ts +1 -0
  92. package/dist/types/mixins/OxyServices.payment.d.ts +1 -0
  93. package/dist/types/mixins/OxyServices.popup.d.ts +40 -0
  94. package/dist/types/mixins/OxyServices.privacy.d.ts +1 -0
  95. package/dist/types/mixins/OxyServices.redirect.d.ts +1 -0
  96. package/dist/types/mixins/OxyServices.security.d.ts +1 -0
  97. package/dist/types/mixins/OxyServices.topics.d.ts +1 -0
  98. package/dist/types/mixins/OxyServices.user.d.ts +16 -1
  99. package/dist/types/mixins/OxyServices.utility.d.ts +1 -0
  100. package/dist/types/models/interfaces.d.ts +98 -0
  101. package/dist/types/models/session.d.ts +8 -0
  102. package/dist/types/utils/accountUtils.d.ts +33 -0
  103. package/dist/types/utils/coldBoot.d.ts +102 -0
  104. package/dist/types/utils/fapiAutoDetect.d.ts +37 -0
  105. package/package.json +9 -18
  106. package/src/AuthManager.ts +776 -7
  107. package/src/AuthManagerTypes.ts +72 -0
  108. package/src/CrossDomainAuth.ts +54 -3
  109. package/src/OxyServices.base.ts +17 -0
  110. package/src/OxyServices.ts +7 -0
  111. package/src/__tests__/authManager.cookiePath.test.ts +339 -0
  112. package/src/__tests__/authManager.security.test.ts +342 -0
  113. package/src/__tests__/crossDomainAuth.test.ts +191 -0
  114. package/src/i18n/locales/ar-SA.json +83 -1
  115. package/src/i18n/locales/ca-ES.json +83 -1
  116. package/src/i18n/locales/de-DE.json +83 -1
  117. package/src/i18n/locales/en-US.json +83 -0
  118. package/src/i18n/locales/es-ES.json +99 -4
  119. package/src/i18n/locales/fr-FR.json +83 -1
  120. package/src/i18n/locales/it-IT.json +83 -1
  121. package/src/i18n/locales/ja-JP.json +200 -117
  122. package/src/i18n/locales/ko-KR.json +83 -1
  123. package/src/i18n/locales/pt-PT.json +83 -1
  124. package/src/i18n/locales/zh-CN.json +83 -1
  125. package/src/index.ts +309 -112
  126. package/src/mixins/OxyServices.auth.ts +268 -1
  127. package/src/mixins/OxyServices.fedcm.ts +63 -0
  128. package/src/mixins/OxyServices.popup.ts +79 -1
  129. package/src/mixins/OxyServices.user.ts +33 -1
  130. package/src/mixins/__tests__/popup.test.ts +307 -0
  131. package/src/mixins/__tests__/sessionBaseUrl.test.ts +61 -0
  132. package/src/models/interfaces.ts +116 -0
  133. package/src/models/session.ts +8 -0
  134. package/src/utils/__tests__/coldBoot.test.ts +226 -0
  135. package/src/utils/__tests__/fapiAutoDetect.test.ts +93 -0
  136. package/src/utils/accountUtils.ts +84 -0
  137. package/src/utils/coldBoot.ts +136 -0
  138. package/src/utils/fapiAutoDetect.ts +82 -0
  139. package/dist/cjs/crypto/index.js +0 -22
  140. package/dist/cjs/shared/index.js +0 -70
  141. package/dist/cjs/utils/index.js +0 -26
  142. package/dist/esm/crypto/index.js +0 -13
  143. package/dist/esm/shared/index.js +0 -31
  144. package/dist/esm/utils/index.js +0 -7
  145. package/dist/types/crypto/index.d.ts +0 -11
  146. package/dist/types/shared/index.d.ts +0 -28
  147. package/dist/types/utils/index.d.ts +0 -6
  148. package/src/crypto/index.ts +0 -30
  149. package/src/shared/index.ts +0 -82
  150. 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
  */
@@ -701,6 +701,42 @@ function OxyServicesFedCMMixin(Base) {
701
701
  // Storage blocked
702
702
  }
703
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
+ }
704
740
  },
705
741
  _a.DEFAULT_CONFIG_URL = 'https://auth.oxy.so/fedcm.json',
706
742
  _a.FEDCM_TIMEOUT = 15000 // 15 seconds for interactive
@@ -81,7 +81,37 @@ function OxyServicesPopupAuthMixin(Base) {
81
81
  clientId: window.location.origin,
82
82
  redirectUri: `${this.resolveAuthUrl()}/auth/callback`,
83
83
  });
84
- const popup = this.openCenteredPopup(authUrl, 'Oxy Sign In', width, height);
84
+ // If the caller pre-opened a popup on the raw user gesture (recommended
85
+ // path — see `openBlankPopup` and `PopupAuthOptions.popup`), navigate it
86
+ // to the auth URL instead of issuing a fresh `window.open` (which would
87
+ // be blocked once any prior `await` has consumed the user activation).
88
+ let popup;
89
+ const preOpened = options.popup ?? null;
90
+ if (preOpened) {
91
+ if (preOpened.closed) {
92
+ // The pre-opened popup is gone — distinguish a user cancel (they
93
+ // closed the blank window before sign-in could navigate it) from a
94
+ // blocker rejection. Lumping these together as "Popup blocked" is
95
+ // misleading: the popup was NOT blocked, it was opened successfully
96
+ // and then dismissed.
97
+ throw new OxyServices_errors_1.OxyAuthenticationError('Sign-in window was closed before authentication could start.');
98
+ }
99
+ try {
100
+ preOpened.location.replace(authUrl);
101
+ }
102
+ catch (replaceError) {
103
+ // `location.replace` can throw in sandboxed / cross-origin-locked
104
+ // environments. Fall back to `href` assignment, which is more
105
+ // permissive. Logged at debug-level so consumers can correlate
106
+ // unusual sign-in behaviour without producing noise in normal flows.
107
+ debug.warn('location.replace failed, falling back to location.href', replaceError);
108
+ preOpened.location.href = authUrl;
109
+ }
110
+ popup = preOpened;
111
+ }
112
+ else {
113
+ popup = this.openCenteredPopup(authUrl, 'Oxy Sign In', width, height);
114
+ }
85
115
  if (!popup) {
86
116
  throw new OxyServices_errors_1.OxyAuthenticationError('Popup blocked. Please allow popups for this site and try again.');
87
117
  }
@@ -224,6 +254,36 @@ function OxyServicesPopupAuthMixin(Base) {
224
254
  document.body.removeChild(iframe);
225
255
  }
226
256
  }
257
+ /**
258
+ * Open a blank, centered popup window SYNCHRONOUSLY.
259
+ *
260
+ * Use this in a click (or other user-gesture) handler BEFORE any `await`
261
+ * to capture the transient user-activation. Pass the returned handle into
262
+ * `signInWithPopup({ popup })` once the async portion of the flow runs.
263
+ *
264
+ * Returns `null` if the browser's popup blocker rejected the open.
265
+ *
266
+ * @example
267
+ * ```typescript
268
+ * const onSignInClick = () => {
269
+ * const popup = oxyServices.openBlankPopup();
270
+ * (async () => {
271
+ * const silent = await oxyServices.silentSignInWithFedCM();
272
+ * if (silent) { popup?.close(); return; }
273
+ * await oxyServices.signInWithPopup({ popup });
274
+ * })();
275
+ * };
276
+ * ```
277
+ */
278
+ openBlankPopup(width, height) {
279
+ if (typeof window === 'undefined') {
280
+ return null;
281
+ }
282
+ const ctor = this.constructor;
283
+ const w = width ?? ctor.POPUP_WIDTH;
284
+ const h = height ?? ctor.POPUP_HEIGHT;
285
+ return this.openCenteredPopup('about:blank', 'Oxy Sign In', w, h);
286
+ }
227
287
  /**
228
288
  * Open a centered popup window
229
289
  *
@@ -218,6 +218,24 @@ function OxyServicesUserMixin(Base) {
218
218
  throw this.handleError(error);
219
219
  }
220
220
  }
221
+ /**
222
+ * Update the authenticated user's notification preferences.
223
+ *
224
+ * Thin wrapper over `updateProfile` that constrains the patch to known
225
+ * notification channels — same persistence path, same cache invalidation,
226
+ * but type-safe at the call site.
227
+ */
228
+ async updateNotificationPreferences(preferences) {
229
+ return this.updateProfile({ notificationPreferences: preferences });
230
+ }
231
+ /**
232
+ * Update the authenticated user's general preferences (language, theme,
233
+ * reduce-motion, timezone). Persisted on the User document via
234
+ * `PUT /users/me` — same cache-invalidation behaviour as `updateProfile`.
235
+ */
236
+ async updateUserPreferences(preferences) {
237
+ return this.updateProfile({ userPreferences: preferences });
238
+ }
221
239
  /**
222
240
  * Request account verification
223
241
  */
@@ -4,7 +4,7 @@
4
4
  * Used by both @oxyhq/services (React Native) and @oxyhq/auth (Web) account stores.
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.createQuickAccount = exports.buildAccountsArray = exports.getAccountFallbackHandle = exports.getAccountDisplayName = exports.formatPublicKeyHandle = void 0;
7
+ exports.getAccountColor = exports.mergeAccountsFromRefreshAll = exports.createQuickAccount = exports.buildAccountsArray = exports.getAccountFallbackHandle = exports.getAccountDisplayName = exports.formatPublicKeyHandle = void 0;
8
8
  const i18n_1 = require("../i18n");
9
9
  /**
10
10
  * Truncate a long public key for display, e.g. `0x12345678…`.
@@ -116,3 +116,66 @@ const createQuickAccount = (sessionId, userData, existingAccount, getFileDownloa
116
116
  };
117
117
  };
118
118
  exports.createQuickAccount = createQuickAccount;
119
+ /**
120
+ * Merge a fresh `/auth/refresh-all` snapshot into an existing QuickAccount
121
+ * list, preserving any cached fields (`avatarUrl`) for slots that didn't
122
+ * change. The fresh response is canonical: the resulting list contains EXACTLY
123
+ * the slots present in `fresh`, sorted by `authuser` ascending. Stale stored
124
+ * accounts that no longer appear in `fresh` are dropped (the server already
125
+ * authoritatively cleared the corresponding cookie).
126
+ *
127
+ * @param stored Previously persisted QuickAccount list (any order).
128
+ * @param fresh Server's authoritative refresh-all response.
129
+ * @returns Canonical merged list, sorted by `authuser` asc.
130
+ */
131
+ const mergeAccountsFromRefreshAll = (stored, fresh) => {
132
+ const storedByAuthuser = new Map();
133
+ if (stored) {
134
+ for (const account of stored) {
135
+ if (typeof account.authuser === 'number') {
136
+ storedByAuthuser.set(account.authuser, account);
137
+ }
138
+ }
139
+ }
140
+ const merged = fresh.map((entry) => {
141
+ const previous = storedByAuthuser.get(entry.authuser);
142
+ // `entry.user` is null on the SDK legacy-fallback path; preserve any
143
+ // previously cached identity for that slot rather than overwriting
144
+ // it with blanks, and let the AuthManager's getCurrentUser() hydration
145
+ // refresh it on the next snapshot.
146
+ const wireUser = entry.user;
147
+ const username = wireUser?.username ?? previous?.username ?? '';
148
+ const displayName = (0, exports.getAccountDisplayName)({
149
+ name: wireUser?.name,
150
+ username,
151
+ });
152
+ const avatar = wireUser?.avatar ?? previous?.avatar ?? undefined;
153
+ const avatarUrl = previous && previous.avatar === avatar ? previous.avatarUrl : undefined;
154
+ return {
155
+ sessionId: entry.sessionId,
156
+ userId: wireUser?.id ?? previous?.userId,
157
+ username,
158
+ displayName,
159
+ avatar,
160
+ avatarUrl,
161
+ authuser: entry.authuser,
162
+ color: wireUser?.color ?? previous?.color ?? null,
163
+ };
164
+ });
165
+ merged.sort((a, b) => {
166
+ const aIdx = a.authuser ?? Number.POSITIVE_INFINITY;
167
+ const bIdx = b.authuser ?? Number.POSITIVE_INFINITY;
168
+ return aIdx - bIdx;
169
+ });
170
+ return merged;
171
+ };
172
+ exports.mergeAccountsFromRefreshAll = mergeAccountsFromRefreshAll;
173
+ /**
174
+ * Return the account's preferred Bloom color preset, or `null` if it has no
175
+ * preference. Centralises the `color ?? null` normalisation so consumers can
176
+ * drive per-account theming without duplicating the nullish-handling.
177
+ */
178
+ const getAccountColor = (account) => {
179
+ return account.color ?? null;
180
+ };
181
+ exports.getAccountColor = getAccountColor;
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ /**
3
+ * coldBoot — a pure, ordered, short-circuit runner for "cold boot"
4
+ * authentication resolution.
5
+ *
6
+ * On a fresh page load / app launch the SDK may have several ways to recover an
7
+ * existing session (silent FedCM, a persisted refresh token, a cross-domain
8
+ * claim, an explicit popup flow, …). They must be attempted in a *deterministic
9
+ * order*, and the FIRST one that yields a session wins — every later step is
10
+ * skipped. This module encodes exactly that contract and nothing else.
11
+ *
12
+ * Design constraints (all enforced):
13
+ * - PURE: no DOM, no `navigator`, no `window`, no React, no platform globals.
14
+ * - NO module-level mutable state. Every call to {@link runColdBoot} is fully
15
+ * self-contained, so it is safe under bundler re-evaluation (e.g. the Metro
16
+ * web bundle, which is precisely why the FedCM silent-SSO guard had to live
17
+ * in consumers rather than a core singleton).
18
+ * - Architecture-agnostic: both candidate cross-domain SSO designs consume
19
+ * this same primitive; it knows nothing about HOW a step resolves a session.
20
+ *
21
+ * A step is skipped (without running) when its `enabled` predicate returns
22
+ * false. Any thrown error — from either `enabled` or `run` — is reported via
23
+ * `onStepError` and treated as a non-fatal skip, so one broken recovery path
24
+ * can never prevent a later, healthy one from succeeding.
25
+ */
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.runColdBoot = runColdBoot;
28
+ /**
29
+ * Run the ordered cold-boot steps and resolve to the first recovered session,
30
+ * or `unauthenticated` if none recovers one.
31
+ *
32
+ * Semantics:
33
+ * 1. Iterate `steps` in order.
34
+ * 2. If a step has an `enabled` predicate, call it inside try/catch:
35
+ * - throw → report via `onStepError(id, err)` → treat as disabled → continue.
36
+ * - returns false → continue (skip, `run` not called).
37
+ * 3. Otherwise await `step.run()` inside try/catch:
38
+ * - throw → report via `onStepError(id, err)` → continue.
39
+ * - `{ kind: 'session' }` → return `{ kind: 'session', via: step.id, session }`.
40
+ * - `{ kind: 'skip' }` → continue.
41
+ * 4. After the loop with no winner → `{ kind: 'unauthenticated' }`.
42
+ */
43
+ async function runColdBoot(options) {
44
+ const { steps, onStepError } = options;
45
+ for (const step of steps) {
46
+ if (step.enabled) {
47
+ let isEnabled;
48
+ try {
49
+ isEnabled = step.enabled();
50
+ }
51
+ catch (error) {
52
+ onStepError?.(step.id, error);
53
+ continue;
54
+ }
55
+ if (!isEnabled)
56
+ continue;
57
+ }
58
+ let result;
59
+ try {
60
+ result = await step.run();
61
+ }
62
+ catch (error) {
63
+ onStepError?.(step.id, error);
64
+ continue;
65
+ }
66
+ if (result.kind === 'session') {
67
+ return { kind: 'session', via: step.id, session: result.session };
68
+ }
69
+ }
70
+ return { kind: 'unauthenticated' };
71
+ }
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ /**
3
+ * Auto-detect the FAPI (IdP) URL from the current browser hostname.
4
+ *
5
+ * This is the canonical cross-domain IdP-resolution primitive for the Oxy
6
+ * ecosystem. Both candidate cross-domain SSO designs derive `auth.<rp-apex>`
7
+ * through this helper; do not fork it.
8
+ *
9
+ * Clerk-style multi-domain SSO depends on the IdP being reachable on a
10
+ * subdomain of the RP's own apex (e.g. `auth.mention.earth` CNAMEd to the
11
+ * central Oxy IdP). That way every FedCM endpoint, the session cookie,
12
+ * and any popup/redirect target are same-site with the RP — the only way
13
+ * to get first-party cookies in Safari ITP and Firefox Total Cookie
14
+ * Protection.
15
+ *
16
+ * This helper computes `https://auth.<rp-apex>` from
17
+ * `window.location.hostname` so a consuming app doesn't have to pass
18
+ * `authWebUrl` explicitly. Returns `undefined` for environments where
19
+ * auto-detection would be wrong:
20
+ *
21
+ * - SSR / non-browser (no `window`).
22
+ * - `localhost`, `127.0.0.1`, IPv4/IPv6 literals.
23
+ * - Hostnames with fewer than two labels.
24
+ * - Hostnames whose trailing two labels form a known multi-part public
25
+ * suffix (e.g. `co.uk`), where the naive `labels.slice(-2)` apex would be
26
+ * an attacker-registrable suffix like `auth.co.uk` rather than the real
27
+ * registrable domain.
28
+ *
29
+ * When the page is already loaded ON the IdP itself (`auth.<anything>`),
30
+ * the helper returns the current origin so the SDK keeps everything
31
+ * same-origin instead of hopping to a different IdP host.
32
+ *
33
+ * The IdP backend independently derives `iss`, `provider_urls`, and the
34
+ * `fedcm.json` icon URLs from the request host
35
+ * (`packages/auth/server/index.ts`), so an honest CNAME pair is all that
36
+ * is required for end-to-end FedCM correctness — no per-RP config.
37
+ */
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.autoDetectAuthWebUrl = autoDetectAuthWebUrl;
40
+ /**
41
+ * Known multi-part public suffixes where the registrable domain is the LAST
42
+ * THREE labels, not two. Deriving an apex from `labels.slice(-2)` against any
43
+ * of these would yield an attacker-registrable suffix (e.g. `auth.co.uk`),
44
+ * so we bail out instead.
45
+ *
46
+ * This is intentionally a small, explicit allow-list rather than the full
47
+ * Public Suffix List — it covers the suffixes the Oxy ecosystem's RPs use.
48
+ * Any multi-part-TLD RP MUST extend this set (or wire in a proper PSL check)
49
+ * before relying on this helper, otherwise auto-detection silently bails to
50
+ * `undefined` and the consumer must pass `authWebUrl` explicitly.
51
+ */
52
+ const MULTIPART_TLDS = new Set([
53
+ 'co.uk',
54
+ 'com.au',
55
+ 'co.jp',
56
+ 'co.nz',
57
+ 'com.br',
58
+ 'co.za',
59
+ 'com.mx',
60
+ 'co.in',
61
+ 'co.kr',
62
+ 'com.sg',
63
+ ]);
64
+ function autoDetectAuthWebUrl(location = typeof window !== 'undefined' ? window.location : undefined) {
65
+ if (!location)
66
+ return undefined;
67
+ const { hostname, protocol } = location;
68
+ if (!hostname)
69
+ return undefined;
70
+ if (protocol !== 'https:' && protocol !== 'http:')
71
+ return undefined;
72
+ if (hostname === 'localhost' || hostname === '127.0.0.1')
73
+ return undefined;
74
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(hostname))
75
+ return undefined;
76
+ if (hostname.startsWith('['))
77
+ return undefined;
78
+ if (hostname.startsWith('auth.')) {
79
+ return `${protocol}//${hostname}`;
80
+ }
81
+ const labels = hostname.split('.');
82
+ if (labels.length < 2)
83
+ return undefined;
84
+ if (MULTIPART_TLDS.has(labels.slice(-2).join('.')))
85
+ return undefined;
86
+ const apex = labels.slice(-2).join('.');
87
+ return `${protocol}//auth.${apex}`;
88
+ }