@sparkvault/sdk-js 12.0.5 → 13.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/dist/index.mjs CHANGED
@@ -27,12 +27,13 @@ function isTransientHttpStatus(status) {
27
27
 
28
28
  /**
29
29
  * The upload publication contract between Forge and Core's activation, and
30
- * the facts of a transfer token both services spell: its shape, the
31
- * publication it is bound to (a content version, and the one an ingot row
32
- * names), Core's revocation of an upload's token, and the refusals of Core's
33
- * a transfer's answer names (the header, and the lock of a vault scheduled
34
- * for deletion). Every client ends an upload it gives up by one rule here
35
- * too: the upload id its delete is conditioned on (givenUpUploadId).
30
+ * the facts of a transfer both services spell: its token's shape and the
31
+ * publication the token is bound to (a content version, and the one an ingot
32
+ * row names), its charge's ledger reference and category, Core's revocation
33
+ * of an upload's token, and the refusals of Core's a transfer's answer names
34
+ * (the header, and the lock of a vault scheduled for deletion). Every client
35
+ * ends an upload it gives up by one rule here too: the upload id its delete is
36
+ * conditioned on (givenUpUploadId).
36
37
  *
37
38
  * Forge stamps UPLOAD_PUBLICATION_PROTOCOL on every upload session it creates
38
39
  * and on the final state it hands Core's activation (POST
@@ -767,33 +768,47 @@ function resumeOffsetProblem(offset, { totalSize, chunkSize }) {
767
768
  * SparkVault SDK Error Types
768
769
  */
769
770
  class SparkVaultError extends Error {
770
- constructor(message, code, statusCode, details, retryAfterMs = null) {
771
+ constructor(message, code, statusCode, details, retryAfterMs = null, serviceCode) {
771
772
  super(message);
772
773
  this.name = 'SparkVaultError';
773
774
  this.code = code;
774
775
  this.statusCode = statusCode;
775
776
  this.details = details;
776
777
  this.retryAfterMs = retryAfterMs;
778
+ this.serviceCode = serviceCode;
777
779
  Object.setPrototypeOf(this, SparkVaultError.prototype);
778
780
  }
779
781
  }
780
782
  class AuthenticationError extends SparkVaultError {
781
- constructor(message, details, retryAfterMs = null) {
782
- super(message, 'authentication_error', 401, details, retryAfterMs);
783
+ constructor(message, details, retryAfterMs = null, serviceCode) {
784
+ super(message, 'authentication_error', 401, details, retryAfterMs, serviceCode);
783
785
  this.name = 'AuthenticationError';
784
786
  Object.setPrototypeOf(this, AuthenticationError.prototype);
785
787
  }
786
788
  }
789
+ /**
790
+ * A key the request presents was refused (401 UNAUTHORIZED): the DVAK an
791
+ * unseal names is invalid or revoked. The caller's own credential stood, so
792
+ * this is no ended session, and signing in again changes nothing: present a
793
+ * live key. Every other 401 is an {@link AuthenticationError}.
794
+ */
795
+ class UnauthorizedError extends SparkVaultError {
796
+ constructor(message, details, retryAfterMs = null, serviceCode) {
797
+ super(message, 'UNAUTHORIZED', 401, details, retryAfterMs, serviceCode);
798
+ this.name = 'UnauthorizedError';
799
+ Object.setPrototypeOf(this, UnauthorizedError.prototype);
800
+ }
801
+ }
787
802
  class AuthorizationError extends SparkVaultError {
788
- constructor(message, details, retryAfterMs = null) {
789
- super(message, 'authorization_error', 403, details, retryAfterMs);
803
+ constructor(message, details, retryAfterMs = null, serviceCode) {
804
+ super(message, 'authorization_error', 403, details, retryAfterMs, serviceCode);
790
805
  this.name = 'AuthorizationError';
791
806
  Object.setPrototypeOf(this, AuthorizationError.prototype);
792
807
  }
793
808
  }
794
809
  class ValidationError extends SparkVaultError {
795
- constructor(message, details, retryAfterMs = null) {
796
- super(message, 'validation_error', 400, details, retryAfterMs);
810
+ constructor(message, details, retryAfterMs = null, serviceCode) {
811
+ super(message, 'validation_error', 400, details, retryAfterMs, serviceCode);
797
812
  this.name = 'ValidationError';
798
813
  Object.setPrototypeOf(this, ValidationError.prototype);
799
814
  }
@@ -804,8 +819,8 @@ class ValidationError extends SparkVaultError {
804
819
  * to admins, or "ask your account admin" to members.
805
820
  */
806
821
  class PlanRequiredError extends SparkVaultError {
807
- constructor(message, details, retryAfterMs = null) {
808
- super(message, 'PLAN_REQUIRED', 402, details, retryAfterMs);
822
+ constructor(message, details, retryAfterMs = null, serviceCode) {
823
+ super(message, 'PLAN_REQUIRED', 402, details, retryAfterMs, serviceCode);
809
824
  this.name = 'PlanRequiredError';
810
825
  Object.setPrototypeOf(this, PlanRequiredError.prototype);
811
826
  }
@@ -816,8 +831,8 @@ class PlanRequiredError extends SparkVaultError {
816
831
  * the right capacity block.
817
832
  */
818
833
  class QuotaExceededError extends SparkVaultError {
819
- constructor(message, details, retryAfterMs = null) {
820
- super(message, 'QUOTA_EXCEEDED', 402, details, retryAfterMs);
834
+ constructor(message, details, retryAfterMs = null, serviceCode) {
835
+ super(message, 'QUOTA_EXCEEDED', 402, details, retryAfterMs, serviceCode);
821
836
  this.name = 'QuotaExceededError';
822
837
  const resource = details?.resource;
823
838
  this.resource =
@@ -826,14 +841,17 @@ class QuotaExceededError extends SparkVaultError {
826
841
  }
827
842
  }
828
843
  /**
829
- * Notify subscription gate (403 NOTIFY_SUBSCRIPTION_REQUIRED) — the account has
830
- * no active Notify subscription and attempted a send. Distinct from a generic
831
- * authorization failure: the credential is fine and re-authenticating changes
832
- * nothing, so surface a subscribe CTA rather than a sign-in prompt.
844
+ * Notify subscription gate (403 NOTIFY_SUBSCRIPTION_REQUIRED) — the account
845
+ * does not hold Notify and attempted a send that names no accepted send's
846
+ * `sendId` (a replay of an accepted send, the same request under its `sendId`,
847
+ * is answered with the stored send), or a config save that selects a new
848
+ * `email.sending_domain`. Distinct from a generic authorization failure: the
849
+ * credential is fine and re-authenticating changes nothing, so surface a
850
+ * subscribe CTA rather than a sign-in prompt.
833
851
  */
834
852
  class NotifySubscriptionRequiredError extends SparkVaultError {
835
- constructor(message, details, retryAfterMs = null) {
836
- super(message, 'NOTIFY_SUBSCRIPTION_REQUIRED', 403, details, retryAfterMs);
853
+ constructor(message, details, retryAfterMs = null, serviceCode) {
854
+ super(message, 'NOTIFY_SUBSCRIPTION_REQUIRED', 403, details, retryAfterMs, serviceCode);
837
855
  this.name = 'NotifySubscriptionRequiredError';
838
856
  Object.setPrototypeOf(this, NotifySubscriptionRequiredError.prototype);
839
857
  }
@@ -965,6 +983,9 @@ async function readApiFailure(response) {
965
983
  *
966
984
  * - `isResourceIdOf(kind, value)`: an id of that kind.
967
985
  * - `isResourceId(value)`: an id of any kind, for a check that takes several.
986
+ * - `resourceIdPattern(kind)`: the same grammar as a regular-expression
987
+ * source, for a JSON Schema `pattern` beside `maxLength:
988
+ * RESOURCE_ID_MAX_LENGTH`, so a route schema and a check never disagree.
968
989
  *
969
990
  * Browser-safe and import-free: sdk-js bundles it, sdk-mobile mirrors it, and
970
991
  * the apps, the console and the mobile app import it.
@@ -997,7 +1018,30 @@ const RESOURCE_ID_PREFIXES = Object.freeze({
997
1018
  /** The longest id, prefix included. */
998
1019
  const RESOURCE_ID_MAX_LENGTH = 128;
999
1020
 
1000
- const ID_BODY = /^[A-Za-z0-9_-]+$/;
1021
+ /** The body every id carries after its prefix's underscore: the path-safe alphabet. */
1022
+ const ID_BODY_SOURCE = '[A-Za-z0-9_-]+';
1023
+
1024
+ /**
1025
+ * The pattern an id of the given kind matches, as a regular-expression source
1026
+ * string: its prefix, '_' and a body of the path-safe alphabet. A JSON Schema
1027
+ * reads it as `pattern`, with `maxLength: RESOURCE_ID_MAX_LENGTH`.
1028
+ *
1029
+ * @param {string} kind - A key of RESOURCE_ID_PREFIXES
1030
+ * @returns {string}
1031
+ * @throws {TypeError} for a kind the grammar does not name: a misspelled kind
1032
+ * would otherwise refuse every id without saying why
1033
+ */
1034
+ function resourceIdPattern(kind) {
1035
+ if (!Object.hasOwn(RESOURCE_ID_PREFIXES, kind)) {
1036
+ throw new TypeError(`No resource kind '${kind}'`);
1037
+ }
1038
+ return `^${RESOURCE_ID_PREFIXES[kind]}_${ID_BODY_SOURCE}$`;
1039
+ }
1040
+
1041
+ /** Each kind's pattern, compiled once. */
1042
+ const ID_PATTERNS = Object.freeze(Object.fromEntries(
1043
+ Object.keys(RESOURCE_ID_PREFIXES).map((kind) => [kind, new RegExp(resourceIdPattern(kind))])
1044
+ ));
1001
1045
 
1002
1046
  /**
1003
1047
  * Whether a value is an id of the given kind.
@@ -1012,11 +1056,9 @@ function isResourceIdOf(kind, value) {
1012
1056
  if (!Object.hasOwn(RESOURCE_ID_PREFIXES, kind)) {
1013
1057
  throw new TypeError(`No resource kind '${kind}'`);
1014
1058
  }
1015
- const prefix = `${RESOURCE_ID_PREFIXES[kind]}_`;
1016
1059
  return typeof value === 'string'
1017
1060
  && value.length <= RESOURCE_ID_MAX_LENGTH
1018
- && value.startsWith(prefix)
1019
- && ID_BODY.test(value.slice(prefix.length));
1061
+ && ID_PATTERNS[kind].test(value);
1020
1062
  }
1021
1063
 
1022
1064
  const KINDS = Object.freeze(Object.keys(RESOURCE_ID_PREFIXES));
@@ -1037,7 +1079,7 @@ function isResourceId(value) {
1037
1079
  * Keep platform domain decisions centralized: CSP, redirect safety, custom
1038
1080
  * domain reservation, and Identity postMessage trust all read this registry.
1039
1081
  * Trust follows the hosts the platform owns (isSparkVaultOwnedHostname);
1040
- * reservation covers those and the help-desk domain's subtree
1082
+ * reservation covers those and each product mail domain's subtree
1041
1083
  * (isSparkVaultReservedDomain), whose hosts are SparkVault's to hand out but
1042
1084
  * never trusted.
1043
1085
  */
@@ -1067,7 +1109,6 @@ const SPARKVAULT_PLATFORM_SV_HOSTS = Object.freeze([
1067
1109
  SPARKVAULT_LINKS_HOST,
1068
1110
  SPARKVAULT_FILES_HOST,
1069
1111
  'file.sv',
1070
- 'send.sv',
1071
1112
  'spark.sv',
1072
1113
  'by.sv',
1073
1114
  'at.sv',
@@ -1512,33 +1553,40 @@ class HttpClient {
1512
1553
  throw new SparkVaultError(`Unexpected response format: expected JSON but received ${contentType ?? 'unknown content type'}`, 'invalid_response_format', response.status, { body: text.slice(0, 500) });
1513
1554
  }
1514
1555
  /**
1515
- * The SDK error for a failed answer, typed by its status: the gates a host
1516
- * page branches on get their own class, and every other answer is the base
1517
- * error under the service's own code. Each carries the answer's
1518
- * `Retry-After` (`retryAfterMs`), the floor for whoever retries it — the
1519
- * SDK's own transfers when the answer is a download link's mint, and the
1520
- * host page otherwise.
1556
+ * The SDK error for a failed answer, typed by its status (a 402's or a 403's
1557
+ * by its code too): the gates a host page branches on get their own class,
1558
+ * and every other answer is the base error under the service's own code.
1559
+ * Each carries the service's code (`serviceCode`), which tells apart two
1560
+ * refusals that share a typed class's `code`, and the answer's `Retry-After`
1561
+ * (`retryAfterMs`), the floor for whoever retries it — the SDK's own
1562
+ * transfers when the answer is a download link's mint, and the host page
1563
+ * otherwise.
1521
1564
  */
1522
1565
  createErrorFromResponse({ status, message, code, details, retryAfterMs }) {
1523
1566
  switch (status) {
1524
1567
  case 400:
1525
- return new ValidationError(message, details, retryAfterMs);
1568
+ return new ValidationError(message, details, retryAfterMs, code);
1526
1569
  case 401:
1527
- return new AuthenticationError(message, details, retryAfterMs);
1570
+ // A refused key the request carries (an unseal's DVAK) is no ended
1571
+ // session: its own class, so a caller never signs out over it.
1572
+ if (code === 'UNAUTHORIZED')
1573
+ return new UnauthorizedError(message, details, retryAfterMs, code);
1574
+ return new AuthenticationError(message, details, retryAfterMs, code);
1528
1575
  case 402:
1529
1576
  if (code === 'QUOTA_EXCEEDED')
1530
- return new QuotaExceededError(message, details, retryAfterMs);
1577
+ return new QuotaExceededError(message, details, retryAfterMs, code);
1531
1578
  // PLAN_REQUIRED is the canonical 402 gate; treat any other 402 as one too.
1532
- return new PlanRequiredError(message, details, retryAfterMs);
1579
+ return new PlanRequiredError(message, details, retryAfterMs, code);
1533
1580
  case 403:
1534
- // A Notify send refused for want of a subscription is a billing gate, not
1535
- // a credential problem — give it its own catchable type.
1581
+ // A Notify send, or a config save selecting a new sending domain, refused
1582
+ // because the account does not hold Notify is a billing gate, not a
1583
+ // credential problem — give it its own catchable type.
1536
1584
  if (code === 'NOTIFY_SUBSCRIPTION_REQUIRED') {
1537
- return new NotifySubscriptionRequiredError(message, details, retryAfterMs);
1585
+ return new NotifySubscriptionRequiredError(message, details, retryAfterMs, code);
1538
1586
  }
1539
- return new AuthorizationError(message, details, retryAfterMs);
1587
+ return new AuthorizationError(message, details, retryAfterMs, code);
1540
1588
  default:
1541
- return new SparkVaultError(message, code, status, details, retryAfterMs);
1589
+ return new SparkVaultError(message, code, status, details, retryAfterMs, code);
1542
1590
  }
1543
1591
  }
1544
1592
  unwrapApiResponse(data) {
@@ -2393,11 +2441,12 @@ class IdentityApi extends SparkVaultApi {
2393
2441
  }
2394
2442
  /**
2395
2443
  * Check whether the SVID resolved from an email or phone has registered
2396
- * passkeys (`has_passkey`; cross-tenant — single global RP).
2444
+ * passkeys (`has_passkey`; cross-tenant — single global RP), for a
2445
+ * verification that admits passkeys.
2397
2446
  */
2398
- async checkPasskey(identity, identityType = 'email') {
2399
- const body = identityType === 'phone' ? { phone: identity } : { email: identity };
2400
- return this.request('POST', apiPath `/passkey/check`, body);
2447
+ async checkPasskey(identity, identityType = 'email', authContext) {
2448
+ const identityParam = identityType === 'phone' ? { phone: identity } : { email: identity };
2449
+ return this.request('POST', apiPath `/passkey/check`, { ...identityParam, ...verifySessionParam(authContext) });
2401
2450
  }
2402
2451
  /**
2403
2452
  * Redeem a one-time sign-in code (with its PKCE verifier) for the sign-in
@@ -2413,28 +2462,15 @@ class IdentityApi extends SparkVaultApi {
2413
2462
  });
2414
2463
  }
2415
2464
  /**
2416
- * The auth context a code or magic-link send carries: only its OIDC
2417
- * `auth_request_id`. Simple mode is read where a login completes
2418
- * (verifyOtp, completePasskeyVerify), never by a send.
2419
- */
2420
- buildAuthRequestParam(authContext) {
2421
- return authContext?.authRequestId ? { auth_request_id: authContext.authRequestId } : {};
2422
- }
2423
- /**
2424
- * Build auth context params for the completing requests (OIDC/simple mode).
2425
- * Converts AuthContext to snake_case params expected by backend.
2465
+ * The auth context a send or a completion carries: its OIDC
2466
+ * `auth_request_id` (a send keeps the auth request alive as long as what it
2467
+ * sent), and the verify session it belongs to.
2426
2468
  */
2427
2469
  buildAuthContextParams(authContext) {
2428
- const params = this.buildAuthRequestParam(authContext);
2429
- if (authContext?.simpleMode) {
2430
- params.simple_mode = {
2431
- success_url: authContext.simpleMode.successUrl,
2432
- failure_url: authContext.simpleMode.failureUrl,
2433
- state: authContext.simpleMode.state,
2434
- session_id: authContext.simpleMode.sessionId,
2435
- };
2436
- }
2437
- return params;
2470
+ return {
2471
+ ...(authContext?.authRequestId ? { auth_request_id: authContext.authRequestId } : {}),
2472
+ ...verifySessionParam(authContext),
2473
+ };
2438
2474
  }
2439
2475
  /**
2440
2476
  * Send OTP code to email or phone
@@ -2443,7 +2479,7 @@ class IdentityApi extends SparkVaultApi {
2443
2479
  return this.request('POST', apiPath `/otp/send`, {
2444
2480
  recipient: params.recipient,
2445
2481
  method: params.method,
2446
- ...this.buildAuthRequestParam(params.authContext),
2482
+ ...this.buildAuthContextParams(params.authContext),
2447
2483
  });
2448
2484
  }
2449
2485
  /**
@@ -2470,16 +2506,17 @@ class IdentityApi extends SparkVaultApi {
2470
2506
  });
2471
2507
  }
2472
2508
  /**
2473
- * Start passkey verification. An optional identifier scopes the ceremony to
2474
- * that person's credentials (`allowCredentials`) so the authenticator offers
2475
- * only the matching passkey; omit it for a discoverable ceremony. Completion
2476
- * always routes via the credential userHandle, so scoping is purely a hint.
2509
+ * Start passkey verification, for a verification that admits passkeys. An
2510
+ * optional identifier scopes the ceremony to that person's credentials
2511
+ * (`allowCredentials`) so the authenticator offers only the matching passkey;
2512
+ * omit it for a discoverable ceremony. Completion always routes via the
2513
+ * credential userHandle, so scoping is purely a hint.
2477
2514
  */
2478
- async startPasskeyVerify(identity, identityType = 'email') {
2515
+ async startPasskeyVerify(identity, identityType = 'email', authContext) {
2479
2516
  const identityParam = identity ? { [identityType]: identity } : {};
2480
2517
  // Backend returns { options: PublicKeyCredentialRequestOptions, session: {...} }
2481
2518
  // Extract and flatten to match PasskeyChallengeResponse
2482
- const response = await this.request('POST', apiPath `/passkey/verify`, identityParam);
2519
+ const response = await this.request('POST', apiPath `/passkey/verify`, { ...identityParam, ...verifySessionParam(authContext) });
2483
2520
  return {
2484
2521
  challenge: response.options.challenge,
2485
2522
  rpId: response.options.rpId,
@@ -2558,14 +2595,8 @@ class IdentityApi extends SparkVaultApi {
2558
2595
  if (authContext?.authRequestId) {
2559
2596
  params.set('auth_request_id', authContext.authRequestId);
2560
2597
  }
2561
- if (authContext?.simpleMode) {
2562
- const simpleMode = authContext.simpleMode.sessionId
2563
- ? { session_id: authContext.simpleMode.sessionId }
2564
- : {
2565
- success_url: authContext.simpleMode.successUrl,
2566
- failure_url: authContext.simpleMode.failureUrl,
2567
- state: authContext.simpleMode.state,
2568
- };
2598
+ const { simple_mode: simpleMode } = verifySessionParam(authContext);
2599
+ if (simpleMode) {
2569
2600
  params.set('simple_mode', JSON.stringify(simpleMode));
2570
2601
  }
2571
2602
  return `${this.baseUrl}/social/${provider}?${params}`;
@@ -2578,7 +2609,7 @@ class IdentityApi extends SparkVaultApi {
2578
2609
  return this.request('POST', apiPath `/sparklink/send`, {
2579
2610
  email,
2580
2611
  connection_id: connectionId,
2581
- ...this.buildAuthRequestParam(authContext),
2612
+ ...this.buildAuthContextParams(authContext),
2582
2613
  });
2583
2614
  }
2584
2615
  /**
@@ -2594,6 +2625,17 @@ class IdentityApi extends SparkVaultApi {
2594
2625
  return parseSparkLinkEvent(data);
2595
2626
  }
2596
2627
  }
2628
+ /**
2629
+ * The verify session a request of a verification against one names, as
2630
+ * `simple_mode: { session_id }`: the one field of it the server reads, the
2631
+ * session's row holding the rest. Every request of the verification carries
2632
+ * it (its sends, its passkey check and start, its completion, in a body or a
2633
+ * popup's query), so the server holds each to what the session admits; a
2634
+ * request that named none would be judged as a sign-in to the account instead.
2635
+ */
2636
+ function verifySessionParam(authContext) {
2637
+ return authContext?.simpleMode ? { simple_mode: { session_id: authContext.simpleMode.sessionId } } : {};
2638
+ }
2597
2639
  /**
2598
2640
  * Read a SparkLink result event. The WebSocket push and the kindling reclaim
2599
2641
  * carry the same server-built event, so this is the one reader for both.
@@ -2790,6 +2832,42 @@ function formatPhoneDisplay(value) {
2790
2832
  return `(${national.slice(0, 3)}) ${national.slice(3, 6)}-${national.slice(6, 10)}`;
2791
2833
  }
2792
2834
 
2835
+ /**
2836
+ * What a recipient is told when the grant they opened asks a stronger
2837
+ * verification than they can give: its sender held it to the `passkey` level,
2838
+ * and the person holds no passkey registered with SparkVault, or proved
2839
+ * themselves by a lesser factor. No ceremony enrols a passkey on the way to a
2840
+ * grant, so nothing the recipient retries can clear it: only the sender can
2841
+ * resend at a level the person can clear, and the words say so.
2842
+ *
2843
+ * One wording for every surface that meets it, each naming what was opened:
2844
+ * x.sv's page for a proof weaker than its grant asks (apps/api
2845
+ * routes/public-domains.js renderStrongerVerificationPage) and the JSON refusal
2846
+ * of the same proof (apps/api sparklinks/public-denial.js
2847
+ * verificationChallenge), the files.sv viewer (apps/web
2848
+ * pages/PublicFileViewer.jsx), and the Identity sign-in renderer on a
2849
+ * recipient's proof that admits a passkey alone, for a person who holds none
2850
+ * (packages/sdk-js products/identity/renderer.ts).
2851
+ *
2852
+ * BROWSER-SAFE: no imports.
2853
+ */
2854
+
2855
+ /** The heading of a page that says it. */
2856
+ const STRONGER_VERIFICATION_TITLE = 'This request needs your passkey';
2857
+
2858
+ /**
2859
+ * The words, naming what was opened and the organization that sent it.
2860
+ *
2861
+ * @param {'request'|'link'|'file'} subject - What the recipient opened
2862
+ * @param {string|null} [organizationName] - The sending organization's name,
2863
+ * when the surface knows it; the words name "the sender" otherwise
2864
+ * @returns {string}
2865
+ */
2866
+ function strongerVerificationMessage(subject, organizationName) {
2867
+ return `This ${subject} requires a passkey already registered with SparkVault. `
2868
+ + `Ask ${organizationName || 'the sender'} to resend it at a different verification level.`;
2869
+ }
2870
+
2793
2871
  /**
2794
2872
  * Method Registry
2795
2873
  *
@@ -2969,7 +3047,29 @@ class VerificationState {
2969
3047
  this._recipient = recipient;
2970
3048
  this._identityType = type;
2971
3049
  }
3050
+ /**
3051
+ * The methods this verification may use: what its verify session admits,
3052
+ * as the hosted page names it, else the account's sign-in methods.
3053
+ */
3054
+ get methodIds() {
3055
+ return this._authContext?.simpleMode?.methods ?? this._sdkConfig?.methods ?? [];
3056
+ }
3057
+ /**
3058
+ * Whether this verification proves a request its sender held to a passkey,
3059
+ * as its verify session's hosted page names it: the session admits the
3060
+ * passkey alone.
3061
+ */
3062
+ get passkeyRequired() {
3063
+ return this._authContext?.simpleMode?.passkeyRequired === true;
3064
+ }
3065
+ /**
3066
+ * The identifier types this verification's methods deliver to: its verify
3067
+ * session's, else the account's.
3068
+ */
2972
3069
  getAllowedIdentityTypes() {
3070
+ const fromSession = this._authContext?.simpleMode?.allowedIdentityTypes;
3071
+ if (fromSession)
3072
+ return fromSession;
2973
3073
  if (!this._sdkConfig)
2974
3074
  return ['email'];
2975
3075
  const allowed = this._sdkConfig.allowedIdentityTypes ?? ['email'];
@@ -3192,7 +3292,7 @@ class PasskeyHandler {
3192
3292
  */
3193
3293
  async checkPasskey() {
3194
3294
  try {
3195
- const response = await this.api.checkPasskey(this.state.recipient, this.state.identityType);
3295
+ const response = await this.api.checkPasskey(this.state.recipient, this.state.identityType, this.state.authContext);
3196
3296
  this.state.setPasskeyStatus(response.has_passkey);
3197
3297
  }
3198
3298
  catch (error) {
@@ -3263,7 +3363,7 @@ class PasskeyHandler {
3263
3363
  // passkeys so the authenticator offers only the matching credential;
3264
3364
  // without one it falls back to a discoverable ceremony.
3265
3365
  const identityType = this.state.identityType === 'phone' ? 'phone' : 'email';
3266
- const challenge = await this.api.startPasskeyVerify(this.state.recipient, identityType);
3366
+ const challenge = await this.api.startPasskeyVerify(this.state.recipient, identityType, this.state.authContext);
3267
3367
  const credential = await navigator.credentials.get({
3268
3368
  ...(signal ? { signal } : {}),
3269
3369
  publicKey: {
@@ -3367,18 +3467,15 @@ class PasskeyHandler {
3367
3467
  const identityParam = this.state.identityType === 'phone' ? 'phone' : 'email';
3368
3468
  params.set(identityParam, this.state.recipient);
3369
3469
  }
3370
- // Add auth context for OIDC/simple mode flows
3470
+ // The ceremony's auth context: an OIDC auth request, or the verify session
3471
+ // every request of the verification names.
3371
3472
  const authContext = this.state.authContext;
3372
3473
  if (authContext?.authRequestId) {
3373
3474
  params.set('auth_request_id', authContext.authRequestId);
3374
3475
  }
3375
- if (authContext?.simpleMode) {
3376
- params.set('simple_mode', JSON.stringify({
3377
- success_url: authContext.simpleMode.successUrl,
3378
- failure_url: authContext.simpleMode.failureUrl,
3379
- state: authContext.simpleMode.state,
3380
- session_id: authContext.simpleMode.sessionId,
3381
- }));
3476
+ const { simple_mode: simpleMode } = verifySessionParam(authContext);
3477
+ if (simpleMode) {
3478
+ params.set('simple_mode', JSON.stringify(simpleMode));
3382
3479
  }
3383
3480
  const hash = mode === 'register' && registrationToken
3384
3481
  ? `#${new URLSearchParams({ registration_token: registrationToken }).toString()}`
@@ -5538,6 +5635,33 @@ const IDENTITY_BLOCKED_ERROR_CODES = [
5538
5635
  function isBlockedCode(code) {
5539
5636
  return IDENTITY_BLOCKED_ERROR_CODES.includes(code);
5540
5637
  }
5638
+ /**
5639
+ * The code of a verification whose request its sender held to a passkey, for
5640
+ * a person who holds none: no ceremony here enrols one, so the person can do
5641
+ * nothing from this page, and only the sender can resend the request at a
5642
+ * level they can clear (the message says so).
5643
+ */
5644
+ const STRONGER_VERIFICATION_REQUIRED_CODE = 'stronger_verification_required';
5645
+ /**
5646
+ * The heading of a state the person can do nothing about from here, by its
5647
+ * code, or null for a genuine error. Retrying cannot clear any of them, so the
5648
+ * view shows such a state with no debug code badge and no "Try Again", only
5649
+ * Close:
5650
+ * - a locked-down identity, which only managing it at auth.sv clears;
5651
+ * - a blocked Identity (trial exhausted or expired, or a paid capacity wall),
5652
+ * which only the site owner subscribing clears, shown as a friendly,
5653
+ * non-leaky interstitial;
5654
+ * - a request held to a passkey the person does not hold.
5655
+ */
5656
+ function terminalTitle(code) {
5657
+ if (code === 'identity_locked')
5658
+ return 'This SparkVault Identity is locked';
5659
+ if (isBlockedCode(code))
5660
+ return 'Sign-in unavailable';
5661
+ if (code === STRONGER_VERIFICATION_REQUIRED_CODE)
5662
+ return STRONGER_VERIFICATION_TITLE;
5663
+ return null;
5664
+ }
5541
5665
  class ErrorView {
5542
5666
  constructor(props) {
5543
5667
  this.retryButton = null;
@@ -5557,24 +5681,11 @@ class ErrorView {
5557
5681
  // Content section
5558
5682
  const contentSection = div();
5559
5683
  contentSection.className = 'sv-error-content';
5560
- // A locked-down identity is a dedicated, non-error state: a specific
5561
- // title, no debug error-code badge, and no "Try Again" (retrying the
5562
- // login cannot clear a lockdown — only managing it at auth.sv can).
5563
- const isLocked = this.props.code === 'identity_locked';
5564
- // A blocked Identity (trial exhausted/expired, or paid capacity wall) is
5565
- // likewise terminal for the end user: retrying cannot restore access, only
5566
- // the site owner subscribing can. Show a friendly, non-leaky interstitial.
5567
- const isBlocked = isBlockedCode(this.props.code);
5568
- // Both states are terminal — suppress the debug code badge and the retry
5569
- // button, leaving only Close.
5570
- const isTerminal = isLocked || isBlocked;
5684
+ const terminal = terminalTitle(this.props.code);
5685
+ const isTerminal = terminal !== null;
5571
5686
  const title = document.createElement('h3');
5572
5687
  title.className = 'sv-error-title';
5573
- title.textContent = isLocked
5574
- ? 'This SparkVault Identity is locked'
5575
- : isBlocked
5576
- ? 'Sign-in unavailable'
5577
- : 'Something went wrong';
5688
+ title.textContent = terminal ?? 'Something went wrong';
5578
5689
  const message = document.createElement('p');
5579
5690
  message.className = 'sv-error-message';
5580
5691
  message.textContent = this.props.message;
@@ -6440,14 +6551,14 @@ class IdentityRenderer {
6440
6551
  }
6441
6552
  /**
6442
6553
  * True when the discoverable ceremony may be started without a gesture and
6443
- * this account actually offers passkey login: the flow runs on the Identity
6444
- * origin, the browser carries the passkey hint, and `passkey` is among the
6445
- * account's enabled methods.
6554
+ * this verification actually offers passkey login: the flow runs on the
6555
+ * Identity origin, the browser carries the passkey hint, and `passkey` is
6556
+ * among the verification's methods.
6446
6557
  */
6447
6558
  canDiscoverableVerify() {
6448
6559
  if (!this.passkeyHandler.canAutoVerify())
6449
6560
  return false;
6450
- const methods = enrichMethods(this.sdkConfig?.methods ?? []);
6561
+ const methods = enrichMethods(this.verificationState.methodIds);
6451
6562
  return methods.some((m) => m.type === 'passkey');
6452
6563
  }
6453
6564
  /**
@@ -6639,15 +6750,18 @@ class IdentityRenderer {
6639
6750
  : state.mode === 'verify'
6640
6751
  // Back returns to the picker with passkey still listed.
6641
6752
  // autoRoute=false prevents the auto-jump from sending the
6642
- // user straight back to this view. If no fallback methods
6643
- // exist at all, fall through to identity-input.
6753
+ // user straight back to this view. With no other method to
6754
+ // pick, it returns to the identifier the person typed; an
6755
+ // identity the flow fixed has no identifier step to return to.
6644
6756
  ? this.passkeyFallbackMethodsAvailable()
6645
6757
  ? () => this.showMethodSelect({ autoRoute: false })
6646
- : this.recipient
6758
+ : this.recipient && !this.isIdentityFixed()
6647
6759
  ? () => this.showIdentityInput()
6648
6760
  : undefined
6649
6761
  : () => this.showMethodSelect(),
6650
- onFallback: passkey.hasPasskey && !passkey.isFallbackMode
6762
+ // A code is offered only where the verification admits another
6763
+ // method: a request held to a passkey admits the passkey alone.
6764
+ onFallback: passkey.hasPasskey && !passkey.isFallbackMode && this.passkeyFallbackMethodsAvailable()
6651
6765
  ? () => this.handlePasskeyFallback()
6652
6766
  : undefined,
6653
6767
  });
@@ -6735,8 +6849,10 @@ class IdentityRenderer {
6735
6849
  const autoRoute = options.autoRoute !== false;
6736
6850
  if (!this.sdkConfig)
6737
6851
  return;
6738
- // Defensive: ensure methods is always an array
6739
- const methodIds = this.sdkConfig.methods ?? [];
6852
+ // The verification's methods: what its verify session admits, else the
6853
+ // account's sign-in methods. An answer that names no list is a
6854
+ // configuration fault, shown as one.
6855
+ const methodIds = this.verificationState.methodIds;
6740
6856
  if (!Array.isArray(methodIds)) {
6741
6857
  this.setState({
6742
6858
  view: 'error',
@@ -6777,11 +6893,7 @@ class IdentityRenderer {
6777
6893
  methods = methods.filter((m) => m.type !== 'passkey');
6778
6894
  }
6779
6895
  if (methods.length === 0) {
6780
- this.setState({
6781
- view: 'error',
6782
- message: 'No authentication methods available',
6783
- code: 'no_methods',
6784
- });
6896
+ this.setState(this.noMethodState());
6785
6897
  return;
6786
6898
  }
6787
6899
  // When a passkey is already registered for this identifier, jump
@@ -6819,6 +6931,24 @@ class IdentityRenderer {
6819
6931
  methods,
6820
6932
  });
6821
6933
  }
6934
+ /**
6935
+ * The state for a verification that leaves this person no method. A request
6936
+ * its sender held to a passkey admits the passkey alone, so a person the
6937
+ * check found holding none is told the request needs a passkey already
6938
+ * registered with SparkVault and that only the sender can resend it at a
6939
+ * level they can clear: no retry here changes that. Any other verification
6940
+ * with nothing to offer is a configuration fault, shown as one.
6941
+ */
6942
+ noMethodState() {
6943
+ if (this.verificationState.passkeyRequired && this.verificationState.passkey.hasPasskey === false) {
6944
+ return {
6945
+ view: 'error',
6946
+ code: STRONGER_VERIFICATION_REQUIRED_CODE,
6947
+ message: strongerVerificationMessage('request', this.sdkConfig?.branding?.companyName),
6948
+ };
6949
+ }
6950
+ return { view: 'error', message: 'No authentication methods available', code: 'no_methods' };
6951
+ }
6822
6952
  handleIdentitySubmit(result) {
6823
6953
  this.verificationState.setIdentity(result.value, result.type);
6824
6954
  // The person typed this identifier, so it is theirs to change — a no-hint
@@ -7169,7 +7299,7 @@ class IdentityRenderer {
7169
7299
  passkeyFallbackMethodsAvailable() {
7170
7300
  if (!this.sdkConfig)
7171
7301
  return false;
7172
- const methods = enrichMethods(this.sdkConfig.methods ?? []);
7302
+ const methods = enrichMethods(this.verificationState.methodIds);
7173
7303
  if (!this.recipient) {
7174
7304
  return methods.some((m) => m.type === 'social');
7175
7305
  }
@@ -10329,7 +10459,7 @@ class IdentityModule {
10329
10459
  * error.
10330
10460
  *
10331
10461
  * @example
10332
- * const result = (await sv.products.identity.isFedcmAvailable())
10462
+ * const result = IdentityModule.isFedcmAvailable()
10333
10463
  * ? await sv.products.identity.signInWithFedcm().catch(() => sv.products.identity.signIn())
10334
10464
  * : await sv.products.identity.signIn();
10335
10465
  */
@@ -10995,8 +11125,10 @@ class IdentityModule {
10995
11125
  /**
10996
11126
  * The Notify API contract values more than one runtime reads: the Core API
10997
11127
  * validates against them, the published API reference states them, and the JS
10998
- * SDK checks and applies them client-side. One definition, so a change reaches
10999
- * every reader instead of leaving a hand-kept copy behind.
11128
+ * SDK checks and applies them client-side; and the field sets each read answers
11129
+ * with, which the Core API's and the JS SDK's suites both hold their code to.
11130
+ * One definition, so a change reaches every reader instead of leaving a
11131
+ * hand-kept copy behind.
11000
11132
  *
11001
11133
  * Browser-safe and dependency-free: the JS SDK bundles this module.
11002
11134
  */
@@ -11023,13 +11155,18 @@ const NOTIFY_INBOX_BULK_MARK_STATES = Object.freeze(['seen', 'read']);
11023
11155
  * The five secure-by-default preset bundles, in the send API's vocabulary.
11024
11156
  *
11025
11157
  * A preset is a merge over the one send contract, never a separate path: the
11026
- * caller's arguments win over its defaults, and `channels` left unset lets the
11027
- * account config resolve the ladder per category.
11158
+ * caller's arguments win over its defaults (mergePresetSend), and `channels`
11159
+ * left unset lets the account config resolve the ladder per category.
11028
11160
  *
11029
11161
  * `alert` is the only plaintext preset: a non-confidential ping is read at a
11030
11162
  * glance, delivered inline rather than behind a tap-to-view link, on the account's
11031
11163
  * ladder narrowed to the channels that can render cleartext. The other four seal.
11032
11164
  *
11165
+ * The ladders the sealed presets name are the channels every sender's recipients
11166
+ * are reached on: the sender's Notify inbox (`in_app`, which the sender's own app
11167
+ * reads) and email. `secureMessage` goes to the person's mailbox alone. The
11168
+ * device channels reach SparkVault's own devices only, so no preset names them.
11169
+ *
11033
11170
  * `approval` and `signatureRequest` verify at `identifier`, not `passkey`: a
11034
11171
  * passkey-level grant is satisfiable only by a recipient who ALREADY has a
11035
11172
  * passkey registered, and the recipient ceremony cannot enrol one mid-flight, so
@@ -11045,34 +11182,86 @@ const NOTIFY_PRESETS$1 = Object.freeze({
11045
11182
  }),
11046
11183
  secureMessage: Object.freeze({
11047
11184
  category: 'secure',
11048
- channels: Object.freeze(['push', 'web_push', 'email']),
11185
+ channels: Object.freeze(['email']),
11049
11186
  policy: Object.freeze({ verification_level: 'identifier', interaction: 'view' })
11050
11187
  }),
11051
11188
  conversation: Object.freeze({
11052
11189
  category: 'conversation',
11053
- channels: Object.freeze(['in_app', 'push', 'web_push', 'email']),
11190
+ channels: Object.freeze(['in_app', 'email']),
11054
11191
  policy: Object.freeze({ verification_level: 'identifier', interaction: 'reply' })
11055
11192
  }),
11056
11193
  approval: Object.freeze({
11057
11194
  category: 'approval',
11058
- channels: Object.freeze(['in_app', 'push', 'web_push', 'email']),
11195
+ channels: Object.freeze(['in_app', 'email']),
11059
11196
  policy: Object.freeze({ verification_level: 'identifier', interaction: 'approve' })
11060
11197
  }),
11061
11198
  signatureRequest: Object.freeze({
11062
11199
  category: 'signature',
11063
- channels: Object.freeze(['in_app', 'push', 'web_push', 'email']),
11200
+ channels: Object.freeze(['in_app', 'email']),
11064
11201
  policy: Object.freeze({ verification_level: 'identifier', interaction: 'sign' })
11065
11202
  })
11066
11203
  });
11067
11204
 
11205
+ /**
11206
+ * The categories the five presets stamp. Every account's config seeds them, and
11207
+ * the send API accepts them whatever the account's map holds: a preset is a
11208
+ * first-class API surface, so an account that deletes one of these categories
11209
+ * narrows what it derives (its place on the compliance floor, its toggle on the
11210
+ * recipient's settings), never what a preset send may be classified as.
11211
+ */
11212
+ Object.freeze([
11213
+ ...new Set(Object.values(NOTIFY_PRESETS$1).map((preset) => preset.category))
11214
+ ]);
11215
+
11216
+ /**
11217
+ * A preset's bundle with the caller's send arguments over it: the one merge the
11218
+ * Core API's presets (`buildPresetSend`) and the JS SDK's
11219
+ * (`buildNotifyPresetSend`) both apply, each in its own vocabulary. The two
11220
+ * share every top-level field name, and the policy merge names no field.
11221
+ *
11222
+ * The caller's `category` wins when it names one, its `delivery` when it states
11223
+ * one (a sealed alert is allowed), and its `channels` when it names a ladder;
11224
+ * neither naming one leaves the ladder to the account config, per category. A
11225
+ * ladder the result carries is its own copy, never the preset's.
11226
+ *
11227
+ * The policy merges field by field, a caller field winning only where it states
11228
+ * a value. Neither undefined nor null states one: the send API types no policy
11229
+ * field as nullable, so either is a field the caller left unset
11230
+ * (`verificationLevel: enrolled ? 'passkey' : undefined` says nothing for an
11231
+ * audience that is not enrolled), and the preset's value stands. Reading it as
11232
+ * an erase would leave the send to fill the field (the account's default level),
11233
+ * never with the preset's value.
11234
+ *
11235
+ * @param {Object} preset - A NOTIFY_PRESETS bundle, in the caller's vocabulary; never modified
11236
+ * @param {Object} args - The caller's send arguments; never modified
11237
+ * @returns {Object} New send arguments
11238
+ */
11239
+ function mergePresetSend(preset, args) {
11240
+ const merged = {
11241
+ ...args,
11242
+ category: args.category || preset.category,
11243
+ delivery: args.delivery ?? preset.delivery,
11244
+ policy: { ...preset.policy }
11245
+ };
11246
+ for (const [field, value] of Object.entries(args.policy ?? {})) {
11247
+ if (value !== undefined && value !== null) merged.policy[field] = value;
11248
+ }
11249
+ const channels = args.channels || preset.channels;
11250
+ if (channels) merged.channels = [...channels];
11251
+ return merged;
11252
+ }
11253
+
11068
11254
  /**
11069
11255
  * Notify Product Module — the TENANT (sender) surface.
11070
11256
  *
11071
- * The counterpart to `sv.notify`: where that module is session-scoped and reads
11072
- * only the signed-in person's OWN inbox, this one is the account-scoped product
11073
- * surface a tenant's BACKEND drives — send, send history, recall, sender-side
11074
- * inbox reads and state, send status, receipts, and the account's Notify config.
11075
- * Every method maps to
11257
+ * The counterpart to `sv.notify`: where that module is SparkVault's own
11258
+ * first-party inbox, which a signed-in SparkVault user reads for the
11259
+ * notifications SparkVault delivered to them `in_app`, this one is the
11260
+ * account-scoped product surface a tenant's BACKEND drives — send, send
11261
+ * history, recall, sender-side inbox reads and state, send status, receipts,
11262
+ * the account's Notify config, and who its email is from.
11263
+ * A tenant reads its own recipients' feeds here (`getInbox`), never through
11264
+ * `sv.notify`. Every method maps to
11076
11265
  * `/v1/products/notify/*` and is authorized by the caller's account, so the
11077
11266
  * recipient is supplied explicitly rather than derived from a session.
11078
11267
  *
@@ -11106,49 +11295,45 @@ const BULK_MARK_STATES$1 = NOTIFY_INBOX_BULK_MARK_STATES;
11106
11295
  *
11107
11296
  * There is no preset endpoint — presets are a merge over the one send contract,
11108
11297
  * so they are applied client-side and produce an ordinary `send` request. Caller
11109
- * arguments always win over a preset's defaults; `channels` left unset lets the
11110
- * account config resolve the ladder per category.
11298
+ * arguments win over a preset's defaults wherever they state a value;
11299
+ * `channels` left unset lets the account config resolve the ladder per category.
11111
11300
  *
11112
11301
  * `alert` is the only plaintext preset: a non-confidential ping is read at a
11113
- * glance rather than behind a tap-to-view link. The other four seal.
11302
+ * glance rather than behind a tap-to-view link, on the account's ladder. The
11303
+ * other four seal, on the channels every organization's recipients are reached
11304
+ * on: `secureMessage` by email alone, `conversation`, `approval` and
11305
+ * `signatureRequest` in your Notify inbox (`in_app`) and then by email.
11114
11306
  * `approval` and `signatureRequest` verify at `identifier`: pass
11115
11307
  * `policy: { verificationLevel: 'passkey' }` explicitly when the audience is
11116
11308
  * known to be enrolled.
11309
+ *
11310
+ * Every send in the process reads this one table, so it is frozen all the way
11311
+ * down; `buildNotifyPresetSend` hands back options of the caller's own.
11117
11312
  */
11118
11313
  const NOTIFY_PRESETS = Object.freeze(Object.fromEntries(Object.keys(NOTIFY_PRESETS$1).map((name) => {
11314
+ // The contract's ladders are frozen already, so the table can carry them as they are.
11119
11315
  const { category, delivery, channels, policy } = NOTIFY_PRESETS$1[name];
11120
11316
  const preset = {
11121
11317
  category,
11122
11318
  ...(delivery ? { delivery } : {}),
11123
- ...(channels ? { channels: [...channels] } : {}),
11124
- policy: { verificationLevel: policy.verification_level, interaction: policy.interaction },
11319
+ ...(channels ? { channels } : {}),
11320
+ policy: Object.freeze({ verificationLevel: policy.verification_level, interaction: policy.interaction }),
11125
11321
  };
11126
11322
  return [name, Object.freeze(preset)];
11127
11323
  })));
11128
11324
  /**
11129
11325
  * Merge a preset's bundle UNDER the caller's arguments, yielding ordinary send
11130
- * options. Exported so a caller can inspect (or further adjust) what a preset
11131
- * would send before sending it.
11326
+ * options: the Core API's own merge (`mergePresetSend`), so a preset sends the
11327
+ * same through either. Exported so a caller can inspect (or further adjust)
11328
+ * what a preset would send before sending it: the options are the caller's own,
11329
+ * so adjusting them never reaches the preset table or any other send.
11132
11330
  */
11133
11331
  function buildNotifyPresetSend(preset, options) {
11134
11332
  const bundle = NOTIFY_PRESETS[preset];
11135
11333
  if (!bundle) {
11136
11334
  throw new ValidationError(`Unknown notify preset "${preset}" (valid: ${Object.keys(NOTIFY_PRESETS).join(', ')})`, { field: 'preset', received: preset });
11137
11335
  }
11138
- const merged = {
11139
- ...options,
11140
- category: options.category || bundle.category,
11141
- // A caller-supplied delivery wins (a sealed override of an alert is allowed);
11142
- // otherwise the preset's mode, or the sealed default when it declares none.
11143
- delivery: options.delivery ?? bundle.delivery,
11144
- policy: { ...bundle.policy, ...(options.policy ?? {}) },
11145
- };
11146
- // Only set channels when the preset declares them and the caller did not
11147
- // override — leaving it unset lets the account config resolve them per category.
11148
- const channels = options.channels || bundle.channels;
11149
- if (channels)
11150
- merged.channels = channels;
11151
- return merged;
11336
+ return mergePresetSend(bundle, options);
11152
11337
  }
11153
11338
  class NotifyProductModule {
11154
11339
  constructor(http) {
@@ -11159,8 +11344,28 @@ class NotifyProductModule {
11159
11344
  * Send a notification: seal the content, mint one single-use SparkLink per
11160
11345
  * recipient, and enqueue delivery across the resolved channel ladder.
11161
11346
  *
11162
- * `sendId` is the idempotency key. Replaying an existing one returns the stored
11163
- * send unchanged — never re-sealed, never re-delivered — flagged `idempotent`.
11347
+ * `sendId` is the idempotency key. Replaying an existing one with the same
11348
+ * request returns the stored send unchanged — never re-sealed, never
11349
+ * re-delivered — flagged `idempotent`; another request under it is refused 400
11350
+ * (`sendId` on `CreateNotifySendOptions`).
11351
+ *
11352
+ * The send speaks in your organization's name, and one that would email
11353
+ * someone goes out from your organization's own sender (`getEmailSender`) and
11354
+ * is admitted against your hourly share of sending capacity. Each refusal is
11355
+ * a thrown `SparkVaultError` whose `serviceCode` names it, made before
11356
+ * anything is sealed, charged or stored:
11357
+ *
11358
+ * | Status | `serviceCode` | `details` | Next |
11359
+ * | --- | --- | --- | --- |
11360
+ * | 403 | `NOTIFY_CHANNEL_NOT_AVAILABLE` | `{ field, channels }` | Name only `in_app` and `email` |
11361
+ * | 409 | `NOTIFY_SENDER_NAME_REQUIRED` | — | Name the organization in Settings |
11362
+ * | 409 | `NOTIFY_SENDER_NAME_RESERVED` | `{ reason: 'reserved_name' }` | Rename the organization |
11363
+ * | 409 | `HANDLE_REQUIRED` | `{ product: 'notify' }` | Choose the organization's handle in Company Settings |
11364
+ * | 429 | `NOTIFY_EMAIL_ADMISSION_LIMIT` | `{ limit, window: 'hour', resets_at }` | Wait `retryAfterMs`, then send |
11365
+ * | 503 | `EMAIL_SETUP_BUSY` | — | Retry the same send after `retryAfterMs` |
11366
+ * | 503 | `NOTIFY_EMAIL_CAPACITY_UNAVAILABLE` | — | Retry the same send |
11367
+ *
11368
+ * A replay is answered from the stored send and meets none of them again.
11164
11369
  *
11165
11370
  * @example
11166
11371
  * const send = await sv.products.notify.send({
@@ -11205,7 +11410,7 @@ class NotifyProductModule {
11205
11410
  /**
11206
11411
  * Frictionless informational ping — no verification, view-only, delivered
11207
11412
  * INLINE (plaintext) so it is read at a glance. Channels resolve from the
11208
- * account config; plaintext requires an inline-capable channel.
11413
+ * account config, narrowed to the ones that render cleartext.
11209
11414
  *
11210
11415
  * @example
11211
11416
  * await sv.products.notify.sendAlert({
@@ -11225,18 +11430,58 @@ class NotifyProductModule {
11225
11430
  async sendConversation(options) {
11226
11431
  return this.send(buildNotifyPresetSend('conversation', options));
11227
11432
  }
11228
- /** High-stakes approve/deny — identifier-verified, with `action_hash` binding. */
11433
+ /**
11434
+ * High-stakes approve/deny, identifier-verified. Pass `policy.actionHash`, the
11435
+ * SHA-256 of the thing being approved, so the signed receipt attests to THAT:
11436
+ * without it the receipt binds a digest of the grant, which no hash of your
11437
+ * own copy can match.
11438
+ *
11439
+ * @example
11440
+ * const actionHash = createHash('sha256').update(canonicalWire).digest('hex');
11441
+ * await sv.products.notify.sendApproval({
11442
+ * sendId: `wire-approval-${wire.id}`,
11443
+ * recipients: [{ id: approver.svid, email: approver.email }],
11444
+ * content: { payload: `Approve ${wire.amount} to ${wire.payee}?` },
11445
+ * policy: { actionHash },
11446
+ * });
11447
+ */
11229
11448
  async sendApproval(options) {
11230
11449
  return this.send(buildNotifyPresetSend('approval', options));
11231
11450
  }
11232
- /** Signature-on-delivery — identifier-verified, with `action_hash` binding. */
11451
+ /**
11452
+ * Signature-on-delivery, identifier-verified. Pass `policy.actionHash`, the
11453
+ * SHA-256 of the document being signed, so the signed receipt attests to THAT
11454
+ * document.
11455
+ *
11456
+ * @example
11457
+ * await sv.products.notify.sendSignatureRequest({
11458
+ * sendId: `contract-${contract.id}`,
11459
+ * recipients: [{ email: signer.email }],
11460
+ * content: { payload: contractPdfBase64, contentType: 'application/pdf' },
11461
+ * policy: { actionHash: createHash('sha256').update(contractPdfBytes).digest('hex') },
11462
+ * });
11463
+ */
11233
11464
  async sendSignatureRequest(options) {
11234
11465
  return this.send(buildNotifyPresetSend('signatureRequest', options));
11235
11466
  }
11236
11467
  // ── Inbox (sender-side) ─────────────────────────────────────────────────────
11237
11468
  /**
11238
- * Read one recipient's metadata-only feed, newest first. Rows are pointers: a
11239
- * sealed row carries only `sparklink_code`, never the content.
11469
+ * Read one recipient's feed in your Notify inbox, newest first: exactly the
11470
+ * notifications delivered to them `in_app`. The row IS the `in_app`
11471
+ * delivery: its ladder carries `in_app`, because the send named it or your
11472
+ * config resolved it and the recipient left In-app on for your site (a
11473
+ * `security` send crosses that switch), and it is listed when that step
11474
+ * runs: as the send fans out when `in_app` leads the ladder, and only when
11475
+ * the step comes due when it follows `email`. A notification whose ladder
11476
+ * carries no `in_app` (a send naming `email` alone, a recipient who switched
11477
+ * In-app off for your site on auth.sv on any send but a `security` one, one
11478
+ * their own preferences or block refused, one no channel reaches), one whose
11479
+ * `in_app` step has not delivered it (and never will once a stop ended its
11480
+ * ladder first), and the per-recipient ceiling's skip are status records
11481
+ * only: in no view, and a mark of one is refused as not found. A sealed row carries
11482
+ * the recipient's own pointer (`sparklink_code`, `pointer_url`) while its
11483
+ * grant still opens, never the content; a plaintext row carries its body.
11484
+ * Treat the answer as sensitive and keep it out of logs.
11240
11485
  *
11241
11486
  * A page can come back SHORT of `limit` yet still carry a non-null cursor —
11242
11487
  * follow the cursor; never treat a short page as the end.
@@ -11261,8 +11506,9 @@ class NotifyProductModule {
11261
11506
  }
11262
11507
  /**
11263
11508
  * Apply a terminal display state to one row (idempotent). `createdAt` MUST be
11264
- * the row's own `created_at`, round-tripped from the feed or the webhook/push
11265
- * payload — the id alone cannot address the row.
11509
+ * the row's own `created_at`, round-tripped from the feed row — the id alone
11510
+ * cannot address the row. Any mark (seen, read or archived) marks the row seen,
11511
+ * which stops its escalation.
11266
11512
  *
11267
11513
  * @example
11268
11514
  * await sv.products.notify.markInboxState(row.notification_id, {
@@ -11324,6 +11570,7 @@ class NotifyProductModule {
11324
11570
  * `getSendStatus(sendId)` for the per-recipient detail.
11325
11571
  *
11326
11572
  * Real pagination: a null `cursor` means the end of the account's history.
11573
+ * A delivery counter is null until its first increment, so it reads 0 there.
11327
11574
  *
11328
11575
  * @example
11329
11576
  * let cursor: string | undefined;
@@ -11331,7 +11578,7 @@ class NotifyProductModule {
11331
11578
  * const page = await sv.products.notify.listSends({ cursor, limit: 50 });
11332
11579
  * for (const send of page.sends) {
11333
11580
  * console.log(send.created_at, send.title, send.state,
11334
- * `${send.delivered_count ?? '?'} / ${send.recipient_count ?? '?'}`);
11581
+ * `${send.delivered_count ?? 0} / ${send.recipient_count ?? '?'}`);
11335
11582
  * }
11336
11583
  * cursor = page.cursor ?? undefined;
11337
11584
  * } while (cursor);
@@ -11348,8 +11595,9 @@ class NotifyProductModule {
11348
11595
  *
11349
11596
  * `mode: 'grant'` (the default) drops access and leaves the content intact.
11350
11597
  * `mode: 'content'` hard-burns the sealed spark so it is unreadable for
11351
- * everyone — spark-backed sends only, since an ingot send merely references the
11352
- * owner's durable vault content.
11598
+ * everyone — spark-backed sends only: an ingot send merely references the
11599
+ * owner's durable vault content, so a content recall of one is a 400, refused
11600
+ * before anything is revoked or stopped.
11353
11601
  *
11354
11602
  * Idempotent: a grant already revoked (or already consumed) counts as recalled,
11355
11603
  * so a repeated call converges rather than accumulating failures. One
@@ -11388,7 +11636,8 @@ class NotifyProductModule {
11388
11636
  // ── Status & receipts ───────────────────────────────────────────────────────
11389
11637
  /**
11390
11638
  * The sender's per-recipient delivery rollup for one send: who it reached and
11391
- * how far each recipient got. Metadata only — never the pointer or contacts.
11639
+ * how far each recipient got. Metadata only — never the pointer, and no contact
11640
+ * beyond the handle each recipient was addressed by (`recipient_id`).
11392
11641
  *
11393
11642
  * @example
11394
11643
  * const { counts } = await sv.products.notify.getSendStatus(send.send_id);
@@ -11399,10 +11648,11 @@ class NotifyProductModule {
11399
11648
  return response.data;
11400
11649
  }
11401
11650
  /**
11402
- * The account's verified-interaction receipts (portable, JWKS-verifiable
11403
- * proofs), newest first, with real pagination. An `interaction` filter can
11404
- * hand back a short or empty page while more follow, so follow `cursor` until
11405
- * it is null before concluding there are none.
11651
+ * The account's verified-interaction receipts (a ceremony's carries portable,
11652
+ * JWKS-verifiable proof; an open's is an unsigned access record), newest
11653
+ * first, with real pagination. An `interaction` filter can hand back a short
11654
+ * or empty page while more follow, so follow `cursor` until it is null before
11655
+ * concluding there are none.
11406
11656
  *
11407
11657
  * @example
11408
11658
  * const { receipts, cursor } = await sv.products.notify.listReceipts({ interaction: 'approve' });
@@ -11419,9 +11669,9 @@ class NotifyProductModule {
11419
11669
  }
11420
11670
  /**
11421
11671
  * Every receipt for one send, each attached to the recipient who produced it.
11422
- * The correlation scan is bounded: when `truncated` is true, some older
11423
- * receipts fall outside the scanned window — pass the returned `cursor` back in
11424
- * to resume the scan exactly where it stopped.
11672
+ * The walk reads the account's receipts back to the send's creation, and no
11673
+ * further. One call is bounded: when `truncated` is true it stopped first —
11674
+ * pass the returned `cursor` back in to resume exactly where it stopped.
11425
11675
  *
11426
11676
  * @example
11427
11677
  * const all: NotifySendReceipt[] = [];
@@ -11463,6 +11713,14 @@ class NotifyProductModule {
11463
11713
  * body as `X-SparkVault-Signature: hex(HMAC-SHA256(secret, rawBody))`. The
11464
11714
  * secret is WRITE-ONLY — reads report `events.secret_set`, never the value.
11465
11715
  *
11716
+ * The `email` section selects a domain of your own for your Notify email to go
11717
+ * out from. `security`, `events` and `email` are an org admin's to change: a
11718
+ * patch from anyone else naming one is refused whole, 403 `FORBIDDEN`
11719
+ * (`details: { sections, required_role: 'admin' }`). A ladder naming a channel
11720
+ * other than `in_app` and `email` is refused 403 `NOTIFY_CHANNEL_NOT_AVAILABLE`
11721
+ * (`details: { field, channels }`); a save that overlapping saves kept
11722
+ * outracing is refused 409 `CONFLICT`: reload and patch again.
11723
+ *
11466
11724
  * @example
11467
11725
  * await sv.products.notify.updateConfig({
11468
11726
  * categories: {
@@ -11482,6 +11740,35 @@ class NotifyProductModule {
11482
11740
  const response = await this.http.put(apiPath `/v1/products/notify/config`, patch);
11483
11741
  return response.data;
11484
11742
  }
11743
+ /**
11744
+ * Who your organization's Notify email is from, as the API answers it
11745
+ * (verbatim snake_case): `"{organization name}" <from_address>`, with a
11746
+ * notice naming SparkVault Notify. A reply reaches no one when the email goes
11747
+ * out from the handle host, or from a domain of your own that is set up as a
11748
+ * help-desk web host or receives the help desk's email; from a domain that
11749
+ * only sends, a reply goes wherever that domain's own MX records route it.
11750
+ *
11751
+ * - `ready`: the email goes out from `from_address`, on `sending_host`: the
11752
+ * domain `email.sending_domain` selects while it serves sending (its
11753
+ * ownership verified and its sending ready), else the organization's handle
11754
+ * host under send.sv, `handle_host`, which it falls back to the moment the
11755
+ * domain stops serving.
11756
+ * - `handle_required`: the organization has not chosen its handle, so a send
11757
+ * that would email someone is refused 409 `HANDLE_REQUIRED` until it does.
11758
+ * - `platform_sender`: SparkVault's own account, whose Notify email is
11759
+ * platform mail.
11760
+ *
11761
+ * `domain_readiness` is the selected domain's readiness flags, null with no
11762
+ * selection or while the organization does not hold the domain's claim.
11763
+ *
11764
+ * @example
11765
+ * const sender = await sv.products.notify.getEmailSender();
11766
+ * if (sender.state === 'handle_required') promptForHandle();
11767
+ */
11768
+ async getEmailSender() {
11769
+ const response = await this.http.get(apiPath `/v1/products/notify/email-sender`);
11770
+ return response.data;
11771
+ }
11485
11772
  }
11486
11773
  /**
11487
11774
  * Map the camelCase option bag onto the send body. Undefined fields drop out at
@@ -11508,6 +11795,7 @@ function toSendBody(options) {
11508
11795
  verification_level: options.policy.verificationLevel,
11509
11796
  interaction: options.policy.interaction,
11510
11797
  reveal_freshness_minutes: options.policy.revealFreshnessMinutes,
11798
+ action_hash: options.policy.actionHash,
11511
11799
  }
11512
11800
  : undefined,
11513
11801
  channels: options.channels,
@@ -11954,7 +12242,12 @@ function stagingRefusalOf(error) {
11954
12242
  function cancelledError() {
11955
12243
  return new UploadApiError('Upload cancelled', 'cancelled', 0);
11956
12244
  }
11957
- /** Refuse a transfer where the browser's XMLHttpRequest is missing: a chunk's upload progress needs it. */
12245
+ /**
12246
+ * Refuse a transfer where the browser's XMLHttpRequest is missing (a server
12247
+ * process: Node has fetch and no XMLHttpRequest): a chunk's upload progress
12248
+ * needs it. A flow that stages its upload with Core first checks this before
12249
+ * the staging request, so a run that cannot transfer stages nothing.
12250
+ */
11958
12251
  function assertBrowserTransfer() {
11959
12252
  if (typeof XMLHttpRequest === 'undefined') {
11960
12253
  throw new UploadApiError('XMLHttpRequest is required for browser uploads', 'environment_unsupported', 0);
@@ -15342,7 +15635,8 @@ class VaultUploadModule {
15342
15635
  });
15343
15636
  }
15344
15637
  catch {
15345
- // Error already handled by callbacks or will use server redirect
15638
+ // The host's onError or onCancel has already received the outcome;
15639
+ // a click handler has no caller to reject to.
15346
15640
  }
15347
15641
  };
15348
15642
  return attachClickHandler(selector, handleClick);
@@ -15564,7 +15858,8 @@ class VaultsModule {
15564
15858
  return mapVaultDetail(response.data);
15565
15859
  }
15566
15860
  /**
15567
- * Get a vault's public-sharing configuration.
15861
+ * Get a vault's public-sharing configuration. Every sharing write below
15862
+ * answers the same configuration as that write left it.
15568
15863
  *
15569
15864
  * @example
15570
15865
  * const sharing = await sv.vaults.getSharingConfig('vlt_abc');
@@ -15654,7 +15949,9 @@ class VaultsModule {
15654
15949
  };
15655
15950
  }
15656
15951
  /**
15657
- * Get a vault's upload-channel configuration.
15952
+ * Get a vault's upload-channel configuration. Every upload write below
15953
+ * answers the same configuration as that write left it: both channels, the
15954
+ * shared settings, and the portal's URL while the portal is on.
15658
15955
  *
15659
15956
  * @example
15660
15957
  * const upload = await sv.vaults.getUploadConfig('vlt_abc');
@@ -15722,17 +16019,7 @@ class VaultsModule {
15722
16019
  throw new ValidationError('VMK is required');
15723
16020
  }
15724
16021
  const response = await this.http.post(apiPath `/v1/vaults/${id}/upload/${channel}/${action}`, action === 'enable' ? { vmk } : undefined);
15725
- const d = response.data;
15726
- return {
15727
- vaultId: d.vault_id,
15728
- uploadPortalEnabled: d.upload_portal_enabled ?? (channel === 'portal' && action === 'enable'),
15729
- uploadPortalEnabledAt: channel === 'portal' && action === 'enable' ? d.enabled_at ?? null : null,
15730
- uploadWidgetEnabled: d.upload_widget_enabled ?? (channel === 'widget' && action === 'enable'),
15731
- uploadWidgetEnabledAt: channel === 'widget' && action === 'enable' ? d.enabled_at ?? null : null,
15732
- maxSizeBytes: null,
15733
- notificationEmail: null,
15734
- portalUrl: d.portal_url,
15735
- };
16022
+ return mapUploadSettings(response.data);
15736
16023
  }
15737
16024
  validateCreateOptions(options) {
15738
16025
  // A name's length is Core's to decide (it answers a ValidationError naming
@@ -16695,7 +16982,10 @@ class IngotsModule {
16695
16982
  * `upload_received_publishing`: every byte is received, and the server
16696
16983
  * finishes the publication on its own, so never upload the file again; a
16697
16984
  * caller that kept the session (`onSessionCreated`) learns what became of
16698
- * it with {@link resumeUpload}.
16985
+ * it with {@link resumeUpload}. A chunk's upload progress needs the
16986
+ * browser's XMLHttpRequest: where there is none (a Node server) it rejects
16987
+ * with code `environment_unsupported` before any request; a server sends
16988
+ * the bytes over tus to `uploadUrl` itself.
16699
16989
  *
16700
16990
  * @param options.signal - Cancels this transfer (it rejects with code
16701
16991
  * `cancelled`); other transfers carry on.
@@ -16784,7 +17074,10 @@ class IngotsModule {
16784
17074
  * any way but one the server received whole ({@link isReceivedUploadFailure}:
16785
17075
  * the server publishes or ends that one on its own) is given up: the end of
16786
17076
  * it with the file its create made ({@link endUpload}) starts as it
16787
- * rejects, without holding up its own error.
17077
+ * rejects, without holding up its own error. It needs the browser's
17078
+ * XMLHttpRequest, as {@link sendUpload} does: in a server process it
17079
+ * rejects with code `environment_unsupported` before any request, so no
17080
+ * create stages an ingot it cannot send.
16788
17081
  *
16789
17082
  * @example
16790
17083
  * const ingot = await sv.ingots.upload(unsealed, {
@@ -16797,6 +17090,7 @@ class IngotsModule {
16797
17090
  throw new ValidationError('Provide folder or folderId, not both');
16798
17091
  }
16799
17092
  const name = options.name ?? getBlobName(options.file);
17093
+ assertBrowserTransfer();
16800
17094
  const created = await this.requestUploadSession(vault, {
16801
17095
  name,
16802
17096
  content_type: sentContentType(options),
@@ -16833,7 +17127,8 @@ class IngotsModule {
16833
17127
  /**
16834
17128
  * Replace an existing ingot's content (high-level flow). Rejects as
16835
17129
  * {@link upload} does, a replacement another upload of the same ingot
16836
- * superseded included (`upload_refused`).
17130
+ * superseded included (`upload_refused`), and `environment_unsupported`
17131
+ * before the replacement is staged where there is no XMLHttpRequest.
16837
17132
  *
16838
17133
  * @example
16839
17134
  * await sv.ingots.replace(unsealed, 'ing_abc', { file: updatedFile });
@@ -16844,6 +17139,7 @@ class IngotsModule {
16844
17139
  const id = requireResourceId(ingotId, 'ingotId');
16845
17140
  const name = options.name ?? getBlobName(options.file);
16846
17141
  const contentType = sentContentType(options);
17142
+ assertBrowserTransfer();
16847
17143
  const response = await this.http.put(apiPath `/v1/vaults/${vaultId}/ingots/${id}`, {
16848
17144
  name,
16849
17145
  // Omitted, Core keeps the ingot's stored type (ReplaceIngotOptions.contentType).
@@ -16911,7 +17207,9 @@ class IngotsModule {
16911
17207
  return mapIngot(response.data);
16912
17208
  }
16913
17209
  /**
16914
- * List ingots in an unsealed vault.
17210
+ * List ingots in an unsealed vault, one page at a time in the vault index's
17211
+ * order: follow `nextCursor`. `sortBy` orders only the page answered; for
17212
+ * one order across a vault, search or list a folder's contents.
16915
17213
  *
16916
17214
  * @example
16917
17215
  * const { ingots } = await sv.ingots.list(unsealed);
@@ -17555,11 +17853,16 @@ function validateEntropyRequest(bytes, format) {
17555
17853
  /**
17556
17854
  * Notify Module
17557
17855
  *
17558
- * The signed-in user's first-party Notify surface: their own metadata-only
17559
- * inbox. The recipient is ALWAYS derived from the session on the server — no
17560
- * method takes a `recipient_id`, and any account/recipient a caller might try
17561
- * to supply is ignored. This mirrors `@sparkvault/sdk-mobile`'s notify client;
17562
- * device push registration is intentionally omitted (Expo-only on mobile).
17856
+ * SparkVault's first-party Notify surface: the metadata-only inbox of a user
17857
+ * signed in to SparkVault itself (a Core session JWT; an API key or an
17858
+ * identity-only token is refused), holding the notifications SparkVault
17859
+ * delivered to them `in_app`, plus this browser's Web Push registration. It is
17860
+ * not a tenant's inbox for its own end users: a tenant reads its recipients'
17861
+ * feeds with `sv.products.notify.getInbox`. The recipient is ALWAYS derived
17862
+ * from the session on the server — no method takes a `recipient_id`, and any
17863
+ * account/recipient a caller might try to supply is ignored. This mirrors
17864
+ * `@sparkvault/sdk-mobile`'s notify client; device push registration is
17865
+ * intentionally omitted (Expo-only on mobile).
17563
17866
  */
17564
17867
  const MARK_STATES = NOTIFY_INBOX_MARK_STATES;
17565
17868
  const BULK_MARK_STATES = NOTIFY_INBOX_BULK_MARK_STATES;
@@ -17569,6 +17872,17 @@ const BULK_MARK_STATES = NOTIFY_INBOX_BULK_MARK_STATES;
17569
17872
  * inbox deeper than the bound finishes on a second call (the drain is idempotent).
17570
17873
  */
17571
17874
  const MARK_ALL_MAX_PAGES = 100;
17875
+ /**
17876
+ * Whether a browser subscription was made against `key`. One that reports no
17877
+ * key at all is treated as bound to another: nothing proves it can deliver.
17878
+ */
17879
+ function isBoundToKey(subscription, key) {
17880
+ const bound = subscription.options?.applicationServerKey;
17881
+ if (!bound)
17882
+ return false;
17883
+ const bytes = new Uint8Array(bound);
17884
+ return bytes.length === key.length && bytes.every((byte, index) => byte === key[index]);
17885
+ }
17572
17886
  /** Normalize a PushSubscription (or its JSON) to the server's wire shape. */
17573
17887
  function toSubscriptionInput(subscription) {
17574
17888
  const json = typeof subscription.toJSON === 'function'
@@ -17714,6 +18028,48 @@ class NotifyModule {
17714
18028
  const response = await this.http.get(apiPath `/v1/me/notifications/web-push/key`);
17715
18029
  return response.data;
17716
18030
  }
18031
+ /**
18032
+ * The VAPID public key the server signs every push with, as the bytes a
18033
+ * browser subscription is bound to; null while no keypair is provisioned.
18034
+ */
18035
+ async serverKey() {
18036
+ const key = await this.getWebPushKey();
18037
+ if (!key.configured || !key.vapid_public_key) {
18038
+ return null;
18039
+ }
18040
+ const bytes = base64urlToBytes(key.vapid_public_key);
18041
+ if (bytes === null) {
18042
+ throw new SparkVaultError('The server returned a Web Push key that is not base64url', 'invalid_response');
18043
+ }
18044
+ return bytes;
18045
+ }
18046
+ /**
18047
+ * This browser's Web Push state, read without prompting, subscribing or
18048
+ * registering anything: `subscribed` only when the browser holds a
18049
+ * subscription made for the key the server signs with now. One made for
18050
+ * another key reads `not_subscribed`: its push service refuses every push
18051
+ * signed with the current key, and `subscribeWebPush` replaces it. Read it to
18052
+ * show whether this browser's notifications are on.
18053
+ *
18054
+ * @example
18055
+ * const registration = await navigator.serviceWorker.getRegistration();
18056
+ * const { status } = await sv.notify.getWebPushStatus({ serviceWorkerRegistration: registration });
18057
+ */
18058
+ async getWebPushStatus(options = {}) {
18059
+ if (!this.isWebPushSupported()) {
18060
+ return { status: 'not_supported' };
18061
+ }
18062
+ const key = await this.serverKey();
18063
+ if (key === null) {
18064
+ return { status: 'not_configured' };
18065
+ }
18066
+ const held = options.serviceWorkerRegistration
18067
+ ? await options.serviceWorkerRegistration.pushManager.getSubscription()
18068
+ : null;
18069
+ return held && isBoundToKey(held, key)
18070
+ ? { status: 'subscribed', subscription: held }
18071
+ : { status: 'not_subscribed' };
18072
+ }
17717
18073
  /**
17718
18074
  * Register (or refresh) a browser push subscription for the signed-in user.
17719
18075
  * Accepts a live PushSubscription or its JSON shape.
@@ -17739,6 +18095,12 @@ class NotifyModule {
17739
18095
  * permission denied) so a host can branch on the outcome. Call it from a user
17740
18096
  * gesture (permission prompts require one).
17741
18097
  *
18098
+ * A subscription the browser holds for the current key is kept
18099
+ * (`already_subscribed`); one made for a previous key can never deliver
18100
+ * again, so it is removed and replaced (`subscribed`). Enabling again is
18101
+ * therefore how a browser recovers after the platform's key changes, and
18102
+ * `getWebPushStatus` reads such a browser as `not_subscribed` until it does.
18103
+ *
17742
18104
  * @example
17743
18105
  * const reg = await navigator.serviceWorker.register('/sw.js');
17744
18106
  * const { status } = await sv.notify.subscribeWebPush({ serviceWorkerRegistration: reg });
@@ -17751,15 +18113,11 @@ class NotifyModule {
17751
18113
  if (!registration || typeof registration.pushManager?.subscribe !== 'function') {
17752
18114
  throw new ValidationError('serviceWorkerRegistration with a pushManager is required');
17753
18115
  }
17754
- const key = await this.getWebPushKey();
17755
- if (!key.configured || !key.vapid_public_key) {
17756
- return { status: 'not_configured' };
17757
- }
17758
- // Checked before the permission prompt: a key the browser cannot use must
18116
+ // Read before the permission prompt: a key the browser cannot use must
17759
18117
  // never cost the user a prompt.
17760
- const applicationServerKey = base64urlToBytes(key.vapid_public_key);
18118
+ const applicationServerKey = await this.serverKey();
17761
18119
  if (applicationServerKey === null) {
17762
- throw new SparkVaultError('The server returned a Web Push key that is not base64url', 'invalid_response');
18120
+ return { status: 'not_configured' };
17763
18121
  }
17764
18122
  if (Notification.permission === 'denied') {
17765
18123
  return { status: 'permission_denied' };
@@ -17770,9 +18128,14 @@ class NotifyModule {
17770
18128
  return { status: 'permission_denied' };
17771
18129
  }
17772
18130
  }
17773
- // Reuse an existing subscription if present; browsers return the same one,
17774
- // but registering again refreshes the server TTL.
17775
- const existing = await registration.pushManager.getSubscription();
18131
+ // A subscription made against the current key is reused: registering it
18132
+ // again refreshes its server TTL. One made against another key is dead — its
18133
+ // push service refuses every push signed with this one — so it is replaced.
18134
+ const held = await registration.pushManager.getSubscription();
18135
+ const existing = held && isBoundToKey(held, applicationServerKey) ? held : null;
18136
+ if (held && !existing) {
18137
+ await this.dropDeadSubscription(held);
18138
+ }
17776
18139
  const subscription = existing ??
17777
18140
  (await registration.pushManager.subscribe({
17778
18141
  userVisibleOnly: true,
@@ -17781,6 +18144,23 @@ class NotifyModule {
17781
18144
  await this.registerWebPushSubscription(subscription);
17782
18145
  return { status: existing ? 'already_subscribed' : 'subscribed', subscription };
17783
18146
  }
18147
+ /**
18148
+ * Retire a browser subscription bound to a key the server no longer signs
18149
+ * with: the server forgets its endpoint first (still authenticated, and the
18150
+ * push service would otherwise refuse that endpoint's every push without it
18151
+ * ever being pruned), then the browser drops it, which a subscribe against the
18152
+ * new key needs. A failure stops here with nothing half-done, so enabling
18153
+ * again starts from the same state.
18154
+ *
18155
+ * `unsubscribe()` resolves false only when the subscription is already gone
18156
+ * (another tab dropped it first), which leaves the browser as a subscribe
18157
+ * needs it; a browser that kept one refuses that subscribe outright
18158
+ * (InvalidStateError), so a kept subscription is never reused unseen.
18159
+ */
18160
+ async dropDeadSubscription(subscription) {
18161
+ await this.unsubscribeWebPushEndpoint(subscription.endpoint);
18162
+ await subscription.unsubscribe();
18163
+ }
17784
18164
  /**
17785
18165
  * Disable Web Push on this device: unsubscribe the browser subscription and
17786
18166
  * remove it server-side. Safe to call when not subscribed (returns false).
@@ -17934,7 +18314,7 @@ class SparkVault {
17934
18314
  }
17935
18315
  /** Get the SDK version */
17936
18316
  static get version() {
17937
- return '12.0.5';
18317
+ return '13.0.1';
17938
18318
  }
17939
18319
  }
17940
18320
  if (typeof window !== 'undefined') {
@@ -17944,5 +18324,5 @@ if (typeof window !== 'undefined') {
17944
18324
  window.SparkVault = instance ?? SparkVault;
17945
18325
  }
17946
18326
 
17947
- export { AuthenticationError, AuthorizationError, EntropyModule, FoldersModule, IdentityModule, IdentityProviderError, IngotsModule, NAME_CONFLICT_POLICIES, NOTIFY_PRESETS, NetworkError, NotifyModule, NotifyProductModule, NotifySubscriptionRequiredError, PlanRequiredError, PopupBlockedError, ProductsModule, QuotaExceededError, SparkVault, SparkVaultError, SparksModule, TimeoutError, UserCancelledError, ValidationError, VaultsModule, buildNotifyPresetSend, SparkVault as default, fetchDownload, isReceivedUploadFailure, logger, setDebugMode };
18327
+ export { AuthenticationError, AuthorizationError, EntropyModule, FoldersModule, IdentityModule, IdentityProviderError, IngotsModule, NAME_CONFLICT_POLICIES, NOTIFY_PRESETS, NetworkError, NotifyModule, NotifyProductModule, NotifySubscriptionRequiredError, PlanRequiredError, PopupBlockedError, ProductsModule, QuotaExceededError, SparkVault, SparkVaultError, SparksModule, TimeoutError, UnauthorizedError, UserCancelledError, ValidationError, VaultsModule, buildNotifyPresetSend, SparkVault as default, fetchDownload, isReceivedUploadFailure, logger, setDebugMode };
17948
18328
  //# sourceMappingURL=index.mjs.map