@sparkvault/sdk-js 2.0.0 → 2.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # SparkVault JavaScript SDK
2
2
 
3
- The official SparkVault JavaScript SDK for browser applications. Add passwordless authentication to your app in minutes with zero-config integration or full programmatic control.
3
+ The official SparkVault JavaScript SDK for browser applications. Add passwordless verification to your app in minutes with CDN auto-init or full programmatic control.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/@sparkvault/sdk-js.svg)](https://www.npmjs.com/package/@sparkvault/sdk-js)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
@@ -8,10 +8,11 @@ The official SparkVault JavaScript SDK for browser applications. Add passwordles
8
8
  ## Table of Contents
9
9
 
10
10
  - [Installation](#installation)
11
- - [Zero-Config Integration](#zero-config-integration)
11
+ - [CDN Auto-Init](#cdn-auto-init)
12
12
  - [Manual Initialization](#manual-initialization)
13
13
  - [Identity Verification](#identity-verification)
14
14
  - [Backend Token Verification](#backend-token-verification)
15
+ - [Full OIDC/BFF Session Ownership](#full-oidcbff-session-ownership)
15
16
  - [React Integration](#react-integration)
16
17
  - [Error Handling](#error-handling)
17
18
  - [TypeScript Support](#typescript-support)
@@ -40,44 +41,39 @@ yarn add @sparkvault/sdk-js
40
41
  - `sparkvault.esm.js` — ES modules for modern bundlers
41
42
  - `sparkvault.cjs.js` — CommonJS for Node.js
42
43
 
43
- ## Zero-Config Integration
44
-
45
- Add SparkVault authentication to your site with a single script tag — no JavaScript required!
44
+ ## CDN Auto-Init
46
45
 
47
46
  ```html
48
- <!-- Add this single script tag -->
49
47
  <script
50
48
  async
51
49
  src="https://cdn.sparkvault.com/sdk/v1/sparkvault.js"
52
50
  data-account-id="acc_YOUR_ACCOUNT_ID"
53
- data-attach-selector=".login-btn"
54
- data-success-url="/auth/verify-token"
55
51
  ></script>
56
52
 
57
- <!-- Any element matching the selector becomes a login button -->
58
53
  <button class="login-btn">Sign In</button>
59
- <a href="#" class="login-btn">Create Account</a>
54
+
55
+ <script>
56
+ SparkVault.identity.attach('.login-btn', {
57
+ onSuccess: async (result) => {
58
+ await fetch('/api/auth/verify', {
59
+ method: 'POST',
60
+ headers: { 'Content-Type': 'application/json' },
61
+ body: JSON.stringify({ token: result.token })
62
+ });
63
+ }
64
+ });
65
+ </script>
60
66
  ```
61
67
 
62
- That's it! The SDK automatically:
63
- - Initializes with your account ID
64
- - Attaches click handlers to all matching elements
65
- - Opens the verification modal when clicked
66
- - POSTs the result to your success URL
67
- - Watches for dynamically added elements (MutationObserver)
68
+ The script auto-initializes `SparkVault` with your account ID. Use
69
+ `SparkVault.identity.attach()` or `SparkVault.identity.pop()` to open the
70
+ verification UI and handle the result.
68
71
 
69
72
  ### Data Attributes
70
73
 
71
74
  | Attribute | Required | Description |
72
75
  |-----------|----------|-------------|
73
76
  | `data-account-id` | Yes | Your SparkVault account ID (required for auto-init) |
74
- | `data-attach-selector` | No | CSS selector for elements to attach click handlers |
75
- | `data-success-url` | No | URL to POST `{ token, identity, identityType }` on success |
76
- | `data-success-function` | No | Global function name to call on success (e.g., `"MyApp.auth.onSuccess"`) |
77
- | `data-error-url` | No | URL to redirect on error (appends `?error=message`) |
78
- | `data-error-function` | No | Global function name to call on error |
79
- | `data-preload-config` | No | Set to `"false"` to defer config loading. Default: true |
80
- | `data-timeout` | No | Request timeout in milliseconds. Default: 30000 |
81
77
  | `data-debug` | No | Set to `"true"` for verbose console logging |
82
78
 
83
79
  ### Complete Example
@@ -87,25 +83,24 @@ That's it! The SDK automatically:
87
83
  async
88
84
  src="https://cdn.sparkvault.com/sdk/v1/sparkvault.js"
89
85
  data-account-id="acc_YOUR_ACCOUNT_ID"
90
- data-attach-selector=".js-sparkvault-auth"
91
- data-success-url="https://example.com/auth/verify-token"
92
- data-success-function="onSparkVaultSuccess"
93
- data-error-function="onSparkVaultError"
94
86
  data-debug="true"
95
87
  ></script>
96
88
 
97
89
  <script>
98
- // Optional: Define callback functions
99
- function onSparkVaultSuccess(result) {
100
- console.log('Verified:', result.identity);
101
- console.log('Token:', result.token);
102
- // The SDK will also POST to data-success-url
103
- }
104
-
105
- function onSparkVaultError(error) {
106
- console.error('Error:', error.message);
107
- alert('Authentication failed. Please try again.');
108
- }
90
+ SparkVault.identity.attach('.js-sparkvault-auth', {
91
+ onSuccess: async (result) => {
92
+ const response = await fetch('/api/auth/verify', {
93
+ method: 'POST',
94
+ headers: { 'Content-Type': 'application/json' },
95
+ body: JSON.stringify({ token: result.token })
96
+ });
97
+ if (!response.ok) throw new Error('Verification failed');
98
+ window.location.assign('/dashboard');
99
+ },
100
+ onError: (error) => {
101
+ console.error('SparkVault verification failed:', error.message);
102
+ }
103
+ });
109
104
  </script>
110
105
 
111
106
  <!-- Multiple elements can use the same selector -->
@@ -113,32 +108,23 @@ That's it! The SDK automatically:
113
108
  <a href="#" class="js-sparkvault-auth">Login with SparkVault</a>
114
109
  ```
115
110
 
116
- ### Success URL Response
111
+ ### Verification Result
117
112
 
118
- When you specify `data-success-url`, the SDK POSTs the verification result:
113
+ The SDK returns this shape from `identity.pop()`, `identity.verify()`, and
114
+ `identity.attach()` callbacks:
119
115
 
120
116
  ```json
121
117
  {
122
118
  "token": "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9...",
123
119
  "identity": "user@example.com",
124
- "identityType": "email"
120
+ "identityType": "email",
121
+ "svid": "ing_019e66a4e27875f2822ede0e4f5d8792",
122
+ "sessionId": "sess_abc123"
125
123
  }
126
124
  ```
127
125
 
128
- Your backend can respond with redirect instructions:
129
-
130
- ```javascript
131
- // Option 1: Redirect to a URL
132
- { "redirectUrl": "/dashboard" }
133
- // or
134
- { "redirect_url": "/dashboard" }
135
-
136
- // Option 2: Reload the current page
137
- { "reload": true }
138
-
139
- // Option 3: Return data (no automatic action)
140
- { "success": true, "user": { "id": 123, "email": "user@example.com" } }
141
- ```
126
+ Send `token` to your backend and verify it with the Identity JWKS before
127
+ trusting any claim. Use `svid` as the canonical user key in your application.
142
128
 
143
129
  ### Manual Trigger from JavaScript
144
130
 
@@ -146,9 +132,8 @@ You can also trigger authentication programmatically using the `SparkVault` glob
146
132
 
147
133
  ```javascript
148
134
  // Trigger authentication from anywhere in your code
149
- SparkVault.identity.pop();
150
-
151
- // This uses your configured success/error handlers
135
+ const result = await SparkVault.identity.pop();
136
+ await sendTokenToBackend(result.token);
152
137
  ```
153
138
 
154
139
  ```html
@@ -237,6 +222,9 @@ await fetch('/api/auth/login', {
237
222
  | `token` | `string` | Signed JWT token (Ed25519). Verify this on your backend. |
238
223
  | `identity` | `string` | The verified email address or phone number |
239
224
  | `identityType` | `"email" \| "phone"` | Type of identity that was verified |
225
+ | `svid` | `string` | Canonical SparkVault ID for the person |
226
+ | `sessionId` | `string` | Managed Identity session ID |
227
+ | `refreshToken` | `string` | Present only for flows that intentionally return managed-session refresh material |
240
228
 
241
229
  ### Example with Options
242
230
 
@@ -309,8 +297,12 @@ app.post('/api/auth/login', async (req, res) => {
309
297
  algorithms: ['EdDSA']
310
298
  });
311
299
 
312
- // Token is valid! Create user session
313
- const user = await findOrCreateUser(payload.identity, payload.identity_type);
300
+ // Token is valid. SVID is the canonical identity reference.
301
+ const svid = payload.svid || payload.sub;
302
+ const user = await findOrCreateUserBySvid(svid, {
303
+ identity: payload.identity,
304
+ identityType: payload.identity_type
305
+ });
314
306
  req.session.userId = user.id;
315
307
 
316
308
  res.json({ success: true, user });
@@ -356,8 +348,13 @@ def login():
356
348
  try:
357
349
  claims = verify_identity_token(token)
358
350
 
359
- # Create session
360
- user = find_or_create_user(claims['identity'], claims['identity_type'])
351
+ # SVID is the canonical identity reference.
352
+ svid = claims.get('svid') or claims['sub']
353
+ user = find_or_create_user_by_svid(
354
+ svid,
355
+ identity=claims['identity'],
356
+ identity_type=claims['identity_type']
357
+ )
361
358
  session['user_id'] = user.id
362
359
 
363
360
  return jsonify({'success': True, 'user': user.to_dict()})
@@ -416,8 +413,11 @@ func loginHandler(w http.ResponseWriter, r *http.Request) {
416
413
  return
417
414
  }
418
415
 
419
- identity, _ := token.Get("identity")
420
- // Create session with identity...
416
+ svid, _ := token.Get("svid")
417
+ if svid == nil {
418
+ svid, _ = token.Subject()
419
+ }
420
+ // Find or create your local user by SVID.
421
421
  }
422
422
  ```
423
423
 
@@ -460,7 +460,8 @@ class AuthController < ApplicationController
460
460
  def login
461
461
  claims = verify_identity_token(params[:token])
462
462
 
463
- user = User.find_or_create_by(email: claims['identity'])
463
+ svid = claims['svid'] || claims['sub']
464
+ user = User.find_or_create_by!(svid: svid)
464
465
  session[:user_id] = user.id
465
466
 
466
467
  render json: { success: true, user: user }
@@ -477,8 +478,11 @@ When decoded, the JWT token contains these claims:
477
478
  ```json
478
479
  {
479
480
  "iss": "https://api.sparkvault.com/v1/products/identity/acc_xxx",
480
- "sub": "identity:a1b2c3d4e5f67890",
481
+ "sub": "ing_019e66a4e27875f2822ede0e4f5d8792",
481
482
  "aud": "acc_xxx",
483
+ "svid": "ing_019e66a4e27875f2822ede0e4f5d8792",
484
+ "session_id": "sess_abc123",
485
+ "token_version": 0,
482
486
  "identity": "user@example.com",
483
487
  "identity_type": "email",
484
488
  "method": "totp_email",
@@ -492,8 +496,11 @@ When decoded, the JWT token contains these claims:
492
496
  | Claim | Type | Description |
493
497
  |-------|------|-------------|
494
498
  | `iss` | `string` | Issuer URL — always verify this matches expected value |
495
- | `sub` | `string` | Subject — hashed identity for consistent user identification |
499
+ | `sub` | `string` | Subject — equals the SVID for managed Identity tokens |
496
500
  | `aud` | `string` | Audience — your account ID |
501
+ | `svid` | `string` | Canonical SparkVault ID for the person |
502
+ | `session_id` | `string` | Managed Identity session ID |
503
+ | `token_version` | `number` | Managed-session version used for revocation/introspection |
497
504
  | `identity` | `string` | The verified email address or phone number |
498
505
  | `identity_type` | `string` | `"email"` or `"phone"` |
499
506
  | `method` | `string` | Authentication method used (e.g., `"totp_email"`, `"passkey"`) |
@@ -502,6 +509,27 @@ When decoded, the JWT token contains these claims:
502
509
  | `exp` | `number` | Expiration timestamp |
503
510
  | `jti` | `string` | Unique token ID for replay protection |
504
511
 
512
+ ## Full OIDC/BFF Session Ownership
513
+
514
+ The JavaScript SDK simple flow is a signed verification proof. It is ideal when
515
+ your backend already owns app sessions and only needs to know which SVID was
516
+ verified.
517
+
518
+ For replacing a production login/session system, use SparkVault Identity as the
519
+ OIDC provider and put a backend-for-frontend (BFF) boundary in front of your
520
+ application:
521
+
522
+ 1. Redirect the browser to `/v1/products/identity/{account_id}/authorize` with PKCE.
523
+ 2. Exchange the callback `code` for `id_token`, `access_token`, and `refresh_token` server-side.
524
+ 3. Store refresh/session material only in encrypted or signed `HttpOnly`, `Secure`, `SameSite=Lax` cookies.
525
+ 4. Keep refresh tokens out of browser JavaScript.
526
+ 5. Validate access JWTs locally with cached JWKS for ordinary API requests.
527
+ 6. Call `/introspect` only for sensitive mutations, account settings, admin/moderation actions, suspicious sessions, or short cached hard checks.
528
+ 7. On logout, call `/revoke` with the current refresh token, then clear local cookies.
529
+
530
+ Application data should key people by `svid`. Keep username, roles, profile,
531
+ preferences, uploads, and moderation state in your application database.
532
+
505
533
  ## React Integration
506
534
 
507
535
  ```jsx
@@ -701,11 +729,15 @@ script-src https://cdn.sparkvault.com;
701
729
 
702
730
  1. **Initialize Once** — Create the SparkVault instance once when your app loads, not on every login attempt. The SDK preloads configuration for instant modal opening.
703
731
 
704
- 2. **Always Verify Server-Side** — Never trust client-side token validation in production. Always verify the JWT signature on your backend using the JWKS endpoint before creating a session.
732
+ 2. **Always Verify Server-Side** — Never trust client-side token validation in production. Always verify the JWT signature on your backend using the JWKS endpoint before trusting claims or issuing an app session.
705
733
 
706
734
  3. **Handle Cancellation Gracefully** — Users may close the modal without completing verification. This throws a `UserCancelledError` — handle it gracefully rather than showing an error message.
707
735
 
708
- 4. **Cache JWKS Keys** — The JWKS endpoint returns public keys with caching headers. Use a library like `jose` that handles caching automatically, or cache keys for 5-10 minutes.
736
+ 4. **Key Users by SVID** — Use `svid` or `sub` as the canonical identity reference. Email and phone are user-facing attributes, not durable account keys.
737
+
738
+ 5. **Cache JWKS Keys** — The JWKS endpoint returns public keys with caching headers. Use a library like `jose` that handles caching automatically, or cache keys for 5-10 minutes.
739
+
740
+ 6. **Use OIDC/BFF for Managed Sessions** — The SDK simple flow gives you a signed proof. Use OIDC when you want SparkVault-owned refresh rotation, revocation, introspection, and logout.
709
741
 
710
742
  ## Browser Support
711
743
 
@@ -45,7 +45,7 @@ export declare abstract class SparkVaultApi {
45
45
  */
46
46
  resetSession(): void;
47
47
  /** Subclass-specific error factory. */
48
- protected abstract makeError(message: string, code: string, statusCode: number): SparkVaultError;
48
+ protected abstract makeError(message: string, code: string, statusCode: number, details?: Record<string, unknown>): SparkVaultError;
49
49
  /**
50
50
  * Issue an HTTP request with timeout + session abort + standard error
51
51
  * mapping. Subclasses build URLs and unwrap response envelopes on top.
@@ -14,7 +14,7 @@ export declare class IdentityApi extends SparkVaultApi {
14
14
  private configCache;
15
15
  constructor(config: ResolvedConfig, timeoutMs?: number);
16
16
  private get baseUrl();
17
- protected makeError(message: string, code: string, statusCode: number): IdentityApiError;
17
+ protected makeError(message: string, code: string, statusCode: number, details?: Record<string, unknown>): IdentityApiError;
18
18
  private request;
19
19
  /**
20
20
  * Fetch SDK configuration (branding, enabled methods).
@@ -105,5 +105,5 @@ export declare class IdentityApi extends SparkVaultApi {
105
105
  sendSparkLink(email: string, connectionId: string, authContext?: AuthContext): Promise<SparkLinkSendResponse>;
106
106
  }
107
107
  export declare class IdentityApiError extends SparkVaultError {
108
- constructor(message: string, code: string, statusCode: number);
108
+ constructor(message: string, code: string, statusCode: number, details?: Record<string, unknown>);
109
109
  }
@@ -69,7 +69,7 @@ export declare class PasskeyHandler {
69
69
  private openPasskeyPopup;
70
70
  /**
71
71
  * Validate that a postMessage came from the identity service's own
72
- * origin. We do not accept the broader sparkvault.com family — a popup
72
+ * origin. We do not accept the broader sparkvault.com family - a popup
73
73
  * is only opened against `this.baseUrl`, so any other origin is
74
74
  * either an unrelated tab or a forgery attempt.
75
75
  */
@@ -42,9 +42,15 @@ export declare class IdentityRenderer {
42
42
  start(): Promise<void>;
43
43
  /**
44
44
  * Map a config-fetch error to the appropriate terminal view.
45
- * `product_not_configured` is a misconfiguration (the account has not
46
- * configured Identity) — show a developer-targeted terminal screen with a
47
- * link to SparkVault.com instead of the generic service-unavailable view.
45
+ *
46
+ * Two failures are permanent developer-misconfigurations, not transient
47
+ * outages, so they get dedicated terminal screens (no "Try Again" — retrying
48
+ * can never clear them) instead of the generic service-unavailable view:
49
+ * - `product_not_configured`: the account has not configured Identity.
50
+ * - `ORIGIN_NOT_ALLOWED`: this site's domain is not on the account's
51
+ * allowlist. Surfacing it as "Temporarily Unavailable / try again" sends
52
+ * the developer chasing a non-existent outage.
53
+ * Everything else (network errors, 5xx) is genuinely transient.
48
54
  */
49
55
  private viewStateForConfigError;
50
56
  /**
@@ -237,4 +237,7 @@ export type IdentityViewState = {
237
237
  view: 'service-unavailable';
238
238
  } | {
239
239
  view: 'product-not-configured';
240
+ } | {
241
+ view: 'origin-not-allowed';
242
+ origin?: string;
240
243
  };
@@ -14,3 +14,4 @@ export * from './sparklink-waiting';
14
14
  export * from './error';
15
15
  export * from './service-unavailable';
16
16
  export * from './product-not-configured';
17
+ export * from './origin-not-allowed';
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Origin Not Allowed View
3
+ *
4
+ * Full-dialog terminal screen shown when the embedding site's origin is not in
5
+ * the account's verified-domains allowlist. The audience is the website owner /
6
+ * developer — this is a misconfiguration surface, not an end-user error, and it
7
+ * is permanent (retrying never clears an origin block) — so the dialog drops
8
+ * customer branding, offers no "Try Again", names the blocked origin, and
9
+ * points to the place that fixes it. Reuses the SparkVault-notice styling from
10
+ * the product-not-configured view.
11
+ */
12
+ import type { View } from './base';
13
+ export interface OriginNotAllowedViewProps {
14
+ /** The blocked embedding origin, when the server reported it. */
15
+ origin?: string;
16
+ onClose: () => void;
17
+ }
18
+ export declare class OriginNotAllowedView implements View {
19
+ private readonly props;
20
+ private dismissButton;
21
+ private readonly boundHandleClose;
22
+ constructor(props: OriginNotAllowedViewProps);
23
+ render(): HTMLElement;
24
+ destroy(): void;
25
+ }