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