@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.
@@ -157,103 +157,6 @@ function validateConfig(config) {
157
157
  }
158
158
  }
159
159
 
160
- /**
161
- * Retry Utility with Exponential Backoff
162
- *
163
- * Per CLAUDE.md §7: Retries allowed only if idempotent, MUST use exponential backoff.
164
- */
165
- const DEFAULT_OPTIONS$2 = {
166
- maxAttempts: 3,
167
- baseDelayMs: 200,
168
- maxDelayMs: 5000,
169
- jitterFactor: 0.2,
170
- isRetryable: defaultIsRetryable,
171
- };
172
- /**
173
- * Default retry eligibility checker
174
- * Retries on network errors, timeouts, and 5xx server errors
175
- */
176
- function defaultIsRetryable(error) {
177
- // Network errors (TypeError from fetch)
178
- if (error instanceof TypeError) {
179
- return true;
180
- }
181
- // DOMException (timeout/abort)
182
- if (error instanceof DOMException && error.name === 'AbortError') {
183
- return true;
184
- }
185
- // SparkVault errors with status codes
186
- if (typeof error === 'object' &&
187
- error !== null &&
188
- 'statusCode' in error) {
189
- const statusCode = error.statusCode;
190
- // Retry on server errors (5xx) and rate limits (429)
191
- return statusCode >= 500 || statusCode === 429;
192
- }
193
- return false;
194
- }
195
- /**
196
- * Return a random unit interval value using Web Crypto.
197
- */
198
- function randomUnit() {
199
- const value = new Uint32Array(1);
200
- crypto.getRandomValues(value);
201
- return value[0] / 0x100000000;
202
- }
203
- /**
204
- * Calculate delay with exponential backoff and jitter
205
- */
206
- function calculateDelay(attempt, baseDelayMs, maxDelayMs, jitterFactor) {
207
- // Exponential backoff: base * 2^attempt
208
- const exponentialDelay = baseDelayMs * Math.pow(2, attempt);
209
- const cappedDelay = Math.min(exponentialDelay, maxDelayMs);
210
- // Add jitter: random value within jitter range
211
- const jitter = cappedDelay * jitterFactor * randomUnit();
212
- return cappedDelay + jitter;
213
- }
214
- /**
215
- * Sleep for specified milliseconds
216
- */
217
- function sleep(ms) {
218
- return new Promise((resolve) => setTimeout(resolve, ms));
219
- }
220
- /**
221
- * Execute an async function with retry logic and exponential backoff.
222
- *
223
- * @param fn - Async function to execute
224
- * @param options - Retry configuration options
225
- * @returns Promise resolving to the function result
226
- * @throws The last error if all retries fail
227
- *
228
- * @example
229
- * const result = await withRetry(
230
- * () => fetch('/api/data'),
231
- * { maxAttempts: 3, baseDelayMs: 100 }
232
- * );
233
- */
234
- async function withRetry(fn, options = {}) {
235
- const config = { ...DEFAULT_OPTIONS$2, ...options };
236
- let lastError;
237
- for (let attempt = 0; attempt < config.maxAttempts; attempt++) {
238
- try {
239
- return await fn();
240
- }
241
- catch (error) {
242
- lastError = error;
243
- // Don't retry on last attempt or non-retryable errors
244
- const isLastAttempt = attempt === config.maxAttempts - 1;
245
- if (isLastAttempt || !config.isRetryable(error)) {
246
- throw error;
247
- }
248
- // Calculate and wait for backoff delay
249
- const delay = calculateDelay(attempt, config.baseDelayMs, config.maxDelayMs, config.jitterFactor);
250
- await sleep(delay);
251
- }
252
- }
253
- // Should not reach here, but TypeScript needs this
254
- throw lastError;
255
- }
256
-
257
160
  /**
258
161
  * SparkVault SDK HTTP Client
259
162
  */
@@ -287,22 +190,6 @@ class HttpClient {
287
190
  return this.config.accessToken ?? null;
288
191
  }
289
192
  async request(path, options = {}) {
290
- const { retry } = options;
291
- // Per CLAUDE.md §7: Wrap with retry logic if enabled
292
- if (retry) {
293
- const retryOptions = typeof retry === 'object' ? retry : {};
294
- return withRetry(() => this.executeRequest(path, options), {
295
- ...retryOptions,
296
- // Only retry on idempotent-safe errors (network, timeout, 5xx)
297
- isRetryable: (error) => this.isRetryableError(error),
298
- });
299
- }
300
- return this.executeRequest(path, options);
301
- }
302
- /**
303
- * Execute the actual HTTP request (internal implementation)
304
- */
305
- async executeRequest(path, options) {
306
193
  const { method = 'GET', headers = {}, body, timeout = this.config.timeout, } = options;
307
194
  const url = `${this.config.apiBaseUrl}${path}`;
308
195
  const requestHeaders = await this.getDefaultHeaders(headers, body !== undefined);
@@ -340,21 +227,6 @@ class HttpClient {
340
227
  throw new SparkVaultError(error instanceof Error ? error.message : 'Unknown error', 'unknown_error');
341
228
  }
342
229
  }
343
- /**
344
- * Check if an error is safe to retry
345
- * Per CLAUDE.md §7: Only retry on transient/network errors, not client errors
346
- */
347
- isRetryableError(error) {
348
- // Network errors are retryable
349
- if (error instanceof NetworkError || error instanceof TimeoutError) {
350
- return true;
351
- }
352
- // 5xx server errors and 429 rate limits are retryable
353
- if (error instanceof SparkVaultError && error.statusCode !== undefined) {
354
- return error.statusCode >= 500 || error.statusCode === 429;
355
- }
356
- return false;
357
- }
358
230
  async parseResponse(response) {
359
231
  // Handle empty responses (204 No Content, etc.)
360
232
  // Callers expecting no body should use <void> as the generic type parameter.
@@ -418,69 +290,9 @@ class HttpClient {
418
290
  post(path, body, options) {
419
291
  return this.request(path, { ...options, method: 'POST', body });
420
292
  }
421
- put(path, body, options) {
422
- return this.request(path, { ...options, method: 'PUT', body });
423
- }
424
- patch(path, body, options) {
425
- return this.request(path, { ...options, method: 'PATCH', body });
426
- }
427
293
  delete(path, options) {
428
294
  return this.request(path, { ...options, method: 'DELETE' });
429
295
  }
430
- /**
431
- * Request raw binary data (e.g., file downloads).
432
- * Returns a Blob instead of parsed JSON.
433
- */
434
- async requestRaw(path, options = {}) {
435
- const { retry } = options;
436
- // Per CLAUDE.md §7: Wrap with retry logic if enabled
437
- if (retry) {
438
- const retryOptions = typeof retry === 'object' ? retry : {};
439
- return withRetry(() => this.executeRequestRaw(path, options), {
440
- ...retryOptions,
441
- isRetryable: (error) => this.isRetryableError(error),
442
- });
443
- }
444
- return this.executeRequestRaw(path, options);
445
- }
446
- /**
447
- * Execute the actual raw HTTP request (internal implementation)
448
- */
449
- async executeRequestRaw(path, options) {
450
- const { method = 'GET', headers = {}, body, timeout = this.config.timeout, } = options;
451
- const url = `${this.config.apiBaseUrl}${path}`;
452
- const requestHeaders = await this.getDefaultHeaders(headers, body !== undefined);
453
- const controller = new AbortController();
454
- const timeoutId = setTimeout(() => controller.abort(), timeout);
455
- try {
456
- const response = await fetch(url, {
457
- method,
458
- headers: requestHeaders,
459
- body: body ? JSON.stringify(body) : undefined,
460
- signal: controller.signal,
461
- });
462
- clearTimeout(timeoutId);
463
- if (!response.ok) {
464
- // Try to parse error as JSON
465
- const errorData = await response.json().catch(() => ({}));
466
- throw this.createErrorFromResponse(response.status, errorData);
467
- }
468
- return response.blob();
469
- }
470
- catch (error) {
471
- clearTimeout(timeoutId);
472
- if (error instanceof SparkVaultError) {
473
- throw error;
474
- }
475
- if (error instanceof DOMException && error.name === 'AbortError') {
476
- throw new TimeoutError();
477
- }
478
- if (error instanceof TypeError) {
479
- throw new NetworkError('Network request failed. Please check your connection.');
480
- }
481
- throw new SparkVaultError(error instanceof Error ? error.message : 'Unknown error', 'unknown_error');
482
- }
483
- }
484
296
  }
485
297
 
486
298
  class HealthModule {
@@ -557,6 +369,37 @@ class HealthModule {
557
369
  */
558
370
  /** Default request timeout in milliseconds (30 seconds). */
559
371
  const DEFAULT_TIMEOUT_MS = 30000;
372
+ /**
373
+ * Combine a fresh timeout with a session close signal into one AbortSignal.
374
+ *
375
+ * The returned dispose() MUST run in a finally block: it clears the timeout
376
+ * and unlinks the close listener (the fallback path for browsers without
377
+ * AbortSignal.any) so nothing leaks across requests. Callers discriminate
378
+ * close-vs-timeout afterwards by checking the close signal's aborted flag.
379
+ */
380
+ function combineTimeoutAndCloseSignals(timeoutMs, closeSignal) {
381
+ const timeoutController = new AbortController();
382
+ const timeoutId = setTimeout(() => timeoutController.abort(), timeoutMs);
383
+ let signal;
384
+ let onCloseAbort = null;
385
+ if ('any' in AbortSignal) {
386
+ signal = AbortSignal.any([timeoutController.signal, closeSignal]);
387
+ }
388
+ else {
389
+ signal = timeoutController.signal;
390
+ onCloseAbort = () => timeoutController.abort();
391
+ closeSignal.addEventListener('abort', onCloseAbort);
392
+ }
393
+ return {
394
+ signal,
395
+ dispose: () => {
396
+ clearTimeout(timeoutId);
397
+ if (onCloseAbort) {
398
+ closeSignal.removeEventListener('abort', onCloseAbort);
399
+ }
400
+ },
401
+ };
402
+ }
560
403
  class SparkVaultApi {
561
404
  constructor(timeoutMs = DEFAULT_TIMEOUT_MS) {
562
405
  /**
@@ -603,24 +446,7 @@ class SparkVaultApi {
603
446
  if (localCloseController.signal.aborted) {
604
447
  throw this.makeError('Request cancelled', 'cancelled', 0);
605
448
  }
606
- const timeoutController = new AbortController();
607
- const timeoutId = setTimeout(() => timeoutController.abort(), this.timeoutMs);
608
- let combinedSignal;
609
- let onCloseAbort = null;
610
- if ('any' in AbortSignal) {
611
- combinedSignal = AbortSignal.any([
612
- timeoutController.signal,
613
- localCloseController.signal,
614
- ]);
615
- }
616
- else {
617
- // Fallback for browsers without AbortSignal.any: link the close
618
- // signal into the timeout controller manually. Listener is removed
619
- // in the finally block so it doesn't leak across requests.
620
- combinedSignal = timeoutController.signal;
621
- onCloseAbort = () => timeoutController.abort();
622
- localCloseController.signal.addEventListener('abort', onCloseAbort);
623
- }
449
+ const { signal: combinedSignal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, localCloseController.signal);
624
450
  try {
625
451
  // Only send Content-Type when there's actually a body — otherwise GETs
626
452
  // with no payload would carry a misleading content-type header.
@@ -662,10 +488,7 @@ class SparkVaultApi {
662
488
  throw this.makeError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
663
489
  }
664
490
  finally {
665
- clearTimeout(timeoutId);
666
- if (onCloseAbort) {
667
- localCloseController.signal.removeEventListener('abort', onCloseAbort);
668
- }
491
+ dispose();
669
492
  }
670
493
  }
671
494
  }
@@ -872,9 +695,7 @@ function base64urlToArrayBuffer(base64url) {
872
695
  * @returns Decoded UTF-8 string
873
696
  */
874
697
  function base64urlToString(base64url) {
875
- const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
876
- const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
877
- return atob(padded);
698
+ return new TextDecoder().decode(base64urlDecode(base64url));
878
699
  }
879
700
 
880
701
  /**
@@ -1351,8 +1172,7 @@ function enrichMethods(ids) {
1351
1172
  /**
1352
1173
  * Verification State Manager
1353
1174
  *
1354
- * Single source of truth for all verification flow state.
1355
- * Centralizes scattered state from IdentityRenderer for:
1175
+ * Single source of truth for all verification flow state:
1356
1176
  * - Predictable state transitions
1357
1177
  * - Easier debugging and testing
1358
1178
  * - Clear data ownership
@@ -1382,25 +1202,6 @@ class VerificationState {
1382
1202
  kindling: '',
1383
1203
  method: null,
1384
1204
  };
1385
- // State change listeners for reactivity
1386
- this.listeners = new Set();
1387
- }
1388
- /**
1389
- * Subscribe to state changes
1390
- * @param listener - Callback invoked on state change
1391
- * @returns Unsubscribe function
1392
- */
1393
- subscribe(listener) {
1394
- this.listeners.add(listener);
1395
- return () => this.listeners.delete(listener);
1396
- }
1397
- /**
1398
- * Notify all listeners of state change
1399
- */
1400
- notify() {
1401
- for (const listener of this.listeners) {
1402
- listener(this._viewState);
1403
- }
1404
1205
  }
1405
1206
  // --- SDK Config ---
1406
1207
  get sdkConfig() {
@@ -1412,24 +1213,6 @@ class VerificationState {
1412
1213
  get accountId() {
1413
1214
  return this._sdkConfig?.accountId ?? '';
1414
1215
  }
1415
- /**
1416
- * Get enriched methods filtered by the fallback identifier type.
1417
- */
1418
- getAvailableMethods() {
1419
- if (!this._sdkConfig)
1420
- return [];
1421
- const methodIds = this._sdkConfig.methods ?? [];
1422
- let methods = enrichMethods(methodIds);
1423
- // Filter by identifier type. Passkeys are SVID-scoped and remain
1424
- // available regardless of whether the fallback identifier is email or phone.
1425
- if (this._identityType === 'phone') {
1426
- methods = methods.filter((m) => m.type === 'passkey' || m.identityType === 'phone');
1427
- }
1428
- else {
1429
- methods = methods.filter((m) => m.identityType === 'email' || m.identityType === undefined);
1430
- }
1431
- return methods;
1432
- }
1433
1216
  /**
1434
1217
  * Check if passkey method is enabled in config
1435
1218
  */
@@ -1442,7 +1225,6 @@ class VerificationState {
1442
1225
  }
1443
1226
  setViewState(state) {
1444
1227
  this._viewState = state;
1445
- this.notify();
1446
1228
  }
1447
1229
  // --- Identity ---
1448
1230
  get recipient() {
@@ -1518,21 +1300,6 @@ class VerificationState {
1518
1300
  setTotpMethod(method) {
1519
1301
  this._totp.method = method;
1520
1302
  }
1521
- // --- Reset ---
1522
- /**
1523
- * Reset state for new verification attempt
1524
- */
1525
- reset() {
1526
- this._viewState = { view: 'loading' };
1527
- this._recipient = '';
1528
- this._identityType = 'email';
1529
- this._authContext = undefined;
1530
- this._passkey.hasPasskey = null;
1531
- this._passkey.isFallbackMode = false;
1532
- this._passkey.pendingResult = null;
1533
- this._totp.kindling = '';
1534
- this._totp.method = null;
1535
- }
1536
1303
  }
1537
1304
 
1538
1305
  /**
@@ -6897,7 +6664,7 @@ class IdentityRenderer {
6897
6664
  }
6898
6665
  }
6899
6666
 
6900
- /* global HTMLIFrameElement */
6667
+ /* global HTMLIFrameElement requestAnimationFrame */
6901
6668
  /**
6902
6669
  * Widget Embedder
6903
6670
  *
@@ -6945,6 +6712,7 @@ class WidgetEmbedder {
6945
6712
  // against — never the broader sparkvault.com family.
6946
6713
  this.trustedOrigin = new URL(this.config.identityBaseUrl).origin;
6947
6714
  this.boundHandleMessage = (event) => this.handleMessage(event);
6715
+ this.boundHandleCspViolation = (event) => this.handleCspViolation(event);
6948
6716
  }
6949
6717
  start() {
6950
6718
  const iframe = document.createElement('iframe');
@@ -6964,6 +6732,12 @@ class WidgetEmbedder {
6964
6732
  'background:transparent',
6965
6733
  'z-index:2147483647',
6966
6734
  ].join(';');
6735
+ // Promote to its own compositing layer up front. iOS Safari can otherwise
6736
+ // leave a freshly-inserted fixed, full-viewport iframe loaded but UNPAINTED
6737
+ // until the next composite (a scroll, resize, or app foreground) — the
6738
+ // frame even runs, but the dialog only appears after an app switch.
6739
+ iframe.style.transform = 'translateZ(0)';
6740
+ iframe.style.willChange = 'transform';
6967
6741
  // A network-level load failure (DNS, connection reset) fires onerror; an
6968
6742
  // HTTP error body or a frame blocked from framing does not, which is what
6969
6743
  // the readiness timeout below covers.
@@ -6973,9 +6747,36 @@ class WidgetEmbedder {
6973
6747
  this.previousBodyOverflow = document.body.style.overflow;
6974
6748
  document.body.style.overflow = 'hidden';
6975
6749
  window.addEventListener('message', this.boundHandleMessage);
6750
+ // A host-page CSP whose frame-src/child-src omits the Identity origin blocks
6751
+ // the iframe before it can load and fires no `onerror`. Catch the violation
6752
+ // so we fail over to the in-page flow at once instead of after the timeout.
6753
+ document.addEventListener('securitypolicyviolation', this.boundHandleCspViolation);
6976
6754
  document.body.appendChild(iframe);
6755
+ // Force the composite the iframe insertion may not have triggered on iOS,
6756
+ // so the dialog paints on the click rather than only after an app switch.
6757
+ this.forceComposite(iframe);
6977
6758
  this.readyTimer = setTimeout(() => this.handleFrameUnavailable(), FRAME_READY_TIMEOUT_MS);
6978
6759
  }
6760
+ /**
6761
+ * Nudge the browser to paint the just-inserted iframe on the next frame.
6762
+ * Reading layout forces a reflow; toggling a transform forces the compositor
6763
+ * to flush the new layer — the workaround for iOS Safari leaving a fixed
6764
+ * full-viewport iframe invisible until an unrelated repaint.
6765
+ */
6766
+ forceComposite(iframe) {
6767
+ const paint = () => {
6768
+ if (!this.iframe)
6769
+ return;
6770
+ void iframe.offsetHeight;
6771
+ iframe.style.transform = 'translateZ(0) scale(1)';
6772
+ };
6773
+ if (typeof requestAnimationFrame === 'function') {
6774
+ requestAnimationFrame(paint);
6775
+ }
6776
+ else {
6777
+ setTimeout(paint, 16);
6778
+ }
6779
+ }
6979
6780
  close() {
6980
6781
  this.clearReadyTimer();
6981
6782
  if (this.iframe?.parentNode) {
@@ -6983,8 +6784,22 @@ class WidgetEmbedder {
6983
6784
  }
6984
6785
  this.iframe = null;
6985
6786
  window.removeEventListener('message', this.boundHandleMessage);
6787
+ document.removeEventListener('securitypolicyviolation', this.boundHandleCspViolation);
6986
6788
  document.body.style.overflow = this.previousBodyOverflow;
6987
6789
  }
6790
+ /**
6791
+ * Host CSP blocked the widget iframe (frame-src/child-src). The frame can
6792
+ * never load, so fail over to the in-page flow immediately.
6793
+ */
6794
+ handleCspViolation(event) {
6795
+ const directive = event.effectiveDirective || event.violatedDirective;
6796
+ if (directive !== 'frame-src' && directive !== 'child-src')
6797
+ return;
6798
+ // blockedURI is the framed URL (sometimes just its origin); match either.
6799
+ if (typeof event.blockedURI === 'string' && event.blockedURI.startsWith(this.trustedOrigin)) {
6800
+ this.handleFrameUnavailable();
6801
+ }
6802
+ }
6988
6803
  clearReadyTimer() {
6989
6804
  if (this.readyTimer !== null) {
6990
6805
  clearTimeout(this.readyTimer);
@@ -7041,6 +6856,26 @@ class WidgetEmbedder {
7041
6856
  this.close();
7042
6857
  window.location.href = url.toString();
7043
6858
  }
6859
+ /**
6860
+ * Navigate the host top window to a widget-supplied URL — only when it
6861
+ * resolves to http(s). The sender is already constrained to the trusted
6862
+ * widget origin, but defense-in-depth across the SparkVault->customer
6863
+ * boundary: compromised widget-origin code must never escalate into script
6864
+ * execution on the embedding page via a javascript:/data: navigation.
6865
+ */
6866
+ safeNavigate(url) {
6867
+ let resolved;
6868
+ try {
6869
+ resolved = new URL(url, window.location.href);
6870
+ }
6871
+ catch {
6872
+ return;
6873
+ }
6874
+ if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') {
6875
+ return;
6876
+ }
6877
+ window.location.href = resolved.href;
6878
+ }
7044
6879
  buildUrl() {
7045
6880
  const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/widget`);
7046
6881
  url.searchParams.set('origin', window.location.origin);
@@ -7091,7 +6926,7 @@ class WidgetEmbedder {
7091
6926
  // iframe; on return the host SDK consumes the redirect token.
7092
6927
  if (data.type === REDIRECT_TYPE && typeof data.url === 'string') {
7093
6928
  this.clearReadyTimer();
7094
- window.location.href = data.url;
6929
+ this.safeNavigate(data.url);
7095
6930
  return;
7096
6931
  }
7097
6932
  if (data.type !== RESULT_TYPE || this.settled)
@@ -7104,7 +6939,7 @@ class WidgetEmbedder {
7104
6939
  // Mirror the renderer's belt-and-suspenders: complete a server-issued
7105
6940
  // redirect from the host's own top window if the customer didn't.
7106
6941
  if (typeof result.redirect === 'string' && result.redirect) {
7107
- window.location.href = result.redirect;
6942
+ this.safeNavigate(result.redirect);
7108
6943
  }
7109
6944
  }
7110
6945
  else if (data.cancelled) {
@@ -7307,6 +7142,7 @@ class InlineContainer {
7307
7142
  }
7308
7143
  }
7309
7144
 
7145
+ /* global Element */
7310
7146
  /**
7311
7147
  * DOM Utilities
7312
7148
  *
@@ -7355,8 +7191,62 @@ function onBodyReady(callback) {
7355
7191
  }
7356
7192
  }
7357
7193
  }
7194
+ /**
7195
+ * Attach a click handler to every element matching `selector` — both elements
7196
+ * present once the DOM is ready and elements added later (observed via
7197
+ * MutationObserver).
7198
+ *
7199
+ * Each call is fully self-contained: the element bookkeeping lives in this
7200
+ * closure, so the returned cleanup removes only the listeners this call
7201
+ * registered. Multiple attachments — different selectors, or even the same
7202
+ * element attached twice — never interfere with one another.
7203
+ *
7204
+ * @param selector - CSS selector for elements to attach to
7205
+ * @param onClick - Click handler to register on every matching element
7206
+ * @returns Cleanup function that removes this call's listeners and observer
7207
+ */
7208
+ function attachClickHandler(selector, onClick) {
7209
+ let observer = null;
7210
+ let cleanedUp = false;
7211
+ const attached = new Map();
7212
+ const listen = (element) => {
7213
+ if (attached.has(element))
7214
+ return;
7215
+ element.addEventListener('click', onClick);
7216
+ attached.set(element, () => element.removeEventListener('click', onClick));
7217
+ };
7218
+ // Defer attachment until the DOM is ready so the selector can match.
7219
+ onDomReady(() => {
7220
+ // Cleanup can run before the DOM is ready; attaching afterwards would
7221
+ // register listeners that nothing could ever remove.
7222
+ if (cleanedUp)
7223
+ return;
7224
+ document.querySelectorAll(selector).forEach(listen);
7225
+ // Watch for dynamically added elements
7226
+ observer = new MutationObserver((mutations) => {
7227
+ mutations.forEach((mutation) => {
7228
+ mutation.addedNodes.forEach((node) => {
7229
+ if (node instanceof Element) {
7230
+ if (node.matches(selector))
7231
+ listen(node);
7232
+ node.querySelectorAll(selector).forEach(listen);
7233
+ }
7234
+ });
7235
+ });
7236
+ });
7237
+ // Use onBodyReady to handle edge cases where body isn't available yet
7238
+ onBodyReady(() => {
7239
+ observer?.observe(document.body, { childList: true, subtree: true });
7240
+ });
7241
+ });
7242
+ return () => {
7243
+ cleanedUp = true;
7244
+ observer?.disconnect();
7245
+ attached.forEach((removeListener) => removeListener());
7246
+ attached.clear();
7247
+ };
7248
+ }
7358
7249
 
7359
- /* global Element */
7360
7250
  /**
7361
7251
  * Identity Module
7362
7252
  *
@@ -7391,7 +7281,6 @@ class IdentityModule {
7391
7281
  constructor(config) {
7392
7282
  this.renderer = null;
7393
7283
  this.embedder = null;
7394
- this.attachedElements = new Map();
7395
7284
  this.config = config;
7396
7285
  this.api = new IdentityApi(config);
7397
7286
  // Preload config in background for instant dialog opening
@@ -7518,7 +7407,6 @@ class IdentityModule {
7518
7407
  * cleanup();
7519
7408
  */
7520
7409
  attach(selector, options = {}) {
7521
- let observer = null;
7522
7410
  const handleClick = async (event) => {
7523
7411
  event.preventDefault();
7524
7412
  try {
@@ -7535,48 +7423,10 @@ class IdentityModule {
7535
7423
  // Error already handled by callbacks or will use server redirect
7536
7424
  }
7537
7425
  };
7538
- const attachToElements = () => {
7539
- const elements = document.querySelectorAll(selector);
7540
- elements.forEach((element) => {
7541
- element.addEventListener('click', handleClick);
7542
- this.attachedElements.set(element, () => {
7543
- element.removeEventListener('click', handleClick);
7544
- });
7545
- });
7546
- // Watch for dynamically added elements
7547
- observer = new MutationObserver((mutations) => {
7548
- mutations.forEach((mutation) => {
7549
- mutation.addedNodes.forEach((node) => {
7550
- if (node instanceof Element) {
7551
- if (node.matches(selector)) {
7552
- node.addEventListener('click', handleClick);
7553
- this.attachedElements.set(node, () => {
7554
- node.removeEventListener('click', handleClick);
7555
- });
7556
- }
7557
- // Check descendants
7558
- node.querySelectorAll(selector).forEach((el) => {
7559
- if (!this.attachedElements.has(el)) {
7560
- el.addEventListener('click', handleClick);
7561
- this.attachedElements.set(el, () => {
7562
- el.removeEventListener('click', handleClick);
7563
- });
7564
- }
7565
- });
7566
- }
7567
- });
7568
- });
7569
- });
7570
- // Observe document.body for dynamic elements
7571
- // Use onBodyReady to handle edge cases where body isn't available yet
7572
- onBodyReady(() => {
7573
- observer?.observe(document.body, { childList: true, subtree: true });
7574
- });
7575
- };
7576
- // Defer attachment until DOM is ready, then complete any full-page
7577
- // social-login redirect result before the user has to click again.
7426
+ const cleanup = attachClickHandler(selector, handleClick);
7427
+ // Once the DOM is ready (after the click listeners attach), complete any
7428
+ // full-page social-login redirect result before the user has to click again.
7578
7429
  onDomReady(() => {
7579
- attachToElements();
7580
7430
  this.consumeRedirectResult()
7581
7431
  .then((result) => {
7582
7432
  if (result)
@@ -7586,12 +7436,7 @@ class IdentityModule {
7586
7436
  options.onError?.(error instanceof Error ? error : new Error(String(error)));
7587
7437
  });
7588
7438
  });
7589
- // Return cleanup function
7590
- return () => {
7591
- observer?.disconnect();
7592
- this.attachedElements.forEach((cleanup) => cleanup());
7593
- this.attachedElements.clear();
7594
- };
7439
+ return cleanup;
7595
7440
  }
7596
7441
  /**
7597
7442
  * Verify and decode an identity token.
@@ -7638,29 +7483,56 @@ class IdentityModule {
7638
7483
  if (!token) {
7639
7484
  return null;
7640
7485
  }
7641
- const expectedState = sessionStorage.getItem('sv_oauth_state');
7642
- if (expectedState && params.get('state') !== expectedState) {
7643
- throw new ValidationError('Invalid OAuth state');
7644
- }
7645
- const claims = await this.verifyToken(token);
7646
- const result = {
7647
- token,
7648
- identity: claims.identity,
7649
- identityType: claims.identity_type,
7650
- svid: claims.svid,
7651
- sessionId: claims.session_id,
7652
- };
7653
- if (typeof window.history?.replaceState === 'function') {
7654
- window.history.replaceState(window.history.state, document.title, `${window.location.pathname}${window.location.search}`);
7486
+ // Once a token is present it must be consumed exactly once: the hash and
7487
+ // one-shot OAuth state are cleared whether validation succeeds or fails.
7488
+ // A failing token left in the URL would make every subsequent verify()
7489
+ // re-consume and re-reject it before the dialog could ever open — login
7490
+ // would stay wedged until the user manually edited the URL.
7491
+ try {
7492
+ let expectedState = null;
7493
+ try {
7494
+ expectedState = sessionStorage.getItem('sv_oauth_state');
7495
+ }
7496
+ catch {
7497
+ // Storage disabled (private mode): proceed; the backend still binds state.
7498
+ }
7499
+ if (expectedState && params.get('state') !== expectedState) {
7500
+ throw new ValidationError('Invalid OAuth state');
7501
+ }
7502
+ const claims = await this.verifyToken(token);
7503
+ return {
7504
+ token,
7505
+ identity: claims.identity,
7506
+ identityType: claims.identity_type,
7507
+ svid: claims.svid,
7508
+ sessionId: claims.session_id,
7509
+ };
7510
+ }
7511
+ finally {
7512
+ if (typeof window.history?.replaceState === 'function') {
7513
+ window.history.replaceState(window.history.state, document.title, `${window.location.pathname}${window.location.search}`);
7514
+ }
7515
+ try {
7516
+ sessionStorage.removeItem('sv_oauth_state');
7517
+ sessionStorage.removeItem('sv_oauth_email');
7518
+ }
7519
+ catch {
7520
+ // Storage disabled (private mode): nothing to clear.
7521
+ }
7655
7522
  }
7656
- sessionStorage.removeItem('sv_oauth_state');
7657
- sessionStorage.removeItem('sv_oauth_email');
7658
- return result;
7659
7523
  }
7660
7524
  /**
7661
7525
  * Close the identity dialog/inline UI if open.
7526
+ *
7527
+ * Tears down whichever surface is active: the hosted-widget iframe
7528
+ * (default dialog mode — also releases the embedder's host scroll lock)
7529
+ * or the local renderer (inline / local mode).
7662
7530
  */
7663
7531
  close() {
7532
+ if (this.embedder) {
7533
+ this.embedder.close();
7534
+ this.embedder = null;
7535
+ }
7664
7536
  if (this.renderer) {
7665
7537
  this.renderer.close();
7666
7538
  this.renderer = null;
@@ -7773,6 +7645,15 @@ function isInitiateUploadResponse(data) {
7773
7645
  }
7774
7646
  /** tus protocol version used for the resumable upload session. */
7775
7647
  const TUS_VERSION = '1.0.0';
7648
+ /** Default TUS chunk size; the server may override via `X-Chunk-Size`. */
7649
+ const DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024;
7650
+ /**
7651
+ * Abort a stalled chunk PATCH after this long with no upload progress.
7652
+ * XHR's own `timeout` measures total request duration, which would abort a
7653
+ * slow-but-progressing 50MB chunk — so a chunk fails only after the
7654
+ * connection has been completely silent for the full window.
7655
+ */
7656
+ const CHUNK_INACTIVITY_TIMEOUT_MS = 60000;
7776
7657
  /**
7777
7658
  * Server-side finalization confirmation poll.
7778
7659
  *
@@ -7855,6 +7736,167 @@ class UploadApi extends SparkVaultApi {
7855
7736
  ingotId: response.data.ingot_id,
7856
7737
  };
7857
7738
  }
7739
+ /**
7740
+ * Upload a file to Forge over the TUS resumable protocol (v1.0.0).
7741
+ *
7742
+ * The single canonical browser transfer path — the upload widget and the
7743
+ * authenticated `uploadIngot` flow both go through here (CLAUDE.md: one
7744
+ * transfer path). Creates the session, PATCHes chunks sized by the server's
7745
+ * `X-Chunk-Size` (50MB default, which keeps every request under CDN body
7746
+ * caps such as Cloudflare's 100MB), validates every server-reported offset,
7747
+ * and honors the session abort signal plus per-request timeouts.
7748
+ *
7749
+ * Returns the TUS session URL so the caller can confirm server-side
7750
+ * finalization via {@link verifyUploadFinalized} before reporting success.
7751
+ */
7752
+ async uploadFileToForge(file, forgeUrl, onProgress) {
7753
+ if (typeof XMLHttpRequest === 'undefined') {
7754
+ throw new UploadApiError('XMLHttpRequest is required for browser uploads', 'environment_unsupported', 0);
7755
+ }
7756
+ const url = new URL(forgeUrl);
7757
+ const istk = url.searchParams.get('istk');
7758
+ if (!istk) {
7759
+ throw new UploadApiError('Forge upload URL is missing ISTK', 'invalid_forge_url', 0);
7760
+ }
7761
+ const session = await this.createTusSession(`${url.origin}${url.pathname}`, istk, file.size);
7762
+ const uploadUrl = session.location.startsWith('http')
7763
+ ? session.location
7764
+ : `${url.origin}${session.location}`;
7765
+ let offset = 0;
7766
+ while (offset < file.size) {
7767
+ if (this.isAborted()) {
7768
+ throw new UploadApiError('Upload cancelled', 'cancelled', 0);
7769
+ }
7770
+ const chunkEnd = Math.min(offset + session.chunkSize, file.size);
7771
+ offset = await this.patchChunk(uploadUrl, file.slice(offset, chunkEnd), offset, file.size, onProgress);
7772
+ }
7773
+ return uploadUrl;
7774
+ }
7775
+ /**
7776
+ * Create the TUS upload session. Forge reads only `Tus-Resumable`,
7777
+ * `Upload-Length`, and `X-ISTK` on create, and returns the session URL in
7778
+ * `Location` (possibly relative) plus its chunk size in `X-Chunk-Size`.
7779
+ */
7780
+ async createTusSession(endpoint, istk, totalSize) {
7781
+ const closeSignal = this.getAbortSignal();
7782
+ const { signal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, closeSignal);
7783
+ try {
7784
+ const response = await fetch(endpoint, {
7785
+ method: 'POST',
7786
+ headers: {
7787
+ 'Tus-Resumable': TUS_VERSION,
7788
+ 'Upload-Length': String(totalSize),
7789
+ 'X-ISTK': istk,
7790
+ },
7791
+ signal,
7792
+ });
7793
+ if (!response.ok) {
7794
+ const errorText = await response.text().catch(() => '');
7795
+ throw new UploadApiError(`Failed to create upload session: ${response.status} ${errorText}`, 'tus_create_failed', response.status);
7796
+ }
7797
+ const location = response.headers.get('Location');
7798
+ if (!location) {
7799
+ throw new UploadApiError('Server did not return upload location', 'tus_create_failed', response.status);
7800
+ }
7801
+ const chunkSizeHeader = response.headers.get('X-Chunk-Size');
7802
+ const chunkSize = chunkSizeHeader ? parseInt(chunkSizeHeader, 10) : NaN;
7803
+ return {
7804
+ location,
7805
+ chunkSize: Number.isFinite(chunkSize) && chunkSize > 0 ? chunkSize : DEFAULT_CHUNK_SIZE,
7806
+ };
7807
+ }
7808
+ catch (error) {
7809
+ if (error instanceof SparkVaultError)
7810
+ throw error;
7811
+ if (error != null && typeof error === 'object' && 'name' in error && error.name === 'AbortError') {
7812
+ if (this.isAborted()) {
7813
+ throw new UploadApiError('Upload cancelled', 'cancelled', 0);
7814
+ }
7815
+ throw new UploadApiError(`Upload session creation timed out after ${this.timeoutMs}ms`, 'timeout', 0);
7816
+ }
7817
+ if (error instanceof TypeError) {
7818
+ throw new UploadApiError('Unable to connect. Please check your connection and try again.', 'network_error', 0);
7819
+ }
7820
+ throw new UploadApiError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
7821
+ }
7822
+ finally {
7823
+ dispose();
7824
+ }
7825
+ }
7826
+ /**
7827
+ * PATCH one chunk with XMLHttpRequest (fetch exposes no upload progress).
7828
+ * Resolves with the server-confirmed offset for the next iteration.
7829
+ *
7830
+ * The server's `Upload-Offset` is validated, never trusted: it must be a
7831
+ * finite number that strictly advances past this chunk's start (this client
7832
+ * never sends an empty chunk, so a non-advancing 2xx would loop forever)
7833
+ * and never exceeds the file size (an inflated offset would skip real
7834
+ * chunks and report a partial upload as success).
7835
+ */
7836
+ patchChunk(uploadUrl, chunk, chunkStart, totalSize, onProgress) {
7837
+ return new Promise((resolve, reject) => {
7838
+ const closeSignal = this.getAbortSignal();
7839
+ if (closeSignal.aborted) {
7840
+ reject(new UploadApiError('Upload cancelled', 'cancelled', 0));
7841
+ return;
7842
+ }
7843
+ const xhr = new XMLHttpRequest();
7844
+ let settled = false;
7845
+ let timedOut = false;
7846
+ let watchdog = null;
7847
+ const onCloseAbort = () => xhr.abort();
7848
+ const finish = (settle) => {
7849
+ if (settled)
7850
+ return;
7851
+ settled = true;
7852
+ if (watchdog !== null)
7853
+ clearTimeout(watchdog);
7854
+ closeSignal.removeEventListener('abort', onCloseAbort);
7855
+ settle();
7856
+ };
7857
+ const resetWatchdog = () => {
7858
+ if (settled)
7859
+ return;
7860
+ if (watchdog !== null)
7861
+ clearTimeout(watchdog);
7862
+ watchdog = setTimeout(() => {
7863
+ timedOut = true;
7864
+ xhr.abort();
7865
+ }, CHUNK_INACTIVITY_TIMEOUT_MS);
7866
+ };
7867
+ closeSignal.addEventListener('abort', onCloseAbort);
7868
+ xhr.upload.onprogress = (event) => {
7869
+ resetWatchdog();
7870
+ if (event.lengthComputable) {
7871
+ onProgress?.(chunkStart + event.loaded, totalSize);
7872
+ }
7873
+ };
7874
+ xhr.onload = () => {
7875
+ if (xhr.status >= 200 && xhr.status < 300) {
7876
+ const header = xhr.getResponseHeader('Upload-Offset');
7877
+ const newOffset = header !== null ? parseInt(header, 10) : NaN;
7878
+ if (!Number.isFinite(newOffset) || newOffset <= chunkStart || newOffset > totalSize) {
7879
+ finish(() => reject(new UploadApiError(`Server returned invalid upload offset (${newOffset})`, 'invalid_offset', xhr.status)));
7880
+ return;
7881
+ }
7882
+ finish(() => resolve(newOffset));
7883
+ }
7884
+ else {
7885
+ finish(() => reject(new UploadApiError(`Chunk upload failed with status ${xhr.status}`, 'chunk_upload_failed', xhr.status)));
7886
+ }
7887
+ };
7888
+ xhr.onerror = () => finish(() => reject(new UploadApiError('Chunk upload failed', 'network_error', 0)));
7889
+ xhr.onabort = () => finish(() => reject(timedOut
7890
+ ? new UploadApiError(`Chunk upload timed out after ${CHUNK_INACTIVITY_TIMEOUT_MS}ms of inactivity`, 'timeout', 0)
7891
+ : new UploadApiError('Upload cancelled', 'cancelled', 0)));
7892
+ xhr.open('PATCH', uploadUrl);
7893
+ xhr.setRequestHeader('Tus-Resumable', TUS_VERSION);
7894
+ xhr.setRequestHeader('Upload-Offset', String(chunkStart));
7895
+ xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream');
7896
+ resetWatchdog();
7897
+ xhr.send(chunk);
7898
+ });
7899
+ }
7858
7900
  /**
7859
7901
  * Confirm the upload was finalized SERVER-SIDE before reporting success.
7860
7902
  *
@@ -7901,21 +7943,7 @@ class UploadApi extends SparkVaultApi {
7901
7943
  */
7902
7944
  async headUploadOffset(uploadUrl) {
7903
7945
  const closeSignal = this.getAbortSignal();
7904
- const timeoutController = new AbortController();
7905
- const timeoutId = setTimeout(() => timeoutController.abort(), this.timeoutMs);
7906
- // Combine timeout + session-close into one signal. Mirror the base
7907
- // client's fallback for browsers without AbortSignal.any: link the close
7908
- // signal into the timeout controller and remove the listener in finally.
7909
- let combinedSignal;
7910
- let onCloseAbort = null;
7911
- if ('any' in AbortSignal) {
7912
- combinedSignal = AbortSignal.any([timeoutController.signal, closeSignal]);
7913
- }
7914
- else {
7915
- combinedSignal = timeoutController.signal;
7916
- onCloseAbort = () => timeoutController.abort();
7917
- closeSignal.addEventListener('abort', onCloseAbort);
7918
- }
7946
+ const { signal: combinedSignal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, closeSignal);
7919
7947
  try {
7920
7948
  const response = await fetch(uploadUrl, {
7921
7949
  method: 'HEAD',
@@ -7947,14 +7975,175 @@ class UploadApi extends SparkVaultApi {
7947
7975
  throw new UploadApiError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
7948
7976
  }
7949
7977
  finally {
7950
- clearTimeout(timeoutId);
7951
- if (onCloseAbort) {
7952
- closeSignal.removeEventListener('abort', onCloseAbort);
7953
- }
7978
+ dispose();
7954
7979
  }
7955
7980
  }
7956
7981
  }
7957
7982
 
7983
+ /**
7984
+ * Upload Widget Chrome
7985
+ *
7986
+ * Shared DOM builders for the branded chrome both upload containers render:
7987
+ * brand header, "Secured by SparkVault" footer, and the Triple Zero-Trust
7988
+ * security sidebar. One canonical copy — any branding/marketing/security-text
7989
+ * change lands here and reaches modal and inline modes alike.
7990
+ */
7991
+ /**
7992
+ * Build the branded header. Returns the close button (when rendered) so the
7993
+ * container can detach `onClose` in its destroy() cleanup.
7994
+ */
7995
+ function createBrandHeader(options) {
7996
+ const { branding, isDarkMode, withCloseButton, titleId, onClose } = options;
7997
+ const header = document.createElement('div');
7998
+ header.className = 'svu-header';
7999
+ const titleContainer = document.createElement('div');
8000
+ titleContainer.className = 'svu-header-title';
8001
+ // Use light logo for light theme (default), dark logo for dark mode
8002
+ const logoUrl = isDarkMode
8003
+ ? branding.logoDarkUrl || branding.logoLightUrl
8004
+ : branding.logoLightUrl || branding.logoDarkUrl;
8005
+ if (logoUrl) {
8006
+ const logo = document.createElement('img');
8007
+ logo.className = 'svu-logo';
8008
+ logo.src = logoUrl;
8009
+ logo.alt = branding.organizationName;
8010
+ titleContainer.appendChild(logo);
8011
+ // Screen reader title
8012
+ const srTitle = document.createElement('span');
8013
+ srTitle.className = 'svu-sr-only';
8014
+ if (titleId)
8015
+ srTitle.id = titleId;
8016
+ srTitle.textContent = branding.organizationName;
8017
+ titleContainer.appendChild(srTitle);
8018
+ }
8019
+ else if (branding.organizationName) {
8020
+ const companyName = document.createElement('h2');
8021
+ companyName.className = 'svu-company-name';
8022
+ if (titleId)
8023
+ companyName.id = titleId;
8024
+ companyName.textContent = branding.organizationName;
8025
+ titleContainer.appendChild(companyName);
8026
+ }
8027
+ header.appendChild(titleContainer);
8028
+ let closeBtn = null;
8029
+ if (withCloseButton) {
8030
+ closeBtn = document.createElement('button');
8031
+ closeBtn.className = 'svu-close-btn';
8032
+ closeBtn.setAttribute('aria-label', 'Close');
8033
+ closeBtn.innerHTML = `
8034
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8035
+ <path d="M18 6L6 18M6 6l12 12"/>
8036
+ </svg>
8037
+ `;
8038
+ closeBtn.addEventListener('click', onClose);
8039
+ header.appendChild(closeBtn);
8040
+ }
8041
+ return { header, closeBtn };
8042
+ }
8043
+ /** Build the "Secured by SparkVault" footer. */
8044
+ function createFooter() {
8045
+ const footer = document.createElement('div');
8046
+ footer.className = 'svu-footer';
8047
+ const footerText = document.createElement('span');
8048
+ footerText.className = 'svu-footer-text';
8049
+ footerText.appendChild(document.createTextNode('Secured by '));
8050
+ const footerLink = document.createElement('a');
8051
+ footerLink.href = 'https://sparkvault.com';
8052
+ footerLink.target = '_blank';
8053
+ footerLink.rel = 'noopener noreferrer';
8054
+ footerLink.className = 'svu-footer-link';
8055
+ footerLink.textContent = 'SparkVault';
8056
+ footerText.appendChild(footerLink);
8057
+ footer.appendChild(footerText);
8058
+ return footer;
8059
+ }
8060
+ /** Build the Triple Zero-Trust security sidebar shown during dark states. */
8061
+ function createSecuritySidebar(branding) {
8062
+ const sidebar = document.createElement('div');
8063
+ sidebar.className = 'svu-sidebar';
8064
+ // Logo
8065
+ const logoDiv = document.createElement('div');
8066
+ logoDiv.className = 'svu-sidebar-logo';
8067
+ if (branding.logoDarkUrl) {
8068
+ const logo = document.createElement('img');
8069
+ logo.src = branding.logoDarkUrl;
8070
+ logo.alt = branding.organizationName;
8071
+ logoDiv.appendChild(logo);
8072
+ }
8073
+ sidebar.appendChild(logoDiv);
8074
+ // Intro
8075
+ const intro = document.createElement('div');
8076
+ intro.className = 'svu-sidebar-intro';
8077
+ intro.innerHTML = `
8078
+ <h3>Secure File Transfer</h3>
8079
+ <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>
8080
+ `;
8081
+ sidebar.appendChild(intro);
8082
+ // Security details
8083
+ const security = document.createElement('div');
8084
+ security.className = 'svu-sidebar-security';
8085
+ security.innerHTML = `
8086
+ <h4>
8087
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8088
+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
8089
+ </svg>
8090
+ SparkVault's Triple Zero-Trust
8091
+ </h4>
8092
+ <p class="svu-security-intro">
8093
+ Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.
8094
+ </p>
8095
+ <div class="svu-key-chain">
8096
+ <div class="svu-key-item">
8097
+ <div class="svu-key-number">1</div>
8098
+ <div class="svu-key-info">
8099
+ <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>
8100
+ <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>
8101
+ <span class="svu-key-desc">Quantum-resistant key exchange</span>
8102
+ </div>
8103
+ </div>
8104
+ <div class="svu-key-connector">
8105
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8106
+ <path d="M12 5v14M5 12h14"/>
8107
+ </svg>
8108
+ </div>
8109
+ <div class="svu-key-item">
8110
+ <div class="svu-key-number">2</div>
8111
+ <div class="svu-key-info">
8112
+ <span class="svu-key-name">X25519 Ephemeral Key</span>
8113
+ <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>
8114
+ <span class="svu-key-desc">Perfect forward secrecy</span>
8115
+ </div>
8116
+ </div>
8117
+ <div class="svu-key-connector">
8118
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8119
+ <path d="M12 5v14M5 12h14"/>
8120
+ </svg>
8121
+ </div>
8122
+ <div class="svu-key-item">
8123
+ <div class="svu-key-number">3</div>
8124
+ <div class="svu-key-info">
8125
+ <span class="svu-key-name">HKDF-SHA512 Derived Key</span>
8126
+ <span class="svu-key-algo">Hardware-bound key derivation</span>
8127
+ <span class="svu-key-desc">Vault master key in secure enclave</span>
8128
+ </div>
8129
+ </div>
8130
+ </div>
8131
+ <div class="svu-encryption-result">
8132
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8133
+ <path d="M20 6L9 17l-5-5"/>
8134
+ </svg>
8135
+ <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>
8136
+ </div>
8137
+ <div class="svu-security-badges">
8138
+ <span class="svu-tls-badge">TLS 1.3 In Transit</span>
8139
+ <span class="svu-tls-badge">Encrypted At Rest</span>
8140
+ <span class="svu-tls-badge">Zero Trust</span>
8141
+ </div>
8142
+ `;
8143
+ sidebar.appendChild(security);
8144
+ return sidebar;
8145
+ }
8146
+
7958
8147
  /**
7959
8148
  * Upload Widget Styles
7960
8149
  *
@@ -7964,19 +8153,19 @@ class UploadApi extends SparkVaultApi {
7964
8153
  const STYLE_ID = 'sparkvault-upload-styles';
7965
8154
  /**
7966
8155
  * Inject upload widget styles into the document head.
8156
+ * Idempotent: the stylesheet is static and shared by every widget instance —
8157
+ * per-instance behavior (backdrop blur, dark mode) is driven by class toggles.
7967
8158
  */
7968
- function injectUploadStyles(options) {
8159
+ function injectUploadStyles() {
7969
8160
  if (document.getElementById(STYLE_ID)) {
7970
8161
  return;
7971
8162
  }
7972
8163
  const style = document.createElement('style');
7973
8164
  style.id = STYLE_ID;
7974
- style.textContent = getUploadStyles(options);
8165
+ style.textContent = getUploadStyles();
7975
8166
  document.head.appendChild(style);
7976
8167
  }
7977
- function getUploadStyles(options) {
7978
- const { backdropBlur } = options;
7979
- const enableBlur = backdropBlur !== false;
8168
+ function getUploadStyles() {
7980
8169
  // Design tokens - light theme for upload widget
7981
8170
  const tokens = {
7982
8171
  // Colors
@@ -8043,8 +8232,8 @@ function getUploadStyles(options) {
8043
8232
  }
8044
8233
 
8045
8234
  .svu-overlay.svu-blur {
8046
- backdrop-filter: blur(${enableBlur ? '8px' : '0'});
8047
- -webkit-backdrop-filter: blur(${enableBlur ? '8px' : '0'});
8235
+ backdrop-filter: blur(8px);
8236
+ -webkit-backdrop-filter: blur(8px);
8048
8237
  }
8049
8238
 
8050
8239
  .svu-modal {
@@ -9072,6 +9261,8 @@ function getUploadStyles(options) {
9072
9261
  */
9073
9262
  const OVERLAY_ID = 'sparkvault-upload-overlay';
9074
9263
  const MODAL_ID = 'sparkvault-upload-modal';
9264
+ /** Title node id referenced by the overlay's aria-labelledby. */
9265
+ const MODAL_TITLE_ID = 'svu-modal-title';
9075
9266
  /**
9076
9267
  * Default branding used for immediate modal display before config loads.
9077
9268
  */
@@ -9112,17 +9303,14 @@ class UploadModalContainer {
9112
9303
  this.onCloseCallback = onClose;
9113
9304
  this.backdropBlur = options.backdropBlur !== false;
9114
9305
  this.branding = options.branding || DEFAULT_BRANDING;
9115
- injectUploadStyles({
9116
- branding: this.branding,
9117
- backdropBlur: this.backdropBlur,
9118
- });
9306
+ injectUploadStyles();
9119
9307
  // Create overlay
9120
9308
  const overlay = document.createElement('div');
9121
9309
  overlay.id = OVERLAY_ID;
9122
9310
  overlay.className = this.backdropBlur ? 'svu-overlay svu-blur' : 'svu-overlay';
9123
9311
  overlay.setAttribute('role', 'dialog');
9124
9312
  overlay.setAttribute('aria-modal', 'true');
9125
- overlay.setAttribute('aria-labelledby', 'svu-modal-title');
9313
+ overlay.setAttribute('aria-labelledby', MODAL_TITLE_ID);
9126
9314
  // Create modal
9127
9315
  const modal = document.createElement('div');
9128
9316
  modal.id = MODAL_ID;
@@ -9137,19 +9325,7 @@ class UploadModalContainer {
9137
9325
  const body = document.createElement('div');
9138
9326
  body.className = 'svu-body';
9139
9327
  // Create footer
9140
- const footer = document.createElement('div');
9141
- footer.className = 'svu-footer';
9142
- const footerText = document.createElement('span');
9143
- footerText.className = 'svu-footer-text';
9144
- footerText.appendChild(document.createTextNode('Secured by '));
9145
- const footerLink = document.createElement('a');
9146
- footerLink.href = 'https://sparkvault.com';
9147
- footerLink.target = '_blank';
9148
- footerLink.rel = 'noopener noreferrer';
9149
- footerLink.className = 'svu-footer-link';
9150
- footerLink.textContent = 'SparkVault';
9151
- footerText.appendChild(footerLink);
9152
- footer.appendChild(footerText);
9328
+ const footer = createFooter();
9153
9329
  main.appendChild(header);
9154
9330
  main.appendChild(body);
9155
9331
  main.appendChild(footer);
@@ -9173,47 +9349,15 @@ class UploadModalContainer {
9173
9349
  this.elements = { overlay, modal, main, header, body, footer, sidebar: null };
9174
9350
  }
9175
9351
  createHeader(branding) {
9176
- const header = document.createElement('div');
9177
- header.className = 'svu-header';
9178
- const titleContainer = document.createElement('div');
9179
- titleContainer.className = 'svu-header-title';
9180
- // Use light logo for light theme (default), dark logo for dark mode
9181
- const logoUrl = this.isDarkMode
9182
- ? branding.logoDarkUrl || branding.logoLightUrl
9183
- : branding.logoLightUrl || branding.logoDarkUrl;
9184
- if (logoUrl) {
9185
- const logo = document.createElement('img');
9186
- logo.className = 'svu-logo';
9187
- logo.src = logoUrl;
9188
- logo.alt = branding.organizationName;
9189
- titleContainer.appendChild(logo);
9190
- // Screen reader title
9191
- const srTitle = document.createElement('span');
9192
- srTitle.className = 'svu-sr-only';
9193
- srTitle.id = 'svu-modal-title';
9194
- srTitle.textContent = branding.organizationName;
9195
- titleContainer.appendChild(srTitle);
9196
- }
9197
- else if (branding.organizationName) {
9198
- const companyName = document.createElement('h2');
9199
- companyName.className = 'svu-company-name';
9200
- companyName.id = 'svu-modal-title';
9201
- companyName.textContent = branding.organizationName;
9202
- titleContainer.appendChild(companyName);
9203
- }
9204
- // Close button
9205
- this.closeBtn = document.createElement('button');
9206
- this.closeBtn.className = 'svu-close-btn';
9207
- this.closeBtn.setAttribute('aria-label', 'Close');
9208
- this.closeBtn.innerHTML = `
9209
- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9210
- <path d="M18 6L6 18M6 6l12 12"/>
9211
- </svg>
9212
- `;
9213
9352
  this.closeBtnClickHandler = () => this.handleClose();
9214
- this.closeBtn.addEventListener('click', this.closeBtnClickHandler);
9215
- header.appendChild(titleContainer);
9216
- header.appendChild(this.closeBtn);
9353
+ const { header, closeBtn } = createBrandHeader({
9354
+ branding,
9355
+ isDarkMode: this.isDarkMode,
9356
+ withCloseButton: true,
9357
+ titleId: MODAL_TITLE_ID,
9358
+ onClose: this.closeBtnClickHandler,
9359
+ });
9360
+ this.closeBtn = closeBtn;
9217
9361
  return header;
9218
9362
  }
9219
9363
  /**
@@ -9275,7 +9419,7 @@ class UploadModalContainer {
9275
9419
  return;
9276
9420
  if (show && !this.elements.sidebar) {
9277
9421
  // Create sidebar
9278
- const sidebar = this.createSecuritySidebar();
9422
+ const sidebar = createSecuritySidebar(this.branding);
9279
9423
  this.elements.modal.classList.add('svu-with-sidebar');
9280
9424
  this.elements.modal.appendChild(sidebar);
9281
9425
  this.elements.sidebar = sidebar;
@@ -9295,91 +9439,6 @@ class UploadModalContainer {
9295
9439
  }
9296
9440
  }
9297
9441
  }
9298
- createSecuritySidebar() {
9299
- const sidebar = document.createElement('div');
9300
- sidebar.className = 'svu-sidebar';
9301
- // Logo
9302
- const logoDiv = document.createElement('div');
9303
- logoDiv.className = 'svu-sidebar-logo';
9304
- if (this.branding.logoDarkUrl) {
9305
- const logo = document.createElement('img');
9306
- logo.src = this.branding.logoDarkUrl;
9307
- logo.alt = this.branding.organizationName;
9308
- logoDiv.appendChild(logo);
9309
- }
9310
- sidebar.appendChild(logoDiv);
9311
- // Intro
9312
- const intro = document.createElement('div');
9313
- intro.className = 'svu-sidebar-intro';
9314
- intro.innerHTML = `
9315
- <h3>Secure File Transfer</h3>
9316
- <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>
9317
- `;
9318
- sidebar.appendChild(intro);
9319
- // Security details
9320
- const security = document.createElement('div');
9321
- security.className = 'svu-sidebar-security';
9322
- security.innerHTML = `
9323
- <h4>
9324
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9325
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
9326
- </svg>
9327
- SparkVault's Triple Zero-Trust
9328
- </h4>
9329
- <p class="svu-security-intro">
9330
- Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.
9331
- </p>
9332
- <div class="svu-key-chain">
9333
- <div class="svu-key-item">
9334
- <div class="svu-key-number">1</div>
9335
- <div class="svu-key-info">
9336
- <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>
9337
- <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>
9338
- <span class="svu-key-desc">Quantum-resistant key exchange</span>
9339
- </div>
9340
- </div>
9341
- <div class="svu-key-connector">
9342
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9343
- <path d="M12 5v14M5 12h14"/>
9344
- </svg>
9345
- </div>
9346
- <div class="svu-key-item">
9347
- <div class="svu-key-number">2</div>
9348
- <div class="svu-key-info">
9349
- <span class="svu-key-name">X25519 Ephemeral Key</span>
9350
- <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>
9351
- <span class="svu-key-desc">Perfect forward secrecy</span>
9352
- </div>
9353
- </div>
9354
- <div class="svu-key-connector">
9355
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9356
- <path d="M12 5v14M5 12h14"/>
9357
- </svg>
9358
- </div>
9359
- <div class="svu-key-item">
9360
- <div class="svu-key-number">3</div>
9361
- <div class="svu-key-info">
9362
- <span class="svu-key-name">HKDF-SHA512 Derived Key</span>
9363
- <span class="svu-key-algo">Hardware-bound key derivation</span>
9364
- <span class="svu-key-desc">Vault master key in secure enclave</span>
9365
- </div>
9366
- </div>
9367
- </div>
9368
- <div class="svu-encryption-result">
9369
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9370
- <path d="M20 6L9 17l-5-5"/>
9371
- </svg>
9372
- <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>
9373
- </div>
9374
- <div class="svu-security-badges">
9375
- <span class="svu-tls-badge">TLS 1.3 In Transit</span>
9376
- <span class="svu-tls-badge">Encrypted At Rest</span>
9377
- <span class="svu-tls-badge">Zero Trust</span>
9378
- </div>
9379
- `;
9380
- sidebar.appendChild(security);
9381
- return sidebar;
9382
- }
9383
9442
  handleClose() {
9384
9443
  if (this.onCloseCallback) {
9385
9444
  this.onCloseCallback();
@@ -9472,10 +9531,7 @@ class UploadInlineContainer {
9472
9531
  }
9473
9532
  this.onCloseCallback = onClose;
9474
9533
  // Inject styles
9475
- injectUploadStyles({
9476
- branding: this.branding,
9477
- backdropBlur: false,
9478
- });
9534
+ injectUploadStyles();
9479
9535
  // Create main container
9480
9536
  this.container = document.createElement('div');
9481
9537
  this.container.className = 'svu-inline-container';
@@ -9490,19 +9546,7 @@ class UploadInlineContainer {
9490
9546
  this.container.appendChild(this.body);
9491
9547
  // Create footer if enabled
9492
9548
  if (this.containerOptions.showFooter) {
9493
- this.footer = document.createElement('div');
9494
- this.footer.className = 'svu-footer';
9495
- const footerText = document.createElement('span');
9496
- footerText.className = 'svu-footer-text';
9497
- footerText.appendChild(document.createTextNode('Secured by '));
9498
- const footerLink = document.createElement('a');
9499
- footerLink.href = 'https://sparkvault.com';
9500
- footerLink.target = '_blank';
9501
- footerLink.rel = 'noopener noreferrer';
9502
- footerLink.className = 'svu-footer-link';
9503
- footerLink.textContent = 'SparkVault';
9504
- footerText.appendChild(footerLink);
9505
- this.footer.appendChild(footerText);
9549
+ this.footer = createFooter();
9506
9550
  this.container.appendChild(this.footer);
9507
9551
  }
9508
9552
  // Clear target and append container
@@ -9560,7 +9604,7 @@ class UploadInlineContainer {
9560
9604
  return;
9561
9605
  if (show && !this.sidebar) {
9562
9606
  // Create sidebar
9563
- this.sidebar = this.createSecuritySidebar();
9607
+ this.sidebar = createSecuritySidebar(this.branding);
9564
9608
  this.container.classList.add('svu-with-sidebar');
9565
9609
  this.container.appendChild(this.sidebar);
9566
9610
  }
@@ -9611,134 +9655,16 @@ class UploadInlineContainer {
9611
9655
  this.onCloseCallback = null;
9612
9656
  }
9613
9657
  createHeader(branding) {
9614
- const header = document.createElement('div');
9615
- header.className = 'svu-header';
9616
- const titleContainer = document.createElement('div');
9617
- titleContainer.className = 'svu-header-title';
9618
- // Use appropriate logo based on dark mode
9619
- const logoUrl = this.isDarkMode
9620
- ? branding.logoDarkUrl || branding.logoLightUrl
9621
- : branding.logoLightUrl || branding.logoDarkUrl;
9622
- if (logoUrl) {
9623
- const logo = document.createElement('img');
9624
- logo.className = 'svu-logo';
9625
- logo.src = logoUrl;
9626
- logo.alt = branding.organizationName;
9627
- titleContainer.appendChild(logo);
9628
- // Screen reader title
9629
- const srTitle = document.createElement('span');
9630
- srTitle.className = 'svu-sr-only';
9631
- srTitle.textContent = branding.organizationName;
9632
- titleContainer.appendChild(srTitle);
9633
- }
9634
- else if (branding.organizationName) {
9635
- const companyName = document.createElement('h2');
9636
- companyName.className = 'svu-company-name';
9637
- companyName.textContent = branding.organizationName;
9638
- titleContainer.appendChild(companyName);
9639
- }
9640
- header.appendChild(titleContainer);
9641
- // Add close button if enabled
9642
- if (this.containerOptions.showCloseButton) {
9643
- this.closeBtn = document.createElement('button');
9644
- this.closeBtn.className = 'svu-close-btn';
9645
- this.closeBtn.setAttribute('aria-label', 'Close');
9646
- this.closeBtn.innerHTML = `
9647
- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9648
- <path d="M18 6L6 18M6 6l12 12"/>
9649
- </svg>
9650
- `;
9651
- this.closeBtnClickHandler = () => this.handleClose();
9652
- this.closeBtn.addEventListener('click', this.closeBtnClickHandler);
9653
- header.appendChild(this.closeBtn);
9654
- }
9658
+ this.closeBtnClickHandler = () => this.handleClose();
9659
+ const { header, closeBtn } = createBrandHeader({
9660
+ branding,
9661
+ isDarkMode: this.isDarkMode,
9662
+ withCloseButton: this.containerOptions.showCloseButton === true,
9663
+ onClose: this.closeBtnClickHandler,
9664
+ });
9665
+ this.closeBtn = closeBtn;
9655
9666
  return header;
9656
9667
  }
9657
- createSecuritySidebar() {
9658
- const sidebar = document.createElement('div');
9659
- sidebar.className = 'svu-sidebar';
9660
- // Logo
9661
- const logoDiv = document.createElement('div');
9662
- logoDiv.className = 'svu-sidebar-logo';
9663
- if (this.branding.logoDarkUrl) {
9664
- const logo = document.createElement('img');
9665
- logo.src = this.branding.logoDarkUrl;
9666
- logo.alt = this.branding.organizationName;
9667
- logoDiv.appendChild(logo);
9668
- }
9669
- sidebar.appendChild(logoDiv);
9670
- // Intro
9671
- const intro = document.createElement('div');
9672
- intro.className = 'svu-sidebar-intro';
9673
- intro.innerHTML = `
9674
- <h3>Secure File Transfer</h3>
9675
- <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>
9676
- `;
9677
- sidebar.appendChild(intro);
9678
- // Security details
9679
- const security = document.createElement('div');
9680
- security.className = 'svu-sidebar-security';
9681
- security.innerHTML = `
9682
- <h4>
9683
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9684
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
9685
- </svg>
9686
- SparkVault's Triple Zero-Trust
9687
- </h4>
9688
- <p class="svu-security-intro">
9689
- Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.
9690
- </p>
9691
- <div class="svu-key-chain">
9692
- <div class="svu-key-item">
9693
- <div class="svu-key-number">1</div>
9694
- <div class="svu-key-info">
9695
- <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>
9696
- <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>
9697
- <span class="svu-key-desc">Quantum-resistant key exchange</span>
9698
- </div>
9699
- </div>
9700
- <div class="svu-key-connector">
9701
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9702
- <path d="M12 5v14M5 12h14"/>
9703
- </svg>
9704
- </div>
9705
- <div class="svu-key-item">
9706
- <div class="svu-key-number">2</div>
9707
- <div class="svu-key-info">
9708
- <span class="svu-key-name">X25519 Ephemeral Key</span>
9709
- <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>
9710
- <span class="svu-key-desc">Perfect forward secrecy</span>
9711
- </div>
9712
- </div>
9713
- <div class="svu-key-connector">
9714
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9715
- <path d="M12 5v14M5 12h14"/>
9716
- </svg>
9717
- </div>
9718
- <div class="svu-key-item">
9719
- <div class="svu-key-number">3</div>
9720
- <div class="svu-key-info">
9721
- <span class="svu-key-name">HKDF-SHA512 Derived Key</span>
9722
- <span class="svu-key-algo">Hardware-bound key derivation</span>
9723
- <span class="svu-key-desc">Vault master key in secure enclave</span>
9724
- </div>
9725
- </div>
9726
- </div>
9727
- <div class="svu-encryption-result">
9728
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9729
- <path d="M20 6L9 17l-5-5"/>
9730
- </svg>
9731
- <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>
9732
- </div>
9733
- <div class="svu-security-badges">
9734
- <span class="svu-tls-badge">TLS 1.3 In Transit</span>
9735
- <span class="svu-tls-badge">Encrypted At Rest</span>
9736
- <span class="svu-tls-badge">Zero Trust</span>
9737
- </div>
9738
- `;
9739
- sidebar.appendChild(security);
9740
- return sidebar;
9741
- }
9742
9668
  handleClose() {
9743
9669
  if (this.onCloseCallback) {
9744
9670
  this.onCloseCallback();
@@ -9781,6 +9707,14 @@ function generateRequestId() {
9781
9707
  const random = Array.from(randomBytes, byte => byte.toString(16).padStart(2, '0')).join('');
9782
9708
  return `${timestamp}${random}`;
9783
9709
  }
9710
+ /**
9711
+ * Whether an error represents a deliberate cancellation (user close,
9712
+ * programmatic close, or session abort) rather than a genuine failure.
9713
+ */
9714
+ function isCancellationError(error) {
9715
+ return (error instanceof UserCancelledError ||
9716
+ (error instanceof SparkVaultError && error.code === 'cancelled'));
9717
+ }
9784
9718
  /**
9785
9719
  * Format bytes to human readable string.
9786
9720
  */
@@ -9803,8 +9737,11 @@ class UploadRenderer {
9803
9737
  this.uploadModal = null;
9804
9738
  this.isInlineMode = false;
9805
9739
  this.hybridModalInitialized = false;
9806
- // Track active XHR for cancellation on close
9807
- this.activeXhr = null;
9740
+ // Lifecycle flags: a closed renderer must never render or fire callbacks,
9741
+ // and onCancel fires at most once per renderer (mutually exclusive with
9742
+ // onError — see cancel()/handleApiError).
9743
+ this.closed = false;
9744
+ this.cancelled = false;
9808
9745
  this.pasteHandler = null;
9809
9746
  this.container = container;
9810
9747
  this.api = api;
@@ -9845,16 +9782,13 @@ class UploadRenderer {
9845
9782
  }
9846
9783
  /**
9847
9784
  * Close the upload flow.
9848
- * Cancels all pending API requests and active uploads to prevent orphaned operations.
9785
+ * Cancels all pending API requests and active uploads (aborting the session
9786
+ * signal tears down any in-flight TUS chunk) to prevent orphaned operations.
9849
9787
  */
9850
9788
  close() {
9851
- // Cancel all pending API requests first
9789
+ this.closed = true;
9790
+ // Cancel all pending API requests and the active TUS transfer
9852
9791
  this.api.abort();
9853
- // Abort any active XHR upload
9854
- if (this.activeXhr) {
9855
- this.activeXhr.abort();
9856
- this.activeXhr = null;
9857
- }
9858
9792
  this.cleanupFileInput();
9859
9793
  this.cleanupPasteHandler();
9860
9794
  // Clean up modal if open (hybrid mode)
@@ -9865,14 +9799,64 @@ class UploadRenderer {
9865
9799
  }
9866
9800
  this.container.destroy();
9867
9801
  }
9868
- handleClose() {
9802
+ /**
9803
+ * Cancel the flow: tear everything down and fire the cancel contract
9804
+ * exactly once. onCancel and onError are mutually exclusive — a deliberate
9805
+ * cancellation (user close, programmatic close, or a new upload replacing
9806
+ * this renderer) must never surface as an error to the host.
9807
+ */
9808
+ cancel() {
9809
+ if (this.cancelled)
9810
+ return;
9811
+ this.cancelled = true;
9869
9812
  this.close();
9870
9813
  this.callbacks.onCancel();
9871
9814
  }
9815
+ handleClose() {
9816
+ this.cancel();
9817
+ }
9872
9818
  setState(state) {
9819
+ // A closed renderer never renders again — a progress event racing the
9820
+ // teardown must not resurrect the hybrid-mode modal or touch the DOM.
9821
+ if (this.closed)
9822
+ return;
9823
+ const previousView = this.viewState.view;
9873
9824
  this.viewState = state;
9825
+ // Progress events fire many times per second for the whole transfer.
9826
+ // While the uploading view is already on screen, mutate its progress
9827
+ // nodes in place instead of tearing down and rebuilding the subtree —
9828
+ // a full rebuild per event thrashes the DOM and restarts the progress
9829
+ // bar's CSS transition and the stage-arrow animation on every tick.
9830
+ if (previousView === 'uploading' &&
9831
+ state.view === 'uploading' &&
9832
+ this.updateUploadProgress(state)) {
9833
+ return;
9834
+ }
9874
9835
  this.render();
9875
9836
  }
9837
+ /**
9838
+ * Targeted DOM update for an already-rendered uploading view: progress fill
9839
+ * width plus the percentage and byte-count labels. Returns false when the
9840
+ * uploading view is not in the DOM, so the caller falls back to a full render.
9841
+ */
9842
+ updateUploadProgress(state) {
9843
+ // Hybrid inline mode renders uploading inside the modal overlay.
9844
+ const body = this.isInlineMode && this.uploadModal
9845
+ ? this.uploadModal.getBody()
9846
+ : this.container.getBody();
9847
+ const fill = body?.querySelector('.svu-progress-fill');
9848
+ if (!body || !fill)
9849
+ return false;
9850
+ fill.style.width = `${state.progress}%`;
9851
+ const [percentLabel, bytesLabel] = body.querySelectorAll('.svu-progress-text span');
9852
+ if (percentLabel) {
9853
+ percentLabel.textContent = `${state.progress}%`;
9854
+ }
9855
+ if (bytesLabel) {
9856
+ bytesLabel.textContent = `${formatBytes(state.bytesUploaded)} / ${formatBytes(state.file.size)}`;
9857
+ }
9858
+ return true;
9859
+ }
9876
9860
  render() {
9877
9861
  const isDarkState = this.viewState.view === 'uploading' || this.viewState.view === 'ceremony';
9878
9862
  // Hybrid mode: For inline containers, use a modal popup for upload/ceremony
@@ -10374,8 +10358,24 @@ class UploadRenderer {
10374
10358
  progress: 0,
10375
10359
  bytesUploaded: 0,
10376
10360
  });
10377
- // Upload file using tus (resumable upload)
10378
- const uploadUrl = await this.uploadWithTus(file, forgeUrl, ingotId, requestId);
10361
+ // Upload file over the canonical TUS transfer path
10362
+ const uploadUrl = await this.api.uploadFileToForge(file, forgeUrl, (bytesUploaded, bytesTotal) => {
10363
+ const progress = Math.round((bytesUploaded / bytesTotal) * 100);
10364
+ this.setState({
10365
+ view: 'uploading',
10366
+ file,
10367
+ ingotId,
10368
+ requestId,
10369
+ progress,
10370
+ bytesUploaded,
10371
+ });
10372
+ this.callbacks.onProgress?.({
10373
+ bytesUploaded,
10374
+ bytesTotal,
10375
+ percentage: progress,
10376
+ phase: 'uploading',
10377
+ });
10378
+ });
10379
10379
  // Confirm the server actually finalized the upload before celebrating.
10380
10380
  // The TUS loop trusts a server-provided offset; this re-reads the
10381
10381
  // server's own persisted offset and requires it to reach the file size,
@@ -10416,129 +10416,6 @@ class UploadRenderer {
10416
10416
  this.handleApiError(error);
10417
10417
  }
10418
10418
  }
10419
- async uploadWithTus(file, forgeUrl, ingotId, requestId) {
10420
- // tus resumable upload protocol v1.0.0
10421
- // Uploads file in chunks to avoid Cloudflare's 100MB request limit
10422
- const TUS_VERSION = '1.0.0';
10423
- const DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024; // 50MB default, server may override
10424
- // Extract base URL and ISTK from forge URL
10425
- const url = new URL(forgeUrl);
10426
- const istk = url.searchParams.get('istk');
10427
- const baseUrl = `${url.origin}${url.pathname}`;
10428
- if (!istk) {
10429
- throw new Error('Missing ISTK in forge URL');
10430
- }
10431
- // Step 1: Create tus upload session
10432
- const createResponse = await fetch(baseUrl, {
10433
- method: 'POST',
10434
- headers: {
10435
- 'Tus-Resumable': TUS_VERSION,
10436
- 'Upload-Length': String(file.size),
10437
- 'X-ISTK': istk,
10438
- 'Content-Type': 'application/offset+octet-stream',
10439
- },
10440
- });
10441
- if (!createResponse.ok) {
10442
- const errorText = await createResponse.text();
10443
- throw new Error(`Failed to create upload session: ${createResponse.status} ${errorText}`);
10444
- }
10445
- // Get upload location and chunk size from response
10446
- const location = createResponse.headers.get('Location');
10447
- const chunkSizeHeader = createResponse.headers.get('X-Chunk-Size');
10448
- const chunkSize = chunkSizeHeader ? parseInt(chunkSizeHeader, 10) : DEFAULT_CHUNK_SIZE;
10449
- if (!location) {
10450
- throw new Error('Server did not return upload location');
10451
- }
10452
- // Build full upload URL
10453
- const uploadUrl = location.startsWith('http') ? location : `${url.origin}${location}`;
10454
- // Step 2: Upload file in chunks with progress tracking
10455
- let offset = 0;
10456
- const totalSize = file.size;
10457
- while (offset < totalSize) {
10458
- const chunkStart = offset;
10459
- const chunkEnd = Math.min(offset + chunkSize, totalSize);
10460
- const chunk = file.slice(chunkStart, chunkEnd);
10461
- // Upload chunk with XHR for progress events
10462
- const newOffset = await this.uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, TUS_VERSION, file, ingotId, requestId);
10463
- offset = newOffset;
10464
- }
10465
- return uploadUrl;
10466
- }
10467
- /**
10468
- * Upload a single chunk using XMLHttpRequest for progress tracking.
10469
- * Tracks the XHR so it can be cancelled if the renderer is closed.
10470
- */
10471
- uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, tusVersion, file, ingotId, requestId) {
10472
- return new Promise((resolve, reject) => {
10473
- // Check if already aborted before starting
10474
- if (this.api.isAborted()) {
10475
- reject(new Error('Upload cancelled'));
10476
- return;
10477
- }
10478
- const xhr = new XMLHttpRequest();
10479
- // Track this XHR so it can be cancelled on close
10480
- this.activeXhr = xhr;
10481
- // Track progress within this chunk
10482
- xhr.upload.onprogress = (e) => {
10483
- if (e.lengthComputable) {
10484
- // Calculate total progress: completed chunks + progress within current chunk
10485
- const totalUploaded = chunkStart + e.loaded;
10486
- const progress = Math.round((totalUploaded / totalSize) * 100);
10487
- this.setState({
10488
- view: 'uploading',
10489
- file,
10490
- ingotId,
10491
- requestId,
10492
- progress,
10493
- bytesUploaded: totalUploaded,
10494
- });
10495
- this.callbacks.onProgress?.({
10496
- bytesUploaded: totalUploaded,
10497
- bytesTotal: totalSize,
10498
- percentage: progress,
10499
- phase: 'uploading',
10500
- });
10501
- }
10502
- };
10503
- xhr.onload = () => {
10504
- this.activeXhr = null;
10505
- if (xhr.status >= 200 && xhr.status < 300) {
10506
- // Get new offset from server response
10507
- const newOffsetHeader = xhr.getResponseHeader('Upload-Offset');
10508
- const newOffset = newOffsetHeader ? parseInt(newOffsetHeader, 10) : chunkStart + chunk.size;
10509
- // Defense-in-depth: the server must never report more bytes accepted
10510
- // than the file contains. A `newOffset > totalSize` is a malformed or
10511
- // inflated response — reject it rather than letting an over-reported
10512
- // offset short-circuit the upload loop and skip real chunks.
10513
- if (!Number.isFinite(newOffset) || newOffset < chunkStart || newOffset > totalSize) {
10514
- reject(new Error(`Server returned invalid upload offset (${newOffset})`));
10515
- return;
10516
- }
10517
- resolve(newOffset);
10518
- }
10519
- else {
10520
- reject(new Error(`Chunk upload failed with status ${xhr.status}`));
10521
- }
10522
- };
10523
- xhr.onerror = () => {
10524
- this.activeXhr = null;
10525
- reject(new Error('Chunk upload failed'));
10526
- };
10527
- xhr.ontimeout = () => {
10528
- this.activeXhr = null;
10529
- reject(new Error('Chunk upload timed out'));
10530
- };
10531
- xhr.onabort = () => {
10532
- this.activeXhr = null;
10533
- reject(new Error('Upload cancelled'));
10534
- };
10535
- xhr.open('PATCH', uploadUrl);
10536
- xhr.setRequestHeader('Tus-Resumable', tusVersion);
10537
- xhr.setRequestHeader('Upload-Offset', String(chunkStart));
10538
- xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream');
10539
- xhr.send(chunk);
10540
- });
10541
- }
10542
10419
  async runCeremony(file, ingotId, requestId) {
10543
10420
  for (let i = 0; i < CEREMONY_STEPS.length; i++) {
10544
10421
  this.setState({
@@ -10569,6 +10446,14 @@ class UploadRenderer {
10569
10446
  await new Promise(resolve => setTimeout(resolve, 500));
10570
10447
  }
10571
10448
  handleApiError(error) {
10449
+ // A closed renderer must not surface errors: cancelling mid-transfer
10450
+ // aborts the in-flight request, whose 'cancelled' rejection races the
10451
+ // teardown. The host has already received onCancel — onCancel and
10452
+ // onError are mutually exclusive — and the container is destroyed, so
10453
+ // there is nothing left to render into.
10454
+ if (this.closed || isCancellationError(error)) {
10455
+ return;
10456
+ }
10572
10457
  if (error instanceof UploadApiError) {
10573
10458
  if (error.code === 'UPLOAD_SOURCE_DISABLED') {
10574
10459
  // The vault exists but the embedded widget isn't enabled.
@@ -10638,7 +10523,6 @@ class UploadRenderer {
10638
10523
  }
10639
10524
  }
10640
10525
 
10641
- /* global Element */
10642
10526
  /**
10643
10527
  * Vault Upload Module
10644
10528
  *
@@ -10659,7 +10543,6 @@ class UploadRenderer {
10659
10543
  class VaultUploadModule {
10660
10544
  constructor(config) {
10661
10545
  this.renderer = null;
10662
- this.attachedElements = new Map();
10663
10546
  this.config = config;
10664
10547
  this.api = new UploadApi(config);
10665
10548
  }
@@ -10683,9 +10566,10 @@ class VaultUploadModule {
10683
10566
  if (!options.vaultId) {
10684
10567
  throw new ValidationError('vaultId is required');
10685
10568
  }
10686
- // Close any existing renderer
10569
+ // Cancel any existing renderer so its pending promise settles via the
10570
+ // cancel contract (onCancel + UserCancelledError) instead of hanging.
10687
10571
  if (this.renderer) {
10688
- this.renderer.close();
10572
+ this.renderer.cancel();
10689
10573
  }
10690
10574
  const isInline = !!options.target;
10691
10575
  const container = isInline
@@ -10744,7 +10628,6 @@ class VaultUploadModule {
10744
10628
  if (!options.vaultId) {
10745
10629
  throw new ValidationError('vaultId is required');
10746
10630
  }
10747
- let observer = null;
10748
10631
  const handleClick = async (event) => {
10749
10632
  event.preventDefault();
10750
10633
  try {
@@ -10760,55 +10643,17 @@ class VaultUploadModule {
10760
10643
  // Error already handled by callbacks or will use server redirect
10761
10644
  }
10762
10645
  };
10763
- const attachToElements = () => {
10764
- const elements = document.querySelectorAll(selector);
10765
- elements.forEach((element) => {
10766
- element.addEventListener('click', handleClick);
10767
- this.attachedElements.set(element, () => {
10768
- element.removeEventListener('click', handleClick);
10769
- });
10770
- });
10771
- // Watch for dynamically added elements
10772
- observer = new MutationObserver((mutations) => {
10773
- mutations.forEach((mutation) => {
10774
- mutation.addedNodes.forEach((node) => {
10775
- if (node instanceof Element) {
10776
- if (node.matches(selector)) {
10777
- node.addEventListener('click', handleClick);
10778
- this.attachedElements.set(node, () => {
10779
- node.removeEventListener('click', handleClick);
10780
- });
10781
- }
10782
- // Check descendants
10783
- node.querySelectorAll(selector).forEach((el) => {
10784
- if (!this.attachedElements.has(el)) {
10785
- el.addEventListener('click', handleClick);
10786
- this.attachedElements.set(el, () => {
10787
- el.removeEventListener('click', handleClick);
10788
- });
10789
- }
10790
- });
10791
- }
10792
- });
10793
- });
10794
- });
10795
- observer.observe(document.body, { childList: true, subtree: true });
10796
- };
10797
- // Defer attachment until DOM is ready
10798
- onDomReady(attachToElements);
10799
- // Return cleanup function
10800
- return () => {
10801
- observer?.disconnect();
10802
- this.attachedElements.forEach((cleanup) => cleanup());
10803
- this.attachedElements.clear();
10804
- };
10646
+ return attachClickHandler(selector, handleClick);
10805
10647
  }
10806
10648
  /**
10807
10649
  * Close the upload dialog/inline UI if open.
10650
+ *
10651
+ * Programmatic close follows the cancel contract: the host's onCancel
10652
+ * fires and the pending upload promise rejects with UserCancelledError.
10808
10653
  */
10809
10654
  close() {
10810
10655
  if (this.renderer) {
10811
- this.renderer.close();
10656
+ this.renderer.cancel();
10812
10657
  this.renderer = null;
10813
10658
  }
10814
10659
  }
@@ -10832,9 +10677,9 @@ class VaultUploadModule {
10832
10677
  }
10833
10678
  return new UploadInlineContainer(element);
10834
10679
  }
10835
- // Public-API aliases. The web vault-edit screen instructs customers to
10836
- // call sv.vaults.upload.pop(vaultId) / .render(vaultId, target) — both
10837
- // are documented entry points that defer to upload() under the hood.
10680
+ // Public-API aliases. The dashboard's vault-edit screen and the SDK docs
10681
+ // document sv.vaults.upload.pop({ vaultId }) and
10682
+ // sv.vaults.upload.render({ vaultId, target }) — both defer to upload().
10838
10683
  /** Open the upload widget as a popup. Equivalent to `upload(options)`. */
10839
10684
  async pop(options) {
10840
10685
  return this.upload(options);
@@ -10856,10 +10701,13 @@ class VaultsModule {
10856
10701
  this.config = config;
10857
10702
  this.http = http;
10858
10703
  this.uploadModule = new VaultUploadModule(config);
10859
- // Create callable that also has attach/close methods
10704
+ this.uploadApi = new UploadApi(config);
10705
+ // Create callable that also has attach/close/pop/render methods
10860
10706
  const uploadFn = ((options) => this.uploadModule.upload(options));
10861
10707
  uploadFn.attach = (selector, options) => this.uploadModule.attach(selector, options);
10862
10708
  uploadFn.close = () => this.uploadModule.close();
10709
+ uploadFn.pop = (options) => this.uploadModule.pop(options);
10710
+ uploadFn.render = (options) => this.uploadModule.render(options);
10863
10711
  this.upload = uploadFn;
10864
10712
  }
10865
10713
  /**
@@ -10967,7 +10815,11 @@ class VaultsModule {
10967
10815
  if (!created.forge_url) {
10968
10816
  throw new ValidationError('Upload endpoint did not return a Forge upload URL');
10969
10817
  }
10970
- await uploadBlobWithTus(options.file, created.forge_url, created.name, created.content_type, options.onProgress);
10818
+ const uploadUrl = await this.uploadApi.uploadFileToForge(options.file, created.forge_url, options.onProgress);
10819
+ // Confirm the server actually finalized the upload before reporting
10820
+ // success — the TUS loop's offsets alone don't prove the final chunk
10821
+ // committed and the ingot went active.
10822
+ await this.uploadApi.verifyUploadFinalized(uploadUrl, options.file.size);
10971
10823
  return {
10972
10824
  id: created.ingot_id,
10973
10825
  name: created.name,
@@ -11077,78 +10929,6 @@ function getBlobName(file) {
11077
10929
  }
11078
10930
  return 'unnamed';
11079
10931
  }
11080
- function base64Encode(value) {
11081
- return btoa(unescape(encodeURIComponent(value)));
11082
- }
11083
- async function uploadBlobWithTus(file, forgeUrl, filename, contentType, onProgress) {
11084
- if (typeof XMLHttpRequest === 'undefined') {
11085
- throw new ValidationError('XMLHttpRequest is required for browser ingot uploads');
11086
- }
11087
- const tusVersion = '1.0.0';
11088
- const defaultChunkSize = 50 * 1024 * 1024;
11089
- const url = new URL(forgeUrl);
11090
- const istk = url.searchParams.get('istk');
11091
- const endpoint = `${url.origin}${url.pathname}`;
11092
- if (!istk) {
11093
- throw new ValidationError('Forge upload URL is missing ISTK');
11094
- }
11095
- const createResponse = await fetch(endpoint, {
11096
- method: 'POST',
11097
- headers: {
11098
- 'Tus-Resumable': tusVersion,
11099
- 'Upload-Length': String(file.size),
11100
- 'Upload-Metadata': `filename ${base64Encode(filename)},filetype ${base64Encode(contentType)}`,
11101
- 'X-ISTK': istk,
11102
- },
11103
- });
11104
- if (!createResponse.ok) {
11105
- const errorText = await createResponse.text();
11106
- throw new Error(`Failed to create upload session: ${createResponse.status} ${errorText}`);
11107
- }
11108
- const location = createResponse.headers.get('Location');
11109
- const chunkSizeHeader = createResponse.headers.get('X-Chunk-Size');
11110
- const chunkSize = chunkSizeHeader ? parseInt(chunkSizeHeader, 10) : defaultChunkSize;
11111
- if (!location) {
11112
- throw new Error('Server did not return upload location');
11113
- }
11114
- const uploadUrl = location.startsWith('http') ? location : `${url.origin}${location}`;
11115
- let offset = 0;
11116
- while (offset < file.size) {
11117
- const chunkStart = offset;
11118
- const chunkEnd = Math.min(offset + chunkSize, file.size);
11119
- const chunk = file.slice(chunkStart, chunkEnd);
11120
- offset = await uploadChunkWithProgress(uploadUrl, chunk, chunkStart, file.size, tusVersion, istk, onProgress);
11121
- }
11122
- }
11123
- function uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, tusVersion, istk, onProgress) {
11124
- return new Promise((resolve, reject) => {
11125
- const xhr = new XMLHttpRequest();
11126
- xhr.upload.onprogress = (event) => {
11127
- if (event.lengthComputable) {
11128
- onProgress?.(chunkStart + event.loaded, totalSize);
11129
- }
11130
- };
11131
- xhr.onload = () => {
11132
- if (xhr.status >= 200 && xhr.status < 300) {
11133
- const newOffsetHeader = xhr.getResponseHeader('Upload-Offset');
11134
- const newOffset = newOffsetHeader ? parseInt(newOffsetHeader, 10) : chunkStart + chunk.size;
11135
- resolve(newOffset);
11136
- }
11137
- else {
11138
- reject(new Error(`Chunk upload failed with status ${xhr.status}`));
11139
- }
11140
- };
11141
- xhr.onerror = () => reject(new Error('Chunk upload failed'));
11142
- xhr.ontimeout = () => reject(new Error('Chunk upload timed out'));
11143
- xhr.onabort = () => reject(new Error('Upload cancelled'));
11144
- xhr.open('PATCH', uploadUrl);
11145
- xhr.setRequestHeader('Tus-Resumable', tusVersion);
11146
- xhr.setRequestHeader('Upload-Offset', String(chunkStart));
11147
- xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream');
11148
- xhr.setRequestHeader('X-ISTK', istk);
11149
- xhr.send(chunk);
11150
- });
11151
- }
11152
10932
  const DOWNLOAD_MAX_ATTEMPTS = 3;
11153
10933
  const DOWNLOAD_RETRY_BASE_MS = 500;
11154
10934
  function delayExponential(attempt) {