@sparkvault/sdk-js 16.0.1 → 16.1.1

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,125 @@ 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. The sign-in providers' marks are the one exception: each is its
4405
+ * owner's filled logo, in the owner's colors, or in `currentColor` where the
4406
+ * owner's mark is one-color (Apple, GitHub). Uses proper DOM element creation
4407
+ * for security.
4049
4408
  */
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
-
4409
+ function createSvgElement(viewBox, width = 16, height = 16) {
4410
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
4411
+ svg.setAttribute('viewBox', viewBox);
4412
+ svg.setAttribute('width', String(width));
4413
+ svg.setAttribute('height', String(height));
4414
+ svg.setAttribute('fill', 'none');
4415
+ svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
4416
+ return svg;
4417
+ }
4418
+ function createPath(d, attrs = {}) {
4419
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
4420
+ path.setAttribute('d', d);
4421
+ for (const [key, value] of Object.entries(attrs)) {
4422
+ path.setAttribute(key, value);
4423
+ }
4424
+ return path;
4425
+ }
4426
+ function createCircle(cx, cy, r, attrs = {}) {
4427
+ const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
4428
+ circle.setAttribute('cx', String(cx));
4429
+ circle.setAttribute('cy', String(cy));
4430
+ circle.setAttribute('r', String(r));
4431
+ for (const [key, value] of Object.entries(attrs)) {
4432
+ circle.setAttribute(key, value);
4433
+ }
4434
+ return circle;
4435
+ }
4057
4436
  /**
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.
4437
+ * Checkmark icon for benefit lists
4075
4438
  */
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 */
4439
+ function createCheckmarkIcon() {
4440
+ const svg = createSvgElement('0 0 16 16');
4441
+ svg.appendChild(createPath('M13.25 4.75L6 12 2.75 8.75', {
4442
+ stroke: 'currentColor',
4443
+ 'stroke-width': '2',
4444
+ 'stroke-linecap': 'round',
4445
+ 'stroke-linejoin': 'round',
4446
+ }));
4447
+ return svg;
4448
+ }
4085
4449
  /**
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.
4450
+ * Back arrow (chevron left)
4093
4451
  */
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;
4452
+ function createBackArrowIcon() {
4453
+ const svg = createSvgElement('0 0 16 16');
4454
+ svg.appendChild(createPath('M10 12L6 8L10 4', {
4455
+ stroke: 'currentColor',
4456
+ 'stroke-width': '2',
4457
+ 'stroke-linecap': 'round',
4458
+ 'stroke-linejoin': 'round',
4459
+ }));
4460
+ return svg;
4103
4461
  }
4104
4462
  /**
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`
4463
+ * Close (X) icon
4109
4464
  */
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;
4465
+ function createCloseIcon() {
4466
+ const svg = createSvgElement('0 0 20 20', 20, 20);
4467
+ svg.appendChild(createPath('M15 5L5 15M5 5L15 15', {
4468
+ stroke: 'currentColor',
4469
+ 'stroke-width': '1.5',
4470
+ 'stroke-linecap': 'round',
4471
+ }));
4472
+ return svg;
4116
4473
  }
4117
-
4118
4474
  /**
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.
4475
+ * Passkey icon - bare outline key design
4126
4476
  */
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
- }
4477
+ function createPasskeyIcon() {
4478
+ const svg = createSvgElement('0 0 56 56', 56, 56);
4479
+ svg.classList.add('sv-passkey-icon');
4480
+ // Key glyph optically centered in the 56px box (footprint unchanged)
4481
+ const group = document.createElementNS('http://www.w3.org/2000/svg', 'g');
4482
+ group.setAttribute('transform', 'translate(29.5, 26.5)');
4483
+ const strokeAttrs = {
4484
+ stroke: 'currentColor',
4485
+ 'stroke-width': '3',
4486
+ 'stroke-linecap': 'round',
4487
+ 'stroke-linejoin': 'round',
4488
+ fill: 'none',
4489
+ };
4490
+ // Key head (circle)
4491
+ group.appendChild(createCircle(-9.5, -9.5, 9.5, strokeAttrs));
4492
+ // Key shaft
4493
+ group.appendChild(createPath('M-2.8 -2.8L16 16', strokeAttrs));
4494
+ // Key teeth
4495
+ group.appendChild(createPath('M9.5 9.5L9.5 15.5', strokeAttrs));
4496
+ group.appendChild(createPath('M16 16L16 22', strokeAttrs));
4497
+ svg.appendChild(group);
4498
+ return svg;
4346
4499
  }
4347
-
4348
4500
  /**
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.
4501
+ * Bare outline alert triangle shared by the error and expired icons.
4502
+ * Color comes from `currentColor` via the class-specific stylesheet rules.
4354
4503
  */
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' }));
4504
+ function createAlertTriangleIcon(className) {
4505
+ const svg = createSvgElement('0 0 48 48', 48, 48);
4506
+ svg.classList.add(className);
4507
+ const strokeAttrs = {
4508
+ stroke: 'currentColor',
4509
+ 'stroke-width': '2.5',
4510
+ 'stroke-linecap': 'round',
4511
+ 'stroke-linejoin': 'round',
4512
+ fill: 'none',
4513
+ };
4514
+ // Triangle outline
4515
+ svg.appendChild(createPath('M24 9L5.5 39h37L24 9z', strokeAttrs));
4516
+ // Exclamation
4517
+ svg.appendChild(createPath('M24 20v8', strokeAttrs));
4518
+ svg.appendChild(createCircle(24, 33.5, 1.5, { fill: 'currentColor' }));
4465
4519
  return svg;
4466
4520
  }
4467
4521
  /**
@@ -4620,9 +4674,10 @@ function createGithubIcon() {
4620
4674
  svg.appendChild(createPath('M10 0C4.48 0 0 4.48 0 10c0 4.42 2.86 8.17 6.84 9.49.5.09.68-.22.68-.48 0-.24-.01-1.02-.01-1.86-2.51.46-3.16-.61-3.36-1.18-.11-.29-.6-1.18-1.02-1.41-.35-.19-.85-.65-.01-.66.79-.01 1.35.72 1.54 1.02.9 1.51 2.34 1.09 2.91.83.09-.65.35-1.09.64-1.34-2.22-.25-4.55-1.11-4.55-4.94 0-1.09.39-1.99 1.02-2.69-.1-.25-.45-1.27.1-2.65 0 0 .84-.27 2.75 1.02.8-.22 1.65-.33 2.5-.33s1.7.11 2.5.33c1.91-1.3 2.75-1.02 2.75-1.02.55 1.38.2 2.4.1 2.65.64.7 1.02 1.59 1.02 2.69 0 3.84-2.34 4.69-4.57 4.94.36.31.67.91.67 1.85 0 1.34-.01 2.41-.01 2.75 0 .27.18.58.69.48C17.14 18.16 20 14.42 20 10c0-5.52-4.48-10-10-10z'));
4621
4675
  return svg;
4622
4676
  }
4677
+ /** Facebook's mark and blue as Simple Icons (CC0-1.0) draws them, in its own 24-unit box. */
4623
4678
  function createFacebookIcon() {
4624
- const svg = createSvgElement('0 0 20 20', 20, 20);
4625
- svg.appendChild(createPath('M20 10.06c0-5.52-4.48-10-10-10S0 4.53 0 10.06c0 4.99 3.66 9.13 8.44 9.88v-6.99H5.9v-2.89h2.54V7.85c0-2.51 1.49-3.89 3.78-3.89 1.09 0 2.24.2 2.24.2v2.46h-1.26c-1.24 0-1.63.77-1.63 1.56v1.88h2.77l-.44 2.89h-2.33v6.99c4.78-.75 8.44-4.89 8.44-9.88z', { fill: '#1877F2' }));
4679
+ const svg = createSvgElement('0 0 24 24', 20, 20);
4680
+ svg.appendChild(createPath('M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978.401 0 .955.042 1.468.103a8.68 8.68 0 0 1 1.141.195v3.325a8.623 8.623 0 0 0-.653-.036 26.805 26.805 0 0 0-.733-.009c-.707 0-1.259.096-1.675.309a1.686 1.686 0 0 0-.679.622c-.258.42-.374.995-.374 1.752v1.297h3.919l-.386 2.103-.287 1.564h-3.246v8.245C19.396 23.238 24 18.179 24 12.044c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.628 3.874 10.35 9.101 11.647Z', { fill: '#0866FF' }));
4626
4681
  return svg;
4627
4682
  }
4628
4683
  function createLinkedinIcon() {
@@ -4658,6 +4713,380 @@ function createUsersIcon() {
4658
4713
  return svg;
4659
4714
  }
4660
4715
 
4716
+ /**
4717
+ * Method Button
4718
+ *
4719
+ * A sign-in method's button, drawn one way wherever a method is offered: the
4720
+ * method list, and the identifier step that leads with the account's own
4721
+ * identity provider. The caller attaches its click handler, and removes it.
4722
+ */
4723
+ /**
4724
+ * The button: its glyph, hidden from assistive technology so the button is
4725
+ * named by its words alone; the method's name; and its description, when it
4726
+ * has one.
4727
+ */
4728
+ function methodButton(method) {
4729
+ const btn = document.createElement('button');
4730
+ btn.className = 'sv-btn sv-btn-method';
4731
+ const content = div('sv-method-content');
4732
+ const icon = div('sv-method-icon');
4733
+ icon.setAttribute('aria-hidden', 'true');
4734
+ icon.appendChild(createMethodIcon(method.icon));
4735
+ content.appendChild(icon);
4736
+ const text = div('sv-method-text');
4737
+ const name = document.createElement('div');
4738
+ name.className = 'sv-method-name';
4739
+ name.textContent = method.name;
4740
+ text.appendChild(name);
4741
+ if (method.description) {
4742
+ const description = document.createElement('div');
4743
+ description.className = 'sv-method-description';
4744
+ description.textContent = method.description;
4745
+ text.appendChild(description);
4746
+ }
4747
+ content.appendChild(text);
4748
+ btn.appendChild(content);
4749
+ return btn;
4750
+ }
4751
+
4752
+ /**
4753
+ * Two consent lines, each in one wording for every surface that shows it: the
4754
+ * SMS and voice consent beside a phone number, and the terms a signup
4755
+ * accepts. Each line is split around the documents it links, and each document
4756
+ * has its one address here: a surface draws the words between the links and
4757
+ * links each document at TERMS_URL or PRIVACY_URL.
4758
+ *
4759
+ * BROWSER-SAFE: data only, no imports. sdk-mobile mirrors it.
4760
+ */
4761
+
4762
+ /** The terms of service, published once, on the marketing site. */
4763
+ const TERMS_URL = 'https://sparkvault.com/terms/';
4764
+
4765
+ /** The privacy policy, published once, on the marketing site. */
4766
+ const PRIVACY_URL = 'https://sparkvault.com/privacy/';
4767
+
4768
+ /**
4769
+ * Beside every field where a person enters a phone number SparkVault texts or
4770
+ * calls (the sign-in field and the backup phone of Identity's sign-in, in
4771
+ * sdk-js and sdk-mobile, the mobile app's backup phone, and auth.sv's new
4772
+ * phone number), and under the sign-in's method picker wherever it offers a
4773
+ * text or a call: a phone number the sign-in was handed reaches the picker
4774
+ * without passing the field. The terms take the consent from whoever provides
4775
+ * the number, so the words fit a number typed and a number handed over alike.
4776
+ * A carrier approves the number SparkVault texts from only when this line, its
4777
+ * call to action, names the service, the consent, how often messages come,
4778
+ * that rates may apply, how to opt out and get help, and links the terms and
4779
+ * the privacy policy, so it says each of them. It agrees with the terms' SMS
4780
+ * and voice disclosures and the privacy policy (apps/www/terms.md 15,
4781
+ * apps/www/privacy.md 1.1, held to them by
4782
+ * apps/www/tests/consent-lines.test.mjs): texts carry the codes, alerts and
4783
+ * notifications they name and calls only the codes, STOP opts the number out,
4784
+ * HELP answers, frequency varies, rates may apply, and where texts and calls
4785
+ * go and how to opt back in (START or UNSTOP) are the terms' to say.
4786
+ */
4787
+ const SMS_CONSENT = Object.freeze({
4788
+ 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 ',
4789
+ terms: 'Terms',
4790
+ beforePrivacy: ' and ',
4791
+ privacy: 'Privacy Policy',
4792
+ afterPrivacy: ' describe. Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help.'
4793
+ });
4794
+
4795
+ /* global HTMLAnchorElement */
4796
+ /**
4797
+ * SMS and Voice Consent
4798
+ *
4799
+ * The line the sign-in shows wherever a person gives SparkVault a phone number
4800
+ * to text or call, in the platform's one wording
4801
+ * (`@sparkvault/app-sdk/consent-lines`): under every field that takes one, and
4802
+ * under the method picker wherever it offers a text or a call. It describes
4803
+ * the field or the methods above it, so a screen reader reads it with them.
4804
+ */
4805
+ /** A document the line names, linked in place and opening in a new tab. */
4806
+ function documentLink(name, href) {
4807
+ const link = document.createElement('a');
4808
+ link.className = 'sv-sms-consent-link';
4809
+ link.href = href;
4810
+ link.target = '_blank';
4811
+ link.rel = 'noopener noreferrer';
4812
+ link.textContent = name;
4813
+ return link;
4814
+ }
4815
+ /**
4816
+ * The consent line, its "Terms" and "Privacy Policy" opening those documents
4817
+ * in a new tab.
4818
+ *
4819
+ * @param id - The line's id, which the field or each method names in its `aria-describedby`
4820
+ */
4821
+ function smsConsent(id) {
4822
+ const line = document.createElement('p');
4823
+ line.className = 'sv-sms-consent';
4824
+ line.id = id;
4825
+ line.append(SMS_CONSENT.beforeTerms, documentLink(SMS_CONSENT.terms, TERMS_URL), SMS_CONSENT.beforePrivacy, documentLink(SMS_CONSENT.privacy, PRIVACY_URL), SMS_CONSENT.afterPrivacy);
4826
+ return line;
4827
+ }
4828
+
4829
+ /**
4830
+ * Identity Input View
4831
+ *
4832
+ * Collects and validates the user's email or phone number: reads the input as
4833
+ * one or the other by the platform's rules (`@sparkvault/app-sdk/phone` and
4834
+ * `@sparkvault/app-sdk/email-address`), and formats a phone-only field as the
4835
+ * number is typed. A field that takes a phone number carries the SMS and voice
4836
+ * consent beneath it.
4837
+ */
4838
+ class IdentityInputView {
4839
+ constructor(props) {
4840
+ this.container = null;
4841
+ this.inputElement = null;
4842
+ this.labelElement = null;
4843
+ this.submitButton = null;
4844
+ this.passkeyLink = null;
4845
+ this.leadingButton = null;
4846
+ this.leadingHandler = null;
4847
+ this.errorContainer = null;
4848
+ this.focusTimeoutId = null;
4849
+ this.detectedType = 'email';
4850
+ this.props = props;
4851
+ this.boundHandleInput = () => {
4852
+ this.handleInput();
4853
+ this.props.onType?.();
4854
+ };
4855
+ this.boundHandleKeyDown = (e) => {
4856
+ if (e.key === 'Enter') {
4857
+ e.preventDefault();
4858
+ this.handleSubmit();
4859
+ }
4860
+ };
4861
+ this.boundHandleSubmit = () => this.handleSubmit();
4862
+ this.boundHandlePasskey = props.onPasskey ? () => props.onPasskey() : null;
4863
+ }
4864
+ get allowsBoth() {
4865
+ return this.props.allowedTypes.includes('email') && this.props.allowedTypes.includes('phone');
4866
+ }
4867
+ get allowsEmail() {
4868
+ return this.props.allowedTypes.includes('email');
4869
+ }
4870
+ get allowsPhone() {
4871
+ return this.props.allowedTypes.includes('phone');
4872
+ }
4873
+ render() {
4874
+ const container = div('sv-email-view');
4875
+ this.container = container;
4876
+ if (this.props.leadingMethod) {
4877
+ this.offerLeadingMethod(this.props.leadingMethod);
4878
+ }
4879
+ // Compact header - just the subtitle instruction
4880
+ const headerSection = div('sv-email-header');
4881
+ const subtitle = document.createElement('p');
4882
+ subtitle.className = 'sv-email-subtitle';
4883
+ subtitle.textContent = this.getSubtitleText();
4884
+ headerSection.appendChild(subtitle);
4885
+ container.appendChild(headerSection);
4886
+ // Error container
4887
+ this.errorContainer = div('sv-email-error-container');
4888
+ if (this.props.error) {
4889
+ this.errorContainer.appendChild(errorMessage(this.props.error));
4890
+ }
4891
+ container.appendChild(this.errorContainer);
4892
+ // Form section
4893
+ const formSection = div('sv-email-form');
4894
+ const inputWrapper = div('sv-email-input-wrapper');
4895
+ this.labelElement = document.createElement('label');
4896
+ this.labelElement.className = 'sv-email-label';
4897
+ this.labelElement.htmlFor = 'sv-identity-input';
4898
+ this.labelElement.textContent = this.getLabelText();
4899
+ this.inputElement = document.createElement('input');
4900
+ this.inputElement.type = this.allowsPhone && !this.allowsEmail ? 'tel' : 'text';
4901
+ this.inputElement.id = 'sv-identity-input';
4902
+ this.inputElement.className = 'sv-email-input';
4903
+ this.inputElement.placeholder = this.getPlaceholderText();
4904
+ this.inputElement.autocomplete = this.allowsBoth ? 'on' : (this.allowsEmail ? 'email' : 'tel');
4905
+ this.inputElement.required = true;
4906
+ this.inputElement.maxLength = EMAIL_ADDRESS_LIMITS.ADDRESS;
4907
+ if (this.props.initialValue) {
4908
+ this.inputElement.value = this.props.initialValue;
4909
+ this.detectAndUpdateType(this.props.initialValue);
4910
+ }
4911
+ this.inputElement.addEventListener('input', this.boundHandleInput);
4912
+ this.inputElement.addEventListener('keydown', this.boundHandleKeyDown);
4913
+ inputWrapper.appendChild(this.labelElement);
4914
+ inputWrapper.appendChild(this.inputElement);
4915
+ if (this.allowsPhone) {
4916
+ const consent = smsConsent('sv-identity-sms-consent');
4917
+ this.inputElement.setAttribute('aria-describedby', consent.id);
4918
+ inputWrapper.appendChild(consent);
4919
+ }
4920
+ formSection.appendChild(inputWrapper);
4921
+ this.submitButton = document.createElement('button');
4922
+ this.submitButton.className = 'sv-btn sv-btn-email-primary';
4923
+ this.submitButton.textContent = 'Continue';
4924
+ this.submitButton.addEventListener('click', this.boundHandleSubmit);
4925
+ formSection.appendChild(this.submitButton);
4926
+ container.appendChild(formSection);
4927
+ if (this.boundHandlePasskey) {
4928
+ this.passkeyLink = document.createElement('button');
4929
+ this.passkeyLink.className = 'sv-fallback-link';
4930
+ this.passkeyLink.textContent = 'Sign in with a passkey';
4931
+ this.passkeyLink.addEventListener('click', this.boundHandlePasskey);
4932
+ container.appendChild(this.passkeyLink);
4933
+ }
4934
+ this.focusTimeoutId = setTimeout(() => this.inputElement?.focus(), 50);
4935
+ return container;
4936
+ }
4937
+ /**
4938
+ * Offer `leading` above the field, set apart by "or". On a view already on
4939
+ * screen it joins in place, so what the person typed and where their focus
4940
+ * is stay as they were. A view that already leads with a method keeps it.
4941
+ */
4942
+ offerLeadingMethod(leading) {
4943
+ if (!this.container || this.leadingButton)
4944
+ return;
4945
+ this.leadingHandler = leading.onSelect;
4946
+ this.leadingButton = methodButton(leading.method);
4947
+ this.leadingButton.addEventListener('click', this.leadingHandler);
4948
+ const divider = div('sv-divider');
4949
+ const or = document.createElement('span');
4950
+ or.className = 'sv-divider-text';
4951
+ or.textContent = 'or';
4952
+ divider.appendChild(or);
4953
+ this.container.prepend(this.leadingButton, divider);
4954
+ }
4955
+ getSubtitleText() {
4956
+ if (this.allowsBoth)
4957
+ return 'Enter your email or phone to continue';
4958
+ if (this.allowsPhone)
4959
+ return 'Enter your phone number to continue';
4960
+ return 'Enter your email to continue';
4961
+ }
4962
+ getLabelText() {
4963
+ if (this.allowsBoth) {
4964
+ return this.detectedType === 'phone' ? 'Phone number' : 'Email address';
4965
+ }
4966
+ if (this.allowsPhone)
4967
+ return 'Phone number';
4968
+ return 'Email address';
4969
+ }
4970
+ getPlaceholderText() {
4971
+ if (this.allowsBoth)
4972
+ return 'you@example.com or (555) 123-4567';
4973
+ if (this.allowsPhone)
4974
+ return '(555) 123-4567';
4975
+ return 'you@example.com';
4976
+ }
4977
+ handleInput() {
4978
+ this.clearError();
4979
+ if (!this.inputElement)
4980
+ return;
4981
+ const value = this.inputElement.value;
4982
+ if (this.allowsBoth) {
4983
+ // The label follows what the input reads as, but the text is never
4984
+ // rewritten: digits typed so far can still begin an email address
4985
+ // ("2024user@gmail.com", "12345678@qq.com"), and phone formatting would
4986
+ // corrupt it. Submit normalizes a phone number whatever its separators.
4987
+ const wasPhone = this.detectedType === 'phone';
4988
+ this.detectAndUpdateType(value);
4989
+ if (wasPhone !== (this.detectedType === 'phone') && this.labelElement) {
4990
+ this.labelElement.textContent = this.getLabelText();
4991
+ }
4992
+ }
4993
+ else if (this.allowsPhone) {
4994
+ // Phone-only mode: always format
4995
+ const cursorPos = this.inputElement.selectionStart ?? value.length;
4996
+ const formatted = formatPhoneDisplay(value);
4997
+ if (formatted !== value) {
4998
+ this.inputElement.value = formatted;
4999
+ const newPos = Math.min(cursorPos + (formatted.length - value.length), formatted.length);
5000
+ this.inputElement.setSelectionRange(newPos, newPos);
5001
+ }
5002
+ }
5003
+ }
5004
+ detectAndUpdateType(value) {
5005
+ this.detectedType = inferIdentityType(value);
5006
+ }
5007
+ clearError() {
5008
+ if (this.errorContainer) {
5009
+ clearChildren(this.errorContainer);
5010
+ }
5011
+ this.inputElement?.classList.remove('sv-email-input-error');
5012
+ }
5013
+ showError(message) {
5014
+ if (this.errorContainer) {
5015
+ clearChildren(this.errorContainer);
5016
+ this.errorContainer.appendChild(errorMessage(message));
5017
+ }
5018
+ this.inputElement?.classList.add('sv-email-input-error');
5019
+ this.inputElement?.focus();
5020
+ }
5021
+ handleSubmit() {
5022
+ if (!this.inputElement || !this.submitButton)
5023
+ return;
5024
+ const rawValue = this.inputElement.value;
5025
+ // Validate based on detected type
5026
+ if (this.allowsBoth) {
5027
+ if (this.detectedType === 'phone') {
5028
+ const validPhone = parsePhone(rawValue);
5029
+ if (!validPhone) {
5030
+ this.showError('Please enter a valid phone number');
5031
+ return;
5032
+ }
5033
+ this.submitButton.disabled = true;
5034
+ this.submitButton.textContent = 'Please wait...';
5035
+ this.props.onSubmit({ value: validPhone, type: 'phone' });
5036
+ }
5037
+ else {
5038
+ const validEmail = validateEmail(rawValue);
5039
+ if (!validEmail) {
5040
+ this.showError('Please enter a valid email address');
5041
+ return;
5042
+ }
5043
+ this.submitButton.disabled = true;
5044
+ this.submitButton.textContent = 'Please wait...';
5045
+ this.props.onSubmit({ value: validEmail, type: 'email' });
5046
+ }
5047
+ }
5048
+ else if (this.allowsPhone) {
5049
+ const validPhone = parsePhone(rawValue);
5050
+ if (!validPhone) {
5051
+ this.showError('Please enter a valid phone number');
5052
+ return;
5053
+ }
5054
+ this.submitButton.disabled = true;
5055
+ this.submitButton.textContent = 'Please wait...';
5056
+ this.props.onSubmit({ value: validPhone, type: 'phone' });
5057
+ }
5058
+ else {
5059
+ const validEmail = validateEmail(rawValue);
5060
+ if (!validEmail) {
5061
+ this.showError('Please enter a valid email address');
5062
+ return;
5063
+ }
5064
+ this.submitButton.disabled = true;
5065
+ this.submitButton.textContent = 'Please wait...';
5066
+ this.props.onSubmit({ value: validEmail, type: 'email' });
5067
+ }
5068
+ }
5069
+ destroy() {
5070
+ if (this.focusTimeoutId !== null) {
5071
+ clearTimeout(this.focusTimeoutId);
5072
+ this.focusTimeoutId = null;
5073
+ }
5074
+ if (this.inputElement) {
5075
+ this.inputElement.removeEventListener('input', this.boundHandleInput);
5076
+ this.inputElement.removeEventListener('keydown', this.boundHandleKeyDown);
5077
+ }
5078
+ if (this.submitButton) {
5079
+ this.submitButton.removeEventListener('click', this.boundHandleSubmit);
5080
+ }
5081
+ if (this.passkeyLink && this.boundHandlePasskey) {
5082
+ this.passkeyLink.removeEventListener('click', this.boundHandlePasskey);
5083
+ }
5084
+ if (this.leadingButton && this.leadingHandler) {
5085
+ this.leadingButton.removeEventListener('click', this.leadingHandler);
5086
+ }
5087
+ }
5088
+ }
5089
+
4661
5090
  /**
4662
5091
  * Method Select View
4663
5092
  *
@@ -4672,6 +5101,7 @@ const textsOrCalls = (method) => method.identityType === 'phone';
4672
5101
  class MethodSelectView {
4673
5102
  constructor(props) {
4674
5103
  this.backLink = null;
5104
+ this.methodsContainer = null;
4675
5105
  this.methodButtons = [];
4676
5106
  this.methodClickHandlers = new Map();
4677
5107
  this.props = props;
@@ -4692,6 +5122,7 @@ class MethodSelectView {
4692
5122
  }
4693
5123
  const consent = this.props.methods.some(textsOrCalls) ? smsConsent('sv-method-sms-consent') : null;
4694
5124
  const methodsContainer = div();
5125
+ this.methodsContainer = methodsContainer;
4695
5126
  for (const method of this.props.methods) {
4696
5127
  const methodButton = this.createMethodButton(method);
4697
5128
  if (consent && textsOrCalls(method)) {
@@ -4713,6 +5144,18 @@ class MethodSelectView {
4713
5144
  }
4714
5145
  return container;
4715
5146
  }
5147
+ /**
5148
+ * Put `method` at the head of a list already on screen, in place, so the
5149
+ * person's focus stays where it was. The method sends no text or call (the
5150
+ * account's own identity provider), so the list's consent stands as it is.
5151
+ */
5152
+ offerLeadingMethod(method) {
5153
+ if (!this.methodsContainer)
5154
+ return;
5155
+ const button = this.createMethodButton(method);
5156
+ this.methodButtons.unshift(button);
5157
+ this.methodsContainer.prepend(button);
5158
+ }
4716
5159
  createBackLink() {
4717
5160
  const link = document.createElement('button');
4718
5161
  link.className = 'sv-back-link';
@@ -4723,33 +5166,13 @@ class MethodSelectView {
4723
5166
  return link;
4724
5167
  }
4725
5168
  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);
5169
+ const btn = methodButton(method);
4742
5170
  // Create and store handler reference for cleanup
4743
5171
  const handler = () => this.props.onSelectMethod(method);
4744
5172
  this.methodClickHandlers.set(btn, handler);
4745
5173
  btn.addEventListener('click', handler);
4746
5174
  return btn;
4747
5175
  }
4748
- getMethodIcon(method) {
4749
- const iconContainer = div('sv-method-icon');
4750
- iconContainer.appendChild(createMethodIcon(method.icon));
4751
- return iconContainer;
4752
- }
4753
5176
  /**
4754
5177
  * Clean up event listeners to prevent memory leaks.
4755
5178
  */
@@ -5857,6 +6280,18 @@ function isBlockedCode(code) {
5857
6280
  * level they can clear (the message says so).
5858
6281
  */
5859
6282
  const STRONGER_VERIFICATION_REQUIRED_CODE = 'stronger_verification_required';
6283
+ /**
6284
+ * The code of a sign-in whose only way in is the account's own identity
6285
+ * provider, on a page that may not offer it: the site's sign-in predates what
6286
+ * that provider needs, so only the site updating it clears this.
6287
+ */
6288
+ const FEDERATION_UNAVAILABLE_CODE = 'federation_unavailable';
6289
+ /**
6290
+ * The code of a sign-in whose only way in is the account's own identity
6291
+ * provider, on a page that could not get its sign-in's reference just now:
6292
+ * a genuine error, which the person's Try Again asks for again.
6293
+ */
6294
+ const SIGNIN_REFERENCE_UNAVAILABLE_CODE = 'signin_reference_unavailable';
5860
6295
  /**
5861
6296
  * The heading of a state the person can do nothing about from here, by its
5862
6297
  * code, or null for a genuine error. Retrying cannot clear any of them, so the
@@ -5866,12 +6301,13 @@ const STRONGER_VERIFICATION_REQUIRED_CODE = 'stronger_verification_required';
5866
6301
  * - a blocked Identity (trial exhausted or expired, or a paid capacity wall),
5867
6302
  * which only the site owner subscribing clears, shown as a friendly,
5868
6303
  * non-leaky interstitial;
5869
- * - a request held to a passkey the person does not hold.
6304
+ * - a request held to a passkey the person does not hold;
6305
+ * - an account whose only way in this page may not offer.
5870
6306
  */
5871
6307
  function terminalTitle(code) {
5872
6308
  if (code === 'identity_locked')
5873
6309
  return 'This SparkVault Identity is locked';
5874
- if (isBlockedCode(code))
6310
+ if (isBlockedCode(code) || code === FEDERATION_UNAVAILABLE_CODE)
5875
6311
  return 'Sign-in unavailable';
5876
6312
  if (code === STRONGER_VERIFICATION_REQUIRED_CODE)
5877
6313
  return STRONGER_VERIFICATION_TITLE;
@@ -6472,6 +6908,12 @@ function blockedSignInMessage(companyName) {
6472
6908
  : 'Sign-in is temporarily unavailable. Please contact the site owner for assistance.';
6473
6909
  }
6474
6910
  const BLOCKED_ERROR_CODES = new Set(IDENTITY_BLOCKED_ERROR_CODES);
6911
+ /**
6912
+ * How long the live region waits after a view is in place before it takes
6913
+ * the view's words: long enough that assistive technology has seen the
6914
+ * view's change and hears the region's as a change of its own.
6915
+ */
6916
+ const STATUS_ANNOUNCE_DELAY_MS = 100;
6475
6917
  const SPARKLINK_CSP_BLOCKED_ERROR = {
6476
6918
  message: [
6477
6919
  'Connection blocked by security policy.',
@@ -6481,7 +6923,7 @@ const SPARKLINK_CSP_BLOCKED_ERROR = {
6481
6923
  code: 'sparklink_csp_blocked',
6482
6924
  };
6483
6925
  class IdentityRenderer {
6484
- constructor(container, api, options, callbacks) {
6926
+ constructor(container, api, options, callbacks, federationReturn = null) {
6485
6927
  // True while the identifier is the one the render options supplied (a host's
6486
6928
  // prefill, a login hint, an invite's identity), false once the person types
6487
6929
  // their own. Gates the "identity is fixed" behavior, so a no-hint
@@ -6509,10 +6951,29 @@ class IdentityRenderer {
6509
6951
  this.sparkLinkVisibilityHandler = null;
6510
6952
  this.sparkLinkClaiming = false;
6511
6953
  this.sparkLinkRetryTimer = null;
6954
+ this.pageRestoreHandler = null;
6955
+ this.referenceAsk = null;
6956
+ this.referenceAsks = 0;
6957
+ // The sign-in step as it first showed, until the person types into it: a
6958
+ // reference that arrives while it is still on screen may start the
6959
+ // provider on its own, as one held from the start would have.
6960
+ this.untouchedStep = null;
6961
+ // The page's one live region: placed beside the flow content when the
6962
+ // container opens, empty, and kept across views, so the words a view
6963
+ // announces (View.announcement) land in a region already in the page, which
6964
+ // assistive technology hears change. A region created with its words already
6965
+ // in it is often never announced.
6966
+ this.statusRegion = null;
6967
+ this.statusTimer = null;
6512
6968
  this.container = container;
6513
6969
  this.api = api;
6514
6970
  this.options = options;
6515
6971
  this.callbacks = callbacks;
6972
+ this.federationReturn = federationReturn;
6973
+ // A start this tab made on its own, read (and removed) here: with no
6974
+ // fragment back, the person came Back from the provider's page.
6975
+ const leftOnItsOwn = takeFederationAutoStart(this.api.accountId);
6976
+ this.federationMayAutoStart = federationReturn === null && !leftOnItsOwn;
6516
6977
  // Initialize centralized state
6517
6978
  this.verificationState = new VerificationState();
6518
6979
  // Initialize handlers with shared state
@@ -6525,6 +6986,20 @@ class IdentityRenderer {
6525
6986
  if (options.authContext) {
6526
6987
  this.verificationState.setAuthContext(options.authContext);
6527
6988
  }
6989
+ // A sign-in through the account's own identity provider opens no hub
6990
+ // session, so a popup whose result is lost can recover it safely only by
6991
+ // its reference: /sso then refuses every hub session that does not carry
6992
+ // it. The page offers the provider only when told it may, never by what
6993
+ // it infers from its window: while it holds its reference (given at
6994
+ // once, or arriving through the function it was given), or, given none
6995
+ // at all, when it says it completes in its own window (it hands no opener
6996
+ // a result, so no recovery stands in for it). A page told it has none, a
6997
+ // value that is no reference, and a page told nothing (a sign-in page
6998
+ // that predates the reference, served from a cache) offer none.
6999
+ const { signinRef, completesInWindow } = options;
7000
+ this.askReference = typeof signinRef === 'function' ? signinRef : null;
7001
+ this.verificationState.setSigninRef(isSigninReference(signinRef) ? signinRef : null);
7002
+ this.offeredWithoutReference = signinRef === undefined && completesInWindow === true;
6528
7003
  }
6529
7004
  /**
6530
7005
  * Seed the verification identity from the render options, deriving the
@@ -6589,6 +7064,9 @@ class IdentityRenderer {
6589
7064
  * Otherwise shows loading state while fetching config.
6590
7065
  */
6591
7066
  async start() {
7067
+ // Asked first, so a reference the page already holds or gets at once is
7068
+ // in place for the first step; the flow never waits on it.
7069
+ this.requestReference();
6592
7070
  // Try to get config quickly if it was preloaded
6593
7071
  // This races the config promise against a short timeout
6594
7072
  let config = null;
@@ -6617,6 +7095,7 @@ class IdentityRenderer {
6617
7095
  this.container.createLoading({
6618
7096
  backdropBlur: this.options.backdropBlur,
6619
7097
  }, () => this.handleClose());
7098
+ this.placeStatusRegion();
6620
7099
  try {
6621
7100
  if (!config) {
6622
7101
  // Config not ready yet - show loading and await it
@@ -6650,6 +7129,7 @@ class IdentityRenderer {
6650
7129
  showStartupError(error) {
6651
7130
  if (!this.container.isOpen()) {
6652
7131
  this.container.createLoading({ backdropBlur: this.options.backdropBlur }, () => this.handleClose());
7132
+ this.placeStatusRegion();
6653
7133
  }
6654
7134
  this.setState(this.viewStateForConfigError(error));
6655
7135
  }
@@ -6723,6 +7203,8 @@ class IdentityRenderer {
6723
7203
  close() {
6724
7204
  // Cancel all pending API requests first
6725
7205
  this.api.abort();
7206
+ // An answer to an open ask for the reference has no flow left to join.
7207
+ this.referenceAsks += 1;
6726
7208
  // A pending discoverable ceremony would otherwise hold the browser sheet
6727
7209
  // open against a dialog that no longer exists.
6728
7210
  this.discoverableVerifyAbort?.abort();
@@ -6735,6 +7217,16 @@ class IdentityRenderer {
6735
7217
  clearTimeout(this.morphTimer);
6736
7218
  this.morphTimer = null;
6737
7219
  }
7220
+ if (this.pageRestoreHandler) {
7221
+ window.removeEventListener('pageshow', this.pageRestoreHandler);
7222
+ this.pageRestoreHandler = null;
7223
+ }
7224
+ if (this.statusTimer !== null) {
7225
+ clearTimeout(this.statusTimer);
7226
+ this.statusTimer = null;
7227
+ }
7228
+ this.statusRegion?.remove();
7229
+ this.statusRegion = null;
6738
7230
  this.cleanupSparkLink();
6739
7231
  this.destroyCurrentView();
6740
7232
  this.container.destroy();
@@ -6751,6 +7243,159 @@ class IdentityRenderer {
6751
7243
  this.render();
6752
7244
  }
6753
7245
  async showInitialAuthStep() {
7246
+ const heldAtStart = this.verificationState.signinRef;
7247
+ if (this.startWithFederation())
7248
+ return;
7249
+ await this.showSignInStep();
7250
+ this.untouchedStep = this.currentView;
7251
+ // A reference that arrived while the step was being prepared joins it now.
7252
+ if (this.verificationState.signinRef !== heldAtStart)
7253
+ this.offerArrivedReference();
7254
+ }
7255
+ /**
7256
+ * The account's own identity provider as the flow's first step. A failed
7257
+ * round trip is said first. Otherwise the provider may start on its own
7258
+ * (startFederationAutomatically). Returns true when it took the step.
7259
+ */
7260
+ startWithFederation() {
7261
+ if (this.federationReturn === 'failed') {
7262
+ this.federationReturn = null;
7263
+ this.setState(this.federationFailedState());
7264
+ return true;
7265
+ }
7266
+ return this.startFederationAutomatically();
7267
+ }
7268
+ /**
7269
+ * Leave for the account's own identity provider without the person's
7270
+ * click, while this page offers it and it starts on its own
7271
+ * (federationStartsOnItsOwn). Returns true when it left.
7272
+ */
7273
+ startFederationAutomatically() {
7274
+ const federation = this.federation;
7275
+ if (!this.federationStartsOnItsOwn(federation))
7276
+ return false;
7277
+ this.leaveForFederation({ silent: federation.silent, automatic: true })
7278
+ .catch((error) => this.handleErrorWithRecovery(error, 'unknown'));
7279
+ return true;
7280
+ }
7281
+ /**
7282
+ * Whether the given account's own identity provider starts without the
7283
+ * person's click while this page may still leave on its own: when the
7284
+ * account asks for a silent attempt (`federation.silent`: the provider
7285
+ * answers without showing anything, and a refusal comes back as
7286
+ * `interaction_required`) or the caller asked for it (`method:
7287
+ * 'federation'`, interactive unless the account asks for the silent
7288
+ * attempt).
7289
+ */
7290
+ federationStartsOnItsOwn(federation) {
7291
+ return federation !== null
7292
+ && this.federationMayAutoStart
7293
+ && (federation.silent || this.options.method === 'federation');
7294
+ }
7295
+ /**
7296
+ * The account's own identity provider while a step for this identifier
7297
+ * lacks it only because the page's ask for the sign-in's reference is still
7298
+ * out: with the reference held, the provider would be on that step, so the
7299
+ * step holds every automatic advance a held reference would not have made.
7300
+ * Once the reference lands the provider joins the step, or starts on its
7301
+ * own from the untouched first step (offerArrivedReference); an ask that
7302
+ * finds none leaves the held step up for the person's tap.
7303
+ */
7304
+ federationAwaitingReference(recipient) {
7305
+ if (this.referenceAsk !== 'pending' || !this.offersFederationBeside(recipient))
7306
+ return null;
7307
+ return this.accountFederation;
7308
+ }
7309
+ /**
7310
+ * Ask the page for the sign-in's reference (VerifyOptions.signinRef as a
7311
+ * function) without waiting on the answer: the flow goes on, and the
7312
+ * answer joins it when it lands. A call that throws or rejects, and an
7313
+ * answer that is no reference, found none.
7314
+ */
7315
+ requestReference() {
7316
+ const ask = this.askReference;
7317
+ if (!ask)
7318
+ return;
7319
+ const asked = ++this.referenceAsks;
7320
+ this.referenceAsk = 'pending';
7321
+ void new Promise((resolve) => { resolve(ask()); })
7322
+ .catch(() => null)
7323
+ .then((reference) => {
7324
+ if (asked !== this.referenceAsks)
7325
+ return;
7326
+ if (isSigninReference(reference)) {
7327
+ this.referenceArrived(reference);
7328
+ }
7329
+ else {
7330
+ this.referenceUnavailable();
7331
+ }
7332
+ });
7333
+ }
7334
+ /** The reference arrived: every completing call from now on carries it, and the step offers the provider. */
7335
+ referenceArrived(reference) {
7336
+ this.referenceAsk = null;
7337
+ this.verificationState.setSigninRef(reference);
7338
+ this.offerArrivedReference();
7339
+ }
7340
+ /**
7341
+ * The ask found no reference for now. An account with other ways in
7342
+ * simply keeps them; a person waiting on the provider as the only way in
7343
+ * is told to try again.
7344
+ */
7345
+ referenceUnavailable() {
7346
+ this.referenceAsk = 'unavailable';
7347
+ if (this.viewState.view === 'awaiting-reference')
7348
+ void this.showMethodSelect();
7349
+ }
7350
+ /** The person's Try Again: ask again, and show the sign-in step meanwhile. */
7351
+ retryReference() {
7352
+ this.requestReference();
7353
+ void this.showSignInStep();
7354
+ }
7355
+ /**
7356
+ * Offer the account's own identity provider on the step that offers it,
7357
+ * now that the page holds its reference. On the sign-in step as it first
7358
+ * showed, still untouched, the provider starts on its own as it would have
7359
+ * with the reference held from the start; otherwise its button joins the
7360
+ * step in place, keeping what the person typed and their focus. A person
7361
+ * who has moved past that step sees nothing change, and the step offers
7362
+ * the provider whenever it shows again.
7363
+ */
7364
+ offerArrivedReference() {
7365
+ const state = this.viewState;
7366
+ const onOfferingStep = state.view === 'awaiting-reference'
7367
+ || state.view === 'identity-input'
7368
+ || (state.view === 'method-select' && this.offersFederationBeside(state.email));
7369
+ if (!onOfferingStep)
7370
+ return;
7371
+ const untouched = this.untouchedStep !== null && this.currentView === this.untouchedStep;
7372
+ if (untouched && this.startFederationAutomatically())
7373
+ return;
7374
+ if (state.view === 'awaiting-reference') {
7375
+ void this.showMethodSelect();
7376
+ return;
7377
+ }
7378
+ const leading = this.leadingFederationMethod();
7379
+ if (!leading)
7380
+ return;
7381
+ const view = this.currentView;
7382
+ if (view instanceof IdentityInputView) {
7383
+ view.offerLeadingMethod(leading);
7384
+ }
7385
+ else if (view instanceof MethodSelectView
7386
+ && state.view === 'method-select'
7387
+ && !state.methods.some((method) => method.type === 'federation')) {
7388
+ view.offerLeadingMethod(leading.method);
7389
+ this.verificationState.setViewState({ ...state, methods: [leading.method, ...state.methods] });
7390
+ }
7391
+ }
7392
+ /**
7393
+ * The sign-in's own first step: the method list when no identifier is
7394
+ * asked for (or one is already known), the discoverable passkey ceremony for
7395
+ * a returning browser, else the identifier field (which leads with the
7396
+ * account's own identity provider when it offers one).
7397
+ */
7398
+ async showSignInStep() {
6754
7399
  if (this.recipient || this.getAllowedIdentityTypes().length === 0) {
6755
7400
  await this.showMethodSelect();
6756
7401
  return;
@@ -6758,8 +7403,12 @@ class IdentityRenderer {
6758
7403
  // Returning browser on the Identity origin (passkey-hint cookie present):
6759
7404
  // auto-start the discoverable ceremony instead of asking for an identifier
6760
7405
  // — 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()) {
7406
+ // form, which keeps a "Sign in with a passkey" way back in. A provider
7407
+ // that starts on its own once the pending reference lands goes first, as
7408
+ // with the reference held (startWithFederation), so the identifier form
7409
+ // waits for it instead.
7410
+ if (this.canDiscoverableVerify()
7411
+ && !this.federationStartsOnItsOwn(this.federationAwaitingReference(this.recipient))) {
6763
7412
  void this.launchDiscoverableVerify();
6764
7413
  return;
6765
7414
  }
@@ -6821,6 +7470,7 @@ class IdentityRenderer {
6821
7470
  this.container.setMinimalChrome(minimalChromeViews.includes(this.viewState.view));
6822
7471
  const view = this.createViewForState(this.viewState);
6823
7472
  this.currentView = view;
7473
+ this.announce(view.announcement ?? '');
6824
7474
  const rendered = view.render();
6825
7475
  // Each step enters with a calm fade + rise (see .sv-step-enter). The brand
6826
7476
  // lockup and footer live outside `body`, so only the flow content moves.
@@ -6829,11 +7479,12 @@ class IdentityRenderer {
6829
7479
  // reshaping between steps (falls back to an instant swap in jsdom).
6830
7480
  this.morphSwap(body, rendered);
6831
7481
  // 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
7482
+ // `window.__sparkvaultProgress`) off the view: a transient `loading` view,
7483
+ // or one awaiting the sign-in's reference, means a network step is in
7484
+ // flight, so keep the bar trickling; any real
6834
7485
  // view completes it. The controller is idempotent, so overlapping calls are
6835
7486
  // safe, and it is a no-op when the hook is absent (any non-popup host).
6836
- if (this.viewState.view === 'loading') {
7487
+ if (this.viewState.view === 'loading' || this.viewState.view === 'awaiting-reference') {
6837
7488
  progressStart();
6838
7489
  }
6839
7490
  else {
@@ -6852,6 +7503,41 @@ class IdentityRenderer {
6852
7503
  this.focusTimeoutId = setTimeout(() => focusable.focus(), 50);
6853
7504
  }
6854
7505
  }
7506
+ /** Place the empty live region beside the flow content, once per container. */
7507
+ placeStatusRegion() {
7508
+ const body = this.container.getBody();
7509
+ if (!body || this.statusRegion?.isConnected)
7510
+ return;
7511
+ const region = document.createElement('div');
7512
+ region.className = 'sv-sr-only';
7513
+ region.setAttribute('role', 'status');
7514
+ region.setAttribute('aria-live', 'polite');
7515
+ region.setAttribute('aria-atomic', 'true');
7516
+ body.insertAdjacentElement('beforebegin', region);
7517
+ this.statusRegion = region;
7518
+ }
7519
+ /**
7520
+ * Put `words` in the live region, a moment after the view that says them
7521
+ * is in place, so they never land in the same change as the region or the
7522
+ * view that holds them; empty words clear it at once.
7523
+ */
7524
+ announce(words) {
7525
+ if (this.statusTimer !== null) {
7526
+ clearTimeout(this.statusTimer);
7527
+ this.statusTimer = null;
7528
+ }
7529
+ const region = this.statusRegion;
7530
+ if (!region)
7531
+ return;
7532
+ if (!words) {
7533
+ region.textContent = '';
7534
+ return;
7535
+ }
7536
+ this.statusTimer = setTimeout(() => {
7537
+ this.statusTimer = null;
7538
+ region.textContent = words;
7539
+ }, STATUS_ANNOUNCE_DELAY_MS);
7540
+ }
6855
7541
  destroyCurrentView() {
6856
7542
  if (this.currentView?.destroy) {
6857
7543
  this.currentView.destroy();
@@ -6910,6 +7596,7 @@ class IdentityRenderer {
6910
7596
  createViewForState(state) {
6911
7597
  switch (state.view) {
6912
7598
  case 'loading':
7599
+ case 'awaiting-reference':
6913
7600
  return new LoadingView({ message: 'Loading...' });
6914
7601
  case 'identity-input':
6915
7602
  return new IdentityInputView({
@@ -6922,6 +7609,10 @@ class IdentityRenderer {
6922
7609
  onPasskey: this.canDiscoverableVerify()
6923
7610
  ? () => { void this.launchDiscoverableVerify(); }
6924
7611
  : undefined,
7612
+ leadingMethod: this.leadingFederationMethod(),
7613
+ // A person who started typing keeps the step: a reference that
7614
+ // arrives later adds the provider's button, never leaves for it.
7615
+ onType: () => { this.untouchedStep = null; },
6925
7616
  });
6926
7617
  case 'method-select':
6927
7618
  return new MethodSelectView({
@@ -7024,11 +7715,20 @@ class IdentityRenderer {
7024
7715
  });
7025
7716
  case 'oauth-pending':
7026
7717
  return new LoadingView({ message: `Connecting to ${state.provider}...` });
7718
+ case 'federation-checking':
7719
+ return new LoadingView({ message: `Checking your ${state.displayName} sign-in…`, announce: true });
7027
7720
  case 'error':
7028
7721
  return new ErrorView({
7029
7722
  message: state.message,
7030
7723
  code: state.code,
7031
- onRetry: () => this.showIdentityInput(),
7724
+ // A failed provider sign-in tries again from the sign-in's first
7725
+ // step, where the provider leads; nothing leaves on its own again.
7726
+ // A reference the page could not get is asked for again.
7727
+ onRetry: state.code === FEDERATION_FAILED
7728
+ ? () => { void this.showSignInStep(); }
7729
+ : state.code === SIGNIN_REFERENCE_UNAVAILABLE_CODE
7730
+ ? () => this.retryReference()
7731
+ : () => this.showIdentityInput(),
7032
7732
  onClose: () => this.handleClose(),
7033
7733
  });
7034
7734
  case 'service-unavailable':
@@ -7077,7 +7777,15 @@ class IdentityRenderer {
7077
7777
  });
7078
7778
  return;
7079
7779
  }
7080
- // Enrich method IDs with metadata from static registry
7780
+ // Read before the passkey check below, so a reference that lands while
7781
+ // the check runs finds this list held, as one landing just after it
7782
+ // would: the provider, read after the check, then leads the list, and
7783
+ // starts on its own from the untouched first step (showInitialAuthStep).
7784
+ const federationAwaited = this.federationAwaitingReference(this.recipient);
7785
+ // Enrich method IDs with metadata from static registry. The account's own
7786
+ // identity provider is set apart: it needs no identifier, and leads every
7787
+ // list that offers it (below), read once the rest of the list is known so
7788
+ // a reference that arrived meanwhile counts.
7081
7789
  let methods = enrichMethods(methodIds);
7082
7790
  if (this.recipient) {
7083
7791
  // Filter by identifier type. Passkeys are SVID-scoped, so they remain
@@ -7108,6 +7816,9 @@ class IdentityRenderer {
7108
7816
  if (this.verificationState.passkey.isFallbackMode) {
7109
7817
  methods = methods.filter((m) => m.type !== 'passkey');
7110
7818
  }
7819
+ if (this.offersFederationBeside(this.recipient)) {
7820
+ methods = [...enrichMethods(['federation'], this.federation), ...methods];
7821
+ }
7111
7822
  if (methods.length === 0) {
7112
7823
  this.setState(this.noMethodState());
7113
7824
  return;
@@ -7117,8 +7828,11 @@ class IdentityRenderer {
7117
7828
  // pick a method — it is the safest, fastest option. The back arrow on
7118
7829
  // the passkey view re-enters this method with autoRoute=false so the
7119
7830
  // user lands on the full picker (passkey still listed) and can pick
7120
- // a code or SparkLink instead.
7831
+ // a code or SparkLink instead. A provider that starts on its own once the
7832
+ // pending reference lands goes first, as with the reference held
7833
+ // (startWithFederation), so the list waits for it instead.
7121
7834
  if (autoRoute
7835
+ && !this.federationStartsOnItsOwn(federationAwaited)
7122
7836
  && this.verificationState.passkey.hasPasskey === true
7123
7837
  && !this.verificationState.passkey.isFallbackMode
7124
7838
  && methods.some((m) => m.type === 'passkey')) {
@@ -7138,11 +7852,22 @@ class IdentityRenderer {
7138
7852
  // link, with no consent, and again on every reload;
7139
7853
  // - a text or call to a phone number the flow supplied: the person never
7140
7854
  // typed it under the SMS and voice consent the identifier field carries,
7141
- // so the picker carries that consent and the tap gives it.
7855
+ // so the picker carries that consent and the tap gives it;
7856
+ // - the account's own identity provider, once the page may no longer leave
7857
+ // for it on its own (it already did, or a round trip came back): Back
7858
+ // from the provider must never be forwarded to it again;
7859
+ // - a list the provider is missing from only while the page's ask for the
7860
+ // sign-in's reference is out (federationAwaitingReference): with the
7861
+ // reference held the provider leads it, so it is never one method.
7142
7862
  // (Passkey auto-route above still applies — a biometric prompt costs
7143
7863
  // nothing and can be dismissed.)
7144
7864
  const sendsToSuppliedPhone = this.identityPrefilled && methods[0].identityType === 'phone';
7145
- if (methods.length === 1 && !this.isIdentityFixed() && !sendsToSuppliedPhone) {
7865
+ const heldFederation = methods[0].type === 'federation' && !this.federationMayAutoStart;
7866
+ if (methods.length === 1
7867
+ && !this.isIdentityFixed()
7868
+ && !sendsToSuppliedPhone
7869
+ && !heldFederation
7870
+ && federationAwaited === null) {
7146
7871
  this.handleMethodSelect(methods[0]);
7147
7872
  return;
7148
7873
  }
@@ -7157,8 +7882,17 @@ class IdentityRenderer {
7157
7882
  * its sender held to a passkey admits the passkey alone, so a person the
7158
7883
  * check found holding none is told the request needs a passkey already
7159
7884
  * 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.
7885
+ * level they can clear: no retry here changes that. An account whose
7886
+ * remaining way in is its own identity provider, which this page does not
7887
+ * offer now (see `federationOffered`), depends on why:
7888
+ * - the page can never hold a reference (an SDK that predates it opened
7889
+ * the page): the site must update its sign-in, and no retry here changes
7890
+ * that;
7891
+ * - the page's ask for its reference is still out: the step waits for it;
7892
+ * - the ask found none for now: the person is told to try again, which
7893
+ * asks again.
7894
+ * Any other verification with nothing to offer is a configuration fault,
7895
+ * shown as one.
7162
7896
  */
7163
7897
  noMethodState() {
7164
7898
  if (this.verificationState.passkeyRequired && this.verificationState.passkey.hasPasskey === false) {
@@ -7168,6 +7902,20 @@ class IdentityRenderer {
7168
7902
  message: strongerVerificationMessage('request', this.sdkConfig?.branding?.companyName),
7169
7903
  };
7170
7904
  }
7905
+ if (this.accountFederation && !this.federationOffered) {
7906
+ if (!this.askReference) {
7907
+ const name = this.sdkConfig?.federation?.display_name?.trim();
7908
+ return {
7909
+ view: 'error',
7910
+ code: FEDERATION_UNAVAILABLE_CODE,
7911
+ message: `This site needs to update its sign-in to use ${name || 'your organization\'s sign-in'}.`,
7912
+ };
7913
+ }
7914
+ if (this.referenceAsk === 'unavailable') {
7915
+ return { view: 'error', code: SIGNIN_REFERENCE_UNAVAILABLE_CODE, message: 'We couldn\'t start sign-in. Try again.' };
7916
+ }
7917
+ return { view: 'awaiting-reference' };
7918
+ }
7171
7919
  return { view: 'error', message: 'No authentication methods available', code: 'no_methods' };
7172
7920
  }
7173
7921
  handleIdentitySubmit(result) {
@@ -7289,6 +8037,12 @@ class IdentityRenderer {
7289
8037
  }
7290
8038
  break;
7291
8039
  }
8040
+ case 'federation': {
8041
+ // A click is always interactive; a start with no click (the only
8042
+ // method, auto-selected) is the page leaving on its own.
8043
+ await this.leaveForFederation({ silent: false, automatic: !userInitiated });
8044
+ break;
8045
+ }
7292
8046
  default:
7293
8047
  this.setState({
7294
8048
  view: 'error',
@@ -7520,13 +8274,15 @@ class IdentityRenderer {
7520
8274
  passkeyFallbackMethodsAvailable() {
7521
8275
  if (!this.sdkConfig)
7522
8276
  return false;
7523
- const methods = enrichMethods(this.verificationState.methodIds);
8277
+ const methods = enrichMethods(this.verificationState.methodIds, this.federation);
7524
8278
  if (!this.recipient) {
7525
- return methods.some((m) => m.type === 'social');
8279
+ return methods.some((m) => m.type === 'social' || m.type === 'federation');
7526
8280
  }
7527
8281
  return methods.some((m) => {
7528
8282
  if (m.type === 'passkey')
7529
8283
  return false;
8284
+ if (m.type === 'federation')
8285
+ return this.offersFederationBeside(this.recipient);
7530
8286
  if (this.identityType === 'phone')
7531
8287
  return m.identityType === 'phone';
7532
8288
  return m.identityType === 'email';
@@ -7555,9 +8311,104 @@ class IdentityRenderer {
7555
8311
  this.setState({ view: 'oauth-pending', provider });
7556
8312
  const { state } = await this.api.drawAuthorizationValues();
7557
8313
  sessionStorage.setItem('sv_oauth_state', state);
7558
- const authUrl = this.api.getSocialAuthUrl(provider, currentPageReturnUrl(), state, this.verificationState.authContext);
8314
+ const authUrl = this.api.getSocialAuthUrl(provider, currentPageReturnUrl(), state, this.verificationState.authContext, this.verificationState.signinRef);
7559
8315
  window.location.href = authUrl;
7560
8316
  }
8317
+ /**
8318
+ * The account's own identity provider, while this verification offers it:
8319
+ * this page offers it now (federationOffered), `/config` describes it, and
8320
+ * the verification's methods list it. A verify session's methods never do,
8321
+ * for such a sign-in cannot complete one.
8322
+ */
8323
+ get federation() {
8324
+ return this.federationOffered ? this.accountFederation : null;
8325
+ }
8326
+ /**
8327
+ * Whether this page offers the account's own identity provider now (see
8328
+ * VerifyOptions.signinRef): while it holds its sign-in's reference, or
8329
+ * when it completes in its own window.
8330
+ */
8331
+ get federationOffered() {
8332
+ return this.offeredWithoutReference || this.verificationState.signinRef !== null;
8333
+ }
8334
+ /** The account's own identity provider while `/config` describes it and the verification's methods list it. */
8335
+ get accountFederation() {
8336
+ const federation = this.sdkConfig?.federation;
8337
+ const methodIds = this.verificationState.methodIds;
8338
+ return federation && Array.isArray(methodIds) && methodIds.includes('federation') ? federation : null;
8339
+ }
8340
+ /**
8341
+ * Whether a list of methods offers the account's own identity provider
8342
+ * beside the identifier it is for. It needs no identifier, so the first
8343
+ * step offers it (above the identifier field, or in a list with none), and
8344
+ * so does a list for an identifier the flow supplied, whose person never saw
8345
+ * that step. An identifier the person typed came from the identifier
8346
+ * field, which already offered it.
8347
+ */
8348
+ offersFederationBeside(recipient) {
8349
+ return !recipient || this.identityPrefilled;
8350
+ }
8351
+ /** The identifier field's leading method: the account's own identity provider, when offered. */
8352
+ leadingFederationMethod() {
8353
+ const [method] = enrichMethods(['federation'], this.federation);
8354
+ if (!method)
8355
+ return undefined;
8356
+ return { method, onSelect: () => { void this.handleMethodSelect(method, true); } };
8357
+ }
8358
+ /**
8359
+ * Leave for the account's own identity provider, the way a social sign-in
8360
+ * leaves (handleSocialLogin): the round trip returns to this page, query
8361
+ * intact, the state stored here is what its `#token` (or its refusal's
8362
+ * fragment) must answer, and the start carries the sign-in's reference
8363
+ * when the page holds one. A silent attempt shows a status the whole time
8364
+ * it runs. A start without the person's click (`automatic`) is recorded, so
8365
+ * a person who comes Back from the provider's page is not sent on again.
8366
+ */
8367
+ async leaveForFederation({ silent, automatic }) {
8368
+ const federation = this.federation;
8369
+ if (!federation)
8370
+ return;
8371
+ if (automatic)
8372
+ this.federationMayAutoStart = false;
8373
+ this.setState(silent
8374
+ ? { view: 'federation-checking', displayName: federation.display_name }
8375
+ : { view: 'oauth-pending', provider: federation.display_name });
8376
+ const { state } = await this.api.drawAuthorizationValues();
8377
+ sessionStorage.setItem('sv_oauth_state', state);
8378
+ if (automatic)
8379
+ markFederationAutoStart(this.api.accountId);
8380
+ this.watchForPageRestore();
8381
+ window.location.href = this.api.getFederationAuthUrl(currentPageReturnUrl(), state, this.verificationState.authContext, { silent, signinRef: this.verificationState.signinRef });
8382
+ }
8383
+ /**
8384
+ * A browser that restores this page from its back/forward cache, as the
8385
+ * person comes Back from the provider, runs nothing again, so the page would
8386
+ * keep the wait it left on. Show the sign-in's first step instead, with the
8387
+ * automatic start spent.
8388
+ */
8389
+ watchForPageRestore() {
8390
+ if (this.pageRestoreHandler)
8391
+ return;
8392
+ this.pageRestoreHandler = (event) => {
8393
+ if (!event.persisted)
8394
+ return;
8395
+ takeFederationAutoStart(this.api.accountId);
8396
+ this.federationMayAutoStart = false;
8397
+ void this.showSignInStep();
8398
+ };
8399
+ window.addEventListener('pageshow', this.pageRestoreHandler);
8400
+ }
8401
+ /** The failure of a sign-in through the account's own identity provider, in fixed words, never the provider's. */
8402
+ federationFailedState() {
8403
+ const name = this.sdkConfig?.federation?.display_name;
8404
+ return {
8405
+ view: 'error',
8406
+ code: FEDERATION_FAILED,
8407
+ message: name
8408
+ ? `We couldn't sign you in with ${name}. Please try again.`
8409
+ : 'We couldn\'t sign you in through your organization. Please try again.',
8410
+ };
8411
+ }
7561
8412
  normalizeError(error) {
7562
8413
  if (error instanceof IdentityApiError) {
7563
8414
  return new SparkVaultError(error.message, error.code);
@@ -10110,7 +10961,13 @@ function createCloseButton(className, onClick) {
10110
10961
  * The popup must open synchronously in the gesture or the browser blocks it as
10111
10962
  * programmatic. `verify()` reaches `start()` through microtask-only awaits (the
10112
10963
  * redirect-result check does no I/O; the preloaded config resolves from cache),
10113
- * so transient activation survives.
10964
+ * so transient activation survives. Each popup's reference (app-sdk
10965
+ * SIGNIN_REFERENCE) is therefore drawn only after that popup opens, by the
10966
+ * owner (`drawSigninReference`). Once the owner has decided it (its pending
10967
+ * marker holds the drawn reference, or the popup has none), the launcher
10968
+ * posts it to the popup in answer to each "ready" ping: the reference, or
10969
+ * null. A popup told null may ask again (`SIGNIN_REFERENCE.retryMessage`),
10970
+ * and the owner then draws afresh for it.
10114
10971
  *
10115
10972
  * It is one dialog. The happy path is clean: logo, a subtle animation, and
10116
10973
  * "continue in the secure window". A single warning appears under the logo only
@@ -10180,6 +11037,8 @@ class DialogLauncher {
10180
11037
  this.modal = null;
10181
11038
  this.alertEl = null;
10182
11039
  this.popupWindow = null;
11040
+ // The current popup has pinged that its page loaded.
11041
+ this.popupReady = false;
10183
11042
  this.openTimer = null;
10184
11043
  this.settled = false;
10185
11044
  // Bumped on every open so a superseded popup's late result or ready ping
@@ -10201,11 +11060,22 @@ class DialogLauncher {
10201
11060
  this.modal = null;
10202
11061
  this.alertEl = null;
10203
11062
  }
11063
+ /**
11064
+ * The owner decided the current popup's reference: tell the popup if it
11065
+ * already pinged. A popup that loads later is told in answer to its ping.
11066
+ */
11067
+ signinReferenceDecided() {
11068
+ if (this.popupReady)
11069
+ this.postSigninReference();
11070
+ }
10204
11071
  openPopup() {
10205
11072
  const generation = ++this.generation;
11073
+ this.popupReady = false;
10206
11074
  this.popupLauncher
10207
11075
  .openPopup({
10208
- url: buildSigninUrl(this.config, this.options),
11076
+ // The popup opens before its reference can be drawn, so its URL says
11077
+ // this opener posts it.
11078
+ url: buildSigninUrl(this.config, this.options, { kind: 'popup' }),
10209
11079
  windowName: 'sparkvault-login',
10210
11080
  resultType: LOGIN_RESULT_TYPE,
10211
11081
  readyType: LOGIN_READY_TYPE,
@@ -10216,15 +11086,59 @@ class DialogLauncher {
10216
11086
  this.popupWindow = popup;
10217
11087
  this.scheduleOpenWarning();
10218
11088
  },
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(); },
11089
+ // The page loaded and pinged back: the open succeeded, so cancel the
11090
+ // open-failure warning no matter how long the person now takes. The
11091
+ // page pings on every load, a provider's round trip included, and
11092
+ // each load is told the popup's reference afresh.
11093
+ onReady: () => {
11094
+ if (generation !== this.generation)
11095
+ return;
11096
+ this.clearOpenTimer();
11097
+ this.popupReady = true;
11098
+ this.postSigninReference();
11099
+ },
11100
+ requestType: SIGNIN_REFERENCE.retryMessage,
11101
+ onRequest: () => {
11102
+ if (generation === this.generation)
11103
+ this.answerSigninReferenceRetry();
11104
+ },
10223
11105
  })
10224
11106
  .then((message) => { if (generation === this.generation)
10225
11107
  this.handleResult(message); })
10226
11108
  .catch((error) => { if (generation === this.generation)
10227
11109
  this.handleError(error); });
11110
+ // Drawn only now, for this popup alone: it opens inside the click, which
11111
+ // no draw can finish within, and no earlier popup's reference is reused.
11112
+ this.callbacks.drawSigninReference();
11113
+ }
11114
+ /**
11115
+ * The current popup asked again for its reference. A popup that has none
11116
+ * gets a fresh draw (the owner re-arms the marker, then decides), one that
11117
+ * holds a reference is told it again, and one whose draw is still out is
11118
+ * told once that draw is decided.
11119
+ */
11120
+ answerSigninReferenceRetry() {
11121
+ const reference = this.callbacks.signinReference();
11122
+ if (reference === null) {
11123
+ this.callbacks.drawSigninReference();
11124
+ return;
11125
+ }
11126
+ if (reference !== undefined)
11127
+ this.postSigninReference();
11128
+ }
11129
+ /**
11130
+ * Post the current popup's reference, once the owner decided it, to this
11131
+ * launcher's own popup: the reference the marker holds, or null for a
11132
+ * popup with none, so the page knows at once that it has none for now
11133
+ * instead of waiting it out. Only a document there on the trusted Identity
11134
+ * origin receives it: the browser drops it while the popup shows any other
11135
+ * origin (a provider's page).
11136
+ */
11137
+ postSigninReference() {
11138
+ const reference = this.callbacks.signinReference();
11139
+ if (reference === undefined || !this.popupWindow)
11140
+ return;
11141
+ this.popupWindow.postMessage({ type: SIGNIN_REFERENCE.message, [SIGNIN_REFERENCE.param]: reference }, this.trustedOrigin);
10228
11142
  }
10229
11143
  handleResult(message) {
10230
11144
  if (this.settled)
@@ -10337,9 +11251,8 @@ class DialogLauncher {
10337
11251
  this.openTimer = null;
10338
11252
  }
10339
11253
  }
10340
- /** "Try again": close any current popup and reopen a fresh one. */
11254
+ /** "Try again": close any current popup and open a fresh one, as the first opened. */
10341
11255
  retry() {
10342
- this.callbacks.onPopupReopened?.();
10343
11256
  this.hideAlert();
10344
11257
  this.closePopup();
10345
11258
  this.openPopup();
@@ -10602,35 +11515,28 @@ function attachClickHandler(selector, onClick) {
10602
11515
  }
10603
11516
 
10604
11517
  /**
10605
- * Identity Module
10606
- *
10607
- * Passwordless sign-in through the first-party SparkVault popup.
10608
- * Supports passkey, OTP, SparkLink, and social authentication.
11518
+ * The pending sign-in marker: what lets a site whose popup result was lost (a
11519
+ * mobile browser discards the backgrounded opener tab, which clears the
11520
+ * message listener but not sessionStorage) recover it on its next load, for
11521
+ * at most SIGNIN_RECOVERY.pendingTtlMs.
10609
11522
  *
10610
- * @example Programmatic
10611
- * const result = await sv.products.identity.signIn();
10612
- *
10613
- * @example Attached to clicks
10614
- * sv.products.identity.attach('.login-btn');
11523
+ * `sv_signin_pending` holds JSON `{ at, hint, ref }`:
11524
+ * - `at`: when the current popup opened, on this browser's clock; the
11525
+ * marker's TTL.
11526
+ * - `hint`: the email or phone the sign-in started with, or null when the
11527
+ * flow collects the identifier itself; the recovery bounce's `login_hint`.
11528
+ * - `ref`: the current popup's reference (app-sdk SIGNIN_REFERENCE), present
11529
+ * once drawn and written; the recovery bounce names it, and `/sso` then
11530
+ * mints only when the hub session it would mint from carries it. A marker
11531
+ * without one bounces with no reference.
10615
11532
  */
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
11533
  const PENDING_KEY = 'sv_signin_pending';
10626
- const PENDING_TTL_MS = 10 * 60 * 1000;
10627
11534
  /**
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.
11535
+ * Read and parse the pending marker. Anything unreadable yields null: a value
11536
+ * that is not a JSON object, an `at` that is no finite number, or a `ref`
11537
+ * that is present but no sign-in reference. A recovery that cannot name the
11538
+ * reference its marker records could mint any hub session in this browser, so
11539
+ * such a marker recovers nothing.
10634
11540
  */
10635
11541
  function readPendingMarker() {
10636
11542
  let raw = null;
@@ -10643,37 +11549,177 @@ function readPendingMarker() {
10643
11549
  if (!raw) {
10644
11550
  return null;
10645
11551
  }
10646
- let at = NaN;
10647
- let hint = null;
11552
+ let parsed;
10648
11553
  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
- }
11554
+ parsed = JSON.parse(raw);
10663
11555
  }
10664
11556
  catch {
10665
- at = Number(raw);
11557
+ return null;
11558
+ }
11559
+ if (typeof parsed !== 'object' || parsed === null) {
11560
+ return null;
11561
+ }
11562
+ const marker = parsed;
11563
+ if (typeof marker.at !== 'number' || !Number.isFinite(marker.at)) {
11564
+ return null;
10666
11565
  }
10667
- return Number.isFinite(at) ? { at, hint } : null;
11566
+ const { ref } = marker;
11567
+ if (ref !== undefined && !isSigninReference(ref)) {
11568
+ return null;
11569
+ }
11570
+ return {
11571
+ at: marker.at,
11572
+ hint: typeof marker.hint === 'string' && marker.hint ? marker.hint : null,
11573
+ ref: typeof ref === 'string' ? ref : null,
11574
+ };
10668
11575
  }
10669
- /** True while a marker is within the self-heal TTL. */
11576
+ /** True while a marker is within the recovery TTL. */
10670
11577
  function isFreshPendingMarker(marker) {
10671
- return marker !== null && Date.now() - marker.at < PENDING_TTL_MS;
11578
+ return marker !== null && Date.now() - marker.at < SIGNIN_RECOVERY.pendingTtlMs;
10672
11579
  }
10673
- /** True when the pending marker is present and still within its TTL. */
10674
- function hasFreshPendingMarker() {
10675
- return isFreshPendingMarker(readPendingMarker());
11580
+ /** Remove the pending marker. */
11581
+ function removePendingMarker() {
11582
+ try {
11583
+ sessionStorage.removeItem(PENDING_KEY);
11584
+ }
11585
+ catch {
11586
+ // Nothing to clear.
11587
+ }
11588
+ }
11589
+ /**
11590
+ * The reference a draw yields within SIGNIN_REFERENCE.drawDeadlineMs, else
11591
+ * null: a draw that fails or misses the deadline leaves the sign-in page
11592
+ * without one, and a draw that lands later is discarded. Never rejects.
11593
+ */
11594
+ function signinReferenceInTime(draw) {
11595
+ return new Promise((settle) => {
11596
+ const deadline = setTimeout(() => settle(null), SIGNIN_REFERENCE.drawDeadlineMs);
11597
+ draw.then((reference) => { clearTimeout(deadline); settle(reference); }, () => { clearTimeout(deadline); settle(null); });
11598
+ });
11599
+ }
11600
+ /**
11601
+ * One popup sign-in's marker, from its first popup's open until the sign-in
11602
+ * settles. Every popup it opens, the first and each "Try again", is an open
11603
+ * of its own: it re-arms the marker holding no reference and draws its own
11604
+ * reference (signinReferenceInTime), which joins the marker once drawn. A
11605
+ * popup that has none asks again, and the same popup is then opened afresh,
11606
+ * with a draw of its own. An earlier open's reference is never reused, and
11607
+ * its draw, should it land later, is discarded. `reference` is what the
11608
+ * current popup is told, and the marker always holds it: a popup can never
11609
+ * hold a reference the marker does not.
11610
+ */
11611
+ class PendingSignIn {
11612
+ constructor(hint) {
11613
+ this.hint = hint;
11614
+ this.at = 0;
11615
+ this.live = true;
11616
+ // Counts the opens and the ends of their popups, so a draw that lands after
11617
+ // its popup ended or was replaced is recognised and dropped.
11618
+ this.opens = 0;
11619
+ this.current = undefined;
11620
+ this.decided = Promise.resolve();
11621
+ }
11622
+ /**
11623
+ * The current popup's reference: undefined while its draw is out, null
11624
+ * when it has none (its draw failed or missed the deadline, the marker
11625
+ * write failed, or the popup already ended), else the reference the marker
11626
+ * holds.
11627
+ */
11628
+ get reference() {
11629
+ return this.current;
11630
+ }
11631
+ /**
11632
+ * A popup opened, or the current one asked again for the reference it
11633
+ * lacks: arm the marker holding no reference, and draw this open's own.
11634
+ * Resolves true once this open's reference is decided while its popup is
11635
+ * still the current one of a live sign-in, so that popup may be told; false
11636
+ * when the popup ended or was replaced, or the sign-in ended. Never
11637
+ * rejects.
11638
+ */
11639
+ open(draw) {
11640
+ if (!this.live)
11641
+ return Promise.resolve(false);
11642
+ const open = ++this.opens;
11643
+ this.at = Date.now();
11644
+ this.current = undefined;
11645
+ // A marker this open cannot write must not keep an earlier open's reference.
11646
+ if (!this.write(null))
11647
+ removePendingMarker();
11648
+ const decided = signinReferenceInTime(draw()).then((reference) => {
11649
+ if (!this.live || open !== this.opens)
11650
+ return false;
11651
+ this.current = reference !== null && this.write(reference) ? reference : null;
11652
+ return true;
11653
+ });
11654
+ this.decided = decided;
11655
+ return decided;
11656
+ }
11657
+ /**
11658
+ * The opener saw the popup end with no result, so there is no lost result
11659
+ * to recover: without this, a reload while the retry alert is up would
11660
+ * bounce for nothing. The ended popup is told nothing more, and its draw,
11661
+ * should it land, is dropped.
11662
+ */
11663
+ retire() {
11664
+ if (!this.live)
11665
+ return;
11666
+ this.opens += 1;
11667
+ this.current = null;
11668
+ removePendingMarker();
11669
+ }
11670
+ /** The sign-in settled, or another replaced it: retire the marker, and nothing this sign-in does later touches it. */
11671
+ end() {
11672
+ this.retire();
11673
+ this.live = false;
11674
+ }
11675
+ /**
11676
+ * The current popup's reference, waiting at most `waitMs` for an open still
11677
+ * drawing it: the reference the marker holds, else null (the popup has
11678
+ * none, or its draw has not landed in time). Never rejects.
11679
+ */
11680
+ referenceWithin(waitMs) {
11681
+ if (this.current !== undefined)
11682
+ return Promise.resolve(this.current);
11683
+ return new Promise((settle) => {
11684
+ const deadline = setTimeout(() => settle(this.current ?? null), waitMs);
11685
+ void this.decided.then(() => {
11686
+ clearTimeout(deadline);
11687
+ settle(this.current ?? null);
11688
+ });
11689
+ });
11690
+ }
11691
+ /** Write the marker; a write that fails leaves the stored marker as it was. */
11692
+ write(reference) {
11693
+ const marker = { at: this.at, hint: this.hint, ...(reference ? { ref: reference } : {}) };
11694
+ try {
11695
+ sessionStorage.setItem(PENDING_KEY, JSON.stringify(marker));
11696
+ }
11697
+ catch {
11698
+ return false;
11699
+ }
11700
+ return true;
11701
+ }
10676
11702
  }
11703
+
11704
+ /**
11705
+ * Identity Module
11706
+ *
11707
+ * Passwordless sign-in through the first-party SparkVault popup.
11708
+ * Supports passkey, OTP, SparkLink, social authentication, and the account's
11709
+ * own identity provider.
11710
+ *
11711
+ * @example Programmatic
11712
+ * const result = await sv.products.identity.signIn();
11713
+ *
11714
+ * @example Attached to clicks
11715
+ * sv.products.identity.attach('.login-btn');
11716
+ */
11717
+ const PORTAL_SECTIONS = ['home', 'identity', 'security', 'sessions', 'sites'];
11718
+ // The exact algorithms the Identity server signs identity tokens with: EdDSA by
11719
+ // default, RS256 when a client opts in via `id_token_signed_response_alg`. The
11720
+ // unverified client-side decode gates on this set so an unsigned (`none`) or
11721
+ // algorithm-confused token cannot masquerade as valid.
11722
+ const ACCEPTED_TOKEN_ALGS = ['EdDSA', 'RS256'];
10677
11723
  /**
10678
11724
  * Whether `handleRedirectResult()` has anything to do on this load — a returned
10679
11725
  * sign-in fragment to consume, or a pending sign-in to self-heal. Public + side
@@ -10689,7 +11735,7 @@ function isSignInRecoveryPending() {
10689
11735
  if (/[#&](sv_code|sv_error|sso)=/.test(window.location.hash || '')) {
10690
11736
  return true;
10691
11737
  }
10692
- return hasFreshPendingMarker();
11738
+ return isFreshPendingMarker(readPendingMarker());
10693
11739
  }
10694
11740
  function isTokenClaims(payload) {
10695
11741
  if (typeof payload !== 'object' || payload === null) {
@@ -10740,6 +11786,8 @@ class IdentityModule {
10740
11786
  constructor(config) {
10741
11787
  this.renderer = null;
10742
11788
  this.launcher = null;
11789
+ // The popup sign-in in flight: its pending marker and reference.
11790
+ this.pendingSignIn = null;
10743
11791
  this.config = config;
10744
11792
  this.api = new IdentityApi(config);
10745
11793
  // Preload config in background for instant dialog opening
@@ -10877,8 +11925,10 @@ class IdentityModule {
10877
11925
  * Resilience: pair this with `handleRedirectResult()` on page load. If the
10878
11926
  * popup's result is ever lost (a mobile browser discards the backgrounded
10879
11927
  * 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.
11928
+ * popup signed in or chose; a sign-in that opened none (the account's own
11929
+ * identity provider) comes back signed out, to sign in again. `flow:
11930
+ * 'redirect'` opts a caller out of the popup into a same-tab navigation
11931
+ * instead.
10882
11932
  *
10883
11933
  * @example
10884
11934
  * const result = await sv.products.identity.signIn();
@@ -10896,13 +11946,12 @@ class IdentityModule {
10896
11946
  * Core flow runner. Default mode (no `target`) opens the popup; `flow:
10897
11947
  * 'redirect'` navigates the tab instead; local mode (`renderMode: 'local'` /
10898
11948
  * `target`) renders into the current document and powers the
10899
- * SparkVault-hosted sign-in surfaces (see the internal `render`).
11949
+ * SparkVault-hosted sign-in surfaces (see the internal `render`), which
11950
+ * hands it what a round trip to the account's own identity provider
11951
+ * returned (`federationReturn`).
10900
11952
  */
10901
- async runFlow(options = {}) {
10902
- if (this.launcher) {
10903
- this.launcher.close();
10904
- this.launcher = null;
10905
- }
11953
+ async runFlow(options = {}, federationReturn = null) {
11954
+ this.closeLauncher();
10906
11955
  if (this.renderer) {
10907
11956
  this.renderer.close();
10908
11957
  }
@@ -10945,7 +11994,7 @@ class IdentityModule {
10945
11994
  },
10946
11995
  };
10947
11996
  const startLocalRender = (container) => {
10948
- this.renderer = new IdentityRenderer(container, this.api, mergedOptions, hostCallbacks);
11997
+ this.renderer = new IdentityRenderer(container, this.api, mergedOptions, hostCallbacks, federationReturn);
10949
11998
  this.renderer.start().catch((error) => {
10950
11999
  // A startup failure must surface inside the SparkVault dialog, never
10951
12000
  // close it silently. Render the error in-dialog instead (consistent with
@@ -10967,10 +12016,11 @@ class IdentityModule {
10967
12016
  // returns via handleRedirectResult() (the escape hatch for hosts that
10968
12017
  // want to skip the popup on mobile). Then this page is unloading, so the
10969
12018
  // promise never settles on success; it rejects only if the redirect
10970
- // cannot start.
12019
+ // cannot start. The sign-in completes in that tab, which no recovery
12020
+ // stands in for, so it draws no reference.
10971
12021
  if (mergedOptions.flow === 'redirect') {
10972
12022
  try {
10973
- if (!await this.startRedirectFlow(mergedOptions)) {
12023
+ if (!await this.startRedirectFlow(mergedOptions, null)) {
10974
12024
  hostCallbacks.onError(new ValidationError('Sign-in requires browser session storage. Enable site data for this site and try again.'));
10975
12025
  }
10976
12026
  }
@@ -10983,24 +12033,44 @@ class IdentityModule {
10983
12033
  // as in flight so that if its result is lost (a mobile browser discards
10984
12034
  // the backgrounded opener tab, killing the postMessage listener),
10985
12035
  // 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(); },
12036
+ // the SSO session the popup signed in or chose, which that popup's
12037
+ // reference names (see pending-signin.ts).
12038
+ const pending = new PendingSignIn(mergedOptions.email || mergedOptions.phone || null);
12039
+ this.pendingSignIn = pending;
12040
+ const launcher = new DialogLauncher(this.config, this.api, mergedOptions, {
12041
+ onSuccess: (result) => { pending.end(); hostCallbacks.onSuccess(result); },
12042
+ onError: (error) => { pending.end(); hostCallbacks.onError(error); },
12043
+ onCancel: () => { pending.end(); hostCallbacks.onCancel(); },
10993
12044
  // Self-heal exists for a result the opener never observed. An observed
10994
12045
  // 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),
12046
+ // while the retry alert is up).
12047
+ onPopupClosedUnresolved: () => pending.retire(),
12048
+ // Every popup, the first and each "Try again", arms the marker anew
12049
+ // with a reference of its own, and so does a popup that has none and
12050
+ // asks again. It reaches the popup only once the marker holds it (or
12051
+ // as null, once the popup has none).
12052
+ drawSigninReference: () => {
12053
+ void pending.open(() => this.api.drawSigninReference()).then((stillCurrent) => {
12054
+ if (stillCurrent)
12055
+ launcher.signinReferenceDecided();
12056
+ });
12057
+ },
10998
12058
  // 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),
12059
+ // to the redirect flow (returns via handleRedirectResult). It carries
12060
+ // the reference the marker holds for this popup, waiting a moment for
12061
+ // a draw still out, and the marker stays armed: the returned #sv_code
12062
+ // fragment retires it. With none by then, the marker is retired, for
12063
+ // no recovery may stand in for a page sent without a reference.
12064
+ onPopupSevered: async () => {
12065
+ const signinRef = await pending.referenceWithin(SIGNIN_REFERENCE.redirectWaitMs);
12066
+ if (signinRef === null)
12067
+ pending.retire();
12068
+ return this.startRedirectFlow(mergedOptions, signinRef);
12069
+ },
12070
+ signinReference: () => pending.reference,
11002
12071
  });
11003
- this.launcher.start();
12072
+ this.launcher = launcher;
12073
+ launcher.start();
11004
12074
  return settledPromise;
11005
12075
  }
11006
12076
  startLocalRender(isInline
@@ -11033,6 +12103,7 @@ class IdentityModule {
11033
12103
  phone: options.phone,
11034
12104
  authContext: options.authContext,
11035
12105
  prompt: options.prompt,
12106
+ method: options.method,
11036
12107
  onSuccess: options.onSuccess,
11037
12108
  onError: options.onError,
11038
12109
  onCancel: options.onCancel,
@@ -11108,10 +12179,13 @@ class IdentityModule {
11108
12179
  * `onSuccess` (and resolve with it).
11109
12180
  * 2. A sign-in was in flight but never delivered (a mobile browser
11110
12181
  * 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.
12182
+ * postMessage) — silently re-mint from the SSO session the popup signed
12183
+ * in or chose, by navigating this tab through the silent SSO endpoint
12184
+ * and straight back with a code (case 1 on return). The bounce names
12185
+ * the sign-in's reference, and the endpoint mints only when the
12186
+ * session it would mint from carries it. Nothing is shown; with no
12187
+ * such session (a sign-in that opened none, such as one through the
12188
+ * account's own identity provider) it comes back logged-out, no oracle.
11115
12189
  *
11116
12190
  * The code is one-time, PKCE-bound, and origin-locked — never the token. The
11117
12191
  * host must still verify `result.token` server-side via the Identity JWKS.
@@ -11140,8 +12214,8 @@ class IdentityModule {
11140
12214
  // No returned result. If a sign-in was in flight and its result never
11141
12215
  // arrived, self-heal once from the SSO session (mobile opener-tab discard).
11142
12216
  const pending = this.consumeSignInPending();
11143
- if (pending.fresh) {
11144
- await this.startRecoveryBounce(pending.hint);
12217
+ if (pending) {
12218
+ await this.startRecoveryBounce(pending);
11145
12219
  }
11146
12220
  return null;
11147
12221
  }
@@ -11152,7 +12226,7 @@ class IdentityModule {
11152
12226
  // A returned fragment means this sign-in resolved (redeem, cancel, or
11153
12227
  // error), so retire any pending marker — otherwise it could fire one
11154
12228
  // spurious silent bounce on a later load inside its TTL.
11155
- this.clearSignInPending();
12229
+ removePendingMarker();
11156
12230
  // Consume exactly once: fragment and one-shot state/verifier are cleared
11157
12231
  // up front on every path, so a failing result cannot wedge future loads
11158
12232
  // (and a StrictMode double-invocation finds an empty hash and no-ops).
@@ -11206,8 +12280,8 @@ class IdentityModule {
11206
12280
  }
11207
12281
  }
11208
12282
  /**
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
12283
+ * Silently re-mint the sign-in result from the SSO session the popup signed
12284
+ * in or chose. Navigates this tab through the silent SSO endpoint
11211
12285
  * (a top-level GET, so the `SameSite=Lax` hub cookie rides along) which,
11212
12286
  * PKCE-bound, returns a one-time code in the fragment — handled by case 1 on
11213
12287
  * return. No-op (stays put) if session storage or WebCrypto is unavailable,
@@ -11217,52 +12291,73 @@ class IdentityModule {
11217
12291
  * malformed answer) rejects `handleRedirectResult()` with that error, and the
11218
12292
  * page stays put.
11219
12293
  */
11220
- async startRecoveryBounce(loginHint) {
12294
+ async startRecoveryBounce(pending) {
12295
+ const handoff = await this.armHandoffReturn();
12296
+ if (!handoff) {
12297
+ return;
12298
+ }
11221
12299
  const sso = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/sso`);
11222
12300
  // 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).
12301
+ // sign-in was addressing: /sso mints silently ONLY for a hint that matched
12302
+ // exactly one hub session's verified identifiers — every unsatisfiable hint
12303
+ // (a stranger's address, an ambiguous match, an account not eligible here)
12304
+ // comes back with no result at all rather than a different account's.
12305
+ if (pending.hint) {
12306
+ sso.searchParams.set('login_hint', pending.hint);
12307
+ }
12308
+ // The sign-in's reference, recorded on the hub session the popup signed
12309
+ // in or chose: /sso mints only when that session carries it. Without it, a
12310
+ // sign-in that opened no hub session of its own (the account's own
12311
+ // identity provider) would recover as whatever session this browser
12312
+ // already held, someone else entirely.
12313
+ if (pending.ref) {
12314
+ sso.searchParams.set(SIGNIN_REFERENCE.param, pending.ref);
12315
+ }
12316
+ sso.searchParams.set('redirect_uri', handoff.redirectUri);
12317
+ sso.searchParams.set('state', handoff.state);
12318
+ sso.searchParams.set('code_challenge', handoff.codeChallenge);
12319
+ window.location.assign(sso.toString());
12320
+ }
12321
+ /**
12322
+ * Navigate this tab to the interactive sign-in page: explicit `flow:
12323
+ * 'redirect'`, or a popup whose handle COOP severed. Plain sign-in carries
12324
+ * redirect_uri + state + PKCE challenge and returns via the fragment code;
12325
+ * OIDC/simple modes navigate without them (their server-rendered pages drive
12326
+ * the server-validated redirect back). Either carries `signinRef`, the
12327
+ * severed popup's reference; a redirect draws none of its own.
11241
12328
  *
12329
+ * @param signinRef - The reference the pending marker holds for this
12330
+ * sign-in, or null for a page sent without one
11242
12331
  * @returns false when the return leg cannot be armed (no session storage or
11243
12332
  * WebCrypto) — the caller surfaces an actionable error instead of a
11244
12333
  * silent dead-end.
11245
12334
  */
11246
- async startRedirectFlow(options) {
12335
+ async startRedirectFlow(options, signinRef) {
12336
+ if (signinRef === null) {
12337
+ // With no marker, no recovery can stand in for this page's result, so
12338
+ // the page needs no reference. A marker left from an earlier sign-in
12339
+ // would otherwise bounce on the next load in place of this one.
12340
+ removePendingMarker();
12341
+ }
11247
12342
  const authContext = options.authContext;
11248
12343
  if (authContext?.authRequestId || authContext?.simpleMode?.sessionId) {
11249
- window.location.assign(buildSigninUrl(this.config, options));
12344
+ window.location.assign(buildSigninUrl(this.config, options, { kind: 'redirect', signinRef }));
11250
12345
  return true;
11251
12346
  }
11252
- const url = await this.prepareHandoffNavigation(buildSigninUrl(this.config, options), (extras) => buildSigninUrl(this.config, options, extras));
11253
- if (!url) {
12347
+ const handoff = await this.armHandoffReturn();
12348
+ if (!handoff) {
11254
12349
  return false;
11255
12350
  }
11256
- window.location.assign(url);
12351
+ window.location.assign(buildSigninUrl(this.config, options, { kind: 'redirect', signinRef, handoff }));
11257
12352
  return true;
11258
12353
  }
11259
12354
  /**
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.
12355
+ * Arm the PKCE + state return leg of a handoff navigation and return what
12356
+ * the navigation carries for it (redirect_uri = this page, per
12357
+ * `currentPageReturnUrl`). Returns null when session storage or WebCrypto is
12358
+ * unavailable so callers can degrade.
11264
12359
  */
11265
- async prepareHandoffNavigation(base, build) {
12360
+ async armHandoffReturn() {
11266
12361
  const { state, codeVerifier } = await this.api.drawAuthorizationValues();
11267
12362
  // Derive the challenge BEFORE persisting: a WebCrypto failure (insecure
11268
12363
  // context) then leaves no orphaned state/verifier behind in storage.
@@ -11280,49 +12375,25 @@ class IdentityModule {
11280
12375
  catch {
11281
12376
  return null;
11282
12377
  }
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
- }
12378
+ return { redirectUri: currentPageReturnUrl(), state, codeChallenge };
11315
12379
  }
11316
12380
  /**
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`.
12381
+ * Consume the pending marker: the marker once (then cleared) while a recent
12382
+ * sign-in is still awaiting its result, else null. Its `hint` is the
12383
+ * identifier that sign-in carried, for the recovery bounce's `login_hint`,
12384
+ * and its `ref` the sign-in's reference, when the marker holds one.
11320
12385
  */
11321
12386
  consumeSignInPending() {
11322
12387
  const marker = readPendingMarker();
11323
- const fresh = isFreshPendingMarker(marker);
11324
- this.clearSignInPending();
11325
- return { fresh, hint: fresh ? marker.hint : null };
12388
+ removePendingMarker();
12389
+ return isFreshPendingMarker(marker) ? marker : null;
12390
+ }
12391
+ /** Close the popup sign-in's launcher, ending the sign-in it ran. */
12392
+ closeLauncher() {
12393
+ this.launcher?.close();
12394
+ this.launcher = null;
12395
+ this.pendingSignIn?.end();
12396
+ this.pendingSignIn = null;
11326
12397
  }
11327
12398
  /** Remove the result fragment from the URL bar (and history entry). */
11328
12399
  clearUrlFragment() {
@@ -11341,8 +12412,9 @@ class IdentityModule {
11341
12412
  }
11342
12413
  }
11343
12414
  /**
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 —
12415
+ * Complete a social round trip, or one through the account's own identity
12416
+ * provider, that returned to the sign-in page as `#token=…&state=…`. Only
12417
+ * `render()`, the Identity-origin sign-in page,
11346
12418
  * reads it: no SDK flow returns a `#token` to a site (a site's results arrive
11347
12419
  * by the popup's postMessage, FedCM, or a PKCE-bound `#sv_code`), so on a site
11348
12420
  * it could only be someone else's token, or the site's own direct
@@ -11353,7 +12425,7 @@ class IdentityModule {
11353
12425
  return null;
11354
12426
  }
11355
12427
  const params = new URLSearchParams(window.location.hash.slice(1));
11356
- const token = params.get('token');
12428
+ const token = params.get(SIGNIN_RESULT_FRAGMENT.token);
11357
12429
  if (!token) {
11358
12430
  return null;
11359
12431
  }
@@ -11376,7 +12448,7 @@ class IdentityModule {
11376
12448
  // provider. Anyone can compose a URL carrying their own genuinely-signed
11377
12449
  // token, so a fragment with no stored state, or a different one, is an
11378
12450
  // unsolicited result (login CSRF) and is refused.
11379
- if (!expectedState || params.get('state') !== expectedState) {
12451
+ if (!expectedState || params.get(SIGNIN_RESULT_FRAGMENT.state) !== expectedState) {
11380
12452
  throw new ValidationError('Invalid OAuth state');
11381
12453
  }
11382
12454
  // Unverified client-side decode — surfaces the claims for the result
@@ -11400,7 +12472,38 @@ class IdentityModule {
11400
12472
  catch {
11401
12473
  // Storage disabled (private mode): nothing to clear.
11402
12474
  }
12475
+ // The round trip came back, so a start this tab made on its own is
12476
+ // answered and must not hold back the page's next sign-in.
12477
+ takeFederationAutoStart(this.config.accountId);
12478
+ }
12479
+ }
12480
+ /**
12481
+ * Read a refusal a round trip through the account's own identity provider
12482
+ * returned to the sign-in page (`#error=…&state=…`, see federation-flow.ts).
12483
+ * Such a fragment is consumed exactly once, with the state it answers,
12484
+ * whatever it holds. Null for any other fragment, and for a refusal whose
12485
+ * state is not the one this browser stored before it left: an answer to no
12486
+ * sign-in this browser started, which the page ignores.
12487
+ */
12488
+ consumeFederationReturn() {
12489
+ if (typeof window === 'undefined' || !window.location.hash) {
12490
+ return null;
12491
+ }
12492
+ const params = new URLSearchParams(window.location.hash.slice(1));
12493
+ const refusal = federationRefusalIn(params);
12494
+ if (!refusal) {
12495
+ return null;
12496
+ }
12497
+ let expectedState = null;
12498
+ try {
12499
+ expectedState = sessionStorage.getItem('sv_oauth_state');
12500
+ sessionStorage.removeItem('sv_oauth_state');
12501
+ }
12502
+ catch {
12503
+ // Storage disabled: no sign-in could have stored a state here.
11403
12504
  }
12505
+ this.clearUrlFragment();
12506
+ return expectedState && params.get(SIGNIN_RESULT_FRAGMENT.state) === expectedState ? refusal : null;
11404
12507
  }
11405
12508
  /**
11406
12509
  * Close the identity dialog/inline UI if open.
@@ -11409,10 +12512,7 @@ class IdentityModule {
11409
12512
  * mode) or the local renderer (inline / local mode).
11410
12513
  */
11411
12514
  close() {
11412
- if (this.launcher) {
11413
- this.launcher.close();
11414
- this.launcher = null;
11415
- }
12515
+ this.closeLauncher();
11416
12516
  if (this.renderer) {
11417
12517
  this.renderer.close();
11418
12518
  this.renderer = null;
@@ -11456,9 +12556,12 @@ class IdentityModule {
11456
12556
  /**
11457
12557
  * Render the flow into a page element instead of a popup.
11458
12558
  *
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.
12559
+ * A social login, or one through the account's own identity provider,
12560
+ * started here returns to this same page with its result in the fragment,
12561
+ * so a returned `#token` is completed first (see `consumeRedirectResult`)
12562
+ * instead of starting the flow again, and a returned refusal of the
12563
+ * account's own identity provider is handed to the flow it starts (see
12564
+ * `consumeFederationReturn`).
11462
12565
  *
11463
12566
  * @internal Used only by the SparkVault-hosted sign-in popup and hosted login
11464
12567
  * page (which own their chrome and pass `renderMode: 'local'`). Customer
@@ -11470,7 +12573,7 @@ class IdentityModule {
11470
12573
  options.onSuccess?.(returned);
11471
12574
  return returned;
11472
12575
  }
11473
- return this.runFlow(options);
12576
+ return this.runFlow(options, this.consumeFederationReturn());
11474
12577
  }
11475
12578
  }
11476
12579
 
@@ -28355,7 +29458,7 @@ class SparkVault {
28355
29458
  }
28356
29459
  /** Get the SDK version */
28357
29460
  static get version() {
28358
- return '16.0.1';
29461
+ return '16.1.1';
28359
29462
  }
28360
29463
  }
28361
29464
  if (typeof window !== 'undefined') {