@sparkvault/sdk-js 8.14.0 → 8.15.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.
package/README.md CHANGED
@@ -240,6 +240,8 @@ await fetch('/api/auth/login', {
240
240
  | `email` | `string` | Pre-fill email address (mutually exclusive with phone) |
241
241
  | `phone` | `string` | Pre-fill phone in E.164 format, e.g. `"+14155551234"` |
242
242
  | `backdropBlur` | `boolean` | Override backdrop blur setting from app config |
243
+ | `flow` | `"auto" \| "popup" \| "redirect"` | `"auto"` (default) and `"popup"` open the popup; `"redirect"` navigates the tab to the sign-in page instead (its return leg is `handleRedirectResult()`) |
244
+ | `prompt` | `"select_account"` | Always show the sign-in page's account chooser instead of silently continuing as the current account — the affordance for a "switch account" button. Any other value is ignored. |
243
245
  | `onCancel` | `function` | Callback when the person closes the popup without signing in |
244
246
  | `onSuccess` | `function` | Callback on success (before promise resolves) |
245
247
  | `onError` | `function` | Callback on error (before promise rejects) |
package/dist/index.d.ts CHANGED
@@ -193,6 +193,12 @@ interface VerifyOptions {
193
193
  * hosts that prefer a full-page redirect over a popup on mobile.
194
194
  */
195
195
  flow?: 'auto' | 'popup' | 'redirect';
196
+ /**
197
+ * `'select_account'` always shows the sign-in page's account chooser instead
198
+ * of silently continuing as the current account — even when only one saved
199
+ * account exists. Any other value is dropped at URL serialization.
200
+ */
201
+ prompt?: 'select_account';
196
202
  /**
197
203
  * Rendering strategy (internal). `'local'` renders the flow directly in this
198
204
  * document — used inside the popup that runs the flow, and forced for inline
@@ -215,6 +221,8 @@ interface AttachOptions {
215
221
  phone?: string;
216
222
  /** Auth context for OIDC/simple mode flows */
217
223
  authContext?: AuthContext;
224
+ /** `'select_account'` always shows the account chooser (see `VerifyOptions.prompt`) */
225
+ prompt?: 'select_account';
218
226
  /** Called when user cancels */
219
227
  onCancel?: () => void;
220
228
  /** Called when verification completes */
@@ -552,13 +560,24 @@ declare class IdentityModule {
552
560
  * session storage or WebCrypto is unavailable so callers can degrade.
553
561
  */
554
562
  private prepareHandoffNavigation;
563
+ /**
564
+ * Arm the self-heal marker for an in-flight sign-in. `hint` is the identifier
565
+ * (email or phone) the sign-in was started with, when the caller supplied
566
+ * one — the recovery bounce forwards it as the /sso `login_hint`, so with
567
+ * several hub sessions recovery re-mints the account this sign-in was for,
568
+ * never a different one.
569
+ */
555
570
  private markSignInPending;
556
571
  private clearSignInPending;
557
- /** True once (then cleared) if a recent sign-in is still awaiting its result. */
572
+ /**
573
+ * Consume the pending marker: `fresh` is true once (then cleared) if a recent
574
+ * sign-in is still awaiting its result; `hint` is the identifier that sign-in
575
+ * carried, for the recovery bounce's `login_hint`.
576
+ */
558
577
  private consumeSignInPending;
559
578
  /** Remove the result fragment from the URL bar (and history entry). */
560
579
  private clearUrlFragment;
561
- /** Drop the one-shot PKCE state/verifier a redirect bounce staged. */
580
+ /** Drop the one-shot PKCE state/verifier (+ recovery hint) a bounce staged. */
562
581
  private clearOneShotAuthState;
563
582
  private consumeRedirectResult;
564
583
  /**
@@ -180,13 +180,24 @@ export declare class IdentityModule {
180
180
  * session storage or WebCrypto is unavailable so callers can degrade.
181
181
  */
182
182
  private prepareHandoffNavigation;
183
+ /**
184
+ * Arm the self-heal marker for an in-flight sign-in. `hint` is the identifier
185
+ * (email or phone) the sign-in was started with, when the caller supplied
186
+ * one — the recovery bounce forwards it as the /sso `login_hint`, so with
187
+ * several hub sessions recovery re-mints the account this sign-in was for,
188
+ * never a different one.
189
+ */
183
190
  private markSignInPending;
184
191
  private clearSignInPending;
185
- /** True once (then cleared) if a recent sign-in is still awaiting its result. */
192
+ /**
193
+ * Consume the pending marker: `fresh` is true once (then cleared) if a recent
194
+ * sign-in is still awaiting its result; `hint` is the identifier that sign-in
195
+ * carried, for the recovery bounce's `login_hint`.
196
+ */
186
197
  private consumeSignInPending;
187
198
  /** Remove the result fragment from the URL bar (and history entry). */
188
199
  private clearUrlFragment;
189
- /** Drop the one-shot PKCE state/verifier a redirect bounce staged. */
200
+ /** Drop the one-shot PKCE state/verifier (+ recovery hint) a bounce staged. */
190
201
  private clearOneShotAuthState;
191
202
  private consumeRedirectResult;
192
203
  /**
@@ -51,6 +51,12 @@ export interface VerifyOptions {
51
51
  * hosts that prefer a full-page redirect over a popup on mobile.
52
52
  */
53
53
  flow?: 'auto' | 'popup' | 'redirect';
54
+ /**
55
+ * `'select_account'` always shows the sign-in page's account chooser instead
56
+ * of silently continuing as the current account — even when only one saved
57
+ * account exists. Any other value is dropped at URL serialization.
58
+ */
59
+ prompt?: 'select_account';
54
60
  /**
55
61
  * Rendering strategy (internal). `'local'` renders the flow directly in this
56
62
  * document — used inside the popup that runs the flow, and forced for inline
@@ -73,6 +79,8 @@ export interface AttachOptions {
73
79
  phone?: string;
74
80
  /** Auth context for OIDC/simple mode flows */
75
81
  authContext?: AuthContext;
82
+ /** `'select_account'` always shows the account chooser (see `VerifyOptions.prompt`) */
83
+ prompt?: 'select_account';
76
84
  /** Called when user cancels */
77
85
  onCancel?: () => void;
78
86
  /** Called when verification completes */
@@ -866,6 +866,12 @@ function buildSigninUrl(config, options, extras) {
866
866
  params.set('mode', 'simple');
867
867
  params.set('session', authContext.simpleMode.sessionId);
868
868
  }
869
+ // `prompt` is validated here, the single serialization point: only the exact
870
+ // literal reaches the sign-in page; anything else is silently dropped, so a
871
+ // plain-JS caller passing junk degrades to the default behavior.
872
+ if (options.prompt === 'select_account') {
873
+ params.set('prompt', 'select_account');
874
+ }
869
875
  if (extras) {
870
876
  params.set('redirect_uri', extras.redirectUri);
871
877
  params.set('state', extras.state);
@@ -8566,17 +8572,67 @@ const PORTAL_SECTIONS = ['home', 'identity', 'security', 'sessions', 'sites'];
8566
8572
  // listener but not sessionStorage) is what lets the next load self-heal.
8567
8573
  const PENDING_KEY = 'sv_signin_pending';
8568
8574
  const PENDING_TTL_MS = 10 * 60 * 1000;
8569
- /** True when the pending marker is present and still within its TTL. */
8570
- function hasFreshPendingMarker() {
8575
+ // One-shot: the identifier the recovery bounce is re-minting for. Written only
8576
+ // by the recovery bounce; the return leg consumes it to verify the redeemed
8577
+ // result is for that same account (see consumeHandoffFragment).
8578
+ const RECOVERY_HINT_KEY = 'sv_recovery_hint';
8579
+ /**
8580
+ * Normalize an identifier for equality, mirroring the server: trim, and
8581
+ * lowercase emails (a value containing '@'). Phones compare trimmed-exact.
8582
+ */
8583
+ function normalizeIdentity(value) {
8584
+ const trimmed = value.trim();
8585
+ return trimmed.includes('@') ? trimmed.toLowerCase() : trimmed;
8586
+ }
8587
+ /**
8588
+ * Read and parse the pending marker — JSON `{ at, hint }`, where `hint` is the
8589
+ * email or phone the sign-in was started with (null when the flow collects the
8590
+ * identifier itself). A bare-timestamp value is accepted as `{ at, hint: null }`:
8591
+ * markers live at most 10 minutes in sessionStorage, so any such value
8592
+ * disappears within one deploy window of this parser going live — the fallback
8593
+ * is bounded and never grows. Anything unreadable yields null.
8594
+ */
8595
+ function readPendingMarker() {
8571
8596
  let raw = null;
8572
8597
  try {
8573
8598
  raw = sessionStorage.getItem(PENDING_KEY);
8574
8599
  }
8575
8600
  catch {
8576
- return false;
8601
+ return null;
8602
+ }
8603
+ if (!raw) {
8604
+ return null;
8577
8605
  }
8578
- const at = raw ? Number(raw) : NaN;
8579
- return Number.isFinite(at) && Date.now() - at < PENDING_TTL_MS;
8606
+ let at = NaN;
8607
+ let hint = null;
8608
+ try {
8609
+ const parsed = JSON.parse(raw);
8610
+ if (typeof parsed === 'object' && parsed !== null) {
8611
+ const marker = parsed;
8612
+ if (typeof marker.at === 'number') {
8613
+ at = marker.at;
8614
+ }
8615
+ if (typeof marker.hint === 'string' && marker.hint) {
8616
+ hint = marker.hint;
8617
+ }
8618
+ }
8619
+ else if (typeof parsed === 'number') {
8620
+ // A bare timestamp parses as a JSON number.
8621
+ at = parsed;
8622
+ }
8623
+ }
8624
+ catch {
8625
+ at = Number(raw);
8626
+ }
8627
+ return Number.isFinite(at) ? { at, hint } : null;
8628
+ }
8629
+ /** True while a marker is within the self-heal TTL. */
8630
+ function isFreshPendingMarker(marker) {
8631
+ return marker !== null && Date.now() - marker.at < PENDING_TTL_MS;
8632
+ }
8633
+ /** True when the pending marker is present and still within its TTL. */
8634
+ function hasFreshPendingMarker() {
8635
+ return isFreshPendingMarker(readPendingMarker());
8580
8636
  }
8581
8637
  /**
8582
8638
  * Whether `handleRedirectResult()` has anything to do on this load — a returned
@@ -8846,7 +8902,8 @@ class IdentityModule {
8846
8902
  // the backgrounded opener tab, killing the postMessage listener),
8847
8903
  // handleRedirectResult() can silently self-heal on the next load from
8848
8904
  // the SSO session the popup login established.
8849
- this.markSignInPending();
8905
+ const pendingHint = mergedOptions.email || mergedOptions.phone || null;
8906
+ this.markSignInPending(pendingHint);
8850
8907
  this.launcher = new DialogLauncher(this.config, this.api, mergedOptions, {
8851
8908
  onSuccess: (result) => { this.clearSignInPending(); hostCallbacks.onSuccess(result); },
8852
8909
  onError: (error) => { this.clearSignInPending(); hostCallbacks.onError(error); },
@@ -8855,7 +8912,7 @@ class IdentityModule {
8855
8912
  // no-result end retires the marker (no spurious bounce on a reload
8856
8913
  // while the retry alert is up); "Try again" re-arms it.
8857
8914
  onPopupClosedUnresolved: () => this.clearSignInPending(),
8858
- onPopupReopened: () => this.markSignInPending(),
8915
+ onPopupReopened: () => this.markSignInPending(pendingHint),
8859
8916
  // COOP-severed popup: postMessage can never deliver, so switch this tab
8860
8917
  // to the redirect flow (returns via handleRedirectResult). The pending
8861
8918
  // marker stays armed — the returned #sv_code fragment retires it.
@@ -8893,6 +8950,7 @@ class IdentityModule {
8893
8950
  email: options.email,
8894
8951
  phone: options.phone,
8895
8952
  authContext: options.authContext,
8953
+ prompt: options.prompt,
8896
8954
  onSuccess: options.onSuccess,
8897
8955
  onError: options.onError,
8898
8956
  onCancel: options.onCancel,
@@ -9008,8 +9066,9 @@ class IdentityModule {
9008
9066
  }
9009
9067
  // No returned result. If a sign-in was in flight and its result never
9010
9068
  // arrived, self-heal once from the SSO session (mobile opener-tab discard).
9011
- if (this.consumeSignInPending()) {
9012
- await this.startRecoveryBounce();
9069
+ const pending = this.consumeSignInPending();
9070
+ if (pending.fresh) {
9071
+ await this.startRecoveryBounce(pending.hint);
9013
9072
  }
9014
9073
  return null;
9015
9074
  }
@@ -9026,9 +9085,11 @@ class IdentityModule {
9026
9085
  // (and a StrictMode double-invocation finds an empty hash and no-ops).
9027
9086
  let expectedState = null;
9028
9087
  let codeVerifier = null;
9088
+ let expectedRecoveryIdentity = null;
9029
9089
  try {
9030
9090
  expectedState = sessionStorage.getItem('sv_oauth_state');
9031
9091
  codeVerifier = sessionStorage.getItem('sv_pkce_verifier');
9092
+ expectedRecoveryIdentity = sessionStorage.getItem(RECOVERY_HINT_KEY);
9032
9093
  this.clearOneShotAuthState();
9033
9094
  }
9034
9095
  catch {
@@ -9058,6 +9119,18 @@ class IdentityModule {
9058
9119
  sessionId: raw.session_id ?? undefined,
9059
9120
  refreshToken: raw.refresh_token ?? undefined,
9060
9121
  };
9122
+ // A recovery bounce carries the identifier the interrupted sign-in was
9123
+ // addressing, but /sso treats a hint matching no hub session like no hint
9124
+ // at all (anti-oracle) — so the bounce can come back holding a DIFFERENT
9125
+ // single-eligible account. The client is the one place that knows which
9126
+ // account the person was signing in to: a mismatched result is discarded,
9127
+ // never handed to the host (a wrong-account handoff). Silent — no
9128
+ // onError — falling through to interactive sign-in, matching the recovery
9129
+ // flow's non-oracle posture.
9130
+ if (expectedRecoveryIdentity &&
9131
+ normalizeIdentity(expectedRecoveryIdentity) !== normalizeIdentity(result.identity)) {
9132
+ return null;
9133
+ }
9061
9134
  options.onSuccess?.(result);
9062
9135
  return result;
9063
9136
  }
@@ -9076,11 +9149,41 @@ class IdentityModule {
9076
9149
  * so a hostile/degraded environment simply never recovers rather than
9077
9150
  * erroring.
9078
9151
  */
9079
- async startRecoveryBounce() {
9080
- const nav = await this.prepareHandoffNavigation(`${this.config.identityBaseUrl}/${this.config.accountId}/sso`);
9152
+ async startRecoveryBounce(loginHint) {
9153
+ const sso = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/sso`);
9154
+ // With several hub sessions, login_hint tells /sso which account the
9155
+ // interrupted sign-in was addressing, so recovery never re-mints another.
9156
+ // Also stash it one-shot: a hint matching no hub session deliberately
9157
+ // behaves server-side like no hint at all (anti-oracle), so the return leg
9158
+ // must verify the redeemed identity is the one this sign-in was for.
9159
+ try {
9160
+ if (loginHint) {
9161
+ sessionStorage.setItem(RECOVERY_HINT_KEY, loginHint);
9162
+ }
9163
+ else {
9164
+ sessionStorage.removeItem(RECOVERY_HINT_KEY);
9165
+ }
9166
+ }
9167
+ catch {
9168
+ // No storage → prepareHandoffNavigation bails below; nothing to verify.
9169
+ }
9170
+ if (loginHint) {
9171
+ sso.searchParams.set('login_hint', loginHint);
9172
+ }
9173
+ const nav = await this.prepareHandoffNavigation(sso.toString());
9081
9174
  if (nav) {
9082
9175
  window.location.assign(nav);
9083
9176
  }
9177
+ else {
9178
+ // The bounce never left (no storage or WebCrypto) — retire the stash so
9179
+ // it cannot linger into an unrelated later return leg.
9180
+ try {
9181
+ sessionStorage.removeItem(RECOVERY_HINT_KEY);
9182
+ }
9183
+ catch {
9184
+ // Storage disabled: nothing was persisted, nothing to clear.
9185
+ }
9186
+ }
9084
9187
  }
9085
9188
  /**
9086
9189
  * Explicit `flow: 'redirect'` — navigate this tab to the interactive sign-in
@@ -9140,9 +9243,16 @@ class IdentityModule {
9140
9243
  url.searchParams.set('code_challenge', codeChallenge);
9141
9244
  return url.toString();
9142
9245
  }
9143
- markSignInPending() {
9246
+ /**
9247
+ * Arm the self-heal marker for an in-flight sign-in. `hint` is the identifier
9248
+ * (email or phone) the sign-in was started with, when the caller supplied
9249
+ * one — the recovery bounce forwards it as the /sso `login_hint`, so with
9250
+ * several hub sessions recovery re-mints the account this sign-in was for,
9251
+ * never a different one.
9252
+ */
9253
+ markSignInPending(hint) {
9144
9254
  try {
9145
- sessionStorage.setItem(PENDING_KEY, String(Date.now()));
9255
+ sessionStorage.setItem(PENDING_KEY, JSON.stringify({ at: Date.now(), hint }));
9146
9256
  }
9147
9257
  catch {
9148
9258
  // No storage → no self-heal; the popup still delivers when it can.
@@ -9156,11 +9266,16 @@ class IdentityModule {
9156
9266
  // Nothing to clear.
9157
9267
  }
9158
9268
  }
9159
- /** True once (then cleared) if a recent sign-in is still awaiting its result. */
9269
+ /**
9270
+ * Consume the pending marker: `fresh` is true once (then cleared) if a recent
9271
+ * sign-in is still awaiting its result; `hint` is the identifier that sign-in
9272
+ * carried, for the recovery bounce's `login_hint`.
9273
+ */
9160
9274
  consumeSignInPending() {
9161
- const fresh = hasFreshPendingMarker();
9275
+ const marker = readPendingMarker();
9276
+ const fresh = isFreshPendingMarker(marker);
9162
9277
  this.clearSignInPending();
9163
- return fresh;
9278
+ return { fresh, hint: fresh ? marker.hint : null };
9164
9279
  }
9165
9280
  /** Remove the result fragment from the URL bar (and history entry). */
9166
9281
  clearUrlFragment() {
@@ -9168,11 +9283,12 @@ class IdentityModule {
9168
9283
  window.history.replaceState(window.history.state, document.title, `${window.location.pathname}${window.location.search}`);
9169
9284
  }
9170
9285
  }
9171
- /** Drop the one-shot PKCE state/verifier a redirect bounce staged. */
9286
+ /** Drop the one-shot PKCE state/verifier (+ recovery hint) a bounce staged. */
9172
9287
  clearOneShotAuthState() {
9173
9288
  try {
9174
9289
  sessionStorage.removeItem('sv_oauth_state');
9175
9290
  sessionStorage.removeItem('sv_pkce_verifier');
9291
+ sessionStorage.removeItem(RECOVERY_HINT_KEY);
9176
9292
  }
9177
9293
  catch {
9178
9294
  // Storage disabled: nothing was persisted, nothing to clear.