@sparkvault/sdk-js 14.1.1 → 14.2.1

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/index.cjs CHANGED
@@ -1215,6 +1215,7 @@ function resolveConfig(config) {
1215
1215
  portalBaseUrl: normalizeBaseUrl(config.portalBaseUrl ?? PORTAL_URL),
1216
1216
  accessToken: config.accessToken,
1217
1217
  getAccessToken: config.getAccessToken,
1218
+ onVaultSessionTiming: config.onVaultSessionTiming,
1218
1219
  apiKey: config.apiKey,
1219
1220
  clientId: config.clientId,
1220
1221
  // Preloading warms a dialog that only a browser can open; default it off
@@ -1430,6 +1431,7 @@ class SparkVaultApi {
1430
1431
  const { status, message, code, details, retryAfterMs } = await readApiFailure(response);
1431
1432
  throw this.makeError(message, code, status, details, retryAfterMs);
1432
1433
  }
1434
+ options.onResponse?.(response);
1433
1435
  return { data: await readJsonBody(response), status: response.status };
1434
1436
  });
1435
1437
  }
@@ -1518,6 +1520,47 @@ function queryString(params) {
1518
1520
  return query ? `?${query}` : '';
1519
1521
  }
1520
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
+
1521
1564
  /**
1522
1565
  * SparkVault SDK HTTP Client
1523
1566
  */
@@ -1557,6 +1600,7 @@ class HttpClient {
1557
1600
  const { method = 'GET', headers = {}, body, query, vat, timeout = this.config.timeout, credentials, } = options;
1558
1601
  const url = `${this.config.apiBaseUrl}${path}${queryString(query)}`;
1559
1602
  const requestHeaders = await this.getDefaultHeaders(headers, body !== undefined, vat);
1603
+ const requestStartedAtMs = Date.now();
1560
1604
  return exchange(url, { method, headers: requestHeaders, body: body ? JSON.stringify(body) : undefined,
1561
1605
  ...(credentials !== undefined ? { credentials } : {}) }, {
1562
1606
  timeoutMs: timeout,
@@ -1564,6 +1608,8 @@ class HttpClient {
1564
1608
  if (!response.ok) {
1565
1609
  throw this.createErrorFromResponse(await readApiFailure(response));
1566
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);
1567
1613
  return { data: this.unwrapApiResponse(await this.parseResponse(response)) };
1568
1614
  },
1569
1615
  fail: (failure, cause) => {
@@ -13381,7 +13427,11 @@ class UploadApi extends SparkVaultApi {
13381
13427
  * envelope.
13382
13428
  */
13383
13429
  async request(path, options) {
13384
- 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
+ });
13385
13435
  const envelope = typeof raw === 'object' && raw !== null ? raw : null;
13386
13436
  const data = envelope && 'data' in envelope ? envelope.data : raw;
13387
13437
  return { data, status, requestId: envelope?.meta?.request_id };
@@ -14478,6 +14528,8 @@ class IngotsModule {
14478
14528
  * when you want the URL itself; otherwise prefer {@link download}. The link
14479
14529
  * is single-use: Forge claims it the moment a request arrives, so a retry or
14480
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.
14481
14533
  *
14482
14534
  * @example
14483
14535
  * const link = await sv.ingots.createDownloadLink(unsealed, 'ing_abc');
@@ -14485,10 +14537,10 @@ class IngotsModule {
14485
14537
  * remint: async () => (await sv.ingots.createDownloadLink(unsealed, 'ing_abc')).downloadUrl,
14486
14538
  * });
14487
14539
  */
14488
- async createDownloadLink(vault, ingotId) {
14540
+ async createDownloadLink(vault, ingotId, options = {}) {
14489
14541
  const vaultId = requireVaultId(vault);
14490
14542
  const id = requireResourceId(ingotId, 'ingotId');
14491
- 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 });
14492
14544
  if (!response.data.download_url) {
14493
14545
  throw new ValidationError('Download endpoint did not return a download URL');
14494
14546
  }
@@ -14528,8 +14580,8 @@ class IngotsModule {
14528
14580
  * link.download = ingot.downloadFilename;
14529
14581
  * link.click();
14530
14582
  */
14531
- async download(vault, ingotId) {
14532
- 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;
14533
14585
  return (await fetchMintedDownload(mint, { isAllowedHost: this.allowsTransferHost })).blob;
14534
14586
  }
14535
14587
  /**
@@ -16444,14 +16496,17 @@ const BRACKET_PAIRS =
16444
16496
  * right-to-left letter or mark, or an Arabic digit, between Latin words
16445
16497
  * reverses their order: "Vault", U+05BE HEBREW PUNCTUATION MAQAF, "Spark" is
16446
16498
  * laid out in a right-to-left paragraph as "Spark", the maqaf, "Vault".
16447
- * An explicit direction control (holdsDirectionControl) sets the direction of
16448
- * the text after it beyond what this lays out, so a caller that judges what a
16449
- * reader sees refuses it as well, as isReservedDisplayText, for any text an
16450
- * organization shows under its name, and isReservedOrganizationName do. Both
16451
- * also judge a text at every cut of it as stored, each cut read in this way,
16452
- * since the platform shows a text cut to fit.
16499
+ * An explicit direction control (holdsDirectionControl, ./display-text.js)
16500
+ * sets the direction of the text after it beyond what this lays out, so a
16501
+ * caller that judges what a reader sees refuses it as well, as
16502
+ * isReservedDisplayText, for any text an organization shows under its name,
16503
+ * and isReservedOrganizationName do. Both also judge a text at every cut of it
16504
+ * as stored, each cut read in this way, since the platform shows a text cut to
16505
+ * fit. The implicit marks are no such control: each is a strong character of
16506
+ * its direction, laid out as a letter of that direction is.
16453
16507
  *
16454
- * BROWSER-SAFE: imports only ./organization-name-unicode.js, and needs
16508
+ * BROWSER-SAFE: imports only ./display-text.js and
16509
+ * ./organization-name-unicode.js, neither of which imports anything, and needs
16455
16510
  * String.prototype.isWellFormed and toWellFormed (ES2024: Chrome 111,
16456
16511
  * Firefox 119, Safari 16.4).
16457
16512
  */
@@ -20270,12 +20325,16 @@ class VaultsModule {
20270
20325
  * const delegated = await sv.vaults.unseal('vlt_abc', 'dvak_...');
20271
20326
  * console.log('Token:', unsealed.vatToken);
20272
20327
  */
20273
- async unseal(vaultId, key) {
20328
+ async unseal(vaultId, key, options = {}) {
20274
20329
  const id = requireResourceId(vaultId, 'vaultId');
20275
20330
  if (typeof key !== 'string' || !key.trim()) {
20276
20331
  throw new ValidationError('A VMK or DVAK token is required');
20277
20332
  }
20278
- const response = await this.http.post(apiPath `/v1/vaults/${id}/unseal`, unsealRequestBody(key));
20333
+ if (options.ttlSeconds !== undefined &&
20334
+ (!Number.isSafeInteger(options.ttlSeconds) || options.ttlSeconds < 1 || options.ttlSeconds > VAULT_RESEAL_LIMITS.maxSeconds)) {
20335
+ throw new ValidationError(`ttlSeconds must be a whole number from 1 to ${VAULT_RESEAL_LIMITS.maxSeconds}`);
20336
+ }
20337
+ const response = await this.http.post(apiPath `/v1/vaults/${id}/unseal`, unsealRequestBody(key, options.ttlSeconds));
20279
20338
  if (!response.data.vat) {
20280
20339
  throw new ValidationError('Unseal response did not include a vault access token');
20281
20340
  }
@@ -20285,6 +20344,30 @@ class VaultsModule {
20285
20344
  issuedAt: response.data.issued_at,
20286
20345
  expiresAt: response.data.expires_at,
20287
20346
  ttlSeconds: response.data.ttl_seconds,
20347
+ ...(response.data.hard_expires_at === undefined ? {} : { hardExpiresAt: response.data.hard_expires_at }),
20348
+ ...(response.data.idle_timeout_seconds === undefined ? {} : { idleTimeoutSeconds: response.data.idle_timeout_seconds }),
20349
+ };
20350
+ }
20351
+ /**
20352
+ * Explicitly extend this live session's inactivity window, up to the
20353
+ * original unseal's fixed maximum. No key is needed and no new VAT is minted.
20354
+ * A fixed-duration session or one at its maximum is refused by Core; another
20355
+ * unseal is required. The normal timing observer receives the new deadline.
20356
+ */
20357
+ async extendSession(vaultId, vat) {
20358
+ const id = requireResourceId(vaultId, 'vaultId');
20359
+ if (typeof vat !== 'string' || !vat.startsWith('vat_')) {
20360
+ throw new ValidationError('A Vault Access Token is required to extend the session');
20361
+ }
20362
+ const response = await this.http.post(apiPath `/v1/vaults/${id}/session/extend`, undefined, { vat });
20363
+ const value = response.data;
20364
+ return {
20365
+ vaultId: value.vault_id,
20366
+ expiresAt: value.expires_at,
20367
+ hardExpiresAt: value.hard_expires_at,
20368
+ idleTimeoutSeconds: value.idle_timeout_seconds,
20369
+ ttlSeconds: value.ttl_seconds,
20370
+ canExtend: value.can_extend,
20288
20371
  };
20289
20372
  }
20290
20373
  /**
@@ -20327,6 +20410,25 @@ class VaultsModule {
20327
20410
  const response = await this.http.get(apiPath `/v1/vaults/${id}`);
20328
20411
  return mapVaultDetail(response.data);
20329
20412
  }
20413
+ /**
20414
+ * Set when this vault reseals after inactivity and after an unseal.
20415
+ * Company administrators only. Changes apply on the next unseal.
20416
+ * Null values inherit system defaults; zero idle seconds disables extensions.
20417
+ */
20418
+ async updateResealSettings(vaultId, settings) {
20419
+ const id = requireResourceId(vaultId, 'vaultId');
20420
+ const response = await this.http.put(apiPath `/v1/vaults/${id}/reseal-settings`, {
20421
+ reseal_idle_seconds: settings.idleSeconds,
20422
+ reseal_max_seconds: settings.maxSeconds,
20423
+ });
20424
+ const value = response.data;
20425
+ return {
20426
+ vaultId: value.vault_id,
20427
+ idleSeconds: value.reseal_idle_seconds,
20428
+ maxSeconds: value.reseal_max_seconds,
20429
+ defaults: { idleSeconds: value.reseal_defaults.idle_seconds, maxSeconds: value.reseal_defaults.max_seconds },
20430
+ };
20431
+ }
20330
20432
  /**
20331
20433
  * Rename a vault.
20332
20434
  *
@@ -20601,6 +20703,11 @@ function mapVaultDetail(v) {
20601
20703
  createdAt: v.created_at,
20602
20704
  lastUnsealedAt: v.last_unsealed_at ?? null,
20603
20705
  unsealCount: v.unseal_count ?? 0,
20706
+ ...(v.reseal_idle_seconds === undefined ? {} : { resealIdleSeconds: v.reseal_idle_seconds }),
20707
+ ...(v.reseal_max_seconds === undefined ? {} : { resealMaxSeconds: v.reseal_max_seconds }),
20708
+ ...(v.reseal_defaults === undefined ? {} : {
20709
+ resealDefaults: { idleSeconds: v.reseal_defaults.idle_seconds, maxSeconds: v.reseal_defaults.max_seconds },
20710
+ }),
20604
20711
  deletionNoticeUnreached: v.deletion_notice_unreached && v.deletion_notice_unreached.map(mapUnreachedAdmin),
20605
20712
  };
20606
20713
  }
@@ -21364,7 +21471,7 @@ class SparkVault {
21364
21471
  }
21365
21472
  /** Get the SDK version */
21366
21473
  static get version() {
21367
- return '14.1.1';
21474
+ return '14.2.1';
21368
21475
  }
21369
21476
  }
21370
21477
  if (typeof window !== 'undefined') {