@sparkvault/sdk-js 2.2.5 → 4.1.0

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.
Files changed (57) hide show
  1. package/README.md +5 -5
  2. package/dist/auto-init.d.ts +1 -1
  3. package/dist/entropy/index.d.ts +28 -0
  4. package/dist/entropy/types.d.ts +32 -0
  5. package/dist/folders/index.d.ts +77 -0
  6. package/dist/folders/types.d.ts +64 -0
  7. package/dist/http.d.ts +3 -1
  8. package/dist/index.d.ts +982 -78
  9. package/dist/ingots/index.d.ts +183 -0
  10. package/dist/ingots/types.d.ts +286 -0
  11. package/dist/{identity → products/identity}/api.d.ts +8 -7
  12. package/dist/{identity → products/identity}/embedder.d.ts +1 -1
  13. package/dist/{identity → products/identity}/index.d.ts +7 -7
  14. package/dist/{identity → products/identity}/types.d.ts +15 -0
  15. package/dist/{identity → products/identity}/utils.d.ts +1 -1
  16. package/dist/products/index.d.ts +18 -0
  17. package/dist/sparks/index.d.ts +65 -0
  18. package/dist/sparks/types.d.ts +174 -0
  19. package/dist/sparkvault.cjs.js +1102 -111
  20. package/dist/sparkvault.cjs.js.map +1 -1
  21. package/dist/sparkvault.esm.js +1096 -112
  22. package/dist/sparkvault.esm.js.map +1 -1
  23. package/dist/sparkvault.js +1 -1
  24. package/dist/sparkvault.js.map +1 -1
  25. package/dist/vaults/index.d.ts +102 -34
  26. package/dist/vaults/types.d.ts +121 -57
  27. package/dist/vaults/upload/api.d.ts +1 -1
  28. package/package.json +1 -1
  29. /package/dist/{identity → products/identity}/container.d.ts +0 -0
  30. /package/dist/{identity → products/identity}/handlers/index.d.ts +0 -0
  31. /package/dist/{identity → products/identity}/handlers/passkey-handler.d.ts +0 -0
  32. /package/dist/{identity → products/identity}/handlers/sparklink-handler.d.ts +0 -0
  33. /package/dist/{identity → products/identity}/handlers/totp-handler.d.ts +0 -0
  34. /package/dist/{identity → products/identity}/inline-container.d.ts +0 -0
  35. /package/dist/{identity → products/identity}/methods.d.ts +0 -0
  36. /package/dist/{identity → products/identity}/modal.d.ts +0 -0
  37. /package/dist/{identity → products/identity}/renderer.d.ts +0 -0
  38. /package/dist/{identity → products/identity}/state.d.ts +0 -0
  39. /package/dist/{identity → products/identity}/styles.d.ts +0 -0
  40. /package/dist/{identity → products/identity}/utils/cooldown-timer.d.ts +0 -0
  41. /package/dist/{identity → products/identity}/utils/index.d.ts +0 -0
  42. /package/dist/{identity → products/identity}/views/backup-verify.d.ts +0 -0
  43. /package/dist/{identity → products/identity}/views/base.d.ts +0 -0
  44. /package/dist/{identity → products/identity}/views/error.d.ts +0 -0
  45. /package/dist/{identity → products/identity}/views/icons.d.ts +0 -0
  46. /package/dist/{identity → products/identity}/views/identity-input.d.ts +0 -0
  47. /package/dist/{identity → products/identity}/views/index.d.ts +0 -0
  48. /package/dist/{identity → products/identity}/views/loading.d.ts +0 -0
  49. /package/dist/{identity → products/identity}/views/method-select.d.ts +0 -0
  50. /package/dist/{identity → products/identity}/views/origin-not-allowed.d.ts +0 -0
  51. /package/dist/{identity → products/identity}/views/passkey-prompt.d.ts +0 -0
  52. /package/dist/{identity → products/identity}/views/passkey.d.ts +0 -0
  53. /package/dist/{identity → products/identity}/views/product-not-configured.d.ts +0 -0
  54. /package/dist/{identity → products/identity}/views/service-unavailable.d.ts +0 -0
  55. /package/dist/{identity → products/identity}/views/sparklink-waiting.d.ts +0 -0
  56. /package/dist/{identity → products/identity}/views/totp-verify.d.ts +0 -0
  57. /package/dist/{identity → products/identity}/views/two-factor.d.ts +0 -0
@@ -337,6 +337,12 @@ class HttpClient {
337
337
  post(path, body, options) {
338
338
  return this.request(path, { ...options, method: 'POST', body });
339
339
  }
340
+ put(path, body, options) {
341
+ return this.request(path, { ...options, method: 'PUT', body });
342
+ }
343
+ patch(path, body, options) {
344
+ return this.request(path, { ...options, method: 'PATCH', body });
345
+ }
340
346
  delete(path, options) {
341
347
  return this.request(path, { ...options, method: 'DELETE' });
342
348
  }
@@ -939,19 +945,22 @@ class IdentityApi extends SparkVaultApi {
939
945
  });
940
946
  }
941
947
  /**
942
- * Start discoverable passkey verification. Legacy identity parameters are
943
- * intentionally ignored; the credential userHandle routes completion to the
944
- * SVID.
948
+ * Start passkey verification. An optional identifier scopes the ceremony to
949
+ * that person's credentials (`allowCredentials`) so the authenticator offers
950
+ * only the matching passkey; omit it for a discoverable ceremony. Completion
951
+ * always routes via the credential userHandle, so scoping is purely a hint.
945
952
  */
946
- async startPasskeyVerify(_identity, _identityType = 'email', authContext) {
953
+ async startPasskeyVerify(identity, identityType = 'email', authContext) {
954
+ const identityParam = identity ? { [identityType]: identity } : {};
947
955
  // Backend returns { options: PublicKeyCredentialRequestOptions, session: {...} }
948
956
  // Extract and flatten to match PasskeyChallengeResponse
949
- const response = await this.request('POST', '/passkey/verify', this.buildAuthContextParams(authContext));
957
+ const response = await this.request('POST', '/passkey/verify', { ...identityParam, ...this.buildAuthContextParams(authContext) });
950
958
  return {
951
959
  challenge: response.options.challenge,
952
960
  rpId: response.options.rpId,
953
961
  rpName: 'SparkVault Identity', // Not returned by verify endpoint
954
962
  timeout: response.options.timeout,
963
+ ...(response.options.allowCredentials ? { allowCredentials: response.options.allowCredentials } : {}),
955
964
  session: response.session,
956
965
  };
957
966
  }
@@ -1417,13 +1426,24 @@ class PasskeyHandler {
1417
1426
  */
1418
1427
  async verifyInline() {
1419
1428
  try {
1420
- const challenge = await this.api.startPasskeyVerify(undefined, 'email', this.state.authContext);
1429
+ // When the widget has an identifier, scope the ceremony to that person's
1430
+ // passkeys so the authenticator offers only the matching credential;
1431
+ // without one it falls back to a discoverable ceremony.
1432
+ const identityType = this.state.identityType === 'phone' ? 'phone' : 'email';
1433
+ const challenge = await this.api.startPasskeyVerify(this.state.recipient, identityType, this.state.authContext);
1421
1434
  const credential = await navigator.credentials.get({
1422
1435
  publicKey: {
1423
1436
  challenge: base64urlToArrayBuffer(challenge.challenge),
1424
1437
  rpId: challenge.rpId,
1425
1438
  timeout: challenge.timeout,
1426
1439
  userVerification: 'required',
1440
+ ...(challenge.allowCredentials ? {
1441
+ allowCredentials: challenge.allowCredentials.map((c) => ({
1442
+ type: c.type,
1443
+ id: base64urlToArrayBuffer(c.id),
1444
+ ...(c.transports ? { transports: c.transports } : {}),
1445
+ })),
1446
+ } : {}),
1427
1447
  },
1428
1448
  });
1429
1449
  if (!credential) {
@@ -1500,14 +1520,15 @@ class PasskeyHandler {
1500
1520
  */
1501
1521
  async openPasskeyPopup(mode, registrationToken) {
1502
1522
  return new Promise((resolve) => {
1503
- // Registration carries the freshly verified identifier so the backend
1504
- // can attach the credential to that SVID. Verification is discoverable:
1505
- // the credential userHandle routes completion to the SVID.
1523
+ // Registration carries the freshly verified identifier so the backend can
1524
+ // attach the credential to that SVID. Verification carries it too when
1525
+ // known, to scope the ceremony to that person's passkeys; the credential
1526
+ // userHandle still routes completion to the SVID.
1506
1527
  const params = new URLSearchParams({
1507
1528
  mode,
1508
1529
  origin: window.location.origin,
1509
1530
  });
1510
- if (mode === 'register' && this.state.recipient) {
1531
+ if (this.state.recipient) {
1511
1532
  const identityParam = this.state.identityType === 'phone' ? 'phone' : 'email';
1512
1533
  params.set(identityParam, this.state.recipient);
1513
1534
  }
@@ -7658,13 +7679,13 @@ function attachClickHandler(selector, onClick) {
7658
7679
  * Supports passkey, TOTP, SparkLink, and social authentication.
7659
7680
  *
7660
7681
  * @example Dialog mode (immediate)
7661
- * const result = await sv.identity.verify();
7682
+ * const result = await sv.products.identity.verify();
7662
7683
  *
7663
7684
  * @example Dialog mode (attached to clicks)
7664
- * sv.identity.attach('.login-btn');
7685
+ * sv.products.identity.attach('.login-btn');
7665
7686
  *
7666
7687
  * @example Inline mode
7667
- * const result = await sv.identity.verify({ target: '#auth-container' });
7688
+ * const result = await sv.products.identity.verify({ target: '#auth-container' });
7668
7689
  */
7669
7690
  function isTokenClaims(payload) {
7670
7691
  if (typeof payload !== 'object' || payload === null) {
@@ -7699,11 +7720,11 @@ class IdentityModule {
7699
7720
  * - With `target`: Renders inline into the specified element
7700
7721
  *
7701
7722
  * @example Dialog mode
7702
- * const result = await sv.identity.verify();
7723
+ * const result = await sv.products.identity.verify();
7703
7724
  * console.log(result.token, result.identity);
7704
7725
  *
7705
7726
  * @example Inline mode
7706
- * const result = await sv.identity.verify({
7727
+ * const result = await sv.products.identity.verify({
7707
7728
  * target: '#auth-container',
7708
7729
  * email: 'user@example.com'
7709
7730
  * });
@@ -7803,7 +7824,7 @@ class IdentityModule {
7803
7824
  * @returns Cleanup function to remove event listeners
7804
7825
  *
7805
7826
  * @example
7806
- * const cleanup = sv.identity.attach('.login-btn', {
7827
+ * const cleanup = sv.products.identity.attach('.login-btn', {
7807
7828
  * onSuccess: (result) => console.log('Verified:', result.identity)
7808
7829
  * });
7809
7830
  *
@@ -8008,6 +8029,19 @@ class IdentityModule {
8008
8029
  }
8009
8030
  }
8010
8031
 
8032
+ /**
8033
+ * Products Module
8034
+ *
8035
+ * Namespace for SparkVault first-party products. Each product is a
8036
+ * self-contained surface (UI + API) the account can enable independently.
8037
+ * Currently exposes `identity`; future products attach here alongside it.
8038
+ */
8039
+ class ProductsModule {
8040
+ constructor(config) {
8041
+ this.identity = new IdentityModule(config);
8042
+ }
8043
+ }
8044
+
8011
8045
  /**
8012
8046
  * Upload API
8013
8047
  *
@@ -8144,7 +8178,7 @@ class UploadApi extends SparkVaultApi {
8144
8178
  * Upload a file to Forge over the TUS resumable protocol (v1.0.0).
8145
8179
  *
8146
8180
  * The single canonical browser transfer path — the upload widget and the
8147
- * authenticated `uploadIngot` flow both go through here (CLAUDE.md: one
8181
+ * authenticated `ingots.upload` flow both go through here (CLAUDE.md: one
8148
8182
  * transfer path). Creates the session, PATCHes chunks sized by the server's
8149
8183
  * `X-Chunk-Size` (50MB default, which keeps every request under CDN body
8150
8184
  * caps such as Cloudflare's 100MB), validates every server-reported offset,
@@ -11097,15 +11131,15 @@ class VaultUploadModule {
11097
11131
  /**
11098
11132
  * Vaults Module
11099
11133
  *
11100
- * Create and manage encrypted vaults and ingots.
11101
- * Uses Triple Zero-Trust encryption (SVMK + AMK + VMK).
11134
+ * Create and manage encrypted vaults (the control plane). Uses Triple
11135
+ * Zero-Trust encryption (SVMK + AMK + VMK). Ingot, folder, spark, and entropy
11136
+ * operations live in their own modules; this module owns the vault record,
11137
+ * its sharing/upload configuration, and the browser upload widget.
11102
11138
  */
11103
11139
  class VaultsModule {
11104
11140
  constructor(config, http) {
11105
- this.config = config;
11106
11141
  this.http = http;
11107
11142
  this.uploadModule = new VaultUploadModule(config);
11108
- this.uploadApi = new UploadApi(config);
11109
11143
  // Create callable that also has attach/close/pop/render methods
11110
11144
  const uploadFn = ((options) => this.uploadModule.upload(options));
11111
11145
  uploadFn.attach = (selector, options) => this.uploadModule.attach(selector, options);
@@ -11126,14 +11160,12 @@ class VaultsModule {
11126
11160
  this.validateCreateOptions(options);
11127
11161
  const response = await this.http.post('/v1/vaults', {
11128
11162
  name: options.name,
11129
- hosted_vmk: options.hostedVmk ?? false,
11130
11163
  });
11131
11164
  return {
11132
11165
  id: response.data.vault_id,
11133
11166
  name: response.data.name,
11134
11167
  vmk: response.data.vmk,
11135
11168
  createdAt: response.data.created_at,
11136
- hostedVmk: response.data.hosted_vmk,
11137
11169
  };
11138
11170
  }
11139
11171
  /**
@@ -11142,16 +11174,13 @@ class VaultsModule {
11142
11174
  *
11143
11175
  * @example
11144
11176
  * const unsealed = await sv.vaults.unseal('vlt_abc', vmk);
11145
- * console.log('Ingots:', unsealed.ingotCount);
11177
+ * console.log('Token:', unsealed.vatToken);
11146
11178
  */
11147
11179
  async unseal(vaultId, vmk) {
11148
- if (!vaultId) {
11149
- throw new ValidationError('Vault ID is required');
11150
- }
11180
+ const cleanId = this.normalizeVaultId(vaultId);
11151
11181
  if (!vmk) {
11152
11182
  throw new ValidationError('VMK is required');
11153
11183
  }
11154
- const cleanId = vaultId.startsWith('vlt_') ? vaultId : `vlt_${vaultId}`;
11155
11184
  const response = await this.http.post(`/v1/vaults/${cleanId}/unseal`, { vmk });
11156
11185
  if (!response.data.vat) {
11157
11186
  throw new ValidationError('Unseal response did not include a vault access token');
@@ -11179,79 +11208,523 @@ class VaultsModule {
11179
11208
  createdAt: v.created_at,
11180
11209
  ingotCount: v.ingot_count,
11181
11210
  storageBytes: v.storage_bytes,
11182
- hostedVmk: v.hosted_vmk,
11183
11211
  }));
11184
11212
  }
11185
11213
  /**
11186
- * Delete a vault and all its ingots.
11187
- * This action is irreversible!
11214
+ * Get a single vault's detail.
11215
+ *
11216
+ * @example
11217
+ * const vault = await sv.vaults.get('vlt_abc');
11218
+ * console.log(vault.status, vault.ingotCount);
11219
+ */
11220
+ async get(vaultId) {
11221
+ const cleanId = this.normalizeVaultId(vaultId);
11222
+ const response = await this.http.get(`/v1/vaults/${cleanId}`);
11223
+ const v = response.data;
11224
+ return {
11225
+ id: v.vault_id,
11226
+ name: v.name,
11227
+ description: v.description ?? null,
11228
+ status: v.status,
11229
+ ingotCount: v.ingot_count ?? 0,
11230
+ storageBytes: v.storage_bytes ?? 0,
11231
+ createdAt: v.created_at,
11232
+ lastUnsealedAt: v.last_unsealed_at ?? null,
11233
+ unsealCount: v.unseal_count ?? 0,
11234
+ };
11235
+ }
11236
+ /**
11237
+ * Rename a vault.
11238
+ *
11239
+ * @example
11240
+ * await sv.vaults.update('vlt_abc', { name: 'Renamed Vault' });
11241
+ */
11242
+ async update(vaultId, options) {
11243
+ const cleanId = this.normalizeVaultId(vaultId);
11244
+ if (!options.name?.trim()) {
11245
+ throw new ValidationError('Vault name is required');
11246
+ }
11247
+ const response = await this.http.put(`/v1/vaults/${cleanId}`, {
11248
+ name: options.name,
11249
+ });
11250
+ const v = response.data;
11251
+ return {
11252
+ id: v.vault_id,
11253
+ name: v.name,
11254
+ description: v.description ?? null,
11255
+ updatedAt: v.updated_at,
11256
+ };
11257
+ }
11258
+ /**
11259
+ * Seal a vault, revoking all active access tokens.
11260
+ *
11261
+ * @example
11262
+ * await sv.vaults.seal('vlt_abc');
11263
+ */
11264
+ async seal(vaultId) {
11265
+ const cleanId = this.normalizeVaultId(vaultId);
11266
+ await this.http.post(`/v1/vaults/${cleanId}/seal`);
11267
+ }
11268
+ /**
11269
+ * Delete a vault and all its ingots. This action is irreversible!
11188
11270
  *
11189
11271
  * @example
11190
11272
  * await sv.vaults.delete('vlt_abc', vmk);
11191
11273
  */
11192
11274
  async delete(vaultId, vmk) {
11193
- const cleanId = vaultId.startsWith('vlt_') ? vaultId : `vlt_${vaultId}`;
11275
+ const cleanId = this.normalizeVaultId(vaultId);
11194
11276
  await this.http.delete(`/v1/vaults/${cleanId}`, {
11195
11277
  headers: { 'X-VMK': vmk },
11196
11278
  });
11197
11279
  }
11198
11280
  /**
11199
- * Upload a file as an ingot to an unsealed vault.
11281
+ * Get a vault's public-sharing configuration.
11200
11282
  *
11201
11283
  * @example
11202
- * const ingot = await sv.vaults.uploadIngot(unsealed, {
11203
- * file: myFile,
11204
- * name: 'document.pdf'
11205
- * });
11284
+ * const sharing = await sv.vaults.getSharingConfig('vlt_abc');
11206
11285
  */
11207
- async uploadIngot(vault, options) {
11208
- this.validateUploadOptions(options);
11209
- const requestedName = options.name ?? getBlobName(options.file);
11210
- const requestedContentType = options.contentType ?? options.file.type ?? 'application/octet-stream';
11211
- const createResponse = await this.http.post(`/v1/vaults/${vault.id}/ingots`, {
11212
- name: requestedName,
11213
- content_type: requestedContentType,
11214
- size_bytes: options.file.size,
11215
- }, {
11216
- headers: { 'X-Vault-Access-Token': vault.vatToken },
11286
+ async getSharingConfig(vaultId) {
11287
+ const cleanId = this.normalizeVaultId(vaultId);
11288
+ const response = await this.http.get(`/v1/vaults/${cleanId}/sharing`);
11289
+ return mapSharingConfig$1(response.data);
11290
+ }
11291
+ /**
11292
+ * Enable public sharing for a vault.
11293
+ *
11294
+ * @example
11295
+ * await sv.vaults.enableSharing('vlt_abc', vmk, { sessionLengthSeconds: 3600 });
11296
+ */
11297
+ async enableSharing(vaultId, vmk, options = {}) {
11298
+ const cleanId = this.normalizeVaultId(vaultId);
11299
+ if (!vmk) {
11300
+ throw new ValidationError('VMK is required');
11301
+ }
11302
+ const response = await this.http.post(`/v1/vaults/${cleanId}/sharing/enable`, {
11303
+ vmk,
11304
+ all_ingots_public: options.allIngotsPublic,
11305
+ session_length_seconds: options.sessionLengthSeconds,
11217
11306
  });
11218
- const created = createResponse.data;
11219
- if (!created.forge_url) {
11220
- throw new ValidationError('Upload endpoint did not return a Forge upload URL');
11307
+ return mapSharingConfig$1(response.data);
11308
+ }
11309
+ /**
11310
+ * Disable public sharing for a vault.
11311
+ *
11312
+ * @example
11313
+ * await sv.vaults.disableSharing('vlt_abc');
11314
+ */
11315
+ async disableSharing(vaultId) {
11316
+ const cleanId = this.normalizeVaultId(vaultId);
11317
+ const response = await this.http.post(`/v1/vaults/${cleanId}/sharing/disable`);
11318
+ return mapSharingConfig$1(response.data);
11319
+ }
11320
+ /**
11321
+ * Update a vault's sharing configuration (without changing enabled state).
11322
+ *
11323
+ * @example
11324
+ * await sv.vaults.updateSharingConfig('vlt_abc', { allIngotsPublic: true });
11325
+ */
11326
+ async updateSharingConfig(vaultId, config) {
11327
+ const cleanId = this.normalizeVaultId(vaultId);
11328
+ const response = await this.http.put(`/v1/vaults/${cleanId}/sharing`, {
11329
+ all_ingots_public: config.allIngotsPublic,
11330
+ session_length_seconds: config.sessionLengthSeconds,
11331
+ });
11332
+ return mapSharingConfig$1(response.data);
11333
+ }
11334
+ /**
11335
+ * Get a vault's access-log retention window.
11336
+ *
11337
+ * @example
11338
+ * const { retentionSeconds } = await sv.vaults.getAccessLogRetention('vlt_abc');
11339
+ */
11340
+ async getAccessLogRetention(vaultId) {
11341
+ const cleanId = this.normalizeVaultId(vaultId);
11342
+ const response = await this.http.get(`/v1/vaults/${cleanId}/access-log-retention`);
11343
+ return {
11344
+ vaultId: response.data.vault_id,
11345
+ retentionSeconds: response.data.access_log_retention_seconds,
11346
+ };
11347
+ }
11348
+ /**
11349
+ * Update a vault's access-log retention window.
11350
+ *
11351
+ * @example
11352
+ * await sv.vaults.updateAccessLogRetention('vlt_abc', 7776000);
11353
+ */
11354
+ async updateAccessLogRetention(vaultId, seconds) {
11355
+ const cleanId = this.normalizeVaultId(vaultId);
11356
+ const response = await this.http.put(`/v1/vaults/${cleanId}/access-log-retention`, { access_log_retention_seconds: seconds });
11357
+ return {
11358
+ vaultId: response.data.vault_id,
11359
+ retentionSeconds: response.data.access_log_retention_seconds,
11360
+ };
11361
+ }
11362
+ /**
11363
+ * Get a vault's upload-channel configuration.
11364
+ *
11365
+ * @example
11366
+ * const upload = await sv.vaults.getUploadConfig('vlt_abc');
11367
+ */
11368
+ async getUploadConfig(vaultId) {
11369
+ const cleanId = this.normalizeVaultId(vaultId);
11370
+ const response = await this.http.get(`/v1/vaults/${cleanId}/upload`);
11371
+ return mapUploadSettings(response.data);
11372
+ }
11373
+ /**
11374
+ * Enable the public upload portal for a vault.
11375
+ *
11376
+ * @example
11377
+ * await sv.vaults.enableUploadPortal('vlt_abc', vmk);
11378
+ */
11379
+ async enableUploadPortal(vaultId, vmk) {
11380
+ return this.toggleUploadChannel(vaultId, 'portal', 'enable', vmk);
11381
+ }
11382
+ /**
11383
+ * Disable the public upload portal for a vault.
11384
+ *
11385
+ * @example
11386
+ * await sv.vaults.disableUploadPortal('vlt_abc');
11387
+ */
11388
+ async disableUploadPortal(vaultId) {
11389
+ return this.toggleUploadChannel(vaultId, 'portal', 'disable');
11390
+ }
11391
+ /**
11392
+ * Enable the upload widget for a vault.
11393
+ *
11394
+ * @example
11395
+ * await sv.vaults.enableUploadWidget('vlt_abc', vmk);
11396
+ */
11397
+ async enableUploadWidget(vaultId, vmk) {
11398
+ return this.toggleUploadChannel(vaultId, 'widget', 'enable', vmk);
11399
+ }
11400
+ /**
11401
+ * Disable the upload widget for a vault.
11402
+ *
11403
+ * @example
11404
+ * await sv.vaults.disableUploadWidget('vlt_abc');
11405
+ */
11406
+ async disableUploadWidget(vaultId) {
11407
+ return this.toggleUploadChannel(vaultId, 'widget', 'disable');
11408
+ }
11409
+ /**
11410
+ * Update a vault's upload settings (max size, notification email).
11411
+ *
11412
+ * @example
11413
+ * await sv.vaults.updateUploadConfig('vlt_abc', { maxSizeBytes: 1048576 });
11414
+ */
11415
+ async updateUploadConfig(vaultId, config) {
11416
+ const cleanId = this.normalizeVaultId(vaultId);
11417
+ const body = {};
11418
+ if (config.maxSizeBytes !== undefined)
11419
+ body.max_size_bytes = config.maxSizeBytes;
11420
+ if (config.notificationEmail !== undefined)
11421
+ body.notification_email = config.notificationEmail;
11422
+ const response = await this.http.put(`/v1/vaults/${cleanId}/upload`, body);
11423
+ return mapUploadSettings(response.data);
11424
+ }
11425
+ async toggleUploadChannel(vaultId, channel, action, vmk) {
11426
+ const cleanId = this.normalizeVaultId(vaultId);
11427
+ if (action === 'enable' && !vmk) {
11428
+ throw new ValidationError('VMK is required');
11221
11429
  }
11222
- const uploadUrl = await this.uploadApi.uploadFileToForge(options.file, created.forge_url, options.onProgress);
11223
- // Confirm the server actually finalized the upload before reporting
11224
- // success — the TUS loop's offsets alone don't prove the final chunk
11225
- // committed and the ingot went active.
11226
- await this.uploadApi.verifyUploadFinalized(uploadUrl, options.file.size);
11430
+ const response = await this.http.post(`/v1/vaults/${cleanId}/upload/${channel}/${action}`, action === 'enable' ? { vmk } : undefined);
11431
+ const d = response.data;
11432
+ return {
11433
+ vaultId: d.vault_id,
11434
+ uploadPortalEnabled: d.upload_portal_enabled ?? (channel === 'portal' && action === 'enable'),
11435
+ uploadPortalEnabledAt: channel === 'portal' && action === 'enable' ? d.enabled_at ?? null : null,
11436
+ uploadWidgetEnabled: d.upload_widget_enabled ?? (channel === 'widget' && action === 'enable'),
11437
+ uploadWidgetEnabledAt: channel === 'widget' && action === 'enable' ? d.enabled_at ?? null : null,
11438
+ maxSizeBytes: null,
11439
+ notificationEmail: null,
11440
+ portalUrl: d.portal_url,
11441
+ };
11442
+ }
11443
+ normalizeVaultId(vaultId) {
11444
+ if (!vaultId) {
11445
+ throw new ValidationError('Vault ID is required');
11446
+ }
11447
+ return vaultId.startsWith('vlt_') ? vaultId : `vlt_${vaultId}`;
11448
+ }
11449
+ validateCreateOptions(options) {
11450
+ if (!options.name?.trim()) {
11451
+ throw new ValidationError('Vault name is required');
11452
+ }
11453
+ if (options.name.length > 255) {
11454
+ throw new ValidationError('Vault name must be 255 characters or less');
11455
+ }
11456
+ }
11457
+ }
11458
+ function mapSharingConfig$1(wire) {
11459
+ return {
11460
+ vaultId: wire.vault_id,
11461
+ publicSharingEnabled: wire.public_sharing_enabled,
11462
+ allIngotsPublic: wire.all_ingots_public,
11463
+ sessionLengthSeconds: wire.session_length_seconds ?? null,
11464
+ enabledAt: wire.enabled_at ?? null,
11465
+ };
11466
+ }
11467
+ function mapUploadSettings(wire) {
11468
+ return {
11469
+ vaultId: wire.vault_id,
11470
+ uploadPortalEnabled: wire.upload_portal_enabled,
11471
+ uploadPortalEnabledAt: wire.upload_portal_enabled_at ?? null,
11472
+ uploadWidgetEnabled: wire.upload_widget_enabled,
11473
+ uploadWidgetEnabledAt: wire.upload_widget_enabled_at ?? null,
11474
+ maxSizeBytes: wire.max_size_bytes ?? null,
11475
+ notificationEmail: wire.notification_email ?? null,
11476
+ portalUrl: wire.portal_url,
11477
+ };
11478
+ }
11479
+
11480
+ /**
11481
+ * Ingots Module
11482
+ *
11483
+ * Data-plane operations on the contents of an *unsealed* vault. Every method
11484
+ * takes the {@link UnsealedVault} returned by `sv.vaults.unseal(...)` and
11485
+ * authenticates with its short-lived Vault Access Token (VAT).
11486
+ *
11487
+ * Uploads and downloads run over the single canonical Forge TUS transfer path
11488
+ * (shared with the public upload widget), with server-side finalization and
11489
+ * download-host allowlisting enforced — no per-size branching.
11490
+ */
11491
+ const DOWNLOAD_MAX_ATTEMPTS = 3;
11492
+ const DOWNLOAD_RETRY_BASE_MS = 500;
11493
+ const DOWNLOAD_FETCH_TIMEOUT_MS = 300000;
11494
+ class IngotsModule {
11495
+ constructor(config, http) {
11496
+ this.config = config;
11497
+ this.http = http;
11498
+ this.uploadApi = new UploadApi(config);
11499
+ }
11500
+ /**
11501
+ * Create an ingot upload session (discrete primitive).
11502
+ *
11503
+ * Reserves the ingot record and returns the Forge upload URL (carrying the
11504
+ * ISTK upload session token). Use this when you want to drive the TUS
11505
+ * transfer yourself; otherwise prefer {@link upload}.
11506
+ *
11507
+ * @example
11508
+ * const session = await sv.ingots.createUpload({
11509
+ * vault: unsealed, name: 'report.pdf',
11510
+ * contentType: 'application/pdf', sizeBytes: file.size,
11511
+ * });
11512
+ * console.log(session.uploadUrl);
11513
+ */
11514
+ async createUpload(options) {
11515
+ if (!options.name?.trim()) {
11516
+ throw new ValidationError('Ingot name is required');
11517
+ }
11518
+ if (!Number.isFinite(options.sizeBytes) || options.sizeBytes < 1) {
11519
+ throw new ValidationError('sizeBytes must be a positive number');
11520
+ }
11521
+ if (options.folder && options.folderId) {
11522
+ throw new ValidationError('Provide folder or folderId, not both');
11523
+ }
11524
+ const created = await this.requestUploadSession(options.vault, {
11525
+ name: options.name,
11526
+ content_type: options.contentType,
11527
+ size_bytes: options.sizeBytes,
11528
+ folder: options.folder,
11529
+ folderId: options.folderId,
11530
+ });
11227
11531
  return {
11228
11532
  id: created.ingot_id,
11229
11533
  name: created.name,
11230
11534
  contentType: created.content_type,
11231
11535
  size: created.size_bytes,
11232
- uploadExpiresAt: created.expires_at,
11536
+ uploadUrl: created.forge_url,
11537
+ expiresAt: created.expires_at,
11233
11538
  };
11234
11539
  }
11235
11540
  /**
11236
- * Download an ingot from an unsealed vault.
11541
+ * Upload a file as a new ingot (high-level flow).
11542
+ *
11543
+ * Creates the upload session, streams the file to Forge over TUS, then
11544
+ * confirms the server finalized the upload before resolving.
11545
+ *
11546
+ * @example
11547
+ * const ingot = await sv.ingots.upload(unsealed, {
11548
+ * file: myFile, name: 'document.pdf'
11549
+ * });
11550
+ */
11551
+ async upload(vault, options) {
11552
+ this.validateFile(options.file);
11553
+ if (options.folder && options.folderId) {
11554
+ throw new ValidationError('Provide folder or folderId, not both');
11555
+ }
11556
+ const name = options.name ?? getBlobName(options.file);
11557
+ const contentType = options.contentType ?? options.file.type ?? 'application/octet-stream';
11558
+ const created = await this.requestUploadSession(vault, {
11559
+ name,
11560
+ content_type: contentType,
11561
+ size_bytes: options.file.size,
11562
+ folder: options.folder,
11563
+ folderId: options.folderId,
11564
+ });
11565
+ return this.transferAndFinalize(created, options.file, options.onProgress);
11566
+ }
11567
+ /**
11568
+ * Replace an existing ingot's content (high-level flow).
11569
+ *
11570
+ * @example
11571
+ * await sv.ingots.replace(unsealed, 'ing_abc', { file: updatedFile });
11572
+ */
11573
+ async replace(vault, ingotId, options) {
11574
+ this.validateFile(options.file);
11575
+ const cleanId = normalizeIngotId(ingotId);
11576
+ const name = options.name ?? getBlobName(options.file);
11577
+ const contentType = options.contentType ?? options.file.type ?? 'application/octet-stream';
11578
+ const response = await this.http.put(`/v1/vaults/${vault.id}/ingots/${cleanId}`, { name, content_type: contentType, size_bytes: options.file.size }, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11579
+ if (!response.data.forge_url) {
11580
+ throw new ValidationError('Replace endpoint did not return a Forge upload URL');
11581
+ }
11582
+ return this.transferAndFinalize(response.data, options.file, options.onProgress);
11583
+ }
11584
+ /**
11585
+ * Rename an ingot.
11586
+ *
11587
+ * @example
11588
+ * await sv.ingots.rename(unsealed, 'ing_abc', 'new-name.pdf');
11589
+ */
11590
+ async rename(vault, ingotId, name) {
11591
+ if (!name?.trim()) {
11592
+ throw new ValidationError('Ingot name is required');
11593
+ }
11594
+ const cleanId = normalizeIngotId(ingotId);
11595
+ const response = await this.http.patch(`/v1/vaults/${vault.id}/ingots/${cleanId}`, { name }, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11596
+ return mapIngot(response.data);
11597
+ }
11598
+ /**
11599
+ * Move an ingot to a folder, or to the vault root with `null`.
11600
+ *
11601
+ * @example
11602
+ * await sv.ingots.move(unsealed, 'ing_abc', 'fld_xyz');
11603
+ * await sv.ingots.move(unsealed, 'ing_abc', null); // root
11604
+ */
11605
+ async move(vault, ingotId, folderId) {
11606
+ const cleanId = normalizeIngotId(ingotId);
11607
+ const response = await this.http.patch(`/v1/vaults/${vault.id}/ingots/${cleanId}`, { folder_id: folderId }, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11608
+ return mapIngot(response.data);
11609
+ }
11610
+ /**
11611
+ * Delete an ingot.
11612
+ *
11613
+ * @example
11614
+ * await sv.ingots.delete(unsealed, 'ing_abc');
11615
+ */
11616
+ async delete(vault, ingotId) {
11617
+ const cleanId = normalizeIngotId(ingotId);
11618
+ await this.http.delete(`/v1/vaults/${vault.id}/ingots/${cleanId}`, {
11619
+ headers: { 'X-Vault-Access-Token': vault.vatToken },
11620
+ });
11621
+ }
11622
+ /**
11623
+ * Get ingot metadata.
11624
+ *
11625
+ * @example
11626
+ * const ingot = await sv.ingots.get(unsealed, 'ing_abc');
11627
+ */
11628
+ async get(vault, ingotId) {
11629
+ const cleanId = normalizeIngotId(ingotId);
11630
+ const response = await this.http.get(`/v1/vaults/${vault.id}/ingots/${cleanId}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11631
+ return mapIngot(response.data);
11632
+ }
11633
+ /**
11634
+ * List ingots in an unsealed vault.
11635
+ *
11636
+ * @example
11637
+ * const { ingots } = await sv.ingots.list(unsealed);
11638
+ */
11639
+ async list(vault, options = {}) {
11640
+ const query = buildQuery$1({
11641
+ limit: options.limit,
11642
+ cursor: options.cursor,
11643
+ sort_by: options.sortBy,
11644
+ sort_order: options.sortOrder,
11645
+ });
11646
+ const response = await this.http.get(`/v1/vaults/${vault.id}/ingots${query}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11647
+ return mapIngotPage(response.data);
11648
+ }
11649
+ /**
11650
+ * Search ingots in an unsealed vault.
11651
+ *
11652
+ * @example
11653
+ * const { ingots } = await sv.ingots.search(unsealed, { q: 'invoice' });
11654
+ */
11655
+ async search(vault, options = {}) {
11656
+ const query = buildQuery$1({
11657
+ q: options.q,
11658
+ file_type: options.fileType,
11659
+ min_size: options.minSize,
11660
+ max_size: options.maxSize,
11661
+ limit: options.limit,
11662
+ cursor: options.cursor,
11663
+ sort_order: options.sortOrder,
11664
+ });
11665
+ const response = await this.http.get(`/v1/vaults/${vault.id}/ingots/search${query}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11666
+ return mapIngotPage(response.data);
11667
+ }
11668
+ /**
11669
+ * List the contents (ingots) of a folder, or the vault root.
11670
+ *
11671
+ * @example
11672
+ * const { ingots } = await sv.ingots.listContents(unsealed, { folderId: 'fld_x' });
11673
+ */
11674
+ async listContents(vault, options = {}) {
11675
+ const query = buildQuery$1({
11676
+ folder_id: options.folderId,
11677
+ limit: options.limit,
11678
+ cursor: options.cursor,
11679
+ sort_by: options.sortBy,
11680
+ sort_order: options.sortOrder,
11681
+ type: options.type,
11682
+ });
11683
+ const response = await this.http.get(`/v1/vaults/${vault.id}/contents${query}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11684
+ return mapIngotPage(response.data);
11685
+ }
11686
+ /**
11687
+ * Create a signed download link for an ingot (discrete primitive).
11688
+ *
11689
+ * Validates the returned URL against the download-host allowlist. Use this
11690
+ * when you want the URL itself; otherwise prefer {@link download}.
11237
11691
  *
11238
11692
  * @example
11239
- * const blob = await sv.vaults.downloadIngot(unsealed, 'ing_abc');
11693
+ * const link = await sv.ingots.createDownloadLink(unsealed, 'ing_abc');
11694
+ * window.location.href = link.downloadUrl;
11695
+ */
11696
+ async createDownloadLink(vault, ingotId) {
11697
+ const cleanId = normalizeIngotId(ingotId);
11698
+ const response = await this.http.post(`/v1/vaults/${vault.id}/ingots/${cleanId}/download`, undefined, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11699
+ if (!response.data.download_url) {
11700
+ throw new ValidationError('Download endpoint did not return a download URL');
11701
+ }
11702
+ this.validateDownloadUrl(response.data.download_url);
11703
+ return {
11704
+ downloadUrl: response.data.download_url,
11705
+ id: response.data.ingot_id,
11706
+ name: response.data.name,
11707
+ size: response.data.size_bytes,
11708
+ contentType: response.data.content_type,
11709
+ };
11710
+ }
11711
+ /**
11712
+ * Download an ingot as a Blob (high-level flow).
11713
+ *
11714
+ * Requests a fresh signed link on every attempt (server URLs are
11715
+ * short-lived) and retries transient transport failures with exponential
11716
+ * backoff. Validation failures (bad host, non-HTTPS) are never retried.
11717
+ *
11718
+ * @example
11719
+ * const blob = await sv.ingots.download(unsealed, 'ing_abc');
11240
11720
  * const url = URL.createObjectURL(blob);
11241
11721
  */
11242
- async downloadIngot(vault, ingotId) {
11243
- const cleanId = ingotId.startsWith('ing_') ? ingotId : `ing_${ingotId}`;
11722
+ async download(vault, ingotId) {
11244
11723
  let lastError = null;
11245
11724
  for (let attempt = 1; attempt <= DOWNLOAD_MAX_ATTEMPTS; attempt++) {
11246
11725
  try {
11247
- const response = await this.http.post(`/v1/vaults/${vault.id}/ingots/${cleanId}/download`, undefined, {
11248
- headers: { 'X-Vault-Access-Token': vault.vatToken },
11249
- });
11250
- if (!response.data.download_url) {
11251
- throw new ValidationError('Download endpoint did not return a download URL');
11252
- }
11253
- this.validateDownloadUrl(response.data.download_url);
11254
- return await fetchBlobWithTimeout(response.data.download_url);
11726
+ const link = await this.createDownloadLink(vault, ingotId);
11727
+ return await fetchBlobWithTimeout(link.downloadUrl, DOWNLOAD_FETCH_TIMEOUT_MS);
11255
11728
  }
11256
11729
  catch (err) {
11257
11730
  lastError = err instanceof Error ? err : new Error(String(err));
@@ -11264,49 +11737,118 @@ class VaultsModule {
11264
11737
  throw lastError ?? new Error('Download failed');
11265
11738
  }
11266
11739
  /**
11267
- * List all ingots in an unsealed vault.
11740
+ * Get an ingot's sharing configuration.
11268
11741
  *
11269
11742
  * @example
11270
- * const ingots = await sv.vaults.listIngots(unsealed);
11271
- * ingots.forEach(i => console.log(i.name, i.size));
11743
+ * const sharing = await sv.ingots.getSharingConfig(unsealed, 'ing_abc');
11272
11744
  */
11273
- async listIngots(vault) {
11274
- const response = await this.http.get(`/v1/vaults/${vault.id}/ingots`, {
11275
- headers: { 'X-Vault-Access-Token': vault.vatToken },
11276
- });
11277
- return response.data.ingots.map((i) => ({
11278
- id: i.ingot_id,
11279
- name: i.name,
11280
- contentType: i.content_type,
11281
- size: i.size_bytes,
11282
- createdAt: i.created_at,
11283
- }));
11745
+ async getSharingConfig(vault, ingotId) {
11746
+ const cleanId = normalizeIngotId(ingotId);
11747
+ const response = await this.http.get(`/v1/vaults/${vault.id}/ingots/${cleanId}/sharing`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11748
+ return mapSharingConfig(response.data);
11284
11749
  }
11285
11750
  /**
11286
- * Delete an ingot from an unsealed vault.
11751
+ * Update an ingot's sharing configuration.
11287
11752
  *
11288
11753
  * @example
11289
- * await sv.vaults.deleteIngot(unsealed, 'ing_abc');
11754
+ * await sv.ingots.updateSharingConfig(unsealed, 'ing_abc', { shared: true });
11290
11755
  */
11291
- async deleteIngot(vault, ingotId) {
11292
- const cleanId = ingotId.startsWith('ing_') ? ingotId : `ing_${ingotId}`;
11293
- await this.http.delete(`/v1/vaults/${vault.id}/ingots/${cleanId}`, {
11294
- headers: { 'X-Vault-Access-Token': vault.vatToken },
11295
- });
11756
+ async updateSharingConfig(vault, ingotId, config) {
11757
+ const cleanId = normalizeIngotId(ingotId);
11758
+ const response = await this.http.put(`/v1/vaults/${vault.id}/ingots/${cleanId}/sharing`, { shared: config.shared, visibility: config.visibility }, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11759
+ return mapSharingConfig(response.data);
11296
11760
  }
11297
- validateCreateOptions(options) {
11298
- if (!options.name?.trim()) {
11299
- throw new ValidationError('Vault name is required');
11761
+ /**
11762
+ * Invite an identity to a shared ingot. The identity type (email or phone)
11763
+ * is inferred server-side from the identity value.
11764
+ *
11765
+ * @example
11766
+ * await sv.ingots.addInvite(unsealed, 'ing_abc', 'user@example.com');
11767
+ * await sv.ingots.addInvite(unsealed, 'ing_abc', 'user@example.com', { expiresInSeconds: 86400 });
11768
+ */
11769
+ async addInvite(vault, ingotId, identity, options = {}) {
11770
+ if (!identity?.trim()) {
11771
+ throw new ValidationError('Invite identity is required');
11300
11772
  }
11301
- if (options.name.length > 255) {
11302
- throw new ValidationError('Vault name must be 255 characters or less');
11773
+ const cleanId = normalizeIngotId(ingotId);
11774
+ const response = await this.http.post(`/v1/vaults/${vault.id}/ingots/${cleanId}/sharing/invite`, { identity, expires_in_seconds: options.expiresInSeconds }, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11775
+ return mapInvite(response.data);
11776
+ }
11777
+ /**
11778
+ * Revoke an ingot sharing invite.
11779
+ *
11780
+ * @example
11781
+ * await sv.ingots.revokeInvite(unsealed, 'ing_abc', 'inv_123');
11782
+ */
11783
+ async revokeInvite(vault, ingotId, inviteId) {
11784
+ if (!inviteId?.trim()) {
11785
+ throw new ValidationError('Invite ID is required');
11786
+ }
11787
+ const cleanId = normalizeIngotId(ingotId);
11788
+ await this.http.delete(`/v1/vaults/${vault.id}/ingots/${cleanId}/sharing/invite/${inviteId}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11789
+ }
11790
+ /**
11791
+ * Get an ingot's access logs.
11792
+ *
11793
+ * @example
11794
+ * const { logs } = await sv.ingots.getAccessLogs(unsealed, 'ing_abc');
11795
+ */
11796
+ async getAccessLogs(vault, ingotId, options = {}) {
11797
+ const cleanId = normalizeIngotId(ingotId);
11798
+ const query = buildQuery$1({ limit: options.limit, cursor: options.cursor });
11799
+ const response = await this.http.get(`/v1/vaults/${vault.id}/ingots/${cleanId}/audit-logs${query}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11800
+ const entries = response.data.entries ?? [];
11801
+ return {
11802
+ logs: entries.map(mapAccessLog),
11803
+ nextCursor: response.data.next_cursor,
11804
+ };
11805
+ }
11806
+ /**
11807
+ * Request a Forge upload session for a new ingot.
11808
+ * Shared by createUpload and upload — the single ingot-create path.
11809
+ */
11810
+ async requestUploadSession(vault, body) {
11811
+ const payload = {
11812
+ name: body.name,
11813
+ content_type: body.content_type ?? 'application/octet-stream',
11814
+ size_bytes: body.size_bytes,
11815
+ };
11816
+ // folder_path (find-or-create) and folder_id (existing folder) are
11817
+ // mutually exclusive server-side; a path takes precedence when both given.
11818
+ if (body.folder) {
11819
+ payload.folder_path = body.folder;
11303
11820
  }
11821
+ else if (body.folderId) {
11822
+ payload.folder_id = body.folderId;
11823
+ }
11824
+ const response = await this.http.post(`/v1/vaults/${vault.id}/ingots`, payload, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11825
+ if (!response.data.forge_url) {
11826
+ throw new ValidationError('Upload endpoint did not return a Forge upload URL');
11827
+ }
11828
+ return response.data;
11829
+ }
11830
+ /**
11831
+ * Run the canonical TUS transfer for a created/replaced ingot, then confirm
11832
+ * the server finalized the upload before reporting success.
11833
+ */
11834
+ async transferAndFinalize(created, file, onProgress) {
11835
+ const uploadUrl = await this.uploadApi.uploadFileToForge(file, created.forge_url, onProgress);
11836
+ // Confirm the server actually finalized the upload before reporting
11837
+ // success — the TUS loop's offsets alone don't prove the final chunk
11838
+ // committed and the ingot went active.
11839
+ await this.uploadApi.verifyUploadFinalized(uploadUrl, file.size);
11840
+ return {
11841
+ id: created.ingot_id,
11842
+ name: created.name,
11843
+ contentType: created.content_type,
11844
+ size: created.size_bytes,
11845
+ };
11304
11846
  }
11305
- validateUploadOptions(options) {
11306
- if (!options.file) {
11847
+ validateFile(file) {
11848
+ if (!file) {
11307
11849
  throw new ValidationError('File is required');
11308
11850
  }
11309
- if (options.file.size === 0) {
11851
+ if (file.size === 0) {
11310
11852
  throw new ValidationError('File cannot be empty');
11311
11853
  }
11312
11854
  }
@@ -11322,7 +11864,7 @@ class VaultsModule {
11322
11864
  throw new ValidationError('Download URL must use HTTPS');
11323
11865
  }
11324
11866
  const allowedHosts = this.config.allowedDownloadHostPatterns;
11325
- if (!allowedHosts.some(pattern => pattern.test(parsed.hostname))) {
11867
+ if (!allowedHosts.some((pattern) => pattern.test(parsed.hostname))) {
11326
11868
  throw new ValidationError('Invalid download URL from server');
11327
11869
  }
11328
11870
  }
@@ -11333,24 +11875,89 @@ function getBlobName(file) {
11333
11875
  }
11334
11876
  return 'unnamed';
11335
11877
  }
11336
- const DOWNLOAD_MAX_ATTEMPTS = 3;
11337
- const DOWNLOAD_RETRY_BASE_MS = 500;
11878
+ function normalizeIngotId(ingotId) {
11879
+ if (!ingotId) {
11880
+ throw new ValidationError('Ingot ID is required');
11881
+ }
11882
+ return ingotId.startsWith('ing_') ? ingotId : `ing_${ingotId}`;
11883
+ }
11884
+ function mapIngot(wire) {
11885
+ return {
11886
+ id: wire.ingot_id,
11887
+ name: wire.name,
11888
+ contentType: wire.content_type,
11889
+ size: wire.size_bytes,
11890
+ status: wire.status ?? 'active',
11891
+ createdAt: wire.created_at ?? 0,
11892
+ folderId: wire.folder_id ?? null,
11893
+ };
11894
+ }
11895
+ function mapIngotPage(response) {
11896
+ return {
11897
+ ingots: (response.ingots ?? []).map(mapIngot),
11898
+ nextCursor: response.next_cursor,
11899
+ };
11900
+ }
11901
+ function mapSharingConfig(wire) {
11902
+ return {
11903
+ shared: wire.shared,
11904
+ visibility: wire.visibility,
11905
+ invites: wire.invites?.map(mapInvite),
11906
+ };
11907
+ }
11908
+ function mapInvite(wire) {
11909
+ return {
11910
+ id: wire.id ?? wire.invite_id ?? '',
11911
+ identity: wire.identity,
11912
+ identityType: wire.identity_type ?? 'email',
11913
+ };
11914
+ }
11915
+ function mapAccessLog(entry) {
11916
+ const eventType = entry.event_type ?? entry.action ?? '';
11917
+ const action = eventType.includes('download') ? 'download' : 'view';
11918
+ const actor = entry.actor;
11919
+ return {
11920
+ id: entry.log_id ?? entry.event_id ?? entry.id ?? String(entry.timestamp ?? entry.created_at ?? ''),
11921
+ action,
11922
+ identity: actor?.email ??
11923
+ entry.actor_email ??
11924
+ entry.identity ??
11925
+ actor?.id ??
11926
+ actor?.user_id ??
11927
+ actor?.api_key_id ??
11928
+ entry.actor_id ??
11929
+ 'Unknown',
11930
+ ipAddress: entry.ip_address ?? '',
11931
+ userAgent: entry.user_agent ?? '',
11932
+ timestamp: entry.timestamp ?? entry.created_at ?? 0,
11933
+ };
11934
+ }
11935
+ function buildQuery$1(params) {
11936
+ const search = new URLSearchParams();
11937
+ for (const [key, value] of Object.entries(params)) {
11938
+ if (value === undefined || value === null || value === '')
11939
+ continue;
11940
+ search.append(key, String(value));
11941
+ }
11942
+ const query = search.toString();
11943
+ return query ? `?${query}` : '';
11944
+ }
11338
11945
  function delayExponential(attempt) {
11339
- return new Promise(resolve => setTimeout(resolve, DOWNLOAD_RETRY_BASE_MS * 2 ** (attempt - 1)));
11946
+ return new Promise((resolve) => setTimeout(resolve, DOWNLOAD_RETRY_BASE_MS * 2 ** (attempt - 1)));
11340
11947
  }
11341
11948
  function isRetryableDownloadError(err) {
11342
11949
  // Server contract / client-side validation errors aren't fixed by retrying.
11343
11950
  if (err instanceof ValidationError)
11344
11951
  return false;
11345
- // Network errors carry a status code only when the SDK HTTP client attached
11346
- // one; treat any explicitly-4xx response as a permanent failure.
11952
+ // Network errors carry a status code only when one was attached; treat any
11953
+ // explicitly-4xx response (except 408/429) as a permanent failure.
11347
11954
  const status = err.statusCode;
11348
11955
  if (typeof status === 'number' && status >= 400 && status < 500 && status !== 408 && status !== 429) {
11349
11956
  return false;
11350
11957
  }
11351
11958
  return true;
11352
11959
  }
11353
- async function fetchBlobWithTimeout(url, timeout = 300000) {
11960
+ async function fetchBlobWithTimeout(url, timeout) {
11354
11961
  const controller = new AbortController();
11355
11962
  const timeoutId = setTimeout(() => controller.abort(), timeout);
11356
11963
  try {
@@ -11360,13 +11967,386 @@ async function fetchBlobWithTimeout(url, timeout = 300000) {
11360
11967
  error.statusCode = response.status;
11361
11968
  throw error;
11362
11969
  }
11363
- return response.blob();
11970
+ return await response.blob();
11364
11971
  }
11365
11972
  finally {
11366
11973
  clearTimeout(timeoutId);
11367
11974
  }
11368
11975
  }
11369
11976
 
11977
+ /**
11978
+ * Folders Module
11979
+ *
11980
+ * Organize ingots within an *unsealed* vault. Every method takes the
11981
+ * {@link UnsealedVault} returned by `sv.vaults.unseal(...)` and authenticates
11982
+ * with its short-lived Vault Access Token (VAT).
11983
+ */
11984
+ class FoldersModule {
11985
+ constructor(http) {
11986
+ this.http = http;
11987
+ }
11988
+ /**
11989
+ * List all folders in a vault (flat list — build the tree client-side).
11990
+ *
11991
+ * @example
11992
+ * const folders = await sv.folders.list(unsealed);
11993
+ */
11994
+ async list(vault) {
11995
+ const response = await this.http.get(`/v1/vaults/${vault.id}/folders`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11996
+ return (response.data.folders ?? []).map(mapFolder);
11997
+ }
11998
+ /**
11999
+ * Get a single folder.
12000
+ *
12001
+ * @example
12002
+ * const folder = await sv.folders.get(unsealed, 'fld_abc');
12003
+ */
12004
+ async get(vault, folderId) {
12005
+ const cleanId = requireFolderId(folderId);
12006
+ const response = await this.http.get(`/v1/vaults/${vault.id}/folders/${cleanId}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
12007
+ return mapFolder(response.data);
12008
+ }
12009
+ /**
12010
+ * Get a folder's breadcrumb trail (Root → … → folder).
12011
+ *
12012
+ * @example
12013
+ * const trail = await sv.folders.getBreadcrumb(unsealed, 'fld_abc');
12014
+ */
12015
+ async getBreadcrumb(vault, folderId) {
12016
+ const cleanId = requireFolderId(folderId);
12017
+ const response = await this.http.get(`/v1/vaults/${vault.id}/folders/${cleanId}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
12018
+ return (response.data.breadcrumb ?? []).map((item) => ({
12019
+ id: item.folder_id,
12020
+ name: item.name,
12021
+ }));
12022
+ }
12023
+ /**
12024
+ * Create a folder.
12025
+ *
12026
+ * @example
12027
+ * const folder = await sv.folders.create(unsealed, { name: 'Invoices' });
12028
+ */
12029
+ async create(vault, data) {
12030
+ if (!data.name?.trim()) {
12031
+ throw new ValidationError('Folder name is required');
12032
+ }
12033
+ const response = await this.http.post(`/v1/vaults/${vault.id}/folders`, { name: data.name, parent_id: data.parentId ?? null }, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
12034
+ return mapFolder(response.data);
12035
+ }
12036
+ /**
12037
+ * Update a folder (rename, move, pin/unpin).
12038
+ *
12039
+ * @example
12040
+ * await sv.folders.update(unsealed, 'fld_abc', { name: 'Renamed' });
12041
+ */
12042
+ async update(vault, folderId, data) {
12043
+ const cleanId = requireFolderId(folderId);
12044
+ const body = {};
12045
+ if (data.name !== undefined)
12046
+ body.name = data.name;
12047
+ if (data.parentId !== undefined)
12048
+ body.parent_id = data.parentId;
12049
+ if (data.pinned !== undefined)
12050
+ body.pinned = data.pinned;
12051
+ const response = await this.http.put(`/v1/vaults/${vault.id}/folders/${cleanId}`, body, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
12052
+ return mapFolder(response.data);
12053
+ }
12054
+ /**
12055
+ * Move a folder under a new parent, or to the vault root with `null`.
12056
+ *
12057
+ * @example
12058
+ * await sv.folders.move(unsealed, 'fld_abc', 'fld_parent');
12059
+ */
12060
+ move(vault, folderId, newParentId) {
12061
+ return this.update(vault, folderId, { parentId: newParentId });
12062
+ }
12063
+ /**
12064
+ * Pin or unpin a folder.
12065
+ *
12066
+ * @example
12067
+ * await sv.folders.togglePin(unsealed, 'fld_abc', true);
12068
+ */
12069
+ togglePin(vault, folderId, pinned) {
12070
+ return this.update(vault, folderId, { pinned });
12071
+ }
12072
+ /**
12073
+ * Delete a folder.
12074
+ *
12075
+ * @example
12076
+ * await sv.folders.delete(unsealed, 'fld_abc');
12077
+ */
12078
+ async delete(vault, folderId) {
12079
+ const cleanId = requireFolderId(folderId);
12080
+ await this.http.delete(`/v1/vaults/${vault.id}/folders/${cleanId}`, {
12081
+ headers: { 'X-Vault-Access-Token': vault.vatToken },
12082
+ });
12083
+ }
12084
+ /**
12085
+ * Move an ingot into a folder, or to the vault root with `null`.
12086
+ *
12087
+ * @example
12088
+ * await sv.folders.moveIngot(unsealed, 'ing_abc', 'fld_xyz');
12089
+ */
12090
+ async moveIngot(vault, ingotId, folderId) {
12091
+ if (!ingotId) {
12092
+ throw new ValidationError('Ingot ID is required');
12093
+ }
12094
+ const cleanIngotId = ingotId.startsWith('ing_') ? ingotId : `ing_${ingotId}`;
12095
+ await this.http.patch(`/v1/vaults/${vault.id}/ingots/${cleanIngotId}`, { folder_id: folderId }, {
12096
+ headers: { 'X-Vault-Access-Token': vault.vatToken },
12097
+ });
12098
+ }
12099
+ }
12100
+ function requireFolderId(folderId) {
12101
+ if (!folderId) {
12102
+ throw new ValidationError('Folder ID is required');
12103
+ }
12104
+ return folderId;
12105
+ }
12106
+ function mapFolder(wire) {
12107
+ return {
12108
+ id: wire.folder_id,
12109
+ name: wire.name,
12110
+ parentId: wire.parent_id ?? null,
12111
+ pinned: wire.pinned ?? false,
12112
+ createdAt: wire.created_at ?? 0,
12113
+ updatedAt: wire.updated_at ?? 0,
12114
+ };
12115
+ }
12116
+
12117
+ /**
12118
+ * Sparks Module
12119
+ *
12120
+ * Create, read, share, and delete end-to-end encrypted, read-once ephemeral
12121
+ * secrets. Sparks are account-scoped — no vault or VAT is involved.
12122
+ */
12123
+ class SparksModule {
12124
+ constructor(http) {
12125
+ this.http = http;
12126
+ }
12127
+ /**
12128
+ * List sparks for the account.
12129
+ *
12130
+ * @example
12131
+ * const { sparks } = await sv.sparks.list();
12132
+ */
12133
+ async list(options = {}) {
12134
+ const query = buildQuery({
12135
+ kindling: options.kindling,
12136
+ status: options.status,
12137
+ limit: options.limit,
12138
+ cursor: options.cursor,
12139
+ });
12140
+ const response = await this.http.get(`/v1/sparks${query}`);
12141
+ return {
12142
+ sparks: (response.data.sparks ?? []).map(mapSummary),
12143
+ nextCursor: response.data.next_cursor,
12144
+ };
12145
+ }
12146
+ /**
12147
+ * Read (and burn) a spark. Reading is destructive — the spark can be read
12148
+ * exactly once.
12149
+ *
12150
+ * @example
12151
+ * const spark = await sv.sparks.get('spk_abc');
12152
+ * console.log(spark.payload);
12153
+ */
12154
+ async get(sparkId) {
12155
+ requireSparkId(sparkId);
12156
+ const response = await this.http.get(`/v1/sparks/${encodeURIComponent(sparkId)}`);
12157
+ const data = response.data;
12158
+ return {
12159
+ id: data.spark_id,
12160
+ payload: data.payload,
12161
+ contentType: data.content_type ?? 'text/plain',
12162
+ size: data.size_bytes,
12163
+ status: data.status,
12164
+ createdAt: data.created_at,
12165
+ burnedAt: data.burned_at,
12166
+ filename: data.filename,
12167
+ };
12168
+ }
12169
+ /**
12170
+ * Create a spark.
12171
+ *
12172
+ * @example
12173
+ * const spark = await sv.sparks.create({ payload: 'top secret', ttlMinutes: 60 });
12174
+ */
12175
+ async create(options) {
12176
+ if (typeof options.payload !== 'string' || options.payload.length === 0) {
12177
+ throw new ValidationError('Spark payload is required');
12178
+ }
12179
+ const body = {
12180
+ payload: options.payload,
12181
+ content_type: options.contentType,
12182
+ ttl_minutes: options.ttlMinutes,
12183
+ kindling: options.kindling,
12184
+ filename: options.filename,
12185
+ };
12186
+ if (options.withKindling) {
12187
+ body.with_kindling = true;
12188
+ }
12189
+ const response = await this.http.post('/v1/sparks', body);
12190
+ const data = response.data;
12191
+ return {
12192
+ id: data.spark_id,
12193
+ size: data.size_bytes,
12194
+ status: data.status,
12195
+ createdAt: data.created_at,
12196
+ expiresAt: data.expires_at,
12197
+ ttlMinutes: data.ttl_minutes,
12198
+ filename: data.filename,
12199
+ kindling: data.kindling,
12200
+ };
12201
+ }
12202
+ /**
12203
+ * Delete a spark.
12204
+ *
12205
+ * @example
12206
+ * await sv.sparks.delete('spk_abc');
12207
+ */
12208
+ async delete(sparkId) {
12209
+ requireSparkId(sparkId);
12210
+ await this.http.delete(`/v1/sparks/${encodeURIComponent(sparkId)}`);
12211
+ }
12212
+ /**
12213
+ * Share a spark via a public SparkLink (x.sv URL).
12214
+ *
12215
+ * @example
12216
+ * const share = await sv.sparks.share('spk_abc', { visibility: 'public' });
12217
+ * console.log(share.shareUrl);
12218
+ */
12219
+ async share(sparkId, options = {}) {
12220
+ requireSparkId(sparkId);
12221
+ const response = await this.http.patch(`/v1/sparks/${encodeURIComponent(sparkId)}/share`, {
12222
+ visibility: options.visibility,
12223
+ invites: options.invites,
12224
+ expires_in_seconds: options.expiresInSeconds,
12225
+ });
12226
+ return mapShare(response.data);
12227
+ }
12228
+ /**
12229
+ * Get a spark's sharing status.
12230
+ *
12231
+ * @example
12232
+ * const share = await sv.sparks.getShare('spk_abc');
12233
+ */
12234
+ async getShare(sparkId) {
12235
+ requireSparkId(sparkId);
12236
+ const response = await this.http.get(`/v1/sparks/${encodeURIComponent(sparkId)}/share`);
12237
+ return mapShare(response.data);
12238
+ }
12239
+ /**
12240
+ * Unshare a spark (delete its SparkLink).
12241
+ *
12242
+ * @example
12243
+ * await sv.sparks.unshare('spk_abc');
12244
+ */
12245
+ async unshare(sparkId) {
12246
+ requireSparkId(sparkId);
12247
+ const response = await this.http.delete(`/v1/sparks/${encodeURIComponent(sparkId)}/share`);
12248
+ return mapShare(response.data);
12249
+ }
12250
+ }
12251
+ function requireSparkId(sparkId) {
12252
+ if (!sparkId || typeof sparkId !== 'string') {
12253
+ throw new ValidationError('Spark ID is required');
12254
+ }
12255
+ }
12256
+ function mapSummary(wire) {
12257
+ return {
12258
+ id: wire.spark_id,
12259
+ contentType: wire.content_type ?? 'text/plain',
12260
+ size: wire.size_bytes,
12261
+ status: wire.status,
12262
+ createdAt: wire.created_at,
12263
+ expiresAt: wire.expires_at,
12264
+ burnedAt: wire.burned_at ?? null,
12265
+ timeRemaining: wire.time_remaining ?? 0,
12266
+ filename: wire.filename,
12267
+ kindling: wire.kindling,
12268
+ };
12269
+ }
12270
+ function mapShare(wire) {
12271
+ return {
12272
+ shared: wire.shared,
12273
+ shareUrl: wire.share_url,
12274
+ linkCode: wire.link_code,
12275
+ visibility: wire.visibility,
12276
+ invites: wire.invites,
12277
+ expiresAt: wire.expires_at,
12278
+ createdAt: wire.created_at,
12279
+ };
12280
+ }
12281
+ function buildQuery(params) {
12282
+ const search = new URLSearchParams();
12283
+ for (const [key, value] of Object.entries(params)) {
12284
+ if (value === undefined || value === '')
12285
+ continue;
12286
+ search.append(key, String(value));
12287
+ }
12288
+ const query = search.toString();
12289
+ return query ? `?${query}` : '';
12290
+ }
12291
+
12292
+ /**
12293
+ * Entropy Module
12294
+ *
12295
+ * Generate cryptographically strong random values from the SparkVault
12296
+ * hardware-backed entropy service.
12297
+ */
12298
+ class EntropyModule {
12299
+ constructor(http) {
12300
+ this.http = http;
12301
+ }
12302
+ /**
12303
+ * Generate random entropy in the requested format.
12304
+ *
12305
+ * @example
12306
+ * const { value } = await sv.entropy.generate({ bytes: 32, format: 'hex' });
12307
+ */
12308
+ async generate(options) {
12309
+ this.validateByteCount(options.bytes);
12310
+ const response = await this.http.post('/v1/entropy/generate', {
12311
+ num_bytes: options.bytes,
12312
+ format: options.format ?? 'hex',
12313
+ });
12314
+ const data = response.data;
12315
+ return {
12316
+ value: data.value,
12317
+ numBytes: data.num_bytes,
12318
+ format: data.format,
12319
+ referenceId: data.reference_id,
12320
+ };
12321
+ }
12322
+ /**
12323
+ * Generate `n` random bytes as a Uint8Array.
12324
+ *
12325
+ * @example
12326
+ * const key = await sv.entropy.generateBytes(32);
12327
+ */
12328
+ async generateBytes(n) {
12329
+ this.validateByteCount(n);
12330
+ const result = await this.generate({ bytes: n, format: 'base64url' });
12331
+ if (typeof result.value !== 'string' || result.value.length === 0) {
12332
+ throw new SparkVaultError('Entropy endpoint returned no value', 'invalid_response');
12333
+ }
12334
+ const bytes = base64urlDecode(result.value);
12335
+ if (bytes.length !== n) {
12336
+ throw new SparkVaultError(`Entropy length mismatch: expected ${n}, got ${bytes.length}`, 'invalid_response');
12337
+ }
12338
+ return bytes;
12339
+ }
12340
+ validateByteCount(bytes) {
12341
+ if (!Number.isInteger(bytes) || bytes < 1 || bytes > 1024) {
12342
+ throw new ValidationError('Entropy byte count must be an integer from 1 to 1024', {
12343
+ field: 'bytes',
12344
+ received: bytes,
12345
+ });
12346
+ }
12347
+ }
12348
+ }
12349
+
11370
12350
  /**
11371
12351
  * SparkVault Debug Logger
11372
12352
  *
@@ -11465,7 +12445,7 @@ const logger = {
11465
12445
  *
11466
12446
  * <script>
11467
12447
  * // SDK is ready - just use it
11468
- * SparkVault.identity.attach('.login-btn', {
12448
+ * SparkVault.products.identity.attach('.login-btn', {
11469
12449
  * onSuccess: (result) => console.log('Verified:', result.identity)
11470
12450
  * });
11471
12451
  * </script>
@@ -11517,7 +12497,7 @@ function autoInit(SparkVaultClass) {
11517
12497
  /**
11518
12498
  * SparkVault JavaScript SDK
11519
12499
  *
11520
- * A unified SDK for Identity and Vaults.
12500
+ * A unified SDK for Identity, Vaults, Ingots, Folders, Sparks, and Entropy.
11521
12501
  *
11522
12502
  * @example CDN Usage (Recommended)
11523
12503
  * ```html
@@ -11527,8 +12507,8 @@ function autoInit(SparkVaultClass) {
11527
12507
  * ></script>
11528
12508
  *
11529
12509
  * <script>
11530
- * // SDK auto-initializes. Use JavaScript API:
11531
- * SparkVault.identity.attach('.login-btn', {
12510
+ * // SDK auto-initializes. Use the JavaScript API:
12511
+ * SparkVault.products.identity.attach('.login-btn', {
11532
12512
  * onSuccess: (result) => console.log('Verified:', result.identity)
11533
12513
  * });
11534
12514
  * </script>
@@ -11540,7 +12520,7 @@ function autoInit(SparkVaultClass) {
11540
12520
  *
11541
12521
  * const sv = SparkVault.init({ accountId: 'acc_your_account' });
11542
12522
  *
11543
- * const result = await sv.identity.verify();
12523
+ * const result = await sv.products.identity.verify();
11544
12524
  * console.log(result.identity, result.identityType);
11545
12525
  * ```
11546
12526
  */
@@ -11549,8 +12529,12 @@ class SparkVault {
11549
12529
  validateConfig(config);
11550
12530
  this.config = resolveConfig(config);
11551
12531
  const http = new HttpClient(this.config);
11552
- this.identity = new IdentityModule(this.config);
12532
+ this.products = new ProductsModule(this.config);
11553
12533
  this.vaults = new VaultsModule(this.config, http);
12534
+ this.ingots = new IngotsModule(this.config, http);
12535
+ this.folders = new FoldersModule(http);
12536
+ this.sparks = new SparksModule(http);
12537
+ this.entropy = new EntropyModule(http);
11554
12538
  this.health = new HealthModule(this.config);
11555
12539
  }
11556
12540
  /**
@@ -11579,5 +12563,5 @@ if (typeof window !== 'undefined') {
11579
12563
  window.SparkVault = instance ?? SparkVault;
11580
12564
  }
11581
12565
 
11582
- export { AuthenticationError, AuthorizationError, NetworkError, PlanRequiredError, PopupBlockedError, QuotaExceededError, SparkVault, SparkVaultError, TimeoutError, UserCancelledError, ValidationError, SparkVault as default, logger, setDebugMode };
12566
+ export { AuthenticationError, AuthorizationError, EntropyModule, FoldersModule, IdentityModule, IngotsModule, NetworkError, PlanRequiredError, PopupBlockedError, ProductsModule, QuotaExceededError, SparkVault, SparkVaultError, SparksModule, TimeoutError, UserCancelledError, ValidationError, VaultsModule, SparkVault as default, logger, setDebugMode };
11583
12567
  //# sourceMappingURL=sparkvault.esm.js.map