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