@sparkvault/sdk-js 2.2.1 → 2.2.2

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.
@@ -153,103 +153,6 @@ function validateConfig(config) {
153
153
  }
154
154
  }
155
155
 
156
- /**
157
- * Retry Utility with Exponential Backoff
158
- *
159
- * Per CLAUDE.md §7: Retries allowed only if idempotent, MUST use exponential backoff.
160
- */
161
- const DEFAULT_OPTIONS$2 = {
162
- maxAttempts: 3,
163
- baseDelayMs: 200,
164
- maxDelayMs: 5000,
165
- jitterFactor: 0.2,
166
- isRetryable: defaultIsRetryable,
167
- };
168
- /**
169
- * Default retry eligibility checker
170
- * Retries on network errors, timeouts, and 5xx server errors
171
- */
172
- function defaultIsRetryable(error) {
173
- // Network errors (TypeError from fetch)
174
- if (error instanceof TypeError) {
175
- return true;
176
- }
177
- // DOMException (timeout/abort)
178
- if (error instanceof DOMException && error.name === 'AbortError') {
179
- return true;
180
- }
181
- // SparkVault errors with status codes
182
- if (typeof error === 'object' &&
183
- error !== null &&
184
- 'statusCode' in error) {
185
- const statusCode = error.statusCode;
186
- // Retry on server errors (5xx) and rate limits (429)
187
- return statusCode >= 500 || statusCode === 429;
188
- }
189
- return false;
190
- }
191
- /**
192
- * Return a random unit interval value using Web Crypto.
193
- */
194
- function randomUnit() {
195
- const value = new Uint32Array(1);
196
- crypto.getRandomValues(value);
197
- return value[0] / 0x100000000;
198
- }
199
- /**
200
- * Calculate delay with exponential backoff and jitter
201
- */
202
- function calculateDelay(attempt, baseDelayMs, maxDelayMs, jitterFactor) {
203
- // Exponential backoff: base * 2^attempt
204
- const exponentialDelay = baseDelayMs * Math.pow(2, attempt);
205
- const cappedDelay = Math.min(exponentialDelay, maxDelayMs);
206
- // Add jitter: random value within jitter range
207
- const jitter = cappedDelay * jitterFactor * randomUnit();
208
- return cappedDelay + jitter;
209
- }
210
- /**
211
- * Sleep for specified milliseconds
212
- */
213
- function sleep(ms) {
214
- return new Promise((resolve) => setTimeout(resolve, ms));
215
- }
216
- /**
217
- * Execute an async function with retry logic and exponential backoff.
218
- *
219
- * @param fn - Async function to execute
220
- * @param options - Retry configuration options
221
- * @returns Promise resolving to the function result
222
- * @throws The last error if all retries fail
223
- *
224
- * @example
225
- * const result = await withRetry(
226
- * () => fetch('/api/data'),
227
- * { maxAttempts: 3, baseDelayMs: 100 }
228
- * );
229
- */
230
- async function withRetry(fn, options = {}) {
231
- const config = { ...DEFAULT_OPTIONS$2, ...options };
232
- let lastError;
233
- for (let attempt = 0; attempt < config.maxAttempts; attempt++) {
234
- try {
235
- return await fn();
236
- }
237
- catch (error) {
238
- lastError = error;
239
- // Don't retry on last attempt or non-retryable errors
240
- const isLastAttempt = attempt === config.maxAttempts - 1;
241
- if (isLastAttempt || !config.isRetryable(error)) {
242
- throw error;
243
- }
244
- // Calculate and wait for backoff delay
245
- const delay = calculateDelay(attempt, config.baseDelayMs, config.maxDelayMs, config.jitterFactor);
246
- await sleep(delay);
247
- }
248
- }
249
- // Should not reach here, but TypeScript needs this
250
- throw lastError;
251
- }
252
-
253
156
  /**
254
157
  * SparkVault SDK HTTP Client
255
158
  */
@@ -283,22 +186,6 @@ class HttpClient {
283
186
  return this.config.accessToken ?? null;
284
187
  }
285
188
  async request(path, options = {}) {
286
- const { retry } = options;
287
- // Per CLAUDE.md §7: Wrap with retry logic if enabled
288
- if (retry) {
289
- const retryOptions = typeof retry === 'object' ? retry : {};
290
- return withRetry(() => this.executeRequest(path, options), {
291
- ...retryOptions,
292
- // Only retry on idempotent-safe errors (network, timeout, 5xx)
293
- isRetryable: (error) => this.isRetryableError(error),
294
- });
295
- }
296
- return this.executeRequest(path, options);
297
- }
298
- /**
299
- * Execute the actual HTTP request (internal implementation)
300
- */
301
- async executeRequest(path, options) {
302
189
  const { method = 'GET', headers = {}, body, timeout = this.config.timeout, } = options;
303
190
  const url = `${this.config.apiBaseUrl}${path}`;
304
191
  const requestHeaders = await this.getDefaultHeaders(headers, body !== undefined);
@@ -336,21 +223,6 @@ class HttpClient {
336
223
  throw new SparkVaultError(error instanceof Error ? error.message : 'Unknown error', 'unknown_error');
337
224
  }
338
225
  }
339
- /**
340
- * Check if an error is safe to retry
341
- * Per CLAUDE.md §7: Only retry on transient/network errors, not client errors
342
- */
343
- isRetryableError(error) {
344
- // Network errors are retryable
345
- if (error instanceof NetworkError || error instanceof TimeoutError) {
346
- return true;
347
- }
348
- // 5xx server errors and 429 rate limits are retryable
349
- if (error instanceof SparkVaultError && error.statusCode !== undefined) {
350
- return error.statusCode >= 500 || error.statusCode === 429;
351
- }
352
- return false;
353
- }
354
226
  async parseResponse(response) {
355
227
  // Handle empty responses (204 No Content, etc.)
356
228
  // Callers expecting no body should use <void> as the generic type parameter.
@@ -414,69 +286,9 @@ class HttpClient {
414
286
  post(path, body, options) {
415
287
  return this.request(path, { ...options, method: 'POST', body });
416
288
  }
417
- put(path, body, options) {
418
- return this.request(path, { ...options, method: 'PUT', body });
419
- }
420
- patch(path, body, options) {
421
- return this.request(path, { ...options, method: 'PATCH', body });
422
- }
423
289
  delete(path, options) {
424
290
  return this.request(path, { ...options, method: 'DELETE' });
425
291
  }
426
- /**
427
- * Request raw binary data (e.g., file downloads).
428
- * Returns a Blob instead of parsed JSON.
429
- */
430
- async requestRaw(path, options = {}) {
431
- const { retry } = options;
432
- // Per CLAUDE.md §7: Wrap with retry logic if enabled
433
- if (retry) {
434
- const retryOptions = typeof retry === 'object' ? retry : {};
435
- return withRetry(() => this.executeRequestRaw(path, options), {
436
- ...retryOptions,
437
- isRetryable: (error) => this.isRetryableError(error),
438
- });
439
- }
440
- return this.executeRequestRaw(path, options);
441
- }
442
- /**
443
- * Execute the actual raw HTTP request (internal implementation)
444
- */
445
- async executeRequestRaw(path, options) {
446
- const { method = 'GET', headers = {}, body, timeout = this.config.timeout, } = options;
447
- const url = `${this.config.apiBaseUrl}${path}`;
448
- const requestHeaders = await this.getDefaultHeaders(headers, body !== undefined);
449
- const controller = new AbortController();
450
- const timeoutId = setTimeout(() => controller.abort(), timeout);
451
- try {
452
- const response = await fetch(url, {
453
- method,
454
- headers: requestHeaders,
455
- body: body ? JSON.stringify(body) : undefined,
456
- signal: controller.signal,
457
- });
458
- clearTimeout(timeoutId);
459
- if (!response.ok) {
460
- // Try to parse error as JSON
461
- const errorData = await response.json().catch(() => ({}));
462
- throw this.createErrorFromResponse(response.status, errorData);
463
- }
464
- return response.blob();
465
- }
466
- catch (error) {
467
- clearTimeout(timeoutId);
468
- if (error instanceof SparkVaultError) {
469
- throw error;
470
- }
471
- if (error instanceof DOMException && error.name === 'AbortError') {
472
- throw new TimeoutError();
473
- }
474
- if (error instanceof TypeError) {
475
- throw new NetworkError('Network request failed. Please check your connection.');
476
- }
477
- throw new SparkVaultError(error instanceof Error ? error.message : 'Unknown error', 'unknown_error');
478
- }
479
- }
480
292
  }
481
293
 
482
294
  class HealthModule {
@@ -553,6 +365,37 @@ class HealthModule {
553
365
  */
554
366
  /** Default request timeout in milliseconds (30 seconds). */
555
367
  const DEFAULT_TIMEOUT_MS = 30000;
368
+ /**
369
+ * Combine a fresh timeout with a session close signal into one AbortSignal.
370
+ *
371
+ * The returned dispose() MUST run in a finally block: it clears the timeout
372
+ * and unlinks the close listener (the fallback path for browsers without
373
+ * AbortSignal.any) so nothing leaks across requests. Callers discriminate
374
+ * close-vs-timeout afterwards by checking the close signal's aborted flag.
375
+ */
376
+ function combineTimeoutAndCloseSignals(timeoutMs, closeSignal) {
377
+ const timeoutController = new AbortController();
378
+ const timeoutId = setTimeout(() => timeoutController.abort(), timeoutMs);
379
+ let signal;
380
+ let onCloseAbort = null;
381
+ if ('any' in AbortSignal) {
382
+ signal = AbortSignal.any([timeoutController.signal, closeSignal]);
383
+ }
384
+ else {
385
+ signal = timeoutController.signal;
386
+ onCloseAbort = () => timeoutController.abort();
387
+ closeSignal.addEventListener('abort', onCloseAbort);
388
+ }
389
+ return {
390
+ signal,
391
+ dispose: () => {
392
+ clearTimeout(timeoutId);
393
+ if (onCloseAbort) {
394
+ closeSignal.removeEventListener('abort', onCloseAbort);
395
+ }
396
+ },
397
+ };
398
+ }
556
399
  class SparkVaultApi {
557
400
  constructor(timeoutMs = DEFAULT_TIMEOUT_MS) {
558
401
  /**
@@ -599,24 +442,7 @@ class SparkVaultApi {
599
442
  if (localCloseController.signal.aborted) {
600
443
  throw this.makeError('Request cancelled', 'cancelled', 0);
601
444
  }
602
- const timeoutController = new AbortController();
603
- const timeoutId = setTimeout(() => timeoutController.abort(), this.timeoutMs);
604
- let combinedSignal;
605
- let onCloseAbort = null;
606
- if ('any' in AbortSignal) {
607
- combinedSignal = AbortSignal.any([
608
- timeoutController.signal,
609
- localCloseController.signal,
610
- ]);
611
- }
612
- else {
613
- // Fallback for browsers without AbortSignal.any: link the close
614
- // signal into the timeout controller manually. Listener is removed
615
- // in the finally block so it doesn't leak across requests.
616
- combinedSignal = timeoutController.signal;
617
- onCloseAbort = () => timeoutController.abort();
618
- localCloseController.signal.addEventListener('abort', onCloseAbort);
619
- }
445
+ const { signal: combinedSignal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, localCloseController.signal);
620
446
  try {
621
447
  // Only send Content-Type when there's actually a body — otherwise GETs
622
448
  // with no payload would carry a misleading content-type header.
@@ -658,10 +484,7 @@ class SparkVaultApi {
658
484
  throw this.makeError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
659
485
  }
660
486
  finally {
661
- clearTimeout(timeoutId);
662
- if (onCloseAbort) {
663
- localCloseController.signal.removeEventListener('abort', onCloseAbort);
664
- }
487
+ dispose();
665
488
  }
666
489
  }
667
490
  }
@@ -868,9 +691,7 @@ function base64urlToArrayBuffer(base64url) {
868
691
  * @returns Decoded UTF-8 string
869
692
  */
870
693
  function base64urlToString(base64url) {
871
- const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
872
- const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
873
- return atob(padded);
694
+ return new TextDecoder().decode(base64urlDecode(base64url));
874
695
  }
875
696
 
876
697
  /**
@@ -1347,8 +1168,7 @@ function enrichMethods(ids) {
1347
1168
  /**
1348
1169
  * Verification State Manager
1349
1170
  *
1350
- * Single source of truth for all verification flow state.
1351
- * Centralizes scattered state from IdentityRenderer for:
1171
+ * Single source of truth for all verification flow state:
1352
1172
  * - Predictable state transitions
1353
1173
  * - Easier debugging and testing
1354
1174
  * - Clear data ownership
@@ -1378,25 +1198,6 @@ class VerificationState {
1378
1198
  kindling: '',
1379
1199
  method: null,
1380
1200
  };
1381
- // State change listeners for reactivity
1382
- this.listeners = new Set();
1383
- }
1384
- /**
1385
- * Subscribe to state changes
1386
- * @param listener - Callback invoked on state change
1387
- * @returns Unsubscribe function
1388
- */
1389
- subscribe(listener) {
1390
- this.listeners.add(listener);
1391
- return () => this.listeners.delete(listener);
1392
- }
1393
- /**
1394
- * Notify all listeners of state change
1395
- */
1396
- notify() {
1397
- for (const listener of this.listeners) {
1398
- listener(this._viewState);
1399
- }
1400
1201
  }
1401
1202
  // --- SDK Config ---
1402
1203
  get sdkConfig() {
@@ -1408,24 +1209,6 @@ class VerificationState {
1408
1209
  get accountId() {
1409
1210
  return this._sdkConfig?.accountId ?? '';
1410
1211
  }
1411
- /**
1412
- * Get enriched methods filtered by the fallback identifier type.
1413
- */
1414
- getAvailableMethods() {
1415
- if (!this._sdkConfig)
1416
- return [];
1417
- const methodIds = this._sdkConfig.methods ?? [];
1418
- let methods = enrichMethods(methodIds);
1419
- // Filter by identifier type. Passkeys are SVID-scoped and remain
1420
- // available regardless of whether the fallback identifier is email or phone.
1421
- if (this._identityType === 'phone') {
1422
- methods = methods.filter((m) => m.type === 'passkey' || m.identityType === 'phone');
1423
- }
1424
- else {
1425
- methods = methods.filter((m) => m.identityType === 'email' || m.identityType === undefined);
1426
- }
1427
- return methods;
1428
- }
1429
1212
  /**
1430
1213
  * Check if passkey method is enabled in config
1431
1214
  */
@@ -1438,7 +1221,6 @@ class VerificationState {
1438
1221
  }
1439
1222
  setViewState(state) {
1440
1223
  this._viewState = state;
1441
- this.notify();
1442
1224
  }
1443
1225
  // --- Identity ---
1444
1226
  get recipient() {
@@ -1514,21 +1296,6 @@ class VerificationState {
1514
1296
  setTotpMethod(method) {
1515
1297
  this._totp.method = method;
1516
1298
  }
1517
- // --- Reset ---
1518
- /**
1519
- * Reset state for new verification attempt
1520
- */
1521
- reset() {
1522
- this._viewState = { view: 'loading' };
1523
- this._recipient = '';
1524
- this._identityType = 'email';
1525
- this._authContext = undefined;
1526
- this._passkey.hasPasskey = null;
1527
- this._passkey.isFallbackMode = false;
1528
- this._passkey.pendingResult = null;
1529
- this._totp.kindling = '';
1530
- this._totp.method = null;
1531
- }
1532
1299
  }
1533
1300
 
1534
1301
  /**
@@ -7085,6 +6852,26 @@ class WidgetEmbedder {
7085
6852
  this.close();
7086
6853
  window.location.href = url.toString();
7087
6854
  }
6855
+ /**
6856
+ * Navigate the host top window to a widget-supplied URL — only when it
6857
+ * resolves to http(s). The sender is already constrained to the trusted
6858
+ * widget origin, but defense-in-depth across the SparkVault->customer
6859
+ * boundary: compromised widget-origin code must never escalate into script
6860
+ * execution on the embedding page via a javascript:/data: navigation.
6861
+ */
6862
+ safeNavigate(url) {
6863
+ let resolved;
6864
+ try {
6865
+ resolved = new URL(url, window.location.href);
6866
+ }
6867
+ catch {
6868
+ return;
6869
+ }
6870
+ if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') {
6871
+ return;
6872
+ }
6873
+ window.location.href = resolved.href;
6874
+ }
7088
6875
  buildUrl() {
7089
6876
  const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/widget`);
7090
6877
  url.searchParams.set('origin', window.location.origin);
@@ -7135,7 +6922,7 @@ class WidgetEmbedder {
7135
6922
  // iframe; on return the host SDK consumes the redirect token.
7136
6923
  if (data.type === REDIRECT_TYPE && typeof data.url === 'string') {
7137
6924
  this.clearReadyTimer();
7138
- window.location.href = data.url;
6925
+ this.safeNavigate(data.url);
7139
6926
  return;
7140
6927
  }
7141
6928
  if (data.type !== RESULT_TYPE || this.settled)
@@ -7148,7 +6935,7 @@ class WidgetEmbedder {
7148
6935
  // Mirror the renderer's belt-and-suspenders: complete a server-issued
7149
6936
  // redirect from the host's own top window if the customer didn't.
7150
6937
  if (typeof result.redirect === 'string' && result.redirect) {
7151
- window.location.href = result.redirect;
6938
+ this.safeNavigate(result.redirect);
7152
6939
  }
7153
6940
  }
7154
6941
  else if (data.cancelled) {
@@ -7351,6 +7138,7 @@ class InlineContainer {
7351
7138
  }
7352
7139
  }
7353
7140
 
7141
+ /* global Element */
7354
7142
  /**
7355
7143
  * DOM Utilities
7356
7144
  *
@@ -7399,8 +7187,62 @@ function onBodyReady(callback) {
7399
7187
  }
7400
7188
  }
7401
7189
  }
7190
+ /**
7191
+ * Attach a click handler to every element matching `selector` — both elements
7192
+ * present once the DOM is ready and elements added later (observed via
7193
+ * MutationObserver).
7194
+ *
7195
+ * Each call is fully self-contained: the element bookkeeping lives in this
7196
+ * closure, so the returned cleanup removes only the listeners this call
7197
+ * registered. Multiple attachments — different selectors, or even the same
7198
+ * element attached twice — never interfere with one another.
7199
+ *
7200
+ * @param selector - CSS selector for elements to attach to
7201
+ * @param onClick - Click handler to register on every matching element
7202
+ * @returns Cleanup function that removes this call's listeners and observer
7203
+ */
7204
+ function attachClickHandler(selector, onClick) {
7205
+ let observer = null;
7206
+ let cleanedUp = false;
7207
+ const attached = new Map();
7208
+ const listen = (element) => {
7209
+ if (attached.has(element))
7210
+ return;
7211
+ element.addEventListener('click', onClick);
7212
+ attached.set(element, () => element.removeEventListener('click', onClick));
7213
+ };
7214
+ // Defer attachment until the DOM is ready so the selector can match.
7215
+ onDomReady(() => {
7216
+ // Cleanup can run before the DOM is ready; attaching afterwards would
7217
+ // register listeners that nothing could ever remove.
7218
+ if (cleanedUp)
7219
+ return;
7220
+ document.querySelectorAll(selector).forEach(listen);
7221
+ // Watch for dynamically added elements
7222
+ observer = new MutationObserver((mutations) => {
7223
+ mutations.forEach((mutation) => {
7224
+ mutation.addedNodes.forEach((node) => {
7225
+ if (node instanceof Element) {
7226
+ if (node.matches(selector))
7227
+ listen(node);
7228
+ node.querySelectorAll(selector).forEach(listen);
7229
+ }
7230
+ });
7231
+ });
7232
+ });
7233
+ // Use onBodyReady to handle edge cases where body isn't available yet
7234
+ onBodyReady(() => {
7235
+ observer?.observe(document.body, { childList: true, subtree: true });
7236
+ });
7237
+ });
7238
+ return () => {
7239
+ cleanedUp = true;
7240
+ observer?.disconnect();
7241
+ attached.forEach((removeListener) => removeListener());
7242
+ attached.clear();
7243
+ };
7244
+ }
7402
7245
 
7403
- /* global Element */
7404
7246
  /**
7405
7247
  * Identity Module
7406
7248
  *
@@ -7435,7 +7277,6 @@ class IdentityModule {
7435
7277
  constructor(config) {
7436
7278
  this.renderer = null;
7437
7279
  this.embedder = null;
7438
- this.attachedElements = new Map();
7439
7280
  this.config = config;
7440
7281
  this.api = new IdentityApi(config);
7441
7282
  // Preload config in background for instant dialog opening
@@ -7562,7 +7403,6 @@ class IdentityModule {
7562
7403
  * cleanup();
7563
7404
  */
7564
7405
  attach(selector, options = {}) {
7565
- let observer = null;
7566
7406
  const handleClick = async (event) => {
7567
7407
  event.preventDefault();
7568
7408
  try {
@@ -7579,48 +7419,10 @@ class IdentityModule {
7579
7419
  // Error already handled by callbacks or will use server redirect
7580
7420
  }
7581
7421
  };
7582
- const attachToElements = () => {
7583
- const elements = document.querySelectorAll(selector);
7584
- elements.forEach((element) => {
7585
- element.addEventListener('click', handleClick);
7586
- this.attachedElements.set(element, () => {
7587
- element.removeEventListener('click', handleClick);
7588
- });
7589
- });
7590
- // Watch for dynamically added elements
7591
- observer = new MutationObserver((mutations) => {
7592
- mutations.forEach((mutation) => {
7593
- mutation.addedNodes.forEach((node) => {
7594
- if (node instanceof Element) {
7595
- if (node.matches(selector)) {
7596
- node.addEventListener('click', handleClick);
7597
- this.attachedElements.set(node, () => {
7598
- node.removeEventListener('click', handleClick);
7599
- });
7600
- }
7601
- // Check descendants
7602
- node.querySelectorAll(selector).forEach((el) => {
7603
- if (!this.attachedElements.has(el)) {
7604
- el.addEventListener('click', handleClick);
7605
- this.attachedElements.set(el, () => {
7606
- el.removeEventListener('click', handleClick);
7607
- });
7608
- }
7609
- });
7610
- }
7611
- });
7612
- });
7613
- });
7614
- // Observe document.body for dynamic elements
7615
- // Use onBodyReady to handle edge cases where body isn't available yet
7616
- onBodyReady(() => {
7617
- observer?.observe(document.body, { childList: true, subtree: true });
7618
- });
7619
- };
7620
- // Defer attachment until DOM is ready, then complete any full-page
7621
- // social-login redirect result before the user has to click again.
7422
+ const cleanup = attachClickHandler(selector, handleClick);
7423
+ // Once the DOM is ready (after the click listeners attach), complete any
7424
+ // full-page social-login redirect result before the user has to click again.
7622
7425
  onDomReady(() => {
7623
- attachToElements();
7624
7426
  this.consumeRedirectResult()
7625
7427
  .then((result) => {
7626
7428
  if (result)
@@ -7630,12 +7432,7 @@ class IdentityModule {
7630
7432
  options.onError?.(error instanceof Error ? error : new Error(String(error)));
7631
7433
  });
7632
7434
  });
7633
- // Return cleanup function
7634
- return () => {
7635
- observer?.disconnect();
7636
- this.attachedElements.forEach((cleanup) => cleanup());
7637
- this.attachedElements.clear();
7638
- };
7435
+ return cleanup;
7639
7436
  }
7640
7437
  /**
7641
7438
  * Verify and decode an identity token.
@@ -7682,29 +7479,56 @@ class IdentityModule {
7682
7479
  if (!token) {
7683
7480
  return null;
7684
7481
  }
7685
- const expectedState = sessionStorage.getItem('sv_oauth_state');
7686
- if (expectedState && params.get('state') !== expectedState) {
7687
- throw new ValidationError('Invalid OAuth state');
7688
- }
7689
- const claims = await this.verifyToken(token);
7690
- const result = {
7691
- token,
7692
- identity: claims.identity,
7693
- identityType: claims.identity_type,
7694
- svid: claims.svid,
7695
- sessionId: claims.session_id,
7696
- };
7697
- if (typeof window.history?.replaceState === 'function') {
7698
- window.history.replaceState(window.history.state, document.title, `${window.location.pathname}${window.location.search}`);
7482
+ // Once a token is present it must be consumed exactly once: the hash and
7483
+ // one-shot OAuth state are cleared whether validation succeeds or fails.
7484
+ // A failing token left in the URL would make every subsequent verify()
7485
+ // re-consume and re-reject it before the dialog could ever open — login
7486
+ // would stay wedged until the user manually edited the URL.
7487
+ try {
7488
+ let expectedState = null;
7489
+ try {
7490
+ expectedState = sessionStorage.getItem('sv_oauth_state');
7491
+ }
7492
+ catch {
7493
+ // Storage disabled (private mode): proceed; the backend still binds state.
7494
+ }
7495
+ if (expectedState && params.get('state') !== expectedState) {
7496
+ throw new ValidationError('Invalid OAuth state');
7497
+ }
7498
+ const claims = await this.verifyToken(token);
7499
+ return {
7500
+ token,
7501
+ identity: claims.identity,
7502
+ identityType: claims.identity_type,
7503
+ svid: claims.svid,
7504
+ sessionId: claims.session_id,
7505
+ };
7506
+ }
7507
+ finally {
7508
+ if (typeof window.history?.replaceState === 'function') {
7509
+ window.history.replaceState(window.history.state, document.title, `${window.location.pathname}${window.location.search}`);
7510
+ }
7511
+ try {
7512
+ sessionStorage.removeItem('sv_oauth_state');
7513
+ sessionStorage.removeItem('sv_oauth_email');
7514
+ }
7515
+ catch {
7516
+ // Storage disabled (private mode): nothing to clear.
7517
+ }
7699
7518
  }
7700
- sessionStorage.removeItem('sv_oauth_state');
7701
- sessionStorage.removeItem('sv_oauth_email');
7702
- return result;
7703
7519
  }
7704
7520
  /**
7705
7521
  * Close the identity dialog/inline UI if open.
7522
+ *
7523
+ * Tears down whichever surface is active: the hosted-widget iframe
7524
+ * (default dialog mode — also releases the embedder's host scroll lock)
7525
+ * or the local renderer (inline / local mode).
7706
7526
  */
7707
7527
  close() {
7528
+ if (this.embedder) {
7529
+ this.embedder.close();
7530
+ this.embedder = null;
7531
+ }
7708
7532
  if (this.renderer) {
7709
7533
  this.renderer.close();
7710
7534
  this.renderer = null;
@@ -7817,6 +7641,15 @@ function isInitiateUploadResponse(data) {
7817
7641
  }
7818
7642
  /** tus protocol version used for the resumable upload session. */
7819
7643
  const TUS_VERSION = '1.0.0';
7644
+ /** Default TUS chunk size; the server may override via `X-Chunk-Size`. */
7645
+ const DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024;
7646
+ /**
7647
+ * Abort a stalled chunk PATCH after this long with no upload progress.
7648
+ * XHR's own `timeout` measures total request duration, which would abort a
7649
+ * slow-but-progressing 50MB chunk — so a chunk fails only after the
7650
+ * connection has been completely silent for the full window.
7651
+ */
7652
+ const CHUNK_INACTIVITY_TIMEOUT_MS = 60000;
7820
7653
  /**
7821
7654
  * Server-side finalization confirmation poll.
7822
7655
  *
@@ -7899,6 +7732,167 @@ class UploadApi extends SparkVaultApi {
7899
7732
  ingotId: response.data.ingot_id,
7900
7733
  };
7901
7734
  }
7735
+ /**
7736
+ * Upload a file to Forge over the TUS resumable protocol (v1.0.0).
7737
+ *
7738
+ * The single canonical browser transfer path — the upload widget and the
7739
+ * authenticated `uploadIngot` flow both go through here (CLAUDE.md: one
7740
+ * transfer path). Creates the session, PATCHes chunks sized by the server's
7741
+ * `X-Chunk-Size` (50MB default, which keeps every request under CDN body
7742
+ * caps such as Cloudflare's 100MB), validates every server-reported offset,
7743
+ * and honors the session abort signal plus per-request timeouts.
7744
+ *
7745
+ * Returns the TUS session URL so the caller can confirm server-side
7746
+ * finalization via {@link verifyUploadFinalized} before reporting success.
7747
+ */
7748
+ async uploadFileToForge(file, forgeUrl, onProgress) {
7749
+ if (typeof XMLHttpRequest === 'undefined') {
7750
+ throw new UploadApiError('XMLHttpRequest is required for browser uploads', 'environment_unsupported', 0);
7751
+ }
7752
+ const url = new URL(forgeUrl);
7753
+ const istk = url.searchParams.get('istk');
7754
+ if (!istk) {
7755
+ throw new UploadApiError('Forge upload URL is missing ISTK', 'invalid_forge_url', 0);
7756
+ }
7757
+ const session = await this.createTusSession(`${url.origin}${url.pathname}`, istk, file.size);
7758
+ const uploadUrl = session.location.startsWith('http')
7759
+ ? session.location
7760
+ : `${url.origin}${session.location}`;
7761
+ let offset = 0;
7762
+ while (offset < file.size) {
7763
+ if (this.isAborted()) {
7764
+ throw new UploadApiError('Upload cancelled', 'cancelled', 0);
7765
+ }
7766
+ const chunkEnd = Math.min(offset + session.chunkSize, file.size);
7767
+ offset = await this.patchChunk(uploadUrl, file.slice(offset, chunkEnd), offset, file.size, onProgress);
7768
+ }
7769
+ return uploadUrl;
7770
+ }
7771
+ /**
7772
+ * Create the TUS upload session. Forge reads only `Tus-Resumable`,
7773
+ * `Upload-Length`, and `X-ISTK` on create, and returns the session URL in
7774
+ * `Location` (possibly relative) plus its chunk size in `X-Chunk-Size`.
7775
+ */
7776
+ async createTusSession(endpoint, istk, totalSize) {
7777
+ const closeSignal = this.getAbortSignal();
7778
+ const { signal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, closeSignal);
7779
+ try {
7780
+ const response = await fetch(endpoint, {
7781
+ method: 'POST',
7782
+ headers: {
7783
+ 'Tus-Resumable': TUS_VERSION,
7784
+ 'Upload-Length': String(totalSize),
7785
+ 'X-ISTK': istk,
7786
+ },
7787
+ signal,
7788
+ });
7789
+ if (!response.ok) {
7790
+ const errorText = await response.text().catch(() => '');
7791
+ throw new UploadApiError(`Failed to create upload session: ${response.status} ${errorText}`, 'tus_create_failed', response.status);
7792
+ }
7793
+ const location = response.headers.get('Location');
7794
+ if (!location) {
7795
+ throw new UploadApiError('Server did not return upload location', 'tus_create_failed', response.status);
7796
+ }
7797
+ const chunkSizeHeader = response.headers.get('X-Chunk-Size');
7798
+ const chunkSize = chunkSizeHeader ? parseInt(chunkSizeHeader, 10) : NaN;
7799
+ return {
7800
+ location,
7801
+ chunkSize: Number.isFinite(chunkSize) && chunkSize > 0 ? chunkSize : DEFAULT_CHUNK_SIZE,
7802
+ };
7803
+ }
7804
+ catch (error) {
7805
+ if (error instanceof SparkVaultError)
7806
+ throw error;
7807
+ if (error != null && typeof error === 'object' && 'name' in error && error.name === 'AbortError') {
7808
+ if (this.isAborted()) {
7809
+ throw new UploadApiError('Upload cancelled', 'cancelled', 0);
7810
+ }
7811
+ throw new UploadApiError(`Upload session creation timed out after ${this.timeoutMs}ms`, 'timeout', 0);
7812
+ }
7813
+ if (error instanceof TypeError) {
7814
+ throw new UploadApiError('Unable to connect. Please check your connection and try again.', 'network_error', 0);
7815
+ }
7816
+ throw new UploadApiError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
7817
+ }
7818
+ finally {
7819
+ dispose();
7820
+ }
7821
+ }
7822
+ /**
7823
+ * PATCH one chunk with XMLHttpRequest (fetch exposes no upload progress).
7824
+ * Resolves with the server-confirmed offset for the next iteration.
7825
+ *
7826
+ * The server's `Upload-Offset` is validated, never trusted: it must be a
7827
+ * finite number that strictly advances past this chunk's start (this client
7828
+ * never sends an empty chunk, so a non-advancing 2xx would loop forever)
7829
+ * and never exceeds the file size (an inflated offset would skip real
7830
+ * chunks and report a partial upload as success).
7831
+ */
7832
+ patchChunk(uploadUrl, chunk, chunkStart, totalSize, onProgress) {
7833
+ return new Promise((resolve, reject) => {
7834
+ const closeSignal = this.getAbortSignal();
7835
+ if (closeSignal.aborted) {
7836
+ reject(new UploadApiError('Upload cancelled', 'cancelled', 0));
7837
+ return;
7838
+ }
7839
+ const xhr = new XMLHttpRequest();
7840
+ let settled = false;
7841
+ let timedOut = false;
7842
+ let watchdog = null;
7843
+ const onCloseAbort = () => xhr.abort();
7844
+ const finish = (settle) => {
7845
+ if (settled)
7846
+ return;
7847
+ settled = true;
7848
+ if (watchdog !== null)
7849
+ clearTimeout(watchdog);
7850
+ closeSignal.removeEventListener('abort', onCloseAbort);
7851
+ settle();
7852
+ };
7853
+ const resetWatchdog = () => {
7854
+ if (settled)
7855
+ return;
7856
+ if (watchdog !== null)
7857
+ clearTimeout(watchdog);
7858
+ watchdog = setTimeout(() => {
7859
+ timedOut = true;
7860
+ xhr.abort();
7861
+ }, CHUNK_INACTIVITY_TIMEOUT_MS);
7862
+ };
7863
+ closeSignal.addEventListener('abort', onCloseAbort);
7864
+ xhr.upload.onprogress = (event) => {
7865
+ resetWatchdog();
7866
+ if (event.lengthComputable) {
7867
+ onProgress?.(chunkStart + event.loaded, totalSize);
7868
+ }
7869
+ };
7870
+ xhr.onload = () => {
7871
+ if (xhr.status >= 200 && xhr.status < 300) {
7872
+ const header = xhr.getResponseHeader('Upload-Offset');
7873
+ const newOffset = header !== null ? parseInt(header, 10) : NaN;
7874
+ if (!Number.isFinite(newOffset) || newOffset <= chunkStart || newOffset > totalSize) {
7875
+ finish(() => reject(new UploadApiError(`Server returned invalid upload offset (${newOffset})`, 'invalid_offset', xhr.status)));
7876
+ return;
7877
+ }
7878
+ finish(() => resolve(newOffset));
7879
+ }
7880
+ else {
7881
+ finish(() => reject(new UploadApiError(`Chunk upload failed with status ${xhr.status}`, 'chunk_upload_failed', xhr.status)));
7882
+ }
7883
+ };
7884
+ xhr.onerror = () => finish(() => reject(new UploadApiError('Chunk upload failed', 'network_error', 0)));
7885
+ xhr.onabort = () => finish(() => reject(timedOut
7886
+ ? new UploadApiError(`Chunk upload timed out after ${CHUNK_INACTIVITY_TIMEOUT_MS}ms of inactivity`, 'timeout', 0)
7887
+ : new UploadApiError('Upload cancelled', 'cancelled', 0)));
7888
+ xhr.open('PATCH', uploadUrl);
7889
+ xhr.setRequestHeader('Tus-Resumable', TUS_VERSION);
7890
+ xhr.setRequestHeader('Upload-Offset', String(chunkStart));
7891
+ xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream');
7892
+ resetWatchdog();
7893
+ xhr.send(chunk);
7894
+ });
7895
+ }
7902
7896
  /**
7903
7897
  * Confirm the upload was finalized SERVER-SIDE before reporting success.
7904
7898
  *
@@ -7945,21 +7939,7 @@ class UploadApi extends SparkVaultApi {
7945
7939
  */
7946
7940
  async headUploadOffset(uploadUrl) {
7947
7941
  const closeSignal = this.getAbortSignal();
7948
- const timeoutController = new AbortController();
7949
- const timeoutId = setTimeout(() => timeoutController.abort(), this.timeoutMs);
7950
- // Combine timeout + session-close into one signal. Mirror the base
7951
- // client's fallback for browsers without AbortSignal.any: link the close
7952
- // signal into the timeout controller and remove the listener in finally.
7953
- let combinedSignal;
7954
- let onCloseAbort = null;
7955
- if ('any' in AbortSignal) {
7956
- combinedSignal = AbortSignal.any([timeoutController.signal, closeSignal]);
7957
- }
7958
- else {
7959
- combinedSignal = timeoutController.signal;
7960
- onCloseAbort = () => timeoutController.abort();
7961
- closeSignal.addEventListener('abort', onCloseAbort);
7962
- }
7942
+ const { signal: combinedSignal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, closeSignal);
7963
7943
  try {
7964
7944
  const response = await fetch(uploadUrl, {
7965
7945
  method: 'HEAD',
@@ -7991,14 +7971,175 @@ class UploadApi extends SparkVaultApi {
7991
7971
  throw new UploadApiError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
7992
7972
  }
7993
7973
  finally {
7994
- clearTimeout(timeoutId);
7995
- if (onCloseAbort) {
7996
- closeSignal.removeEventListener('abort', onCloseAbort);
7997
- }
7974
+ dispose();
7998
7975
  }
7999
7976
  }
8000
7977
  }
8001
7978
 
7979
+ /**
7980
+ * Upload Widget Chrome
7981
+ *
7982
+ * Shared DOM builders for the branded chrome both upload containers render:
7983
+ * brand header, "Secured by SparkVault" footer, and the Triple Zero-Trust
7984
+ * security sidebar. One canonical copy — any branding/marketing/security-text
7985
+ * change lands here and reaches modal and inline modes alike.
7986
+ */
7987
+ /**
7988
+ * Build the branded header. Returns the close button (when rendered) so the
7989
+ * container can detach `onClose` in its destroy() cleanup.
7990
+ */
7991
+ function createBrandHeader(options) {
7992
+ const { branding, isDarkMode, withCloseButton, titleId, onClose } = options;
7993
+ const header = document.createElement('div');
7994
+ header.className = 'svu-header';
7995
+ const titleContainer = document.createElement('div');
7996
+ titleContainer.className = 'svu-header-title';
7997
+ // Use light logo for light theme (default), dark logo for dark mode
7998
+ const logoUrl = isDarkMode
7999
+ ? branding.logoDarkUrl || branding.logoLightUrl
8000
+ : branding.logoLightUrl || branding.logoDarkUrl;
8001
+ if (logoUrl) {
8002
+ const logo = document.createElement('img');
8003
+ logo.className = 'svu-logo';
8004
+ logo.src = logoUrl;
8005
+ logo.alt = branding.organizationName;
8006
+ titleContainer.appendChild(logo);
8007
+ // Screen reader title
8008
+ const srTitle = document.createElement('span');
8009
+ srTitle.className = 'svu-sr-only';
8010
+ if (titleId)
8011
+ srTitle.id = titleId;
8012
+ srTitle.textContent = branding.organizationName;
8013
+ titleContainer.appendChild(srTitle);
8014
+ }
8015
+ else if (branding.organizationName) {
8016
+ const companyName = document.createElement('h2');
8017
+ companyName.className = 'svu-company-name';
8018
+ if (titleId)
8019
+ companyName.id = titleId;
8020
+ companyName.textContent = branding.organizationName;
8021
+ titleContainer.appendChild(companyName);
8022
+ }
8023
+ header.appendChild(titleContainer);
8024
+ let closeBtn = null;
8025
+ if (withCloseButton) {
8026
+ closeBtn = document.createElement('button');
8027
+ closeBtn.className = 'svu-close-btn';
8028
+ closeBtn.setAttribute('aria-label', 'Close');
8029
+ closeBtn.innerHTML = `
8030
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8031
+ <path d="M18 6L6 18M6 6l12 12"/>
8032
+ </svg>
8033
+ `;
8034
+ closeBtn.addEventListener('click', onClose);
8035
+ header.appendChild(closeBtn);
8036
+ }
8037
+ return { header, closeBtn };
8038
+ }
8039
+ /** Build the "Secured by SparkVault" footer. */
8040
+ function createFooter() {
8041
+ const footer = document.createElement('div');
8042
+ footer.className = 'svu-footer';
8043
+ const footerText = document.createElement('span');
8044
+ footerText.className = 'svu-footer-text';
8045
+ footerText.appendChild(document.createTextNode('Secured by '));
8046
+ const footerLink = document.createElement('a');
8047
+ footerLink.href = 'https://sparkvault.com';
8048
+ footerLink.target = '_blank';
8049
+ footerLink.rel = 'noopener noreferrer';
8050
+ footerLink.className = 'svu-footer-link';
8051
+ footerLink.textContent = 'SparkVault';
8052
+ footerText.appendChild(footerLink);
8053
+ footer.appendChild(footerText);
8054
+ return footer;
8055
+ }
8056
+ /** Build the Triple Zero-Trust security sidebar shown during dark states. */
8057
+ function createSecuritySidebar(branding) {
8058
+ const sidebar = document.createElement('div');
8059
+ sidebar.className = 'svu-sidebar';
8060
+ // Logo
8061
+ const logoDiv = document.createElement('div');
8062
+ logoDiv.className = 'svu-sidebar-logo';
8063
+ if (branding.logoDarkUrl) {
8064
+ const logo = document.createElement('img');
8065
+ logo.src = branding.logoDarkUrl;
8066
+ logo.alt = branding.organizationName;
8067
+ logoDiv.appendChild(logo);
8068
+ }
8069
+ sidebar.appendChild(logoDiv);
8070
+ // Intro
8071
+ const intro = document.createElement('div');
8072
+ intro.className = 'svu-sidebar-intro';
8073
+ intro.innerHTML = `
8074
+ <h3>Secure File Transfer</h3>
8075
+ <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>
8076
+ `;
8077
+ sidebar.appendChild(intro);
8078
+ // Security details
8079
+ const security = document.createElement('div');
8080
+ security.className = 'svu-sidebar-security';
8081
+ security.innerHTML = `
8082
+ <h4>
8083
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8084
+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
8085
+ </svg>
8086
+ SparkVault's Triple Zero-Trust
8087
+ </h4>
8088
+ <p class="svu-security-intro">
8089
+ Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.
8090
+ </p>
8091
+ <div class="svu-key-chain">
8092
+ <div class="svu-key-item">
8093
+ <div class="svu-key-number">1</div>
8094
+ <div class="svu-key-info">
8095
+ <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>
8096
+ <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>
8097
+ <span class="svu-key-desc">Quantum-resistant key exchange</span>
8098
+ </div>
8099
+ </div>
8100
+ <div class="svu-key-connector">
8101
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8102
+ <path d="M12 5v14M5 12h14"/>
8103
+ </svg>
8104
+ </div>
8105
+ <div class="svu-key-item">
8106
+ <div class="svu-key-number">2</div>
8107
+ <div class="svu-key-info">
8108
+ <span class="svu-key-name">X25519 Ephemeral Key</span>
8109
+ <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>
8110
+ <span class="svu-key-desc">Perfect forward secrecy</span>
8111
+ </div>
8112
+ </div>
8113
+ <div class="svu-key-connector">
8114
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8115
+ <path d="M12 5v14M5 12h14"/>
8116
+ </svg>
8117
+ </div>
8118
+ <div class="svu-key-item">
8119
+ <div class="svu-key-number">3</div>
8120
+ <div class="svu-key-info">
8121
+ <span class="svu-key-name">HKDF-SHA512 Derived Key</span>
8122
+ <span class="svu-key-algo">Hardware-bound key derivation</span>
8123
+ <span class="svu-key-desc">Vault master key in secure enclave</span>
8124
+ </div>
8125
+ </div>
8126
+ </div>
8127
+ <div class="svu-encryption-result">
8128
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8129
+ <path d="M20 6L9 17l-5-5"/>
8130
+ </svg>
8131
+ <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>
8132
+ </div>
8133
+ <div class="svu-security-badges">
8134
+ <span class="svu-tls-badge">TLS 1.3 In Transit</span>
8135
+ <span class="svu-tls-badge">Encrypted At Rest</span>
8136
+ <span class="svu-tls-badge">Zero Trust</span>
8137
+ </div>
8138
+ `;
8139
+ sidebar.appendChild(security);
8140
+ return sidebar;
8141
+ }
8142
+
8002
8143
  /**
8003
8144
  * Upload Widget Styles
8004
8145
  *
@@ -8008,19 +8149,19 @@ class UploadApi extends SparkVaultApi {
8008
8149
  const STYLE_ID = 'sparkvault-upload-styles';
8009
8150
  /**
8010
8151
  * Inject upload widget styles into the document head.
8152
+ * Idempotent: the stylesheet is static and shared by every widget instance —
8153
+ * per-instance behavior (backdrop blur, dark mode) is driven by class toggles.
8011
8154
  */
8012
- function injectUploadStyles(options) {
8155
+ function injectUploadStyles() {
8013
8156
  if (document.getElementById(STYLE_ID)) {
8014
8157
  return;
8015
8158
  }
8016
8159
  const style = document.createElement('style');
8017
8160
  style.id = STYLE_ID;
8018
- style.textContent = getUploadStyles(options);
8161
+ style.textContent = getUploadStyles();
8019
8162
  document.head.appendChild(style);
8020
8163
  }
8021
- function getUploadStyles(options) {
8022
- const { backdropBlur } = options;
8023
- const enableBlur = backdropBlur !== false;
8164
+ function getUploadStyles() {
8024
8165
  // Design tokens - light theme for upload widget
8025
8166
  const tokens = {
8026
8167
  // Colors
@@ -8087,8 +8228,8 @@ function getUploadStyles(options) {
8087
8228
  }
8088
8229
 
8089
8230
  .svu-overlay.svu-blur {
8090
- backdrop-filter: blur(${enableBlur ? '8px' : '0'});
8091
- -webkit-backdrop-filter: blur(${enableBlur ? '8px' : '0'});
8231
+ backdrop-filter: blur(8px);
8232
+ -webkit-backdrop-filter: blur(8px);
8092
8233
  }
8093
8234
 
8094
8235
  .svu-modal {
@@ -9116,6 +9257,8 @@ function getUploadStyles(options) {
9116
9257
  */
9117
9258
  const OVERLAY_ID = 'sparkvault-upload-overlay';
9118
9259
  const MODAL_ID = 'sparkvault-upload-modal';
9260
+ /** Title node id referenced by the overlay's aria-labelledby. */
9261
+ const MODAL_TITLE_ID = 'svu-modal-title';
9119
9262
  /**
9120
9263
  * Default branding used for immediate modal display before config loads.
9121
9264
  */
@@ -9156,17 +9299,14 @@ class UploadModalContainer {
9156
9299
  this.onCloseCallback = onClose;
9157
9300
  this.backdropBlur = options.backdropBlur !== false;
9158
9301
  this.branding = options.branding || DEFAULT_BRANDING;
9159
- injectUploadStyles({
9160
- branding: this.branding,
9161
- backdropBlur: this.backdropBlur,
9162
- });
9302
+ injectUploadStyles();
9163
9303
  // Create overlay
9164
9304
  const overlay = document.createElement('div');
9165
9305
  overlay.id = OVERLAY_ID;
9166
9306
  overlay.className = this.backdropBlur ? 'svu-overlay svu-blur' : 'svu-overlay';
9167
9307
  overlay.setAttribute('role', 'dialog');
9168
9308
  overlay.setAttribute('aria-modal', 'true');
9169
- overlay.setAttribute('aria-labelledby', 'svu-modal-title');
9309
+ overlay.setAttribute('aria-labelledby', MODAL_TITLE_ID);
9170
9310
  // Create modal
9171
9311
  const modal = document.createElement('div');
9172
9312
  modal.id = MODAL_ID;
@@ -9181,19 +9321,7 @@ class UploadModalContainer {
9181
9321
  const body = document.createElement('div');
9182
9322
  body.className = 'svu-body';
9183
9323
  // Create footer
9184
- const footer = document.createElement('div');
9185
- footer.className = 'svu-footer';
9186
- const footerText = document.createElement('span');
9187
- footerText.className = 'svu-footer-text';
9188
- footerText.appendChild(document.createTextNode('Secured by '));
9189
- const footerLink = document.createElement('a');
9190
- footerLink.href = 'https://sparkvault.com';
9191
- footerLink.target = '_blank';
9192
- footerLink.rel = 'noopener noreferrer';
9193
- footerLink.className = 'svu-footer-link';
9194
- footerLink.textContent = 'SparkVault';
9195
- footerText.appendChild(footerLink);
9196
- footer.appendChild(footerText);
9324
+ const footer = createFooter();
9197
9325
  main.appendChild(header);
9198
9326
  main.appendChild(body);
9199
9327
  main.appendChild(footer);
@@ -9217,47 +9345,15 @@ class UploadModalContainer {
9217
9345
  this.elements = { overlay, modal, main, header, body, footer, sidebar: null };
9218
9346
  }
9219
9347
  createHeader(branding) {
9220
- const header = document.createElement('div');
9221
- header.className = 'svu-header';
9222
- const titleContainer = document.createElement('div');
9223
- titleContainer.className = 'svu-header-title';
9224
- // Use light logo for light theme (default), dark logo for dark mode
9225
- const logoUrl = this.isDarkMode
9226
- ? branding.logoDarkUrl || branding.logoLightUrl
9227
- : branding.logoLightUrl || branding.logoDarkUrl;
9228
- if (logoUrl) {
9229
- const logo = document.createElement('img');
9230
- logo.className = 'svu-logo';
9231
- logo.src = logoUrl;
9232
- logo.alt = branding.organizationName;
9233
- titleContainer.appendChild(logo);
9234
- // Screen reader title
9235
- const srTitle = document.createElement('span');
9236
- srTitle.className = 'svu-sr-only';
9237
- srTitle.id = 'svu-modal-title';
9238
- srTitle.textContent = branding.organizationName;
9239
- titleContainer.appendChild(srTitle);
9240
- }
9241
- else if (branding.organizationName) {
9242
- const companyName = document.createElement('h2');
9243
- companyName.className = 'svu-company-name';
9244
- companyName.id = 'svu-modal-title';
9245
- companyName.textContent = branding.organizationName;
9246
- titleContainer.appendChild(companyName);
9247
- }
9248
- // Close button
9249
- this.closeBtn = document.createElement('button');
9250
- this.closeBtn.className = 'svu-close-btn';
9251
- this.closeBtn.setAttribute('aria-label', 'Close');
9252
- this.closeBtn.innerHTML = `
9253
- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9254
- <path d="M18 6L6 18M6 6l12 12"/>
9255
- </svg>
9256
- `;
9257
9348
  this.closeBtnClickHandler = () => this.handleClose();
9258
- this.closeBtn.addEventListener('click', this.closeBtnClickHandler);
9259
- header.appendChild(titleContainer);
9260
- header.appendChild(this.closeBtn);
9349
+ const { header, closeBtn } = createBrandHeader({
9350
+ branding,
9351
+ isDarkMode: this.isDarkMode,
9352
+ withCloseButton: true,
9353
+ titleId: MODAL_TITLE_ID,
9354
+ onClose: this.closeBtnClickHandler,
9355
+ });
9356
+ this.closeBtn = closeBtn;
9261
9357
  return header;
9262
9358
  }
9263
9359
  /**
@@ -9319,7 +9415,7 @@ class UploadModalContainer {
9319
9415
  return;
9320
9416
  if (show && !this.elements.sidebar) {
9321
9417
  // Create sidebar
9322
- const sidebar = this.createSecuritySidebar();
9418
+ const sidebar = createSecuritySidebar(this.branding);
9323
9419
  this.elements.modal.classList.add('svu-with-sidebar');
9324
9420
  this.elements.modal.appendChild(sidebar);
9325
9421
  this.elements.sidebar = sidebar;
@@ -9339,91 +9435,6 @@ class UploadModalContainer {
9339
9435
  }
9340
9436
  }
9341
9437
  }
9342
- createSecuritySidebar() {
9343
- const sidebar = document.createElement('div');
9344
- sidebar.className = 'svu-sidebar';
9345
- // Logo
9346
- const logoDiv = document.createElement('div');
9347
- logoDiv.className = 'svu-sidebar-logo';
9348
- if (this.branding.logoDarkUrl) {
9349
- const logo = document.createElement('img');
9350
- logo.src = this.branding.logoDarkUrl;
9351
- logo.alt = this.branding.organizationName;
9352
- logoDiv.appendChild(logo);
9353
- }
9354
- sidebar.appendChild(logoDiv);
9355
- // Intro
9356
- const intro = document.createElement('div');
9357
- intro.className = 'svu-sidebar-intro';
9358
- intro.innerHTML = `
9359
- <h3>Secure File Transfer</h3>
9360
- <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>
9361
- `;
9362
- sidebar.appendChild(intro);
9363
- // Security details
9364
- const security = document.createElement('div');
9365
- security.className = 'svu-sidebar-security';
9366
- security.innerHTML = `
9367
- <h4>
9368
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9369
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
9370
- </svg>
9371
- SparkVault's Triple Zero-Trust
9372
- </h4>
9373
- <p class="svu-security-intro">
9374
- Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.
9375
- </p>
9376
- <div class="svu-key-chain">
9377
- <div class="svu-key-item">
9378
- <div class="svu-key-number">1</div>
9379
- <div class="svu-key-info">
9380
- <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>
9381
- <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>
9382
- <span class="svu-key-desc">Quantum-resistant key exchange</span>
9383
- </div>
9384
- </div>
9385
- <div class="svu-key-connector">
9386
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9387
- <path d="M12 5v14M5 12h14"/>
9388
- </svg>
9389
- </div>
9390
- <div class="svu-key-item">
9391
- <div class="svu-key-number">2</div>
9392
- <div class="svu-key-info">
9393
- <span class="svu-key-name">X25519 Ephemeral Key</span>
9394
- <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>
9395
- <span class="svu-key-desc">Perfect forward secrecy</span>
9396
- </div>
9397
- </div>
9398
- <div class="svu-key-connector">
9399
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9400
- <path d="M12 5v14M5 12h14"/>
9401
- </svg>
9402
- </div>
9403
- <div class="svu-key-item">
9404
- <div class="svu-key-number">3</div>
9405
- <div class="svu-key-info">
9406
- <span class="svu-key-name">HKDF-SHA512 Derived Key</span>
9407
- <span class="svu-key-algo">Hardware-bound key derivation</span>
9408
- <span class="svu-key-desc">Vault master key in secure enclave</span>
9409
- </div>
9410
- </div>
9411
- </div>
9412
- <div class="svu-encryption-result">
9413
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9414
- <path d="M20 6L9 17l-5-5"/>
9415
- </svg>
9416
- <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>
9417
- </div>
9418
- <div class="svu-security-badges">
9419
- <span class="svu-tls-badge">TLS 1.3 In Transit</span>
9420
- <span class="svu-tls-badge">Encrypted At Rest</span>
9421
- <span class="svu-tls-badge">Zero Trust</span>
9422
- </div>
9423
- `;
9424
- sidebar.appendChild(security);
9425
- return sidebar;
9426
- }
9427
9438
  handleClose() {
9428
9439
  if (this.onCloseCallback) {
9429
9440
  this.onCloseCallback();
@@ -9516,10 +9527,7 @@ class UploadInlineContainer {
9516
9527
  }
9517
9528
  this.onCloseCallback = onClose;
9518
9529
  // Inject styles
9519
- injectUploadStyles({
9520
- branding: this.branding,
9521
- backdropBlur: false,
9522
- });
9530
+ injectUploadStyles();
9523
9531
  // Create main container
9524
9532
  this.container = document.createElement('div');
9525
9533
  this.container.className = 'svu-inline-container';
@@ -9534,19 +9542,7 @@ class UploadInlineContainer {
9534
9542
  this.container.appendChild(this.body);
9535
9543
  // Create footer if enabled
9536
9544
  if (this.containerOptions.showFooter) {
9537
- this.footer = document.createElement('div');
9538
- this.footer.className = 'svu-footer';
9539
- const footerText = document.createElement('span');
9540
- footerText.className = 'svu-footer-text';
9541
- footerText.appendChild(document.createTextNode('Secured by '));
9542
- const footerLink = document.createElement('a');
9543
- footerLink.href = 'https://sparkvault.com';
9544
- footerLink.target = '_blank';
9545
- footerLink.rel = 'noopener noreferrer';
9546
- footerLink.className = 'svu-footer-link';
9547
- footerLink.textContent = 'SparkVault';
9548
- footerText.appendChild(footerLink);
9549
- this.footer.appendChild(footerText);
9545
+ this.footer = createFooter();
9550
9546
  this.container.appendChild(this.footer);
9551
9547
  }
9552
9548
  // Clear target and append container
@@ -9604,7 +9600,7 @@ class UploadInlineContainer {
9604
9600
  return;
9605
9601
  if (show && !this.sidebar) {
9606
9602
  // Create sidebar
9607
- this.sidebar = this.createSecuritySidebar();
9603
+ this.sidebar = createSecuritySidebar(this.branding);
9608
9604
  this.container.classList.add('svu-with-sidebar');
9609
9605
  this.container.appendChild(this.sidebar);
9610
9606
  }
@@ -9655,134 +9651,16 @@ class UploadInlineContainer {
9655
9651
  this.onCloseCallback = null;
9656
9652
  }
9657
9653
  createHeader(branding) {
9658
- const header = document.createElement('div');
9659
- header.className = 'svu-header';
9660
- const titleContainer = document.createElement('div');
9661
- titleContainer.className = 'svu-header-title';
9662
- // Use appropriate logo based on dark mode
9663
- const logoUrl = this.isDarkMode
9664
- ? branding.logoDarkUrl || branding.logoLightUrl
9665
- : branding.logoLightUrl || branding.logoDarkUrl;
9666
- if (logoUrl) {
9667
- const logo = document.createElement('img');
9668
- logo.className = 'svu-logo';
9669
- logo.src = logoUrl;
9670
- logo.alt = branding.organizationName;
9671
- titleContainer.appendChild(logo);
9672
- // Screen reader title
9673
- const srTitle = document.createElement('span');
9674
- srTitle.className = 'svu-sr-only';
9675
- srTitle.textContent = branding.organizationName;
9676
- titleContainer.appendChild(srTitle);
9677
- }
9678
- else if (branding.organizationName) {
9679
- const companyName = document.createElement('h2');
9680
- companyName.className = 'svu-company-name';
9681
- companyName.textContent = branding.organizationName;
9682
- titleContainer.appendChild(companyName);
9683
- }
9684
- header.appendChild(titleContainer);
9685
- // Add close button if enabled
9686
- if (this.containerOptions.showCloseButton) {
9687
- this.closeBtn = document.createElement('button');
9688
- this.closeBtn.className = 'svu-close-btn';
9689
- this.closeBtn.setAttribute('aria-label', 'Close');
9690
- this.closeBtn.innerHTML = `
9691
- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9692
- <path d="M18 6L6 18M6 6l12 12"/>
9693
- </svg>
9694
- `;
9695
- this.closeBtnClickHandler = () => this.handleClose();
9696
- this.closeBtn.addEventListener('click', this.closeBtnClickHandler);
9697
- header.appendChild(this.closeBtn);
9698
- }
9654
+ this.closeBtnClickHandler = () => this.handleClose();
9655
+ const { header, closeBtn } = createBrandHeader({
9656
+ branding,
9657
+ isDarkMode: this.isDarkMode,
9658
+ withCloseButton: this.containerOptions.showCloseButton === true,
9659
+ onClose: this.closeBtnClickHandler,
9660
+ });
9661
+ this.closeBtn = closeBtn;
9699
9662
  return header;
9700
9663
  }
9701
- createSecuritySidebar() {
9702
- const sidebar = document.createElement('div');
9703
- sidebar.className = 'svu-sidebar';
9704
- // Logo
9705
- const logoDiv = document.createElement('div');
9706
- logoDiv.className = 'svu-sidebar-logo';
9707
- if (this.branding.logoDarkUrl) {
9708
- const logo = document.createElement('img');
9709
- logo.src = this.branding.logoDarkUrl;
9710
- logo.alt = this.branding.organizationName;
9711
- logoDiv.appendChild(logo);
9712
- }
9713
- sidebar.appendChild(logoDiv);
9714
- // Intro
9715
- const intro = document.createElement('div');
9716
- intro.className = 'svu-sidebar-intro';
9717
- intro.innerHTML = `
9718
- <h3>Secure File Transfer</h3>
9719
- <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>
9720
- `;
9721
- sidebar.appendChild(intro);
9722
- // Security details
9723
- const security = document.createElement('div');
9724
- security.className = 'svu-sidebar-security';
9725
- security.innerHTML = `
9726
- <h4>
9727
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9728
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
9729
- </svg>
9730
- SparkVault's Triple Zero-Trust
9731
- </h4>
9732
- <p class="svu-security-intro">
9733
- Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.
9734
- </p>
9735
- <div class="svu-key-chain">
9736
- <div class="svu-key-item">
9737
- <div class="svu-key-number">1</div>
9738
- <div class="svu-key-info">
9739
- <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>
9740
- <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>
9741
- <span class="svu-key-desc">Quantum-resistant key exchange</span>
9742
- </div>
9743
- </div>
9744
- <div class="svu-key-connector">
9745
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9746
- <path d="M12 5v14M5 12h14"/>
9747
- </svg>
9748
- </div>
9749
- <div class="svu-key-item">
9750
- <div class="svu-key-number">2</div>
9751
- <div class="svu-key-info">
9752
- <span class="svu-key-name">X25519 Ephemeral Key</span>
9753
- <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>
9754
- <span class="svu-key-desc">Perfect forward secrecy</span>
9755
- </div>
9756
- </div>
9757
- <div class="svu-key-connector">
9758
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9759
- <path d="M12 5v14M5 12h14"/>
9760
- </svg>
9761
- </div>
9762
- <div class="svu-key-item">
9763
- <div class="svu-key-number">3</div>
9764
- <div class="svu-key-info">
9765
- <span class="svu-key-name">HKDF-SHA512 Derived Key</span>
9766
- <span class="svu-key-algo">Hardware-bound key derivation</span>
9767
- <span class="svu-key-desc">Vault master key in secure enclave</span>
9768
- </div>
9769
- </div>
9770
- </div>
9771
- <div class="svu-encryption-result">
9772
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9773
- <path d="M20 6L9 17l-5-5"/>
9774
- </svg>
9775
- <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>
9776
- </div>
9777
- <div class="svu-security-badges">
9778
- <span class="svu-tls-badge">TLS 1.3 In Transit</span>
9779
- <span class="svu-tls-badge">Encrypted At Rest</span>
9780
- <span class="svu-tls-badge">Zero Trust</span>
9781
- </div>
9782
- `;
9783
- sidebar.appendChild(security);
9784
- return sidebar;
9785
- }
9786
9664
  handleClose() {
9787
9665
  if (this.onCloseCallback) {
9788
9666
  this.onCloseCallback();
@@ -9825,6 +9703,14 @@ function generateRequestId() {
9825
9703
  const random = Array.from(randomBytes, byte => byte.toString(16).padStart(2, '0')).join('');
9826
9704
  return `${timestamp}${random}`;
9827
9705
  }
9706
+ /**
9707
+ * Whether an error represents a deliberate cancellation (user close,
9708
+ * programmatic close, or session abort) rather than a genuine failure.
9709
+ */
9710
+ function isCancellationError(error) {
9711
+ return (error instanceof UserCancelledError ||
9712
+ (error instanceof SparkVaultError && error.code === 'cancelled'));
9713
+ }
9828
9714
  /**
9829
9715
  * Format bytes to human readable string.
9830
9716
  */
@@ -9847,8 +9733,11 @@ class UploadRenderer {
9847
9733
  this.uploadModal = null;
9848
9734
  this.isInlineMode = false;
9849
9735
  this.hybridModalInitialized = false;
9850
- // Track active XHR for cancellation on close
9851
- this.activeXhr = null;
9736
+ // Lifecycle flags: a closed renderer must never render or fire callbacks,
9737
+ // and onCancel fires at most once per renderer (mutually exclusive with
9738
+ // onError — see cancel()/handleApiError).
9739
+ this.closed = false;
9740
+ this.cancelled = false;
9852
9741
  this.pasteHandler = null;
9853
9742
  this.container = container;
9854
9743
  this.api = api;
@@ -9889,16 +9778,13 @@ class UploadRenderer {
9889
9778
  }
9890
9779
  /**
9891
9780
  * Close the upload flow.
9892
- * Cancels all pending API requests and active uploads to prevent orphaned operations.
9781
+ * Cancels all pending API requests and active uploads (aborting the session
9782
+ * signal tears down any in-flight TUS chunk) to prevent orphaned operations.
9893
9783
  */
9894
9784
  close() {
9895
- // Cancel all pending API requests first
9785
+ this.closed = true;
9786
+ // Cancel all pending API requests and the active TUS transfer
9896
9787
  this.api.abort();
9897
- // Abort any active XHR upload
9898
- if (this.activeXhr) {
9899
- this.activeXhr.abort();
9900
- this.activeXhr = null;
9901
- }
9902
9788
  this.cleanupFileInput();
9903
9789
  this.cleanupPasteHandler();
9904
9790
  // Clean up modal if open (hybrid mode)
@@ -9909,14 +9795,64 @@ class UploadRenderer {
9909
9795
  }
9910
9796
  this.container.destroy();
9911
9797
  }
9912
- handleClose() {
9798
+ /**
9799
+ * Cancel the flow: tear everything down and fire the cancel contract
9800
+ * exactly once. onCancel and onError are mutually exclusive — a deliberate
9801
+ * cancellation (user close, programmatic close, or a new upload replacing
9802
+ * this renderer) must never surface as an error to the host.
9803
+ */
9804
+ cancel() {
9805
+ if (this.cancelled)
9806
+ return;
9807
+ this.cancelled = true;
9913
9808
  this.close();
9914
9809
  this.callbacks.onCancel();
9915
9810
  }
9811
+ handleClose() {
9812
+ this.cancel();
9813
+ }
9916
9814
  setState(state) {
9815
+ // A closed renderer never renders again — a progress event racing the
9816
+ // teardown must not resurrect the hybrid-mode modal or touch the DOM.
9817
+ if (this.closed)
9818
+ return;
9819
+ const previousView = this.viewState.view;
9917
9820
  this.viewState = state;
9821
+ // Progress events fire many times per second for the whole transfer.
9822
+ // While the uploading view is already on screen, mutate its progress
9823
+ // nodes in place instead of tearing down and rebuilding the subtree —
9824
+ // a full rebuild per event thrashes the DOM and restarts the progress
9825
+ // bar's CSS transition and the stage-arrow animation on every tick.
9826
+ if (previousView === 'uploading' &&
9827
+ state.view === 'uploading' &&
9828
+ this.updateUploadProgress(state)) {
9829
+ return;
9830
+ }
9918
9831
  this.render();
9919
9832
  }
9833
+ /**
9834
+ * Targeted DOM update for an already-rendered uploading view: progress fill
9835
+ * width plus the percentage and byte-count labels. Returns false when the
9836
+ * uploading view is not in the DOM, so the caller falls back to a full render.
9837
+ */
9838
+ updateUploadProgress(state) {
9839
+ // Hybrid inline mode renders uploading inside the modal overlay.
9840
+ const body = this.isInlineMode && this.uploadModal
9841
+ ? this.uploadModal.getBody()
9842
+ : this.container.getBody();
9843
+ const fill = body?.querySelector('.svu-progress-fill');
9844
+ if (!body || !fill)
9845
+ return false;
9846
+ fill.style.width = `${state.progress}%`;
9847
+ const [percentLabel, bytesLabel] = body.querySelectorAll('.svu-progress-text span');
9848
+ if (percentLabel) {
9849
+ percentLabel.textContent = `${state.progress}%`;
9850
+ }
9851
+ if (bytesLabel) {
9852
+ bytesLabel.textContent = `${formatBytes(state.bytesUploaded)} / ${formatBytes(state.file.size)}`;
9853
+ }
9854
+ return true;
9855
+ }
9920
9856
  render() {
9921
9857
  const isDarkState = this.viewState.view === 'uploading' || this.viewState.view === 'ceremony';
9922
9858
  // Hybrid mode: For inline containers, use a modal popup for upload/ceremony
@@ -10418,8 +10354,24 @@ class UploadRenderer {
10418
10354
  progress: 0,
10419
10355
  bytesUploaded: 0,
10420
10356
  });
10421
- // Upload file using tus (resumable upload)
10422
- const uploadUrl = await this.uploadWithTus(file, forgeUrl, ingotId, requestId);
10357
+ // Upload file over the canonical TUS transfer path
10358
+ const uploadUrl = await this.api.uploadFileToForge(file, forgeUrl, (bytesUploaded, bytesTotal) => {
10359
+ const progress = Math.round((bytesUploaded / bytesTotal) * 100);
10360
+ this.setState({
10361
+ view: 'uploading',
10362
+ file,
10363
+ ingotId,
10364
+ requestId,
10365
+ progress,
10366
+ bytesUploaded,
10367
+ });
10368
+ this.callbacks.onProgress?.({
10369
+ bytesUploaded,
10370
+ bytesTotal,
10371
+ percentage: progress,
10372
+ phase: 'uploading',
10373
+ });
10374
+ });
10423
10375
  // Confirm the server actually finalized the upload before celebrating.
10424
10376
  // The TUS loop trusts a server-provided offset; this re-reads the
10425
10377
  // server's own persisted offset and requires it to reach the file size,
@@ -10460,129 +10412,6 @@ class UploadRenderer {
10460
10412
  this.handleApiError(error);
10461
10413
  }
10462
10414
  }
10463
- async uploadWithTus(file, forgeUrl, ingotId, requestId) {
10464
- // tus resumable upload protocol v1.0.0
10465
- // Uploads file in chunks to avoid Cloudflare's 100MB request limit
10466
- const TUS_VERSION = '1.0.0';
10467
- const DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024; // 50MB default, server may override
10468
- // Extract base URL and ISTK from forge URL
10469
- const url = new URL(forgeUrl);
10470
- const istk = url.searchParams.get('istk');
10471
- const baseUrl = `${url.origin}${url.pathname}`;
10472
- if (!istk) {
10473
- throw new Error('Missing ISTK in forge URL');
10474
- }
10475
- // Step 1: Create tus upload session
10476
- const createResponse = await fetch(baseUrl, {
10477
- method: 'POST',
10478
- headers: {
10479
- 'Tus-Resumable': TUS_VERSION,
10480
- 'Upload-Length': String(file.size),
10481
- 'X-ISTK': istk,
10482
- 'Content-Type': 'application/offset+octet-stream',
10483
- },
10484
- });
10485
- if (!createResponse.ok) {
10486
- const errorText = await createResponse.text();
10487
- throw new Error(`Failed to create upload session: ${createResponse.status} ${errorText}`);
10488
- }
10489
- // Get upload location and chunk size from response
10490
- const location = createResponse.headers.get('Location');
10491
- const chunkSizeHeader = createResponse.headers.get('X-Chunk-Size');
10492
- const chunkSize = chunkSizeHeader ? parseInt(chunkSizeHeader, 10) : DEFAULT_CHUNK_SIZE;
10493
- if (!location) {
10494
- throw new Error('Server did not return upload location');
10495
- }
10496
- // Build full upload URL
10497
- const uploadUrl = location.startsWith('http') ? location : `${url.origin}${location}`;
10498
- // Step 2: Upload file in chunks with progress tracking
10499
- let offset = 0;
10500
- const totalSize = file.size;
10501
- while (offset < totalSize) {
10502
- const chunkStart = offset;
10503
- const chunkEnd = Math.min(offset + chunkSize, totalSize);
10504
- const chunk = file.slice(chunkStart, chunkEnd);
10505
- // Upload chunk with XHR for progress events
10506
- const newOffset = await this.uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, TUS_VERSION, file, ingotId, requestId);
10507
- offset = newOffset;
10508
- }
10509
- return uploadUrl;
10510
- }
10511
- /**
10512
- * Upload a single chunk using XMLHttpRequest for progress tracking.
10513
- * Tracks the XHR so it can be cancelled if the renderer is closed.
10514
- */
10515
- uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, tusVersion, file, ingotId, requestId) {
10516
- return new Promise((resolve, reject) => {
10517
- // Check if already aborted before starting
10518
- if (this.api.isAborted()) {
10519
- reject(new Error('Upload cancelled'));
10520
- return;
10521
- }
10522
- const xhr = new XMLHttpRequest();
10523
- // Track this XHR so it can be cancelled on close
10524
- this.activeXhr = xhr;
10525
- // Track progress within this chunk
10526
- xhr.upload.onprogress = (e) => {
10527
- if (e.lengthComputable) {
10528
- // Calculate total progress: completed chunks + progress within current chunk
10529
- const totalUploaded = chunkStart + e.loaded;
10530
- const progress = Math.round((totalUploaded / totalSize) * 100);
10531
- this.setState({
10532
- view: 'uploading',
10533
- file,
10534
- ingotId,
10535
- requestId,
10536
- progress,
10537
- bytesUploaded: totalUploaded,
10538
- });
10539
- this.callbacks.onProgress?.({
10540
- bytesUploaded: totalUploaded,
10541
- bytesTotal: totalSize,
10542
- percentage: progress,
10543
- phase: 'uploading',
10544
- });
10545
- }
10546
- };
10547
- xhr.onload = () => {
10548
- this.activeXhr = null;
10549
- if (xhr.status >= 200 && xhr.status < 300) {
10550
- // Get new offset from server response
10551
- const newOffsetHeader = xhr.getResponseHeader('Upload-Offset');
10552
- const newOffset = newOffsetHeader ? parseInt(newOffsetHeader, 10) : chunkStart + chunk.size;
10553
- // Defense-in-depth: the server must never report more bytes accepted
10554
- // than the file contains. A `newOffset > totalSize` is a malformed or
10555
- // inflated response — reject it rather than letting an over-reported
10556
- // offset short-circuit the upload loop and skip real chunks.
10557
- if (!Number.isFinite(newOffset) || newOffset < chunkStart || newOffset > totalSize) {
10558
- reject(new Error(`Server returned invalid upload offset (${newOffset})`));
10559
- return;
10560
- }
10561
- resolve(newOffset);
10562
- }
10563
- else {
10564
- reject(new Error(`Chunk upload failed with status ${xhr.status}`));
10565
- }
10566
- };
10567
- xhr.onerror = () => {
10568
- this.activeXhr = null;
10569
- reject(new Error('Chunk upload failed'));
10570
- };
10571
- xhr.ontimeout = () => {
10572
- this.activeXhr = null;
10573
- reject(new Error('Chunk upload timed out'));
10574
- };
10575
- xhr.onabort = () => {
10576
- this.activeXhr = null;
10577
- reject(new Error('Upload cancelled'));
10578
- };
10579
- xhr.open('PATCH', uploadUrl);
10580
- xhr.setRequestHeader('Tus-Resumable', tusVersion);
10581
- xhr.setRequestHeader('Upload-Offset', String(chunkStart));
10582
- xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream');
10583
- xhr.send(chunk);
10584
- });
10585
- }
10586
10415
  async runCeremony(file, ingotId, requestId) {
10587
10416
  for (let i = 0; i < CEREMONY_STEPS.length; i++) {
10588
10417
  this.setState({
@@ -10613,6 +10442,14 @@ class UploadRenderer {
10613
10442
  await new Promise(resolve => setTimeout(resolve, 500));
10614
10443
  }
10615
10444
  handleApiError(error) {
10445
+ // A closed renderer must not surface errors: cancelling mid-transfer
10446
+ // aborts the in-flight request, whose 'cancelled' rejection races the
10447
+ // teardown. The host has already received onCancel — onCancel and
10448
+ // onError are mutually exclusive — and the container is destroyed, so
10449
+ // there is nothing left to render into.
10450
+ if (this.closed || isCancellationError(error)) {
10451
+ return;
10452
+ }
10616
10453
  if (error instanceof UploadApiError) {
10617
10454
  if (error.code === 'UPLOAD_SOURCE_DISABLED') {
10618
10455
  // The vault exists but the embedded widget isn't enabled.
@@ -10682,7 +10519,6 @@ class UploadRenderer {
10682
10519
  }
10683
10520
  }
10684
10521
 
10685
- /* global Element */
10686
10522
  /**
10687
10523
  * Vault Upload Module
10688
10524
  *
@@ -10703,7 +10539,6 @@ class UploadRenderer {
10703
10539
  class VaultUploadModule {
10704
10540
  constructor(config) {
10705
10541
  this.renderer = null;
10706
- this.attachedElements = new Map();
10707
10542
  this.config = config;
10708
10543
  this.api = new UploadApi(config);
10709
10544
  }
@@ -10727,9 +10562,10 @@ class VaultUploadModule {
10727
10562
  if (!options.vaultId) {
10728
10563
  throw new ValidationError('vaultId is required');
10729
10564
  }
10730
- // Close any existing renderer
10565
+ // Cancel any existing renderer so its pending promise settles via the
10566
+ // cancel contract (onCancel + UserCancelledError) instead of hanging.
10731
10567
  if (this.renderer) {
10732
- this.renderer.close();
10568
+ this.renderer.cancel();
10733
10569
  }
10734
10570
  const isInline = !!options.target;
10735
10571
  const container = isInline
@@ -10788,7 +10624,6 @@ class VaultUploadModule {
10788
10624
  if (!options.vaultId) {
10789
10625
  throw new ValidationError('vaultId is required');
10790
10626
  }
10791
- let observer = null;
10792
10627
  const handleClick = async (event) => {
10793
10628
  event.preventDefault();
10794
10629
  try {
@@ -10804,55 +10639,17 @@ class VaultUploadModule {
10804
10639
  // Error already handled by callbacks or will use server redirect
10805
10640
  }
10806
10641
  };
10807
- const attachToElements = () => {
10808
- const elements = document.querySelectorAll(selector);
10809
- elements.forEach((element) => {
10810
- element.addEventListener('click', handleClick);
10811
- this.attachedElements.set(element, () => {
10812
- element.removeEventListener('click', handleClick);
10813
- });
10814
- });
10815
- // Watch for dynamically added elements
10816
- observer = new MutationObserver((mutations) => {
10817
- mutations.forEach((mutation) => {
10818
- mutation.addedNodes.forEach((node) => {
10819
- if (node instanceof Element) {
10820
- if (node.matches(selector)) {
10821
- node.addEventListener('click', handleClick);
10822
- this.attachedElements.set(node, () => {
10823
- node.removeEventListener('click', handleClick);
10824
- });
10825
- }
10826
- // Check descendants
10827
- node.querySelectorAll(selector).forEach((el) => {
10828
- if (!this.attachedElements.has(el)) {
10829
- el.addEventListener('click', handleClick);
10830
- this.attachedElements.set(el, () => {
10831
- el.removeEventListener('click', handleClick);
10832
- });
10833
- }
10834
- });
10835
- }
10836
- });
10837
- });
10838
- });
10839
- observer.observe(document.body, { childList: true, subtree: true });
10840
- };
10841
- // Defer attachment until DOM is ready
10842
- onDomReady(attachToElements);
10843
- // Return cleanup function
10844
- return () => {
10845
- observer?.disconnect();
10846
- this.attachedElements.forEach((cleanup) => cleanup());
10847
- this.attachedElements.clear();
10848
- };
10642
+ return attachClickHandler(selector, handleClick);
10849
10643
  }
10850
10644
  /**
10851
10645
  * Close the upload dialog/inline UI if open.
10646
+ *
10647
+ * Programmatic close follows the cancel contract: the host's onCancel
10648
+ * fires and the pending upload promise rejects with UserCancelledError.
10852
10649
  */
10853
10650
  close() {
10854
10651
  if (this.renderer) {
10855
- this.renderer.close();
10652
+ this.renderer.cancel();
10856
10653
  this.renderer = null;
10857
10654
  }
10858
10655
  }
@@ -10876,9 +10673,9 @@ class VaultUploadModule {
10876
10673
  }
10877
10674
  return new UploadInlineContainer(element);
10878
10675
  }
10879
- // Public-API aliases. The web vault-edit screen instructs customers to
10880
- // call sv.vaults.upload.pop(vaultId) / .render(vaultId, target) — both
10881
- // are documented entry points that defer to upload() under the hood.
10676
+ // Public-API aliases. The dashboard's vault-edit screen and the SDK docs
10677
+ // document sv.vaults.upload.pop({ vaultId }) and
10678
+ // sv.vaults.upload.render({ vaultId, target }) — both defer to upload().
10882
10679
  /** Open the upload widget as a popup. Equivalent to `upload(options)`. */
10883
10680
  async pop(options) {
10884
10681
  return this.upload(options);
@@ -10900,10 +10697,13 @@ class VaultsModule {
10900
10697
  this.config = config;
10901
10698
  this.http = http;
10902
10699
  this.uploadModule = new VaultUploadModule(config);
10903
- // Create callable that also has attach/close methods
10700
+ this.uploadApi = new UploadApi(config);
10701
+ // Create callable that also has attach/close/pop/render methods
10904
10702
  const uploadFn = ((options) => this.uploadModule.upload(options));
10905
10703
  uploadFn.attach = (selector, options) => this.uploadModule.attach(selector, options);
10906
10704
  uploadFn.close = () => this.uploadModule.close();
10705
+ uploadFn.pop = (options) => this.uploadModule.pop(options);
10706
+ uploadFn.render = (options) => this.uploadModule.render(options);
10907
10707
  this.upload = uploadFn;
10908
10708
  }
10909
10709
  /**
@@ -11011,7 +10811,11 @@ class VaultsModule {
11011
10811
  if (!created.forge_url) {
11012
10812
  throw new ValidationError('Upload endpoint did not return a Forge upload URL');
11013
10813
  }
11014
- await uploadBlobWithTus(options.file, created.forge_url, created.name, created.content_type, options.onProgress);
10814
+ const uploadUrl = await this.uploadApi.uploadFileToForge(options.file, created.forge_url, options.onProgress);
10815
+ // Confirm the server actually finalized the upload before reporting
10816
+ // success — the TUS loop's offsets alone don't prove the final chunk
10817
+ // committed and the ingot went active.
10818
+ await this.uploadApi.verifyUploadFinalized(uploadUrl, options.file.size);
11015
10819
  return {
11016
10820
  id: created.ingot_id,
11017
10821
  name: created.name,
@@ -11121,78 +10925,6 @@ function getBlobName(file) {
11121
10925
  }
11122
10926
  return 'unnamed';
11123
10927
  }
11124
- function base64Encode(value) {
11125
- return btoa(unescape(encodeURIComponent(value)));
11126
- }
11127
- async function uploadBlobWithTus(file, forgeUrl, filename, contentType, onProgress) {
11128
- if (typeof XMLHttpRequest === 'undefined') {
11129
- throw new ValidationError('XMLHttpRequest is required for browser ingot uploads');
11130
- }
11131
- const tusVersion = '1.0.0';
11132
- const defaultChunkSize = 50 * 1024 * 1024;
11133
- const url = new URL(forgeUrl);
11134
- const istk = url.searchParams.get('istk');
11135
- const endpoint = `${url.origin}${url.pathname}`;
11136
- if (!istk) {
11137
- throw new ValidationError('Forge upload URL is missing ISTK');
11138
- }
11139
- const createResponse = await fetch(endpoint, {
11140
- method: 'POST',
11141
- headers: {
11142
- 'Tus-Resumable': tusVersion,
11143
- 'Upload-Length': String(file.size),
11144
- 'Upload-Metadata': `filename ${base64Encode(filename)},filetype ${base64Encode(contentType)}`,
11145
- 'X-ISTK': istk,
11146
- },
11147
- });
11148
- if (!createResponse.ok) {
11149
- const errorText = await createResponse.text();
11150
- throw new Error(`Failed to create upload session: ${createResponse.status} ${errorText}`);
11151
- }
11152
- const location = createResponse.headers.get('Location');
11153
- const chunkSizeHeader = createResponse.headers.get('X-Chunk-Size');
11154
- const chunkSize = chunkSizeHeader ? parseInt(chunkSizeHeader, 10) : defaultChunkSize;
11155
- if (!location) {
11156
- throw new Error('Server did not return upload location');
11157
- }
11158
- const uploadUrl = location.startsWith('http') ? location : `${url.origin}${location}`;
11159
- let offset = 0;
11160
- while (offset < file.size) {
11161
- const chunkStart = offset;
11162
- const chunkEnd = Math.min(offset + chunkSize, file.size);
11163
- const chunk = file.slice(chunkStart, chunkEnd);
11164
- offset = await uploadChunkWithProgress(uploadUrl, chunk, chunkStart, file.size, tusVersion, istk, onProgress);
11165
- }
11166
- }
11167
- function uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, tusVersion, istk, onProgress) {
11168
- return new Promise((resolve, reject) => {
11169
- const xhr = new XMLHttpRequest();
11170
- xhr.upload.onprogress = (event) => {
11171
- if (event.lengthComputable) {
11172
- onProgress?.(chunkStart + event.loaded, totalSize);
11173
- }
11174
- };
11175
- xhr.onload = () => {
11176
- if (xhr.status >= 200 && xhr.status < 300) {
11177
- const newOffsetHeader = xhr.getResponseHeader('Upload-Offset');
11178
- const newOffset = newOffsetHeader ? parseInt(newOffsetHeader, 10) : chunkStart + chunk.size;
11179
- resolve(newOffset);
11180
- }
11181
- else {
11182
- reject(new Error(`Chunk upload failed with status ${xhr.status}`));
11183
- }
11184
- };
11185
- xhr.onerror = () => reject(new Error('Chunk upload failed'));
11186
- xhr.ontimeout = () => reject(new Error('Chunk upload timed out'));
11187
- xhr.onabort = () => reject(new Error('Upload cancelled'));
11188
- xhr.open('PATCH', uploadUrl);
11189
- xhr.setRequestHeader('Tus-Resumable', tusVersion);
11190
- xhr.setRequestHeader('Upload-Offset', String(chunkStart));
11191
- xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream');
11192
- xhr.setRequestHeader('X-ISTK', istk);
11193
- xhr.send(chunk);
11194
- });
11195
- }
11196
10928
  const DOWNLOAD_MAX_ATTEMPTS = 3;
11197
10929
  const DOWNLOAD_RETRY_BASE_MS = 500;
11198
10930
  function delayExponential(attempt) {