@sparkvault/sdk-js 7.0.0 → 7.0.2

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/config.d.ts CHANGED
@@ -16,6 +16,11 @@ export interface SparkVaultConfig {
16
16
  getAccessToken?: () => string | null | Promise<string | null>;
17
17
  /** Optional API key for server-side SDK use. */
18
18
  apiKey?: string;
19
+ /**
20
+ * OIDC client id registered for this account. Required only for FedCM
21
+ * one-click sign-in (`signInWithFedcm()`), which asserts to a registered RP.
22
+ */
23
+ clientId?: string;
19
24
  /** Request timeout in milliseconds (default: 30000) */
20
25
  timeout?: number;
21
26
  /**
@@ -43,6 +48,7 @@ export interface ResolvedConfig {
43
48
  accessToken?: string;
44
49
  getAccessToken?: () => string | null | Promise<string | null>;
45
50
  apiKey?: string;
51
+ clientId?: string;
46
52
  preloadConfig: boolean;
47
53
  backdropBlur: boolean;
48
54
  allowedDownloadHostPatterns: RegExp[];
package/dist/index.d.ts CHANGED
@@ -16,6 +16,11 @@ interface SparkVaultConfig {
16
16
  getAccessToken?: () => string | null | Promise<string | null>;
17
17
  /** Optional API key for server-side SDK use. */
18
18
  apiKey?: string;
19
+ /**
20
+ * OIDC client id registered for this account. Required only for FedCM
21
+ * one-click sign-in (`signInWithFedcm()`), which asserts to a registered RP.
22
+ */
23
+ clientId?: string;
19
24
  /** Request timeout in milliseconds (default: 30000) */
20
25
  timeout?: number;
21
26
  /**
@@ -43,6 +48,7 @@ interface ResolvedConfig {
43
48
  accessToken?: string;
44
49
  getAccessToken?: () => string | null | Promise<string | null>;
45
50
  apiKey?: string;
51
+ clientId?: string;
46
52
  preloadConfig: boolean;
47
53
  backdropBlur: boolean;
48
54
  allowedDownloadHostPatterns: RegExp[];
@@ -307,6 +313,30 @@ declare class IdentityModule {
307
313
  * @returns An absolute URL on the configured `portalBaseUrl` (default https://auth.sv).
308
314
  */
309
315
  portalUrl(options?: PortalUrlOptions): string;
316
+ /**
317
+ * One-click sign-in through the browser's native FedCM account chooser.
318
+ *
319
+ * When the person is already signed into auth.sv (carrying the SSO session),
320
+ * the browser surfaces a "Continue as …" prompt with no popup, redirect, or
321
+ * typing. Requires a registered `clientId` in the SDK config and a browser
322
+ * with FedCM support — callers should feature-detect with
323
+ * `IdentityModule.isFedcmAvailable()` and fall back to `verify()` otherwise.
324
+ *
325
+ * @returns the verified result, or `null` when the browser has no FedCM
326
+ * support (so the caller can fall back). Throws `UserCancelledError` when the
327
+ * person dismisses the chooser.
328
+ *
329
+ * @example
330
+ * const result = (await sv.products.identity.isFedcmAvailable())
331
+ * ? await sv.products.identity.signInWithFedcm().catch(() => sv.products.identity.verify())
332
+ * : await sv.products.identity.verify();
333
+ */
334
+ signInWithFedcm(options?: {
335
+ mediation?: 'optional' | 'required' | 'silent';
336
+ nonce?: string;
337
+ }): Promise<VerifyResult | null>;
338
+ /** Whether this browser exposes the FedCM API (`navigator.credentials` + IdentityCredential). */
339
+ static isFedcmAvailable(): boolean;
310
340
  /**
311
341
  * Verify user identity.
312
342
  *
@@ -22,7 +22,12 @@ export interface PasskeyResult {
22
22
  result?: VerifyResult;
23
23
  error?: string;
24
24
  errorType?: 'cancelled' | 'not_found' | 'not_allowed' | 'popup_blocked' | 'unknown';
25
- /** Machine-readable API error code (e.g. 'identity_locked'). */
25
+ /**
26
+ * Machine-readable API error code (e.g. 'identity_locked',
27
+ * 'identity_trial_exhausted'). Forwarded unchanged from the inline ceremony
28
+ * and the popup so the renderer can route blocked-Identity codes to the
29
+ * dedicated interstitial.
30
+ */
26
31
  errorCode?: string;
27
32
  }
28
33
  /**
@@ -16,6 +16,9 @@ export interface SparkLinkSendResult {
16
16
  /** Login-ceremony handle used to reclaim the result if the WebSocket is lost. */
17
17
  kindling?: string;
18
18
  error?: string;
19
+ /** Machine-readable API error code (e.g. 'identity_trial_exhausted'); routes a
20
+ * blocked Identity to the terminal interstitial instead of a retryable error. */
21
+ errorCode?: string;
19
22
  }
20
23
  /**
21
24
  * Handles SparkLink sending
@@ -15,6 +15,13 @@ export interface TotpSendResult {
15
15
  kindling?: string;
16
16
  expiresAt?: number;
17
17
  error?: string;
18
+ /**
19
+ * Machine-readable API error code (e.g. 'identity_trial_exhausted'). Set when
20
+ * the send-boundary gate refuses to dispatch a code because the owner's
21
+ * Identity access is blocked, so the renderer can show the interstitial
22
+ * instead of a generic "failed to send" error.
23
+ */
24
+ errorCode?: string;
18
25
  }
19
26
  /**
20
27
  * Result of TOTP verify operation
@@ -37,6 +37,30 @@ export declare class IdentityModule {
37
37
  * @returns An absolute URL on the configured `portalBaseUrl` (default https://auth.sv).
38
38
  */
39
39
  portalUrl(options?: PortalUrlOptions): string;
40
+ /**
41
+ * One-click sign-in through the browser's native FedCM account chooser.
42
+ *
43
+ * When the person is already signed into auth.sv (carrying the SSO session),
44
+ * the browser surfaces a "Continue as …" prompt with no popup, redirect, or
45
+ * typing. Requires a registered `clientId` in the SDK config and a browser
46
+ * with FedCM support — callers should feature-detect with
47
+ * `IdentityModule.isFedcmAvailable()` and fall back to `verify()` otherwise.
48
+ *
49
+ * @returns the verified result, or `null` when the browser has no FedCM
50
+ * support (so the caller can fall back). Throws `UserCancelledError` when the
51
+ * person dismisses the chooser.
52
+ *
53
+ * @example
54
+ * const result = (await sv.products.identity.isFedcmAvailable())
55
+ * ? await sv.products.identity.signInWithFedcm().catch(() => sv.products.identity.verify())
56
+ * : await sv.products.identity.verify();
57
+ */
58
+ signInWithFedcm(options?: {
59
+ mediation?: 'optional' | 'required' | 'silent';
60
+ nonce?: string;
61
+ }): Promise<VerifyResult | null>;
62
+ /** Whether this browser exposes the FedCM API (`navigator.credentials` + IdentityCredential). */
63
+ static isFedcmAvailable(): boolean;
40
64
  /**
41
65
  * Verify user identity.
42
66
  *
@@ -113,6 +113,14 @@ export declare class IdentityRenderer {
113
113
  * opening a popup would be blocked.
114
114
  */
115
115
  private handleMethodSelect;
116
+ /**
117
+ * If the error code means the site owner's Identity access is blocked
118
+ * (trial exhausted/expired, or paid capacity wall), render the dedicated
119
+ * end-user interstitial and return true. The message is intentionally
120
+ * generic so no billing internals leak to the end user. Returns false for
121
+ * any other code so the caller falls through to its normal handling.
122
+ */
123
+ private renderBlockedInterstitial;
116
124
  private handleTotpSubmit;
117
125
  private handleSecondFactorSubmit;
118
126
  private handleTotpResend;
@@ -181,6 +181,12 @@ export interface SdkConfig {
181
181
  methods: MethodId[];
182
182
  /** WebSocket domain for SparkLink push notifications (e.g., 'ws.sparkvault.com') */
183
183
  wsDomain?: string;
184
+ /** Cross-domain SSO posture. `enabled`: this account participates in silent
185
+ * SSO. `forced`: auth.sv is the only sign-in surface (no local widget UI). */
186
+ sso?: {
187
+ enabled: boolean;
188
+ forced: boolean;
189
+ };
184
190
  }
185
191
  /** Method metadata for SDK rendering (static lookup) */
186
192
  export interface MethodMetadata {
@@ -4,6 +4,15 @@
4
4
  * Professional enterprise-quality error display with clear visual hierarchy.
5
5
  */
6
6
  import type { View } from './base';
7
+ /**
8
+ * Error codes that mean the site owner's Identity access is blocked — the
9
+ * free trial was exhausted or expired, or a paid plan hit its capacity wall.
10
+ * The end user can do nothing about these, so the ErrorView renders a friendly,
11
+ * non-leaky interstitial (no "Try Again", no debug code badge) exactly like
12
+ * `identity_locked`. The owner is nudged to subscribe through their own
13
+ * dashboard, never through this end-user surface.
14
+ */
15
+ export declare const IDENTITY_BLOCKED_ERROR_CODES: readonly ["identity_trial_exhausted", "identity_trial_expired", "identity_capacity_blocked"];
7
16
  export interface ErrorViewProps {
8
17
  message: string;
9
18
  code: string;
@@ -171,6 +171,7 @@ function resolveConfig(config) {
171
171
  accessToken: config.accessToken,
172
172
  getAccessToken: config.getAccessToken,
173
173
  apiKey: config.apiKey,
174
+ clientId: config.clientId,
174
175
  preloadConfig: config.preloadConfig !== false, // Default: true
175
176
  backdropBlur: config.backdropBlur !== false, // Default: true
176
177
  allowedDownloadHostPatterns: config.allowedDownloadHostPatterns ?? DEFAULT_ALLOWED_DOWNLOAD_HOST_PATTERNS,
@@ -1715,9 +1716,11 @@ class TotpHandler {
1715
1716
  }
1716
1717
  catch (error) {
1717
1718
  const message = error instanceof Error ? error.message : 'Failed to send code';
1719
+ const errorCode = error instanceof SparkVaultError ? error.code : undefined;
1718
1720
  return {
1719
1721
  success: false,
1720
1722
  error: message,
1723
+ errorCode,
1721
1724
  };
1722
1725
  }
1723
1726
  }
@@ -1748,9 +1751,11 @@ class TotpHandler {
1748
1751
  }
1749
1752
  catch (error) {
1750
1753
  const message = error instanceof Error ? error.message : 'Failed to resend code';
1754
+ const errorCode = error instanceof SparkVaultError ? error.code : undefined;
1751
1755
  return {
1752
1756
  success: false,
1753
1757
  error: `Failed to resend: ${message}`,
1758
+ errorCode,
1754
1759
  };
1755
1760
  }
1756
1761
  }
@@ -1852,6 +1857,7 @@ class SparkLinkHandler {
1852
1857
  return {
1853
1858
  success: false,
1854
1859
  error: message,
1860
+ errorCode: error instanceof SparkVaultError ? error.code : undefined,
1855
1861
  };
1856
1862
  }
1857
1863
  }
@@ -5181,6 +5187,22 @@ class SparkLinkWaitingView {
5181
5187
  *
5182
5188
  * Professional enterprise-quality error display with clear visual hierarchy.
5183
5189
  */
5190
+ /**
5191
+ * Error codes that mean the site owner's Identity access is blocked — the
5192
+ * free trial was exhausted or expired, or a paid plan hit its capacity wall.
5193
+ * The end user can do nothing about these, so the ErrorView renders a friendly,
5194
+ * non-leaky interstitial (no "Try Again", no debug code badge) exactly like
5195
+ * `identity_locked`. The owner is nudged to subscribe through their own
5196
+ * dashboard, never through this end-user surface.
5197
+ */
5198
+ const IDENTITY_BLOCKED_ERROR_CODES = [
5199
+ 'identity_trial_exhausted',
5200
+ 'identity_trial_expired',
5201
+ 'identity_capacity_blocked',
5202
+ ];
5203
+ function isBlockedCode(code) {
5204
+ return IDENTITY_BLOCKED_ERROR_CODES.includes(code);
5205
+ }
5184
5206
  class ErrorView {
5185
5207
  constructor(props) {
5186
5208
  this.retryButton = null;
@@ -5204,15 +5226,26 @@ class ErrorView {
5204
5226
  // title, no debug error-code badge, and no "Try Again" (retrying the
5205
5227
  // login cannot clear a lockdown — only managing it at auth.sv can).
5206
5228
  const isLocked = this.props.code === 'identity_locked';
5229
+ // A blocked Identity (trial exhausted/expired, or paid capacity wall) is
5230
+ // likewise terminal for the end user: retrying cannot restore access, only
5231
+ // the site owner subscribing can. Show a friendly, non-leaky interstitial.
5232
+ const isBlocked = isBlockedCode(this.props.code);
5233
+ // Both states are terminal — suppress the debug code badge and the retry
5234
+ // button, leaving only Close.
5235
+ const isTerminal = isLocked || isBlocked;
5207
5236
  const title = document.createElement('h3');
5208
5237
  title.className = 'sv-error-title';
5209
- title.textContent = isLocked ? 'This SparkVault Identity is locked' : 'Something went wrong';
5238
+ title.textContent = isLocked
5239
+ ? 'This SparkVault Identity is locked'
5240
+ : isBlocked
5241
+ ? 'Sign-in unavailable'
5242
+ : 'Something went wrong';
5210
5243
  const message = document.createElement('p');
5211
5244
  message.className = 'sv-error-message';
5212
5245
  message.textContent = this.props.message;
5213
5246
  contentSection.appendChild(title);
5214
5247
  contentSection.appendChild(message);
5215
- if (!isLocked) {
5248
+ if (!isTerminal) {
5216
5249
  // Error code badge — useful for debugging genuine errors only.
5217
5250
  const codeBadge = document.createElement('div');
5218
5251
  codeBadge.className = 'sv-error-code-badge';
@@ -5229,7 +5262,7 @@ class ErrorView {
5229
5262
  // Action buttons with proper styling
5230
5263
  const buttonContainer = div();
5231
5264
  buttonContainer.className = 'sv-error-actions';
5232
- if (!isLocked) {
5265
+ if (!isTerminal) {
5233
5266
  this.retryButton = document.createElement('button');
5234
5267
  this.retryButton.className = 'sv-btn sv-btn-error-primary';
5235
5268
  this.retryButton.textContent = 'Try Again';
@@ -5696,6 +5729,13 @@ class OriginNotAllowedView {
5696
5729
  * Orchestrates view state and rendering for identity verification flows.
5697
5730
  * Uses extracted handlers for TOTP and Passkey operations.
5698
5731
  */
5732
+ /**
5733
+ * End-user copy for a blocked Identity. Intentionally generic — it never names
5734
+ * the trial, billing, usage, or any owner-facing internal. The site owner is
5735
+ * nudged to subscribe through their own dashboard and emails, not here.
5736
+ */
5737
+ const IDENTITY_BLOCKED_END_USER_MESSAGE = "This app's sign-in is temporarily unavailable. Please contact the site owner.";
5738
+ const BLOCKED_ERROR_CODES = new Set(IDENTITY_BLOCKED_ERROR_CODES);
5699
5739
  const SPARKLINK_CSP_BLOCKED_ERROR = {
5700
5740
  message: [
5701
5741
  'Connection blocked by security policy.',
@@ -6229,6 +6269,8 @@ class IdentityRenderer {
6229
6269
  this.setState({ view: 'loading' });
6230
6270
  const result = await this.totpHandler.send(totpMethod);
6231
6271
  if (!result.success) {
6272
+ if (this.renderBlockedInterstitial(result.errorCode))
6273
+ return;
6232
6274
  this.setState({
6233
6275
  view: 'error',
6234
6276
  message: result.error ?? 'Failed to send code',
@@ -6287,6 +6329,12 @@ class IdentityRenderer {
6287
6329
  const result = await this.sparkLinkHandler.send(wsResult.connectionId);
6288
6330
  if (!result.success) {
6289
6331
  this.cleanupSparkLink();
6332
+ // A blocked Identity (trial exhausted/expired, paid capacity) is
6333
+ // terminal — show the "sign-in unavailable" interstitial, not a
6334
+ // retryable "Try Again" that invites retrying a permanently-blocked
6335
+ // login. Mirrors the totp send path.
6336
+ if (this.renderBlockedInterstitial(result.errorCode))
6337
+ return;
6290
6338
  this.setState({
6291
6339
  view: 'error',
6292
6340
  message: result.error ?? 'Failed to send SparkLink',
@@ -6324,6 +6372,24 @@ class IdentityRenderer {
6324
6372
  this.handleErrorWithRecovery(error, 'unknown');
6325
6373
  }
6326
6374
  }
6375
+ /**
6376
+ * If the error code means the site owner's Identity access is blocked
6377
+ * (trial exhausted/expired, or paid capacity wall), render the dedicated
6378
+ * end-user interstitial and return true. The message is intentionally
6379
+ * generic so no billing internals leak to the end user. Returns false for
6380
+ * any other code so the caller falls through to its normal handling.
6381
+ */
6382
+ renderBlockedInterstitial(code) {
6383
+ if (!code || !BLOCKED_ERROR_CODES.has(code)) {
6384
+ return false;
6385
+ }
6386
+ this.setState({
6387
+ view: 'error',
6388
+ code,
6389
+ message: IDENTITY_BLOCKED_END_USER_MESSAGE,
6390
+ });
6391
+ return true;
6392
+ }
6327
6393
  async handleTotpSubmit(code) {
6328
6394
  if (this.viewState.view !== 'totp-verify')
6329
6395
  return;
@@ -6340,6 +6406,7 @@ class IdentityRenderer {
6340
6406
  if (result.success && result.result) {
6341
6407
  this.runPostLogin(result.result);
6342
6408
  }
6409
+ else if (this.renderBlockedInterstitial(result.errorCode)) ;
6343
6410
  else if (result.errorCode === 'identity_locked') {
6344
6411
  // The identity is locked down — a dedicated, actionable state, not a
6345
6412
  // generic "invalid code" retry. The person must manage it at auth.sv.
@@ -6420,6 +6487,8 @@ class IdentityRenderer {
6420
6487
  const currentMethod = this.verificationState.totp.method ?? 'email';
6421
6488
  const result = await this.totpHandler.resend();
6422
6489
  if (!result.success) {
6490
+ if (this.renderBlockedInterstitial(result.errorCode))
6491
+ return;
6423
6492
  this.setState({
6424
6493
  view: 'totp-verify',
6425
6494
  email: this.recipient,
@@ -6462,6 +6531,7 @@ class IdentityRenderer {
6462
6531
  navigateWith(this.options, result.result.redirect);
6463
6532
  }
6464
6533
  }
6534
+ else if (this.renderBlockedInterstitial(result.errorCode)) ;
6465
6535
  else if (result.errorCode === 'identity_locked') {
6466
6536
  // Dedicated state — retrying cannot unlock the identity.
6467
6537
  this.setState({
@@ -7101,6 +7171,8 @@ class IdentityRenderer {
7101
7171
  this.setState({ view: 'loading' });
7102
7172
  const result = await this.totpHandler.send('email');
7103
7173
  if (!result.success) {
7174
+ if (this.renderBlockedInterstitial(result.errorCode))
7175
+ return;
7104
7176
  this.setState({
7105
7177
  view: 'error',
7106
7178
  message: result.error ?? 'Failed to send code',
@@ -7778,6 +7850,74 @@ class IdentityModule {
7778
7850
  }
7779
7851
  return new URL(path, this.config.portalBaseUrl).toString();
7780
7852
  }
7853
+ /**
7854
+ * One-click sign-in through the browser's native FedCM account chooser.
7855
+ *
7856
+ * When the person is already signed into auth.sv (carrying the SSO session),
7857
+ * the browser surfaces a "Continue as …" prompt with no popup, redirect, or
7858
+ * typing. Requires a registered `clientId` in the SDK config and a browser
7859
+ * with FedCM support — callers should feature-detect with
7860
+ * `IdentityModule.isFedcmAvailable()` and fall back to `verify()` otherwise.
7861
+ *
7862
+ * @returns the verified result, or `null` when the browser has no FedCM
7863
+ * support (so the caller can fall back). Throws `UserCancelledError` when the
7864
+ * person dismisses the chooser.
7865
+ *
7866
+ * @example
7867
+ * const result = (await sv.products.identity.isFedcmAvailable())
7868
+ * ? await sv.products.identity.signInWithFedcm().catch(() => sv.products.identity.verify())
7869
+ * : await sv.products.identity.verify();
7870
+ */
7871
+ async signInWithFedcm(options = {}) {
7872
+ if (!IdentityModule.isFedcmAvailable()) {
7873
+ return null;
7874
+ }
7875
+ if (!this.config.clientId) {
7876
+ throw new ValidationError('clientId must be set in the SDK config to use FedCM sign-in', {
7877
+ field: 'clientId',
7878
+ });
7879
+ }
7880
+ const nonce = options.nonce ?? generateState();
7881
+ const configURL = `${this.config.portalBaseUrl}/${this.config.accountId}/fedcm/config.json`;
7882
+ const request = {
7883
+ identity: { providers: [{ configURL, clientId: this.config.clientId, nonce }] },
7884
+ ...(options.mediation ? { mediation: options.mediation } : {}),
7885
+ };
7886
+ let credential;
7887
+ try {
7888
+ // FedCM's `identity` provider request isn't in every TS DOM lib version, so
7889
+ // adapt navigator.credentials.get through our own request/credential types
7890
+ // (avoids naming the type-only `CredentialRequestOptions` DOM global).
7891
+ const getCredential = navigator.credentials.get.bind(navigator.credentials);
7892
+ credential = await getCredential(request);
7893
+ }
7894
+ catch (error) {
7895
+ // The browser rejects with an AbortError/NotAllowedError when the person
7896
+ // dismisses the chooser — normalize that to the SDK's cancel signal.
7897
+ throw new UserCancelledError(error instanceof Error ? error.message : undefined);
7898
+ }
7899
+ const token = credential?.token;
7900
+ if (!token) {
7901
+ throw new ValidationError('FedCM did not return a token');
7902
+ }
7903
+ // Same decode + issuer/expiry/alg validation every returned token goes through.
7904
+ const claims = this.decodeToken(token);
7905
+ return {
7906
+ token,
7907
+ identity: claims.identity,
7908
+ identityType: claims.identity_type,
7909
+ svid: claims.svid,
7910
+ sessionId: claims.session_id,
7911
+ };
7912
+ }
7913
+ /** Whether this browser exposes the FedCM API (`navigator.credentials` + IdentityCredential). */
7914
+ static isFedcmAvailable() {
7915
+ return (typeof window !== 'undefined' &&
7916
+ 'IdentityCredential' in window &&
7917
+ typeof navigator !== 'undefined' &&
7918
+ !!navigator.credentials &&
7919
+ typeof navigator.credentials.get === 'function');
7920
+ }
7781
7921
  /**
7782
7922
  * Verify user identity.
7783
7923
  *