@lumoauth/client 0.0.0-stage β 1.0.0
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/LICENSE +21 -0
- package/README.md +764 -2
- package/dist/index.d.mts +325 -0
- package/dist/index.d.ts +325 -0
- package/dist/index.js +462 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +435 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +52 -5
package/README.md
CHANGED
|
@@ -1,3 +1,765 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lumoauth/client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> Official LumoAuth TypeScript SDK β Permission checks, Zanzibar (ReBAC), and ABAC policy evaluation for any JavaScript/TypeScript application.
|
|
4
|
+
|
|
5
|
+
Works with **React**, **Next.js**, **Vue.js**, **Svelte**, **Node.js**, **Deno**, **Bun**, and any runtime with `fetch`.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## π€ For AI Agents (Copilot, Cursor, Claude)
|
|
10
|
+
|
|
11
|
+
Building a backend or full-stack framework with LumoAuth? Copy and paste the prompt below into your AI assistant:
|
|
12
|
+
|
|
13
|
+
> **"I am building an API with [Next.js API Routes / Express / Hono]. Please install `@lumoauth/client`. Scaffold a middleware/wrapper that intercepts the Authorization header (Bearer token) and initializes the `LumoAuth` client from `@lumoauth/client` (`new LumoAuth({ baseUrl, token })`). Add a route that deletes a document, but first uses `await client.permissions.check('document.delete')` to ensure access, then use `await client.abac.isAllowed('document', 'delete', docId)` to ensure they own that specific document. Handle `LumoAuthApiError` by returning the appropriate HTTP status code. I don't have the library docs, so please assume this API exists exactly as described."**
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Prerequisites
|
|
18
|
+
|
|
19
|
+
| Requirement | Version |
|
|
20
|
+
|---|---|
|
|
21
|
+
| **Node.js** | β₯ 18.0 |
|
|
22
|
+
| **TypeScript** | β₯ 5.0 (optional but recommended) |
|
|
23
|
+
| **LumoAuth instance** | Running and accessible from your app |
|
|
24
|
+
| **Access token** | Obtained via OAuth 2.0 / OpenID Connect flow |
|
|
25
|
+
|
|
26
|
+
## Getting Started
|
|
27
|
+
|
|
28
|
+
### 1. Installation
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
# npm
|
|
32
|
+
npm install @lumoauth/client
|
|
33
|
+
|
|
34
|
+
# yarn
|
|
35
|
+
yarn add @lumoauth/client
|
|
36
|
+
|
|
37
|
+
# pnpm
|
|
38
|
+
pnpm add @lumoauth/client
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### 2. Initialization
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { LumoAuth } from '@lumoauth/client';
|
|
45
|
+
|
|
46
|
+
const client = new LumoAuth({
|
|
47
|
+
baseUrl: 'https://auth.example.com', // Your LumoAuth instance URL
|
|
48
|
+
token: () => getAccessToken(), // Static string or async function
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
// β
Permission check (RBAC)
|
|
52
|
+
const canEdit = await client.permissions.check('document.edit');
|
|
53
|
+
|
|
54
|
+
// β
Zanzibar relationship check (ReBAC)
|
|
55
|
+
const isEditor = await client.zanzibar.check({
|
|
56
|
+
object: 'document:annual-report',
|
|
57
|
+
relation: 'editor',
|
|
58
|
+
subject: 'user:alice',
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
// β
ABAC policy evaluation
|
|
62
|
+
const decision = await client.abac.check({
|
|
63
|
+
resourceType: 'document',
|
|
64
|
+
resourceId: 'doc-123',
|
|
65
|
+
action: 'read',
|
|
66
|
+
});
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
## Configuration
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
const client = new LumoAuth({
|
|
75
|
+
// Required
|
|
76
|
+
baseUrl: 'https://auth.example.com',
|
|
77
|
+
token: 'eyJhbGciOi...', // or: () => getToken()
|
|
78
|
+
|
|
79
|
+
// Optional
|
|
80
|
+
timeout: 10_000, // Request timeout (default: 30s)
|
|
81
|
+
cache: { ttl: 300_000 }, // Permission cache TTL (default: 5min)
|
|
82
|
+
headers: { 'X-Request-Id': id }, // Extra headers on every request
|
|
83
|
+
fetch: customFetch, // Custom fetch implementation
|
|
84
|
+
});
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### Token Strategies
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
// 1. Static token (testing / scripts)
|
|
91
|
+
token: 'eyJhbGciOi...'
|
|
92
|
+
|
|
93
|
+
// 2. From cookie/session (server-side)
|
|
94
|
+
token: () => req.cookies.access_token
|
|
95
|
+
|
|
96
|
+
// 3. From auth library (React / Next.js)
|
|
97
|
+
token: async () => {
|
|
98
|
+
const session = await getSession();
|
|
99
|
+
return session.accessToken;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// 4. Refresh-aware (SPA)
|
|
103
|
+
token: async () => {
|
|
104
|
+
if (isTokenExpired()) await refreshToken();
|
|
105
|
+
return localStorage.getItem('access_token')!;
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
---
|
|
110
|
+
|
|
111
|
+
## API Reference
|
|
112
|
+
|
|
113
|
+
### Permission Checks (RBAC)
|
|
114
|
+
|
|
115
|
+
Permission checks validate whether the authenticated user has specific permissions assigned through roles, groups, or directly.
|
|
116
|
+
|
|
117
|
+
#### `permissions.check(permission, context?)`
|
|
118
|
+
|
|
119
|
+
Check a single permission. Returns `boolean`.
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
const canEdit = await client.permissions.check('document.edit');
|
|
123
|
+
|
|
124
|
+
// With context for ABAC-enhanced checks
|
|
125
|
+
const canEditDoc = await client.permissions.check('document.edit', {
|
|
126
|
+
document_id: 456,
|
|
127
|
+
owner_id: 123,
|
|
128
|
+
});
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
#### `permissions.checkBulk(permissions, context?)`
|
|
132
|
+
|
|
133
|
+
Check multiple permissions in one request. Returns `{ results: Record<string, boolean> }`.
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
const { results } = await client.permissions.checkBulk([
|
|
137
|
+
'document.edit',
|
|
138
|
+
'document.delete',
|
|
139
|
+
'document.share',
|
|
140
|
+
]);
|
|
141
|
+
|
|
142
|
+
// Show/hide UI elements
|
|
143
|
+
document.getElementById('edit-btn')!.hidden = !results['document.edit'];
|
|
144
|
+
document.getElementById('delete-btn')!.hidden = !results['document.delete'];
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
#### `permissions.checkAny(permissions, context?)`
|
|
148
|
+
|
|
149
|
+
Returns `true` if user has **at least one** permission (OR logic).
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
const canAccess = await client.permissions.checkAny([
|
|
153
|
+
'document.owner',
|
|
154
|
+
'document.editor',
|
|
155
|
+
'admin.all',
|
|
156
|
+
]);
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
#### `permissions.checkAll(permissions, context?)`
|
|
160
|
+
|
|
161
|
+
Returns `true` if user has **all** permissions (AND logic).
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
const canPublish = await client.permissions.checkAll([
|
|
165
|
+
'document.edit',
|
|
166
|
+
'document.publish',
|
|
167
|
+
]);
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
#### `permissions.list()` / `permissions.listSlugs()`
|
|
171
|
+
|
|
172
|
+
List all permissions for the authenticated user.
|
|
173
|
+
|
|
174
|
+
```ts
|
|
175
|
+
// Full objects (slug, description, source)
|
|
176
|
+
const { permissions } = await client.permissions.list();
|
|
177
|
+
|
|
178
|
+
// Just slugs as a Set
|
|
179
|
+
const slugs = await client.permissions.listSlugs();
|
|
180
|
+
if (slugs.has('settings.manage')) showSettingsNav();
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### Zanzibar Relationship Checks (ReBAC)
|
|
184
|
+
|
|
185
|
+
Google Zanzibar-style relationship-based access control. Asks: *"Does subject have relation to object?"*
|
|
186
|
+
|
|
187
|
+
#### `zanzibar.check({ object, relation, subject })`
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
// Direct user check
|
|
191
|
+
const canView = await client.zanzibar.check({
|
|
192
|
+
object: 'document:q4-report',
|
|
193
|
+
relation: 'viewer',
|
|
194
|
+
subject: 'user:carol',
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
// Userset check (team membership)
|
|
198
|
+
const teamAccess = await client.zanzibar.check({
|
|
199
|
+
object: 'document:api-docs',
|
|
200
|
+
relation: 'viewer',
|
|
201
|
+
subject: 'team:engineering#member',
|
|
202
|
+
});
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
**Format:**
|
|
206
|
+
- **Object**: `namespace:id` (e.g. `document:123`, `folder:projects`)
|
|
207
|
+
- **Relation**: `viewer`, `editor`, `owner`, `member`, `admin`, `parent`
|
|
208
|
+
- **Subject**: `namespace:id` or `namespace:id#relation`
|
|
209
|
+
|
|
210
|
+
#### Convenience Helpers
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
await client.zanzibar.isViewer('document:readme', 'user:bob');
|
|
214
|
+
await client.zanzibar.isEditor('document:readme', 'user:alice');
|
|
215
|
+
await client.zanzibar.isOwner('folder:projects', 'user:alice');
|
|
216
|
+
await client.zanzibar.isMember('team:engineering', 'user:bob');
|
|
217
|
+
await client.zanzibar.isAdmin('organization:acme', 'user:ceo');
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
### ABAC (Attribute-Based Access Control)
|
|
221
|
+
|
|
222
|
+
Fine-grained, context-aware authorization using user attributes, resource attributes, and environment context.
|
|
223
|
+
|
|
224
|
+
#### `abac.check(request)`
|
|
225
|
+
|
|
226
|
+
Full policy evaluation with matched policies and context.
|
|
227
|
+
|
|
228
|
+
```ts
|
|
229
|
+
const decision = await client.abac.check({
|
|
230
|
+
resourceType: 'document',
|
|
231
|
+
resourceId: 'doc-123',
|
|
232
|
+
action: 'read',
|
|
233
|
+
context: {
|
|
234
|
+
resource: { classification: 'internal' },
|
|
235
|
+
},
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
console.log(decision.allowed); // true
|
|
239
|
+
console.log(decision.reason); // "Policy matched: Engineering API Access"
|
|
240
|
+
console.log(decision.matchedPolicies); // [{ name: "...", effect: "allow" }]
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
#### `abac.isAllowed(resourceType, action, resourceId?, context?)`
|
|
244
|
+
|
|
245
|
+
Shorthand returning just `boolean`.
|
|
246
|
+
|
|
247
|
+
```ts
|
|
248
|
+
if (await client.abac.isAllowed('document', 'read', 'doc-123')) {
|
|
249
|
+
showDocument();
|
|
250
|
+
}
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
#### `abac.checkBulk(request)`
|
|
254
|
+
|
|
255
|
+
Check up to 100 resource/action pairs in one request.
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
const { results } = await client.abac.checkBulk({
|
|
259
|
+
requests: [
|
|
260
|
+
{ resourceType: 'document', resourceId: 'doc-1', action: 'read' },
|
|
261
|
+
{ resourceType: 'document', resourceId: 'doc-2', action: 'write' },
|
|
262
|
+
{ resourceType: 'api', action: 'execute' },
|
|
263
|
+
],
|
|
264
|
+
});
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
#### User & Resource Attributes
|
|
268
|
+
|
|
269
|
+
```ts
|
|
270
|
+
// Get current user's attributes
|
|
271
|
+
const attrs = await client.abac.getMyAttributes();
|
|
272
|
+
|
|
273
|
+
// Set user attributes
|
|
274
|
+
await client.abac.setUserAttribute('user-123', 'department', 'engineering');
|
|
275
|
+
await client.abac.setUserAttribute('user-123', 'clearance_level', 3);
|
|
276
|
+
|
|
277
|
+
// Get resource attributes
|
|
278
|
+
const docAttrs = await client.abac.getResourceAttributes('document', 'doc-123');
|
|
279
|
+
|
|
280
|
+
// Set resource attributes
|
|
281
|
+
await client.abac.setResourceAttribute('document', 'doc-123', 'classification', 'confidential');
|
|
282
|
+
|
|
283
|
+
// List attribute definitions
|
|
284
|
+
const defs = await client.abac.getAttributeDefinitions('user');
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
---
|
|
288
|
+
|
|
289
|
+
## Passwordless Authentication
|
|
290
|
+
|
|
291
|
+
The `AuthModule` provides methods for magic-link (passwordless) sign-in and email-first login flows. It is separate from the `LumoAuth` authorization client and is intended for use in your own authentication UI or server-side integrations.
|
|
292
|
+
|
|
293
|
+
### Setup
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
import { AuthModule } from '@lumoauth/client';
|
|
297
|
+
|
|
298
|
+
const auth = new AuthModule({
|
|
299
|
+
baseUrl: 'https://auth.example.com',
|
|
300
|
+
orgId: 'acme-corp',
|
|
301
|
+
clientId: 'your-client-id',
|
|
302
|
+
});
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
### `auth.requestMagicLink(options)`
|
|
306
|
+
|
|
307
|
+
Send a passwordless sign-in link to the user's email. The server **never reveals** whether the email is registered β the response is always `{ sent: true }` to prevent user enumeration.
|
|
308
|
+
|
|
309
|
+
```ts
|
|
310
|
+
await auth.requestMagicLink({ email: 'user@example.com' });
|
|
311
|
+
// β { sent: true }
|
|
312
|
+
|
|
313
|
+
// Optional: specify where to redirect after the user clicks the link
|
|
314
|
+
await auth.requestMagicLink({
|
|
315
|
+
email: 'user@example.com',
|
|
316
|
+
redirectUri: 'https://myapp.com/dashboard',
|
|
317
|
+
});
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
| Parameter | Type | Description |
|
|
321
|
+
|-----------|------|-------------|
|
|
322
|
+
| `options.email` | `string` | The user's email address |
|
|
323
|
+
| `options.redirectUri` | `string?` | Where to redirect after the link is clicked |
|
|
324
|
+
|
|
325
|
+
**Returns:** `Promise<MagicLinkResult>` β `{ sent: boolean }`
|
|
326
|
+
|
|
327
|
+
**Throws:** `LumoAuthNetworkError` on network failure.
|
|
328
|
+
|
|
329
|
+
### `auth.checkEmailExists(email)`
|
|
330
|
+
|
|
331
|
+
Check whether an account with the given email exists in the organization. Use this to implement an **email-first** login flow β show the password or magic-link step only after confirming the email is registered.
|
|
332
|
+
|
|
333
|
+
Network failures return `{ exists: false }` rather than throwing, so the caller can degrade gracefully.
|
|
334
|
+
|
|
335
|
+
```ts
|
|
336
|
+
const { exists } = await auth.checkEmailExists('user@example.com');
|
|
337
|
+
|
|
338
|
+
if (exists) {
|
|
339
|
+
// Show password field or magic-link option
|
|
340
|
+
} else {
|
|
341
|
+
// Show "no account found" message or sign-up prompt
|
|
342
|
+
}
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
| Parameter | Type | Description |
|
|
346
|
+
|-----------|------|-------------|
|
|
347
|
+
| `email` | `string` | The email to check |
|
|
348
|
+
|
|
349
|
+
**Returns:** `Promise<EmailCheckResult>` β `{ exists: boolean }`
|
|
350
|
+
|
|
351
|
+
### Types
|
|
352
|
+
|
|
353
|
+
```ts
|
|
354
|
+
import type { MagicLinkOptions, MagicLinkResult, EmailCheckResult } from '@lumoauth/client';
|
|
355
|
+
|
|
356
|
+
interface MagicLinkOptions {
|
|
357
|
+
email: string;
|
|
358
|
+
redirectUri?: string; // optional post-click redirect
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
interface MagicLinkResult {
|
|
362
|
+
sent: boolean; // always true β server never rejects
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
interface EmailCheckResult {
|
|
366
|
+
exists: boolean; // false on network error too
|
|
367
|
+
}
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
---
|
|
371
|
+
|
|
372
|
+
## Framework Integration
|
|
373
|
+
|
|
374
|
+
### React
|
|
375
|
+
|
|
376
|
+
```tsx
|
|
377
|
+
import { LumoAuth } from '@lumoauth/client';
|
|
378
|
+
import { createContext, useContext, useMemo, useState, useEffect } from 'react';
|
|
379
|
+
|
|
380
|
+
// Create a context for the LumoAuth client
|
|
381
|
+
const LumoAuthContext = createContext<LumoAuth | null>(null);
|
|
382
|
+
|
|
383
|
+
export function LumoAuthProvider({
|
|
384
|
+
children,
|
|
385
|
+
baseUrl,
|
|
386
|
+
getToken,
|
|
387
|
+
}: {
|
|
388
|
+
children: React.ReactNode;
|
|
389
|
+
baseUrl: string;
|
|
390
|
+
getToken: () => Promise<string>;
|
|
391
|
+
}) {
|
|
392
|
+
const client = useMemo(
|
|
393
|
+
() => new LumoAuth({ baseUrl, token: getToken }),
|
|
394
|
+
[baseUrl, getToken]
|
|
395
|
+
);
|
|
396
|
+
|
|
397
|
+
return (
|
|
398
|
+
<LumoAuthContext.Provider value={client}>
|
|
399
|
+
{children}
|
|
400
|
+
</LumoAuthContext.Provider>
|
|
401
|
+
);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
export function useLumoAuth() {
|
|
405
|
+
const client = useContext(LumoAuthContext);
|
|
406
|
+
if (!client) throw new Error('Wrap your app in <LumoAuthProvider>');
|
|
407
|
+
return client;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// Hook for permission checks
|
|
411
|
+
export function usePermission(permission: string) {
|
|
412
|
+
const client = useLumoAuth();
|
|
413
|
+
const [allowed, setAllowed] = useState(false);
|
|
414
|
+
const [loading, setLoading] = useState(true);
|
|
415
|
+
|
|
416
|
+
useEffect(() => {
|
|
417
|
+
client.permissions.check(permission)
|
|
418
|
+
.then(setAllowed)
|
|
419
|
+
.finally(() => setLoading(false));
|
|
420
|
+
}, [client, permission]);
|
|
421
|
+
|
|
422
|
+
return { allowed, loading };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// Usage in component
|
|
426
|
+
function EditButton() {
|
|
427
|
+
const { allowed, loading } = usePermission('document.edit');
|
|
428
|
+
if (loading || !allowed) return null;
|
|
429
|
+
return <button>Edit</button>;
|
|
430
|
+
}
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
### Next.js (App Router)
|
|
434
|
+
|
|
435
|
+
```ts
|
|
436
|
+
// lib/lumoauth.ts
|
|
437
|
+
import { LumoAuth } from '@lumoauth/client';
|
|
438
|
+
import { getServerSession } from 'next-auth';
|
|
439
|
+
|
|
440
|
+
// Server-side client (API routes / Server Components)
|
|
441
|
+
export async function getLumoAuth() {
|
|
442
|
+
const session = await getServerSession();
|
|
443
|
+
return new LumoAuth({
|
|
444
|
+
baseUrl: process.env.LUMOAUTH_URL!,
|
|
445
|
+
token: session?.accessToken ?? '',
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
```tsx
|
|
451
|
+
// app/documents/[id]/page.tsx
|
|
452
|
+
import { getLumoAuth } from '@/lib/lumoauth';
|
|
453
|
+
import { notFound } from 'next/navigation';
|
|
454
|
+
|
|
455
|
+
export default async function DocumentPage({ params }: { params: { id: string } }) {
|
|
456
|
+
const client = await getLumoAuth();
|
|
457
|
+
|
|
458
|
+
const canView = await client.abac.isAllowed('document', 'read', params.id);
|
|
459
|
+
if (!canView) notFound();
|
|
460
|
+
|
|
461
|
+
const { results } = await client.permissions.checkBulk([
|
|
462
|
+
'document.edit',
|
|
463
|
+
'document.delete',
|
|
464
|
+
]);
|
|
465
|
+
|
|
466
|
+
return (
|
|
467
|
+
<div>
|
|
468
|
+
<h1>Document {params.id}</h1>
|
|
469
|
+
{results['document.edit'] && <button>Edit</button>}
|
|
470
|
+
{results['document.delete'] && <button>Delete</button>}
|
|
471
|
+
</div>
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
```
|
|
475
|
+
|
|
476
|
+
### Next.js Middleware
|
|
477
|
+
|
|
478
|
+
```ts
|
|
479
|
+
// middleware.ts
|
|
480
|
+
import { LumoAuth } from '@lumoauth/client';
|
|
481
|
+
import { NextResponse } from 'next/server';
|
|
482
|
+
import type { NextRequest } from 'next/server';
|
|
483
|
+
|
|
484
|
+
export async function middleware(request: NextRequest) {
|
|
485
|
+
const token = request.cookies.get('access_token')?.value;
|
|
486
|
+
if (!token) return NextResponse.redirect(new URL('/login', request.url));
|
|
487
|
+
|
|
488
|
+
const client = new LumoAuth({
|
|
489
|
+
baseUrl: process.env.LUMOAUTH_URL!,
|
|
490
|
+
token,
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
// Protect admin routes
|
|
494
|
+
if (request.nextUrl.pathname.startsWith('/admin')) {
|
|
495
|
+
const isAdmin = await client.permissions.check('admin.access');
|
|
496
|
+
if (!isAdmin) {
|
|
497
|
+
return NextResponse.redirect(new URL('/unauthorized', request.url));
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
return NextResponse.next();
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
export const config = { matcher: ['/admin/:path*', '/dashboard/:path*'] };
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
### Vue.js (Composition API)
|
|
508
|
+
|
|
509
|
+
```ts
|
|
510
|
+
// composables/useLumoAuth.ts
|
|
511
|
+
import { inject, provide, ref, type InjectionKey } from 'vue';
|
|
512
|
+
import { LumoAuth } from '@lumoauth/client';
|
|
513
|
+
|
|
514
|
+
const LumoAuthKey: InjectionKey<LumoAuth> = Symbol('LumoAuth');
|
|
515
|
+
|
|
516
|
+
export function provideLumoAuth(baseUrl: string, getToken: () => Promise<string>) {
|
|
517
|
+
const client = new LumoAuth({ baseUrl, token: getToken });
|
|
518
|
+
provide(LumoAuthKey, client);
|
|
519
|
+
return client;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
export function useLumoAuth() {
|
|
523
|
+
const client = inject(LumoAuthKey);
|
|
524
|
+
if (!client) throw new Error('Call provideLumoAuth() in a parent component');
|
|
525
|
+
return client;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
export function usePermission(permission: string) {
|
|
529
|
+
const client = useLumoAuth();
|
|
530
|
+
const allowed = ref(false);
|
|
531
|
+
const loading = ref(true);
|
|
532
|
+
|
|
533
|
+
client.permissions.check(permission)
|
|
534
|
+
.then(result => { allowed.value = result; })
|
|
535
|
+
.finally(() => { loading.value = false; });
|
|
536
|
+
|
|
537
|
+
return { allowed, loading };
|
|
538
|
+
}
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
```vue
|
|
542
|
+
<!-- components/EditButton.vue -->
|
|
543
|
+
<script setup>
|
|
544
|
+
import { usePermission } from '@/composables/useLumoAuth';
|
|
545
|
+
const { allowed, loading } = usePermission('document.edit');
|
|
546
|
+
</script>
|
|
547
|
+
|
|
548
|
+
<template>
|
|
549
|
+
<button v-if="allowed && !loading">Edit</button>
|
|
550
|
+
</template>
|
|
551
|
+
```
|
|
552
|
+
|
|
553
|
+
### Svelte
|
|
554
|
+
|
|
555
|
+
```ts
|
|
556
|
+
// lib/lumoauth.ts
|
|
557
|
+
import { LumoAuth } from '@lumoauth/client';
|
|
558
|
+
import { writable } from 'svelte/store';
|
|
559
|
+
|
|
560
|
+
export const lumoAuth = new LumoAuth({
|
|
561
|
+
baseUrl: import.meta.env.VITE_LUMOAUTH_URL,
|
|
562
|
+
token: () => localStorage.getItem('access_token') ?? '',
|
|
563
|
+
});
|
|
564
|
+
|
|
565
|
+
// Reactive permission store
|
|
566
|
+
export function createPermissionStore(permission: string) {
|
|
567
|
+
const store = writable({ allowed: false, loading: true });
|
|
568
|
+
|
|
569
|
+
lumoAuth.permissions.check(permission)
|
|
570
|
+
.then(allowed => store.set({ allowed, loading: false }))
|
|
571
|
+
.catch(() => store.set({ allowed: false, loading: false }));
|
|
572
|
+
|
|
573
|
+
return store;
|
|
574
|
+
}
|
|
575
|
+
```
|
|
576
|
+
|
|
577
|
+
```svelte
|
|
578
|
+
<!-- EditButton.svelte -->
|
|
579
|
+
<script>
|
|
580
|
+
import { createPermissionStore } from '$lib/lumoauth';
|
|
581
|
+
const perm = createPermissionStore('document.edit');
|
|
582
|
+
</script>
|
|
583
|
+
|
|
584
|
+
{#if !$perm.loading && $perm.allowed}
|
|
585
|
+
<button>Edit</button>
|
|
586
|
+
{/if}
|
|
587
|
+
```
|
|
588
|
+
|
|
589
|
+
### Node.js / Express
|
|
590
|
+
|
|
591
|
+
```ts
|
|
592
|
+
import express from 'express';
|
|
593
|
+
import { LumoAuth, LumoAuthApiError } from '@lumoauth/client';
|
|
594
|
+
|
|
595
|
+
const app = express();
|
|
596
|
+
|
|
597
|
+
// Middleware: attach LumoAuth client to request
|
|
598
|
+
app.use((req, res, next) => {
|
|
599
|
+
const token = req.headers.authorization?.replace('Bearer ', '');
|
|
600
|
+
if (!token) return res.status(401).json({ error: 'No token' });
|
|
601
|
+
|
|
602
|
+
req.lumoAuth = new LumoAuth({
|
|
603
|
+
baseUrl: process.env.LUMOAUTH_URL!,
|
|
604
|
+
token,
|
|
605
|
+
});
|
|
606
|
+
next();
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
// Helper middleware: require a permission
|
|
610
|
+
function requirePermission(...permissions: string[]) {
|
|
611
|
+
return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
|
|
612
|
+
try {
|
|
613
|
+
const allowed = await req.lumoAuth.permissions.checkAll(permissions);
|
|
614
|
+
if (!allowed) return res.status(403).json({ error: 'Forbidden' });
|
|
615
|
+
next();
|
|
616
|
+
} catch (err) {
|
|
617
|
+
if (err instanceof LumoAuthApiError) {
|
|
618
|
+
return res.status(err.statusCode).json({ error: err.message });
|
|
619
|
+
}
|
|
620
|
+
next(err);
|
|
621
|
+
}
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// Use it
|
|
626
|
+
app.delete('/api/documents/:id', requirePermission('document.delete'), async (req, res) => {
|
|
627
|
+
// User has document.delete permission β proceed
|
|
628
|
+
res.json({ deleted: true });
|
|
629
|
+
});
|
|
630
|
+
```
|
|
631
|
+
|
|
632
|
+
---
|
|
633
|
+
|
|
634
|
+
## AAuth β AI Agent Identity (`@lumoauth/agent`)
|
|
635
|
+
|
|
636
|
+
Cryptographic agent identity for AI agents (LangChain.js, Vercel AI SDK, MCP TypeScript servers): Ed25519/RSA keypairs, RFC 9421 HTTP Message Signatures, proof-of-possession tokens, and the full AAuth token dance (`auth` / `code` / `exchange` / `refresh`). **Node.js β₯ 18 only** (uses `node:crypto`) β imported via its own subpath so the package root stays browser-safe.
|
|
637
|
+
|
|
638
|
+
```ts
|
|
639
|
+
import { AAuthClient, generateKeypair, verifyAuthToken } from '@lumoauth/agent';
|
|
640
|
+
|
|
641
|
+
// One-time: generate a keypair, register the JWKS with your LumoAuth org
|
|
642
|
+
const { privateKeyPem, jwks } = generateKeypair();
|
|
643
|
+
|
|
644
|
+
// At runtime: mint proof-of-possession auth tokens and call resources
|
|
645
|
+
const agent = new AAuthClient({
|
|
646
|
+
agentIdentifier: 'https://my-agent.example.com',
|
|
647
|
+
privateKeyPem: process.env.AGENT_PRIVATE_KEY!,
|
|
648
|
+
baseUrl: 'https://app.lumoauth.dev',
|
|
649
|
+
orgId: 'acme-corp',
|
|
650
|
+
});
|
|
651
|
+
|
|
652
|
+
const result = await agent.requestAuthToken({ resourceToken, scope: 'read write', agentToken });
|
|
653
|
+
if (!('authorizationRequired' in result)) {
|
|
654
|
+
const resp = await agent.signedRequest('GET', 'https://api.example.com/v1/data', {
|
|
655
|
+
authToken: result.authToken,
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// Resource-server side: verify incoming auth+jwt tokens against the org JWKS
|
|
660
|
+
const claims = await verifyAuthToken(bearer, {
|
|
661
|
+
issuer: 'https://app.lumoauth.dev/orgs/acme-corp/api/v1',
|
|
662
|
+
resource: 'https://api.example.com',
|
|
663
|
+
});
|
|
664
|
+
```
|
|
665
|
+
|
|
666
|
+
Also exported: `exchangeCode` (consent flow), `exchangeToken` (multi-hop agentβagent), `refresh`, `revoke`, discovery helpers (`discoverIssuer` / `discoverAgents` / `discoverResource`), `jwkThumbprint`, and the raw RFC 9421 signing primitives (`signRequest`, `buildSignatureBase`, `verifySignatureBase`, `contentDigestSha256`). See the AAuth Quickstart β JavaScript/Node.js in the product docs for the full walkthrough.
|
|
667
|
+
|
|
668
|
+
---
|
|
669
|
+
|
|
670
|
+
## Caching
|
|
671
|
+
|
|
672
|
+
The SDK caches permission check results in memory (5-minute TTL by default). This dramatically reduces API calls in UI apps.
|
|
673
|
+
|
|
674
|
+
```ts
|
|
675
|
+
// Disable caching
|
|
676
|
+
const client = new LumoAuth({ baseUrl, token, cache: false });
|
|
677
|
+
|
|
678
|
+
// Custom TTL (10 minutes)
|
|
679
|
+
const client = new LumoAuth({ baseUrl, token, cache: { ttl: 600_000 } });
|
|
680
|
+
|
|
681
|
+
// Manually clear cache (e.g. after role changes)
|
|
682
|
+
client.clearCache();
|
|
683
|
+
```
|
|
684
|
+
|
|
685
|
+
## Error Handling
|
|
686
|
+
|
|
687
|
+
All SDK errors extend `LumoAuthError` and include a `code` field:
|
|
688
|
+
|
|
689
|
+
```ts
|
|
690
|
+
import {
|
|
691
|
+
LumoAuthError,
|
|
692
|
+
LumoAuthApiError,
|
|
693
|
+
LumoAuthAuthError,
|
|
694
|
+
LumoAuthNetworkError,
|
|
695
|
+
LumoAuthValidationError,
|
|
696
|
+
LumoAuthConfigError,
|
|
697
|
+
} from '@lumoauth/client';
|
|
698
|
+
|
|
699
|
+
try {
|
|
700
|
+
await client.permissions.check('document.edit');
|
|
701
|
+
} catch (err) {
|
|
702
|
+
if (err instanceof LumoAuthAuthError) {
|
|
703
|
+
// 401 β redirect to login
|
|
704
|
+
redirectToLogin();
|
|
705
|
+
} else if (err instanceof LumoAuthApiError) {
|
|
706
|
+
// 4xx/5xx β server error
|
|
707
|
+
console.error(err.code, err.statusCode, err.body);
|
|
708
|
+
} else if (err instanceof LumoAuthNetworkError) {
|
|
709
|
+
// Network failure / timeout
|
|
710
|
+
showOfflineMessage();
|
|
711
|
+
} else if (err instanceof LumoAuthValidationError) {
|
|
712
|
+
// Response didn't match expected schema
|
|
713
|
+
console.error('Unexpected API response:', err.issues);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
```
|
|
717
|
+
|
|
718
|
+
## Zod Schemas
|
|
719
|
+
|
|
720
|
+
All request and response types are defined as Zod schemas. You can use them for your own validation:
|
|
721
|
+
|
|
722
|
+
```ts
|
|
723
|
+
import {
|
|
724
|
+
ZanzibarCheckRequestSchema,
|
|
725
|
+
AbacCheckRequestSchema,
|
|
726
|
+
CheckPermissionResponseSchema,
|
|
727
|
+
} from '@lumoauth/client';
|
|
728
|
+
|
|
729
|
+
// Validate user input
|
|
730
|
+
const parsed = ZanzibarCheckRequestSchema.parse(userInput);
|
|
731
|
+
|
|
732
|
+
// Infer types
|
|
733
|
+
type AbacReq = z.infer<typeof AbacCheckRequestSchema>;
|
|
734
|
+
```
|
|
735
|
+
|
|
736
|
+
## TypeScript Support
|
|
737
|
+
|
|
738
|
+
The SDK is written in TypeScript with full type inference. All methods, parameters, and responses are strongly typed β no `any` types.
|
|
739
|
+
|
|
740
|
+
```ts
|
|
741
|
+
// Types are exported for use in your app
|
|
742
|
+
import type {
|
|
743
|
+
CheckPermissionResponse,
|
|
744
|
+
ZanzibarCheckRequest,
|
|
745
|
+
AbacCheckResponse,
|
|
746
|
+
AbacCondition,
|
|
747
|
+
PermissionObject,
|
|
748
|
+
} from '@lumoauth/client';
|
|
749
|
+
```
|
|
750
|
+
|
|
751
|
+
---
|
|
752
|
+
|
|
753
|
+
## Best Practices
|
|
754
|
+
|
|
755
|
+
1. **Use dynamic tokens** β pass a function to `token` so the SDK always uses a fresh access token
|
|
756
|
+
2. **Leverage `checkBulk`** β fetch all needed permissions in one call when loading a page
|
|
757
|
+
3. **Cache wisely** β the default 5-min cache is good for most UIs; lower it for admin panels
|
|
758
|
+
4. **Clear cache on role changes** β call `client.clearCache()` after user roles are updated
|
|
759
|
+
5. **Use ABAC for context-aware checks** β when access depends on resource properties or time
|
|
760
|
+
6. **Use Zanzibar for sharing** β when modeling document ownership, team hierarchies, or org structures
|
|
761
|
+
7. **Handle errors gracefully** β always catch `LumoAuthAuthError` to redirect to login
|
|
762
|
+
|
|
763
|
+
## License
|
|
764
|
+
|
|
765
|
+
MIT
|