@sparkvault/sdk-js 2.2.1 → 2.2.3

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.
@@ -36,6 +36,38 @@ class ValidationError extends SparkVaultError {
36
36
  Object.setPrototypeOf(this, ValidationError.prototype);
37
37
  }
38
38
  }
39
+ /**
40
+ * Plan required gate (402 PLAN_REQUIRED) — the account has no active
41
+ * subscription and attempted a billable/create action. Surface a subscribe CTA
42
+ * to admins, or "ask your account admin" to members.
43
+ */
44
+ class PlanRequiredError extends SparkVaultError {
45
+ constructor(message, details) {
46
+ super(message, 'PLAN_REQUIRED', 402, details);
47
+ this.name = 'PlanRequiredError';
48
+ Object.setPrototypeOf(this, PlanRequiredError.prototype);
49
+ }
50
+ }
51
+ /**
52
+ * Quota exceeded gate (402 QUOTA_EXCEEDED) — a pooled-capacity or seat limit is
53
+ * exhausted. `resource` identifies which pool so callers can branch on the CTA
54
+ * (add a capacity block for storage/bandwidth, free a seat for seats).
55
+ */
56
+ class QuotaExceededError extends SparkVaultError {
57
+ constructor(message, details) {
58
+ super(message, 'QUOTA_EXCEEDED', 402, details);
59
+ this.name = 'QuotaExceededError';
60
+ const resource = details?.resource;
61
+ this.resource =
62
+ resource === 'storage' ||
63
+ resource === 'bandwidth' ||
64
+ resource === 'seats' ||
65
+ resource === 'identity'
66
+ ? resource
67
+ : undefined;
68
+ Object.setPrototypeOf(this, QuotaExceededError.prototype);
69
+ }
70
+ }
39
71
  class NetworkError extends SparkVaultError {
40
72
  constructor(message, details) {
41
73
  super(message, 'network_error', undefined, details);
@@ -157,103 +189,6 @@ function validateConfig(config) {
157
189
  }
158
190
  }
159
191
 
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
192
  /**
258
193
  * SparkVault SDK HTTP Client
259
194
  */
@@ -287,22 +222,6 @@ class HttpClient {
287
222
  return this.config.accessToken ?? null;
288
223
  }
289
224
  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
225
  const { method = 'GET', headers = {}, body, timeout = this.config.timeout, } = options;
307
226
  const url = `${this.config.apiBaseUrl}${path}`;
308
227
  const requestHeaders = await this.getDefaultHeaders(headers, body !== undefined);
@@ -322,6 +241,7 @@ class HttpClient {
322
241
  }
323
242
  return {
324
243
  data: this.unwrapApiResponse(parsed),
244
+ meta: this.extractResponseMeta(parsed),
325
245
  status: response.status,
326
246
  headers: response.headers,
327
247
  };
@@ -340,21 +260,6 @@ class HttpClient {
340
260
  throw new SparkVaultError(error instanceof Error ? error.message : 'Unknown error', 'unknown_error');
341
261
  }
342
262
  }
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
263
  async parseResponse(response) {
359
264
  // Handle empty responses (204 No Content, etc.)
360
265
  // Callers expecting no body should use <void> as the generic type parameter.
@@ -397,6 +302,11 @@ class HttpClient {
397
302
  return new ValidationError(message, details);
398
303
  case 401:
399
304
  return new AuthenticationError(message, details);
305
+ case 402:
306
+ if (code === 'QUOTA_EXCEEDED')
307
+ return new QuotaExceededError(message, details);
308
+ // PLAN_REQUIRED is the canonical 402 gate; treat any other 402 as one too.
309
+ return new PlanRequiredError(message, details);
400
310
  case 403:
401
311
  return new AuthorizationError(message, details);
402
312
  default:
@@ -412,75 +322,28 @@ class HttpClient {
412
322
  }
413
323
  return data;
414
324
  }
325
+ /**
326
+ * Pull the `meta` envelope (carrying `pools` capacity snapshots) off a
327
+ * standard `{ data, meta }` response. Returns undefined for bare responses.
328
+ */
329
+ extractResponseMeta(data) {
330
+ if (typeof data === 'object' && data !== null) {
331
+ const record = data;
332
+ if (typeof record.meta === 'object' && record.meta !== null) {
333
+ return record.meta;
334
+ }
335
+ }
336
+ return undefined;
337
+ }
415
338
  get(path, options) {
416
339
  return this.request(path, { ...options, method: 'GET' });
417
340
  }
418
341
  post(path, body, options) {
419
342
  return this.request(path, { ...options, method: 'POST', body });
420
343
  }
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
344
  delete(path, options) {
428
345
  return this.request(path, { ...options, method: 'DELETE' });
429
346
  }
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
347
  }
485
348
 
486
349
  class HealthModule {
@@ -557,6 +420,37 @@ class HealthModule {
557
420
  */
558
421
  /** Default request timeout in milliseconds (30 seconds). */
559
422
  const DEFAULT_TIMEOUT_MS = 30000;
423
+ /**
424
+ * Combine a fresh timeout with a session close signal into one AbortSignal.
425
+ *
426
+ * The returned dispose() MUST run in a finally block: it clears the timeout
427
+ * and unlinks the close listener (the fallback path for browsers without
428
+ * AbortSignal.any) so nothing leaks across requests. Callers discriminate
429
+ * close-vs-timeout afterwards by checking the close signal's aborted flag.
430
+ */
431
+ function combineTimeoutAndCloseSignals(timeoutMs, closeSignal) {
432
+ const timeoutController = new AbortController();
433
+ const timeoutId = setTimeout(() => timeoutController.abort(), timeoutMs);
434
+ let signal;
435
+ let onCloseAbort = null;
436
+ if ('any' in AbortSignal) {
437
+ signal = AbortSignal.any([timeoutController.signal, closeSignal]);
438
+ }
439
+ else {
440
+ signal = timeoutController.signal;
441
+ onCloseAbort = () => timeoutController.abort();
442
+ closeSignal.addEventListener('abort', onCloseAbort);
443
+ }
444
+ return {
445
+ signal,
446
+ dispose: () => {
447
+ clearTimeout(timeoutId);
448
+ if (onCloseAbort) {
449
+ closeSignal.removeEventListener('abort', onCloseAbort);
450
+ }
451
+ },
452
+ };
453
+ }
560
454
  class SparkVaultApi {
561
455
  constructor(timeoutMs = DEFAULT_TIMEOUT_MS) {
562
456
  /**
@@ -603,24 +497,7 @@ class SparkVaultApi {
603
497
  if (localCloseController.signal.aborted) {
604
498
  throw this.makeError('Request cancelled', 'cancelled', 0);
605
499
  }
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
- }
500
+ const { signal: combinedSignal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, localCloseController.signal);
624
501
  try {
625
502
  // Only send Content-Type when there's actually a body — otherwise GETs
626
503
  // with no payload would carry a misleading content-type header.
@@ -662,10 +539,7 @@ class SparkVaultApi {
662
539
  throw this.makeError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
663
540
  }
664
541
  finally {
665
- clearTimeout(timeoutId);
666
- if (onCloseAbort) {
667
- localCloseController.signal.removeEventListener('abort', onCloseAbort);
668
- }
542
+ dispose();
669
543
  }
670
544
  }
671
545
  }
@@ -872,9 +746,7 @@ function base64urlToArrayBuffer(base64url) {
872
746
  * @returns Decoded UTF-8 string
873
747
  */
874
748
  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);
749
+ return new TextDecoder().decode(base64urlDecode(base64url));
878
750
  }
879
751
 
880
752
  /**
@@ -1222,6 +1094,28 @@ class IdentityApi extends SparkVaultApi {
1222
1094
  ...this.buildAuthContextParams(authContext),
1223
1095
  });
1224
1096
  }
1097
+ /**
1098
+ * Claim the SparkLink verification result by kindling — the WebSocket-loss
1099
+ * fallback. The SDK calls this when its socket was suspended with the tab and
1100
+ * it refocuses. Returns the verified result, or null while still pending (not
1101
+ * yet clicked) or already consumed. The read burns the server-side spark, so
1102
+ * the result can be claimed exactly once.
1103
+ */
1104
+ async consumeSparkLinkResult(kindling) {
1105
+ const data = await this.request('GET', `/sparklink/result?kindling=${encodeURIComponent(kindling)}`);
1106
+ if (!data || typeof data !== 'object' || typeof data.token !== 'string') {
1107
+ return null;
1108
+ }
1109
+ return {
1110
+ token: data.token,
1111
+ identity: data.identity,
1112
+ identityType: data.identityType || 'email',
1113
+ svid: typeof data.svid === 'string' ? data.svid : undefined,
1114
+ sessionId: typeof data.session_id === 'string' ? data.session_id : undefined,
1115
+ refreshToken: typeof data.refresh_token === 'string' ? data.refresh_token : undefined,
1116
+ redirect: typeof data.redirect === 'string' ? data.redirect : undefined,
1117
+ };
1118
+ }
1225
1119
  }
1226
1120
  class IdentityApiError extends SparkVaultError {
1227
1121
  constructor(message, code, statusCode, details) {
@@ -1351,8 +1245,7 @@ function enrichMethods(ids) {
1351
1245
  /**
1352
1246
  * Verification State Manager
1353
1247
  *
1354
- * Single source of truth for all verification flow state.
1355
- * Centralizes scattered state from IdentityRenderer for:
1248
+ * Single source of truth for all verification flow state:
1356
1249
  * - Predictable state transitions
1357
1250
  * - Easier debugging and testing
1358
1251
  * - Clear data ownership
@@ -1382,25 +1275,6 @@ class VerificationState {
1382
1275
  kindling: '',
1383
1276
  method: null,
1384
1277
  };
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
1278
  }
1405
1279
  // --- SDK Config ---
1406
1280
  get sdkConfig() {
@@ -1412,24 +1286,6 @@ class VerificationState {
1412
1286
  get accountId() {
1413
1287
  return this._sdkConfig?.accountId ?? '';
1414
1288
  }
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
1289
  /**
1434
1290
  * Check if passkey method is enabled in config
1435
1291
  */
@@ -1442,7 +1298,6 @@ class VerificationState {
1442
1298
  }
1443
1299
  setViewState(state) {
1444
1300
  this._viewState = state;
1445
- this.notify();
1446
1301
  }
1447
1302
  // --- Identity ---
1448
1303
  get recipient() {
@@ -1518,21 +1373,6 @@ class VerificationState {
1518
1373
  setTotpMethod(method) {
1519
1374
  this._totp.method = method;
1520
1375
  }
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
1376
  }
1537
1377
 
1538
1378
  /**
@@ -2028,6 +1868,7 @@ class SparkLinkHandler {
2028
1868
  success: true,
2029
1869
  sparkId: result.sparkId,
2030
1870
  expiresAt: result.expiresAt,
1871
+ kindling: result.kindling,
2031
1872
  };
2032
1873
  }
2033
1874
  catch (error) {
@@ -5766,6 +5607,13 @@ class IdentityRenderer {
5766
5607
  this.focusTimeoutId = null;
5767
5608
  // SparkLink WebSocket
5768
5609
  this.sparkLinkWs = null;
5610
+ // SparkLink WebSocket-loss fallback: the login kindling lets the SDK reclaim
5611
+ // the verified result if the socket was suspended with the tab (mobile). The
5612
+ // visibility handler fires the single re-check on refocus.
5613
+ this.sparkLinkKindling = null;
5614
+ this.sparkLinkVisibilityHandler = null;
5615
+ this.sparkLinkClaiming = false;
5616
+ this.sparkLinkRetryTimer = null;
5769
5617
  this.container = container;
5770
5618
  this.api = api;
5771
5619
  this.options = options;
@@ -6116,6 +5964,11 @@ class IdentityRenderer {
6116
5964
  * actual list of alternatives instead of bouncing back to passkey.
6117
5965
  */
6118
5966
  async showMethodSelect(options = {}) {
5967
+ // Leaving the SparkLink waiting view (e.g. "Choose another method") must
5968
+ // tear down its WebSocket + refocus listeners and clear the kindling, or a
5969
+ // later tab refocus would fire a stale claim for an abandoned flow.
5970
+ // Idempotent — a no-op when SparkLink was never armed.
5971
+ this.cleanupSparkLink();
6119
5972
  const autoRoute = options.autoRoute !== false;
6120
5973
  if (!this.sdkConfig)
6121
5974
  return;
@@ -6281,6 +6134,11 @@ class IdentityRenderer {
6281
6134
  });
6282
6135
  return;
6283
6136
  }
6137
+ // Arm the WebSocket-loss fallback: keep the kindling and re-check for
6138
+ // the result whenever the tab is brought back to the foreground with
6139
+ // a dead socket (the mobile email round-trip).
6140
+ this.sparkLinkKindling = result.kindling ?? null;
6141
+ this.armSparkLinkRefocusClaim();
6284
6142
  this.setState({
6285
6143
  view: 'sparklink-waiting',
6286
6144
  email: this.recipient,
@@ -6798,7 +6656,14 @@ class IdentityRenderer {
6798
6656
  * delegate navigation entirely to the SDK.
6799
6657
  */
6800
6658
  async handleSparkLinkVerified(result) {
6659
+ // Burn the server-side fallback spark so a completed login never leaves a
6660
+ // second claimable auth path floating around. Capture the kindling before
6661
+ // cleanup clears it; fire-and-forget (the WS path may already have it).
6662
+ const kindling = this.sparkLinkKindling;
6801
6663
  this.cleanupSparkLink();
6664
+ if (kindling) {
6665
+ void this.api.consumeSparkLinkResult(kindling).catch(() => { });
6666
+ }
6802
6667
  // Passkey upsell only when there's no redirect target — once we have
6803
6668
  // a destination we go there immediately, no upsell.
6804
6669
  if (!result.redirect && await this.shouldShowPasskeyPrompt()) {
@@ -6809,11 +6674,11 @@ class IdentityRenderer {
6809
6674
  });
6810
6675
  return;
6811
6676
  }
6812
- this.close();
6813
- // Hand the full result (including redirect) to the host first so the
6814
- // page-level handler can do app-specific work (logging, navigation,
6815
- // etc.) before we steal the browsing context with a navigation.
6677
+ // Hand the full result (including redirect) to the host BEFORE tearing down
6678
+ // the modal, so the host's onSuccess can act (logging, navigation) without
6679
+ // racing the teardown of the browsing context.
6816
6680
  this.safeOnSuccess(result);
6681
+ this.close();
6817
6682
  // SDK-side fallback navigation. If the host already navigated this is
6818
6683
  // a no-op (the document is already unloading); if not, this rescues
6819
6684
  // simple-mode flows whose host forgot to act on result.redirect.
@@ -6821,6 +6686,67 @@ class IdentityRenderer {
6821
6686
  navigateWith(this.options, result.redirect);
6822
6687
  }
6823
6688
  }
6689
+ /**
6690
+ * Arm the WebSocket-loss fallback for the waiting screen.
6691
+ *
6692
+ * While waiting for the emailed link, the socket can be dropped when the tab
6693
+ * is suspended (mobile: the user leaves to the mail app). On refocus, if the
6694
+ * socket is no longer open, reclaim the verified result once by kindling. A
6695
+ * single ~2s retry covers returning before the server finished writing it.
6696
+ * Deliberately NOT a polling loop — it fires only on refocus, and only when
6697
+ * the socket is actually gone.
6698
+ */
6699
+ armSparkLinkRefocusClaim() {
6700
+ if (this.sparkLinkVisibilityHandler || !this.sparkLinkKindling)
6701
+ return;
6702
+ if (typeof document === 'undefined')
6703
+ return;
6704
+ const handler = () => {
6705
+ if (typeof document !== 'undefined' && document.visibilityState !== 'visible')
6706
+ return;
6707
+ // Healthy socket → the push path owns completion; nothing to reclaim.
6708
+ if (this.sparkLinkWs && this.sparkLinkWs.readyState === WebSocket.OPEN)
6709
+ return;
6710
+ void this.claimSparkLinkResult(true);
6711
+ };
6712
+ this.sparkLinkVisibilityHandler = handler;
6713
+ document.addEventListener('visibilitychange', handler);
6714
+ if (typeof window !== 'undefined') {
6715
+ window.addEventListener('pageshow', handler);
6716
+ }
6717
+ }
6718
+ /**
6719
+ * Reclaim the verified result by kindling. Single attempt; if still pending
6720
+ * and allowRetry, schedule exactly one ~2s retry, then stop (the next refocus
6721
+ * or Resend can try again).
6722
+ */
6723
+ async claimSparkLinkResult(allowRetry) {
6724
+ const kindling = this.sparkLinkKindling;
6725
+ if (!kindling || this.sparkLinkClaiming)
6726
+ return;
6727
+ this.sparkLinkClaiming = true;
6728
+ let result = null;
6729
+ try {
6730
+ result = await this.api.consumeSparkLinkResult(kindling);
6731
+ }
6732
+ catch {
6733
+ result = null;
6734
+ }
6735
+ this.sparkLinkClaiming = false;
6736
+ if (result) {
6737
+ await this.handleSparkLinkVerified(result);
6738
+ return;
6739
+ }
6740
+ // Pending — the click may still be processing server-side. One short retry,
6741
+ // then stop. No ongoing polling. Tracked so cleanup can cancel it.
6742
+ if (allowRetry && this.sparkLinkKindling === kindling) {
6743
+ this.sparkLinkRetryTimer = setTimeout(() => {
6744
+ this.sparkLinkRetryTimer = null;
6745
+ if (this.sparkLinkKindling === kindling)
6746
+ void this.claimSparkLinkResult(false);
6747
+ }, 2000);
6748
+ }
6749
+ }
6824
6750
  /**
6825
6751
  * Clean up SparkLink WebSocket connection.
6826
6752
  */
@@ -6832,6 +6758,20 @@ class IdentityRenderer {
6832
6758
  this.sparkLinkWs.close();
6833
6759
  this.sparkLinkWs = null;
6834
6760
  }
6761
+ if (this.sparkLinkVisibilityHandler) {
6762
+ if (typeof document !== 'undefined') {
6763
+ document.removeEventListener('visibilitychange', this.sparkLinkVisibilityHandler);
6764
+ }
6765
+ if (typeof window !== 'undefined') {
6766
+ window.removeEventListener('pageshow', this.sparkLinkVisibilityHandler);
6767
+ }
6768
+ this.sparkLinkVisibilityHandler = null;
6769
+ }
6770
+ if (this.sparkLinkRetryTimer !== null) {
6771
+ clearTimeout(this.sparkLinkRetryTimer);
6772
+ this.sparkLinkRetryTimer = null;
6773
+ }
6774
+ this.sparkLinkKindling = null;
6835
6775
  }
6836
6776
  /**
6837
6777
  * Handle resending SparkLink.
@@ -6858,6 +6798,10 @@ class IdentityRenderer {
6858
6798
  }
6859
6799
  const result = await this.sparkLinkHandler.send(wsResult.connectionId);
6860
6800
  if (result.success) {
6801
+ // Re-arm the fallback against the resend's fresh kindling (openSparkLink-
6802
+ // WebSocket cleared the previous one).
6803
+ this.sparkLinkKindling = result.kindling ?? null;
6804
+ this.armSparkLinkRefocusClaim();
6861
6805
  this.setState({
6862
6806
  view: 'sparklink-waiting',
6863
6807
  email: this.recipient,
@@ -7089,6 +7033,26 @@ class WidgetEmbedder {
7089
7033
  this.close();
7090
7034
  window.location.href = url.toString();
7091
7035
  }
7036
+ /**
7037
+ * Navigate the host top window to a widget-supplied URL — only when it
7038
+ * resolves to http(s). The sender is already constrained to the trusted
7039
+ * widget origin, but defense-in-depth across the SparkVault->customer
7040
+ * boundary: compromised widget-origin code must never escalate into script
7041
+ * execution on the embedding page via a javascript:/data: navigation.
7042
+ */
7043
+ safeNavigate(url) {
7044
+ let resolved;
7045
+ try {
7046
+ resolved = new URL(url, window.location.href);
7047
+ }
7048
+ catch {
7049
+ return;
7050
+ }
7051
+ if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') {
7052
+ return;
7053
+ }
7054
+ window.location.href = resolved.href;
7055
+ }
7092
7056
  buildUrl() {
7093
7057
  const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/widget`);
7094
7058
  url.searchParams.set('origin', window.location.origin);
@@ -7139,7 +7103,7 @@ class WidgetEmbedder {
7139
7103
  // iframe; on return the host SDK consumes the redirect token.
7140
7104
  if (data.type === REDIRECT_TYPE && typeof data.url === 'string') {
7141
7105
  this.clearReadyTimer();
7142
- window.location.href = data.url;
7106
+ this.safeNavigate(data.url);
7143
7107
  return;
7144
7108
  }
7145
7109
  if (data.type !== RESULT_TYPE || this.settled)
@@ -7152,7 +7116,7 @@ class WidgetEmbedder {
7152
7116
  // Mirror the renderer's belt-and-suspenders: complete a server-issued
7153
7117
  // redirect from the host's own top window if the customer didn't.
7154
7118
  if (typeof result.redirect === 'string' && result.redirect) {
7155
- window.location.href = result.redirect;
7119
+ this.safeNavigate(result.redirect);
7156
7120
  }
7157
7121
  }
7158
7122
  else if (data.cancelled) {
@@ -7355,6 +7319,7 @@ class InlineContainer {
7355
7319
  }
7356
7320
  }
7357
7321
 
7322
+ /* global Element */
7358
7323
  /**
7359
7324
  * DOM Utilities
7360
7325
  *
@@ -7403,8 +7368,62 @@ function onBodyReady(callback) {
7403
7368
  }
7404
7369
  }
7405
7370
  }
7371
+ /**
7372
+ * Attach a click handler to every element matching `selector` — both elements
7373
+ * present once the DOM is ready and elements added later (observed via
7374
+ * MutationObserver).
7375
+ *
7376
+ * Each call is fully self-contained: the element bookkeeping lives in this
7377
+ * closure, so the returned cleanup removes only the listeners this call
7378
+ * registered. Multiple attachments — different selectors, or even the same
7379
+ * element attached twice — never interfere with one another.
7380
+ *
7381
+ * @param selector - CSS selector for elements to attach to
7382
+ * @param onClick - Click handler to register on every matching element
7383
+ * @returns Cleanup function that removes this call's listeners and observer
7384
+ */
7385
+ function attachClickHandler(selector, onClick) {
7386
+ let observer = null;
7387
+ let cleanedUp = false;
7388
+ const attached = new Map();
7389
+ const listen = (element) => {
7390
+ if (attached.has(element))
7391
+ return;
7392
+ element.addEventListener('click', onClick);
7393
+ attached.set(element, () => element.removeEventListener('click', onClick));
7394
+ };
7395
+ // Defer attachment until the DOM is ready so the selector can match.
7396
+ onDomReady(() => {
7397
+ // Cleanup can run before the DOM is ready; attaching afterwards would
7398
+ // register listeners that nothing could ever remove.
7399
+ if (cleanedUp)
7400
+ return;
7401
+ document.querySelectorAll(selector).forEach(listen);
7402
+ // Watch for dynamically added elements
7403
+ observer = new MutationObserver((mutations) => {
7404
+ mutations.forEach((mutation) => {
7405
+ mutation.addedNodes.forEach((node) => {
7406
+ if (node instanceof Element) {
7407
+ if (node.matches(selector))
7408
+ listen(node);
7409
+ node.querySelectorAll(selector).forEach(listen);
7410
+ }
7411
+ });
7412
+ });
7413
+ });
7414
+ // Use onBodyReady to handle edge cases where body isn't available yet
7415
+ onBodyReady(() => {
7416
+ observer?.observe(document.body, { childList: true, subtree: true });
7417
+ });
7418
+ });
7419
+ return () => {
7420
+ cleanedUp = true;
7421
+ observer?.disconnect();
7422
+ attached.forEach((removeListener) => removeListener());
7423
+ attached.clear();
7424
+ };
7425
+ }
7406
7426
 
7407
- /* global Element */
7408
7427
  /**
7409
7428
  * Identity Module
7410
7429
  *
@@ -7439,7 +7458,6 @@ class IdentityModule {
7439
7458
  constructor(config) {
7440
7459
  this.renderer = null;
7441
7460
  this.embedder = null;
7442
- this.attachedElements = new Map();
7443
7461
  this.config = config;
7444
7462
  this.api = new IdentityApi(config);
7445
7463
  // Preload config in background for instant dialog opening
@@ -7566,7 +7584,6 @@ class IdentityModule {
7566
7584
  * cleanup();
7567
7585
  */
7568
7586
  attach(selector, options = {}) {
7569
- let observer = null;
7570
7587
  const handleClick = async (event) => {
7571
7588
  event.preventDefault();
7572
7589
  try {
@@ -7583,48 +7600,10 @@ class IdentityModule {
7583
7600
  // Error already handled by callbacks or will use server redirect
7584
7601
  }
7585
7602
  };
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.
7603
+ const cleanup = attachClickHandler(selector, handleClick);
7604
+ // Once the DOM is ready (after the click listeners attach), complete any
7605
+ // full-page social-login redirect result before the user has to click again.
7626
7606
  onDomReady(() => {
7627
- attachToElements();
7628
7607
  this.consumeRedirectResult()
7629
7608
  .then((result) => {
7630
7609
  if (result)
@@ -7634,12 +7613,7 @@ class IdentityModule {
7634
7613
  options.onError?.(error instanceof Error ? error : new Error(String(error)));
7635
7614
  });
7636
7615
  });
7637
- // Return cleanup function
7638
- return () => {
7639
- observer?.disconnect();
7640
- this.attachedElements.forEach((cleanup) => cleanup());
7641
- this.attachedElements.clear();
7642
- };
7616
+ return cleanup;
7643
7617
  }
7644
7618
  /**
7645
7619
  * Verify and decode an identity token.
@@ -7686,29 +7660,56 @@ class IdentityModule {
7686
7660
  if (!token) {
7687
7661
  return null;
7688
7662
  }
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}`);
7663
+ // Once a token is present it must be consumed exactly once: the hash and
7664
+ // one-shot OAuth state are cleared whether validation succeeds or fails.
7665
+ // A failing token left in the URL would make every subsequent verify()
7666
+ // re-consume and re-reject it before the dialog could ever open — login
7667
+ // would stay wedged until the user manually edited the URL.
7668
+ try {
7669
+ let expectedState = null;
7670
+ try {
7671
+ expectedState = sessionStorage.getItem('sv_oauth_state');
7672
+ }
7673
+ catch {
7674
+ // Storage disabled (private mode): proceed; the backend still binds state.
7675
+ }
7676
+ if (expectedState && params.get('state') !== expectedState) {
7677
+ throw new ValidationError('Invalid OAuth state');
7678
+ }
7679
+ const claims = await this.verifyToken(token);
7680
+ return {
7681
+ token,
7682
+ identity: claims.identity,
7683
+ identityType: claims.identity_type,
7684
+ svid: claims.svid,
7685
+ sessionId: claims.session_id,
7686
+ };
7687
+ }
7688
+ finally {
7689
+ if (typeof window.history?.replaceState === 'function') {
7690
+ window.history.replaceState(window.history.state, document.title, `${window.location.pathname}${window.location.search}`);
7691
+ }
7692
+ try {
7693
+ sessionStorage.removeItem('sv_oauth_state');
7694
+ sessionStorage.removeItem('sv_oauth_email');
7695
+ }
7696
+ catch {
7697
+ // Storage disabled (private mode): nothing to clear.
7698
+ }
7703
7699
  }
7704
- sessionStorage.removeItem('sv_oauth_state');
7705
- sessionStorage.removeItem('sv_oauth_email');
7706
- return result;
7707
7700
  }
7708
7701
  /**
7709
7702
  * Close the identity dialog/inline UI if open.
7703
+ *
7704
+ * Tears down whichever surface is active: the hosted-widget iframe
7705
+ * (default dialog mode — also releases the embedder's host scroll lock)
7706
+ * or the local renderer (inline / local mode).
7710
7707
  */
7711
7708
  close() {
7709
+ if (this.embedder) {
7710
+ this.embedder.close();
7711
+ this.embedder = null;
7712
+ }
7712
7713
  if (this.renderer) {
7713
7714
  this.renderer.close();
7714
7715
  this.renderer = null;
@@ -7821,6 +7822,15 @@ function isInitiateUploadResponse(data) {
7821
7822
  }
7822
7823
  /** tus protocol version used for the resumable upload session. */
7823
7824
  const TUS_VERSION = '1.0.0';
7825
+ /** Default TUS chunk size; the server may override via `X-Chunk-Size`. */
7826
+ const DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024;
7827
+ /**
7828
+ * Abort a stalled chunk PATCH after this long with no upload progress.
7829
+ * XHR's own `timeout` measures total request duration, which would abort a
7830
+ * slow-but-progressing 50MB chunk — so a chunk fails only after the
7831
+ * connection has been completely silent for the full window.
7832
+ */
7833
+ const CHUNK_INACTIVITY_TIMEOUT_MS = 60000;
7824
7834
  /**
7825
7835
  * Server-side finalization confirmation poll.
7826
7836
  *
@@ -7904,21 +7914,182 @@ class UploadApi extends SparkVaultApi {
7904
7914
  };
7905
7915
  }
7906
7916
  /**
7907
- * Confirm the upload was finalized SERVER-SIDE before reporting success.
7908
- *
7909
- * The TUS PATCH loop trusts a server-provided `Upload-Offset`; a buggy or
7910
- * malicious Forge could return an inflated offset before every chunk was
7911
- * actually committed and encrypted. This re-reads the server's own
7912
- * persisted offset via a TUS HEAD (which Forge only advances on a real S3
7913
- * commit) and requires it to reach the declared total — the web equivalent
7914
- * of the mobile SDK's `verifyIngotActive` (status === 'active') guarantee.
7917
+ * Upload a file to Forge over the TUS resumable protocol (v1.0.0).
7915
7918
  *
7916
- * Polls because the final chunk's commit and the offset write can lag the
7917
- * PATCH acknowledgement by a moment. Throws on a non-2xx HEAD, on a session
7918
- * that never reaches the expected offset within the poll budget, or on a
7919
- * cancelled session — never reports a half-finished upload as done.
7919
+ * The single canonical browser transfer path — the upload widget and the
7920
+ * authenticated `uploadIngot` flow both go through here (CLAUDE.md: one
7921
+ * transfer path). Creates the session, PATCHes chunks sized by the server's
7922
+ * `X-Chunk-Size` (50MB default, which keeps every request under CDN body
7923
+ * caps such as Cloudflare's 100MB), validates every server-reported offset,
7924
+ * and honors the session abort signal plus per-request timeouts.
7920
7925
  *
7921
- * @param uploadUrl - The TUS session URL (Forge `Location`, ISTK-bound).
7926
+ * Returns the TUS session URL so the caller can confirm server-side
7927
+ * finalization via {@link verifyUploadFinalized} before reporting success.
7928
+ */
7929
+ async uploadFileToForge(file, forgeUrl, onProgress) {
7930
+ if (typeof XMLHttpRequest === 'undefined') {
7931
+ throw new UploadApiError('XMLHttpRequest is required for browser uploads', 'environment_unsupported', 0);
7932
+ }
7933
+ const url = new URL(forgeUrl);
7934
+ const istk = url.searchParams.get('istk');
7935
+ if (!istk) {
7936
+ throw new UploadApiError('Forge upload URL is missing ISTK', 'invalid_forge_url', 0);
7937
+ }
7938
+ const session = await this.createTusSession(`${url.origin}${url.pathname}`, istk, file.size);
7939
+ const uploadUrl = session.location.startsWith('http')
7940
+ ? session.location
7941
+ : `${url.origin}${session.location}`;
7942
+ let offset = 0;
7943
+ while (offset < file.size) {
7944
+ if (this.isAborted()) {
7945
+ throw new UploadApiError('Upload cancelled', 'cancelled', 0);
7946
+ }
7947
+ const chunkEnd = Math.min(offset + session.chunkSize, file.size);
7948
+ offset = await this.patchChunk(uploadUrl, file.slice(offset, chunkEnd), offset, file.size, onProgress);
7949
+ }
7950
+ return uploadUrl;
7951
+ }
7952
+ /**
7953
+ * Create the TUS upload session. Forge reads only `Tus-Resumable`,
7954
+ * `Upload-Length`, and `X-ISTK` on create, and returns the session URL in
7955
+ * `Location` (possibly relative) plus its chunk size in `X-Chunk-Size`.
7956
+ */
7957
+ async createTusSession(endpoint, istk, totalSize) {
7958
+ const closeSignal = this.getAbortSignal();
7959
+ const { signal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, closeSignal);
7960
+ try {
7961
+ const response = await fetch(endpoint, {
7962
+ method: 'POST',
7963
+ headers: {
7964
+ 'Tus-Resumable': TUS_VERSION,
7965
+ 'Upload-Length': String(totalSize),
7966
+ 'X-ISTK': istk,
7967
+ },
7968
+ signal,
7969
+ });
7970
+ if (!response.ok) {
7971
+ const errorText = await response.text().catch(() => '');
7972
+ throw new UploadApiError(`Failed to create upload session: ${response.status} ${errorText}`, 'tus_create_failed', response.status);
7973
+ }
7974
+ const location = response.headers.get('Location');
7975
+ if (!location) {
7976
+ throw new UploadApiError('Server did not return upload location', 'tus_create_failed', response.status);
7977
+ }
7978
+ const chunkSizeHeader = response.headers.get('X-Chunk-Size');
7979
+ const chunkSize = chunkSizeHeader ? parseInt(chunkSizeHeader, 10) : NaN;
7980
+ return {
7981
+ location,
7982
+ chunkSize: Number.isFinite(chunkSize) && chunkSize > 0 ? chunkSize : DEFAULT_CHUNK_SIZE,
7983
+ };
7984
+ }
7985
+ catch (error) {
7986
+ if (error instanceof SparkVaultError)
7987
+ throw error;
7988
+ if (error != null && typeof error === 'object' && 'name' in error && error.name === 'AbortError') {
7989
+ if (this.isAborted()) {
7990
+ throw new UploadApiError('Upload cancelled', 'cancelled', 0);
7991
+ }
7992
+ throw new UploadApiError(`Upload session creation timed out after ${this.timeoutMs}ms`, 'timeout', 0);
7993
+ }
7994
+ if (error instanceof TypeError) {
7995
+ throw new UploadApiError('Unable to connect. Please check your connection and try again.', 'network_error', 0);
7996
+ }
7997
+ throw new UploadApiError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
7998
+ }
7999
+ finally {
8000
+ dispose();
8001
+ }
8002
+ }
8003
+ /**
8004
+ * PATCH one chunk with XMLHttpRequest (fetch exposes no upload progress).
8005
+ * Resolves with the server-confirmed offset for the next iteration.
8006
+ *
8007
+ * The server's `Upload-Offset` is validated, never trusted: it must be a
8008
+ * finite number that strictly advances past this chunk's start (this client
8009
+ * never sends an empty chunk, so a non-advancing 2xx would loop forever)
8010
+ * and never exceeds the file size (an inflated offset would skip real
8011
+ * chunks and report a partial upload as success).
8012
+ */
8013
+ patchChunk(uploadUrl, chunk, chunkStart, totalSize, onProgress) {
8014
+ return new Promise((resolve, reject) => {
8015
+ const closeSignal = this.getAbortSignal();
8016
+ if (closeSignal.aborted) {
8017
+ reject(new UploadApiError('Upload cancelled', 'cancelled', 0));
8018
+ return;
8019
+ }
8020
+ const xhr = new XMLHttpRequest();
8021
+ let settled = false;
8022
+ let timedOut = false;
8023
+ let watchdog = null;
8024
+ const onCloseAbort = () => xhr.abort();
8025
+ const finish = (settle) => {
8026
+ if (settled)
8027
+ return;
8028
+ settled = true;
8029
+ if (watchdog !== null)
8030
+ clearTimeout(watchdog);
8031
+ closeSignal.removeEventListener('abort', onCloseAbort);
8032
+ settle();
8033
+ };
8034
+ const resetWatchdog = () => {
8035
+ if (settled)
8036
+ return;
8037
+ if (watchdog !== null)
8038
+ clearTimeout(watchdog);
8039
+ watchdog = setTimeout(() => {
8040
+ timedOut = true;
8041
+ xhr.abort();
8042
+ }, CHUNK_INACTIVITY_TIMEOUT_MS);
8043
+ };
8044
+ closeSignal.addEventListener('abort', onCloseAbort);
8045
+ xhr.upload.onprogress = (event) => {
8046
+ resetWatchdog();
8047
+ if (event.lengthComputable) {
8048
+ onProgress?.(chunkStart + event.loaded, totalSize);
8049
+ }
8050
+ };
8051
+ xhr.onload = () => {
8052
+ if (xhr.status >= 200 && xhr.status < 300) {
8053
+ const header = xhr.getResponseHeader('Upload-Offset');
8054
+ const newOffset = header !== null ? parseInt(header, 10) : NaN;
8055
+ if (!Number.isFinite(newOffset) || newOffset <= chunkStart || newOffset > totalSize) {
8056
+ finish(() => reject(new UploadApiError(`Server returned invalid upload offset (${newOffset})`, 'invalid_offset', xhr.status)));
8057
+ return;
8058
+ }
8059
+ finish(() => resolve(newOffset));
8060
+ }
8061
+ else {
8062
+ finish(() => reject(new UploadApiError(`Chunk upload failed with status ${xhr.status}`, 'chunk_upload_failed', xhr.status)));
8063
+ }
8064
+ };
8065
+ xhr.onerror = () => finish(() => reject(new UploadApiError('Chunk upload failed', 'network_error', 0)));
8066
+ xhr.onabort = () => finish(() => reject(timedOut
8067
+ ? new UploadApiError(`Chunk upload timed out after ${CHUNK_INACTIVITY_TIMEOUT_MS}ms of inactivity`, 'timeout', 0)
8068
+ : new UploadApiError('Upload cancelled', 'cancelled', 0)));
8069
+ xhr.open('PATCH', uploadUrl);
8070
+ xhr.setRequestHeader('Tus-Resumable', TUS_VERSION);
8071
+ xhr.setRequestHeader('Upload-Offset', String(chunkStart));
8072
+ xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream');
8073
+ resetWatchdog();
8074
+ xhr.send(chunk);
8075
+ });
8076
+ }
8077
+ /**
8078
+ * Confirm the upload was finalized SERVER-SIDE before reporting success.
8079
+ *
8080
+ * The TUS PATCH loop trusts a server-provided `Upload-Offset`; a buggy or
8081
+ * malicious Forge could return an inflated offset before every chunk was
8082
+ * actually committed and encrypted. This re-reads the server's own
8083
+ * persisted offset via a TUS HEAD (which Forge only advances on a real S3
8084
+ * commit) and requires it to reach the declared total — the web equivalent
8085
+ * of the mobile SDK's `verifyIngotActive` (status === 'active') guarantee.
8086
+ *
8087
+ * Polls because the final chunk's commit and the offset write can lag the
8088
+ * PATCH acknowledgement by a moment. Throws on a non-2xx HEAD, on a session
8089
+ * that never reaches the expected offset within the poll budget, or on a
8090
+ * cancelled session — never reports a half-finished upload as done.
8091
+ *
8092
+ * @param uploadUrl - The TUS session URL (Forge `Location`, ISTK-bound).
7922
8093
  * @param expectedOffset - The declared total upload size in bytes.
7923
8094
  */
7924
8095
  async verifyUploadFinalized(uploadUrl, expectedOffset) {
@@ -7949,21 +8120,7 @@ class UploadApi extends SparkVaultApi {
7949
8120
  */
7950
8121
  async headUploadOffset(uploadUrl) {
7951
8122
  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
- }
8123
+ const { signal: combinedSignal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, closeSignal);
7967
8124
  try {
7968
8125
  const response = await fetch(uploadUrl, {
7969
8126
  method: 'HEAD',
@@ -7995,14 +8152,175 @@ class UploadApi extends SparkVaultApi {
7995
8152
  throw new UploadApiError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
7996
8153
  }
7997
8154
  finally {
7998
- clearTimeout(timeoutId);
7999
- if (onCloseAbort) {
8000
- closeSignal.removeEventListener('abort', onCloseAbort);
8001
- }
8155
+ dispose();
8002
8156
  }
8003
8157
  }
8004
8158
  }
8005
8159
 
8160
+ /**
8161
+ * Upload Widget Chrome
8162
+ *
8163
+ * Shared DOM builders for the branded chrome both upload containers render:
8164
+ * brand header, "Secured by SparkVault" footer, and the Triple Zero-Trust
8165
+ * security sidebar. One canonical copy — any branding/marketing/security-text
8166
+ * change lands here and reaches modal and inline modes alike.
8167
+ */
8168
+ /**
8169
+ * Build the branded header. Returns the close button (when rendered) so the
8170
+ * container can detach `onClose` in its destroy() cleanup.
8171
+ */
8172
+ function createBrandHeader(options) {
8173
+ const { branding, isDarkMode, withCloseButton, titleId, onClose } = options;
8174
+ const header = document.createElement('div');
8175
+ header.className = 'svu-header';
8176
+ const titleContainer = document.createElement('div');
8177
+ titleContainer.className = 'svu-header-title';
8178
+ // Use light logo for light theme (default), dark logo for dark mode
8179
+ const logoUrl = isDarkMode
8180
+ ? branding.logoDarkUrl || branding.logoLightUrl
8181
+ : branding.logoLightUrl || branding.logoDarkUrl;
8182
+ if (logoUrl) {
8183
+ const logo = document.createElement('img');
8184
+ logo.className = 'svu-logo';
8185
+ logo.src = logoUrl;
8186
+ logo.alt = branding.organizationName;
8187
+ titleContainer.appendChild(logo);
8188
+ // Screen reader title
8189
+ const srTitle = document.createElement('span');
8190
+ srTitle.className = 'svu-sr-only';
8191
+ if (titleId)
8192
+ srTitle.id = titleId;
8193
+ srTitle.textContent = branding.organizationName;
8194
+ titleContainer.appendChild(srTitle);
8195
+ }
8196
+ else if (branding.organizationName) {
8197
+ const companyName = document.createElement('h2');
8198
+ companyName.className = 'svu-company-name';
8199
+ if (titleId)
8200
+ companyName.id = titleId;
8201
+ companyName.textContent = branding.organizationName;
8202
+ titleContainer.appendChild(companyName);
8203
+ }
8204
+ header.appendChild(titleContainer);
8205
+ let closeBtn = null;
8206
+ if (withCloseButton) {
8207
+ closeBtn = document.createElement('button');
8208
+ closeBtn.className = 'svu-close-btn';
8209
+ closeBtn.setAttribute('aria-label', 'Close');
8210
+ closeBtn.innerHTML = `
8211
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8212
+ <path d="M18 6L6 18M6 6l12 12"/>
8213
+ </svg>
8214
+ `;
8215
+ closeBtn.addEventListener('click', onClose);
8216
+ header.appendChild(closeBtn);
8217
+ }
8218
+ return { header, closeBtn };
8219
+ }
8220
+ /** Build the "Secured by SparkVault" footer. */
8221
+ function createFooter() {
8222
+ const footer = document.createElement('div');
8223
+ footer.className = 'svu-footer';
8224
+ const footerText = document.createElement('span');
8225
+ footerText.className = 'svu-footer-text';
8226
+ footerText.appendChild(document.createTextNode('Secured by '));
8227
+ const footerLink = document.createElement('a');
8228
+ footerLink.href = 'https://sparkvault.com';
8229
+ footerLink.target = '_blank';
8230
+ footerLink.rel = 'noopener noreferrer';
8231
+ footerLink.className = 'svu-footer-link';
8232
+ footerLink.textContent = 'SparkVault';
8233
+ footerText.appendChild(footerLink);
8234
+ footer.appendChild(footerText);
8235
+ return footer;
8236
+ }
8237
+ /** Build the Triple Zero-Trust security sidebar shown during dark states. */
8238
+ function createSecuritySidebar(branding) {
8239
+ const sidebar = document.createElement('div');
8240
+ sidebar.className = 'svu-sidebar';
8241
+ // Logo
8242
+ const logoDiv = document.createElement('div');
8243
+ logoDiv.className = 'svu-sidebar-logo';
8244
+ if (branding.logoDarkUrl) {
8245
+ const logo = document.createElement('img');
8246
+ logo.src = branding.logoDarkUrl;
8247
+ logo.alt = branding.organizationName;
8248
+ logoDiv.appendChild(logo);
8249
+ }
8250
+ sidebar.appendChild(logoDiv);
8251
+ // Intro
8252
+ const intro = document.createElement('div');
8253
+ intro.className = 'svu-sidebar-intro';
8254
+ intro.innerHTML = `
8255
+ <h3>Secure File Transfer</h3>
8256
+ <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>
8257
+ `;
8258
+ sidebar.appendChild(intro);
8259
+ // Security details
8260
+ const security = document.createElement('div');
8261
+ security.className = 'svu-sidebar-security';
8262
+ security.innerHTML = `
8263
+ <h4>
8264
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8265
+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
8266
+ </svg>
8267
+ SparkVault's Triple Zero-Trust
8268
+ </h4>
8269
+ <p class="svu-security-intro">
8270
+ Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.
8271
+ </p>
8272
+ <div class="svu-key-chain">
8273
+ <div class="svu-key-item">
8274
+ <div class="svu-key-number">1</div>
8275
+ <div class="svu-key-info">
8276
+ <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>
8277
+ <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>
8278
+ <span class="svu-key-desc">Quantum-resistant key exchange</span>
8279
+ </div>
8280
+ </div>
8281
+ <div class="svu-key-connector">
8282
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8283
+ <path d="M12 5v14M5 12h14"/>
8284
+ </svg>
8285
+ </div>
8286
+ <div class="svu-key-item">
8287
+ <div class="svu-key-number">2</div>
8288
+ <div class="svu-key-info">
8289
+ <span class="svu-key-name">X25519 Ephemeral Key</span>
8290
+ <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>
8291
+ <span class="svu-key-desc">Perfect forward secrecy</span>
8292
+ </div>
8293
+ </div>
8294
+ <div class="svu-key-connector">
8295
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8296
+ <path d="M12 5v14M5 12h14"/>
8297
+ </svg>
8298
+ </div>
8299
+ <div class="svu-key-item">
8300
+ <div class="svu-key-number">3</div>
8301
+ <div class="svu-key-info">
8302
+ <span class="svu-key-name">HKDF-SHA512 Derived Key</span>
8303
+ <span class="svu-key-algo">Hardware-bound key derivation</span>
8304
+ <span class="svu-key-desc">Vault master key in secure enclave</span>
8305
+ </div>
8306
+ </div>
8307
+ </div>
8308
+ <div class="svu-encryption-result">
8309
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8310
+ <path d="M20 6L9 17l-5-5"/>
8311
+ </svg>
8312
+ <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>
8313
+ </div>
8314
+ <div class="svu-security-badges">
8315
+ <span class="svu-tls-badge">TLS 1.3 In Transit</span>
8316
+ <span class="svu-tls-badge">Encrypted At Rest</span>
8317
+ <span class="svu-tls-badge">Zero Trust</span>
8318
+ </div>
8319
+ `;
8320
+ sidebar.appendChild(security);
8321
+ return sidebar;
8322
+ }
8323
+
8006
8324
  /**
8007
8325
  * Upload Widget Styles
8008
8326
  *
@@ -8012,19 +8330,19 @@ class UploadApi extends SparkVaultApi {
8012
8330
  const STYLE_ID = 'sparkvault-upload-styles';
8013
8331
  /**
8014
8332
  * Inject upload widget styles into the document head.
8333
+ * Idempotent: the stylesheet is static and shared by every widget instance —
8334
+ * per-instance behavior (backdrop blur, dark mode) is driven by class toggles.
8015
8335
  */
8016
- function injectUploadStyles(options) {
8336
+ function injectUploadStyles() {
8017
8337
  if (document.getElementById(STYLE_ID)) {
8018
8338
  return;
8019
8339
  }
8020
8340
  const style = document.createElement('style');
8021
8341
  style.id = STYLE_ID;
8022
- style.textContent = getUploadStyles(options);
8342
+ style.textContent = getUploadStyles();
8023
8343
  document.head.appendChild(style);
8024
8344
  }
8025
- function getUploadStyles(options) {
8026
- const { backdropBlur } = options;
8027
- const enableBlur = backdropBlur !== false;
8345
+ function getUploadStyles() {
8028
8346
  // Design tokens - light theme for upload widget
8029
8347
  const tokens = {
8030
8348
  // Colors
@@ -8091,8 +8409,8 @@ function getUploadStyles(options) {
8091
8409
  }
8092
8410
 
8093
8411
  .svu-overlay.svu-blur {
8094
- backdrop-filter: blur(${enableBlur ? '8px' : '0'});
8095
- -webkit-backdrop-filter: blur(${enableBlur ? '8px' : '0'});
8412
+ backdrop-filter: blur(8px);
8413
+ -webkit-backdrop-filter: blur(8px);
8096
8414
  }
8097
8415
 
8098
8416
  .svu-modal {
@@ -9120,6 +9438,8 @@ function getUploadStyles(options) {
9120
9438
  */
9121
9439
  const OVERLAY_ID = 'sparkvault-upload-overlay';
9122
9440
  const MODAL_ID = 'sparkvault-upload-modal';
9441
+ /** Title node id referenced by the overlay's aria-labelledby. */
9442
+ const MODAL_TITLE_ID = 'svu-modal-title';
9123
9443
  /**
9124
9444
  * Default branding used for immediate modal display before config loads.
9125
9445
  */
@@ -9160,17 +9480,14 @@ class UploadModalContainer {
9160
9480
  this.onCloseCallback = onClose;
9161
9481
  this.backdropBlur = options.backdropBlur !== false;
9162
9482
  this.branding = options.branding || DEFAULT_BRANDING;
9163
- injectUploadStyles({
9164
- branding: this.branding,
9165
- backdropBlur: this.backdropBlur,
9166
- });
9483
+ injectUploadStyles();
9167
9484
  // Create overlay
9168
9485
  const overlay = document.createElement('div');
9169
9486
  overlay.id = OVERLAY_ID;
9170
9487
  overlay.className = this.backdropBlur ? 'svu-overlay svu-blur' : 'svu-overlay';
9171
9488
  overlay.setAttribute('role', 'dialog');
9172
9489
  overlay.setAttribute('aria-modal', 'true');
9173
- overlay.setAttribute('aria-labelledby', 'svu-modal-title');
9490
+ overlay.setAttribute('aria-labelledby', MODAL_TITLE_ID);
9174
9491
  // Create modal
9175
9492
  const modal = document.createElement('div');
9176
9493
  modal.id = MODAL_ID;
@@ -9185,19 +9502,7 @@ class UploadModalContainer {
9185
9502
  const body = document.createElement('div');
9186
9503
  body.className = 'svu-body';
9187
9504
  // 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);
9505
+ const footer = createFooter();
9201
9506
  main.appendChild(header);
9202
9507
  main.appendChild(body);
9203
9508
  main.appendChild(footer);
@@ -9221,47 +9526,15 @@ class UploadModalContainer {
9221
9526
  this.elements = { overlay, modal, main, header, body, footer, sidebar: null };
9222
9527
  }
9223
9528
  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
9529
  this.closeBtnClickHandler = () => this.handleClose();
9262
- this.closeBtn.addEventListener('click', this.closeBtnClickHandler);
9263
- header.appendChild(titleContainer);
9264
- header.appendChild(this.closeBtn);
9530
+ const { header, closeBtn } = createBrandHeader({
9531
+ branding,
9532
+ isDarkMode: this.isDarkMode,
9533
+ withCloseButton: true,
9534
+ titleId: MODAL_TITLE_ID,
9535
+ onClose: this.closeBtnClickHandler,
9536
+ });
9537
+ this.closeBtn = closeBtn;
9265
9538
  return header;
9266
9539
  }
9267
9540
  /**
@@ -9323,7 +9596,7 @@ class UploadModalContainer {
9323
9596
  return;
9324
9597
  if (show && !this.elements.sidebar) {
9325
9598
  // Create sidebar
9326
- const sidebar = this.createSecuritySidebar();
9599
+ const sidebar = createSecuritySidebar(this.branding);
9327
9600
  this.elements.modal.classList.add('svu-with-sidebar');
9328
9601
  this.elements.modal.appendChild(sidebar);
9329
9602
  this.elements.sidebar = sidebar;
@@ -9343,91 +9616,6 @@ class UploadModalContainer {
9343
9616
  }
9344
9617
  }
9345
9618
  }
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
9619
  handleClose() {
9432
9620
  if (this.onCloseCallback) {
9433
9621
  this.onCloseCallback();
@@ -9520,10 +9708,7 @@ class UploadInlineContainer {
9520
9708
  }
9521
9709
  this.onCloseCallback = onClose;
9522
9710
  // Inject styles
9523
- injectUploadStyles({
9524
- branding: this.branding,
9525
- backdropBlur: false,
9526
- });
9711
+ injectUploadStyles();
9527
9712
  // Create main container
9528
9713
  this.container = document.createElement('div');
9529
9714
  this.container.className = 'svu-inline-container';
@@ -9538,19 +9723,7 @@ class UploadInlineContainer {
9538
9723
  this.container.appendChild(this.body);
9539
9724
  // Create footer if enabled
9540
9725
  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);
9726
+ this.footer = createFooter();
9554
9727
  this.container.appendChild(this.footer);
9555
9728
  }
9556
9729
  // Clear target and append container
@@ -9608,7 +9781,7 @@ class UploadInlineContainer {
9608
9781
  return;
9609
9782
  if (show && !this.sidebar) {
9610
9783
  // Create sidebar
9611
- this.sidebar = this.createSecuritySidebar();
9784
+ this.sidebar = createSecuritySidebar(this.branding);
9612
9785
  this.container.classList.add('svu-with-sidebar');
9613
9786
  this.container.appendChild(this.sidebar);
9614
9787
  }
@@ -9659,134 +9832,16 @@ class UploadInlineContainer {
9659
9832
  this.onCloseCallback = null;
9660
9833
  }
9661
9834
  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
- }
9835
+ this.closeBtnClickHandler = () => this.handleClose();
9836
+ const { header, closeBtn } = createBrandHeader({
9837
+ branding,
9838
+ isDarkMode: this.isDarkMode,
9839
+ withCloseButton: this.containerOptions.showCloseButton === true,
9840
+ onClose: this.closeBtnClickHandler,
9841
+ });
9842
+ this.closeBtn = closeBtn;
9703
9843
  return header;
9704
9844
  }
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
9845
  handleClose() {
9791
9846
  if (this.onCloseCallback) {
9792
9847
  this.onCloseCallback();
@@ -9829,6 +9884,14 @@ function generateRequestId() {
9829
9884
  const random = Array.from(randomBytes, byte => byte.toString(16).padStart(2, '0')).join('');
9830
9885
  return `${timestamp}${random}`;
9831
9886
  }
9887
+ /**
9888
+ * Whether an error represents a deliberate cancellation (user close,
9889
+ * programmatic close, or session abort) rather than a genuine failure.
9890
+ */
9891
+ function isCancellationError(error) {
9892
+ return (error instanceof UserCancelledError ||
9893
+ (error instanceof SparkVaultError && error.code === 'cancelled'));
9894
+ }
9832
9895
  /**
9833
9896
  * Format bytes to human readable string.
9834
9897
  */
@@ -9851,8 +9914,11 @@ class UploadRenderer {
9851
9914
  this.uploadModal = null;
9852
9915
  this.isInlineMode = false;
9853
9916
  this.hybridModalInitialized = false;
9854
- // Track active XHR for cancellation on close
9855
- this.activeXhr = null;
9917
+ // Lifecycle flags: a closed renderer must never render or fire callbacks,
9918
+ // and onCancel fires at most once per renderer (mutually exclusive with
9919
+ // onError — see cancel()/handleApiError).
9920
+ this.closed = false;
9921
+ this.cancelled = false;
9856
9922
  this.pasteHandler = null;
9857
9923
  this.container = container;
9858
9924
  this.api = api;
@@ -9893,16 +9959,13 @@ class UploadRenderer {
9893
9959
  }
9894
9960
  /**
9895
9961
  * Close the upload flow.
9896
- * Cancels all pending API requests and active uploads to prevent orphaned operations.
9962
+ * Cancels all pending API requests and active uploads (aborting the session
9963
+ * signal tears down any in-flight TUS chunk) to prevent orphaned operations.
9897
9964
  */
9898
9965
  close() {
9899
- // Cancel all pending API requests first
9966
+ this.closed = true;
9967
+ // Cancel all pending API requests and the active TUS transfer
9900
9968
  this.api.abort();
9901
- // Abort any active XHR upload
9902
- if (this.activeXhr) {
9903
- this.activeXhr.abort();
9904
- this.activeXhr = null;
9905
- }
9906
9969
  this.cleanupFileInput();
9907
9970
  this.cleanupPasteHandler();
9908
9971
  // Clean up modal if open (hybrid mode)
@@ -9913,14 +9976,64 @@ class UploadRenderer {
9913
9976
  }
9914
9977
  this.container.destroy();
9915
9978
  }
9916
- handleClose() {
9979
+ /**
9980
+ * Cancel the flow: tear everything down and fire the cancel contract
9981
+ * exactly once. onCancel and onError are mutually exclusive — a deliberate
9982
+ * cancellation (user close, programmatic close, or a new upload replacing
9983
+ * this renderer) must never surface as an error to the host.
9984
+ */
9985
+ cancel() {
9986
+ if (this.cancelled)
9987
+ return;
9988
+ this.cancelled = true;
9917
9989
  this.close();
9918
9990
  this.callbacks.onCancel();
9919
9991
  }
9992
+ handleClose() {
9993
+ this.cancel();
9994
+ }
9920
9995
  setState(state) {
9996
+ // A closed renderer never renders again — a progress event racing the
9997
+ // teardown must not resurrect the hybrid-mode modal or touch the DOM.
9998
+ if (this.closed)
9999
+ return;
10000
+ const previousView = this.viewState.view;
9921
10001
  this.viewState = state;
10002
+ // Progress events fire many times per second for the whole transfer.
10003
+ // While the uploading view is already on screen, mutate its progress
10004
+ // nodes in place instead of tearing down and rebuilding the subtree —
10005
+ // a full rebuild per event thrashes the DOM and restarts the progress
10006
+ // bar's CSS transition and the stage-arrow animation on every tick.
10007
+ if (previousView === 'uploading' &&
10008
+ state.view === 'uploading' &&
10009
+ this.updateUploadProgress(state)) {
10010
+ return;
10011
+ }
9922
10012
  this.render();
9923
10013
  }
10014
+ /**
10015
+ * Targeted DOM update for an already-rendered uploading view: progress fill
10016
+ * width plus the percentage and byte-count labels. Returns false when the
10017
+ * uploading view is not in the DOM, so the caller falls back to a full render.
10018
+ */
10019
+ updateUploadProgress(state) {
10020
+ // Hybrid inline mode renders uploading inside the modal overlay.
10021
+ const body = this.isInlineMode && this.uploadModal
10022
+ ? this.uploadModal.getBody()
10023
+ : this.container.getBody();
10024
+ const fill = body?.querySelector('.svu-progress-fill');
10025
+ if (!body || !fill)
10026
+ return false;
10027
+ fill.style.width = `${state.progress}%`;
10028
+ const [percentLabel, bytesLabel] = body.querySelectorAll('.svu-progress-text span');
10029
+ if (percentLabel) {
10030
+ percentLabel.textContent = `${state.progress}%`;
10031
+ }
10032
+ if (bytesLabel) {
10033
+ bytesLabel.textContent = `${formatBytes(state.bytesUploaded)} / ${formatBytes(state.file.size)}`;
10034
+ }
10035
+ return true;
10036
+ }
9924
10037
  render() {
9925
10038
  const isDarkState = this.viewState.view === 'uploading' || this.viewState.view === 'ceremony';
9926
10039
  // Hybrid mode: For inline containers, use a modal popup for upload/ceremony
@@ -10422,8 +10535,24 @@ class UploadRenderer {
10422
10535
  progress: 0,
10423
10536
  bytesUploaded: 0,
10424
10537
  });
10425
- // Upload file using tus (resumable upload)
10426
- const uploadUrl = await this.uploadWithTus(file, forgeUrl, ingotId, requestId);
10538
+ // Upload file over the canonical TUS transfer path
10539
+ const uploadUrl = await this.api.uploadFileToForge(file, forgeUrl, (bytesUploaded, bytesTotal) => {
10540
+ const progress = Math.round((bytesUploaded / bytesTotal) * 100);
10541
+ this.setState({
10542
+ view: 'uploading',
10543
+ file,
10544
+ ingotId,
10545
+ requestId,
10546
+ progress,
10547
+ bytesUploaded,
10548
+ });
10549
+ this.callbacks.onProgress?.({
10550
+ bytesUploaded,
10551
+ bytesTotal,
10552
+ percentage: progress,
10553
+ phase: 'uploading',
10554
+ });
10555
+ });
10427
10556
  // Confirm the server actually finalized the upload before celebrating.
10428
10557
  // The TUS loop trusts a server-provided offset; this re-reads the
10429
10558
  // server's own persisted offset and requires it to reach the file size,
@@ -10464,129 +10593,6 @@ class UploadRenderer {
10464
10593
  this.handleApiError(error);
10465
10594
  }
10466
10595
  }
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
10596
  async runCeremony(file, ingotId, requestId) {
10591
10597
  for (let i = 0; i < CEREMONY_STEPS.length; i++) {
10592
10598
  this.setState({
@@ -10617,6 +10623,14 @@ class UploadRenderer {
10617
10623
  await new Promise(resolve => setTimeout(resolve, 500));
10618
10624
  }
10619
10625
  handleApiError(error) {
10626
+ // A closed renderer must not surface errors: cancelling mid-transfer
10627
+ // aborts the in-flight request, whose 'cancelled' rejection races the
10628
+ // teardown. The host has already received onCancel — onCancel and
10629
+ // onError are mutually exclusive — and the container is destroyed, so
10630
+ // there is nothing left to render into.
10631
+ if (this.closed || isCancellationError(error)) {
10632
+ return;
10633
+ }
10620
10634
  if (error instanceof UploadApiError) {
10621
10635
  if (error.code === 'UPLOAD_SOURCE_DISABLED') {
10622
10636
  // The vault exists but the embedded widget isn't enabled.
@@ -10686,7 +10700,6 @@ class UploadRenderer {
10686
10700
  }
10687
10701
  }
10688
10702
 
10689
- /* global Element */
10690
10703
  /**
10691
10704
  * Vault Upload Module
10692
10705
  *
@@ -10707,7 +10720,6 @@ class UploadRenderer {
10707
10720
  class VaultUploadModule {
10708
10721
  constructor(config) {
10709
10722
  this.renderer = null;
10710
- this.attachedElements = new Map();
10711
10723
  this.config = config;
10712
10724
  this.api = new UploadApi(config);
10713
10725
  }
@@ -10731,9 +10743,10 @@ class VaultUploadModule {
10731
10743
  if (!options.vaultId) {
10732
10744
  throw new ValidationError('vaultId is required');
10733
10745
  }
10734
- // Close any existing renderer
10746
+ // Cancel any existing renderer so its pending promise settles via the
10747
+ // cancel contract (onCancel + UserCancelledError) instead of hanging.
10735
10748
  if (this.renderer) {
10736
- this.renderer.close();
10749
+ this.renderer.cancel();
10737
10750
  }
10738
10751
  const isInline = !!options.target;
10739
10752
  const container = isInline
@@ -10792,7 +10805,6 @@ class VaultUploadModule {
10792
10805
  if (!options.vaultId) {
10793
10806
  throw new ValidationError('vaultId is required');
10794
10807
  }
10795
- let observer = null;
10796
10808
  const handleClick = async (event) => {
10797
10809
  event.preventDefault();
10798
10810
  try {
@@ -10808,55 +10820,17 @@ class VaultUploadModule {
10808
10820
  // Error already handled by callbacks or will use server redirect
10809
10821
  }
10810
10822
  };
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
- };
10823
+ return attachClickHandler(selector, handleClick);
10853
10824
  }
10854
10825
  /**
10855
10826
  * Close the upload dialog/inline UI if open.
10827
+ *
10828
+ * Programmatic close follows the cancel contract: the host's onCancel
10829
+ * fires and the pending upload promise rejects with UserCancelledError.
10856
10830
  */
10857
10831
  close() {
10858
10832
  if (this.renderer) {
10859
- this.renderer.close();
10833
+ this.renderer.cancel();
10860
10834
  this.renderer = null;
10861
10835
  }
10862
10836
  }
@@ -10880,9 +10854,9 @@ class VaultUploadModule {
10880
10854
  }
10881
10855
  return new UploadInlineContainer(element);
10882
10856
  }
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.
10857
+ // Public-API aliases. The dashboard's vault-edit screen and the SDK docs
10858
+ // document sv.vaults.upload.pop({ vaultId }) and
10859
+ // sv.vaults.upload.render({ vaultId, target }) — both defer to upload().
10886
10860
  /** Open the upload widget as a popup. Equivalent to `upload(options)`. */
10887
10861
  async pop(options) {
10888
10862
  return this.upload(options);
@@ -10904,10 +10878,13 @@ class VaultsModule {
10904
10878
  this.config = config;
10905
10879
  this.http = http;
10906
10880
  this.uploadModule = new VaultUploadModule(config);
10907
- // Create callable that also has attach/close methods
10881
+ this.uploadApi = new UploadApi(config);
10882
+ // Create callable that also has attach/close/pop/render methods
10908
10883
  const uploadFn = ((options) => this.uploadModule.upload(options));
10909
10884
  uploadFn.attach = (selector, options) => this.uploadModule.attach(selector, options);
10910
10885
  uploadFn.close = () => this.uploadModule.close();
10886
+ uploadFn.pop = (options) => this.uploadModule.pop(options);
10887
+ uploadFn.render = (options) => this.uploadModule.render(options);
10911
10888
  this.upload = uploadFn;
10912
10889
  }
10913
10890
  /**
@@ -11015,7 +10992,11 @@ class VaultsModule {
11015
10992
  if (!created.forge_url) {
11016
10993
  throw new ValidationError('Upload endpoint did not return a Forge upload URL');
11017
10994
  }
11018
- await uploadBlobWithTus(options.file, created.forge_url, created.name, created.content_type, options.onProgress);
10995
+ const uploadUrl = await this.uploadApi.uploadFileToForge(options.file, created.forge_url, options.onProgress);
10996
+ // Confirm the server actually finalized the upload before reporting
10997
+ // success — the TUS loop's offsets alone don't prove the final chunk
10998
+ // committed and the ingot went active.
10999
+ await this.uploadApi.verifyUploadFinalized(uploadUrl, options.file.size);
11019
11000
  return {
11020
11001
  id: created.ingot_id,
11021
11002
  name: created.name,
@@ -11125,78 +11106,6 @@ function getBlobName(file) {
11125
11106
  }
11126
11107
  return 'unnamed';
11127
11108
  }
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
11109
  const DOWNLOAD_MAX_ATTEMPTS = 3;
11201
11110
  const DOWNLOAD_RETRY_BASE_MS = 500;
11202
11111
  function delayExponential(attempt) {
@@ -11446,7 +11355,9 @@ if (typeof window !== 'undefined') {
11446
11355
  exports.AuthenticationError = AuthenticationError;
11447
11356
  exports.AuthorizationError = AuthorizationError;
11448
11357
  exports.NetworkError = NetworkError;
11358
+ exports.PlanRequiredError = PlanRequiredError;
11449
11359
  exports.PopupBlockedError = PopupBlockedError;
11360
+ exports.QuotaExceededError = QuotaExceededError;
11450
11361
  exports.SparkVault = SparkVault;
11451
11362
  exports.SparkVaultError = SparkVaultError;
11452
11363
  exports.TimeoutError = TimeoutError;