@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.
package/dist/config.d.ts CHANGED
@@ -25,6 +25,12 @@ export interface SparkVaultConfig {
25
25
  preloadConfig?: boolean;
26
26
  /** Enable backdrop blur on dialogs (default: true) */
27
27
  backdropBlur?: boolean;
28
+ /**
29
+ * Host allowlist for backend-issued ingot download URLs. Defaults to the
30
+ * canonical SparkVault Forge / S3 / CloudFront hosts. Override only when
31
+ * pointing at a custom deployment.
32
+ */
33
+ allowedDownloadHostPatterns?: RegExp[];
28
34
  }
29
35
  export interface ResolvedConfig {
30
36
  accountId: string;
@@ -36,6 +42,7 @@ export interface ResolvedConfig {
36
42
  apiKey?: string;
37
43
  preloadConfig: boolean;
38
44
  backdropBlur: boolean;
45
+ allowedDownloadHostPatterns: RegExp[];
39
46
  }
40
47
  export declare function resolveConfig(config: SparkVaultConfig): ResolvedConfig;
41
48
  export declare function validateConfig(config: SparkVaultConfig): void;
package/dist/index.d.ts CHANGED
@@ -25,6 +25,12 @@ interface SparkVaultConfig {
25
25
  preloadConfig?: boolean;
26
26
  /** Enable backdrop blur on dialogs (default: true) */
27
27
  backdropBlur?: boolean;
28
+ /**
29
+ * Host allowlist for backend-issued ingot download URLs. Defaults to the
30
+ * canonical SparkVault Forge / S3 / CloudFront hosts. Override only when
31
+ * pointing at a custom deployment.
32
+ */
33
+ allowedDownloadHostPatterns?: RegExp[];
28
34
  }
29
35
  interface ResolvedConfig {
30
36
  accountId: string;
@@ -36,6 +42,7 @@ interface ResolvedConfig {
36
42
  apiKey?: string;
37
43
  preloadConfig: boolean;
38
44
  backdropBlur: boolean;
45
+ allowedDownloadHostPatterns: RegExp[];
39
46
  }
40
47
 
41
48
  interface HealthCheckOptions {
@@ -358,16 +365,14 @@ interface Vault {
358
365
  interface UnsealedVault {
359
366
  /** Vault ID */
360
367
  id: string;
361
- /** Vault name */
362
- name: string;
363
- /** Vault Access Token (short-lived session) */
368
+ /** Vault Access Token (short-lived session, required for all ingot operations) */
364
369
  vatToken: string;
370
+ /** VAT issued-at timestamp (Unix seconds) */
371
+ issuedAt: number;
365
372
  /** VAT expiry timestamp (Unix seconds) */
366
373
  expiresAt: number;
367
- /** Number of ingots in vault */
368
- ingotCount: number;
369
- /** Total storage used in bytes */
370
- storageBytes: number;
374
+ /** VAT lifetime in seconds */
375
+ ttlSeconds: number;
371
376
  }
372
377
  interface VaultSummary {
373
378
  /** Vault ID */
@@ -394,8 +399,18 @@ interface Ingot {
394
399
  size: number;
395
400
  /** Creation timestamp (Unix seconds) */
396
401
  createdAt: number;
397
- /** Ingot type: 'standard' or 'structured' */
398
- type: 'standard' | 'structured';
402
+ }
403
+ interface CreatedIngot {
404
+ /** Ingot ID */
405
+ id: string;
406
+ /** Ingot name */
407
+ name: string;
408
+ /** Content type (MIME) */
409
+ contentType: string;
410
+ /** Size in bytes */
411
+ size: number;
412
+ /** Forge upload session expiry (Unix seconds) */
413
+ uploadExpiresAt: number;
399
414
  }
400
415
  interface UploadIngotOptions {
401
416
  /** File to upload */
@@ -539,6 +554,7 @@ interface UploadCallable {
539
554
  close(): void;
540
555
  }
541
556
  declare class VaultsModule {
557
+ private readonly config;
542
558
  private readonly http;
543
559
  private readonly uploadModule;
544
560
  /**
@@ -598,7 +614,7 @@ declare class VaultsModule {
598
614
  * name: 'document.pdf'
599
615
  * });
600
616
  */
601
- uploadIngot(vault: UnsealedVault, options: UploadIngotOptions): Promise<Ingot>;
617
+ uploadIngot(vault: UnsealedVault, options: UploadIngotOptions): Promise<CreatedIngot>;
602
618
  /**
603
619
  * Download an ingot from an unsealed vault.
604
620
  *
@@ -624,6 +640,7 @@ declare class VaultsModule {
624
640
  deleteIngot(vault: UnsealedVault, ingotId: string): Promise<void>;
625
641
  private validateCreateOptions;
626
642
  private validateUploadOptions;
643
+ private validateDownloadUrl;
627
644
  }
628
645
 
629
646
  /**
@@ -689,7 +706,7 @@ declare const logger: {
689
706
  *
690
707
  * @example npm/Bundler Usage
691
708
  * ```typescript
692
- * import SparkVault from '@sparkvault/sdk';
709
+ * import SparkVault from '@sparkvault/sdk-js';
693
710
  *
694
711
  * const sv = SparkVault.init({ accountId: 'acc_your_account' });
695
712
  *
@@ -730,4 +747,4 @@ declare global {
730
747
  }
731
748
 
732
749
  export { AuthenticationError, AuthorizationError, NetworkError, PopupBlockedError, SparkVault, SparkVaultError, TimeoutError, UserCancelledError, ValidationError, SparkVault as default, logger, setDebugMode };
733
- export type { AuthMethod, CreateVaultOptions, HealthCheckOptions, HealthCheckResult, AttachOptions as IdentityAttachOptions, Ingot, SparkVaultConfig, Theme, TokenClaims, UnsealedVault, UploadAttachOptions, UploadBranding, UploadIngotOptions, UploadOptions, UploadProgress, UploadResult, Vault, VaultSummary, VaultUploadConfig, VerifyOptions, VerifyResult };
750
+ export type { AuthMethod, CreateVaultOptions, CreatedIngot, HealthCheckOptions, HealthCheckResult, AttachOptions as IdentityAttachOptions, Ingot, SparkVaultConfig, Theme, TokenClaims, UnsealedVault, UploadAttachOptions, UploadBranding, UploadIngotOptions, UploadOptions, UploadProgress, UploadResult, Vault, VaultSummary, VaultUploadConfig, VerifyOptions, VerifyResult };
@@ -68,6 +68,14 @@ class PopupBlockedError extends SparkVaultError {
68
68
  /**
69
69
  * SparkVault SDK Configuration
70
70
  */
71
+ // Hosts that are allowed to serve backend-issued ingot download URLs.
72
+ // Keep in sync with the sdk-mobile default in packages/sdk-mobile/src/config.ts.
73
+ const DEFAULT_ALLOWED_DOWNLOAD_HOST_PATTERNS = [
74
+ /(^|\.)sparkvault\.com$/i,
75
+ /(^|\.)(x|files|file|send|spark|by|at|db|auth)\.sv$/i,
76
+ /\.amazonaws\.com$/i,
77
+ /\.cloudfront\.net$/i,
78
+ ];
71
79
  const API_URL = 'https://api.sparkvault.com';
72
80
  const IDENTITY_URL = 'https://api.sparkvault.com/v1/apps/identity';
73
81
  function normalizeApiBaseUrl(url) {
@@ -88,6 +96,7 @@ function resolveConfig(config) {
88
96
  apiKey: config.apiKey,
89
97
  preloadConfig: config.preloadConfig !== false, // Default: true
90
98
  backdropBlur: config.backdropBlur !== false, // Default: true
99
+ allowedDownloadHostPatterns: config.allowedDownloadHostPatterns ?? DEFAULT_ALLOWED_DOWNLOAD_HOST_PATTERNS,
91
100
  };
92
101
  }
93
102
  function validateConfig(config) {
@@ -9657,6 +9666,7 @@ class VaultUploadModule {
9657
9666
  */
9658
9667
  class VaultsModule {
9659
9668
  constructor(config, http) {
9669
+ this.config = config;
9660
9670
  this.http = http;
9661
9671
  this.uploadModule = new VaultUploadModule(config);
9662
9672
  // Create callable that also has attach/close methods
@@ -9704,13 +9714,15 @@ class VaultsModule {
9704
9714
  }
9705
9715
  const cleanId = vaultId.startsWith('vlt_') ? vaultId : `vlt_${vaultId}`;
9706
9716
  const response = await this.http.post(`/v1/vaults/${cleanId}/unseal`, { vmk });
9717
+ if (!response.data.vat) {
9718
+ throw new ValidationError('Unseal response did not include a vault access token');
9719
+ }
9707
9720
  return {
9708
9721
  id: response.data.vault_id,
9709
- name: response.data.name ?? '',
9710
- vatToken: response.data.vat_token ?? response.data.vat ?? '',
9722
+ vatToken: response.data.vat,
9723
+ issuedAt: response.data.issued_at,
9711
9724
  expiresAt: response.data.expires_at,
9712
- ingotCount: response.data.ingot_count ?? 0,
9713
- storageBytes: response.data.storage_bytes ?? response.data.storage_used_bytes ?? 0,
9725
+ ttlSeconds: response.data.ttl_seconds,
9714
9726
  };
9715
9727
  }
9716
9728
  /**
@@ -9755,26 +9767,26 @@ class VaultsModule {
9755
9767
  */
9756
9768
  async uploadIngot(vault, options) {
9757
9769
  this.validateUploadOptions(options);
9758
- const name = options.name ?? getBlobName(options.file);
9759
- const contentType = options.contentType ?? options.file.type ?? 'application/octet-stream';
9770
+ const requestedName = options.name ?? getBlobName(options.file);
9771
+ const requestedContentType = options.contentType ?? options.file.type ?? 'application/octet-stream';
9760
9772
  const createResponse = await this.http.post(`/v1/vaults/${vault.id}/ingots`, {
9761
- name,
9762
- content_type: contentType,
9773
+ name: requestedName,
9774
+ content_type: requestedContentType,
9763
9775
  size_bytes: options.file.size,
9764
9776
  }, {
9765
9777
  headers: { 'X-Vault-Access-Token': vault.vatToken },
9766
9778
  });
9767
- if (!createResponse.data.forge_url) {
9779
+ const created = createResponse.data;
9780
+ if (!created.forge_url) {
9768
9781
  throw new ValidationError('Upload endpoint did not return a Forge upload URL');
9769
9782
  }
9770
- await uploadBlobWithTus(options.file, createResponse.data.forge_url, name, contentType, options.onProgress);
9783
+ await uploadBlobWithTus(options.file, created.forge_url, created.name, created.content_type, options.onProgress);
9771
9784
  return {
9772
- id: createResponse.data.ingot_id,
9773
- name: createResponse.data.name ?? name,
9774
- contentType: createResponse.data.content_type ?? contentType,
9775
- size: createResponse.data.size_bytes ?? options.file.size,
9776
- createdAt: createResponse.data.created_at ?? Math.floor(Date.now() / 1000),
9777
- type: createResponse.data.ingot_type ?? 'standard',
9785
+ id: created.ingot_id,
9786
+ name: created.name,
9787
+ contentType: created.content_type,
9788
+ size: created.size_bytes,
9789
+ uploadExpiresAt: created.expires_at,
9778
9790
  };
9779
9791
  }
9780
9792
  /**
@@ -9786,13 +9798,27 @@ class VaultsModule {
9786
9798
  */
9787
9799
  async downloadIngot(vault, ingotId) {
9788
9800
  const cleanId = ingotId.startsWith('ing_') ? ingotId : `ing_${ingotId}`;
9789
- const response = await this.http.post(`/v1/vaults/${vault.id}/ingots/${cleanId}/download`, undefined, {
9790
- headers: { 'X-Vault-Access-Token': vault.vatToken },
9791
- });
9792
- if (!response.data.download_url) {
9793
- throw new ValidationError('Download endpoint did not return a download URL');
9801
+ let lastError = null;
9802
+ for (let attempt = 1; attempt <= DOWNLOAD_MAX_ATTEMPTS; attempt++) {
9803
+ try {
9804
+ const response = await this.http.post(`/v1/vaults/${vault.id}/ingots/${cleanId}/download`, undefined, {
9805
+ headers: { 'X-Vault-Access-Token': vault.vatToken },
9806
+ });
9807
+ if (!response.data.download_url) {
9808
+ throw new ValidationError('Download endpoint did not return a download URL');
9809
+ }
9810
+ this.validateDownloadUrl(response.data.download_url);
9811
+ return await fetchBlobWithTimeout(response.data.download_url);
9812
+ }
9813
+ catch (err) {
9814
+ lastError = err instanceof Error ? err : new Error(String(err));
9815
+ if (!isRetryableDownloadError(lastError) || attempt === DOWNLOAD_MAX_ATTEMPTS) {
9816
+ throw lastError;
9817
+ }
9818
+ await delayExponential(attempt);
9819
+ }
9794
9820
  }
9795
- return fetchBlobWithTimeout(response.data.download_url);
9821
+ throw lastError ?? new Error('Download failed');
9796
9822
  }
9797
9823
  /**
9798
9824
  * List all ingots in an unsealed vault.
@@ -9811,7 +9837,6 @@ class VaultsModule {
9811
9837
  contentType: i.content_type,
9812
9838
  size: i.size_bytes,
9813
9839
  createdAt: i.created_at,
9814
- type: i.ingot_type,
9815
9840
  }));
9816
9841
  }
9817
9842
  /**
@@ -9842,6 +9867,22 @@ class VaultsModule {
9842
9867
  throw new ValidationError('File cannot be empty');
9843
9868
  }
9844
9869
  }
9870
+ validateDownloadUrl(downloadUrl) {
9871
+ let parsed;
9872
+ try {
9873
+ parsed = new URL(downloadUrl);
9874
+ }
9875
+ catch {
9876
+ throw new ValidationError('Invalid download URL from server');
9877
+ }
9878
+ if (parsed.protocol !== 'https:') {
9879
+ throw new ValidationError('Download URL must use HTTPS');
9880
+ }
9881
+ const allowedHosts = this.config.allowedDownloadHostPatterns;
9882
+ if (!allowedHosts.some(pattern => pattern.test(parsed.hostname))) {
9883
+ throw new ValidationError('Invalid download URL from server');
9884
+ }
9885
+ }
9845
9886
  }
9846
9887
  function getBlobName(file) {
9847
9888
  if (typeof File !== 'undefined' && file instanceof File && file.name) {
@@ -9921,17 +9962,32 @@ function uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, tusVer
9921
9962
  xhr.send(chunk);
9922
9963
  });
9923
9964
  }
9924
- async function fetchBlobWithTimeout(url, timeout = 300000) {
9925
- const parsed = new URL(url);
9926
- if (parsed.protocol !== 'https:') {
9927
- throw new ValidationError('Download URL must use HTTPS');
9965
+ const DOWNLOAD_MAX_ATTEMPTS = 3;
9966
+ const DOWNLOAD_RETRY_BASE_MS = 500;
9967
+ function delayExponential(attempt) {
9968
+ return new Promise(resolve => setTimeout(resolve, DOWNLOAD_RETRY_BASE_MS * 2 ** (attempt - 1)));
9969
+ }
9970
+ function isRetryableDownloadError(err) {
9971
+ // Server contract / client-side validation errors aren't fixed by retrying.
9972
+ if (err instanceof ValidationError)
9973
+ return false;
9974
+ // Network errors carry a status code only when the SDK HTTP client attached
9975
+ // one; treat any explicitly-4xx response as a permanent failure.
9976
+ const status = err.statusCode;
9977
+ if (typeof status === 'number' && status >= 400 && status < 500 && status !== 408 && status !== 429) {
9978
+ return false;
9928
9979
  }
9980
+ return true;
9981
+ }
9982
+ async function fetchBlobWithTimeout(url, timeout = 300000) {
9929
9983
  const controller = new AbortController();
9930
9984
  const timeoutId = setTimeout(() => controller.abort(), timeout);
9931
9985
  try {
9932
9986
  const response = await fetch(url, { signal: controller.signal });
9933
9987
  if (!response.ok) {
9934
- throw new Error(`Download failed with status ${response.status}`);
9988
+ const error = new Error(`Download failed with status ${response.status}`);
9989
+ error.statusCode = response.status;
9990
+ throw error;
9935
9991
  }
9936
9992
  return response.blob();
9937
9993
  }
@@ -10109,7 +10165,7 @@ function autoInit(SparkVaultClass) {
10109
10165
  *
10110
10166
  * @example npm/Bundler Usage
10111
10167
  * ```typescript
10112
- * import SparkVault from '@sparkvault/sdk';
10168
+ * import SparkVault from '@sparkvault/sdk-js';
10113
10169
  *
10114
10170
  * const sv = SparkVault.init({ accountId: 'acc_your_account' });
10115
10171
  *