@sparkvault/sdk-js 2.0.3 → 2.1.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.
@@ -1064,6 +1064,18 @@ class IdentityApi extends SparkVaultApi {
1064
1064
  ...this.buildAuthContextParams(params.authContext),
1065
1065
  });
1066
1066
  }
1067
+ /**
1068
+ * Submit a second factor (authenticator-app code or recovery code) to finish
1069
+ * a login that the primary factor left in a `second_factor_required` state.
1070
+ * The ticket is the opaque pending-login handle returned by the primary
1071
+ * verify call.
1072
+ */
1073
+ async submitSecondFactor(params) {
1074
+ return this.request('POST', '/second-factor/verify', {
1075
+ ticket: params.ticket,
1076
+ code: params.code,
1077
+ });
1078
+ }
1067
1079
  /**
1068
1080
  * Start passkey registration from a freshly verified identifier.
1069
1081
  */
@@ -1808,6 +1820,14 @@ class TotpHandler {
1808
1820
  recipient: this.state.recipient,
1809
1821
  authContext: this.state.authContext,
1810
1822
  });
1823
+ // Primary factor accepted, but the account requires a second factor.
1824
+ // Not a success and not a retry — hand the ticket up to drive the 2FA step.
1825
+ if (response.second_factor_required && response.ticket) {
1826
+ return {
1827
+ success: false,
1828
+ secondFactor: { ticket: response.ticket, methods: response.methods ?? ['authenticator'] },
1829
+ };
1830
+ }
1811
1831
  if (response.verified && (response.token || response.redirect)) {
1812
1832
  return {
1813
1833
  success: true,
@@ -4556,6 +4576,144 @@ class TotpVerifyView {
4556
4576
  }
4557
4577
  }
4558
4578
 
4579
+ /**
4580
+ * Two-Factor View
4581
+ *
4582
+ * Shown after a primary factor succeeds for an account with 2FA enabled.
4583
+ * Collects a 6-digit authenticator-app code, or (if offered) a recovery code,
4584
+ * and submits it to complete the login.
4585
+ */
4586
+ class TwoFactorView {
4587
+ constructor(props) {
4588
+ this.input = null;
4589
+ this.submitButton = null;
4590
+ this.toggleButton = null;
4591
+ this.errorContainer = null;
4592
+ this.promptEl = null;
4593
+ this.recoveryMode = false;
4594
+ this.isSubmitting = false;
4595
+ this.focusTimeoutId = null;
4596
+ this.props = props;
4597
+ this.boundSubmit = () => this.handleSubmit();
4598
+ this.boundToggle = () => this.toggleRecovery();
4599
+ this.boundKeydown = (e) => { if (e.key === 'Enter')
4600
+ this.handleSubmit(); };
4601
+ this.boundInput = () => this.clearError();
4602
+ }
4603
+ render() {
4604
+ const container = div();
4605
+ container.style.display = 'flex';
4606
+ container.style.flexDirection = 'column';
4607
+ const title = document.createElement('h3');
4608
+ title.className = 'sv-title';
4609
+ title.textContent = 'Two-step verification';
4610
+ this.promptEl = document.createElement('p');
4611
+ this.promptEl.className = 'sv-subtitle';
4612
+ this.promptEl.innerHTML = 'Enter the 6-digit code from your authenticator app.';
4613
+ this.errorContainer = div();
4614
+ if (this.props.error) {
4615
+ this.errorContainer.appendChild(errorMessage(this.props.error));
4616
+ }
4617
+ this.input = document.createElement('input');
4618
+ this.input.type = 'text';
4619
+ this.input.inputMode = 'numeric';
4620
+ this.input.autocomplete = 'one-time-code';
4621
+ this.input.maxLength = 6;
4622
+ this.input.className = 'sv-input';
4623
+ this.input.setAttribute('aria-label', 'Verification code');
4624
+ this.input.placeholder = '000000';
4625
+ this.input.addEventListener('keydown', this.boundKeydown);
4626
+ this.input.addEventListener('input', this.boundInput);
4627
+ this.submitButton = document.createElement('button');
4628
+ this.submitButton.className = 'sv-btn sv-btn-primary';
4629
+ this.submitButton.textContent = 'Verify';
4630
+ this.submitButton.addEventListener('click', this.boundSubmit);
4631
+ container.appendChild(title);
4632
+ container.appendChild(this.promptEl);
4633
+ container.appendChild(this.errorContainer);
4634
+ container.appendChild(this.input);
4635
+ container.appendChild(this.submitButton);
4636
+ if (this.props.methods?.includes('recovery_code')) {
4637
+ this.toggleButton = document.createElement('button');
4638
+ this.toggleButton.className = 'sv-back-link';
4639
+ this.toggleButton.textContent = 'Use a recovery code instead';
4640
+ this.toggleButton.addEventListener('click', this.boundToggle);
4641
+ container.appendChild(this.toggleButton);
4642
+ }
4643
+ this.focusTimeoutId = setTimeout(() => this.input?.focus(), 50);
4644
+ return container;
4645
+ }
4646
+ toggleRecovery() {
4647
+ if (!this.input || !this.promptEl || !this.toggleButton)
4648
+ return;
4649
+ this.recoveryMode = !this.recoveryMode;
4650
+ this.input.value = '';
4651
+ this.clearError();
4652
+ if (this.recoveryMode) {
4653
+ this.input.inputMode = 'text';
4654
+ this.input.removeAttribute('maxlength');
4655
+ this.input.placeholder = 'XXXX-XXXX-XXXX-XXXX';
4656
+ this.promptEl.innerHTML = 'Enter one of your recovery codes.';
4657
+ this.toggleButton.textContent = 'Use your authenticator app instead';
4658
+ }
4659
+ else {
4660
+ this.input.inputMode = 'numeric';
4661
+ this.input.maxLength = 6;
4662
+ this.input.placeholder = '000000';
4663
+ this.promptEl.innerHTML = 'Enter the 6-digit code from your authenticator app.';
4664
+ this.toggleButton.textContent = 'Use a recovery code instead';
4665
+ }
4666
+ this.input.focus();
4667
+ }
4668
+ clearError() {
4669
+ if (this.errorContainer)
4670
+ clearChildren(this.errorContainer);
4671
+ this.input?.classList.remove('sv-input-error');
4672
+ }
4673
+ /** Surface a server-side error and re-enable the form for another attempt. */
4674
+ showError(message) {
4675
+ if (this.errorContainer) {
4676
+ clearChildren(this.errorContainer);
4677
+ this.errorContainer.appendChild(errorMessage(message));
4678
+ }
4679
+ this.input?.classList.add('sv-input-error');
4680
+ this.isSubmitting = false;
4681
+ if (this.submitButton) {
4682
+ this.submitButton.disabled = false;
4683
+ this.submitButton.textContent = 'Verify';
4684
+ }
4685
+ this.input?.focus();
4686
+ this.input?.select();
4687
+ }
4688
+ handleSubmit() {
4689
+ if (this.isSubmitting || !this.submitButton || !this.input)
4690
+ return;
4691
+ const code = this.input.value.trim();
4692
+ if (!code) {
4693
+ this.showError(this.recoveryMode ? 'Enter a recovery code' : 'Enter the 6-digit code');
4694
+ return;
4695
+ }
4696
+ if (!this.recoveryMode && !/^\d{6}$/.test(code)) {
4697
+ this.showError('Enter the complete 6-digit code');
4698
+ return;
4699
+ }
4700
+ this.isSubmitting = true;
4701
+ this.submitButton.disabled = true;
4702
+ this.submitButton.textContent = 'Verifying...';
4703
+ this.props.onSubmit(code);
4704
+ }
4705
+ destroy() {
4706
+ if (this.focusTimeoutId !== null) {
4707
+ clearTimeout(this.focusTimeoutId);
4708
+ this.focusTimeoutId = null;
4709
+ }
4710
+ this.input?.removeEventListener('keydown', this.boundKeydown);
4711
+ this.input?.removeEventListener('input', this.boundInput);
4712
+ this.submitButton?.removeEventListener('click', this.boundSubmit);
4713
+ this.toggleButton?.removeEventListener('click', this.boundToggle);
4714
+ }
4715
+ }
4716
+
4559
4717
  /**
4560
4718
  * Passkey View
4561
4719
  *
@@ -5711,7 +5869,7 @@ class IdentityRenderer {
5711
5869
  return new MethodSelectView({
5712
5870
  email: state.email,
5713
5871
  methods: state.methods,
5714
- onSelectMethod: (method) => this.handleMethodSelect(method),
5872
+ onSelectMethod: (method) => this.handleMethodSelect(method, true),
5715
5873
  onBack: state.email ? () => this.showIdentityInput() : undefined,
5716
5874
  });
5717
5875
  case 'totp-verify':
@@ -5724,6 +5882,12 @@ class IdentityRenderer {
5724
5882
  onResend: () => this.handleTotpResend(),
5725
5883
  onBack: () => this.showMethodSelect(),
5726
5884
  });
5885
+ case 'two-factor':
5886
+ return new TwoFactorView({
5887
+ methods: state.methods,
5888
+ error: state.error,
5889
+ onSubmit: (code) => this.handleSecondFactorSubmit(code),
5890
+ });
5727
5891
  case 'passkey': {
5728
5892
  // If coming from passkey prompt with a pending result, "back" should skip registration
5729
5893
  const { passkey } = this.verificationState;
@@ -5884,7 +6048,13 @@ class IdentityRenderer {
5884
6048
  getAllowedIdentityTypes() {
5885
6049
  return this.verificationState.getAllowedIdentityTypes();
5886
6050
  }
5887
- async handleMethodSelect(method) {
6051
+ /**
6052
+ * @param userInitiated True when called from a live click on the picker, so
6053
+ * a popup may be opened synchronously within that gesture. False when
6054
+ * auto-selected after an async step (e.g. the single enabled method), where
6055
+ * opening a popup would be blocked.
6056
+ */
6057
+ async handleMethodSelect(method, userInitiated = false) {
5888
6058
  try {
5889
6059
  switch (method.type) {
5890
6060
  case 'totp': {
@@ -5912,11 +6082,21 @@ class IdentityRenderer {
5912
6082
  break;
5913
6083
  }
5914
6084
  case 'passkey': {
5915
- this.setState({
5916
- view: 'passkey',
5917
- recipient: this.recipient,
5918
- mode: 'verify',
5919
- });
6085
+ if (userInitiated) {
6086
+ // Live picker tap: open the passkey popup directly within this
6087
+ // gesture (window.open in verify() runs before the first await),
6088
+ // skipping the redundant in-widget passkey screen.
6089
+ await this.launchPasskeyVerify();
6090
+ }
6091
+ else {
6092
+ // Auto-selected without a fresh gesture: a popup would be blocked,
6093
+ // so land on the passkey view whose button supplies the gesture.
6094
+ this.setState({
6095
+ view: 'passkey',
6096
+ recipient: this.recipient,
6097
+ mode: 'verify',
6098
+ });
6099
+ }
5920
6100
  break;
5921
6101
  }
5922
6102
  case 'sparklink': {
@@ -5981,6 +6161,14 @@ class IdentityRenderer {
5981
6161
  return;
5982
6162
  const currentMethod = this.verificationState.totp.method ?? 'email';
5983
6163
  const result = await this.totpHandler.verify(code);
6164
+ if (result.secondFactor) {
6165
+ this.setState({
6166
+ view: 'two-factor',
6167
+ ticket: result.secondFactor.ticket,
6168
+ methods: result.secondFactor.methods,
6169
+ });
6170
+ return;
6171
+ }
5984
6172
  if (result.success && result.result) {
5985
6173
  // Passkey upsell only when there's no redirect target — with one,
5986
6174
  // we head to the destination immediately.
@@ -6046,6 +6234,34 @@ class IdentityRenderer {
6046
6234
  });
6047
6235
  }
6048
6236
  }
6237
+ async handleSecondFactorSubmit(code) {
6238
+ if (this.viewState.view !== 'two-factor')
6239
+ return;
6240
+ const { ticket, methods } = this.viewState;
6241
+ try {
6242
+ const response = await this.api.submitSecondFactor({ ticket, code });
6243
+ const result = {
6244
+ token: response.token ?? '',
6245
+ identity: response.identity ?? this.recipient,
6246
+ identityType: response.identity_type ?? this.identityType,
6247
+ svid: response.svid,
6248
+ sessionId: response.session_id,
6249
+ refreshToken: response.refresh_token,
6250
+ redirect: response.redirect,
6251
+ };
6252
+ this.close();
6253
+ this.safeOnSuccess(result);
6254
+ if (typeof result.redirect === 'string' && result.redirect) {
6255
+ window.location.href = result.redirect;
6256
+ }
6257
+ }
6258
+ catch (error) {
6259
+ const message = error instanceof Error ? error.message : 'That code is not valid. Please try again.';
6260
+ // The login ticket is not consumed on a wrong code, so the user can retry
6261
+ // against the same ticket — re-render the view carrying the error.
6262
+ this.setState({ view: 'two-factor', ticket, methods, error: message });
6263
+ }
6264
+ }
6049
6265
  async handleTotpResend() {
6050
6266
  if (this.viewState.view !== 'totp-verify')
6051
6267
  return;
@@ -6069,6 +6285,24 @@ class IdentityRenderer {
6069
6285
  const result = currentMode === 'register'
6070
6286
  ? await this.passkeyHandler.register()
6071
6287
  : await this.passkeyHandler.verify();
6288
+ this.applyPasskeyResult(result, currentMode);
6289
+ }
6290
+ /**
6291
+ * Open the verify popup straight from a live picker gesture, showing a
6292
+ * loading state while the ceremony runs. window.open inside verify() fires
6293
+ * synchronously (before the first await), so it stays within the gesture.
6294
+ */
6295
+ async launchPasskeyVerify() {
6296
+ this.setState({ view: 'loading' });
6297
+ const result = await this.passkeyHandler.verify();
6298
+ this.applyPasskeyResult(result, 'verify');
6299
+ }
6300
+ /**
6301
+ * Apply a passkey ceremony result: complete on success, or route to the
6302
+ * matching recovery state. Shared by the passkey view and the direct
6303
+ * picker launch so both behave identically.
6304
+ */
6305
+ applyPasskeyResult(result, currentMode) {
6072
6306
  if (result.success && result.result) {
6073
6307
  this.close();
6074
6308
  this.safeOnSuccess(result.result);
@@ -6084,24 +6318,22 @@ class IdentityRenderer {
6084
6318
  message: 'This SparkVault Identity is locked. Visit auth.sv to manage it.',
6085
6319
  });
6086
6320
  }
6321
+ else if (result.errorType === 'not_found') {
6322
+ // No passkey yet — pivot the same screen to registration.
6323
+ this.setState({
6324
+ view: 'passkey',
6325
+ recipient: this.recipient,
6326
+ mode: 'register',
6327
+ error: result.error,
6328
+ });
6329
+ }
6087
6330
  else {
6088
- // Handle different error types
6089
- if (result.errorType === 'not_found') {
6090
- this.setState({
6091
- view: 'passkey',
6092
- recipient: this.recipient,
6093
- mode: 'register',
6094
- error: result.error,
6095
- });
6096
- }
6097
- else {
6098
- this.setState({
6099
- view: 'passkey',
6100
- recipient: this.recipient,
6101
- mode: currentMode,
6102
- error: result.error,
6103
- });
6104
- }
6331
+ this.setState({
6332
+ view: 'passkey',
6333
+ recipient: this.recipient,
6334
+ mode: currentMode,
6335
+ error: result.error,
6336
+ });
6105
6337
  }
6106
6338
  }
6107
6339
  /**