@sparkvault/sdk-js 1.24.4 → 1.24.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.
@@ -64,6 +64,14 @@ class PopupBlockedError extends SparkVaultError {
64
64
  /**
65
65
  * SparkVault SDK Configuration
66
66
  */
67
+ // Hosts that are allowed to serve backend-issued ingot download URLs.
68
+ // Keep in sync with the sdk-mobile default in packages/sdk-mobile/src/config.ts.
69
+ const DEFAULT_ALLOWED_DOWNLOAD_HOST_PATTERNS = [
70
+ /(^|\.)sparkvault\.com$/i,
71
+ /(^|\.)(x|files|file|send|spark|by|at|db|auth)\.sv$/i,
72
+ /\.amazonaws\.com$/i,
73
+ /\.cloudfront\.net$/i,
74
+ ];
67
75
  const API_URL = 'https://api.sparkvault.com';
68
76
  const IDENTITY_URL = 'https://api.sparkvault.com/v1/apps/identity';
69
77
  function normalizeApiBaseUrl(url) {
@@ -84,6 +92,7 @@ function resolveConfig(config) {
84
92
  apiKey: config.apiKey,
85
93
  preloadConfig: config.preloadConfig !== false, // Default: true
86
94
  backdropBlur: config.backdropBlur !== false, // Default: true
95
+ allowedDownloadHostPatterns: config.allowedDownloadHostPatterns ?? DEFAULT_ALLOWED_DOWNLOAD_HOST_PATTERNS,
87
96
  };
88
97
  }
89
98
  function validateConfig(config) {
@@ -9653,6 +9662,7 @@ class VaultUploadModule {
9653
9662
  */
9654
9663
  class VaultsModule {
9655
9664
  constructor(config, http) {
9665
+ this.config = config;
9656
9666
  this.http = http;
9657
9667
  this.uploadModule = new VaultUploadModule(config);
9658
9668
  // Create callable that also has attach/close methods
@@ -9700,13 +9710,15 @@ class VaultsModule {
9700
9710
  }
9701
9711
  const cleanId = vaultId.startsWith('vlt_') ? vaultId : `vlt_${vaultId}`;
9702
9712
  const response = await this.http.post(`/v1/vaults/${cleanId}/unseal`, { vmk });
9713
+ if (!response.data.vat) {
9714
+ throw new ValidationError('Unseal response did not include a vault access token');
9715
+ }
9703
9716
  return {
9704
9717
  id: response.data.vault_id,
9705
- name: response.data.name ?? '',
9706
- vatToken: response.data.vat_token ?? response.data.vat ?? '',
9718
+ vatToken: response.data.vat,
9719
+ issuedAt: response.data.issued_at,
9707
9720
  expiresAt: response.data.expires_at,
9708
- ingotCount: response.data.ingot_count ?? 0,
9709
- storageBytes: response.data.storage_bytes ?? response.data.storage_used_bytes ?? 0,
9721
+ ttlSeconds: response.data.ttl_seconds,
9710
9722
  };
9711
9723
  }
9712
9724
  /**
@@ -9751,26 +9763,26 @@ class VaultsModule {
9751
9763
  */
9752
9764
  async uploadIngot(vault, options) {
9753
9765
  this.validateUploadOptions(options);
9754
- const name = options.name ?? getBlobName(options.file);
9755
- const contentType = options.contentType ?? options.file.type ?? 'application/octet-stream';
9766
+ const requestedName = options.name ?? getBlobName(options.file);
9767
+ const requestedContentType = options.contentType ?? options.file.type ?? 'application/octet-stream';
9756
9768
  const createResponse = await this.http.post(`/v1/vaults/${vault.id}/ingots`, {
9757
- name,
9758
- content_type: contentType,
9769
+ name: requestedName,
9770
+ content_type: requestedContentType,
9759
9771
  size_bytes: options.file.size,
9760
9772
  }, {
9761
9773
  headers: { 'X-Vault-Access-Token': vault.vatToken },
9762
9774
  });
9763
- if (!createResponse.data.forge_url) {
9775
+ const created = createResponse.data;
9776
+ if (!created.forge_url) {
9764
9777
  throw new ValidationError('Upload endpoint did not return a Forge upload URL');
9765
9778
  }
9766
- await uploadBlobWithTus(options.file, createResponse.data.forge_url, name, contentType, options.onProgress);
9779
+ await uploadBlobWithTus(options.file, created.forge_url, created.name, created.content_type, options.onProgress);
9767
9780
  return {
9768
- id: createResponse.data.ingot_id,
9769
- name: createResponse.data.name ?? name,
9770
- contentType: createResponse.data.content_type ?? contentType,
9771
- size: createResponse.data.size_bytes ?? options.file.size,
9772
- createdAt: createResponse.data.created_at ?? Math.floor(Date.now() / 1000),
9773
- type: createResponse.data.ingot_type ?? 'standard',
9781
+ id: created.ingot_id,
9782
+ name: created.name,
9783
+ contentType: created.content_type,
9784
+ size: created.size_bytes,
9785
+ uploadExpiresAt: created.expires_at,
9774
9786
  };
9775
9787
  }
9776
9788
  /**
@@ -9782,13 +9794,27 @@ class VaultsModule {
9782
9794
  */
9783
9795
  async downloadIngot(vault, ingotId) {
9784
9796
  const cleanId = ingotId.startsWith('ing_') ? ingotId : `ing_${ingotId}`;
9785
- const response = await this.http.post(`/v1/vaults/${vault.id}/ingots/${cleanId}/download`, undefined, {
9786
- headers: { 'X-Vault-Access-Token': vault.vatToken },
9787
- });
9788
- if (!response.data.download_url) {
9789
- throw new ValidationError('Download endpoint did not return a download URL');
9797
+ let lastError = null;
9798
+ for (let attempt = 1; attempt <= DOWNLOAD_MAX_ATTEMPTS; attempt++) {
9799
+ try {
9800
+ const response = await this.http.post(`/v1/vaults/${vault.id}/ingots/${cleanId}/download`, undefined, {
9801
+ headers: { 'X-Vault-Access-Token': vault.vatToken },
9802
+ });
9803
+ if (!response.data.download_url) {
9804
+ throw new ValidationError('Download endpoint did not return a download URL');
9805
+ }
9806
+ this.validateDownloadUrl(response.data.download_url);
9807
+ return await fetchBlobWithTimeout(response.data.download_url);
9808
+ }
9809
+ catch (err) {
9810
+ lastError = err instanceof Error ? err : new Error(String(err));
9811
+ if (!isRetryableDownloadError(lastError) || attempt === DOWNLOAD_MAX_ATTEMPTS) {
9812
+ throw lastError;
9813
+ }
9814
+ await delayExponential(attempt);
9815
+ }
9790
9816
  }
9791
- return fetchBlobWithTimeout(response.data.download_url);
9817
+ throw lastError ?? new Error('Download failed');
9792
9818
  }
9793
9819
  /**
9794
9820
  * List all ingots in an unsealed vault.
@@ -9807,7 +9833,6 @@ class VaultsModule {
9807
9833
  contentType: i.content_type,
9808
9834
  size: i.size_bytes,
9809
9835
  createdAt: i.created_at,
9810
- type: i.ingot_type,
9811
9836
  }));
9812
9837
  }
9813
9838
  /**
@@ -9838,6 +9863,22 @@ class VaultsModule {
9838
9863
  throw new ValidationError('File cannot be empty');
9839
9864
  }
9840
9865
  }
9866
+ validateDownloadUrl(downloadUrl) {
9867
+ let parsed;
9868
+ try {
9869
+ parsed = new URL(downloadUrl);
9870
+ }
9871
+ catch {
9872
+ throw new ValidationError('Invalid download URL from server');
9873
+ }
9874
+ if (parsed.protocol !== 'https:') {
9875
+ throw new ValidationError('Download URL must use HTTPS');
9876
+ }
9877
+ const allowedHosts = this.config.allowedDownloadHostPatterns;
9878
+ if (!allowedHosts.some(pattern => pattern.test(parsed.hostname))) {
9879
+ throw new ValidationError('Invalid download URL from server');
9880
+ }
9881
+ }
9841
9882
  }
9842
9883
  function getBlobName(file) {
9843
9884
  if (typeof File !== 'undefined' && file instanceof File && file.name) {
@@ -9917,17 +9958,32 @@ function uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, tusVer
9917
9958
  xhr.send(chunk);
9918
9959
  });
9919
9960
  }
9920
- async function fetchBlobWithTimeout(url, timeout = 300000) {
9921
- const parsed = new URL(url);
9922
- if (parsed.protocol !== 'https:') {
9923
- throw new ValidationError('Download URL must use HTTPS');
9961
+ const DOWNLOAD_MAX_ATTEMPTS = 3;
9962
+ const DOWNLOAD_RETRY_BASE_MS = 500;
9963
+ function delayExponential(attempt) {
9964
+ return new Promise(resolve => setTimeout(resolve, DOWNLOAD_RETRY_BASE_MS * 2 ** (attempt - 1)));
9965
+ }
9966
+ function isRetryableDownloadError(err) {
9967
+ // Server contract / client-side validation errors aren't fixed by retrying.
9968
+ if (err instanceof ValidationError)
9969
+ return false;
9970
+ // Network errors carry a status code only when the SDK HTTP client attached
9971
+ // one; treat any explicitly-4xx response as a permanent failure.
9972
+ const status = err.statusCode;
9973
+ if (typeof status === 'number' && status >= 400 && status < 500 && status !== 408 && status !== 429) {
9974
+ return false;
9924
9975
  }
9976
+ return true;
9977
+ }
9978
+ async function fetchBlobWithTimeout(url, timeout = 300000) {
9925
9979
  const controller = new AbortController();
9926
9980
  const timeoutId = setTimeout(() => controller.abort(), timeout);
9927
9981
  try {
9928
9982
  const response = await fetch(url, { signal: controller.signal });
9929
9983
  if (!response.ok) {
9930
- throw new Error(`Download failed with status ${response.status}`);
9984
+ const error = new Error(`Download failed with status ${response.status}`);
9985
+ error.statusCode = response.status;
9986
+ throw error;
9931
9987
  }
9932
9988
  return response.blob();
9933
9989
  }
@@ -10105,7 +10161,7 @@ function autoInit(SparkVaultClass) {
10105
10161
  *
10106
10162
  * @example npm/Bundler Usage
10107
10163
  * ```typescript
10108
- * import SparkVault from '@sparkvault/sdk';
10164
+ * import SparkVault from '@sparkvault/sdk-js';
10109
10165
  *
10110
10166
  * const sv = SparkVault.init({ accountId: 'acc_your_account' });
10111
10167
  *