@sparkvault/sdk-js 2.2.0 → 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
  /**
@@ -6893,7 +6660,7 @@ class IdentityRenderer {
6893
6660
  }
6894
6661
  }
6895
6662
 
6896
- /* global HTMLIFrameElement */
6663
+ /* global HTMLIFrameElement requestAnimationFrame */
6897
6664
  /**
6898
6665
  * Widget Embedder
6899
6666
  *
@@ -6941,6 +6708,7 @@ class WidgetEmbedder {
6941
6708
  // against — never the broader sparkvault.com family.
6942
6709
  this.trustedOrigin = new URL(this.config.identityBaseUrl).origin;
6943
6710
  this.boundHandleMessage = (event) => this.handleMessage(event);
6711
+ this.boundHandleCspViolation = (event) => this.handleCspViolation(event);
6944
6712
  }
6945
6713
  start() {
6946
6714
  const iframe = document.createElement('iframe');
@@ -6960,6 +6728,12 @@ class WidgetEmbedder {
6960
6728
  'background:transparent',
6961
6729
  'z-index:2147483647',
6962
6730
  ].join(';');
6731
+ // Promote to its own compositing layer up front. iOS Safari can otherwise
6732
+ // leave a freshly-inserted fixed, full-viewport iframe loaded but UNPAINTED
6733
+ // until the next composite (a scroll, resize, or app foreground) — the
6734
+ // frame even runs, but the dialog only appears after an app switch.
6735
+ iframe.style.transform = 'translateZ(0)';
6736
+ iframe.style.willChange = 'transform';
6963
6737
  // A network-level load failure (DNS, connection reset) fires onerror; an
6964
6738
  // HTTP error body or a frame blocked from framing does not, which is what
6965
6739
  // the readiness timeout below covers.
@@ -6969,9 +6743,36 @@ class WidgetEmbedder {
6969
6743
  this.previousBodyOverflow = document.body.style.overflow;
6970
6744
  document.body.style.overflow = 'hidden';
6971
6745
  window.addEventListener('message', this.boundHandleMessage);
6746
+ // A host-page CSP whose frame-src/child-src omits the Identity origin blocks
6747
+ // the iframe before it can load and fires no `onerror`. Catch the violation
6748
+ // so we fail over to the in-page flow at once instead of after the timeout.
6749
+ document.addEventListener('securitypolicyviolation', this.boundHandleCspViolation);
6972
6750
  document.body.appendChild(iframe);
6751
+ // Force the composite the iframe insertion may not have triggered on iOS,
6752
+ // so the dialog paints on the click rather than only after an app switch.
6753
+ this.forceComposite(iframe);
6973
6754
  this.readyTimer = setTimeout(() => this.handleFrameUnavailable(), FRAME_READY_TIMEOUT_MS);
6974
6755
  }
6756
+ /**
6757
+ * Nudge the browser to paint the just-inserted iframe on the next frame.
6758
+ * Reading layout forces a reflow; toggling a transform forces the compositor
6759
+ * to flush the new layer — the workaround for iOS Safari leaving a fixed
6760
+ * full-viewport iframe invisible until an unrelated repaint.
6761
+ */
6762
+ forceComposite(iframe) {
6763
+ const paint = () => {
6764
+ if (!this.iframe)
6765
+ return;
6766
+ void iframe.offsetHeight;
6767
+ iframe.style.transform = 'translateZ(0) scale(1)';
6768
+ };
6769
+ if (typeof requestAnimationFrame === 'function') {
6770
+ requestAnimationFrame(paint);
6771
+ }
6772
+ else {
6773
+ setTimeout(paint, 16);
6774
+ }
6775
+ }
6975
6776
  close() {
6976
6777
  this.clearReadyTimer();
6977
6778
  if (this.iframe?.parentNode) {
@@ -6979,8 +6780,22 @@ class WidgetEmbedder {
6979
6780
  }
6980
6781
  this.iframe = null;
6981
6782
  window.removeEventListener('message', this.boundHandleMessage);
6783
+ document.removeEventListener('securitypolicyviolation', this.boundHandleCspViolation);
6982
6784
  document.body.style.overflow = this.previousBodyOverflow;
6983
6785
  }
6786
+ /**
6787
+ * Host CSP blocked the widget iframe (frame-src/child-src). The frame can
6788
+ * never load, so fail over to the in-page flow immediately.
6789
+ */
6790
+ handleCspViolation(event) {
6791
+ const directive = event.effectiveDirective || event.violatedDirective;
6792
+ if (directive !== 'frame-src' && directive !== 'child-src')
6793
+ return;
6794
+ // blockedURI is the framed URL (sometimes just its origin); match either.
6795
+ if (typeof event.blockedURI === 'string' && event.blockedURI.startsWith(this.trustedOrigin)) {
6796
+ this.handleFrameUnavailable();
6797
+ }
6798
+ }
6984
6799
  clearReadyTimer() {
6985
6800
  if (this.readyTimer !== null) {
6986
6801
  clearTimeout(this.readyTimer);
@@ -7037,6 +6852,26 @@ class WidgetEmbedder {
7037
6852
  this.close();
7038
6853
  window.location.href = url.toString();
7039
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
+ }
7040
6875
  buildUrl() {
7041
6876
  const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/widget`);
7042
6877
  url.searchParams.set('origin', window.location.origin);
@@ -7087,7 +6922,7 @@ class WidgetEmbedder {
7087
6922
  // iframe; on return the host SDK consumes the redirect token.
7088
6923
  if (data.type === REDIRECT_TYPE && typeof data.url === 'string') {
7089
6924
  this.clearReadyTimer();
7090
- window.location.href = data.url;
6925
+ this.safeNavigate(data.url);
7091
6926
  return;
7092
6927
  }
7093
6928
  if (data.type !== RESULT_TYPE || this.settled)
@@ -7100,7 +6935,7 @@ class WidgetEmbedder {
7100
6935
  // Mirror the renderer's belt-and-suspenders: complete a server-issued
7101
6936
  // redirect from the host's own top window if the customer didn't.
7102
6937
  if (typeof result.redirect === 'string' && result.redirect) {
7103
- window.location.href = result.redirect;
6938
+ this.safeNavigate(result.redirect);
7104
6939
  }
7105
6940
  }
7106
6941
  else if (data.cancelled) {
@@ -7303,6 +7138,7 @@ class InlineContainer {
7303
7138
  }
7304
7139
  }
7305
7140
 
7141
+ /* global Element */
7306
7142
  /**
7307
7143
  * DOM Utilities
7308
7144
  *
@@ -7351,8 +7187,62 @@ function onBodyReady(callback) {
7351
7187
  }
7352
7188
  }
7353
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
+ }
7354
7245
 
7355
- /* global Element */
7356
7246
  /**
7357
7247
  * Identity Module
7358
7248
  *
@@ -7387,7 +7277,6 @@ class IdentityModule {
7387
7277
  constructor(config) {
7388
7278
  this.renderer = null;
7389
7279
  this.embedder = null;
7390
- this.attachedElements = new Map();
7391
7280
  this.config = config;
7392
7281
  this.api = new IdentityApi(config);
7393
7282
  // Preload config in background for instant dialog opening
@@ -7514,7 +7403,6 @@ class IdentityModule {
7514
7403
  * cleanup();
7515
7404
  */
7516
7405
  attach(selector, options = {}) {
7517
- let observer = null;
7518
7406
  const handleClick = async (event) => {
7519
7407
  event.preventDefault();
7520
7408
  try {
@@ -7531,48 +7419,10 @@ class IdentityModule {
7531
7419
  // Error already handled by callbacks or will use server redirect
7532
7420
  }
7533
7421
  };
7534
- const attachToElements = () => {
7535
- const elements = document.querySelectorAll(selector);
7536
- elements.forEach((element) => {
7537
- element.addEventListener('click', handleClick);
7538
- this.attachedElements.set(element, () => {
7539
- element.removeEventListener('click', handleClick);
7540
- });
7541
- });
7542
- // Watch for dynamically added elements
7543
- observer = new MutationObserver((mutations) => {
7544
- mutations.forEach((mutation) => {
7545
- mutation.addedNodes.forEach((node) => {
7546
- if (node instanceof Element) {
7547
- if (node.matches(selector)) {
7548
- node.addEventListener('click', handleClick);
7549
- this.attachedElements.set(node, () => {
7550
- node.removeEventListener('click', handleClick);
7551
- });
7552
- }
7553
- // Check descendants
7554
- node.querySelectorAll(selector).forEach((el) => {
7555
- if (!this.attachedElements.has(el)) {
7556
- el.addEventListener('click', handleClick);
7557
- this.attachedElements.set(el, () => {
7558
- el.removeEventListener('click', handleClick);
7559
- });
7560
- }
7561
- });
7562
- }
7563
- });
7564
- });
7565
- });
7566
- // Observe document.body for dynamic elements
7567
- // Use onBodyReady to handle edge cases where body isn't available yet
7568
- onBodyReady(() => {
7569
- observer?.observe(document.body, { childList: true, subtree: true });
7570
- });
7571
- };
7572
- // Defer attachment until DOM is ready, then complete any full-page
7573
- // 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.
7574
7425
  onDomReady(() => {
7575
- attachToElements();
7576
7426
  this.consumeRedirectResult()
7577
7427
  .then((result) => {
7578
7428
  if (result)
@@ -7582,12 +7432,7 @@ class IdentityModule {
7582
7432
  options.onError?.(error instanceof Error ? error : new Error(String(error)));
7583
7433
  });
7584
7434
  });
7585
- // Return cleanup function
7586
- return () => {
7587
- observer?.disconnect();
7588
- this.attachedElements.forEach((cleanup) => cleanup());
7589
- this.attachedElements.clear();
7590
- };
7435
+ return cleanup;
7591
7436
  }
7592
7437
  /**
7593
7438
  * Verify and decode an identity token.
@@ -7634,29 +7479,56 @@ class IdentityModule {
7634
7479
  if (!token) {
7635
7480
  return null;
7636
7481
  }
7637
- const expectedState = sessionStorage.getItem('sv_oauth_state');
7638
- if (expectedState && params.get('state') !== expectedState) {
7639
- throw new ValidationError('Invalid OAuth state');
7640
- }
7641
- const claims = await this.verifyToken(token);
7642
- const result = {
7643
- token,
7644
- identity: claims.identity,
7645
- identityType: claims.identity_type,
7646
- svid: claims.svid,
7647
- sessionId: claims.session_id,
7648
- };
7649
- if (typeof window.history?.replaceState === 'function') {
7650
- 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
+ }
7651
7518
  }
7652
- sessionStorage.removeItem('sv_oauth_state');
7653
- sessionStorage.removeItem('sv_oauth_email');
7654
- return result;
7655
7519
  }
7656
7520
  /**
7657
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).
7658
7526
  */
7659
7527
  close() {
7528
+ if (this.embedder) {
7529
+ this.embedder.close();
7530
+ this.embedder = null;
7531
+ }
7660
7532
  if (this.renderer) {
7661
7533
  this.renderer.close();
7662
7534
  this.renderer = null;
@@ -7769,6 +7641,15 @@ function isInitiateUploadResponse(data) {
7769
7641
  }
7770
7642
  /** tus protocol version used for the resumable upload session. */
7771
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;
7772
7653
  /**
7773
7654
  * Server-side finalization confirmation poll.
7774
7655
  *
@@ -7851,6 +7732,167 @@ class UploadApi extends SparkVaultApi {
7851
7732
  ingotId: response.data.ingot_id,
7852
7733
  };
7853
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
+ }
7854
7896
  /**
7855
7897
  * Confirm the upload was finalized SERVER-SIDE before reporting success.
7856
7898
  *
@@ -7897,21 +7939,7 @@ class UploadApi extends SparkVaultApi {
7897
7939
  */
7898
7940
  async headUploadOffset(uploadUrl) {
7899
7941
  const closeSignal = this.getAbortSignal();
7900
- const timeoutController = new AbortController();
7901
- const timeoutId = setTimeout(() => timeoutController.abort(), this.timeoutMs);
7902
- // Combine timeout + session-close into one signal. Mirror the base
7903
- // client's fallback for browsers without AbortSignal.any: link the close
7904
- // signal into the timeout controller and remove the listener in finally.
7905
- let combinedSignal;
7906
- let onCloseAbort = null;
7907
- if ('any' in AbortSignal) {
7908
- combinedSignal = AbortSignal.any([timeoutController.signal, closeSignal]);
7909
- }
7910
- else {
7911
- combinedSignal = timeoutController.signal;
7912
- onCloseAbort = () => timeoutController.abort();
7913
- closeSignal.addEventListener('abort', onCloseAbort);
7914
- }
7942
+ const { signal: combinedSignal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, closeSignal);
7915
7943
  try {
7916
7944
  const response = await fetch(uploadUrl, {
7917
7945
  method: 'HEAD',
@@ -7943,14 +7971,175 @@ class UploadApi extends SparkVaultApi {
7943
7971
  throw new UploadApiError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
7944
7972
  }
7945
7973
  finally {
7946
- clearTimeout(timeoutId);
7947
- if (onCloseAbort) {
7948
- closeSignal.removeEventListener('abort', onCloseAbort);
7949
- }
7974
+ dispose();
7950
7975
  }
7951
7976
  }
7952
7977
  }
7953
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
+
7954
8143
  /**
7955
8144
  * Upload Widget Styles
7956
8145
  *
@@ -7960,19 +8149,19 @@ class UploadApi extends SparkVaultApi {
7960
8149
  const STYLE_ID = 'sparkvault-upload-styles';
7961
8150
  /**
7962
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.
7963
8154
  */
7964
- function injectUploadStyles(options) {
8155
+ function injectUploadStyles() {
7965
8156
  if (document.getElementById(STYLE_ID)) {
7966
8157
  return;
7967
8158
  }
7968
8159
  const style = document.createElement('style');
7969
8160
  style.id = STYLE_ID;
7970
- style.textContent = getUploadStyles(options);
8161
+ style.textContent = getUploadStyles();
7971
8162
  document.head.appendChild(style);
7972
8163
  }
7973
- function getUploadStyles(options) {
7974
- const { backdropBlur } = options;
7975
- const enableBlur = backdropBlur !== false;
8164
+ function getUploadStyles() {
7976
8165
  // Design tokens - light theme for upload widget
7977
8166
  const tokens = {
7978
8167
  // Colors
@@ -8039,8 +8228,8 @@ function getUploadStyles(options) {
8039
8228
  }
8040
8229
 
8041
8230
  .svu-overlay.svu-blur {
8042
- backdrop-filter: blur(${enableBlur ? '8px' : '0'});
8043
- -webkit-backdrop-filter: blur(${enableBlur ? '8px' : '0'});
8231
+ backdrop-filter: blur(8px);
8232
+ -webkit-backdrop-filter: blur(8px);
8044
8233
  }
8045
8234
 
8046
8235
  .svu-modal {
@@ -9068,6 +9257,8 @@ function getUploadStyles(options) {
9068
9257
  */
9069
9258
  const OVERLAY_ID = 'sparkvault-upload-overlay';
9070
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';
9071
9262
  /**
9072
9263
  * Default branding used for immediate modal display before config loads.
9073
9264
  */
@@ -9108,17 +9299,14 @@ class UploadModalContainer {
9108
9299
  this.onCloseCallback = onClose;
9109
9300
  this.backdropBlur = options.backdropBlur !== false;
9110
9301
  this.branding = options.branding || DEFAULT_BRANDING;
9111
- injectUploadStyles({
9112
- branding: this.branding,
9113
- backdropBlur: this.backdropBlur,
9114
- });
9302
+ injectUploadStyles();
9115
9303
  // Create overlay
9116
9304
  const overlay = document.createElement('div');
9117
9305
  overlay.id = OVERLAY_ID;
9118
9306
  overlay.className = this.backdropBlur ? 'svu-overlay svu-blur' : 'svu-overlay';
9119
9307
  overlay.setAttribute('role', 'dialog');
9120
9308
  overlay.setAttribute('aria-modal', 'true');
9121
- overlay.setAttribute('aria-labelledby', 'svu-modal-title');
9309
+ overlay.setAttribute('aria-labelledby', MODAL_TITLE_ID);
9122
9310
  // Create modal
9123
9311
  const modal = document.createElement('div');
9124
9312
  modal.id = MODAL_ID;
@@ -9133,19 +9321,7 @@ class UploadModalContainer {
9133
9321
  const body = document.createElement('div');
9134
9322
  body.className = 'svu-body';
9135
9323
  // Create footer
9136
- const footer = document.createElement('div');
9137
- footer.className = 'svu-footer';
9138
- const footerText = document.createElement('span');
9139
- footerText.className = 'svu-footer-text';
9140
- footerText.appendChild(document.createTextNode('Secured by '));
9141
- const footerLink = document.createElement('a');
9142
- footerLink.href = 'https://sparkvault.com';
9143
- footerLink.target = '_blank';
9144
- footerLink.rel = 'noopener noreferrer';
9145
- footerLink.className = 'svu-footer-link';
9146
- footerLink.textContent = 'SparkVault';
9147
- footerText.appendChild(footerLink);
9148
- footer.appendChild(footerText);
9324
+ const footer = createFooter();
9149
9325
  main.appendChild(header);
9150
9326
  main.appendChild(body);
9151
9327
  main.appendChild(footer);
@@ -9169,47 +9345,15 @@ class UploadModalContainer {
9169
9345
  this.elements = { overlay, modal, main, header, body, footer, sidebar: null };
9170
9346
  }
9171
9347
  createHeader(branding) {
9172
- const header = document.createElement('div');
9173
- header.className = 'svu-header';
9174
- const titleContainer = document.createElement('div');
9175
- titleContainer.className = 'svu-header-title';
9176
- // Use light logo for light theme (default), dark logo for dark mode
9177
- const logoUrl = this.isDarkMode
9178
- ? branding.logoDarkUrl || branding.logoLightUrl
9179
- : branding.logoLightUrl || branding.logoDarkUrl;
9180
- if (logoUrl) {
9181
- const logo = document.createElement('img');
9182
- logo.className = 'svu-logo';
9183
- logo.src = logoUrl;
9184
- logo.alt = branding.organizationName;
9185
- titleContainer.appendChild(logo);
9186
- // Screen reader title
9187
- const srTitle = document.createElement('span');
9188
- srTitle.className = 'svu-sr-only';
9189
- srTitle.id = 'svu-modal-title';
9190
- srTitle.textContent = branding.organizationName;
9191
- titleContainer.appendChild(srTitle);
9192
- }
9193
- else if (branding.organizationName) {
9194
- const companyName = document.createElement('h2');
9195
- companyName.className = 'svu-company-name';
9196
- companyName.id = 'svu-modal-title';
9197
- companyName.textContent = branding.organizationName;
9198
- titleContainer.appendChild(companyName);
9199
- }
9200
- // Close button
9201
- this.closeBtn = document.createElement('button');
9202
- this.closeBtn.className = 'svu-close-btn';
9203
- this.closeBtn.setAttribute('aria-label', 'Close');
9204
- this.closeBtn.innerHTML = `
9205
- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9206
- <path d="M18 6L6 18M6 6l12 12"/>
9207
- </svg>
9208
- `;
9209
9348
  this.closeBtnClickHandler = () => this.handleClose();
9210
- this.closeBtn.addEventListener('click', this.closeBtnClickHandler);
9211
- header.appendChild(titleContainer);
9212
- 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;
9213
9357
  return header;
9214
9358
  }
9215
9359
  /**
@@ -9271,7 +9415,7 @@ class UploadModalContainer {
9271
9415
  return;
9272
9416
  if (show && !this.elements.sidebar) {
9273
9417
  // Create sidebar
9274
- const sidebar = this.createSecuritySidebar();
9418
+ const sidebar = createSecuritySidebar(this.branding);
9275
9419
  this.elements.modal.classList.add('svu-with-sidebar');
9276
9420
  this.elements.modal.appendChild(sidebar);
9277
9421
  this.elements.sidebar = sidebar;
@@ -9291,91 +9435,6 @@ class UploadModalContainer {
9291
9435
  }
9292
9436
  }
9293
9437
  }
9294
- createSecuritySidebar() {
9295
- const sidebar = document.createElement('div');
9296
- sidebar.className = 'svu-sidebar';
9297
- // Logo
9298
- const logoDiv = document.createElement('div');
9299
- logoDiv.className = 'svu-sidebar-logo';
9300
- if (this.branding.logoDarkUrl) {
9301
- const logo = document.createElement('img');
9302
- logo.src = this.branding.logoDarkUrl;
9303
- logo.alt = this.branding.organizationName;
9304
- logoDiv.appendChild(logo);
9305
- }
9306
- sidebar.appendChild(logoDiv);
9307
- // Intro
9308
- const intro = document.createElement('div');
9309
- intro.className = 'svu-sidebar-intro';
9310
- intro.innerHTML = `
9311
- <h3>Secure File Transfer</h3>
9312
- <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>
9313
- `;
9314
- sidebar.appendChild(intro);
9315
- // Security details
9316
- const security = document.createElement('div');
9317
- security.className = 'svu-sidebar-security';
9318
- security.innerHTML = `
9319
- <h4>
9320
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9321
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
9322
- </svg>
9323
- SparkVault's Triple Zero-Trust
9324
- </h4>
9325
- <p class="svu-security-intro">
9326
- Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.
9327
- </p>
9328
- <div class="svu-key-chain">
9329
- <div class="svu-key-item">
9330
- <div class="svu-key-number">1</div>
9331
- <div class="svu-key-info">
9332
- <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>
9333
- <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>
9334
- <span class="svu-key-desc">Quantum-resistant key exchange</span>
9335
- </div>
9336
- </div>
9337
- <div class="svu-key-connector">
9338
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9339
- <path d="M12 5v14M5 12h14"/>
9340
- </svg>
9341
- </div>
9342
- <div class="svu-key-item">
9343
- <div class="svu-key-number">2</div>
9344
- <div class="svu-key-info">
9345
- <span class="svu-key-name">X25519 Ephemeral Key</span>
9346
- <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>
9347
- <span class="svu-key-desc">Perfect forward secrecy</span>
9348
- </div>
9349
- </div>
9350
- <div class="svu-key-connector">
9351
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9352
- <path d="M12 5v14M5 12h14"/>
9353
- </svg>
9354
- </div>
9355
- <div class="svu-key-item">
9356
- <div class="svu-key-number">3</div>
9357
- <div class="svu-key-info">
9358
- <span class="svu-key-name">HKDF-SHA512 Derived Key</span>
9359
- <span class="svu-key-algo">Hardware-bound key derivation</span>
9360
- <span class="svu-key-desc">Vault master key in secure enclave</span>
9361
- </div>
9362
- </div>
9363
- </div>
9364
- <div class="svu-encryption-result">
9365
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9366
- <path d="M20 6L9 17l-5-5"/>
9367
- </svg>
9368
- <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>
9369
- </div>
9370
- <div class="svu-security-badges">
9371
- <span class="svu-tls-badge">TLS 1.3 In Transit</span>
9372
- <span class="svu-tls-badge">Encrypted At Rest</span>
9373
- <span class="svu-tls-badge">Zero Trust</span>
9374
- </div>
9375
- `;
9376
- sidebar.appendChild(security);
9377
- return sidebar;
9378
- }
9379
9438
  handleClose() {
9380
9439
  if (this.onCloseCallback) {
9381
9440
  this.onCloseCallback();
@@ -9468,10 +9527,7 @@ class UploadInlineContainer {
9468
9527
  }
9469
9528
  this.onCloseCallback = onClose;
9470
9529
  // Inject styles
9471
- injectUploadStyles({
9472
- branding: this.branding,
9473
- backdropBlur: false,
9474
- });
9530
+ injectUploadStyles();
9475
9531
  // Create main container
9476
9532
  this.container = document.createElement('div');
9477
9533
  this.container.className = 'svu-inline-container';
@@ -9486,19 +9542,7 @@ class UploadInlineContainer {
9486
9542
  this.container.appendChild(this.body);
9487
9543
  // Create footer if enabled
9488
9544
  if (this.containerOptions.showFooter) {
9489
- this.footer = document.createElement('div');
9490
- this.footer.className = 'svu-footer';
9491
- const footerText = document.createElement('span');
9492
- footerText.className = 'svu-footer-text';
9493
- footerText.appendChild(document.createTextNode('Secured by '));
9494
- const footerLink = document.createElement('a');
9495
- footerLink.href = 'https://sparkvault.com';
9496
- footerLink.target = '_blank';
9497
- footerLink.rel = 'noopener noreferrer';
9498
- footerLink.className = 'svu-footer-link';
9499
- footerLink.textContent = 'SparkVault';
9500
- footerText.appendChild(footerLink);
9501
- this.footer.appendChild(footerText);
9545
+ this.footer = createFooter();
9502
9546
  this.container.appendChild(this.footer);
9503
9547
  }
9504
9548
  // Clear target and append container
@@ -9556,7 +9600,7 @@ class UploadInlineContainer {
9556
9600
  return;
9557
9601
  if (show && !this.sidebar) {
9558
9602
  // Create sidebar
9559
- this.sidebar = this.createSecuritySidebar();
9603
+ this.sidebar = createSecuritySidebar(this.branding);
9560
9604
  this.container.classList.add('svu-with-sidebar');
9561
9605
  this.container.appendChild(this.sidebar);
9562
9606
  }
@@ -9607,134 +9651,16 @@ class UploadInlineContainer {
9607
9651
  this.onCloseCallback = null;
9608
9652
  }
9609
9653
  createHeader(branding) {
9610
- const header = document.createElement('div');
9611
- header.className = 'svu-header';
9612
- const titleContainer = document.createElement('div');
9613
- titleContainer.className = 'svu-header-title';
9614
- // Use appropriate logo based on dark mode
9615
- const logoUrl = this.isDarkMode
9616
- ? branding.logoDarkUrl || branding.logoLightUrl
9617
- : branding.logoLightUrl || branding.logoDarkUrl;
9618
- if (logoUrl) {
9619
- const logo = document.createElement('img');
9620
- logo.className = 'svu-logo';
9621
- logo.src = logoUrl;
9622
- logo.alt = branding.organizationName;
9623
- titleContainer.appendChild(logo);
9624
- // Screen reader title
9625
- const srTitle = document.createElement('span');
9626
- srTitle.className = 'svu-sr-only';
9627
- srTitle.textContent = branding.organizationName;
9628
- titleContainer.appendChild(srTitle);
9629
- }
9630
- else if (branding.organizationName) {
9631
- const companyName = document.createElement('h2');
9632
- companyName.className = 'svu-company-name';
9633
- companyName.textContent = branding.organizationName;
9634
- titleContainer.appendChild(companyName);
9635
- }
9636
- header.appendChild(titleContainer);
9637
- // Add close button if enabled
9638
- if (this.containerOptions.showCloseButton) {
9639
- this.closeBtn = document.createElement('button');
9640
- this.closeBtn.className = 'svu-close-btn';
9641
- this.closeBtn.setAttribute('aria-label', 'Close');
9642
- this.closeBtn.innerHTML = `
9643
- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9644
- <path d="M18 6L6 18M6 6l12 12"/>
9645
- </svg>
9646
- `;
9647
- this.closeBtnClickHandler = () => this.handleClose();
9648
- this.closeBtn.addEventListener('click', this.closeBtnClickHandler);
9649
- header.appendChild(this.closeBtn);
9650
- }
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;
9651
9662
  return header;
9652
9663
  }
9653
- createSecuritySidebar() {
9654
- const sidebar = document.createElement('div');
9655
- sidebar.className = 'svu-sidebar';
9656
- // Logo
9657
- const logoDiv = document.createElement('div');
9658
- logoDiv.className = 'svu-sidebar-logo';
9659
- if (this.branding.logoDarkUrl) {
9660
- const logo = document.createElement('img');
9661
- logo.src = this.branding.logoDarkUrl;
9662
- logo.alt = this.branding.organizationName;
9663
- logoDiv.appendChild(logo);
9664
- }
9665
- sidebar.appendChild(logoDiv);
9666
- // Intro
9667
- const intro = document.createElement('div');
9668
- intro.className = 'svu-sidebar-intro';
9669
- intro.innerHTML = `
9670
- <h3>Secure File Transfer</h3>
9671
- <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>
9672
- `;
9673
- sidebar.appendChild(intro);
9674
- // Security details
9675
- const security = document.createElement('div');
9676
- security.className = 'svu-sidebar-security';
9677
- security.innerHTML = `
9678
- <h4>
9679
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9680
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
9681
- </svg>
9682
- SparkVault's Triple Zero-Trust
9683
- </h4>
9684
- <p class="svu-security-intro">
9685
- Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.
9686
- </p>
9687
- <div class="svu-key-chain">
9688
- <div class="svu-key-item">
9689
- <div class="svu-key-number">1</div>
9690
- <div class="svu-key-info">
9691
- <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>
9692
- <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>
9693
- <span class="svu-key-desc">Quantum-resistant key exchange</span>
9694
- </div>
9695
- </div>
9696
- <div class="svu-key-connector">
9697
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9698
- <path d="M12 5v14M5 12h14"/>
9699
- </svg>
9700
- </div>
9701
- <div class="svu-key-item">
9702
- <div class="svu-key-number">2</div>
9703
- <div class="svu-key-info">
9704
- <span class="svu-key-name">X25519 Ephemeral Key</span>
9705
- <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>
9706
- <span class="svu-key-desc">Perfect forward secrecy</span>
9707
- </div>
9708
- </div>
9709
- <div class="svu-key-connector">
9710
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9711
- <path d="M12 5v14M5 12h14"/>
9712
- </svg>
9713
- </div>
9714
- <div class="svu-key-item">
9715
- <div class="svu-key-number">3</div>
9716
- <div class="svu-key-info">
9717
- <span class="svu-key-name">HKDF-SHA512 Derived Key</span>
9718
- <span class="svu-key-algo">Hardware-bound key derivation</span>
9719
- <span class="svu-key-desc">Vault master key in secure enclave</span>
9720
- </div>
9721
- </div>
9722
- </div>
9723
- <div class="svu-encryption-result">
9724
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9725
- <path d="M20 6L9 17l-5-5"/>
9726
- </svg>
9727
- <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>
9728
- </div>
9729
- <div class="svu-security-badges">
9730
- <span class="svu-tls-badge">TLS 1.3 In Transit</span>
9731
- <span class="svu-tls-badge">Encrypted At Rest</span>
9732
- <span class="svu-tls-badge">Zero Trust</span>
9733
- </div>
9734
- `;
9735
- sidebar.appendChild(security);
9736
- return sidebar;
9737
- }
9738
9664
  handleClose() {
9739
9665
  if (this.onCloseCallback) {
9740
9666
  this.onCloseCallback();
@@ -9777,6 +9703,14 @@ function generateRequestId() {
9777
9703
  const random = Array.from(randomBytes, byte => byte.toString(16).padStart(2, '0')).join('');
9778
9704
  return `${timestamp}${random}`;
9779
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
+ }
9780
9714
  /**
9781
9715
  * Format bytes to human readable string.
9782
9716
  */
@@ -9799,8 +9733,11 @@ class UploadRenderer {
9799
9733
  this.uploadModal = null;
9800
9734
  this.isInlineMode = false;
9801
9735
  this.hybridModalInitialized = false;
9802
- // Track active XHR for cancellation on close
9803
- 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;
9804
9741
  this.pasteHandler = null;
9805
9742
  this.container = container;
9806
9743
  this.api = api;
@@ -9841,16 +9778,13 @@ class UploadRenderer {
9841
9778
  }
9842
9779
  /**
9843
9780
  * Close the upload flow.
9844
- * 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.
9845
9783
  */
9846
9784
  close() {
9847
- // Cancel all pending API requests first
9785
+ this.closed = true;
9786
+ // Cancel all pending API requests and the active TUS transfer
9848
9787
  this.api.abort();
9849
- // Abort any active XHR upload
9850
- if (this.activeXhr) {
9851
- this.activeXhr.abort();
9852
- this.activeXhr = null;
9853
- }
9854
9788
  this.cleanupFileInput();
9855
9789
  this.cleanupPasteHandler();
9856
9790
  // Clean up modal if open (hybrid mode)
@@ -9861,14 +9795,64 @@ class UploadRenderer {
9861
9795
  }
9862
9796
  this.container.destroy();
9863
9797
  }
9864
- 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;
9865
9808
  this.close();
9866
9809
  this.callbacks.onCancel();
9867
9810
  }
9811
+ handleClose() {
9812
+ this.cancel();
9813
+ }
9868
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;
9869
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
+ }
9870
9831
  this.render();
9871
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
+ }
9872
9856
  render() {
9873
9857
  const isDarkState = this.viewState.view === 'uploading' || this.viewState.view === 'ceremony';
9874
9858
  // Hybrid mode: For inline containers, use a modal popup for upload/ceremony
@@ -10370,8 +10354,24 @@ class UploadRenderer {
10370
10354
  progress: 0,
10371
10355
  bytesUploaded: 0,
10372
10356
  });
10373
- // Upload file using tus (resumable upload)
10374
- 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
+ });
10375
10375
  // Confirm the server actually finalized the upload before celebrating.
10376
10376
  // The TUS loop trusts a server-provided offset; this re-reads the
10377
10377
  // server's own persisted offset and requires it to reach the file size,
@@ -10412,129 +10412,6 @@ class UploadRenderer {
10412
10412
  this.handleApiError(error);
10413
10413
  }
10414
10414
  }
10415
- async uploadWithTus(file, forgeUrl, ingotId, requestId) {
10416
- // tus resumable upload protocol v1.0.0
10417
- // Uploads file in chunks to avoid Cloudflare's 100MB request limit
10418
- const TUS_VERSION = '1.0.0';
10419
- const DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024; // 50MB default, server may override
10420
- // Extract base URL and ISTK from forge URL
10421
- const url = new URL(forgeUrl);
10422
- const istk = url.searchParams.get('istk');
10423
- const baseUrl = `${url.origin}${url.pathname}`;
10424
- if (!istk) {
10425
- throw new Error('Missing ISTK in forge URL');
10426
- }
10427
- // Step 1: Create tus upload session
10428
- const createResponse = await fetch(baseUrl, {
10429
- method: 'POST',
10430
- headers: {
10431
- 'Tus-Resumable': TUS_VERSION,
10432
- 'Upload-Length': String(file.size),
10433
- 'X-ISTK': istk,
10434
- 'Content-Type': 'application/offset+octet-stream',
10435
- },
10436
- });
10437
- if (!createResponse.ok) {
10438
- const errorText = await createResponse.text();
10439
- throw new Error(`Failed to create upload session: ${createResponse.status} ${errorText}`);
10440
- }
10441
- // Get upload location and chunk size from response
10442
- const location = createResponse.headers.get('Location');
10443
- const chunkSizeHeader = createResponse.headers.get('X-Chunk-Size');
10444
- const chunkSize = chunkSizeHeader ? parseInt(chunkSizeHeader, 10) : DEFAULT_CHUNK_SIZE;
10445
- if (!location) {
10446
- throw new Error('Server did not return upload location');
10447
- }
10448
- // Build full upload URL
10449
- const uploadUrl = location.startsWith('http') ? location : `${url.origin}${location}`;
10450
- // Step 2: Upload file in chunks with progress tracking
10451
- let offset = 0;
10452
- const totalSize = file.size;
10453
- while (offset < totalSize) {
10454
- const chunkStart = offset;
10455
- const chunkEnd = Math.min(offset + chunkSize, totalSize);
10456
- const chunk = file.slice(chunkStart, chunkEnd);
10457
- // Upload chunk with XHR for progress events
10458
- const newOffset = await this.uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, TUS_VERSION, file, ingotId, requestId);
10459
- offset = newOffset;
10460
- }
10461
- return uploadUrl;
10462
- }
10463
- /**
10464
- * Upload a single chunk using XMLHttpRequest for progress tracking.
10465
- * Tracks the XHR so it can be cancelled if the renderer is closed.
10466
- */
10467
- uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, tusVersion, file, ingotId, requestId) {
10468
- return new Promise((resolve, reject) => {
10469
- // Check if already aborted before starting
10470
- if (this.api.isAborted()) {
10471
- reject(new Error('Upload cancelled'));
10472
- return;
10473
- }
10474
- const xhr = new XMLHttpRequest();
10475
- // Track this XHR so it can be cancelled on close
10476
- this.activeXhr = xhr;
10477
- // Track progress within this chunk
10478
- xhr.upload.onprogress = (e) => {
10479
- if (e.lengthComputable) {
10480
- // Calculate total progress: completed chunks + progress within current chunk
10481
- const totalUploaded = chunkStart + e.loaded;
10482
- const progress = Math.round((totalUploaded / totalSize) * 100);
10483
- this.setState({
10484
- view: 'uploading',
10485
- file,
10486
- ingotId,
10487
- requestId,
10488
- progress,
10489
- bytesUploaded: totalUploaded,
10490
- });
10491
- this.callbacks.onProgress?.({
10492
- bytesUploaded: totalUploaded,
10493
- bytesTotal: totalSize,
10494
- percentage: progress,
10495
- phase: 'uploading',
10496
- });
10497
- }
10498
- };
10499
- xhr.onload = () => {
10500
- this.activeXhr = null;
10501
- if (xhr.status >= 200 && xhr.status < 300) {
10502
- // Get new offset from server response
10503
- const newOffsetHeader = xhr.getResponseHeader('Upload-Offset');
10504
- const newOffset = newOffsetHeader ? parseInt(newOffsetHeader, 10) : chunkStart + chunk.size;
10505
- // Defense-in-depth: the server must never report more bytes accepted
10506
- // than the file contains. A `newOffset > totalSize` is a malformed or
10507
- // inflated response — reject it rather than letting an over-reported
10508
- // offset short-circuit the upload loop and skip real chunks.
10509
- if (!Number.isFinite(newOffset) || newOffset < chunkStart || newOffset > totalSize) {
10510
- reject(new Error(`Server returned invalid upload offset (${newOffset})`));
10511
- return;
10512
- }
10513
- resolve(newOffset);
10514
- }
10515
- else {
10516
- reject(new Error(`Chunk upload failed with status ${xhr.status}`));
10517
- }
10518
- };
10519
- xhr.onerror = () => {
10520
- this.activeXhr = null;
10521
- reject(new Error('Chunk upload failed'));
10522
- };
10523
- xhr.ontimeout = () => {
10524
- this.activeXhr = null;
10525
- reject(new Error('Chunk upload timed out'));
10526
- };
10527
- xhr.onabort = () => {
10528
- this.activeXhr = null;
10529
- reject(new Error('Upload cancelled'));
10530
- };
10531
- xhr.open('PATCH', uploadUrl);
10532
- xhr.setRequestHeader('Tus-Resumable', tusVersion);
10533
- xhr.setRequestHeader('Upload-Offset', String(chunkStart));
10534
- xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream');
10535
- xhr.send(chunk);
10536
- });
10537
- }
10538
10415
  async runCeremony(file, ingotId, requestId) {
10539
10416
  for (let i = 0; i < CEREMONY_STEPS.length; i++) {
10540
10417
  this.setState({
@@ -10565,6 +10442,14 @@ class UploadRenderer {
10565
10442
  await new Promise(resolve => setTimeout(resolve, 500));
10566
10443
  }
10567
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
+ }
10568
10453
  if (error instanceof UploadApiError) {
10569
10454
  if (error.code === 'UPLOAD_SOURCE_DISABLED') {
10570
10455
  // The vault exists but the embedded widget isn't enabled.
@@ -10634,7 +10519,6 @@ class UploadRenderer {
10634
10519
  }
10635
10520
  }
10636
10521
 
10637
- /* global Element */
10638
10522
  /**
10639
10523
  * Vault Upload Module
10640
10524
  *
@@ -10655,7 +10539,6 @@ class UploadRenderer {
10655
10539
  class VaultUploadModule {
10656
10540
  constructor(config) {
10657
10541
  this.renderer = null;
10658
- this.attachedElements = new Map();
10659
10542
  this.config = config;
10660
10543
  this.api = new UploadApi(config);
10661
10544
  }
@@ -10679,9 +10562,10 @@ class VaultUploadModule {
10679
10562
  if (!options.vaultId) {
10680
10563
  throw new ValidationError('vaultId is required');
10681
10564
  }
10682
- // Close any existing renderer
10565
+ // Cancel any existing renderer so its pending promise settles via the
10566
+ // cancel contract (onCancel + UserCancelledError) instead of hanging.
10683
10567
  if (this.renderer) {
10684
- this.renderer.close();
10568
+ this.renderer.cancel();
10685
10569
  }
10686
10570
  const isInline = !!options.target;
10687
10571
  const container = isInline
@@ -10740,7 +10624,6 @@ class VaultUploadModule {
10740
10624
  if (!options.vaultId) {
10741
10625
  throw new ValidationError('vaultId is required');
10742
10626
  }
10743
- let observer = null;
10744
10627
  const handleClick = async (event) => {
10745
10628
  event.preventDefault();
10746
10629
  try {
@@ -10756,55 +10639,17 @@ class VaultUploadModule {
10756
10639
  // Error already handled by callbacks or will use server redirect
10757
10640
  }
10758
10641
  };
10759
- const attachToElements = () => {
10760
- const elements = document.querySelectorAll(selector);
10761
- elements.forEach((element) => {
10762
- element.addEventListener('click', handleClick);
10763
- this.attachedElements.set(element, () => {
10764
- element.removeEventListener('click', handleClick);
10765
- });
10766
- });
10767
- // Watch for dynamically added elements
10768
- observer = new MutationObserver((mutations) => {
10769
- mutations.forEach((mutation) => {
10770
- mutation.addedNodes.forEach((node) => {
10771
- if (node instanceof Element) {
10772
- if (node.matches(selector)) {
10773
- node.addEventListener('click', handleClick);
10774
- this.attachedElements.set(node, () => {
10775
- node.removeEventListener('click', handleClick);
10776
- });
10777
- }
10778
- // Check descendants
10779
- node.querySelectorAll(selector).forEach((el) => {
10780
- if (!this.attachedElements.has(el)) {
10781
- el.addEventListener('click', handleClick);
10782
- this.attachedElements.set(el, () => {
10783
- el.removeEventListener('click', handleClick);
10784
- });
10785
- }
10786
- });
10787
- }
10788
- });
10789
- });
10790
- });
10791
- observer.observe(document.body, { childList: true, subtree: true });
10792
- };
10793
- // Defer attachment until DOM is ready
10794
- onDomReady(attachToElements);
10795
- // Return cleanup function
10796
- return () => {
10797
- observer?.disconnect();
10798
- this.attachedElements.forEach((cleanup) => cleanup());
10799
- this.attachedElements.clear();
10800
- };
10642
+ return attachClickHandler(selector, handleClick);
10801
10643
  }
10802
10644
  /**
10803
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.
10804
10649
  */
10805
10650
  close() {
10806
10651
  if (this.renderer) {
10807
- this.renderer.close();
10652
+ this.renderer.cancel();
10808
10653
  this.renderer = null;
10809
10654
  }
10810
10655
  }
@@ -10828,9 +10673,9 @@ class VaultUploadModule {
10828
10673
  }
10829
10674
  return new UploadInlineContainer(element);
10830
10675
  }
10831
- // Public-API aliases. The web vault-edit screen instructs customers to
10832
- // call sv.vaults.upload.pop(vaultId) / .render(vaultId, target) — both
10833
- // 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().
10834
10679
  /** Open the upload widget as a popup. Equivalent to `upload(options)`. */
10835
10680
  async pop(options) {
10836
10681
  return this.upload(options);
@@ -10852,10 +10697,13 @@ class VaultsModule {
10852
10697
  this.config = config;
10853
10698
  this.http = http;
10854
10699
  this.uploadModule = new VaultUploadModule(config);
10855
- // 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
10856
10702
  const uploadFn = ((options) => this.uploadModule.upload(options));
10857
10703
  uploadFn.attach = (selector, options) => this.uploadModule.attach(selector, options);
10858
10704
  uploadFn.close = () => this.uploadModule.close();
10705
+ uploadFn.pop = (options) => this.uploadModule.pop(options);
10706
+ uploadFn.render = (options) => this.uploadModule.render(options);
10859
10707
  this.upload = uploadFn;
10860
10708
  }
10861
10709
  /**
@@ -10963,7 +10811,11 @@ class VaultsModule {
10963
10811
  if (!created.forge_url) {
10964
10812
  throw new ValidationError('Upload endpoint did not return a Forge upload URL');
10965
10813
  }
10966
- 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);
10967
10819
  return {
10968
10820
  id: created.ingot_id,
10969
10821
  name: created.name,
@@ -11073,78 +10925,6 @@ function getBlobName(file) {
11073
10925
  }
11074
10926
  return 'unnamed';
11075
10927
  }
11076
- function base64Encode(value) {
11077
- return btoa(unescape(encodeURIComponent(value)));
11078
- }
11079
- async function uploadBlobWithTus(file, forgeUrl, filename, contentType, onProgress) {
11080
- if (typeof XMLHttpRequest === 'undefined') {
11081
- throw new ValidationError('XMLHttpRequest is required for browser ingot uploads');
11082
- }
11083
- const tusVersion = '1.0.0';
11084
- const defaultChunkSize = 50 * 1024 * 1024;
11085
- const url = new URL(forgeUrl);
11086
- const istk = url.searchParams.get('istk');
11087
- const endpoint = `${url.origin}${url.pathname}`;
11088
- if (!istk) {
11089
- throw new ValidationError('Forge upload URL is missing ISTK');
11090
- }
11091
- const createResponse = await fetch(endpoint, {
11092
- method: 'POST',
11093
- headers: {
11094
- 'Tus-Resumable': tusVersion,
11095
- 'Upload-Length': String(file.size),
11096
- 'Upload-Metadata': `filename ${base64Encode(filename)},filetype ${base64Encode(contentType)}`,
11097
- 'X-ISTK': istk,
11098
- },
11099
- });
11100
- if (!createResponse.ok) {
11101
- const errorText = await createResponse.text();
11102
- throw new Error(`Failed to create upload session: ${createResponse.status} ${errorText}`);
11103
- }
11104
- const location = createResponse.headers.get('Location');
11105
- const chunkSizeHeader = createResponse.headers.get('X-Chunk-Size');
11106
- const chunkSize = chunkSizeHeader ? parseInt(chunkSizeHeader, 10) : defaultChunkSize;
11107
- if (!location) {
11108
- throw new Error('Server did not return upload location');
11109
- }
11110
- const uploadUrl = location.startsWith('http') ? location : `${url.origin}${location}`;
11111
- let offset = 0;
11112
- while (offset < file.size) {
11113
- const chunkStart = offset;
11114
- const chunkEnd = Math.min(offset + chunkSize, file.size);
11115
- const chunk = file.slice(chunkStart, chunkEnd);
11116
- offset = await uploadChunkWithProgress(uploadUrl, chunk, chunkStart, file.size, tusVersion, istk, onProgress);
11117
- }
11118
- }
11119
- function uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, tusVersion, istk, onProgress) {
11120
- return new Promise((resolve, reject) => {
11121
- const xhr = new XMLHttpRequest();
11122
- xhr.upload.onprogress = (event) => {
11123
- if (event.lengthComputable) {
11124
- onProgress?.(chunkStart + event.loaded, totalSize);
11125
- }
11126
- };
11127
- xhr.onload = () => {
11128
- if (xhr.status >= 200 && xhr.status < 300) {
11129
- const newOffsetHeader = xhr.getResponseHeader('Upload-Offset');
11130
- const newOffset = newOffsetHeader ? parseInt(newOffsetHeader, 10) : chunkStart + chunk.size;
11131
- resolve(newOffset);
11132
- }
11133
- else {
11134
- reject(new Error(`Chunk upload failed with status ${xhr.status}`));
11135
- }
11136
- };
11137
- xhr.onerror = () => reject(new Error('Chunk upload failed'));
11138
- xhr.ontimeout = () => reject(new Error('Chunk upload timed out'));
11139
- xhr.onabort = () => reject(new Error('Upload cancelled'));
11140
- xhr.open('PATCH', uploadUrl);
11141
- xhr.setRequestHeader('Tus-Resumable', tusVersion);
11142
- xhr.setRequestHeader('Upload-Offset', String(chunkStart));
11143
- xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream');
11144
- xhr.setRequestHeader('X-ISTK', istk);
11145
- xhr.send(chunk);
11146
- });
11147
- }
11148
10928
  const DOWNLOAD_MAX_ATTEMPTS = 3;
11149
10929
  const DOWNLOAD_RETRY_BASE_MS = 500;
11150
10930
  function delayExponential(attempt) {