@sparkvault/sdk-js 2.2.3 → 2.2.5

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.
@@ -752,83 +752,6 @@ function base64urlToString(base64url) {
752
752
  * Consolidates duplicated logic from renderer, api, and index.
753
753
  */
754
754
  // Re-export timer utilities
755
- /**
756
- * Common multi-part public suffixes where the last two labels form the TLD.
757
- * Domains under these suffixes need three labels for a valid registrable domain
758
- * (e.g., "app.client.co.uk" → registrable domain is "client.co.uk").
759
- */
760
- const MULTI_PART_TLDS = new Set([
761
- 'co.uk', 'co.jp', 'co.kr', 'co.nz', 'co.za', 'co.in', 'co.id', 'co.th',
762
- 'com.au', 'com.br', 'com.cn', 'com.mx', 'com.sg', 'com.tw', 'com.hk',
763
- 'com.ar', 'com.co', 'com.my', 'com.ph', 'com.pk', 'com.tr', 'com.ua',
764
- 'com.vn', 'com.ng', 'com.eg', 'com.sa', 'com.pe', 'com.ec',
765
- 'net.au', 'net.br', 'net.cn', 'net.nz',
766
- 'org.au', 'org.br', 'org.cn', 'org.nz', 'org.uk',
767
- 'ac.uk', 'gov.uk', 'ac.jp', 'ne.jp', 'or.jp',
768
- 'ac.kr', 'go.kr', 'or.kr',
769
- 'ac.nz', 'govt.nz',
770
- 'ac.za', 'gov.za',
771
- 'ac.in', 'gov.in', 'net.in', 'org.in',
772
- ]);
773
- /**
774
- * Extract the root (registrable) domain from a hostname for cross-subdomain cookies.
775
- * Returns the domain prefixed with a dot (e.g., ".client.com") or null when
776
- * the domain attribute should not be set (loopback hosts, IP addresses).
777
- *
778
- * @param hostname - The hostname to extract the root domain from
779
- * @returns Root domain with leading dot, or null
780
- */
781
- function getRootDomain(hostname) {
782
- // Loopback host — browsers reject domain attribute for localhost
783
- if (hostname === 'localhost' || hostname === '127.0.0.1')
784
- return null;
785
- // IPv4 addresses
786
- if (/^\d{1,3}(\.\d{1,3}){3}$/.test(hostname))
787
- return null;
788
- // IPv6 addresses
789
- if (hostname.includes(':'))
790
- return null;
791
- const parts = hostname.split('.');
792
- // Single-label hostnames (no dots)
793
- if (parts.length <= 1)
794
- return null;
795
- // Two-part domain (e.g., "client.com") — already the root
796
- if (parts.length === 2)
797
- return `.${hostname}`;
798
- // Check for multi-part TLD (e.g., "co.uk" in "app.client.co.uk")
799
- const lastTwo = parts.slice(-2).join('.');
800
- if (MULTI_PART_TLDS.has(lastTwo) && parts.length >= 3) {
801
- return `.${parts.slice(-3).join('.')}`;
802
- }
803
- // Standard TLD — root domain is last two parts (e.g., "app.client.com" → ".client.com")
804
- return `.${lastTwo}`;
805
- }
806
- /**
807
- * Get cookie value by name
808
- * @param name - Cookie name
809
- * @returns Cookie value or null if not found
810
- */
811
- function getCookie(name) {
812
- const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`));
813
- return match ? match[2] : null;
814
- }
815
- /**
816
- * Set cookie with expiration on the root domain for cross-subdomain access.
817
- * The domain is automatically extracted from the current hostname and prefixed
818
- * with a dot (e.g., ".client.com") so the cookie is shared across all subdomains.
819
- *
820
- * @param name - Cookie name
821
- * @param value - Cookie value
822
- * @param days - Days until expiration
823
- */
824
- function setCookie(name, value, days) {
825
- const date = new Date();
826
- date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
827
- const expires = `expires=${date.toUTCString()}`;
828
- const domain = getRootDomain(window.location.hostname);
829
- const domainAttr = domain ? `; domain=${domain}` : '';
830
- document.cookie = `${name}=${value}; ${expires}; path=/${domainAttr}; SameSite=Lax`;
831
- }
832
755
  /**
833
756
  * Generate cryptographically secure random state string
834
757
  * Used for OAuth CSRF protection
@@ -1055,6 +978,42 @@ class IdentityApi extends SparkVaultApi {
1055
978
  },
1056
979
  });
1057
980
  }
981
+ /**
982
+ * Send a one-time code to a new backup identifier (the inverse of the
983
+ * identifier just logged in with). Authorized by the login's verification
984
+ * token. Returns a pending-attach `session_id`, or `already_verified` when
985
+ * the identifier is already on the identity.
986
+ */
987
+ async sendBackupVerification(params) {
988
+ return this.request('POST', '/backup-verification/send', {
989
+ verification_token: params.verificationToken,
990
+ type: params.type,
991
+ value: params.value,
992
+ ...(params.method ? { method: params.method } : {}),
993
+ });
994
+ }
995
+ /**
996
+ * Confirm the backup-identifier code and attach it to the identity. A 409
997
+ * `backup_conflict` (identifier owned by another identity) surfaces as a
998
+ * thrown IdentityApiError with code `backup_conflict`.
999
+ */
1000
+ async verifyBackupVerification(params) {
1001
+ return this.request('POST', '/backup-verification/verify', {
1002
+ session_id: params.sessionId,
1003
+ code: params.code,
1004
+ });
1005
+ }
1006
+ /**
1007
+ * Skip a post-login recommendation, suppressing it server-side for 30 days.
1008
+ * Authorized by the login's verification token. Best-effort — a failure here
1009
+ * must not block completing the login.
1010
+ */
1011
+ async dismissRecommendation(params) {
1012
+ await this.request('POST', '/recommendations/dismiss', {
1013
+ verification_token: params.verificationToken,
1014
+ key: params.key,
1015
+ });
1016
+ }
1058
1017
  /**
1059
1018
  * Get OAuth redirect URL for social provider
1060
1019
  */
@@ -1110,9 +1069,32 @@ class IdentityApi extends SparkVaultApi {
1110
1069
  sessionId: typeof data.session_id === 'string' ? data.session_id : undefined,
1111
1070
  refreshToken: typeof data.refresh_token === 'string' ? data.refresh_token : undefined,
1112
1071
  redirect: typeof data.redirect === 'string' ? data.redirect : undefined,
1072
+ recommendations: mapRecommendations(data.recommendations),
1113
1073
  };
1114
1074
  }
1115
1075
  }
1076
+ /**
1077
+ * Map the API's snake_case recommendation list to the SDK's typed shape,
1078
+ * dropping any entries the SDK does not understand. Returns undefined when
1079
+ * absent so callers treat it as "no nudges".
1080
+ */
1081
+ function mapRecommendations(raw) {
1082
+ if (!Array.isArray(raw))
1083
+ return undefined;
1084
+ const result = [];
1085
+ for (const item of raw) {
1086
+ if (!item || typeof item !== 'object')
1087
+ continue;
1088
+ const rec = item;
1089
+ if (rec.type === 'passkey') {
1090
+ result.push({ type: 'passkey' });
1091
+ }
1092
+ else if (rec.type === 'backup_identifier' && (rec.missing_type === 'email' || rec.missing_type === 'phone')) {
1093
+ result.push({ type: 'backup_identifier', missingType: rec.missing_type });
1094
+ }
1095
+ }
1096
+ return result;
1097
+ }
1116
1098
  class IdentityApiError extends SparkVaultError {
1117
1099
  constructor(message, code, statusCode, details) {
1118
1100
  super(message, code, statusCode, details);
@@ -1282,12 +1264,6 @@ class VerificationState {
1282
1264
  get accountId() {
1283
1265
  return this._sdkConfig?.accountId ?? '';
1284
1266
  }
1285
- /**
1286
- * Check if passkey method is enabled in config
1287
- */
1288
- isPasskeyEnabled() {
1289
- return this._sdkConfig?.methods?.includes('passkey') ?? false;
1290
- }
1291
1267
  // --- View State ---
1292
1268
  get viewState() {
1293
1269
  return this._viewState;
@@ -1332,33 +1308,6 @@ class VerificationState {
1332
1308
  setPendingResult(result) {
1333
1309
  this._passkey.pendingResult = result;
1334
1310
  }
1335
- /**
1336
- * Check if we should show passkey registration prompt
1337
- * Based on: passkey enabled, the current SVID doesn't have one, not dismissed
1338
- */
1339
- shouldShowPasskeyPrompt() {
1340
- if (!this.isPasskeyEnabled())
1341
- return false;
1342
- if (this.isPasskeyPromptDismissed())
1343
- return false;
1344
- if (this._passkey.hasPasskey === true)
1345
- return false;
1346
- return true;
1347
- }
1348
- /**
1349
- * Check if passkey prompt was dismissed (30-day cookie)
1350
- */
1351
- isPasskeyPromptDismissed() {
1352
- const cookieName = `sv_passkey_prompt_dismissed_${this.accountId}`;
1353
- return getCookie(cookieName) !== null;
1354
- }
1355
- /**
1356
- * Dismiss passkey prompt for 30 days
1357
- */
1358
- dismissPasskeyPrompt() {
1359
- const cookieName = `sv_passkey_prompt_dismissed_${this.accountId}`;
1360
- setCookie(cookieName, '1', 30);
1361
- }
1362
1311
  // --- TOTP State ---
1363
1312
  get totp() {
1364
1313
  return this._totp;
@@ -1812,6 +1761,7 @@ class TotpHandler {
1812
1761
  sessionId: response.session_id,
1813
1762
  refreshToken: response.refresh_token,
1814
1763
  redirect: response.redirect,
1764
+ recommendations: mapRecommendations(response.recommendations),
1815
1765
  },
1816
1766
  };
1817
1767
  }
@@ -4875,6 +4825,147 @@ class PasskeyPromptView {
4875
4825
  }
4876
4826
  }
4877
4827
 
4828
+ /**
4829
+ * Backup Verification Input View
4830
+ *
4831
+ * Post-login nudge to add the inverse identifier as a recovery backup:
4832
+ * collects a new phone (for an email login) or email (for a phone login),
4833
+ * then hands it off to send a one-time code. Includes a "Not now" skip that
4834
+ * suppresses this method's prompt for 30 days (handled by the renderer).
4835
+ *
4836
+ * Sibling of PasskeyPromptView — same low-friction, skippable shape.
4837
+ */
4838
+ class BackupVerifyView {
4839
+ constructor(props) {
4840
+ this.inputElement = null;
4841
+ this.submitButton = null;
4842
+ this.skipLink = null;
4843
+ this.errorContainer = null;
4844
+ this.focusTimeoutId = null;
4845
+ this.props = props;
4846
+ this.boundHandleInput = () => this.handleInput();
4847
+ this.boundHandleKeyDown = (e) => {
4848
+ if (e.key === 'Enter') {
4849
+ e.preventDefault();
4850
+ this.handleSubmit();
4851
+ }
4852
+ };
4853
+ this.boundHandleSubmit = () => this.handleSubmit();
4854
+ this.boundHandleSkip = () => this.props.onSkip();
4855
+ }
4856
+ get isPhone() {
4857
+ return this.props.missingType === 'phone';
4858
+ }
4859
+ render() {
4860
+ const container = div('sv-email-view');
4861
+ const headerSection = div('sv-email-header');
4862
+ const title = document.createElement('h3');
4863
+ title.className = 'sv-title';
4864
+ title.textContent = this.isPhone ? 'Add a backup phone number' : 'Add a backup email';
4865
+ const subtitle = document.createElement('p');
4866
+ subtitle.className = 'sv-email-subtitle';
4867
+ subtitle.textContent = this.isPhone
4868
+ ? 'Add a phone number so you can always get back into your account.'
4869
+ : 'Add an email so you can always get back into your account.';
4870
+ headerSection.appendChild(title);
4871
+ headerSection.appendChild(subtitle);
4872
+ container.appendChild(headerSection);
4873
+ this.errorContainer = div('sv-email-error-container');
4874
+ if (this.props.error) {
4875
+ this.errorContainer.appendChild(errorMessage(this.props.error));
4876
+ }
4877
+ container.appendChild(this.errorContainer);
4878
+ const formSection = div('sv-email-form');
4879
+ const inputWrapper = div('sv-email-input-wrapper');
4880
+ const label = document.createElement('label');
4881
+ label.className = 'sv-email-label';
4882
+ label.htmlFor = 'sv-backup-input';
4883
+ label.textContent = this.isPhone ? 'Phone number' : 'Email address';
4884
+ this.inputElement = document.createElement('input');
4885
+ this.inputElement.type = this.isPhone ? 'tel' : 'email';
4886
+ this.inputElement.id = 'sv-backup-input';
4887
+ this.inputElement.className = 'sv-email-input';
4888
+ this.inputElement.placeholder = this.isPhone ? '(555) 123-4567' : 'you@example.com';
4889
+ this.inputElement.autocomplete = this.isPhone ? 'tel' : 'email';
4890
+ this.inputElement.required = true;
4891
+ this.inputElement.maxLength = 254;
4892
+ this.inputElement.addEventListener('input', this.boundHandleInput);
4893
+ this.inputElement.addEventListener('keydown', this.boundHandleKeyDown);
4894
+ inputWrapper.appendChild(label);
4895
+ inputWrapper.appendChild(this.inputElement);
4896
+ formSection.appendChild(inputWrapper);
4897
+ this.submitButton = document.createElement('button');
4898
+ this.submitButton.className = 'sv-btn sv-btn-primary';
4899
+ this.submitButton.textContent = 'Send code';
4900
+ this.submitButton.addEventListener('click', this.boundHandleSubmit);
4901
+ formSection.appendChild(this.submitButton);
4902
+ this.skipLink = document.createElement('button');
4903
+ this.skipLink.className = 'sv-skip-link';
4904
+ this.skipLink.textContent = 'Not now';
4905
+ this.skipLink.addEventListener('click', this.boundHandleSkip);
4906
+ formSection.appendChild(this.skipLink);
4907
+ container.appendChild(formSection);
4908
+ this.focusTimeoutId = setTimeout(() => this.inputElement?.focus(), 50);
4909
+ return container;
4910
+ }
4911
+ handleInput() {
4912
+ this.clearError();
4913
+ // Live-format phone numbers as the user types (email needs no formatting).
4914
+ if (!this.inputElement || !this.isPhone)
4915
+ return;
4916
+ const value = this.inputElement.value;
4917
+ const cursorPos = this.inputElement.selectionStart ?? value.length;
4918
+ const formatted = formatPhoneDisplay(value);
4919
+ if (formatted !== value) {
4920
+ this.inputElement.value = formatted;
4921
+ const newPos = Math.min(cursorPos + (formatted.length - value.length), formatted.length);
4922
+ this.inputElement.setSelectionRange(newPos, newPos);
4923
+ }
4924
+ }
4925
+ clearError() {
4926
+ if (this.errorContainer)
4927
+ clearChildren(this.errorContainer);
4928
+ this.inputElement?.classList.remove('sv-email-input-error');
4929
+ }
4930
+ showError(message) {
4931
+ if (this.errorContainer) {
4932
+ clearChildren(this.errorContainer);
4933
+ this.errorContainer.appendChild(errorMessage(message));
4934
+ }
4935
+ this.inputElement?.classList.add('sv-email-input-error');
4936
+ this.inputElement?.focus();
4937
+ }
4938
+ handleSubmit() {
4939
+ if (!this.inputElement || !this.submitButton)
4940
+ return;
4941
+ const raw = this.inputElement.value;
4942
+ const normalized = this.isPhone ? validatePhone(raw) : validateEmail(raw);
4943
+ if (!normalized) {
4944
+ this.showError(this.isPhone ? 'Please enter a valid phone number' : 'Please enter a valid email address');
4945
+ return;
4946
+ }
4947
+ this.submitButton.disabled = true;
4948
+ this.submitButton.textContent = 'Please wait...';
4949
+ this.props.onSubmit(normalized);
4950
+ }
4951
+ destroy() {
4952
+ if (this.focusTimeoutId !== null) {
4953
+ clearTimeout(this.focusTimeoutId);
4954
+ this.focusTimeoutId = null;
4955
+ }
4956
+ if (this.inputElement) {
4957
+ this.inputElement.removeEventListener('input', this.boundHandleInput);
4958
+ this.inputElement.removeEventListener('keydown', this.boundHandleKeyDown);
4959
+ }
4960
+ if (this.submitButton) {
4961
+ this.submitButton.removeEventListener('click', this.boundHandleSubmit);
4962
+ }
4963
+ if (this.skipLink) {
4964
+ this.skipLink.removeEventListener('click', this.boundHandleSkip);
4965
+ }
4966
+ }
4967
+ }
4968
+
4878
4969
  /**
4879
4970
  * SparkLink Waiting View
4880
4971
  *
@@ -5601,6 +5692,10 @@ class IdentityRenderer {
5601
5692
  // View management
5602
5693
  this.currentView = null;
5603
5694
  this.focusTimeoutId = null;
5695
+ // Post-login recommendation pipeline: the verified result to finalize with,
5696
+ // and the remaining server-recommended steps to walk before finalizing.
5697
+ this.postLoginResult = null;
5698
+ this.postLoginQueue = [];
5604
5699
  // SparkLink WebSocket
5605
5700
  this.sparkLinkWs = null;
5606
5701
  // SparkLink WebSocket-loss fallback: the login kindling lets the SDK reclaim
@@ -5916,6 +6011,26 @@ class IdentityRenderer {
5916
6011
  onSkip: () => this.handlePasskeyPromptSkip(state.pendingResult),
5917
6012
  error: state.error,
5918
6013
  });
6014
+ case 'backup-verify':
6015
+ return new BackupVerifyView({
6016
+ missingType: state.missingType,
6017
+ error: state.error,
6018
+ onSubmit: (value) => this.handleBackupSubmit(value),
6019
+ onSkip: () => this.handleBackupSkip(),
6020
+ });
6021
+ case 'backup-code':
6022
+ return new TotpVerifyView({
6023
+ email: state.value,
6024
+ method: state.method,
6025
+ error: state.error,
6026
+ onSubmit: (code) => this.handleBackupCodeSubmit(code),
6027
+ onResend: () => this.handleBackupResend(),
6028
+ onBack: () => this.setState({
6029
+ view: 'backup-verify',
6030
+ missingType: state.missingType,
6031
+ pendingResult: state.pendingResult,
6032
+ }),
6033
+ });
5919
6034
  case 'sparklink-waiting':
5920
6035
  return new SparkLinkWaitingView({
5921
6036
  email: state.email,
@@ -6174,23 +6289,7 @@ class IdentityRenderer {
6174
6289
  return;
6175
6290
  }
6176
6291
  if (result.success && result.result) {
6177
- // Passkey upsell only when there's no redirect target — with one,
6178
- // we head to the destination immediately.
6179
- if (!result.result.redirect && await this.shouldShowPasskeyPrompt()) {
6180
- this.setState({
6181
- view: 'passkey-prompt',
6182
- recipient: this.recipient,
6183
- pendingResult: result.result,
6184
- });
6185
- return;
6186
- }
6187
- this.close();
6188
- // Hand the full result (including redirect) to the host first so the
6189
- // page-level handler can act before we navigate away.
6190
- this.safeOnSuccess(result.result);
6191
- if (typeof result.result.redirect === 'string' && result.result.redirect) {
6192
- navigateWith(this.options, result.result.redirect);
6193
- }
6292
+ this.runPostLogin(result.result);
6194
6293
  }
6195
6294
  else if (result.errorCode === 'identity_locked') {
6196
6295
  // The identity is locked down — a dedicated, actionable state, not a
@@ -6368,15 +6467,10 @@ class IdentityRenderer {
6368
6467
  * User clicked "Back" or cancelled registration after being prompted.
6369
6468
  */
6370
6469
  handlePasskeyRegistrationSkip() {
6371
- const pendingResult = this.verificationState.passkey.pendingResult;
6372
- if (pendingResult) {
6373
- this.verificationState.setPendingResult(null);
6374
- this.close();
6375
- this.safeOnSuccess(pendingResult);
6376
- if (typeof pendingResult.redirect === 'string' && pendingResult.redirect) {
6377
- navigateWith(this.options, pendingResult.redirect);
6378
- }
6379
- }
6470
+ this.verificationState.setPendingResult(null);
6471
+ // Treat as skipping the passkey recommendation, then advance the pipeline.
6472
+ this.dismissRecommendation('passkey');
6473
+ this.advancePostLogin();
6380
6474
  }
6381
6475
  handleSocialLogin(provider) {
6382
6476
  this.setState({ view: 'oauth-pending', provider });
@@ -6436,21 +6530,182 @@ class IdentityRenderer {
6436
6530
  }
6437
6531
  }
6438
6532
  /**
6439
- * Check if we should show the passkey registration prompt after PIN verification.
6533
+ * Run the post-login step pipeline for a completed primary login.
6534
+ *
6535
+ * The server returns an ordered `recommendations` list (passkey upsell,
6536
+ * backup verification, …); this walks it, rendering the step views the SDK
6537
+ * supports and finalizing when the queue drains. A redirect target skips the
6538
+ * pipeline. A future nudge is one new recommendation type + view case — no
6539
+ * primary-login handler changes.
6540
+ */
6541
+ runPostLogin(result) {
6542
+ if (result.redirect) {
6543
+ this.finalizeLogin(result);
6544
+ return;
6545
+ }
6546
+ this.postLoginResult = result;
6547
+ this.postLoginQueue = [...(result.recommendations ?? [])];
6548
+ this.advancePostLogin();
6549
+ }
6550
+ /**
6551
+ * Show the next supported recommendation, or finalize when the queue is
6552
+ * empty. The single hand-off from each step back into the pipeline.
6440
6553
  */
6441
- async shouldShowPasskeyPrompt() {
6442
- // Use centralized state for this check
6443
- if (!this.verificationState.shouldShowPasskeyPrompt()) {
6444
- return false;
6554
+ advancePostLogin() {
6555
+ const result = this.postLoginResult;
6556
+ if (!result)
6557
+ return;
6558
+ const next = this.postLoginQueue.shift();
6559
+ if (!next) {
6560
+ this.postLoginResult = null;
6561
+ this.finalizeLogin(result);
6562
+ return;
6563
+ }
6564
+ if (next.type === 'passkey') {
6565
+ this.setState({ view: 'passkey-prompt', recipient: this.recipient, pendingResult: result });
6566
+ }
6567
+ else if (next.type === 'backup_identifier') {
6568
+ this.setState({ view: 'backup-verify', missingType: next.missingType, pendingResult: result });
6569
+ }
6570
+ else {
6571
+ // A recommendation type this SDK build does not render — skip it.
6572
+ this.advancePostLogin();
6573
+ }
6574
+ }
6575
+ /**
6576
+ * Best-effort: tell the server the person skipped a recommendation so it is
6577
+ * suppressed for 30 days. Never blocks completing the login.
6578
+ */
6579
+ dismissRecommendation(key) {
6580
+ const token = this.postLoginResult?.token;
6581
+ if (!token)
6582
+ return;
6583
+ void this.api.dismissRecommendation({ verificationToken: token, key }).catch(() => { });
6584
+ }
6585
+ /**
6586
+ * Complete the login: hand the result to the host before tearing down the
6587
+ * modal (so its onSuccess can act while the browsing context is alive), then
6588
+ * navigate any redirect the flow returned.
6589
+ */
6590
+ finalizeLogin(result) {
6591
+ this.safeOnSuccess(result);
6592
+ this.close();
6593
+ if (typeof result.redirect === 'string' && result.redirect) {
6594
+ navigateWith(this.options, result.redirect);
6595
+ }
6596
+ }
6597
+ /**
6598
+ * Send a code to the new backup identifier the person entered. Already-attached
6599
+ * identifiers short-circuit straight to completion; otherwise advance to code
6600
+ * entry.
6601
+ */
6602
+ async handleBackupSubmit(value) {
6603
+ if (this.viewState.view !== 'backup-verify')
6604
+ return;
6605
+ const { missingType, pendingResult } = this.viewState;
6606
+ this.setState({ view: 'loading' });
6607
+ try {
6608
+ const response = await this.api.sendBackupVerification({
6609
+ verificationToken: pendingResult.token,
6610
+ type: missingType,
6611
+ value,
6612
+ });
6613
+ if (response.already_verified || !response.session_id) {
6614
+ this.advancePostLogin();
6615
+ return;
6616
+ }
6617
+ this.setState({
6618
+ view: 'backup-code',
6619
+ missingType,
6620
+ value,
6621
+ method: response.method ?? (missingType === 'phone' ? 'sms' : 'email'),
6622
+ sessionId: response.session_id,
6623
+ pendingResult,
6624
+ });
6625
+ }
6626
+ catch (error) {
6627
+ this.setState({
6628
+ view: 'backup-verify',
6629
+ missingType,
6630
+ pendingResult,
6631
+ error: error instanceof Error ? error.message : 'Could not send a code. Please try again.',
6632
+ });
6633
+ }
6634
+ }
6635
+ /**
6636
+ * Verify the backup code and attach the identifier, then finish the original
6637
+ * login. An identifier owned by another account (409 backup_conflict) bounces
6638
+ * back to the input so the person can try a different one.
6639
+ */
6640
+ async handleBackupCodeSubmit(code) {
6641
+ if (this.viewState.view !== 'backup-code')
6642
+ return;
6643
+ const { missingType, value, method, sessionId, pendingResult } = this.viewState;
6644
+ try {
6645
+ await this.api.verifyBackupVerification({ sessionId, code });
6646
+ this.advancePostLogin();
6445
6647
  }
6446
- // If we haven't checked yet, check with API
6447
- const { passkey } = this.verificationState;
6448
- if (passkey.hasPasskey === null) {
6449
- const checkResult = await this.passkeyHandler.checkPasskey();
6450
- // Only prompt if the verified identifier resolves to an SVID without a passkey.
6451
- return checkResult !== null && checkResult.identityValid && !checkResult.hasPasskey;
6648
+ catch (error) {
6649
+ const errorCode = error instanceof IdentityApiError ? error.code : '';
6650
+ if (errorCode === 'backup_conflict') {
6651
+ this.setState({
6652
+ view: 'backup-verify',
6653
+ missingType,
6654
+ pendingResult,
6655
+ error: error instanceof Error ? error.message : 'That identifier is already linked to another account.',
6656
+ });
6657
+ return;
6658
+ }
6659
+ this.setState({
6660
+ view: 'backup-code',
6661
+ missingType,
6662
+ value,
6663
+ method,
6664
+ sessionId,
6665
+ pendingResult,
6666
+ error: error instanceof Error ? error.message : 'That code is not valid. Please try again.',
6667
+ });
6452
6668
  }
6453
- return !passkey.hasPasskey;
6669
+ }
6670
+ /**
6671
+ * Resend the backup code, refreshing the pending-attach session.
6672
+ */
6673
+ async handleBackupResend() {
6674
+ if (this.viewState.view !== 'backup-code')
6675
+ return;
6676
+ const { missingType, value, method, pendingResult } = this.viewState;
6677
+ try {
6678
+ const response = await this.api.sendBackupVerification({
6679
+ verificationToken: pendingResult.token,
6680
+ type: missingType,
6681
+ value,
6682
+ method,
6683
+ });
6684
+ if (response.session_id) {
6685
+ this.setState({
6686
+ view: 'backup-code',
6687
+ missingType,
6688
+ value,
6689
+ method: response.method ?? method,
6690
+ sessionId: response.session_id,
6691
+ pendingResult,
6692
+ });
6693
+ }
6694
+ }
6695
+ catch {
6696
+ // Keep the current code view; the user can press resend again.
6697
+ }
6698
+ }
6699
+ /**
6700
+ * "Not now" on the backup prompt: suppress this identifier type for 30 days
6701
+ * (server-side) and advance to the next step.
6702
+ */
6703
+ handleBackupSkip() {
6704
+ if (this.viewState.view !== 'backup-verify')
6705
+ return;
6706
+ const { missingType } = this.viewState;
6707
+ this.dismissRecommendation(missingType === 'phone' ? 'backup_phone' : 'backup_email');
6708
+ this.advancePostLogin();
6454
6709
  }
6455
6710
  /**
6456
6711
  * Handle user clicking "Add Passkey" in the prompt.
@@ -6464,12 +6719,11 @@ class IdentityRenderer {
6464
6719
  // Directly trigger passkey registration
6465
6720
  const result = await this.passkeyHandler.register(pendingResult.token);
6466
6721
  if (result.success && result.result) {
6467
- // Passkey created successfully - use the new token
6468
- this.close();
6469
- this.safeOnSuccess(result.result);
6470
- if (typeof result.result.redirect === 'string' && result.result.redirect) {
6471
- navigateWith(this.options, result.result.redirect);
6472
- }
6722
+ // Passkey created — adopt its fresh token/session as the result to
6723
+ // finalize with (and to authorize any later backup-attach step), then
6724
+ // advance to the next recommendation.
6725
+ this.postLoginResult = result.result;
6726
+ this.advancePostLogin();
6473
6727
  }
6474
6728
  else if (result.errorType === 'cancelled') {
6475
6729
  // User cancelled browser dialog - go back to prompt so they can skip or try again
@@ -6491,17 +6745,12 @@ class IdentityRenderer {
6491
6745
  }
6492
6746
  }
6493
6747
  /**
6494
- * Handle user clicking "Not now" / "Skip" in the prompt.
6748
+ * Handle user clicking "Not now" / "Skip" in the passkey prompt: suppress it
6749
+ * for 30 days (server-side) and advance to the next step.
6495
6750
  */
6496
- handlePasskeyPromptSkip(pendingResult) {
6497
- // Set 30-day cookie to suppress future prompts
6498
- this.verificationState.dismissPasskeyPrompt();
6499
- // Complete the verification
6500
- this.close();
6501
- this.safeOnSuccess(pendingResult);
6502
- if (typeof pendingResult.redirect === 'string' && pendingResult.redirect) {
6503
- navigateWith(this.options, pendingResult.redirect);
6504
- }
6751
+ handlePasskeyPromptSkip(_pendingResult) {
6752
+ this.dismissRecommendation('passkey');
6753
+ this.advancePostLogin();
6505
6754
  }
6506
6755
  /**
6507
6756
  * Open a WebSocket connection and return the connectionId.
@@ -6660,27 +6909,9 @@ class IdentityRenderer {
6660
6909
  if (kindling) {
6661
6910
  void this.api.consumeSparkLinkResult(kindling).catch(() => { });
6662
6911
  }
6663
- // Passkey upsell only when there's no redirect target — once we have
6664
- // a destination we go there immediately, no upsell.
6665
- if (!result.redirect && await this.shouldShowPasskeyPrompt()) {
6666
- this.setState({
6667
- view: 'passkey-prompt',
6668
- recipient: this.recipient,
6669
- pendingResult: result,
6670
- });
6671
- return;
6672
- }
6673
- // Hand the full result (including redirect) to the host BEFORE tearing down
6674
- // the modal, so the host's onSuccess can act (logging, navigation) without
6675
- // racing the teardown of the browsing context.
6676
- this.safeOnSuccess(result);
6677
- this.close();
6678
- // SDK-side fallback navigation. If the host already navigated this is
6679
- // a no-op (the document is already unloading); if not, this rescues
6680
- // simple-mode flows whose host forgot to act on result.redirect.
6681
- if (typeof result.redirect === 'string' && result.redirect) {
6682
- navigateWith(this.options, result.redirect);
6683
- }
6912
+ // Run the post-login step pipeline (passkey upsell, then backup
6913
+ // verification). With a redirect target it finalizes immediately.
6914
+ this.runPostLogin(result);
6684
6915
  }
6685
6916
  /**
6686
6917
  * Arm the WebSocket-loss fallback for the waiting screen.