@sparkvault/sdk-js 16.0.1 → 16.1.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/dist/index.cjs CHANGED
@@ -2175,8 +2175,11 @@ async function s256Challenge(verifier) {
2175
2175
  * already reaches the Identity origin, so its CSP needs no other origin for
2176
2176
  * the draw.
2177
2177
  *
2178
- * Request: `{ num_bytes }`, 1 to IDENTITY_DRAW_MAX_BYTES. Answer (in the
2179
- * `data` envelope): `{ value, num_bytes }`, the bytes as unpadded base64url.
2178
+ * Request: `{ num_bytes }`, 1 to IDENTITY_DRAW_MAX_BYTES; a sign-in's
2179
+ * reference is drawn as `{ num_bytes, purpose }`, its size and purpose as
2180
+ * ./identity-signin-contract.js SIGNIN_REFERENCE names them, against a budget
2181
+ * of its own. Answer (in the `data` envelope): `{ value, num_bytes }`, the
2182
+ * bytes as unpadded base64url.
2180
2183
  *
2181
2184
  * BROWSER-SAFE.
2182
2185
  */
@@ -2203,6 +2206,157 @@ function identityDrawBytes(answer, numBytes) {
2203
2206
  return bytes;
2204
2207
  }
2205
2208
 
2209
+ /**
2210
+ * The wire between the browser SDK's sign-in (packages/sdk-js
2211
+ * src/products/identity) and Identity's sign-in endpoints and pages: the
2212
+ * names and values both sides read, defined once so a start, a returned
2213
+ * fragment or a recovery bounce can never be written one way and read
2214
+ * another.
2215
+ *
2216
+ * - A start that leaves for a provider (`/{account}/social/{provider}`,
2217
+ * `/{account}/federation`) names its return by START_PARAMS; a silent
2218
+ * attempt through the account's own identity provider sends
2219
+ * `prompt=none` (FEDERATION_SILENT_PROMPT).
2220
+ * - The return comes back to the page that started it as a fragment: a
2221
+ * sign-in as `#token=…&state=…` (SIGNIN_RESULT_FRAGMENT), and a refusal of
2222
+ * the account's own identity provider as federationRefusalFragment builds
2223
+ * it and federationRefusalIn reads it.
2224
+ * - The sign-in page (`/{account}/signin`) takes `method=federation`
2225
+ * (SIGNIN_METHOD_PARAM, FEDERATION_METHOD) to start with the account's own
2226
+ * identity provider, whose button says federationButtonLabel's words.
2227
+ * - Every sign-in the SDK opens carries a reference (SIGNIN_REFERENCE) that
2228
+ * Identity records on the hub session the sign-in creates or chooses. A
2229
+ * sign-in whose popup result was lost recovers through `/{account}/sso`
2230
+ * naming that reference, and the recovery may only veto: it mints what the
2231
+ * same call without a reference would, and only when that hub session
2232
+ * carries this sign-in's reference.
2233
+ *
2234
+ * Browser-safe and dependency-free: the JS SDK bundles this module, and the
2235
+ * sign-in shells inline federationRefusalIn's own source into their pages.
2236
+ */
2237
+
2238
+ /** The query parameters a start that leaves for a provider names its return with. */
2239
+ const START_PARAMS = Object.freeze({
2240
+ redirectUri: 'redirect_uri',
2241
+ state: 'state',
2242
+ authRequestId: 'auth_request_id',
2243
+ prompt: 'prompt'
2244
+ });
2245
+
2246
+ /** The `prompt` a silent attempt through the account's own identity provider sends. */
2247
+ const FEDERATION_SILENT_PROMPT = 'none';
2248
+
2249
+ /** The fragment a provider round trip returns a sign-in in: `#token=…&state=…`. */
2250
+ const SIGNIN_RESULT_FRAGMENT = Object.freeze({ token: 'token', state: 'state' });
2251
+
2252
+ /** The sign-in page's parameter naming the method to start with, and the account's own identity provider as its value. */
2253
+ const SIGNIN_METHOD_PARAM = 'method';
2254
+ const FEDERATION_METHOD = 'federation';
2255
+
2256
+ /**
2257
+ * The words on the sign-in page's button for the account's own identity
2258
+ * provider, by the name the account gave it (`display_name`): the SDK's
2259
+ * sign-in draws the button with them, and the console's settings quote them
2260
+ * beside the name.
2261
+ *
2262
+ * @param {string} displayName
2263
+ * @returns {string}
2264
+ */
2265
+ function federationButtonLabel(displayName) {
2266
+ return `Continue with ${displayName}`;
2267
+ }
2268
+
2269
+ /**
2270
+ * The refusal a returned fragment carries (federationRefusalFragment), or
2271
+ * null for any other fragment. Whether it answers a sign-in this browser
2272
+ * started is the reader's check, against the `state` it stored before it
2273
+ * left.
2274
+ *
2275
+ * Self-contained: it reads nothing outside its own body, because the sign-in
2276
+ * shells inline its source (`String(federationRefusalIn)`) into their pages.
2277
+ *
2278
+ * @param {URLSearchParams} fragment - The returned fragment's parameters
2279
+ * @returns {'interaction_required'|'failed'|null}
2280
+ */
2281
+ function federationRefusalIn(fragment) {
2282
+ const error = fragment.get('error');
2283
+ if (error === 'interaction_required' && fragment.get('method') === 'federation') return 'interaction_required';
2284
+ if (error === 'federation_failed') return 'failed';
2285
+ return null;
2286
+ }
2287
+
2288
+ /**
2289
+ * How long a sign-in stays recoverable: the SDK's pending marker lives this
2290
+ * long, and Identity honours a sign-in reference recorded on a hub session at
2291
+ * most this long ago.
2292
+ */
2293
+ const SIGNIN_RECOVERY = Object.freeze({
2294
+ pendingTtlMs: 10 * 60 * 1000
2295
+ });
2296
+
2297
+ /**
2298
+ * A sign-in's reference: `bytes` drawn by the SDK that opens the sign-in page
2299
+ * (from the Entropy service, like its other values), unpadded base64url. It is
2300
+ * no secret and grants nothing by itself; it names one sign-in, and each
2301
+ * popup the SDK opens for it (the first, and each "Try again") draws its own.
2302
+ *
2303
+ * - `param`: the name it travels under, in a query (the sign-in page's URL,
2304
+ * a provider start, the recovery bounce to `/sso`) and in a JSON body (each
2305
+ * call that completes a sign-in, `/sso/continue`).
2306
+ * - `drawPurpose`: the `purpose` a draw of a reference names at the Identity
2307
+ * origin's draw (identity-entropy.js), which counts it against a budget of
2308
+ * its own, apart from the draws a sign-in needs to complete.
2309
+ * - `fromOpenerParam` = `fromOpenerValue`: the sign-in popup's URL says its
2310
+ * opener posts the reference (the popup opens inside the click, before any
2311
+ * draw can finish). The opener posts `{ type: message, [param] }` once its
2312
+ * pending marker holds the reference, or `[param]: null` once it knows the
2313
+ * popup has none right now; the popup asks again with
2314
+ * `{ type: retryMessage }`, and the opener then draws afresh.
2315
+ * - `fromOpenerParam` = `noRecoveryValue`: the SDK sent this page by redirect
2316
+ * with no reference and holds no pending marker for it (it removes any
2317
+ * first), so no recovery can ever stand in for the page's result, which the
2318
+ * page completes in its own window.
2319
+ * - `drawDeadlineMs`: the longest the opener waits for its draw. A draw that
2320
+ * fails or misses it leaves the popup without a reference for now, and one
2321
+ * that lands later is discarded.
2322
+ * - `openerWaitMs`: the longest the popup waits for its opener's message
2323
+ * before it treats the reference as unavailable for now. The popup renders
2324
+ * at once and never waits on it to show its first step. It exceeds
2325
+ * `drawDeadlineMs`: the popup starts waiting only once its page loads,
2326
+ * after the click that started the draw, so the opener always decides
2327
+ * first.
2328
+ * - `redirectWaitMs`: the longest a redirect waits for the reference its
2329
+ * popup's draw is still deciding (a popup whose handle the page's opener
2330
+ * policy severed), before it goes without one.
2331
+ */
2332
+ const SIGNIN_REFERENCE = Object.freeze({
2333
+ param: 'signin_ref',
2334
+ bytes: 32,
2335
+ drawPurpose: 'signin_reference',
2336
+ fromOpenerParam: 'signin_ref_from',
2337
+ fromOpenerValue: 'opener',
2338
+ noRecoveryValue: 'none',
2339
+ message: 'sparkvault-signin-ref',
2340
+ retryMessage: 'sparkvault-signin-ref-retry',
2341
+ drawDeadlineMs: 2500,
2342
+ openerWaitMs: 4000,
2343
+ redirectWaitMs: 500
2344
+ });
2345
+
2346
+ /**
2347
+ * Whether a value is a sign-in reference in its one spelling: 32 bytes as
2348
+ * 43 unpadded base64url characters.
2349
+ *
2350
+ * Self-contained, like federationRefusalIn: the sign-in shells inline its
2351
+ * source.
2352
+ *
2353
+ * @param {unknown} value
2354
+ * @returns {boolean}
2355
+ */
2356
+ function isSigninReference(value) {
2357
+ return typeof value === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value);
2358
+ }
2359
+
2206
2360
  /**
2207
2361
  * Request paths: the one way a module names a SparkVault route.
2208
2362
  *
@@ -2396,7 +2550,7 @@ function currentPageReturnUrl() {
2396
2550
  * delivery modes: the popup (opener + postMessage) and the same-tab redirect
2397
2551
  * (redirect_uri + state + code_challenge → one-time code in the fragment).
2398
2552
  */
2399
- function buildSigninUrl(config, options, extras) {
2553
+ function buildSigninUrl(config, options, delivery) {
2400
2554
  const params = new URLSearchParams({ origin: window.location.origin });
2401
2555
  // Identifier prefill - the sign-in page collects it itself when absent.
2402
2556
  if (options.email) {
@@ -2422,10 +2576,26 @@ function buildSigninUrl(config, options, extras) {
2422
2576
  if (options.prompt === 'select_account') {
2423
2577
  params.set('prompt', 'select_account');
2424
2578
  }
2425
- if (extras) {
2426
- params.set('redirect_uri', extras.redirectUri);
2427
- params.set('state', extras.state);
2428
- params.set('code_challenge', extras.codeChallenge);
2579
+ // `method` likewise: only the account's own identity provider can be asked
2580
+ // for by name, and only that literal reaches the sign-in page.
2581
+ if (options.method === FEDERATION_METHOD) {
2582
+ params.set(SIGNIN_METHOD_PARAM, FEDERATION_METHOD);
2583
+ }
2584
+ if (delivery.kind === 'popup') {
2585
+ params.set(SIGNIN_REFERENCE.fromOpenerParam, SIGNIN_REFERENCE.fromOpenerValue);
2586
+ }
2587
+ else {
2588
+ if (delivery.signinRef) {
2589
+ params.set(SIGNIN_REFERENCE.param, delivery.signinRef);
2590
+ }
2591
+ else {
2592
+ params.set(SIGNIN_REFERENCE.fromOpenerParam, SIGNIN_REFERENCE.noRecoveryValue);
2593
+ }
2594
+ if (delivery.handoff) {
2595
+ params.set('redirect_uri', delivery.handoff.redirectUri);
2596
+ params.set('state', delivery.handoff.state);
2597
+ params.set('code_challenge', delivery.handoff.codeChallenge);
2598
+ }
2429
2599
  }
2430
2600
  return `${config.identityBaseUrl}/${config.accountId}/signin?${params}`;
2431
2601
  }
@@ -2479,6 +2649,10 @@ class IdentityApi extends SparkVaultApi {
2479
2649
  this.configCache = null;
2480
2650
  this.config = config;
2481
2651
  }
2652
+ /** The account this API signs people in to. */
2653
+ get accountId() {
2654
+ return this.config.accountId;
2655
+ }
2482
2656
  get baseUrl() {
2483
2657
  return `${this.config.identityBaseUrl}${apiPath `/${this.config.accountId}`}`;
2484
2658
  }
@@ -2552,6 +2726,25 @@ class IdentityApi extends SparkVaultApi {
2552
2726
  const answer = await this.request('POST', apiPath `/entropy`, { num_bytes: AUTHORIZATION_DRAW.bytes });
2553
2727
  return authorizationValues(identityDrawBytes(answer, AUTHORIZATION_DRAW.bytes));
2554
2728
  }
2729
+ /**
2730
+ * A sign-in's reference (app-sdk SIGNIN_REFERENCE): its own draw through
2731
+ * the Identity origin, like drawAuthorizationValues, spelled unpadded
2732
+ * base64url. The draw names its purpose, so the origin counts it against a
2733
+ * budget of its own and a network's reference draws never spend the draws
2734
+ * its sign-ins need to complete. Rejects on a draw that fails (a spent
2735
+ * budget among them) or answers malformed.
2736
+ */
2737
+ async drawSigninReference() {
2738
+ const answer = await this.request('POST', apiPath `/entropy`, {
2739
+ num_bytes: SIGNIN_REFERENCE.bytes,
2740
+ purpose: SIGNIN_REFERENCE.drawPurpose,
2741
+ });
2742
+ const reference = bytesToBase64url(identityDrawBytes(answer, SIGNIN_REFERENCE.bytes));
2743
+ if (!isSigninReference(reference)) {
2744
+ throw new SparkVaultError('The Identity origin answered a malformed sign-in reference', 'invalid_response');
2745
+ }
2746
+ return reference;
2747
+ }
2555
2748
  /**
2556
2749
  * Check whether the SVID resolved from an email or phone has registered
2557
2750
  * passkeys (`has_passkey`; cross-tenant — single global RP), for a
@@ -2604,6 +2797,7 @@ class IdentityApi extends SparkVaultApi {
2604
2797
  pin: params.pin,
2605
2798
  recipient: params.recipient,
2606
2799
  ...this.buildAuthContextParams(params.authContext),
2800
+ ...signinRefParam(params.signinRef),
2607
2801
  });
2608
2802
  }
2609
2803
  /**
@@ -2646,6 +2840,7 @@ class IdentityApi extends SparkVaultApi {
2646
2840
  return this.request('POST', apiPath `/passkey/verify/complete`, {
2647
2841
  session: params.session,
2648
2842
  ...this.buildAuthContextParams(params.authContext),
2843
+ ...signinRefParam(params.signinRef),
2649
2844
  credential: {
2650
2845
  id: params.credential.id,
2651
2846
  rawId: arrayBufferToBase64url(params.credential.rawId),
@@ -2698,15 +2893,18 @@ class IdentityApi extends SparkVaultApi {
2698
2893
  });
2699
2894
  }
2700
2895
  /**
2701
- * Get OAuth redirect URL for social provider
2896
+ * Get OAuth redirect URL for social provider. The start carries the
2897
+ * sign-in's reference, when it has one, so the hub session the provider's
2898
+ * answer creates or chooses records it.
2702
2899
  */
2703
- getSocialAuthUrl(provider, redirectUri, state, authContext) {
2900
+ getSocialAuthUrl(provider, redirectUri, state, authContext, signinRef) {
2704
2901
  const params = new URLSearchParams({
2705
- redirect_uri: redirectUri,
2706
- state,
2902
+ [START_PARAMS.redirectUri]: redirectUri,
2903
+ [START_PARAMS.state]: state,
2904
+ ...signinRefParam(signinRef),
2707
2905
  });
2708
2906
  if (authContext?.authRequestId) {
2709
- params.set('auth_request_id', authContext.authRequestId);
2907
+ params.set(START_PARAMS.authRequestId, authContext.authRequestId);
2710
2908
  }
2711
2909
  const { simple_mode: simpleMode } = verifySessionParam(authContext);
2712
2910
  if (simpleMode) {
@@ -2714,15 +2912,42 @@ class IdentityApi extends SparkVaultApi {
2714
2912
  }
2715
2913
  return `${this.baseUrl}/social/${provider}?${params}`;
2716
2914
  }
2915
+ /**
2916
+ * The start of a sign-in with the account's own identity provider: the same
2917
+ * return as a social start (the page `redirectUri` names, answered with
2918
+ * `#token` and the `state` sent, or the OIDC auth request it continues), and
2919
+ * `prompt=none` for a silent attempt, which the provider answers without
2920
+ * showing anything. The start carries the sign-in's reference, when it has
2921
+ * one: such a sign-in opens no hub session, so Identity releases that
2922
+ * reference from the browser's hub sessions on its completion, and a
2923
+ * recovery naming it mints none of them. A verify session is never named:
2924
+ * such a sign-in cannot complete one, so its start refuses it, and a verify
2925
+ * session never admits the method.
2926
+ */
2927
+ getFederationAuthUrl(redirectUri, state, authContext, options = {}) {
2928
+ const params = new URLSearchParams({
2929
+ [START_PARAMS.redirectUri]: redirectUri,
2930
+ [START_PARAMS.state]: state,
2931
+ ...signinRefParam(options.signinRef),
2932
+ });
2933
+ if (authContext?.authRequestId) {
2934
+ params.set(START_PARAMS.authRequestId, authContext.authRequestId);
2935
+ }
2936
+ if (options.silent) {
2937
+ params.set(START_PARAMS.prompt, FEDERATION_SILENT_PROMPT);
2938
+ }
2939
+ return `${this.baseUrl}/federation?${params}`;
2940
+ }
2717
2941
  /**
2718
2942
  * Send SparkLink email for identity verification.
2719
2943
  * Includes connectionId for WebSocket push notification of verification result.
2720
2944
  */
2721
- async sendSparkLink(email, connectionId, authContext) {
2945
+ async sendSparkLink(email, connectionId, authContext, signinRef) {
2722
2946
  return this.request('POST', apiPath `/sparklink/send`, {
2723
2947
  email,
2724
2948
  connection_id: connectionId,
2725
2949
  ...this.buildAuthContextParams(authContext),
2950
+ ...signinRefParam(signinRef),
2726
2951
  });
2727
2952
  }
2728
2953
  /**
@@ -2749,6 +2974,15 @@ class IdentityApi extends SparkVaultApi {
2749
2974
  function verifySessionParam(authContext) {
2750
2975
  return authContext?.simpleMode ? { simple_mode: { session_id: authContext.simpleMode.sessionId } } : {};
2751
2976
  }
2977
+ /**
2978
+ * The sign-in's reference (app-sdk SIGNIN_REFERENCE) a call that completes a
2979
+ * sign-in carries, in a body or a provider start's query, so Identity records
2980
+ * it on the hub session the sign-in creates or chooses. None when the sign-in
2981
+ * has none.
2982
+ */
2983
+ function signinRefParam(signinRef) {
2984
+ return signinRef ? { [SIGNIN_REFERENCE.param]: signinRef } : {};
2985
+ }
2752
2986
  /**
2753
2987
  * Read a SparkLink result event. The WebSocket push and the kindling reclaim
2754
2988
  * carry the same server-built event, so this is the one reader for both.
@@ -3086,18 +3320,108 @@ const METHOD_REGISTRY = {
3086
3320
  icon: 'linkedin',
3087
3321
  provider: 'linkedin',
3088
3322
  },
3323
+ // The account's own identity provider. Its button names the provider the
3324
+ // way the account named it in `/config` (`federation.display_name`), so its
3325
+ // `name` here is only the registry's placeholder (enrichMethods replaces it).
3326
+ federation: {
3327
+ id: 'federation',
3328
+ type: 'federation',
3329
+ name: 'Your organization',
3330
+ description: '',
3331
+ icon: 'building',
3332
+ },
3089
3333
  };
3090
3334
  /**
3091
3335
  * Enrich method IDs with full metadata
3092
3336
  * @param ids - Array of method IDs from config
3337
+ * @param federation - The account's own identity provider as `/config` describes it;
3338
+ * without it no `federation` method is offered, for its button has no name to show
3093
3339
  * @returns Array of method metadata objects
3094
3340
  */
3095
- function enrichMethods(ids) {
3341
+ function enrichMethods(ids, federation) {
3096
3342
  return ids
3097
- .map(id => METHOD_REGISTRY[id])
3343
+ .map((id) => {
3344
+ if (id !== 'federation')
3345
+ return METHOD_REGISTRY[id];
3346
+ return federation ? { ...METHOD_REGISTRY.federation, name: federationButtonLabel(federation.display_name) } : undefined;
3347
+ })
3098
3348
  .filter((m) => m !== undefined);
3099
3349
  }
3100
3350
 
3351
+ /**
3352
+ * The browser side of a sign-in with the account's own identity provider, on
3353
+ * the Identity origin's sign-in pages: what the provider's round trip returned
3354
+ * in the fragment, and whether this tab already left for the provider without
3355
+ * the person's click.
3356
+ *
3357
+ * The Identity callback returns a sign-in the way it returns a social one
3358
+ * (`#token=…&state=…`, completed by `IdentityModule.render`), and its two
3359
+ * refusals as fragments of their own (app-sdk identity-signin-contract:
3360
+ * federationRefusalFragment writes them, federationRefusalIn reads them),
3361
+ * each with the `state` the start sent, read by `IdentityModule.render`
3362
+ * before the flow starts:
3363
+ * - `interaction_required`: a silent attempt the provider could not answer
3364
+ * without the person. The page offers the account's methods, this one
3365
+ * first, and never tries silently again.
3366
+ * - `failed`: the attempt failed. The page says so in fixed words, never
3367
+ * the provider's.
3368
+ */
3369
+ /** The error view's code for a failed sign-in through the account's own identity provider. */
3370
+ const FEDERATION_FAILED = 'federation_failed';
3371
+ /**
3372
+ * Marks a tab that left for the provider without the person's click: the
3373
+ * silent first attempt, a start the caller asked for (`method: 'federation'`),
3374
+ * or the provider as the only method. A person who comes Back from the
3375
+ * provider's page reloads this page with no fragment, and the marker stops it
3376
+ * leaving on its own again, so Back is never forwarded to the provider. Read
3377
+ * and removed by the next sign-in on the page (takeFederationAutoStart). It
3378
+ * names its account, so a sign-in page for another account in the same tab is
3379
+ * never held back by it.
3380
+ */
3381
+ const AUTO_START_KEY = 'sv_federation_auto_start';
3382
+ /** Identity's OAuth state lifetime: a round trip older than this cannot complete anyway. */
3383
+ const AUTO_START_TTL_MS = 15 * 60 * 1000;
3384
+ /** Record that this tab is leaving for the account's provider without the person's click. */
3385
+ function markFederationAutoStart(accountId) {
3386
+ try {
3387
+ sessionStorage.setItem(AUTO_START_KEY, JSON.stringify({ at: Date.now(), accountId }));
3388
+ }
3389
+ catch {
3390
+ // Storage disabled: the start's own state cannot be stored either, so the
3391
+ // sign-in fails before it leaves.
3392
+ }
3393
+ }
3394
+ /**
3395
+ * Whether this tab left for this account's provider on its own within the
3396
+ * state's lifetime. The record is removed either way: whatever it said, the
3397
+ * page's next sign-in has read it.
3398
+ */
3399
+ function takeFederationAutoStart(accountId) {
3400
+ let raw;
3401
+ try {
3402
+ raw = sessionStorage.getItem(AUTO_START_KEY);
3403
+ sessionStorage.removeItem(AUTO_START_KEY);
3404
+ }
3405
+ catch {
3406
+ return false;
3407
+ }
3408
+ if (raw === null)
3409
+ return false;
3410
+ try {
3411
+ const marker = JSON.parse(raw);
3412
+ if (typeof marker !== 'object' || marker === null)
3413
+ return false;
3414
+ const { at, accountId: markedAccount } = marker;
3415
+ return markedAccount === accountId
3416
+ && typeof at === 'number'
3417
+ && Number.isFinite(at)
3418
+ && Date.now() - at < AUTO_START_TTL_MS;
3419
+ }
3420
+ catch {
3421
+ return false;
3422
+ }
3423
+ }
3424
+
3101
3425
  /**
3102
3426
  * Verification State Manager
3103
3427
  *
@@ -3120,6 +3444,8 @@ class VerificationState {
3120
3444
  this._identityType = 'email';
3121
3445
  // Auth context for OIDC/simple mode flows
3122
3446
  this._authContext = undefined;
3447
+ // The sign-in's reference (app-sdk SIGNIN_REFERENCE), when the sign-in page has one
3448
+ this._signinRef = null;
3123
3449
  // Passkey state
3124
3450
  this._passkey = {
3125
3451
  hasPasskey: null,
@@ -3195,6 +3521,14 @@ class VerificationState {
3195
3521
  setAuthContext(context) {
3196
3522
  this._authContext = context;
3197
3523
  }
3524
+ // --- Sign-in reference ---
3525
+ /** The reference every call that completes this sign-in carries, else null. */
3526
+ get signinRef() {
3527
+ return this._signinRef;
3528
+ }
3529
+ setSigninRef(signinRef) {
3530
+ this._signinRef = signinRef;
3531
+ }
3198
3532
  // --- Passkey State ---
3199
3533
  get passkey() {
3200
3534
  return this._passkey;
@@ -3308,6 +3642,11 @@ class PopupLauncher {
3308
3642
  options.onReady?.();
3309
3643
  return;
3310
3644
  }
3645
+ if (options.requestType && data?.type === options.requestType) {
3646
+ if (event.source === popup)
3647
+ options.onRequest?.();
3648
+ return;
3649
+ }
3311
3650
  if (data?.type !== options.resultType) {
3312
3651
  return;
3313
3652
  }
@@ -3499,6 +3838,7 @@ class PasskeyHandler {
3499
3838
  session: challenge.session,
3500
3839
  credential,
3501
3840
  authContext: this.state.authContext,
3841
+ signinRef: this.state.signinRef,
3502
3842
  });
3503
3843
  return {
3504
3844
  success: true,
@@ -3590,6 +3930,14 @@ class PasskeyHandler {
3590
3930
  if (simpleMode) {
3591
3931
  params.set('simple_mode', JSON.stringify(simpleMode));
3592
3932
  }
3933
+ // The sign-in this ceremony completes, when the sign-in page has its
3934
+ // reference: the popup names it on the call that completes the sign-in, so
3935
+ // the hub session that call opens is bound to it and a lost result of this
3936
+ // sign-in still recovers.
3937
+ const { signinRef } = this.state;
3938
+ if (signinRef) {
3939
+ params.set(SIGNIN_REFERENCE.param, signinRef);
3940
+ }
3593
3941
  const hash = mode === 'register' && registrationToken
3594
3942
  ? `#${new URLSearchParams({ registration_token: registrationToken }).toString()}`
3595
3943
  : '';
@@ -3772,6 +4120,7 @@ class OtpHandler {
3772
4120
  pin: code,
3773
4121
  recipient: this.state.recipient,
3774
4122
  authContext: this.state.authContext,
4123
+ signinRef: this.state.signinRef,
3775
4124
  });
3776
4125
  // Primary factor accepted, but the account requires a second factor.
3777
4126
  // Not a success and not a retry — hand the ticket up to drive the 2FA step.
@@ -3840,7 +4189,7 @@ class SparkLinkHandler {
3840
4189
  */
3841
4190
  async send(connectionId) {
3842
4191
  try {
3843
- const result = await this.api.sendSparkLink(this.state.recipient, connectionId, this.state.authContext);
4192
+ const result = await this.api.sendSparkLink(this.state.recipient, connectionId, this.state.authContext, this.state.signinRef);
3844
4193
  return {
3845
4194
  success: true,
3846
4195
  expiresAt: result.expiresAt,
@@ -4019,16 +4368,25 @@ function validateOtpCode(code) {
4019
4368
  class LoadingView {
4020
4369
  constructor(props = {}) {
4021
4370
  this.message = props.message ?? 'Loading...';
4371
+ if (props.announce === true) {
4372
+ this.announcement = this.message;
4373
+ }
4022
4374
  }
4023
4375
  render() {
4024
4376
  const container = div('sv-loading');
4025
4377
  const spinner = document.createElement('div');
4026
4378
  spinner.className = 'sv-spinner';
4027
- spinner.setAttribute('role', 'status');
4028
- spinner.setAttribute('aria-label', 'Loading');
4029
4379
  const text = document.createElement('p');
4030
4380
  text.className = 'sv-loading-text';
4031
4381
  text.textContent = this.message;
4382
+ if (this.announcement !== undefined) {
4383
+ spinner.setAttribute('aria-hidden', 'true');
4384
+ text.setAttribute('aria-hidden', 'true');
4385
+ }
4386
+ else {
4387
+ spinner.setAttribute('role', 'status');
4388
+ spinner.setAttribute('aria-label', 'Loading');
4389
+ }
4032
4390
  container.appendChild(spinner);
4033
4391
  container.appendChild(text);
4034
4392
  return container;
@@ -4039,429 +4397,122 @@ class LoadingView {
4039
4397
  }
4040
4398
 
4041
4399
  /**
4042
- * Two consent lines, each in one wording for every surface that shows it: the
4043
- * SMS and voice consent beside a phone number, and the terms a signup
4044
- * accepts. Each line is split around the documents it links, and each document
4045
- * has its one address here: a surface draws the words between the links and
4046
- * links each document at TERMS_URL or PRIVACY_URL.
4400
+ * SVG Icon Factory
4047
4401
  *
4048
- * BROWSER-SAFE: data only, no imports. sdk-mobile mirrors it.
4402
+ * Bare outline glyphs per the SparkVault design system: stroke `currentColor`
4403
+ * so the stylesheet drives color, no tinted container backgrounds, round
4404
+ * caps/joins. Uses proper DOM element creation for security.
4049
4405
  */
4050
-
4051
- /** The terms of service, published once, on the marketing site. */
4052
- const TERMS_URL = 'https://sparkvault.com/terms/';
4053
-
4054
- /** The privacy policy, published once, on the marketing site. */
4055
- const PRIVACY_URL = 'https://sparkvault.com/privacy/';
4056
-
4406
+ function createSvgElement(viewBox, width = 16, height = 16) {
4407
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
4408
+ svg.setAttribute('viewBox', viewBox);
4409
+ svg.setAttribute('width', String(width));
4410
+ svg.setAttribute('height', String(height));
4411
+ svg.setAttribute('fill', 'none');
4412
+ svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
4413
+ return svg;
4414
+ }
4415
+ function createPath(d, attrs = {}) {
4416
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
4417
+ path.setAttribute('d', d);
4418
+ for (const [key, value] of Object.entries(attrs)) {
4419
+ path.setAttribute(key, value);
4420
+ }
4421
+ return path;
4422
+ }
4423
+ function createCircle(cx, cy, r, attrs = {}) {
4424
+ const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
4425
+ circle.setAttribute('cx', String(cx));
4426
+ circle.setAttribute('cy', String(cy));
4427
+ circle.setAttribute('r', String(r));
4428
+ for (const [key, value] of Object.entries(attrs)) {
4429
+ circle.setAttribute(key, value);
4430
+ }
4431
+ return circle;
4432
+ }
4057
4433
  /**
4058
- * Beside every field where a person enters a phone number SparkVault texts or
4059
- * calls (the sign-in field and the backup phone of Identity's sign-in, in
4060
- * sdk-js and sdk-mobile, the mobile app's backup phone, and auth.sv's new
4061
- * phone number), and under the sign-in's method picker wherever it offers a
4062
- * text or a call: a phone number the sign-in was handed reaches the picker
4063
- * without passing the field. The terms take the consent from whoever provides
4064
- * the number, so the words fit a number typed and a number handed over alike.
4065
- * A carrier approves the number SparkVault texts from only when this line, its
4066
- * call to action, names the service, the consent, how often messages come,
4067
- * that rates may apply, how to opt out and get help, and links the terms and
4068
- * the privacy policy, so it says each of them. It agrees with the terms' SMS
4069
- * and voice disclosures and the privacy policy (apps/www/terms.md 15,
4070
- * apps/www/privacy.md 1.1, held to them by
4071
- * apps/www/tests/consent-lines.test.mjs): texts carry the codes, alerts and
4072
- * notifications they name and calls only the codes, STOP opts the number out,
4073
- * HELP answers, frequency varies, rates may apply, and where texts and calls
4074
- * go and how to opt back in (START or UNSTOP) are the terms' to say.
4434
+ * Checkmark icon for benefit lists
4075
4435
  */
4076
- const SMS_CONSENT = Object.freeze({
4077
- beforeTerms: 'By providing a phone number, you agree to receive texts from SparkVault with verification codes, security alerts and account notifications, and automated calls with verification codes, as its ',
4078
- terms: 'Terms',
4079
- beforePrivacy: ' and ',
4080
- privacy: 'Privacy Policy',
4081
- afterPrivacy: ' describe. Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help.'
4082
- });
4083
-
4084
- /* global HTMLAnchorElement */
4436
+ function createCheckmarkIcon() {
4437
+ const svg = createSvgElement('0 0 16 16');
4438
+ svg.appendChild(createPath('M13.25 4.75L6 12 2.75 8.75', {
4439
+ stroke: 'currentColor',
4440
+ 'stroke-width': '2',
4441
+ 'stroke-linecap': 'round',
4442
+ 'stroke-linejoin': 'round',
4443
+ }));
4444
+ return svg;
4445
+ }
4085
4446
  /**
4086
- * SMS and Voice Consent
4087
- *
4088
- * The line the sign-in shows wherever a person gives SparkVault a phone number
4089
- * to text or call, in the platform's one wording
4090
- * (`@sparkvault/app-sdk/consent-lines`): under every field that takes one, and
4091
- * under the method picker wherever it offers a text or a call. It describes
4092
- * the field or the methods above it, so a screen reader reads it with them.
4447
+ * Back arrow (chevron left)
4093
4448
  */
4094
- /** A document the line names, linked in place and opening in a new tab. */
4095
- function documentLink(name, href) {
4096
- const link = document.createElement('a');
4097
- link.className = 'sv-sms-consent-link';
4098
- link.href = href;
4099
- link.target = '_blank';
4100
- link.rel = 'noopener noreferrer';
4101
- link.textContent = name;
4102
- return link;
4449
+ function createBackArrowIcon() {
4450
+ const svg = createSvgElement('0 0 16 16');
4451
+ svg.appendChild(createPath('M10 12L6 8L10 4', {
4452
+ stroke: 'currentColor',
4453
+ 'stroke-width': '2',
4454
+ 'stroke-linecap': 'round',
4455
+ 'stroke-linejoin': 'round',
4456
+ }));
4457
+ return svg;
4103
4458
  }
4104
4459
  /**
4105
- * The consent line, its "Terms" and "Privacy Policy" opening those documents
4106
- * in a new tab.
4107
- *
4108
- * @param id - The line's id, which the field or each method names in its `aria-describedby`
4460
+ * Close (X) icon
4109
4461
  */
4110
- function smsConsent(id) {
4111
- const line = document.createElement('p');
4112
- line.className = 'sv-sms-consent';
4113
- line.id = id;
4114
- line.append(SMS_CONSENT.beforeTerms, documentLink(SMS_CONSENT.terms, TERMS_URL), SMS_CONSENT.beforePrivacy, documentLink(SMS_CONSENT.privacy, PRIVACY_URL), SMS_CONSENT.afterPrivacy);
4115
- return line;
4462
+ function createCloseIcon() {
4463
+ const svg = createSvgElement('0 0 20 20', 20, 20);
4464
+ svg.appendChild(createPath('M15 5L5 15M5 5L15 15', {
4465
+ stroke: 'currentColor',
4466
+ 'stroke-width': '1.5',
4467
+ 'stroke-linecap': 'round',
4468
+ }));
4469
+ return svg;
4116
4470
  }
4117
-
4118
4471
  /**
4119
- * Identity Input View
4120
- *
4121
- * Collects and validates the user's email or phone number: reads the input as
4122
- * one or the other by the platform's rules (`@sparkvault/app-sdk/phone` and
4123
- * `@sparkvault/app-sdk/email-address`), and formats a phone-only field as the
4124
- * number is typed. A field that takes a phone number carries the SMS and voice
4125
- * consent beneath it.
4472
+ * Passkey icon - bare outline key design
4126
4473
  */
4127
- class IdentityInputView {
4128
- constructor(props) {
4129
- this.inputElement = null;
4130
- this.labelElement = null;
4131
- this.submitButton = null;
4132
- this.passkeyLink = null;
4133
- this.errorContainer = null;
4134
- this.focusTimeoutId = null;
4135
- this.detectedType = 'email';
4136
- this.props = props;
4137
- this.boundHandleInput = () => this.handleInput();
4138
- this.boundHandleKeyDown = (e) => {
4139
- if (e.key === 'Enter') {
4140
- e.preventDefault();
4141
- this.handleSubmit();
4142
- }
4143
- };
4144
- this.boundHandleSubmit = () => this.handleSubmit();
4145
- this.boundHandlePasskey = props.onPasskey ? () => props.onPasskey() : null;
4146
- }
4147
- get allowsBoth() {
4148
- return this.props.allowedTypes.includes('email') && this.props.allowedTypes.includes('phone');
4149
- }
4150
- get allowsEmail() {
4151
- return this.props.allowedTypes.includes('email');
4152
- }
4153
- get allowsPhone() {
4154
- return this.props.allowedTypes.includes('phone');
4155
- }
4156
- render() {
4157
- const container = div('sv-email-view');
4158
- // Compact header - just the subtitle instruction
4159
- const headerSection = div('sv-email-header');
4160
- const subtitle = document.createElement('p');
4161
- subtitle.className = 'sv-email-subtitle';
4162
- subtitle.textContent = this.getSubtitleText();
4163
- headerSection.appendChild(subtitle);
4164
- container.appendChild(headerSection);
4165
- // Error container
4166
- this.errorContainer = div('sv-email-error-container');
4167
- if (this.props.error) {
4168
- this.errorContainer.appendChild(errorMessage(this.props.error));
4169
- }
4170
- container.appendChild(this.errorContainer);
4171
- // Form section
4172
- const formSection = div('sv-email-form');
4173
- const inputWrapper = div('sv-email-input-wrapper');
4174
- this.labelElement = document.createElement('label');
4175
- this.labelElement.className = 'sv-email-label';
4176
- this.labelElement.htmlFor = 'sv-identity-input';
4177
- this.labelElement.textContent = this.getLabelText();
4178
- this.inputElement = document.createElement('input');
4179
- this.inputElement.type = this.allowsPhone && !this.allowsEmail ? 'tel' : 'text';
4180
- this.inputElement.id = 'sv-identity-input';
4181
- this.inputElement.className = 'sv-email-input';
4182
- this.inputElement.placeholder = this.getPlaceholderText();
4183
- this.inputElement.autocomplete = this.allowsBoth ? 'on' : (this.allowsEmail ? 'email' : 'tel');
4184
- this.inputElement.required = true;
4185
- this.inputElement.maxLength = EMAIL_ADDRESS_LIMITS.ADDRESS;
4186
- if (this.props.initialValue) {
4187
- this.inputElement.value = this.props.initialValue;
4188
- this.detectAndUpdateType(this.props.initialValue);
4189
- }
4190
- this.inputElement.addEventListener('input', this.boundHandleInput);
4191
- this.inputElement.addEventListener('keydown', this.boundHandleKeyDown);
4192
- inputWrapper.appendChild(this.labelElement);
4193
- inputWrapper.appendChild(this.inputElement);
4194
- if (this.allowsPhone) {
4195
- const consent = smsConsent('sv-identity-sms-consent');
4196
- this.inputElement.setAttribute('aria-describedby', consent.id);
4197
- inputWrapper.appendChild(consent);
4198
- }
4199
- formSection.appendChild(inputWrapper);
4200
- this.submitButton = document.createElement('button');
4201
- this.submitButton.className = 'sv-btn sv-btn-email-primary';
4202
- this.submitButton.textContent = 'Continue';
4203
- this.submitButton.addEventListener('click', this.boundHandleSubmit);
4204
- formSection.appendChild(this.submitButton);
4205
- container.appendChild(formSection);
4206
- if (this.boundHandlePasskey) {
4207
- this.passkeyLink = document.createElement('button');
4208
- this.passkeyLink.className = 'sv-fallback-link';
4209
- this.passkeyLink.textContent = 'Sign in with a passkey';
4210
- this.passkeyLink.addEventListener('click', this.boundHandlePasskey);
4211
- container.appendChild(this.passkeyLink);
4212
- }
4213
- this.focusTimeoutId = setTimeout(() => this.inputElement?.focus(), 50);
4214
- return container;
4215
- }
4216
- getSubtitleText() {
4217
- if (this.allowsBoth)
4218
- return 'Enter your email or phone to continue';
4219
- if (this.allowsPhone)
4220
- return 'Enter your phone number to continue';
4221
- return 'Enter your email to continue';
4222
- }
4223
- getLabelText() {
4224
- if (this.allowsBoth) {
4225
- return this.detectedType === 'phone' ? 'Phone number' : 'Email address';
4226
- }
4227
- if (this.allowsPhone)
4228
- return 'Phone number';
4229
- return 'Email address';
4230
- }
4231
- getPlaceholderText() {
4232
- if (this.allowsBoth)
4233
- return 'you@example.com or (555) 123-4567';
4234
- if (this.allowsPhone)
4235
- return '(555) 123-4567';
4236
- return 'you@example.com';
4237
- }
4238
- handleInput() {
4239
- this.clearError();
4240
- if (!this.inputElement)
4241
- return;
4242
- const value = this.inputElement.value;
4243
- if (this.allowsBoth) {
4244
- // The label follows what the input reads as, but the text is never
4245
- // rewritten: digits typed so far can still begin an email address
4246
- // ("2024user@gmail.com", "12345678@qq.com"), and phone formatting would
4247
- // corrupt it. Submit normalizes a phone number whatever its separators.
4248
- const wasPhone = this.detectedType === 'phone';
4249
- this.detectAndUpdateType(value);
4250
- if (wasPhone !== (this.detectedType === 'phone') && this.labelElement) {
4251
- this.labelElement.textContent = this.getLabelText();
4252
- }
4253
- }
4254
- else if (this.allowsPhone) {
4255
- // Phone-only mode: always format
4256
- const cursorPos = this.inputElement.selectionStart ?? value.length;
4257
- const formatted = formatPhoneDisplay(value);
4258
- if (formatted !== value) {
4259
- this.inputElement.value = formatted;
4260
- const newPos = Math.min(cursorPos + (formatted.length - value.length), formatted.length);
4261
- this.inputElement.setSelectionRange(newPos, newPos);
4262
- }
4263
- }
4264
- }
4265
- detectAndUpdateType(value) {
4266
- this.detectedType = inferIdentityType(value);
4267
- }
4268
- clearError() {
4269
- if (this.errorContainer) {
4270
- clearChildren(this.errorContainer);
4271
- }
4272
- this.inputElement?.classList.remove('sv-email-input-error');
4273
- }
4274
- showError(message) {
4275
- if (this.errorContainer) {
4276
- clearChildren(this.errorContainer);
4277
- this.errorContainer.appendChild(errorMessage(message));
4278
- }
4279
- this.inputElement?.classList.add('sv-email-input-error');
4280
- this.inputElement?.focus();
4281
- }
4282
- handleSubmit() {
4283
- if (!this.inputElement || !this.submitButton)
4284
- return;
4285
- const rawValue = this.inputElement.value;
4286
- // Validate based on detected type
4287
- if (this.allowsBoth) {
4288
- if (this.detectedType === 'phone') {
4289
- const validPhone = parsePhone(rawValue);
4290
- if (!validPhone) {
4291
- this.showError('Please enter a valid phone number');
4292
- return;
4293
- }
4294
- this.submitButton.disabled = true;
4295
- this.submitButton.textContent = 'Please wait...';
4296
- this.props.onSubmit({ value: validPhone, type: 'phone' });
4297
- }
4298
- else {
4299
- const validEmail = validateEmail(rawValue);
4300
- if (!validEmail) {
4301
- this.showError('Please enter a valid email address');
4302
- return;
4303
- }
4304
- this.submitButton.disabled = true;
4305
- this.submitButton.textContent = 'Please wait...';
4306
- this.props.onSubmit({ value: validEmail, type: 'email' });
4307
- }
4308
- }
4309
- else if (this.allowsPhone) {
4310
- const validPhone = parsePhone(rawValue);
4311
- if (!validPhone) {
4312
- this.showError('Please enter a valid phone number');
4313
- return;
4314
- }
4315
- this.submitButton.disabled = true;
4316
- this.submitButton.textContent = 'Please wait...';
4317
- this.props.onSubmit({ value: validPhone, type: 'phone' });
4318
- }
4319
- else {
4320
- const validEmail = validateEmail(rawValue);
4321
- if (!validEmail) {
4322
- this.showError('Please enter a valid email address');
4323
- return;
4324
- }
4325
- this.submitButton.disabled = true;
4326
- this.submitButton.textContent = 'Please wait...';
4327
- this.props.onSubmit({ value: validEmail, type: 'email' });
4328
- }
4329
- }
4330
- destroy() {
4331
- if (this.focusTimeoutId !== null) {
4332
- clearTimeout(this.focusTimeoutId);
4333
- this.focusTimeoutId = null;
4334
- }
4335
- if (this.inputElement) {
4336
- this.inputElement.removeEventListener('input', this.boundHandleInput);
4337
- this.inputElement.removeEventListener('keydown', this.boundHandleKeyDown);
4338
- }
4339
- if (this.submitButton) {
4340
- this.submitButton.removeEventListener('click', this.boundHandleSubmit);
4341
- }
4342
- if (this.passkeyLink && this.boundHandlePasskey) {
4343
- this.passkeyLink.removeEventListener('click', this.boundHandlePasskey);
4344
- }
4345
- }
4474
+ function createPasskeyIcon() {
4475
+ const svg = createSvgElement('0 0 56 56', 56, 56);
4476
+ svg.classList.add('sv-passkey-icon');
4477
+ // Key glyph optically centered in the 56px box (footprint unchanged)
4478
+ const group = document.createElementNS('http://www.w3.org/2000/svg', 'g');
4479
+ group.setAttribute('transform', 'translate(29.5, 26.5)');
4480
+ const strokeAttrs = {
4481
+ stroke: 'currentColor',
4482
+ 'stroke-width': '3',
4483
+ 'stroke-linecap': 'round',
4484
+ 'stroke-linejoin': 'round',
4485
+ fill: 'none',
4486
+ };
4487
+ // Key head (circle)
4488
+ group.appendChild(createCircle(-9.5, -9.5, 9.5, strokeAttrs));
4489
+ // Key shaft
4490
+ group.appendChild(createPath('M-2.8 -2.8L16 16', strokeAttrs));
4491
+ // Key teeth
4492
+ group.appendChild(createPath('M9.5 9.5L9.5 15.5', strokeAttrs));
4493
+ group.appendChild(createPath('M16 16L16 22', strokeAttrs));
4494
+ svg.appendChild(group);
4495
+ return svg;
4346
4496
  }
4347
-
4348
4497
  /**
4349
- * SVG Icon Factory
4350
- *
4351
- * Bare outline glyphs per the SparkVault design system: stroke `currentColor`
4352
- * so the stylesheet drives color, no tinted container backgrounds, round
4353
- * caps/joins. Uses proper DOM element creation for security.
4498
+ * Bare outline alert triangle shared by the error and expired icons.
4499
+ * Color comes from `currentColor` via the class-specific stylesheet rules.
4354
4500
  */
4355
- function createSvgElement(viewBox, width = 16, height = 16) {
4356
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
4357
- svg.setAttribute('viewBox', viewBox);
4358
- svg.setAttribute('width', String(width));
4359
- svg.setAttribute('height', String(height));
4360
- svg.setAttribute('fill', 'none');
4361
- svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
4362
- return svg;
4363
- }
4364
- function createPath(d, attrs = {}) {
4365
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
4366
- path.setAttribute('d', d);
4367
- for (const [key, value] of Object.entries(attrs)) {
4368
- path.setAttribute(key, value);
4369
- }
4370
- return path;
4371
- }
4372
- function createCircle(cx, cy, r, attrs = {}) {
4373
- const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
4374
- circle.setAttribute('cx', String(cx));
4375
- circle.setAttribute('cy', String(cy));
4376
- circle.setAttribute('r', String(r));
4377
- for (const [key, value] of Object.entries(attrs)) {
4378
- circle.setAttribute(key, value);
4379
- }
4380
- return circle;
4381
- }
4382
- /**
4383
- * Checkmark icon for benefit lists
4384
- */
4385
- function createCheckmarkIcon() {
4386
- const svg = createSvgElement('0 0 16 16');
4387
- svg.appendChild(createPath('M13.25 4.75L6 12 2.75 8.75', {
4388
- stroke: 'currentColor',
4389
- 'stroke-width': '2',
4390
- 'stroke-linecap': 'round',
4391
- 'stroke-linejoin': 'round',
4392
- }));
4393
- return svg;
4394
- }
4395
- /**
4396
- * Back arrow (chevron left)
4397
- */
4398
- function createBackArrowIcon() {
4399
- const svg = createSvgElement('0 0 16 16');
4400
- svg.appendChild(createPath('M10 12L6 8L10 4', {
4401
- stroke: 'currentColor',
4402
- 'stroke-width': '2',
4403
- 'stroke-linecap': 'round',
4404
- 'stroke-linejoin': 'round',
4405
- }));
4406
- return svg;
4407
- }
4408
- /**
4409
- * Close (X) icon
4410
- */
4411
- function createCloseIcon() {
4412
- const svg = createSvgElement('0 0 20 20', 20, 20);
4413
- svg.appendChild(createPath('M15 5L5 15M5 5L15 15', {
4414
- stroke: 'currentColor',
4415
- 'stroke-width': '1.5',
4416
- 'stroke-linecap': 'round',
4417
- }));
4418
- return svg;
4419
- }
4420
- /**
4421
- * Passkey icon - bare outline key design
4422
- */
4423
- function createPasskeyIcon() {
4424
- const svg = createSvgElement('0 0 56 56', 56, 56);
4425
- svg.classList.add('sv-passkey-icon');
4426
- // Key glyph optically centered in the 56px box (footprint unchanged)
4427
- const group = document.createElementNS('http://www.w3.org/2000/svg', 'g');
4428
- group.setAttribute('transform', 'translate(29.5, 26.5)');
4429
- const strokeAttrs = {
4430
- stroke: 'currentColor',
4431
- 'stroke-width': '3',
4432
- 'stroke-linecap': 'round',
4433
- 'stroke-linejoin': 'round',
4434
- fill: 'none',
4435
- };
4436
- // Key head (circle)
4437
- group.appendChild(createCircle(-9.5, -9.5, 9.5, strokeAttrs));
4438
- // Key shaft
4439
- group.appendChild(createPath('M-2.8 -2.8L16 16', strokeAttrs));
4440
- // Key teeth
4441
- group.appendChild(createPath('M9.5 9.5L9.5 15.5', strokeAttrs));
4442
- group.appendChild(createPath('M16 16L16 22', strokeAttrs));
4443
- svg.appendChild(group);
4444
- return svg;
4445
- }
4446
- /**
4447
- * Bare outline alert triangle shared by the error and expired icons.
4448
- * Color comes from `currentColor` via the class-specific stylesheet rules.
4449
- */
4450
- function createAlertTriangleIcon(className) {
4451
- const svg = createSvgElement('0 0 48 48', 48, 48);
4452
- svg.classList.add(className);
4453
- const strokeAttrs = {
4454
- stroke: 'currentColor',
4455
- 'stroke-width': '2.5',
4456
- 'stroke-linecap': 'round',
4457
- 'stroke-linejoin': 'round',
4458
- fill: 'none',
4459
- };
4460
- // Triangle outline
4461
- svg.appendChild(createPath('M24 9L5.5 39h37L24 9z', strokeAttrs));
4462
- // Exclamation
4463
- svg.appendChild(createPath('M24 20v8', strokeAttrs));
4464
- svg.appendChild(createCircle(24, 33.5, 1.5, { fill: 'currentColor' }));
4501
+ function createAlertTriangleIcon(className) {
4502
+ const svg = createSvgElement('0 0 48 48', 48, 48);
4503
+ svg.classList.add(className);
4504
+ const strokeAttrs = {
4505
+ stroke: 'currentColor',
4506
+ 'stroke-width': '2.5',
4507
+ 'stroke-linecap': 'round',
4508
+ 'stroke-linejoin': 'round',
4509
+ fill: 'none',
4510
+ };
4511
+ // Triangle outline
4512
+ svg.appendChild(createPath('M24 9L5.5 39h37L24 9z', strokeAttrs));
4513
+ // Exclamation
4514
+ svg.appendChild(createPath('M24 20v8', strokeAttrs));
4515
+ svg.appendChild(createCircle(24, 33.5, 1.5, { fill: 'currentColor' }));
4465
4516
  return svg;
4466
4517
  }
4467
4518
  /**
@@ -4658,6 +4709,380 @@ function createUsersIcon() {
4658
4709
  return svg;
4659
4710
  }
4660
4711
 
4712
+ /**
4713
+ * Method Button
4714
+ *
4715
+ * A sign-in method's button, drawn one way wherever a method is offered: the
4716
+ * method list, and the identifier step that leads with the account's own
4717
+ * identity provider. The caller attaches its click handler, and removes it.
4718
+ */
4719
+ /**
4720
+ * The button: its glyph, hidden from assistive technology so the button is
4721
+ * named by its words alone; the method's name; and its description, when it
4722
+ * has one.
4723
+ */
4724
+ function methodButton(method) {
4725
+ const btn = document.createElement('button');
4726
+ btn.className = 'sv-btn sv-btn-method';
4727
+ const content = div('sv-method-content');
4728
+ const icon = div('sv-method-icon');
4729
+ icon.setAttribute('aria-hidden', 'true');
4730
+ icon.appendChild(createMethodIcon(method.icon));
4731
+ content.appendChild(icon);
4732
+ const text = div('sv-method-text');
4733
+ const name = document.createElement('div');
4734
+ name.className = 'sv-method-name';
4735
+ name.textContent = method.name;
4736
+ text.appendChild(name);
4737
+ if (method.description) {
4738
+ const description = document.createElement('div');
4739
+ description.className = 'sv-method-description';
4740
+ description.textContent = method.description;
4741
+ text.appendChild(description);
4742
+ }
4743
+ content.appendChild(text);
4744
+ btn.appendChild(content);
4745
+ return btn;
4746
+ }
4747
+
4748
+ /**
4749
+ * Two consent lines, each in one wording for every surface that shows it: the
4750
+ * SMS and voice consent beside a phone number, and the terms a signup
4751
+ * accepts. Each line is split around the documents it links, and each document
4752
+ * has its one address here: a surface draws the words between the links and
4753
+ * links each document at TERMS_URL or PRIVACY_URL.
4754
+ *
4755
+ * BROWSER-SAFE: data only, no imports. sdk-mobile mirrors it.
4756
+ */
4757
+
4758
+ /** The terms of service, published once, on the marketing site. */
4759
+ const TERMS_URL = 'https://sparkvault.com/terms/';
4760
+
4761
+ /** The privacy policy, published once, on the marketing site. */
4762
+ const PRIVACY_URL = 'https://sparkvault.com/privacy/';
4763
+
4764
+ /**
4765
+ * Beside every field where a person enters a phone number SparkVault texts or
4766
+ * calls (the sign-in field and the backup phone of Identity's sign-in, in
4767
+ * sdk-js and sdk-mobile, the mobile app's backup phone, and auth.sv's new
4768
+ * phone number), and under the sign-in's method picker wherever it offers a
4769
+ * text or a call: a phone number the sign-in was handed reaches the picker
4770
+ * without passing the field. The terms take the consent from whoever provides
4771
+ * the number, so the words fit a number typed and a number handed over alike.
4772
+ * A carrier approves the number SparkVault texts from only when this line, its
4773
+ * call to action, names the service, the consent, how often messages come,
4774
+ * that rates may apply, how to opt out and get help, and links the terms and
4775
+ * the privacy policy, so it says each of them. It agrees with the terms' SMS
4776
+ * and voice disclosures and the privacy policy (apps/www/terms.md 15,
4777
+ * apps/www/privacy.md 1.1, held to them by
4778
+ * apps/www/tests/consent-lines.test.mjs): texts carry the codes, alerts and
4779
+ * notifications they name and calls only the codes, STOP opts the number out,
4780
+ * HELP answers, frequency varies, rates may apply, and where texts and calls
4781
+ * go and how to opt back in (START or UNSTOP) are the terms' to say.
4782
+ */
4783
+ const SMS_CONSENT = Object.freeze({
4784
+ beforeTerms: 'By providing a phone number, you agree to receive texts from SparkVault with verification codes, security alerts and account notifications, and automated calls with verification codes, as its ',
4785
+ terms: 'Terms',
4786
+ beforePrivacy: ' and ',
4787
+ privacy: 'Privacy Policy',
4788
+ afterPrivacy: ' describe. Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help.'
4789
+ });
4790
+
4791
+ /* global HTMLAnchorElement */
4792
+ /**
4793
+ * SMS and Voice Consent
4794
+ *
4795
+ * The line the sign-in shows wherever a person gives SparkVault a phone number
4796
+ * to text or call, in the platform's one wording
4797
+ * (`@sparkvault/app-sdk/consent-lines`): under every field that takes one, and
4798
+ * under the method picker wherever it offers a text or a call. It describes
4799
+ * the field or the methods above it, so a screen reader reads it with them.
4800
+ */
4801
+ /** A document the line names, linked in place and opening in a new tab. */
4802
+ function documentLink(name, href) {
4803
+ const link = document.createElement('a');
4804
+ link.className = 'sv-sms-consent-link';
4805
+ link.href = href;
4806
+ link.target = '_blank';
4807
+ link.rel = 'noopener noreferrer';
4808
+ link.textContent = name;
4809
+ return link;
4810
+ }
4811
+ /**
4812
+ * The consent line, its "Terms" and "Privacy Policy" opening those documents
4813
+ * in a new tab.
4814
+ *
4815
+ * @param id - The line's id, which the field or each method names in its `aria-describedby`
4816
+ */
4817
+ function smsConsent(id) {
4818
+ const line = document.createElement('p');
4819
+ line.className = 'sv-sms-consent';
4820
+ line.id = id;
4821
+ line.append(SMS_CONSENT.beforeTerms, documentLink(SMS_CONSENT.terms, TERMS_URL), SMS_CONSENT.beforePrivacy, documentLink(SMS_CONSENT.privacy, PRIVACY_URL), SMS_CONSENT.afterPrivacy);
4822
+ return line;
4823
+ }
4824
+
4825
+ /**
4826
+ * Identity Input View
4827
+ *
4828
+ * Collects and validates the user's email or phone number: reads the input as
4829
+ * one or the other by the platform's rules (`@sparkvault/app-sdk/phone` and
4830
+ * `@sparkvault/app-sdk/email-address`), and formats a phone-only field as the
4831
+ * number is typed. A field that takes a phone number carries the SMS and voice
4832
+ * consent beneath it.
4833
+ */
4834
+ class IdentityInputView {
4835
+ constructor(props) {
4836
+ this.container = null;
4837
+ this.inputElement = null;
4838
+ this.labelElement = null;
4839
+ this.submitButton = null;
4840
+ this.passkeyLink = null;
4841
+ this.leadingButton = null;
4842
+ this.leadingHandler = null;
4843
+ this.errorContainer = null;
4844
+ this.focusTimeoutId = null;
4845
+ this.detectedType = 'email';
4846
+ this.props = props;
4847
+ this.boundHandleInput = () => {
4848
+ this.handleInput();
4849
+ this.props.onType?.();
4850
+ };
4851
+ this.boundHandleKeyDown = (e) => {
4852
+ if (e.key === 'Enter') {
4853
+ e.preventDefault();
4854
+ this.handleSubmit();
4855
+ }
4856
+ };
4857
+ this.boundHandleSubmit = () => this.handleSubmit();
4858
+ this.boundHandlePasskey = props.onPasskey ? () => props.onPasskey() : null;
4859
+ }
4860
+ get allowsBoth() {
4861
+ return this.props.allowedTypes.includes('email') && this.props.allowedTypes.includes('phone');
4862
+ }
4863
+ get allowsEmail() {
4864
+ return this.props.allowedTypes.includes('email');
4865
+ }
4866
+ get allowsPhone() {
4867
+ return this.props.allowedTypes.includes('phone');
4868
+ }
4869
+ render() {
4870
+ const container = div('sv-email-view');
4871
+ this.container = container;
4872
+ if (this.props.leadingMethod) {
4873
+ this.offerLeadingMethod(this.props.leadingMethod);
4874
+ }
4875
+ // Compact header - just the subtitle instruction
4876
+ const headerSection = div('sv-email-header');
4877
+ const subtitle = document.createElement('p');
4878
+ subtitle.className = 'sv-email-subtitle';
4879
+ subtitle.textContent = this.getSubtitleText();
4880
+ headerSection.appendChild(subtitle);
4881
+ container.appendChild(headerSection);
4882
+ // Error container
4883
+ this.errorContainer = div('sv-email-error-container');
4884
+ if (this.props.error) {
4885
+ this.errorContainer.appendChild(errorMessage(this.props.error));
4886
+ }
4887
+ container.appendChild(this.errorContainer);
4888
+ // Form section
4889
+ const formSection = div('sv-email-form');
4890
+ const inputWrapper = div('sv-email-input-wrapper');
4891
+ this.labelElement = document.createElement('label');
4892
+ this.labelElement.className = 'sv-email-label';
4893
+ this.labelElement.htmlFor = 'sv-identity-input';
4894
+ this.labelElement.textContent = this.getLabelText();
4895
+ this.inputElement = document.createElement('input');
4896
+ this.inputElement.type = this.allowsPhone && !this.allowsEmail ? 'tel' : 'text';
4897
+ this.inputElement.id = 'sv-identity-input';
4898
+ this.inputElement.className = 'sv-email-input';
4899
+ this.inputElement.placeholder = this.getPlaceholderText();
4900
+ this.inputElement.autocomplete = this.allowsBoth ? 'on' : (this.allowsEmail ? 'email' : 'tel');
4901
+ this.inputElement.required = true;
4902
+ this.inputElement.maxLength = EMAIL_ADDRESS_LIMITS.ADDRESS;
4903
+ if (this.props.initialValue) {
4904
+ this.inputElement.value = this.props.initialValue;
4905
+ this.detectAndUpdateType(this.props.initialValue);
4906
+ }
4907
+ this.inputElement.addEventListener('input', this.boundHandleInput);
4908
+ this.inputElement.addEventListener('keydown', this.boundHandleKeyDown);
4909
+ inputWrapper.appendChild(this.labelElement);
4910
+ inputWrapper.appendChild(this.inputElement);
4911
+ if (this.allowsPhone) {
4912
+ const consent = smsConsent('sv-identity-sms-consent');
4913
+ this.inputElement.setAttribute('aria-describedby', consent.id);
4914
+ inputWrapper.appendChild(consent);
4915
+ }
4916
+ formSection.appendChild(inputWrapper);
4917
+ this.submitButton = document.createElement('button');
4918
+ this.submitButton.className = 'sv-btn sv-btn-email-primary';
4919
+ this.submitButton.textContent = 'Continue';
4920
+ this.submitButton.addEventListener('click', this.boundHandleSubmit);
4921
+ formSection.appendChild(this.submitButton);
4922
+ container.appendChild(formSection);
4923
+ if (this.boundHandlePasskey) {
4924
+ this.passkeyLink = document.createElement('button');
4925
+ this.passkeyLink.className = 'sv-fallback-link';
4926
+ this.passkeyLink.textContent = 'Sign in with a passkey';
4927
+ this.passkeyLink.addEventListener('click', this.boundHandlePasskey);
4928
+ container.appendChild(this.passkeyLink);
4929
+ }
4930
+ this.focusTimeoutId = setTimeout(() => this.inputElement?.focus(), 50);
4931
+ return container;
4932
+ }
4933
+ /**
4934
+ * Offer `leading` above the field, set apart by "or". On a view already on
4935
+ * screen it joins in place, so what the person typed and where their focus
4936
+ * is stay as they were. A view that already leads with a method keeps it.
4937
+ */
4938
+ offerLeadingMethod(leading) {
4939
+ if (!this.container || this.leadingButton)
4940
+ return;
4941
+ this.leadingHandler = leading.onSelect;
4942
+ this.leadingButton = methodButton(leading.method);
4943
+ this.leadingButton.addEventListener('click', this.leadingHandler);
4944
+ const divider = div('sv-divider');
4945
+ const or = document.createElement('span');
4946
+ or.className = 'sv-divider-text';
4947
+ or.textContent = 'or';
4948
+ divider.appendChild(or);
4949
+ this.container.prepend(this.leadingButton, divider);
4950
+ }
4951
+ getSubtitleText() {
4952
+ if (this.allowsBoth)
4953
+ return 'Enter your email or phone to continue';
4954
+ if (this.allowsPhone)
4955
+ return 'Enter your phone number to continue';
4956
+ return 'Enter your email to continue';
4957
+ }
4958
+ getLabelText() {
4959
+ if (this.allowsBoth) {
4960
+ return this.detectedType === 'phone' ? 'Phone number' : 'Email address';
4961
+ }
4962
+ if (this.allowsPhone)
4963
+ return 'Phone number';
4964
+ return 'Email address';
4965
+ }
4966
+ getPlaceholderText() {
4967
+ if (this.allowsBoth)
4968
+ return 'you@example.com or (555) 123-4567';
4969
+ if (this.allowsPhone)
4970
+ return '(555) 123-4567';
4971
+ return 'you@example.com';
4972
+ }
4973
+ handleInput() {
4974
+ this.clearError();
4975
+ if (!this.inputElement)
4976
+ return;
4977
+ const value = this.inputElement.value;
4978
+ if (this.allowsBoth) {
4979
+ // The label follows what the input reads as, but the text is never
4980
+ // rewritten: digits typed so far can still begin an email address
4981
+ // ("2024user@gmail.com", "12345678@qq.com"), and phone formatting would
4982
+ // corrupt it. Submit normalizes a phone number whatever its separators.
4983
+ const wasPhone = this.detectedType === 'phone';
4984
+ this.detectAndUpdateType(value);
4985
+ if (wasPhone !== (this.detectedType === 'phone') && this.labelElement) {
4986
+ this.labelElement.textContent = this.getLabelText();
4987
+ }
4988
+ }
4989
+ else if (this.allowsPhone) {
4990
+ // Phone-only mode: always format
4991
+ const cursorPos = this.inputElement.selectionStart ?? value.length;
4992
+ const formatted = formatPhoneDisplay(value);
4993
+ if (formatted !== value) {
4994
+ this.inputElement.value = formatted;
4995
+ const newPos = Math.min(cursorPos + (formatted.length - value.length), formatted.length);
4996
+ this.inputElement.setSelectionRange(newPos, newPos);
4997
+ }
4998
+ }
4999
+ }
5000
+ detectAndUpdateType(value) {
5001
+ this.detectedType = inferIdentityType(value);
5002
+ }
5003
+ clearError() {
5004
+ if (this.errorContainer) {
5005
+ clearChildren(this.errorContainer);
5006
+ }
5007
+ this.inputElement?.classList.remove('sv-email-input-error');
5008
+ }
5009
+ showError(message) {
5010
+ if (this.errorContainer) {
5011
+ clearChildren(this.errorContainer);
5012
+ this.errorContainer.appendChild(errorMessage(message));
5013
+ }
5014
+ this.inputElement?.classList.add('sv-email-input-error');
5015
+ this.inputElement?.focus();
5016
+ }
5017
+ handleSubmit() {
5018
+ if (!this.inputElement || !this.submitButton)
5019
+ return;
5020
+ const rawValue = this.inputElement.value;
5021
+ // Validate based on detected type
5022
+ if (this.allowsBoth) {
5023
+ if (this.detectedType === 'phone') {
5024
+ const validPhone = parsePhone(rawValue);
5025
+ if (!validPhone) {
5026
+ this.showError('Please enter a valid phone number');
5027
+ return;
5028
+ }
5029
+ this.submitButton.disabled = true;
5030
+ this.submitButton.textContent = 'Please wait...';
5031
+ this.props.onSubmit({ value: validPhone, type: 'phone' });
5032
+ }
5033
+ else {
5034
+ const validEmail = validateEmail(rawValue);
5035
+ if (!validEmail) {
5036
+ this.showError('Please enter a valid email address');
5037
+ return;
5038
+ }
5039
+ this.submitButton.disabled = true;
5040
+ this.submitButton.textContent = 'Please wait...';
5041
+ this.props.onSubmit({ value: validEmail, type: 'email' });
5042
+ }
5043
+ }
5044
+ else if (this.allowsPhone) {
5045
+ const validPhone = parsePhone(rawValue);
5046
+ if (!validPhone) {
5047
+ this.showError('Please enter a valid phone number');
5048
+ return;
5049
+ }
5050
+ this.submitButton.disabled = true;
5051
+ this.submitButton.textContent = 'Please wait...';
5052
+ this.props.onSubmit({ value: validPhone, type: 'phone' });
5053
+ }
5054
+ else {
5055
+ const validEmail = validateEmail(rawValue);
5056
+ if (!validEmail) {
5057
+ this.showError('Please enter a valid email address');
5058
+ return;
5059
+ }
5060
+ this.submitButton.disabled = true;
5061
+ this.submitButton.textContent = 'Please wait...';
5062
+ this.props.onSubmit({ value: validEmail, type: 'email' });
5063
+ }
5064
+ }
5065
+ destroy() {
5066
+ if (this.focusTimeoutId !== null) {
5067
+ clearTimeout(this.focusTimeoutId);
5068
+ this.focusTimeoutId = null;
5069
+ }
5070
+ if (this.inputElement) {
5071
+ this.inputElement.removeEventListener('input', this.boundHandleInput);
5072
+ this.inputElement.removeEventListener('keydown', this.boundHandleKeyDown);
5073
+ }
5074
+ if (this.submitButton) {
5075
+ this.submitButton.removeEventListener('click', this.boundHandleSubmit);
5076
+ }
5077
+ if (this.passkeyLink && this.boundHandlePasskey) {
5078
+ this.passkeyLink.removeEventListener('click', this.boundHandlePasskey);
5079
+ }
5080
+ if (this.leadingButton && this.leadingHandler) {
5081
+ this.leadingButton.removeEventListener('click', this.leadingHandler);
5082
+ }
5083
+ }
5084
+ }
5085
+
4661
5086
  /**
4662
5087
  * Method Select View
4663
5088
  *
@@ -4672,6 +5097,7 @@ const textsOrCalls = (method) => method.identityType === 'phone';
4672
5097
  class MethodSelectView {
4673
5098
  constructor(props) {
4674
5099
  this.backLink = null;
5100
+ this.methodsContainer = null;
4675
5101
  this.methodButtons = [];
4676
5102
  this.methodClickHandlers = new Map();
4677
5103
  this.props = props;
@@ -4692,6 +5118,7 @@ class MethodSelectView {
4692
5118
  }
4693
5119
  const consent = this.props.methods.some(textsOrCalls) ? smsConsent('sv-method-sms-consent') : null;
4694
5120
  const methodsContainer = div();
5121
+ this.methodsContainer = methodsContainer;
4695
5122
  for (const method of this.props.methods) {
4696
5123
  const methodButton = this.createMethodButton(method);
4697
5124
  if (consent && textsOrCalls(method)) {
@@ -4713,6 +5140,18 @@ class MethodSelectView {
4713
5140
  }
4714
5141
  return container;
4715
5142
  }
5143
+ /**
5144
+ * Put `method` at the head of a list already on screen, in place, so the
5145
+ * person's focus stays where it was. The method sends no text or call (the
5146
+ * account's own identity provider), so the list's consent stands as it is.
5147
+ */
5148
+ offerLeadingMethod(method) {
5149
+ if (!this.methodsContainer)
5150
+ return;
5151
+ const button = this.createMethodButton(method);
5152
+ this.methodButtons.unshift(button);
5153
+ this.methodsContainer.prepend(button);
5154
+ }
4716
5155
  createBackLink() {
4717
5156
  const link = document.createElement('button');
4718
5157
  link.className = 'sv-back-link';
@@ -4723,33 +5162,13 @@ class MethodSelectView {
4723
5162
  return link;
4724
5163
  }
4725
5164
  createMethodButton(method) {
4726
- const btn = document.createElement('button');
4727
- btn.className = 'sv-btn sv-btn-method';
4728
- const content = div('sv-method-content');
4729
- const icon = this.getMethodIcon(method);
4730
- content.appendChild(icon);
4731
- const text = div('sv-method-text');
4732
- const name = document.createElement('div');
4733
- name.className = 'sv-method-name';
4734
- name.textContent = method.name;
4735
- const description = document.createElement('div');
4736
- description.className = 'sv-method-description';
4737
- description.textContent = method.description;
4738
- text.appendChild(name);
4739
- text.appendChild(description);
4740
- content.appendChild(text);
4741
- btn.appendChild(content);
5165
+ const btn = methodButton(method);
4742
5166
  // Create and store handler reference for cleanup
4743
5167
  const handler = () => this.props.onSelectMethod(method);
4744
5168
  this.methodClickHandlers.set(btn, handler);
4745
5169
  btn.addEventListener('click', handler);
4746
5170
  return btn;
4747
5171
  }
4748
- getMethodIcon(method) {
4749
- const iconContainer = div('sv-method-icon');
4750
- iconContainer.appendChild(createMethodIcon(method.icon));
4751
- return iconContainer;
4752
- }
4753
5172
  /**
4754
5173
  * Clean up event listeners to prevent memory leaks.
4755
5174
  */
@@ -5857,6 +6276,18 @@ function isBlockedCode(code) {
5857
6276
  * level they can clear (the message says so).
5858
6277
  */
5859
6278
  const STRONGER_VERIFICATION_REQUIRED_CODE = 'stronger_verification_required';
6279
+ /**
6280
+ * The code of a sign-in whose only way in is the account's own identity
6281
+ * provider, on a page that may not offer it: the site's sign-in predates what
6282
+ * that provider needs, so only the site updating it clears this.
6283
+ */
6284
+ const FEDERATION_UNAVAILABLE_CODE = 'federation_unavailable';
6285
+ /**
6286
+ * The code of a sign-in whose only way in is the account's own identity
6287
+ * provider, on a page that could not get its sign-in's reference just now:
6288
+ * a genuine error, which the person's Try Again asks for again.
6289
+ */
6290
+ const SIGNIN_REFERENCE_UNAVAILABLE_CODE = 'signin_reference_unavailable';
5860
6291
  /**
5861
6292
  * The heading of a state the person can do nothing about from here, by its
5862
6293
  * code, or null for a genuine error. Retrying cannot clear any of them, so the
@@ -5866,12 +6297,13 @@ const STRONGER_VERIFICATION_REQUIRED_CODE = 'stronger_verification_required';
5866
6297
  * - a blocked Identity (trial exhausted or expired, or a paid capacity wall),
5867
6298
  * which only the site owner subscribing clears, shown as a friendly,
5868
6299
  * non-leaky interstitial;
5869
- * - a request held to a passkey the person does not hold.
6300
+ * - a request held to a passkey the person does not hold;
6301
+ * - an account whose only way in this page may not offer.
5870
6302
  */
5871
6303
  function terminalTitle(code) {
5872
6304
  if (code === 'identity_locked')
5873
6305
  return 'This SparkVault Identity is locked';
5874
- if (isBlockedCode(code))
6306
+ if (isBlockedCode(code) || code === FEDERATION_UNAVAILABLE_CODE)
5875
6307
  return 'Sign-in unavailable';
5876
6308
  if (code === STRONGER_VERIFICATION_REQUIRED_CODE)
5877
6309
  return STRONGER_VERIFICATION_TITLE;
@@ -6472,6 +6904,12 @@ function blockedSignInMessage(companyName) {
6472
6904
  : 'Sign-in is temporarily unavailable. Please contact the site owner for assistance.';
6473
6905
  }
6474
6906
  const BLOCKED_ERROR_CODES = new Set(IDENTITY_BLOCKED_ERROR_CODES);
6907
+ /**
6908
+ * How long the live region waits after a view is in place before it takes
6909
+ * the view's words: long enough that assistive technology has seen the
6910
+ * view's change and hears the region's as a change of its own.
6911
+ */
6912
+ const STATUS_ANNOUNCE_DELAY_MS = 100;
6475
6913
  const SPARKLINK_CSP_BLOCKED_ERROR = {
6476
6914
  message: [
6477
6915
  'Connection blocked by security policy.',
@@ -6481,7 +6919,7 @@ const SPARKLINK_CSP_BLOCKED_ERROR = {
6481
6919
  code: 'sparklink_csp_blocked',
6482
6920
  };
6483
6921
  class IdentityRenderer {
6484
- constructor(container, api, options, callbacks) {
6922
+ constructor(container, api, options, callbacks, federationReturn = null) {
6485
6923
  // True while the identifier is the one the render options supplied (a host's
6486
6924
  // prefill, a login hint, an invite's identity), false once the person types
6487
6925
  // their own. Gates the "identity is fixed" behavior, so a no-hint
@@ -6509,10 +6947,29 @@ class IdentityRenderer {
6509
6947
  this.sparkLinkVisibilityHandler = null;
6510
6948
  this.sparkLinkClaiming = false;
6511
6949
  this.sparkLinkRetryTimer = null;
6950
+ this.pageRestoreHandler = null;
6951
+ this.referenceAsk = null;
6952
+ this.referenceAsks = 0;
6953
+ // The sign-in step as it first showed, until the person types into it: a
6954
+ // reference that arrives while it is still on screen may start the
6955
+ // provider on its own, as one held from the start would have.
6956
+ this.untouchedStep = null;
6957
+ // The page's one live region: placed beside the flow content when the
6958
+ // container opens, empty, and kept across views, so the words a view
6959
+ // announces (View.announcement) land in a region already in the page, which
6960
+ // assistive technology hears change. A region created with its words already
6961
+ // in it is often never announced.
6962
+ this.statusRegion = null;
6963
+ this.statusTimer = null;
6512
6964
  this.container = container;
6513
6965
  this.api = api;
6514
6966
  this.options = options;
6515
6967
  this.callbacks = callbacks;
6968
+ this.federationReturn = federationReturn;
6969
+ // A start this tab made on its own, read (and removed) here: with no
6970
+ // fragment back, the person came Back from the provider's page.
6971
+ const leftOnItsOwn = takeFederationAutoStart(this.api.accountId);
6972
+ this.federationMayAutoStart = federationReturn === null && !leftOnItsOwn;
6516
6973
  // Initialize centralized state
6517
6974
  this.verificationState = new VerificationState();
6518
6975
  // Initialize handlers with shared state
@@ -6525,6 +6982,20 @@ class IdentityRenderer {
6525
6982
  if (options.authContext) {
6526
6983
  this.verificationState.setAuthContext(options.authContext);
6527
6984
  }
6985
+ // A sign-in through the account's own identity provider opens no hub
6986
+ // session, so a popup whose result is lost can recover it safely only by
6987
+ // its reference: /sso then refuses every hub session that does not carry
6988
+ // it. The page offers the provider only when told it may, never by what
6989
+ // it infers from its window: while it holds its reference (given at
6990
+ // once, or arriving through the function it was given), or, given none
6991
+ // at all, when it says it completes in its own window (it hands no opener
6992
+ // a result, so no recovery stands in for it). A page told it has none, a
6993
+ // value that is no reference, and a page told nothing (a sign-in page
6994
+ // that predates the reference, served from a cache) offer none.
6995
+ const { signinRef, completesInWindow } = options;
6996
+ this.askReference = typeof signinRef === 'function' ? signinRef : null;
6997
+ this.verificationState.setSigninRef(isSigninReference(signinRef) ? signinRef : null);
6998
+ this.offeredWithoutReference = signinRef === undefined && completesInWindow === true;
6528
6999
  }
6529
7000
  /**
6530
7001
  * Seed the verification identity from the render options, deriving the
@@ -6589,6 +7060,9 @@ class IdentityRenderer {
6589
7060
  * Otherwise shows loading state while fetching config.
6590
7061
  */
6591
7062
  async start() {
7063
+ // Asked first, so a reference the page already holds or gets at once is
7064
+ // in place for the first step; the flow never waits on it.
7065
+ this.requestReference();
6592
7066
  // Try to get config quickly if it was preloaded
6593
7067
  // This races the config promise against a short timeout
6594
7068
  let config = null;
@@ -6617,6 +7091,7 @@ class IdentityRenderer {
6617
7091
  this.container.createLoading({
6618
7092
  backdropBlur: this.options.backdropBlur,
6619
7093
  }, () => this.handleClose());
7094
+ this.placeStatusRegion();
6620
7095
  try {
6621
7096
  if (!config) {
6622
7097
  // Config not ready yet - show loading and await it
@@ -6650,6 +7125,7 @@ class IdentityRenderer {
6650
7125
  showStartupError(error) {
6651
7126
  if (!this.container.isOpen()) {
6652
7127
  this.container.createLoading({ backdropBlur: this.options.backdropBlur }, () => this.handleClose());
7128
+ this.placeStatusRegion();
6653
7129
  }
6654
7130
  this.setState(this.viewStateForConfigError(error));
6655
7131
  }
@@ -6723,6 +7199,8 @@ class IdentityRenderer {
6723
7199
  close() {
6724
7200
  // Cancel all pending API requests first
6725
7201
  this.api.abort();
7202
+ // An answer to an open ask for the reference has no flow left to join.
7203
+ this.referenceAsks += 1;
6726
7204
  // A pending discoverable ceremony would otherwise hold the browser sheet
6727
7205
  // open against a dialog that no longer exists.
6728
7206
  this.discoverableVerifyAbort?.abort();
@@ -6735,6 +7213,16 @@ class IdentityRenderer {
6735
7213
  clearTimeout(this.morphTimer);
6736
7214
  this.morphTimer = null;
6737
7215
  }
7216
+ if (this.pageRestoreHandler) {
7217
+ window.removeEventListener('pageshow', this.pageRestoreHandler);
7218
+ this.pageRestoreHandler = null;
7219
+ }
7220
+ if (this.statusTimer !== null) {
7221
+ clearTimeout(this.statusTimer);
7222
+ this.statusTimer = null;
7223
+ }
7224
+ this.statusRegion?.remove();
7225
+ this.statusRegion = null;
6738
7226
  this.cleanupSparkLink();
6739
7227
  this.destroyCurrentView();
6740
7228
  this.container.destroy();
@@ -6751,6 +7239,159 @@ class IdentityRenderer {
6751
7239
  this.render();
6752
7240
  }
6753
7241
  async showInitialAuthStep() {
7242
+ const heldAtStart = this.verificationState.signinRef;
7243
+ if (this.startWithFederation())
7244
+ return;
7245
+ await this.showSignInStep();
7246
+ this.untouchedStep = this.currentView;
7247
+ // A reference that arrived while the step was being prepared joins it now.
7248
+ if (this.verificationState.signinRef !== heldAtStart)
7249
+ this.offerArrivedReference();
7250
+ }
7251
+ /**
7252
+ * The account's own identity provider as the flow's first step. A failed
7253
+ * round trip is said first. Otherwise the provider may start on its own
7254
+ * (startFederationAutomatically). Returns true when it took the step.
7255
+ */
7256
+ startWithFederation() {
7257
+ if (this.federationReturn === 'failed') {
7258
+ this.federationReturn = null;
7259
+ this.setState(this.federationFailedState());
7260
+ return true;
7261
+ }
7262
+ return this.startFederationAutomatically();
7263
+ }
7264
+ /**
7265
+ * Leave for the account's own identity provider without the person's
7266
+ * click, while this page offers it and it starts on its own
7267
+ * (federationStartsOnItsOwn). Returns true when it left.
7268
+ */
7269
+ startFederationAutomatically() {
7270
+ const federation = this.federation;
7271
+ if (!this.federationStartsOnItsOwn(federation))
7272
+ return false;
7273
+ this.leaveForFederation({ silent: federation.silent, automatic: true })
7274
+ .catch((error) => this.handleErrorWithRecovery(error, 'unknown'));
7275
+ return true;
7276
+ }
7277
+ /**
7278
+ * Whether the given account's own identity provider starts without the
7279
+ * person's click while this page may still leave on its own: when the
7280
+ * account asks for a silent attempt (`federation.silent`: the provider
7281
+ * answers without showing anything, and a refusal comes back as
7282
+ * `interaction_required`) or the caller asked for it (`method:
7283
+ * 'federation'`, interactive unless the account asks for the silent
7284
+ * attempt).
7285
+ */
7286
+ federationStartsOnItsOwn(federation) {
7287
+ return federation !== null
7288
+ && this.federationMayAutoStart
7289
+ && (federation.silent || this.options.method === 'federation');
7290
+ }
7291
+ /**
7292
+ * The account's own identity provider while a step for this identifier
7293
+ * lacks it only because the page's ask for the sign-in's reference is still
7294
+ * out: with the reference held, the provider would be on that step, so the
7295
+ * step holds every automatic advance a held reference would not have made.
7296
+ * Once the reference lands the provider joins the step, or starts on its
7297
+ * own from the untouched first step (offerArrivedReference); an ask that
7298
+ * finds none leaves the held step up for the person's tap.
7299
+ */
7300
+ federationAwaitingReference(recipient) {
7301
+ if (this.referenceAsk !== 'pending' || !this.offersFederationBeside(recipient))
7302
+ return null;
7303
+ return this.accountFederation;
7304
+ }
7305
+ /**
7306
+ * Ask the page for the sign-in's reference (VerifyOptions.signinRef as a
7307
+ * function) without waiting on the answer: the flow goes on, and the
7308
+ * answer joins it when it lands. A call that throws or rejects, and an
7309
+ * answer that is no reference, found none.
7310
+ */
7311
+ requestReference() {
7312
+ const ask = this.askReference;
7313
+ if (!ask)
7314
+ return;
7315
+ const asked = ++this.referenceAsks;
7316
+ this.referenceAsk = 'pending';
7317
+ void new Promise((resolve) => { resolve(ask()); })
7318
+ .catch(() => null)
7319
+ .then((reference) => {
7320
+ if (asked !== this.referenceAsks)
7321
+ return;
7322
+ if (isSigninReference(reference)) {
7323
+ this.referenceArrived(reference);
7324
+ }
7325
+ else {
7326
+ this.referenceUnavailable();
7327
+ }
7328
+ });
7329
+ }
7330
+ /** The reference arrived: every completing call from now on carries it, and the step offers the provider. */
7331
+ referenceArrived(reference) {
7332
+ this.referenceAsk = null;
7333
+ this.verificationState.setSigninRef(reference);
7334
+ this.offerArrivedReference();
7335
+ }
7336
+ /**
7337
+ * The ask found no reference for now. An account with other ways in
7338
+ * simply keeps them; a person waiting on the provider as the only way in
7339
+ * is told to try again.
7340
+ */
7341
+ referenceUnavailable() {
7342
+ this.referenceAsk = 'unavailable';
7343
+ if (this.viewState.view === 'awaiting-reference')
7344
+ void this.showMethodSelect();
7345
+ }
7346
+ /** The person's Try Again: ask again, and show the sign-in step meanwhile. */
7347
+ retryReference() {
7348
+ this.requestReference();
7349
+ void this.showSignInStep();
7350
+ }
7351
+ /**
7352
+ * Offer the account's own identity provider on the step that offers it,
7353
+ * now that the page holds its reference. On the sign-in step as it first
7354
+ * showed, still untouched, the provider starts on its own as it would have
7355
+ * with the reference held from the start; otherwise its button joins the
7356
+ * step in place, keeping what the person typed and their focus. A person
7357
+ * who has moved past that step sees nothing change, and the step offers
7358
+ * the provider whenever it shows again.
7359
+ */
7360
+ offerArrivedReference() {
7361
+ const state = this.viewState;
7362
+ const onOfferingStep = state.view === 'awaiting-reference'
7363
+ || state.view === 'identity-input'
7364
+ || (state.view === 'method-select' && this.offersFederationBeside(state.email));
7365
+ if (!onOfferingStep)
7366
+ return;
7367
+ const untouched = this.untouchedStep !== null && this.currentView === this.untouchedStep;
7368
+ if (untouched && this.startFederationAutomatically())
7369
+ return;
7370
+ if (state.view === 'awaiting-reference') {
7371
+ void this.showMethodSelect();
7372
+ return;
7373
+ }
7374
+ const leading = this.leadingFederationMethod();
7375
+ if (!leading)
7376
+ return;
7377
+ const view = this.currentView;
7378
+ if (view instanceof IdentityInputView) {
7379
+ view.offerLeadingMethod(leading);
7380
+ }
7381
+ else if (view instanceof MethodSelectView
7382
+ && state.view === 'method-select'
7383
+ && !state.methods.some((method) => method.type === 'federation')) {
7384
+ view.offerLeadingMethod(leading.method);
7385
+ this.verificationState.setViewState({ ...state, methods: [leading.method, ...state.methods] });
7386
+ }
7387
+ }
7388
+ /**
7389
+ * The sign-in's own first step: the method list when no identifier is
7390
+ * asked for (or one is already known), the discoverable passkey ceremony for
7391
+ * a returning browser, else the identifier field (which leads with the
7392
+ * account's own identity provider when it offers one).
7393
+ */
7394
+ async showSignInStep() {
6754
7395
  if (this.recipient || this.getAllowedIdentityTypes().length === 0) {
6755
7396
  await this.showMethodSelect();
6756
7397
  return;
@@ -6758,8 +7399,12 @@ class IdentityRenderer {
6758
7399
  // Returning browser on the Identity origin (passkey-hint cookie present):
6759
7400
  // auto-start the discoverable ceremony instead of asking for an identifier
6760
7401
  // — the Google-style one-touch return. A cancel lands on the identifier
6761
- // form, which keeps a "Sign in with a passkey" way back in.
6762
- if (this.canDiscoverableVerify()) {
7402
+ // form, which keeps a "Sign in with a passkey" way back in. A provider
7403
+ // that starts on its own once the pending reference lands goes first, as
7404
+ // with the reference held (startWithFederation), so the identifier form
7405
+ // waits for it instead.
7406
+ if (this.canDiscoverableVerify()
7407
+ && !this.federationStartsOnItsOwn(this.federationAwaitingReference(this.recipient))) {
6763
7408
  void this.launchDiscoverableVerify();
6764
7409
  return;
6765
7410
  }
@@ -6821,6 +7466,7 @@ class IdentityRenderer {
6821
7466
  this.container.setMinimalChrome(minimalChromeViews.includes(this.viewState.view));
6822
7467
  const view = this.createViewForState(this.viewState);
6823
7468
  this.currentView = view;
7469
+ this.announce(view.announcement ?? '');
6824
7470
  const rendered = view.render();
6825
7471
  // Each step enters with a calm fade + rise (see .sv-step-enter). The brand
6826
7472
  // lockup and footer live outside `body`, so only the flow content moves.
@@ -6829,11 +7475,12 @@ class IdentityRenderer {
6829
7475
  // reshaping between steps (falls back to an instant swap in jsdom).
6830
7476
  this.morphSwap(body, rendered);
6831
7477
  // Drive the top progress bar (owned by login-popup.js as
6832
- // `window.__sparkvaultProgress`) off the view: a transient `loading` view
6833
- // means a network step is in flight, so keep the bar trickling; any real
7478
+ // `window.__sparkvaultProgress`) off the view: a transient `loading` view,
7479
+ // or one awaiting the sign-in's reference, means a network step is in
7480
+ // flight, so keep the bar trickling; any real
6834
7481
  // view completes it. The controller is idempotent, so overlapping calls are
6835
7482
  // safe, and it is a no-op when the hook is absent (any non-popup host).
6836
- if (this.viewState.view === 'loading') {
7483
+ if (this.viewState.view === 'loading' || this.viewState.view === 'awaiting-reference') {
6837
7484
  progressStart();
6838
7485
  }
6839
7486
  else {
@@ -6852,6 +7499,41 @@ class IdentityRenderer {
6852
7499
  this.focusTimeoutId = setTimeout(() => focusable.focus(), 50);
6853
7500
  }
6854
7501
  }
7502
+ /** Place the empty live region beside the flow content, once per container. */
7503
+ placeStatusRegion() {
7504
+ const body = this.container.getBody();
7505
+ if (!body || this.statusRegion?.isConnected)
7506
+ return;
7507
+ const region = document.createElement('div');
7508
+ region.className = 'sv-sr-only';
7509
+ region.setAttribute('role', 'status');
7510
+ region.setAttribute('aria-live', 'polite');
7511
+ region.setAttribute('aria-atomic', 'true');
7512
+ body.insertAdjacentElement('beforebegin', region);
7513
+ this.statusRegion = region;
7514
+ }
7515
+ /**
7516
+ * Put `words` in the live region, a moment after the view that says them
7517
+ * is in place, so they never land in the same change as the region or the
7518
+ * view that holds them; empty words clear it at once.
7519
+ */
7520
+ announce(words) {
7521
+ if (this.statusTimer !== null) {
7522
+ clearTimeout(this.statusTimer);
7523
+ this.statusTimer = null;
7524
+ }
7525
+ const region = this.statusRegion;
7526
+ if (!region)
7527
+ return;
7528
+ if (!words) {
7529
+ region.textContent = '';
7530
+ return;
7531
+ }
7532
+ this.statusTimer = setTimeout(() => {
7533
+ this.statusTimer = null;
7534
+ region.textContent = words;
7535
+ }, STATUS_ANNOUNCE_DELAY_MS);
7536
+ }
6855
7537
  destroyCurrentView() {
6856
7538
  if (this.currentView?.destroy) {
6857
7539
  this.currentView.destroy();
@@ -6910,6 +7592,7 @@ class IdentityRenderer {
6910
7592
  createViewForState(state) {
6911
7593
  switch (state.view) {
6912
7594
  case 'loading':
7595
+ case 'awaiting-reference':
6913
7596
  return new LoadingView({ message: 'Loading...' });
6914
7597
  case 'identity-input':
6915
7598
  return new IdentityInputView({
@@ -6922,6 +7605,10 @@ class IdentityRenderer {
6922
7605
  onPasskey: this.canDiscoverableVerify()
6923
7606
  ? () => { void this.launchDiscoverableVerify(); }
6924
7607
  : undefined,
7608
+ leadingMethod: this.leadingFederationMethod(),
7609
+ // A person who started typing keeps the step: a reference that
7610
+ // arrives later adds the provider's button, never leaves for it.
7611
+ onType: () => { this.untouchedStep = null; },
6925
7612
  });
6926
7613
  case 'method-select':
6927
7614
  return new MethodSelectView({
@@ -7024,11 +7711,20 @@ class IdentityRenderer {
7024
7711
  });
7025
7712
  case 'oauth-pending':
7026
7713
  return new LoadingView({ message: `Connecting to ${state.provider}...` });
7714
+ case 'federation-checking':
7715
+ return new LoadingView({ message: `Checking your ${state.displayName} sign-in…`, announce: true });
7027
7716
  case 'error':
7028
7717
  return new ErrorView({
7029
7718
  message: state.message,
7030
7719
  code: state.code,
7031
- onRetry: () => this.showIdentityInput(),
7720
+ // A failed provider sign-in tries again from the sign-in's first
7721
+ // step, where the provider leads; nothing leaves on its own again.
7722
+ // A reference the page could not get is asked for again.
7723
+ onRetry: state.code === FEDERATION_FAILED
7724
+ ? () => { void this.showSignInStep(); }
7725
+ : state.code === SIGNIN_REFERENCE_UNAVAILABLE_CODE
7726
+ ? () => this.retryReference()
7727
+ : () => this.showIdentityInput(),
7032
7728
  onClose: () => this.handleClose(),
7033
7729
  });
7034
7730
  case 'service-unavailable':
@@ -7077,7 +7773,15 @@ class IdentityRenderer {
7077
7773
  });
7078
7774
  return;
7079
7775
  }
7080
- // Enrich method IDs with metadata from static registry
7776
+ // Read before the passkey check below, so a reference that lands while
7777
+ // the check runs finds this list held, as one landing just after it
7778
+ // would: the provider, read after the check, then leads the list, and
7779
+ // starts on its own from the untouched first step (showInitialAuthStep).
7780
+ const federationAwaited = this.federationAwaitingReference(this.recipient);
7781
+ // Enrich method IDs with metadata from static registry. The account's own
7782
+ // identity provider is set apart: it needs no identifier, and leads every
7783
+ // list that offers it (below), read once the rest of the list is known so
7784
+ // a reference that arrived meanwhile counts.
7081
7785
  let methods = enrichMethods(methodIds);
7082
7786
  if (this.recipient) {
7083
7787
  // Filter by identifier type. Passkeys are SVID-scoped, so they remain
@@ -7108,6 +7812,9 @@ class IdentityRenderer {
7108
7812
  if (this.verificationState.passkey.isFallbackMode) {
7109
7813
  methods = methods.filter((m) => m.type !== 'passkey');
7110
7814
  }
7815
+ if (this.offersFederationBeside(this.recipient)) {
7816
+ methods = [...enrichMethods(['federation'], this.federation), ...methods];
7817
+ }
7111
7818
  if (methods.length === 0) {
7112
7819
  this.setState(this.noMethodState());
7113
7820
  return;
@@ -7117,8 +7824,11 @@ class IdentityRenderer {
7117
7824
  // pick a method — it is the safest, fastest option. The back arrow on
7118
7825
  // the passkey view re-enters this method with autoRoute=false so the
7119
7826
  // user lands on the full picker (passkey still listed) and can pick
7120
- // a code or SparkLink instead.
7827
+ // a code or SparkLink instead. A provider that starts on its own once the
7828
+ // pending reference lands goes first, as with the reference held
7829
+ // (startWithFederation), so the list waits for it instead.
7121
7830
  if (autoRoute
7831
+ && !this.federationStartsOnItsOwn(federationAwaited)
7122
7832
  && this.verificationState.passkey.hasPasskey === true
7123
7833
  && !this.verificationState.passkey.isFallbackMode
7124
7834
  && methods.some((m) => m.type === 'passkey')) {
@@ -7138,11 +7848,22 @@ class IdentityRenderer {
7138
7848
  // link, with no consent, and again on every reload;
7139
7849
  // - a text or call to a phone number the flow supplied: the person never
7140
7850
  // typed it under the SMS and voice consent the identifier field carries,
7141
- // so the picker carries that consent and the tap gives it.
7851
+ // so the picker carries that consent and the tap gives it;
7852
+ // - the account's own identity provider, once the page may no longer leave
7853
+ // for it on its own (it already did, or a round trip came back): Back
7854
+ // from the provider must never be forwarded to it again;
7855
+ // - a list the provider is missing from only while the page's ask for the
7856
+ // sign-in's reference is out (federationAwaitingReference): with the
7857
+ // reference held the provider leads it, so it is never one method.
7142
7858
  // (Passkey auto-route above still applies — a biometric prompt costs
7143
7859
  // nothing and can be dismissed.)
7144
7860
  const sendsToSuppliedPhone = this.identityPrefilled && methods[0].identityType === 'phone';
7145
- if (methods.length === 1 && !this.isIdentityFixed() && !sendsToSuppliedPhone) {
7861
+ const heldFederation = methods[0].type === 'federation' && !this.federationMayAutoStart;
7862
+ if (methods.length === 1
7863
+ && !this.isIdentityFixed()
7864
+ && !sendsToSuppliedPhone
7865
+ && !heldFederation
7866
+ && federationAwaited === null) {
7146
7867
  this.handleMethodSelect(methods[0]);
7147
7868
  return;
7148
7869
  }
@@ -7157,8 +7878,17 @@ class IdentityRenderer {
7157
7878
  * its sender held to a passkey admits the passkey alone, so a person the
7158
7879
  * check found holding none is told the request needs a passkey already
7159
7880
  * registered with SparkVault and that only the sender can resend it at a
7160
- * level they can clear: no retry here changes that. Any other verification
7161
- * with nothing to offer is a configuration fault, shown as one.
7881
+ * level they can clear: no retry here changes that. An account whose
7882
+ * remaining way in is its own identity provider, which this page does not
7883
+ * offer now (see `federationOffered`), depends on why:
7884
+ * - the page can never hold a reference (an SDK that predates it opened
7885
+ * the page): the site must update its sign-in, and no retry here changes
7886
+ * that;
7887
+ * - the page's ask for its reference is still out: the step waits for it;
7888
+ * - the ask found none for now: the person is told to try again, which
7889
+ * asks again.
7890
+ * Any other verification with nothing to offer is a configuration fault,
7891
+ * shown as one.
7162
7892
  */
7163
7893
  noMethodState() {
7164
7894
  if (this.verificationState.passkeyRequired && this.verificationState.passkey.hasPasskey === false) {
@@ -7168,6 +7898,20 @@ class IdentityRenderer {
7168
7898
  message: strongerVerificationMessage('request', this.sdkConfig?.branding?.companyName),
7169
7899
  };
7170
7900
  }
7901
+ if (this.accountFederation && !this.federationOffered) {
7902
+ if (!this.askReference) {
7903
+ const name = this.sdkConfig?.federation?.display_name?.trim();
7904
+ return {
7905
+ view: 'error',
7906
+ code: FEDERATION_UNAVAILABLE_CODE,
7907
+ message: `This site needs to update its sign-in to use ${name || 'your organization\'s sign-in'}.`,
7908
+ };
7909
+ }
7910
+ if (this.referenceAsk === 'unavailable') {
7911
+ return { view: 'error', code: SIGNIN_REFERENCE_UNAVAILABLE_CODE, message: 'We couldn\'t start sign-in. Try again.' };
7912
+ }
7913
+ return { view: 'awaiting-reference' };
7914
+ }
7171
7915
  return { view: 'error', message: 'No authentication methods available', code: 'no_methods' };
7172
7916
  }
7173
7917
  handleIdentitySubmit(result) {
@@ -7289,6 +8033,12 @@ class IdentityRenderer {
7289
8033
  }
7290
8034
  break;
7291
8035
  }
8036
+ case 'federation': {
8037
+ // A click is always interactive; a start with no click (the only
8038
+ // method, auto-selected) is the page leaving on its own.
8039
+ await this.leaveForFederation({ silent: false, automatic: !userInitiated });
8040
+ break;
8041
+ }
7292
8042
  default:
7293
8043
  this.setState({
7294
8044
  view: 'error',
@@ -7520,13 +8270,15 @@ class IdentityRenderer {
7520
8270
  passkeyFallbackMethodsAvailable() {
7521
8271
  if (!this.sdkConfig)
7522
8272
  return false;
7523
- const methods = enrichMethods(this.verificationState.methodIds);
8273
+ const methods = enrichMethods(this.verificationState.methodIds, this.federation);
7524
8274
  if (!this.recipient) {
7525
- return methods.some((m) => m.type === 'social');
8275
+ return methods.some((m) => m.type === 'social' || m.type === 'federation');
7526
8276
  }
7527
8277
  return methods.some((m) => {
7528
8278
  if (m.type === 'passkey')
7529
8279
  return false;
8280
+ if (m.type === 'federation')
8281
+ return this.offersFederationBeside(this.recipient);
7530
8282
  if (this.identityType === 'phone')
7531
8283
  return m.identityType === 'phone';
7532
8284
  return m.identityType === 'email';
@@ -7555,9 +8307,104 @@ class IdentityRenderer {
7555
8307
  this.setState({ view: 'oauth-pending', provider });
7556
8308
  const { state } = await this.api.drawAuthorizationValues();
7557
8309
  sessionStorage.setItem('sv_oauth_state', state);
7558
- const authUrl = this.api.getSocialAuthUrl(provider, currentPageReturnUrl(), state, this.verificationState.authContext);
8310
+ const authUrl = this.api.getSocialAuthUrl(provider, currentPageReturnUrl(), state, this.verificationState.authContext, this.verificationState.signinRef);
7559
8311
  window.location.href = authUrl;
7560
8312
  }
8313
+ /**
8314
+ * The account's own identity provider, while this verification offers it:
8315
+ * this page offers it now (federationOffered), `/config` describes it, and
8316
+ * the verification's methods list it. A verify session's methods never do,
8317
+ * for such a sign-in cannot complete one.
8318
+ */
8319
+ get federation() {
8320
+ return this.federationOffered ? this.accountFederation : null;
8321
+ }
8322
+ /**
8323
+ * Whether this page offers the account's own identity provider now (see
8324
+ * VerifyOptions.signinRef): while it holds its sign-in's reference, or
8325
+ * when it completes in its own window.
8326
+ */
8327
+ get federationOffered() {
8328
+ return this.offeredWithoutReference || this.verificationState.signinRef !== null;
8329
+ }
8330
+ /** The account's own identity provider while `/config` describes it and the verification's methods list it. */
8331
+ get accountFederation() {
8332
+ const federation = this.sdkConfig?.federation;
8333
+ const methodIds = this.verificationState.methodIds;
8334
+ return federation && Array.isArray(methodIds) && methodIds.includes('federation') ? federation : null;
8335
+ }
8336
+ /**
8337
+ * Whether a list of methods offers the account's own identity provider
8338
+ * beside the identifier it is for. It needs no identifier, so the first
8339
+ * step offers it (above the identifier field, or in a list with none), and
8340
+ * so does a list for an identifier the flow supplied, whose person never saw
8341
+ * that step. An identifier the person typed came from the identifier
8342
+ * field, which already offered it.
8343
+ */
8344
+ offersFederationBeside(recipient) {
8345
+ return !recipient || this.identityPrefilled;
8346
+ }
8347
+ /** The identifier field's leading method: the account's own identity provider, when offered. */
8348
+ leadingFederationMethod() {
8349
+ const [method] = enrichMethods(['federation'], this.federation);
8350
+ if (!method)
8351
+ return undefined;
8352
+ return { method, onSelect: () => { void this.handleMethodSelect(method, true); } };
8353
+ }
8354
+ /**
8355
+ * Leave for the account's own identity provider, the way a social sign-in
8356
+ * leaves (handleSocialLogin): the round trip returns to this page, query
8357
+ * intact, the state stored here is what its `#token` (or its refusal's
8358
+ * fragment) must answer, and the start carries the sign-in's reference
8359
+ * when the page holds one. A silent attempt shows a status the whole time
8360
+ * it runs. A start without the person's click (`automatic`) is recorded, so
8361
+ * a person who comes Back from the provider's page is not sent on again.
8362
+ */
8363
+ async leaveForFederation({ silent, automatic }) {
8364
+ const federation = this.federation;
8365
+ if (!federation)
8366
+ return;
8367
+ if (automatic)
8368
+ this.federationMayAutoStart = false;
8369
+ this.setState(silent
8370
+ ? { view: 'federation-checking', displayName: federation.display_name }
8371
+ : { view: 'oauth-pending', provider: federation.display_name });
8372
+ const { state } = await this.api.drawAuthorizationValues();
8373
+ sessionStorage.setItem('sv_oauth_state', state);
8374
+ if (automatic)
8375
+ markFederationAutoStart(this.api.accountId);
8376
+ this.watchForPageRestore();
8377
+ window.location.href = this.api.getFederationAuthUrl(currentPageReturnUrl(), state, this.verificationState.authContext, { silent, signinRef: this.verificationState.signinRef });
8378
+ }
8379
+ /**
8380
+ * A browser that restores this page from its back/forward cache, as the
8381
+ * person comes Back from the provider, runs nothing again, so the page would
8382
+ * keep the wait it left on. Show the sign-in's first step instead, with the
8383
+ * automatic start spent.
8384
+ */
8385
+ watchForPageRestore() {
8386
+ if (this.pageRestoreHandler)
8387
+ return;
8388
+ this.pageRestoreHandler = (event) => {
8389
+ if (!event.persisted)
8390
+ return;
8391
+ takeFederationAutoStart(this.api.accountId);
8392
+ this.federationMayAutoStart = false;
8393
+ void this.showSignInStep();
8394
+ };
8395
+ window.addEventListener('pageshow', this.pageRestoreHandler);
8396
+ }
8397
+ /** The failure of a sign-in through the account's own identity provider, in fixed words, never the provider's. */
8398
+ federationFailedState() {
8399
+ const name = this.sdkConfig?.federation?.display_name;
8400
+ return {
8401
+ view: 'error',
8402
+ code: FEDERATION_FAILED,
8403
+ message: name
8404
+ ? `We couldn't sign you in with ${name}. Please try again.`
8405
+ : 'We couldn\'t sign you in through your organization. Please try again.',
8406
+ };
8407
+ }
7561
8408
  normalizeError(error) {
7562
8409
  if (error instanceof IdentityApiError) {
7563
8410
  return new SparkVaultError(error.message, error.code);
@@ -10110,7 +10957,13 @@ function createCloseButton(className, onClick) {
10110
10957
  * The popup must open synchronously in the gesture or the browser blocks it as
10111
10958
  * programmatic. `verify()` reaches `start()` through microtask-only awaits (the
10112
10959
  * redirect-result check does no I/O; the preloaded config resolves from cache),
10113
- * so transient activation survives.
10960
+ * so transient activation survives. Each popup's reference (app-sdk
10961
+ * SIGNIN_REFERENCE) is therefore drawn only after that popup opens, by the
10962
+ * owner (`drawSigninReference`). Once the owner has decided it (its pending
10963
+ * marker holds the drawn reference, or the popup has none), the launcher
10964
+ * posts it to the popup in answer to each "ready" ping: the reference, or
10965
+ * null. A popup told null may ask again (`SIGNIN_REFERENCE.retryMessage`),
10966
+ * and the owner then draws afresh for it.
10114
10967
  *
10115
10968
  * It is one dialog. The happy path is clean: logo, a subtle animation, and
10116
10969
  * "continue in the secure window". A single warning appears under the logo only
@@ -10180,6 +11033,8 @@ class DialogLauncher {
10180
11033
  this.modal = null;
10181
11034
  this.alertEl = null;
10182
11035
  this.popupWindow = null;
11036
+ // The current popup has pinged that its page loaded.
11037
+ this.popupReady = false;
10183
11038
  this.openTimer = null;
10184
11039
  this.settled = false;
10185
11040
  // Bumped on every open so a superseded popup's late result or ready ping
@@ -10201,11 +11056,22 @@ class DialogLauncher {
10201
11056
  this.modal = null;
10202
11057
  this.alertEl = null;
10203
11058
  }
11059
+ /**
11060
+ * The owner decided the current popup's reference: tell the popup if it
11061
+ * already pinged. A popup that loads later is told in answer to its ping.
11062
+ */
11063
+ signinReferenceDecided() {
11064
+ if (this.popupReady)
11065
+ this.postSigninReference();
11066
+ }
10204
11067
  openPopup() {
10205
11068
  const generation = ++this.generation;
11069
+ this.popupReady = false;
10206
11070
  this.popupLauncher
10207
11071
  .openPopup({
10208
- url: buildSigninUrl(this.config, this.options),
11072
+ // The popup opens before its reference can be drawn, so its URL says
11073
+ // this opener posts it.
11074
+ url: buildSigninUrl(this.config, this.options, { kind: 'popup' }),
10209
11075
  windowName: 'sparkvault-login',
10210
11076
  resultType: LOGIN_RESULT_TYPE,
10211
11077
  readyType: LOGIN_READY_TYPE,
@@ -10216,15 +11082,59 @@ class DialogLauncher {
10216
11082
  this.popupWindow = popup;
10217
11083
  this.scheduleOpenWarning();
10218
11084
  },
10219
- // The page loaded and pinged back — the open succeeded, so cancel the
10220
- // open-failure warning no matter how long the person now takes.
10221
- onReady: () => { if (generation === this.generation)
10222
- this.clearOpenTimer(); },
11085
+ // The page loaded and pinged back: the open succeeded, so cancel the
11086
+ // open-failure warning no matter how long the person now takes. The
11087
+ // page pings on every load, a provider's round trip included, and
11088
+ // each load is told the popup's reference afresh.
11089
+ onReady: () => {
11090
+ if (generation !== this.generation)
11091
+ return;
11092
+ this.clearOpenTimer();
11093
+ this.popupReady = true;
11094
+ this.postSigninReference();
11095
+ },
11096
+ requestType: SIGNIN_REFERENCE.retryMessage,
11097
+ onRequest: () => {
11098
+ if (generation === this.generation)
11099
+ this.answerSigninReferenceRetry();
11100
+ },
10223
11101
  })
10224
11102
  .then((message) => { if (generation === this.generation)
10225
11103
  this.handleResult(message); })
10226
11104
  .catch((error) => { if (generation === this.generation)
10227
11105
  this.handleError(error); });
11106
+ // Drawn only now, for this popup alone: it opens inside the click, which
11107
+ // no draw can finish within, and no earlier popup's reference is reused.
11108
+ this.callbacks.drawSigninReference();
11109
+ }
11110
+ /**
11111
+ * The current popup asked again for its reference. A popup that has none
11112
+ * gets a fresh draw (the owner re-arms the marker, then decides), one that
11113
+ * holds a reference is told it again, and one whose draw is still out is
11114
+ * told once that draw is decided.
11115
+ */
11116
+ answerSigninReferenceRetry() {
11117
+ const reference = this.callbacks.signinReference();
11118
+ if (reference === null) {
11119
+ this.callbacks.drawSigninReference();
11120
+ return;
11121
+ }
11122
+ if (reference !== undefined)
11123
+ this.postSigninReference();
11124
+ }
11125
+ /**
11126
+ * Post the current popup's reference, once the owner decided it, to this
11127
+ * launcher's own popup: the reference the marker holds, or null for a
11128
+ * popup with none, so the page knows at once that it has none for now
11129
+ * instead of waiting it out. Only a document there on the trusted Identity
11130
+ * origin receives it: the browser drops it while the popup shows any other
11131
+ * origin (a provider's page).
11132
+ */
11133
+ postSigninReference() {
11134
+ const reference = this.callbacks.signinReference();
11135
+ if (reference === undefined || !this.popupWindow)
11136
+ return;
11137
+ this.popupWindow.postMessage({ type: SIGNIN_REFERENCE.message, [SIGNIN_REFERENCE.param]: reference }, this.trustedOrigin);
10228
11138
  }
10229
11139
  handleResult(message) {
10230
11140
  if (this.settled)
@@ -10337,9 +11247,8 @@ class DialogLauncher {
10337
11247
  this.openTimer = null;
10338
11248
  }
10339
11249
  }
10340
- /** "Try again": close any current popup and reopen a fresh one. */
11250
+ /** "Try again": close any current popup and open a fresh one, as the first opened. */
10341
11251
  retry() {
10342
- this.callbacks.onPopupReopened?.();
10343
11252
  this.hideAlert();
10344
11253
  this.closePopup();
10345
11254
  this.openPopup();
@@ -10602,35 +11511,28 @@ function attachClickHandler(selector, onClick) {
10602
11511
  }
10603
11512
 
10604
11513
  /**
10605
- * Identity Module
10606
- *
10607
- * Passwordless sign-in through the first-party SparkVault popup.
10608
- * Supports passkey, OTP, SparkLink, and social authentication.
11514
+ * The pending sign-in marker: what lets a site whose popup result was lost (a
11515
+ * mobile browser discards the backgrounded opener tab, which clears the
11516
+ * message listener but not sessionStorage) recover it on its next load, for
11517
+ * at most SIGNIN_RECOVERY.pendingTtlMs.
10609
11518
  *
10610
- * @example Programmatic
10611
- * const result = await sv.products.identity.signIn();
10612
- *
10613
- * @example Attached to clicks
10614
- * sv.products.identity.attach('.login-btn');
11519
+ * `sv_signin_pending` holds JSON `{ at, hint, ref }`:
11520
+ * - `at`: when the current popup opened, on this browser's clock; the
11521
+ * marker's TTL.
11522
+ * - `hint`: the email or phone the sign-in started with, or null when the
11523
+ * flow collects the identifier itself; the recovery bounce's `login_hint`.
11524
+ * - `ref`: the current popup's reference (app-sdk SIGNIN_REFERENCE), present
11525
+ * once drawn and written; the recovery bounce names it, and `/sso` then
11526
+ * mints only when the hub session it would mint from carries it. A marker
11527
+ * without one bounces with no reference.
10615
11528
  */
10616
- const PORTAL_SECTIONS = ['home', 'identity', 'security', 'sessions', 'sites'];
10617
- // The exact algorithms the Identity server signs identity tokens with: EdDSA by
10618
- // default, RS256 when a client opts in via `id_token_signed_response_alg`. The
10619
- // unverified client-side decode gates on this set so an unsigned (`none`) or
10620
- // algorithm-confused token cannot masquerade as valid.
10621
- const ACCEPTED_TOKEN_ALGS = ['EdDSA', 'RS256'];
10622
- // A sign-in is "pending" from popup open until its result arrives; a marker
10623
- // that outlives a lost result (a mobile opener-tab discard clears the message
10624
- // listener but not sessionStorage) is what lets the next load self-heal.
10625
11529
  const PENDING_KEY = 'sv_signin_pending';
10626
- const PENDING_TTL_MS = 10 * 60 * 1000;
10627
11530
  /**
10628
- * Read and parse the pending marker — JSON `{ at, hint }`, where `hint` is the
10629
- * email or phone the sign-in was started with (null when the flow collects the
10630
- * identifier itself). A bare-timestamp value is accepted as `{ at, hint: null }`:
10631
- * markers live at most 10 minutes in sessionStorage, so any such value
10632
- * disappears within one deploy window of this parser going live — the fallback
10633
- * is bounded and never grows. Anything unreadable yields null.
11531
+ * Read and parse the pending marker. Anything unreadable yields null: a value
11532
+ * that is not a JSON object, an `at` that is no finite number, or a `ref`
11533
+ * that is present but no sign-in reference. A recovery that cannot name the
11534
+ * reference its marker records could mint any hub session in this browser, so
11535
+ * such a marker recovers nothing.
10634
11536
  */
10635
11537
  function readPendingMarker() {
10636
11538
  let raw = null;
@@ -10643,37 +11545,177 @@ function readPendingMarker() {
10643
11545
  if (!raw) {
10644
11546
  return null;
10645
11547
  }
10646
- let at = NaN;
10647
- let hint = null;
11548
+ let parsed;
10648
11549
  try {
10649
- const parsed = JSON.parse(raw);
10650
- if (typeof parsed === 'object' && parsed !== null) {
10651
- const marker = parsed;
10652
- if (typeof marker.at === 'number') {
10653
- at = marker.at;
10654
- }
10655
- if (typeof marker.hint === 'string' && marker.hint) {
10656
- hint = marker.hint;
10657
- }
10658
- }
10659
- else if (typeof parsed === 'number') {
10660
- // A bare timestamp parses as a JSON number.
10661
- at = parsed;
10662
- }
11550
+ parsed = JSON.parse(raw);
10663
11551
  }
10664
11552
  catch {
10665
- at = Number(raw);
11553
+ return null;
11554
+ }
11555
+ if (typeof parsed !== 'object' || parsed === null) {
11556
+ return null;
11557
+ }
11558
+ const marker = parsed;
11559
+ if (typeof marker.at !== 'number' || !Number.isFinite(marker.at)) {
11560
+ return null;
10666
11561
  }
10667
- return Number.isFinite(at) ? { at, hint } : null;
11562
+ const { ref } = marker;
11563
+ if (ref !== undefined && !isSigninReference(ref)) {
11564
+ return null;
11565
+ }
11566
+ return {
11567
+ at: marker.at,
11568
+ hint: typeof marker.hint === 'string' && marker.hint ? marker.hint : null,
11569
+ ref: typeof ref === 'string' ? ref : null,
11570
+ };
10668
11571
  }
10669
- /** True while a marker is within the self-heal TTL. */
11572
+ /** True while a marker is within the recovery TTL. */
10670
11573
  function isFreshPendingMarker(marker) {
10671
- return marker !== null && Date.now() - marker.at < PENDING_TTL_MS;
11574
+ return marker !== null && Date.now() - marker.at < SIGNIN_RECOVERY.pendingTtlMs;
10672
11575
  }
10673
- /** True when the pending marker is present and still within its TTL. */
10674
- function hasFreshPendingMarker() {
10675
- return isFreshPendingMarker(readPendingMarker());
11576
+ /** Remove the pending marker. */
11577
+ function removePendingMarker() {
11578
+ try {
11579
+ sessionStorage.removeItem(PENDING_KEY);
11580
+ }
11581
+ catch {
11582
+ // Nothing to clear.
11583
+ }
11584
+ }
11585
+ /**
11586
+ * The reference a draw yields within SIGNIN_REFERENCE.drawDeadlineMs, else
11587
+ * null: a draw that fails or misses the deadline leaves the sign-in page
11588
+ * without one, and a draw that lands later is discarded. Never rejects.
11589
+ */
11590
+ function signinReferenceInTime(draw) {
11591
+ return new Promise((settle) => {
11592
+ const deadline = setTimeout(() => settle(null), SIGNIN_REFERENCE.drawDeadlineMs);
11593
+ draw.then((reference) => { clearTimeout(deadline); settle(reference); }, () => { clearTimeout(deadline); settle(null); });
11594
+ });
11595
+ }
11596
+ /**
11597
+ * One popup sign-in's marker, from its first popup's open until the sign-in
11598
+ * settles. Every popup it opens, the first and each "Try again", is an open
11599
+ * of its own: it re-arms the marker holding no reference and draws its own
11600
+ * reference (signinReferenceInTime), which joins the marker once drawn. A
11601
+ * popup that has none asks again, and the same popup is then opened afresh,
11602
+ * with a draw of its own. An earlier open's reference is never reused, and
11603
+ * its draw, should it land later, is discarded. `reference` is what the
11604
+ * current popup is told, and the marker always holds it: a popup can never
11605
+ * hold a reference the marker does not.
11606
+ */
11607
+ class PendingSignIn {
11608
+ constructor(hint) {
11609
+ this.hint = hint;
11610
+ this.at = 0;
11611
+ this.live = true;
11612
+ // Counts the opens and the ends of their popups, so a draw that lands after
11613
+ // its popup ended or was replaced is recognised and dropped.
11614
+ this.opens = 0;
11615
+ this.current = undefined;
11616
+ this.decided = Promise.resolve();
11617
+ }
11618
+ /**
11619
+ * The current popup's reference: undefined while its draw is out, null
11620
+ * when it has none (its draw failed or missed the deadline, the marker
11621
+ * write failed, or the popup already ended), else the reference the marker
11622
+ * holds.
11623
+ */
11624
+ get reference() {
11625
+ return this.current;
11626
+ }
11627
+ /**
11628
+ * A popup opened, or the current one asked again for the reference it
11629
+ * lacks: arm the marker holding no reference, and draw this open's own.
11630
+ * Resolves true once this open's reference is decided while its popup is
11631
+ * still the current one of a live sign-in, so that popup may be told; false
11632
+ * when the popup ended or was replaced, or the sign-in ended. Never
11633
+ * rejects.
11634
+ */
11635
+ open(draw) {
11636
+ if (!this.live)
11637
+ return Promise.resolve(false);
11638
+ const open = ++this.opens;
11639
+ this.at = Date.now();
11640
+ this.current = undefined;
11641
+ // A marker this open cannot write must not keep an earlier open's reference.
11642
+ if (!this.write(null))
11643
+ removePendingMarker();
11644
+ const decided = signinReferenceInTime(draw()).then((reference) => {
11645
+ if (!this.live || open !== this.opens)
11646
+ return false;
11647
+ this.current = reference !== null && this.write(reference) ? reference : null;
11648
+ return true;
11649
+ });
11650
+ this.decided = decided;
11651
+ return decided;
11652
+ }
11653
+ /**
11654
+ * The opener saw the popup end with no result, so there is no lost result
11655
+ * to recover: without this, a reload while the retry alert is up would
11656
+ * bounce for nothing. The ended popup is told nothing more, and its draw,
11657
+ * should it land, is dropped.
11658
+ */
11659
+ retire() {
11660
+ if (!this.live)
11661
+ return;
11662
+ this.opens += 1;
11663
+ this.current = null;
11664
+ removePendingMarker();
11665
+ }
11666
+ /** The sign-in settled, or another replaced it: retire the marker, and nothing this sign-in does later touches it. */
11667
+ end() {
11668
+ this.retire();
11669
+ this.live = false;
11670
+ }
11671
+ /**
11672
+ * The current popup's reference, waiting at most `waitMs` for an open still
11673
+ * drawing it: the reference the marker holds, else null (the popup has
11674
+ * none, or its draw has not landed in time). Never rejects.
11675
+ */
11676
+ referenceWithin(waitMs) {
11677
+ if (this.current !== undefined)
11678
+ return Promise.resolve(this.current);
11679
+ return new Promise((settle) => {
11680
+ const deadline = setTimeout(() => settle(this.current ?? null), waitMs);
11681
+ void this.decided.then(() => {
11682
+ clearTimeout(deadline);
11683
+ settle(this.current ?? null);
11684
+ });
11685
+ });
11686
+ }
11687
+ /** Write the marker; a write that fails leaves the stored marker as it was. */
11688
+ write(reference) {
11689
+ const marker = { at: this.at, hint: this.hint, ...(reference ? { ref: reference } : {}) };
11690
+ try {
11691
+ sessionStorage.setItem(PENDING_KEY, JSON.stringify(marker));
11692
+ }
11693
+ catch {
11694
+ return false;
11695
+ }
11696
+ return true;
11697
+ }
10676
11698
  }
11699
+
11700
+ /**
11701
+ * Identity Module
11702
+ *
11703
+ * Passwordless sign-in through the first-party SparkVault popup.
11704
+ * Supports passkey, OTP, SparkLink, social authentication, and the account's
11705
+ * own identity provider.
11706
+ *
11707
+ * @example Programmatic
11708
+ * const result = await sv.products.identity.signIn();
11709
+ *
11710
+ * @example Attached to clicks
11711
+ * sv.products.identity.attach('.login-btn');
11712
+ */
11713
+ const PORTAL_SECTIONS = ['home', 'identity', 'security', 'sessions', 'sites'];
11714
+ // The exact algorithms the Identity server signs identity tokens with: EdDSA by
11715
+ // default, RS256 when a client opts in via `id_token_signed_response_alg`. The
11716
+ // unverified client-side decode gates on this set so an unsigned (`none`) or
11717
+ // algorithm-confused token cannot masquerade as valid.
11718
+ const ACCEPTED_TOKEN_ALGS = ['EdDSA', 'RS256'];
10677
11719
  /**
10678
11720
  * Whether `handleRedirectResult()` has anything to do on this load — a returned
10679
11721
  * sign-in fragment to consume, or a pending sign-in to self-heal. Public + side
@@ -10689,7 +11731,7 @@ function isSignInRecoveryPending() {
10689
11731
  if (/[#&](sv_code|sv_error|sso)=/.test(window.location.hash || '')) {
10690
11732
  return true;
10691
11733
  }
10692
- return hasFreshPendingMarker();
11734
+ return isFreshPendingMarker(readPendingMarker());
10693
11735
  }
10694
11736
  function isTokenClaims(payload) {
10695
11737
  if (typeof payload !== 'object' || payload === null) {
@@ -10740,6 +11782,8 @@ class IdentityModule {
10740
11782
  constructor(config) {
10741
11783
  this.renderer = null;
10742
11784
  this.launcher = null;
11785
+ // The popup sign-in in flight: its pending marker and reference.
11786
+ this.pendingSignIn = null;
10743
11787
  this.config = config;
10744
11788
  this.api = new IdentityApi(config);
10745
11789
  // Preload config in background for instant dialog opening
@@ -10877,8 +11921,10 @@ class IdentityModule {
10877
11921
  * Resilience: pair this with `handleRedirectResult()` on page load. If the
10878
11922
  * popup's result is ever lost (a mobile browser discards the backgrounded
10879
11923
  * opener tab), the next load silently self-heals from the SSO session the
10880
- * login established. `flow: 'redirect'` opts a caller out of the popup into a
10881
- * same-tab navigation instead.
11924
+ * popup signed in or chose; a sign-in that opened none (the account's own
11925
+ * identity provider) comes back signed out, to sign in again. `flow:
11926
+ * 'redirect'` opts a caller out of the popup into a same-tab navigation
11927
+ * instead.
10882
11928
  *
10883
11929
  * @example
10884
11930
  * const result = await sv.products.identity.signIn();
@@ -10896,13 +11942,12 @@ class IdentityModule {
10896
11942
  * Core flow runner. Default mode (no `target`) opens the popup; `flow:
10897
11943
  * 'redirect'` navigates the tab instead; local mode (`renderMode: 'local'` /
10898
11944
  * `target`) renders into the current document and powers the
10899
- * SparkVault-hosted sign-in surfaces (see the internal `render`).
11945
+ * SparkVault-hosted sign-in surfaces (see the internal `render`), which
11946
+ * hands it what a round trip to the account's own identity provider
11947
+ * returned (`federationReturn`).
10900
11948
  */
10901
- async runFlow(options = {}) {
10902
- if (this.launcher) {
10903
- this.launcher.close();
10904
- this.launcher = null;
10905
- }
11949
+ async runFlow(options = {}, federationReturn = null) {
11950
+ this.closeLauncher();
10906
11951
  if (this.renderer) {
10907
11952
  this.renderer.close();
10908
11953
  }
@@ -10945,7 +11990,7 @@ class IdentityModule {
10945
11990
  },
10946
11991
  };
10947
11992
  const startLocalRender = (container) => {
10948
- this.renderer = new IdentityRenderer(container, this.api, mergedOptions, hostCallbacks);
11993
+ this.renderer = new IdentityRenderer(container, this.api, mergedOptions, hostCallbacks, federationReturn);
10949
11994
  this.renderer.start().catch((error) => {
10950
11995
  // A startup failure must surface inside the SparkVault dialog, never
10951
11996
  // close it silently. Render the error in-dialog instead (consistent with
@@ -10967,10 +12012,11 @@ class IdentityModule {
10967
12012
  // returns via handleRedirectResult() (the escape hatch for hosts that
10968
12013
  // want to skip the popup on mobile). Then this page is unloading, so the
10969
12014
  // promise never settles on success; it rejects only if the redirect
10970
- // cannot start.
12015
+ // cannot start. The sign-in completes in that tab, which no recovery
12016
+ // stands in for, so it draws no reference.
10971
12017
  if (mergedOptions.flow === 'redirect') {
10972
12018
  try {
10973
- if (!await this.startRedirectFlow(mergedOptions)) {
12019
+ if (!await this.startRedirectFlow(mergedOptions, null)) {
10974
12020
  hostCallbacks.onError(new ValidationError('Sign-in requires browser session storage. Enable site data for this site and try again.'));
10975
12021
  }
10976
12022
  }
@@ -10983,24 +12029,44 @@ class IdentityModule {
10983
12029
  // as in flight so that if its result is lost (a mobile browser discards
10984
12030
  // the backgrounded opener tab, killing the postMessage listener),
10985
12031
  // handleRedirectResult() can silently self-heal on the next load from
10986
- // the SSO session the popup login established.
10987
- const pendingHint = mergedOptions.email || mergedOptions.phone || null;
10988
- this.markSignInPending(pendingHint);
10989
- this.launcher = new DialogLauncher(this.config, this.api, mergedOptions, {
10990
- onSuccess: (result) => { this.clearSignInPending(); hostCallbacks.onSuccess(result); },
10991
- onError: (error) => { this.clearSignInPending(); hostCallbacks.onError(error); },
10992
- onCancel: () => { this.clearSignInPending(); hostCallbacks.onCancel(); },
12032
+ // the SSO session the popup signed in or chose, which that popup's
12033
+ // reference names (see pending-signin.ts).
12034
+ const pending = new PendingSignIn(mergedOptions.email || mergedOptions.phone || null);
12035
+ this.pendingSignIn = pending;
12036
+ const launcher = new DialogLauncher(this.config, this.api, mergedOptions, {
12037
+ onSuccess: (result) => { pending.end(); hostCallbacks.onSuccess(result); },
12038
+ onError: (error) => { pending.end(); hostCallbacks.onError(error); },
12039
+ onCancel: () => { pending.end(); hostCallbacks.onCancel(); },
10993
12040
  // Self-heal exists for a result the opener never observed. An observed
10994
12041
  // no-result end retires the marker (no spurious bounce on a reload
10995
- // while the retry alert is up); "Try again" re-arms it.
10996
- onPopupClosedUnresolved: () => this.clearSignInPending(),
10997
- onPopupReopened: () => this.markSignInPending(pendingHint),
12042
+ // while the retry alert is up).
12043
+ onPopupClosedUnresolved: () => pending.retire(),
12044
+ // Every popup, the first and each "Try again", arms the marker anew
12045
+ // with a reference of its own, and so does a popup that has none and
12046
+ // asks again. It reaches the popup only once the marker holds it (or
12047
+ // as null, once the popup has none).
12048
+ drawSigninReference: () => {
12049
+ void pending.open(() => this.api.drawSigninReference()).then((stillCurrent) => {
12050
+ if (stillCurrent)
12051
+ launcher.signinReferenceDecided();
12052
+ });
12053
+ },
10998
12054
  // COOP-severed popup: postMessage can never deliver, so switch this tab
10999
- // to the redirect flow (returns via handleRedirectResult). The pending
11000
- // marker stays armed — the returned #sv_code fragment retires it.
11001
- onPopupSevered: () => this.startRedirectFlow(mergedOptions),
12055
+ // to the redirect flow (returns via handleRedirectResult). It carries
12056
+ // the reference the marker holds for this popup, waiting a moment for
12057
+ // a draw still out, and the marker stays armed: the returned #sv_code
12058
+ // fragment retires it. With none by then, the marker is retired, for
12059
+ // no recovery may stand in for a page sent without a reference.
12060
+ onPopupSevered: async () => {
12061
+ const signinRef = await pending.referenceWithin(SIGNIN_REFERENCE.redirectWaitMs);
12062
+ if (signinRef === null)
12063
+ pending.retire();
12064
+ return this.startRedirectFlow(mergedOptions, signinRef);
12065
+ },
12066
+ signinReference: () => pending.reference,
11002
12067
  });
11003
- this.launcher.start();
12068
+ this.launcher = launcher;
12069
+ launcher.start();
11004
12070
  return settledPromise;
11005
12071
  }
11006
12072
  startLocalRender(isInline
@@ -11033,6 +12099,7 @@ class IdentityModule {
11033
12099
  phone: options.phone,
11034
12100
  authContext: options.authContext,
11035
12101
  prompt: options.prompt,
12102
+ method: options.method,
11036
12103
  onSuccess: options.onSuccess,
11037
12104
  onError: options.onError,
11038
12105
  onCancel: options.onCancel,
@@ -11108,10 +12175,13 @@ class IdentityModule {
11108
12175
  * `onSuccess` (and resolve with it).
11109
12176
  * 2. A sign-in was in flight but never delivered (a mobile browser
11110
12177
  * discarded the backgrounded opener tab, killing the popup's
11111
- * postMessage) — silently re-mint from the SSO session the completed
11112
- * popup login established, by navigating this tab through the silent SSO
11113
- * endpoint and straight back with a code (case 1 on return). Nothing is
11114
- * shown; if there is no live session it comes back logged-out, no oracle.
12178
+ * postMessage) — silently re-mint from the SSO session the popup signed
12179
+ * in or chose, by navigating this tab through the silent SSO endpoint
12180
+ * and straight back with a code (case 1 on return). The bounce names
12181
+ * the sign-in's reference, and the endpoint mints only when the
12182
+ * session it would mint from carries it. Nothing is shown; with no
12183
+ * such session (a sign-in that opened none, such as one through the
12184
+ * account's own identity provider) it comes back logged-out, no oracle.
11115
12185
  *
11116
12186
  * The code is one-time, PKCE-bound, and origin-locked — never the token. The
11117
12187
  * host must still verify `result.token` server-side via the Identity JWKS.
@@ -11140,8 +12210,8 @@ class IdentityModule {
11140
12210
  // No returned result. If a sign-in was in flight and its result never
11141
12211
  // arrived, self-heal once from the SSO session (mobile opener-tab discard).
11142
12212
  const pending = this.consumeSignInPending();
11143
- if (pending.fresh) {
11144
- await this.startRecoveryBounce(pending.hint);
12213
+ if (pending) {
12214
+ await this.startRecoveryBounce(pending);
11145
12215
  }
11146
12216
  return null;
11147
12217
  }
@@ -11152,7 +12222,7 @@ class IdentityModule {
11152
12222
  // A returned fragment means this sign-in resolved (redeem, cancel, or
11153
12223
  // error), so retire any pending marker — otherwise it could fire one
11154
12224
  // spurious silent bounce on a later load inside its TTL.
11155
- this.clearSignInPending();
12225
+ removePendingMarker();
11156
12226
  // Consume exactly once: fragment and one-shot state/verifier are cleared
11157
12227
  // up front on every path, so a failing result cannot wedge future loads
11158
12228
  // (and a StrictMode double-invocation finds an empty hash and no-ops).
@@ -11206,8 +12276,8 @@ class IdentityModule {
11206
12276
  }
11207
12277
  }
11208
12278
  /**
11209
- * Silently re-mint the sign-in result from the SSO session the completed
11210
- * popup login left behind. Navigates this tab through the silent SSO endpoint
12279
+ * Silently re-mint the sign-in result from the SSO session the popup signed
12280
+ * in or chose. Navigates this tab through the silent SSO endpoint
11211
12281
  * (a top-level GET, so the `SameSite=Lax` hub cookie rides along) which,
11212
12282
  * PKCE-bound, returns a one-time code in the fragment — handled by case 1 on
11213
12283
  * return. No-op (stays put) if session storage or WebCrypto is unavailable,
@@ -11217,52 +12287,73 @@ class IdentityModule {
11217
12287
  * malformed answer) rejects `handleRedirectResult()` with that error, and the
11218
12288
  * page stays put.
11219
12289
  */
11220
- async startRecoveryBounce(loginHint) {
12290
+ async startRecoveryBounce(pending) {
12291
+ const handoff = await this.armHandoffReturn();
12292
+ if (!handoff) {
12293
+ return;
12294
+ }
11221
12295
  const sso = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/sso`);
11222
12296
  // With several hub sessions, login_hint names the account the interrupted
11223
- // sign-in was addressing, and it is the whole wrong-account defence: /sso
11224
- // mints silently ONLY for a hint that matched exactly one hub session's
11225
- // verified identifiers — every unsatisfiable hint (a stranger's address, an
11226
- // ambiguous match, an account not eligible here) comes back with no result
11227
- // at all rather than a different account's.
11228
- if (loginHint) {
11229
- sso.searchParams.set('login_hint', loginHint);
11230
- }
11231
- const nav = await this.prepareHandoffNavigation(sso.toString());
11232
- if (nav) {
11233
- window.location.assign(nav);
11234
- }
11235
- }
11236
- /**
11237
- * Explicit `flow: 'redirect'` — navigate this tab to the interactive sign-in
11238
- * page. Plain sign-in carries redirect_uri + state + PKCE challenge and
11239
- * returns via the fragment code; OIDC/simple modes navigate bare (their
11240
- * server-rendered pages drive the server-validated redirect back).
12297
+ // sign-in was addressing: /sso mints silently ONLY for a hint that matched
12298
+ // exactly one hub session's verified identifiers — every unsatisfiable hint
12299
+ // (a stranger's address, an ambiguous match, an account not eligible here)
12300
+ // comes back with no result at all rather than a different account's.
12301
+ if (pending.hint) {
12302
+ sso.searchParams.set('login_hint', pending.hint);
12303
+ }
12304
+ // The sign-in's reference, recorded on the hub session the popup signed
12305
+ // in or chose: /sso mints only when that session carries it. Without it, a
12306
+ // sign-in that opened no hub session of its own (the account's own
12307
+ // identity provider) would recover as whatever session this browser
12308
+ // already held, someone else entirely.
12309
+ if (pending.ref) {
12310
+ sso.searchParams.set(SIGNIN_REFERENCE.param, pending.ref);
12311
+ }
12312
+ sso.searchParams.set('redirect_uri', handoff.redirectUri);
12313
+ sso.searchParams.set('state', handoff.state);
12314
+ sso.searchParams.set('code_challenge', handoff.codeChallenge);
12315
+ window.location.assign(sso.toString());
12316
+ }
12317
+ /**
12318
+ * Navigate this tab to the interactive sign-in page: explicit `flow:
12319
+ * 'redirect'`, or a popup whose handle COOP severed. Plain sign-in carries
12320
+ * redirect_uri + state + PKCE challenge and returns via the fragment code;
12321
+ * OIDC/simple modes navigate without them (their server-rendered pages drive
12322
+ * the server-validated redirect back). Either carries `signinRef`, the
12323
+ * severed popup's reference; a redirect draws none of its own.
11241
12324
  *
12325
+ * @param signinRef - The reference the pending marker holds for this
12326
+ * sign-in, or null for a page sent without one
11242
12327
  * @returns false when the return leg cannot be armed (no session storage or
11243
12328
  * WebCrypto) — the caller surfaces an actionable error instead of a
11244
12329
  * silent dead-end.
11245
12330
  */
11246
- async startRedirectFlow(options) {
12331
+ async startRedirectFlow(options, signinRef) {
12332
+ if (signinRef === null) {
12333
+ // With no marker, no recovery can stand in for this page's result, so
12334
+ // the page needs no reference. A marker left from an earlier sign-in
12335
+ // would otherwise bounce on the next load in place of this one.
12336
+ removePendingMarker();
12337
+ }
11247
12338
  const authContext = options.authContext;
11248
12339
  if (authContext?.authRequestId || authContext?.simpleMode?.sessionId) {
11249
- window.location.assign(buildSigninUrl(this.config, options));
12340
+ window.location.assign(buildSigninUrl(this.config, options, { kind: 'redirect', signinRef }));
11250
12341
  return true;
11251
12342
  }
11252
- const url = await this.prepareHandoffNavigation(buildSigninUrl(this.config, options), (extras) => buildSigninUrl(this.config, options, extras));
11253
- if (!url) {
12343
+ const handoff = await this.armHandoffReturn();
12344
+ if (!handoff) {
11254
12345
  return false;
11255
12346
  }
11256
- window.location.assign(url);
12347
+ window.location.assign(buildSigninUrl(this.config, options, { kind: 'redirect', signinRef, handoff }));
11257
12348
  return true;
11258
12349
  }
11259
12350
  /**
11260
- * Arm the PKCE + state return leg for a handoff navigation and return the URL
11261
- * to navigate to (redirect_uri = this page, per `currentPageReturnUrl`).
11262
- * Returns null when session storage or WebCrypto is unavailable so callers
11263
- * can degrade.
12351
+ * Arm the PKCE + state return leg of a handoff navigation and return what
12352
+ * the navigation carries for it (redirect_uri = this page, per
12353
+ * `currentPageReturnUrl`). Returns null when session storage or WebCrypto is
12354
+ * unavailable so callers can degrade.
11264
12355
  */
11265
- async prepareHandoffNavigation(base, build) {
12356
+ async armHandoffReturn() {
11266
12357
  const { state, codeVerifier } = await this.api.drawAuthorizationValues();
11267
12358
  // Derive the challenge BEFORE persisting: a WebCrypto failure (insecure
11268
12359
  // context) then leaves no orphaned state/verifier behind in storage.
@@ -11280,49 +12371,25 @@ class IdentityModule {
11280
12371
  catch {
11281
12372
  return null;
11282
12373
  }
11283
- const redirectUri = currentPageReturnUrl();
11284
- if (build) {
11285
- return build({ redirectUri, state, codeChallenge });
11286
- }
11287
- const url = new URL(base);
11288
- url.searchParams.set('redirect_uri', redirectUri);
11289
- url.searchParams.set('state', state);
11290
- url.searchParams.set('code_challenge', codeChallenge);
11291
- return url.toString();
11292
- }
11293
- /**
11294
- * Arm the self-heal marker for an in-flight sign-in. `hint` is the identifier
11295
- * (email or phone) the sign-in was started with, when the caller supplied
11296
- * one — the recovery bounce forwards it as the /sso `login_hint`, so with
11297
- * several hub sessions recovery re-mints the account this sign-in was for,
11298
- * never a different one.
11299
- */
11300
- markSignInPending(hint) {
11301
- try {
11302
- sessionStorage.setItem(PENDING_KEY, JSON.stringify({ at: Date.now(), hint }));
11303
- }
11304
- catch {
11305
- // No storage → no self-heal; the popup still delivers when it can.
11306
- }
11307
- }
11308
- clearSignInPending() {
11309
- try {
11310
- sessionStorage.removeItem(PENDING_KEY);
11311
- }
11312
- catch {
11313
- // Nothing to clear.
11314
- }
12374
+ return { redirectUri: currentPageReturnUrl(), state, codeChallenge };
11315
12375
  }
11316
12376
  /**
11317
- * Consume the pending marker: `fresh` is true once (then cleared) if a recent
11318
- * sign-in is still awaiting its result; `hint` is the identifier that sign-in
11319
- * carried, for the recovery bounce's `login_hint`.
12377
+ * Consume the pending marker: the marker once (then cleared) while a recent
12378
+ * sign-in is still awaiting its result, else null. Its `hint` is the
12379
+ * identifier that sign-in carried, for the recovery bounce's `login_hint`,
12380
+ * and its `ref` the sign-in's reference, when the marker holds one.
11320
12381
  */
11321
12382
  consumeSignInPending() {
11322
12383
  const marker = readPendingMarker();
11323
- const fresh = isFreshPendingMarker(marker);
11324
- this.clearSignInPending();
11325
- return { fresh, hint: fresh ? marker.hint : null };
12384
+ removePendingMarker();
12385
+ return isFreshPendingMarker(marker) ? marker : null;
12386
+ }
12387
+ /** Close the popup sign-in's launcher, ending the sign-in it ran. */
12388
+ closeLauncher() {
12389
+ this.launcher?.close();
12390
+ this.launcher = null;
12391
+ this.pendingSignIn?.end();
12392
+ this.pendingSignIn = null;
11326
12393
  }
11327
12394
  /** Remove the result fragment from the URL bar (and history entry). */
11328
12395
  clearUrlFragment() {
@@ -11341,8 +12408,9 @@ class IdentityModule {
11341
12408
  }
11342
12409
  }
11343
12410
  /**
11344
- * Complete a social round trip that returned to the sign-in page as
11345
- * `#token=…&state=…`. Only `render()` — the Identity-origin sign-in page —
12411
+ * Complete a social round trip, or one through the account's own identity
12412
+ * provider, that returned to the sign-in page as `#token=…&state=…`. Only
12413
+ * `render()`, the Identity-origin sign-in page,
11346
12414
  * reads it: no SDK flow returns a `#token` to a site (a site's results arrive
11347
12415
  * by the popup's postMessage, FedCM, or a PKCE-bound `#sv_code`), so on a site
11348
12416
  * it could only be someone else's token, or the site's own direct
@@ -11353,7 +12421,7 @@ class IdentityModule {
11353
12421
  return null;
11354
12422
  }
11355
12423
  const params = new URLSearchParams(window.location.hash.slice(1));
11356
- const token = params.get('token');
12424
+ const token = params.get(SIGNIN_RESULT_FRAGMENT.token);
11357
12425
  if (!token) {
11358
12426
  return null;
11359
12427
  }
@@ -11376,7 +12444,7 @@ class IdentityModule {
11376
12444
  // provider. Anyone can compose a URL carrying their own genuinely-signed
11377
12445
  // token, so a fragment with no stored state, or a different one, is an
11378
12446
  // unsolicited result (login CSRF) and is refused.
11379
- if (!expectedState || params.get('state') !== expectedState) {
12447
+ if (!expectedState || params.get(SIGNIN_RESULT_FRAGMENT.state) !== expectedState) {
11380
12448
  throw new ValidationError('Invalid OAuth state');
11381
12449
  }
11382
12450
  // Unverified client-side decode — surfaces the claims for the result
@@ -11400,7 +12468,38 @@ class IdentityModule {
11400
12468
  catch {
11401
12469
  // Storage disabled (private mode): nothing to clear.
11402
12470
  }
12471
+ // The round trip came back, so a start this tab made on its own is
12472
+ // answered and must not hold back the page's next sign-in.
12473
+ takeFederationAutoStart(this.config.accountId);
12474
+ }
12475
+ }
12476
+ /**
12477
+ * Read a refusal a round trip through the account's own identity provider
12478
+ * returned to the sign-in page (`#error=…&state=…`, see federation-flow.ts).
12479
+ * Such a fragment is consumed exactly once, with the state it answers,
12480
+ * whatever it holds. Null for any other fragment, and for a refusal whose
12481
+ * state is not the one this browser stored before it left: an answer to no
12482
+ * sign-in this browser started, which the page ignores.
12483
+ */
12484
+ consumeFederationReturn() {
12485
+ if (typeof window === 'undefined' || !window.location.hash) {
12486
+ return null;
12487
+ }
12488
+ const params = new URLSearchParams(window.location.hash.slice(1));
12489
+ const refusal = federationRefusalIn(params);
12490
+ if (!refusal) {
12491
+ return null;
12492
+ }
12493
+ let expectedState = null;
12494
+ try {
12495
+ expectedState = sessionStorage.getItem('sv_oauth_state');
12496
+ sessionStorage.removeItem('sv_oauth_state');
12497
+ }
12498
+ catch {
12499
+ // Storage disabled: no sign-in could have stored a state here.
11403
12500
  }
12501
+ this.clearUrlFragment();
12502
+ return expectedState && params.get(SIGNIN_RESULT_FRAGMENT.state) === expectedState ? refusal : null;
11404
12503
  }
11405
12504
  /**
11406
12505
  * Close the identity dialog/inline UI if open.
@@ -11409,10 +12508,7 @@ class IdentityModule {
11409
12508
  * mode) or the local renderer (inline / local mode).
11410
12509
  */
11411
12510
  close() {
11412
- if (this.launcher) {
11413
- this.launcher.close();
11414
- this.launcher = null;
11415
- }
12511
+ this.closeLauncher();
11416
12512
  if (this.renderer) {
11417
12513
  this.renderer.close();
11418
12514
  this.renderer = null;
@@ -11456,9 +12552,12 @@ class IdentityModule {
11456
12552
  /**
11457
12553
  * Render the flow into a page element instead of a popup.
11458
12554
  *
11459
- * A social login started here returns to this same page with its result in
11460
- * the fragment, so a returned `#token` is completed first (see
11461
- * `consumeRedirectResult`) instead of starting the flow again.
12555
+ * A social login, or one through the account's own identity provider,
12556
+ * started here returns to this same page with its result in the fragment,
12557
+ * so a returned `#token` is completed first (see `consumeRedirectResult`)
12558
+ * instead of starting the flow again, and a returned refusal of the
12559
+ * account's own identity provider is handed to the flow it starts (see
12560
+ * `consumeFederationReturn`).
11462
12561
  *
11463
12562
  * @internal Used only by the SparkVault-hosted sign-in popup and hosted login
11464
12563
  * page (which own their chrome and pass `renderMode: 'local'`). Customer
@@ -11470,7 +12569,7 @@ class IdentityModule {
11470
12569
  options.onSuccess?.(returned);
11471
12570
  return returned;
11472
12571
  }
11473
- return this.runFlow(options);
12572
+ return this.runFlow(options, this.consumeFederationReturn());
11474
12573
  }
11475
12574
  }
11476
12575
 
@@ -28355,7 +29454,7 @@ class SparkVault {
28355
29454
  }
28356
29455
  /** Get the SDK version */
28357
29456
  static get version() {
28358
- return '16.0.1';
29457
+ return '16.1.0';
28359
29458
  }
28360
29459
  }
28361
29460
  if (typeof window !== 'undefined') {