@sparkvault/sdk-js 16.10.0 → 16.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -940,15 +940,17 @@ class PopupBlockedError extends SparkVaultError {
940
940
  }
941
941
  /**
942
942
  * The popup opened but its window handle went dead before the page ever
943
- * pinged back — the signature of a Cross-Origin-Opener-Policy severance
944
- * (a host page serving `COOP: same-origin` detaches any cross-origin popup:
945
- * the popup loses `window.opener`, the opener's handle reports `closed`).
946
- * postMessage can never work in this state, so retrying the popup is futile;
947
- * callers should fall back to the redirect flow.
943
+ * pinged back: the host page's Cross-Origin-Opener-Policy severed it (a host
944
+ * page serving `COOP: same-origin` detaches any cross-origin popup: the popup
945
+ * loses `window.opener`, the opener's handle reports `closed`). postMessage
946
+ * can never work in this state, so retrying the popup is futile. Identity
947
+ * sign-in falls back to the redirect flow (popup-launcher.ts); the help desk
948
+ * widget's sign-in, which has none, passes a message that tells the person
949
+ * what to do (help-desk/widget-identity.ts).
948
950
  */
949
951
  class PopupSeveredError extends SparkVaultError {
950
- constructor() {
951
- super('The sign-in window could not communicate with this page.', 'popup_severed');
952
+ constructor(message = 'The sign-in window could not communicate with this page.') {
953
+ super(message, 'popup_severed');
952
954
  this.name = 'PopupSeveredError';
953
955
  Object.setPrototypeOf(this, PopupSeveredError.prototype);
954
956
  }
@@ -2226,6 +2228,10 @@ function identityDrawBytes(answer, numBytes) {
2226
2228
  * naming that reference, and the recovery may only veto: it mints what the
2227
2229
  * same call without a reference would, and only when that hub session
2228
2230
  * carries this sign-in's reference.
2231
+ * - A sign-in may name the identity types it accepts (SIGNIN_IDENTITY_TYPES):
2232
+ * its page offers only the methods that can produce one, and Identity
2233
+ * records the restriction where each sign-in starts and refuses a sign-in
2234
+ * of any other type before it is counted, billed or minted.
2229
2235
  *
2230
2236
  * Browser-safe and dependency-free: the JS SDK bundles this module, and the
2231
2237
  * sign-in shells inline federationRefusalIn's own source into their pages.
@@ -2353,6 +2359,138 @@ function isSigninReference(value) {
2353
2359
  return typeof value === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value);
2354
2360
  }
2355
2361
 
2362
+ /**
2363
+ * A sign-in's restriction on the identity types it may produce (the
2364
+ * `identity_type` its token carries): a caller that takes only some types
2365
+ * names them, and Identity refuses a sign-in of any other type, before it is
2366
+ * counted, billed or minted, with `refusalCode`. A restriction only refuses:
2367
+ * it never chooses which of a person's identifiers a sign-in carries, so a
2368
+ * sign-in it admits carries exactly what an unrestricted one would. A
2369
+ * sign-in that names none is unrestricted. An OIDC authorization or a verify
2370
+ * session carries its client's own policy and takes no restriction.
2371
+ *
2372
+ * - `param`: the name it travels under, spelled as formatSigninIdentityTypes
2373
+ * writes it: in a query (the sign-in page's URL, a provider start,
2374
+ * `/sso`, `/sso/accounts`), in a JSON body (each call that starts a
2375
+ * ceremony, `/sso/continue`), and in a FedCM request's `params`.
2376
+ * - `values`: the types, in the one order every spelling lists them.
2377
+ * - `refusalCode`: the error code of a refused sign-in, whose message
2378
+ * signinIdentityTypesRefusal words.
2379
+ *
2380
+ * Identity records the restriction where each ceremony starts (the code it
2381
+ * sends, the passkey challenge, the provider round trip's state, the second
2382
+ * factor's ticket) and reads it from there at completion, never from the
2383
+ * completing request, so a later step cannot widen it. A caller's own check
2384
+ * of the token stays its final gate: a page that drops the parameter gets an
2385
+ * unrestricted sign-in, which that check refuses.
2386
+ */
2387
+ const SIGNIN_IDENTITY_TYPES = Object.freeze({
2388
+ param: 'identity_types',
2389
+ values: Object.freeze(['email', 'phone', 'social', 'federated']),
2390
+ refusalCode: 'IDENTITY_TYPE_NOT_ALLOWED'
2391
+ });
2392
+
2393
+ /**
2394
+ * A restriction as its one spelling writes it: its types, comma-separated, in
2395
+ * SIGNIN_IDENTITY_TYPES.values order.
2396
+ *
2397
+ * @param {string[]} types - At least one of SIGNIN_IDENTITY_TYPES.values
2398
+ * @returns {string}
2399
+ * @throws {TypeError} For an empty list or a type outside the values
2400
+ */
2401
+ function formatSigninIdentityTypes(types) {
2402
+ if (!Array.isArray(types) || types.length === 0 || !types.every((type) => SIGNIN_IDENTITY_TYPES.values.includes(type))) {
2403
+ throw new TypeError(`identity types must name at least one of ${SIGNIN_IDENTITY_TYPES.values.join(', ')}`);
2404
+ }
2405
+ return SIGNIN_IDENTITY_TYPES.values.filter((type) => types.includes(type)).join(',');
2406
+ }
2407
+
2408
+ /**
2409
+ * Read a restriction as it arrived: absent (`undefined` or `null`) is no
2410
+ * restriction; anything else must be its spelling (formatSigninIdentityTypes),
2411
+ * whose types it answers in values order.
2412
+ *
2413
+ * @param {unknown} raw
2414
+ * @returns {{ ok: true, types: string[]|null } | { ok: false }}
2415
+ */
2416
+ function readSigninIdentityTypes(raw) {
2417
+ if (raw === undefined || raw === null) return { ok: true, types: null };
2418
+ if (typeof raw !== 'string') return { ok: false };
2419
+ const named = raw.split(',');
2420
+ if (!named.every((type) => SIGNIN_IDENTITY_TYPES.values.includes(type)) || new Set(named).size !== named.length) return { ok: false };
2421
+ return { ok: true, types: SIGNIN_IDENTITY_TYPES.values.filter((type) => named.includes(type)) };
2422
+ }
2423
+
2424
+ /**
2425
+ * Whether a restriction admits an identity type: no restriction admits every
2426
+ * type, and a restriction admits the types it names.
2427
+ *
2428
+ * @param {string} identityType
2429
+ * @param {string[]|null} types - A restriction readSigninIdentityTypes read
2430
+ * @returns {boolean}
2431
+ */
2432
+ function signinIdentityTypeAdmitted(identityType, types) {
2433
+ return types === null || types.includes(identityType);
2434
+ }
2435
+
2436
+ /**
2437
+ * The identity types a sign-in by `methodId` can produce: a code to an
2438
+ * address or a SparkLink signs in by email, a code to a phone by phone, a
2439
+ * social provider by social, an enterprise (SAML) provider by the email it
2440
+ * asserts, the account's own identity provider by federated, and a passkey by
2441
+ * the person's primary identifier (the first of email, phone and social they
2442
+ * hold, whatever the restriction names: a restriction only refuses one it
2443
+ * excludes). An unknown method produces none.
2444
+ *
2445
+ * @param {string} methodId
2446
+ * @returns {string[]}
2447
+ */
2448
+ function signinMethodIdentityTypes(methodId) {
2449
+ if (methodId === 'otp_email' || methodId === 'sparklink') return ['email'];
2450
+ if (methodId === 'otp_sms' || methodId === 'otp_voice') return ['phone'];
2451
+ if (methodId === 'passkey') return ['email', 'phone', 'social'];
2452
+ if (methodId === FEDERATION_METHOD) return ['federated'];
2453
+ if (typeof methodId === 'string' && methodId.startsWith('social_')) return ['social'];
2454
+ if (typeof methodId === 'string' && methodId.startsWith('enterprise_')) return ['email'];
2455
+ return [];
2456
+ }
2457
+
2458
+ /**
2459
+ * Whether a restriction admits a method: no restriction admits every method,
2460
+ * and a restriction admits one that can produce a type it names.
2461
+ *
2462
+ * @param {string} methodId
2463
+ * @param {string[]|null} types - A restriction readSigninIdentityTypes read
2464
+ * @returns {boolean}
2465
+ */
2466
+ function signinMethodAdmitted(methodId, types) {
2467
+ return types === null || signinMethodIdentityTypes(methodId).some((type) => signinIdentityTypeAdmitted(type, types));
2468
+ }
2469
+
2470
+ const IDENTITY_TYPE_WORDS = Object.freeze({
2471
+ email: 'an email address',
2472
+ phone: 'a phone number',
2473
+ social: 'a social account',
2474
+ federated: "your organization's sign-in"
2475
+ });
2476
+
2477
+ /** The types a restriction accepts, in words: "a, b or c". */
2478
+ function acceptedTypesInWords(types) {
2479
+ const words = types.map((type) => IDENTITY_TYPE_WORDS[type]);
2480
+ return words.length === 1 ? words[0] : `${words.slice(0, -1).join(', ')} or ${words[words.length - 1]}`;
2481
+ }
2482
+
2483
+ /**
2484
+ * What a sign-in page with no method its restriction admits says instead of
2485
+ * an empty list.
2486
+ *
2487
+ * @param {string[]} types - A restriction readSigninIdentityTypes read
2488
+ * @returns {string}
2489
+ */
2490
+ function signinIdentityTypesUnavailable(types) {
2491
+ return `This sign-in accepts only ${acceptedTypesInWords(types)}, and none of the ways to sign in here gives one. Contact the site you came from for help.`;
2492
+ }
2493
+
2356
2494
  /**
2357
2495
  * Request paths: the one way a module names a SparkVault route.
2358
2496
  *
@@ -2532,6 +2670,40 @@ class ExpirationTimer {
2532
2670
  function arrayBufferToBase64url(buffer) {
2533
2671
  return bytesToBase64url(new Uint8Array(buffer));
2534
2672
  }
2673
+ /**
2674
+ * The restriction a caller's `identityTypes` option names, in the contract's
2675
+ * one order, or null when it names none. Synchronous, so a sign-in refuses a
2676
+ * bad value before it opens anything.
2677
+ *
2678
+ * @throws {ValidationError} For a value that is no list of at least one
2679
+ * SigninIdentityType
2680
+ */
2681
+ function callerIdentityTypes(identityTypes) {
2682
+ if (identityTypes === undefined)
2683
+ return null;
2684
+ const refusal = () => new ValidationError(`identityTypes must name at least one of ${SIGNIN_IDENTITY_TYPES.values.join(', ')}`, { field: 'identityTypes', received: identityTypes });
2685
+ let spelling;
2686
+ try {
2687
+ spelling = formatSigninIdentityTypes(identityTypes);
2688
+ }
2689
+ catch {
2690
+ throw refusal();
2691
+ }
2692
+ // A value that names a restriction never runs as none: anything the
2693
+ // spelling does not read back as one is the caller's error too.
2694
+ const read = readSigninIdentityTypes(spelling);
2695
+ if (!read.ok || read.types === null)
2696
+ throw refusal();
2697
+ return read.types;
2698
+ }
2699
+ /**
2700
+ * The restriction as the wire carries it, `{ identity_types: <spelling> }`,
2701
+ * or nothing for none: a sign-in that names no restriction sends no field,
2702
+ * and Identity applies none.
2703
+ */
2704
+ function identityTypesParam(types) {
2705
+ return types ? { [SIGNIN_IDENTITY_TYPES.param]: formatSigninIdentityTypes(types) } : {};
2706
+ }
2535
2707
  /**
2536
2708
  * This page as a navigation return target: origin, path, and query — the query
2537
2709
  * carries the page's own state (app routing, or the sign-in page's validated
@@ -2577,6 +2749,11 @@ function buildSigninUrl(config, options, delivery) {
2577
2749
  if (options.method === FEDERATION_METHOD) {
2578
2750
  params.set(SIGNIN_METHOD_PARAM, FEDERATION_METHOD);
2579
2751
  }
2752
+ // The restriction the caller named, validated before anything opened
2753
+ // (callerIdentityTypes), in its one spelling.
2754
+ if (options.identityTypes) {
2755
+ params.set(SIGNIN_IDENTITY_TYPES.param, formatSigninIdentityTypes(options.identityTypes));
2756
+ }
2580
2757
  if (delivery.kind === 'popup') {
2581
2758
  params.set(SIGNIN_REFERENCE.fromOpenerParam, SIGNIN_REFERENCE.fromOpenerValue);
2582
2759
  }
@@ -2775,13 +2952,16 @@ class IdentityApi extends SparkVaultApi {
2775
2952
  };
2776
2953
  }
2777
2954
  /**
2778
- * Send OTP code to email or phone
2955
+ * Send OTP code to email or phone. The send starts the ceremony, so it
2956
+ * carries the sign-in's restriction, which Identity records on the code and
2957
+ * reads again at /otp/verify: the verify never names it.
2779
2958
  */
2780
2959
  async sendOtp(params) {
2781
2960
  return this.request('POST', apiPath `/otp/send`, {
2782
2961
  recipient: params.recipient,
2783
2962
  method: params.method,
2784
2963
  ...this.buildAuthContextParams(params.authContext),
2964
+ ...identityTypesParam(params.identityTypes ?? null),
2785
2965
  });
2786
2966
  }
2787
2967
  /**
@@ -2813,13 +2993,19 @@ class IdentityApi extends SparkVaultApi {
2813
2993
  * optional identifier scopes the ceremony to that person's credentials
2814
2994
  * (`allowCredentials`) so the authenticator offers only the matching passkey;
2815
2995
  * omit it for a discoverable ceremony. Completion always routes via the
2816
- * credential userHandle, so scoping is purely a hint.
2996
+ * credential userHandle, so scoping is purely a hint. The start carries the
2997
+ * sign-in's restriction, which Identity records on the challenge's session
2998
+ * and reads again at completion.
2817
2999
  */
2818
- async startPasskeyVerify(identity, identityType = 'email', authContext) {
3000
+ async startPasskeyVerify(identity, identityType = 'email', authContext, identityTypes = null) {
2819
3001
  const identityParam = identity ? { [identityType]: identity } : {};
2820
3002
  // Backend returns { options: PublicKeyCredentialRequestOptions, session: {...} }
2821
3003
  // Extract and flatten to match PasskeyChallengeResponse
2822
- const response = await this.request('POST', apiPath `/passkey/verify`, { ...identityParam, ...verifySessionParam(authContext) });
3004
+ const response = await this.request('POST', apiPath `/passkey/verify`, {
3005
+ ...identityParam,
3006
+ ...verifySessionParam(authContext),
3007
+ ...identityTypesParam(identityTypes),
3008
+ });
2823
3009
  return {
2824
3010
  challenge: response.options.challenge,
2825
3011
  rpId: response.options.rpId,
@@ -2891,13 +3077,15 @@ class IdentityApi extends SparkVaultApi {
2891
3077
  /**
2892
3078
  * Get OAuth redirect URL for social provider. The start carries the
2893
3079
  * sign-in's reference, when it has one, so the hub session the provider's
2894
- * answer creates or chooses records it.
3080
+ * answer creates or chooses records it, and the sign-in's restriction, which
3081
+ * Identity records in the round trip's state.
2895
3082
  */
2896
- getSocialAuthUrl(provider, redirectUri, state, authContext, signinRef) {
3083
+ getSocialAuthUrl(provider, redirectUri, state, authContext, options = {}) {
2897
3084
  const params = new URLSearchParams({
2898
3085
  [START_PARAMS.redirectUri]: redirectUri,
2899
3086
  [START_PARAMS.state]: state,
2900
- ...signinRefParam(signinRef),
3087
+ ...signinRefParam(options.signinRef),
3088
+ ...identityTypesParam(options.identityTypes ?? null),
2901
3089
  });
2902
3090
  if (authContext?.authRequestId) {
2903
3091
  params.set(START_PARAMS.authRequestId, authContext.authRequestId);
@@ -2916,15 +3104,17 @@ class IdentityApi extends SparkVaultApi {
2916
3104
  * showing anything. The start carries the sign-in's reference, when it has
2917
3105
  * one: such a sign-in opens no hub session, so Identity releases that
2918
3106
  * 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.
3107
+ * recovery naming it mints none of them. It carries the sign-in's
3108
+ * restriction too, which Identity records in the round trip's state. A
3109
+ * verify session is never named: such a sign-in cannot complete one, so its
3110
+ * start refuses it, and a verify session never admits the method.
2922
3111
  */
2923
3112
  getFederationAuthUrl(redirectUri, state, authContext, options = {}) {
2924
3113
  const params = new URLSearchParams({
2925
3114
  [START_PARAMS.redirectUri]: redirectUri,
2926
3115
  [START_PARAMS.state]: state,
2927
3116
  ...signinRefParam(options.signinRef),
3117
+ ...identityTypesParam(options.identityTypes ?? null),
2928
3118
  });
2929
3119
  if (authContext?.authRequestId) {
2930
3120
  params.set(START_PARAMS.authRequestId, authContext.authRequestId);
@@ -2936,14 +3126,17 @@ class IdentityApi extends SparkVaultApi {
2936
3126
  }
2937
3127
  /**
2938
3128
  * Send SparkLink email for identity verification.
2939
- * Includes connectionId for WebSocket push notification of verification result.
3129
+ * Includes connectionId for WebSocket push notification of verification
3130
+ * result. The send starts the ceremony, so it carries the sign-in's
3131
+ * restriction, which Identity records for the link's click.
2940
3132
  */
2941
- async sendSparkLink(email, connectionId, authContext, signinRef) {
3133
+ async sendSparkLink(email, connectionId, authContext, signinRef, identityTypes = null) {
2942
3134
  return this.request('POST', apiPath `/sparklink/send`, {
2943
3135
  email,
2944
3136
  connection_id: connectionId,
2945
3137
  ...this.buildAuthContextParams(authContext),
2946
3138
  ...signinRefParam(signinRef),
3139
+ ...identityTypesParam(identityTypes),
2947
3140
  });
2948
3141
  }
2949
3142
  /**
@@ -3442,6 +3635,9 @@ class VerificationState {
3442
3635
  this._authContext = undefined;
3443
3636
  // The sign-in's reference (app-sdk SIGNIN_REFERENCE), when the sign-in page has one
3444
3637
  this._signinRef = null;
3638
+ // The sign-in's restriction on the identity types it may produce (app-sdk
3639
+ // SIGNIN_IDENTITY_TYPES), null for none
3640
+ this._identityTypes = null;
3445
3641
  // Passkey state
3446
3642
  this._passkey = {
3447
3643
  hasPasskey: null,
@@ -3525,6 +3721,14 @@ class VerificationState {
3525
3721
  setSigninRef(signinRef) {
3526
3722
  this._signinRef = signinRef;
3527
3723
  }
3724
+ // --- Identity-type restriction ---
3725
+ /** The restriction every call that starts a ceremony carries, else null. */
3726
+ get identityTypes() {
3727
+ return this._identityTypes;
3728
+ }
3729
+ setIdentityTypes(identityTypes) {
3730
+ this._identityTypes = identityTypes;
3731
+ }
3528
3732
  // --- Passkey State ---
3529
3733
  get passkey() {
3530
3734
  return this._passkey;
@@ -3811,7 +4015,7 @@ class PasskeyHandler {
3811
4015
  // passkeys so the authenticator offers only the matching credential;
3812
4016
  // without one it falls back to a discoverable ceremony.
3813
4017
  const identityType = this.state.identityType === 'phone' ? 'phone' : 'email';
3814
- const challenge = await this.api.startPasskeyVerify(this.state.recipient, identityType, this.state.authContext);
4018
+ const challenge = await this.api.startPasskeyVerify(this.state.recipient, identityType, this.state.authContext, this.state.identityTypes);
3815
4019
  const credential = await navigator.credentials.get({
3816
4020
  ...(signal ? { signal } : {}),
3817
4021
  publicKey: {
@@ -3934,6 +4138,12 @@ class PasskeyHandler {
3934
4138
  if (signinRef) {
3935
4139
  params.set(SIGNIN_REFERENCE.param, signinRef);
3936
4140
  }
4141
+ // The sign-in's restriction: the popup names it on the call that starts
4142
+ // the ceremony, where Identity records it for the completion to read.
4143
+ const { identityTypes } = this.state;
4144
+ if (identityTypes) {
4145
+ params.set(SIGNIN_IDENTITY_TYPES.param, formatSigninIdentityTypes(identityTypes));
4146
+ }
3937
4147
  const hash = mode === 'register' && registrationToken
3938
4148
  ? `#${new URLSearchParams({ registration_token: registrationToken }).toString()}`
3939
4149
  : '';
@@ -4044,6 +4254,7 @@ class OtpHandler {
4044
4254
  recipient: this.state.recipient,
4045
4255
  method,
4046
4256
  authContext: this.state.authContext,
4257
+ identityTypes: this.state.identityTypes,
4047
4258
  });
4048
4259
  // Update state with kindling
4049
4260
  this.state.setKindling(response.kindling);
@@ -4080,6 +4291,7 @@ class OtpHandler {
4080
4291
  recipient: this.state.recipient,
4081
4292
  method,
4082
4293
  authContext: this.state.authContext,
4294
+ identityTypes: this.state.identityTypes,
4083
4295
  });
4084
4296
  // Update state with new kindling
4085
4297
  this.state.setKindling(response.kindling);
@@ -4185,7 +4397,7 @@ class SparkLinkHandler {
4185
4397
  */
4186
4398
  async send(connectionId) {
4187
4399
  try {
4188
- const result = await this.api.sendSparkLink(this.state.recipient, connectionId, this.state.authContext, this.state.signinRef);
4400
+ const result = await this.api.sendSparkLink(this.state.recipient, connectionId, this.state.authContext, this.state.signinRef, this.state.identityTypes);
4189
4401
  return {
4190
4402
  success: true,
4191
4403
  expiresAt: result.expiresAt,
@@ -6348,6 +6560,18 @@ const FEDERATION_UNAVAILABLE_CODE = 'federation_unavailable';
6348
6560
  * a genuine error, which the person's Try Again asks for again.
6349
6561
  */
6350
6562
  const SIGNIN_REFERENCE_UNAVAILABLE_CODE = 'signin_reference_unavailable';
6563
+ /**
6564
+ * The code of a sign-in whose restriction on the identity types it may
6565
+ * produce (SignInOptions.identityTypes) admits none of the account's ways in:
6566
+ * only the site that asked for the restriction can change that.
6567
+ */
6568
+ const IDENTITY_TYPES_UNAVAILABLE_CODE = 'identity_types_unavailable';
6569
+ /**
6570
+ * The code of a sign-in page whose URL names a restriction it cannot read:
6571
+ * the page runs no sign-in under it rather than one wider than the site
6572
+ * asked for, and only a sign-in the site opens afresh clears it.
6573
+ */
6574
+ const IDENTITY_TYPES_UNREADABLE_CODE = 'identity_types_unreadable';
6351
6575
  /**
6352
6576
  * The heading of a state the person can do nothing about from here, by its
6353
6577
  * code, or null for a genuine error. Retrying cannot clear any of them, so the
@@ -6358,17 +6582,36 @@ const SIGNIN_REFERENCE_UNAVAILABLE_CODE = 'signin_reference_unavailable';
6358
6582
  * which only the site owner subscribing clears, shown as a friendly,
6359
6583
  * non-leaky interstitial;
6360
6584
  * - a request held to a passkey the person does not hold;
6361
- * - an account whose only way in this page may not offer.
6585
+ * - an account whose only way in this page may not offer;
6586
+ * - a sign-in whose restriction admits none of the account's ways in, or
6587
+ * that names one this page cannot read.
6362
6588
  */
6363
6589
  function terminalTitle(code) {
6364
6590
  if (code === 'identity_locked')
6365
6591
  return 'This SparkVault Identity is locked';
6366
- if (isBlockedCode(code) || code === FEDERATION_UNAVAILABLE_CODE)
6592
+ if (isBlockedCode(code)
6593
+ || code === FEDERATION_UNAVAILABLE_CODE
6594
+ || code === IDENTITY_TYPES_UNAVAILABLE_CODE
6595
+ || code === IDENTITY_TYPES_UNREADABLE_CODE)
6367
6596
  return 'Sign-in unavailable';
6368
6597
  if (code === STRONGER_VERIFICATION_REQUIRED_CODE)
6369
6598
  return STRONGER_VERIFICATION_TITLE;
6370
6599
  return null;
6371
6600
  }
6601
+ /**
6602
+ * A refusal the person clears by choosing another way in, by its code, or
6603
+ * null: its heading and the label of the action that opens the other ways in
6604
+ * (ErrorViewProps.onRetry). Identity refusing a sign-in for an identity type
6605
+ * the sign-in's restriction excludes is one: its message says what the site
6606
+ * accepts sign-in with. Neither a code badge nor Try Again, which would
6607
+ * repeat the refused sign-in.
6608
+ */
6609
+ function redirectingState(code) {
6610
+ if (code === SIGNIN_IDENTITY_TYPES.refusalCode) {
6611
+ return { title: 'That sign-in is not accepted here', action: 'Other ways to sign in' };
6612
+ }
6613
+ return null;
6614
+ }
6372
6615
  class ErrorView {
6373
6616
  constructor(props) {
6374
6617
  this.retryButton = null;
@@ -6389,16 +6632,17 @@ class ErrorView {
6389
6632
  const contentSection = div();
6390
6633
  contentSection.className = 'sv-error-content';
6391
6634
  const terminal = terminalTitle(this.props.code);
6392
- const isTerminal = terminal !== null;
6635
+ const redirecting = redirectingState(this.props.code);
6636
+ const isGenuine = terminal === null && redirecting === null;
6393
6637
  const title = document.createElement('h3');
6394
6638
  title.className = 'sv-error-title';
6395
- title.textContent = terminal ?? 'Something went wrong';
6639
+ title.textContent = terminal ?? redirecting?.title ?? 'Something went wrong';
6396
6640
  const message = document.createElement('p');
6397
6641
  message.className = 'sv-error-message';
6398
6642
  message.textContent = this.props.message;
6399
6643
  contentSection.appendChild(title);
6400
6644
  contentSection.appendChild(message);
6401
- if (!isTerminal) {
6645
+ if (isGenuine) {
6402
6646
  // Error code badge — useful for debugging genuine errors only.
6403
6647
  const codeBadge = document.createElement('div');
6404
6648
  codeBadge.className = 'sv-error-code-badge';
@@ -6415,10 +6659,10 @@ class ErrorView {
6415
6659
  // Action buttons with proper styling
6416
6660
  const buttonContainer = div();
6417
6661
  buttonContainer.className = 'sv-error-actions';
6418
- if (!isTerminal) {
6662
+ if (terminal === null) {
6419
6663
  this.retryButton = document.createElement('button');
6420
6664
  this.retryButton.className = 'sv-btn sv-btn-error-primary';
6421
- this.retryButton.textContent = 'Try Again';
6665
+ this.retryButton.textContent = redirecting?.action ?? 'Try Again';
6422
6666
  this.retryButton.addEventListener('click', this.boundHandleRetry);
6423
6667
  buttonContainer.appendChild(this.retryButton);
6424
6668
  }
@@ -7018,7 +7262,7 @@ const SPARKLINK_CSP_BLOCKED_ERROR = {
7018
7262
  code: 'sparklink_csp_blocked',
7019
7263
  };
7020
7264
  class IdentityRenderer {
7021
- constructor(container, api, options, callbacks, federationReturn = null) {
7265
+ constructor(container, api, options, callbacks, federationReturn = null, identityTypes = { ok: true, types: null }) {
7022
7266
  // True while the identifier is the one the render options supplied (a host's
7023
7267
  // prefill, a login hint, an invite's identity), false once the person types
7024
7268
  // their own. Gates the "identity is fixed" behavior, so a no-hint
@@ -7072,6 +7316,10 @@ class IdentityRenderer {
7072
7316
  this.passkeyHandler = new PasskeyHandler(api, this.verificationState);
7073
7317
  this.otpHandler = new OtpHandler(api, this.verificationState);
7074
7318
  this.sparkLinkHandler = new SparkLinkHandler(api, this.verificationState);
7319
+ // The restriction lists only the ways in that can produce a type it names,
7320
+ // and rides every start (see SigninIdentityTypesRead).
7321
+ this.identityTypesUnreadable = !identityTypes.ok;
7322
+ this.verificationState.setIdentityTypes(identityTypes.ok ? identityTypes.types : null);
7075
7323
  // Seed the identity being verified from the render options.
7076
7324
  this.applyInitialIdentity();
7077
7325
  // Set auth context for OIDC/simple mode flows
@@ -7107,7 +7355,12 @@ class IdentityRenderer {
7107
7355
  const raw = explicitPhone ? this.options.phone : this.options.email;
7108
7356
  if (!raw)
7109
7357
  return;
7110
- if (explicitPhone || inferIdentityType(raw) === 'phone') {
7358
+ const type = explicitPhone || inferIdentityType(raw) === 'phone' ? 'phone' : 'email';
7359
+ // A hint of a type the sign-in's restriction excludes could lead only to
7360
+ // ways in it refuses: the person starts from the ways in it admits.
7361
+ if (!signinIdentityTypeAdmitted(type, this.verificationState.identityTypes))
7362
+ return;
7363
+ if (type === 'phone') {
7111
7364
  this.verificationState.setIdentity(parsePhone(raw) ?? raw, 'phone');
7112
7365
  }
7113
7366
  else {
@@ -7331,6 +7584,14 @@ class IdentityRenderer {
7331
7584
  this.render();
7332
7585
  }
7333
7586
  async showInitialAuthStep() {
7587
+ if (this.identityTypesUnreadable) {
7588
+ this.setState({
7589
+ view: 'error',
7590
+ code: IDENTITY_TYPES_UNREADABLE_CODE,
7591
+ message: 'This sign-in link is not valid. Contact the site you came from for help.',
7592
+ });
7593
+ return;
7594
+ }
7334
7595
  const heldAtStart = this.verificationState.signinRef;
7335
7596
  if (this.startWithFederation())
7336
7597
  return;
@@ -7511,7 +7772,7 @@ class IdentityRenderer {
7511
7772
  canDiscoverableVerify() {
7512
7773
  if (!this.passkeyHandler.canAutoVerify())
7513
7774
  return false;
7514
- const methods = enrichMethods(this.verificationState.methodIds);
7775
+ const methods = this.admittedMethods(enrichMethods(this.verificationState.methodIds));
7515
7776
  return methods.some((m) => m.type === 'passkey');
7516
7777
  }
7517
7778
  /**
@@ -7790,7 +8051,9 @@ class IdentityRenderer {
7790
8051
  ? () => { void this.showSignInStep(); }
7791
8052
  : state.code === SIGNIN_REFERENCE_UNAVAILABLE_CODE
7792
8053
  ? () => this.retryReference()
7793
- : () => this.showIdentityInput(),
8054
+ : state.code === SIGNIN_IDENTITY_TYPES.refusalCode
8055
+ ? () => this.chooseAnotherWay()
8056
+ : () => this.showIdentityInput(),
7794
8057
  onClose: () => this.handleClose(),
7795
8058
  });
7796
8059
  case 'service-unavailable':
@@ -7848,7 +8111,7 @@ class IdentityRenderer {
7848
8111
  // identity provider is set apart: it needs no identifier, and leads every
7849
8112
  // list that offers it (below), read once the rest of the list is known so
7850
8113
  // a reference that arrived meanwhile counts.
7851
- let methods = enrichMethods(methodIds);
8114
+ let methods = this.admittedMethods(enrichMethods(methodIds));
7852
8115
  if (this.recipient) {
7853
8116
  // Filter by identifier type. Passkeys are SVID-scoped, so they remain
7854
8117
  // available regardless of whether the fallback identifier is email or phone.
@@ -7953,8 +8216,11 @@ class IdentityRenderer {
7953
8216
  * - the page's ask for its reference is still out: the step waits for it;
7954
8217
  * - the ask found none for now: the person is told to try again, which
7955
8218
  * asks again.
7956
- * Any other verification with nothing to offer is a configuration fault,
7957
- * shown as one.
8219
+ * A sign-in whose restriction on the identity types it may produce took
8220
+ * away a way in it would otherwise offer is told which types it accepts and
8221
+ * that none of the ways here gives one: only the site that asked for the
8222
+ * restriction can change that. Any other verification with nothing to
8223
+ * offer is a configuration fault, shown as one.
7958
8224
  */
7959
8225
  noMethodState() {
7960
8226
  if (this.verificationState.passkeyRequired && this.verificationState.passkey.hasPasskey === false) {
@@ -7978,8 +8244,49 @@ class IdentityRenderer {
7978
8244
  }
7979
8245
  return { view: 'awaiting-reference' };
7980
8246
  }
8247
+ const identityTypes = this.verificationState.identityTypes;
8248
+ if (identityTypes && this.verificationState.methodIds.some((id) => !signinMethodAdmitted(id, identityTypes))) {
8249
+ return {
8250
+ view: 'error',
8251
+ code: IDENTITY_TYPES_UNAVAILABLE_CODE,
8252
+ message: signinIdentityTypesUnavailable(identityTypes),
8253
+ };
8254
+ }
7981
8255
  return { view: 'error', message: 'No authentication methods available', code: 'no_methods' };
7982
8256
  }
8257
+ /**
8258
+ * The methods the sign-in's restriction admits (app-sdk
8259
+ * signinMethodAdmitted): every method for a sign-in with none, else those
8260
+ * that can produce a type it names.
8261
+ */
8262
+ admittedMethods(methods) {
8263
+ const identityTypes = this.verificationState.identityTypes;
8264
+ return methods.filter((method) => signinMethodAdmitted(method.id, identityTypes));
8265
+ }
8266
+ /**
8267
+ * After Identity refused a sign-in of a type the restriction does not name:
8268
+ * the ways in for this identifier, with nothing starting on its own, or the
8269
+ * identifier field when the person has typed none.
8270
+ */
8271
+ chooseAnotherWay() {
8272
+ if (this.recipient || this.getAllowedIdentityTypes().length === 0) {
8273
+ void this.showMethodSelect({ autoRoute: false });
8274
+ return;
8275
+ }
8276
+ this.showIdentityInput();
8277
+ }
8278
+ /**
8279
+ * Identity refused the sign-in for a type its restriction does not name
8280
+ * (SIGNIN_IDENTITY_TYPES.refusalCode): show Identity's own words, which say
8281
+ * what this sign-in accepts, and return true. False for any other code.
8282
+ */
8283
+ renderIdentityTypeRefusal(code, message) {
8284
+ if (code !== SIGNIN_IDENTITY_TYPES.refusalCode || !message) {
8285
+ return false;
8286
+ }
8287
+ this.setState({ view: 'error', code, message });
8288
+ return true;
8289
+ }
7983
8290
  handleIdentitySubmit(result) {
7984
8291
  this.verificationState.setIdentity(result.value, result.type);
7985
8292
  // The person typed this identifier, so it is theirs to change — a no-hint
@@ -7987,8 +8294,15 @@ class IdentityRenderer {
7987
8294
  this.identityPrefilled = false;
7988
8295
  this.showMethodSelect();
7989
8296
  }
8297
+ /**
8298
+ * The identifier types the identifier field takes: the verification's,
8299
+ * less any its restriction does not name, whose codes and links could only
8300
+ * produce a sign-in it refuses.
8301
+ */
7990
8302
  getAllowedIdentityTypes() {
7991
- return this.verificationState.getAllowedIdentityTypes();
8303
+ const allowed = this.verificationState.getAllowedIdentityTypes();
8304
+ const identityTypes = this.verificationState.identityTypes;
8305
+ return identityTypes ? allowed.filter((type) => identityTypes.includes(type)) : allowed;
7992
8306
  }
7993
8307
  /**
7994
8308
  * @param userInitiated True when called from a live click on the picker, so
@@ -8010,6 +8324,8 @@ class IdentityRenderer {
8010
8324
  if (!result.success) {
8011
8325
  if (this.renderBlockedInterstitial(result.errorCode))
8012
8326
  return;
8327
+ if (this.renderIdentityTypeRefusal(result.errorCode, result.error))
8328
+ return;
8013
8329
  this.setState({
8014
8330
  view: 'error',
8015
8331
  message: result.error ?? 'Failed to send code',
@@ -8074,6 +8390,8 @@ class IdentityRenderer {
8074
8390
  // login. Mirrors the otp send path.
8075
8391
  if (this.renderBlockedInterstitial(result.errorCode))
8076
8392
  return;
8393
+ if (this.renderIdentityTypeRefusal(result.errorCode, result.error))
8394
+ return;
8077
8395
  this.setState({
8078
8396
  view: 'error',
8079
8397
  message: result.error ?? 'Failed to send SparkLink',
@@ -8153,6 +8471,7 @@ class IdentityRenderer {
8153
8471
  this.runPostLogin(result.result);
8154
8472
  }
8155
8473
  else if (this.renderBlockedInterstitial(result.errorCode)) ;
8474
+ else if (this.renderIdentityTypeRefusal(result.errorCode, result.error)) ;
8156
8475
  else if (result.errorCode === 'identity_locked') {
8157
8476
  // The identity is locked down — a dedicated, actionable state, not a
8158
8477
  // generic "invalid code" retry. The person must manage it at auth.sv.
@@ -8222,6 +8541,8 @@ class IdentityRenderer {
8222
8541
  }
8223
8542
  catch (error) {
8224
8543
  const message = error instanceof Error ? error.message : 'That code is not valid. Please try again.';
8544
+ if (error instanceof IdentityApiError && this.renderIdentityTypeRefusal(error.code, message))
8545
+ return;
8225
8546
  // The login ticket is not consumed on a wrong code, so the user can retry
8226
8547
  // against the same ticket — re-render the view carrying the error.
8227
8548
  this.setState({ view: 'two-factor', ticket, methods, error: message });
@@ -8283,6 +8604,9 @@ class IdentityRenderer {
8283
8604
  // Terminal interstitial already rendered — the owner must subscribe.
8284
8605
  return true;
8285
8606
  }
8607
+ if (this.renderIdentityTypeRefusal(result.errorCode, result.error)) {
8608
+ return true;
8609
+ }
8286
8610
  if (result.errorCode === 'identity_locked') {
8287
8611
  // Dedicated state — retrying cannot unlock the identity.
8288
8612
  this.setState({
@@ -8336,7 +8660,7 @@ class IdentityRenderer {
8336
8660
  passkeyFallbackMethodsAvailable() {
8337
8661
  if (!this.sdkConfig)
8338
8662
  return false;
8339
- const methods = enrichMethods(this.verificationState.methodIds, this.federation);
8663
+ const methods = this.admittedMethods(enrichMethods(this.verificationState.methodIds, this.federation));
8340
8664
  if (!this.recipient) {
8341
8665
  return methods.some((m) => m.type === 'social' || m.type === 'federation');
8342
8666
  }
@@ -8373,7 +8697,7 @@ class IdentityRenderer {
8373
8697
  this.setState({ view: 'oauth-pending', provider });
8374
8698
  const { state } = await this.api.drawAuthorizationValues();
8375
8699
  sessionStorage.setItem('sv_oauth_state', state);
8376
- const authUrl = this.api.getSocialAuthUrl(provider, currentPageReturnUrl(), state, this.verificationState.authContext, this.verificationState.signinRef);
8700
+ const authUrl = this.api.getSocialAuthUrl(provider, currentPageReturnUrl(), state, this.verificationState.authContext, { signinRef: this.verificationState.signinRef, identityTypes: this.verificationState.identityTypes });
8377
8701
  window.location.href = authUrl;
8378
8702
  }
8379
8703
  /**
@@ -8393,11 +8717,19 @@ class IdentityRenderer {
8393
8717
  get federationOffered() {
8394
8718
  return this.offeredWithoutReference || this.verificationState.signinRef !== null;
8395
8719
  }
8396
- /** The account's own identity provider while `/config` describes it and the verification's methods list it. */
8720
+ /**
8721
+ * The account's own identity provider while `/config` describes it, the
8722
+ * verification's methods list it, and the sign-in's restriction admits it.
8723
+ */
8397
8724
  get accountFederation() {
8398
8725
  const federation = this.sdkConfig?.federation;
8399
8726
  const methodIds = this.verificationState.methodIds;
8400
- return federation && Array.isArray(methodIds) && methodIds.includes('federation') ? federation : null;
8727
+ return federation
8728
+ && Array.isArray(methodIds)
8729
+ && methodIds.includes(FEDERATION_METHOD)
8730
+ && signinMethodAdmitted(FEDERATION_METHOD, this.verificationState.identityTypes)
8731
+ ? federation
8732
+ : null;
8401
8733
  }
8402
8734
  /**
8403
8735
  * Whether a list of methods offers the account's own identity provider
@@ -8440,7 +8772,7 @@ class IdentityRenderer {
8440
8772
  if (automatic)
8441
8773
  markFederationAutoStart(this.api.accountId);
8442
8774
  this.watchForPageRestore();
8443
- window.location.href = this.api.getFederationAuthUrl(currentPageReturnUrl(), state, this.verificationState.authContext, { silent, signinRef: this.verificationState.signinRef });
8775
+ window.location.href = this.api.getFederationAuthUrl(currentPageReturnUrl(), state, this.verificationState.authContext, { silent, signinRef: this.verificationState.signinRef, identityTypes: this.verificationState.identityTypes });
8444
8776
  }
8445
8777
  /**
8446
8778
  * A browser that restores this page from its back/forward cache, as the
@@ -8499,6 +8831,9 @@ class IdentityRenderer {
8499
8831
  */
8500
8832
  handleErrorWithRecovery(error, fallbackCode) {
8501
8833
  const err = this.normalizeError(error);
8834
+ if (err instanceof SparkVaultError && this.renderIdentityTypeRefusal(err.code, err.message)) {
8835
+ return;
8836
+ }
8502
8837
  if (this.isSessionExpiredError(err)) {
8503
8838
  // Session expired - let user start over
8504
8839
  this.showIdentityInput('Your session has expired. Please try again.');
@@ -9035,6 +9370,8 @@ class IdentityRenderer {
9035
9370
  }
9036
9371
  else {
9037
9372
  this.cleanupSparkLink();
9373
+ if (this.renderIdentityTypeRefusal(result.errorCode, result.error))
9374
+ return;
9038
9375
  this.setState({
9039
9376
  view: 'error',
9040
9377
  message: result.error ?? 'Failed to resend verification link. Please try again.',
@@ -9052,6 +9389,8 @@ class IdentityRenderer {
9052
9389
  if (!result.success) {
9053
9390
  if (this.renderBlockedInterstitial(result.errorCode))
9054
9391
  return;
9392
+ if (this.renderIdentityTypeRefusal(result.errorCode, result.error))
9393
+ return;
9055
9394
  this.setState({
9056
9395
  view: 'error',
9057
9396
  message: result.error ?? 'Failed to send code',
@@ -11582,7 +11921,7 @@ function attachClickHandler(selector, onClick) {
11582
11921
  * message listener but not sessionStorage) recover it on its next load, for
11583
11922
  * at most SIGNIN_RECOVERY.pendingTtlMs.
11584
11923
  *
11585
- * `sv_signin_pending` holds JSON `{ at, hint, ref }`:
11924
+ * `sv_signin_pending` holds JSON `{ at, hint, ref, identity_types }`:
11586
11925
  * - `at`: when the current popup opened, on this browser's clock; the
11587
11926
  * marker's TTL.
11588
11927
  * - `hint`: the email or phone the sign-in started with, or null when the
@@ -11591,14 +11930,20 @@ function attachClickHandler(selector, onClick) {
11591
11930
  * once drawn and written; the recovery bounce names it, and `/sso` then
11592
11931
  * mints only when the hub session it would mint from carries it. A marker
11593
11932
  * without one bounces with no reference.
11933
+ * - `identity_types` (SIGNIN_IDENTITY_TYPES.param): the sign-in's restriction
11934
+ * on the identity types it may produce, in its one spelling, present only
11935
+ * when the sign-in named one; the recovery bounce names it, so `/sso` mints
11936
+ * only a type the sign-in accepts.
11594
11937
  */
11595
11938
  const PENDING_KEY = 'sv_signin_pending';
11596
11939
  /**
11597
11940
  * Read and parse the pending marker. Anything unreadable yields null: a value
11598
- * that is not a JSON object, an `at` that is no finite number, or a `ref`
11599
- * that is present but no sign-in reference. A recovery that cannot name the
11600
- * reference its marker records could mint any hub session in this browser, so
11601
- * such a marker recovers nothing.
11941
+ * that is not a JSON object, an `at` that is no finite number, a `ref` that
11942
+ * is present but no sign-in reference, or a restriction that is present but
11943
+ * not in its spelling. A recovery that cannot name the reference its marker
11944
+ * records could mint any hub session in this browser, and one that cannot
11945
+ * name its restriction could mint a type its sign-in refuses, so such a
11946
+ * marker recovers nothing.
11602
11947
  */
11603
11948
  function readPendingMarker() {
11604
11949
  let raw = null;
@@ -11629,10 +11974,15 @@ function readPendingMarker() {
11629
11974
  if (ref !== undefined && !isSigninReference(ref)) {
11630
11975
  return null;
11631
11976
  }
11977
+ const identityTypes = marker[SIGNIN_IDENTITY_TYPES.param];
11978
+ if (!readSigninIdentityTypes(identityTypes).ok) {
11979
+ return null;
11980
+ }
11632
11981
  return {
11633
11982
  at: marker.at,
11634
11983
  hint: typeof marker.hint === 'string' && marker.hint ? marker.hint : null,
11635
11984
  ref: typeof ref === 'string' ? ref : null,
11985
+ identityTypes: typeof identityTypes === 'string' ? identityTypes : null,
11636
11986
  };
11637
11987
  }
11638
11988
  /** True while a marker is within the recovery TTL. */
@@ -11671,8 +12021,13 @@ function signinReferenceInTime(draw) {
11671
12021
  * hold a reference the marker does not.
11672
12022
  */
11673
12023
  class PendingSignIn {
11674
- constructor(hint) {
12024
+ /**
12025
+ * @param hint - The identifier the sign-in started with, or null
12026
+ * @param identityTypes - The sign-in's restriction in its one spelling, or null for none
12027
+ */
12028
+ constructor(hint, identityTypes) {
11675
12029
  this.hint = hint;
12030
+ this.identityTypes = identityTypes;
11676
12031
  this.at = 0;
11677
12032
  this.ended = false;
11678
12033
  // Counts the opens and the ends of their popups, so a draw that lands after
@@ -11756,7 +12111,12 @@ class PendingSignIn {
11756
12111
  }
11757
12112
  /** Write the marker; a write that fails leaves the stored marker as it was. */
11758
12113
  write(reference) {
11759
- const marker = { at: this.at, hint: this.hint, ...(reference ? { ref: reference } : {}) };
12114
+ const marker = {
12115
+ at: this.at,
12116
+ hint: this.hint,
12117
+ ...(reference ? { ref: reference } : {}),
12118
+ ...(this.identityTypes ? { [SIGNIN_IDENTITY_TYPES.param]: this.identityTypes } : {}),
12119
+ };
11760
12120
  try {
11761
12121
  sessionStorage.setItem(PENDING_KEY, JSON.stringify(marker));
11762
12122
  }
@@ -11917,7 +12277,11 @@ class IdentityModule {
11917
12277
  * the chooser, or the browser had no SparkVault account to offer (the
11918
12278
  * browser reports both alike). Throws `IdentityProviderError`, carrying
11919
12279
  * SparkVault's own error code, when SparkVault answered the sign-in with an
11920
- * error.
12280
+ * error (`IDENTITY_TYPE_NOT_ALLOWED` for an account of a type
12281
+ * `identityTypes` does not name).
12282
+ *
12283
+ * `identityTypes` restricts the sign-in as `SignInOptions.identityTypes`
12284
+ * does; a bad value is a ValidationError before anything is asked.
11921
12285
  *
11922
12286
  * @example
11923
12287
  * const result = IdentityModule.isFedcmAvailable()
@@ -11925,6 +12289,7 @@ class IdentityModule {
11925
12289
  * : await sv.products.identity.signIn();
11926
12290
  */
11927
12291
  async signInWithFedcm(options = {}) {
12292
+ const identityTypes = callerIdentityTypes(options.identityTypes);
11928
12293
  if (!IdentityModule.isFedcmAvailable()) {
11929
12294
  return null;
11930
12295
  }
@@ -11938,8 +12303,16 @@ class IdentityModule {
11938
12303
  // cookie lives) — not the auth.sv portal. The config, its endpoints, and
11939
12304
  // the credentialed accounts fetch must all be same-origin with that cookie.
11940
12305
  const configURL = `${this.config.identityBaseUrl}/${this.config.accountId}/fedcm/config.json`;
12306
+ // A restriction rides the provider's `params`, which the browser hands the
12307
+ // id-assertion endpoint; a sign-in that names none sends no `params`.
12308
+ const provider = {
12309
+ configURL,
12310
+ clientId: this.config.clientId,
12311
+ nonce,
12312
+ ...(identityTypes ? { params: identityTypesParam(identityTypes) } : {}),
12313
+ };
11941
12314
  const request = {
11942
- identity: { providers: [{ configURL, clientId: this.config.clientId, nonce }] },
12315
+ identity: { providers: [provider] },
11943
12316
  ...(options.mediation ? { mediation: options.mediation } : {}),
11944
12317
  };
11945
12318
  let credential;
@@ -12006,17 +12379,31 @@ class IdentityModule {
12006
12379
  * });
12007
12380
  */
12008
12381
  async signIn(options = {}) {
12009
- return this.runFlow(options);
12382
+ // Read before anything closes or opens, inside the caller's gesture: a
12383
+ // bad restriction is the caller's error, never a narrower or wider
12384
+ // sign-in than it asked for.
12385
+ let identityTypes;
12386
+ try {
12387
+ identityTypes = callerIdentityTypes(options.identityTypes);
12388
+ }
12389
+ catch (error) {
12390
+ const err = error instanceof Error ? error : new Error(String(error));
12391
+ options.onError?.(err);
12392
+ throw err;
12393
+ }
12394
+ return this.runFlow(options, { ok: true, types: identityTypes });
12010
12395
  }
12011
12396
  /**
12012
12397
  * Core flow runner. Default mode (no `target`) opens the popup; `flow:
12013
12398
  * 'redirect'` navigates the tab instead; local mode (`renderMode: 'local'` /
12014
12399
  * `target`) renders into the current document and powers the
12015
12400
  * SparkVault-hosted sign-in surfaces (see the internal `render`), which
12016
- * hands it what a round trip to the account's own identity provider
12017
- * returned (`federationReturn`).
12401
+ * hands it its restriction as its page's URL spelled it (`identityTypes`)
12402
+ * and what a round trip to the account's own identity provider returned
12403
+ * (`federationReturn`). The popup and the redirect carry the restriction
12404
+ * `options.identityTypes` names, which signIn() validated.
12018
12405
  */
12019
- async runFlow(options = {}, federationReturn = null) {
12406
+ async runFlow(options, identityTypes, federationReturn = null) {
12020
12407
  this.closeLauncher();
12021
12408
  if (this.renderer) {
12022
12409
  this.renderer.close();
@@ -12060,7 +12447,7 @@ class IdentityModule {
12060
12447
  },
12061
12448
  };
12062
12449
  const startLocalRender = (container) => {
12063
- this.renderer = new IdentityRenderer(container, this.api, mergedOptions, hostCallbacks, federationReturn);
12450
+ this.renderer = new IdentityRenderer(container, this.api, mergedOptions, hostCallbacks, federationReturn, identityTypes);
12064
12451
  this.renderer.start().catch((error) => {
12065
12452
  // A startup failure must surface inside the SparkVault dialog, never
12066
12453
  // close it silently. Render the error in-dialog instead (consistent with
@@ -12101,7 +12488,7 @@ class IdentityModule {
12101
12488
  // handleRedirectResult() can silently self-heal on the next load from
12102
12489
  // the SSO session the popup signed in or chose, which that popup's
12103
12490
  // reference names (see pending-signin.ts).
12104
- const pending = new PendingSignIn(mergedOptions.email || mergedOptions.phone || null);
12491
+ const pending = new PendingSignIn(mergedOptions.email || mergedOptions.phone || null, mergedOptions.identityTypes ? formatSigninIdentityTypes(mergedOptions.identityTypes) : null);
12105
12492
  this.pendingSignIn = pending;
12106
12493
  const launcher = new DialogLauncher(this.config, this.api, mergedOptions, {
12107
12494
  onSuccess: (result) => { pending.end(); hostCallbacks.onSuccess(result); },
@@ -12170,6 +12557,7 @@ class IdentityModule {
12170
12557
  authContext: options.authContext,
12171
12558
  prompt: options.prompt,
12172
12559
  method: options.method,
12560
+ identityTypes: options.identityTypes,
12173
12561
  onSuccess: options.onSuccess,
12174
12562
  onError: options.onError,
12175
12563
  onCancel: options.onCancel,
@@ -12379,6 +12767,11 @@ class IdentityModule {
12379
12767
  if (pending.ref) {
12380
12768
  sso.searchParams.set(SIGNIN_REFERENCE.param, pending.ref);
12381
12769
  }
12770
+ // The sign-in's restriction, so /sso mints only a type it accepts: a
12771
+ // recovery mints what the sign-in itself would have, never wider.
12772
+ if (pending.identityTypes) {
12773
+ sso.searchParams.set(SIGNIN_IDENTITY_TYPES.param, pending.identityTypes);
12774
+ }
12382
12775
  sso.searchParams.set('redirect_uri', handoff.redirectUri);
12383
12776
  sso.searchParams.set('state', handoff.state);
12384
12777
  sso.searchParams.set('code_challenge', handoff.codeChallenge);
@@ -12639,6 +13032,9 @@ class IdentityModule {
12639
13032
  * account's own identity provider is handed to the flow it starts (see
12640
13033
  * `consumeFederationReturn`).
12641
13034
  *
13035
+ * The page hands its restriction as its URL spelled it (`identityTypes`),
13036
+ * which the flow reads here: a spelling it cannot read shows as an error.
13037
+ *
12642
13038
  * @internal Used only by the SparkVault-hosted sign-in popup and hosted login
12643
13039
  * page (which own their chrome and pass `renderMode: 'local'`). Customer
12644
13040
  * integrations have no inline mode — use `signIn()` / `attach()`.
@@ -12649,7 +13045,8 @@ class IdentityModule {
12649
13045
  options.onSuccess?.(returned);
12650
13046
  return returned;
12651
13047
  }
12652
- return this.runFlow(options, this.consumeFederationReturn());
13048
+ const { identityTypes, ...flowOptions } = options;
13049
+ return this.runFlow(flowOptions, readSigninIdentityTypes(identityTypes), this.consumeFederationReturn());
12653
13050
  }
12654
13051
  }
12655
13052
 
@@ -17546,6 +17943,36 @@ function mapInvitation(wire) {
17546
17943
 
17547
17944
  /** The native support ceremony. Identity receipts stay inside the first-party window. */
17548
17945
  const VALUE = /^[A-Za-z0-9_-]{43}$/;
17946
+ /** The website's own opener policy cut the window off: no retry on this page can work, only its owner can fix it. */
17947
+ const SEVERED_MESSAGE = 'This website stops the support sign-in window from reporting back, so sign-in cannot finish here. Let the website\'s owner know.';
17948
+ /** How often the sign-in window's handle is checked once it leaves for the sign-in page. */
17949
+ const HANDLE_CHECK_MS = 500;
17950
+ /**
17951
+ * What a sign-in window's handle reading `closed` before its page's ready
17952
+ * message means. A website serving `Cross-Origin-Opener-Policy: same-origin`
17953
+ * severs the window the moment its auth.sv page loads: the handle reads
17954
+ * `closed` while the window stays open in front of the person, showing that
17955
+ * page's own "not connected" notice. So:
17956
+ * - the website's page holding focus again means the person closed the
17957
+ * window and is back on it: a cancellation;
17958
+ * - a handle that reads `closed` at the first check after the window left
17959
+ * for the sign-in page, while the website's page still lacks focus, is a
17960
+ * severance: the window is still in front of the person, for no person
17961
+ * closes it that fast and then leaves the website;
17962
+ * - anything else cannot be told apart (a severance on a slow load, or a
17963
+ * person who closed the window and moved on): a retryable failure that
17964
+ * blames no one.
17965
+ * The ready message proves the website still holds the window, so after it
17966
+ * a closed handle decides nothing: a browser can sever the window during the
17967
+ * Identity round trip, which the result polling still completes.
17968
+ */
17969
+ function closedBeforeReady(firstCheck) {
17970
+ if (document.hasFocus())
17971
+ return new UserCancelledError();
17972
+ if (firstCheck)
17973
+ return new PopupSeveredError(SEVERED_MESSAGE);
17974
+ return new SparkVaultError('Support sign-in did not start. Try again.', 'HELP_DESK_WIDGET_SIGN_IN_INTERRUPTED');
17975
+ }
17549
17976
  /** Open synchronously inside the user's gesture, before preparing the server challenge. */
17550
17977
  function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
17551
17978
  if (!isHelpDeskId(deskId))
@@ -17568,6 +17995,7 @@ function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
17568
17995
  let settled = false;
17569
17996
  let checking = false;
17570
17997
  let interval;
17998
+ let watch;
17571
17999
  const timeout = setTimeout(() => finish(new SparkVaultError('Support sign-in expired. Try again.', 'HELP_DESK_WIDGET_SIGN_IN_EXPIRED')), 15 * 60 * 1000);
17572
18000
  const finish = (error, session) => {
17573
18001
  if (settled)
@@ -17576,6 +18004,8 @@ function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
17576
18004
  clearTimeout(timeout);
17577
18005
  if (interval)
17578
18006
  clearInterval(interval);
18007
+ if (watch)
18008
+ clearInterval(watch);
17579
18009
  window.removeEventListener('message', receive);
17580
18010
  options.signal?.removeEventListener('abort', cancel);
17581
18011
  try {
@@ -17610,6 +18040,8 @@ function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
17610
18040
  // at the first-party origin, is ever answered, so a sign-in link opened
17611
18041
  // in any other window or browser completes nothing.
17612
18042
  if (data.type === HELP_DESK_WIDGET_IDENTITY_MESSAGES.ready) {
18043
+ if (watch)
18044
+ clearInterval(watch);
17613
18045
  popup.postMessage({ type: HELP_DESK_WIDGET_IDENTITY_MESSAGES.state, challenge_id: challenge.challenge_id, state: challenge.state }, event.origin);
17614
18046
  return;
17615
18047
  }
@@ -17632,9 +18064,24 @@ function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
17632
18064
  url.protocol !== 'https:' || url.origin !== 'https://auth.sv' || url.username || url.password || url.search || url.hash ||
17633
18065
  url.pathname !== `/help-desk/${deskId}/${value.challenge_id}`)
17634
18066
  throw new SparkVaultError('The support sign-in address is invalid.', 'HELP_DESK_INVALID_RESPONSE');
18067
+ // The window still holds this page's own placeholder, which no opener
18068
+ // policy severs: closed now, the person closed it.
18069
+ if (popup.closed) {
18070
+ cancel();
18071
+ return;
18072
+ }
17635
18073
  challenge = value;
17636
18074
  firstPartyOrigin = url.origin;
17637
18075
  popup.location.replace(url.href);
18076
+ // A window whose handle dies before its page asks for the state can
18077
+ // never be handed it, so the sign-in ends at once (closedBeforeReady)
18078
+ // rather than polling until the challenge expires.
18079
+ let checks = 0;
18080
+ watch = setInterval(() => {
18081
+ checks += 1;
18082
+ if (popup.closed)
18083
+ finish(closedBeforeReady(checks === 1));
18084
+ }, HANDLE_CHECK_MS);
17638
18085
  // Code delivery must survive a browser severing window.opener during
17639
18086
  // the first-party Identity redirect. Polling knows only the original
17640
18087
  // challenge and verifier; no Identity JWT ever reaches this page.
@@ -31001,7 +31448,7 @@ class SparkVault {
31001
31448
  }
31002
31449
  /** Get the SDK version */
31003
31450
  static get version() {
31004
- return '16.10.0';
31451
+ return '16.11.0';
31005
31452
  }
31006
31453
  }
31007
31454
  if (typeof window !== 'undefined') {
@@ -31011,5 +31458,5 @@ if (typeof window !== 'undefined') {
31011
31458
  window.SparkVault = instance ?? SparkVault;
31012
31459
  }
31013
31460
 
31014
- export { AuthenticationError, AuthorizationError, EntropyModule, FoldersModule, HelpDeskClient, HelpDeskModule, IdentityModule, IdentityProviderError, IngotsModule, MessagingModule, NAME_CONFLICT_POLICIES, NOTIFY_PRESETS, NetworkError, NotifyModule, NotifyProductModule, NotifyProjectsModule, NotifySubscriptionRequiredError, PlanRequiredError, PopupBlockedError, ProductsModule, QuotaExceededError, SparkVault, SparkVaultError, SparksModule, StructuredIngotTypesModule, StructuredIngotsModule, TimeoutError, UnauthorizedError, UsageCreditFundingReviewError, UsageCreditsExhaustedError, UserCancelledError, ValidationError, VaultsModule, buildNotifyPresetSend, SparkVault as default, fetchDownload, isReceivedUploadFailure, logger, setDebugMode };
31461
+ export { AuthenticationError, AuthorizationError, EntropyModule, FoldersModule, HelpDeskClient, HelpDeskModule, IdentityModule, IdentityProviderError, IngotsModule, MessagingModule, NAME_CONFLICT_POLICIES, NOTIFY_PRESETS, NetworkError, NotifyModule, NotifyProductModule, NotifyProjectsModule, NotifySubscriptionRequiredError, PlanRequiredError, PopupBlockedError, PopupSeveredError, ProductsModule, QuotaExceededError, SparkVault, SparkVaultError, SparksModule, StructuredIngotTypesModule, StructuredIngotsModule, TimeoutError, UnauthorizedError, UsageCreditFundingReviewError, UsageCreditsExhaustedError, UserCancelledError, ValidationError, VaultsModule, buildNotifyPresetSend, SparkVault as default, fetchDownload, isReceivedUploadFailure, logger, setDebugMode };
31015
31462
  //# sourceMappingURL=index.mjs.map