@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.cjs CHANGED
@@ -944,15 +944,17 @@ class PopupBlockedError extends SparkVaultError {
944
944
  }
945
945
  /**
946
946
  * The popup opened but its window handle went dead before the page ever
947
- * pinged back — the signature of a Cross-Origin-Opener-Policy severance
948
- * (a host page serving `COOP: same-origin` detaches any cross-origin popup:
949
- * the popup loses `window.opener`, the opener's handle reports `closed`).
950
- * postMessage can never work in this state, so retrying the popup is futile;
951
- * callers should fall back to the redirect flow.
947
+ * pinged back: the host page's Cross-Origin-Opener-Policy severed it (a host
948
+ * page serving `COOP: same-origin` detaches any cross-origin popup: the popup
949
+ * loses `window.opener`, the opener's handle reports `closed`). postMessage
950
+ * can never work in this state, so retrying the popup is futile. Identity
951
+ * sign-in falls back to the redirect flow (popup-launcher.ts); the help desk
952
+ * widget's sign-in, which has none, passes a message that tells the person
953
+ * what to do (help-desk/widget-identity.ts).
952
954
  */
953
955
  class PopupSeveredError extends SparkVaultError {
954
- constructor() {
955
- super('The sign-in window could not communicate with this page.', 'popup_severed');
956
+ constructor(message = 'The sign-in window could not communicate with this page.') {
957
+ super(message, 'popup_severed');
956
958
  this.name = 'PopupSeveredError';
957
959
  Object.setPrototypeOf(this, PopupSeveredError.prototype);
958
960
  }
@@ -2230,6 +2232,10 @@ function identityDrawBytes(answer, numBytes) {
2230
2232
  * naming that reference, and the recovery may only veto: it mints what the
2231
2233
  * same call without a reference would, and only when that hub session
2232
2234
  * carries this sign-in's reference.
2235
+ * - A sign-in may name the identity types it accepts (SIGNIN_IDENTITY_TYPES):
2236
+ * its page offers only the methods that can produce one, and Identity
2237
+ * records the restriction where each sign-in starts and refuses a sign-in
2238
+ * of any other type before it is counted, billed or minted.
2233
2239
  *
2234
2240
  * Browser-safe and dependency-free: the JS SDK bundles this module, and the
2235
2241
  * sign-in shells inline federationRefusalIn's own source into their pages.
@@ -2357,6 +2363,138 @@ function isSigninReference(value) {
2357
2363
  return typeof value === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value);
2358
2364
  }
2359
2365
 
2366
+ /**
2367
+ * A sign-in's restriction on the identity types it may produce (the
2368
+ * `identity_type` its token carries): a caller that takes only some types
2369
+ * names them, and Identity refuses a sign-in of any other type, before it is
2370
+ * counted, billed or minted, with `refusalCode`. A restriction only refuses:
2371
+ * it never chooses which of a person's identifiers a sign-in carries, so a
2372
+ * sign-in it admits carries exactly what an unrestricted one would. A
2373
+ * sign-in that names none is unrestricted. An OIDC authorization or a verify
2374
+ * session carries its client's own policy and takes no restriction.
2375
+ *
2376
+ * - `param`: the name it travels under, spelled as formatSigninIdentityTypes
2377
+ * writes it: in a query (the sign-in page's URL, a provider start,
2378
+ * `/sso`, `/sso/accounts`), in a JSON body (each call that starts a
2379
+ * ceremony, `/sso/continue`), and in a FedCM request's `params`.
2380
+ * - `values`: the types, in the one order every spelling lists them.
2381
+ * - `refusalCode`: the error code of a refused sign-in, whose message
2382
+ * signinIdentityTypesRefusal words.
2383
+ *
2384
+ * Identity records the restriction where each ceremony starts (the code it
2385
+ * sends, the passkey challenge, the provider round trip's state, the second
2386
+ * factor's ticket) and reads it from there at completion, never from the
2387
+ * completing request, so a later step cannot widen it. A caller's own check
2388
+ * of the token stays its final gate: a page that drops the parameter gets an
2389
+ * unrestricted sign-in, which that check refuses.
2390
+ */
2391
+ const SIGNIN_IDENTITY_TYPES = Object.freeze({
2392
+ param: 'identity_types',
2393
+ values: Object.freeze(['email', 'phone', 'social', 'federated']),
2394
+ refusalCode: 'IDENTITY_TYPE_NOT_ALLOWED'
2395
+ });
2396
+
2397
+ /**
2398
+ * A restriction as its one spelling writes it: its types, comma-separated, in
2399
+ * SIGNIN_IDENTITY_TYPES.values order.
2400
+ *
2401
+ * @param {string[]} types - At least one of SIGNIN_IDENTITY_TYPES.values
2402
+ * @returns {string}
2403
+ * @throws {TypeError} For an empty list or a type outside the values
2404
+ */
2405
+ function formatSigninIdentityTypes(types) {
2406
+ if (!Array.isArray(types) || types.length === 0 || !types.every((type) => SIGNIN_IDENTITY_TYPES.values.includes(type))) {
2407
+ throw new TypeError(`identity types must name at least one of ${SIGNIN_IDENTITY_TYPES.values.join(', ')}`);
2408
+ }
2409
+ return SIGNIN_IDENTITY_TYPES.values.filter((type) => types.includes(type)).join(',');
2410
+ }
2411
+
2412
+ /**
2413
+ * Read a restriction as it arrived: absent (`undefined` or `null`) is no
2414
+ * restriction; anything else must be its spelling (formatSigninIdentityTypes),
2415
+ * whose types it answers in values order.
2416
+ *
2417
+ * @param {unknown} raw
2418
+ * @returns {{ ok: true, types: string[]|null } | { ok: false }}
2419
+ */
2420
+ function readSigninIdentityTypes(raw) {
2421
+ if (raw === undefined || raw === null) return { ok: true, types: null };
2422
+ if (typeof raw !== 'string') return { ok: false };
2423
+ const named = raw.split(',');
2424
+ if (!named.every((type) => SIGNIN_IDENTITY_TYPES.values.includes(type)) || new Set(named).size !== named.length) return { ok: false };
2425
+ return { ok: true, types: SIGNIN_IDENTITY_TYPES.values.filter((type) => named.includes(type)) };
2426
+ }
2427
+
2428
+ /**
2429
+ * Whether a restriction admits an identity type: no restriction admits every
2430
+ * type, and a restriction admits the types it names.
2431
+ *
2432
+ * @param {string} identityType
2433
+ * @param {string[]|null} types - A restriction readSigninIdentityTypes read
2434
+ * @returns {boolean}
2435
+ */
2436
+ function signinIdentityTypeAdmitted(identityType, types) {
2437
+ return types === null || types.includes(identityType);
2438
+ }
2439
+
2440
+ /**
2441
+ * The identity types a sign-in by `methodId` can produce: a code to an
2442
+ * address or a SparkLink signs in by email, a code to a phone by phone, a
2443
+ * social provider by social, an enterprise (SAML) provider by the email it
2444
+ * asserts, the account's own identity provider by federated, and a passkey by
2445
+ * the person's primary identifier (the first of email, phone and social they
2446
+ * hold, whatever the restriction names: a restriction only refuses one it
2447
+ * excludes). An unknown method produces none.
2448
+ *
2449
+ * @param {string} methodId
2450
+ * @returns {string[]}
2451
+ */
2452
+ function signinMethodIdentityTypes(methodId) {
2453
+ if (methodId === 'otp_email' || methodId === 'sparklink') return ['email'];
2454
+ if (methodId === 'otp_sms' || methodId === 'otp_voice') return ['phone'];
2455
+ if (methodId === 'passkey') return ['email', 'phone', 'social'];
2456
+ if (methodId === FEDERATION_METHOD) return ['federated'];
2457
+ if (typeof methodId === 'string' && methodId.startsWith('social_')) return ['social'];
2458
+ if (typeof methodId === 'string' && methodId.startsWith('enterprise_')) return ['email'];
2459
+ return [];
2460
+ }
2461
+
2462
+ /**
2463
+ * Whether a restriction admits a method: no restriction admits every method,
2464
+ * and a restriction admits one that can produce a type it names.
2465
+ *
2466
+ * @param {string} methodId
2467
+ * @param {string[]|null} types - A restriction readSigninIdentityTypes read
2468
+ * @returns {boolean}
2469
+ */
2470
+ function signinMethodAdmitted(methodId, types) {
2471
+ return types === null || signinMethodIdentityTypes(methodId).some((type) => signinIdentityTypeAdmitted(type, types));
2472
+ }
2473
+
2474
+ const IDENTITY_TYPE_WORDS = Object.freeze({
2475
+ email: 'an email address',
2476
+ phone: 'a phone number',
2477
+ social: 'a social account',
2478
+ federated: "your organization's sign-in"
2479
+ });
2480
+
2481
+ /** The types a restriction accepts, in words: "a, b or c". */
2482
+ function acceptedTypesInWords(types) {
2483
+ const words = types.map((type) => IDENTITY_TYPE_WORDS[type]);
2484
+ return words.length === 1 ? words[0] : `${words.slice(0, -1).join(', ')} or ${words[words.length - 1]}`;
2485
+ }
2486
+
2487
+ /**
2488
+ * What a sign-in page with no method its restriction admits says instead of
2489
+ * an empty list.
2490
+ *
2491
+ * @param {string[]} types - A restriction readSigninIdentityTypes read
2492
+ * @returns {string}
2493
+ */
2494
+ function signinIdentityTypesUnavailable(types) {
2495
+ 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.`;
2496
+ }
2497
+
2360
2498
  /**
2361
2499
  * Request paths: the one way a module names a SparkVault route.
2362
2500
  *
@@ -2536,6 +2674,40 @@ class ExpirationTimer {
2536
2674
  function arrayBufferToBase64url(buffer) {
2537
2675
  return bytesToBase64url(new Uint8Array(buffer));
2538
2676
  }
2677
+ /**
2678
+ * The restriction a caller's `identityTypes` option names, in the contract's
2679
+ * one order, or null when it names none. Synchronous, so a sign-in refuses a
2680
+ * bad value before it opens anything.
2681
+ *
2682
+ * @throws {ValidationError} For a value that is no list of at least one
2683
+ * SigninIdentityType
2684
+ */
2685
+ function callerIdentityTypes(identityTypes) {
2686
+ if (identityTypes === undefined)
2687
+ return null;
2688
+ const refusal = () => new ValidationError(`identityTypes must name at least one of ${SIGNIN_IDENTITY_TYPES.values.join(', ')}`, { field: 'identityTypes', received: identityTypes });
2689
+ let spelling;
2690
+ try {
2691
+ spelling = formatSigninIdentityTypes(identityTypes);
2692
+ }
2693
+ catch {
2694
+ throw refusal();
2695
+ }
2696
+ // A value that names a restriction never runs as none: anything the
2697
+ // spelling does not read back as one is the caller's error too.
2698
+ const read = readSigninIdentityTypes(spelling);
2699
+ if (!read.ok || read.types === null)
2700
+ throw refusal();
2701
+ return read.types;
2702
+ }
2703
+ /**
2704
+ * The restriction as the wire carries it, `{ identity_types: <spelling> }`,
2705
+ * or nothing for none: a sign-in that names no restriction sends no field,
2706
+ * and Identity applies none.
2707
+ */
2708
+ function identityTypesParam(types) {
2709
+ return types ? { [SIGNIN_IDENTITY_TYPES.param]: formatSigninIdentityTypes(types) } : {};
2710
+ }
2539
2711
  /**
2540
2712
  * This page as a navigation return target: origin, path, and query — the query
2541
2713
  * carries the page's own state (app routing, or the sign-in page's validated
@@ -2581,6 +2753,11 @@ function buildSigninUrl(config, options, delivery) {
2581
2753
  if (options.method === FEDERATION_METHOD) {
2582
2754
  params.set(SIGNIN_METHOD_PARAM, FEDERATION_METHOD);
2583
2755
  }
2756
+ // The restriction the caller named, validated before anything opened
2757
+ // (callerIdentityTypes), in its one spelling.
2758
+ if (options.identityTypes) {
2759
+ params.set(SIGNIN_IDENTITY_TYPES.param, formatSigninIdentityTypes(options.identityTypes));
2760
+ }
2584
2761
  if (delivery.kind === 'popup') {
2585
2762
  params.set(SIGNIN_REFERENCE.fromOpenerParam, SIGNIN_REFERENCE.fromOpenerValue);
2586
2763
  }
@@ -2779,13 +2956,16 @@ class IdentityApi extends SparkVaultApi {
2779
2956
  };
2780
2957
  }
2781
2958
  /**
2782
- * Send OTP code to email or phone
2959
+ * Send OTP code to email or phone. The send starts the ceremony, so it
2960
+ * carries the sign-in's restriction, which Identity records on the code and
2961
+ * reads again at /otp/verify: the verify never names it.
2783
2962
  */
2784
2963
  async sendOtp(params) {
2785
2964
  return this.request('POST', apiPath `/otp/send`, {
2786
2965
  recipient: params.recipient,
2787
2966
  method: params.method,
2788
2967
  ...this.buildAuthContextParams(params.authContext),
2968
+ ...identityTypesParam(params.identityTypes ?? null),
2789
2969
  });
2790
2970
  }
2791
2971
  /**
@@ -2817,13 +2997,19 @@ class IdentityApi extends SparkVaultApi {
2817
2997
  * optional identifier scopes the ceremony to that person's credentials
2818
2998
  * (`allowCredentials`) so the authenticator offers only the matching passkey;
2819
2999
  * omit it for a discoverable ceremony. Completion always routes via the
2820
- * credential userHandle, so scoping is purely a hint.
3000
+ * credential userHandle, so scoping is purely a hint. The start carries the
3001
+ * sign-in's restriction, which Identity records on the challenge's session
3002
+ * and reads again at completion.
2821
3003
  */
2822
- async startPasskeyVerify(identity, identityType = 'email', authContext) {
3004
+ async startPasskeyVerify(identity, identityType = 'email', authContext, identityTypes = null) {
2823
3005
  const identityParam = identity ? { [identityType]: identity } : {};
2824
3006
  // Backend returns { options: PublicKeyCredentialRequestOptions, session: {...} }
2825
3007
  // Extract and flatten to match PasskeyChallengeResponse
2826
- const response = await this.request('POST', apiPath `/passkey/verify`, { ...identityParam, ...verifySessionParam(authContext) });
3008
+ const response = await this.request('POST', apiPath `/passkey/verify`, {
3009
+ ...identityParam,
3010
+ ...verifySessionParam(authContext),
3011
+ ...identityTypesParam(identityTypes),
3012
+ });
2827
3013
  return {
2828
3014
  challenge: response.options.challenge,
2829
3015
  rpId: response.options.rpId,
@@ -2895,13 +3081,15 @@ class IdentityApi extends SparkVaultApi {
2895
3081
  /**
2896
3082
  * Get OAuth redirect URL for social provider. The start carries the
2897
3083
  * sign-in's reference, when it has one, so the hub session the provider's
2898
- * answer creates or chooses records it.
3084
+ * answer creates or chooses records it, and the sign-in's restriction, which
3085
+ * Identity records in the round trip's state.
2899
3086
  */
2900
- getSocialAuthUrl(provider, redirectUri, state, authContext, signinRef) {
3087
+ getSocialAuthUrl(provider, redirectUri, state, authContext, options = {}) {
2901
3088
  const params = new URLSearchParams({
2902
3089
  [START_PARAMS.redirectUri]: redirectUri,
2903
3090
  [START_PARAMS.state]: state,
2904
- ...signinRefParam(signinRef),
3091
+ ...signinRefParam(options.signinRef),
3092
+ ...identityTypesParam(options.identityTypes ?? null),
2905
3093
  });
2906
3094
  if (authContext?.authRequestId) {
2907
3095
  params.set(START_PARAMS.authRequestId, authContext.authRequestId);
@@ -2920,15 +3108,17 @@ class IdentityApi extends SparkVaultApi {
2920
3108
  * showing anything. The start carries the sign-in's reference, when it has
2921
3109
  * one: such a sign-in opens no hub session, so Identity releases that
2922
3110
  * reference from the browser's hub sessions on its completion, and a
2923
- * recovery naming it mints none of them. A verify session is never named:
2924
- * such a sign-in cannot complete one, so its start refuses it, and a verify
2925
- * session never admits the method.
3111
+ * recovery naming it mints none of them. It carries the sign-in's
3112
+ * restriction too, which Identity records in the round trip's state. A
3113
+ * verify session is never named: such a sign-in cannot complete one, so its
3114
+ * start refuses it, and a verify session never admits the method.
2926
3115
  */
2927
3116
  getFederationAuthUrl(redirectUri, state, authContext, options = {}) {
2928
3117
  const params = new URLSearchParams({
2929
3118
  [START_PARAMS.redirectUri]: redirectUri,
2930
3119
  [START_PARAMS.state]: state,
2931
3120
  ...signinRefParam(options.signinRef),
3121
+ ...identityTypesParam(options.identityTypes ?? null),
2932
3122
  });
2933
3123
  if (authContext?.authRequestId) {
2934
3124
  params.set(START_PARAMS.authRequestId, authContext.authRequestId);
@@ -2940,14 +3130,17 @@ class IdentityApi extends SparkVaultApi {
2940
3130
  }
2941
3131
  /**
2942
3132
  * Send SparkLink email for identity verification.
2943
- * Includes connectionId for WebSocket push notification of verification result.
3133
+ * Includes connectionId for WebSocket push notification of verification
3134
+ * result. The send starts the ceremony, so it carries the sign-in's
3135
+ * restriction, which Identity records for the link's click.
2944
3136
  */
2945
- async sendSparkLink(email, connectionId, authContext, signinRef) {
3137
+ async sendSparkLink(email, connectionId, authContext, signinRef, identityTypes = null) {
2946
3138
  return this.request('POST', apiPath `/sparklink/send`, {
2947
3139
  email,
2948
3140
  connection_id: connectionId,
2949
3141
  ...this.buildAuthContextParams(authContext),
2950
3142
  ...signinRefParam(signinRef),
3143
+ ...identityTypesParam(identityTypes),
2951
3144
  });
2952
3145
  }
2953
3146
  /**
@@ -3446,6 +3639,9 @@ class VerificationState {
3446
3639
  this._authContext = undefined;
3447
3640
  // The sign-in's reference (app-sdk SIGNIN_REFERENCE), when the sign-in page has one
3448
3641
  this._signinRef = null;
3642
+ // The sign-in's restriction on the identity types it may produce (app-sdk
3643
+ // SIGNIN_IDENTITY_TYPES), null for none
3644
+ this._identityTypes = null;
3449
3645
  // Passkey state
3450
3646
  this._passkey = {
3451
3647
  hasPasskey: null,
@@ -3529,6 +3725,14 @@ class VerificationState {
3529
3725
  setSigninRef(signinRef) {
3530
3726
  this._signinRef = signinRef;
3531
3727
  }
3728
+ // --- Identity-type restriction ---
3729
+ /** The restriction every call that starts a ceremony carries, else null. */
3730
+ get identityTypes() {
3731
+ return this._identityTypes;
3732
+ }
3733
+ setIdentityTypes(identityTypes) {
3734
+ this._identityTypes = identityTypes;
3735
+ }
3532
3736
  // --- Passkey State ---
3533
3737
  get passkey() {
3534
3738
  return this._passkey;
@@ -3815,7 +4019,7 @@ class PasskeyHandler {
3815
4019
  // passkeys so the authenticator offers only the matching credential;
3816
4020
  // without one it falls back to a discoverable ceremony.
3817
4021
  const identityType = this.state.identityType === 'phone' ? 'phone' : 'email';
3818
- const challenge = await this.api.startPasskeyVerify(this.state.recipient, identityType, this.state.authContext);
4022
+ const challenge = await this.api.startPasskeyVerify(this.state.recipient, identityType, this.state.authContext, this.state.identityTypes);
3819
4023
  const credential = await navigator.credentials.get({
3820
4024
  ...(signal ? { signal } : {}),
3821
4025
  publicKey: {
@@ -3938,6 +4142,12 @@ class PasskeyHandler {
3938
4142
  if (signinRef) {
3939
4143
  params.set(SIGNIN_REFERENCE.param, signinRef);
3940
4144
  }
4145
+ // The sign-in's restriction: the popup names it on the call that starts
4146
+ // the ceremony, where Identity records it for the completion to read.
4147
+ const { identityTypes } = this.state;
4148
+ if (identityTypes) {
4149
+ params.set(SIGNIN_IDENTITY_TYPES.param, formatSigninIdentityTypes(identityTypes));
4150
+ }
3941
4151
  const hash = mode === 'register' && registrationToken
3942
4152
  ? `#${new URLSearchParams({ registration_token: registrationToken }).toString()}`
3943
4153
  : '';
@@ -4048,6 +4258,7 @@ class OtpHandler {
4048
4258
  recipient: this.state.recipient,
4049
4259
  method,
4050
4260
  authContext: this.state.authContext,
4261
+ identityTypes: this.state.identityTypes,
4051
4262
  });
4052
4263
  // Update state with kindling
4053
4264
  this.state.setKindling(response.kindling);
@@ -4084,6 +4295,7 @@ class OtpHandler {
4084
4295
  recipient: this.state.recipient,
4085
4296
  method,
4086
4297
  authContext: this.state.authContext,
4298
+ identityTypes: this.state.identityTypes,
4087
4299
  });
4088
4300
  // Update state with new kindling
4089
4301
  this.state.setKindling(response.kindling);
@@ -4189,7 +4401,7 @@ class SparkLinkHandler {
4189
4401
  */
4190
4402
  async send(connectionId) {
4191
4403
  try {
4192
- const result = await this.api.sendSparkLink(this.state.recipient, connectionId, this.state.authContext, this.state.signinRef);
4404
+ const result = await this.api.sendSparkLink(this.state.recipient, connectionId, this.state.authContext, this.state.signinRef, this.state.identityTypes);
4193
4405
  return {
4194
4406
  success: true,
4195
4407
  expiresAt: result.expiresAt,
@@ -6352,6 +6564,18 @@ const FEDERATION_UNAVAILABLE_CODE = 'federation_unavailable';
6352
6564
  * a genuine error, which the person's Try Again asks for again.
6353
6565
  */
6354
6566
  const SIGNIN_REFERENCE_UNAVAILABLE_CODE = 'signin_reference_unavailable';
6567
+ /**
6568
+ * The code of a sign-in whose restriction on the identity types it may
6569
+ * produce (SignInOptions.identityTypes) admits none of the account's ways in:
6570
+ * only the site that asked for the restriction can change that.
6571
+ */
6572
+ const IDENTITY_TYPES_UNAVAILABLE_CODE = 'identity_types_unavailable';
6573
+ /**
6574
+ * The code of a sign-in page whose URL names a restriction it cannot read:
6575
+ * the page runs no sign-in under it rather than one wider than the site
6576
+ * asked for, and only a sign-in the site opens afresh clears it.
6577
+ */
6578
+ const IDENTITY_TYPES_UNREADABLE_CODE = 'identity_types_unreadable';
6355
6579
  /**
6356
6580
  * The heading of a state the person can do nothing about from here, by its
6357
6581
  * code, or null for a genuine error. Retrying cannot clear any of them, so the
@@ -6362,17 +6586,36 @@ const SIGNIN_REFERENCE_UNAVAILABLE_CODE = 'signin_reference_unavailable';
6362
6586
  * which only the site owner subscribing clears, shown as a friendly,
6363
6587
  * non-leaky interstitial;
6364
6588
  * - a request held to a passkey the person does not hold;
6365
- * - an account whose only way in this page may not offer.
6589
+ * - an account whose only way in this page may not offer;
6590
+ * - a sign-in whose restriction admits none of the account's ways in, or
6591
+ * that names one this page cannot read.
6366
6592
  */
6367
6593
  function terminalTitle(code) {
6368
6594
  if (code === 'identity_locked')
6369
6595
  return 'This SparkVault Identity is locked';
6370
- if (isBlockedCode(code) || code === FEDERATION_UNAVAILABLE_CODE)
6596
+ if (isBlockedCode(code)
6597
+ || code === FEDERATION_UNAVAILABLE_CODE
6598
+ || code === IDENTITY_TYPES_UNAVAILABLE_CODE
6599
+ || code === IDENTITY_TYPES_UNREADABLE_CODE)
6371
6600
  return 'Sign-in unavailable';
6372
6601
  if (code === STRONGER_VERIFICATION_REQUIRED_CODE)
6373
6602
  return STRONGER_VERIFICATION_TITLE;
6374
6603
  return null;
6375
6604
  }
6605
+ /**
6606
+ * A refusal the person clears by choosing another way in, by its code, or
6607
+ * null: its heading and the label of the action that opens the other ways in
6608
+ * (ErrorViewProps.onRetry). Identity refusing a sign-in for an identity type
6609
+ * the sign-in's restriction excludes is one: its message says what the site
6610
+ * accepts sign-in with. Neither a code badge nor Try Again, which would
6611
+ * repeat the refused sign-in.
6612
+ */
6613
+ function redirectingState(code) {
6614
+ if (code === SIGNIN_IDENTITY_TYPES.refusalCode) {
6615
+ return { title: 'That sign-in is not accepted here', action: 'Other ways to sign in' };
6616
+ }
6617
+ return null;
6618
+ }
6376
6619
  class ErrorView {
6377
6620
  constructor(props) {
6378
6621
  this.retryButton = null;
@@ -6393,16 +6636,17 @@ class ErrorView {
6393
6636
  const contentSection = div();
6394
6637
  contentSection.className = 'sv-error-content';
6395
6638
  const terminal = terminalTitle(this.props.code);
6396
- const isTerminal = terminal !== null;
6639
+ const redirecting = redirectingState(this.props.code);
6640
+ const isGenuine = terminal === null && redirecting === null;
6397
6641
  const title = document.createElement('h3');
6398
6642
  title.className = 'sv-error-title';
6399
- title.textContent = terminal ?? 'Something went wrong';
6643
+ title.textContent = terminal ?? redirecting?.title ?? 'Something went wrong';
6400
6644
  const message = document.createElement('p');
6401
6645
  message.className = 'sv-error-message';
6402
6646
  message.textContent = this.props.message;
6403
6647
  contentSection.appendChild(title);
6404
6648
  contentSection.appendChild(message);
6405
- if (!isTerminal) {
6649
+ if (isGenuine) {
6406
6650
  // Error code badge — useful for debugging genuine errors only.
6407
6651
  const codeBadge = document.createElement('div');
6408
6652
  codeBadge.className = 'sv-error-code-badge';
@@ -6419,10 +6663,10 @@ class ErrorView {
6419
6663
  // Action buttons with proper styling
6420
6664
  const buttonContainer = div();
6421
6665
  buttonContainer.className = 'sv-error-actions';
6422
- if (!isTerminal) {
6666
+ if (terminal === null) {
6423
6667
  this.retryButton = document.createElement('button');
6424
6668
  this.retryButton.className = 'sv-btn sv-btn-error-primary';
6425
- this.retryButton.textContent = 'Try Again';
6669
+ this.retryButton.textContent = redirecting?.action ?? 'Try Again';
6426
6670
  this.retryButton.addEventListener('click', this.boundHandleRetry);
6427
6671
  buttonContainer.appendChild(this.retryButton);
6428
6672
  }
@@ -7022,7 +7266,7 @@ const SPARKLINK_CSP_BLOCKED_ERROR = {
7022
7266
  code: 'sparklink_csp_blocked',
7023
7267
  };
7024
7268
  class IdentityRenderer {
7025
- constructor(container, api, options, callbacks, federationReturn = null) {
7269
+ constructor(container, api, options, callbacks, federationReturn = null, identityTypes = { ok: true, types: null }) {
7026
7270
  // True while the identifier is the one the render options supplied (a host's
7027
7271
  // prefill, a login hint, an invite's identity), false once the person types
7028
7272
  // their own. Gates the "identity is fixed" behavior, so a no-hint
@@ -7076,6 +7320,10 @@ class IdentityRenderer {
7076
7320
  this.passkeyHandler = new PasskeyHandler(api, this.verificationState);
7077
7321
  this.otpHandler = new OtpHandler(api, this.verificationState);
7078
7322
  this.sparkLinkHandler = new SparkLinkHandler(api, this.verificationState);
7323
+ // The restriction lists only the ways in that can produce a type it names,
7324
+ // and rides every start (see SigninIdentityTypesRead).
7325
+ this.identityTypesUnreadable = !identityTypes.ok;
7326
+ this.verificationState.setIdentityTypes(identityTypes.ok ? identityTypes.types : null);
7079
7327
  // Seed the identity being verified from the render options.
7080
7328
  this.applyInitialIdentity();
7081
7329
  // Set auth context for OIDC/simple mode flows
@@ -7111,7 +7359,12 @@ class IdentityRenderer {
7111
7359
  const raw = explicitPhone ? this.options.phone : this.options.email;
7112
7360
  if (!raw)
7113
7361
  return;
7114
- if (explicitPhone || inferIdentityType(raw) === 'phone') {
7362
+ const type = explicitPhone || inferIdentityType(raw) === 'phone' ? 'phone' : 'email';
7363
+ // A hint of a type the sign-in's restriction excludes could lead only to
7364
+ // ways in it refuses: the person starts from the ways in it admits.
7365
+ if (!signinIdentityTypeAdmitted(type, this.verificationState.identityTypes))
7366
+ return;
7367
+ if (type === 'phone') {
7115
7368
  this.verificationState.setIdentity(parsePhone(raw) ?? raw, 'phone');
7116
7369
  }
7117
7370
  else {
@@ -7335,6 +7588,14 @@ class IdentityRenderer {
7335
7588
  this.render();
7336
7589
  }
7337
7590
  async showInitialAuthStep() {
7591
+ if (this.identityTypesUnreadable) {
7592
+ this.setState({
7593
+ view: 'error',
7594
+ code: IDENTITY_TYPES_UNREADABLE_CODE,
7595
+ message: 'This sign-in link is not valid. Contact the site you came from for help.',
7596
+ });
7597
+ return;
7598
+ }
7338
7599
  const heldAtStart = this.verificationState.signinRef;
7339
7600
  if (this.startWithFederation())
7340
7601
  return;
@@ -7515,7 +7776,7 @@ class IdentityRenderer {
7515
7776
  canDiscoverableVerify() {
7516
7777
  if (!this.passkeyHandler.canAutoVerify())
7517
7778
  return false;
7518
- const methods = enrichMethods(this.verificationState.methodIds);
7779
+ const methods = this.admittedMethods(enrichMethods(this.verificationState.methodIds));
7519
7780
  return methods.some((m) => m.type === 'passkey');
7520
7781
  }
7521
7782
  /**
@@ -7794,7 +8055,9 @@ class IdentityRenderer {
7794
8055
  ? () => { void this.showSignInStep(); }
7795
8056
  : state.code === SIGNIN_REFERENCE_UNAVAILABLE_CODE
7796
8057
  ? () => this.retryReference()
7797
- : () => this.showIdentityInput(),
8058
+ : state.code === SIGNIN_IDENTITY_TYPES.refusalCode
8059
+ ? () => this.chooseAnotherWay()
8060
+ : () => this.showIdentityInput(),
7798
8061
  onClose: () => this.handleClose(),
7799
8062
  });
7800
8063
  case 'service-unavailable':
@@ -7852,7 +8115,7 @@ class IdentityRenderer {
7852
8115
  // identity provider is set apart: it needs no identifier, and leads every
7853
8116
  // list that offers it (below), read once the rest of the list is known so
7854
8117
  // a reference that arrived meanwhile counts.
7855
- let methods = enrichMethods(methodIds);
8118
+ let methods = this.admittedMethods(enrichMethods(methodIds));
7856
8119
  if (this.recipient) {
7857
8120
  // Filter by identifier type. Passkeys are SVID-scoped, so they remain
7858
8121
  // available regardless of whether the fallback identifier is email or phone.
@@ -7957,8 +8220,11 @@ class IdentityRenderer {
7957
8220
  * - the page's ask for its reference is still out: the step waits for it;
7958
8221
  * - the ask found none for now: the person is told to try again, which
7959
8222
  * asks again.
7960
- * Any other verification with nothing to offer is a configuration fault,
7961
- * shown as one.
8223
+ * A sign-in whose restriction on the identity types it may produce took
8224
+ * away a way in it would otherwise offer is told which types it accepts and
8225
+ * that none of the ways here gives one: only the site that asked for the
8226
+ * restriction can change that. Any other verification with nothing to
8227
+ * offer is a configuration fault, shown as one.
7962
8228
  */
7963
8229
  noMethodState() {
7964
8230
  if (this.verificationState.passkeyRequired && this.verificationState.passkey.hasPasskey === false) {
@@ -7982,8 +8248,49 @@ class IdentityRenderer {
7982
8248
  }
7983
8249
  return { view: 'awaiting-reference' };
7984
8250
  }
8251
+ const identityTypes = this.verificationState.identityTypes;
8252
+ if (identityTypes && this.verificationState.methodIds.some((id) => !signinMethodAdmitted(id, identityTypes))) {
8253
+ return {
8254
+ view: 'error',
8255
+ code: IDENTITY_TYPES_UNAVAILABLE_CODE,
8256
+ message: signinIdentityTypesUnavailable(identityTypes),
8257
+ };
8258
+ }
7985
8259
  return { view: 'error', message: 'No authentication methods available', code: 'no_methods' };
7986
8260
  }
8261
+ /**
8262
+ * The methods the sign-in's restriction admits (app-sdk
8263
+ * signinMethodAdmitted): every method for a sign-in with none, else those
8264
+ * that can produce a type it names.
8265
+ */
8266
+ admittedMethods(methods) {
8267
+ const identityTypes = this.verificationState.identityTypes;
8268
+ return methods.filter((method) => signinMethodAdmitted(method.id, identityTypes));
8269
+ }
8270
+ /**
8271
+ * After Identity refused a sign-in of a type the restriction does not name:
8272
+ * the ways in for this identifier, with nothing starting on its own, or the
8273
+ * identifier field when the person has typed none.
8274
+ */
8275
+ chooseAnotherWay() {
8276
+ if (this.recipient || this.getAllowedIdentityTypes().length === 0) {
8277
+ void this.showMethodSelect({ autoRoute: false });
8278
+ return;
8279
+ }
8280
+ this.showIdentityInput();
8281
+ }
8282
+ /**
8283
+ * Identity refused the sign-in for a type its restriction does not name
8284
+ * (SIGNIN_IDENTITY_TYPES.refusalCode): show Identity's own words, which say
8285
+ * what this sign-in accepts, and return true. False for any other code.
8286
+ */
8287
+ renderIdentityTypeRefusal(code, message) {
8288
+ if (code !== SIGNIN_IDENTITY_TYPES.refusalCode || !message) {
8289
+ return false;
8290
+ }
8291
+ this.setState({ view: 'error', code, message });
8292
+ return true;
8293
+ }
7987
8294
  handleIdentitySubmit(result) {
7988
8295
  this.verificationState.setIdentity(result.value, result.type);
7989
8296
  // The person typed this identifier, so it is theirs to change — a no-hint
@@ -7991,8 +8298,15 @@ class IdentityRenderer {
7991
8298
  this.identityPrefilled = false;
7992
8299
  this.showMethodSelect();
7993
8300
  }
8301
+ /**
8302
+ * The identifier types the identifier field takes: the verification's,
8303
+ * less any its restriction does not name, whose codes and links could only
8304
+ * produce a sign-in it refuses.
8305
+ */
7994
8306
  getAllowedIdentityTypes() {
7995
- return this.verificationState.getAllowedIdentityTypes();
8307
+ const allowed = this.verificationState.getAllowedIdentityTypes();
8308
+ const identityTypes = this.verificationState.identityTypes;
8309
+ return identityTypes ? allowed.filter((type) => identityTypes.includes(type)) : allowed;
7996
8310
  }
7997
8311
  /**
7998
8312
  * @param userInitiated True when called from a live click on the picker, so
@@ -8014,6 +8328,8 @@ class IdentityRenderer {
8014
8328
  if (!result.success) {
8015
8329
  if (this.renderBlockedInterstitial(result.errorCode))
8016
8330
  return;
8331
+ if (this.renderIdentityTypeRefusal(result.errorCode, result.error))
8332
+ return;
8017
8333
  this.setState({
8018
8334
  view: 'error',
8019
8335
  message: result.error ?? 'Failed to send code',
@@ -8078,6 +8394,8 @@ class IdentityRenderer {
8078
8394
  // login. Mirrors the otp send path.
8079
8395
  if (this.renderBlockedInterstitial(result.errorCode))
8080
8396
  return;
8397
+ if (this.renderIdentityTypeRefusal(result.errorCode, result.error))
8398
+ return;
8081
8399
  this.setState({
8082
8400
  view: 'error',
8083
8401
  message: result.error ?? 'Failed to send SparkLink',
@@ -8157,6 +8475,7 @@ class IdentityRenderer {
8157
8475
  this.runPostLogin(result.result);
8158
8476
  }
8159
8477
  else if (this.renderBlockedInterstitial(result.errorCode)) ;
8478
+ else if (this.renderIdentityTypeRefusal(result.errorCode, result.error)) ;
8160
8479
  else if (result.errorCode === 'identity_locked') {
8161
8480
  // The identity is locked down — a dedicated, actionable state, not a
8162
8481
  // generic "invalid code" retry. The person must manage it at auth.sv.
@@ -8226,6 +8545,8 @@ class IdentityRenderer {
8226
8545
  }
8227
8546
  catch (error) {
8228
8547
  const message = error instanceof Error ? error.message : 'That code is not valid. Please try again.';
8548
+ if (error instanceof IdentityApiError && this.renderIdentityTypeRefusal(error.code, message))
8549
+ return;
8229
8550
  // The login ticket is not consumed on a wrong code, so the user can retry
8230
8551
  // against the same ticket — re-render the view carrying the error.
8231
8552
  this.setState({ view: 'two-factor', ticket, methods, error: message });
@@ -8287,6 +8608,9 @@ class IdentityRenderer {
8287
8608
  // Terminal interstitial already rendered — the owner must subscribe.
8288
8609
  return true;
8289
8610
  }
8611
+ if (this.renderIdentityTypeRefusal(result.errorCode, result.error)) {
8612
+ return true;
8613
+ }
8290
8614
  if (result.errorCode === 'identity_locked') {
8291
8615
  // Dedicated state — retrying cannot unlock the identity.
8292
8616
  this.setState({
@@ -8340,7 +8664,7 @@ class IdentityRenderer {
8340
8664
  passkeyFallbackMethodsAvailable() {
8341
8665
  if (!this.sdkConfig)
8342
8666
  return false;
8343
- const methods = enrichMethods(this.verificationState.methodIds, this.federation);
8667
+ const methods = this.admittedMethods(enrichMethods(this.verificationState.methodIds, this.federation));
8344
8668
  if (!this.recipient) {
8345
8669
  return methods.some((m) => m.type === 'social' || m.type === 'federation');
8346
8670
  }
@@ -8377,7 +8701,7 @@ class IdentityRenderer {
8377
8701
  this.setState({ view: 'oauth-pending', provider });
8378
8702
  const { state } = await this.api.drawAuthorizationValues();
8379
8703
  sessionStorage.setItem('sv_oauth_state', state);
8380
- const authUrl = this.api.getSocialAuthUrl(provider, currentPageReturnUrl(), state, this.verificationState.authContext, this.verificationState.signinRef);
8704
+ const authUrl = this.api.getSocialAuthUrl(provider, currentPageReturnUrl(), state, this.verificationState.authContext, { signinRef: this.verificationState.signinRef, identityTypes: this.verificationState.identityTypes });
8381
8705
  window.location.href = authUrl;
8382
8706
  }
8383
8707
  /**
@@ -8397,11 +8721,19 @@ class IdentityRenderer {
8397
8721
  get federationOffered() {
8398
8722
  return this.offeredWithoutReference || this.verificationState.signinRef !== null;
8399
8723
  }
8400
- /** The account's own identity provider while `/config` describes it and the verification's methods list it. */
8724
+ /**
8725
+ * The account's own identity provider while `/config` describes it, the
8726
+ * verification's methods list it, and the sign-in's restriction admits it.
8727
+ */
8401
8728
  get accountFederation() {
8402
8729
  const federation = this.sdkConfig?.federation;
8403
8730
  const methodIds = this.verificationState.methodIds;
8404
- return federation && Array.isArray(methodIds) && methodIds.includes('federation') ? federation : null;
8731
+ return federation
8732
+ && Array.isArray(methodIds)
8733
+ && methodIds.includes(FEDERATION_METHOD)
8734
+ && signinMethodAdmitted(FEDERATION_METHOD, this.verificationState.identityTypes)
8735
+ ? federation
8736
+ : null;
8405
8737
  }
8406
8738
  /**
8407
8739
  * Whether a list of methods offers the account's own identity provider
@@ -8444,7 +8776,7 @@ class IdentityRenderer {
8444
8776
  if (automatic)
8445
8777
  markFederationAutoStart(this.api.accountId);
8446
8778
  this.watchForPageRestore();
8447
- window.location.href = this.api.getFederationAuthUrl(currentPageReturnUrl(), state, this.verificationState.authContext, { silent, signinRef: this.verificationState.signinRef });
8779
+ window.location.href = this.api.getFederationAuthUrl(currentPageReturnUrl(), state, this.verificationState.authContext, { silent, signinRef: this.verificationState.signinRef, identityTypes: this.verificationState.identityTypes });
8448
8780
  }
8449
8781
  /**
8450
8782
  * A browser that restores this page from its back/forward cache, as the
@@ -8503,6 +8835,9 @@ class IdentityRenderer {
8503
8835
  */
8504
8836
  handleErrorWithRecovery(error, fallbackCode) {
8505
8837
  const err = this.normalizeError(error);
8838
+ if (err instanceof SparkVaultError && this.renderIdentityTypeRefusal(err.code, err.message)) {
8839
+ return;
8840
+ }
8506
8841
  if (this.isSessionExpiredError(err)) {
8507
8842
  // Session expired - let user start over
8508
8843
  this.showIdentityInput('Your session has expired. Please try again.');
@@ -9039,6 +9374,8 @@ class IdentityRenderer {
9039
9374
  }
9040
9375
  else {
9041
9376
  this.cleanupSparkLink();
9377
+ if (this.renderIdentityTypeRefusal(result.errorCode, result.error))
9378
+ return;
9042
9379
  this.setState({
9043
9380
  view: 'error',
9044
9381
  message: result.error ?? 'Failed to resend verification link. Please try again.',
@@ -9056,6 +9393,8 @@ class IdentityRenderer {
9056
9393
  if (!result.success) {
9057
9394
  if (this.renderBlockedInterstitial(result.errorCode))
9058
9395
  return;
9396
+ if (this.renderIdentityTypeRefusal(result.errorCode, result.error))
9397
+ return;
9059
9398
  this.setState({
9060
9399
  view: 'error',
9061
9400
  message: result.error ?? 'Failed to send code',
@@ -11586,7 +11925,7 @@ function attachClickHandler(selector, onClick) {
11586
11925
  * message listener but not sessionStorage) recover it on its next load, for
11587
11926
  * at most SIGNIN_RECOVERY.pendingTtlMs.
11588
11927
  *
11589
- * `sv_signin_pending` holds JSON `{ at, hint, ref }`:
11928
+ * `sv_signin_pending` holds JSON `{ at, hint, ref, identity_types }`:
11590
11929
  * - `at`: when the current popup opened, on this browser's clock; the
11591
11930
  * marker's TTL.
11592
11931
  * - `hint`: the email or phone the sign-in started with, or null when the
@@ -11595,14 +11934,20 @@ function attachClickHandler(selector, onClick) {
11595
11934
  * once drawn and written; the recovery bounce names it, and `/sso` then
11596
11935
  * mints only when the hub session it would mint from carries it. A marker
11597
11936
  * without one bounces with no reference.
11937
+ * - `identity_types` (SIGNIN_IDENTITY_TYPES.param): the sign-in's restriction
11938
+ * on the identity types it may produce, in its one spelling, present only
11939
+ * when the sign-in named one; the recovery bounce names it, so `/sso` mints
11940
+ * only a type the sign-in accepts.
11598
11941
  */
11599
11942
  const PENDING_KEY = 'sv_signin_pending';
11600
11943
  /**
11601
11944
  * Read and parse the pending marker. Anything unreadable yields null: a value
11602
- * that is not a JSON object, an `at` that is no finite number, or a `ref`
11603
- * that is present but no sign-in reference. A recovery that cannot name the
11604
- * reference its marker records could mint any hub session in this browser, so
11605
- * such a marker recovers nothing.
11945
+ * that is not a JSON object, an `at` that is no finite number, a `ref` that
11946
+ * is present but no sign-in reference, or a restriction that is present but
11947
+ * not in its spelling. A recovery that cannot name the reference its marker
11948
+ * records could mint any hub session in this browser, and one that cannot
11949
+ * name its restriction could mint a type its sign-in refuses, so such a
11950
+ * marker recovers nothing.
11606
11951
  */
11607
11952
  function readPendingMarker() {
11608
11953
  let raw = null;
@@ -11633,10 +11978,15 @@ function readPendingMarker() {
11633
11978
  if (ref !== undefined && !isSigninReference(ref)) {
11634
11979
  return null;
11635
11980
  }
11981
+ const identityTypes = marker[SIGNIN_IDENTITY_TYPES.param];
11982
+ if (!readSigninIdentityTypes(identityTypes).ok) {
11983
+ return null;
11984
+ }
11636
11985
  return {
11637
11986
  at: marker.at,
11638
11987
  hint: typeof marker.hint === 'string' && marker.hint ? marker.hint : null,
11639
11988
  ref: typeof ref === 'string' ? ref : null,
11989
+ identityTypes: typeof identityTypes === 'string' ? identityTypes : null,
11640
11990
  };
11641
11991
  }
11642
11992
  /** True while a marker is within the recovery TTL. */
@@ -11675,8 +12025,13 @@ function signinReferenceInTime(draw) {
11675
12025
  * hold a reference the marker does not.
11676
12026
  */
11677
12027
  class PendingSignIn {
11678
- constructor(hint) {
12028
+ /**
12029
+ * @param hint - The identifier the sign-in started with, or null
12030
+ * @param identityTypes - The sign-in's restriction in its one spelling, or null for none
12031
+ */
12032
+ constructor(hint, identityTypes) {
11679
12033
  this.hint = hint;
12034
+ this.identityTypes = identityTypes;
11680
12035
  this.at = 0;
11681
12036
  this.ended = false;
11682
12037
  // Counts the opens and the ends of their popups, so a draw that lands after
@@ -11760,7 +12115,12 @@ class PendingSignIn {
11760
12115
  }
11761
12116
  /** Write the marker; a write that fails leaves the stored marker as it was. */
11762
12117
  write(reference) {
11763
- const marker = { at: this.at, hint: this.hint, ...(reference ? { ref: reference } : {}) };
12118
+ const marker = {
12119
+ at: this.at,
12120
+ hint: this.hint,
12121
+ ...(reference ? { ref: reference } : {}),
12122
+ ...(this.identityTypes ? { [SIGNIN_IDENTITY_TYPES.param]: this.identityTypes } : {}),
12123
+ };
11764
12124
  try {
11765
12125
  sessionStorage.setItem(PENDING_KEY, JSON.stringify(marker));
11766
12126
  }
@@ -11921,7 +12281,11 @@ class IdentityModule {
11921
12281
  * the chooser, or the browser had no SparkVault account to offer (the
11922
12282
  * browser reports both alike). Throws `IdentityProviderError`, carrying
11923
12283
  * SparkVault's own error code, when SparkVault answered the sign-in with an
11924
- * error.
12284
+ * error (`IDENTITY_TYPE_NOT_ALLOWED` for an account of a type
12285
+ * `identityTypes` does not name).
12286
+ *
12287
+ * `identityTypes` restricts the sign-in as `SignInOptions.identityTypes`
12288
+ * does; a bad value is a ValidationError before anything is asked.
11925
12289
  *
11926
12290
  * @example
11927
12291
  * const result = IdentityModule.isFedcmAvailable()
@@ -11929,6 +12293,7 @@ class IdentityModule {
11929
12293
  * : await sv.products.identity.signIn();
11930
12294
  */
11931
12295
  async signInWithFedcm(options = {}) {
12296
+ const identityTypes = callerIdentityTypes(options.identityTypes);
11932
12297
  if (!IdentityModule.isFedcmAvailable()) {
11933
12298
  return null;
11934
12299
  }
@@ -11942,8 +12307,16 @@ class IdentityModule {
11942
12307
  // cookie lives) — not the auth.sv portal. The config, its endpoints, and
11943
12308
  // the credentialed accounts fetch must all be same-origin with that cookie.
11944
12309
  const configURL = `${this.config.identityBaseUrl}/${this.config.accountId}/fedcm/config.json`;
12310
+ // A restriction rides the provider's `params`, which the browser hands the
12311
+ // id-assertion endpoint; a sign-in that names none sends no `params`.
12312
+ const provider = {
12313
+ configURL,
12314
+ clientId: this.config.clientId,
12315
+ nonce,
12316
+ ...(identityTypes ? { params: identityTypesParam(identityTypes) } : {}),
12317
+ };
11945
12318
  const request = {
11946
- identity: { providers: [{ configURL, clientId: this.config.clientId, nonce }] },
12319
+ identity: { providers: [provider] },
11947
12320
  ...(options.mediation ? { mediation: options.mediation } : {}),
11948
12321
  };
11949
12322
  let credential;
@@ -12010,17 +12383,31 @@ class IdentityModule {
12010
12383
  * });
12011
12384
  */
12012
12385
  async signIn(options = {}) {
12013
- return this.runFlow(options);
12386
+ // Read before anything closes or opens, inside the caller's gesture: a
12387
+ // bad restriction is the caller's error, never a narrower or wider
12388
+ // sign-in than it asked for.
12389
+ let identityTypes;
12390
+ try {
12391
+ identityTypes = callerIdentityTypes(options.identityTypes);
12392
+ }
12393
+ catch (error) {
12394
+ const err = error instanceof Error ? error : new Error(String(error));
12395
+ options.onError?.(err);
12396
+ throw err;
12397
+ }
12398
+ return this.runFlow(options, { ok: true, types: identityTypes });
12014
12399
  }
12015
12400
  /**
12016
12401
  * Core flow runner. Default mode (no `target`) opens the popup; `flow:
12017
12402
  * 'redirect'` navigates the tab instead; local mode (`renderMode: 'local'` /
12018
12403
  * `target`) renders into the current document and powers the
12019
12404
  * SparkVault-hosted sign-in surfaces (see the internal `render`), which
12020
- * hands it what a round trip to the account's own identity provider
12021
- * returned (`federationReturn`).
12405
+ * hands it its restriction as its page's URL spelled it (`identityTypes`)
12406
+ * and what a round trip to the account's own identity provider returned
12407
+ * (`federationReturn`). The popup and the redirect carry the restriction
12408
+ * `options.identityTypes` names, which signIn() validated.
12022
12409
  */
12023
- async runFlow(options = {}, federationReturn = null) {
12410
+ async runFlow(options, identityTypes, federationReturn = null) {
12024
12411
  this.closeLauncher();
12025
12412
  if (this.renderer) {
12026
12413
  this.renderer.close();
@@ -12064,7 +12451,7 @@ class IdentityModule {
12064
12451
  },
12065
12452
  };
12066
12453
  const startLocalRender = (container) => {
12067
- this.renderer = new IdentityRenderer(container, this.api, mergedOptions, hostCallbacks, federationReturn);
12454
+ this.renderer = new IdentityRenderer(container, this.api, mergedOptions, hostCallbacks, federationReturn, identityTypes);
12068
12455
  this.renderer.start().catch((error) => {
12069
12456
  // A startup failure must surface inside the SparkVault dialog, never
12070
12457
  // close it silently. Render the error in-dialog instead (consistent with
@@ -12105,7 +12492,7 @@ class IdentityModule {
12105
12492
  // handleRedirectResult() can silently self-heal on the next load from
12106
12493
  // the SSO session the popup signed in or chose, which that popup's
12107
12494
  // reference names (see pending-signin.ts).
12108
- const pending = new PendingSignIn(mergedOptions.email || mergedOptions.phone || null);
12495
+ const pending = new PendingSignIn(mergedOptions.email || mergedOptions.phone || null, mergedOptions.identityTypes ? formatSigninIdentityTypes(mergedOptions.identityTypes) : null);
12109
12496
  this.pendingSignIn = pending;
12110
12497
  const launcher = new DialogLauncher(this.config, this.api, mergedOptions, {
12111
12498
  onSuccess: (result) => { pending.end(); hostCallbacks.onSuccess(result); },
@@ -12174,6 +12561,7 @@ class IdentityModule {
12174
12561
  authContext: options.authContext,
12175
12562
  prompt: options.prompt,
12176
12563
  method: options.method,
12564
+ identityTypes: options.identityTypes,
12177
12565
  onSuccess: options.onSuccess,
12178
12566
  onError: options.onError,
12179
12567
  onCancel: options.onCancel,
@@ -12383,6 +12771,11 @@ class IdentityModule {
12383
12771
  if (pending.ref) {
12384
12772
  sso.searchParams.set(SIGNIN_REFERENCE.param, pending.ref);
12385
12773
  }
12774
+ // The sign-in's restriction, so /sso mints only a type it accepts: a
12775
+ // recovery mints what the sign-in itself would have, never wider.
12776
+ if (pending.identityTypes) {
12777
+ sso.searchParams.set(SIGNIN_IDENTITY_TYPES.param, pending.identityTypes);
12778
+ }
12386
12779
  sso.searchParams.set('redirect_uri', handoff.redirectUri);
12387
12780
  sso.searchParams.set('state', handoff.state);
12388
12781
  sso.searchParams.set('code_challenge', handoff.codeChallenge);
@@ -12643,6 +13036,9 @@ class IdentityModule {
12643
13036
  * account's own identity provider is handed to the flow it starts (see
12644
13037
  * `consumeFederationReturn`).
12645
13038
  *
13039
+ * The page hands its restriction as its URL spelled it (`identityTypes`),
13040
+ * which the flow reads here: a spelling it cannot read shows as an error.
13041
+ *
12646
13042
  * @internal Used only by the SparkVault-hosted sign-in popup and hosted login
12647
13043
  * page (which own their chrome and pass `renderMode: 'local'`). Customer
12648
13044
  * integrations have no inline mode — use `signIn()` / `attach()`.
@@ -12653,7 +13049,8 @@ class IdentityModule {
12653
13049
  options.onSuccess?.(returned);
12654
13050
  return returned;
12655
13051
  }
12656
- return this.runFlow(options, this.consumeFederationReturn());
13052
+ const { identityTypes, ...flowOptions } = options;
13053
+ return this.runFlow(flowOptions, readSigninIdentityTypes(identityTypes), this.consumeFederationReturn());
12657
13054
  }
12658
13055
  }
12659
13056
 
@@ -17550,6 +17947,36 @@ function mapInvitation(wire) {
17550
17947
 
17551
17948
  /** The native support ceremony. Identity receipts stay inside the first-party window. */
17552
17949
  const VALUE = /^[A-Za-z0-9_-]{43}$/;
17950
+ /** The website's own opener policy cut the window off: no retry on this page can work, only its owner can fix it. */
17951
+ 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.';
17952
+ /** How often the sign-in window's handle is checked once it leaves for the sign-in page. */
17953
+ const HANDLE_CHECK_MS = 500;
17954
+ /**
17955
+ * What a sign-in window's handle reading `closed` before its page's ready
17956
+ * message means. A website serving `Cross-Origin-Opener-Policy: same-origin`
17957
+ * severs the window the moment its auth.sv page loads: the handle reads
17958
+ * `closed` while the window stays open in front of the person, showing that
17959
+ * page's own "not connected" notice. So:
17960
+ * - the website's page holding focus again means the person closed the
17961
+ * window and is back on it: a cancellation;
17962
+ * - a handle that reads `closed` at the first check after the window left
17963
+ * for the sign-in page, while the website's page still lacks focus, is a
17964
+ * severance: the window is still in front of the person, for no person
17965
+ * closes it that fast and then leaves the website;
17966
+ * - anything else cannot be told apart (a severance on a slow load, or a
17967
+ * person who closed the window and moved on): a retryable failure that
17968
+ * blames no one.
17969
+ * The ready message proves the website still holds the window, so after it
17970
+ * a closed handle decides nothing: a browser can sever the window during the
17971
+ * Identity round trip, which the result polling still completes.
17972
+ */
17973
+ function closedBeforeReady(firstCheck) {
17974
+ if (document.hasFocus())
17975
+ return new UserCancelledError();
17976
+ if (firstCheck)
17977
+ return new PopupSeveredError(SEVERED_MESSAGE);
17978
+ return new SparkVaultError('Support sign-in did not start. Try again.', 'HELP_DESK_WIDGET_SIGN_IN_INTERRUPTED');
17979
+ }
17553
17980
  /** Open synchronously inside the user's gesture, before preparing the server challenge. */
17554
17981
  function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
17555
17982
  if (!isHelpDeskId(deskId))
@@ -17572,6 +17999,7 @@ function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
17572
17999
  let settled = false;
17573
18000
  let checking = false;
17574
18001
  let interval;
18002
+ let watch;
17575
18003
  const timeout = setTimeout(() => finish(new SparkVaultError('Support sign-in expired. Try again.', 'HELP_DESK_WIDGET_SIGN_IN_EXPIRED')), 15 * 60 * 1000);
17576
18004
  const finish = (error, session) => {
17577
18005
  if (settled)
@@ -17580,6 +18008,8 @@ function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
17580
18008
  clearTimeout(timeout);
17581
18009
  if (interval)
17582
18010
  clearInterval(interval);
18011
+ if (watch)
18012
+ clearInterval(watch);
17583
18013
  window.removeEventListener('message', receive);
17584
18014
  options.signal?.removeEventListener('abort', cancel);
17585
18015
  try {
@@ -17614,6 +18044,8 @@ function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
17614
18044
  // at the first-party origin, is ever answered, so a sign-in link opened
17615
18045
  // in any other window or browser completes nothing.
17616
18046
  if (data.type === HELP_DESK_WIDGET_IDENTITY_MESSAGES.ready) {
18047
+ if (watch)
18048
+ clearInterval(watch);
17617
18049
  popup.postMessage({ type: HELP_DESK_WIDGET_IDENTITY_MESSAGES.state, challenge_id: challenge.challenge_id, state: challenge.state }, event.origin);
17618
18050
  return;
17619
18051
  }
@@ -17636,9 +18068,24 @@ function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
17636
18068
  url.protocol !== 'https:' || url.origin !== 'https://auth.sv' || url.username || url.password || url.search || url.hash ||
17637
18069
  url.pathname !== `/help-desk/${deskId}/${value.challenge_id}`)
17638
18070
  throw new SparkVaultError('The support sign-in address is invalid.', 'HELP_DESK_INVALID_RESPONSE');
18071
+ // The window still holds this page's own placeholder, which no opener
18072
+ // policy severs: closed now, the person closed it.
18073
+ if (popup.closed) {
18074
+ cancel();
18075
+ return;
18076
+ }
17639
18077
  challenge = value;
17640
18078
  firstPartyOrigin = url.origin;
17641
18079
  popup.location.replace(url.href);
18080
+ // A window whose handle dies before its page asks for the state can
18081
+ // never be handed it, so the sign-in ends at once (closedBeforeReady)
18082
+ // rather than polling until the challenge expires.
18083
+ let checks = 0;
18084
+ watch = setInterval(() => {
18085
+ checks += 1;
18086
+ if (popup.closed)
18087
+ finish(closedBeforeReady(checks === 1));
18088
+ }, HANDLE_CHECK_MS);
17642
18089
  // Code delivery must survive a browser severing window.opener during
17643
18090
  // the first-party Identity redirect. Polling knows only the original
17644
18091
  // challenge and verifier; no Identity JWT ever reaches this page.
@@ -31005,7 +31452,7 @@ class SparkVault {
31005
31452
  }
31006
31453
  /** Get the SDK version */
31007
31454
  static get version() {
31008
- return '16.10.0';
31455
+ return '16.11.0';
31009
31456
  }
31010
31457
  }
31011
31458
  if (typeof window !== 'undefined') {
@@ -31034,6 +31481,7 @@ exports.NotifyProjectsModule = NotifyProjectsModule;
31034
31481
  exports.NotifySubscriptionRequiredError = NotifySubscriptionRequiredError;
31035
31482
  exports.PlanRequiredError = PlanRequiredError;
31036
31483
  exports.PopupBlockedError = PopupBlockedError;
31484
+ exports.PopupSeveredError = PopupSeveredError;
31037
31485
  exports.ProductsModule = ProductsModule;
31038
31486
  exports.QuotaExceededError = QuotaExceededError;
31039
31487
  exports.SparkVault = SparkVault;