@sparkvault/sdk-js 14.1.0 → 14.2.0

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.
package/README.md CHANGED
@@ -268,6 +268,16 @@ completion remains restricted to desk portal origins. See the
268
268
  [website integration guide](https://github.com/Spark-Vault/platform/blob/main/docs/HELP_DESK_WEBSITE_INTEGRATION.md)
269
269
  and [company-session contract](https://github.com/Spark-Vault/platform/blob/main/docs/HELP_DESK_IDENTITY_HANDOFF.md).
270
270
 
271
+ ## Vault resealing
272
+
273
+ `vaults.unseal(vaultId, key)` follows the vault's reseal settings: by default, one hour of inactivity with a maximum of 24 hours from unseal. An optional third argument, `{ ttlSeconds: 60 }`, requests a shorter maximum for that session. A company administrator can save the two vault settings with `vaults.updateResealSettings(vaultId, { idleSeconds: 900, maxSeconds: 43200 })`. Null values inherit system defaults; zero idle seconds disables activity extensions. Settings changes apply on the next unseal.
274
+
275
+ An explicit `vaults.extendSession(vaultId, vat)` extends a live session's inactivity deadline without a key or a new VAT. It stays within the original maximum; a fixed-duration session, expired session, or one already extended to that maximum requires another unseal. This is an action the person requests, never an automatic keep-alive.
276
+
277
+ Hosts displaying a session countdown can pass `onVaultSessionTiming` to SDK initialization. Its `{ vat, expiresAt, hardExpiresAt, remainingSeconds, hardRemainingSeconds, requestStartedAtMs }` argument carries server-confirmed deadlines for the exact VAT the request presented. Apply it only to that held session, ignore older deadlines, and anchor remaining seconds to `requestStartedAtMs` for a conservative device-local countdown. Upload/download authorization and supported file changes can extend inactivity; navigation and listings do not. Forge transfers keep their existing independent lifetimes when the vault reseals.
278
+
279
+ For automatic display or prefetch, pass `{ countAsActivity: false }` as the third argument to `ingots.download` or `ingots.createDownloadLink`. This suppresses inactivity renewal and stays in effect when a download retries with a fresh link. Ordinary downloads omit this option.
280
+
271
281
  ## Content Security Policy (CSP)
272
282
 
273
283
  A page with a Content Security Policy adds these sources to its directives:
@@ -17,6 +17,8 @@ export interface RawRequestOptions {
17
17
  method: string;
18
18
  body?: string;
19
19
  headers?: Record<string, string>;
20
+ /** Observe a successful response before its body is consumed. */
21
+ onResponse?: (response: Response) => void;
20
22
  }
21
23
  export interface RawResponse {
22
24
  data: unknown;
package/dist/config.d.ts CHANGED
@@ -1,6 +1,21 @@
1
1
  /**
2
2
  * SparkVault SDK Configuration
3
3
  */
4
+ /** Server-confirmed timing for the exact vault session a request presented. */
5
+ export interface VaultSessionTiming {
6
+ vat: string;
7
+ /** Current reseal deadline in server Unix seconds. */
8
+ expiresAt: number;
9
+ /** Fixed maximum deadline from the original unseal, in server Unix seconds. */
10
+ hardExpiresAt: number;
11
+ /** Seconds remaining on the server, suitable for a device-local countdown. */
12
+ remainingSeconds: number;
13
+ hardRemainingSeconds: number;
14
+ /** Zero for a fixed session; absent when talking to an older Core version. */
15
+ idleTimeoutSeconds?: number;
16
+ /** Device clock before the Core request, for conservative local countdowns. */
17
+ requestStartedAtMs?: number;
18
+ }
4
19
  export interface SparkVaultConfig {
5
20
  /** Account ID for Identity operations */
6
21
  accountId: string;
@@ -14,6 +29,8 @@ export interface SparkVaultConfig {
14
29
  accessToken?: string;
15
30
  /** Dynamic SparkVault Core access token provider for authenticated API calls. */
16
31
  getAccessToken?: () => string | null | Promise<string | null>;
32
+ /** Observe server-confirmed vault-session timing after an authorized Core response. */
33
+ onVaultSessionTiming?: (timing: VaultSessionTiming) => void;
17
34
  /** Optional API key for server-side SDK use. */
18
35
  apiKey?: string;
19
36
  /**
@@ -49,6 +66,7 @@ export interface ResolvedConfig {
49
66
  portalBaseUrl: string;
50
67
  accessToken?: string;
51
68
  getAccessToken?: () => string | null | Promise<string | null>;
69
+ onVaultSessionTiming?: (timing: VaultSessionTiming) => void;
52
70
  apiKey?: string;
53
71
  clientId?: string;
54
72
  preloadConfig: boolean;
package/dist/errors.d.ts CHANGED
@@ -6,11 +6,11 @@ export declare class SparkVaultError extends Error {
6
6
  readonly statusCode?: number;
7
7
  readonly details?: Record<string, unknown>;
8
8
  /**
9
- * The answer's `Retry-After`, in ms from the answer, read as the platform's
10
- * transfer policy reads it (RFC 9110 §10.2.3: delay-seconds or an
9
+ * The answer's `Retry-After`, in ms from the answer, read by the platform's
10
+ * one parser (`parseRetryAfterMs`; RFC 9110 §10.2.3: delay-seconds or an
11
11
  * HTTP-date): the earliest a next attempt can expect another answer, which
12
12
  * every retry the SDK makes waits out as a floor. Null when the answer
13
- * carried none the policy could read, or no answer arrived.
13
+ * carried none the parser could read, or no answer arrived.
14
14
  */
15
15
  readonly retryAfterMs: number | null;
16
16
  /**
package/dist/index.cjs CHANGED
@@ -191,6 +191,12 @@ const UPLOAD_REFUSAL_HEADER = 'X-Upload-Refusal';
191
191
  * (forge-tus), the browser SDK (sdk-js bundles this module) and the mobile SDK
192
192
  * (sdk-mobile carries a generated copy) read every answer the same way.
193
193
  *
194
+ * It also holds the one reading of `Retry-After` every JavaScript client
195
+ * applies to any answer, a transfer's or not (parseRetryAfterMs), and the one
196
+ * wait a thumbnail fetch gives a busy Forge before its single retry
197
+ * (thumbnailBusyWaitMs), so no client keeps a parser of its own that drifts
198
+ * in what it accepts.
199
+ *
194
200
  * It encodes what Google Drive, Google Cloud Storage, OneDrive, Dropbox and
195
201
  * AWS document for resumable transfers:
196
202
  * - only a request that got no answer, 408, 425, 429 or a 5xx is retried;
@@ -311,6 +317,8 @@ const CORE_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
311
317
 
312
318
 
313
319
  const UPLOAD_OFFSET_HEADER = 'Upload-Offset';
320
+
321
+ /** The header every client reads an answer's wait from (parseRetryAfterMs). */
314
322
  const RETRY_AFTER_HEADER = 'Retry-After';
315
323
 
316
324
  /**
@@ -395,7 +403,7 @@ function classifyTransferResponse({ status, headers = null, details = null, rece
395
403
  const coreCode = mayNameCoreCode(status, offset)
396
404
  ? coreCodeIn(details) ?? coreCodeOf(header(UPLOAD_REFUSAL_HEADER))
397
405
  : null;
398
- const retryAfterMs = readRetryAfterMs(header(RETRY_AFTER_HEADER), now);
406
+ const retryAfterMs = parseRetryAfterMs(header(RETRY_AFTER_HEADER), now);
399
407
  return {
400
408
  verdict: verdictFor(status, { offset, coreCode, deferral: receipt && retryAfterMs !== null }),
401
409
  retryAfterMs,
@@ -454,14 +462,26 @@ function readCount(value) {
454
462
  return Number.isSafeInteger(count) ? count : null;
455
463
  }
456
464
 
457
- /** RFC 9110 §10.2.3: `Retry-After` is delay-seconds or an HTTP-date. */
458
- function readRetryAfterMs(value, now) {
459
- const seconds = readCount(value);
465
+ /**
466
+ * An answer's `Retry-After` (RFC 9110 §10.2.3: delay-seconds or an
467
+ * HTTP-date), as every JavaScript client reads it from any answer: whole
468
+ * seconds, or the time until the date, an HTTP-date already past reading as 0.
469
+ *
470
+ * @param {unknown} headerValue - The header as received (null when absent)
471
+ * @param {number} [now] - When the answer arrived (epoch ms), which an
472
+ * HTTP-date counts from and an obsolete two-digit year is placed by
473
+ * @returns {number|null} ms from the answer, or null when absent or
474
+ * unreadable: not text, a delay other than whole seconds in decimal digits,
475
+ * words, a date that names no real moment, or seconds too large to count
476
+ * in ms
477
+ */
478
+ function parseRetryAfterMs(headerValue, now = Date.now()) {
479
+ const seconds = readCount(headerValue);
460
480
  if (seconds !== null) {
461
481
  const ms = seconds * 1000;
462
482
  return Number.isSafeInteger(ms) ? ms : null;
463
483
  }
464
- const at = typeof value === 'string' ? parseHttpDate(value.trim(), now) : null;
484
+ const at = typeof headerValue === 'string' ? parseHttpDate(headerValue.trim(), now) : null;
465
485
  return at === null ? null : Math.max(0, at - now);
466
486
  }
467
487
 
@@ -942,10 +962,8 @@ function parseJson(text) {
942
962
  * `{ message }`) or with no JSON at all, so each field falls back to its flat
943
963
  * form and then to a default. The body is read leniently: a failure's status
944
964
  * and class never depend on the body being JSON. The `Retry-After` is read by
945
- * the transfer policy's one parser (`@sparkvault/app-sdk/transfer-retry`),
946
- * never a second one: the policy reads a whole answer at once, and only its
947
- * header reading is kept here, because an API answer is the service's
948
- * verdict, never a transfer answer the policy's verdict applies to.
965
+ * the platform's one parser (`parseRetryAfterMs`,
966
+ * `@sparkvault/app-sdk/transfer-retry`), never a second one.
949
967
  */
950
968
  function failureOf(status, body, header) {
951
969
  const root = recordField(body) ?? {};
@@ -955,7 +973,7 @@ function failureOf(status, body, header) {
955
973
  message: stringField(nested?.message) ?? stringField(root.message) ?? stringField(root.error) ?? 'Request failed',
956
974
  code: stringField(nested?.code) ?? stringField(root.code) ?? 'api_error',
957
975
  details: recordField(nested?.details) ?? recordField(root.details),
958
- retryAfterMs: classifyTransferResponse({ status, headers: header }).retryAfterMs,
976
+ retryAfterMs: parseRetryAfterMs(header(RETRY_AFTER_HEADER)),
959
977
  };
960
978
  }
961
979
  /**
@@ -1197,6 +1215,7 @@ function resolveConfig(config) {
1197
1215
  portalBaseUrl: normalizeBaseUrl(config.portalBaseUrl ?? PORTAL_URL),
1198
1216
  accessToken: config.accessToken,
1199
1217
  getAccessToken: config.getAccessToken,
1218
+ onVaultSessionTiming: config.onVaultSessionTiming,
1200
1219
  apiKey: config.apiKey,
1201
1220
  clientId: config.clientId,
1202
1221
  // Preloading warms a dialog that only a browser can open; default it off
@@ -1412,6 +1431,7 @@ class SparkVaultApi {
1412
1431
  const { status, message, code, details, retryAfterMs } = await readApiFailure(response);
1413
1432
  throw this.makeError(message, code, status, details, retryAfterMs);
1414
1433
  }
1434
+ options.onResponse?.(response);
1415
1435
  return { data: await readJsonBody(response), status: response.status };
1416
1436
  });
1417
1437
  }
@@ -1500,6 +1520,47 @@ function queryString(params) {
1500
1520
  return query ? `?${query}` : '';
1501
1521
  }
1502
1522
 
1523
+ /** Vault settings for resealing, and the server's timing of a held session. */
1524
+ const VAULT_RESEAL_LIMITS = Object.freeze({ minSeconds: 60, maxSeconds: 86400 });
1525
+
1526
+ /** Timing is bound by clients to the VAT on the request, never a returned bearer. */
1527
+ const VAULT_SESSION_HEADERS = Object.freeze({
1528
+ expiresAt: 'X-Vault-Session-Expires-At',
1529
+ hardExpiresAt: 'X-Vault-Session-Hard-Expires-At',
1530
+ remainingSeconds: 'X-Vault-Session-Remaining-Seconds',
1531
+ hardRemainingSeconds: 'X-Vault-Session-Hard-Remaining-Seconds',
1532
+ idleTimeoutSeconds: 'X-Vault-Session-Idle-Timeout-Seconds'
1533
+ });
1534
+
1535
+ /** Read Fetch Headers or ordinary response headers; old servers return no timing. */
1536
+ function readVaultSessionTiming(headers) {
1537
+ if (!headers) return null;
1538
+ const timing = {};
1539
+ for (const [field, name] of Object.entries(VAULT_SESSION_HEADERS)) {
1540
+ const raw = typeof headers.get === 'function'
1541
+ ? headers.get(name)
1542
+ : headers[name.toLowerCase()] ?? headers[name];
1543
+ if (raw === null || raw === undefined || raw === '') {
1544
+ if (field === 'idleTimeoutSeconds') continue;
1545
+ return null;
1546
+ }
1547
+ const value = Number(raw);
1548
+ if (!Number.isSafeInteger(value) || value < 0) return null;
1549
+ timing[field] = value;
1550
+ }
1551
+ if (timing.expiresAt > timing.hardExpiresAt || timing.remainingSeconds > timing.hardRemainingSeconds) return null;
1552
+ return timing;
1553
+ }
1554
+
1555
+ /** Read only server-confirmed session deadlines, bound to the request's VAT. */
1556
+ function publishVaultSessionTiming(config, vat, response, requestStartedAtMs) {
1557
+ if (!vat || !response.ok || !config.onVaultSessionTiming)
1558
+ return;
1559
+ const timing = readVaultSessionTiming(response.headers);
1560
+ if (timing)
1561
+ config.onVaultSessionTiming({ vat, ...timing, requestStartedAtMs });
1562
+ }
1563
+
1503
1564
  /**
1504
1565
  * SparkVault SDK HTTP Client
1505
1566
  */
@@ -1539,6 +1600,7 @@ class HttpClient {
1539
1600
  const { method = 'GET', headers = {}, body, query, vat, timeout = this.config.timeout, credentials, } = options;
1540
1601
  const url = `${this.config.apiBaseUrl}${path}${queryString(query)}`;
1541
1602
  const requestHeaders = await this.getDefaultHeaders(headers, body !== undefined, vat);
1603
+ const requestStartedAtMs = Date.now();
1542
1604
  return exchange(url, { method, headers: requestHeaders, body: body ? JSON.stringify(body) : undefined,
1543
1605
  ...(credentials !== undefined ? { credentials } : {}) }, {
1544
1606
  timeoutMs: timeout,
@@ -1546,6 +1608,8 @@ class HttpClient {
1546
1608
  if (!response.ok) {
1547
1609
  throw this.createErrorFromResponse(await readApiFailure(response));
1548
1610
  }
1611
+ // Read timing before the body: a successful mutation may answer 204.
1612
+ publishVaultSessionTiming(this.config, new Headers(requestHeaders).get('X-Vault-Access-Token') ?? undefined, response, requestStartedAtMs);
1549
1613
  return { data: this.unwrapApiResponse(await this.parseResponse(response)) };
1550
1614
  },
1551
1615
  fail: (failure, cause) => {
@@ -13363,7 +13427,11 @@ class UploadApi extends SparkVaultApi {
13363
13427
  * envelope.
13364
13428
  */
13365
13429
  async request(path, options) {
13366
- const { data: raw, status } = await this.rawRequest(`${this.config.apiBaseUrl}${path}`, options);
13430
+ const requestStartedAtMs = Date.now();
13431
+ const { data: raw, status } = await this.rawRequest(`${this.config.apiBaseUrl}${path}`, {
13432
+ ...options,
13433
+ onResponse: (response) => publishVaultSessionTiming(this.config, new Headers(options.headers).get('X-Vault-Access-Token') ?? undefined, response, requestStartedAtMs),
13434
+ });
13367
13435
  const envelope = typeof raw === 'object' && raw !== null ? raw : null;
13368
13436
  const data = envelope && 'data' in envelope ? envelope.data : raw;
13369
13437
  return { data, status, requestId: envelope?.meta?.request_id };
@@ -14460,6 +14528,8 @@ class IngotsModule {
14460
14528
  * when you want the URL itself; otherwise prefer {@link download}. The link
14461
14529
  * is single-use: Forge claims it the moment a request arrives, so a retry or
14462
14530
  * a resume needs a link of its own (`fetchDownload`'s `remint`).
14531
+ * Automatic display/prefetch should pass `{ countAsActivity: false }` so
14532
+ * loading visible content does not extend the vault's inactivity deadline.
14463
14533
  *
14464
14534
  * @example
14465
14535
  * const link = await sv.ingots.createDownloadLink(unsealed, 'ing_abc');
@@ -14467,10 +14537,10 @@ class IngotsModule {
14467
14537
  * remint: async () => (await sv.ingots.createDownloadLink(unsealed, 'ing_abc')).downloadUrl,
14468
14538
  * });
14469
14539
  */
14470
- async createDownloadLink(vault, ingotId) {
14540
+ async createDownloadLink(vault, ingotId, options = {}) {
14471
14541
  const vaultId = requireVaultId(vault);
14472
14542
  const id = requireResourceId(ingotId, 'ingotId');
14473
- const response = await this.http.post(apiPath `/v1/vaults/${vaultId}/ingots/${id}/download`, undefined, { vat: vault.vatToken });
14543
+ const response = await this.http.post(apiPath `/v1/vaults/${vaultId}/ingots/${id}/download`, options.countAsActivity === undefined ? undefined : { count_as_activity: options.countAsActivity }, { vat: vault.vatToken });
14474
14544
  if (!response.data.download_url) {
14475
14545
  throw new ValidationError('Download endpoint did not return a download URL');
14476
14546
  }
@@ -14510,8 +14580,8 @@ class IngotsModule {
14510
14580
  * link.download = ingot.downloadFilename;
14511
14581
  * link.click();
14512
14582
  */
14513
- async download(vault, ingotId) {
14514
- const mint = async () => (await this.createDownloadLink(vault, ingotId)).downloadUrl;
14583
+ async download(vault, ingotId, options = {}) {
14584
+ const mint = async () => (await this.createDownloadLink(vault, ingotId, options)).downloadUrl;
14515
14585
  return (await fetchMintedDownload(mint, { isAllowedHost: this.allowsTransferHost })).blob;
14516
14586
  }
14517
14587
  /**
@@ -20252,12 +20322,16 @@ class VaultsModule {
20252
20322
  * const delegated = await sv.vaults.unseal('vlt_abc', 'dvak_...');
20253
20323
  * console.log('Token:', unsealed.vatToken);
20254
20324
  */
20255
- async unseal(vaultId, key) {
20325
+ async unseal(vaultId, key, options = {}) {
20256
20326
  const id = requireResourceId(vaultId, 'vaultId');
20257
20327
  if (typeof key !== 'string' || !key.trim()) {
20258
20328
  throw new ValidationError('A VMK or DVAK token is required');
20259
20329
  }
20260
- const response = await this.http.post(apiPath `/v1/vaults/${id}/unseal`, unsealRequestBody(key));
20330
+ if (options.ttlSeconds !== undefined &&
20331
+ (!Number.isSafeInteger(options.ttlSeconds) || options.ttlSeconds < 1 || options.ttlSeconds > VAULT_RESEAL_LIMITS.maxSeconds)) {
20332
+ throw new ValidationError(`ttlSeconds must be a whole number from 1 to ${VAULT_RESEAL_LIMITS.maxSeconds}`);
20333
+ }
20334
+ const response = await this.http.post(apiPath `/v1/vaults/${id}/unseal`, unsealRequestBody(key, options.ttlSeconds));
20261
20335
  if (!response.data.vat) {
20262
20336
  throw new ValidationError('Unseal response did not include a vault access token');
20263
20337
  }
@@ -20267,6 +20341,30 @@ class VaultsModule {
20267
20341
  issuedAt: response.data.issued_at,
20268
20342
  expiresAt: response.data.expires_at,
20269
20343
  ttlSeconds: response.data.ttl_seconds,
20344
+ ...(response.data.hard_expires_at === undefined ? {} : { hardExpiresAt: response.data.hard_expires_at }),
20345
+ ...(response.data.idle_timeout_seconds === undefined ? {} : { idleTimeoutSeconds: response.data.idle_timeout_seconds }),
20346
+ };
20347
+ }
20348
+ /**
20349
+ * Explicitly extend this live session's inactivity window, up to the
20350
+ * original unseal's fixed maximum. No key is needed and no new VAT is minted.
20351
+ * A fixed-duration session or one at its maximum is refused by Core; another
20352
+ * unseal is required. The normal timing observer receives the new deadline.
20353
+ */
20354
+ async extendSession(vaultId, vat) {
20355
+ const id = requireResourceId(vaultId, 'vaultId');
20356
+ if (typeof vat !== 'string' || !vat.startsWith('vat_')) {
20357
+ throw new ValidationError('A Vault Access Token is required to extend the session');
20358
+ }
20359
+ const response = await this.http.post(apiPath `/v1/vaults/${id}/session/extend`, undefined, { vat });
20360
+ const value = response.data;
20361
+ return {
20362
+ vaultId: value.vault_id,
20363
+ expiresAt: value.expires_at,
20364
+ hardExpiresAt: value.hard_expires_at,
20365
+ idleTimeoutSeconds: value.idle_timeout_seconds,
20366
+ ttlSeconds: value.ttl_seconds,
20367
+ canExtend: value.can_extend,
20270
20368
  };
20271
20369
  }
20272
20370
  /**
@@ -20309,6 +20407,25 @@ class VaultsModule {
20309
20407
  const response = await this.http.get(apiPath `/v1/vaults/${id}`);
20310
20408
  return mapVaultDetail(response.data);
20311
20409
  }
20410
+ /**
20411
+ * Set when this vault reseals after inactivity and after an unseal.
20412
+ * Company administrators only. Changes apply on the next unseal.
20413
+ * Null values inherit system defaults; zero idle seconds disables extensions.
20414
+ */
20415
+ async updateResealSettings(vaultId, settings) {
20416
+ const id = requireResourceId(vaultId, 'vaultId');
20417
+ const response = await this.http.put(apiPath `/v1/vaults/${id}/reseal-settings`, {
20418
+ reseal_idle_seconds: settings.idleSeconds,
20419
+ reseal_max_seconds: settings.maxSeconds,
20420
+ });
20421
+ const value = response.data;
20422
+ return {
20423
+ vaultId: value.vault_id,
20424
+ idleSeconds: value.reseal_idle_seconds,
20425
+ maxSeconds: value.reseal_max_seconds,
20426
+ defaults: { idleSeconds: value.reseal_defaults.idle_seconds, maxSeconds: value.reseal_defaults.max_seconds },
20427
+ };
20428
+ }
20312
20429
  /**
20313
20430
  * Rename a vault.
20314
20431
  *
@@ -20583,6 +20700,11 @@ function mapVaultDetail(v) {
20583
20700
  createdAt: v.created_at,
20584
20701
  lastUnsealedAt: v.last_unsealed_at ?? null,
20585
20702
  unsealCount: v.unseal_count ?? 0,
20703
+ ...(v.reseal_idle_seconds === undefined ? {} : { resealIdleSeconds: v.reseal_idle_seconds }),
20704
+ ...(v.reseal_max_seconds === undefined ? {} : { resealMaxSeconds: v.reseal_max_seconds }),
20705
+ ...(v.reseal_defaults === undefined ? {} : {
20706
+ resealDefaults: { idleSeconds: v.reseal_defaults.idle_seconds, maxSeconds: v.reseal_defaults.max_seconds },
20707
+ }),
20586
20708
  deletionNoticeUnreached: v.deletion_notice_unreached && v.deletion_notice_unreached.map(mapUnreachedAdmin),
20587
20709
  };
20588
20710
  }
@@ -21346,7 +21468,7 @@ class SparkVault {
21346
21468
  }
21347
21469
  /** Get the SDK version */
21348
21470
  static get version() {
21349
- return '14.1.0';
21471
+ return '14.2.0';
21350
21472
  }
21351
21473
  }
21352
21474
  if (typeof window !== 'undefined') {