@oxyhq/core 1.11.22 → 1.11.24

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 (41) hide show
  1. package/README.md +2 -2
  2. package/dist/cjs/.tsbuildinfo +1 -1
  3. package/dist/cjs/HttpService.js +52 -0
  4. package/dist/cjs/OxyServices.base.js +16 -0
  5. package/dist/cjs/mixins/OxyServices.fedcm.js +169 -73
  6. package/dist/esm/.tsbuildinfo +1 -1
  7. package/dist/esm/HttpService.js +52 -0
  8. package/dist/esm/OxyServices.base.js +16 -0
  9. package/dist/esm/mixins/OxyServices.fedcm.js +169 -73
  10. package/dist/types/.tsbuildinfo +1 -1
  11. package/dist/types/HttpService.d.ts +31 -0
  12. package/dist/types/OxyServices.base.d.ts +14 -0
  13. package/dist/types/OxyServices.d.ts +9 -0
  14. package/dist/types/mixins/OxyServices.analytics.d.ts +1 -0
  15. package/dist/types/mixins/OxyServices.appData.d.ts +1 -0
  16. package/dist/types/mixins/OxyServices.assets.d.ts +1 -0
  17. package/dist/types/mixins/OxyServices.auth.d.ts +1 -0
  18. package/dist/types/mixins/OxyServices.contacts.d.ts +1 -0
  19. package/dist/types/mixins/OxyServices.developer.d.ts +1 -0
  20. package/dist/types/mixins/OxyServices.devices.d.ts +1 -0
  21. package/dist/types/mixins/OxyServices.features.d.ts +6 -1
  22. package/dist/types/mixins/OxyServices.fedcm.d.ts +20 -1
  23. package/dist/types/mixins/OxyServices.karma.d.ts +1 -0
  24. package/dist/types/mixins/OxyServices.language.d.ts +1 -0
  25. package/dist/types/mixins/OxyServices.location.d.ts +1 -0
  26. package/dist/types/mixins/OxyServices.managedAccounts.d.ts +1 -0
  27. package/dist/types/mixins/OxyServices.payment.d.ts +1 -0
  28. package/dist/types/mixins/OxyServices.popup.d.ts +1 -0
  29. package/dist/types/mixins/OxyServices.privacy.d.ts +1 -0
  30. package/dist/types/mixins/OxyServices.redirect.d.ts +1 -0
  31. package/dist/types/mixins/OxyServices.security.d.ts +1 -0
  32. package/dist/types/mixins/OxyServices.topics.d.ts +1 -0
  33. package/dist/types/mixins/OxyServices.user.d.ts +1 -0
  34. package/dist/types/mixins/OxyServices.utility.d.ts +1 -0
  35. package/package.json +1 -1
  36. package/src/HttpService.ts +53 -0
  37. package/src/OxyServices.base.ts +17 -0
  38. package/src/OxyServices.ts +10 -0
  39. package/src/mixins/OxyServices.fedcm.ts +187 -78
  40. package/src/mixins/__tests__/fedcm.test.ts +231 -0
  41. package/src/mixins/__tests__/onTokensChanged.test.ts +130 -0
@@ -106,6 +106,16 @@ export class HttpService {
106
106
  this.tokenRefreshPromise = null;
107
107
  this.tokenRefreshCooldownUntil = 0;
108
108
  this._onTokenRefreshed = null;
109
+ /**
110
+ * Fan-out listeners notified on EVERY access-token change on this instance:
111
+ * explicit `setTokens`, `clearTokens`, a successful silent refresh, and the
112
+ * internal 401-driven clear. Unlike the single-slot `_onTokenRefreshed`
113
+ * (owned by AuthManager for the refresh path only), this is a Set so multiple
114
+ * independent observers can mirror token state without clobbering each other.
115
+ *
116
+ * Each listener receives the resulting access token, or `null` when cleared.
117
+ */
118
+ this._tokenChangeListeners = new Set();
109
119
  // Acting-as identity for managed accounts
110
120
  this._actingAsUserId = null;
111
121
  // Performance monitoring
@@ -309,6 +319,7 @@ export class HttpService {
309
319
  // Refresh failed or no token — clear tokens and stale CSRF
310
320
  this.tokenStore.clearTokens();
311
321
  this.tokenStore.clearCsrfToken();
322
+ this.notifyTokenChange();
312
323
  }
313
324
  // On 403 with CSRF error, clear cached token and retry once
314
325
  if (response.status === 403 && !config._isCsrfRetry) {
@@ -688,6 +699,7 @@ export class HttpService {
688
699
  const { accessToken: newToken } = await response.json();
689
700
  this.tokenStore.setTokens(newToken);
690
701
  this._onTokenRefreshed?.(newToken);
702
+ this.notifyTokenChange();
691
703
  this.logger.debug('Token refreshed');
692
704
  return `Bearer ${newToken}`;
693
705
  }
@@ -753,6 +765,7 @@ export class HttpService {
753
765
  // Token management
754
766
  setTokens(accessToken, refreshToken = '') {
755
767
  this.tokenStore.setTokens(accessToken, refreshToken);
768
+ this.notifyTokenChange();
756
769
  }
757
770
  set onTokenRefreshed(callback) {
758
771
  this._onTokenRefreshed = callback;
@@ -760,6 +773,45 @@ export class HttpService {
760
773
  clearTokens() {
761
774
  this.tokenStore.clearTokens();
762
775
  this.tokenStore.clearCsrfToken();
776
+ this.notifyTokenChange();
777
+ }
778
+ /**
779
+ * Subscribe to access-token changes on this instance.
780
+ *
781
+ * Fires on every mutation of the access token — `setTokens`, `clearTokens`,
782
+ * a successful silent refresh, and the internal 401-driven clear — passing
783
+ * the resulting token (or `null` when cleared). Returns an unsubscribe
784
+ * function; call it on teardown to avoid leaks.
785
+ *
786
+ * This is the single hook downstream code (e.g. @oxyhq/services' OxyProvider)
787
+ * uses to keep an external token sink — such as the shared `oxyClient`
788
+ * singleton — in lockstep with the active session, regardless of which code
789
+ * path mutated the token.
790
+ */
791
+ addTokenChangeListener(listener) {
792
+ this._tokenChangeListeners.add(listener);
793
+ return () => {
794
+ this._tokenChangeListeners.delete(listener);
795
+ };
796
+ }
797
+ /**
798
+ * Notify all token-change listeners with the current access token.
799
+ * Listener exceptions are isolated so one bad subscriber cannot break token
800
+ * propagation to the others or to the calling auth flow.
801
+ * @internal
802
+ */
803
+ notifyTokenChange() {
804
+ if (this._tokenChangeListeners.size === 0)
805
+ return;
806
+ const accessToken = this.tokenStore.getAccessToken();
807
+ for (const listener of this._tokenChangeListeners) {
808
+ try {
809
+ listener(accessToken);
810
+ }
811
+ catch (error) {
812
+ this.logger.error('Token change listener threw:', error);
813
+ }
814
+ }
763
815
  }
764
816
  getAccessToken() {
765
817
  return this.tokenStore.getAccessToken();
@@ -110,6 +110,22 @@ export class OxyServicesBase {
110
110
  this._cachedUserId = undefined;
111
111
  this._cachedAccessToken = null;
112
112
  }
113
+ /**
114
+ * Subscribe to access-token changes on this client.
115
+ *
116
+ * The listener fires on every access-token mutation — explicit
117
+ * `setTokens`/`clearTokens`, a successful silent refresh, and the internal
118
+ * 401-driven clear — receiving the resulting token, or `null` when cleared.
119
+ * Returns an unsubscribe function.
120
+ *
121
+ * Primary use: keeping an external token sink (e.g. the shared `oxyClient`
122
+ * singleton) in lockstep with whichever `OxyServices` instance actually owns
123
+ * the session, so imperative consumers reading the singleton always observe
124
+ * the live token regardless of the code path that changed it.
125
+ */
126
+ onTokensChanged(listener) {
127
+ return this.httpService.addTokenChangeListener(listener);
128
+ }
113
129
  /**
114
130
  * Get the current user ID from the access token.
115
131
  * Caches the decoded value and invalidates when the token changes.
@@ -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,68 +148,105 @@ 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.');
167
- }
168
- if (errorMessage.includes('multiple accounts')) {
169
- throw new OxyAuthenticationError('Please sign out and sign in again to use FedCM with a single account');
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);
170
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);
176
172
  }
177
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 ?? '');
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;
249
+ }
178
250
  /**
179
251
  * Silent sign-in using FedCM
180
252
  *
@@ -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;
@@ -610,7 +701,12 @@ export function OxyServicesFedCMMixin(Base) {
610
701
  _a.DEFAULT_CONFIG_URL = 'https://auth.oxy.so/fedcm.json',
611
702
  _a.FEDCM_TIMEOUT = 15000 // 15 seconds for interactive
612
703
  ,
613
- _a.FEDCM_SILENT_TIMEOUT = 3000 // 3 seconds for silent mediation
704
+ // Silent mediation runs on page load (e.g. re-signing-in a user whose stored
705
+ // session was cleared after a cold-boot token fetch 401'd). The real silent
706
+ // round-trip — mint nonce → navigator.credentials.get → /fedcm/exchange — was
707
+ // measured to take more than 3s for live users, so a 3s budget timed out and
708
+ // left them signed out on reload. 10s gives ample margin while staying bounded.
709
+ _a.FEDCM_SILENT_TIMEOUT = 10000 // 10 seconds for silent mediation
614
710
  ,
615
711
  _a;
616
712
  }