@oxyhq/core 1.11.24 → 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 (140) 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 +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/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 +36 -0
  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 +7 -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 +34 -0
  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 +7 -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 +63 -0
  122. package/src/mixins/OxyServices.popup.ts +79 -1
  123. package/src/mixins/OxyServices.user.ts +33 -1
  124. package/src/mixins/__tests__/popup.test.ts +307 -0
  125. package/src/mixins/__tests__/sessionBaseUrl.test.ts +61 -0
  126. package/src/models/interfaces.ts +116 -0
  127. package/src/models/session.ts +8 -0
  128. package/src/utils/accountUtils.ts +84 -0
  129. package/dist/cjs/crypto/index.js +0 -22
  130. package/dist/cjs/shared/index.js +0 -70
  131. package/dist/cjs/utils/index.js +0 -26
  132. package/dist/esm/crypto/index.js +0 -13
  133. package/dist/esm/shared/index.js +0 -31
  134. package/dist/esm/utils/index.js +0 -7
  135. package/dist/types/crypto/index.d.ts +0 -11
  136. package/dist/types/shared/index.d.ts +0 -28
  137. package/dist/types/utils/index.d.ts +0 -6
  138. package/src/crypto/index.ts +0 -30
  139. package/src/shared/index.ts +0 -82
  140. package/src/utils/index.ts +0 -21
@@ -3,7 +3,12 @@
3
3
  *
4
4
  * Supports password-based login (email/username) and public key challenge-response.
5
5
  */
6
- import type { User } from '../models/interfaces';
6
+ import type {
7
+ User,
8
+ RefreshAllResponse,
9
+ RefreshAllAccount,
10
+ RefreshCookieResponse,
11
+ } from '../models/interfaces';
7
12
  import type { SessionLoginResponse } from '../models/session';
8
13
  import type { OxyServicesBase } from '../OxyServices.base';
9
14
  import { OxyAuthenticationError } from '../OxyServices.errors';
@@ -536,6 +541,268 @@ export function OxyServicesAuthMixin<T extends typeof OxyServicesBase>(Base: T)
536
541
  }
537
542
  }
538
543
 
544
+ /**
545
+ * Refresh every device-local refresh-cookie slot in a single round trip
546
+ * (Google-style multi-account rebuild).
547
+ *
548
+ * Calls `POST {sessionBaseUrl}/auth/refresh-all` with `credentials: 'include'`
549
+ * and NO bearer. The browser attaches every `oxy_rt*` cookie it has; the
550
+ * server rotates each in parallel and returns one entry per VALID account.
551
+ *
552
+ * Failure handling:
553
+ * - 401 → no signed-in accounts on this device → returns `{ accounts: [] }`
554
+ * (NOT an error; this is the cold-boot "not signed in" path).
555
+ * - 404 → server is older than the multi-account endpoint. We fall back to
556
+ * `POST /auth/refresh` (single-slot) and wrap its response in the
557
+ * refresh-all shape so callers can treat the two paths uniformly. The
558
+ * fallback entry has `authuser: 0` (the legacy slot maps to slot 0 by
559
+ * convention) and a minimal `user` shape — consumers needing the full
560
+ * user must fetch it separately. Always exactly one account in this
561
+ * shape.
562
+ * - Any other non-2xx → throws via `handleError`.
563
+ *
564
+ * The refresh cookie itself never enters JS — only the rotated access
565
+ * tokens do. Each access token still needs to be planted via
566
+ * `setTokens(...)` (or per-account in-memory storage) at the consumer.
567
+ */
568
+ async refreshAllSessions(): Promise<RefreshAllResponse> {
569
+ const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/auth/refresh-all`;
570
+
571
+ let response: Response;
572
+ try {
573
+ response = await fetch(url, {
574
+ method: 'POST',
575
+ credentials: 'include',
576
+ headers: { Accept: 'application/json' },
577
+ });
578
+ } catch (error) {
579
+ throw this.handleError(error);
580
+ }
581
+
582
+ if (response.status === 401) {
583
+ return { accounts: [] };
584
+ }
585
+
586
+ if (response.status === 404) {
587
+ // Legacy single-account refresh fallback. Wrap the response so the
588
+ // caller can treat both paths identically.
589
+ const legacy = await this._refreshCookieRaw();
590
+ if (!legacy) {
591
+ return { accounts: [] };
592
+ }
593
+ const fallbackAccount: RefreshAllAccount = {
594
+ authuser: 0,
595
+ accessToken: legacy.accessToken,
596
+ expiresAt: legacy.expiresAt,
597
+ sessionId: this._decodeSessionIdFromAccessToken(legacy.accessToken) ?? '',
598
+ // Legacy /auth/refresh does NOT project the user shape; the caller
599
+ // (AuthManager) is expected to hydrate via /users/me after planting.
600
+ user: null,
601
+ };
602
+ return { accounts: [fallbackAccount] };
603
+ }
604
+
605
+ if (!response.ok) {
606
+ throw this.handleError(
607
+ new Error(`Refresh-all failed with HTTP ${response.status}`)
608
+ );
609
+ }
610
+
611
+ const payload = (await response.json()) as { accounts?: unknown };
612
+ const raw = Array.isArray(payload.accounts) ? payload.accounts : [];
613
+ const accounts: RefreshAllAccount[] = [];
614
+
615
+ for (const entry of raw) {
616
+ if (entry === null || typeof entry !== 'object') {
617
+ continue;
618
+ }
619
+ const e = entry as {
620
+ authuser?: number | null;
621
+ accessToken?: string;
622
+ expiresAt?: string;
623
+ sessionId?: string;
624
+ user?: { id?: string; _id?: string; username?: string; name?: string; avatar?: string | null; email?: string; color?: string | null };
625
+ };
626
+ if (!e.accessToken || !e.expiresAt || !e.sessionId || !e.user) {
627
+ continue;
628
+ }
629
+ const userId = e.user.id ?? e.user._id;
630
+ if (!userId || !e.user.username) {
631
+ continue;
632
+ }
633
+ // Normalise the legacy un-suffixed cookie (`authuser: null` on the
634
+ // wire) to slot 0. The SDK surface always operates on numeric indices.
635
+ const authuser = typeof e.authuser === 'number' ? e.authuser : 0;
636
+ accounts.push({
637
+ authuser,
638
+ accessToken: e.accessToken,
639
+ expiresAt: e.expiresAt,
640
+ sessionId: e.sessionId,
641
+ user: {
642
+ id: userId,
643
+ username: e.user.username,
644
+ name: e.user.name,
645
+ avatar: e.user.avatar ?? null,
646
+ email: e.user.email,
647
+ color: e.user.color ?? null,
648
+ },
649
+ });
650
+ }
651
+
652
+ return { accounts };
653
+ }
654
+
655
+ /**
656
+ * Rotate a single refresh-cookie slot and return the fresh access token.
657
+ *
658
+ * When `authuser` is provided, the server rotates ONLY that slot
659
+ * (`oxy_rt_${authuser}`) — sibling accounts on the same device stay
660
+ * untouched. When omitted, the server picks the lowest indexed slot
661
+ * present (legacy fallback applies). The refresh cookie itself never
662
+ * enters JS.
663
+ *
664
+ * Returns `null` on 401 (no cookie / expired / reused) so the caller can
665
+ * fall through cleanly to the unauthenticated path.
666
+ */
667
+ async refreshTokenViaCookie(
668
+ opts: { authuser?: number } = {}
669
+ ): Promise<RefreshCookieResponse | null> {
670
+ const result = await this._refreshCookieRaw(opts.authuser);
671
+ return result;
672
+ }
673
+
674
+ /**
675
+ * Sign out a single device-local account by its authuser slot index.
676
+ *
677
+ * Revokes that slot's refresh-token family and deactivates its session;
678
+ * sibling indexed slots stay signed in. The browser-side `oxy_rt_${n}`
679
+ * cookie is cleared by the server's `Set-Cookie` response header.
680
+ */
681
+ async logoutSessionByAuthuser(authuser: number): Promise<void> {
682
+ const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/auth/logout?authuser=${encodeURIComponent(String(authuser))}`;
683
+ try {
684
+ const response = await fetch(url, {
685
+ method: 'POST',
686
+ credentials: 'include',
687
+ headers: { Accept: 'application/json' },
688
+ });
689
+ if (!response.ok && response.status !== 401) {
690
+ throw new Error(`Logout (authuser=${authuser}) failed with HTTP ${response.status}`);
691
+ }
692
+ } catch (error) {
693
+ throw this.handleError(error);
694
+ }
695
+ }
696
+
697
+ /**
698
+ * Sign out EVERY device-local account on this device by clearing every
699
+ * presented refresh-cookie slot at once. Revokes every family + clears
700
+ * every slot. Always succeeds (idempotent on unknown/garbage tokens).
701
+ */
702
+ async logoutAllSessionsViaCookie(): Promise<void> {
703
+ const url = `${this.getSessionBaseUrl().replace(/\/$/, '')}/auth/logout`;
704
+ try {
705
+ const response = await fetch(url, {
706
+ method: 'POST',
707
+ credentials: 'include',
708
+ headers: { Accept: 'application/json' },
709
+ });
710
+ if (!response.ok && response.status !== 401) {
711
+ throw new Error(`Logout-all failed with HTTP ${response.status}`);
712
+ }
713
+ } catch (error) {
714
+ throw this.handleError(error);
715
+ }
716
+ }
717
+
718
+ /**
719
+ * Internal: raw `POST /auth/refresh[?authuser=N]` call returning the
720
+ * minted access token. Returns `null` on 401 / non-2xx. Used as both the
721
+ * implementation of `refreshTokenViaCookie` and the legacy fallback for
722
+ * `refreshAllSessions` against older servers.
723
+ *
724
+ * @internal
725
+ */
726
+ async _refreshCookieRaw(authuser?: number): Promise<RefreshCookieResponse | null> {
727
+ const base = this.getSessionBaseUrl().replace(/\/$/, '');
728
+ const url = typeof authuser === 'number'
729
+ ? `${base}/auth/refresh?authuser=${encodeURIComponent(String(authuser))}`
730
+ : `${base}/auth/refresh`;
731
+
732
+ let response: Response;
733
+ try {
734
+ response = await fetch(url, {
735
+ method: 'POST',
736
+ credentials: 'include',
737
+ headers: { Accept: 'application/json' },
738
+ });
739
+ } catch (error) {
740
+ throw this.handleError(error);
741
+ }
742
+
743
+ if (!response.ok) {
744
+ return null;
745
+ }
746
+
747
+ const payload = (await response.json()) as {
748
+ accessToken?: unknown;
749
+ expiresAt?: unknown;
750
+ authuser?: unknown;
751
+ };
752
+ if (typeof payload.accessToken !== 'string' || !payload.accessToken) {
753
+ return null;
754
+ }
755
+ const expiresAt = typeof payload.expiresAt === 'string' ? payload.expiresAt : '';
756
+ const respAuthuser = typeof payload.authuser === 'number' ? payload.authuser : null;
757
+ return {
758
+ accessToken: payload.accessToken,
759
+ expiresAt,
760
+ authuser: respAuthuser,
761
+ };
762
+ }
763
+
764
+ /**
765
+ * Internal: decode (without verifying) the `sessionId` claim from a
766
+ * server-signed access token. The server already verified the signature;
767
+ * the client only reads the claim to drive multi-session state.
768
+ *
769
+ * @internal
770
+ */
771
+ _decodeSessionIdFromAccessToken(token: string): string | null {
772
+ if (!token || typeof token !== 'string') {
773
+ return null;
774
+ }
775
+ const segments = token.split('.');
776
+ if (segments.length !== 3) {
777
+ return null;
778
+ }
779
+ const payloadSegment = segments[1];
780
+ if (!payloadSegment) {
781
+ return null;
782
+ }
783
+ try {
784
+ const base64 = payloadSegment.replace(/-/g, '+').replace(/_/g, '/');
785
+ const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), '=');
786
+ if (typeof atob !== 'function') {
787
+ return null;
788
+ }
789
+ const json = decodeURIComponent(
790
+ atob(padded)
791
+ .split('')
792
+ .map((char) => `%${`00${char.charCodeAt(0).toString(16)}`.slice(-2)}`)
793
+ .join(''),
794
+ );
795
+ const parsed: unknown = JSON.parse(json);
796
+ if (parsed === null || typeof parsed !== 'object') {
797
+ return null;
798
+ }
799
+ const claims = parsed as Record<string, unknown>;
800
+ return typeof claims.sessionId === 'string' ? claims.sessionId : null;
801
+ } catch {
802
+ return null;
803
+ }
804
+ }
805
+
539
806
  /**
540
807
  * Get sessions by session ID
541
808
  */
@@ -880,8 +880,71 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
880
880
  // Storage blocked
881
881
  }
882
882
  }
883
+
884
+ /**
885
+ * List the authenticated user's authorized RP apps.
886
+ *
887
+ * Returns the intersection of the user's FedCM grants and the currently-
888
+ * approved RP catalog — what powers the "Connected apps" management UI in
889
+ * @oxyhq/services. Requires a real user session; service tokens are
890
+ * rejected by the underlying endpoint.
891
+ */
892
+ async listAuthorizedApps(): Promise<AuthorizedApp[]> {
893
+ try {
894
+ const response = await this.makeRequest<{ apps: AuthorizedApp[] }>(
895
+ 'GET',
896
+ '/fedcm/me/authorized-apps',
897
+ undefined,
898
+ {
899
+ cache: true,
900
+ cacheTTL: 30 * 1000, // 30 second cache — short, this drives a manageable UI
901
+ }
902
+ );
903
+ return response.apps ?? [];
904
+ } catch (error) {
905
+ throw this.handleError(error);
906
+ }
907
+ }
908
+
909
+ /**
910
+ * Revoke the authenticated user's authorization for a specific RP origin.
911
+ *
912
+ * The next FedCM sign-in from that origin will require explicit re-consent.
913
+ * The corresponding cache entry is invalidated so a subsequent
914
+ * `listAuthorizedApps()` call sees fresh data.
915
+ */
916
+ async revokeAuthorizedApp(origin: string): Promise<void> {
917
+ try {
918
+ await this.makeRequest(
919
+ 'DELETE',
920
+ `/fedcm/me/authorized-apps/${encodeURIComponent(origin)}`,
921
+ undefined,
922
+ { cache: false }
923
+ );
924
+ this.clearCacheEntry('GET:/fedcm/me/authorized-apps');
925
+ } catch (error) {
926
+ throw this.handleError(error);
927
+ }
928
+ }
883
929
  };
884
930
  }
885
931
 
932
+ /**
933
+ * Public summary of an RP application the user has authorized — mirrors the
934
+ * `AuthorizedAppSummary` shape returned by `GET /fedcm/me/authorized-apps`.
935
+ */
936
+ export interface AuthorizedApp {
937
+ /** Normalised RP origin. */
938
+ origin: string;
939
+ /** Friendly display name. */
940
+ name: string;
941
+ /** Optional human-readable description. */
942
+ description?: string;
943
+ /** ISO-8601 timestamp of when the user first authorized this RP. */
944
+ firstGrantedAt: string;
945
+ /** ISO-8601 timestamp of the most recent FedCM exchange for this user+RP. */
946
+ lastUsedAt: string;
947
+ }
948
+
886
949
  // Export the mixin function as both named and default
887
950
  export { OxyServicesFedCMMixin as FedCMMixin };
@@ -10,6 +10,23 @@ export interface PopupAuthOptions {
10
10
  height?: number;
11
11
  timeout?: number;
12
12
  mode?: 'login' | 'signup';
13
+ /**
14
+ * A popup window handle the caller already opened SYNCHRONOUSLY inside the
15
+ * user-gesture event handler (e.g. an `onClick`). The mixin will navigate
16
+ * this window to the auth URL instead of calling `window.open` itself.
17
+ *
18
+ * Why this exists: Chrome (and other modern browsers) only honor
19
+ * `window.open` while a transient user-activation is in scope. The
20
+ * activation is consumed by the FIRST `await` in the click handler — so any
21
+ * caller that awaits FedCM / silent SSO before reaching `signInWithPopup`
22
+ * loses the activation and sees the popup blocked. The caller can dodge
23
+ * this by opening a blank popup on the raw click via `openBlankPopup()`,
24
+ * then passing the handle in here.
25
+ *
26
+ * `null` is accepted (and is the same as omitting the option) so consumers
27
+ * can pass through the result of `openBlankPopup()` without an extra guard.
28
+ */
29
+ popup?: Window | null;
13
30
  }
14
31
 
15
32
  export interface SilentAuthOptions {
@@ -104,7 +121,37 @@ export function OxyServicesPopupAuthMixin<T extends typeof OxyServicesBase>(Base
104
121
  redirectUri: `${this.resolveAuthUrl()}/auth/callback`,
105
122
  });
106
123
 
107
- const popup = this.openCenteredPopup(authUrl, 'Oxy Sign In', width, height);
124
+ // If the caller pre-opened a popup on the raw user gesture (recommended
125
+ // path — see `openBlankPopup` and `PopupAuthOptions.popup`), navigate it
126
+ // to the auth URL instead of issuing a fresh `window.open` (which would
127
+ // be blocked once any prior `await` has consumed the user activation).
128
+ let popup: Window | null;
129
+ const preOpened = options.popup ?? null;
130
+ if (preOpened) {
131
+ if (preOpened.closed) {
132
+ // The pre-opened popup is gone — distinguish a user cancel (they
133
+ // closed the blank window before sign-in could navigate it) from a
134
+ // blocker rejection. Lumping these together as "Popup blocked" is
135
+ // misleading: the popup was NOT blocked, it was opened successfully
136
+ // and then dismissed.
137
+ throw new OxyAuthenticationError(
138
+ 'Sign-in window was closed before authentication could start.'
139
+ );
140
+ }
141
+ try {
142
+ preOpened.location.replace(authUrl);
143
+ } catch (replaceError) {
144
+ // `location.replace` can throw in sandboxed / cross-origin-locked
145
+ // environments. Fall back to `href` assignment, which is more
146
+ // permissive. Logged at debug-level so consumers can correlate
147
+ // unusual sign-in behaviour without producing noise in normal flows.
148
+ debug.warn('location.replace failed, falling back to location.href', replaceError);
149
+ preOpened.location.href = authUrl;
150
+ }
151
+ popup = preOpened;
152
+ } else {
153
+ popup = this.openCenteredPopup(authUrl, 'Oxy Sign In', width, height);
154
+ }
108
155
 
109
156
  if (!popup) {
110
157
  throw new OxyAuthenticationError(
@@ -269,6 +316,37 @@ export function OxyServicesPopupAuthMixin<T extends typeof OxyServicesBase>(Base
269
316
  }
270
317
  }
271
318
 
319
+ /**
320
+ * Open a blank, centered popup window SYNCHRONOUSLY.
321
+ *
322
+ * Use this in a click (or other user-gesture) handler BEFORE any `await`
323
+ * to capture the transient user-activation. Pass the returned handle into
324
+ * `signInWithPopup({ popup })` once the async portion of the flow runs.
325
+ *
326
+ * Returns `null` if the browser's popup blocker rejected the open.
327
+ *
328
+ * @example
329
+ * ```typescript
330
+ * const onSignInClick = () => {
331
+ * const popup = oxyServices.openBlankPopup();
332
+ * (async () => {
333
+ * const silent = await oxyServices.silentSignInWithFedCM();
334
+ * if (silent) { popup?.close(); return; }
335
+ * await oxyServices.signInWithPopup({ popup });
336
+ * })();
337
+ * };
338
+ * ```
339
+ */
340
+ public openBlankPopup(width?: number, height?: number): Window | null {
341
+ if (typeof window === 'undefined') {
342
+ return null;
343
+ }
344
+ const ctor = this.constructor as unknown as { POPUP_WIDTH: number; POPUP_HEIGHT: number };
345
+ const w = width ?? ctor.POPUP_WIDTH;
346
+ const h = height ?? ctor.POPUP_HEIGHT;
347
+ return this.openCenteredPopup('about:blank', 'Oxy Sign In', w, h);
348
+ }
349
+
272
350
  /**
273
351
  * Open a centered popup window
274
352
  *
@@ -1,7 +1,15 @@
1
1
  /**
2
2
  * User Management Methods Mixin
3
3
  */
4
- import type { User, Notification, SearchProfilesResponse, PaginationInfo, PrivacySettings } from '../models/interfaces';
4
+ import type {
5
+ User,
6
+ Notification,
7
+ NotificationPreferences,
8
+ UserPreferences,
9
+ SearchProfilesResponse,
10
+ PaginationInfo,
11
+ PrivacySettings,
12
+ } from '../models/interfaces';
5
13
  import type { OxyServicesBase } from '../OxyServices.base';
6
14
  import { buildSearchParams, buildPaginationParams, type PaginationParams } from '../utils/apiUtils';
7
15
  import { KeyManager } from '../crypto/keyManager';
@@ -271,6 +279,30 @@ export function OxyServicesUserMixin<T extends typeof OxyServicesBase>(Base: T)
271
279
  }
272
280
  }
273
281
 
282
+ /**
283
+ * Update the authenticated user's notification preferences.
284
+ *
285
+ * Thin wrapper over `updateProfile` that constrains the patch to known
286
+ * notification channels — same persistence path, same cache invalidation,
287
+ * but type-safe at the call site.
288
+ */
289
+ async updateNotificationPreferences(
290
+ preferences: Partial<NotificationPreferences>
291
+ ): Promise<User> {
292
+ return this.updateProfile({ notificationPreferences: preferences });
293
+ }
294
+
295
+ /**
296
+ * Update the authenticated user's general preferences (language, theme,
297
+ * reduce-motion, timezone). Persisted on the User document via
298
+ * `PUT /users/me` — same cache-invalidation behaviour as `updateProfile`.
299
+ */
300
+ async updateUserPreferences(
301
+ preferences: Partial<UserPreferences>
302
+ ): Promise<User> {
303
+ return this.updateProfile({ userPreferences: preferences });
304
+ }
305
+
274
306
  /**
275
307
  * Request account verification
276
308
  */