@sparkvault/sdk-js 2.2.4 → 4.0.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 (56) hide show
  1. package/dist/auto-init.d.ts +1 -1
  2. package/dist/entropy/index.d.ts +28 -0
  3. package/dist/entropy/types.d.ts +32 -0
  4. package/dist/folders/index.d.ts +77 -0
  5. package/dist/folders/types.d.ts +64 -0
  6. package/dist/http.d.ts +3 -1
  7. package/dist/index.d.ts +994 -78
  8. package/dist/ingots/index.d.ts +183 -0
  9. package/dist/ingots/types.d.ts +286 -0
  10. package/dist/{identity → products/identity}/api.d.ts +40 -4
  11. package/dist/{identity → products/identity}/embedder.d.ts +1 -1
  12. package/dist/{identity → products/identity}/handlers/totp-handler.d.ts +1 -1
  13. package/dist/{identity → products/identity}/index.d.ts +7 -7
  14. package/dist/{identity → products/identity}/renderer.d.ts +49 -3
  15. package/dist/{identity → products/identity}/state.d.ts +0 -17
  16. package/dist/{identity → products/identity}/types.d.ts +53 -0
  17. package/dist/{identity → products/identity}/utils.d.ts +1 -1
  18. package/dist/products/identity/views/backup-verify.d.ts +41 -0
  19. package/dist/{identity → products/identity}/views/index.d.ts +1 -0
  20. package/dist/products/index.d.ts +18 -0
  21. package/dist/sparks/index.d.ts +65 -0
  22. package/dist/sparks/types.d.ts +174 -0
  23. package/dist/sparkvault.cjs.js +1573 -366
  24. package/dist/sparkvault.cjs.js.map +1 -1
  25. package/dist/sparkvault.esm.js +1567 -367
  26. package/dist/sparkvault.esm.js.map +1 -1
  27. package/dist/sparkvault.js +1 -1
  28. package/dist/sparkvault.js.map +1 -1
  29. package/dist/vaults/index.d.ts +102 -34
  30. package/dist/vaults/types.d.ts +121 -57
  31. package/dist/vaults/upload/api.d.ts +1 -1
  32. package/package.json +1 -1
  33. /package/dist/{identity → products/identity}/container.d.ts +0 -0
  34. /package/dist/{identity → products/identity}/handlers/index.d.ts +0 -0
  35. /package/dist/{identity → products/identity}/handlers/passkey-handler.d.ts +0 -0
  36. /package/dist/{identity → products/identity}/handlers/sparklink-handler.d.ts +0 -0
  37. /package/dist/{identity → products/identity}/inline-container.d.ts +0 -0
  38. /package/dist/{identity → products/identity}/methods.d.ts +0 -0
  39. /package/dist/{identity → products/identity}/modal.d.ts +0 -0
  40. /package/dist/{identity → products/identity}/styles.d.ts +0 -0
  41. /package/dist/{identity → products/identity}/utils/cooldown-timer.d.ts +0 -0
  42. /package/dist/{identity → products/identity}/utils/index.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/loading.d.ts +0 -0
  48. /package/dist/{identity → products/identity}/views/method-select.d.ts +0 -0
  49. /package/dist/{identity → products/identity}/views/origin-not-allowed.d.ts +0 -0
  50. /package/dist/{identity → products/identity}/views/passkey-prompt.d.ts +0 -0
  51. /package/dist/{identity → products/identity}/views/passkey.d.ts +0 -0
  52. /package/dist/{identity → products/identity}/views/product-not-configured.d.ts +0 -0
  53. /package/dist/{identity → products/identity}/views/service-unavailable.d.ts +0 -0
  54. /package/dist/{identity → products/identity}/views/sparklink-waiting.d.ts +0 -0
  55. /package/dist/{identity → products/identity}/views/totp-verify.d.ts +0 -0
  56. /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
  }
@@ -752,83 +758,6 @@ function base64urlToString(base64url) {
752
758
  * Consolidates duplicated logic from renderer, api, and index.
753
759
  */
754
760
  // Re-export timer utilities
755
- /**
756
- * Common multi-part public suffixes where the last two labels form the TLD.
757
- * Domains under these suffixes need three labels for a valid registrable domain
758
- * (e.g., "app.client.co.uk" → registrable domain is "client.co.uk").
759
- */
760
- const MULTI_PART_TLDS = new Set([
761
- 'co.uk', 'co.jp', 'co.kr', 'co.nz', 'co.za', 'co.in', 'co.id', 'co.th',
762
- 'com.au', 'com.br', 'com.cn', 'com.mx', 'com.sg', 'com.tw', 'com.hk',
763
- 'com.ar', 'com.co', 'com.my', 'com.ph', 'com.pk', 'com.tr', 'com.ua',
764
- 'com.vn', 'com.ng', 'com.eg', 'com.sa', 'com.pe', 'com.ec',
765
- 'net.au', 'net.br', 'net.cn', 'net.nz',
766
- 'org.au', 'org.br', 'org.cn', 'org.nz', 'org.uk',
767
- 'ac.uk', 'gov.uk', 'ac.jp', 'ne.jp', 'or.jp',
768
- 'ac.kr', 'go.kr', 'or.kr',
769
- 'ac.nz', 'govt.nz',
770
- 'ac.za', 'gov.za',
771
- 'ac.in', 'gov.in', 'net.in', 'org.in',
772
- ]);
773
- /**
774
- * Extract the root (registrable) domain from a hostname for cross-subdomain cookies.
775
- * Returns the domain prefixed with a dot (e.g., ".client.com") or null when
776
- * the domain attribute should not be set (loopback hosts, IP addresses).
777
- *
778
- * @param hostname - The hostname to extract the root domain from
779
- * @returns Root domain with leading dot, or null
780
- */
781
- function getRootDomain(hostname) {
782
- // Loopback host — browsers reject domain attribute for localhost
783
- if (hostname === 'localhost' || hostname === '127.0.0.1')
784
- return null;
785
- // IPv4 addresses
786
- if (/^\d{1,3}(\.\d{1,3}){3}$/.test(hostname))
787
- return null;
788
- // IPv6 addresses
789
- if (hostname.includes(':'))
790
- return null;
791
- const parts = hostname.split('.');
792
- // Single-label hostnames (no dots)
793
- if (parts.length <= 1)
794
- return null;
795
- // Two-part domain (e.g., "client.com") — already the root
796
- if (parts.length === 2)
797
- return `.${hostname}`;
798
- // Check for multi-part TLD (e.g., "co.uk" in "app.client.co.uk")
799
- const lastTwo = parts.slice(-2).join('.');
800
- if (MULTI_PART_TLDS.has(lastTwo) && parts.length >= 3) {
801
- return `.${parts.slice(-3).join('.')}`;
802
- }
803
- // Standard TLD — root domain is last two parts (e.g., "app.client.com" → ".client.com")
804
- return `.${lastTwo}`;
805
- }
806
- /**
807
- * Get cookie value by name
808
- * @param name - Cookie name
809
- * @returns Cookie value or null if not found
810
- */
811
- function getCookie(name) {
812
- const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`));
813
- return match ? match[2] : null;
814
- }
815
- /**
816
- * Set cookie with expiration on the root domain for cross-subdomain access.
817
- * The domain is automatically extracted from the current hostname and prefixed
818
- * with a dot (e.g., ".client.com") so the cookie is shared across all subdomains.
819
- *
820
- * @param name - Cookie name
821
- * @param value - Cookie value
822
- * @param days - Days until expiration
823
- */
824
- function setCookie(name, value, days) {
825
- const date = new Date();
826
- date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
827
- const expires = `expires=${date.toUTCString()}`;
828
- const domain = getRootDomain(window.location.hostname);
829
- const domainAttr = domain ? `; domain=${domain}` : '';
830
- document.cookie = `${name}=${value}; ${expires}; path=/${domainAttr}; SameSite=Lax`;
831
- }
832
761
  /**
833
762
  * Generate cryptographically secure random state string
834
763
  * Used for OAuth CSRF protection
@@ -1055,6 +984,42 @@ class IdentityApi extends SparkVaultApi {
1055
984
  },
1056
985
  });
1057
986
  }
987
+ /**
988
+ * Send a one-time code to a new backup identifier (the inverse of the
989
+ * identifier just logged in with). Authorized by the login's verification
990
+ * token. Returns a pending-attach `session_id`, or `already_verified` when
991
+ * the identifier is already on the identity.
992
+ */
993
+ async sendBackupVerification(params) {
994
+ return this.request('POST', '/backup-verification/send', {
995
+ verification_token: params.verificationToken,
996
+ type: params.type,
997
+ value: params.value,
998
+ ...(params.method ? { method: params.method } : {}),
999
+ });
1000
+ }
1001
+ /**
1002
+ * Confirm the backup-identifier code and attach it to the identity. A 409
1003
+ * `backup_conflict` (identifier owned by another identity) surfaces as a
1004
+ * thrown IdentityApiError with code `backup_conflict`.
1005
+ */
1006
+ async verifyBackupVerification(params) {
1007
+ return this.request('POST', '/backup-verification/verify', {
1008
+ session_id: params.sessionId,
1009
+ code: params.code,
1010
+ });
1011
+ }
1012
+ /**
1013
+ * Skip a post-login recommendation, suppressing it server-side for 30 days.
1014
+ * Authorized by the login's verification token. Best-effort — a failure here
1015
+ * must not block completing the login.
1016
+ */
1017
+ async dismissRecommendation(params) {
1018
+ await this.request('POST', '/recommendations/dismiss', {
1019
+ verification_token: params.verificationToken,
1020
+ key: params.key,
1021
+ });
1022
+ }
1058
1023
  /**
1059
1024
  * Get OAuth redirect URL for social provider
1060
1025
  */
@@ -1110,9 +1075,32 @@ class IdentityApi extends SparkVaultApi {
1110
1075
  sessionId: typeof data.session_id === 'string' ? data.session_id : undefined,
1111
1076
  refreshToken: typeof data.refresh_token === 'string' ? data.refresh_token : undefined,
1112
1077
  redirect: typeof data.redirect === 'string' ? data.redirect : undefined,
1078
+ recommendations: mapRecommendations(data.recommendations),
1113
1079
  };
1114
1080
  }
1115
1081
  }
1082
+ /**
1083
+ * Map the API's snake_case recommendation list to the SDK's typed shape,
1084
+ * dropping any entries the SDK does not understand. Returns undefined when
1085
+ * absent so callers treat it as "no nudges".
1086
+ */
1087
+ function mapRecommendations(raw) {
1088
+ if (!Array.isArray(raw))
1089
+ return undefined;
1090
+ const result = [];
1091
+ for (const item of raw) {
1092
+ if (!item || typeof item !== 'object')
1093
+ continue;
1094
+ const rec = item;
1095
+ if (rec.type === 'passkey') {
1096
+ result.push({ type: 'passkey' });
1097
+ }
1098
+ else if (rec.type === 'backup_identifier' && (rec.missing_type === 'email' || rec.missing_type === 'phone')) {
1099
+ result.push({ type: 'backup_identifier', missingType: rec.missing_type });
1100
+ }
1101
+ }
1102
+ return result;
1103
+ }
1116
1104
  class IdentityApiError extends SparkVaultError {
1117
1105
  constructor(message, code, statusCode, details) {
1118
1106
  super(message, code, statusCode, details);
@@ -1282,12 +1270,6 @@ class VerificationState {
1282
1270
  get accountId() {
1283
1271
  return this._sdkConfig?.accountId ?? '';
1284
1272
  }
1285
- /**
1286
- * Check if passkey method is enabled in config
1287
- */
1288
- isPasskeyEnabled() {
1289
- return this._sdkConfig?.methods?.includes('passkey') ?? false;
1290
- }
1291
1273
  // --- View State ---
1292
1274
  get viewState() {
1293
1275
  return this._viewState;
@@ -1332,33 +1314,6 @@ class VerificationState {
1332
1314
  setPendingResult(result) {
1333
1315
  this._passkey.pendingResult = result;
1334
1316
  }
1335
- /**
1336
- * Check if we should show passkey registration prompt
1337
- * Based on: passkey enabled, the current SVID doesn't have one, not dismissed
1338
- */
1339
- shouldShowPasskeyPrompt() {
1340
- if (!this.isPasskeyEnabled())
1341
- return false;
1342
- if (this.isPasskeyPromptDismissed())
1343
- return false;
1344
- if (this._passkey.hasPasskey === true)
1345
- return false;
1346
- return true;
1347
- }
1348
- /**
1349
- * Check if passkey prompt was dismissed (30-day cookie)
1350
- */
1351
- isPasskeyPromptDismissed() {
1352
- const cookieName = `sv_passkey_prompt_dismissed_${this.accountId}`;
1353
- return getCookie(cookieName) !== null;
1354
- }
1355
- /**
1356
- * Dismiss passkey prompt for 30 days
1357
- */
1358
- dismissPasskeyPrompt() {
1359
- const cookieName = `sv_passkey_prompt_dismissed_${this.accountId}`;
1360
- setCookie(cookieName, '1', 30);
1361
- }
1362
1317
  // --- TOTP State ---
1363
1318
  get totp() {
1364
1319
  return this._totp;
@@ -1812,6 +1767,7 @@ class TotpHandler {
1812
1767
  sessionId: response.session_id,
1813
1768
  refreshToken: response.refresh_token,
1814
1769
  redirect: response.redirect,
1770
+ recommendations: mapRecommendations(response.recommendations),
1815
1771
  },
1816
1772
  };
1817
1773
  }
@@ -4875,6 +4831,147 @@ class PasskeyPromptView {
4875
4831
  }
4876
4832
  }
4877
4833
 
4834
+ /**
4835
+ * Backup Verification Input View
4836
+ *
4837
+ * Post-login nudge to add the inverse identifier as a recovery backup:
4838
+ * collects a new phone (for an email login) or email (for a phone login),
4839
+ * then hands it off to send a one-time code. Includes a "Not now" skip that
4840
+ * suppresses this method's prompt for 30 days (handled by the renderer).
4841
+ *
4842
+ * Sibling of PasskeyPromptView — same low-friction, skippable shape.
4843
+ */
4844
+ class BackupVerifyView {
4845
+ constructor(props) {
4846
+ this.inputElement = null;
4847
+ this.submitButton = null;
4848
+ this.skipLink = null;
4849
+ this.errorContainer = null;
4850
+ this.focusTimeoutId = null;
4851
+ this.props = props;
4852
+ this.boundHandleInput = () => this.handleInput();
4853
+ this.boundHandleKeyDown = (e) => {
4854
+ if (e.key === 'Enter') {
4855
+ e.preventDefault();
4856
+ this.handleSubmit();
4857
+ }
4858
+ };
4859
+ this.boundHandleSubmit = () => this.handleSubmit();
4860
+ this.boundHandleSkip = () => this.props.onSkip();
4861
+ }
4862
+ get isPhone() {
4863
+ return this.props.missingType === 'phone';
4864
+ }
4865
+ render() {
4866
+ const container = div('sv-email-view');
4867
+ const headerSection = div('sv-email-header');
4868
+ const title = document.createElement('h3');
4869
+ title.className = 'sv-title';
4870
+ title.textContent = this.isPhone ? 'Add a backup phone number' : 'Add a backup email';
4871
+ const subtitle = document.createElement('p');
4872
+ subtitle.className = 'sv-email-subtitle';
4873
+ subtitle.textContent = this.isPhone
4874
+ ? 'Add a phone number so you can always get back into your account.'
4875
+ : 'Add an email so you can always get back into your account.';
4876
+ headerSection.appendChild(title);
4877
+ headerSection.appendChild(subtitle);
4878
+ container.appendChild(headerSection);
4879
+ this.errorContainer = div('sv-email-error-container');
4880
+ if (this.props.error) {
4881
+ this.errorContainer.appendChild(errorMessage(this.props.error));
4882
+ }
4883
+ container.appendChild(this.errorContainer);
4884
+ const formSection = div('sv-email-form');
4885
+ const inputWrapper = div('sv-email-input-wrapper');
4886
+ const label = document.createElement('label');
4887
+ label.className = 'sv-email-label';
4888
+ label.htmlFor = 'sv-backup-input';
4889
+ label.textContent = this.isPhone ? 'Phone number' : 'Email address';
4890
+ this.inputElement = document.createElement('input');
4891
+ this.inputElement.type = this.isPhone ? 'tel' : 'email';
4892
+ this.inputElement.id = 'sv-backup-input';
4893
+ this.inputElement.className = 'sv-email-input';
4894
+ this.inputElement.placeholder = this.isPhone ? '(555) 123-4567' : 'you@example.com';
4895
+ this.inputElement.autocomplete = this.isPhone ? 'tel' : 'email';
4896
+ this.inputElement.required = true;
4897
+ this.inputElement.maxLength = 254;
4898
+ this.inputElement.addEventListener('input', this.boundHandleInput);
4899
+ this.inputElement.addEventListener('keydown', this.boundHandleKeyDown);
4900
+ inputWrapper.appendChild(label);
4901
+ inputWrapper.appendChild(this.inputElement);
4902
+ formSection.appendChild(inputWrapper);
4903
+ this.submitButton = document.createElement('button');
4904
+ this.submitButton.className = 'sv-btn sv-btn-primary';
4905
+ this.submitButton.textContent = 'Send code';
4906
+ this.submitButton.addEventListener('click', this.boundHandleSubmit);
4907
+ formSection.appendChild(this.submitButton);
4908
+ this.skipLink = document.createElement('button');
4909
+ this.skipLink.className = 'sv-skip-link';
4910
+ this.skipLink.textContent = 'Not now';
4911
+ this.skipLink.addEventListener('click', this.boundHandleSkip);
4912
+ formSection.appendChild(this.skipLink);
4913
+ container.appendChild(formSection);
4914
+ this.focusTimeoutId = setTimeout(() => this.inputElement?.focus(), 50);
4915
+ return container;
4916
+ }
4917
+ handleInput() {
4918
+ this.clearError();
4919
+ // Live-format phone numbers as the user types (email needs no formatting).
4920
+ if (!this.inputElement || !this.isPhone)
4921
+ return;
4922
+ const value = this.inputElement.value;
4923
+ const cursorPos = this.inputElement.selectionStart ?? value.length;
4924
+ const formatted = formatPhoneDisplay(value);
4925
+ if (formatted !== value) {
4926
+ this.inputElement.value = formatted;
4927
+ const newPos = Math.min(cursorPos + (formatted.length - value.length), formatted.length);
4928
+ this.inputElement.setSelectionRange(newPos, newPos);
4929
+ }
4930
+ }
4931
+ clearError() {
4932
+ if (this.errorContainer)
4933
+ clearChildren(this.errorContainer);
4934
+ this.inputElement?.classList.remove('sv-email-input-error');
4935
+ }
4936
+ showError(message) {
4937
+ if (this.errorContainer) {
4938
+ clearChildren(this.errorContainer);
4939
+ this.errorContainer.appendChild(errorMessage(message));
4940
+ }
4941
+ this.inputElement?.classList.add('sv-email-input-error');
4942
+ this.inputElement?.focus();
4943
+ }
4944
+ handleSubmit() {
4945
+ if (!this.inputElement || !this.submitButton)
4946
+ return;
4947
+ const raw = this.inputElement.value;
4948
+ const normalized = this.isPhone ? validatePhone(raw) : validateEmail(raw);
4949
+ if (!normalized) {
4950
+ this.showError(this.isPhone ? 'Please enter a valid phone number' : 'Please enter a valid email address');
4951
+ return;
4952
+ }
4953
+ this.submitButton.disabled = true;
4954
+ this.submitButton.textContent = 'Please wait...';
4955
+ this.props.onSubmit(normalized);
4956
+ }
4957
+ destroy() {
4958
+ if (this.focusTimeoutId !== null) {
4959
+ clearTimeout(this.focusTimeoutId);
4960
+ this.focusTimeoutId = null;
4961
+ }
4962
+ if (this.inputElement) {
4963
+ this.inputElement.removeEventListener('input', this.boundHandleInput);
4964
+ this.inputElement.removeEventListener('keydown', this.boundHandleKeyDown);
4965
+ }
4966
+ if (this.submitButton) {
4967
+ this.submitButton.removeEventListener('click', this.boundHandleSubmit);
4968
+ }
4969
+ if (this.skipLink) {
4970
+ this.skipLink.removeEventListener('click', this.boundHandleSkip);
4971
+ }
4972
+ }
4973
+ }
4974
+
4878
4975
  /**
4879
4976
  * SparkLink Waiting View
4880
4977
  *
@@ -5601,6 +5698,10 @@ class IdentityRenderer {
5601
5698
  // View management
5602
5699
  this.currentView = null;
5603
5700
  this.focusTimeoutId = null;
5701
+ // Post-login recommendation pipeline: the verified result to finalize with,
5702
+ // and the remaining server-recommended steps to walk before finalizing.
5703
+ this.postLoginResult = null;
5704
+ this.postLoginQueue = [];
5604
5705
  // SparkLink WebSocket
5605
5706
  this.sparkLinkWs = null;
5606
5707
  // SparkLink WebSocket-loss fallback: the login kindling lets the SDK reclaim
@@ -5916,6 +6017,26 @@ class IdentityRenderer {
5916
6017
  onSkip: () => this.handlePasskeyPromptSkip(state.pendingResult),
5917
6018
  error: state.error,
5918
6019
  });
6020
+ case 'backup-verify':
6021
+ return new BackupVerifyView({
6022
+ missingType: state.missingType,
6023
+ error: state.error,
6024
+ onSubmit: (value) => this.handleBackupSubmit(value),
6025
+ onSkip: () => this.handleBackupSkip(),
6026
+ });
6027
+ case 'backup-code':
6028
+ return new TotpVerifyView({
6029
+ email: state.value,
6030
+ method: state.method,
6031
+ error: state.error,
6032
+ onSubmit: (code) => this.handleBackupCodeSubmit(code),
6033
+ onResend: () => this.handleBackupResend(),
6034
+ onBack: () => this.setState({
6035
+ view: 'backup-verify',
6036
+ missingType: state.missingType,
6037
+ pendingResult: state.pendingResult,
6038
+ }),
6039
+ });
5919
6040
  case 'sparklink-waiting':
5920
6041
  return new SparkLinkWaitingView({
5921
6042
  email: state.email,
@@ -6174,23 +6295,7 @@ class IdentityRenderer {
6174
6295
  return;
6175
6296
  }
6176
6297
  if (result.success && result.result) {
6177
- // Passkey upsell only when there's no redirect target — with one,
6178
- // we head to the destination immediately.
6179
- if (!result.result.redirect && await this.shouldShowPasskeyPrompt()) {
6180
- this.setState({
6181
- view: 'passkey-prompt',
6182
- recipient: this.recipient,
6183
- pendingResult: result.result,
6184
- });
6185
- return;
6186
- }
6187
- this.close();
6188
- // Hand the full result (including redirect) to the host first so the
6189
- // page-level handler can act before we navigate away.
6190
- this.safeOnSuccess(result.result);
6191
- if (typeof result.result.redirect === 'string' && result.result.redirect) {
6192
- navigateWith(this.options, result.result.redirect);
6193
- }
6298
+ this.runPostLogin(result.result);
6194
6299
  }
6195
6300
  else if (result.errorCode === 'identity_locked') {
6196
6301
  // The identity is locked down — a dedicated, actionable state, not a
@@ -6368,15 +6473,10 @@ class IdentityRenderer {
6368
6473
  * User clicked "Back" or cancelled registration after being prompted.
6369
6474
  */
6370
6475
  handlePasskeyRegistrationSkip() {
6371
- const pendingResult = this.verificationState.passkey.pendingResult;
6372
- if (pendingResult) {
6373
- this.verificationState.setPendingResult(null);
6374
- this.close();
6375
- this.safeOnSuccess(pendingResult);
6376
- if (typeof pendingResult.redirect === 'string' && pendingResult.redirect) {
6377
- navigateWith(this.options, pendingResult.redirect);
6378
- }
6379
- }
6476
+ this.verificationState.setPendingResult(null);
6477
+ // Treat as skipping the passkey recommendation, then advance the pipeline.
6478
+ this.dismissRecommendation('passkey');
6479
+ this.advancePostLogin();
6380
6480
  }
6381
6481
  handleSocialLogin(provider) {
6382
6482
  this.setState({ view: 'oauth-pending', provider });
@@ -6436,89 +6536,244 @@ class IdentityRenderer {
6436
6536
  }
6437
6537
  }
6438
6538
  /**
6439
- * Check if we should show the passkey registration prompt after PIN verification.
6539
+ * Run the post-login step pipeline for a completed primary login.
6540
+ *
6541
+ * The server returns an ordered `recommendations` list (passkey upsell,
6542
+ * backup verification, …); this walks it, rendering the step views the SDK
6543
+ * supports and finalizing when the queue drains. A redirect target skips the
6544
+ * pipeline. A future nudge is one new recommendation type + view case — no
6545
+ * primary-login handler changes.
6546
+ */
6547
+ runPostLogin(result) {
6548
+ if (result.redirect) {
6549
+ this.finalizeLogin(result);
6550
+ return;
6551
+ }
6552
+ this.postLoginResult = result;
6553
+ this.postLoginQueue = [...(result.recommendations ?? [])];
6554
+ this.advancePostLogin();
6555
+ }
6556
+ /**
6557
+ * Show the next supported recommendation, or finalize when the queue is
6558
+ * empty. The single hand-off from each step back into the pipeline.
6440
6559
  */
6441
- async shouldShowPasskeyPrompt() {
6442
- // Use centralized state for this check
6443
- if (!this.verificationState.shouldShowPasskeyPrompt()) {
6444
- return false;
6560
+ advancePostLogin() {
6561
+ const result = this.postLoginResult;
6562
+ if (!result)
6563
+ return;
6564
+ const next = this.postLoginQueue.shift();
6565
+ if (!next) {
6566
+ this.postLoginResult = null;
6567
+ this.finalizeLogin(result);
6568
+ return;
6445
6569
  }
6446
- // If we haven't checked yet, check with API
6447
- const { passkey } = this.verificationState;
6448
- if (passkey.hasPasskey === null) {
6449
- const checkResult = await this.passkeyHandler.checkPasskey();
6450
- // Only prompt if the verified identifier resolves to an SVID without a passkey.
6451
- return checkResult !== null && checkResult.identityValid && !checkResult.hasPasskey;
6570
+ if (next.type === 'passkey') {
6571
+ this.setState({ view: 'passkey-prompt', recipient: this.recipient, pendingResult: result });
6572
+ }
6573
+ else if (next.type === 'backup_identifier') {
6574
+ this.setState({ view: 'backup-verify', missingType: next.missingType, pendingResult: result });
6575
+ }
6576
+ else {
6577
+ // A recommendation type this SDK build does not render — skip it.
6578
+ this.advancePostLogin();
6452
6579
  }
6453
- return !passkey.hasPasskey;
6454
6580
  }
6455
6581
  /**
6456
- * Handle user clicking "Add Passkey" in the prompt.
6457
- * Directly triggers browser passkey creation without intermediate screen.
6582
+ * Best-effort: tell the server the person skipped a recommendation so it is
6583
+ * suppressed for 30 days. Never blocks completing the login.
6458
6584
  */
6459
- async handlePasskeyPromptAdd(pendingResult) {
6460
- // Store the pending result in case user cancels passkey registration
6461
- this.verificationState.setPendingResult(pendingResult);
6462
- // Show loading while browser passkey dialog is active
6585
+ dismissRecommendation(key) {
6586
+ const token = this.postLoginResult?.token;
6587
+ if (!token)
6588
+ return;
6589
+ void this.api.dismissRecommendation({ verificationToken: token, key }).catch(() => { });
6590
+ }
6591
+ /**
6592
+ * Complete the login: hand the result to the host before tearing down the
6593
+ * modal (so its onSuccess can act while the browsing context is alive), then
6594
+ * navigate any redirect the flow returned.
6595
+ */
6596
+ finalizeLogin(result) {
6597
+ this.safeOnSuccess(result);
6598
+ this.close();
6599
+ if (typeof result.redirect === 'string' && result.redirect) {
6600
+ navigateWith(this.options, result.redirect);
6601
+ }
6602
+ }
6603
+ /**
6604
+ * Send a code to the new backup identifier the person entered. Already-attached
6605
+ * identifiers short-circuit straight to completion; otherwise advance to code
6606
+ * entry.
6607
+ */
6608
+ async handleBackupSubmit(value) {
6609
+ if (this.viewState.view !== 'backup-verify')
6610
+ return;
6611
+ const { missingType, pendingResult } = this.viewState;
6463
6612
  this.setState({ view: 'loading' });
6464
- // Directly trigger passkey registration
6465
- const result = await this.passkeyHandler.register(pendingResult.token);
6466
- if (result.success && result.result) {
6467
- // Passkey created successfully - use the new token
6468
- this.close();
6469
- this.safeOnSuccess(result.result);
6470
- if (typeof result.result.redirect === 'string' && result.result.redirect) {
6471
- navigateWith(this.options, result.result.redirect);
6613
+ try {
6614
+ const response = await this.api.sendBackupVerification({
6615
+ verificationToken: pendingResult.token,
6616
+ type: missingType,
6617
+ value,
6618
+ });
6619
+ if (response.already_verified || !response.session_id) {
6620
+ this.advancePostLogin();
6621
+ return;
6472
6622
  }
6473
- }
6474
- else if (result.errorType === 'cancelled') {
6475
- // User cancelled browser dialog - go back to prompt so they can skip or try again
6476
6623
  this.setState({
6477
- view: 'passkey-prompt',
6478
- recipient: this.recipient,
6624
+ view: 'backup-code',
6625
+ missingType,
6626
+ value,
6627
+ method: response.method ?? (missingType === 'phone' ? 'sms' : 'email'),
6628
+ sessionId: response.session_id,
6479
6629
  pendingResult,
6480
6630
  });
6481
6631
  }
6482
- else {
6483
- // Registration failed - show error with retry option
6484
- const errorMessage = result.error || 'Failed to create passkey. Please try again.';
6632
+ catch (error) {
6485
6633
  this.setState({
6486
- view: 'passkey-prompt',
6487
- recipient: this.recipient,
6634
+ view: 'backup-verify',
6635
+ missingType,
6488
6636
  pendingResult,
6489
- error: errorMessage,
6637
+ error: error instanceof Error ? error.message : 'Could not send a code. Please try again.',
6490
6638
  });
6491
6639
  }
6492
6640
  }
6493
6641
  /**
6494
- * Handle user clicking "Not now" / "Skip" in the prompt.
6642
+ * Verify the backup code and attach the identifier, then finish the original
6643
+ * login. An identifier owned by another account (409 backup_conflict) bounces
6644
+ * back to the input so the person can try a different one.
6495
6645
  */
6496
- handlePasskeyPromptSkip(pendingResult) {
6497
- // Set 30-day cookie to suppress future prompts
6498
- this.verificationState.dismissPasskeyPrompt();
6499
- // Complete the verification
6500
- this.close();
6501
- this.safeOnSuccess(pendingResult);
6502
- if (typeof pendingResult.redirect === 'string' && pendingResult.redirect) {
6503
- navigateWith(this.options, pendingResult.redirect);
6646
+ async handleBackupCodeSubmit(code) {
6647
+ if (this.viewState.view !== 'backup-code')
6648
+ return;
6649
+ const { missingType, value, method, sessionId, pendingResult } = this.viewState;
6650
+ try {
6651
+ await this.api.verifyBackupVerification({ sessionId, code });
6652
+ this.advancePostLogin();
6653
+ }
6654
+ catch (error) {
6655
+ const errorCode = error instanceof IdentityApiError ? error.code : '';
6656
+ if (errorCode === 'backup_conflict') {
6657
+ this.setState({
6658
+ view: 'backup-verify',
6659
+ missingType,
6660
+ pendingResult,
6661
+ error: error instanceof Error ? error.message : 'That identifier is already linked to another account.',
6662
+ });
6663
+ return;
6664
+ }
6665
+ this.setState({
6666
+ view: 'backup-code',
6667
+ missingType,
6668
+ value,
6669
+ method,
6670
+ sessionId,
6671
+ pendingResult,
6672
+ error: error instanceof Error ? error.message : 'That code is not valid. Please try again.',
6673
+ });
6504
6674
  }
6505
6675
  }
6506
6676
  /**
6507
- * Open a WebSocket connection and return the connectionId.
6508
- * The server echoes back the connectionId on init; this is used to route
6509
- * the SparkLink verification result back to this SDK instance.
6510
- *
6511
- * Returns:
6512
- * - { connectionId: string } on success
6513
- * - { error: 'csp' } if blocked by Content Security Policy
6514
- * - { error: 'connection' } for other connection failures
6677
+ * Resend the backup code, refreshing the pending-attach session.
6515
6678
  */
6516
- openSparkLinkWebSocket() {
6517
- this.cleanupSparkLink();
6518
- const wsDomain = this.sdkConfig?.wsDomain || 'ws.sparkvault.com';
6519
- const wsUrl = `wss://${wsDomain}`;
6520
- return new Promise((resolve) => {
6521
- let resolved = false;
6679
+ async handleBackupResend() {
6680
+ if (this.viewState.view !== 'backup-code')
6681
+ return;
6682
+ const { missingType, value, method, pendingResult } = this.viewState;
6683
+ try {
6684
+ const response = await this.api.sendBackupVerification({
6685
+ verificationToken: pendingResult.token,
6686
+ type: missingType,
6687
+ value,
6688
+ method,
6689
+ });
6690
+ if (response.session_id) {
6691
+ this.setState({
6692
+ view: 'backup-code',
6693
+ missingType,
6694
+ value,
6695
+ method: response.method ?? method,
6696
+ sessionId: response.session_id,
6697
+ pendingResult,
6698
+ });
6699
+ }
6700
+ }
6701
+ catch {
6702
+ // Keep the current code view; the user can press resend again.
6703
+ }
6704
+ }
6705
+ /**
6706
+ * "Not now" on the backup prompt: suppress this identifier type for 30 days
6707
+ * (server-side) and advance to the next step.
6708
+ */
6709
+ handleBackupSkip() {
6710
+ if (this.viewState.view !== 'backup-verify')
6711
+ return;
6712
+ const { missingType } = this.viewState;
6713
+ this.dismissRecommendation(missingType === 'phone' ? 'backup_phone' : 'backup_email');
6714
+ this.advancePostLogin();
6715
+ }
6716
+ /**
6717
+ * Handle user clicking "Add Passkey" in the prompt.
6718
+ * Directly triggers browser passkey creation without intermediate screen.
6719
+ */
6720
+ async handlePasskeyPromptAdd(pendingResult) {
6721
+ // Store the pending result in case user cancels passkey registration
6722
+ this.verificationState.setPendingResult(pendingResult);
6723
+ // Show loading while browser passkey dialog is active
6724
+ this.setState({ view: 'loading' });
6725
+ // Directly trigger passkey registration
6726
+ const result = await this.passkeyHandler.register(pendingResult.token);
6727
+ if (result.success && result.result) {
6728
+ // Passkey created — adopt its fresh token/session as the result to
6729
+ // finalize with (and to authorize any later backup-attach step), then
6730
+ // advance to the next recommendation.
6731
+ this.postLoginResult = result.result;
6732
+ this.advancePostLogin();
6733
+ }
6734
+ else if (result.errorType === 'cancelled') {
6735
+ // User cancelled browser dialog - go back to prompt so they can skip or try again
6736
+ this.setState({
6737
+ view: 'passkey-prompt',
6738
+ recipient: this.recipient,
6739
+ pendingResult,
6740
+ });
6741
+ }
6742
+ else {
6743
+ // Registration failed - show error with retry option
6744
+ const errorMessage = result.error || 'Failed to create passkey. Please try again.';
6745
+ this.setState({
6746
+ view: 'passkey-prompt',
6747
+ recipient: this.recipient,
6748
+ pendingResult,
6749
+ error: errorMessage,
6750
+ });
6751
+ }
6752
+ }
6753
+ /**
6754
+ * Handle user clicking "Not now" / "Skip" in the passkey prompt: suppress it
6755
+ * for 30 days (server-side) and advance to the next step.
6756
+ */
6757
+ handlePasskeyPromptSkip(_pendingResult) {
6758
+ this.dismissRecommendation('passkey');
6759
+ this.advancePostLogin();
6760
+ }
6761
+ /**
6762
+ * Open a WebSocket connection and return the connectionId.
6763
+ * The server echoes back the connectionId on init; this is used to route
6764
+ * the SparkLink verification result back to this SDK instance.
6765
+ *
6766
+ * Returns:
6767
+ * - { connectionId: string } on success
6768
+ * - { error: 'csp' } if blocked by Content Security Policy
6769
+ * - { error: 'connection' } for other connection failures
6770
+ */
6771
+ openSparkLinkWebSocket() {
6772
+ this.cleanupSparkLink();
6773
+ const wsDomain = this.sdkConfig?.wsDomain || 'ws.sparkvault.com';
6774
+ const wsUrl = `wss://${wsDomain}`;
6775
+ return new Promise((resolve) => {
6776
+ let resolved = false;
6522
6777
  let cspViolationDetected = false;
6523
6778
  // Listen for CSP violations to provide a more helpful error message
6524
6779
  const cspHandler = (event) => {
@@ -6660,27 +6915,9 @@ class IdentityRenderer {
6660
6915
  if (kindling) {
6661
6916
  void this.api.consumeSparkLinkResult(kindling).catch(() => { });
6662
6917
  }
6663
- // Passkey upsell only when there's no redirect target — once we have
6664
- // a destination we go there immediately, no upsell.
6665
- if (!result.redirect && await this.shouldShowPasskeyPrompt()) {
6666
- this.setState({
6667
- view: 'passkey-prompt',
6668
- recipient: this.recipient,
6669
- pendingResult: result,
6670
- });
6671
- return;
6672
- }
6673
- // Hand the full result (including redirect) to the host BEFORE tearing down
6674
- // the modal, so the host's onSuccess can act (logging, navigation) without
6675
- // racing the teardown of the browsing context.
6676
- this.safeOnSuccess(result);
6677
- this.close();
6678
- // SDK-side fallback navigation. If the host already navigated this is
6679
- // a no-op (the document is already unloading); if not, this rescues
6680
- // simple-mode flows whose host forgot to act on result.redirect.
6681
- if (typeof result.redirect === 'string' && result.redirect) {
6682
- navigateWith(this.options, result.redirect);
6683
- }
6918
+ // Run the post-login step pipeline (passkey upsell, then backup
6919
+ // verification). With a redirect target it finalizes immediately.
6920
+ this.runPostLogin(result);
6684
6921
  }
6685
6922
  /**
6686
6923
  * Arm the WebSocket-loss fallback for the waiting screen.
@@ -7427,13 +7664,13 @@ function attachClickHandler(selector, onClick) {
7427
7664
  * Supports passkey, TOTP, SparkLink, and social authentication.
7428
7665
  *
7429
7666
  * @example Dialog mode (immediate)
7430
- * const result = await sv.identity.verify();
7667
+ * const result = await sv.products.identity.verify();
7431
7668
  *
7432
7669
  * @example Dialog mode (attached to clicks)
7433
- * sv.identity.attach('.login-btn');
7670
+ * sv.products.identity.attach('.login-btn');
7434
7671
  *
7435
7672
  * @example Inline mode
7436
- * const result = await sv.identity.verify({ target: '#auth-container' });
7673
+ * const result = await sv.products.identity.verify({ target: '#auth-container' });
7437
7674
  */
7438
7675
  function isTokenClaims(payload) {
7439
7676
  if (typeof payload !== 'object' || payload === null) {
@@ -7468,11 +7705,11 @@ class IdentityModule {
7468
7705
  * - With `target`: Renders inline into the specified element
7469
7706
  *
7470
7707
  * @example Dialog mode
7471
- * const result = await sv.identity.verify();
7708
+ * const result = await sv.products.identity.verify();
7472
7709
  * console.log(result.token, result.identity);
7473
7710
  *
7474
7711
  * @example Inline mode
7475
- * const result = await sv.identity.verify({
7712
+ * const result = await sv.products.identity.verify({
7476
7713
  * target: '#auth-container',
7477
7714
  * email: 'user@example.com'
7478
7715
  * });
@@ -7572,7 +7809,7 @@ class IdentityModule {
7572
7809
  * @returns Cleanup function to remove event listeners
7573
7810
  *
7574
7811
  * @example
7575
- * const cleanup = sv.identity.attach('.login-btn', {
7812
+ * const cleanup = sv.products.identity.attach('.login-btn', {
7576
7813
  * onSuccess: (result) => console.log('Verified:', result.identity)
7577
7814
  * });
7578
7815
  *
@@ -7777,6 +8014,19 @@ class IdentityModule {
7777
8014
  }
7778
8015
  }
7779
8016
 
8017
+ /**
8018
+ * Products Module
8019
+ *
8020
+ * Namespace for SparkVault first-party products. Each product is a
8021
+ * self-contained surface (UI + API) the account can enable independently.
8022
+ * Currently exposes `identity`; future products attach here alongside it.
8023
+ */
8024
+ class ProductsModule {
8025
+ constructor(config) {
8026
+ this.identity = new IdentityModule(config);
8027
+ }
8028
+ }
8029
+
7780
8030
  /**
7781
8031
  * Upload API
7782
8032
  *
@@ -7913,7 +8163,7 @@ class UploadApi extends SparkVaultApi {
7913
8163
  * Upload a file to Forge over the TUS resumable protocol (v1.0.0).
7914
8164
  *
7915
8165
  * The single canonical browser transfer path — the upload widget and the
7916
- * authenticated `uploadIngot` flow both go through here (CLAUDE.md: one
8166
+ * authenticated `ingots.upload` flow both go through here (CLAUDE.md: one
7917
8167
  * transfer path). Creates the session, PATCHes chunks sized by the server's
7918
8168
  * `X-Chunk-Size` (50MB default, which keeps every request under CDN body
7919
8169
  * caps such as Cloudflare's 100MB), validates every server-reported offset,
@@ -10866,15 +11116,15 @@ class VaultUploadModule {
10866
11116
  /**
10867
11117
  * Vaults Module
10868
11118
  *
10869
- * Create and manage encrypted vaults and ingots.
10870
- * Uses Triple Zero-Trust encryption (SVMK + AMK + VMK).
11119
+ * Create and manage encrypted vaults (the control plane). Uses Triple
11120
+ * Zero-Trust encryption (SVMK + AMK + VMK). Ingot, folder, spark, and entropy
11121
+ * operations live in their own modules; this module owns the vault record,
11122
+ * its sharing/upload configuration, and the browser upload widget.
10871
11123
  */
10872
11124
  class VaultsModule {
10873
11125
  constructor(config, http) {
10874
- this.config = config;
10875
11126
  this.http = http;
10876
11127
  this.uploadModule = new VaultUploadModule(config);
10877
- this.uploadApi = new UploadApi(config);
10878
11128
  // Create callable that also has attach/close/pop/render methods
10879
11129
  const uploadFn = ((options) => this.uploadModule.upload(options));
10880
11130
  uploadFn.attach = (selector, options) => this.uploadModule.attach(selector, options);
@@ -10895,14 +11145,12 @@ class VaultsModule {
10895
11145
  this.validateCreateOptions(options);
10896
11146
  const response = await this.http.post('/v1/vaults', {
10897
11147
  name: options.name,
10898
- hosted_vmk: options.hostedVmk ?? false,
10899
11148
  });
10900
11149
  return {
10901
11150
  id: response.data.vault_id,
10902
11151
  name: response.data.name,
10903
11152
  vmk: response.data.vmk,
10904
11153
  createdAt: response.data.created_at,
10905
- hostedVmk: response.data.hosted_vmk,
10906
11154
  };
10907
11155
  }
10908
11156
  /**
@@ -10911,16 +11159,13 @@ class VaultsModule {
10911
11159
  *
10912
11160
  * @example
10913
11161
  * const unsealed = await sv.vaults.unseal('vlt_abc', vmk);
10914
- * console.log('Ingots:', unsealed.ingotCount);
11162
+ * console.log('Token:', unsealed.vatToken);
10915
11163
  */
10916
11164
  async unseal(vaultId, vmk) {
10917
- if (!vaultId) {
10918
- throw new ValidationError('Vault ID is required');
10919
- }
11165
+ const cleanId = this.normalizeVaultId(vaultId);
10920
11166
  if (!vmk) {
10921
11167
  throw new ValidationError('VMK is required');
10922
11168
  }
10923
- const cleanId = vaultId.startsWith('vlt_') ? vaultId : `vlt_${vaultId}`;
10924
11169
  const response = await this.http.post(`/v1/vaults/${cleanId}/unseal`, { vmk });
10925
11170
  if (!response.data.vat) {
10926
11171
  throw new ValidationError('Unseal response did not include a vault access token');
@@ -10948,120 +11193,243 @@ class VaultsModule {
10948
11193
  createdAt: v.created_at,
10949
11194
  ingotCount: v.ingot_count,
10950
11195
  storageBytes: v.storage_bytes,
10951
- hostedVmk: v.hosted_vmk,
10952
11196
  }));
10953
11197
  }
10954
11198
  /**
10955
- * Delete a vault and all its ingots.
10956
- * This action is irreversible!
11199
+ * Get a single vault's detail.
11200
+ *
11201
+ * @example
11202
+ * const vault = await sv.vaults.get('vlt_abc');
11203
+ * console.log(vault.status, vault.ingotCount);
11204
+ */
11205
+ async get(vaultId) {
11206
+ const cleanId = this.normalizeVaultId(vaultId);
11207
+ const response = await this.http.get(`/v1/vaults/${cleanId}`);
11208
+ const v = response.data;
11209
+ return {
11210
+ id: v.vault_id,
11211
+ name: v.name,
11212
+ description: v.description ?? null,
11213
+ status: v.status,
11214
+ ingotCount: v.ingot_count ?? 0,
11215
+ storageBytes: v.storage_bytes ?? 0,
11216
+ createdAt: v.created_at,
11217
+ lastUnsealedAt: v.last_unsealed_at ?? null,
11218
+ unsealCount: v.unseal_count ?? 0,
11219
+ };
11220
+ }
11221
+ /**
11222
+ * Rename a vault.
11223
+ *
11224
+ * @example
11225
+ * await sv.vaults.update('vlt_abc', { name: 'Renamed Vault' });
11226
+ */
11227
+ async update(vaultId, options) {
11228
+ const cleanId = this.normalizeVaultId(vaultId);
11229
+ if (!options.name?.trim()) {
11230
+ throw new ValidationError('Vault name is required');
11231
+ }
11232
+ const response = await this.http.put(`/v1/vaults/${cleanId}`, {
11233
+ name: options.name,
11234
+ });
11235
+ const v = response.data;
11236
+ return {
11237
+ id: v.vault_id,
11238
+ name: v.name,
11239
+ description: v.description ?? null,
11240
+ updatedAt: v.updated_at,
11241
+ };
11242
+ }
11243
+ /**
11244
+ * Seal a vault, revoking all active access tokens.
11245
+ *
11246
+ * @example
11247
+ * await sv.vaults.seal('vlt_abc');
11248
+ */
11249
+ async seal(vaultId) {
11250
+ const cleanId = this.normalizeVaultId(vaultId);
11251
+ await this.http.post(`/v1/vaults/${cleanId}/seal`);
11252
+ }
11253
+ /**
11254
+ * Delete a vault and all its ingots. This action is irreversible!
10957
11255
  *
10958
11256
  * @example
10959
11257
  * await sv.vaults.delete('vlt_abc', vmk);
10960
11258
  */
10961
11259
  async delete(vaultId, vmk) {
10962
- const cleanId = vaultId.startsWith('vlt_') ? vaultId : `vlt_${vaultId}`;
11260
+ const cleanId = this.normalizeVaultId(vaultId);
10963
11261
  await this.http.delete(`/v1/vaults/${cleanId}`, {
10964
11262
  headers: { 'X-VMK': vmk },
10965
11263
  });
10966
11264
  }
10967
11265
  /**
10968
- * Upload a file as an ingot to an unsealed vault.
11266
+ * Get a vault's public-sharing configuration.
10969
11267
  *
10970
11268
  * @example
10971
- * const ingot = await sv.vaults.uploadIngot(unsealed, {
10972
- * file: myFile,
10973
- * name: 'document.pdf'
10974
- * });
11269
+ * const sharing = await sv.vaults.getSharingConfig('vlt_abc');
10975
11270
  */
10976
- async uploadIngot(vault, options) {
10977
- this.validateUploadOptions(options);
10978
- const requestedName = options.name ?? getBlobName(options.file);
10979
- const requestedContentType = options.contentType ?? options.file.type ?? 'application/octet-stream';
10980
- const createResponse = await this.http.post(`/v1/vaults/${vault.id}/ingots`, {
10981
- name: requestedName,
10982
- content_type: requestedContentType,
10983
- size_bytes: options.file.size,
10984
- }, {
10985
- headers: { 'X-Vault-Access-Token': vault.vatToken },
10986
- });
10987
- const created = createResponse.data;
10988
- if (!created.forge_url) {
10989
- throw new ValidationError('Upload endpoint did not return a Forge upload URL');
11271
+ async getSharingConfig(vaultId) {
11272
+ const cleanId = this.normalizeVaultId(vaultId);
11273
+ const response = await this.http.get(`/v1/vaults/${cleanId}/sharing`);
11274
+ return mapSharingConfig$1(response.data);
11275
+ }
11276
+ /**
11277
+ * Enable public sharing for a vault.
11278
+ *
11279
+ * @example
11280
+ * await sv.vaults.enableSharing('vlt_abc', vmk, { sessionLengthSeconds: 3600 });
11281
+ */
11282
+ async enableSharing(vaultId, vmk, options = {}) {
11283
+ const cleanId = this.normalizeVaultId(vaultId);
11284
+ if (!vmk) {
11285
+ throw new ValidationError('VMK is required');
10990
11286
  }
10991
- const uploadUrl = await this.uploadApi.uploadFileToForge(options.file, created.forge_url, options.onProgress);
10992
- // Confirm the server actually finalized the upload before reporting
10993
- // success — the TUS loop's offsets alone don't prove the final chunk
10994
- // committed and the ingot went active.
10995
- await this.uploadApi.verifyUploadFinalized(uploadUrl, options.file.size);
11287
+ const response = await this.http.post(`/v1/vaults/${cleanId}/sharing/enable`, {
11288
+ vmk,
11289
+ all_ingots_public: options.allIngotsPublic,
11290
+ session_length_seconds: options.sessionLengthSeconds,
11291
+ });
11292
+ return mapSharingConfig$1(response.data);
11293
+ }
11294
+ /**
11295
+ * Disable public sharing for a vault.
11296
+ *
11297
+ * @example
11298
+ * await sv.vaults.disableSharing('vlt_abc');
11299
+ */
11300
+ async disableSharing(vaultId) {
11301
+ const cleanId = this.normalizeVaultId(vaultId);
11302
+ const response = await this.http.post(`/v1/vaults/${cleanId}/sharing/disable`);
11303
+ return mapSharingConfig$1(response.data);
11304
+ }
11305
+ /**
11306
+ * Update a vault's sharing configuration (without changing enabled state).
11307
+ *
11308
+ * @example
11309
+ * await sv.vaults.updateSharingConfig('vlt_abc', { allIngotsPublic: true });
11310
+ */
11311
+ async updateSharingConfig(vaultId, config) {
11312
+ const cleanId = this.normalizeVaultId(vaultId);
11313
+ const response = await this.http.put(`/v1/vaults/${cleanId}/sharing`, {
11314
+ all_ingots_public: config.allIngotsPublic,
11315
+ session_length_seconds: config.sessionLengthSeconds,
11316
+ });
11317
+ return mapSharingConfig$1(response.data);
11318
+ }
11319
+ /**
11320
+ * Get a vault's access-log retention window.
11321
+ *
11322
+ * @example
11323
+ * const { retentionSeconds } = await sv.vaults.getAccessLogRetention('vlt_abc');
11324
+ */
11325
+ async getAccessLogRetention(vaultId) {
11326
+ const cleanId = this.normalizeVaultId(vaultId);
11327
+ const response = await this.http.get(`/v1/vaults/${cleanId}/access-log-retention`);
10996
11328
  return {
10997
- id: created.ingot_id,
10998
- name: created.name,
10999
- contentType: created.content_type,
11000
- size: created.size_bytes,
11001
- uploadExpiresAt: created.expires_at,
11329
+ vaultId: response.data.vault_id,
11330
+ retentionSeconds: response.data.access_log_retention_seconds,
11002
11331
  };
11003
11332
  }
11004
11333
  /**
11005
- * Download an ingot from an unsealed vault.
11334
+ * Update a vault's access-log retention window.
11006
11335
  *
11007
11336
  * @example
11008
- * const blob = await sv.vaults.downloadIngot(unsealed, 'ing_abc');
11009
- * const url = URL.createObjectURL(blob);
11337
+ * await sv.vaults.updateAccessLogRetention('vlt_abc', 7776000);
11010
11338
  */
11011
- async downloadIngot(vault, ingotId) {
11012
- const cleanId = ingotId.startsWith('ing_') ? ingotId : `ing_${ingotId}`;
11013
- let lastError = null;
11014
- for (let attempt = 1; attempt <= DOWNLOAD_MAX_ATTEMPTS; attempt++) {
11015
- try {
11016
- const response = await this.http.post(`/v1/vaults/${vault.id}/ingots/${cleanId}/download`, undefined, {
11017
- headers: { 'X-Vault-Access-Token': vault.vatToken },
11018
- });
11019
- if (!response.data.download_url) {
11020
- throw new ValidationError('Download endpoint did not return a download URL');
11021
- }
11022
- this.validateDownloadUrl(response.data.download_url);
11023
- return await fetchBlobWithTimeout(response.data.download_url);
11024
- }
11025
- catch (err) {
11026
- lastError = err instanceof Error ? err : new Error(String(err));
11027
- if (!isRetryableDownloadError(lastError) || attempt === DOWNLOAD_MAX_ATTEMPTS) {
11028
- throw lastError;
11029
- }
11030
- await delayExponential(attempt);
11031
- }
11032
- }
11033
- throw lastError ?? new Error('Download failed');
11339
+ async updateAccessLogRetention(vaultId, seconds) {
11340
+ const cleanId = this.normalizeVaultId(vaultId);
11341
+ const response = await this.http.put(`/v1/vaults/${cleanId}/access-log-retention`, { access_log_retention_seconds: seconds });
11342
+ return {
11343
+ vaultId: response.data.vault_id,
11344
+ retentionSeconds: response.data.access_log_retention_seconds,
11345
+ };
11034
11346
  }
11035
11347
  /**
11036
- * List all ingots in an unsealed vault.
11348
+ * Get a vault's upload-channel configuration.
11037
11349
  *
11038
11350
  * @example
11039
- * const ingots = await sv.vaults.listIngots(unsealed);
11040
- * ingots.forEach(i => console.log(i.name, i.size));
11351
+ * const upload = await sv.vaults.getUploadConfig('vlt_abc');
11041
11352
  */
11042
- async listIngots(vault) {
11043
- const response = await this.http.get(`/v1/vaults/${vault.id}/ingots`, {
11044
- headers: { 'X-Vault-Access-Token': vault.vatToken },
11045
- });
11046
- return response.data.ingots.map((i) => ({
11047
- id: i.ingot_id,
11048
- name: i.name,
11049
- contentType: i.content_type,
11050
- size: i.size_bytes,
11051
- createdAt: i.created_at,
11052
- }));
11353
+ async getUploadConfig(vaultId) {
11354
+ const cleanId = this.normalizeVaultId(vaultId);
11355
+ const response = await this.http.get(`/v1/vaults/${cleanId}/upload`);
11356
+ return mapUploadSettings(response.data);
11053
11357
  }
11054
11358
  /**
11055
- * Delete an ingot from an unsealed vault.
11359
+ * Enable the public upload portal for a vault.
11056
11360
  *
11057
11361
  * @example
11058
- * await sv.vaults.deleteIngot(unsealed, 'ing_abc');
11362
+ * await sv.vaults.enableUploadPortal('vlt_abc', vmk);
11059
11363
  */
11060
- async deleteIngot(vault, ingotId) {
11061
- const cleanId = ingotId.startsWith('ing_') ? ingotId : `ing_${ingotId}`;
11062
- await this.http.delete(`/v1/vaults/${vault.id}/ingots/${cleanId}`, {
11063
- headers: { 'X-Vault-Access-Token': vault.vatToken },
11064
- });
11364
+ async enableUploadPortal(vaultId, vmk) {
11365
+ return this.toggleUploadChannel(vaultId, 'portal', 'enable', vmk);
11366
+ }
11367
+ /**
11368
+ * Disable the public upload portal for a vault.
11369
+ *
11370
+ * @example
11371
+ * await sv.vaults.disableUploadPortal('vlt_abc');
11372
+ */
11373
+ async disableUploadPortal(vaultId) {
11374
+ return this.toggleUploadChannel(vaultId, 'portal', 'disable');
11375
+ }
11376
+ /**
11377
+ * Enable the upload widget for a vault.
11378
+ *
11379
+ * @example
11380
+ * await sv.vaults.enableUploadWidget('vlt_abc', vmk);
11381
+ */
11382
+ async enableUploadWidget(vaultId, vmk) {
11383
+ return this.toggleUploadChannel(vaultId, 'widget', 'enable', vmk);
11384
+ }
11385
+ /**
11386
+ * Disable the upload widget for a vault.
11387
+ *
11388
+ * @example
11389
+ * await sv.vaults.disableUploadWidget('vlt_abc');
11390
+ */
11391
+ async disableUploadWidget(vaultId) {
11392
+ return this.toggleUploadChannel(vaultId, 'widget', 'disable');
11393
+ }
11394
+ /**
11395
+ * Update a vault's upload settings (max size, notification email).
11396
+ *
11397
+ * @example
11398
+ * await sv.vaults.updateUploadConfig('vlt_abc', { maxSizeBytes: 1048576 });
11399
+ */
11400
+ async updateUploadConfig(vaultId, config) {
11401
+ const cleanId = this.normalizeVaultId(vaultId);
11402
+ const body = {};
11403
+ if (config.maxSizeBytes !== undefined)
11404
+ body.max_size_bytes = config.maxSizeBytes;
11405
+ if (config.notificationEmail !== undefined)
11406
+ body.notification_email = config.notificationEmail;
11407
+ const response = await this.http.put(`/v1/vaults/${cleanId}/upload`, body);
11408
+ return mapUploadSettings(response.data);
11409
+ }
11410
+ async toggleUploadChannel(vaultId, channel, action, vmk) {
11411
+ const cleanId = this.normalizeVaultId(vaultId);
11412
+ if (action === 'enable' && !vmk) {
11413
+ throw new ValidationError('VMK is required');
11414
+ }
11415
+ const response = await this.http.post(`/v1/vaults/${cleanId}/upload/${channel}/${action}`, action === 'enable' ? { vmk } : undefined);
11416
+ const d = response.data;
11417
+ return {
11418
+ vaultId: d.vault_id,
11419
+ uploadPortalEnabled: d.upload_portal_enabled ?? (channel === 'portal' && action === 'enable'),
11420
+ uploadPortalEnabledAt: channel === 'portal' && action === 'enable' ? d.enabled_at ?? null : null,
11421
+ uploadWidgetEnabled: d.upload_widget_enabled ?? (channel === 'widget' && action === 'enable'),
11422
+ uploadWidgetEnabledAt: channel === 'widget' && action === 'enable' ? d.enabled_at ?? null : null,
11423
+ maxSizeBytes: null,
11424
+ notificationEmail: null,
11425
+ portalUrl: d.portal_url,
11426
+ };
11427
+ }
11428
+ normalizeVaultId(vaultId) {
11429
+ if (!vaultId) {
11430
+ throw new ValidationError('Vault ID is required');
11431
+ }
11432
+ return vaultId.startsWith('vlt_') ? vaultId : `vlt_${vaultId}`;
11065
11433
  }
11066
11434
  validateCreateOptions(options) {
11067
11435
  if (!options.name?.trim()) {
@@ -11071,55 +11439,510 @@ class VaultsModule {
11071
11439
  throw new ValidationError('Vault name must be 255 characters or less');
11072
11440
  }
11073
11441
  }
11074
- validateUploadOptions(options) {
11075
- if (!options.file) {
11076
- throw new ValidationError('File is required');
11077
- }
11078
- if (options.file.size === 0) {
11079
- throw new ValidationError('File cannot be empty');
11080
- }
11081
- }
11082
- validateDownloadUrl(downloadUrl) {
11083
- let parsed;
11084
- try {
11085
- parsed = new URL(downloadUrl);
11086
- }
11087
- catch {
11088
- throw new ValidationError('Invalid download URL from server');
11089
- }
11090
- if (parsed.protocol !== 'https:') {
11091
- throw new ValidationError('Download URL must use HTTPS');
11092
- }
11093
- const allowedHosts = this.config.allowedDownloadHostPatterns;
11094
- if (!allowedHosts.some(pattern => pattern.test(parsed.hostname))) {
11095
- throw new ValidationError('Invalid download URL from server');
11096
- }
11097
- }
11098
11442
  }
11099
- function getBlobName(file) {
11100
- if (typeof File !== 'undefined' && file instanceof File && file.name) {
11101
- return file.name;
11102
- }
11103
- return 'unnamed';
11443
+ function mapSharingConfig$1(wire) {
11444
+ return {
11445
+ vaultId: wire.vault_id,
11446
+ publicSharingEnabled: wire.public_sharing_enabled,
11447
+ allIngotsPublic: wire.all_ingots_public,
11448
+ sessionLengthSeconds: wire.session_length_seconds ?? null,
11449
+ enabledAt: wire.enabled_at ?? null,
11450
+ };
11451
+ }
11452
+ function mapUploadSettings(wire) {
11453
+ return {
11454
+ vaultId: wire.vault_id,
11455
+ uploadPortalEnabled: wire.upload_portal_enabled,
11456
+ uploadPortalEnabledAt: wire.upload_portal_enabled_at ?? null,
11457
+ uploadWidgetEnabled: wire.upload_widget_enabled,
11458
+ uploadWidgetEnabledAt: wire.upload_widget_enabled_at ?? null,
11459
+ maxSizeBytes: wire.max_size_bytes ?? null,
11460
+ notificationEmail: wire.notification_email ?? null,
11461
+ portalUrl: wire.portal_url,
11462
+ };
11104
11463
  }
11464
+
11465
+ /**
11466
+ * Ingots Module
11467
+ *
11468
+ * Data-plane operations on the contents of an *unsealed* vault. Every method
11469
+ * takes the {@link UnsealedVault} returned by `sv.vaults.unseal(...)` and
11470
+ * authenticates with its short-lived Vault Access Token (VAT).
11471
+ *
11472
+ * Uploads and downloads run over the single canonical Forge TUS transfer path
11473
+ * (shared with the public upload widget), with server-side finalization and
11474
+ * download-host allowlisting enforced — no per-size branching.
11475
+ */
11105
11476
  const DOWNLOAD_MAX_ATTEMPTS = 3;
11106
11477
  const DOWNLOAD_RETRY_BASE_MS = 500;
11107
- function delayExponential(attempt) {
11108
- return new Promise(resolve => setTimeout(resolve, DOWNLOAD_RETRY_BASE_MS * 2 ** (attempt - 1)));
11109
- }
11110
- function isRetryableDownloadError(err) {
11111
- // Server contract / client-side validation errors aren't fixed by retrying.
11112
- if (err instanceof ValidationError)
11113
- return false;
11114
- // Network errors carry a status code only when the SDK HTTP client attached
11115
- // one; treat any explicitly-4xx response as a permanent failure.
11116
- const status = err.statusCode;
11117
- if (typeof status === 'number' && status >= 400 && status < 500 && status !== 408 && status !== 429) {
11118
- return false;
11478
+ const DOWNLOAD_FETCH_TIMEOUT_MS = 300000;
11479
+ class IngotsModule {
11480
+ constructor(config, http) {
11481
+ this.config = config;
11482
+ this.http = http;
11483
+ this.uploadApi = new UploadApi(config);
11119
11484
  }
11120
- return true;
11121
- }
11122
- async function fetchBlobWithTimeout(url, timeout = 300000) {
11485
+ /**
11486
+ * Create an ingot upload session (discrete primitive).
11487
+ *
11488
+ * Reserves the ingot record and returns the Forge upload URL (carrying the
11489
+ * ISTK upload session token). Use this when you want to drive the TUS
11490
+ * transfer yourself; otherwise prefer {@link upload}.
11491
+ *
11492
+ * @example
11493
+ * const session = await sv.ingots.createUpload({
11494
+ * vault: unsealed, name: 'report.pdf',
11495
+ * contentType: 'application/pdf', sizeBytes: file.size,
11496
+ * });
11497
+ * console.log(session.uploadUrl);
11498
+ */
11499
+ async createUpload(options) {
11500
+ if (!options.name?.trim()) {
11501
+ throw new ValidationError('Ingot name is required');
11502
+ }
11503
+ if (!Number.isFinite(options.sizeBytes) || options.sizeBytes < 1) {
11504
+ throw new ValidationError('sizeBytes must be a positive number');
11505
+ }
11506
+ if (options.folder && options.folderId) {
11507
+ throw new ValidationError('Provide folder or folderId, not both');
11508
+ }
11509
+ const created = await this.requestUploadSession(options.vault, {
11510
+ name: options.name,
11511
+ content_type: options.contentType,
11512
+ size_bytes: options.sizeBytes,
11513
+ folder: options.folder,
11514
+ folderId: options.folderId,
11515
+ });
11516
+ return {
11517
+ id: created.ingot_id,
11518
+ name: created.name,
11519
+ contentType: created.content_type,
11520
+ size: created.size_bytes,
11521
+ uploadUrl: created.forge_url,
11522
+ expiresAt: created.expires_at,
11523
+ };
11524
+ }
11525
+ /**
11526
+ * Upload a file as a new ingot (high-level flow).
11527
+ *
11528
+ * Creates the upload session, streams the file to Forge over TUS, then
11529
+ * confirms the server finalized the upload before resolving.
11530
+ *
11531
+ * @example
11532
+ * const ingot = await sv.ingots.upload(unsealed, {
11533
+ * file: myFile, name: 'document.pdf'
11534
+ * });
11535
+ */
11536
+ async upload(vault, options) {
11537
+ this.validateFile(options.file);
11538
+ if (options.folder && options.folderId) {
11539
+ throw new ValidationError('Provide folder or folderId, not both');
11540
+ }
11541
+ const name = options.name ?? getBlobName(options.file);
11542
+ const contentType = options.contentType ?? options.file.type ?? 'application/octet-stream';
11543
+ const created = await this.requestUploadSession(vault, {
11544
+ name,
11545
+ content_type: contentType,
11546
+ size_bytes: options.file.size,
11547
+ folder: options.folder,
11548
+ folderId: options.folderId,
11549
+ });
11550
+ return this.transferAndFinalize(created, options.file, options.onProgress);
11551
+ }
11552
+ /**
11553
+ * Replace an existing ingot's content (high-level flow).
11554
+ *
11555
+ * @example
11556
+ * await sv.ingots.replace(unsealed, 'ing_abc', { file: updatedFile });
11557
+ */
11558
+ async replace(vault, ingotId, options) {
11559
+ this.validateFile(options.file);
11560
+ const cleanId = normalizeIngotId(ingotId);
11561
+ const name = options.name ?? getBlobName(options.file);
11562
+ const contentType = options.contentType ?? options.file.type ?? 'application/octet-stream';
11563
+ 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 } });
11564
+ if (!response.data.forge_url) {
11565
+ throw new ValidationError('Replace endpoint did not return a Forge upload URL');
11566
+ }
11567
+ return this.transferAndFinalize(response.data, options.file, options.onProgress);
11568
+ }
11569
+ /**
11570
+ * Rename an ingot.
11571
+ *
11572
+ * @example
11573
+ * await sv.ingots.rename(unsealed, 'ing_abc', 'new-name.pdf');
11574
+ */
11575
+ async rename(vault, ingotId, name) {
11576
+ if (!name?.trim()) {
11577
+ throw new ValidationError('Ingot name is required');
11578
+ }
11579
+ const cleanId = normalizeIngotId(ingotId);
11580
+ const response = await this.http.patch(`/v1/vaults/${vault.id}/ingots/${cleanId}`, { name }, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11581
+ return mapIngot(response.data);
11582
+ }
11583
+ /**
11584
+ * Move an ingot to a folder, or to the vault root with `null`.
11585
+ *
11586
+ * @example
11587
+ * await sv.ingots.move(unsealed, 'ing_abc', 'fld_xyz');
11588
+ * await sv.ingots.move(unsealed, 'ing_abc', null); // root
11589
+ */
11590
+ async move(vault, ingotId, folderId) {
11591
+ const cleanId = normalizeIngotId(ingotId);
11592
+ const response = await this.http.patch(`/v1/vaults/${vault.id}/ingots/${cleanId}`, { folder_id: folderId }, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11593
+ return mapIngot(response.data);
11594
+ }
11595
+ /**
11596
+ * Delete an ingot.
11597
+ *
11598
+ * @example
11599
+ * await sv.ingots.delete(unsealed, 'ing_abc');
11600
+ */
11601
+ async delete(vault, ingotId) {
11602
+ const cleanId = normalizeIngotId(ingotId);
11603
+ await this.http.delete(`/v1/vaults/${vault.id}/ingots/${cleanId}`, {
11604
+ headers: { 'X-Vault-Access-Token': vault.vatToken },
11605
+ });
11606
+ }
11607
+ /**
11608
+ * Get ingot metadata.
11609
+ *
11610
+ * @example
11611
+ * const ingot = await sv.ingots.get(unsealed, 'ing_abc');
11612
+ */
11613
+ async get(vault, ingotId) {
11614
+ const cleanId = normalizeIngotId(ingotId);
11615
+ const response = await this.http.get(`/v1/vaults/${vault.id}/ingots/${cleanId}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11616
+ return mapIngot(response.data);
11617
+ }
11618
+ /**
11619
+ * List ingots in an unsealed vault.
11620
+ *
11621
+ * @example
11622
+ * const { ingots } = await sv.ingots.list(unsealed);
11623
+ */
11624
+ async list(vault, options = {}) {
11625
+ const query = buildQuery$1({
11626
+ limit: options.limit,
11627
+ cursor: options.cursor,
11628
+ sort_by: options.sortBy,
11629
+ sort_order: options.sortOrder,
11630
+ });
11631
+ const response = await this.http.get(`/v1/vaults/${vault.id}/ingots${query}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11632
+ return mapIngotPage(response.data);
11633
+ }
11634
+ /**
11635
+ * Search ingots in an unsealed vault.
11636
+ *
11637
+ * @example
11638
+ * const { ingots } = await sv.ingots.search(unsealed, { q: 'invoice' });
11639
+ */
11640
+ async search(vault, options = {}) {
11641
+ const query = buildQuery$1({
11642
+ q: options.q,
11643
+ file_type: options.fileType,
11644
+ min_size: options.minSize,
11645
+ max_size: options.maxSize,
11646
+ limit: options.limit,
11647
+ cursor: options.cursor,
11648
+ sort_order: options.sortOrder,
11649
+ });
11650
+ const response = await this.http.get(`/v1/vaults/${vault.id}/ingots/search${query}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11651
+ return mapIngotPage(response.data);
11652
+ }
11653
+ /**
11654
+ * List the contents (ingots) of a folder, or the vault root.
11655
+ *
11656
+ * @example
11657
+ * const { ingots } = await sv.ingots.listContents(unsealed, { folderId: 'fld_x' });
11658
+ */
11659
+ async listContents(vault, options = {}) {
11660
+ const query = buildQuery$1({
11661
+ folder_id: options.folderId,
11662
+ limit: options.limit,
11663
+ cursor: options.cursor,
11664
+ sort_by: options.sortBy,
11665
+ sort_order: options.sortOrder,
11666
+ type: options.type,
11667
+ });
11668
+ const response = await this.http.get(`/v1/vaults/${vault.id}/contents${query}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11669
+ return mapIngotPage(response.data);
11670
+ }
11671
+ /**
11672
+ * Create a signed download link for an ingot (discrete primitive).
11673
+ *
11674
+ * Validates the returned URL against the download-host allowlist. Use this
11675
+ * when you want the URL itself; otherwise prefer {@link download}.
11676
+ *
11677
+ * @example
11678
+ * const link = await sv.ingots.createDownloadLink(unsealed, 'ing_abc');
11679
+ * window.location.href = link.downloadUrl;
11680
+ */
11681
+ async createDownloadLink(vault, ingotId) {
11682
+ const cleanId = normalizeIngotId(ingotId);
11683
+ const response = await this.http.post(`/v1/vaults/${vault.id}/ingots/${cleanId}/download`, undefined, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11684
+ if (!response.data.download_url) {
11685
+ throw new ValidationError('Download endpoint did not return a download URL');
11686
+ }
11687
+ this.validateDownloadUrl(response.data.download_url);
11688
+ return {
11689
+ downloadUrl: response.data.download_url,
11690
+ id: response.data.ingot_id,
11691
+ name: response.data.name,
11692
+ size: response.data.size_bytes,
11693
+ contentType: response.data.content_type,
11694
+ };
11695
+ }
11696
+ /**
11697
+ * Download an ingot as a Blob (high-level flow).
11698
+ *
11699
+ * Requests a fresh signed link on every attempt (server URLs are
11700
+ * short-lived) and retries transient transport failures with exponential
11701
+ * backoff. Validation failures (bad host, non-HTTPS) are never retried.
11702
+ *
11703
+ * @example
11704
+ * const blob = await sv.ingots.download(unsealed, 'ing_abc');
11705
+ * const url = URL.createObjectURL(blob);
11706
+ */
11707
+ async download(vault, ingotId) {
11708
+ let lastError = null;
11709
+ for (let attempt = 1; attempt <= DOWNLOAD_MAX_ATTEMPTS; attempt++) {
11710
+ try {
11711
+ const link = await this.createDownloadLink(vault, ingotId);
11712
+ return await fetchBlobWithTimeout(link.downloadUrl, DOWNLOAD_FETCH_TIMEOUT_MS);
11713
+ }
11714
+ catch (err) {
11715
+ lastError = err instanceof Error ? err : new Error(String(err));
11716
+ if (!isRetryableDownloadError(lastError) || attempt === DOWNLOAD_MAX_ATTEMPTS) {
11717
+ throw lastError;
11718
+ }
11719
+ await delayExponential(attempt);
11720
+ }
11721
+ }
11722
+ throw lastError ?? new Error('Download failed');
11723
+ }
11724
+ /**
11725
+ * Get an ingot's sharing configuration.
11726
+ *
11727
+ * @example
11728
+ * const sharing = await sv.ingots.getSharingConfig(unsealed, 'ing_abc');
11729
+ */
11730
+ async getSharingConfig(vault, ingotId) {
11731
+ const cleanId = normalizeIngotId(ingotId);
11732
+ const response = await this.http.get(`/v1/vaults/${vault.id}/ingots/${cleanId}/sharing`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11733
+ return mapSharingConfig(response.data);
11734
+ }
11735
+ /**
11736
+ * Update an ingot's sharing configuration.
11737
+ *
11738
+ * @example
11739
+ * await sv.ingots.updateSharingConfig(unsealed, 'ing_abc', { shared: true });
11740
+ */
11741
+ async updateSharingConfig(vault, ingotId, config) {
11742
+ const cleanId = normalizeIngotId(ingotId);
11743
+ 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 } });
11744
+ return mapSharingConfig(response.data);
11745
+ }
11746
+ /**
11747
+ * Invite an identity to a shared ingot. The identity type (email or phone)
11748
+ * is inferred server-side from the identity value.
11749
+ *
11750
+ * @example
11751
+ * await sv.ingots.addInvite(unsealed, 'ing_abc', 'user@example.com');
11752
+ * await sv.ingots.addInvite(unsealed, 'ing_abc', 'user@example.com', { expiresInSeconds: 86400 });
11753
+ */
11754
+ async addInvite(vault, ingotId, identity, options = {}) {
11755
+ if (!identity?.trim()) {
11756
+ throw new ValidationError('Invite identity is required');
11757
+ }
11758
+ const cleanId = normalizeIngotId(ingotId);
11759
+ 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 } });
11760
+ return mapInvite(response.data);
11761
+ }
11762
+ /**
11763
+ * Revoke an ingot sharing invite.
11764
+ *
11765
+ * @example
11766
+ * await sv.ingots.revokeInvite(unsealed, 'ing_abc', 'inv_123');
11767
+ */
11768
+ async revokeInvite(vault, ingotId, inviteId) {
11769
+ if (!inviteId?.trim()) {
11770
+ throw new ValidationError('Invite ID is required');
11771
+ }
11772
+ const cleanId = normalizeIngotId(ingotId);
11773
+ await this.http.delete(`/v1/vaults/${vault.id}/ingots/${cleanId}/sharing/invite/${inviteId}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11774
+ }
11775
+ /**
11776
+ * Get an ingot's access logs.
11777
+ *
11778
+ * @example
11779
+ * const { logs } = await sv.ingots.getAccessLogs(unsealed, 'ing_abc');
11780
+ */
11781
+ async getAccessLogs(vault, ingotId, options = {}) {
11782
+ const cleanId = normalizeIngotId(ingotId);
11783
+ const query = buildQuery$1({ limit: options.limit, cursor: options.cursor });
11784
+ const response = await this.http.get(`/v1/vaults/${vault.id}/ingots/${cleanId}/audit-logs${query}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11785
+ const entries = response.data.entries ?? [];
11786
+ return {
11787
+ logs: entries.map(mapAccessLog),
11788
+ nextCursor: response.data.next_cursor,
11789
+ };
11790
+ }
11791
+ /**
11792
+ * Request a Forge upload session for a new ingot.
11793
+ * Shared by createUpload and upload — the single ingot-create path.
11794
+ */
11795
+ async requestUploadSession(vault, body) {
11796
+ const payload = {
11797
+ name: body.name,
11798
+ content_type: body.content_type ?? 'application/octet-stream',
11799
+ size_bytes: body.size_bytes,
11800
+ };
11801
+ // folder_path (find-or-create) and folder_id (existing folder) are
11802
+ // mutually exclusive server-side; a path takes precedence when both given.
11803
+ if (body.folder) {
11804
+ payload.folder_path = body.folder;
11805
+ }
11806
+ else if (body.folderId) {
11807
+ payload.folder_id = body.folderId;
11808
+ }
11809
+ const response = await this.http.post(`/v1/vaults/${vault.id}/ingots`, payload, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11810
+ if (!response.data.forge_url) {
11811
+ throw new ValidationError('Upload endpoint did not return a Forge upload URL');
11812
+ }
11813
+ return response.data;
11814
+ }
11815
+ /**
11816
+ * Run the canonical TUS transfer for a created/replaced ingot, then confirm
11817
+ * the server finalized the upload before reporting success.
11818
+ */
11819
+ async transferAndFinalize(created, file, onProgress) {
11820
+ const uploadUrl = await this.uploadApi.uploadFileToForge(file, created.forge_url, onProgress);
11821
+ // Confirm the server actually finalized the upload before reporting
11822
+ // success — the TUS loop's offsets alone don't prove the final chunk
11823
+ // committed and the ingot went active.
11824
+ await this.uploadApi.verifyUploadFinalized(uploadUrl, file.size);
11825
+ return {
11826
+ id: created.ingot_id,
11827
+ name: created.name,
11828
+ contentType: created.content_type,
11829
+ size: created.size_bytes,
11830
+ };
11831
+ }
11832
+ validateFile(file) {
11833
+ if (!file) {
11834
+ throw new ValidationError('File is required');
11835
+ }
11836
+ if (file.size === 0) {
11837
+ throw new ValidationError('File cannot be empty');
11838
+ }
11839
+ }
11840
+ validateDownloadUrl(downloadUrl) {
11841
+ let parsed;
11842
+ try {
11843
+ parsed = new URL(downloadUrl);
11844
+ }
11845
+ catch {
11846
+ throw new ValidationError('Invalid download URL from server');
11847
+ }
11848
+ if (parsed.protocol !== 'https:') {
11849
+ throw new ValidationError('Download URL must use HTTPS');
11850
+ }
11851
+ const allowedHosts = this.config.allowedDownloadHostPatterns;
11852
+ if (!allowedHosts.some((pattern) => pattern.test(parsed.hostname))) {
11853
+ throw new ValidationError('Invalid download URL from server');
11854
+ }
11855
+ }
11856
+ }
11857
+ function getBlobName(file) {
11858
+ if (typeof File !== 'undefined' && file instanceof File && file.name) {
11859
+ return file.name;
11860
+ }
11861
+ return 'unnamed';
11862
+ }
11863
+ function normalizeIngotId(ingotId) {
11864
+ if (!ingotId) {
11865
+ throw new ValidationError('Ingot ID is required');
11866
+ }
11867
+ return ingotId.startsWith('ing_') ? ingotId : `ing_${ingotId}`;
11868
+ }
11869
+ function mapIngot(wire) {
11870
+ return {
11871
+ id: wire.ingot_id,
11872
+ name: wire.name,
11873
+ contentType: wire.content_type,
11874
+ size: wire.size_bytes,
11875
+ status: wire.status ?? 'active',
11876
+ createdAt: wire.created_at ?? 0,
11877
+ folderId: wire.folder_id ?? null,
11878
+ };
11879
+ }
11880
+ function mapIngotPage(response) {
11881
+ return {
11882
+ ingots: (response.ingots ?? []).map(mapIngot),
11883
+ nextCursor: response.next_cursor,
11884
+ };
11885
+ }
11886
+ function mapSharingConfig(wire) {
11887
+ return {
11888
+ shared: wire.shared,
11889
+ visibility: wire.visibility,
11890
+ invites: wire.invites?.map(mapInvite),
11891
+ };
11892
+ }
11893
+ function mapInvite(wire) {
11894
+ return {
11895
+ id: wire.id ?? wire.invite_id ?? '',
11896
+ identity: wire.identity,
11897
+ identityType: wire.identity_type ?? 'email',
11898
+ };
11899
+ }
11900
+ function mapAccessLog(entry) {
11901
+ const eventType = entry.event_type ?? entry.action ?? '';
11902
+ const action = eventType.includes('download') ? 'download' : 'view';
11903
+ const actor = entry.actor;
11904
+ return {
11905
+ id: entry.log_id ?? entry.event_id ?? entry.id ?? String(entry.timestamp ?? entry.created_at ?? ''),
11906
+ action,
11907
+ identity: actor?.email ??
11908
+ entry.actor_email ??
11909
+ entry.identity ??
11910
+ actor?.id ??
11911
+ actor?.user_id ??
11912
+ actor?.api_key_id ??
11913
+ entry.actor_id ??
11914
+ 'Unknown',
11915
+ ipAddress: entry.ip_address ?? '',
11916
+ userAgent: entry.user_agent ?? '',
11917
+ timestamp: entry.timestamp ?? entry.created_at ?? 0,
11918
+ };
11919
+ }
11920
+ function buildQuery$1(params) {
11921
+ const search = new URLSearchParams();
11922
+ for (const [key, value] of Object.entries(params)) {
11923
+ if (value === undefined || value === null || value === '')
11924
+ continue;
11925
+ search.append(key, String(value));
11926
+ }
11927
+ const query = search.toString();
11928
+ return query ? `?${query}` : '';
11929
+ }
11930
+ function delayExponential(attempt) {
11931
+ return new Promise((resolve) => setTimeout(resolve, DOWNLOAD_RETRY_BASE_MS * 2 ** (attempt - 1)));
11932
+ }
11933
+ function isRetryableDownloadError(err) {
11934
+ // Server contract / client-side validation errors aren't fixed by retrying.
11935
+ if (err instanceof ValidationError)
11936
+ return false;
11937
+ // Network errors carry a status code only when one was attached; treat any
11938
+ // explicitly-4xx response (except 408/429) as a permanent failure.
11939
+ const status = err.statusCode;
11940
+ if (typeof status === 'number' && status >= 400 && status < 500 && status !== 408 && status !== 429) {
11941
+ return false;
11942
+ }
11943
+ return true;
11944
+ }
11945
+ async function fetchBlobWithTimeout(url, timeout) {
11123
11946
  const controller = new AbortController();
11124
11947
  const timeoutId = setTimeout(() => controller.abort(), timeout);
11125
11948
  try {
@@ -11129,13 +11952,386 @@ async function fetchBlobWithTimeout(url, timeout = 300000) {
11129
11952
  error.statusCode = response.status;
11130
11953
  throw error;
11131
11954
  }
11132
- return response.blob();
11955
+ return await response.blob();
11133
11956
  }
11134
11957
  finally {
11135
11958
  clearTimeout(timeoutId);
11136
11959
  }
11137
11960
  }
11138
11961
 
11962
+ /**
11963
+ * Folders Module
11964
+ *
11965
+ * Organize ingots within an *unsealed* vault. Every method takes the
11966
+ * {@link UnsealedVault} returned by `sv.vaults.unseal(...)` and authenticates
11967
+ * with its short-lived Vault Access Token (VAT).
11968
+ */
11969
+ class FoldersModule {
11970
+ constructor(http) {
11971
+ this.http = http;
11972
+ }
11973
+ /**
11974
+ * List all folders in a vault (flat list — build the tree client-side).
11975
+ *
11976
+ * @example
11977
+ * const folders = await sv.folders.list(unsealed);
11978
+ */
11979
+ async list(vault) {
11980
+ const response = await this.http.get(`/v1/vaults/${vault.id}/folders`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11981
+ return (response.data.folders ?? []).map(mapFolder);
11982
+ }
11983
+ /**
11984
+ * Get a single folder.
11985
+ *
11986
+ * @example
11987
+ * const folder = await sv.folders.get(unsealed, 'fld_abc');
11988
+ */
11989
+ async get(vault, folderId) {
11990
+ const cleanId = requireFolderId(folderId);
11991
+ const response = await this.http.get(`/v1/vaults/${vault.id}/folders/${cleanId}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
11992
+ return mapFolder(response.data);
11993
+ }
11994
+ /**
11995
+ * Get a folder's breadcrumb trail (Root → … → folder).
11996
+ *
11997
+ * @example
11998
+ * const trail = await sv.folders.getBreadcrumb(unsealed, 'fld_abc');
11999
+ */
12000
+ async getBreadcrumb(vault, folderId) {
12001
+ const cleanId = requireFolderId(folderId);
12002
+ const response = await this.http.get(`/v1/vaults/${vault.id}/folders/${cleanId}`, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
12003
+ return (response.data.breadcrumb ?? []).map((item) => ({
12004
+ id: item.folder_id,
12005
+ name: item.name,
12006
+ }));
12007
+ }
12008
+ /**
12009
+ * Create a folder.
12010
+ *
12011
+ * @example
12012
+ * const folder = await sv.folders.create(unsealed, { name: 'Invoices' });
12013
+ */
12014
+ async create(vault, data) {
12015
+ if (!data.name?.trim()) {
12016
+ throw new ValidationError('Folder name is required');
12017
+ }
12018
+ 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 } });
12019
+ return mapFolder(response.data);
12020
+ }
12021
+ /**
12022
+ * Update a folder (rename, move, pin/unpin).
12023
+ *
12024
+ * @example
12025
+ * await sv.folders.update(unsealed, 'fld_abc', { name: 'Renamed' });
12026
+ */
12027
+ async update(vault, folderId, data) {
12028
+ const cleanId = requireFolderId(folderId);
12029
+ const body = {};
12030
+ if (data.name !== undefined)
12031
+ body.name = data.name;
12032
+ if (data.parentId !== undefined)
12033
+ body.parent_id = data.parentId;
12034
+ if (data.pinned !== undefined)
12035
+ body.pinned = data.pinned;
12036
+ const response = await this.http.put(`/v1/vaults/${vault.id}/folders/${cleanId}`, body, { headers: { 'X-Vault-Access-Token': vault.vatToken } });
12037
+ return mapFolder(response.data);
12038
+ }
12039
+ /**
12040
+ * Move a folder under a new parent, or to the vault root with `null`.
12041
+ *
12042
+ * @example
12043
+ * await sv.folders.move(unsealed, 'fld_abc', 'fld_parent');
12044
+ */
12045
+ move(vault, folderId, newParentId) {
12046
+ return this.update(vault, folderId, { parentId: newParentId });
12047
+ }
12048
+ /**
12049
+ * Pin or unpin a folder.
12050
+ *
12051
+ * @example
12052
+ * await sv.folders.togglePin(unsealed, 'fld_abc', true);
12053
+ */
12054
+ togglePin(vault, folderId, pinned) {
12055
+ return this.update(vault, folderId, { pinned });
12056
+ }
12057
+ /**
12058
+ * Delete a folder.
12059
+ *
12060
+ * @example
12061
+ * await sv.folders.delete(unsealed, 'fld_abc');
12062
+ */
12063
+ async delete(vault, folderId) {
12064
+ const cleanId = requireFolderId(folderId);
12065
+ await this.http.delete(`/v1/vaults/${vault.id}/folders/${cleanId}`, {
12066
+ headers: { 'X-Vault-Access-Token': vault.vatToken },
12067
+ });
12068
+ }
12069
+ /**
12070
+ * Move an ingot into a folder, or to the vault root with `null`.
12071
+ *
12072
+ * @example
12073
+ * await sv.folders.moveIngot(unsealed, 'ing_abc', 'fld_xyz');
12074
+ */
12075
+ async moveIngot(vault, ingotId, folderId) {
12076
+ if (!ingotId) {
12077
+ throw new ValidationError('Ingot ID is required');
12078
+ }
12079
+ const cleanIngotId = ingotId.startsWith('ing_') ? ingotId : `ing_${ingotId}`;
12080
+ await this.http.patch(`/v1/vaults/${vault.id}/ingots/${cleanIngotId}`, { folder_id: folderId }, {
12081
+ headers: { 'X-Vault-Access-Token': vault.vatToken },
12082
+ });
12083
+ }
12084
+ }
12085
+ function requireFolderId(folderId) {
12086
+ if (!folderId) {
12087
+ throw new ValidationError('Folder ID is required');
12088
+ }
12089
+ return folderId;
12090
+ }
12091
+ function mapFolder(wire) {
12092
+ return {
12093
+ id: wire.folder_id,
12094
+ name: wire.name,
12095
+ parentId: wire.parent_id ?? null,
12096
+ pinned: wire.pinned ?? false,
12097
+ createdAt: wire.created_at ?? 0,
12098
+ updatedAt: wire.updated_at ?? 0,
12099
+ };
12100
+ }
12101
+
12102
+ /**
12103
+ * Sparks Module
12104
+ *
12105
+ * Create, read, share, and delete end-to-end encrypted, read-once ephemeral
12106
+ * secrets. Sparks are account-scoped — no vault or VAT is involved.
12107
+ */
12108
+ class SparksModule {
12109
+ constructor(http) {
12110
+ this.http = http;
12111
+ }
12112
+ /**
12113
+ * List sparks for the account.
12114
+ *
12115
+ * @example
12116
+ * const { sparks } = await sv.sparks.list();
12117
+ */
12118
+ async list(options = {}) {
12119
+ const query = buildQuery({
12120
+ kindling: options.kindling,
12121
+ status: options.status,
12122
+ limit: options.limit,
12123
+ cursor: options.cursor,
12124
+ });
12125
+ const response = await this.http.get(`/v1/sparks${query}`);
12126
+ return {
12127
+ sparks: (response.data.sparks ?? []).map(mapSummary),
12128
+ nextCursor: response.data.next_cursor,
12129
+ };
12130
+ }
12131
+ /**
12132
+ * Read (and burn) a spark. Reading is destructive — the spark can be read
12133
+ * exactly once.
12134
+ *
12135
+ * @example
12136
+ * const spark = await sv.sparks.get('spk_abc');
12137
+ * console.log(spark.payload);
12138
+ */
12139
+ async get(sparkId) {
12140
+ requireSparkId(sparkId);
12141
+ const response = await this.http.get(`/v1/sparks/${encodeURIComponent(sparkId)}`);
12142
+ const data = response.data;
12143
+ return {
12144
+ id: data.spark_id,
12145
+ payload: data.payload,
12146
+ contentType: data.content_type ?? 'text/plain',
12147
+ size: data.size_bytes,
12148
+ status: data.status,
12149
+ createdAt: data.created_at,
12150
+ burnedAt: data.burned_at,
12151
+ filename: data.filename,
12152
+ };
12153
+ }
12154
+ /**
12155
+ * Create a spark.
12156
+ *
12157
+ * @example
12158
+ * const spark = await sv.sparks.create({ payload: 'top secret', ttlMinutes: 60 });
12159
+ */
12160
+ async create(options) {
12161
+ if (typeof options.payload !== 'string' || options.payload.length === 0) {
12162
+ throw new ValidationError('Spark payload is required');
12163
+ }
12164
+ const body = {
12165
+ payload: options.payload,
12166
+ content_type: options.contentType,
12167
+ ttl_minutes: options.ttlMinutes,
12168
+ kindling: options.kindling,
12169
+ filename: options.filename,
12170
+ };
12171
+ if (options.withKindling) {
12172
+ body.with_kindling = true;
12173
+ }
12174
+ const response = await this.http.post('/v1/sparks', body);
12175
+ const data = response.data;
12176
+ return {
12177
+ id: data.spark_id,
12178
+ size: data.size_bytes,
12179
+ status: data.status,
12180
+ createdAt: data.created_at,
12181
+ expiresAt: data.expires_at,
12182
+ ttlMinutes: data.ttl_minutes,
12183
+ filename: data.filename,
12184
+ kindling: data.kindling,
12185
+ };
12186
+ }
12187
+ /**
12188
+ * Delete a spark.
12189
+ *
12190
+ * @example
12191
+ * await sv.sparks.delete('spk_abc');
12192
+ */
12193
+ async delete(sparkId) {
12194
+ requireSparkId(sparkId);
12195
+ await this.http.delete(`/v1/sparks/${encodeURIComponent(sparkId)}`);
12196
+ }
12197
+ /**
12198
+ * Share a spark via a public SparkLink (x.sv URL).
12199
+ *
12200
+ * @example
12201
+ * const share = await sv.sparks.share('spk_abc', { visibility: 'public' });
12202
+ * console.log(share.shareUrl);
12203
+ */
12204
+ async share(sparkId, options = {}) {
12205
+ requireSparkId(sparkId);
12206
+ const response = await this.http.patch(`/v1/sparks/${encodeURIComponent(sparkId)}/share`, {
12207
+ visibility: options.visibility,
12208
+ invites: options.invites,
12209
+ expires_in_seconds: options.expiresInSeconds,
12210
+ });
12211
+ return mapShare(response.data);
12212
+ }
12213
+ /**
12214
+ * Get a spark's sharing status.
12215
+ *
12216
+ * @example
12217
+ * const share = await sv.sparks.getShare('spk_abc');
12218
+ */
12219
+ async getShare(sparkId) {
12220
+ requireSparkId(sparkId);
12221
+ const response = await this.http.get(`/v1/sparks/${encodeURIComponent(sparkId)}/share`);
12222
+ return mapShare(response.data);
12223
+ }
12224
+ /**
12225
+ * Unshare a spark (delete its SparkLink).
12226
+ *
12227
+ * @example
12228
+ * await sv.sparks.unshare('spk_abc');
12229
+ */
12230
+ async unshare(sparkId) {
12231
+ requireSparkId(sparkId);
12232
+ const response = await this.http.delete(`/v1/sparks/${encodeURIComponent(sparkId)}/share`);
12233
+ return mapShare(response.data);
12234
+ }
12235
+ }
12236
+ function requireSparkId(sparkId) {
12237
+ if (!sparkId || typeof sparkId !== 'string') {
12238
+ throw new ValidationError('Spark ID is required');
12239
+ }
12240
+ }
12241
+ function mapSummary(wire) {
12242
+ return {
12243
+ id: wire.spark_id,
12244
+ contentType: wire.content_type ?? 'text/plain',
12245
+ size: wire.size_bytes,
12246
+ status: wire.status,
12247
+ createdAt: wire.created_at,
12248
+ expiresAt: wire.expires_at,
12249
+ burnedAt: wire.burned_at ?? null,
12250
+ timeRemaining: wire.time_remaining ?? 0,
12251
+ filename: wire.filename,
12252
+ kindling: wire.kindling,
12253
+ };
12254
+ }
12255
+ function mapShare(wire) {
12256
+ return {
12257
+ shared: wire.shared,
12258
+ shareUrl: wire.share_url,
12259
+ linkCode: wire.link_code,
12260
+ visibility: wire.visibility,
12261
+ invites: wire.invites,
12262
+ expiresAt: wire.expires_at,
12263
+ createdAt: wire.created_at,
12264
+ };
12265
+ }
12266
+ function buildQuery(params) {
12267
+ const search = new URLSearchParams();
12268
+ for (const [key, value] of Object.entries(params)) {
12269
+ if (value === undefined || value === '')
12270
+ continue;
12271
+ search.append(key, String(value));
12272
+ }
12273
+ const query = search.toString();
12274
+ return query ? `?${query}` : '';
12275
+ }
12276
+
12277
+ /**
12278
+ * Entropy Module
12279
+ *
12280
+ * Generate cryptographically strong random values from the SparkVault
12281
+ * hardware-backed entropy service.
12282
+ */
12283
+ class EntropyModule {
12284
+ constructor(http) {
12285
+ this.http = http;
12286
+ }
12287
+ /**
12288
+ * Generate random entropy in the requested format.
12289
+ *
12290
+ * @example
12291
+ * const { value } = await sv.entropy.generate({ bytes: 32, format: 'hex' });
12292
+ */
12293
+ async generate(options) {
12294
+ this.validateByteCount(options.bytes);
12295
+ const response = await this.http.post('/v1/entropy/generate', {
12296
+ num_bytes: options.bytes,
12297
+ format: options.format ?? 'hex',
12298
+ });
12299
+ const data = response.data;
12300
+ return {
12301
+ value: data.value,
12302
+ numBytes: data.num_bytes,
12303
+ format: data.format,
12304
+ referenceId: data.reference_id,
12305
+ };
12306
+ }
12307
+ /**
12308
+ * Generate `n` random bytes as a Uint8Array.
12309
+ *
12310
+ * @example
12311
+ * const key = await sv.entropy.generateBytes(32);
12312
+ */
12313
+ async generateBytes(n) {
12314
+ this.validateByteCount(n);
12315
+ const result = await this.generate({ bytes: n, format: 'base64url' });
12316
+ if (typeof result.value !== 'string' || result.value.length === 0) {
12317
+ throw new SparkVaultError('Entropy endpoint returned no value', 'invalid_response');
12318
+ }
12319
+ const bytes = base64urlDecode(result.value);
12320
+ if (bytes.length !== n) {
12321
+ throw new SparkVaultError(`Entropy length mismatch: expected ${n}, got ${bytes.length}`, 'invalid_response');
12322
+ }
12323
+ return bytes;
12324
+ }
12325
+ validateByteCount(bytes) {
12326
+ if (!Number.isInteger(bytes) || bytes < 1 || bytes > 1024) {
12327
+ throw new ValidationError('Entropy byte count must be an integer from 1 to 1024', {
12328
+ field: 'bytes',
12329
+ received: bytes,
12330
+ });
12331
+ }
12332
+ }
12333
+ }
12334
+
11139
12335
  /**
11140
12336
  * SparkVault Debug Logger
11141
12337
  *
@@ -11234,7 +12430,7 @@ const logger = {
11234
12430
  *
11235
12431
  * <script>
11236
12432
  * // SDK is ready - just use it
11237
- * SparkVault.identity.attach('.login-btn', {
12433
+ * SparkVault.products.identity.attach('.login-btn', {
11238
12434
  * onSuccess: (result) => console.log('Verified:', result.identity)
11239
12435
  * });
11240
12436
  * </script>
@@ -11286,7 +12482,7 @@ function autoInit(SparkVaultClass) {
11286
12482
  /**
11287
12483
  * SparkVault JavaScript SDK
11288
12484
  *
11289
- * A unified SDK for Identity and Vaults.
12485
+ * A unified SDK for Identity, Vaults, Ingots, Folders, Sparks, and Entropy.
11290
12486
  *
11291
12487
  * @example CDN Usage (Recommended)
11292
12488
  * ```html
@@ -11296,8 +12492,8 @@ function autoInit(SparkVaultClass) {
11296
12492
  * ></script>
11297
12493
  *
11298
12494
  * <script>
11299
- * // SDK auto-initializes. Use JavaScript API:
11300
- * SparkVault.identity.attach('.login-btn', {
12495
+ * // SDK auto-initializes. Use the JavaScript API:
12496
+ * SparkVault.products.identity.attach('.login-btn', {
11301
12497
  * onSuccess: (result) => console.log('Verified:', result.identity)
11302
12498
  * });
11303
12499
  * </script>
@@ -11309,7 +12505,7 @@ function autoInit(SparkVaultClass) {
11309
12505
  *
11310
12506
  * const sv = SparkVault.init({ accountId: 'acc_your_account' });
11311
12507
  *
11312
- * const result = await sv.identity.verify();
12508
+ * const result = await sv.products.identity.verify();
11313
12509
  * console.log(result.identity, result.identityType);
11314
12510
  * ```
11315
12511
  */
@@ -11318,8 +12514,12 @@ class SparkVault {
11318
12514
  validateConfig(config);
11319
12515
  this.config = resolveConfig(config);
11320
12516
  const http = new HttpClient(this.config);
11321
- this.identity = new IdentityModule(this.config);
12517
+ this.products = new ProductsModule(this.config);
11322
12518
  this.vaults = new VaultsModule(this.config, http);
12519
+ this.ingots = new IngotsModule(this.config, http);
12520
+ this.folders = new FoldersModule(http);
12521
+ this.sparks = new SparksModule(http);
12522
+ this.entropy = new EntropyModule(http);
11323
12523
  this.health = new HealthModule(this.config);
11324
12524
  }
11325
12525
  /**
@@ -11348,5 +12548,5 @@ if (typeof window !== 'undefined') {
11348
12548
  window.SparkVault = instance ?? SparkVault;
11349
12549
  }
11350
12550
 
11351
- export { AuthenticationError, AuthorizationError, NetworkError, PlanRequiredError, PopupBlockedError, QuotaExceededError, SparkVault, SparkVaultError, TimeoutError, UserCancelledError, ValidationError, SparkVault as default, logger, setDebugMode };
12551
+ export { AuthenticationError, AuthorizationError, EntropyModule, FoldersModule, IdentityModule, IngotsModule, NetworkError, PlanRequiredError, PopupBlockedError, ProductsModule, QuotaExceededError, SparkVault, SparkVaultError, SparksModule, TimeoutError, UserCancelledError, ValidationError, VaultsModule, SparkVault as default, logger, setDebugMode };
11352
12552
  //# sourceMappingURL=sparkvault.esm.js.map