@sparkvault/sdk-js 2.0.2 → 2.0.3

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.
@@ -7094,6 +7094,19 @@ function isInitiateUploadResponse(data) {
7094
7094
  const d = data;
7095
7095
  return typeof d.forge_url === 'string' && typeof d.ingot_id === 'string';
7096
7096
  }
7097
+ /** tus protocol version used for the resumable upload session. */
7098
+ const TUS_VERSION = '1.0.0';
7099
+ /**
7100
+ * Server-side finalization confirmation poll.
7101
+ *
7102
+ * After the last chunk is PATCHed, Forge advances the session offset (and
7103
+ * flips the ingot to `active`) only once the chunk has actually committed to
7104
+ * S3. We re-read the server's *own persisted* `Upload-Offset` via a TUS HEAD
7105
+ * — independent of the offset the PATCH response claimed — and require it to
7106
+ * reach the declared total before reporting success.
7107
+ */
7108
+ const FINALIZE_POLL_MAX = 10;
7109
+ const FINALIZE_POLL_MS = 1000;
7097
7110
  class UploadApi extends SparkVaultApi {
7098
7111
  constructor(config) {
7099
7112
  super(config.timeout);
@@ -7165,6 +7178,104 @@ class UploadApi extends SparkVaultApi {
7165
7178
  ingotId: response.data.ingot_id,
7166
7179
  };
7167
7180
  }
7181
+ /**
7182
+ * Confirm the upload was finalized SERVER-SIDE before reporting success.
7183
+ *
7184
+ * The TUS PATCH loop trusts a server-provided `Upload-Offset`; a buggy or
7185
+ * malicious Forge could return an inflated offset before every chunk was
7186
+ * actually committed and encrypted. This re-reads the server's own
7187
+ * persisted offset via a TUS HEAD (which Forge only advances on a real S3
7188
+ * commit) and requires it to reach the declared total — the web equivalent
7189
+ * of the mobile SDK's `verifyIngotActive` (status === 'active') guarantee.
7190
+ *
7191
+ * Polls because the final chunk's commit and the offset write can lag the
7192
+ * PATCH acknowledgement by a moment. Throws on a non-2xx HEAD, on a session
7193
+ * that never reaches the expected offset within the poll budget, or on a
7194
+ * cancelled session — never reports a half-finished upload as done.
7195
+ *
7196
+ * @param uploadUrl - The TUS session URL (Forge `Location`, ISTK-bound).
7197
+ * @param expectedOffset - The declared total upload size in bytes.
7198
+ */
7199
+ async verifyUploadFinalized(uploadUrl, expectedOffset) {
7200
+ let lastOffset = null;
7201
+ for (let attempt = 1; attempt <= FINALIZE_POLL_MAX; attempt++) {
7202
+ if (this.isAborted()) {
7203
+ throw new UploadApiError('Upload cancelled', 'cancelled', 0);
7204
+ }
7205
+ const offset = await this.headUploadOffset(uploadUrl);
7206
+ lastOffset = offset;
7207
+ if (offset >= expectedOffset) {
7208
+ return;
7209
+ }
7210
+ if (attempt < FINALIZE_POLL_MAX) {
7211
+ await new Promise(resolve => setTimeout(resolve, FINALIZE_POLL_MS));
7212
+ }
7213
+ }
7214
+ throw new UploadApiError('Upload could not be confirmed: the server never finalized the file. ' +
7215
+ `Confirmed ${lastOffset ?? 0} of ${expectedOffset} bytes.`, 'finalization_unconfirmed', 0, { confirmedBytes: lastOffset ?? 0, expectedBytes: expectedOffset });
7216
+ }
7217
+ /**
7218
+ * Read the server's persisted upload offset via a TUS HEAD request.
7219
+ *
7220
+ * Uses raw `fetch` rather than the JSON envelope helper: TUS responses
7221
+ * carry an empty body and surface state in the `Upload-Offset` header.
7222
+ * Honors the session abort signal and request timeout like every other
7223
+ * client call.
7224
+ */
7225
+ async headUploadOffset(uploadUrl) {
7226
+ const closeSignal = this.getAbortSignal();
7227
+ const timeoutController = new AbortController();
7228
+ const timeoutId = setTimeout(() => timeoutController.abort(), this.timeoutMs);
7229
+ // Combine timeout + session-close into one signal. Mirror the base
7230
+ // client's fallback for browsers without AbortSignal.any: link the close
7231
+ // signal into the timeout controller and remove the listener in finally.
7232
+ let combinedSignal;
7233
+ let onCloseAbort = null;
7234
+ if ('any' in AbortSignal) {
7235
+ combinedSignal = AbortSignal.any([timeoutController.signal, closeSignal]);
7236
+ }
7237
+ else {
7238
+ combinedSignal = timeoutController.signal;
7239
+ onCloseAbort = () => timeoutController.abort();
7240
+ closeSignal.addEventListener('abort', onCloseAbort);
7241
+ }
7242
+ try {
7243
+ const response = await fetch(uploadUrl, {
7244
+ method: 'HEAD',
7245
+ headers: { 'Tus-Resumable': TUS_VERSION },
7246
+ signal: combinedSignal,
7247
+ });
7248
+ if (!response.ok) {
7249
+ throw new UploadApiError(`Upload finalization check failed: ${response.status}`, 'finalization_check_failed', response.status);
7250
+ }
7251
+ const header = response.headers.get('Upload-Offset');
7252
+ const offset = header !== null ? parseInt(header, 10) : NaN;
7253
+ if (!Number.isFinite(offset) || offset < 0) {
7254
+ throw new UploadApiError('Upload finalization check returned an invalid offset', 'finalization_check_failed', response.status);
7255
+ }
7256
+ return offset;
7257
+ }
7258
+ catch (error) {
7259
+ if (error instanceof SparkVaultError)
7260
+ throw error;
7261
+ if (error != null && typeof error === 'object' && 'name' in error && error.name === 'AbortError') {
7262
+ if (this.isAborted()) {
7263
+ throw new UploadApiError('Upload cancelled', 'cancelled', 0);
7264
+ }
7265
+ throw new UploadApiError(`Upload finalization check timed out after ${this.timeoutMs}ms`, 'timeout', 0);
7266
+ }
7267
+ if (error instanceof TypeError) {
7268
+ throw new UploadApiError('Unable to confirm upload. Please check your connection and try again.', 'network_error', 0);
7269
+ }
7270
+ throw new UploadApiError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
7271
+ }
7272
+ finally {
7273
+ clearTimeout(timeoutId);
7274
+ if (onCloseAbort) {
7275
+ closeSignal.removeEventListener('abort', onCloseAbort);
7276
+ }
7277
+ }
7278
+ }
7168
7279
  }
7169
7280
 
7170
7281
  /**
@@ -9587,7 +9698,13 @@ class UploadRenderer {
9587
9698
  bytesUploaded: 0,
9588
9699
  });
9589
9700
  // Upload file using tus (resumable upload)
9590
- await this.uploadWithTus(file, forgeUrl, ingotId, requestId);
9701
+ const uploadUrl = await this.uploadWithTus(file, forgeUrl, ingotId, requestId);
9702
+ // Confirm the server actually finalized the upload before celebrating.
9703
+ // The TUS loop trusts a server-provided offset; this re-reads the
9704
+ // server's own persisted offset and requires it to reach the file size,
9705
+ // mirroring the mobile SDK's active-status check. A non-finalized
9706
+ // upload throws here and never reaches the success ceremony.
9707
+ await this.api.verifyUploadFinalized(uploadUrl, file.size);
9591
9708
  // Run ceremony animation
9592
9709
  await this.runCeremony(file, ingotId, requestId);
9593
9710
  // Complete
@@ -9668,6 +9785,7 @@ class UploadRenderer {
9668
9785
  const newOffset = await this.uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, TUS_VERSION, file, ingotId, requestId);
9669
9786
  offset = newOffset;
9670
9787
  }
9788
+ return uploadUrl;
9671
9789
  }
9672
9790
  /**
9673
9791
  * Upload a single chunk using XMLHttpRequest for progress tracking.
@@ -9711,6 +9829,14 @@ class UploadRenderer {
9711
9829
  // Get new offset from server response
9712
9830
  const newOffsetHeader = xhr.getResponseHeader('Upload-Offset');
9713
9831
  const newOffset = newOffsetHeader ? parseInt(newOffsetHeader, 10) : chunkStart + chunk.size;
9832
+ // Defense-in-depth: the server must never report more bytes accepted
9833
+ // than the file contains. A `newOffset > totalSize` is a malformed or
9834
+ // inflated response — reject it rather than letting an over-reported
9835
+ // offset short-circuit the upload loop and skip real chunks.
9836
+ if (!Number.isFinite(newOffset) || newOffset < chunkStart || newOffset > totalSize) {
9837
+ reject(new Error(`Server returned invalid upload offset (${newOffset})`));
9838
+ return;
9839
+ }
9714
9840
  resolve(newOffset);
9715
9841
  }
9716
9842
  else {