@sparkvault/sdk-js 2.0.2 → 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.
@@ -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
  *
@@ -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;
@@ -5981,6 +6145,14 @@ class IdentityRenderer {
5981
6145
  return;
5982
6146
  const currentMethod = this.verificationState.totp.method ?? 'email';
5983
6147
  const result = await this.totpHandler.verify(code);
6148
+ if (result.secondFactor) {
6149
+ this.setState({
6150
+ view: 'two-factor',
6151
+ ticket: result.secondFactor.ticket,
6152
+ methods: result.secondFactor.methods,
6153
+ });
6154
+ return;
6155
+ }
5984
6156
  if (result.success && result.result) {
5985
6157
  // Passkey upsell only when there's no redirect target — with one,
5986
6158
  // we head to the destination immediately.
@@ -6046,6 +6218,34 @@ class IdentityRenderer {
6046
6218
  });
6047
6219
  }
6048
6220
  }
6221
+ async handleSecondFactorSubmit(code) {
6222
+ if (this.viewState.view !== 'two-factor')
6223
+ return;
6224
+ const { ticket, methods } = this.viewState;
6225
+ try {
6226
+ const response = await this.api.submitSecondFactor({ ticket, code });
6227
+ const result = {
6228
+ token: response.token ?? '',
6229
+ identity: response.identity ?? this.recipient,
6230
+ identityType: response.identity_type ?? this.identityType,
6231
+ svid: response.svid,
6232
+ sessionId: response.session_id,
6233
+ refreshToken: response.refresh_token,
6234
+ redirect: response.redirect,
6235
+ };
6236
+ this.close();
6237
+ this.safeOnSuccess(result);
6238
+ if (typeof result.redirect === 'string' && result.redirect) {
6239
+ window.location.href = result.redirect;
6240
+ }
6241
+ }
6242
+ catch (error) {
6243
+ const message = error instanceof Error ? error.message : 'That code is not valid. Please try again.';
6244
+ // The login ticket is not consumed on a wrong code, so the user can retry
6245
+ // against the same ticket — re-render the view carrying the error.
6246
+ this.setState({ view: 'two-factor', ticket, methods, error: message });
6247
+ }
6248
+ }
6049
6249
  async handleTotpResend() {
6050
6250
  if (this.viewState.view !== 'totp-verify')
6051
6251
  return;
@@ -7094,6 +7294,19 @@ function isInitiateUploadResponse(data) {
7094
7294
  const d = data;
7095
7295
  return typeof d.forge_url === 'string' && typeof d.ingot_id === 'string';
7096
7296
  }
7297
+ /** tus protocol version used for the resumable upload session. */
7298
+ const TUS_VERSION = '1.0.0';
7299
+ /**
7300
+ * Server-side finalization confirmation poll.
7301
+ *
7302
+ * After the last chunk is PATCHed, Forge advances the session offset (and
7303
+ * flips the ingot to `active`) only once the chunk has actually committed to
7304
+ * S3. We re-read the server's *own persisted* `Upload-Offset` via a TUS HEAD
7305
+ * — independent of the offset the PATCH response claimed — and require it to
7306
+ * reach the declared total before reporting success.
7307
+ */
7308
+ const FINALIZE_POLL_MAX = 10;
7309
+ const FINALIZE_POLL_MS = 1000;
7097
7310
  class UploadApi extends SparkVaultApi {
7098
7311
  constructor(config) {
7099
7312
  super(config.timeout);
@@ -7165,6 +7378,104 @@ class UploadApi extends SparkVaultApi {
7165
7378
  ingotId: response.data.ingot_id,
7166
7379
  };
7167
7380
  }
7381
+ /**
7382
+ * Confirm the upload was finalized SERVER-SIDE before reporting success.
7383
+ *
7384
+ * The TUS PATCH loop trusts a server-provided `Upload-Offset`; a buggy or
7385
+ * malicious Forge could return an inflated offset before every chunk was
7386
+ * actually committed and encrypted. This re-reads the server's own
7387
+ * persisted offset via a TUS HEAD (which Forge only advances on a real S3
7388
+ * commit) and requires it to reach the declared total — the web equivalent
7389
+ * of the mobile SDK's `verifyIngotActive` (status === 'active') guarantee.
7390
+ *
7391
+ * Polls because the final chunk's commit and the offset write can lag the
7392
+ * PATCH acknowledgement by a moment. Throws on a non-2xx HEAD, on a session
7393
+ * that never reaches the expected offset within the poll budget, or on a
7394
+ * cancelled session — never reports a half-finished upload as done.
7395
+ *
7396
+ * @param uploadUrl - The TUS session URL (Forge `Location`, ISTK-bound).
7397
+ * @param expectedOffset - The declared total upload size in bytes.
7398
+ */
7399
+ async verifyUploadFinalized(uploadUrl, expectedOffset) {
7400
+ let lastOffset = null;
7401
+ for (let attempt = 1; attempt <= FINALIZE_POLL_MAX; attempt++) {
7402
+ if (this.isAborted()) {
7403
+ throw new UploadApiError('Upload cancelled', 'cancelled', 0);
7404
+ }
7405
+ const offset = await this.headUploadOffset(uploadUrl);
7406
+ lastOffset = offset;
7407
+ if (offset >= expectedOffset) {
7408
+ return;
7409
+ }
7410
+ if (attempt < FINALIZE_POLL_MAX) {
7411
+ await new Promise(resolve => setTimeout(resolve, FINALIZE_POLL_MS));
7412
+ }
7413
+ }
7414
+ throw new UploadApiError('Upload could not be confirmed: the server never finalized the file. ' +
7415
+ `Confirmed ${lastOffset ?? 0} of ${expectedOffset} bytes.`, 'finalization_unconfirmed', 0, { confirmedBytes: lastOffset ?? 0, expectedBytes: expectedOffset });
7416
+ }
7417
+ /**
7418
+ * Read the server's persisted upload offset via a TUS HEAD request.
7419
+ *
7420
+ * Uses raw `fetch` rather than the JSON envelope helper: TUS responses
7421
+ * carry an empty body and surface state in the `Upload-Offset` header.
7422
+ * Honors the session abort signal and request timeout like every other
7423
+ * client call.
7424
+ */
7425
+ async headUploadOffset(uploadUrl) {
7426
+ const closeSignal = this.getAbortSignal();
7427
+ const timeoutController = new AbortController();
7428
+ const timeoutId = setTimeout(() => timeoutController.abort(), this.timeoutMs);
7429
+ // Combine timeout + session-close into one signal. Mirror the base
7430
+ // client's fallback for browsers without AbortSignal.any: link the close
7431
+ // signal into the timeout controller and remove the listener in finally.
7432
+ let combinedSignal;
7433
+ let onCloseAbort = null;
7434
+ if ('any' in AbortSignal) {
7435
+ combinedSignal = AbortSignal.any([timeoutController.signal, closeSignal]);
7436
+ }
7437
+ else {
7438
+ combinedSignal = timeoutController.signal;
7439
+ onCloseAbort = () => timeoutController.abort();
7440
+ closeSignal.addEventListener('abort', onCloseAbort);
7441
+ }
7442
+ try {
7443
+ const response = await fetch(uploadUrl, {
7444
+ method: 'HEAD',
7445
+ headers: { 'Tus-Resumable': TUS_VERSION },
7446
+ signal: combinedSignal,
7447
+ });
7448
+ if (!response.ok) {
7449
+ throw new UploadApiError(`Upload finalization check failed: ${response.status}`, 'finalization_check_failed', response.status);
7450
+ }
7451
+ const header = response.headers.get('Upload-Offset');
7452
+ const offset = header !== null ? parseInt(header, 10) : NaN;
7453
+ if (!Number.isFinite(offset) || offset < 0) {
7454
+ throw new UploadApiError('Upload finalization check returned an invalid offset', 'finalization_check_failed', response.status);
7455
+ }
7456
+ return offset;
7457
+ }
7458
+ catch (error) {
7459
+ if (error instanceof SparkVaultError)
7460
+ throw error;
7461
+ if (error != null && typeof error === 'object' && 'name' in error && error.name === 'AbortError') {
7462
+ if (this.isAborted()) {
7463
+ throw new UploadApiError('Upload cancelled', 'cancelled', 0);
7464
+ }
7465
+ throw new UploadApiError(`Upload finalization check timed out after ${this.timeoutMs}ms`, 'timeout', 0);
7466
+ }
7467
+ if (error instanceof TypeError) {
7468
+ throw new UploadApiError('Unable to confirm upload. Please check your connection and try again.', 'network_error', 0);
7469
+ }
7470
+ throw new UploadApiError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
7471
+ }
7472
+ finally {
7473
+ clearTimeout(timeoutId);
7474
+ if (onCloseAbort) {
7475
+ closeSignal.removeEventListener('abort', onCloseAbort);
7476
+ }
7477
+ }
7478
+ }
7168
7479
  }
7169
7480
 
7170
7481
  /**
@@ -9587,7 +9898,13 @@ class UploadRenderer {
9587
9898
  bytesUploaded: 0,
9588
9899
  });
9589
9900
  // Upload file using tus (resumable upload)
9590
- await this.uploadWithTus(file, forgeUrl, ingotId, requestId);
9901
+ const uploadUrl = await this.uploadWithTus(file, forgeUrl, ingotId, requestId);
9902
+ // Confirm the server actually finalized the upload before celebrating.
9903
+ // The TUS loop trusts a server-provided offset; this re-reads the
9904
+ // server's own persisted offset and requires it to reach the file size,
9905
+ // mirroring the mobile SDK's active-status check. A non-finalized
9906
+ // upload throws here and never reaches the success ceremony.
9907
+ await this.api.verifyUploadFinalized(uploadUrl, file.size);
9591
9908
  // Run ceremony animation
9592
9909
  await this.runCeremony(file, ingotId, requestId);
9593
9910
  // Complete
@@ -9668,6 +9985,7 @@ class UploadRenderer {
9668
9985
  const newOffset = await this.uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, TUS_VERSION, file, ingotId, requestId);
9669
9986
  offset = newOffset;
9670
9987
  }
9988
+ return uploadUrl;
9671
9989
  }
9672
9990
  /**
9673
9991
  * Upload a single chunk using XMLHttpRequest for progress tracking.
@@ -9711,6 +10029,14 @@ class UploadRenderer {
9711
10029
  // Get new offset from server response
9712
10030
  const newOffsetHeader = xhr.getResponseHeader('Upload-Offset');
9713
10031
  const newOffset = newOffsetHeader ? parseInt(newOffsetHeader, 10) : chunkStart + chunk.size;
10032
+ // Defense-in-depth: the server must never report more bytes accepted
10033
+ // than the file contains. A `newOffset > totalSize` is a malformed or
10034
+ // inflated response — reject it rather than letting an over-reported
10035
+ // offset short-circuit the upload loop and skip real chunks.
10036
+ if (!Number.isFinite(newOffset) || newOffset < chunkStart || newOffset > totalSize) {
10037
+ reject(new Error(`Server returned invalid upload offset (${newOffset})`));
10038
+ return;
10039
+ }
9714
10040
  resolve(newOffset);
9715
10041
  }
9716
10042
  else {