@sparkvault/sdk-js 2.2.1 → 2.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  /**
@@ -7089,6 +6856,26 @@ class WidgetEmbedder {
7089
6856
  this.close();
7090
6857
  window.location.href = url.toString();
7091
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
+ }
7092
6879
  buildUrl() {
7093
6880
  const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/widget`);
7094
6881
  url.searchParams.set('origin', window.location.origin);
@@ -7139,7 +6926,7 @@ class WidgetEmbedder {
7139
6926
  // iframe; on return the host SDK consumes the redirect token.
7140
6927
  if (data.type === REDIRECT_TYPE && typeof data.url === 'string') {
7141
6928
  this.clearReadyTimer();
7142
- window.location.href = data.url;
6929
+ this.safeNavigate(data.url);
7143
6930
  return;
7144
6931
  }
7145
6932
  if (data.type !== RESULT_TYPE || this.settled)
@@ -7152,7 +6939,7 @@ class WidgetEmbedder {
7152
6939
  // Mirror the renderer's belt-and-suspenders: complete a server-issued
7153
6940
  // redirect from the host's own top window if the customer didn't.
7154
6941
  if (typeof result.redirect === 'string' && result.redirect) {
7155
- window.location.href = result.redirect;
6942
+ this.safeNavigate(result.redirect);
7156
6943
  }
7157
6944
  }
7158
6945
  else if (data.cancelled) {
@@ -7355,6 +7142,7 @@ class InlineContainer {
7355
7142
  }
7356
7143
  }
7357
7144
 
7145
+ /* global Element */
7358
7146
  /**
7359
7147
  * DOM Utilities
7360
7148
  *
@@ -7403,8 +7191,62 @@ function onBodyReady(callback) {
7403
7191
  }
7404
7192
  }
7405
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
+ }
7406
7249
 
7407
- /* global Element */
7408
7250
  /**
7409
7251
  * Identity Module
7410
7252
  *
@@ -7439,7 +7281,6 @@ class IdentityModule {
7439
7281
  constructor(config) {
7440
7282
  this.renderer = null;
7441
7283
  this.embedder = null;
7442
- this.attachedElements = new Map();
7443
7284
  this.config = config;
7444
7285
  this.api = new IdentityApi(config);
7445
7286
  // Preload config in background for instant dialog opening
@@ -7566,7 +7407,6 @@ class IdentityModule {
7566
7407
  * cleanup();
7567
7408
  */
7568
7409
  attach(selector, options = {}) {
7569
- let observer = null;
7570
7410
  const handleClick = async (event) => {
7571
7411
  event.preventDefault();
7572
7412
  try {
@@ -7583,48 +7423,10 @@ class IdentityModule {
7583
7423
  // Error already handled by callbacks or will use server redirect
7584
7424
  }
7585
7425
  };
7586
- const attachToElements = () => {
7587
- const elements = document.querySelectorAll(selector);
7588
- elements.forEach((element) => {
7589
- element.addEventListener('click', handleClick);
7590
- this.attachedElements.set(element, () => {
7591
- element.removeEventListener('click', handleClick);
7592
- });
7593
- });
7594
- // Watch for dynamically added elements
7595
- observer = new MutationObserver((mutations) => {
7596
- mutations.forEach((mutation) => {
7597
- mutation.addedNodes.forEach((node) => {
7598
- if (node instanceof Element) {
7599
- if (node.matches(selector)) {
7600
- node.addEventListener('click', handleClick);
7601
- this.attachedElements.set(node, () => {
7602
- node.removeEventListener('click', handleClick);
7603
- });
7604
- }
7605
- // Check descendants
7606
- node.querySelectorAll(selector).forEach((el) => {
7607
- if (!this.attachedElements.has(el)) {
7608
- el.addEventListener('click', handleClick);
7609
- this.attachedElements.set(el, () => {
7610
- el.removeEventListener('click', handleClick);
7611
- });
7612
- }
7613
- });
7614
- }
7615
- });
7616
- });
7617
- });
7618
- // Observe document.body for dynamic elements
7619
- // Use onBodyReady to handle edge cases where body isn't available yet
7620
- onBodyReady(() => {
7621
- observer?.observe(document.body, { childList: true, subtree: true });
7622
- });
7623
- };
7624
- // Defer attachment until DOM is ready, then complete any full-page
7625
- // 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.
7626
7429
  onDomReady(() => {
7627
- attachToElements();
7628
7430
  this.consumeRedirectResult()
7629
7431
  .then((result) => {
7630
7432
  if (result)
@@ -7634,12 +7436,7 @@ class IdentityModule {
7634
7436
  options.onError?.(error instanceof Error ? error : new Error(String(error)));
7635
7437
  });
7636
7438
  });
7637
- // Return cleanup function
7638
- return () => {
7639
- observer?.disconnect();
7640
- this.attachedElements.forEach((cleanup) => cleanup());
7641
- this.attachedElements.clear();
7642
- };
7439
+ return cleanup;
7643
7440
  }
7644
7441
  /**
7645
7442
  * Verify and decode an identity token.
@@ -7686,29 +7483,56 @@ class IdentityModule {
7686
7483
  if (!token) {
7687
7484
  return null;
7688
7485
  }
7689
- const expectedState = sessionStorage.getItem('sv_oauth_state');
7690
- if (expectedState && params.get('state') !== expectedState) {
7691
- throw new ValidationError('Invalid OAuth state');
7692
- }
7693
- const claims = await this.verifyToken(token);
7694
- const result = {
7695
- token,
7696
- identity: claims.identity,
7697
- identityType: claims.identity_type,
7698
- svid: claims.svid,
7699
- sessionId: claims.session_id,
7700
- };
7701
- if (typeof window.history?.replaceState === 'function') {
7702
- 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
+ }
7703
7522
  }
7704
- sessionStorage.removeItem('sv_oauth_state');
7705
- sessionStorage.removeItem('sv_oauth_email');
7706
- return result;
7707
7523
  }
7708
7524
  /**
7709
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).
7710
7530
  */
7711
7531
  close() {
7532
+ if (this.embedder) {
7533
+ this.embedder.close();
7534
+ this.embedder = null;
7535
+ }
7712
7536
  if (this.renderer) {
7713
7537
  this.renderer.close();
7714
7538
  this.renderer = null;
@@ -7821,6 +7645,15 @@ function isInitiateUploadResponse(data) {
7821
7645
  }
7822
7646
  /** tus protocol version used for the resumable upload session. */
7823
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;
7824
7657
  /**
7825
7658
  * Server-side finalization confirmation poll.
7826
7659
  *
@@ -7903,6 +7736,167 @@ class UploadApi extends SparkVaultApi {
7903
7736
  ingotId: response.data.ingot_id,
7904
7737
  };
7905
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
+ }
7906
7900
  /**
7907
7901
  * Confirm the upload was finalized SERVER-SIDE before reporting success.
7908
7902
  *
@@ -7949,21 +7943,7 @@ class UploadApi extends SparkVaultApi {
7949
7943
  */
7950
7944
  async headUploadOffset(uploadUrl) {
7951
7945
  const closeSignal = this.getAbortSignal();
7952
- const timeoutController = new AbortController();
7953
- const timeoutId = setTimeout(() => timeoutController.abort(), this.timeoutMs);
7954
- // Combine timeout + session-close into one signal. Mirror the base
7955
- // client's fallback for browsers without AbortSignal.any: link the close
7956
- // signal into the timeout controller and remove the listener in finally.
7957
- let combinedSignal;
7958
- let onCloseAbort = null;
7959
- if ('any' in AbortSignal) {
7960
- combinedSignal = AbortSignal.any([timeoutController.signal, closeSignal]);
7961
- }
7962
- else {
7963
- combinedSignal = timeoutController.signal;
7964
- onCloseAbort = () => timeoutController.abort();
7965
- closeSignal.addEventListener('abort', onCloseAbort);
7966
- }
7946
+ const { signal: combinedSignal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, closeSignal);
7967
7947
  try {
7968
7948
  const response = await fetch(uploadUrl, {
7969
7949
  method: 'HEAD',
@@ -7995,14 +7975,175 @@ class UploadApi extends SparkVaultApi {
7995
7975
  throw new UploadApiError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
7996
7976
  }
7997
7977
  finally {
7998
- clearTimeout(timeoutId);
7999
- if (onCloseAbort) {
8000
- closeSignal.removeEventListener('abort', onCloseAbort);
8001
- }
7978
+ dispose();
8002
7979
  }
8003
7980
  }
8004
7981
  }
8005
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
+
8006
8147
  /**
8007
8148
  * Upload Widget Styles
8008
8149
  *
@@ -8012,19 +8153,19 @@ class UploadApi extends SparkVaultApi {
8012
8153
  const STYLE_ID = 'sparkvault-upload-styles';
8013
8154
  /**
8014
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.
8015
8158
  */
8016
- function injectUploadStyles(options) {
8159
+ function injectUploadStyles() {
8017
8160
  if (document.getElementById(STYLE_ID)) {
8018
8161
  return;
8019
8162
  }
8020
8163
  const style = document.createElement('style');
8021
8164
  style.id = STYLE_ID;
8022
- style.textContent = getUploadStyles(options);
8165
+ style.textContent = getUploadStyles();
8023
8166
  document.head.appendChild(style);
8024
8167
  }
8025
- function getUploadStyles(options) {
8026
- const { backdropBlur } = options;
8027
- const enableBlur = backdropBlur !== false;
8168
+ function getUploadStyles() {
8028
8169
  // Design tokens - light theme for upload widget
8029
8170
  const tokens = {
8030
8171
  // Colors
@@ -8091,8 +8232,8 @@ function getUploadStyles(options) {
8091
8232
  }
8092
8233
 
8093
8234
  .svu-overlay.svu-blur {
8094
- backdrop-filter: blur(${enableBlur ? '8px' : '0'});
8095
- -webkit-backdrop-filter: blur(${enableBlur ? '8px' : '0'});
8235
+ backdrop-filter: blur(8px);
8236
+ -webkit-backdrop-filter: blur(8px);
8096
8237
  }
8097
8238
 
8098
8239
  .svu-modal {
@@ -9120,6 +9261,8 @@ function getUploadStyles(options) {
9120
9261
  */
9121
9262
  const OVERLAY_ID = 'sparkvault-upload-overlay';
9122
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';
9123
9266
  /**
9124
9267
  * Default branding used for immediate modal display before config loads.
9125
9268
  */
@@ -9160,17 +9303,14 @@ class UploadModalContainer {
9160
9303
  this.onCloseCallback = onClose;
9161
9304
  this.backdropBlur = options.backdropBlur !== false;
9162
9305
  this.branding = options.branding || DEFAULT_BRANDING;
9163
- injectUploadStyles({
9164
- branding: this.branding,
9165
- backdropBlur: this.backdropBlur,
9166
- });
9306
+ injectUploadStyles();
9167
9307
  // Create overlay
9168
9308
  const overlay = document.createElement('div');
9169
9309
  overlay.id = OVERLAY_ID;
9170
9310
  overlay.className = this.backdropBlur ? 'svu-overlay svu-blur' : 'svu-overlay';
9171
9311
  overlay.setAttribute('role', 'dialog');
9172
9312
  overlay.setAttribute('aria-modal', 'true');
9173
- overlay.setAttribute('aria-labelledby', 'svu-modal-title');
9313
+ overlay.setAttribute('aria-labelledby', MODAL_TITLE_ID);
9174
9314
  // Create modal
9175
9315
  const modal = document.createElement('div');
9176
9316
  modal.id = MODAL_ID;
@@ -9185,19 +9325,7 @@ class UploadModalContainer {
9185
9325
  const body = document.createElement('div');
9186
9326
  body.className = 'svu-body';
9187
9327
  // Create footer
9188
- const footer = document.createElement('div');
9189
- footer.className = 'svu-footer';
9190
- const footerText = document.createElement('span');
9191
- footerText.className = 'svu-footer-text';
9192
- footerText.appendChild(document.createTextNode('Secured by '));
9193
- const footerLink = document.createElement('a');
9194
- footerLink.href = 'https://sparkvault.com';
9195
- footerLink.target = '_blank';
9196
- footerLink.rel = 'noopener noreferrer';
9197
- footerLink.className = 'svu-footer-link';
9198
- footerLink.textContent = 'SparkVault';
9199
- footerText.appendChild(footerLink);
9200
- footer.appendChild(footerText);
9328
+ const footer = createFooter();
9201
9329
  main.appendChild(header);
9202
9330
  main.appendChild(body);
9203
9331
  main.appendChild(footer);
@@ -9221,47 +9349,15 @@ class UploadModalContainer {
9221
9349
  this.elements = { overlay, modal, main, header, body, footer, sidebar: null };
9222
9350
  }
9223
9351
  createHeader(branding) {
9224
- const header = document.createElement('div');
9225
- header.className = 'svu-header';
9226
- const titleContainer = document.createElement('div');
9227
- titleContainer.className = 'svu-header-title';
9228
- // Use light logo for light theme (default), dark logo for dark mode
9229
- const logoUrl = this.isDarkMode
9230
- ? branding.logoDarkUrl || branding.logoLightUrl
9231
- : branding.logoLightUrl || branding.logoDarkUrl;
9232
- if (logoUrl) {
9233
- const logo = document.createElement('img');
9234
- logo.className = 'svu-logo';
9235
- logo.src = logoUrl;
9236
- logo.alt = branding.organizationName;
9237
- titleContainer.appendChild(logo);
9238
- // Screen reader title
9239
- const srTitle = document.createElement('span');
9240
- srTitle.className = 'svu-sr-only';
9241
- srTitle.id = 'svu-modal-title';
9242
- srTitle.textContent = branding.organizationName;
9243
- titleContainer.appendChild(srTitle);
9244
- }
9245
- else if (branding.organizationName) {
9246
- const companyName = document.createElement('h2');
9247
- companyName.className = 'svu-company-name';
9248
- companyName.id = 'svu-modal-title';
9249
- companyName.textContent = branding.organizationName;
9250
- titleContainer.appendChild(companyName);
9251
- }
9252
- // Close button
9253
- this.closeBtn = document.createElement('button');
9254
- this.closeBtn.className = 'svu-close-btn';
9255
- this.closeBtn.setAttribute('aria-label', 'Close');
9256
- this.closeBtn.innerHTML = `
9257
- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9258
- <path d="M18 6L6 18M6 6l12 12"/>
9259
- </svg>
9260
- `;
9261
9352
  this.closeBtnClickHandler = () => this.handleClose();
9262
- this.closeBtn.addEventListener('click', this.closeBtnClickHandler);
9263
- header.appendChild(titleContainer);
9264
- 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;
9265
9361
  return header;
9266
9362
  }
9267
9363
  /**
@@ -9323,7 +9419,7 @@ class UploadModalContainer {
9323
9419
  return;
9324
9420
  if (show && !this.elements.sidebar) {
9325
9421
  // Create sidebar
9326
- const sidebar = this.createSecuritySidebar();
9422
+ const sidebar = createSecuritySidebar(this.branding);
9327
9423
  this.elements.modal.classList.add('svu-with-sidebar');
9328
9424
  this.elements.modal.appendChild(sidebar);
9329
9425
  this.elements.sidebar = sidebar;
@@ -9343,91 +9439,6 @@ class UploadModalContainer {
9343
9439
  }
9344
9440
  }
9345
9441
  }
9346
- createSecuritySidebar() {
9347
- const sidebar = document.createElement('div');
9348
- sidebar.className = 'svu-sidebar';
9349
- // Logo
9350
- const logoDiv = document.createElement('div');
9351
- logoDiv.className = 'svu-sidebar-logo';
9352
- if (this.branding.logoDarkUrl) {
9353
- const logo = document.createElement('img');
9354
- logo.src = this.branding.logoDarkUrl;
9355
- logo.alt = this.branding.organizationName;
9356
- logoDiv.appendChild(logo);
9357
- }
9358
- sidebar.appendChild(logoDiv);
9359
- // Intro
9360
- const intro = document.createElement('div');
9361
- intro.className = 'svu-sidebar-intro';
9362
- intro.innerHTML = `
9363
- <h3>Secure File Transfer</h3>
9364
- <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>
9365
- `;
9366
- sidebar.appendChild(intro);
9367
- // Security details
9368
- const security = document.createElement('div');
9369
- security.className = 'svu-sidebar-security';
9370
- security.innerHTML = `
9371
- <h4>
9372
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9373
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
9374
- </svg>
9375
- SparkVault's Triple Zero-Trust
9376
- </h4>
9377
- <p class="svu-security-intro">
9378
- Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.
9379
- </p>
9380
- <div class="svu-key-chain">
9381
- <div class="svu-key-item">
9382
- <div class="svu-key-number">1</div>
9383
- <div class="svu-key-info">
9384
- <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>
9385
- <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>
9386
- <span class="svu-key-desc">Quantum-resistant key exchange</span>
9387
- </div>
9388
- </div>
9389
- <div class="svu-key-connector">
9390
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9391
- <path d="M12 5v14M5 12h14"/>
9392
- </svg>
9393
- </div>
9394
- <div class="svu-key-item">
9395
- <div class="svu-key-number">2</div>
9396
- <div class="svu-key-info">
9397
- <span class="svu-key-name">X25519 Ephemeral Key</span>
9398
- <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>
9399
- <span class="svu-key-desc">Perfect forward secrecy</span>
9400
- </div>
9401
- </div>
9402
- <div class="svu-key-connector">
9403
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9404
- <path d="M12 5v14M5 12h14"/>
9405
- </svg>
9406
- </div>
9407
- <div class="svu-key-item">
9408
- <div class="svu-key-number">3</div>
9409
- <div class="svu-key-info">
9410
- <span class="svu-key-name">HKDF-SHA512 Derived Key</span>
9411
- <span class="svu-key-algo">Hardware-bound key derivation</span>
9412
- <span class="svu-key-desc">Vault master key in secure enclave</span>
9413
- </div>
9414
- </div>
9415
- </div>
9416
- <div class="svu-encryption-result">
9417
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9418
- <path d="M20 6L9 17l-5-5"/>
9419
- </svg>
9420
- <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>
9421
- </div>
9422
- <div class="svu-security-badges">
9423
- <span class="svu-tls-badge">TLS 1.3 In Transit</span>
9424
- <span class="svu-tls-badge">Encrypted At Rest</span>
9425
- <span class="svu-tls-badge">Zero Trust</span>
9426
- </div>
9427
- `;
9428
- sidebar.appendChild(security);
9429
- return sidebar;
9430
- }
9431
9442
  handleClose() {
9432
9443
  if (this.onCloseCallback) {
9433
9444
  this.onCloseCallback();
@@ -9520,10 +9531,7 @@ class UploadInlineContainer {
9520
9531
  }
9521
9532
  this.onCloseCallback = onClose;
9522
9533
  // Inject styles
9523
- injectUploadStyles({
9524
- branding: this.branding,
9525
- backdropBlur: false,
9526
- });
9534
+ injectUploadStyles();
9527
9535
  // Create main container
9528
9536
  this.container = document.createElement('div');
9529
9537
  this.container.className = 'svu-inline-container';
@@ -9538,19 +9546,7 @@ class UploadInlineContainer {
9538
9546
  this.container.appendChild(this.body);
9539
9547
  // Create footer if enabled
9540
9548
  if (this.containerOptions.showFooter) {
9541
- this.footer = document.createElement('div');
9542
- this.footer.className = 'svu-footer';
9543
- const footerText = document.createElement('span');
9544
- footerText.className = 'svu-footer-text';
9545
- footerText.appendChild(document.createTextNode('Secured by '));
9546
- const footerLink = document.createElement('a');
9547
- footerLink.href = 'https://sparkvault.com';
9548
- footerLink.target = '_blank';
9549
- footerLink.rel = 'noopener noreferrer';
9550
- footerLink.className = 'svu-footer-link';
9551
- footerLink.textContent = 'SparkVault';
9552
- footerText.appendChild(footerLink);
9553
- this.footer.appendChild(footerText);
9549
+ this.footer = createFooter();
9554
9550
  this.container.appendChild(this.footer);
9555
9551
  }
9556
9552
  // Clear target and append container
@@ -9608,7 +9604,7 @@ class UploadInlineContainer {
9608
9604
  return;
9609
9605
  if (show && !this.sidebar) {
9610
9606
  // Create sidebar
9611
- this.sidebar = this.createSecuritySidebar();
9607
+ this.sidebar = createSecuritySidebar(this.branding);
9612
9608
  this.container.classList.add('svu-with-sidebar');
9613
9609
  this.container.appendChild(this.sidebar);
9614
9610
  }
@@ -9659,134 +9655,16 @@ class UploadInlineContainer {
9659
9655
  this.onCloseCallback = null;
9660
9656
  }
9661
9657
  createHeader(branding) {
9662
- const header = document.createElement('div');
9663
- header.className = 'svu-header';
9664
- const titleContainer = document.createElement('div');
9665
- titleContainer.className = 'svu-header-title';
9666
- // Use appropriate logo based on dark mode
9667
- const logoUrl = this.isDarkMode
9668
- ? branding.logoDarkUrl || branding.logoLightUrl
9669
- : branding.logoLightUrl || branding.logoDarkUrl;
9670
- if (logoUrl) {
9671
- const logo = document.createElement('img');
9672
- logo.className = 'svu-logo';
9673
- logo.src = logoUrl;
9674
- logo.alt = branding.organizationName;
9675
- titleContainer.appendChild(logo);
9676
- // Screen reader title
9677
- const srTitle = document.createElement('span');
9678
- srTitle.className = 'svu-sr-only';
9679
- srTitle.textContent = branding.organizationName;
9680
- titleContainer.appendChild(srTitle);
9681
- }
9682
- else if (branding.organizationName) {
9683
- const companyName = document.createElement('h2');
9684
- companyName.className = 'svu-company-name';
9685
- companyName.textContent = branding.organizationName;
9686
- titleContainer.appendChild(companyName);
9687
- }
9688
- header.appendChild(titleContainer);
9689
- // Add close button if enabled
9690
- if (this.containerOptions.showCloseButton) {
9691
- this.closeBtn = document.createElement('button');
9692
- this.closeBtn.className = 'svu-close-btn';
9693
- this.closeBtn.setAttribute('aria-label', 'Close');
9694
- this.closeBtn.innerHTML = `
9695
- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9696
- <path d="M18 6L6 18M6 6l12 12"/>
9697
- </svg>
9698
- `;
9699
- this.closeBtnClickHandler = () => this.handleClose();
9700
- this.closeBtn.addEventListener('click', this.closeBtnClickHandler);
9701
- header.appendChild(this.closeBtn);
9702
- }
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;
9703
9666
  return header;
9704
9667
  }
9705
- createSecuritySidebar() {
9706
- const sidebar = document.createElement('div');
9707
- sidebar.className = 'svu-sidebar';
9708
- // Logo
9709
- const logoDiv = document.createElement('div');
9710
- logoDiv.className = 'svu-sidebar-logo';
9711
- if (this.branding.logoDarkUrl) {
9712
- const logo = document.createElement('img');
9713
- logo.src = this.branding.logoDarkUrl;
9714
- logo.alt = this.branding.organizationName;
9715
- logoDiv.appendChild(logo);
9716
- }
9717
- sidebar.appendChild(logoDiv);
9718
- // Intro
9719
- const intro = document.createElement('div');
9720
- intro.className = 'svu-sidebar-intro';
9721
- intro.innerHTML = `
9722
- <h3>Secure File Transfer</h3>
9723
- <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>
9724
- `;
9725
- sidebar.appendChild(intro);
9726
- // Security details
9727
- const security = document.createElement('div');
9728
- security.className = 'svu-sidebar-security';
9729
- security.innerHTML = `
9730
- <h4>
9731
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9732
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
9733
- </svg>
9734
- SparkVault's Triple Zero-Trust
9735
- </h4>
9736
- <p class="svu-security-intro">
9737
- Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.
9738
- </p>
9739
- <div class="svu-key-chain">
9740
- <div class="svu-key-item">
9741
- <div class="svu-key-number">1</div>
9742
- <div class="svu-key-info">
9743
- <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>
9744
- <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>
9745
- <span class="svu-key-desc">Quantum-resistant key exchange</span>
9746
- </div>
9747
- </div>
9748
- <div class="svu-key-connector">
9749
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9750
- <path d="M12 5v14M5 12h14"/>
9751
- </svg>
9752
- </div>
9753
- <div class="svu-key-item">
9754
- <div class="svu-key-number">2</div>
9755
- <div class="svu-key-info">
9756
- <span class="svu-key-name">X25519 Ephemeral Key</span>
9757
- <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>
9758
- <span class="svu-key-desc">Perfect forward secrecy</span>
9759
- </div>
9760
- </div>
9761
- <div class="svu-key-connector">
9762
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9763
- <path d="M12 5v14M5 12h14"/>
9764
- </svg>
9765
- </div>
9766
- <div class="svu-key-item">
9767
- <div class="svu-key-number">3</div>
9768
- <div class="svu-key-info">
9769
- <span class="svu-key-name">HKDF-SHA512 Derived Key</span>
9770
- <span class="svu-key-algo">Hardware-bound key derivation</span>
9771
- <span class="svu-key-desc">Vault master key in secure enclave</span>
9772
- </div>
9773
- </div>
9774
- </div>
9775
- <div class="svu-encryption-result">
9776
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9777
- <path d="M20 6L9 17l-5-5"/>
9778
- </svg>
9779
- <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>
9780
- </div>
9781
- <div class="svu-security-badges">
9782
- <span class="svu-tls-badge">TLS 1.3 In Transit</span>
9783
- <span class="svu-tls-badge">Encrypted At Rest</span>
9784
- <span class="svu-tls-badge">Zero Trust</span>
9785
- </div>
9786
- `;
9787
- sidebar.appendChild(security);
9788
- return sidebar;
9789
- }
9790
9668
  handleClose() {
9791
9669
  if (this.onCloseCallback) {
9792
9670
  this.onCloseCallback();
@@ -9829,6 +9707,14 @@ function generateRequestId() {
9829
9707
  const random = Array.from(randomBytes, byte => byte.toString(16).padStart(2, '0')).join('');
9830
9708
  return `${timestamp}${random}`;
9831
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
+ }
9832
9718
  /**
9833
9719
  * Format bytes to human readable string.
9834
9720
  */
@@ -9851,8 +9737,11 @@ class UploadRenderer {
9851
9737
  this.uploadModal = null;
9852
9738
  this.isInlineMode = false;
9853
9739
  this.hybridModalInitialized = false;
9854
- // Track active XHR for cancellation on close
9855
- 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;
9856
9745
  this.pasteHandler = null;
9857
9746
  this.container = container;
9858
9747
  this.api = api;
@@ -9893,16 +9782,13 @@ class UploadRenderer {
9893
9782
  }
9894
9783
  /**
9895
9784
  * Close the upload flow.
9896
- * 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.
9897
9787
  */
9898
9788
  close() {
9899
- // Cancel all pending API requests first
9789
+ this.closed = true;
9790
+ // Cancel all pending API requests and the active TUS transfer
9900
9791
  this.api.abort();
9901
- // Abort any active XHR upload
9902
- if (this.activeXhr) {
9903
- this.activeXhr.abort();
9904
- this.activeXhr = null;
9905
- }
9906
9792
  this.cleanupFileInput();
9907
9793
  this.cleanupPasteHandler();
9908
9794
  // Clean up modal if open (hybrid mode)
@@ -9913,14 +9799,64 @@ class UploadRenderer {
9913
9799
  }
9914
9800
  this.container.destroy();
9915
9801
  }
9916
- 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;
9917
9812
  this.close();
9918
9813
  this.callbacks.onCancel();
9919
9814
  }
9815
+ handleClose() {
9816
+ this.cancel();
9817
+ }
9920
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;
9921
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
+ }
9922
9835
  this.render();
9923
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
+ }
9924
9860
  render() {
9925
9861
  const isDarkState = this.viewState.view === 'uploading' || this.viewState.view === 'ceremony';
9926
9862
  // Hybrid mode: For inline containers, use a modal popup for upload/ceremony
@@ -10422,8 +10358,24 @@ class UploadRenderer {
10422
10358
  progress: 0,
10423
10359
  bytesUploaded: 0,
10424
10360
  });
10425
- // Upload file using tus (resumable upload)
10426
- 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
+ });
10427
10379
  // Confirm the server actually finalized the upload before celebrating.
10428
10380
  // The TUS loop trusts a server-provided offset; this re-reads the
10429
10381
  // server's own persisted offset and requires it to reach the file size,
@@ -10464,129 +10416,6 @@ class UploadRenderer {
10464
10416
  this.handleApiError(error);
10465
10417
  }
10466
10418
  }
10467
- async uploadWithTus(file, forgeUrl, ingotId, requestId) {
10468
- // tus resumable upload protocol v1.0.0
10469
- // Uploads file in chunks to avoid Cloudflare's 100MB request limit
10470
- const TUS_VERSION = '1.0.0';
10471
- const DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024; // 50MB default, server may override
10472
- // Extract base URL and ISTK from forge URL
10473
- const url = new URL(forgeUrl);
10474
- const istk = url.searchParams.get('istk');
10475
- const baseUrl = `${url.origin}${url.pathname}`;
10476
- if (!istk) {
10477
- throw new Error('Missing ISTK in forge URL');
10478
- }
10479
- // Step 1: Create tus upload session
10480
- const createResponse = await fetch(baseUrl, {
10481
- method: 'POST',
10482
- headers: {
10483
- 'Tus-Resumable': TUS_VERSION,
10484
- 'Upload-Length': String(file.size),
10485
- 'X-ISTK': istk,
10486
- 'Content-Type': 'application/offset+octet-stream',
10487
- },
10488
- });
10489
- if (!createResponse.ok) {
10490
- const errorText = await createResponse.text();
10491
- throw new Error(`Failed to create upload session: ${createResponse.status} ${errorText}`);
10492
- }
10493
- // Get upload location and chunk size from response
10494
- const location = createResponse.headers.get('Location');
10495
- const chunkSizeHeader = createResponse.headers.get('X-Chunk-Size');
10496
- const chunkSize = chunkSizeHeader ? parseInt(chunkSizeHeader, 10) : DEFAULT_CHUNK_SIZE;
10497
- if (!location) {
10498
- throw new Error('Server did not return upload location');
10499
- }
10500
- // Build full upload URL
10501
- const uploadUrl = location.startsWith('http') ? location : `${url.origin}${location}`;
10502
- // Step 2: Upload file in chunks with progress tracking
10503
- let offset = 0;
10504
- const totalSize = file.size;
10505
- while (offset < totalSize) {
10506
- const chunkStart = offset;
10507
- const chunkEnd = Math.min(offset + chunkSize, totalSize);
10508
- const chunk = file.slice(chunkStart, chunkEnd);
10509
- // Upload chunk with XHR for progress events
10510
- const newOffset = await this.uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, TUS_VERSION, file, ingotId, requestId);
10511
- offset = newOffset;
10512
- }
10513
- return uploadUrl;
10514
- }
10515
- /**
10516
- * Upload a single chunk using XMLHttpRequest for progress tracking.
10517
- * Tracks the XHR so it can be cancelled if the renderer is closed.
10518
- */
10519
- uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, tusVersion, file, ingotId, requestId) {
10520
- return new Promise((resolve, reject) => {
10521
- // Check if already aborted before starting
10522
- if (this.api.isAborted()) {
10523
- reject(new Error('Upload cancelled'));
10524
- return;
10525
- }
10526
- const xhr = new XMLHttpRequest();
10527
- // Track this XHR so it can be cancelled on close
10528
- this.activeXhr = xhr;
10529
- // Track progress within this chunk
10530
- xhr.upload.onprogress = (e) => {
10531
- if (e.lengthComputable) {
10532
- // Calculate total progress: completed chunks + progress within current chunk
10533
- const totalUploaded = chunkStart + e.loaded;
10534
- const progress = Math.round((totalUploaded / totalSize) * 100);
10535
- this.setState({
10536
- view: 'uploading',
10537
- file,
10538
- ingotId,
10539
- requestId,
10540
- progress,
10541
- bytesUploaded: totalUploaded,
10542
- });
10543
- this.callbacks.onProgress?.({
10544
- bytesUploaded: totalUploaded,
10545
- bytesTotal: totalSize,
10546
- percentage: progress,
10547
- phase: 'uploading',
10548
- });
10549
- }
10550
- };
10551
- xhr.onload = () => {
10552
- this.activeXhr = null;
10553
- if (xhr.status >= 200 && xhr.status < 300) {
10554
- // Get new offset from server response
10555
- const newOffsetHeader = xhr.getResponseHeader('Upload-Offset');
10556
- const newOffset = newOffsetHeader ? parseInt(newOffsetHeader, 10) : chunkStart + chunk.size;
10557
- // Defense-in-depth: the server must never report more bytes accepted
10558
- // than the file contains. A `newOffset > totalSize` is a malformed or
10559
- // inflated response — reject it rather than letting an over-reported
10560
- // offset short-circuit the upload loop and skip real chunks.
10561
- if (!Number.isFinite(newOffset) || newOffset < chunkStart || newOffset > totalSize) {
10562
- reject(new Error(`Server returned invalid upload offset (${newOffset})`));
10563
- return;
10564
- }
10565
- resolve(newOffset);
10566
- }
10567
- else {
10568
- reject(new Error(`Chunk upload failed with status ${xhr.status}`));
10569
- }
10570
- };
10571
- xhr.onerror = () => {
10572
- this.activeXhr = null;
10573
- reject(new Error('Chunk upload failed'));
10574
- };
10575
- xhr.ontimeout = () => {
10576
- this.activeXhr = null;
10577
- reject(new Error('Chunk upload timed out'));
10578
- };
10579
- xhr.onabort = () => {
10580
- this.activeXhr = null;
10581
- reject(new Error('Upload cancelled'));
10582
- };
10583
- xhr.open('PATCH', uploadUrl);
10584
- xhr.setRequestHeader('Tus-Resumable', tusVersion);
10585
- xhr.setRequestHeader('Upload-Offset', String(chunkStart));
10586
- xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream');
10587
- xhr.send(chunk);
10588
- });
10589
- }
10590
10419
  async runCeremony(file, ingotId, requestId) {
10591
10420
  for (let i = 0; i < CEREMONY_STEPS.length; i++) {
10592
10421
  this.setState({
@@ -10617,6 +10446,14 @@ class UploadRenderer {
10617
10446
  await new Promise(resolve => setTimeout(resolve, 500));
10618
10447
  }
10619
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
+ }
10620
10457
  if (error instanceof UploadApiError) {
10621
10458
  if (error.code === 'UPLOAD_SOURCE_DISABLED') {
10622
10459
  // The vault exists but the embedded widget isn't enabled.
@@ -10686,7 +10523,6 @@ class UploadRenderer {
10686
10523
  }
10687
10524
  }
10688
10525
 
10689
- /* global Element */
10690
10526
  /**
10691
10527
  * Vault Upload Module
10692
10528
  *
@@ -10707,7 +10543,6 @@ class UploadRenderer {
10707
10543
  class VaultUploadModule {
10708
10544
  constructor(config) {
10709
10545
  this.renderer = null;
10710
- this.attachedElements = new Map();
10711
10546
  this.config = config;
10712
10547
  this.api = new UploadApi(config);
10713
10548
  }
@@ -10731,9 +10566,10 @@ class VaultUploadModule {
10731
10566
  if (!options.vaultId) {
10732
10567
  throw new ValidationError('vaultId is required');
10733
10568
  }
10734
- // Close any existing renderer
10569
+ // Cancel any existing renderer so its pending promise settles via the
10570
+ // cancel contract (onCancel + UserCancelledError) instead of hanging.
10735
10571
  if (this.renderer) {
10736
- this.renderer.close();
10572
+ this.renderer.cancel();
10737
10573
  }
10738
10574
  const isInline = !!options.target;
10739
10575
  const container = isInline
@@ -10792,7 +10628,6 @@ class VaultUploadModule {
10792
10628
  if (!options.vaultId) {
10793
10629
  throw new ValidationError('vaultId is required');
10794
10630
  }
10795
- let observer = null;
10796
10631
  const handleClick = async (event) => {
10797
10632
  event.preventDefault();
10798
10633
  try {
@@ -10808,55 +10643,17 @@ class VaultUploadModule {
10808
10643
  // Error already handled by callbacks or will use server redirect
10809
10644
  }
10810
10645
  };
10811
- const attachToElements = () => {
10812
- const elements = document.querySelectorAll(selector);
10813
- elements.forEach((element) => {
10814
- element.addEventListener('click', handleClick);
10815
- this.attachedElements.set(element, () => {
10816
- element.removeEventListener('click', handleClick);
10817
- });
10818
- });
10819
- // Watch for dynamically added elements
10820
- observer = new MutationObserver((mutations) => {
10821
- mutations.forEach((mutation) => {
10822
- mutation.addedNodes.forEach((node) => {
10823
- if (node instanceof Element) {
10824
- if (node.matches(selector)) {
10825
- node.addEventListener('click', handleClick);
10826
- this.attachedElements.set(node, () => {
10827
- node.removeEventListener('click', handleClick);
10828
- });
10829
- }
10830
- // Check descendants
10831
- node.querySelectorAll(selector).forEach((el) => {
10832
- if (!this.attachedElements.has(el)) {
10833
- el.addEventListener('click', handleClick);
10834
- this.attachedElements.set(el, () => {
10835
- el.removeEventListener('click', handleClick);
10836
- });
10837
- }
10838
- });
10839
- }
10840
- });
10841
- });
10842
- });
10843
- observer.observe(document.body, { childList: true, subtree: true });
10844
- };
10845
- // Defer attachment until DOM is ready
10846
- onDomReady(attachToElements);
10847
- // Return cleanup function
10848
- return () => {
10849
- observer?.disconnect();
10850
- this.attachedElements.forEach((cleanup) => cleanup());
10851
- this.attachedElements.clear();
10852
- };
10646
+ return attachClickHandler(selector, handleClick);
10853
10647
  }
10854
10648
  /**
10855
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.
10856
10653
  */
10857
10654
  close() {
10858
10655
  if (this.renderer) {
10859
- this.renderer.close();
10656
+ this.renderer.cancel();
10860
10657
  this.renderer = null;
10861
10658
  }
10862
10659
  }
@@ -10880,9 +10677,9 @@ class VaultUploadModule {
10880
10677
  }
10881
10678
  return new UploadInlineContainer(element);
10882
10679
  }
10883
- // Public-API aliases. The web vault-edit screen instructs customers to
10884
- // call sv.vaults.upload.pop(vaultId) / .render(vaultId, target) — both
10885
- // 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().
10886
10683
  /** Open the upload widget as a popup. Equivalent to `upload(options)`. */
10887
10684
  async pop(options) {
10888
10685
  return this.upload(options);
@@ -10904,10 +10701,13 @@ class VaultsModule {
10904
10701
  this.config = config;
10905
10702
  this.http = http;
10906
10703
  this.uploadModule = new VaultUploadModule(config);
10907
- // 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
10908
10706
  const uploadFn = ((options) => this.uploadModule.upload(options));
10909
10707
  uploadFn.attach = (selector, options) => this.uploadModule.attach(selector, options);
10910
10708
  uploadFn.close = () => this.uploadModule.close();
10709
+ uploadFn.pop = (options) => this.uploadModule.pop(options);
10710
+ uploadFn.render = (options) => this.uploadModule.render(options);
10911
10711
  this.upload = uploadFn;
10912
10712
  }
10913
10713
  /**
@@ -11015,7 +10815,11 @@ class VaultsModule {
11015
10815
  if (!created.forge_url) {
11016
10816
  throw new ValidationError('Upload endpoint did not return a Forge upload URL');
11017
10817
  }
11018
- 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);
11019
10823
  return {
11020
10824
  id: created.ingot_id,
11021
10825
  name: created.name,
@@ -11125,78 +10929,6 @@ function getBlobName(file) {
11125
10929
  }
11126
10930
  return 'unnamed';
11127
10931
  }
11128
- function base64Encode(value) {
11129
- return btoa(unescape(encodeURIComponent(value)));
11130
- }
11131
- async function uploadBlobWithTus(file, forgeUrl, filename, contentType, onProgress) {
11132
- if (typeof XMLHttpRequest === 'undefined') {
11133
- throw new ValidationError('XMLHttpRequest is required for browser ingot uploads');
11134
- }
11135
- const tusVersion = '1.0.0';
11136
- const defaultChunkSize = 50 * 1024 * 1024;
11137
- const url = new URL(forgeUrl);
11138
- const istk = url.searchParams.get('istk');
11139
- const endpoint = `${url.origin}${url.pathname}`;
11140
- if (!istk) {
11141
- throw new ValidationError('Forge upload URL is missing ISTK');
11142
- }
11143
- const createResponse = await fetch(endpoint, {
11144
- method: 'POST',
11145
- headers: {
11146
- 'Tus-Resumable': tusVersion,
11147
- 'Upload-Length': String(file.size),
11148
- 'Upload-Metadata': `filename ${base64Encode(filename)},filetype ${base64Encode(contentType)}`,
11149
- 'X-ISTK': istk,
11150
- },
11151
- });
11152
- if (!createResponse.ok) {
11153
- const errorText = await createResponse.text();
11154
- throw new Error(`Failed to create upload session: ${createResponse.status} ${errorText}`);
11155
- }
11156
- const location = createResponse.headers.get('Location');
11157
- const chunkSizeHeader = createResponse.headers.get('X-Chunk-Size');
11158
- const chunkSize = chunkSizeHeader ? parseInt(chunkSizeHeader, 10) : defaultChunkSize;
11159
- if (!location) {
11160
- throw new Error('Server did not return upload location');
11161
- }
11162
- const uploadUrl = location.startsWith('http') ? location : `${url.origin}${location}`;
11163
- let offset = 0;
11164
- while (offset < file.size) {
11165
- const chunkStart = offset;
11166
- const chunkEnd = Math.min(offset + chunkSize, file.size);
11167
- const chunk = file.slice(chunkStart, chunkEnd);
11168
- offset = await uploadChunkWithProgress(uploadUrl, chunk, chunkStart, file.size, tusVersion, istk, onProgress);
11169
- }
11170
- }
11171
- function uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, tusVersion, istk, onProgress) {
11172
- return new Promise((resolve, reject) => {
11173
- const xhr = new XMLHttpRequest();
11174
- xhr.upload.onprogress = (event) => {
11175
- if (event.lengthComputable) {
11176
- onProgress?.(chunkStart + event.loaded, totalSize);
11177
- }
11178
- };
11179
- xhr.onload = () => {
11180
- if (xhr.status >= 200 && xhr.status < 300) {
11181
- const newOffsetHeader = xhr.getResponseHeader('Upload-Offset');
11182
- const newOffset = newOffsetHeader ? parseInt(newOffsetHeader, 10) : chunkStart + chunk.size;
11183
- resolve(newOffset);
11184
- }
11185
- else {
11186
- reject(new Error(`Chunk upload failed with status ${xhr.status}`));
11187
- }
11188
- };
11189
- xhr.onerror = () => reject(new Error('Chunk upload failed'));
11190
- xhr.ontimeout = () => reject(new Error('Chunk upload timed out'));
11191
- xhr.onabort = () => reject(new Error('Upload cancelled'));
11192
- xhr.open('PATCH', uploadUrl);
11193
- xhr.setRequestHeader('Tus-Resumable', tusVersion);
11194
- xhr.setRequestHeader('Upload-Offset', String(chunkStart));
11195
- xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream');
11196
- xhr.setRequestHeader('X-ISTK', istk);
11197
- xhr.send(chunk);
11198
- });
11199
- }
11200
10932
  const DOWNLOAD_MAX_ATTEMPTS = 3;
11201
10933
  const DOWNLOAD_RETRY_BASE_MS = 500;
11202
10934
  function delayExponential(attempt) {