@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/README.md CHANGED
@@ -1,810 +1,175 @@
1
1
  # SparkVault JavaScript SDK
2
2
 
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.
3
+ `@sparkvault/sdk-js` is SparkVault's SDK for browsers and Node 18+. A web page signs people in through SparkVault Identity, uploads ingots and embeds the encrypted upload widget; a backend sends Notify notifications and manages vaults, ingots, folders, sparks and entropy over the Core API. Uploads need a browser's XMLHttpRequest: in Node, an `ingots` upload or replacement rejects with `code` `environment_unsupported` before any request, so nothing is staged; a server stages with `ingots.createUpload` and sends the file over tus itself.
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)
7
7
 
8
- ## Table of Contents
9
-
10
- - [Installation](#installation)
11
- - [CDN Auto-Init](#cdn-auto-init)
12
- - [Manual Initialization](#manual-initialization)
13
- - [Identity Verification](#identity-verification)
14
- - [Backend Token Verification](#backend-token-verification)
15
- - [Full OIDC/BFF Session Ownership](#full-oidcbff-session-ownership)
16
- - [React Integration](#react-integration)
17
- - [Error Handling](#error-handling)
18
- - [TypeScript Support](#typescript-support)
19
- - [Browser Support](#browser-support)
20
- - [Build & Release](#build--release)
21
- - [License](#license)
22
-
23
- ## Installation
24
-
25
- ### CDN (Recommended)
26
-
27
- ```html
28
- <script src="https://cdn.sparkvault.com/sdk/v1/sparkvault.js"></script>
29
- ```
30
-
31
- ### npm / yarn
32
-
33
- ```bash
34
- npm install @sparkvault/sdk-js
35
- ```
36
-
37
- Both module systems resolve to a working entry through the package's `exports` map:
38
-
39
- ```js
40
- import SparkVault from '@sparkvault/sdk-js'; // ESM → dist/index.mjs
41
- const { SparkVault } = require('@sparkvault/sdk-js'); // CJS → dist/index.cjs
42
- ```
43
-
44
- **Bundle Formats:**
45
- - `dist/index.mjs` — ES module, resolved by `import`
46
- - `dist/index.cjs` — CommonJS, resolved by `require`
47
- - `dist/sparkvault.js` — UMD bundle for a browser `<script>` tag (also served from the CDN)
48
- - `dist/index.d.ts` — bundled TypeScript declarations
8
+ ## Contents
49
9
 
50
- ### Caching & version pinning
51
-
52
- The CDN serves the browser bundle in two tiers:
53
-
54
- | URL | Effective cache | Use when |
55
- |-----|-----------------|----------|
56
- | `sdk/v1/sparkvault.js` | Short-lived (edge cache TTL, ~4h) — bust with `?v=<version>` for immediate freshness | Default. Auto-updates each release; the `?v=<version>` query gives you the new build immediately. |
57
- | `sdk/v1/sparkvault.<hash>.js` | `immutable`, 1 year | You want a reproducible, forever-cached, integrity-pinned build. |
58
-
59
- `sdk/v1/version.json` advertises the current immutable URL, its hash, and a
60
- Subresource Integrity (SRI) digest:
61
-
62
- ```json
63
- { "version": "7.0.1", "hash": "f771160fa23a09d8", "umd": "sparkvault.f771160fa23a09d8.js", "integrity": "sha384-…" }
64
- ```
65
-
66
- To pin a build with integrity verification:
67
-
68
- ```html
69
- <script
70
- src="https://cdn.sparkvault.com/sdk/v1/sparkvault.f771160fa23a09d8.js"
71
- integrity="sha384-…"
72
- crossorigin="anonymous"
73
- ></script>
74
- ```
10
+ - [Install](#install)
11
+ - [Quickstart: sign in](#quickstart-sign-in)
12
+ - [Modules](#modules)
13
+ - [Content Security Policy (CSP)](#content-security-policy-csp)
14
+ - [Browser support](#browser-support)
15
+ - [Build and release](#build-and-release)
16
+ - [License](#license)
17
+ - [Links](#links)
75
18
 
76
- Pinning trades automatic updates for a byte-stable, forever-cached asset — you
77
- update by pointing at the next `version.json` entry.
19
+ ## Install
78
20
 
79
- ## CDN Auto-Init
21
+ ### CDN
80
22
 
81
23
  ```html
82
24
  <script
83
- async
84
25
  src="https://cdn.sparkvault.com/sdk/v1/sparkvault.js"
85
26
  data-account-id="acc_YOUR_ACCOUNT_ID"
86
27
  ></script>
87
-
88
- <button class="login-btn">Sign In</button>
89
-
90
- <script>
91
- SparkVault.products.identity.attach('.login-btn', {
92
- onSuccess: async (result) => {
93
- await fetch('/api/auth/verify', {
94
- method: 'POST',
95
- headers: { 'Content-Type': 'application/json' },
96
- body: JSON.stringify({ token: result.token })
97
- });
98
- }
99
- });
100
- </script>
101
28
  ```
102
29
 
103
- The script auto-initializes `SparkVault` with your account ID. Use
104
- `SparkVault.products.identity.attach()` or `SparkVault.products.identity.signIn()` to open the
105
- verification UI and handle the result.
106
-
107
- ### Data Attributes
108
-
109
- | Attribute | Required | Description |
110
- |-----------|----------|-------------|
111
- | `data-account-id` | Yes | Your SparkVault account ID (required for auto-init) |
112
- | `data-debug` | No | Set to `"true"` for verbose console logging |
113
-
114
- ### Complete Example
30
+ - `data-account-id` initializes the SDK, and `window.SparkVault` is the instance; without it `window.SparkVault` is the class (`SparkVault.init({ accountId })`). `data-debug="true"` logs verbosely.
31
+ - Load it as a plain script, ahead of the code that calls it: an `async` script runs whenever its download completes, so an inline script after it can find `SparkVault` unset.
32
+ - `sdk/v1/sparkvault.js` is the stable URL, replaced by each release (bust with `?v=<version>`). To pin one build, take the content-hashed file and its SRI digest that `https://cdn.sparkvault.com/sdk/v1/version.json` names (`{ version, hash, umd, integrity }`):
115
33
 
116
34
  ```html
117
35
  <script
118
- async
119
- src="https://cdn.sparkvault.com/sdk/v1/sparkvault.js"
36
+ src="https://cdn.sparkvault.com/sdk/v1/sparkvault.<hash>.js"
37
+ integrity="sha384-<digest>"
38
+ crossorigin="anonymous"
120
39
  data-account-id="acc_YOUR_ACCOUNT_ID"
121
- data-debug="true"
122
40
  ></script>
123
-
124
- <script>
125
- SparkVault.products.identity.attach('.js-sparkvault-auth', {
126
- onSuccess: async (result) => {
127
- const response = await fetch('/api/auth/verify', {
128
- method: 'POST',
129
- headers: { 'Content-Type': 'application/json' },
130
- body: JSON.stringify({ token: result.token })
131
- });
132
- if (!response.ok) throw new Error('Verification failed');
133
- window.location.assign('/dashboard');
134
- },
135
- onError: (error) => {
136
- console.error('SparkVault verification failed:', error.message);
137
- }
138
- });
139
- </script>
140
-
141
- <!-- Multiple elements can use the same selector -->
142
- <button class="js-sparkvault-auth">Sign In</button>
143
- <a href="#" class="js-sparkvault-auth">Login with SparkVault</a>
144
- ```
145
-
146
- ### Verification Result
147
-
148
- The SDK returns this shape from `products.identity.signIn()` and
149
- `products.identity.attach()` callbacks:
150
-
151
- ```json
152
- {
153
- "token": "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9...",
154
- "identity": "user@example.com",
155
- "identityType": "email",
156
- "svid": "ing_019e66a4e27875f2822ede0e4f5d8792",
157
- "sessionId": "sess_abc123"
158
- }
159
41
  ```
160
42
 
161
- Send `token` to your backend and verify it with the Identity JWKS before
162
- trusting any claim. Use `svid` as the canonical user key in your application.
43
+ ### npm
163
44
 
164
- ### Manual Trigger from JavaScript
165
-
166
- You can also trigger authentication programmatically using the `SparkVault` global:
167
-
168
- ```javascript
169
- // Trigger authentication from anywhere in your code
170
- const result = await SparkVault.products.identity.signIn();
171
- await sendTokenToBackend(result.token);
172
- ```
173
-
174
- ```html
175
- <button onclick="SparkVault.products.identity.signIn()">
176
- Sign In with SparkVault
177
- </button>
45
+ ```bash
46
+ npm install @sparkvault/sdk-js
178
47
  ```
179
48
 
180
- ## Manual Initialization
181
-
182
- For full control over the SDK, initialize it manually in JavaScript:
183
-
184
- ```javascript
185
- import SparkVault from '@sparkvault/sdk-js';
186
-
187
- const sparkvault = SparkVault.init({
188
- accountId: 'acc_YOUR_ACCOUNT_ID' // Required
189
- });
49
+ ```js
50
+ import SparkVault from '@sparkvault/sdk-js'; // ESM → dist/index.mjs
51
+ const { SparkVault } = require('@sparkvault/sdk-js'); // CJS → dist/index.cjs
190
52
 
191
- // The SDK is now ready to use
192
- const result = await sparkvault.products.identity.signIn();
53
+ const sv = SparkVault.init({ accountId: 'acc_YOUR_ACCOUNT_ID' });
193
54
  ```
194
55
 
195
- ### Configuration Options
196
-
197
- | Option | Type | Default | Description |
198
- |--------|------|---------|-------------|
199
- | `accountId` | `string` | **required** | Your SparkVault account ID (starts with `acc_`) |
200
- | `timeout` | `number` | `30000` | HTTP request timeout in milliseconds |
201
- | `preloadConfig` | `boolean` | `true` | Preload Identity config for instant popup |
56
+ Types ship in `dist/index.d.ts` (the sign-in result is `VerifyResult`); the `browser` field is the UMD bundle the CDN serves (`dist/sparkvault.js`).
202
57
 
203
- ### CDN Usage
58
+ ## Quickstart: sign in
204
59
 
205
60
  ```html
206
- <script src="https://cdn.sparkvault.com/sdk/v1/sparkvault.js"></script>
207
- <script>
208
- const sparkvault = SparkVault.init({
209
- accountId: 'acc_YOUR_ACCOUNT_ID'
210
- });
211
-
212
- document.getElementById('login-btn').addEventListener('click', async () => {
213
- const result = await sparkvault.products.identity.signIn();
214
- console.log('Verified:', result.identity);
215
- });
216
- </script>
217
- ```
218
-
219
- ## Identity Verification
220
-
221
- The Identity module provides passwordless authentication through a first-party SparkVault popup. Users can sign in via passkeys, email codes, SMS codes, SparkLink, or social providers.
222
-
223
- ### Basic Usage
224
-
225
- ```javascript
226
- // Open the sign-in popup
227
- const result = await sparkvault.products.identity.signIn();
228
-
229
- // User verified!
230
- console.log(result.identity); // "user@example.com" or "+14155551234"
231
- console.log(result.identityType); // "email" or "phone"
232
- console.log(result.token); // Signed JWT token
233
-
234
- // Send the token to your backend for verification
235
- await fetch('/api/auth/login', {
236
- method: 'POST',
237
- headers: { 'Content-Type': 'application/json' },
238
- body: JSON.stringify({ token: result.token })
239
- });
240
- ```
241
-
242
- ### signIn() Options
243
-
244
- | Option | Type | Description |
245
- |--------|------|-------------|
246
- | `email` | `string` | Pre-fill email address (mutually exclusive with phone) |
247
- | `phone` | `string` | Pre-fill phone in E.164 format, e.g. `"+14155551234"` |
248
- | `backdropBlur` | `boolean` | Override the `backdropBlur` set at `SparkVault.init()` for this sign-in |
249
- | `flow` | `"auto" \| "popup" \| "redirect"` | `"auto"` (default) and `"popup"` open the popup; `"redirect"` navigates the tab to the sign-in page instead (its return leg is `handleRedirectResult()`) |
250
- | `prompt` | `"select_account"` | Always show the sign-in page's account chooser instead of silently continuing as the current account — the affordance for a "switch account" button. Any other value is ignored. |
251
- | `onCancel` | `function` | Callback when the person closes the popup without signing in |
252
- | `onSuccess` | `function` | Callback on success (before promise resolves) |
253
- | `onError` | `function` | Callback on error (before promise rejects) |
61
+ <button class="login-btn">Sign in</button>
254
62
 
255
- ### signIn() Result
256
-
257
- | Field | Type | Description |
258
- |-------|------|-------------|
259
- | `token` | `string` | Signed JWT token (Ed25519). Verify this on your backend. |
260
- | `identity` | `string` | The verified email address or phone number |
261
- | `identityType` | `"email" \| "phone"` | Type of identity that was verified |
262
- | `svid` | `string` | Canonical SparkVault ID for the person |
263
- | `sessionId` | `string` | Managed Identity session ID |
264
- | `refreshToken` | `string` | Present only for flows that intentionally return managed-session refresh material |
265
-
266
- ### Example with Options
267
-
268
- ```javascript
269
- try {
270
- const result = await sparkvault.products.identity.signIn({
271
- // Pre-fill the email field
272
- email: 'user@example.com',
273
-
274
- // Handle cancellation
275
- onCancel: () => {
276
- console.log('User cancelled');
277
- }
278
- });
279
-
280
- // Success! Send token to your backend
281
- await loginWithToken(result.token);
282
-
283
- } catch (error) {
284
- if (error.code === 'user_cancelled') {
285
- // Person closed the popup
286
- } else {
287
- // Handle other errors
288
- console.error('Verification failed:', error.message);
63
+ <script>
64
+ function signInToApp(result) {
65
+ fetch('/api/auth/login', {
66
+ method: 'POST',
67
+ headers: { 'Content-Type': 'application/json' },
68
+ body: JSON.stringify({ token: result.token }),
69
+ }).then((response) => {
70
+ if (response.ok) window.location.assign('/dashboard');
71
+ });
289
72
  }
290
- }
291
- ```
292
-
293
- ### Authentication Methods
294
73
 
295
- Authentication methods are configured in your Identity Product settings. The SDK automatically shows only the methods you have enabled.
74
+ // On every page load: completes a `flow: 'redirect'` sign-in, or one a
75
+ // mobile browser lost mid-popup.
76
+ SparkVault.products.identity
77
+ .handleRedirectResult({ onSuccess: signInToApp })
78
+ .catch((error) => console.error('Sign-in failed:', error.message));
296
79
 
297
- | Method | Description | Identity Type |
298
- |--------|-------------|---------------|
299
- | `passkey` | WebAuthn/FIDO2 biometric or security key | Email |
300
- | `otp_email` | 6-digit code sent via email | Email |
301
- | `otp_sms` | 6-digit code sent via SMS | Phone |
302
- | `otp_voice` | 6-digit code sent via voice call | Phone |
303
- | `sparklink` | One-click sign-in link via email | Email |
304
- | `social_google` | Sign in with Google | Social account |
305
- | `social_apple` | Sign in with Apple | Social account |
306
- | `social_microsoft` | Sign in with Microsoft | Social account |
307
- | `social_github` | Sign in with GitHub | Social account |
308
- | `social_facebook` | Sign in with Facebook | Social account |
309
- | `social_linkedin` | Sign in with LinkedIn | Social account |
310
-
311
- ## Backend Token Verification
312
-
313
- > **Security Critical:** Always verify tokens on your backend. Never trust the frontend result alone. Tokens are signed with Ed25519 — use the JWKS endpoint to verify the signature.
80
+ // Each click opens the first-party sign-in popup.
81
+ SparkVault.products.identity.attach('.login-btn', { onSuccess: signInToApp });
82
+ </script>
83
+ ```
314
84
 
315
- ### Node.js
85
+ Verify the token on your backend before trusting any claim (Node, with [`jose`](https://www.npmjs.com/package/jose)):
316
86
 
317
87
  ```javascript
318
88
  import * as jose from 'jose';
319
89
 
320
90
  const ACCOUNT_ID = 'acc_YOUR_ACCOUNT_ID';
321
- const IDENTITY_URL = 'https://auth.sparkvault.com';
91
+ const ISSUER = `https://auth.sparkvault.com/${ACCOUNT_ID}`;
92
+ const JWKS = jose.createRemoteJWKSet(new URL(`${ISSUER}/.well-known/jwks.json`)); // one key set per process
322
93
 
323
94
  app.post('/api/auth/login', async (req, res) => {
324
- const { token } = req.body;
325
-
326
95
  try {
327
- // Fetch public keys and verify signature
328
- const jwksUrl = `${IDENTITY_URL}/${ACCOUNT_ID}/.well-known/jwks.json`;
329
- const JWKS = jose.createRemoteJWKSet(new URL(jwksUrl));
330
-
331
- const { payload } = await jose.jwtVerify(token, JWKS, {
332
- issuer: `${IDENTITY_URL}/${ACCOUNT_ID}`,
96
+ const { payload } = await jose.jwtVerify(req.body.token, JWKS, {
97
+ issuer: ISSUER,
333
98
  audience: ACCOUNT_ID,
334
- algorithms: ['EdDSA']
99
+ algorithms: ['EdDSA'],
335
100
  });
101
+ // The account's key signs other tokens with this issuer and audience;
102
+ // only a sign-in carries this purpose, so refuse every other token.
103
+ if (payload.token_purpose !== 'identity_verification') throw new Error('Not a sign-in token');
336
104
 
337
- // Token is valid. SVID is the canonical identity reference.
338
- const svid = payload.svid || payload.sub;
339
- const user = await findOrCreateUserBySvid(svid, {
340
- identity: payload.identity,
341
- identityType: payload.identity_type
342
- });
105
+ // Key your records by the SVID; email and phone are attributes, not keys.
106
+ const user = await findOrCreateUserBySvid(payload.svid);
343
107
  req.session.userId = user.id;
344
-
345
- res.json({ success: true, user });
346
- } catch (error) {
347
- res.status(401).json({ error: 'Invalid token' });
108
+ res.json({ ok: true });
109
+ } catch {
110
+ res.status(401).json({ error: 'invalid_token' });
348
111
  }
349
112
  });
350
113
  ```
351
114
 
352
- ### Python
353
-
354
- ```python
355
- import jwt
356
- from jwt import PyJWKClient
357
-
358
- ACCOUNT_ID = 'acc_YOUR_ACCOUNT_ID'
359
- IDENTITY_URL = 'https://auth.sparkvault.com'
360
-
361
- def verify_identity_token(token: str):
362
- """Verify a SparkVault Identity token and return the claims."""
363
- jwks_url = f"{IDENTITY_URL}/{ACCOUNT_ID}/.well-known/jwks.json"
364
- jwks_client = PyJWKClient(jwks_url)
365
-
366
- # Get the signing key
367
- signing_key = jwks_client.get_signing_key_from_jwt(token)
368
-
369
- # Verify and decode
370
- claims = jwt.decode(
371
- token,
372
- signing_key.key,
373
- algorithms=["EdDSA"],
374
- issuer=f"{IDENTITY_URL}/{ACCOUNT_ID}",
375
- audience=ACCOUNT_ID
376
- )
377
-
378
- return claims
379
-
380
- # Usage in Flask
381
- @app.route('/api/auth/login', methods=['POST'])
382
- def login():
383
- token = request.json.get('token')
384
-
385
- try:
386
- claims = verify_identity_token(token)
387
-
388
- # SVID is the canonical identity reference.
389
- svid = claims.get('svid') or claims['sub']
390
- user = find_or_create_user_by_svid(
391
- svid,
392
- identity=claims['identity'],
393
- identity_type=claims['identity_type']
394
- )
395
- session['user_id'] = user.id
396
-
397
- return jsonify({'success': True, 'user': user.to_dict()})
398
- except jwt.InvalidTokenError as e:
399
- return jsonify({'error': 'Invalid token'}), 401
400
- ```
115
+ - A sign-in token lives 300 s. Its claims, and the full rule a verifier applies: [Identity API reference](https://sparkvault.com/api/docs/sdk-js/#identity-api-reference); in the monorepo, `docs/SDK.md` → Verifying a sign-in token.
116
+ - `signIn()` resolves only when the person signs in. Cancelling inside the sign-in window, or dismissing the SDK's dialog, rejects with `UserCancelledError` (`code` `user_cancelled`); a blocked or closed popup leaves the dialog open with Try again.
117
+ - To have SparkVault own sessions (refresh rotation, revocation, logout), run OIDC with a backend-for-frontend instead: [Quick Start (OIDC)](https://sparkvault.com/api/docs/products/identity/#quick-start-oidc).
401
118
 
402
- ### Go
403
-
404
- ```go
405
- package main
406
-
407
- import (
408
- "github.com/lestrrat-go/jwx/v2/jwk"
409
- "github.com/lestrrat-go/jwx/v2/jwt"
410
- )
411
-
412
- const (
413
- AccountID = "acc_YOUR_ACCOUNT_ID"
414
- IdentityURL = "https://auth.sparkvault.com"
415
- )
416
-
417
- func verifyToken(tokenString string) (jwt.Token, error) {
418
- jwksURL := fmt.Sprintf("%s/%s/.well-known/jwks.json", IdentityURL, AccountID)
419
-
420
- // Fetch JWKS
421
- keySet, err := jwk.Fetch(context.Background(), jwksURL)
422
- if err != nil {
423
- return nil, err
424
- }
425
-
426
- // Parse and verify token
427
- token, err := jwt.Parse(
428
- []byte(tokenString),
429
- jwt.WithKeySet(keySet),
430
- jwt.WithIssuer(fmt.Sprintf("%s/%s", IdentityURL, AccountID)),
431
- jwt.WithAudience(AccountID),
432
- )
433
- if err != nil {
434
- return nil, err
435
- }
436
-
437
- return token, nil
438
- }
439
-
440
- // Usage in HTTP handler
441
- func loginHandler(w http.ResponseWriter, r *http.Request) {
442
- var body struct {
443
- Token string `json:"token"`
444
- }
445
- json.NewDecoder(r.Body).Decode(&body)
446
-
447
- token, err := verifyToken(body.Token)
448
- if err != nil {
449
- http.Error(w, "Invalid token", http.StatusUnauthorized)
450
- return
451
- }
452
-
453
- svid, _ := token.Get("svid")
454
- if svid == nil {
455
- svid, _ = token.Subject()
456
- }
457
- // Find or create your local user by SVID.
458
- }
459
- ```
119
+ ## Modules
460
120
 
461
- ### Ruby
121
+ | Module | What it does | Reference |
122
+ |--------|--------------|-----------|
123
+ | `products.identity` | The sign-in popup, its redirect return leg, FedCM one-click, auth.sv portal links, an unverified claim decode | [Identity](https://sparkvault.com/api/docs/sdk-js/#identity-api-reference) |
124
+ | `vaults.upload` | The embeddable encrypted upload widget | [Upload](https://sparkvault.com/api/docs/sdk-js/#upload-api-reference) |
125
+ | `vaults` | Vault lifecycle, unseal, sharing, upload settings | [Vaults](https://sparkvault.com/api/docs/sdk-js/#reference-vaults) |
126
+ | `ingots` | Encrypted file transfer over Forge, listing, sharing, access logs | [Ingots](https://sparkvault.com/api/docs/sdk-js/#reference-ingots) |
127
+ | `folders` | Folders within a vault | [Folders](https://sparkvault.com/api/docs/sdk-js/#reference-folders) |
128
+ | `sparks` | Read-once secrets and their SparkLinks | [Sparks](https://sparkvault.com/api/docs/sdk-js/#reference-sparks) |
129
+ | `entropy` | Server-generated random values | [Entropy](https://sparkvault.com/api/docs/sdk-js/#reference-entropy) |
130
+ | `notify` | SparkVault's own inbox and Web Push, for a person signed in to SparkVault itself | [Notifications](https://sparkvault.com/api/docs/sdk-js/#reference-notify) |
131
+ | `products.notify` | Your Notify sends, your recipients' inboxes, send history, receipts and config (server-side, with `apiKey`) | [Notify API](https://sparkvault.com/api/docs/products/notify/) |
132
+ | `health` | API availability | [Health](https://sparkvault.com/api/docs/sdk-js/#health-api-reference) |
462
133
 
463
- ```ruby
464
- require 'jwt'
465
- require 'net/http'
466
- require 'json'
467
-
468
- ACCOUNT_ID = 'acc_YOUR_ACCOUNT_ID'
469
- IDENTITY_URL = 'https://auth.sparkvault.com'
470
-
471
- def verify_identity_token(token)
472
- jwks_url = "#{IDENTITY_URL}/#{ACCOUNT_ID}/.well-known/jwks.json"
473
-
474
- # Fetch JWKS
475
- uri = URI(jwks_url)
476
- response = Net::HTTP.get(uri)
477
- jwks = JSON.parse(response)
478
-
479
- # Decode and verify
480
- JWT.decode(
481
- token,
482
- nil,
483
- true,
484
- {
485
- algorithms: ['EdDSA'],
486
- iss: "#{IDENTITY_URL}/#{ACCOUNT_ID}",
487
- aud: ACCOUNT_ID,
488
- verify_iss: true,
489
- verify_aud: true,
490
- jwks: jwks
491
- }
492
- ).first
493
- end
494
-
495
- # Usage in Rails controller
496
- class AuthController < ApplicationController
497
- def login
498
- claims = verify_identity_token(params[:token])
499
-
500
- svid = claims['svid'] || claims['sub']
501
- user = User.find_or_create_by!(svid: svid)
502
- session[:user_id] = user.id
503
-
504
- render json: { success: true, user: user }
505
- rescue JWT::DecodeError => e
506
- render json: { error: 'Invalid token' }, status: :unauthorized
507
- end
508
- end
509
- ```
510
-
511
- ### Token Claims
512
-
513
- When decoded, the JWT token contains these claims:
514
-
515
- ```json
516
- {
517
- "iss": "https://auth.sparkvault.com/acc_xxx",
518
- "sub": "ing_019e66a4e27875f2822ede0e4f5d8792",
519
- "aud": "acc_xxx",
520
- "svid": "ing_019e66a4e27875f2822ede0e4f5d8792",
521
- "session_id": "sess_abc123",
522
- "token_version": 0,
523
- "identity": "user@example.com",
524
- "identity_type": "email",
525
- "method": "otp_email",
526
- "verified_at": 1703977195,
527
- "iat": 1703977200,
528
- "exp": 1703980800,
529
- "jti": "tok_unique_id"
530
- }
531
- ```
532
-
533
- | Claim | Type | Description |
534
- |-------|------|-------------|
535
- | `iss` | `string` | Issuer URL — always verify this matches expected value |
536
- | `sub` | `string` | Subject — equals the SVID for managed Identity tokens |
537
- | `aud` | `string` | Audience — your account ID |
538
- | `svid` | `string` | Canonical SparkVault ID for the person |
539
- | `session_id` | `string` | Managed Identity session ID |
540
- | `token_version` | `number` | Managed-session version used for revocation/introspection |
541
- | `identity` | `string` | The verified email address or phone number |
542
- | `identity_type` | `string` | `"email"` or `"phone"` |
543
- | `method` | `string` | Authentication method used (e.g., `"otp_email"`, `"passkey"`) |
544
- | `verified_at` | `number` | Unix timestamp when identity was verified |
545
- | `iat` | `number` | Issued at timestamp |
546
- | `exp` | `number` | Expiration timestamp |
547
- | `jti` | `string` | Unique token ID for replay protection |
548
-
549
- ## Full OIDC/BFF Session Ownership
550
-
551
- The JavaScript SDK simple flow is a signed verification proof. It is ideal when
552
- your backend already owns app sessions and only needs to know which SVID was
553
- verified.
554
-
555
- For replacing a production login/session system, use SparkVault Identity as the
556
- OIDC provider and put a backend-for-frontend (BFF) boundary in front of your
557
- application:
558
-
559
- 1. Redirect the browser to `/v1/products/identity/{account_id}/authorize` with PKCE.
560
- 2. Exchange the callback `code` for `id_token`, `access_token`, and `refresh_token` server-side.
561
- 3. Store refresh/session material only in encrypted or signed `HttpOnly`, `Secure`, `SameSite=Lax` cookies.
562
- 4. Keep refresh tokens out of browser JavaScript.
563
- 5. Validate access JWTs locally with cached JWKS for ordinary API requests.
564
- 6. Call `/introspect` only for sensitive mutations, account settings, admin/moderation actions, suspicious sessions, or short cached hard checks.
565
- 7. On logout, call `/revoke` with the current refresh token, then clear local cookies.
566
-
567
- Application data should key people by `svid`. Keep username, roles, profile,
568
- preferences, uploads, and moderation state in your application database.
569
-
570
- ## React Integration
571
-
572
- ```jsx
573
- import { useState, useCallback } from 'react';
574
- import SparkVault from '@sparkvault/sdk-js';
575
-
576
- // Initialize once, outside component
577
- const sparkvault = SparkVault.init({
578
- accountId: 'acc_YOUR_ACCOUNT_ID'
579
- });
580
-
581
- function useSparkVaultAuth() {
582
- const [user, setUser] = useState(null);
583
- const [loading, setLoading] = useState(false);
584
- const [error, setError] = useState(null);
585
-
586
- const login = useCallback(async (options = {}) => {
587
- setLoading(true);
588
- setError(null);
589
-
590
- try {
591
- // Open the sign-in popup
592
- const result = await sparkvault.products.identity.signIn(options);
593
-
594
- // Send token to backend
595
- const response = await fetch('/api/auth/login', {
596
- method: 'POST',
597
- headers: { 'Content-Type': 'application/json' },
598
- body: JSON.stringify({ token: result.token })
599
- });
600
-
601
- if (!response.ok) throw new Error('Login failed');
602
-
603
- const data = await response.json();
604
- setUser(data.user);
605
- return data.user;
606
-
607
- } catch (err) {
608
- if (err.code !== 'user_cancelled') {
609
- setError(err.message);
610
- }
611
- throw err;
612
- } finally {
613
- setLoading(false);
614
- }
615
- }, []);
616
-
617
- const logout = useCallback(async () => {
618
- await fetch('/api/auth/logout', { method: 'POST' });
619
- setUser(null);
620
- }, []);
621
-
622
- return { user, loading, error, login, logout };
623
- }
624
-
625
- // Usage in component
626
- function LoginPage() {
627
- const { user, loading, error, login, logout } = useSparkVaultAuth();
628
-
629
- if (user) {
630
- return (
631
- <div>
632
- <p>Welcome, {user.email}!</p>
633
- <button onClick={logout}>Sign out</button>
634
- </div>
635
- );
636
- }
637
-
638
- return (
639
- <div>
640
- <button onClick={() => login()} disabled={loading}>
641
- {loading ? 'Verifying...' : 'Sign in'}
642
- </button>
643
- {error && <p className="error">{error}</p>}
644
- </div>
645
- );
646
- }
647
- ```
648
-
649
- ## Error Handling
650
-
651
- The SDK throws typed errors that you can catch and handle appropriately.
652
-
653
- ```javascript
654
- import SparkVault, {
655
- UserCancelledError,
656
- ValidationError,
657
- NetworkError,
658
- TimeoutError
659
- } from '@sparkvault/sdk-js';
660
-
661
- try {
662
- const result = await sparkvault.products.identity.signIn();
663
- } catch (error) {
664
- switch (error.code) {
665
- case 'user_cancelled':
666
- // Person closed the popup — not necessarily an error
667
- console.log('User cancelled verification');
668
- break;
669
-
670
- case 'validation_error':
671
- // Invalid input (e.g., malformed email)
672
- console.error('Validation error:', error.message);
673
- break;
674
-
675
- case 'network_error':
676
- // Network connectivity issue
677
- console.error('Network error — please check your connection');
678
- break;
679
-
680
- case 'timeout_error':
681
- // Request timed out
682
- console.error('Request timed out — please try again');
683
- break;
684
-
685
- case 'popup_blocked':
686
- // Browser blocked the popup
687
- console.error('Please allow popups for this site');
688
- break;
689
-
690
- default:
691
- console.error('Unexpected error:', error.message);
692
- }
693
- }
694
- ```
695
-
696
- ### Error Types
697
-
698
- | Error Class | Code | Description |
699
- |-------------|------|-------------|
700
- | `UserCancelledError` | `user_cancelled` | Person closed the popup without completing sign-in |
701
- | `ValidationError` | `validation_error` | Invalid input or configuration |
702
- | `NetworkError` | `network_error` | Network connectivity failure |
703
- | `TimeoutError` | `timeout_error` | Request exceeded timeout limit (the limit covers the whole response, body included) |
704
- | `PopupBlockedError` | `popup_blocked` | Browser blocked the popup window |
705
- | `AuthenticationError` | `authentication_error` | Authentication failed (e.g., expired token) |
706
- | `SparkVaultError` | `download_failed` | The download host refused an ingot download (`statusCode` carries its status) |
707
-
708
- A refused request is typed by its HTTP status even when a gateway answers with
709
- a non-JSON body (an HTML 401 is still an `AuthenticationError`).
710
-
711
- ## TypeScript Support
712
-
713
- The SDK is written in TypeScript and includes full type definitions.
714
-
715
- ```typescript
716
- import SparkVault, {
717
- // Configuration
718
- SparkVaultConfig,
719
-
720
- // Identity types
721
- SignInOptions,
722
- SignInResult,
723
- TokenClaims,
724
-
725
- // Error types
726
- SparkVaultError,
727
- UserCancelledError,
728
- ValidationError,
729
- NetworkError,
730
- TimeoutError,
731
- PopupBlockedError,
732
- } from '@sparkvault/sdk-js';
733
-
734
- // Fully typed configuration
735
- const config: SparkVaultConfig = {
736
- accountId: 'acc_YOUR_ACCOUNT_ID',
737
- timeout: 30000,
738
- };
739
-
740
- const sparkvault = SparkVault.init(config);
741
-
742
- // Fully typed options and result
743
- const options: SignInOptions = {
744
- email: 'user@example.com',
745
- onCancel: () => console.log('Cancelled'),
746
- };
747
-
748
- const result: SignInResult = await sparkvault.products.identity.signIn(options);
749
- // result.token: string
750
- // result.identity: string
751
- // result.identityType: 'email' | 'phone'
752
- ```
134
+ `products.identity`, `vaults.upload` and `health` send neither a Core JWT nor an `apiKey`. The widget needs the vault's Embedded Upload Widget setting enabled, with or without a `token`: it opens by reading the vault's upload info, a request that carries no VAT and is refused while the setting is off. The other modules call the Core API with a Core JWT (`accessToken` or `getAccessToken`) or, server-side, an `apiKey`; `notify` needs a SparkVault user's session JWT. Configuration, errors and TypeScript: the [reference](https://sparkvault.com/api/docs/sdk-js/#configuration-options).
753
135
 
754
136
  ## Content Security Policy (CSP)
755
137
 
756
- If your site uses a Content Security Policy, you must allow the SparkVault domains:
138
+ A page with a Content Security Policy adds these sources to its directives:
757
139
 
758
140
  ```
759
- connect-src https://auth.sparkvault.com https://api.sparkvault.com https://forge.sparkvault.com wss://ws.sparkvault.com;
141
+ connect-src https://auth.sparkvault.com https://api.sparkvault.com https://forge.sparkvault.com;
760
142
  script-src https://cdn.sparkvault.com;
143
+ style-src 'unsafe-inline';
144
+ img-src https://img.sparkvault.com;
761
145
  ```
762
146
 
763
- | Directive | Domain | Reason |
147
+ | Directive | Source | Reason |
764
148
  |-----------|--------|--------|
765
- | `connect-src` | `https://auth.sparkvault.com` | Identity verification (config, OTP, passkey, SparkLink) and the entropy draw a sign-in binds its PKCE verifier, state and nonce with |
766
- | `connect-src` | `https://api.sparkvault.com` | SparkVault Core API (vaults, ingots, sessions) |
767
- | `connect-src` | `https://forge.sparkvault.com` | Encrypted file transfers (the vault upload widget, `sv.ingots` uploads and downloads) |
768
- | `connect-src` | `wss://ws.sparkvault.com` | WebSocket for SparkLink push notifications |
769
- | `script-src` | `https://cdn.sparkvault.com` | SDK script (if using CDN installation) |
770
-
771
- ## Best Practices
772
-
773
- 1. **Initialize Once** — Create the SparkVault instance once when your app loads, not on every login attempt. The SDK preloads configuration so the popup opens instantly.
774
-
775
- 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.
776
-
777
- 3. **Handle Cancellation Gracefully** — People may close the popup without completing sign-in. This throws a `UserCancelledError` — handle it gracefully rather than showing an error message.
778
-
779
- 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.
780
-
781
- 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.
782
-
783
- 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.
784
-
785
- ## Browser Support
149
+ | `connect-src` | `https://auth.sparkvault.com` | Identity: the `/config` preload, the entropy draw behind a redirect's PKCE values and FedCM's nonce, redeeming a returned sign-in code |
150
+ | `connect-src` | `https://api.sparkvault.com` | The Core API (vaults, ingots, the upload widget, Notify) |
151
+ | `connect-src` | `https://forge.sparkvault.com` | Encrypted transfers (the upload widget, `ingots` uploads and downloads) |
152
+ | `script-src` | `https://cdn.sparkvault.com` | The SDK script, when loaded from the CDN |
153
+ | `style-src` | `'unsafe-inline'` | The sign-in dialog and the upload widget inject their stylesheet as a `<style>` element |
154
+ | `img-src` | `https://img.sparkvault.com` | The account's logo in the sign-in dialog and the upload widget |
786
155
 
787
- The SDK supports all modern browsers:
156
+ The sign-in itself (OTP, passkey, SparkLink's WebSocket, social) runs on the sign-in page at auth.sparkvault.com, under that page's own policy.
788
157
 
789
- - Chrome 80+
790
- - Firefox 75+
791
- - Safari 13.1+
792
- - Edge 80+
158
+ ## Browser support
793
159
 
794
- **Note:** Passkey authentication requires WebAuthn support. On unsupported browsers, passkey will not appear as an option — other methods will still work.
160
+ - Chrome and Edge 93+, Firefox 92+, Safari 15.4+: the floor of `Object.hasOwn`, which `SparkVault.init()` calls to validate the account id. On an older browser `init()` throws, and the CDN's auto-init logs the failure and leaves `window.SparkVault` the class.
161
+ - A passkey needs WebAuthn: where a browser lacks it, the ceremony fails and the person continues with another method the account enables.
795
162
 
796
- ## Build & Release
163
+ ## Build and release
797
164
 
798
- The SDK is built, tested and released from the `Spark-Vault/platform` monorepo, in `packages/sdk-js`. Run its scripts from the repository root with `npx pnpm --filter @sparkvault/sdk-js <script>`: `build`, `build:watch`, `typecheck`, `lint`, `test`, `test:watch` and `test:package`. A push to `main` that changes the package's code runs `.github/workflows/deploy-sdk-js.yml`, which publishes the package to npm and the bundles to the CDN. The SDK's architecture is in the monorepo's `docs/SDK.md`, and its release pipeline in `docs/INFRASTRUCTURE.md`.
165
+ The SDK is built, tested and released from the `Spark-Vault/platform` monorepo (`packages/sdk-js`). From the repository root, with the repo's pinned pnpm (`packageManager`): `pnpm --filter @sparkvault/sdk-js <script>`, for `build`, `build:watch`, `typecheck`, `lint`, `test`, `test:watch` and `test:package`. A push to `main` that changes the package's code, or an app-sdk module its bundle inlines, runs `.github/workflows/deploy-sdk-js.yml`, which publishes the package to npm and the bundles to the CDN. Design: `docs/SDK.md`; release pipeline and CDN cache tiers: `docs/INFRASTRUCTURE.md`.
799
166
 
800
167
  ## License
801
168
 
802
- MIT License.
169
+ MIT.
803
170
 
804
171
  ## Links
805
172
 
806
- - [SparkVault Documentation](https://sparkvault.com/api/docs/)
807
- - [SDK API Reference](https://sparkvault.com/api/docs/sdk-js/)
808
- - [GitHub Repository](https://github.com/Spark-Vault/platform)
809
- - [npm Package](https://www.npmjs.com/package/@sparkvault/sdk-js)
810
- - [Report Issues](https://github.com/Spark-Vault/platform/issues)
173
+ - [SparkVault API documentation](https://sparkvault.com/api/docs/)
174
+ - [JavaScript SDK reference](https://sparkvault.com/api/docs/sdk-js/)
175
+ - [npm package](https://www.npmjs.com/package/@sparkvault/sdk-js)