@sparkvault/sdk-js 2.0.1 → 2.0.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.
@@ -45,7 +45,7 @@ export declare abstract class SparkVaultApi {
45
45
  */
46
46
  resetSession(): void;
47
47
  /** Subclass-specific error factory. */
48
- protected abstract makeError(message: string, code: string, statusCode: number): SparkVaultError;
48
+ protected abstract makeError(message: string, code: string, statusCode: number, details?: Record<string, unknown>): SparkVaultError;
49
49
  /**
50
50
  * Issue an HTTP request with timeout + session abort + standard error
51
51
  * mapping. Subclasses build URLs and unwrap response envelopes on top.
@@ -14,7 +14,7 @@ export declare class IdentityApi extends SparkVaultApi {
14
14
  private configCache;
15
15
  constructor(config: ResolvedConfig, timeoutMs?: number);
16
16
  private get baseUrl();
17
- protected makeError(message: string, code: string, statusCode: number): IdentityApiError;
17
+ protected makeError(message: string, code: string, statusCode: number, details?: Record<string, unknown>): IdentityApiError;
18
18
  private request;
19
19
  /**
20
20
  * Fetch SDK configuration (branding, enabled methods).
@@ -105,5 +105,5 @@ export declare class IdentityApi extends SparkVaultApi {
105
105
  sendSparkLink(email: string, connectionId: string, authContext?: AuthContext): Promise<SparkLinkSendResponse>;
106
106
  }
107
107
  export declare class IdentityApiError extends SparkVaultError {
108
- constructor(message: string, code: string, statusCode: number);
108
+ constructor(message: string, code: string, statusCode: number, details?: Record<string, unknown>);
109
109
  }
@@ -42,9 +42,15 @@ export declare class IdentityRenderer {
42
42
  start(): Promise<void>;
43
43
  /**
44
44
  * Map a config-fetch error to the appropriate terminal view.
45
- * `product_not_configured` is a misconfiguration (the account has not
46
- * configured Identity) — show a developer-targeted terminal screen with a
47
- * link to SparkVault.com instead of the generic service-unavailable view.
45
+ *
46
+ * Two failures are permanent developer-misconfigurations, not transient
47
+ * outages, so they get dedicated terminal screens (no "Try Again" — retrying
48
+ * can never clear them) instead of the generic service-unavailable view:
49
+ * - `product_not_configured`: the account has not configured Identity.
50
+ * - `ORIGIN_NOT_ALLOWED`: this site's domain is not on the account's
51
+ * allowlist. Surfacing it as "Temporarily Unavailable / try again" sends
52
+ * the developer chasing a non-existent outage.
53
+ * Everything else (network errors, 5xx) is genuinely transient.
48
54
  */
49
55
  private viewStateForConfigError;
50
56
  /**
@@ -237,4 +237,7 @@ export type IdentityViewState = {
237
237
  view: 'service-unavailable';
238
238
  } | {
239
239
  view: 'product-not-configured';
240
+ } | {
241
+ view: 'origin-not-allowed';
242
+ origin?: string;
240
243
  };
@@ -14,3 +14,4 @@ export * from './sparklink-waiting';
14
14
  export * from './error';
15
15
  export * from './service-unavailable';
16
16
  export * from './product-not-configured';
17
+ export * from './origin-not-allowed';
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Origin Not Allowed View
3
+ *
4
+ * Full-dialog terminal screen shown when the embedding site's origin is not in
5
+ * the account's verified-domains allowlist. The audience is the website owner /
6
+ * developer — this is a misconfiguration surface, not an end-user error, and it
7
+ * is permanent (retrying never clears an origin block) — so the dialog drops
8
+ * customer branding, offers no "Try Again", names the blocked origin, and
9
+ * points to the place that fixes it. Reuses the SparkVault-notice styling from
10
+ * the product-not-configured view.
11
+ */
12
+ import type { View } from './base';
13
+ export interface OriginNotAllowedViewProps {
14
+ /** The blocked embedding origin, when the server reported it. */
15
+ origin?: string;
16
+ onClose: () => void;
17
+ }
18
+ export declare class OriginNotAllowedView implements View {
19
+ private readonly props;
20
+ private dismissButton;
21
+ private readonly boundHandleClose;
22
+ constructor(props: OriginNotAllowedViewProps);
23
+ render(): HTMLElement;
24
+ destroy(): void;
25
+ }
@@ -637,8 +637,8 @@ class SparkVaultApi {
637
637
  });
638
638
  const json = await response.json().catch(() => null);
639
639
  if (!response.ok) {
640
- const { message, code } = extractApiError(json);
641
- throw this.makeError(message, code, response.status);
640
+ const { message, code, details } = extractApiError(json);
641
+ throw this.makeError(message, code, response.status, details);
642
642
  }
643
643
  return { data: json, status: response.status };
644
644
  }
@@ -684,7 +684,10 @@ function extractApiError(json) {
684
684
  (typeof root.message === 'string' ? root.message : null) ??
685
685
  'Request failed';
686
686
  const code = typeof errorObj.code === 'string' ? errorObj.code : 'api_error';
687
- return { message, code };
687
+ const details = typeof errorObj.details === 'object' && errorObj.details !== null
688
+ ? errorObj.details
689
+ : undefined;
690
+ return { message, code, details };
688
691
  }
689
692
 
690
693
  /**
@@ -955,8 +958,8 @@ class IdentityApi extends SparkVaultApi {
955
958
  get baseUrl() {
956
959
  return `${this.config.identityBaseUrl}/${this.config.accountId}`;
957
960
  }
958
- makeError(message, code, statusCode) {
959
- return new IdentityApiError(message, code, statusCode);
961
+ makeError(message, code, statusCode, details) {
962
+ return new IdentityApiError(message, code, statusCode, details);
960
963
  }
961
964
  async request(method, endpoint, body) {
962
965
  const { data } = await this.rawRequest(`${this.baseUrl}${endpoint}`, {
@@ -1180,8 +1183,8 @@ class IdentityApi extends SparkVaultApi {
1180
1183
  }
1181
1184
  }
1182
1185
  class IdentityApiError extends SparkVaultError {
1183
- constructor(message, code, statusCode) {
1184
- super(message, code, statusCode);
1186
+ constructor(message, code, statusCode, details) {
1187
+ super(message, code, statusCode, details);
1185
1188
  this.name = 'IdentityApiError';
1186
1189
  Object.setPrototypeOf(this, IdentityApiError.prototype);
1187
1190
  }
@@ -5115,7 +5118,7 @@ class ServiceUnavailableView {
5115
5118
  * presents itself as an unmistakable SparkVault notice.
5116
5119
  */
5117
5120
  const ACTIVATION_URL = 'https://app.sparkvault.com/products/identity';
5118
- function createBadge() {
5121
+ function createBadge$1() {
5119
5122
  const badge = div('sv-not-activated-badge');
5120
5123
  const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
5121
5124
  svg.setAttribute('viewBox', '0 0 64 64');
@@ -5169,7 +5172,7 @@ function createBadge() {
5169
5172
  badge.appendChild(svg);
5170
5173
  return badge;
5171
5174
  }
5172
- function createExternalLinkIcon() {
5175
+ function createExternalLinkIcon$1() {
5173
5176
  const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
5174
5177
  svg.setAttribute('viewBox', '0 0 16 16');
5175
5178
  svg.setAttribute('width', '14');
@@ -5185,7 +5188,7 @@ function createExternalLinkIcon() {
5185
5188
  svg.appendChild(arrow);
5186
5189
  return svg;
5187
5190
  }
5188
- function createSparkVaultMark() {
5191
+ function createSparkVaultMark$1() {
5189
5192
  const mark = div('sv-not-activated-mark');
5190
5193
  const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
5191
5194
  svg.setAttribute('viewBox', '0 0 16 16');
@@ -5211,7 +5214,7 @@ class ProductNotConfiguredView {
5211
5214
  render() {
5212
5215
  const container = div('sv-not-activated-view');
5213
5216
  const eyebrow = div('sv-not-activated-eyebrow');
5214
- eyebrow.appendChild(createSparkVaultMark());
5217
+ eyebrow.appendChild(createSparkVaultMark$1());
5215
5218
  const eyebrowDivider = document.createElement('span');
5216
5219
  eyebrowDivider.className = 'sv-not-activated-eyebrow-divider';
5217
5220
  eyebrowDivider.textContent = '•';
@@ -5221,7 +5224,7 @@ class ProductNotConfiguredView {
5221
5224
  eyebrowLabel.textContent = 'Identity';
5222
5225
  eyebrow.appendChild(eyebrowLabel);
5223
5226
  container.appendChild(eyebrow);
5224
- const badge = createBadge();
5227
+ const badge = createBadge$1();
5225
5228
  container.appendChild(badge);
5226
5229
  const title = document.createElement('h2');
5227
5230
  title.className = 'sv-not-activated-title';
@@ -5253,6 +5256,173 @@ class ProductNotConfiguredView {
5253
5256
  const ctaLabel = document.createElement('span');
5254
5257
  ctaLabel.textContent = 'Configure in SparkVault';
5255
5258
  cta.appendChild(ctaLabel);
5259
+ cta.appendChild(createExternalLinkIcon$1());
5260
+ actions.appendChild(cta);
5261
+ this.dismissButton = document.createElement('button');
5262
+ this.dismissButton.className = 'sv-not-activated-dismiss';
5263
+ this.dismissButton.type = 'button';
5264
+ this.dismissButton.textContent = 'Dismiss';
5265
+ this.dismissButton.addEventListener('click', this.boundHandleClose);
5266
+ actions.appendChild(this.dismissButton);
5267
+ container.appendChild(actions);
5268
+ return container;
5269
+ }
5270
+ destroy() {
5271
+ if (this.dismissButton) {
5272
+ this.dismissButton.removeEventListener('click', this.boundHandleClose);
5273
+ }
5274
+ }
5275
+ }
5276
+
5277
+ /**
5278
+ * Origin Not Allowed View
5279
+ *
5280
+ * Full-dialog terminal screen shown when the embedding site's origin is not in
5281
+ * the account's verified-domains allowlist. The audience is the website owner /
5282
+ * developer — this is a misconfiguration surface, not an end-user error, and it
5283
+ * is permanent (retrying never clears an origin block) — so the dialog drops
5284
+ * customer branding, offers no "Try Again", names the blocked origin, and
5285
+ * points to the place that fixes it. Reuses the SparkVault-notice styling from
5286
+ * the product-not-configured view.
5287
+ */
5288
+ const DOMAINS_URL = 'https://app.sparkvault.com/company/domains';
5289
+ function createBadge() {
5290
+ const badge = div('sv-not-activated-badge');
5291
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
5292
+ svg.setAttribute('viewBox', '0 0 64 64');
5293
+ svg.setAttribute('width', '72');
5294
+ svg.setAttribute('height', '72');
5295
+ svg.setAttribute('fill', 'none');
5296
+ svg.setAttribute('aria-hidden', 'true');
5297
+ svg.classList.add('sv-not-activated-badge-svg');
5298
+ const surface = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
5299
+ surface.setAttribute('cx', '32');
5300
+ surface.setAttribute('cy', '32');
5301
+ surface.setAttribute('r', '29.5');
5302
+ surface.setAttribute('fill', '#F8FAFC');
5303
+ surface.setAttribute('stroke', '#E2E8F0');
5304
+ surface.setAttribute('stroke-width', '1');
5305
+ svg.appendChild(surface);
5306
+ // Globe with a slash — an unrecognized domain.
5307
+ const globe = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
5308
+ globe.setAttribute('cx', '32');
5309
+ globe.setAttribute('cy', '32');
5310
+ globe.setAttribute('r', '13');
5311
+ globe.setAttribute('fill', '#FFFFFF');
5312
+ globe.setAttribute('stroke', '#CBD5E1');
5313
+ globe.setAttribute('stroke-width', '2');
5314
+ svg.appendChild(globe);
5315
+ const meridian = document.createElementNS('http://www.w3.org/2000/svg', 'ellipse');
5316
+ meridian.setAttribute('cx', '32');
5317
+ meridian.setAttribute('cy', '32');
5318
+ meridian.setAttribute('rx', '5.5');
5319
+ meridian.setAttribute('ry', '13');
5320
+ meridian.setAttribute('fill', 'none');
5321
+ meridian.setAttribute('stroke', '#CBD5E1');
5322
+ meridian.setAttribute('stroke-width', '2');
5323
+ svg.appendChild(meridian);
5324
+ const equator = document.createElementNS('http://www.w3.org/2000/svg', 'path');
5325
+ equator.setAttribute('d', 'M19 32H45');
5326
+ equator.setAttribute('stroke', '#CBD5E1');
5327
+ equator.setAttribute('stroke-width', '2');
5328
+ equator.setAttribute('stroke-linecap', 'round');
5329
+ svg.appendChild(equator);
5330
+ const slash = document.createElementNS('http://www.w3.org/2000/svg', 'path');
5331
+ slash.setAttribute('d', 'M23 23L41 41');
5332
+ slash.setAttribute('stroke', '#4F46E5');
5333
+ slash.setAttribute('stroke-width', '2.5');
5334
+ slash.setAttribute('stroke-linecap', 'round');
5335
+ svg.appendChild(slash);
5336
+ badge.appendChild(svg);
5337
+ return badge;
5338
+ }
5339
+ function createExternalLinkIcon() {
5340
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
5341
+ svg.setAttribute('viewBox', '0 0 16 16');
5342
+ svg.setAttribute('width', '14');
5343
+ svg.setAttribute('height', '14');
5344
+ svg.setAttribute('fill', 'none');
5345
+ svg.classList.add('sv-not-activated-cta-icon');
5346
+ const arrow = document.createElementNS('http://www.w3.org/2000/svg', 'path');
5347
+ arrow.setAttribute('d', 'M6 3h7v7M13 3l-8 8');
5348
+ arrow.setAttribute('stroke', 'currentColor');
5349
+ arrow.setAttribute('stroke-width', '2');
5350
+ arrow.setAttribute('stroke-linecap', 'round');
5351
+ arrow.setAttribute('stroke-linejoin', 'round');
5352
+ svg.appendChild(arrow);
5353
+ return svg;
5354
+ }
5355
+ function createSparkVaultMark() {
5356
+ const mark = div('sv-not-activated-mark');
5357
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
5358
+ svg.setAttribute('viewBox', '0 0 16 16');
5359
+ svg.setAttribute('width', '14');
5360
+ svg.setAttribute('height', '14');
5361
+ svg.setAttribute('fill', 'none');
5362
+ const flame = document.createElementNS('http://www.w3.org/2000/svg', 'path');
5363
+ flame.setAttribute('d', 'M8 1.5c.6 1.8 2 2.7 2 4.4 0 .9-.5 1.6-1.2 1.6-.6 0-1-.4-1-.9 0-.4.2-.8.2-1.2 0-.7-.5-1.1-1-1.1-1.4 0-2.5 1.5-2.5 3.4 0 2.4 1.9 4.3 4.5 4.3s4.5-1.9 4.5-4.3c0-3.6-3-4.6-5.5-6.2z');
5364
+ flame.setAttribute('fill', 'currentColor');
5365
+ svg.appendChild(flame);
5366
+ const label = document.createElement('span');
5367
+ label.textContent = 'SparkVault';
5368
+ mark.appendChild(svg);
5369
+ mark.appendChild(label);
5370
+ return mark;
5371
+ }
5372
+ class OriginNotAllowedView {
5373
+ constructor(props) {
5374
+ this.dismissButton = null;
5375
+ this.props = props;
5376
+ this.boundHandleClose = () => this.props.onClose();
5377
+ }
5378
+ render() {
5379
+ const container = div('sv-not-activated-view');
5380
+ const eyebrow = div('sv-not-activated-eyebrow');
5381
+ eyebrow.appendChild(createSparkVaultMark());
5382
+ const eyebrowDivider = document.createElement('span');
5383
+ eyebrowDivider.className = 'sv-not-activated-eyebrow-divider';
5384
+ eyebrowDivider.textContent = '•';
5385
+ eyebrow.appendChild(eyebrowDivider);
5386
+ const eyebrowLabel = document.createElement('span');
5387
+ eyebrowLabel.className = 'sv-not-activated-eyebrow-label';
5388
+ eyebrowLabel.textContent = 'Identity';
5389
+ eyebrow.appendChild(eyebrowLabel);
5390
+ container.appendChild(eyebrow);
5391
+ const badge = createBadge();
5392
+ container.appendChild(badge);
5393
+ const title = document.createElement('h2');
5394
+ title.className = 'sv-not-activated-title';
5395
+ title.id = 'sv-modal-title';
5396
+ title.textContent = 'This domain isn’t allowed';
5397
+ container.appendChild(title);
5398
+ const message = document.createElement('p');
5399
+ message.className = 'sv-not-activated-message';
5400
+ message.textContent =
5401
+ 'Sign-in is blocked because this website’s domain is not on the SparkVault Identity allowlist for this account.';
5402
+ container.appendChild(message);
5403
+ const ownerCard = div('sv-not-activated-owner');
5404
+ const ownerLabel = document.createElement('span');
5405
+ ownerLabel.className = 'sv-not-activated-owner-label';
5406
+ ownerLabel.textContent = 'Are you the site owner?';
5407
+ const ownerHint = document.createElement('span');
5408
+ ownerHint.className = 'sv-not-activated-owner-hint';
5409
+ // textContent (not innerHTML) — the origin is server-reported but we never
5410
+ // trust it into the DOM as markup.
5411
+ ownerHint.textContent = this.props.origin
5412
+ ? `Add ${this.props.origin} to your verified domains in SparkVault, then reload this page.`
5413
+ : 'Add this website’s domain to your verified domains in SparkVault, then reload this page.';
5414
+ ownerCard.appendChild(ownerLabel);
5415
+ ownerCard.appendChild(ownerHint);
5416
+ container.appendChild(ownerCard);
5417
+ const actions = div('sv-not-activated-actions');
5418
+ const cta = document.createElement('a');
5419
+ cta.className = 'sv-btn sv-btn-primary sv-not-activated-cta';
5420
+ cta.href = DOMAINS_URL;
5421
+ cta.target = '_blank';
5422
+ cta.rel = 'noopener noreferrer';
5423
+ const ctaLabel = document.createElement('span');
5424
+ ctaLabel.textContent = 'Manage domains in SparkVault';
5425
+ cta.appendChild(ctaLabel);
5256
5426
  cta.appendChild(createExternalLinkIcon());
5257
5427
  actions.appendChild(cta);
5258
5428
  this.dismissButton = document.createElement('button');
@@ -5397,13 +5567,25 @@ class IdentityRenderer {
5397
5567
  }
5398
5568
  /**
5399
5569
  * Map a config-fetch error to the appropriate terminal view.
5400
- * `product_not_configured` is a misconfiguration (the account has not
5401
- * configured Identity) — show a developer-targeted terminal screen with a
5402
- * link to SparkVault.com instead of the generic service-unavailable view.
5570
+ *
5571
+ * Two failures are permanent developer-misconfigurations, not transient
5572
+ * outages, so they get dedicated terminal screens (no "Try Again" — retrying
5573
+ * can never clear them) instead of the generic service-unavailable view:
5574
+ * - `product_not_configured`: the account has not configured Identity.
5575
+ * - `ORIGIN_NOT_ALLOWED`: this site's domain is not on the account's
5576
+ * allowlist. Surfacing it as "Temporarily Unavailable / try again" sends
5577
+ * the developer chasing a non-existent outage.
5578
+ * Everything else (network errors, 5xx) is genuinely transient.
5403
5579
  */
5404
5580
  viewStateForConfigError(error) {
5405
- if (error instanceof IdentityApiError && error.code === 'product_not_configured') {
5406
- return { view: 'product-not-configured' };
5581
+ if (error instanceof IdentityApiError) {
5582
+ if (error.code === 'product_not_configured') {
5583
+ return { view: 'product-not-configured' };
5584
+ }
5585
+ if (error.code === 'ORIGIN_NOT_ALLOWED') {
5586
+ const origin = typeof error.details?.origin === 'string' ? error.details.origin : undefined;
5587
+ return { view: 'origin-not-allowed', origin };
5588
+ }
5407
5589
  }
5408
5590
  return { view: 'service-unavailable' };
5409
5591
  }
@@ -5493,7 +5675,8 @@ class IdentityRenderer {
5493
5675
  // Full-dialog terminal screens own the entire modal; toggle the container
5494
5676
  // chrome accordingly so the customer header doesn't bleed into a
5495
5677
  // SparkVault-owned message.
5496
- this.container.setMinimalChrome(this.viewState.view === 'product-not-configured');
5678
+ const minimalChromeViews = ['product-not-configured', 'origin-not-allowed'];
5679
+ this.container.setMinimalChrome(minimalChromeViews.includes(this.viewState.view));
5497
5680
  const view = this.createViewForState(this.viewState);
5498
5681
  this.currentView = view;
5499
5682
  clearChildren(body);
@@ -5606,6 +5789,11 @@ class IdentityRenderer {
5606
5789
  return new ProductNotConfiguredView({
5607
5790
  onClose: () => this.handleClose(),
5608
5791
  });
5792
+ case 'origin-not-allowed':
5793
+ return new OriginNotAllowedView({
5794
+ origin: state.origin,
5795
+ onClose: () => this.handleClose(),
5796
+ });
5609
5797
  }
5610
5798
  }
5611
5799
  showIdentityInput(error) {
@@ -6881,8 +7069,8 @@ class IdentityModule {
6881
7069
  * SparkVaultError — no duplicate `httpStatus` field.
6882
7070
  */
6883
7071
  class UploadApiError extends SparkVaultError {
6884
- constructor(message, code, statusCode) {
6885
- super(message, code, statusCode);
7072
+ constructor(message, code, statusCode, details) {
7073
+ super(message, code, statusCode, details);
6886
7074
  this.name = 'UploadApiError';
6887
7075
  Object.setPrototypeOf(this, UploadApiError.prototype);
6888
7076
  }
@@ -6910,13 +7098,26 @@ function isInitiateUploadResponse(data) {
6910
7098
  const d = data;
6911
7099
  return typeof d.forge_url === 'string' && typeof d.ingot_id === 'string';
6912
7100
  }
7101
+ /** tus protocol version used for the resumable upload session. */
7102
+ const TUS_VERSION = '1.0.0';
7103
+ /**
7104
+ * Server-side finalization confirmation poll.
7105
+ *
7106
+ * After the last chunk is PATCHed, Forge advances the session offset (and
7107
+ * flips the ingot to `active`) only once the chunk has actually committed to
7108
+ * S3. We re-read the server's *own persisted* `Upload-Offset` via a TUS HEAD
7109
+ * — independent of the offset the PATCH response claimed — and require it to
7110
+ * reach the declared total before reporting success.
7111
+ */
7112
+ const FINALIZE_POLL_MAX = 10;
7113
+ const FINALIZE_POLL_MS = 1000;
6913
7114
  class UploadApi extends SparkVaultApi {
6914
7115
  constructor(config) {
6915
7116
  super(config.timeout);
6916
7117
  this.config = config;
6917
7118
  }
6918
- makeError(message, code, statusCode) {
6919
- return new UploadApiError(message, code, statusCode);
7119
+ makeError(message, code, statusCode, details) {
7120
+ return new UploadApiError(message, code, statusCode, details);
6920
7121
  }
6921
7122
  /**
6922
7123
  * Issue a request and unwrap the standard `{ data, meta }` envelope.
@@ -6981,6 +7182,104 @@ class UploadApi extends SparkVaultApi {
6981
7182
  ingotId: response.data.ingot_id,
6982
7183
  };
6983
7184
  }
7185
+ /**
7186
+ * Confirm the upload was finalized SERVER-SIDE before reporting success.
7187
+ *
7188
+ * The TUS PATCH loop trusts a server-provided `Upload-Offset`; a buggy or
7189
+ * malicious Forge could return an inflated offset before every chunk was
7190
+ * actually committed and encrypted. This re-reads the server's own
7191
+ * persisted offset via a TUS HEAD (which Forge only advances on a real S3
7192
+ * commit) and requires it to reach the declared total — the web equivalent
7193
+ * of the mobile SDK's `verifyIngotActive` (status === 'active') guarantee.
7194
+ *
7195
+ * Polls because the final chunk's commit and the offset write can lag the
7196
+ * PATCH acknowledgement by a moment. Throws on a non-2xx HEAD, on a session
7197
+ * that never reaches the expected offset within the poll budget, or on a
7198
+ * cancelled session — never reports a half-finished upload as done.
7199
+ *
7200
+ * @param uploadUrl - The TUS session URL (Forge `Location`, ISTK-bound).
7201
+ * @param expectedOffset - The declared total upload size in bytes.
7202
+ */
7203
+ async verifyUploadFinalized(uploadUrl, expectedOffset) {
7204
+ let lastOffset = null;
7205
+ for (let attempt = 1; attempt <= FINALIZE_POLL_MAX; attempt++) {
7206
+ if (this.isAborted()) {
7207
+ throw new UploadApiError('Upload cancelled', 'cancelled', 0);
7208
+ }
7209
+ const offset = await this.headUploadOffset(uploadUrl);
7210
+ lastOffset = offset;
7211
+ if (offset >= expectedOffset) {
7212
+ return;
7213
+ }
7214
+ if (attempt < FINALIZE_POLL_MAX) {
7215
+ await new Promise(resolve => setTimeout(resolve, FINALIZE_POLL_MS));
7216
+ }
7217
+ }
7218
+ throw new UploadApiError('Upload could not be confirmed: the server never finalized the file. ' +
7219
+ `Confirmed ${lastOffset ?? 0} of ${expectedOffset} bytes.`, 'finalization_unconfirmed', 0, { confirmedBytes: lastOffset ?? 0, expectedBytes: expectedOffset });
7220
+ }
7221
+ /**
7222
+ * Read the server's persisted upload offset via a TUS HEAD request.
7223
+ *
7224
+ * Uses raw `fetch` rather than the JSON envelope helper: TUS responses
7225
+ * carry an empty body and surface state in the `Upload-Offset` header.
7226
+ * Honors the session abort signal and request timeout like every other
7227
+ * client call.
7228
+ */
7229
+ async headUploadOffset(uploadUrl) {
7230
+ const closeSignal = this.getAbortSignal();
7231
+ const timeoutController = new AbortController();
7232
+ const timeoutId = setTimeout(() => timeoutController.abort(), this.timeoutMs);
7233
+ // Combine timeout + session-close into one signal. Mirror the base
7234
+ // client's fallback for browsers without AbortSignal.any: link the close
7235
+ // signal into the timeout controller and remove the listener in finally.
7236
+ let combinedSignal;
7237
+ let onCloseAbort = null;
7238
+ if ('any' in AbortSignal) {
7239
+ combinedSignal = AbortSignal.any([timeoutController.signal, closeSignal]);
7240
+ }
7241
+ else {
7242
+ combinedSignal = timeoutController.signal;
7243
+ onCloseAbort = () => timeoutController.abort();
7244
+ closeSignal.addEventListener('abort', onCloseAbort);
7245
+ }
7246
+ try {
7247
+ const response = await fetch(uploadUrl, {
7248
+ method: 'HEAD',
7249
+ headers: { 'Tus-Resumable': TUS_VERSION },
7250
+ signal: combinedSignal,
7251
+ });
7252
+ if (!response.ok) {
7253
+ throw new UploadApiError(`Upload finalization check failed: ${response.status}`, 'finalization_check_failed', response.status);
7254
+ }
7255
+ const header = response.headers.get('Upload-Offset');
7256
+ const offset = header !== null ? parseInt(header, 10) : NaN;
7257
+ if (!Number.isFinite(offset) || offset < 0) {
7258
+ throw new UploadApiError('Upload finalization check returned an invalid offset', 'finalization_check_failed', response.status);
7259
+ }
7260
+ return offset;
7261
+ }
7262
+ catch (error) {
7263
+ if (error instanceof SparkVaultError)
7264
+ throw error;
7265
+ if (error != null && typeof error === 'object' && 'name' in error && error.name === 'AbortError') {
7266
+ if (this.isAborted()) {
7267
+ throw new UploadApiError('Upload cancelled', 'cancelled', 0);
7268
+ }
7269
+ throw new UploadApiError(`Upload finalization check timed out after ${this.timeoutMs}ms`, 'timeout', 0);
7270
+ }
7271
+ if (error instanceof TypeError) {
7272
+ throw new UploadApiError('Unable to confirm upload. Please check your connection and try again.', 'network_error', 0);
7273
+ }
7274
+ throw new UploadApiError(error instanceof Error ? error.message : 'An unexpected error occurred', 'unknown_error', 0);
7275
+ }
7276
+ finally {
7277
+ clearTimeout(timeoutId);
7278
+ if (onCloseAbort) {
7279
+ closeSignal.removeEventListener('abort', onCloseAbort);
7280
+ }
7281
+ }
7282
+ }
6984
7283
  }
6985
7284
 
6986
7285
  /**
@@ -9403,7 +9702,13 @@ class UploadRenderer {
9403
9702
  bytesUploaded: 0,
9404
9703
  });
9405
9704
  // Upload file using tus (resumable upload)
9406
- await this.uploadWithTus(file, forgeUrl, ingotId, requestId);
9705
+ const uploadUrl = await this.uploadWithTus(file, forgeUrl, ingotId, requestId);
9706
+ // Confirm the server actually finalized the upload before celebrating.
9707
+ // The TUS loop trusts a server-provided offset; this re-reads the
9708
+ // server's own persisted offset and requires it to reach the file size,
9709
+ // mirroring the mobile SDK's active-status check. A non-finalized
9710
+ // upload throws here and never reaches the success ceremony.
9711
+ await this.api.verifyUploadFinalized(uploadUrl, file.size);
9407
9712
  // Run ceremony animation
9408
9713
  await this.runCeremony(file, ingotId, requestId);
9409
9714
  // Complete
@@ -9484,6 +9789,7 @@ class UploadRenderer {
9484
9789
  const newOffset = await this.uploadChunkWithProgress(uploadUrl, chunk, chunkStart, totalSize, TUS_VERSION, file, ingotId, requestId);
9485
9790
  offset = newOffset;
9486
9791
  }
9792
+ return uploadUrl;
9487
9793
  }
9488
9794
  /**
9489
9795
  * Upload a single chunk using XMLHttpRequest for progress tracking.
@@ -9527,6 +9833,14 @@ class UploadRenderer {
9527
9833
  // Get new offset from server response
9528
9834
  const newOffsetHeader = xhr.getResponseHeader('Upload-Offset');
9529
9835
  const newOffset = newOffsetHeader ? parseInt(newOffsetHeader, 10) : chunkStart + chunk.size;
9836
+ // Defense-in-depth: the server must never report more bytes accepted
9837
+ // than the file contains. A `newOffset > totalSize` is a malformed or
9838
+ // inflated response — reject it rather than letting an over-reported
9839
+ // offset short-circuit the upload loop and skip real chunks.
9840
+ if (!Number.isFinite(newOffset) || newOffset < chunkStart || newOffset > totalSize) {
9841
+ reject(new Error(`Server returned invalid upload offset (${newOffset})`));
9842
+ return;
9843
+ }
9530
9844
  resolve(newOffset);
9531
9845
  }
9532
9846
  else {