@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
@@ -66,6 +66,33 @@ function isUnknownModeEnumError(error: unknown): boolean {
66
66
  );
67
67
  }
68
68
 
69
+ /**
70
+ * Detect a `navigator.credentials.get` rejection that is consistent with
71
+ * "the supplied loginHint matched no account at the IdP".
72
+ *
73
+ * When an RP passes a `loginHint` and the IdP returns accounts but NONE of them
74
+ * declare that hint in their `login_hints`, Chrome filters every account out,
75
+ * greys it in the chooser ("You can't sign in using this account"), logs
76
+ * "Accounts were received, but none matched the login hint…", and ultimately
77
+ * rejects the credential request — surfacing as a `NotAllowedError` /
78
+ * `AbortError` (the same shape as a user-cancelled or timed-out request). A
79
+ * stale hint left over from a previously-signed-in/test account therefore hard
80
+ * -blocks sign-in.
81
+ *
82
+ * We can only safely apply the clear-and-retry recovery when a `loginHint` was
83
+ * actually supplied; without one this is just a normal cancel/timeout and must
84
+ * NOT be retried. Callers gate on `hadLoginHint` before calling this.
85
+ */
86
+ function isPossibleHintMismatchError(error: unknown): boolean {
87
+ if (!(error instanceof Error)) return false;
88
+ // FedCM surfaces a filtered-out / no-eligible-account outcome as
89
+ // NotAllowedError (current Chrome) or AbortError (our own timeout abort while
90
+ // the chooser had no selectable account). Both are indistinguishable from a
91
+ // genuine user cancel at the API level, so the gate on "a hint was supplied"
92
+ // (in the caller) is what makes the retry safe and targeted.
93
+ return error.name === 'NotAllowedError' || error.name === 'AbortError';
94
+ }
95
+
69
96
  // Minimal structural types for the FedCM `navigator.credentials.get` surface.
70
97
  // The DOM lib does not ship these in every TypeScript version we build against,
71
98
  // so we model only the fields this mixin reads/writes. This lets the FedCM code
@@ -129,6 +156,11 @@ const FEDCM_LOGIN_HINT_KEY = 'oxy_fedcm_login_hint';
129
156
  let fedCMRequestInProgress = false;
130
157
  let fedCMRequestPromise: Promise<FedCMTokenResult | null> | null = null;
131
158
  let currentMediationMode: string | null = null;
159
+ // AbortController of the in-flight request, exposed at module scope so an
160
+ // arriving INTERACTIVE request can abort a slow/hung SILENT one instead of
161
+ // blocking on it (see requestIdentityCredential). Set when a request starts,
162
+ // cleared in that request's `finally`.
163
+ let fedCMActiveController: AbortController | null = null;
132
164
 
133
165
  /**
134
166
  * Federated Credential Management (FedCM) Authentication Mixin
@@ -159,13 +191,23 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
159
191
  public static readonly DEFAULT_CONFIG_URL = 'https://auth.oxy.so/fedcm.json';
160
192
 
161
193
  public resolveFedcmConfigUrl(): string {
194
+ // `DEFAULT_CONFIG_URL` is a static on the composed class; read it off the
195
+ // most-derived constructor through a typed cast (not `any`).
196
+ const configCtor = this.constructor as typeof OxyServicesBase & {
197
+ DEFAULT_CONFIG_URL: string;
198
+ };
162
199
  return this.config.authWebUrl
163
200
  ? `${this.config.authWebUrl}/fedcm.json`
164
- : (this.constructor as any).DEFAULT_CONFIG_URL;
201
+ : configCtor.DEFAULT_CONFIG_URL;
165
202
  }
166
203
 
167
204
  public static readonly FEDCM_TIMEOUT = 15000; // 15 seconds for interactive
168
- public static readonly FEDCM_SILENT_TIMEOUT = 3000; // 3 seconds for silent mediation
205
+ // Silent mediation runs on page load (e.g. re-signing-in a user whose stored
206
+ // session was cleared after a cold-boot token fetch 401'd). The real silent
207
+ // round-trip — mint nonce → navigator.credentials.get → /fedcm/exchange — was
208
+ // measured to take more than 3s for live users, so a 3s budget timed out and
209
+ // left them signed out on reload. 10s gives ample margin while staying bounded.
210
+ public static readonly FEDCM_SILENT_TIMEOUT = 10000; // 10 seconds for silent mediation
169
211
 
170
212
  /**
171
213
  * Check if FedCM is supported in the current browser
@@ -213,77 +255,121 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
213
255
  );
214
256
  }
215
257
 
216
- try {
217
- // Prefer a server-minted, origin-bound nonce so the downstream
218
- // `/fedcm/exchange` can validate it. A caller-supplied nonce is
219
- // respected as-is for advanced use cases.
220
- const nonce = options.nonce || (await this.getFedcmNonce());
221
- const clientId = this.getClientId();
222
-
223
- // Use provided loginHint, or fall back to stored last-used account ID
224
- const loginHint = options.loginHint || this.getStoredLoginHint();
225
-
226
- debug.log('Interactive sign-in: Requesting credential for', clientId, loginHint ? `(hint: ${loginHint})` : '');
227
-
228
- // Request credential from browser's native identity flow.
229
- // mode: 'active' signals this is a user-gesture-initiated (button) flow.
230
- // 'active' is the current W3C spec value; requestIdentityCredential
231
- // transparently retries with the legacy 'button' value for Chrome 125–131.
232
- const credential = await this.requestIdentityCredential({
233
- configURL: this.resolveFedcmConfigUrl(),
234
- clientId,
235
- nonce,
236
- context: options.context,
237
- loginHint,
238
- mode: 'active',
239
- });
258
+ // Use provided loginHint, or fall back to stored last-used account ID.
259
+ const initialLoginHint = options.loginHint || this.getStoredLoginHint();
240
260
 
241
- if (!credential || !credential.token) {
242
- throw new OxyAuthenticationError('No credential received from browser');
261
+ try {
262
+ return await this.attemptInteractiveSignIn(options, initialLoginHint);
263
+ } catch (error) {
264
+ // A STALE loginHint (e.g. left over from a previously-signed-in or test
265
+ // account) that matches no account at the IdP makes Chrome filter out
266
+ // every account and reject the request — indistinguishable from a user
267
+ // cancel. When that happens AND we supplied a hint, clear the bad hint
268
+ // and retry the credential request ONCE with no hint, which lets the
269
+ // chooser surface the genuinely available account(s). We only do this for
270
+ // a hint we pulled from storage (not a caller-supplied one), and only
271
+ // once, so a real cancel never loops.
272
+ const usedStoredHint = !!initialLoginHint && !options.loginHint;
273
+ if (usedStoredHint && isPossibleHintMismatchError(error)) {
274
+ debug.log(
275
+ 'Interactive sign-in: stored loginHint matched no account; clearing it and retrying without a hint'
276
+ );
277
+ this.clearLoginHint();
278
+ return await this.attemptInteractiveSignIn(options, undefined);
243
279
  }
280
+ throw this.normalizeInteractiveSignInError(error);
281
+ }
282
+ }
244
283
 
245
- debug.log('Interactive sign-in: Got credential, exchanging for session');
284
+ /**
285
+ * Run a single interactive FedCM credential request + token exchange for the
286
+ * given (possibly undefined) loginHint. A successful exchange plants the
287
+ * access token and persists the user id as the future loginHint — the hint is
288
+ * therefore only ever stored after a GENUINELY successful sign-in, never
289
+ * speculatively.
290
+ *
291
+ * @private
292
+ */
293
+ public async attemptInteractiveSignIn(
294
+ options: FedCMAuthOptions,
295
+ loginHint: string | undefined
296
+ ): Promise<SessionLoginResponse> {
297
+ // Prefer a server-minted, origin-bound nonce so the downstream
298
+ // `/fedcm/exchange` can validate it. A caller-supplied nonce is
299
+ // respected as-is for advanced use cases.
300
+ const nonce = options.nonce || (await this.getFedcmNonce());
301
+ const clientId = this.getClientId();
246
302
 
247
- // Exchange FedCM ID token for Oxy session
248
- const session = await this.exchangeIdTokenForSession(credential.token);
303
+ debug.log('Interactive sign-in: Requesting credential for', clientId, loginHint ? `(hint: ${loginHint})` : '');
249
304
 
250
- // Store access token in HttpService. `accessToken`/`refreshToken` are
251
- // declared optional on SessionLoginResponse; default the refresh token to
252
- // an empty string when the exchange did not return one.
253
- if (session?.accessToken) {
254
- this.httpService.setTokens(session.accessToken, session.refreshToken ?? '');
255
- }
305
+ // Request credential from browser's native identity flow.
306
+ // mode: 'active' signals this is a user-gesture-initiated (button) flow.
307
+ // 'active' is the current W3C spec value; requestIdentityCredential
308
+ // transparently retries with the legacy 'button' value for Chrome 125–131.
309
+ const credential = await this.requestIdentityCredential({
310
+ configURL: this.resolveFedcmConfigUrl(),
311
+ clientId,
312
+ nonce,
313
+ context: options.context,
314
+ loginHint,
315
+ mode: 'active',
316
+ });
256
317
 
257
- // Store the user ID as loginHint for future FedCM requests
258
- if (session?.user?.id) {
259
- this.storeLoginHint(session.user.id);
260
- }
318
+ if (!credential || !credential.token) {
319
+ throw new OxyAuthenticationError('No credential received from browser');
320
+ }
261
321
 
262
- debug.log('Interactive sign-in: Success!', { userId: session?.user?.id });
322
+ debug.log('Interactive sign-in: Got credential, exchanging for session');
263
323
 
264
- return session;
265
- } catch (error) {
266
- debug.log('Interactive sign-in failed:', error);
267
- const errorMessage = error instanceof Error ? error.message : String(error);
268
- // FedCM aborts/network failures surface as DOMException/Error instances,
269
- // both of which carry a `name`. Anything else has no meaningful name.
270
- const errorName = error instanceof Error ? error.name : '';
271
-
272
- if (errorName === 'AbortError') {
273
- throw new OxyAuthenticationError('Sign-in was cancelled by user');
274
- }
275
- if (errorName === 'NetworkError') {
276
- throw new OxyAuthenticationError('Network error during sign-in. Please check your connection.');
277
- }
278
- if (errorMessage.includes('multiple accounts')) {
279
- throw new OxyAuthenticationError('Please sign out and sign in again to use FedCM with a single account');
280
- }
281
- if (errorMessage.includes('retrieving a token') || errorMessage.includes('Error retrieving')) {
282
- debug.error('FedCM token retrieval error - this may be a browser or IdP configuration issue');
283
- throw new OxyAuthenticationError('Authentication failed. Please try again or use an alternative sign-in method.');
284
- }
285
- throw error;
324
+ // Exchange FedCM ID token for Oxy session
325
+ const session = await this.exchangeIdTokenForSession(credential.token);
326
+
327
+ // Store access token in HttpService. `accessToken`/`refreshToken` are
328
+ // declared optional on SessionLoginResponse; default the refresh token to
329
+ // an empty string when the exchange did not return one.
330
+ if (session?.accessToken) {
331
+ this.httpService.setTokens(session.accessToken, session.refreshToken ?? '');
332
+ }
333
+
334
+ // Store the user ID as loginHint for future FedCM requests — only now, after
335
+ // a real successful exchange, so we never persist a hint that cannot resolve.
336
+ if (session?.user?.id) {
337
+ this.storeLoginHint(session.user.id);
338
+ }
339
+
340
+ debug.log('Interactive sign-in: Success!', { userId: session?.user?.id });
341
+
342
+ return session;
343
+ }
344
+
345
+ /**
346
+ * Map a raw FedCM/exchange failure to a user-facing {@link OxyAuthenticationError}
347
+ * (or pass it through). Extracted so the clear-and-retry path can reuse the
348
+ * exact same error normalisation as the first attempt.
349
+ *
350
+ * @private
351
+ */
352
+ public normalizeInteractiveSignInError(error: unknown): unknown {
353
+ debug.log('Interactive sign-in failed:', error);
354
+ const errorMessage = error instanceof Error ? error.message : String(error);
355
+ // FedCM aborts/network failures surface as DOMException/Error instances,
356
+ // both of which carry a `name`. Anything else has no meaningful name.
357
+ const errorName = error instanceof Error ? error.name : '';
358
+
359
+ if (errorName === 'AbortError') {
360
+ return new OxyAuthenticationError('Sign-in was cancelled by user');
361
+ }
362
+ if (errorName === 'NetworkError') {
363
+ return new OxyAuthenticationError('Network error during sign-in. Please check your connection.');
364
+ }
365
+ if (errorMessage.includes('multiple accounts')) {
366
+ return new OxyAuthenticationError('Please sign out and sign in again to use FedCM with a single account');
286
367
  }
368
+ if (errorMessage.includes('retrieving a token') || errorMessage.includes('Error retrieving')) {
369
+ debug.error('FedCM token retrieval error - this may be a browser or IdP configuration issue');
370
+ return new OxyAuthenticationError('Authentication failed. Please try again or use an alternative sign-in method.');
371
+ }
372
+ return error;
287
373
  }
288
374
 
289
375
  /**
@@ -457,15 +543,20 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
457
543
  // If a request is already in progress...
458
544
  if (fedCMRequestInProgress && fedCMRequestPromise) {
459
545
  debug.log('Request already in progress, waiting...');
460
- // If current request is silent and new request is interactive,
461
- // wait for silent to finish, then make the interactive request
546
+ // If the in-flight request is SILENT and this new one is INTERACTIVE,
547
+ // abort the silent and proceed immediately. The silent round-trip can be
548
+ // slow (it runs on page load and may stall in the browser), and a user who
549
+ // just clicked "Sign In" must never be made to wait on — or be blocked by —
550
+ // it. Awaiting the silent here is what previously let a hung silent
551
+ // request deadlock the sign-in button, so we deliberately do NOT await it:
552
+ // we abort it (its own `finally` resets the lock as it settles) and fall
553
+ // through to start the interactive request synchronously below.
462
554
  if (currentMediationMode === 'silent' && isInteractive) {
463
- try {
464
- await fedCMRequestPromise;
465
- } catch {
466
- // Ignore silent request errors
467
- }
468
- // Now fall through to make the interactive request
555
+ debug.log('Aborting in-flight silent request to make way for interactive request');
556
+ fedCMActiveController?.abort();
557
+ // Fall through. The interactive request synchronously overwrites the
558
+ // lock globals (below); the aborted silent's `finally` uses identity
559
+ // guards so it cannot later clobber this interactive request's state.
469
560
  } else {
470
561
  // Same type of request - wait for the existing one
471
562
  try {
@@ -479,10 +570,17 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
479
570
  fedCMRequestInProgress = true;
480
571
  currentMediationMode = requestedMediation;
481
572
  const controller = new AbortController();
482
- // Use shorter timeout for silent mediation since it should be quick
573
+ fedCMActiveController = controller;
574
+ // Use shorter timeout for silent mediation since it should be quick.
575
+ // The timeout constants are static on the composed class; read them off the
576
+ // most-derived constructor through a typed cast (not `any`).
577
+ const timeoutCtor = this.constructor as typeof OxyServicesBase & {
578
+ FEDCM_SILENT_TIMEOUT: number;
579
+ FEDCM_TIMEOUT: number;
580
+ };
483
581
  const timeoutMs = requestedMediation === 'silent'
484
- ? (this.constructor as any).FEDCM_SILENT_TIMEOUT
485
- : (this.constructor as any).FEDCM_TIMEOUT;
582
+ ? timeoutCtor.FEDCM_SILENT_TIMEOUT
583
+ : timeoutCtor.FEDCM_TIMEOUT;
486
584
  const timeout = setTimeout(() => {
487
585
  debug.log('Request timed out after', timeoutMs, 'ms (mediation:', requestedMediation + ')');
488
586
  controller.abort();
@@ -562,9 +660,20 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
562
660
  throw error;
563
661
  } finally {
564
662
  clearTimeout(timeout);
565
- fedCMRequestInProgress = false;
566
- fedCMRequestPromise = null;
567
- currentMediationMode = null;
663
+ // Only reset the shared lock if it still belongs to THIS request. When an
664
+ // interactive request aborts a slow silent one, the silent settles (and
665
+ // runs this `finally`) AFTER the interactive has already taken over the
666
+ // lock and installed its own controller/promise. Guarding on identity
667
+ // (`fedCMActiveController === controller`) ensures the settling silent
668
+ // cannot null out the interactive request's in-progress state. The
669
+ // request that still owns the lock clears it; the superseded one is a
670
+ // no-op here.
671
+ if (fedCMActiveController === controller) {
672
+ fedCMRequestInProgress = false;
673
+ fedCMRequestPromise = null;
674
+ currentMediationMode = null;
675
+ fedCMActiveController = null;
676
+ }
568
677
  }
569
678
  })();
570
679
 
@@ -771,8 +880,71 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
771
880
  // Storage blocked
772
881
  }
773
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
+ }
774
929
  };
775
930
  }
776
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
+
777
949
  // Export the mixin function as both named and default
778
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
  */