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