@sparkvault/sdk-js 8.15.0 → 9.0.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
@@ -32,14 +32,20 @@ The official SparkVault JavaScript SDK for browser applications. Add passwordles
32
32
 
33
33
  ```bash
34
34
  npm install @sparkvault/sdk-js
35
- # or
36
- yarn add @sparkvault/sdk-js
35
+ ```
36
+
37
+ Both module systems resolve to a working entry through the package's `exports` map:
38
+
39
+ ```js
40
+ import SparkVault from '@sparkvault/sdk-js'; // ESM → dist/index.mjs
41
+ const { SparkVault } = require('@sparkvault/sdk-js'); // CJS → dist/index.cjs
37
42
  ```
38
43
 
39
44
  **Bundle Formats:**
40
- - `sparkvault.js` — UMD bundle for browsers (recommended)
41
- - `sparkvault.esm.js` — ES modules for modern bundlers
42
- - `sparkvault.cjs.js` — CommonJS for Node.js
45
+ - `dist/index.mjs` — ES module, resolved by `import`
46
+ - `dist/index.cjs` — CommonJS, resolved by `require`
47
+ - `dist/sparkvault.js` — UMD bundle for a browser `<script>` tag (also served from the CDN)
48
+ - `dist/index.d.ts` — bundled TypeScript declarations
43
49
 
44
50
  ### Caching & version pinning
45
51
 
package/dist/config.d.ts CHANGED
@@ -24,10 +24,12 @@ export interface SparkVaultConfig {
24
24
  /** Request timeout in milliseconds (default: 30000) */
25
25
  timeout?: number;
26
26
  /**
27
- * Preload Identity configuration on SDK init (default: true).
28
- * When enabled, the /config call is made immediately when the SDK initializes,
29
- * so verify() opens instantly without waiting for the config fetch.
30
- * Set to false to defer config loading until verify() is called.
27
+ * Preload Identity configuration on SDK init (default: true in a browser,
28
+ * false off-DOM). When enabled, the /config call is made immediately when the
29
+ * SDK initializes, so verify() opens instantly without waiting for the config
30
+ * fetch. It buys nothing in a server process — there is no dialog to open —
31
+ * so a Node host does not pay for a network call it will never use.
32
+ * Set explicitly to override in either direction.
31
33
  */
32
34
  preloadConfig?: boolean;
33
35
  /** Enable backdrop blur on dialogs (default: true) */
@@ -196,7 +196,9 @@ function resolveConfig(config) {
196
196
  getAccessToken: config.getAccessToken,
197
197
  apiKey: config.apiKey,
198
198
  clientId: config.clientId,
199
- preloadConfig: config.preloadConfig !== false, // Default: true
199
+ // Preloading warms a dialog that only a browser can open; default it off
200
+ // where there is no DOM so server hosts make no init-time network call.
201
+ preloadConfig: config.preloadConfig ?? typeof window !== 'undefined',
200
202
  backdropBlur: config.backdropBlur !== false, // Default: true
201
203
  allowedDownloadHostPatterns: config.allowedDownloadHostPatterns ?? DEFAULT_ALLOWED_DOWNLOAD_HOST_PATTERNS,
202
204
  };
@@ -975,11 +977,15 @@ class IdentityApi extends SparkVaultApi {
975
977
  * If preload fails, getConfig() will clear the cache and retry.
976
978
  */
977
979
  preloadConfig() {
978
- if (!this.configCache) {
979
- // Fire and forget - errors are handled when getConfig() is awaited.
980
- // If this fails, getConfig() clears the cache and retries.
981
- this.configCache = this.request('GET', '/config');
980
+ if (this.configCache) {
981
+ return;
982
982
  }
983
+ const pending = this.request('GET', '/config');
984
+ this.configCache = pending;
985
+ // Nobody awaits a background preload, and an unawaited rejection aborts the
986
+ // whole Node process. Attach a terminal handler so the failure stays parked
987
+ // on the cached promise, which getConfig() re-raises to its caller on demand.
988
+ pending.catch(() => { });
983
989
  }
984
990
  /**
985
991
  * Check if config has been preloaded and is ready.
@@ -8572,18 +8578,6 @@ const PORTAL_SECTIONS = ['home', 'identity', 'security', 'sessions', 'sites'];
8572
8578
  // listener but not sessionStorage) is what lets the next load self-heal.
8573
8579
  const PENDING_KEY = 'sv_signin_pending';
8574
8580
  const PENDING_TTL_MS = 10 * 60 * 1000;
8575
- // One-shot: the identifier the recovery bounce is re-minting for. Written only
8576
- // by the recovery bounce; the return leg consumes it to verify the redeemed
8577
- // result is for that same account (see consumeHandoffFragment).
8578
- const RECOVERY_HINT_KEY = 'sv_recovery_hint';
8579
- /**
8580
- * Normalize an identifier for equality, mirroring the server: trim, and
8581
- * lowercase emails (a value containing '@'). Phones compare trimmed-exact.
8582
- */
8583
- function normalizeIdentity(value) {
8584
- const trimmed = value.trim();
8585
- return trimmed.includes('@') ? trimmed.toLowerCase() : trimmed;
8586
- }
8587
8581
  /**
8588
8582
  * Read and parse the pending marker — JSON `{ at, hint }`, where `hint` is the
8589
8583
  * email or phone the sign-in was started with (null when the flow collects the
@@ -9085,11 +9079,9 @@ class IdentityModule {
9085
9079
  // (and a StrictMode double-invocation finds an empty hash and no-ops).
9086
9080
  let expectedState = null;
9087
9081
  let codeVerifier = null;
9088
- let expectedRecoveryIdentity = null;
9089
9082
  try {
9090
9083
  expectedState = sessionStorage.getItem('sv_oauth_state');
9091
9084
  codeVerifier = sessionStorage.getItem('sv_pkce_verifier');
9092
- expectedRecoveryIdentity = sessionStorage.getItem(RECOVERY_HINT_KEY);
9093
9085
  this.clearOneShotAuthState();
9094
9086
  }
9095
9087
  catch {
@@ -9110,6 +9102,12 @@ class IdentityModule {
9110
9102
  if (!codeVerifier) {
9111
9103
  throw new ValidationError('Sign-in session was lost — please sign in again.');
9112
9104
  }
9105
+ // WHICH account the code carries is settled where it is minted, never
9106
+ // here: the code is PKCE- and origin-bound to this tab, and a recovery
9107
+ // bounce only ever mints for the account its `login_hint` named (see
9108
+ // startRecoveryBounce). The redeemed result exposes just that account's
9109
+ // PRIMARY identifier — not necessarily the one the caller signed in
9110
+ // with — so re-checking it here could only discard valid sign-ins.
9113
9111
  const raw = await this.api.redeemHandoffCode(code, codeVerifier);
9114
9112
  const result = {
9115
9113
  token: raw.token,
@@ -9119,18 +9117,6 @@ class IdentityModule {
9119
9117
  sessionId: raw.session_id ?? undefined,
9120
9118
  refreshToken: raw.refresh_token ?? undefined,
9121
9119
  };
9122
- // A recovery bounce carries the identifier the interrupted sign-in was
9123
- // addressing, but /sso treats a hint matching no hub session like no hint
9124
- // at all (anti-oracle) — so the bounce can come back holding a DIFFERENT
9125
- // single-eligible account. The client is the one place that knows which
9126
- // account the person was signing in to: a mismatched result is discarded,
9127
- // never handed to the host (a wrong-account handoff). Silent — no
9128
- // onError — falling through to interactive sign-in, matching the recovery
9129
- // flow's non-oracle posture.
9130
- if (expectedRecoveryIdentity &&
9131
- normalizeIdentity(expectedRecoveryIdentity) !== normalizeIdentity(result.identity)) {
9132
- return null;
9133
- }
9134
9120
  options.onSuccess?.(result);
9135
9121
  return result;
9136
9122
  }
@@ -9151,22 +9137,12 @@ class IdentityModule {
9151
9137
  */
9152
9138
  async startRecoveryBounce(loginHint) {
9153
9139
  const sso = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/sso`);
9154
- // With several hub sessions, login_hint tells /sso which account the
9155
- // interrupted sign-in was addressing, so recovery never re-mints another.
9156
- // Also stash it one-shot: a hint matching no hub session deliberately
9157
- // behaves server-side like no hint at all (anti-oracle), so the return leg
9158
- // must verify the redeemed identity is the one this sign-in was for.
9159
- try {
9160
- if (loginHint) {
9161
- sessionStorage.setItem(RECOVERY_HINT_KEY, loginHint);
9162
- }
9163
- else {
9164
- sessionStorage.removeItem(RECOVERY_HINT_KEY);
9165
- }
9166
- }
9167
- catch {
9168
- // No storage → prepareHandoffNavigation bails below; nothing to verify.
9169
- }
9140
+ // With several hub sessions, login_hint names the account the interrupted
9141
+ // sign-in was addressing, and it is the whole wrong-account defence: /sso
9142
+ // mints silently ONLY for a hint that matched exactly one hub session's
9143
+ // verified identifiers — every unsatisfiable hint (a stranger's address, an
9144
+ // ambiguous match, an account not eligible here) comes back with no result
9145
+ // at all rather than a different account's.
9170
9146
  if (loginHint) {
9171
9147
  sso.searchParams.set('login_hint', loginHint);
9172
9148
  }
@@ -9174,16 +9150,6 @@ class IdentityModule {
9174
9150
  if (nav) {
9175
9151
  window.location.assign(nav);
9176
9152
  }
9177
- else {
9178
- // The bounce never left (no storage or WebCrypto) — retire the stash so
9179
- // it cannot linger into an unrelated later return leg.
9180
- try {
9181
- sessionStorage.removeItem(RECOVERY_HINT_KEY);
9182
- }
9183
- catch {
9184
- // Storage disabled: nothing was persisted, nothing to clear.
9185
- }
9186
- }
9187
9153
  }
9188
9154
  /**
9189
9155
  * Explicit `flow: 'redirect'` — navigate this tab to the interactive sign-in
@@ -9283,12 +9249,11 @@ class IdentityModule {
9283
9249
  window.history.replaceState(window.history.state, document.title, `${window.location.pathname}${window.location.search}`);
9284
9250
  }
9285
9251
  }
9286
- /** Drop the one-shot PKCE state/verifier (+ recovery hint) a bounce staged. */
9252
+ /** Drop the one-shot PKCE state/verifier a bounce staged. */
9287
9253
  clearOneShotAuthState() {
9288
9254
  try {
9289
9255
  sessionStorage.removeItem('sv_oauth_state');
9290
9256
  sessionStorage.removeItem('sv_pkce_verifier');
9291
- sessionStorage.removeItem(RECOVERY_HINT_KEY);
9292
9257
  }
9293
9258
  catch {
9294
9259
  // Storage disabled: nothing was persisted, nothing to clear.
@@ -9425,8 +9390,9 @@ class IdentityModule {
9425
9390
  *
9426
9391
  * The counterpart to `sv.notify`: where that module is session-scoped and reads
9427
9392
  * only the signed-in person's OWN inbox, this one is the account-scoped product
9428
- * surface a tenant's BACKEND drives — send, sender-side inbox reads and state,
9429
- * send status, receipts, and the account's Notify config. Every method maps to
9393
+ * surface a tenant's BACKEND drives — send, send history, recall, sender-side
9394
+ * inbox reads and state, send status, receipts, and the account's Notify config.
9395
+ * Every method maps to
9430
9396
  * `/v1/products/notify/*` and is authorized by the caller's account, so the
9431
9397
  * recipient is supplied explicitly rather than derived from a session.
9432
9398
  *
@@ -9478,15 +9444,22 @@ const NOTIFY_PRESETS = Object.freeze({
9478
9444
  channels: ['in_app', 'push', 'web_push', 'email'],
9479
9445
  policy: { verificationLevel: 'identifier', interaction: 'reply' },
9480
9446
  },
9447
+ // `approval` and `signatureRequest` verify at `identifier`, not `passkey`: a
9448
+ // passkey-level grant is only satisfiable by a recipient who ALREADY has a
9449
+ // passkey registered with SparkVault, and the recipient ceremony cannot enrol
9450
+ // one mid-flight — a passkey default strands every first-time raw-email
9451
+ // recipient on a request they can never answer. Pass
9452
+ // `policy: { verificationLevel: 'passkey' }` explicitly when the audience is
9453
+ // known to be enrolled.
9481
9454
  approval: {
9482
9455
  category: 'approval',
9483
9456
  channels: ['in_app', 'push', 'web_push', 'email'],
9484
- policy: { verificationLevel: 'passkey', interaction: 'approve' },
9457
+ policy: { verificationLevel: 'identifier', interaction: 'approve' },
9485
9458
  },
9486
9459
  signatureRequest: {
9487
9460
  category: 'signature',
9488
9461
  channels: ['in_app', 'push', 'web_push', 'email'],
9489
- policy: { verificationLevel: 'passkey', interaction: 'sign' },
9462
+ policy: { verificationLevel: 'identifier', interaction: 'sign' },
9490
9463
  },
9491
9464
  });
9492
9465
  /**
@@ -9576,11 +9549,11 @@ class NotifyProductModule {
9576
9549
  async sendConversation(options) {
9577
9550
  return this.send(buildNotifyPresetSend('conversation', options));
9578
9551
  }
9579
- /** High-stakes approve/deny — passkey-verified, with `action_hash` binding. */
9552
+ /** High-stakes approve/deny — identifier-verified, with `action_hash` binding. */
9580
9553
  async sendApproval(options) {
9581
9554
  return this.send(buildNotifyPresetSend('approval', options));
9582
9555
  }
9583
- /** Signature-on-delivery — passkey-verified, with `action_hash` binding. */
9556
+ /** Signature-on-delivery — identifier-verified, with `action_hash` binding. */
9584
9557
  async sendSignatureRequest(options) {
9585
9558
  return this.send(buildNotifyPresetSend('signatureRequest', options));
9586
9559
  }
@@ -9666,6 +9639,76 @@ class NotifyProductModule {
9666
9639
  });
9667
9640
  return response.data;
9668
9641
  }
9642
+ // ── Send history & recall ───────────────────────────────────────────────────
9643
+ /**
9644
+ * The account's send history, newest first — what you sent, to how many, and
9645
+ * how it landed.
9646
+ *
9647
+ * Metadata only by construction: the history index does not project the
9648
+ * audience, so no recipient contact or SparkLink pointer can travel here. Take
9649
+ * `getSendStatus(sendId)` for the per-recipient detail.
9650
+ *
9651
+ * Real pagination: a null `cursor` means the end of the account's history.
9652
+ *
9653
+ * @example
9654
+ * let cursor: string | undefined;
9655
+ * do {
9656
+ * const page = await sv.products.notify.listSends({ cursor, limit: 50 });
9657
+ * for (const send of page.sends) {
9658
+ * console.log(send.created_at, send.title, send.state,
9659
+ * `${send.delivered_count ?? '?'} / ${send.recipient_count ?? '?'}`);
9660
+ * }
9661
+ * cursor = page.cursor ?? undefined;
9662
+ * } while (cursor);
9663
+ */
9664
+ async listSends(options = {}) {
9665
+ const query = buildQuery$3({ limit: options.limit, cursor: options.cursor });
9666
+ const response = await this.http.get(`${BASE_PATH}/sends${query}`);
9667
+ return response.data;
9668
+ }
9669
+ /**
9670
+ * Recall a sealed send: revoke the single-use SparkLink grants it minted, so
9671
+ * the content can no longer be revealed.
9672
+ *
9673
+ * `mode: 'grant'` (the default) drops access and leaves the content intact.
9674
+ * `mode: 'content'` hard-burns the sealed spark so it is unreadable for
9675
+ * everyone — spark-backed sends only, since an ingot send merely references the
9676
+ * owner's durable vault content.
9677
+ *
9678
+ * Idempotent: a grant already revoked (or already consumed) counts as recalled,
9679
+ * so a repeated call converges rather than accumulating failures. One
9680
+ * recipient's failure never stops the rest — the response reports every one.
9681
+ *
9682
+ * PLAINTEXT SENDS CANNOT BE RECALLED (400): they delivered their body inline,
9683
+ * in the clear, and minted no grant. There is nothing to revoke, and saying
9684
+ * otherwise would be a lie about the one thing you are asking.
9685
+ *
9686
+ * @example
9687
+ * // Whole audience, access only
9688
+ * await sv.products.notify.recallSend(send.send_id);
9689
+ *
9690
+ * // One recipient, burn the content for everyone
9691
+ * const { recalled, failed } = await sv.products.notify.recallSend(send.send_id, {
9692
+ * recipientIds: [user.svid],
9693
+ * mode: 'content',
9694
+ * });
9695
+ */
9696
+ async recallSend(sendId, options = {}) {
9697
+ requireSendId(sendId);
9698
+ if (options.recipientIds !== undefined) {
9699
+ if (!Array.isArray(options.recipientIds) || options.recipientIds.length === 0) {
9700
+ throw new ValidationError('recipientIds must be a non-empty array; omit it entirely to recall the whole audience', { field: 'recipientIds', received: options.recipientIds });
9701
+ }
9702
+ }
9703
+ if (options.mode !== undefined && options.mode !== 'grant' && options.mode !== 'content') {
9704
+ throw new ValidationError("mode must be 'grant' or 'content'", {
9705
+ field: 'mode',
9706
+ received: options.mode,
9707
+ });
9708
+ }
9709
+ const response = await this.http.post(`${BASE_PATH}/sends/${encodeURIComponent(sendId)}/recall`, { recipient_ids: options.recipientIds, mode: options.mode });
9710
+ return response.data;
9711
+ }
9669
9712
  // ── Status & receipts ───────────────────────────────────────────────────────
9670
9713
  /**
9671
9714
  * The sender's per-recipient delivery rollup for one send: who it reached and
@@ -9683,13 +9726,14 @@ class NotifyProductModule {
9683
9726
  * The account's verified-interaction receipts (portable, JWKS-verifiable
9684
9727
  * proofs), newest first. Follow `cursor` to page.
9685
9728
  *
9686
- * A page can come back SHORT of `limit` — even EMPTY — yet still carry a
9687
- * non-null cursor: the receipt-subtype and `interaction` filters are applied
9688
- * after the key query, so a page of non-matching rows yields no receipts and a
9689
- * live cursor. Follow the cursor; never treat a short or empty page as the end.
9729
+ * `source` says which store answered. `receipt_index` is the normal path — a
9730
+ * bounded query with real pagination. `legacy_scan` appears only for an account
9731
+ * whose receipts all predate that index; it filters the account audit log, so
9732
+ * it can hand back EMPTY pages that are nowhere near the end. On EITHER source,
9733
+ * follow the cursor until it is null before concluding there are none.
9690
9734
  *
9691
9735
  * @example
9692
- * const { receipts, cursor } = await sv.products.notify.listReceipts({ interaction: 'approve' });
9736
+ * const { receipts, cursor, source } = await sv.products.notify.listReceipts({ interaction: 'approve' });
9693
9737
  */
9694
9738
  async listReceipts(options = {}) {
9695
9739
  const query = buildQuery$3({
@@ -9742,12 +9786,21 @@ class NotifyProductModule {
9742
9786
  * a seeded default from re-appearing on the next merge. The reserved `security`
9743
9787
  * category can neither be removed nor made optional.
9744
9788
  *
9789
+ * The `events` section configures the outbound event webhook: `webhook_url`
9790
+ * must be https on a public host, and `secret` (16-256 chars) signs every event
9791
+ * body as `X-SparkVault-Signature: hex(HMAC-SHA256(secret, rawBody))`. The
9792
+ * secret is WRITE-ONLY — reads report `events.secret_set`, never the value.
9793
+ *
9745
9794
  * @example
9746
9795
  * await sv.products.notify.updateConfig({
9747
9796
  * categories: {
9748
9797
  * weekly_newsletter: { label: 'Weekly newsletter', required: false },
9749
9798
  * marketing: null, // tombstone — remove the seeded default
9750
9799
  * },
9800
+ * events: {
9801
+ * webhook_url: 'https://api.example.com/hooks/sparkvault',
9802
+ * secret: process.env.SPARKVAULT_EVENT_SECRET,
9803
+ * },
9751
9804
  * });
9752
9805
  */
9753
9806
  async updateConfig(patch) {
@@ -14703,7 +14756,7 @@ class SparkVault {
14703
14756
  }
14704
14757
  /** Get the SDK version */
14705
14758
  static get version() {
14706
- return '__VERSION__';
14759
+ return '9.0.1';
14707
14760
  }
14708
14761
  }
14709
14762
  if (typeof window !== 'undefined') {
@@ -14739,4 +14792,4 @@ exports.buildNotifyPresetSend = buildNotifyPresetSend;
14739
14792
  exports.default = SparkVault;
14740
14793
  exports.logger = logger;
14741
14794
  exports.setDebugMode = setDebugMode;
14742
- //# sourceMappingURL=sparkvault.cjs.js.map
14795
+ //# sourceMappingURL=index.cjs.map