@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
@@ -33,12 +33,44 @@ function isUnknownModeEnumError(error) {
33
33
  ((message.includes('active') || message.includes('passive')) &&
34
34
  (message.includes('enum') || message.includes('not a valid'))));
35
35
  }
36
+ /**
37
+ * Detect a `navigator.credentials.get` rejection that is consistent with
38
+ * "the supplied loginHint matched no account at the IdP".
39
+ *
40
+ * When an RP passes a `loginHint` and the IdP returns accounts but NONE of them
41
+ * declare that hint in their `login_hints`, Chrome filters every account out,
42
+ * greys it in the chooser ("You can't sign in using this account"), logs
43
+ * "Accounts were received, but none matched the login hint…", and ultimately
44
+ * rejects the credential request — surfacing as a `NotAllowedError` /
45
+ * `AbortError` (the same shape as a user-cancelled or timed-out request). A
46
+ * stale hint left over from a previously-signed-in/test account therefore hard
47
+ * -blocks sign-in.
48
+ *
49
+ * We can only safely apply the clear-and-retry recovery when a `loginHint` was
50
+ * actually supplied; without one this is just a normal cancel/timeout and must
51
+ * NOT be retried. Callers gate on `hadLoginHint` before calling this.
52
+ */
53
+ function isPossibleHintMismatchError(error) {
54
+ if (!(error instanceof Error))
55
+ return false;
56
+ // FedCM surfaces a filtered-out / no-eligible-account outcome as
57
+ // NotAllowedError (current Chrome) or AbortError (our own timeout abort while
58
+ // the chooser had no selectable account). Both are indistinguishable from a
59
+ // genuine user cancel at the API level, so the gate on "a hint was supplied"
60
+ // (in the caller) is what makes the retry safe and targeted.
61
+ return error.name === 'NotAllowedError' || error.name === 'AbortError';
62
+ }
36
63
  const FEDCM_LOGIN_HINT_KEY = 'oxy_fedcm_login_hint';
37
64
  // Global lock to prevent concurrent FedCM requests
38
65
  // FedCM only allows one navigator.credentials.get request at a time
39
66
  let fedCMRequestInProgress = false;
40
67
  let fedCMRequestPromise = null;
41
68
  let currentMediationMode = null;
69
+ // AbortController of the in-flight request, exposed at module scope so an
70
+ // arriving INTERACTIVE request can abort a slow/hung SILENT one instead of
71
+ // blocking on it (see requestIdentityCredential). Set when a request starts,
72
+ // cleared in that request's `finally`.
73
+ let fedCMActiveController = null;
42
74
  /**
43
75
  * Federated Credential Management (FedCM) Authentication Mixin
44
76
  *
@@ -67,9 +99,12 @@ export function OxyServicesFedCMMixin(Base) {
67
99
  super(...args);
68
100
  }
69
101
  resolveFedcmConfigUrl() {
102
+ // `DEFAULT_CONFIG_URL` is a static on the composed class; read it off the
103
+ // most-derived constructor through a typed cast (not `any`).
104
+ const configCtor = this.constructor;
70
105
  return this.config.authWebUrl
71
106
  ? `${this.config.authWebUrl}/fedcm.json`
72
- : this.constructor.DEFAULT_CONFIG_URL;
107
+ : configCtor.DEFAULT_CONFIG_URL;
73
108
  }
74
109
  /**
75
110
  * Check if FedCM is supported in the current browser
@@ -113,67 +148,104 @@ export function OxyServicesFedCMMixin(Base) {
113
148
  if (!this.isFedCMSupported()) {
114
149
  throw new OxyAuthenticationError('FedCM not supported in this browser. Please update your browser or use an alternative sign-in method.');
115
150
  }
151
+ // Use provided loginHint, or fall back to stored last-used account ID.
152
+ const initialLoginHint = options.loginHint || this.getStoredLoginHint();
116
153
  try {
117
- // Prefer a server-minted, origin-bound nonce so the downstream
118
- // `/fedcm/exchange` can validate it. A caller-supplied nonce is
119
- // respected as-is for advanced use cases.
120
- const nonce = options.nonce || (await this.getFedcmNonce());
121
- const clientId = this.getClientId();
122
- // Use provided loginHint, or fall back to stored last-used account ID
123
- const loginHint = options.loginHint || this.getStoredLoginHint();
124
- debug.log('Interactive sign-in: Requesting credential for', clientId, loginHint ? `(hint: ${loginHint})` : '');
125
- // Request credential from browser's native identity flow.
126
- // mode: 'active' signals this is a user-gesture-initiated (button) flow.
127
- // 'active' is the current W3C spec value; requestIdentityCredential
128
- // transparently retries with the legacy 'button' value for Chrome 125–131.
129
- const credential = await this.requestIdentityCredential({
130
- configURL: this.resolveFedcmConfigUrl(),
131
- clientId,
132
- nonce,
133
- context: options.context,
134
- loginHint,
135
- mode: 'active',
136
- });
137
- if (!credential || !credential.token) {
138
- throw new OxyAuthenticationError('No credential received from browser');
139
- }
140
- debug.log('Interactive sign-in: Got credential, exchanging for session');
141
- // Exchange FedCM ID token for Oxy session
142
- const session = await this.exchangeIdTokenForSession(credential.token);
143
- // Store access token in HttpService. `accessToken`/`refreshToken` are
144
- // declared optional on SessionLoginResponse; default the refresh token to
145
- // an empty string when the exchange did not return one.
146
- if (session?.accessToken) {
147
- this.httpService.setTokens(session.accessToken, session.refreshToken ?? '');
148
- }
149
- // Store the user ID as loginHint for future FedCM requests
150
- if (session?.user?.id) {
151
- this.storeLoginHint(session.user.id);
152
- }
153
- debug.log('Interactive sign-in: Success!', { userId: session?.user?.id });
154
- return session;
154
+ return await this.attemptInteractiveSignIn(options, initialLoginHint);
155
155
  }
156
156
  catch (error) {
157
- debug.log('Interactive sign-in failed:', error);
158
- const errorMessage = error instanceof Error ? error.message : String(error);
159
- // FedCM aborts/network failures surface as DOMException/Error instances,
160
- // both of which carry a `name`. Anything else has no meaningful name.
161
- const errorName = error instanceof Error ? error.name : '';
162
- if (errorName === 'AbortError') {
163
- throw new OxyAuthenticationError('Sign-in was cancelled by user');
164
- }
165
- if (errorName === 'NetworkError') {
166
- throw new OxyAuthenticationError('Network error during sign-in. Please check your connection.');
157
+ // A STALE loginHint (e.g. left over from a previously-signed-in or test
158
+ // account) that matches no account at the IdP makes Chrome filter out
159
+ // every account and reject the request — indistinguishable from a user
160
+ // cancel. When that happens AND we supplied a hint, clear the bad hint
161
+ // and retry the credential request ONCE with no hint, which lets the
162
+ // chooser surface the genuinely available account(s). We only do this for
163
+ // a hint we pulled from storage (not a caller-supplied one), and only
164
+ // once, so a real cancel never loops.
165
+ const usedStoredHint = !!initialLoginHint && !options.loginHint;
166
+ if (usedStoredHint && isPossibleHintMismatchError(error)) {
167
+ debug.log('Interactive sign-in: stored loginHint matched no account; clearing it and retrying without a hint');
168
+ this.clearLoginHint();
169
+ return await this.attemptInteractiveSignIn(options, undefined);
167
170
  }
168
- if (errorMessage.includes('multiple accounts')) {
169
- throw new OxyAuthenticationError('Please sign out and sign in again to use FedCM with a single account');
170
- }
171
- if (errorMessage.includes('retrieving a token') || errorMessage.includes('Error retrieving')) {
172
- debug.error('FedCM token retrieval error - this may be a browser or IdP configuration issue');
173
- throw new OxyAuthenticationError('Authentication failed. Please try again or use an alternative sign-in method.');
174
- }
175
- throw error;
171
+ throw this.normalizeInteractiveSignInError(error);
172
+ }
173
+ }
174
+ /**
175
+ * Run a single interactive FedCM credential request + token exchange for the
176
+ * given (possibly undefined) loginHint. A successful exchange plants the
177
+ * access token and persists the user id as the future loginHint — the hint is
178
+ * therefore only ever stored after a GENUINELY successful sign-in, never
179
+ * speculatively.
180
+ *
181
+ * @private
182
+ */
183
+ async attemptInteractiveSignIn(options, loginHint) {
184
+ // Prefer a server-minted, origin-bound nonce so the downstream
185
+ // `/fedcm/exchange` can validate it. A caller-supplied nonce is
186
+ // respected as-is for advanced use cases.
187
+ const nonce = options.nonce || (await this.getFedcmNonce());
188
+ const clientId = this.getClientId();
189
+ debug.log('Interactive sign-in: Requesting credential for', clientId, loginHint ? `(hint: ${loginHint})` : '');
190
+ // Request credential from browser's native identity flow.
191
+ // mode: 'active' signals this is a user-gesture-initiated (button) flow.
192
+ // 'active' is the current W3C spec value; requestIdentityCredential
193
+ // transparently retries with the legacy 'button' value for Chrome 125–131.
194
+ const credential = await this.requestIdentityCredential({
195
+ configURL: this.resolveFedcmConfigUrl(),
196
+ clientId,
197
+ nonce,
198
+ context: options.context,
199
+ loginHint,
200
+ mode: 'active',
201
+ });
202
+ if (!credential || !credential.token) {
203
+ throw new OxyAuthenticationError('No credential received from browser');
204
+ }
205
+ debug.log('Interactive sign-in: Got credential, exchanging for session');
206
+ // Exchange FedCM ID token for Oxy session
207
+ const session = await this.exchangeIdTokenForSession(credential.token);
208
+ // Store access token in HttpService. `accessToken`/`refreshToken` are
209
+ // declared optional on SessionLoginResponse; default the refresh token to
210
+ // an empty string when the exchange did not return one.
211
+ if (session?.accessToken) {
212
+ this.httpService.setTokens(session.accessToken, session.refreshToken ?? '');
176
213
  }
214
+ // Store the user ID as loginHint for future FedCM requests — only now, after
215
+ // a real successful exchange, so we never persist a hint that cannot resolve.
216
+ if (session?.user?.id) {
217
+ this.storeLoginHint(session.user.id);
218
+ }
219
+ debug.log('Interactive sign-in: Success!', { userId: session?.user?.id });
220
+ return session;
221
+ }
222
+ /**
223
+ * Map a raw FedCM/exchange failure to a user-facing {@link OxyAuthenticationError}
224
+ * (or pass it through). Extracted so the clear-and-retry path can reuse the
225
+ * exact same error normalisation as the first attempt.
226
+ *
227
+ * @private
228
+ */
229
+ normalizeInteractiveSignInError(error) {
230
+ debug.log('Interactive sign-in failed:', error);
231
+ const errorMessage = error instanceof Error ? error.message : String(error);
232
+ // FedCM aborts/network failures surface as DOMException/Error instances,
233
+ // both of which carry a `name`. Anything else has no meaningful name.
234
+ const errorName = error instanceof Error ? error.name : '';
235
+ if (errorName === 'AbortError') {
236
+ return new OxyAuthenticationError('Sign-in was cancelled by user');
237
+ }
238
+ if (errorName === 'NetworkError') {
239
+ return new OxyAuthenticationError('Network error during sign-in. Please check your connection.');
240
+ }
241
+ if (errorMessage.includes('multiple accounts')) {
242
+ return new OxyAuthenticationError('Please sign out and sign in again to use FedCM with a single account');
243
+ }
244
+ if (errorMessage.includes('retrieving a token') || errorMessage.includes('Error retrieving')) {
245
+ debug.error('FedCM token retrieval error - this may be a browser or IdP configuration issue');
246
+ return new OxyAuthenticationError('Authentication failed. Please try again or use an alternative sign-in method.');
247
+ }
248
+ return error;
177
249
  }
178
250
  /**
179
251
  * Silent sign-in using FedCM
@@ -315,16 +387,20 @@ export function OxyServicesFedCMMixin(Base) {
315
387
  // If a request is already in progress...
316
388
  if (fedCMRequestInProgress && fedCMRequestPromise) {
317
389
  debug.log('Request already in progress, waiting...');
318
- // If current request is silent and new request is interactive,
319
- // wait for silent to finish, then make the interactive request
390
+ // If the in-flight request is SILENT and this new one is INTERACTIVE,
391
+ // abort the silent and proceed immediately. The silent round-trip can be
392
+ // slow (it runs on page load and may stall in the browser), and a user who
393
+ // just clicked "Sign In" must never be made to wait on — or be blocked by —
394
+ // it. Awaiting the silent here is what previously let a hung silent
395
+ // request deadlock the sign-in button, so we deliberately do NOT await it:
396
+ // we abort it (its own `finally` resets the lock as it settles) and fall
397
+ // through to start the interactive request synchronously below.
320
398
  if (currentMediationMode === 'silent' && isInteractive) {
321
- try {
322
- await fedCMRequestPromise;
323
- }
324
- catch {
325
- // Ignore silent request errors
326
- }
327
- // Now fall through to make the interactive request
399
+ debug.log('Aborting in-flight silent request to make way for interactive request');
400
+ fedCMActiveController?.abort();
401
+ // Fall through. The interactive request synchronously overwrites the
402
+ // lock globals (below); the aborted silent's `finally` uses identity
403
+ // guards so it cannot later clobber this interactive request's state.
328
404
  }
329
405
  else {
330
406
  // Same type of request - wait for the existing one
@@ -339,10 +415,14 @@ export function OxyServicesFedCMMixin(Base) {
339
415
  fedCMRequestInProgress = true;
340
416
  currentMediationMode = requestedMediation;
341
417
  const controller = new AbortController();
342
- // Use shorter timeout for silent mediation since it should be quick
418
+ fedCMActiveController = controller;
419
+ // Use shorter timeout for silent mediation since it should be quick.
420
+ // The timeout constants are static on the composed class; read them off the
421
+ // most-derived constructor through a typed cast (not `any`).
422
+ const timeoutCtor = this.constructor;
343
423
  const timeoutMs = requestedMediation === 'silent'
344
- ? this.constructor.FEDCM_SILENT_TIMEOUT
345
- : this.constructor.FEDCM_TIMEOUT;
424
+ ? timeoutCtor.FEDCM_SILENT_TIMEOUT
425
+ : timeoutCtor.FEDCM_TIMEOUT;
346
426
  const timeout = setTimeout(() => {
347
427
  debug.log('Request timed out after', timeoutMs, 'ms (mediation:', requestedMediation + ')');
348
428
  controller.abort();
@@ -419,9 +499,20 @@ export function OxyServicesFedCMMixin(Base) {
419
499
  }
420
500
  finally {
421
501
  clearTimeout(timeout);
422
- fedCMRequestInProgress = false;
423
- fedCMRequestPromise = null;
424
- currentMediationMode = null;
502
+ // Only reset the shared lock if it still belongs to THIS request. When an
503
+ // interactive request aborts a slow silent one, the silent settles (and
504
+ // runs this `finally`) AFTER the interactive has already taken over the
505
+ // lock and installed its own controller/promise. Guarding on identity
506
+ // (`fedCMActiveController === controller`) ensures the settling silent
507
+ // cannot null out the interactive request's in-progress state. The
508
+ // request that still owns the lock clears it; the superseded one is a
509
+ // no-op here.
510
+ if (fedCMActiveController === controller) {
511
+ fedCMRequestInProgress = false;
512
+ fedCMRequestPromise = null;
513
+ currentMediationMode = null;
514
+ fedCMActiveController = null;
515
+ }
425
516
  }
426
517
  })();
427
518
  return fedCMRequestPromise;
@@ -606,11 +697,52 @@ export function OxyServicesFedCMMixin(Base) {
606
697
  // Storage blocked
607
698
  }
608
699
  }
700
+ /**
701
+ * List the authenticated user's authorized RP apps.
702
+ *
703
+ * Returns the intersection of the user's FedCM grants and the currently-
704
+ * approved RP catalog — what powers the "Connected apps" management UI in
705
+ * @oxyhq/services. Requires a real user session; service tokens are
706
+ * rejected by the underlying endpoint.
707
+ */
708
+ async listAuthorizedApps() {
709
+ try {
710
+ const response = await this.makeRequest('GET', '/fedcm/me/authorized-apps', undefined, {
711
+ cache: true,
712
+ cacheTTL: 30 * 1000, // 30 second cache — short, this drives a manageable UI
713
+ });
714
+ return response.apps ?? [];
715
+ }
716
+ catch (error) {
717
+ throw this.handleError(error);
718
+ }
719
+ }
720
+ /**
721
+ * Revoke the authenticated user's authorization for a specific RP origin.
722
+ *
723
+ * The next FedCM sign-in from that origin will require explicit re-consent.
724
+ * The corresponding cache entry is invalidated so a subsequent
725
+ * `listAuthorizedApps()` call sees fresh data.
726
+ */
727
+ async revokeAuthorizedApp(origin) {
728
+ try {
729
+ await this.makeRequest('DELETE', `/fedcm/me/authorized-apps/${encodeURIComponent(origin)}`, undefined, { cache: false });
730
+ this.clearCacheEntry('GET:/fedcm/me/authorized-apps');
731
+ }
732
+ catch (error) {
733
+ throw this.handleError(error);
734
+ }
735
+ }
609
736
  },
610
737
  _a.DEFAULT_CONFIG_URL = 'https://auth.oxy.so/fedcm.json',
611
738
  _a.FEDCM_TIMEOUT = 15000 // 15 seconds for interactive
612
739
  ,
613
- _a.FEDCM_SILENT_TIMEOUT = 3000 // 3 seconds for silent mediation
740
+ // Silent mediation runs on page load (e.g. re-signing-in a user whose stored
741
+ // session was cleared after a cold-boot token fetch 401'd). The real silent
742
+ // round-trip — mint nonce → navigator.credentials.get → /fedcm/exchange — was
743
+ // measured to take more than 3s for live users, so a 3s budget timed out and
744
+ // left them signed out on reload. 10s gives ample margin while staying bounded.
745
+ _a.FEDCM_SILENT_TIMEOUT = 10000 // 10 seconds for silent mediation
614
746
  ,
615
747
  _a;
616
748
  }
@@ -77,7 +77,37 @@ export function OxyServicesPopupAuthMixin(Base) {
77
77
  clientId: window.location.origin,
78
78
  redirectUri: `${this.resolveAuthUrl()}/auth/callback`,
79
79
  });
80
- const popup = this.openCenteredPopup(authUrl, 'Oxy Sign In', width, height);
80
+ // If the caller pre-opened a popup on the raw user gesture (recommended
81
+ // path — see `openBlankPopup` and `PopupAuthOptions.popup`), navigate it
82
+ // to the auth URL instead of issuing a fresh `window.open` (which would
83
+ // be blocked once any prior `await` has consumed the user activation).
84
+ let popup;
85
+ const preOpened = options.popup ?? null;
86
+ if (preOpened) {
87
+ if (preOpened.closed) {
88
+ // The pre-opened popup is gone — distinguish a user cancel (they
89
+ // closed the blank window before sign-in could navigate it) from a
90
+ // blocker rejection. Lumping these together as "Popup blocked" is
91
+ // misleading: the popup was NOT blocked, it was opened successfully
92
+ // and then dismissed.
93
+ throw new OxyAuthenticationError('Sign-in window was closed before authentication could start.');
94
+ }
95
+ try {
96
+ preOpened.location.replace(authUrl);
97
+ }
98
+ catch (replaceError) {
99
+ // `location.replace` can throw in sandboxed / cross-origin-locked
100
+ // environments. Fall back to `href` assignment, which is more
101
+ // permissive. Logged at debug-level so consumers can correlate
102
+ // unusual sign-in behaviour without producing noise in normal flows.
103
+ debug.warn('location.replace failed, falling back to location.href', replaceError);
104
+ preOpened.location.href = authUrl;
105
+ }
106
+ popup = preOpened;
107
+ }
108
+ else {
109
+ popup = this.openCenteredPopup(authUrl, 'Oxy Sign In', width, height);
110
+ }
81
111
  if (!popup) {
82
112
  throw new OxyAuthenticationError('Popup blocked. Please allow popups for this site and try again.');
83
113
  }
@@ -220,6 +250,36 @@ export function OxyServicesPopupAuthMixin(Base) {
220
250
  document.body.removeChild(iframe);
221
251
  }
222
252
  }
253
+ /**
254
+ * Open a blank, centered popup window SYNCHRONOUSLY.
255
+ *
256
+ * Use this in a click (or other user-gesture) handler BEFORE any `await`
257
+ * to capture the transient user-activation. Pass the returned handle into
258
+ * `signInWithPopup({ popup })` once the async portion of the flow runs.
259
+ *
260
+ * Returns `null` if the browser's popup blocker rejected the open.
261
+ *
262
+ * @example
263
+ * ```typescript
264
+ * const onSignInClick = () => {
265
+ * const popup = oxyServices.openBlankPopup();
266
+ * (async () => {
267
+ * const silent = await oxyServices.silentSignInWithFedCM();
268
+ * if (silent) { popup?.close(); return; }
269
+ * await oxyServices.signInWithPopup({ popup });
270
+ * })();
271
+ * };
272
+ * ```
273
+ */
274
+ openBlankPopup(width, height) {
275
+ if (typeof window === 'undefined') {
276
+ return null;
277
+ }
278
+ const ctor = this.constructor;
279
+ const w = width ?? ctor.POPUP_WIDTH;
280
+ const h = height ?? ctor.POPUP_HEIGHT;
281
+ return this.openCenteredPopup('about:blank', 'Oxy Sign In', w, h);
282
+ }
223
283
  /**
224
284
  * Open a centered popup window
225
285
  *
@@ -215,6 +215,24 @@ export function OxyServicesUserMixin(Base) {
215
215
  throw this.handleError(error);
216
216
  }
217
217
  }
218
+ /**
219
+ * Update the authenticated user's notification preferences.
220
+ *
221
+ * Thin wrapper over `updateProfile` that constrains the patch to known
222
+ * notification channels — same persistence path, same cache invalidation,
223
+ * but type-safe at the call site.
224
+ */
225
+ async updateNotificationPreferences(preferences) {
226
+ return this.updateProfile({ notificationPreferences: preferences });
227
+ }
228
+ /**
229
+ * Update the authenticated user's general preferences (language, theme,
230
+ * reduce-motion, timezone). Persisted on the User document via
231
+ * `PUT /users/me` — same cache-invalidation behaviour as `updateProfile`.
232
+ */
233
+ async updateUserPreferences(preferences) {
234
+ return this.updateProfile({ userPreferences: preferences });
235
+ }
218
236
  /**
219
237
  * Request account verification
220
238
  */
@@ -108,3 +108,64 @@ export const createQuickAccount = (sessionId, userData, existingAccount, getFile
108
108
  avatarUrl,
109
109
  };
110
110
  };
111
+ /**
112
+ * Merge a fresh `/auth/refresh-all` snapshot into an existing QuickAccount
113
+ * list, preserving any cached fields (`avatarUrl`) for slots that didn't
114
+ * change. The fresh response is canonical: the resulting list contains EXACTLY
115
+ * the slots present in `fresh`, sorted by `authuser` ascending. Stale stored
116
+ * accounts that no longer appear in `fresh` are dropped (the server already
117
+ * authoritatively cleared the corresponding cookie).
118
+ *
119
+ * @param stored Previously persisted QuickAccount list (any order).
120
+ * @param fresh Server's authoritative refresh-all response.
121
+ * @returns Canonical merged list, sorted by `authuser` asc.
122
+ */
123
+ export const mergeAccountsFromRefreshAll = (stored, fresh) => {
124
+ const storedByAuthuser = new Map();
125
+ if (stored) {
126
+ for (const account of stored) {
127
+ if (typeof account.authuser === 'number') {
128
+ storedByAuthuser.set(account.authuser, account);
129
+ }
130
+ }
131
+ }
132
+ const merged = fresh.map((entry) => {
133
+ const previous = storedByAuthuser.get(entry.authuser);
134
+ // `entry.user` is null on the SDK legacy-fallback path; preserve any
135
+ // previously cached identity for that slot rather than overwriting
136
+ // it with blanks, and let the AuthManager's getCurrentUser() hydration
137
+ // refresh it on the next snapshot.
138
+ const wireUser = entry.user;
139
+ const username = wireUser?.username ?? previous?.username ?? '';
140
+ const displayName = getAccountDisplayName({
141
+ name: wireUser?.name,
142
+ username,
143
+ });
144
+ const avatar = wireUser?.avatar ?? previous?.avatar ?? undefined;
145
+ const avatarUrl = previous && previous.avatar === avatar ? previous.avatarUrl : undefined;
146
+ return {
147
+ sessionId: entry.sessionId,
148
+ userId: wireUser?.id ?? previous?.userId,
149
+ username,
150
+ displayName,
151
+ avatar,
152
+ avatarUrl,
153
+ authuser: entry.authuser,
154
+ color: wireUser?.color ?? previous?.color ?? null,
155
+ };
156
+ });
157
+ merged.sort((a, b) => {
158
+ const aIdx = a.authuser ?? Number.POSITIVE_INFINITY;
159
+ const bIdx = b.authuser ?? Number.POSITIVE_INFINITY;
160
+ return aIdx - bIdx;
161
+ });
162
+ return merged;
163
+ };
164
+ /**
165
+ * Return the account's preferred Bloom color preset, or `null` if it has no
166
+ * preference. Centralises the `color ?? null` normalisation so consumers can
167
+ * drive per-account theming without duplicating the nullish-handling.
168
+ */
169
+ export const getAccountColor = (account) => {
170
+ return account.color ?? null;
171
+ };