@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.
@@ -32,6 +32,38 @@ class ValidationError extends SparkVaultError {
32
32
  Object.setPrototypeOf(this, ValidationError.prototype);
33
33
  }
34
34
  }
35
+ /**
36
+ * Plan required gate (402 PLAN_REQUIRED) — the account has no active
37
+ * subscription and attempted a billable/create action. Surface a subscribe CTA
38
+ * to admins, or "ask your account admin" to members.
39
+ */
40
+ class PlanRequiredError extends SparkVaultError {
41
+ constructor(message, details) {
42
+ super(message, 'PLAN_REQUIRED', 402, details);
43
+ this.name = 'PlanRequiredError';
44
+ Object.setPrototypeOf(this, PlanRequiredError.prototype);
45
+ }
46
+ }
47
+ /**
48
+ * Quota exceeded gate (402 QUOTA_EXCEEDED) — a pooled-capacity or seat limit is
49
+ * exhausted. `resource` identifies which pool so callers can branch on the CTA
50
+ * (add a capacity block for storage/bandwidth, free a seat for seats).
51
+ */
52
+ class QuotaExceededError extends SparkVaultError {
53
+ constructor(message, details) {
54
+ super(message, 'QUOTA_EXCEEDED', 402, details);
55
+ this.name = 'QuotaExceededError';
56
+ const resource = details?.resource;
57
+ this.resource =
58
+ resource === 'storage' ||
59
+ resource === 'bandwidth' ||
60
+ resource === 'seats' ||
61
+ resource === 'identity'
62
+ ? resource
63
+ : undefined;
64
+ Object.setPrototypeOf(this, QuotaExceededError.prototype);
65
+ }
66
+ }
35
67
  class NetworkError extends SparkVaultError {
36
68
  constructor(message, details) {
37
69
  super(message, 'network_error', undefined, details);
@@ -153,103 +185,6 @@ function validateConfig(config) {
153
185
  }
154
186
  }
155
187
 
156
- /**
157
- * Retry Utility with Exponential Backoff
158
- *
159
- * Per CLAUDE.md §7: Retries allowed only if idempotent, MUST use exponential backoff.
160
- */
161
- const DEFAULT_OPTIONS$2 = {
162
- maxAttempts: 3,
163
- baseDelayMs: 200,
164
- maxDelayMs: 5000,
165
- jitterFactor: 0.2,
166
- isRetryable: defaultIsRetryable,
167
- };
168
- /**
169
- * Default retry eligibility checker
170
- * Retries on network errors, timeouts, and 5xx server errors
171
- */
172
- function defaultIsRetryable(error) {
173
- // Network errors (TypeError from fetch)
174
- if (error instanceof TypeError) {
175
- return true;
176
- }
177
- // DOMException (timeout/abort)
178
- if (error instanceof DOMException && error.name === 'AbortError') {
179
- return true;
180
- }
181
- // SparkVault errors with status codes
182
- if (typeof error === 'object' &&
183
- error !== null &&
184
- 'statusCode' in error) {
185
- const statusCode = error.statusCode;
186
- // Retry on server errors (5xx) and rate limits (429)
187
- return statusCode >= 500 || statusCode === 429;
188
- }
189
- return false;
190
- }
191
- /**
192
- * Return a random unit interval value using Web Crypto.
193
- */
194
- function randomUnit() {
195
- const value = new Uint32Array(1);
196
- crypto.getRandomValues(value);
197
- return value[0] / 0x100000000;
198
- }
199
- /**
200
- * Calculate delay with exponential backoff and jitter
201
- */
202
- function calculateDelay(attempt, baseDelayMs, maxDelayMs, jitterFactor) {
203
- // Exponential backoff: base * 2^attempt
204
- const exponentialDelay = baseDelayMs * Math.pow(2, attempt);
205
- const cappedDelay = Math.min(exponentialDelay, maxDelayMs);
206
- // Add jitter: random value within jitter range
207
- const jitter = cappedDelay * jitterFactor * randomUnit();
208
- return cappedDelay + jitter;
209
- }
210
- /**
211
- * Sleep for specified milliseconds
212
- */
213
- function sleep(ms) {
214
- return new Promise((resolve) => setTimeout(resolve, ms));
215
- }
216
- /**
217
- * Execute an async function with retry logic and exponential backoff.
218
- *
219
- * @param fn - Async function to execute
220
- * @param options - Retry configuration options
221
- * @returns Promise resolving to the function result
222
- * @throws The last error if all retries fail
223
- *
224
- * @example
225
- * const result = await withRetry(
226
- * () => fetch('/api/data'),
227
- * { maxAttempts: 3, baseDelayMs: 100 }
228
- * );
229
- */
230
- async function withRetry(fn, options = {}) {
231
- const config = { ...DEFAULT_OPTIONS$2, ...options };
232
- let lastError;
233
- for (let attempt = 0; attempt < config.maxAttempts; attempt++) {
234
- try {
235
- return await fn();
236
- }
237
- catch (error) {
238
- lastError = error;
239
- // Don't retry on last attempt or non-retryable errors
240
- const isLastAttempt = attempt === config.maxAttempts - 1;
241
- if (isLastAttempt || !config.isRetryable(error)) {
242
- throw error;
243
- }
244
- // Calculate and wait for backoff delay
245
- const delay = calculateDelay(attempt, config.baseDelayMs, config.maxDelayMs, config.jitterFactor);
246
- await sleep(delay);
247
- }
248
- }
249
- // Should not reach here, but TypeScript needs this
250
- throw lastError;
251
- }
252
-
253
188
  /**
254
189
  * SparkVault SDK HTTP Client
255
190
  */
@@ -283,22 +218,6 @@ class HttpClient {
283
218
  return this.config.accessToken ?? null;
284
219
  }
285
220
  async request(path, options = {}) {
286
- const { retry } = options;
287
- // Per CLAUDE.md §7: Wrap with retry logic if enabled
288
- if (retry) {
289
- const retryOptions = typeof retry === 'object' ? retry : {};
290
- return withRetry(() => this.executeRequest(path, options), {
291
- ...retryOptions,
292
- // Only retry on idempotent-safe errors (network, timeout, 5xx)
293
- isRetryable: (error) => this.isRetryableError(error),
294
- });
295
- }
296
- return this.executeRequest(path, options);
297
- }
298
- /**
299
- * Execute the actual HTTP request (internal implementation)
300
- */
301
- async executeRequest(path, options) {
302
221
  const { method = 'GET', headers = {}, body, timeout = this.config.timeout, } = options;
303
222
  const url = `${this.config.apiBaseUrl}${path}`;
304
223
  const requestHeaders = await this.getDefaultHeaders(headers, body !== undefined);
@@ -318,6 +237,7 @@ class HttpClient {
318
237
  }
319
238
  return {
320
239
  data: this.unwrapApiResponse(parsed),
240
+ meta: this.extractResponseMeta(parsed),
321
241
  status: response.status,
322
242
  headers: response.headers,
323
243
  };
@@ -336,21 +256,6 @@ class HttpClient {
336
256
  throw new SparkVaultError(error instanceof Error ? error.message : 'Unknown error', 'unknown_error');
337
257
  }
338
258
  }
339
- /**
340
- * Check if an error is safe to retry
341
- * Per CLAUDE.md §7: Only retry on transient/network errors, not client errors
342
- */
343
- isRetryableError(error) {
344
- // Network errors are retryable
345
- if (error instanceof NetworkError || error instanceof TimeoutError) {
346
- return true;
347
- }
348
- // 5xx server errors and 429 rate limits are retryable
349
- if (error instanceof SparkVaultError && error.statusCode !== undefined) {
350
- return error.statusCode >= 500 || error.statusCode === 429;
351
- }
352
- return false;
353
- }
354
259
  async parseResponse(response) {
355
260
  // Handle empty responses (204 No Content, etc.)
356
261
  // Callers expecting no body should use <void> as the generic type parameter.
@@ -393,6 +298,11 @@ class HttpClient {
393
298
  return new ValidationError(message, details);
394
299
  case 401:
395
300
  return new AuthenticationError(message, details);
301
+ case 402:
302
+ if (code === 'QUOTA_EXCEEDED')
303
+ return new QuotaExceededError(message, details);
304
+ // PLAN_REQUIRED is the canonical 402 gate; treat any other 402 as one too.
305
+ return new PlanRequiredError(message, details);
396
306
  case 403:
397
307
  return new AuthorizationError(message, details);
398
308
  default:
@@ -408,75 +318,28 @@ class HttpClient {
408
318
  }
409
319
  return data;
410
320
  }
321
+ /**
322
+ * Pull the `meta` envelope (carrying `pools` capacity snapshots) off a
323
+ * standard `{ data, meta }` response. Returns undefined for bare responses.
324
+ */
325
+ extractResponseMeta(data) {
326
+ if (typeof data === 'object' && data !== null) {
327
+ const record = data;
328
+ if (typeof record.meta === 'object' && record.meta !== null) {
329
+ return record.meta;
330
+ }
331
+ }
332
+ return undefined;
333
+ }
411
334
  get(path, options) {
412
335
  return this.request(path, { ...options, method: 'GET' });
413
336
  }
414
337
  post(path, body, options) {
415
338
  return this.request(path, { ...options, method: 'POST', body });
416
339
  }
417
- put(path, body, options) {
418
- return this.request(path, { ...options, method: 'PUT', body });
419
- }
420
- patch(path, body, options) {
421
- return this.request(path, { ...options, method: 'PATCH', body });
422
- }
423
340
  delete(path, options) {
424
341
  return this.request(path, { ...options, method: 'DELETE' });
425
342
  }
426
- /**
427
- * Request raw binary data (e.g., file downloads).
428
- * Returns a Blob instead of parsed JSON.
429
- */
430
- async requestRaw(path, options = {}) {
431
- const { retry } = options;
432
- // Per CLAUDE.md §7: Wrap with retry logic if enabled
433
- if (retry) {
434
- const retryOptions = typeof retry === 'object' ? retry : {};
435
- return withRetry(() => this.executeRequestRaw(path, options), {
436
- ...retryOptions,
437
- isRetryable: (error) => this.isRetryableError(error),
438
- });
439
- }
440
- return this.executeRequestRaw(path, options);
441
- }
442
- /**
443
- * Execute the actual raw HTTP request (internal implementation)
444
- */
445
- async executeRequestRaw(path, options) {
446
- const { method = 'GET', headers = {}, body, timeout = this.config.timeout, } = options;
447
- const url = `${this.config.apiBaseUrl}${path}`;
448
- const requestHeaders = await this.getDefaultHeaders(headers, body !== undefined);
449
- const controller = new AbortController();
450
- const timeoutId = setTimeout(() => controller.abort(), timeout);
451
- try {
452
- const response = await fetch(url, {
453
- method,
454
- headers: requestHeaders,
455
- body: body ? JSON.stringify(body) : undefined,
456
- signal: controller.signal,
457
- });
458
- clearTimeout(timeoutId);
459
- if (!response.ok) {
460
- // Try to parse error as JSON
461
- const errorData = await response.json().catch(() => ({}));
462
- throw this.createErrorFromResponse(response.status, errorData);
463
- }
464
- return response.blob();
465
- }
466
- catch (error) {
467
- clearTimeout(timeoutId);
468
- if (error instanceof SparkVaultError) {
469
- throw error;
470
- }
471
- if (error instanceof DOMException && error.name === 'AbortError') {
472
- throw new TimeoutError();
473
- }
474
- if (error instanceof TypeError) {
475
- throw new NetworkError('Network request failed. Please check your connection.');
476
- }
477
- throw new SparkVaultError(error instanceof Error ? error.message : 'Unknown error', 'unknown_error');
478
- }
479
- }
480
343
  }
481
344
 
482
345
  class HealthModule {
@@ -553,6 +416,37 @@ class HealthModule {
553
416
  */
554
417
  /** Default request timeout in milliseconds (30 seconds). */
555
418
  const DEFAULT_TIMEOUT_MS = 30000;
419
+ /**
420
+ * Combine a fresh timeout with a session close signal into one AbortSignal.
421
+ *
422
+ * The returned dispose() MUST run in a finally block: it clears the timeout
423
+ * and unlinks the close listener (the fallback path for browsers without
424
+ * AbortSignal.any) so nothing leaks across requests. Callers discriminate
425
+ * close-vs-timeout afterwards by checking the close signal's aborted flag.
426
+ */
427
+ function combineTimeoutAndCloseSignals(timeoutMs, closeSignal) {
428
+ const timeoutController = new AbortController();
429
+ const timeoutId = setTimeout(() => timeoutController.abort(), timeoutMs);
430
+ let signal;
431
+ let onCloseAbort = null;
432
+ if ('any' in AbortSignal) {
433
+ signal = AbortSignal.any([timeoutController.signal, closeSignal]);
434
+ }
435
+ else {
436
+ signal = timeoutController.signal;
437
+ onCloseAbort = () => timeoutController.abort();
438
+ closeSignal.addEventListener('abort', onCloseAbort);
439
+ }
440
+ return {
441
+ signal,
442
+ dispose: () => {
443
+ clearTimeout(timeoutId);
444
+ if (onCloseAbort) {
445
+ closeSignal.removeEventListener('abort', onCloseAbort);
446
+ }
447
+ },
448
+ };
449
+ }
556
450
  class SparkVaultApi {
557
451
  constructor(timeoutMs = DEFAULT_TIMEOUT_MS) {
558
452
  /**
@@ -599,24 +493,7 @@ class SparkVaultApi {
599
493
  if (localCloseController.signal.aborted) {
600
494
  throw this.makeError('Request cancelled', 'cancelled', 0);
601
495
  }
602
- const timeoutController = new AbortController();
603
- const timeoutId = setTimeout(() => timeoutController.abort(), this.timeoutMs);
604
- let combinedSignal;
605
- let onCloseAbort = null;
606
- if ('any' in AbortSignal) {
607
- combinedSignal = AbortSignal.any([
608
- timeoutController.signal,
609
- localCloseController.signal,
610
- ]);
611
- }
612
- else {
613
- // Fallback for browsers without AbortSignal.any: link the close
614
- // signal into the timeout controller manually. Listener is removed
615
- // in the finally block so it doesn't leak across requests.
616
- combinedSignal = timeoutController.signal;
617
- onCloseAbort = () => timeoutController.abort();
618
- localCloseController.signal.addEventListener('abort', onCloseAbort);
619
- }
496
+ const { signal: combinedSignal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, localCloseController.signal);
620
497
  try {
621
498
  // Only send Content-Type when there's actually a body — otherwise GETs
622
499
  // with no payload would carry a misleading content-type header.
@@ -658,10 +535,7 @@ class SparkVaultApi {
658
535
  throw this.makeError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
659
536
  }
660
537
  finally {
661
- clearTimeout(timeoutId);
662
- if (onCloseAbort) {
663
- localCloseController.signal.removeEventListener('abort', onCloseAbort);
664
- }
538
+ dispose();
665
539
  }
666
540
  }
667
541
  }
@@ -868,9 +742,7 @@ function base64urlToArrayBuffer(base64url) {
868
742
  * @returns Decoded UTF-8 string
869
743
  */
870
744
  function base64urlToString(base64url) {
871
- const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
872
- const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
873
- return atob(padded);
745
+ return new TextDecoder().decode(base64urlDecode(base64url));
874
746
  }
875
747
 
876
748
  /**
@@ -1218,6 +1090,28 @@ class IdentityApi extends SparkVaultApi {
1218
1090
  ...this.buildAuthContextParams(authContext),
1219
1091
  });
1220
1092
  }
1093
+ /**
1094
+ * Claim the SparkLink verification result by kindling — the WebSocket-loss
1095
+ * fallback. The SDK calls this when its socket was suspended with the tab and
1096
+ * it refocuses. Returns the verified result, or null while still pending (not
1097
+ * yet clicked) or already consumed. The read burns the server-side spark, so
1098
+ * the result can be claimed exactly once.
1099
+ */
1100
+ async consumeSparkLinkResult(kindling) {
1101
+ const data = await this.request('GET', `/sparklink/result?kindling=${encodeURIComponent(kindling)}`);
1102
+ if (!data || typeof data !== 'object' || typeof data.token !== 'string') {
1103
+ return null;
1104
+ }
1105
+ return {
1106
+ token: data.token,
1107
+ identity: data.identity,
1108
+ identityType: data.identityType || 'email',
1109
+ svid: typeof data.svid === 'string' ? data.svid : undefined,
1110
+ sessionId: typeof data.session_id === 'string' ? data.session_id : undefined,
1111
+ refreshToken: typeof data.refresh_token === 'string' ? data.refresh_token : undefined,
1112
+ redirect: typeof data.redirect === 'string' ? data.redirect : undefined,
1113
+ };
1114
+ }
1221
1115
  }
1222
1116
  class IdentityApiError extends SparkVaultError {
1223
1117
  constructor(message, code, statusCode, details) {
@@ -1347,8 +1241,7 @@ function enrichMethods(ids) {
1347
1241
  /**
1348
1242
  * Verification State Manager
1349
1243
  *
1350
- * Single source of truth for all verification flow state.
1351
- * Centralizes scattered state from IdentityRenderer for:
1244
+ * Single source of truth for all verification flow state:
1352
1245
  * - Predictable state transitions
1353
1246
  * - Easier debugging and testing
1354
1247
  * - Clear data ownership
@@ -1378,25 +1271,6 @@ class VerificationState {
1378
1271
  kindling: '',
1379
1272
  method: null,
1380
1273
  };
1381
- // State change listeners for reactivity
1382
- this.listeners = new Set();
1383
- }
1384
- /**
1385
- * Subscribe to state changes
1386
- * @param listener - Callback invoked on state change
1387
- * @returns Unsubscribe function
1388
- */
1389
- subscribe(listener) {
1390
- this.listeners.add(listener);
1391
- return () => this.listeners.delete(listener);
1392
- }
1393
- /**
1394
- * Notify all listeners of state change
1395
- */
1396
- notify() {
1397
- for (const listener of this.listeners) {
1398
- listener(this._viewState);
1399
- }
1400
1274
  }
1401
1275
  // --- SDK Config ---
1402
1276
  get sdkConfig() {
@@ -1408,24 +1282,6 @@ class VerificationState {
1408
1282
  get accountId() {
1409
1283
  return this._sdkConfig?.accountId ?? '';
1410
1284
  }
1411
- /**
1412
- * Get enriched methods filtered by the fallback identifier type.
1413
- */
1414
- getAvailableMethods() {
1415
- if (!this._sdkConfig)
1416
- return [];
1417
- const methodIds = this._sdkConfig.methods ?? [];
1418
- let methods = enrichMethods(methodIds);
1419
- // Filter by identifier type. Passkeys are SVID-scoped and remain
1420
- // available regardless of whether the fallback identifier is email or phone.
1421
- if (this._identityType === 'phone') {
1422
- methods = methods.filter((m) => m.type === 'passkey' || m.identityType === 'phone');
1423
- }
1424
- else {
1425
- methods = methods.filter((m) => m.identityType === 'email' || m.identityType === undefined);
1426
- }
1427
- return methods;
1428
- }
1429
1285
  /**
1430
1286
  * Check if passkey method is enabled in config
1431
1287
  */
@@ -1438,7 +1294,6 @@ class VerificationState {
1438
1294
  }
1439
1295
  setViewState(state) {
1440
1296
  this._viewState = state;
1441
- this.notify();
1442
1297
  }
1443
1298
  // --- Identity ---
1444
1299
  get recipient() {
@@ -1514,21 +1369,6 @@ class VerificationState {
1514
1369
  setTotpMethod(method) {
1515
1370
  this._totp.method = method;
1516
1371
  }
1517
- // --- Reset ---
1518
- /**
1519
- * Reset state for new verification attempt
1520
- */
1521
- reset() {
1522
- this._viewState = { view: 'loading' };
1523
- this._recipient = '';
1524
- this._identityType = 'email';
1525
- this._authContext = undefined;
1526
- this._passkey.hasPasskey = null;
1527
- this._passkey.isFallbackMode = false;
1528
- this._passkey.pendingResult = null;
1529
- this._totp.kindling = '';
1530
- this._totp.method = null;
1531
- }
1532
1372
  }
1533
1373
 
1534
1374
  /**
@@ -2024,6 +1864,7 @@ class SparkLinkHandler {
2024
1864
  success: true,
2025
1865
  sparkId: result.sparkId,
2026
1866
  expiresAt: result.expiresAt,
1867
+ kindling: result.kindling,
2027
1868
  };
2028
1869
  }
2029
1870
  catch (error) {
@@ -5762,6 +5603,13 @@ class IdentityRenderer {
5762
5603
  this.focusTimeoutId = null;
5763
5604
  // SparkLink WebSocket
5764
5605
  this.sparkLinkWs = null;
5606
+ // SparkLink WebSocket-loss fallback: the login kindling lets the SDK reclaim
5607
+ // the verified result if the socket was suspended with the tab (mobile). The
5608
+ // visibility handler fires the single re-check on refocus.
5609
+ this.sparkLinkKindling = null;
5610
+ this.sparkLinkVisibilityHandler = null;
5611
+ this.sparkLinkClaiming = false;
5612
+ this.sparkLinkRetryTimer = null;
5765
5613
  this.container = container;
5766
5614
  this.api = api;
5767
5615
  this.options = options;
@@ -6112,6 +5960,11 @@ class IdentityRenderer {
6112
5960
  * actual list of alternatives instead of bouncing back to passkey.
6113
5961
  */
6114
5962
  async showMethodSelect(options = {}) {
5963
+ // Leaving the SparkLink waiting view (e.g. "Choose another method") must
5964
+ // tear down its WebSocket + refocus listeners and clear the kindling, or a
5965
+ // later tab refocus would fire a stale claim for an abandoned flow.
5966
+ // Idempotent — a no-op when SparkLink was never armed.
5967
+ this.cleanupSparkLink();
6115
5968
  const autoRoute = options.autoRoute !== false;
6116
5969
  if (!this.sdkConfig)
6117
5970
  return;
@@ -6277,6 +6130,11 @@ class IdentityRenderer {
6277
6130
  });
6278
6131
  return;
6279
6132
  }
6133
+ // Arm the WebSocket-loss fallback: keep the kindling and re-check for
6134
+ // the result whenever the tab is brought back to the foreground with
6135
+ // a dead socket (the mobile email round-trip).
6136
+ this.sparkLinkKindling = result.kindling ?? null;
6137
+ this.armSparkLinkRefocusClaim();
6280
6138
  this.setState({
6281
6139
  view: 'sparklink-waiting',
6282
6140
  email: this.recipient,
@@ -6794,7 +6652,14 @@ class IdentityRenderer {
6794
6652
  * delegate navigation entirely to the SDK.
6795
6653
  */
6796
6654
  async handleSparkLinkVerified(result) {
6655
+ // Burn the server-side fallback spark so a completed login never leaves a
6656
+ // second claimable auth path floating around. Capture the kindling before
6657
+ // cleanup clears it; fire-and-forget (the WS path may already have it).
6658
+ const kindling = this.sparkLinkKindling;
6797
6659
  this.cleanupSparkLink();
6660
+ if (kindling) {
6661
+ void this.api.consumeSparkLinkResult(kindling).catch(() => { });
6662
+ }
6798
6663
  // Passkey upsell only when there's no redirect target — once we have
6799
6664
  // a destination we go there immediately, no upsell.
6800
6665
  if (!result.redirect && await this.shouldShowPasskeyPrompt()) {
@@ -6805,11 +6670,11 @@ class IdentityRenderer {
6805
6670
  });
6806
6671
  return;
6807
6672
  }
6808
- this.close();
6809
- // Hand the full result (including redirect) to the host first so the
6810
- // page-level handler can do app-specific work (logging, navigation,
6811
- // etc.) before we steal the browsing context with a navigation.
6673
+ // Hand the full result (including redirect) to the host BEFORE tearing down
6674
+ // the modal, so the host's onSuccess can act (logging, navigation) without
6675
+ // racing the teardown of the browsing context.
6812
6676
  this.safeOnSuccess(result);
6677
+ this.close();
6813
6678
  // SDK-side fallback navigation. If the host already navigated this is
6814
6679
  // a no-op (the document is already unloading); if not, this rescues
6815
6680
  // simple-mode flows whose host forgot to act on result.redirect.
@@ -6817,6 +6682,67 @@ class IdentityRenderer {
6817
6682
  navigateWith(this.options, result.redirect);
6818
6683
  }
6819
6684
  }
6685
+ /**
6686
+ * Arm the WebSocket-loss fallback for the waiting screen.
6687
+ *
6688
+ * While waiting for the emailed link, the socket can be dropped when the tab
6689
+ * is suspended (mobile: the user leaves to the mail app). On refocus, if the
6690
+ * socket is no longer open, reclaim the verified result once by kindling. A
6691
+ * single ~2s retry covers returning before the server finished writing it.
6692
+ * Deliberately NOT a polling loop — it fires only on refocus, and only when
6693
+ * the socket is actually gone.
6694
+ */
6695
+ armSparkLinkRefocusClaim() {
6696
+ if (this.sparkLinkVisibilityHandler || !this.sparkLinkKindling)
6697
+ return;
6698
+ if (typeof document === 'undefined')
6699
+ return;
6700
+ const handler = () => {
6701
+ if (typeof document !== 'undefined' && document.visibilityState !== 'visible')
6702
+ return;
6703
+ // Healthy socket → the push path owns completion; nothing to reclaim.
6704
+ if (this.sparkLinkWs && this.sparkLinkWs.readyState === WebSocket.OPEN)
6705
+ return;
6706
+ void this.claimSparkLinkResult(true);
6707
+ };
6708
+ this.sparkLinkVisibilityHandler = handler;
6709
+ document.addEventListener('visibilitychange', handler);
6710
+ if (typeof window !== 'undefined') {
6711
+ window.addEventListener('pageshow', handler);
6712
+ }
6713
+ }
6714
+ /**
6715
+ * Reclaim the verified result by kindling. Single attempt; if still pending
6716
+ * and allowRetry, schedule exactly one ~2s retry, then stop (the next refocus
6717
+ * or Resend can try again).
6718
+ */
6719
+ async claimSparkLinkResult(allowRetry) {
6720
+ const kindling = this.sparkLinkKindling;
6721
+ if (!kindling || this.sparkLinkClaiming)
6722
+ return;
6723
+ this.sparkLinkClaiming = true;
6724
+ let result = null;
6725
+ try {
6726
+ result = await this.api.consumeSparkLinkResult(kindling);
6727
+ }
6728
+ catch {
6729
+ result = null;
6730
+ }
6731
+ this.sparkLinkClaiming = false;
6732
+ if (result) {
6733
+ await this.handleSparkLinkVerified(result);
6734
+ return;
6735
+ }
6736
+ // Pending — the click may still be processing server-side. One short retry,
6737
+ // then stop. No ongoing polling. Tracked so cleanup can cancel it.
6738
+ if (allowRetry && this.sparkLinkKindling === kindling) {
6739
+ this.sparkLinkRetryTimer = setTimeout(() => {
6740
+ this.sparkLinkRetryTimer = null;
6741
+ if (this.sparkLinkKindling === kindling)
6742
+ void this.claimSparkLinkResult(false);
6743
+ }, 2000);
6744
+ }
6745
+ }
6820
6746
  /**
6821
6747
  * Clean up SparkLink WebSocket connection.
6822
6748
  */
@@ -6828,6 +6754,20 @@ class IdentityRenderer {
6828
6754
  this.sparkLinkWs.close();
6829
6755
  this.sparkLinkWs = null;
6830
6756
  }
6757
+ if (this.sparkLinkVisibilityHandler) {
6758
+ if (typeof document !== 'undefined') {
6759
+ document.removeEventListener('visibilitychange', this.sparkLinkVisibilityHandler);
6760
+ }
6761
+ if (typeof window !== 'undefined') {
6762
+ window.removeEventListener('pageshow', this.sparkLinkVisibilityHandler);
6763
+ }
6764
+ this.sparkLinkVisibilityHandler = null;
6765
+ }
6766
+ if (this.sparkLinkRetryTimer !== null) {
6767
+ clearTimeout(this.sparkLinkRetryTimer);
6768
+ this.sparkLinkRetryTimer = null;
6769
+ }
6770
+ this.sparkLinkKindling = null;
6831
6771
  }
6832
6772
  /**
6833
6773
  * Handle resending SparkLink.
@@ -6854,6 +6794,10 @@ class IdentityRenderer {
6854
6794
  }
6855
6795
  const result = await this.sparkLinkHandler.send(wsResult.connectionId);
6856
6796
  if (result.success) {
6797
+ // Re-arm the fallback against the resend's fresh kindling (openSparkLink-
6798
+ // WebSocket cleared the previous one).
6799
+ this.sparkLinkKindling = result.kindling ?? null;
6800
+ this.armSparkLinkRefocusClaim();
6857
6801
  this.setState({
6858
6802
  view: 'sparklink-waiting',
6859
6803
  email: this.recipient,
@@ -7085,6 +7029,26 @@ class WidgetEmbedder {
7085
7029
  this.close();
7086
7030
  window.location.href = url.toString();
7087
7031
  }
7032
+ /**
7033
+ * Navigate the host top window to a widget-supplied URL — only when it
7034
+ * resolves to http(s). The sender is already constrained to the trusted
7035
+ * widget origin, but defense-in-depth across the SparkVault->customer
7036
+ * boundary: compromised widget-origin code must never escalate into script
7037
+ * execution on the embedding page via a javascript:/data: navigation.
7038
+ */
7039
+ safeNavigate(url) {
7040
+ let resolved;
7041
+ try {
7042
+ resolved = new URL(url, window.location.href);
7043
+ }
7044
+ catch {
7045
+ return;
7046
+ }
7047
+ if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') {
7048
+ return;
7049
+ }
7050
+ window.location.href = resolved.href;
7051
+ }
7088
7052
  buildUrl() {
7089
7053
  const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/widget`);
7090
7054
  url.searchParams.set('origin', window.location.origin);
@@ -7135,7 +7099,7 @@ class WidgetEmbedder {
7135
7099
  // iframe; on return the host SDK consumes the redirect token.
7136
7100
  if (data.type === REDIRECT_TYPE && typeof data.url === 'string') {
7137
7101
  this.clearReadyTimer();
7138
- window.location.href = data.url;
7102
+ this.safeNavigate(data.url);
7139
7103
  return;
7140
7104
  }
7141
7105
  if (data.type !== RESULT_TYPE || this.settled)
@@ -7148,7 +7112,7 @@ class WidgetEmbedder {
7148
7112
  // Mirror the renderer's belt-and-suspenders: complete a server-issued
7149
7113
  // redirect from the host's own top window if the customer didn't.
7150
7114
  if (typeof result.redirect === 'string' && result.redirect) {
7151
- window.location.href = result.redirect;
7115
+ this.safeNavigate(result.redirect);
7152
7116
  }
7153
7117
  }
7154
7118
  else if (data.cancelled) {
@@ -7351,6 +7315,7 @@ class InlineContainer {
7351
7315
  }
7352
7316
  }
7353
7317
 
7318
+ /* global Element */
7354
7319
  /**
7355
7320
  * DOM Utilities
7356
7321
  *
@@ -7399,8 +7364,62 @@ function onBodyReady(callback) {
7399
7364
  }
7400
7365
  }
7401
7366
  }
7367
+ /**
7368
+ * Attach a click handler to every element matching `selector` — both elements
7369
+ * present once the DOM is ready and elements added later (observed via
7370
+ * MutationObserver).
7371
+ *
7372
+ * Each call is fully self-contained: the element bookkeeping lives in this
7373
+ * closure, so the returned cleanup removes only the listeners this call
7374
+ * registered. Multiple attachments — different selectors, or even the same
7375
+ * element attached twice — never interfere with one another.
7376
+ *
7377
+ * @param selector - CSS selector for elements to attach to
7378
+ * @param onClick - Click handler to register on every matching element
7379
+ * @returns Cleanup function that removes this call's listeners and observer
7380
+ */
7381
+ function attachClickHandler(selector, onClick) {
7382
+ let observer = null;
7383
+ let cleanedUp = false;
7384
+ const attached = new Map();
7385
+ const listen = (element) => {
7386
+ if (attached.has(element))
7387
+ return;
7388
+ element.addEventListener('click', onClick);
7389
+ attached.set(element, () => element.removeEventListener('click', onClick));
7390
+ };
7391
+ // Defer attachment until the DOM is ready so the selector can match.
7392
+ onDomReady(() => {
7393
+ // Cleanup can run before the DOM is ready; attaching afterwards would
7394
+ // register listeners that nothing could ever remove.
7395
+ if (cleanedUp)
7396
+ return;
7397
+ document.querySelectorAll(selector).forEach(listen);
7398
+ // Watch for dynamically added elements
7399
+ observer = new MutationObserver((mutations) => {
7400
+ mutations.forEach((mutation) => {
7401
+ mutation.addedNodes.forEach((node) => {
7402
+ if (node instanceof Element) {
7403
+ if (node.matches(selector))
7404
+ listen(node);
7405
+ node.querySelectorAll(selector).forEach(listen);
7406
+ }
7407
+ });
7408
+ });
7409
+ });
7410
+ // Use onBodyReady to handle edge cases where body isn't available yet
7411
+ onBodyReady(() => {
7412
+ observer?.observe(document.body, { childList: true, subtree: true });
7413
+ });
7414
+ });
7415
+ return () => {
7416
+ cleanedUp = true;
7417
+ observer?.disconnect();
7418
+ attached.forEach((removeListener) => removeListener());
7419
+ attached.clear();
7420
+ };
7421
+ }
7402
7422
 
7403
- /* global Element */
7404
7423
  /**
7405
7424
  * Identity Module
7406
7425
  *
@@ -7435,7 +7454,6 @@ class IdentityModule {
7435
7454
  constructor(config) {
7436
7455
  this.renderer = null;
7437
7456
  this.embedder = null;
7438
- this.attachedElements = new Map();
7439
7457
  this.config = config;
7440
7458
  this.api = new IdentityApi(config);
7441
7459
  // Preload config in background for instant dialog opening
@@ -7562,7 +7580,6 @@ class IdentityModule {
7562
7580
  * cleanup();
7563
7581
  */
7564
7582
  attach(selector, options = {}) {
7565
- let observer = null;
7566
7583
  const handleClick = async (event) => {
7567
7584
  event.preventDefault();
7568
7585
  try {
@@ -7579,48 +7596,10 @@ class IdentityModule {
7579
7596
  // Error already handled by callbacks or will use server redirect
7580
7597
  }
7581
7598
  };
7582
- const attachToElements = () => {
7583
- const elements = document.querySelectorAll(selector);
7584
- elements.forEach((element) => {
7585
- element.addEventListener('click', handleClick);
7586
- this.attachedElements.set(element, () => {
7587
- element.removeEventListener('click', handleClick);
7588
- });
7589
- });
7590
- // Watch for dynamically added elements
7591
- observer = new MutationObserver((mutations) => {
7592
- mutations.forEach((mutation) => {
7593
- mutation.addedNodes.forEach((node) => {
7594
- if (node instanceof Element) {
7595
- if (node.matches(selector)) {
7596
- node.addEventListener('click', handleClick);
7597
- this.attachedElements.set(node, () => {
7598
- node.removeEventListener('click', handleClick);
7599
- });
7600
- }
7601
- // Check descendants
7602
- node.querySelectorAll(selector).forEach((el) => {
7603
- if (!this.attachedElements.has(el)) {
7604
- el.addEventListener('click', handleClick);
7605
- this.attachedElements.set(el, () => {
7606
- el.removeEventListener('click', handleClick);
7607
- });
7608
- }
7609
- });
7610
- }
7611
- });
7612
- });
7613
- });
7614
- // Observe document.body for dynamic elements
7615
- // Use onBodyReady to handle edge cases where body isn't available yet
7616
- onBodyReady(() => {
7617
- observer?.observe(document.body, { childList: true, subtree: true });
7618
- });
7619
- };
7620
- // Defer attachment until DOM is ready, then complete any full-page
7621
- // social-login redirect result before the user has to click again.
7599
+ const cleanup = attachClickHandler(selector, handleClick);
7600
+ // Once the DOM is ready (after the click listeners attach), complete any
7601
+ // full-page social-login redirect result before the user has to click again.
7622
7602
  onDomReady(() => {
7623
- attachToElements();
7624
7603
  this.consumeRedirectResult()
7625
7604
  .then((result) => {
7626
7605
  if (result)
@@ -7630,12 +7609,7 @@ class IdentityModule {
7630
7609
  options.onError?.(error instanceof Error ? error : new Error(String(error)));
7631
7610
  });
7632
7611
  });
7633
- // Return cleanup function
7634
- return () => {
7635
- observer?.disconnect();
7636
- this.attachedElements.forEach((cleanup) => cleanup());
7637
- this.attachedElements.clear();
7638
- };
7612
+ return cleanup;
7639
7613
  }
7640
7614
  /**
7641
7615
  * Verify and decode an identity token.
@@ -7682,29 +7656,56 @@ class IdentityModule {
7682
7656
  if (!token) {
7683
7657
  return null;
7684
7658
  }
7685
- const expectedState = sessionStorage.getItem('sv_oauth_state');
7686
- if (expectedState && params.get('state') !== expectedState) {
7687
- throw new ValidationError('Invalid OAuth state');
7688
- }
7689
- const claims = await this.verifyToken(token);
7690
- const result = {
7691
- token,
7692
- identity: claims.identity,
7693
- identityType: claims.identity_type,
7694
- svid: claims.svid,
7695
- sessionId: claims.session_id,
7696
- };
7697
- if (typeof window.history?.replaceState === 'function') {
7698
- window.history.replaceState(window.history.state, document.title, `${window.location.pathname}${window.location.search}`);
7659
+ // Once a token is present it must be consumed exactly once: the hash and
7660
+ // one-shot OAuth state are cleared whether validation succeeds or fails.
7661
+ // A failing token left in the URL would make every subsequent verify()
7662
+ // re-consume and re-reject it before the dialog could ever open — login
7663
+ // would stay wedged until the user manually edited the URL.
7664
+ try {
7665
+ let expectedState = null;
7666
+ try {
7667
+ expectedState = sessionStorage.getItem('sv_oauth_state');
7668
+ }
7669
+ catch {
7670
+ // Storage disabled (private mode): proceed; the backend still binds state.
7671
+ }
7672
+ if (expectedState && params.get('state') !== expectedState) {
7673
+ throw new ValidationError('Invalid OAuth state');
7674
+ }
7675
+ const claims = await this.verifyToken(token);
7676
+ return {
7677
+ token,
7678
+ identity: claims.identity,
7679
+ identityType: claims.identity_type,
7680
+ svid: claims.svid,
7681
+ sessionId: claims.session_id,
7682
+ };
7683
+ }
7684
+ finally {
7685
+ if (typeof window.history?.replaceState === 'function') {
7686
+ window.history.replaceState(window.history.state, document.title, `${window.location.pathname}${window.location.search}`);
7687
+ }
7688
+ try {
7689
+ sessionStorage.removeItem('sv_oauth_state');
7690
+ sessionStorage.removeItem('sv_oauth_email');
7691
+ }
7692
+ catch {
7693
+ // Storage disabled (private mode): nothing to clear.
7694
+ }
7699
7695
  }
7700
- sessionStorage.removeItem('sv_oauth_state');
7701
- sessionStorage.removeItem('sv_oauth_email');
7702
- return result;
7703
7696
  }
7704
7697
  /**
7705
7698
  * Close the identity dialog/inline UI if open.
7699
+ *
7700
+ * Tears down whichever surface is active: the hosted-widget iframe
7701
+ * (default dialog mode — also releases the embedder's host scroll lock)
7702
+ * or the local renderer (inline / local mode).
7706
7703
  */
7707
7704
  close() {
7705
+ if (this.embedder) {
7706
+ this.embedder.close();
7707
+ this.embedder = null;
7708
+ }
7708
7709
  if (this.renderer) {
7709
7710
  this.renderer.close();
7710
7711
  this.renderer = null;
@@ -7817,6 +7818,15 @@ function isInitiateUploadResponse(data) {
7817
7818
  }
7818
7819
  /** tus protocol version used for the resumable upload session. */
7819
7820
  const TUS_VERSION = '1.0.0';
7821
+ /** Default TUS chunk size; the server may override via `X-Chunk-Size`. */
7822
+ const DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024;
7823
+ /**
7824
+ * Abort a stalled chunk PATCH after this long with no upload progress.
7825
+ * XHR's own `timeout` measures total request duration, which would abort a
7826
+ * slow-but-progressing 50MB chunk — so a chunk fails only after the
7827
+ * connection has been completely silent for the full window.
7828
+ */
7829
+ const CHUNK_INACTIVITY_TIMEOUT_MS = 60000;
7820
7830
  /**
7821
7831
  * Server-side finalization confirmation poll.
7822
7832
  *
@@ -7900,21 +7910,182 @@ class UploadApi extends SparkVaultApi {
7900
7910
  };
7901
7911
  }
7902
7912
  /**
7903
- * Confirm the upload was finalized SERVER-SIDE before reporting success.
7904
- *
7905
- * The TUS PATCH loop trusts a server-provided `Upload-Offset`; a buggy or
7906
- * malicious Forge could return an inflated offset before every chunk was
7907
- * actually committed and encrypted. This re-reads the server's own
7908
- * persisted offset via a TUS HEAD (which Forge only advances on a real S3
7909
- * commit) and requires it to reach the declared total — the web equivalent
7910
- * of the mobile SDK's `verifyIngotActive` (status === 'active') guarantee.
7913
+ * Upload a file to Forge over the TUS resumable protocol (v1.0.0).
7911
7914
  *
7912
- * Polls because the final chunk's commit and the offset write can lag the
7913
- * PATCH acknowledgement by a moment. Throws on a non-2xx HEAD, on a session
7914
- * that never reaches the expected offset within the poll budget, or on a
7915
- * cancelled session — never reports a half-finished upload as done.
7915
+ * The single canonical browser transfer path — the upload widget and the
7916
+ * authenticated `uploadIngot` flow both go through here (CLAUDE.md: one
7917
+ * transfer path). Creates the session, PATCHes chunks sized by the server's
7918
+ * `X-Chunk-Size` (50MB default, which keeps every request under CDN body
7919
+ * caps such as Cloudflare's 100MB), validates every server-reported offset,
7920
+ * and honors the session abort signal plus per-request timeouts.
7916
7921
  *
7917
- * @param uploadUrl - The TUS session URL (Forge `Location`, ISTK-bound).
7922
+ * Returns the TUS session URL so the caller can confirm server-side
7923
+ * finalization via {@link verifyUploadFinalized} before reporting success.
7924
+ */
7925
+ async uploadFileToForge(file, forgeUrl, onProgress) {
7926
+ if (typeof XMLHttpRequest === 'undefined') {
7927
+ throw new UploadApiError('XMLHttpRequest is required for browser uploads', 'environment_unsupported', 0);
7928
+ }
7929
+ const url = new URL(forgeUrl);
7930
+ const istk = url.searchParams.get('istk');
7931
+ if (!istk) {
7932
+ throw new UploadApiError('Forge upload URL is missing ISTK', 'invalid_forge_url', 0);
7933
+ }
7934
+ const session = await this.createTusSession(`${url.origin}${url.pathname}`, istk, file.size);
7935
+ const uploadUrl = session.location.startsWith('http')
7936
+ ? session.location
7937
+ : `${url.origin}${session.location}`;
7938
+ let offset = 0;
7939
+ while (offset < file.size) {
7940
+ if (this.isAborted()) {
7941
+ throw new UploadApiError('Upload cancelled', 'cancelled', 0);
7942
+ }
7943
+ const chunkEnd = Math.min(offset + session.chunkSize, file.size);
7944
+ offset = await this.patchChunk(uploadUrl, file.slice(offset, chunkEnd), offset, file.size, onProgress);
7945
+ }
7946
+ return uploadUrl;
7947
+ }
7948
+ /**
7949
+ * Create the TUS upload session. Forge reads only `Tus-Resumable`,
7950
+ * `Upload-Length`, and `X-ISTK` on create, and returns the session URL in
7951
+ * `Location` (possibly relative) plus its chunk size in `X-Chunk-Size`.
7952
+ */
7953
+ async createTusSession(endpoint, istk, totalSize) {
7954
+ const closeSignal = this.getAbortSignal();
7955
+ const { signal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, closeSignal);
7956
+ try {
7957
+ const response = await fetch(endpoint, {
7958
+ method: 'POST',
7959
+ headers: {
7960
+ 'Tus-Resumable': TUS_VERSION,
7961
+ 'Upload-Length': String(totalSize),
7962
+ 'X-ISTK': istk,
7963
+ },
7964
+ signal,
7965
+ });
7966
+ if (!response.ok) {
7967
+ const errorText = await response.text().catch(() => '');
7968
+ throw new UploadApiError(`Failed to create upload session: ${response.status} ${errorText}`, 'tus_create_failed', response.status);
7969
+ }
7970
+ const location = response.headers.get('Location');
7971
+ if (!location) {
7972
+ throw new UploadApiError('Server did not return upload location', 'tus_create_failed', response.status);
7973
+ }
7974
+ const chunkSizeHeader = response.headers.get('X-Chunk-Size');
7975
+ const chunkSize = chunkSizeHeader ? parseInt(chunkSizeHeader, 10) : NaN;
7976
+ return {
7977
+ location,
7978
+ chunkSize: Number.isFinite(chunkSize) && chunkSize > 0 ? chunkSize : DEFAULT_CHUNK_SIZE,
7979
+ };
7980
+ }
7981
+ catch (error) {
7982
+ if (error instanceof SparkVaultError)
7983
+ throw error;
7984
+ if (error != null && typeof error === 'object' && 'name' in error && error.name === 'AbortError') {
7985
+ if (this.isAborted()) {
7986
+ throw new UploadApiError('Upload cancelled', 'cancelled', 0);
7987
+ }
7988
+ throw new UploadApiError(`Upload session creation timed out after ${this.timeoutMs}ms`, 'timeout', 0);
7989
+ }
7990
+ if (error instanceof TypeError) {
7991
+ throw new UploadApiError('Unable to connect. Please check your connection and try again.', 'network_error', 0);
7992
+ }
7993
+ throw new UploadApiError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
7994
+ }
7995
+ finally {
7996
+ dispose();
7997
+ }
7998
+ }
7999
+ /**
8000
+ * PATCH one chunk with XMLHttpRequest (fetch exposes no upload progress).
8001
+ * Resolves with the server-confirmed offset for the next iteration.
8002
+ *
8003
+ * The server's `Upload-Offset` is validated, never trusted: it must be a
8004
+ * finite number that strictly advances past this chunk's start (this client
8005
+ * never sends an empty chunk, so a non-advancing 2xx would loop forever)
8006
+ * and never exceeds the file size (an inflated offset would skip real
8007
+ * chunks and report a partial upload as success).
8008
+ */
8009
+ patchChunk(uploadUrl, chunk, chunkStart, totalSize, onProgress) {
8010
+ return new Promise((resolve, reject) => {
8011
+ const closeSignal = this.getAbortSignal();
8012
+ if (closeSignal.aborted) {
8013
+ reject(new UploadApiError('Upload cancelled', 'cancelled', 0));
8014
+ return;
8015
+ }
8016
+ const xhr = new XMLHttpRequest();
8017
+ let settled = false;
8018
+ let timedOut = false;
8019
+ let watchdog = null;
8020
+ const onCloseAbort = () => xhr.abort();
8021
+ const finish = (settle) => {
8022
+ if (settled)
8023
+ return;
8024
+ settled = true;
8025
+ if (watchdog !== null)
8026
+ clearTimeout(watchdog);
8027
+ closeSignal.removeEventListener('abort', onCloseAbort);
8028
+ settle();
8029
+ };
8030
+ const resetWatchdog = () => {
8031
+ if (settled)
8032
+ return;
8033
+ if (watchdog !== null)
8034
+ clearTimeout(watchdog);
8035
+ watchdog = setTimeout(() => {
8036
+ timedOut = true;
8037
+ xhr.abort();
8038
+ }, CHUNK_INACTIVITY_TIMEOUT_MS);
8039
+ };
8040
+ closeSignal.addEventListener('abort', onCloseAbort);
8041
+ xhr.upload.onprogress = (event) => {
8042
+ resetWatchdog();
8043
+ if (event.lengthComputable) {
8044
+ onProgress?.(chunkStart + event.loaded, totalSize);
8045
+ }
8046
+ };
8047
+ xhr.onload = () => {
8048
+ if (xhr.status >= 200 && xhr.status < 300) {
8049
+ const header = xhr.getResponseHeader('Upload-Offset');
8050
+ const newOffset = header !== null ? parseInt(header, 10) : NaN;
8051
+ if (!Number.isFinite(newOffset) || newOffset <= chunkStart || newOffset > totalSize) {
8052
+ finish(() => reject(new UploadApiError(`Server returned invalid upload offset (${newOffset})`, 'invalid_offset', xhr.status)));
8053
+ return;
8054
+ }
8055
+ finish(() => resolve(newOffset));
8056
+ }
8057
+ else {
8058
+ finish(() => reject(new UploadApiError(`Chunk upload failed with status ${xhr.status}`, 'chunk_upload_failed', xhr.status)));
8059
+ }
8060
+ };
8061
+ xhr.onerror = () => finish(() => reject(new UploadApiError('Chunk upload failed', 'network_error', 0)));
8062
+ xhr.onabort = () => finish(() => reject(timedOut
8063
+ ? new UploadApiError(`Chunk upload timed out after ${CHUNK_INACTIVITY_TIMEOUT_MS}ms of inactivity`, 'timeout', 0)
8064
+ : new UploadApiError('Upload cancelled', 'cancelled', 0)));
8065
+ xhr.open('PATCH', uploadUrl);
8066
+ xhr.setRequestHeader('Tus-Resumable', TUS_VERSION);
8067
+ xhr.setRequestHeader('Upload-Offset', String(chunkStart));
8068
+ xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream');
8069
+ resetWatchdog();
8070
+ xhr.send(chunk);
8071
+ });
8072
+ }
8073
+ /**
8074
+ * Confirm the upload was finalized SERVER-SIDE before reporting success.
8075
+ *
8076
+ * The TUS PATCH loop trusts a server-provided `Upload-Offset`; a buggy or
8077
+ * malicious Forge could return an inflated offset before every chunk was
8078
+ * actually committed and encrypted. This re-reads the server's own
8079
+ * persisted offset via a TUS HEAD (which Forge only advances on a real S3
8080
+ * commit) and requires it to reach the declared total — the web equivalent
8081
+ * of the mobile SDK's `verifyIngotActive` (status === 'active') guarantee.
8082
+ *
8083
+ * Polls because the final chunk's commit and the offset write can lag the
8084
+ * PATCH acknowledgement by a moment. Throws on a non-2xx HEAD, on a session
8085
+ * that never reaches the expected offset within the poll budget, or on a
8086
+ * cancelled session — never reports a half-finished upload as done.
8087
+ *
8088
+ * @param uploadUrl - The TUS session URL (Forge `Location`, ISTK-bound).
7918
8089
  * @param expectedOffset - The declared total upload size in bytes.
7919
8090
  */
7920
8091
  async verifyUploadFinalized(uploadUrl, expectedOffset) {
@@ -7945,21 +8116,7 @@ class UploadApi extends SparkVaultApi {
7945
8116
  */
7946
8117
  async headUploadOffset(uploadUrl) {
7947
8118
  const closeSignal = this.getAbortSignal();
7948
- const timeoutController = new AbortController();
7949
- const timeoutId = setTimeout(() => timeoutController.abort(), this.timeoutMs);
7950
- // Combine timeout + session-close into one signal. Mirror the base
7951
- // client's fallback for browsers without AbortSignal.any: link the close
7952
- // signal into the timeout controller and remove the listener in finally.
7953
- let combinedSignal;
7954
- let onCloseAbort = null;
7955
- if ('any' in AbortSignal) {
7956
- combinedSignal = AbortSignal.any([timeoutController.signal, closeSignal]);
7957
- }
7958
- else {
7959
- combinedSignal = timeoutController.signal;
7960
- onCloseAbort = () => timeoutController.abort();
7961
- closeSignal.addEventListener('abort', onCloseAbort);
7962
- }
8119
+ const { signal: combinedSignal, dispose } = combineTimeoutAndCloseSignals(this.timeoutMs, closeSignal);
7963
8120
  try {
7964
8121
  const response = await fetch(uploadUrl, {
7965
8122
  method: 'HEAD',
@@ -7991,14 +8148,175 @@ class UploadApi extends SparkVaultApi {
7991
8148
  throw new UploadApiError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
7992
8149
  }
7993
8150
  finally {
7994
- clearTimeout(timeoutId);
7995
- if (onCloseAbort) {
7996
- closeSignal.removeEventListener('abort', onCloseAbort);
7997
- }
8151
+ dispose();
7998
8152
  }
7999
8153
  }
8000
8154
  }
8001
8155
 
8156
+ /**
8157
+ * Upload Widget Chrome
8158
+ *
8159
+ * Shared DOM builders for the branded chrome both upload containers render:
8160
+ * brand header, "Secured by SparkVault" footer, and the Triple Zero-Trust
8161
+ * security sidebar. One canonical copy — any branding/marketing/security-text
8162
+ * change lands here and reaches modal and inline modes alike.
8163
+ */
8164
+ /**
8165
+ * Build the branded header. Returns the close button (when rendered) so the
8166
+ * container can detach `onClose` in its destroy() cleanup.
8167
+ */
8168
+ function createBrandHeader(options) {
8169
+ const { branding, isDarkMode, withCloseButton, titleId, onClose } = options;
8170
+ const header = document.createElement('div');
8171
+ header.className = 'svu-header';
8172
+ const titleContainer = document.createElement('div');
8173
+ titleContainer.className = 'svu-header-title';
8174
+ // Use light logo for light theme (default), dark logo for dark mode
8175
+ const logoUrl = isDarkMode
8176
+ ? branding.logoDarkUrl || branding.logoLightUrl
8177
+ : branding.logoLightUrl || branding.logoDarkUrl;
8178
+ if (logoUrl) {
8179
+ const logo = document.createElement('img');
8180
+ logo.className = 'svu-logo';
8181
+ logo.src = logoUrl;
8182
+ logo.alt = branding.organizationName;
8183
+ titleContainer.appendChild(logo);
8184
+ // Screen reader title
8185
+ const srTitle = document.createElement('span');
8186
+ srTitle.className = 'svu-sr-only';
8187
+ if (titleId)
8188
+ srTitle.id = titleId;
8189
+ srTitle.textContent = branding.organizationName;
8190
+ titleContainer.appendChild(srTitle);
8191
+ }
8192
+ else if (branding.organizationName) {
8193
+ const companyName = document.createElement('h2');
8194
+ companyName.className = 'svu-company-name';
8195
+ if (titleId)
8196
+ companyName.id = titleId;
8197
+ companyName.textContent = branding.organizationName;
8198
+ titleContainer.appendChild(companyName);
8199
+ }
8200
+ header.appendChild(titleContainer);
8201
+ let closeBtn = null;
8202
+ if (withCloseButton) {
8203
+ closeBtn = document.createElement('button');
8204
+ closeBtn.className = 'svu-close-btn';
8205
+ closeBtn.setAttribute('aria-label', 'Close');
8206
+ closeBtn.innerHTML = `
8207
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8208
+ <path d="M18 6L6 18M6 6l12 12"/>
8209
+ </svg>
8210
+ `;
8211
+ closeBtn.addEventListener('click', onClose);
8212
+ header.appendChild(closeBtn);
8213
+ }
8214
+ return { header, closeBtn };
8215
+ }
8216
+ /** Build the "Secured by SparkVault" footer. */
8217
+ function createFooter() {
8218
+ const footer = document.createElement('div');
8219
+ footer.className = 'svu-footer';
8220
+ const footerText = document.createElement('span');
8221
+ footerText.className = 'svu-footer-text';
8222
+ footerText.appendChild(document.createTextNode('Secured by '));
8223
+ const footerLink = document.createElement('a');
8224
+ footerLink.href = 'https://sparkvault.com';
8225
+ footerLink.target = '_blank';
8226
+ footerLink.rel = 'noopener noreferrer';
8227
+ footerLink.className = 'svu-footer-link';
8228
+ footerLink.textContent = 'SparkVault';
8229
+ footerText.appendChild(footerLink);
8230
+ footer.appendChild(footerText);
8231
+ return footer;
8232
+ }
8233
+ /** Build the Triple Zero-Trust security sidebar shown during dark states. */
8234
+ function createSecuritySidebar(branding) {
8235
+ const sidebar = document.createElement('div');
8236
+ sidebar.className = 'svu-sidebar';
8237
+ // Logo
8238
+ const logoDiv = document.createElement('div');
8239
+ logoDiv.className = 'svu-sidebar-logo';
8240
+ if (branding.logoDarkUrl) {
8241
+ const logo = document.createElement('img');
8242
+ logo.src = branding.logoDarkUrl;
8243
+ logo.alt = branding.organizationName;
8244
+ logoDiv.appendChild(logo);
8245
+ }
8246
+ sidebar.appendChild(logoDiv);
8247
+ // Intro
8248
+ const intro = document.createElement('div');
8249
+ intro.className = 'svu-sidebar-intro';
8250
+ intro.innerHTML = `
8251
+ <h3>Secure File Transfer</h3>
8252
+ <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>
8253
+ `;
8254
+ sidebar.appendChild(intro);
8255
+ // Security details
8256
+ const security = document.createElement('div');
8257
+ security.className = 'svu-sidebar-security';
8258
+ security.innerHTML = `
8259
+ <h4>
8260
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8261
+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
8262
+ </svg>
8263
+ SparkVault's Triple Zero-Trust
8264
+ </h4>
8265
+ <p class="svu-security-intro">
8266
+ Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.
8267
+ </p>
8268
+ <div class="svu-key-chain">
8269
+ <div class="svu-key-item">
8270
+ <div class="svu-key-number">1</div>
8271
+ <div class="svu-key-info">
8272
+ <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>
8273
+ <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>
8274
+ <span class="svu-key-desc">Quantum-resistant key exchange</span>
8275
+ </div>
8276
+ </div>
8277
+ <div class="svu-key-connector">
8278
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8279
+ <path d="M12 5v14M5 12h14"/>
8280
+ </svg>
8281
+ </div>
8282
+ <div class="svu-key-item">
8283
+ <div class="svu-key-number">2</div>
8284
+ <div class="svu-key-info">
8285
+ <span class="svu-key-name">X25519 Ephemeral Key</span>
8286
+ <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>
8287
+ <span class="svu-key-desc">Perfect forward secrecy</span>
8288
+ </div>
8289
+ </div>
8290
+ <div class="svu-key-connector">
8291
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8292
+ <path d="M12 5v14M5 12h14"/>
8293
+ </svg>
8294
+ </div>
8295
+ <div class="svu-key-item">
8296
+ <div class="svu-key-number">3</div>
8297
+ <div class="svu-key-info">
8298
+ <span class="svu-key-name">HKDF-SHA512 Derived Key</span>
8299
+ <span class="svu-key-algo">Hardware-bound key derivation</span>
8300
+ <span class="svu-key-desc">Vault master key in secure enclave</span>
8301
+ </div>
8302
+ </div>
8303
+ </div>
8304
+ <div class="svu-encryption-result">
8305
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
8306
+ <path d="M20 6L9 17l-5-5"/>
8307
+ </svg>
8308
+ <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>
8309
+ </div>
8310
+ <div class="svu-security-badges">
8311
+ <span class="svu-tls-badge">TLS 1.3 In Transit</span>
8312
+ <span class="svu-tls-badge">Encrypted At Rest</span>
8313
+ <span class="svu-tls-badge">Zero Trust</span>
8314
+ </div>
8315
+ `;
8316
+ sidebar.appendChild(security);
8317
+ return sidebar;
8318
+ }
8319
+
8002
8320
  /**
8003
8321
  * Upload Widget Styles
8004
8322
  *
@@ -8008,19 +8326,19 @@ class UploadApi extends SparkVaultApi {
8008
8326
  const STYLE_ID = 'sparkvault-upload-styles';
8009
8327
  /**
8010
8328
  * Inject upload widget styles into the document head.
8329
+ * Idempotent: the stylesheet is static and shared by every widget instance —
8330
+ * per-instance behavior (backdrop blur, dark mode) is driven by class toggles.
8011
8331
  */
8012
- function injectUploadStyles(options) {
8332
+ function injectUploadStyles() {
8013
8333
  if (document.getElementById(STYLE_ID)) {
8014
8334
  return;
8015
8335
  }
8016
8336
  const style = document.createElement('style');
8017
8337
  style.id = STYLE_ID;
8018
- style.textContent = getUploadStyles(options);
8338
+ style.textContent = getUploadStyles();
8019
8339
  document.head.appendChild(style);
8020
8340
  }
8021
- function getUploadStyles(options) {
8022
- const { backdropBlur } = options;
8023
- const enableBlur = backdropBlur !== false;
8341
+ function getUploadStyles() {
8024
8342
  // Design tokens - light theme for upload widget
8025
8343
  const tokens = {
8026
8344
  // Colors
@@ -8087,8 +8405,8 @@ function getUploadStyles(options) {
8087
8405
  }
8088
8406
 
8089
8407
  .svu-overlay.svu-blur {
8090
- backdrop-filter: blur(${enableBlur ? '8px' : '0'});
8091
- -webkit-backdrop-filter: blur(${enableBlur ? '8px' : '0'});
8408
+ backdrop-filter: blur(8px);
8409
+ -webkit-backdrop-filter: blur(8px);
8092
8410
  }
8093
8411
 
8094
8412
  .svu-modal {
@@ -9116,6 +9434,8 @@ function getUploadStyles(options) {
9116
9434
  */
9117
9435
  const OVERLAY_ID = 'sparkvault-upload-overlay';
9118
9436
  const MODAL_ID = 'sparkvault-upload-modal';
9437
+ /** Title node id referenced by the overlay's aria-labelledby. */
9438
+ const MODAL_TITLE_ID = 'svu-modal-title';
9119
9439
  /**
9120
9440
  * Default branding used for immediate modal display before config loads.
9121
9441
  */
@@ -9156,17 +9476,14 @@ class UploadModalContainer {
9156
9476
  this.onCloseCallback = onClose;
9157
9477
  this.backdropBlur = options.backdropBlur !== false;
9158
9478
  this.branding = options.branding || DEFAULT_BRANDING;
9159
- injectUploadStyles({
9160
- branding: this.branding,
9161
- backdropBlur: this.backdropBlur,
9162
- });
9479
+ injectUploadStyles();
9163
9480
  // Create overlay
9164
9481
  const overlay = document.createElement('div');
9165
9482
  overlay.id = OVERLAY_ID;
9166
9483
  overlay.className = this.backdropBlur ? 'svu-overlay svu-blur' : 'svu-overlay';
9167
9484
  overlay.setAttribute('role', 'dialog');
9168
9485
  overlay.setAttribute('aria-modal', 'true');
9169
- overlay.setAttribute('aria-labelledby', 'svu-modal-title');
9486
+ overlay.setAttribute('aria-labelledby', MODAL_TITLE_ID);
9170
9487
  // Create modal
9171
9488
  const modal = document.createElement('div');
9172
9489
  modal.id = MODAL_ID;
@@ -9181,19 +9498,7 @@ class UploadModalContainer {
9181
9498
  const body = document.createElement('div');
9182
9499
  body.className = 'svu-body';
9183
9500
  // Create footer
9184
- const footer = document.createElement('div');
9185
- footer.className = 'svu-footer';
9186
- const footerText = document.createElement('span');
9187
- footerText.className = 'svu-footer-text';
9188
- footerText.appendChild(document.createTextNode('Secured by '));
9189
- const footerLink = document.createElement('a');
9190
- footerLink.href = 'https://sparkvault.com';
9191
- footerLink.target = '_blank';
9192
- footerLink.rel = 'noopener noreferrer';
9193
- footerLink.className = 'svu-footer-link';
9194
- footerLink.textContent = 'SparkVault';
9195
- footerText.appendChild(footerLink);
9196
- footer.appendChild(footerText);
9501
+ const footer = createFooter();
9197
9502
  main.appendChild(header);
9198
9503
  main.appendChild(body);
9199
9504
  main.appendChild(footer);
@@ -9217,47 +9522,15 @@ class UploadModalContainer {
9217
9522
  this.elements = { overlay, modal, main, header, body, footer, sidebar: null };
9218
9523
  }
9219
9524
  createHeader(branding) {
9220
- const header = document.createElement('div');
9221
- header.className = 'svu-header';
9222
- const titleContainer = document.createElement('div');
9223
- titleContainer.className = 'svu-header-title';
9224
- // Use light logo for light theme (default), dark logo for dark mode
9225
- const logoUrl = this.isDarkMode
9226
- ? branding.logoDarkUrl || branding.logoLightUrl
9227
- : branding.logoLightUrl || branding.logoDarkUrl;
9228
- if (logoUrl) {
9229
- const logo = document.createElement('img');
9230
- logo.className = 'svu-logo';
9231
- logo.src = logoUrl;
9232
- logo.alt = branding.organizationName;
9233
- titleContainer.appendChild(logo);
9234
- // Screen reader title
9235
- const srTitle = document.createElement('span');
9236
- srTitle.className = 'svu-sr-only';
9237
- srTitle.id = 'svu-modal-title';
9238
- srTitle.textContent = branding.organizationName;
9239
- titleContainer.appendChild(srTitle);
9240
- }
9241
- else if (branding.organizationName) {
9242
- const companyName = document.createElement('h2');
9243
- companyName.className = 'svu-company-name';
9244
- companyName.id = 'svu-modal-title';
9245
- companyName.textContent = branding.organizationName;
9246
- titleContainer.appendChild(companyName);
9247
- }
9248
- // Close button
9249
- this.closeBtn = document.createElement('button');
9250
- this.closeBtn.className = 'svu-close-btn';
9251
- this.closeBtn.setAttribute('aria-label', 'Close');
9252
- this.closeBtn.innerHTML = `
9253
- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9254
- <path d="M18 6L6 18M6 6l12 12"/>
9255
- </svg>
9256
- `;
9257
9525
  this.closeBtnClickHandler = () => this.handleClose();
9258
- this.closeBtn.addEventListener('click', this.closeBtnClickHandler);
9259
- header.appendChild(titleContainer);
9260
- header.appendChild(this.closeBtn);
9526
+ const { header, closeBtn } = createBrandHeader({
9527
+ branding,
9528
+ isDarkMode: this.isDarkMode,
9529
+ withCloseButton: true,
9530
+ titleId: MODAL_TITLE_ID,
9531
+ onClose: this.closeBtnClickHandler,
9532
+ });
9533
+ this.closeBtn = closeBtn;
9261
9534
  return header;
9262
9535
  }
9263
9536
  /**
@@ -9319,7 +9592,7 @@ class UploadModalContainer {
9319
9592
  return;
9320
9593
  if (show && !this.elements.sidebar) {
9321
9594
  // Create sidebar
9322
- const sidebar = this.createSecuritySidebar();
9595
+ const sidebar = createSecuritySidebar(this.branding);
9323
9596
  this.elements.modal.classList.add('svu-with-sidebar');
9324
9597
  this.elements.modal.appendChild(sidebar);
9325
9598
  this.elements.sidebar = sidebar;
@@ -9339,91 +9612,6 @@ class UploadModalContainer {
9339
9612
  }
9340
9613
  }
9341
9614
  }
9342
- createSecuritySidebar() {
9343
- const sidebar = document.createElement('div');
9344
- sidebar.className = 'svu-sidebar';
9345
- // Logo
9346
- const logoDiv = document.createElement('div');
9347
- logoDiv.className = 'svu-sidebar-logo';
9348
- if (this.branding.logoDarkUrl) {
9349
- const logo = document.createElement('img');
9350
- logo.src = this.branding.logoDarkUrl;
9351
- logo.alt = this.branding.organizationName;
9352
- logoDiv.appendChild(logo);
9353
- }
9354
- sidebar.appendChild(logoDiv);
9355
- // Intro
9356
- const intro = document.createElement('div');
9357
- intro.className = 'svu-sidebar-intro';
9358
- intro.innerHTML = `
9359
- <h3>Secure File Transfer</h3>
9360
- <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>
9361
- `;
9362
- sidebar.appendChild(intro);
9363
- // Security details
9364
- const security = document.createElement('div');
9365
- security.className = 'svu-sidebar-security';
9366
- security.innerHTML = `
9367
- <h4>
9368
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9369
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
9370
- </svg>
9371
- SparkVault's Triple Zero-Trust
9372
- </h4>
9373
- <p class="svu-security-intro">
9374
- Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.
9375
- </p>
9376
- <div class="svu-key-chain">
9377
- <div class="svu-key-item">
9378
- <div class="svu-key-number">1</div>
9379
- <div class="svu-key-info">
9380
- <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>
9381
- <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>
9382
- <span class="svu-key-desc">Quantum-resistant key exchange</span>
9383
- </div>
9384
- </div>
9385
- <div class="svu-key-connector">
9386
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9387
- <path d="M12 5v14M5 12h14"/>
9388
- </svg>
9389
- </div>
9390
- <div class="svu-key-item">
9391
- <div class="svu-key-number">2</div>
9392
- <div class="svu-key-info">
9393
- <span class="svu-key-name">X25519 Ephemeral Key</span>
9394
- <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>
9395
- <span class="svu-key-desc">Perfect forward secrecy</span>
9396
- </div>
9397
- </div>
9398
- <div class="svu-key-connector">
9399
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9400
- <path d="M12 5v14M5 12h14"/>
9401
- </svg>
9402
- </div>
9403
- <div class="svu-key-item">
9404
- <div class="svu-key-number">3</div>
9405
- <div class="svu-key-info">
9406
- <span class="svu-key-name">HKDF-SHA512 Derived Key</span>
9407
- <span class="svu-key-algo">Hardware-bound key derivation</span>
9408
- <span class="svu-key-desc">Vault master key in secure enclave</span>
9409
- </div>
9410
- </div>
9411
- </div>
9412
- <div class="svu-encryption-result">
9413
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9414
- <path d="M20 6L9 17l-5-5"/>
9415
- </svg>
9416
- <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>
9417
- </div>
9418
- <div class="svu-security-badges">
9419
- <span class="svu-tls-badge">TLS 1.3 In Transit</span>
9420
- <span class="svu-tls-badge">Encrypted At Rest</span>
9421
- <span class="svu-tls-badge">Zero Trust</span>
9422
- </div>
9423
- `;
9424
- sidebar.appendChild(security);
9425
- return sidebar;
9426
- }
9427
9615
  handleClose() {
9428
9616
  if (this.onCloseCallback) {
9429
9617
  this.onCloseCallback();
@@ -9516,10 +9704,7 @@ class UploadInlineContainer {
9516
9704
  }
9517
9705
  this.onCloseCallback = onClose;
9518
9706
  // Inject styles
9519
- injectUploadStyles({
9520
- branding: this.branding,
9521
- backdropBlur: false,
9522
- });
9707
+ injectUploadStyles();
9523
9708
  // Create main container
9524
9709
  this.container = document.createElement('div');
9525
9710
  this.container.className = 'svu-inline-container';
@@ -9534,19 +9719,7 @@ class UploadInlineContainer {
9534
9719
  this.container.appendChild(this.body);
9535
9720
  // Create footer if enabled
9536
9721
  if (this.containerOptions.showFooter) {
9537
- this.footer = document.createElement('div');
9538
- this.footer.className = 'svu-footer';
9539
- const footerText = document.createElement('span');
9540
- footerText.className = 'svu-footer-text';
9541
- footerText.appendChild(document.createTextNode('Secured by '));
9542
- const footerLink = document.createElement('a');
9543
- footerLink.href = 'https://sparkvault.com';
9544
- footerLink.target = '_blank';
9545
- footerLink.rel = 'noopener noreferrer';
9546
- footerLink.className = 'svu-footer-link';
9547
- footerLink.textContent = 'SparkVault';
9548
- footerText.appendChild(footerLink);
9549
- this.footer.appendChild(footerText);
9722
+ this.footer = createFooter();
9550
9723
  this.container.appendChild(this.footer);
9551
9724
  }
9552
9725
  // Clear target and append container
@@ -9604,7 +9777,7 @@ class UploadInlineContainer {
9604
9777
  return;
9605
9778
  if (show && !this.sidebar) {
9606
9779
  // Create sidebar
9607
- this.sidebar = this.createSecuritySidebar();
9780
+ this.sidebar = createSecuritySidebar(this.branding);
9608
9781
  this.container.classList.add('svu-with-sidebar');
9609
9782
  this.container.appendChild(this.sidebar);
9610
9783
  }
@@ -9655,134 +9828,16 @@ class UploadInlineContainer {
9655
9828
  this.onCloseCallback = null;
9656
9829
  }
9657
9830
  createHeader(branding) {
9658
- const header = document.createElement('div');
9659
- header.className = 'svu-header';
9660
- const titleContainer = document.createElement('div');
9661
- titleContainer.className = 'svu-header-title';
9662
- // Use appropriate logo based on dark mode
9663
- const logoUrl = this.isDarkMode
9664
- ? branding.logoDarkUrl || branding.logoLightUrl
9665
- : branding.logoLightUrl || branding.logoDarkUrl;
9666
- if (logoUrl) {
9667
- const logo = document.createElement('img');
9668
- logo.className = 'svu-logo';
9669
- logo.src = logoUrl;
9670
- logo.alt = branding.organizationName;
9671
- titleContainer.appendChild(logo);
9672
- // Screen reader title
9673
- const srTitle = document.createElement('span');
9674
- srTitle.className = 'svu-sr-only';
9675
- srTitle.textContent = branding.organizationName;
9676
- titleContainer.appendChild(srTitle);
9677
- }
9678
- else if (branding.organizationName) {
9679
- const companyName = document.createElement('h2');
9680
- companyName.className = 'svu-company-name';
9681
- companyName.textContent = branding.organizationName;
9682
- titleContainer.appendChild(companyName);
9683
- }
9684
- header.appendChild(titleContainer);
9685
- // Add close button if enabled
9686
- if (this.containerOptions.showCloseButton) {
9687
- this.closeBtn = document.createElement('button');
9688
- this.closeBtn.className = 'svu-close-btn';
9689
- this.closeBtn.setAttribute('aria-label', 'Close');
9690
- this.closeBtn.innerHTML = `
9691
- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9692
- <path d="M18 6L6 18M6 6l12 12"/>
9693
- </svg>
9694
- `;
9695
- this.closeBtnClickHandler = () => this.handleClose();
9696
- this.closeBtn.addEventListener('click', this.closeBtnClickHandler);
9697
- header.appendChild(this.closeBtn);
9698
- }
9831
+ this.closeBtnClickHandler = () => this.handleClose();
9832
+ const { header, closeBtn } = createBrandHeader({
9833
+ branding,
9834
+ isDarkMode: this.isDarkMode,
9835
+ withCloseButton: this.containerOptions.showCloseButton === true,
9836
+ onClose: this.closeBtnClickHandler,
9837
+ });
9838
+ this.closeBtn = closeBtn;
9699
9839
  return header;
9700
9840
  }
9701
- createSecuritySidebar() {
9702
- const sidebar = document.createElement('div');
9703
- sidebar.className = 'svu-sidebar';
9704
- // Logo
9705
- const logoDiv = document.createElement('div');
9706
- logoDiv.className = 'svu-sidebar-logo';
9707
- if (this.branding.logoDarkUrl) {
9708
- const logo = document.createElement('img');
9709
- logo.src = this.branding.logoDarkUrl;
9710
- logo.alt = this.branding.organizationName;
9711
- logoDiv.appendChild(logo);
9712
- }
9713
- sidebar.appendChild(logoDiv);
9714
- // Intro
9715
- const intro = document.createElement('div');
9716
- intro.className = 'svu-sidebar-intro';
9717
- intro.innerHTML = `
9718
- <h3>Secure File Transfer</h3>
9719
- <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>
9720
- `;
9721
- sidebar.appendChild(intro);
9722
- // Security details
9723
- const security = document.createElement('div');
9724
- security.className = 'svu-sidebar-security';
9725
- security.innerHTML = `
9726
- <h4>
9727
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9728
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
9729
- </svg>
9730
- SparkVault's Triple Zero-Trust
9731
- </h4>
9732
- <p class="svu-security-intro">
9733
- Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.
9734
- </p>
9735
- <div class="svu-key-chain">
9736
- <div class="svu-key-item">
9737
- <div class="svu-key-number">1</div>
9738
- <div class="svu-key-info">
9739
- <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>
9740
- <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>
9741
- <span class="svu-key-desc">Quantum-resistant key exchange</span>
9742
- </div>
9743
- </div>
9744
- <div class="svu-key-connector">
9745
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9746
- <path d="M12 5v14M5 12h14"/>
9747
- </svg>
9748
- </div>
9749
- <div class="svu-key-item">
9750
- <div class="svu-key-number">2</div>
9751
- <div class="svu-key-info">
9752
- <span class="svu-key-name">X25519 Ephemeral Key</span>
9753
- <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>
9754
- <span class="svu-key-desc">Perfect forward secrecy</span>
9755
- </div>
9756
- </div>
9757
- <div class="svu-key-connector">
9758
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9759
- <path d="M12 5v14M5 12h14"/>
9760
- </svg>
9761
- </div>
9762
- <div class="svu-key-item">
9763
- <div class="svu-key-number">3</div>
9764
- <div class="svu-key-info">
9765
- <span class="svu-key-name">HKDF-SHA512 Derived Key</span>
9766
- <span class="svu-key-algo">Hardware-bound key derivation</span>
9767
- <span class="svu-key-desc">Vault master key in secure enclave</span>
9768
- </div>
9769
- </div>
9770
- </div>
9771
- <div class="svu-encryption-result">
9772
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
9773
- <path d="M20 6L9 17l-5-5"/>
9774
- </svg>
9775
- <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>
9776
- </div>
9777
- <div class="svu-security-badges">
9778
- <span class="svu-tls-badge">TLS 1.3 In Transit</span>
9779
- <span class="svu-tls-badge">Encrypted At Rest</span>
9780
- <span class="svu-tls-badge">Zero Trust</span>
9781
- </div>
9782
- `;
9783
- sidebar.appendChild(security);
9784
- return sidebar;
9785
- }
9786
9841
  handleClose() {
9787
9842
  if (this.onCloseCallback) {
9788
9843
  this.onCloseCallback();
@@ -9825,6 +9880,14 @@ function generateRequestId() {
9825
9880
  const random = Array.from(randomBytes, byte => byte.toString(16).padStart(2, '0')).join('');
9826
9881
  return `${timestamp}${random}`;
9827
9882
  }
9883
+ /**
9884
+ * Whether an error represents a deliberate cancellation (user close,
9885
+ * programmatic close, or session abort) rather than a genuine failure.
9886
+ */
9887
+ function isCancellationError(error) {
9888
+ return (error instanceof UserCancelledError ||
9889
+ (error instanceof SparkVaultError && error.code === 'cancelled'));
9890
+ }
9828
9891
  /**
9829
9892
  * Format bytes to human readable string.
9830
9893
  */
@@ -9847,8 +9910,11 @@ class UploadRenderer {
9847
9910
  this.uploadModal = null;
9848
9911
  this.isInlineMode = false;
9849
9912
  this.hybridModalInitialized = false;
9850
- // Track active XHR for cancellation on close
9851
- this.activeXhr = null;
9913
+ // Lifecycle flags: a closed renderer must never render or fire callbacks,
9914
+ // and onCancel fires at most once per renderer (mutually exclusive with
9915
+ // onError — see cancel()/handleApiError).
9916
+ this.closed = false;
9917
+ this.cancelled = false;
9852
9918
  this.pasteHandler = null;
9853
9919
  this.container = container;
9854
9920
  this.api = api;
@@ -9889,16 +9955,13 @@ class UploadRenderer {
9889
9955
  }
9890
9956
  /**
9891
9957
  * Close the upload flow.
9892
- * Cancels all pending API requests and active uploads to prevent orphaned operations.
9958
+ * Cancels all pending API requests and active uploads (aborting the session
9959
+ * signal tears down any in-flight TUS chunk) to prevent orphaned operations.
9893
9960
  */
9894
9961
  close() {
9895
- // Cancel all pending API requests first
9962
+ this.closed = true;
9963
+ // Cancel all pending API requests and the active TUS transfer
9896
9964
  this.api.abort();
9897
- // Abort any active XHR upload
9898
- if (this.activeXhr) {
9899
- this.activeXhr.abort();
9900
- this.activeXhr = null;
9901
- }
9902
9965
  this.cleanupFileInput();
9903
9966
  this.cleanupPasteHandler();
9904
9967
  // Clean up modal if open (hybrid mode)
@@ -9909,14 +9972,64 @@ class UploadRenderer {
9909
9972
  }
9910
9973
  this.container.destroy();
9911
9974
  }
9912
- handleClose() {
9975
+ /**
9976
+ * Cancel the flow: tear everything down and fire the cancel contract
9977
+ * exactly once. onCancel and onError are mutually exclusive — a deliberate
9978
+ * cancellation (user close, programmatic close, or a new upload replacing
9979
+ * this renderer) must never surface as an error to the host.
9980
+ */
9981
+ cancel() {
9982
+ if (this.cancelled)
9983
+ return;
9984
+ this.cancelled = true;
9913
9985
  this.close();
9914
9986
  this.callbacks.onCancel();
9915
9987
  }
9988
+ handleClose() {
9989
+ this.cancel();
9990
+ }
9916
9991
  setState(state) {
9992
+ // A closed renderer never renders again — a progress event racing the
9993
+ // teardown must not resurrect the hybrid-mode modal or touch the DOM.
9994
+ if (this.closed)
9995
+ return;
9996
+ const previousView = this.viewState.view;
9917
9997
  this.viewState = state;
9998
+ // Progress events fire many times per second for the whole transfer.
9999
+ // While the uploading view is already on screen, mutate its progress
10000
+ // nodes in place instead of tearing down and rebuilding the subtree —
10001
+ // a full rebuild per event thrashes the DOM and restarts the progress
10002
+ // bar's CSS transition and the stage-arrow animation on every tick.
10003
+ if (previousView === 'uploading' &&
10004
+ state.view === 'uploading' &&
10005
+ this.updateUploadProgress(state)) {
10006
+ return;
10007
+ }
9918
10008
  this.render();
9919
10009
  }
10010
+ /**
10011
+ * Targeted DOM update for an already-rendered uploading view: progress fill
10012
+ * width plus the percentage and byte-count labels. Returns false when the
10013
+ * uploading view is not in the DOM, so the caller falls back to a full render.
10014
+ */
10015
+ updateUploadProgress(state) {
10016
+ // Hybrid inline mode renders uploading inside the modal overlay.
10017
+ const body = this.isInlineMode && this.uploadModal
10018
+ ? this.uploadModal.getBody()
10019
+ : this.container.getBody();
10020
+ const fill = body?.querySelector('.svu-progress-fill');
10021
+ if (!body || !fill)
10022
+ return false;
10023
+ fill.style.width = `${state.progress}%`;
10024
+ const [percentLabel, bytesLabel] = body.querySelectorAll('.svu-progress-text span');
10025
+ if (percentLabel) {
10026
+ percentLabel.textContent = `${state.progress}%`;
10027
+ }
10028
+ if (bytesLabel) {
10029
+ bytesLabel.textContent = `${formatBytes(state.bytesUploaded)} / ${formatBytes(state.file.size)}`;
10030
+ }
10031
+ return true;
10032
+ }
9920
10033
  render() {
9921
10034
  const isDarkState = this.viewState.view === 'uploading' || this.viewState.view === 'ceremony';
9922
10035
  // Hybrid mode: For inline containers, use a modal popup for upload/ceremony
@@ -10418,8 +10531,24 @@ class UploadRenderer {
10418
10531
  progress: 0,
10419
10532
  bytesUploaded: 0,
10420
10533
  });
10421
- // Upload file using tus (resumable upload)
10422
- const uploadUrl = await this.uploadWithTus(file, forgeUrl, ingotId, requestId);
10534
+ // Upload file over the canonical TUS transfer path
10535
+ const uploadUrl = await this.api.uploadFileToForge(file, forgeUrl, (bytesUploaded, bytesTotal) => {
10536
+ const progress = Math.round((bytesUploaded / bytesTotal) * 100);
10537
+ this.setState({
10538
+ view: 'uploading',
10539
+ file,
10540
+ ingotId,
10541
+ requestId,
10542
+ progress,
10543
+ bytesUploaded,
10544
+ });
10545
+ this.callbacks.onProgress?.({
10546
+ bytesUploaded,
10547
+ bytesTotal,
10548
+ percentage: progress,
10549
+ phase: 'uploading',
10550
+ });
10551
+ });
10423
10552
  // Confirm the server actually finalized the upload before celebrating.
10424
10553
  // The TUS loop trusts a server-provided offset; this re-reads the
10425
10554
  // server's own persisted offset and requires it to reach the file size,
@@ -10460,129 +10589,6 @@ class UploadRenderer {
10460
10589
  this.handleApiError(error);
10461
10590
  }
10462
10591
  }
10463
- async uploadWithTus(file, forgeUrl, ingotId, requestId) {
10464
- // tus resumable upload protocol v1.0.0
10465
- // Uploads file in chunks to avoid Cloudflare's 100MB request limit
10466
- const TUS_VERSION = '1.0.0';
10467
- const DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024; // 50MB default, server may override
10468
- // Extract base URL and ISTK from forge URL
10469
- const url = new URL(forgeUrl);
10470
- const istk = url.searchParams.get('istk');
10471
- const baseUrl = `${url.origin}${url.pathname}`;
10472
- if (!istk) {
10473
- throw new Error('Missing ISTK in forge URL');
10474
- }
10475
- // Step 1: Create tus upload session
10476
- const createResponse = await fetch(baseUrl, {
10477
- method: 'POST',
10478
- headers: {
10479
- 'Tus-Resumable': TUS_VERSION,
10480
- 'Upload-Length': String(file.size),
10481
- 'X-ISTK': istk,
10482
- 'Content-Type': 'application/offset+octet-stream',
10483
- },
10484
- });
10485
- if (!createResponse.ok) {
10486
- const errorText = await createResponse.text();
10487
- throw new Error(`Failed to create upload session: ${createResponse.status} ${errorText}`);
10488
- }
10489
- // Get upload location and chunk size from response
10490
- const location = createResponse.headers.get('Location');
10491
- const chunkSizeHeader = createResponse.headers.get('X-Chunk-Size');
10492
- const chunkSize = chunkSizeHeader ? parseInt(chunkSizeHeader, 10) : DEFAULT_CHUNK_SIZE;
10493
- if (!location) {
10494
- throw new Error('Server did not return upload location');
10495
- }
10496
- // Build full upload URL
10497
- const uploadUrl = location.startsWith('http') ? location : `${url.origin}${location}`;
10498
- // Step 2: Upload file in chunks with progress tracking
10499
- let offset = 0;
10500
- const totalSize = file.size;
10501
- while (offset < totalSize) {
10502
- const chunkStart = offset;
10503
- const chunkEnd = Math.min(offset + chunkSize, totalSize);
10504
- const chunk = file.slice(chunkStart, chunkEnd);
10505
- // Upload chunk with XHR for progress events
10506
- const newOffset = await this.uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, TUS_VERSION, file, ingotId, requestId);
10507
- offset = newOffset;
10508
- }
10509
- return uploadUrl;
10510
- }
10511
- /**
10512
- * Upload a single chunk using XMLHttpRequest for progress tracking.
10513
- * Tracks the XHR so it can be cancelled if the renderer is closed.
10514
- */
10515
- uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, tusVersion, file, ingotId, requestId) {
10516
- return new Promise((resolve, reject) => {
10517
- // Check if already aborted before starting
10518
- if (this.api.isAborted()) {
10519
- reject(new Error('Upload cancelled'));
10520
- return;
10521
- }
10522
- const xhr = new XMLHttpRequest();
10523
- // Track this XHR so it can be cancelled on close
10524
- this.activeXhr = xhr;
10525
- // Track progress within this chunk
10526
- xhr.upload.onprogress = (e) => {
10527
- if (e.lengthComputable) {
10528
- // Calculate total progress: completed chunks + progress within current chunk
10529
- const totalUploaded = chunkStart + e.loaded;
10530
- const progress = Math.round((totalUploaded / totalSize) * 100);
10531
- this.setState({
10532
- view: 'uploading',
10533
- file,
10534
- ingotId,
10535
- requestId,
10536
- progress,
10537
- bytesUploaded: totalUploaded,
10538
- });
10539
- this.callbacks.onProgress?.({
10540
- bytesUploaded: totalUploaded,
10541
- bytesTotal: totalSize,
10542
- percentage: progress,
10543
- phase: 'uploading',
10544
- });
10545
- }
10546
- };
10547
- xhr.onload = () => {
10548
- this.activeXhr = null;
10549
- if (xhr.status >= 200 && xhr.status < 300) {
10550
- // Get new offset from server response
10551
- const newOffsetHeader = xhr.getResponseHeader('Upload-Offset');
10552
- const newOffset = newOffsetHeader ? parseInt(newOffsetHeader, 10) : chunkStart + chunk.size;
10553
- // Defense-in-depth: the server must never report more bytes accepted
10554
- // than the file contains. A `newOffset > totalSize` is a malformed or
10555
- // inflated response — reject it rather than letting an over-reported
10556
- // offset short-circuit the upload loop and skip real chunks.
10557
- if (!Number.isFinite(newOffset) || newOffset < chunkStart || newOffset > totalSize) {
10558
- reject(new Error(`Server returned invalid upload offset (${newOffset})`));
10559
- return;
10560
- }
10561
- resolve(newOffset);
10562
- }
10563
- else {
10564
- reject(new Error(`Chunk upload failed with status ${xhr.status}`));
10565
- }
10566
- };
10567
- xhr.onerror = () => {
10568
- this.activeXhr = null;
10569
- reject(new Error('Chunk upload failed'));
10570
- };
10571
- xhr.ontimeout = () => {
10572
- this.activeXhr = null;
10573
- reject(new Error('Chunk upload timed out'));
10574
- };
10575
- xhr.onabort = () => {
10576
- this.activeXhr = null;
10577
- reject(new Error('Upload cancelled'));
10578
- };
10579
- xhr.open('PATCH', uploadUrl);
10580
- xhr.setRequestHeader('Tus-Resumable', tusVersion);
10581
- xhr.setRequestHeader('Upload-Offset', String(chunkStart));
10582
- xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream');
10583
- xhr.send(chunk);
10584
- });
10585
- }
10586
10592
  async runCeremony(file, ingotId, requestId) {
10587
10593
  for (let i = 0; i < CEREMONY_STEPS.length; i++) {
10588
10594
  this.setState({
@@ -10613,6 +10619,14 @@ class UploadRenderer {
10613
10619
  await new Promise(resolve => setTimeout(resolve, 500));
10614
10620
  }
10615
10621
  handleApiError(error) {
10622
+ // A closed renderer must not surface errors: cancelling mid-transfer
10623
+ // aborts the in-flight request, whose 'cancelled' rejection races the
10624
+ // teardown. The host has already received onCancel — onCancel and
10625
+ // onError are mutually exclusive — and the container is destroyed, so
10626
+ // there is nothing left to render into.
10627
+ if (this.closed || isCancellationError(error)) {
10628
+ return;
10629
+ }
10616
10630
  if (error instanceof UploadApiError) {
10617
10631
  if (error.code === 'UPLOAD_SOURCE_DISABLED') {
10618
10632
  // The vault exists but the embedded widget isn't enabled.
@@ -10682,7 +10696,6 @@ class UploadRenderer {
10682
10696
  }
10683
10697
  }
10684
10698
 
10685
- /* global Element */
10686
10699
  /**
10687
10700
  * Vault Upload Module
10688
10701
  *
@@ -10703,7 +10716,6 @@ class UploadRenderer {
10703
10716
  class VaultUploadModule {
10704
10717
  constructor(config) {
10705
10718
  this.renderer = null;
10706
- this.attachedElements = new Map();
10707
10719
  this.config = config;
10708
10720
  this.api = new UploadApi(config);
10709
10721
  }
@@ -10727,9 +10739,10 @@ class VaultUploadModule {
10727
10739
  if (!options.vaultId) {
10728
10740
  throw new ValidationError('vaultId is required');
10729
10741
  }
10730
- // Close any existing renderer
10742
+ // Cancel any existing renderer so its pending promise settles via the
10743
+ // cancel contract (onCancel + UserCancelledError) instead of hanging.
10731
10744
  if (this.renderer) {
10732
- this.renderer.close();
10745
+ this.renderer.cancel();
10733
10746
  }
10734
10747
  const isInline = !!options.target;
10735
10748
  const container = isInline
@@ -10788,7 +10801,6 @@ class VaultUploadModule {
10788
10801
  if (!options.vaultId) {
10789
10802
  throw new ValidationError('vaultId is required');
10790
10803
  }
10791
- let observer = null;
10792
10804
  const handleClick = async (event) => {
10793
10805
  event.preventDefault();
10794
10806
  try {
@@ -10804,55 +10816,17 @@ class VaultUploadModule {
10804
10816
  // Error already handled by callbacks or will use server redirect
10805
10817
  }
10806
10818
  };
10807
- const attachToElements = () => {
10808
- const elements = document.querySelectorAll(selector);
10809
- elements.forEach((element) => {
10810
- element.addEventListener('click', handleClick);
10811
- this.attachedElements.set(element, () => {
10812
- element.removeEventListener('click', handleClick);
10813
- });
10814
- });
10815
- // Watch for dynamically added elements
10816
- observer = new MutationObserver((mutations) => {
10817
- mutations.forEach((mutation) => {
10818
- mutation.addedNodes.forEach((node) => {
10819
- if (node instanceof Element) {
10820
- if (node.matches(selector)) {
10821
- node.addEventListener('click', handleClick);
10822
- this.attachedElements.set(node, () => {
10823
- node.removeEventListener('click', handleClick);
10824
- });
10825
- }
10826
- // Check descendants
10827
- node.querySelectorAll(selector).forEach((el) => {
10828
- if (!this.attachedElements.has(el)) {
10829
- el.addEventListener('click', handleClick);
10830
- this.attachedElements.set(el, () => {
10831
- el.removeEventListener('click', handleClick);
10832
- });
10833
- }
10834
- });
10835
- }
10836
- });
10837
- });
10838
- });
10839
- observer.observe(document.body, { childList: true, subtree: true });
10840
- };
10841
- // Defer attachment until DOM is ready
10842
- onDomReady(attachToElements);
10843
- // Return cleanup function
10844
- return () => {
10845
- observer?.disconnect();
10846
- this.attachedElements.forEach((cleanup) => cleanup());
10847
- this.attachedElements.clear();
10848
- };
10819
+ return attachClickHandler(selector, handleClick);
10849
10820
  }
10850
10821
  /**
10851
10822
  * Close the upload dialog/inline UI if open.
10823
+ *
10824
+ * Programmatic close follows the cancel contract: the host's onCancel
10825
+ * fires and the pending upload promise rejects with UserCancelledError.
10852
10826
  */
10853
10827
  close() {
10854
10828
  if (this.renderer) {
10855
- this.renderer.close();
10829
+ this.renderer.cancel();
10856
10830
  this.renderer = null;
10857
10831
  }
10858
10832
  }
@@ -10876,9 +10850,9 @@ class VaultUploadModule {
10876
10850
  }
10877
10851
  return new UploadInlineContainer(element);
10878
10852
  }
10879
- // Public-API aliases. The web vault-edit screen instructs customers to
10880
- // call sv.vaults.upload.pop(vaultId) / .render(vaultId, target) — both
10881
- // are documented entry points that defer to upload() under the hood.
10853
+ // Public-API aliases. The dashboard's vault-edit screen and the SDK docs
10854
+ // document sv.vaults.upload.pop({ vaultId }) and
10855
+ // sv.vaults.upload.render({ vaultId, target }) — both defer to upload().
10882
10856
  /** Open the upload widget as a popup. Equivalent to `upload(options)`. */
10883
10857
  async pop(options) {
10884
10858
  return this.upload(options);
@@ -10900,10 +10874,13 @@ class VaultsModule {
10900
10874
  this.config = config;
10901
10875
  this.http = http;
10902
10876
  this.uploadModule = new VaultUploadModule(config);
10903
- // Create callable that also has attach/close methods
10877
+ this.uploadApi = new UploadApi(config);
10878
+ // Create callable that also has attach/close/pop/render methods
10904
10879
  const uploadFn = ((options) => this.uploadModule.upload(options));
10905
10880
  uploadFn.attach = (selector, options) => this.uploadModule.attach(selector, options);
10906
10881
  uploadFn.close = () => this.uploadModule.close();
10882
+ uploadFn.pop = (options) => this.uploadModule.pop(options);
10883
+ uploadFn.render = (options) => this.uploadModule.render(options);
10907
10884
  this.upload = uploadFn;
10908
10885
  }
10909
10886
  /**
@@ -11011,7 +10988,11 @@ class VaultsModule {
11011
10988
  if (!created.forge_url) {
11012
10989
  throw new ValidationError('Upload endpoint did not return a Forge upload URL');
11013
10990
  }
11014
- await uploadBlobWithTus(options.file, created.forge_url, created.name, created.content_type, options.onProgress);
10991
+ const uploadUrl = await this.uploadApi.uploadFileToForge(options.file, created.forge_url, options.onProgress);
10992
+ // Confirm the server actually finalized the upload before reporting
10993
+ // success — the TUS loop's offsets alone don't prove the final chunk
10994
+ // committed and the ingot went active.
10995
+ await this.uploadApi.verifyUploadFinalized(uploadUrl, options.file.size);
11015
10996
  return {
11016
10997
  id: created.ingot_id,
11017
10998
  name: created.name,
@@ -11121,78 +11102,6 @@ function getBlobName(file) {
11121
11102
  }
11122
11103
  return 'unnamed';
11123
11104
  }
11124
- function base64Encode(value) {
11125
- return btoa(unescape(encodeURIComponent(value)));
11126
- }
11127
- async function uploadBlobWithTus(file, forgeUrl, filename, contentType, onProgress) {
11128
- if (typeof XMLHttpRequest === 'undefined') {
11129
- throw new ValidationError('XMLHttpRequest is required for browser ingot uploads');
11130
- }
11131
- const tusVersion = '1.0.0';
11132
- const defaultChunkSize = 50 * 1024 * 1024;
11133
- const url = new URL(forgeUrl);
11134
- const istk = url.searchParams.get('istk');
11135
- const endpoint = `${url.origin}${url.pathname}`;
11136
- if (!istk) {
11137
- throw new ValidationError('Forge upload URL is missing ISTK');
11138
- }
11139
- const createResponse = await fetch(endpoint, {
11140
- method: 'POST',
11141
- headers: {
11142
- 'Tus-Resumable': tusVersion,
11143
- 'Upload-Length': String(file.size),
11144
- 'Upload-Metadata': `filename ${base64Encode(filename)},filetype ${base64Encode(contentType)}`,
11145
- 'X-ISTK': istk,
11146
- },
11147
- });
11148
- if (!createResponse.ok) {
11149
- const errorText = await createResponse.text();
11150
- throw new Error(`Failed to create upload session: ${createResponse.status} ${errorText}`);
11151
- }
11152
- const location = createResponse.headers.get('Location');
11153
- const chunkSizeHeader = createResponse.headers.get('X-Chunk-Size');
11154
- const chunkSize = chunkSizeHeader ? parseInt(chunkSizeHeader, 10) : defaultChunkSize;
11155
- if (!location) {
11156
- throw new Error('Server did not return upload location');
11157
- }
11158
- const uploadUrl = location.startsWith('http') ? location : `${url.origin}${location}`;
11159
- let offset = 0;
11160
- while (offset < file.size) {
11161
- const chunkStart = offset;
11162
- const chunkEnd = Math.min(offset + chunkSize, file.size);
11163
- const chunk = file.slice(chunkStart, chunkEnd);
11164
- offset = await uploadChunkWithProgress(uploadUrl, chunk, chunkStart, file.size, tusVersion, istk, onProgress);
11165
- }
11166
- }
11167
- function uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, tusVersion, istk, onProgress) {
11168
- return new Promise((resolve, reject) => {
11169
- const xhr = new XMLHttpRequest();
11170
- xhr.upload.onprogress = (event) => {
11171
- if (event.lengthComputable) {
11172
- onProgress?.(chunkStart + event.loaded, totalSize);
11173
- }
11174
- };
11175
- xhr.onload = () => {
11176
- if (xhr.status >= 200 && xhr.status < 300) {
11177
- const newOffsetHeader = xhr.getResponseHeader('Upload-Offset');
11178
- const newOffset = newOffsetHeader ? parseInt(newOffsetHeader, 10) : chunkStart + chunk.size;
11179
- resolve(newOffset);
11180
- }
11181
- else {
11182
- reject(new Error(`Chunk upload failed with status ${xhr.status}`));
11183
- }
11184
- };
11185
- xhr.onerror = () => reject(new Error('Chunk upload failed'));
11186
- xhr.ontimeout = () => reject(new Error('Chunk upload timed out'));
11187
- xhr.onabort = () => reject(new Error('Upload cancelled'));
11188
- xhr.open('PATCH', uploadUrl);
11189
- xhr.setRequestHeader('Tus-Resumable', tusVersion);
11190
- xhr.setRequestHeader('Upload-Offset', String(chunkStart));
11191
- xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream');
11192
- xhr.setRequestHeader('X-ISTK', istk);
11193
- xhr.send(chunk);
11194
- });
11195
- }
11196
11105
  const DOWNLOAD_MAX_ATTEMPTS = 3;
11197
11106
  const DOWNLOAD_RETRY_BASE_MS = 500;
11198
11107
  function delayExponential(attempt) {
@@ -11439,5 +11348,5 @@ if (typeof window !== 'undefined') {
11439
11348
  window.SparkVault = instance ?? SparkVault;
11440
11349
  }
11441
11350
 
11442
- export { AuthenticationError, AuthorizationError, NetworkError, PopupBlockedError, SparkVault, SparkVaultError, TimeoutError, UserCancelledError, ValidationError, SparkVault as default, logger, setDebugMode };
11351
+ export { AuthenticationError, AuthorizationError, NetworkError, PlanRequiredError, PopupBlockedError, QuotaExceededError, SparkVault, SparkVaultError, TimeoutError, UserCancelledError, ValidationError, SparkVault as default, logger, setDebugMode };
11443
11352
  //# sourceMappingURL=sparkvault.esm.js.map