@sparkvault/sdk-js 2.0.3 → 2.0.4

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.
@@ -7,7 +7,7 @@
7
7
  import type { ResolvedConfig } from '../config';
8
8
  import { SparkVaultApi } from '../api-base';
9
9
  import { SparkVaultError } from '../errors';
10
- import type { SdkConfig, TotpSendResponse, TotpVerifyResponse, PasskeyChallengeResponse, PasskeyVerifyResponse, SparkLinkSendResponse, AuthContext } from './types';
10
+ import type { SdkConfig, TotpSendResponse, TotpVerifyResponse, PasskeyChallengeResponse, PasskeyVerifyResponse, SecondFactorVerifyResponse, SparkLinkSendResponse, AuthContext } from './types';
11
11
  export declare class IdentityApi extends SparkVaultApi {
12
12
  private readonly config;
13
13
  /** Cached config promise - allows preloading and deduplication */
@@ -69,6 +69,16 @@ export declare class IdentityApi extends SparkVaultApi {
69
69
  recipient: string;
70
70
  authContext?: AuthContext;
71
71
  }): Promise<TotpVerifyResponse>;
72
+ /**
73
+ * Submit a second factor (authenticator-app code or recovery code) to finish
74
+ * a login that the primary factor left in a `second_factor_required` state.
75
+ * The ticket is the opaque pending-login handle returned by the primary
76
+ * verify call.
77
+ */
78
+ submitSecondFactor(params: {
79
+ ticket: string;
80
+ code: string;
81
+ }): Promise<SecondFactorVerifyResponse>;
72
82
  /**
73
83
  * Start passkey registration from a freshly verified identifier.
74
84
  */
@@ -31,6 +31,14 @@ export interface TotpVerifyResult {
31
31
  error?: string;
32
32
  /** Machine-readable API error code (e.g. 'identity_locked'). */
33
33
  errorCode?: string;
34
+ /**
35
+ * Set when the code was correct but the account has 2FA enabled — the login
36
+ * is not complete until a second factor is submitted against this ticket.
37
+ */
38
+ secondFactor?: {
39
+ ticket: string;
40
+ methods: string[];
41
+ };
34
42
  }
35
43
  /**
36
44
  * Handles TOTP code sending and verification
@@ -88,6 +88,7 @@ export declare class IdentityRenderer {
88
88
  private getAllowedIdentityTypes;
89
89
  private handleMethodSelect;
90
90
  private handleTotpSubmit;
91
+ private handleSecondFactorSubmit;
91
92
  private handleTotpResend;
92
93
  private handlePasskeyStart;
93
94
  /**
@@ -168,6 +168,12 @@ export interface TotpVerifyResponse {
168
168
  retry_after?: number;
169
169
  /** Returned on failure - when the backoff expires */
170
170
  expires_at?: number;
171
+ /** Set when the primary factor succeeded but 2FA is still owed */
172
+ second_factor_required?: boolean;
173
+ /** Opaque pending-login handle to submit the second factor against */
174
+ ticket?: string;
175
+ /** Second-factor methods the user can use, e.g. ['authenticator','recovery_code'] */
176
+ methods?: string[];
171
177
  }
172
178
  export interface PasskeyChallengeResponse {
173
179
  challenge: string;
@@ -192,6 +198,21 @@ export interface PasskeyVerifyResponse {
192
198
  /** Redirect URL for OIDC/simple mode flows */
193
199
  redirect?: string;
194
200
  }
201
+ /**
202
+ * Result of completing a login via the second factor. On success this is the
203
+ * same shape as any verified login; a wrong code surfaces as a thrown error.
204
+ */
205
+ export interface SecondFactorVerifyResponse {
206
+ verified?: boolean;
207
+ token?: string;
208
+ identity?: string;
209
+ identity_type?: VerifiedIdentityType;
210
+ svid?: string;
211
+ session_id?: string;
212
+ refresh_token?: string;
213
+ /** Redirect URL the caller should navigate to. */
214
+ redirect?: string;
215
+ }
195
216
  export interface SparkLinkSendResponse {
196
217
  sparkId: string;
197
218
  expiresAt: number;
@@ -212,6 +233,11 @@ export type IdentityViewState = {
212
233
  kindling: string;
213
234
  error?: string;
214
235
  backoffExpires?: number;
236
+ } | {
237
+ view: 'two-factor';
238
+ ticket: string;
239
+ methods: string[];
240
+ error?: string;
215
241
  } | {
216
242
  view: 'passkey';
217
243
  recipient: string;
@@ -8,6 +8,7 @@ export * from './loading';
8
8
  export * from './identity-input';
9
9
  export * from './method-select';
10
10
  export * from './totp-verify';
11
+ export * from './two-factor';
11
12
  export * from './passkey';
12
13
  export * from './passkey-prompt';
13
14
  export * from './sparklink-waiting';
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Two-Factor View
3
+ *
4
+ * Shown after a primary factor succeeds for an account with 2FA enabled.
5
+ * Collects a 6-digit authenticator-app code, or (if offered) a recovery code,
6
+ * and submits it to complete the login.
7
+ */
8
+ import type { View } from './base';
9
+ export interface TwoFactorViewProps {
10
+ /** Second-factor methods the server offers, e.g. ['authenticator','recovery_code']. */
11
+ methods: string[];
12
+ error?: string;
13
+ onSubmit: (code: string) => void;
14
+ }
15
+ export declare class TwoFactorView implements View {
16
+ private readonly props;
17
+ private input;
18
+ private submitButton;
19
+ private toggleButton;
20
+ private errorContainer;
21
+ private promptEl;
22
+ private recoveryMode;
23
+ private isSubmitting;
24
+ private focusTimeoutId;
25
+ private readonly boundSubmit;
26
+ private readonly boundToggle;
27
+ private readonly boundKeydown;
28
+ private readonly boundInput;
29
+ constructor(props: TwoFactorViewProps);
30
+ render(): HTMLElement;
31
+ private toggleRecovery;
32
+ private clearError;
33
+ /** Surface a server-side error and re-enable the form for another attempt. */
34
+ showError(message: string): void;
35
+ private handleSubmit;
36
+ destroy(): void;
37
+ }
@@ -1068,6 +1068,18 @@ class IdentityApi extends SparkVaultApi {
1068
1068
  ...this.buildAuthContextParams(params.authContext),
1069
1069
  });
1070
1070
  }
1071
+ /**
1072
+ * Submit a second factor (authenticator-app code or recovery code) to finish
1073
+ * a login that the primary factor left in a `second_factor_required` state.
1074
+ * The ticket is the opaque pending-login handle returned by the primary
1075
+ * verify call.
1076
+ */
1077
+ async submitSecondFactor(params) {
1078
+ return this.request('POST', '/second-factor/verify', {
1079
+ ticket: params.ticket,
1080
+ code: params.code,
1081
+ });
1082
+ }
1071
1083
  /**
1072
1084
  * Start passkey registration from a freshly verified identifier.
1073
1085
  */
@@ -1812,6 +1824,14 @@ class TotpHandler {
1812
1824
  recipient: this.state.recipient,
1813
1825
  authContext: this.state.authContext,
1814
1826
  });
1827
+ // Primary factor accepted, but the account requires a second factor.
1828
+ // Not a success and not a retry — hand the ticket up to drive the 2FA step.
1829
+ if (response.second_factor_required && response.ticket) {
1830
+ return {
1831
+ success: false,
1832
+ secondFactor: { ticket: response.ticket, methods: response.methods ?? ['authenticator'] },
1833
+ };
1834
+ }
1815
1835
  if (response.verified && (response.token || response.redirect)) {
1816
1836
  return {
1817
1837
  success: true,
@@ -4560,6 +4580,144 @@ class TotpVerifyView {
4560
4580
  }
4561
4581
  }
4562
4582
 
4583
+ /**
4584
+ * Two-Factor View
4585
+ *
4586
+ * Shown after a primary factor succeeds for an account with 2FA enabled.
4587
+ * Collects a 6-digit authenticator-app code, or (if offered) a recovery code,
4588
+ * and submits it to complete the login.
4589
+ */
4590
+ class TwoFactorView {
4591
+ constructor(props) {
4592
+ this.input = null;
4593
+ this.submitButton = null;
4594
+ this.toggleButton = null;
4595
+ this.errorContainer = null;
4596
+ this.promptEl = null;
4597
+ this.recoveryMode = false;
4598
+ this.isSubmitting = false;
4599
+ this.focusTimeoutId = null;
4600
+ this.props = props;
4601
+ this.boundSubmit = () => this.handleSubmit();
4602
+ this.boundToggle = () => this.toggleRecovery();
4603
+ this.boundKeydown = (e) => { if (e.key === 'Enter')
4604
+ this.handleSubmit(); };
4605
+ this.boundInput = () => this.clearError();
4606
+ }
4607
+ render() {
4608
+ const container = div();
4609
+ container.style.display = 'flex';
4610
+ container.style.flexDirection = 'column';
4611
+ const title = document.createElement('h3');
4612
+ title.className = 'sv-title';
4613
+ title.textContent = 'Two-step verification';
4614
+ this.promptEl = document.createElement('p');
4615
+ this.promptEl.className = 'sv-subtitle';
4616
+ this.promptEl.innerHTML = 'Enter the 6-digit code from your authenticator app.';
4617
+ this.errorContainer = div();
4618
+ if (this.props.error) {
4619
+ this.errorContainer.appendChild(errorMessage(this.props.error));
4620
+ }
4621
+ this.input = document.createElement('input');
4622
+ this.input.type = 'text';
4623
+ this.input.inputMode = 'numeric';
4624
+ this.input.autocomplete = 'one-time-code';
4625
+ this.input.maxLength = 6;
4626
+ this.input.className = 'sv-input';
4627
+ this.input.setAttribute('aria-label', 'Verification code');
4628
+ this.input.placeholder = '000000';
4629
+ this.input.addEventListener('keydown', this.boundKeydown);
4630
+ this.input.addEventListener('input', this.boundInput);
4631
+ this.submitButton = document.createElement('button');
4632
+ this.submitButton.className = 'sv-btn sv-btn-primary';
4633
+ this.submitButton.textContent = 'Verify';
4634
+ this.submitButton.addEventListener('click', this.boundSubmit);
4635
+ container.appendChild(title);
4636
+ container.appendChild(this.promptEl);
4637
+ container.appendChild(this.errorContainer);
4638
+ container.appendChild(this.input);
4639
+ container.appendChild(this.submitButton);
4640
+ if (this.props.methods?.includes('recovery_code')) {
4641
+ this.toggleButton = document.createElement('button');
4642
+ this.toggleButton.className = 'sv-back-link';
4643
+ this.toggleButton.textContent = 'Use a recovery code instead';
4644
+ this.toggleButton.addEventListener('click', this.boundToggle);
4645
+ container.appendChild(this.toggleButton);
4646
+ }
4647
+ this.focusTimeoutId = setTimeout(() => this.input?.focus(), 50);
4648
+ return container;
4649
+ }
4650
+ toggleRecovery() {
4651
+ if (!this.input || !this.promptEl || !this.toggleButton)
4652
+ return;
4653
+ this.recoveryMode = !this.recoveryMode;
4654
+ this.input.value = '';
4655
+ this.clearError();
4656
+ if (this.recoveryMode) {
4657
+ this.input.inputMode = 'text';
4658
+ this.input.removeAttribute('maxlength');
4659
+ this.input.placeholder = 'XXXX-XXXX-XXXX-XXXX';
4660
+ this.promptEl.innerHTML = 'Enter one of your recovery codes.';
4661
+ this.toggleButton.textContent = 'Use your authenticator app instead';
4662
+ }
4663
+ else {
4664
+ this.input.inputMode = 'numeric';
4665
+ this.input.maxLength = 6;
4666
+ this.input.placeholder = '000000';
4667
+ this.promptEl.innerHTML = 'Enter the 6-digit code from your authenticator app.';
4668
+ this.toggleButton.textContent = 'Use a recovery code instead';
4669
+ }
4670
+ this.input.focus();
4671
+ }
4672
+ clearError() {
4673
+ if (this.errorContainer)
4674
+ clearChildren(this.errorContainer);
4675
+ this.input?.classList.remove('sv-input-error');
4676
+ }
4677
+ /** Surface a server-side error and re-enable the form for another attempt. */
4678
+ showError(message) {
4679
+ if (this.errorContainer) {
4680
+ clearChildren(this.errorContainer);
4681
+ this.errorContainer.appendChild(errorMessage(message));
4682
+ }
4683
+ this.input?.classList.add('sv-input-error');
4684
+ this.isSubmitting = false;
4685
+ if (this.submitButton) {
4686
+ this.submitButton.disabled = false;
4687
+ this.submitButton.textContent = 'Verify';
4688
+ }
4689
+ this.input?.focus();
4690
+ this.input?.select();
4691
+ }
4692
+ handleSubmit() {
4693
+ if (this.isSubmitting || !this.submitButton || !this.input)
4694
+ return;
4695
+ const code = this.input.value.trim();
4696
+ if (!code) {
4697
+ this.showError(this.recoveryMode ? 'Enter a recovery code' : 'Enter the 6-digit code');
4698
+ return;
4699
+ }
4700
+ if (!this.recoveryMode && !/^\d{6}$/.test(code)) {
4701
+ this.showError('Enter the complete 6-digit code');
4702
+ return;
4703
+ }
4704
+ this.isSubmitting = true;
4705
+ this.submitButton.disabled = true;
4706
+ this.submitButton.textContent = 'Verifying...';
4707
+ this.props.onSubmit(code);
4708
+ }
4709
+ destroy() {
4710
+ if (this.focusTimeoutId !== null) {
4711
+ clearTimeout(this.focusTimeoutId);
4712
+ this.focusTimeoutId = null;
4713
+ }
4714
+ this.input?.removeEventListener('keydown', this.boundKeydown);
4715
+ this.input?.removeEventListener('input', this.boundInput);
4716
+ this.submitButton?.removeEventListener('click', this.boundSubmit);
4717
+ this.toggleButton?.removeEventListener('click', this.boundToggle);
4718
+ }
4719
+ }
4720
+
4563
4721
  /**
4564
4722
  * Passkey View
4565
4723
  *
@@ -5728,6 +5886,12 @@ class IdentityRenderer {
5728
5886
  onResend: () => this.handleTotpResend(),
5729
5887
  onBack: () => this.showMethodSelect(),
5730
5888
  });
5889
+ case 'two-factor':
5890
+ return new TwoFactorView({
5891
+ methods: state.methods,
5892
+ error: state.error,
5893
+ onSubmit: (code) => this.handleSecondFactorSubmit(code),
5894
+ });
5731
5895
  case 'passkey': {
5732
5896
  // If coming from passkey prompt with a pending result, "back" should skip registration
5733
5897
  const { passkey } = this.verificationState;
@@ -5985,6 +6149,14 @@ class IdentityRenderer {
5985
6149
  return;
5986
6150
  const currentMethod = this.verificationState.totp.method ?? 'email';
5987
6151
  const result = await this.totpHandler.verify(code);
6152
+ if (result.secondFactor) {
6153
+ this.setState({
6154
+ view: 'two-factor',
6155
+ ticket: result.secondFactor.ticket,
6156
+ methods: result.secondFactor.methods,
6157
+ });
6158
+ return;
6159
+ }
5988
6160
  if (result.success && result.result) {
5989
6161
  // Passkey upsell only when there's no redirect target — with one,
5990
6162
  // we head to the destination immediately.
@@ -6050,6 +6222,34 @@ class IdentityRenderer {
6050
6222
  });
6051
6223
  }
6052
6224
  }
6225
+ async handleSecondFactorSubmit(code) {
6226
+ if (this.viewState.view !== 'two-factor')
6227
+ return;
6228
+ const { ticket, methods } = this.viewState;
6229
+ try {
6230
+ const response = await this.api.submitSecondFactor({ ticket, code });
6231
+ const result = {
6232
+ token: response.token ?? '',
6233
+ identity: response.identity ?? this.recipient,
6234
+ identityType: response.identity_type ?? this.identityType,
6235
+ svid: response.svid,
6236
+ sessionId: response.session_id,
6237
+ refreshToken: response.refresh_token,
6238
+ redirect: response.redirect,
6239
+ };
6240
+ this.close();
6241
+ this.safeOnSuccess(result);
6242
+ if (typeof result.redirect === 'string' && result.redirect) {
6243
+ window.location.href = result.redirect;
6244
+ }
6245
+ }
6246
+ catch (error) {
6247
+ const message = error instanceof Error ? error.message : 'That code is not valid. Please try again.';
6248
+ // The login ticket is not consumed on a wrong code, so the user can retry
6249
+ // against the same ticket — re-render the view carrying the error.
6250
+ this.setState({ view: 'two-factor', ticket, methods, error: message });
6251
+ }
6252
+ }
6053
6253
  async handleTotpResend() {
6054
6254
  if (this.viewState.view !== 'totp-verify')
6055
6255
  return;