@sparkvault/sdk-js 1.24.4
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 +769 -0
- package/dist/api-base.d.ts +58 -0
- package/dist/auto-init.d.ts +32 -0
- package/dist/config.d.ts +41 -0
- package/dist/errors.d.ts +30 -0
- package/dist/health.d.ts +18 -0
- package/dist/http.d.ts +51 -0
- package/dist/identity/api.d.ts +110 -0
- package/dist/identity/container.d.ts +56 -0
- package/dist/identity/handlers/index.d.ts +9 -0
- package/dist/identity/handlers/passkey-handler.d.ts +69 -0
- package/dist/identity/handlers/sparklink-handler.d.ts +30 -0
- package/dist/identity/handlers/totp-handler.d.ts +52 -0
- package/dist/identity/index.d.ts +89 -0
- package/dist/identity/inline-container.d.ts +65 -0
- package/dist/identity/methods.d.ts +23 -0
- package/dist/identity/modal.d.ts +82 -0
- package/dist/identity/renderer.d.ts +146 -0
- package/dist/identity/state.d.ts +98 -0
- package/dist/identity/styles.d.ts +22 -0
- package/dist/identity/types.d.ts +221 -0
- package/dist/identity/utils/cooldown-timer.d.ts +73 -0
- package/dist/identity/utils/index.d.ts +5 -0
- package/dist/identity/utils.d.ts +39 -0
- package/dist/identity/views/app-not-activated.d.ts +21 -0
- package/dist/identity/views/base.d.ts +62 -0
- package/dist/identity/views/error.d.ts +25 -0
- package/dist/identity/views/icons.d.ts +38 -0
- package/dist/identity/views/identity-input.d.ts +48 -0
- package/dist/identity/views/index.d.ts +16 -0
- package/dist/identity/views/loading.d.ts +15 -0
- package/dist/identity/views/method-select.d.ts +29 -0
- package/dist/identity/views/passkey-prompt.d.ts +24 -0
- package/dist/identity/views/passkey.d.ts +38 -0
- package/dist/identity/views/service-unavailable.d.ts +21 -0
- package/dist/identity/views/sparklink-waiting.d.ts +40 -0
- package/dist/identity/views/totp-verify.d.ts +58 -0
- package/dist/index.d.ts +733 -0
- package/dist/logger.d.ts +45 -0
- package/dist/rng/index.d.ts +54 -0
- package/dist/rng/types.d.ts +26 -0
- package/dist/sparks/index.d.ts +37 -0
- package/dist/sparks/types.d.ts +56 -0
- package/dist/sparkvault.cjs.js +10167 -0
- package/dist/sparkvault.cjs.js.map +1 -0
- package/dist/sparkvault.esm.js +10152 -0
- package/dist/sparkvault.esm.js.map +1 -0
- package/dist/sparkvault.js +2 -0
- package/dist/sparkvault.js.map +1 -0
- package/dist/utils/base64url.d.ts +41 -0
- package/dist/utils/dom.d.ts +17 -0
- package/dist/utils/retry.d.ts +32 -0
- package/dist/vaults/index.d.ts +109 -0
- package/dist/vaults/types.d.ts +128 -0
- package/dist/vaults/upload/api.d.ts +36 -0
- package/dist/vaults/upload/container.d.ts +57 -0
- package/dist/vaults/upload/index.d.ts +75 -0
- package/dist/vaults/upload/inline-container.d.ts +75 -0
- package/dist/vaults/upload/modal.d.ts +79 -0
- package/dist/vaults/upload/renderer.d.ts +70 -0
- package/dist/vaults/upload/styles.d.ts +20 -0
- package/dist/vaults/upload/types.d.ts +182 -0
- package/package.json +63 -0
package/README.md
ADDED
|
@@ -0,0 +1,769 @@
|
|
|
1
|
+
# SparkVault JavaScript SDK
|
|
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.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@sparkvault/sdk-js)
|
|
6
|
+
[](https://opensource.org/licenses/MIT)
|
|
7
|
+
|
|
8
|
+
## Table of Contents
|
|
9
|
+
|
|
10
|
+
- [Installation](#installation)
|
|
11
|
+
- [Zero-Config Integration](#zero-config-integration)
|
|
12
|
+
- [Manual Initialization](#manual-initialization)
|
|
13
|
+
- [Identity Verification](#identity-verification)
|
|
14
|
+
- [Backend Token Verification](#backend-token-verification)
|
|
15
|
+
- [React Integration](#react-integration)
|
|
16
|
+
- [Error Handling](#error-handling)
|
|
17
|
+
- [TypeScript Support](#typescript-support)
|
|
18
|
+
- [Browser Support](#browser-support)
|
|
19
|
+
- [Build & Release](#build--release)
|
|
20
|
+
- [License](#license)
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
### CDN (Recommended)
|
|
25
|
+
|
|
26
|
+
```html
|
|
27
|
+
<script src="https://cdn.sparkvault.com/sdk/v1/sparkvault.js"></script>
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### npm / yarn
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
npm install @sparkvault/sdk-js
|
|
34
|
+
# or
|
|
35
|
+
yarn add @sparkvault/sdk-js
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
**Bundle Formats:**
|
|
39
|
+
- `sparkvault.js` — UMD bundle for browsers (recommended)
|
|
40
|
+
- `sparkvault.esm.js` — ES modules for modern bundlers
|
|
41
|
+
- `sparkvault.cjs.js` — CommonJS for Node.js
|
|
42
|
+
|
|
43
|
+
## Zero-Config Integration
|
|
44
|
+
|
|
45
|
+
Add SparkVault authentication to your site with a single script tag — no JavaScript required!
|
|
46
|
+
|
|
47
|
+
```html
|
|
48
|
+
<!-- Add this single script tag -->
|
|
49
|
+
<script
|
|
50
|
+
async
|
|
51
|
+
src="https://cdn.sparkvault.com/sdk/v1/sparkvault.js"
|
|
52
|
+
data-account-id="acc_YOUR_ACCOUNT_ID"
|
|
53
|
+
data-attach-selector=".login-btn"
|
|
54
|
+
data-success-url="/auth/verify-token"
|
|
55
|
+
></script>
|
|
56
|
+
|
|
57
|
+
<!-- Any element matching the selector becomes a login button -->
|
|
58
|
+
<button class="login-btn">Sign In</button>
|
|
59
|
+
<a href="#" class="login-btn">Create Account</a>
|
|
60
|
+
```
|
|
61
|
+
|
|
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
|
+
|
|
69
|
+
### Data Attributes
|
|
70
|
+
|
|
71
|
+
| Attribute | Required | Description |
|
|
72
|
+
|-----------|----------|-------------|
|
|
73
|
+
| `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
|
+
| `data-debug` | No | Set to `"true"` for verbose console logging |
|
|
82
|
+
|
|
83
|
+
### Complete Example
|
|
84
|
+
|
|
85
|
+
```html
|
|
86
|
+
<script
|
|
87
|
+
async
|
|
88
|
+
src="https://cdn.sparkvault.com/sdk/v1/sparkvault.js"
|
|
89
|
+
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
|
+
data-debug="true"
|
|
95
|
+
></script>
|
|
96
|
+
|
|
97
|
+
<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
|
+
}
|
|
109
|
+
</script>
|
|
110
|
+
|
|
111
|
+
<!-- Multiple elements can use the same selector -->
|
|
112
|
+
<button class="js-sparkvault-auth">Sign In</button>
|
|
113
|
+
<a href="#" class="js-sparkvault-auth">Login with SparkVault</a>
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Success URL Response
|
|
117
|
+
|
|
118
|
+
When you specify `data-success-url`, the SDK POSTs the verification result:
|
|
119
|
+
|
|
120
|
+
```json
|
|
121
|
+
{
|
|
122
|
+
"token": "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9...",
|
|
123
|
+
"identity": "user@example.com",
|
|
124
|
+
"identityType": "email"
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
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
|
+
```
|
|
142
|
+
|
|
143
|
+
### Manual Trigger from JavaScript
|
|
144
|
+
|
|
145
|
+
You can also trigger authentication programmatically using the `SparkVault` global:
|
|
146
|
+
|
|
147
|
+
```javascript
|
|
148
|
+
// Trigger authentication from anywhere in your code
|
|
149
|
+
SparkVault.identity.pop();
|
|
150
|
+
|
|
151
|
+
// This uses your configured success/error handlers
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
```html
|
|
155
|
+
<button onclick="SparkVault.identity.pop()">
|
|
156
|
+
Sign In with SparkVault
|
|
157
|
+
</button>
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## Manual Initialization
|
|
161
|
+
|
|
162
|
+
For full control over the SDK, initialize it manually in JavaScript:
|
|
163
|
+
|
|
164
|
+
```javascript
|
|
165
|
+
import SparkVault from '@sparkvault/sdk-js';
|
|
166
|
+
|
|
167
|
+
const sparkvault = SparkVault.init({
|
|
168
|
+
accountId: 'acc_YOUR_ACCOUNT_ID' // Required
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
// The SDK is now ready to use
|
|
172
|
+
const result = await sparkvault.identity.pop();
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Configuration Options
|
|
176
|
+
|
|
177
|
+
| Option | Type | Default | Description |
|
|
178
|
+
|--------|------|---------|-------------|
|
|
179
|
+
| `accountId` | `string` | **required** | Your SparkVault account ID (starts with `acc_`) |
|
|
180
|
+
| `timeout` | `number` | `30000` | HTTP request timeout in milliseconds |
|
|
181
|
+
| `preloadConfig` | `boolean` | `true` | Preload Identity config for instant modal |
|
|
182
|
+
|
|
183
|
+
### CDN Usage
|
|
184
|
+
|
|
185
|
+
```html
|
|
186
|
+
<script src="https://cdn.sparkvault.com/sdk/v1/sparkvault.js"></script>
|
|
187
|
+
<script>
|
|
188
|
+
const sparkvault = SparkVault.init({
|
|
189
|
+
accountId: 'acc_YOUR_ACCOUNT_ID'
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
document.getElementById('login-btn').addEventListener('click', async () => {
|
|
193
|
+
const result = await sparkvault.identity.pop();
|
|
194
|
+
console.log('Verified:', result.identity);
|
|
195
|
+
});
|
|
196
|
+
</script>
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
## Identity Verification
|
|
200
|
+
|
|
201
|
+
The Identity module provides passwordless authentication through a beautiful, customizable modal. Users can verify via passkeys, email codes, SMS codes, SparkLink, or social providers.
|
|
202
|
+
|
|
203
|
+
### Basic Usage
|
|
204
|
+
|
|
205
|
+
```javascript
|
|
206
|
+
// Open the verification modal
|
|
207
|
+
const result = await sparkvault.identity.pop();
|
|
208
|
+
|
|
209
|
+
// User verified!
|
|
210
|
+
console.log(result.identity); // "user@example.com" or "+14155551234"
|
|
211
|
+
console.log(result.identityType); // "email" or "phone"
|
|
212
|
+
console.log(result.token); // Signed JWT token
|
|
213
|
+
|
|
214
|
+
// Send the token to your backend for verification
|
|
215
|
+
await fetch('/api/auth/login', {
|
|
216
|
+
method: 'POST',
|
|
217
|
+
headers: { 'Content-Type': 'application/json' },
|
|
218
|
+
body: JSON.stringify({ token: result.token })
|
|
219
|
+
});
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
### pop() Options
|
|
223
|
+
|
|
224
|
+
| Option | Type | Description |
|
|
225
|
+
|--------|------|-------------|
|
|
226
|
+
| `email` | `string` | Pre-fill email address (mutually exclusive with phone) |
|
|
227
|
+
| `phone` | `string` | Pre-fill phone in E.164 format, e.g. `"+14155551234"` |
|
|
228
|
+
| `backdropBlur` | `boolean` | Override backdrop blur setting from app config |
|
|
229
|
+
| `onCancel` | `function` | Callback when user closes modal without verifying |
|
|
230
|
+
| `onSuccess` | `function` | Callback on success (before promise resolves) |
|
|
231
|
+
| `onError` | `function` | Callback on error (before promise rejects) |
|
|
232
|
+
|
|
233
|
+
### pop() Result
|
|
234
|
+
|
|
235
|
+
| Field | Type | Description |
|
|
236
|
+
|-------|------|-------------|
|
|
237
|
+
| `token` | `string` | Signed JWT token (Ed25519). Verify this on your backend. |
|
|
238
|
+
| `identity` | `string` | The verified email address or phone number |
|
|
239
|
+
| `identityType` | `"email" \| "phone"` | Type of identity that was verified |
|
|
240
|
+
|
|
241
|
+
### Example with Options
|
|
242
|
+
|
|
243
|
+
```javascript
|
|
244
|
+
try {
|
|
245
|
+
const result = await sparkvault.identity.pop({
|
|
246
|
+
// Pre-fill the email field
|
|
247
|
+
email: 'user@example.com',
|
|
248
|
+
|
|
249
|
+
// Handle cancellation
|
|
250
|
+
onCancel: () => {
|
|
251
|
+
console.log('User cancelled');
|
|
252
|
+
}
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
// Success! Send token to your backend
|
|
256
|
+
await loginWithToken(result.token);
|
|
257
|
+
|
|
258
|
+
} catch (error) {
|
|
259
|
+
if (error.code === 'user_cancelled') {
|
|
260
|
+
// User closed the modal
|
|
261
|
+
} else {
|
|
262
|
+
// Handle other errors
|
|
263
|
+
console.error('Verification failed:', error.message);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
### Authentication Methods
|
|
269
|
+
|
|
270
|
+
Authentication methods are configured in your Identity App settings. The SDK automatically shows only the methods you have enabled.
|
|
271
|
+
|
|
272
|
+
| Method | Description | Identity Type |
|
|
273
|
+
|--------|-------------|---------------|
|
|
274
|
+
| `passkey` | WebAuthn/FIDO2 biometric or security key | Email |
|
|
275
|
+
| `totp_email` | 6-digit code sent via email | Email |
|
|
276
|
+
| `totp_sms` | 6-digit code sent via SMS | Phone |
|
|
277
|
+
| `totp_voice` | 6-digit code sent via voice call | Phone |
|
|
278
|
+
| `sparklink` | One-click sign-in link via email | Email |
|
|
279
|
+
| `social_google` | Sign in with Google | Email |
|
|
280
|
+
| `social_apple` | Sign in with Apple | Email |
|
|
281
|
+
| `social_microsoft` | Sign in with Microsoft | Email |
|
|
282
|
+
| `social_github` | Sign in with GitHub | Email |
|
|
283
|
+
| `social_facebook` | Sign in with Facebook | Email |
|
|
284
|
+
| `social_linkedin` | Sign in with LinkedIn | Email |
|
|
285
|
+
|
|
286
|
+
## Backend Token Verification
|
|
287
|
+
|
|
288
|
+
> **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.
|
|
289
|
+
|
|
290
|
+
### Node.js
|
|
291
|
+
|
|
292
|
+
```javascript
|
|
293
|
+
import * as jose from 'jose';
|
|
294
|
+
|
|
295
|
+
const ACCOUNT_ID = 'acc_YOUR_ACCOUNT_ID';
|
|
296
|
+
const IDENTITY_URL = 'https://api.sparkvault.com/v1/apps/identity';
|
|
297
|
+
|
|
298
|
+
app.post('/api/auth/login', async (req, res) => {
|
|
299
|
+
const { token } = req.body;
|
|
300
|
+
|
|
301
|
+
try {
|
|
302
|
+
// Fetch public keys and verify signature
|
|
303
|
+
const jwksUrl = `${IDENTITY_URL}/${ACCOUNT_ID}/.well-known/jwks.json`;
|
|
304
|
+
const JWKS = jose.createRemoteJWKSet(new URL(jwksUrl));
|
|
305
|
+
|
|
306
|
+
const { payload } = await jose.jwtVerify(token, JWKS, {
|
|
307
|
+
issuer: `${IDENTITY_URL}/${ACCOUNT_ID}`,
|
|
308
|
+
audience: ACCOUNT_ID
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
// Token is valid! Create user session
|
|
312
|
+
const user = await findOrCreateUser(payload.identity, payload.identity_type);
|
|
313
|
+
req.session.userId = user.id;
|
|
314
|
+
|
|
315
|
+
res.json({ success: true, user });
|
|
316
|
+
} catch (error) {
|
|
317
|
+
res.status(401).json({ error: 'Invalid token' });
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
### Python
|
|
323
|
+
|
|
324
|
+
```python
|
|
325
|
+
import jwt
|
|
326
|
+
from jwt import PyJWKClient
|
|
327
|
+
|
|
328
|
+
ACCOUNT_ID = 'acc_YOUR_ACCOUNT_ID'
|
|
329
|
+
IDENTITY_URL = 'https://api.sparkvault.com/v1/apps/identity'
|
|
330
|
+
|
|
331
|
+
def verify_identity_token(token: str):
|
|
332
|
+
"""Verify a SparkVault Identity token and return the claims."""
|
|
333
|
+
jwks_url = f"{IDENTITY_URL}/{ACCOUNT_ID}/.well-known/jwks.json"
|
|
334
|
+
jwks_client = PyJWKClient(jwks_url)
|
|
335
|
+
|
|
336
|
+
# Get the signing key
|
|
337
|
+
signing_key = jwks_client.get_signing_key_from_jwt(token)
|
|
338
|
+
|
|
339
|
+
# Verify and decode
|
|
340
|
+
claims = jwt.decode(
|
|
341
|
+
token,
|
|
342
|
+
signing_key.key,
|
|
343
|
+
algorithms=["EdDSA"],
|
|
344
|
+
issuer=f"{IDENTITY_URL}/{ACCOUNT_ID}",
|
|
345
|
+
audience=ACCOUNT_ID
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
return claims
|
|
349
|
+
|
|
350
|
+
# Usage in Flask
|
|
351
|
+
@app.route('/api/auth/login', methods=['POST'])
|
|
352
|
+
def login():
|
|
353
|
+
token = request.json.get('token')
|
|
354
|
+
|
|
355
|
+
try:
|
|
356
|
+
claims = verify_identity_token(token)
|
|
357
|
+
|
|
358
|
+
# Create session
|
|
359
|
+
user = find_or_create_user(claims['identity'], claims['identity_type'])
|
|
360
|
+
session['user_id'] = user.id
|
|
361
|
+
|
|
362
|
+
return jsonify({'success': True, 'user': user.to_dict()})
|
|
363
|
+
except jwt.InvalidTokenError as e:
|
|
364
|
+
return jsonify({'error': 'Invalid token'}), 401
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
### Go
|
|
368
|
+
|
|
369
|
+
```go
|
|
370
|
+
package main
|
|
371
|
+
|
|
372
|
+
import (
|
|
373
|
+
"github.com/lestrrat-go/jwx/v2/jwk"
|
|
374
|
+
"github.com/lestrrat-go/jwx/v2/jwt"
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
const (
|
|
378
|
+
AccountID = "acc_YOUR_ACCOUNT_ID"
|
|
379
|
+
IdentityURL = "https://api.sparkvault.com/v1/apps/identity"
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
func verifyToken(tokenString string) (jwt.Token, error) {
|
|
383
|
+
jwksURL := fmt.Sprintf("%s/%s/.well-known/jwks.json", IdentityURL, AccountID)
|
|
384
|
+
|
|
385
|
+
// Fetch JWKS
|
|
386
|
+
keySet, err := jwk.Fetch(context.Background(), jwksURL)
|
|
387
|
+
if err != nil {
|
|
388
|
+
return nil, err
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// Parse and verify token
|
|
392
|
+
token, err := jwt.Parse(
|
|
393
|
+
[]byte(tokenString),
|
|
394
|
+
jwt.WithKeySet(keySet),
|
|
395
|
+
jwt.WithIssuer(fmt.Sprintf("%s/%s", IdentityURL, AccountID)),
|
|
396
|
+
jwt.WithAudience(AccountID),
|
|
397
|
+
)
|
|
398
|
+
if err != nil {
|
|
399
|
+
return nil, err
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
return token, nil
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// Usage in HTTP handler
|
|
406
|
+
func loginHandler(w http.ResponseWriter, r *http.Request) {
|
|
407
|
+
var body struct {
|
|
408
|
+
Token string `json:"token"`
|
|
409
|
+
}
|
|
410
|
+
json.NewDecoder(r.Body).Decode(&body)
|
|
411
|
+
|
|
412
|
+
token, err := verifyToken(body.Token)
|
|
413
|
+
if err != nil {
|
|
414
|
+
http.Error(w, "Invalid token", http.StatusUnauthorized)
|
|
415
|
+
return
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
identity, _ := token.Get("identity")
|
|
419
|
+
// Create session with identity...
|
|
420
|
+
}
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
### Ruby
|
|
424
|
+
|
|
425
|
+
```ruby
|
|
426
|
+
require 'jwt'
|
|
427
|
+
require 'net/http'
|
|
428
|
+
require 'json'
|
|
429
|
+
|
|
430
|
+
ACCOUNT_ID = 'acc_YOUR_ACCOUNT_ID'
|
|
431
|
+
IDENTITY_URL = 'https://api.sparkvault.com/v1/apps/identity'
|
|
432
|
+
|
|
433
|
+
def verify_identity_token(token)
|
|
434
|
+
jwks_url = "#{IDENTITY_URL}/#{ACCOUNT_ID}/.well-known/jwks.json"
|
|
435
|
+
|
|
436
|
+
# Fetch JWKS
|
|
437
|
+
uri = URI(jwks_url)
|
|
438
|
+
response = Net::HTTP.get(uri)
|
|
439
|
+
jwks = JSON.parse(response)
|
|
440
|
+
|
|
441
|
+
# Decode and verify
|
|
442
|
+
JWT.decode(
|
|
443
|
+
token,
|
|
444
|
+
nil,
|
|
445
|
+
true,
|
|
446
|
+
{
|
|
447
|
+
algorithms: ['EdDSA'],
|
|
448
|
+
iss: "#{IDENTITY_URL}/#{ACCOUNT_ID}",
|
|
449
|
+
aud: ACCOUNT_ID,
|
|
450
|
+
verify_iss: true,
|
|
451
|
+
verify_aud: true,
|
|
452
|
+
jwks: jwks
|
|
453
|
+
}
|
|
454
|
+
).first
|
|
455
|
+
end
|
|
456
|
+
|
|
457
|
+
# Usage in Rails controller
|
|
458
|
+
class AuthController < ApplicationController
|
|
459
|
+
def login
|
|
460
|
+
claims = verify_identity_token(params[:token])
|
|
461
|
+
|
|
462
|
+
user = User.find_or_create_by(email: claims['identity'])
|
|
463
|
+
session[:user_id] = user.id
|
|
464
|
+
|
|
465
|
+
render json: { success: true, user: user }
|
|
466
|
+
rescue JWT::DecodeError => e
|
|
467
|
+
render json: { error: 'Invalid token' }, status: :unauthorized
|
|
468
|
+
end
|
|
469
|
+
end
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
### Token Claims
|
|
473
|
+
|
|
474
|
+
When decoded, the JWT token contains these claims:
|
|
475
|
+
|
|
476
|
+
```json
|
|
477
|
+
{
|
|
478
|
+
"iss": "https://api.sparkvault.com/v1/apps/identity/acc_xxx",
|
|
479
|
+
"sub": "identity:a1b2c3d4e5f67890",
|
|
480
|
+
"aud": "acc_xxx",
|
|
481
|
+
"identity": "user@example.com",
|
|
482
|
+
"identity_type": "email",
|
|
483
|
+
"method": "totp_email",
|
|
484
|
+
"verified_at": 1703977195,
|
|
485
|
+
"iat": 1703977200,
|
|
486
|
+
"exp": 1703980800,
|
|
487
|
+
"jti": "tok_unique_id"
|
|
488
|
+
}
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
| Claim | Type | Description |
|
|
492
|
+
|-------|------|-------------|
|
|
493
|
+
| `iss` | `string` | Issuer URL — always verify this matches expected value |
|
|
494
|
+
| `sub` | `string` | Subject — hashed identity for consistent user identification |
|
|
495
|
+
| `aud` | `string` | Audience — your account ID |
|
|
496
|
+
| `identity` | `string` | The verified email address or phone number |
|
|
497
|
+
| `identity_type` | `string` | `"email"` or `"phone"` |
|
|
498
|
+
| `method` | `string` | Authentication method used (e.g., `"totp_email"`, `"passkey"`) |
|
|
499
|
+
| `verified_at` | `number` | Unix timestamp when identity was verified |
|
|
500
|
+
| `iat` | `number` | Issued at timestamp |
|
|
501
|
+
| `exp` | `number` | Expiration timestamp |
|
|
502
|
+
| `jti` | `string` | Unique token ID for replay protection |
|
|
503
|
+
|
|
504
|
+
## React Integration
|
|
505
|
+
|
|
506
|
+
```jsx
|
|
507
|
+
import { useState, useCallback } from 'react';
|
|
508
|
+
import SparkVault from '@sparkvault/sdk-js';
|
|
509
|
+
|
|
510
|
+
// Initialize once, outside component
|
|
511
|
+
const sparkvault = SparkVault.init({
|
|
512
|
+
accountId: 'acc_YOUR_ACCOUNT_ID'
|
|
513
|
+
});
|
|
514
|
+
|
|
515
|
+
function useSparkVaultAuth() {
|
|
516
|
+
const [user, setUser] = useState(null);
|
|
517
|
+
const [loading, setLoading] = useState(false);
|
|
518
|
+
const [error, setError] = useState(null);
|
|
519
|
+
|
|
520
|
+
const login = useCallback(async (options = {}) => {
|
|
521
|
+
setLoading(true);
|
|
522
|
+
setError(null);
|
|
523
|
+
|
|
524
|
+
try {
|
|
525
|
+
// Open verification modal
|
|
526
|
+
const result = await sparkvault.identity.pop(options);
|
|
527
|
+
|
|
528
|
+
// Send token to backend
|
|
529
|
+
const response = await fetch('/api/auth/login', {
|
|
530
|
+
method: 'POST',
|
|
531
|
+
headers: { 'Content-Type': 'application/json' },
|
|
532
|
+
body: JSON.stringify({ token: result.token })
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
if (!response.ok) throw new Error('Login failed');
|
|
536
|
+
|
|
537
|
+
const data = await response.json();
|
|
538
|
+
setUser(data.user);
|
|
539
|
+
return data.user;
|
|
540
|
+
|
|
541
|
+
} catch (err) {
|
|
542
|
+
if (err.code !== 'user_cancelled') {
|
|
543
|
+
setError(err.message);
|
|
544
|
+
}
|
|
545
|
+
throw err;
|
|
546
|
+
} finally {
|
|
547
|
+
setLoading(false);
|
|
548
|
+
}
|
|
549
|
+
}, []);
|
|
550
|
+
|
|
551
|
+
const logout = useCallback(async () => {
|
|
552
|
+
await fetch('/api/auth/logout', { method: 'POST' });
|
|
553
|
+
setUser(null);
|
|
554
|
+
}, []);
|
|
555
|
+
|
|
556
|
+
return { user, loading, error, login, logout };
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// Usage in component
|
|
560
|
+
function LoginPage() {
|
|
561
|
+
const { user, loading, error, login, logout } = useSparkVaultAuth();
|
|
562
|
+
|
|
563
|
+
if (user) {
|
|
564
|
+
return (
|
|
565
|
+
<div>
|
|
566
|
+
<p>Welcome, {user.email}!</p>
|
|
567
|
+
<button onClick={logout}>Sign out</button>
|
|
568
|
+
</div>
|
|
569
|
+
);
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
return (
|
|
573
|
+
<div>
|
|
574
|
+
<button onClick={() => login()} disabled={loading}>
|
|
575
|
+
{loading ? 'Verifying...' : 'Sign in'}
|
|
576
|
+
</button>
|
|
577
|
+
{error && <p className="error">{error}</p>}
|
|
578
|
+
</div>
|
|
579
|
+
);
|
|
580
|
+
}
|
|
581
|
+
```
|
|
582
|
+
|
|
583
|
+
## Error Handling
|
|
584
|
+
|
|
585
|
+
The SDK throws typed errors that you can catch and handle appropriately.
|
|
586
|
+
|
|
587
|
+
```javascript
|
|
588
|
+
import SparkVault, {
|
|
589
|
+
UserCancelledError,
|
|
590
|
+
ValidationError,
|
|
591
|
+
NetworkError,
|
|
592
|
+
TimeoutError
|
|
593
|
+
} from '@sparkvault/sdk-js';
|
|
594
|
+
|
|
595
|
+
try {
|
|
596
|
+
const result = await sparkvault.identity.pop();
|
|
597
|
+
} catch (error) {
|
|
598
|
+
switch (error.code) {
|
|
599
|
+
case 'user_cancelled':
|
|
600
|
+
// User closed the modal — not necessarily an error
|
|
601
|
+
console.log('User cancelled verification');
|
|
602
|
+
break;
|
|
603
|
+
|
|
604
|
+
case 'validation_error':
|
|
605
|
+
// Invalid input (e.g., malformed email)
|
|
606
|
+
console.error('Validation error:', error.message);
|
|
607
|
+
break;
|
|
608
|
+
|
|
609
|
+
case 'network_error':
|
|
610
|
+
// Network connectivity issue
|
|
611
|
+
console.error('Network error — please check your connection');
|
|
612
|
+
break;
|
|
613
|
+
|
|
614
|
+
case 'timeout_error':
|
|
615
|
+
// Request timed out
|
|
616
|
+
console.error('Request timed out — please try again');
|
|
617
|
+
break;
|
|
618
|
+
|
|
619
|
+
case 'popup_blocked':
|
|
620
|
+
// Browser blocked the popup
|
|
621
|
+
console.error('Please allow popups for this site');
|
|
622
|
+
break;
|
|
623
|
+
|
|
624
|
+
default:
|
|
625
|
+
console.error('Unexpected error:', error.message);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
```
|
|
629
|
+
|
|
630
|
+
### Error Types
|
|
631
|
+
|
|
632
|
+
| Error Class | Code | Description |
|
|
633
|
+
|-------------|------|-------------|
|
|
634
|
+
| `UserCancelledError` | `user_cancelled` | User closed the modal without completing verification |
|
|
635
|
+
| `ValidationError` | `validation_error` | Invalid input or configuration |
|
|
636
|
+
| `NetworkError` | `network_error` | Network connectivity failure |
|
|
637
|
+
| `TimeoutError` | `timeout_error` | Request exceeded timeout limit |
|
|
638
|
+
| `PopupBlockedError` | `popup_blocked` | Browser blocked the popup window |
|
|
639
|
+
| `AuthenticationError` | `authentication_error` | Authentication failed (e.g., expired token) |
|
|
640
|
+
|
|
641
|
+
## TypeScript Support
|
|
642
|
+
|
|
643
|
+
The SDK is written in TypeScript and includes full type definitions.
|
|
644
|
+
|
|
645
|
+
```typescript
|
|
646
|
+
import SparkVault, {
|
|
647
|
+
// Configuration
|
|
648
|
+
SparkVaultConfig,
|
|
649
|
+
|
|
650
|
+
// Identity types
|
|
651
|
+
VerifyOptions,
|
|
652
|
+
VerifyResult,
|
|
653
|
+
TokenClaims,
|
|
654
|
+
|
|
655
|
+
// Error types
|
|
656
|
+
SparkVaultError,
|
|
657
|
+
UserCancelledError,
|
|
658
|
+
ValidationError,
|
|
659
|
+
NetworkError,
|
|
660
|
+
TimeoutError,
|
|
661
|
+
PopupBlockedError,
|
|
662
|
+
} from '@sparkvault/sdk-js';
|
|
663
|
+
|
|
664
|
+
// Fully typed configuration
|
|
665
|
+
const config: SparkVaultConfig = {
|
|
666
|
+
accountId: 'acc_YOUR_ACCOUNT_ID',
|
|
667
|
+
timeout: 30000,
|
|
668
|
+
};
|
|
669
|
+
|
|
670
|
+
const sparkvault = SparkVault.init(config);
|
|
671
|
+
|
|
672
|
+
// Fully typed options and result
|
|
673
|
+
const options: VerifyOptions = {
|
|
674
|
+
email: 'user@example.com',
|
|
675
|
+
onCancel: () => console.log('Cancelled'),
|
|
676
|
+
};
|
|
677
|
+
|
|
678
|
+
const result: VerifyResult = await sparkvault.identity.pop(options);
|
|
679
|
+
// result.token: string
|
|
680
|
+
// result.identity: string
|
|
681
|
+
// result.identityType: 'email' | 'phone'
|
|
682
|
+
```
|
|
683
|
+
|
|
684
|
+
## Content Security Policy (CSP)
|
|
685
|
+
|
|
686
|
+
If your site uses a Content Security Policy, you must allow the SparkVault domains:
|
|
687
|
+
|
|
688
|
+
```
|
|
689
|
+
connect-src https://api.sparkvault.com wss://ws.sparkvault.com;
|
|
690
|
+
script-src https://cdn.sparkvault.com;
|
|
691
|
+
```
|
|
692
|
+
|
|
693
|
+
| Directive | Domain | Reason |
|
|
694
|
+
|-----------|--------|--------|
|
|
695
|
+
| `connect-src` | `https://api.sparkvault.com` | API requests (identity verification, config) |
|
|
696
|
+
| `connect-src` | `wss://ws.sparkvault.com` | WebSocket for SparkLink push notifications |
|
|
697
|
+
| `script-src` | `https://cdn.sparkvault.com` | SDK script (if using CDN installation) |
|
|
698
|
+
|
|
699
|
+
## Best Practices
|
|
700
|
+
|
|
701
|
+
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.
|
|
702
|
+
|
|
703
|
+
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.
|
|
704
|
+
|
|
705
|
+
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.
|
|
706
|
+
|
|
707
|
+
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.
|
|
708
|
+
|
|
709
|
+
## Browser Support
|
|
710
|
+
|
|
711
|
+
The SDK supports all modern browsers:
|
|
712
|
+
|
|
713
|
+
- Chrome 80+
|
|
714
|
+
- Firefox 75+
|
|
715
|
+
- Safari 13.1+
|
|
716
|
+
- Edge 80+
|
|
717
|
+
|
|
718
|
+
**Note:** Passkey authentication requires WebAuthn support. On unsupported browsers, passkey will not appear as an option — other methods will still work.
|
|
719
|
+
|
|
720
|
+
## Build & Release
|
|
721
|
+
|
|
722
|
+
### Setup
|
|
723
|
+
|
|
724
|
+
```bash
|
|
725
|
+
git clone https://github.com/Spark-Vault/sdk-js.git
|
|
726
|
+
cd sdk-js
|
|
727
|
+
npm install
|
|
728
|
+
```
|
|
729
|
+
|
|
730
|
+
### Scripts
|
|
731
|
+
|
|
732
|
+
```bash
|
|
733
|
+
npm run build # Build all bundles
|
|
734
|
+
npm run build:watch # Build with watch mode
|
|
735
|
+
npm run typecheck # Run TypeScript type checking
|
|
736
|
+
npm run lint # Run ESLint
|
|
737
|
+
npm run test # Run tests
|
|
738
|
+
npm run test:watch # Run tests in watch mode
|
|
739
|
+
```
|
|
740
|
+
|
|
741
|
+
### Project Structure
|
|
742
|
+
|
|
743
|
+
```
|
|
744
|
+
sdk-js/
|
|
745
|
+
├── src/
|
|
746
|
+
│ ├── index.ts # Main entry point
|
|
747
|
+
│ ├── config.ts # Configuration management
|
|
748
|
+
│ ├── http.ts # HTTP client
|
|
749
|
+
│ ├── errors.ts # Error types
|
|
750
|
+
│ └── identity/ # Identity module
|
|
751
|
+
├── dist/ # Built bundles
|
|
752
|
+
├── tests/ # Test files
|
|
753
|
+
├── .github/workflows/ # CI/CD workflows
|
|
754
|
+
├── rollup.config.js # Rollup bundler config
|
|
755
|
+
├── tsconfig.json # TypeScript config
|
|
756
|
+
└── package.json
|
|
757
|
+
```
|
|
758
|
+
|
|
759
|
+
## License
|
|
760
|
+
|
|
761
|
+
MIT License - see [LICENSE](LICENSE) for details.
|
|
762
|
+
|
|
763
|
+
## Links
|
|
764
|
+
|
|
765
|
+
- [SparkVault Documentation](https://sparkvault.com/api/docs)
|
|
766
|
+
- [SDK API Reference](https://sparkvault.com/api/docs/sdk)
|
|
767
|
+
- [GitHub Repository](https://github.com/Spark-Vault/sdk-js)
|
|
768
|
+
- [npm Package](https://www.npmjs.com/package/@sparkvault/sdk-js)
|
|
769
|
+
- [Report Issues](https://github.com/Spark-Vault/sdk-js/issues)
|