@lumoauth/client 0.0.0-stage → 1.1.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/README.md CHANGED
@@ -1,3 +1,755 @@
1
- # Temporary Holding Version
1
+ # @lumoauth/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@lumoauth/client.svg)](https://www.npmjs.com/package/@lumoauth/client)
4
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
5
+
6
+ `@lumoauth/client` is the LumoAuth SDK for code that runs in the browser, or anywhere else that
7
+ holds a **user's** access token. It gives you one `LumoAuth` client for four jobs:
8
+
9
+ - checking permissions (RBAC), relationships (Zanzibar) and attribute policies (ABAC);
10
+ - signing users in with OAuth 2.0 and PKCE;
11
+ - keeping the session alive, with token refresh and sync across browser tabs;
12
+ - storing tokens in the place that you choose.
13
+
14
+ It works with any framework, or with none. It is part of the
15
+ [LumoAuth JavaScript SDK](../../README.md).
16
+
17
+ ## Contents
18
+
19
+ - [Is this the right package?](#is-this-the-right-package)
20
+ - [Requirements](#requirements)
21
+ - [Install](#install)
22
+ - [Quick start](#quick-start)
23
+ - [Core concepts](#core-concepts)
24
+ - [Credentials](#credentials)
25
+ - [Scopes](#scopes)
26
+ - [Configuration](#configuration)
27
+ - [Guides](#guides)
28
+ - [Check permissions (RBAC)](#check-permissions-rbac)
29
+ - [Check relationships (Zanzibar)](#check-relationships-zanzibar)
30
+ - [Evaluate attribute policies (ABAC)](#evaluate-attribute-policies-abac)
31
+ - [Sign users in (OAuth 2.0 and PKCE)](#sign-users-in-oauth-20-and-pkce)
32
+ - [Passwordless, email-first and embedded sign-in](#passwordless-email-first-and-embedded-sign-in)
33
+ - [Keep the session alive](#keep-the-session-alive)
34
+ - [Choose where tokens are stored](#choose-where-tokens-are-stored)
35
+ - [Read an agent's identity and poll an approval](#read-an-agents-identity-and-poll-an-approval)
36
+ - [Use it from other frameworks](#use-it-from-other-frameworks)
37
+ - [Caching](#caching)
38
+ - [Errors](#errors)
39
+ - [API reference](#api-reference)
40
+ - [Troubleshooting](#troubleshooting)
41
+ - [Versioning and compatibility](#versioning-and-compatibility)
42
+ - [Related packages](#related-packages)
43
+ - [Licence](#licence)
44
+
45
+ ## Is this the right package?
46
+
47
+ | You are building… | Use |
48
+ |---|---|
49
+ | A React app | [`@lumoauth/react`](../react/README.md). It wraps this package in a provider, components and hooks. |
50
+ | A Next.js App Router app | [`@lumoauth/nextjs`](../nextjs/README.md) |
51
+ | A browser app in Vue, Svelte, Angular, Solid or plain JavaScript | **This package** |
52
+ | A Node API that receives the user's bearer token and checks permissions as that user | **This package** |
53
+ | Server code that holds an organization API key (`lmk_…`) | [`@lumoauth/backend`](../backend/README.md). This package rejects API keys in the browser. |
54
+ | An AI agent | [`@lumoauth/agent`](../agent/README.md) |
55
+
56
+ ## Requirements
57
+
58
+ - A runtime with `fetch` and Web Crypto: every current browser, Node 18 or newer, Deno or Bun.
59
+ - TypeScript 5 or newer is recommended. It is not required.
60
+ - A LumoAuth organization and an OAuth client. For browser apps, use a **public** client with PKCE.
61
+
62
+ ## Install
63
+
64
+ ```bash
65
+ npm install @lumoauth/client
66
+ # or
67
+ pnpm add @lumoauth/client
68
+ yarn add @lumoauth/client
69
+ ```
70
+
71
+ This package re-exports all of `@lumoauth/shared`, so you need only one install.
72
+
73
+ ## Quick start
74
+
75
+ Check a permission for the signed-in user:
76
+
77
+ ```ts
78
+ import { LumoAuth } from '@lumoauth/client';
79
+
80
+ const client = new LumoAuth({
81
+ baseUrl: 'https://app.lumoauth.dev', // EU region: https://eu.app.lumoauth.dev
82
+ orgId: 'acme-corp',
83
+ token: () => getAccessToken(), // returns the user's current access token
84
+ });
85
+
86
+ if (await client.permissions.check('document.edit')) {
87
+ showEditButton();
88
+ }
89
+ ```
90
+
91
+ `getAccessToken()` is your own function. If you do not have a token yet, see
92
+ [Sign users in](#sign-users-in-oauth-20-and-pkce).
93
+
94
+ This package is for users, not agents. For an agent, start with
95
+ [`@lumoauth/agent`](../agent/README.md).
96
+
97
+ ## Core concepts
98
+
99
+ **Organization.** Every LumoAuth tenant has a slug, such as `acme-corp`. Pass it as `orgId`.
100
+ The ABAC, agent, approval and sign-in calls need it. Permission and Zanzibar checks do not,
101
+ because LumoAuth reads the organization from the token.
102
+
103
+ **Base URL.** Use `https://app.lumoauth.dev`, or `https://eu.app.lumoauth.dev` for the EU region.
104
+ Pass the root URL, not an `/orgs/…` path.
105
+
106
+ ### Credentials
107
+
108
+ LumoAuth accepts three kinds of credential. This package uses only the first.
109
+
110
+ | Credential | How it is sent | What it may call |
111
+ |---|---|---|
112
+ | A user access token | `Authorization: Bearer` | The calls in this package, as that user. Some calls also need a scope (see below). |
113
+ | An organization API key (`lmk_…`) | `X-API-Key` | The admin API, client registration and the permission-check routes. Never in a browser. |
114
+ | An agent credential | `Authorization: Bearer` | Agent, JIT and approval routes, governed by the agent's capabilities |
115
+
116
+ If you pass a static `lmk_…` string as `token` in a browser, the constructor throws a
117
+ `LumoAuthConfigError`. A key in a browser bundle is readable by every user of the app, and it
118
+ acts for the whole organization. Move that code to the server and use
119
+ [`@lumoauth/backend`](../backend/README.md).
120
+
121
+ ### Scopes
122
+
123
+ Some calls need an OAuth scope on the user's access token. You request scopes when the user
124
+ signs in, and the OAuth client must allow them.
125
+
126
+ | Call | Scope that the user access token needs |
127
+ |---|---|
128
+ | `permissions.list()`, `permissions.listSlugs()` | `authz:read` |
129
+ | `abac.check`, `abac.isAllowed`, `abac.checkBulk`, `abac.getMyAttributes`, `abac.getResourceAttributes`, `abac.getAttributeDefinitions` | `abac:read` |
130
+ | `abac.setUserAttribute`, `abac.setResourceAttribute` | `abac:write` |
131
+ | `agents.register` | `admin:agents:write`. Organization API keys cannot register agents. |
132
+ | `permissions.check*`, `zanzibar.check` and `expand`, `agents.ask`, `agents.me`, `auth.getUserInfo` | none |
133
+
134
+ The blanket `admin` scope satisfies all of them. A Zanzibar check about a subject other than
135
+ the caller needs `authz:check`.
136
+
137
+ When a scope is missing, LumoAuth answers `403`. The SDK throws a
138
+ `LumoAuthPermissionDeniedError`, and its `requiredScopes` lists the scopes that the token lacks.
139
+ To request a scope, add it to `scope` when you build the authorization URL:
140
+
141
+ ```ts
142
+ await client.auth.buildAuthorizationUrl({
143
+ redirectUri: 'https://myapp.example.com/auth/callback',
144
+ scope: 'openid profile email authz:read abac:read',
145
+ });
146
+ ```
147
+
148
+ ## Configuration
149
+
150
+ `new LumoAuth(config)` accepts these options:
151
+
152
+ | Option | Type | Default | Description |
153
+ |---|---|---|---|
154
+ | `baseUrl` | `string` | required | Root URL of LumoAuth |
155
+ | `token` | `string \| () => string \| Promise<string>` | none | The user's access token. A function is called before each request, so it can return a fresh token. You can leave it out before the user signs in. |
156
+ | `orgId` | `string` | none | Organization slug. Needed for `auth`, `abac`, `agents` and `approvals`. |
157
+ | `clientId` | `string` | none | OAuth client ID. Needed for `auth`. |
158
+ | `authStrategy` | `'pkce' \| 'password'` | `'pkce'` | PKCE is the flow for browsers. `'password'` is the older resource-owner grant. |
159
+ | `timeout` | `number` | `30000` | Request timeout in milliseconds |
160
+ | `cache` | `boolean \| { ttl?: number; maxSize?: number }` | on: 5 minutes, 1000 entries | Cache for permission-check results. `false` turns it off. |
161
+ | `headers` | `Record<string, string>` | none | Extra headers on every request |
162
+ | `fetch` | `typeof fetch` | global `fetch` | A custom `fetch`, for tests or older runtimes |
163
+
164
+ Ways to supply the token:
165
+
166
+ ```ts
167
+ token: 'eyJhbGciOi…' // static: tests and scripts
168
+ token: async () => (await getSession()).accessToken // from your own session store
169
+ token: () => session.getToken().then((t) => t ?? '') // from LumoAuthSession (see below)
170
+ ```
171
+
172
+ ## Guides
173
+
174
+ ### Check permissions (RBAC)
175
+
176
+ Use permission checks when access depends on the user's roles and groups. A permission is a slug
177
+ such as `document.edit`.
178
+
179
+ ```ts
180
+ const canEdit = await client.permissions.check('document.edit');
181
+
182
+ // Optional context for policies that read request data
183
+ const canEditThis = await client.permissions.check('document.edit', { document_id: 456 });
184
+
185
+ // Many permissions in one request
186
+ const { results } = await client.permissions.checkBulk(['document.edit', 'document.delete']);
187
+ deleteButton.hidden = !results['document.delete'];
188
+
189
+ // Any one of them, or all of them
190
+ const canOpen = await client.permissions.checkAny(['document.owner', 'document.editor']);
191
+ const canPublish = await client.permissions.checkAll(['document.edit', 'document.publish']);
192
+ ```
193
+
194
+ `check`, `checkAny` and `checkAll` return a boolean. The `…Detailed` variants return the full
195
+ response from the server. These calls check the user whose token you passed. To check a
196
+ different user or an agent, pass `{ userId }` or `{ agentId }` as the third argument. That needs
197
+ the `authz:check` scope or the `authz.check` permission; see the
198
+ [workspace README](../../README.md#check-permissions-rbac).
199
+
200
+ To list every permission that the user holds, the token needs the `authz:read` scope:
201
+
202
+ ```ts
203
+ const slugs = await client.permissions.listSlugs(); // Set<string>
204
+ if (slugs.has('settings.manage')) showSettingsNav();
205
+ ```
206
+
207
+ Without `authz:read`, `list()` and `listSlugs()` throw a `LumoAuthPermissionDeniedError` whose
208
+ `requiredScopes` is `['authz:read']`.
209
+
210
+ ### Check relationships (Zanzibar)
211
+
212
+ Use relationship checks for sharing, ownership and hierarchies. The question is: does this
213
+ subject have this relation to this object?
214
+
215
+ ```ts
216
+ const canView = await client.zanzibar.check({
217
+ object: 'document:q4-report',
218
+ relation: 'viewer',
219
+ subject: 'user:carol',
220
+ });
221
+
222
+ // A subject can also be a set, such as the members of a team
223
+ await client.zanzibar.check({
224
+ object: 'document:api-docs',
225
+ relation: 'viewer',
226
+ subject: 'team:engineering#member',
227
+ });
228
+
229
+ // Shorthands for common relations: isViewer, isEditor, isOwner, isMember, isAdmin
230
+ await client.zanzibar.isOwner('folder:projects', 'user:alice');
231
+
232
+ // Who has a relation, as a tree of subjects and sets
233
+ const tree = await client.zanzibar.expand({ object: 'document:q4-report', relation: 'viewer' });
234
+ ```
235
+
236
+ Objects are written `namespace:id`. Subjects are `namespace:id` or `namespace:id#relation`. A
237
+ check about the caller needs no scope. A check about someone else needs the `authz:check`
238
+ scope or permission.
239
+
240
+ ### Evaluate attribute policies (ABAC)
241
+
242
+ Use ABAC when the answer depends on attributes of the user, the resource or the request, such
243
+ as a department, a classification or the time of day. ABAC calls need `orgId`. A user access
244
+ token needs `abac:read` for checks and reads, and `abac:write` for writes. Organization API keys
245
+ are not accepted on the ABAC routes.
246
+
247
+ ```ts
248
+ const decision = await client.abac.check({
249
+ resourceType: 'document',
250
+ resourceId: 'doc-123',
251
+ action: 'read',
252
+ context: { channel: 'web' }, // environment attributes that policies can read
253
+ });
254
+ decision.allowed; // boolean
255
+ decision.reason; // the reason that the server gave, when there is one
256
+ decision.matchedPolicies; // the policies that matched, when the server returns them
257
+
258
+ if (await client.abac.isAllowed('document', 'read', 'doc-123')) showDocument();
259
+
260
+ // Up to 100 checks in one request, with one context for all of them
261
+ const { results } = await client.abac.checkBulk({
262
+ checks: [
263
+ { resourceType: 'document', resourceId: 'doc-1', action: 'read' },
264
+ { resourceType: 'document', resourceId: 'doc-2', action: 'write' },
265
+ ],
266
+ context: { channel: 'web' },
267
+ });
268
+ // results[i] → { index, resourceType, action, resourceId, allowed, reason, error? }
269
+ ```
270
+
271
+ The SDK sends `context` as the ABAC environment of the request. Resource attributes come only
272
+ from the attributes that are stored for the resource. Set them with `setResourceAttribute()`.
273
+ A caller without the `policies.view` permission gets only `id` and `name` for each matched
274
+ policy.
275
+
276
+ LumoAuth fills in `ip`, `userAgent`, `requestMethod` and `requestPath` from the request that it
277
+ received. You cannot override them. If you pass a value under one of those names, LumoAuth keeps
278
+ it as `pep.<name>`. To forward the end user's IP address from your own server, send
279
+ `context: { pep: { ip } }` and write the policy against `pep.ip`.
280
+
281
+ Attribute calls:
282
+
283
+ ```ts
284
+ await client.abac.getMyAttributes();
285
+ await client.abac.setUserAttribute('user_42', 'department', 'finance'); // abac:write
286
+ await client.abac.getResourceAttributes('document', 'doc-123');
287
+ await client.abac.setResourceAttribute('document', 'doc-123', 'classification', 'internal');
288
+ await client.abac.getAttributeDefinitions('user'); // 'user', 'resource' or 'environment'; optional
289
+ ```
290
+
291
+ Setting attributes also needs the `abac.manage` permission.
292
+
293
+ ### Sign users in (OAuth 2.0 and PKCE)
294
+
295
+ `client.auth` runs the OAuth 2.0 authorization-code flow with PKCE. It needs `baseUrl`, `orgId`
296
+ and `clientId`. Register your callback URL as a redirect URI on the OAuth client. Also add your
297
+ app's origin to the client's allowed origins, because the browser calls the token endpoint
298
+ directly.
299
+
300
+ Most browser apps should use the [session runtime](#keep-the-session-alive), which does these
301
+ steps for you. The steps below show what it does.
302
+
303
+ ```ts
304
+ const client = new LumoAuth({ baseUrl, orgId: 'acme-corp', clientId: 'your-client-id' });
305
+ const redirectUri = 'https://myapp.example.com/auth/callback';
306
+
307
+ // 1. Build the authorization URL. Save the verifier and state, then redirect.
308
+ const { url, codeVerifier, state } = await client.auth.buildAuthorizationUrl({
309
+ redirectUri,
310
+ scope: 'openid profile email', // the default; add scopes such as authz:read here
311
+ });
312
+ sessionStorage.setItem('pkce', JSON.stringify({ codeVerifier, state }));
313
+ location.assign(url);
314
+
315
+ // 2. On the callback page, check that `state` matches, then exchange the code.
316
+ const params = new URLSearchParams(location.search);
317
+ const saved = JSON.parse(sessionStorage.getItem('pkce')!);
318
+ if (params.get('state') !== saved.state) throw new Error('state mismatch');
319
+
320
+ const tokens = await client.auth.exchangeCodeForTokens({
321
+ code: params.get('code')!,
322
+ codeVerifier: saved.codeVerifier,
323
+ redirectUri,
324
+ });
325
+
326
+ // 3. Later
327
+ const profile = await client.auth.getUserInfo(tokens.access_token);
328
+ const fresh = await client.auth.refreshToken(tokens.refresh_token!);
329
+ await client.auth.revokeToken(fresh.refresh_token ?? tokens.refresh_token!);
330
+ ```
331
+
332
+ `TokenResponse` has `access_token`, `token_type`, `expires_in`, and, when they are issued,
333
+ `refresh_token`, `id_token` and `scope`. LumoAuth rotates refresh tokens. Each refresh returns a
334
+ new refresh token, and the old one stops working, so always save the new one.
335
+
336
+ `buildAuthorizationUrl` also takes `extraParams`. For example, `{ provider: 'google' }` sends the
337
+ user straight to that social provider.
338
+
339
+ ### Passwordless, email-first and embedded sign-in
340
+
341
+ These calls let you build your own sign-in screen.
342
+
343
+ ```ts
344
+ // Which sign-in methods can this person use?
345
+ const found = await client.auth.checkEmailExists('ada@example.com');
346
+ // found.exists, found.passwordEnabled, found.passkeyEnabled, found.magicLinkEnabled,
347
+ // found.hasPasskey, found.hasPushDevice, found.maskedEmail, …
348
+
349
+ // Email a one-time sign-in link. The result is always { sent: true },
350
+ // so the response never reveals whether the account exists.
351
+ await client.auth.requestMagicLink({ email: 'ada@example.com', redirectUri: 'https://myapp.example.com/' });
352
+
353
+ // Sign in with a password on your own form
354
+ const result = await client.auth.loginWithPassword({ email, password });
355
+ if (result.status === 'complete') {
356
+ // A LumoAuth session now exists. Start the PKCE redirect: LumoAuth issues a code
357
+ // without showing its own login page.
358
+ } else if (result.status === 'mfa_required') {
359
+ location.assign(result.challengeUrl!);
360
+ }
361
+ ```
362
+
363
+ `checkEmailExists` never throws for a network failure or an unknown email. It returns an object
364
+ in which every flag is `false`, so your screen can fall back to the hosted login page.
365
+
366
+ `loginWithPassword` returns one of these statuses: `complete`, `mfa_required`,
367
+ `invalid_credentials`, `blocked`, `inactive`, `rate_limited`, `invalid_request` or `error`. The
368
+ request is sent with `credentials: 'include'`, so your origin must be in the client's allowed
369
+ origins.
370
+
371
+ ### Keep the session alive
372
+
373
+ `LumoAuthSession` manages a browser session without depending on a framework. It handles these
374
+ jobs:
375
+
376
+ - building the PKCE authorization URL;
377
+ - saving tokens in the storage that you choose;
378
+ - refreshing the access token 60 seconds before it expires;
379
+ - sharing the session across tabs, with one tab doing each refresh.
380
+
381
+ `@lumoauth/react` is built on it. A Vue or Svelte binding can use it in the same way.
382
+
383
+ ```ts
384
+ import { LumoAuthSession, AuthModule, LumoAuth, localStorageAdapter } from '@lumoauth/client';
385
+
386
+ const auth = new AuthModule({ baseUrl, orgId: 'acme-corp', clientId: 'your-client-id' });
387
+
388
+ const session = new LumoAuthSession({
389
+ auth,
390
+ redirectUri: `${location.origin}/auth/callback`,
391
+ scope: 'openid profile email', // default
392
+ storage: localStorageAdapter(), // default: sessionStorage in a browser, memory on a server
393
+ crossTab: true, // default
394
+ });
395
+
396
+ await session.hydrate(); // load saved tokens and schedule the next refresh
397
+
398
+ // Sign in
399
+ const { url, codeVerifier, state } = await session.buildAuthorizationUrl();
400
+ // …save codeVerifier and state, redirect to url, then on the callback page:
401
+ await session.adopt(await auth.exchangeCodeForTokens({ code, codeVerifier, redirectUri }));
402
+
403
+ // Use the session's token for API calls
404
+ const client = new LumoAuth({ baseUrl, orgId: 'acme-corp', token: () => session.getToken().then((t) => t ?? '') });
405
+
406
+ // React to changes
407
+ const unsubscribe = session.subscribe(() => render(session.getSnapshot()));
408
+
409
+ // Sign out locally
410
+ await session.clearSession();
411
+ ```
412
+
413
+ | Member | What it does |
414
+ |---|---|
415
+ | `hydrate()` | Loads saved tokens, sets the state and schedules a refresh |
416
+ | `getToken()` | Returns a valid access token. It refreshes first when the token expires within 30 seconds. Returns `null` when there is no session. |
417
+ | `refresh()` | Refreshes now. Callers that run at the same time share one request. |
418
+ | `adopt(tokenResponse)` | Stores tokens that you obtained elsewhere, such as from a code exchange |
419
+ | `buildAuthorizationUrl(extraParams?)` | Builds the PKCE URL with the session's redirect URI and scope |
420
+ | `clearSession(error?, { broadcast?, emit? })` | Drops the tokens and tells other tabs |
421
+ | `subscribe(listener)` / `getSnapshot()` | Store interface; works with React's `useSyncExternalStore` |
422
+ | `getTokens()` | The stored tokens |
423
+ | `dispose()` | Stops timers and listeners |
424
+
425
+ `getSnapshot()` returns `{ status, isLoaded, isSignedIn, error }`. `status` is `'loading'`,
426
+ `'authenticated'` or `'unauthenticated'`. `error` says why the last step failed, for example
427
+ `'refresh_failed'`.
428
+
429
+ `clearSession()` clears local state only. To end the LumoAuth session too, send the browser to
430
+ the organization's logout endpoint, `/orgs/{orgId}/api/v1/oauth/logout`, with
431
+ `post_logout_redirect_uri` and `id_token_hint`. `@lumoauth/react` does this in `signOut()`.
432
+
433
+ ### Choose where tokens are stored
434
+
435
+ Where tokens are stored is a security decision, so the SDK makes you choose it.
436
+
437
+ | Adapter | Readable by injected script | Survives reload | Shared across tabs | Safe for server rendering |
438
+ |---|---|---|---|---|
439
+ | `sessionStorageAdapter()` (browser default) | yes | yes, per tab | no | no |
440
+ | `localStorageAdapter()` | yes | yes | yes | no |
441
+ | `memoryStorageAdapter()` (server default) | in memory only | no | no | yes |
442
+ | `cookieStorageAdapter(options?)` | **no** | yes | yes | yes |
443
+
444
+ `cookieStorageAdapter` is the only option that protects tokens from cross-site scripting. Tokens
445
+ stay in an httpOnly cookie that only your server can read. Your same-origin server must own the
446
+ code exchange and the refresh, and it must serve two endpoints:
447
+
448
+ | Option | Default | What the endpoint does |
449
+ |---|---|---|
450
+ | `sessionEndpoint` | `/auth/session` | Returns `{ accessToken, idToken, expiresAt }` as JSON, read from the cookie |
451
+ | `logoutEndpoint` | `/auth/logout` | Clears the cookie (called with `POST`) |
452
+
453
+ `@lumoauth/nextjs` provides both endpoints. Its provider sets this adapter up for you.
454
+ `@lumoauth/express` 1.0.0 has no session endpoint, so you would need to add one yourself.
455
+
456
+ To store tokens somewhere else, implement the `TokenStorage` interface: `name`, `get()`,
457
+ `set(tokens)`, `clear()`, and an optional `subscribe(onExternalChange)`.
458
+
459
+ ### Read an agent's identity and poll an approval
460
+
461
+ This client includes two parts of the agent API that are safe in a browser:
462
+
463
+ ```ts
464
+ // The caller's identity and capabilities
465
+ const me = await client.agents.me();
466
+ // For an agent credential, me.capabilities lists the agent's capability roles.
467
+ // A user access token without authz:read gets an empty list.
468
+
469
+ // Wait for a human approval that an agent created on the server
470
+ const result = await client.approvals.wait(approvalToken, { timeoutMs: 90_000 });
471
+ // result.status: 'approved' | 'denied' | 'expired' | 'pending'
472
+ ```
473
+
474
+ `client.approvals` can only read approvals (`getStatus` and `wait`). An agent creates approvals
475
+ on the server with `@lumoauth/agent` or `@lumoauth/backend`.
476
+
477
+ ### Use it from other frameworks
478
+
479
+ For React and Next.js, use [`@lumoauth/react`](../react/README.md) and
480
+ [`@lumoauth/nextjs`](../nextjs/README.md). For other frameworks, a small wrapper is enough.
481
+
482
+ <details>
483
+ <summary><strong>Vue 3</strong> (Composition API)</summary>
484
+
485
+ ```ts
486
+ // composables/useLumoAuth.ts
487
+ import { inject, provide, ref, type InjectionKey } from 'vue';
488
+ import { LumoAuth } from '@lumoauth/client';
489
+
490
+ const LumoAuthKey: InjectionKey<LumoAuth> = Symbol('LumoAuth');
491
+
492
+ export function provideLumoAuth(baseUrl: string, getToken: () => Promise<string>) {
493
+ const client = new LumoAuth({ baseUrl, token: getToken });
494
+ provide(LumoAuthKey, client);
495
+ return client;
496
+ }
497
+
498
+ export function useLumoAuth() {
499
+ const client = inject(LumoAuthKey);
500
+ if (!client) throw new Error('Call provideLumoAuth() in a parent component');
501
+ return client;
502
+ }
503
+
504
+ export function usePermission(permission: string) {
505
+ const client = useLumoAuth();
506
+ const allowed = ref(false);
507
+ const loading = ref(true);
508
+ client.permissions.check(permission)
509
+ .then((r) => { allowed.value = r; })
510
+ .finally(() => { loading.value = false; });
511
+ return { allowed, loading };
512
+ }
513
+ ```
514
+
515
+ ```vue
516
+ <script setup>
517
+ import { usePermission } from '@/composables/useLumoAuth';
518
+ const { allowed, loading } = usePermission('document.edit');
519
+ </script>
520
+
521
+ <template>
522
+ <button v-if="allowed && !loading">Edit</button>
523
+ </template>
524
+ ```
525
+
526
+ </details>
527
+
528
+ <details>
529
+ <summary><strong>Svelte</strong></summary>
530
+
531
+ ```ts
532
+ // lib/lumoauth.ts
533
+ import { LumoAuth } from '@lumoauth/client';
534
+ import { writable } from 'svelte/store';
535
+
536
+ export const lumoAuth = new LumoAuth({
537
+ baseUrl: import.meta.env.VITE_LUMOAUTH_URL,
538
+ token: () => localStorage.getItem('access_token') ?? '',
539
+ });
540
+
541
+ export function createPermissionStore(permission: string) {
542
+ const store = writable({ allowed: false, loading: true });
543
+ lumoAuth.permissions.check(permission)
544
+ .then((allowed) => store.set({ allowed, loading: false }))
545
+ .catch(() => store.set({ allowed: false, loading: false }));
546
+ return store;
547
+ }
548
+ ```
549
+
550
+ ```svelte
551
+ <script>
552
+ import { createPermissionStore } from '$lib/lumoauth';
553
+ const perm = createPermissionStore('document.edit');
554
+ </script>
555
+
556
+ {#if !$perm.loading && $perm.allowed}
557
+ <button>Edit</button>
558
+ {/if}
559
+ ```
560
+
561
+ </details>
562
+
563
+ <details>
564
+ <summary><strong>A Node API that checks permissions as the calling user</strong> (Express shown)</summary>
565
+
566
+ When your API receives the user's bearer token, you can run checks as that user. For checks that
567
+ use your organization's credential, or for admin calls, use
568
+ [`@lumoauth/backend`](../backend/README.md).
569
+
570
+ ```ts
571
+ import express from 'express';
572
+ import { LumoAuth, LumoAuthApiError } from '@lumoauth/client';
573
+
574
+ const app = express();
575
+
576
+ app.use((req, res, next) => {
577
+ const token = req.headers.authorization?.replace(/^Bearer /, '');
578
+ if (!token) return res.status(401).json({ error: 'missing token' });
579
+ req.lumoAuth = new LumoAuth({ baseUrl: process.env.LUMOAUTH_URL!, token });
580
+ next();
581
+ });
582
+
583
+ function requirePermission(...permissions: string[]) {
584
+ return async (req, res, next) => {
585
+ try {
586
+ if (!(await req.lumoAuth.permissions.checkAll(permissions))) {
587
+ return res.status(403).json({ error: 'forbidden' });
588
+ }
589
+ next();
590
+ } catch (err) {
591
+ if (err instanceof LumoAuthApiError) return res.status(err.statusCode ?? 502).json({ error: err.message });
592
+ next(err);
593
+ }
594
+ };
595
+ }
596
+
597
+ app.delete('/api/documents/:id', requirePermission('document.delete'), (req, res) => res.json({ deleted: true }));
598
+ ```
599
+
600
+ </details>
601
+
602
+ ## Caching
603
+
604
+ Permission-check results are cached in memory for 5 minutes by default. This removes most
605
+ repeated calls from a user interface.
606
+
607
+ ```ts
608
+ new LumoAuth({ baseUrl, token, cache: false }); // no cache
609
+ new LumoAuth({ baseUrl, token, cache: { ttl: 600_000 } }); // 10 minutes
610
+ client.clearCache(); // after a role change
611
+ ```
612
+
613
+ Call `clearCache()` after the user's roles, groups or attributes change. Otherwise the client can
614
+ return an old answer until the entry expires.
615
+
616
+ ## Errors
617
+
618
+ Every error is a `LumoAuthError` with a stable `code`. The classes are exported from this package.
619
+
620
+ ```
621
+ LumoAuthError
622
+ ├── LumoAuthApiError any other non-2xx response API_ERROR
623
+ │ ├── LumoAuthAuthenticationError 401 AUTHENTICATION_ERROR
624
+ │ ├── LumoAuthPermissionDeniedError 403 PERMISSION_DENIED
625
+ │ ├── LumoAuthNotFoundError 404 NOT_FOUND
626
+ │ └── LumoAuthRateLimitError 429 RATE_LIMITED
627
+ ├── LumoAuthValidationError the response did not match its schema
628
+ ├── LumoAuthConfigError bad options, such as an API key in the browser
629
+ ├── LumoAuthNetworkError the request failed or timed out
630
+ ├── LumoAuthApprovalDeniedError a human declined an approval
631
+ ├── LumoAuthApprovalTimeoutError nobody answered an approval in time
632
+ ├── LumoAuthApprovalNotDeliveredError the approval prompt reached no device
633
+ └── LumoAuthBudgetExceededError an agent ran out of budget
634
+ ```
635
+
636
+ `LumoAuthApiError` has `statusCode` and `body`. `LumoAuthPermissionDeniedError` also has
637
+ `requiredScopes`, and `LumoAuthRateLimitError` has `retryAfter` in seconds.
638
+ `LumoAuthAuthError` is an older name for `LumoAuthAuthenticationError`. It will be removed in 2.0.
639
+
640
+ ```ts
641
+ import {
642
+ LumoAuthAuthenticationError,
643
+ LumoAuthPermissionDeniedError,
644
+ LumoAuthRateLimitError,
645
+ LumoAuthApiError,
646
+ LumoAuthNetworkError,
647
+ } from '@lumoauth/client';
648
+
649
+ try {
650
+ const slugs = await client.permissions.listSlugs();
651
+ } catch (err) {
652
+ if (err instanceof LumoAuthAuthenticationError) {
653
+ redirectToSignIn(); // 401: the token is missing or expired
654
+ } else if (err instanceof LumoAuthPermissionDeniedError) {
655
+ if (err.requiredScopes.length > 0) {
656
+ requestScopes(err.requiredScopes); // e.g. ['authz:read']
657
+ } else {
658
+ showForbidden();
659
+ }
660
+ } else if (err instanceof LumoAuthRateLimitError) {
661
+ retryLater(err.retryAfter); // seconds, when the server sent Retry-After
662
+ } else if (err instanceof LumoAuthApiError) {
663
+ console.error(err.code, err.statusCode, err.body);
664
+ } else if (err instanceof LumoAuthNetworkError) {
665
+ showOfflineMessage();
666
+ } else {
667
+ throw err;
668
+ }
669
+ }
670
+ ```
671
+
672
+ Every request and response also has a Zod schema, exported with its type, such as
673
+ `ZanzibarCheckRequestSchema` and `AbacCheckResponse`. You can use them to check your own input.
674
+
675
+ ## API reference
676
+
677
+ | Namespace | Method | Returns | Needs |
678
+ |---|---|---|---|
679
+ | `permissions` | `check(permission, context?, subject?)` | `boolean` | user token; `authz:check` for a `subject` other than the user |
680
+ | | `checkDetailed(permission, context?, subject?)` | full response | as above |
681
+ | | `checkBulk(permissions, context?, subject?)` | `{ results }` | as above |
682
+ | | `checkAny` / `checkAll(permissions, context?, subject?)` | `boolean` | as above |
683
+ | | `checkAnyDetailed` / `checkAllDetailed` | full response | user token |
684
+ | | `list()` | `{ permissions }` | `authz:read` |
685
+ | | `listSlugs()` | `Set<string>` | `authz:read` |
686
+ | | `clearCache()` | `void` | none |
687
+ | `zanzibar` | `check({ object, relation, subject })` | `boolean` | user token; `authz:check` for another subject |
688
+ | | `checkDetailed(…)` | full response | as above |
689
+ | | `expand({ object, relation })` | subject tree | as above |
690
+ | | `isViewer` / `isEditor` / `isOwner` / `isMember` / `isAdmin(object, subject)` | `boolean` | as above |
691
+ | `abac` | `check(request)` | `{ allowed, reason?, matchedPolicies? }` | `orgId`, `abac:read` |
692
+ | | `isAllowed(type, action, id?, context?)` | `boolean` | `orgId`, `abac:read` |
693
+ | | `checkBulk({ checks, context? })` | `{ results }` | `orgId`, `abac:read` |
694
+ | | `getMyAttributes()` | attributes | `orgId`, `abac:read` |
695
+ | | `getResourceAttributes(type, id)` | attributes | `orgId`, `abac:read` |
696
+ | | `getAttributeDefinitions(kind?)` | definitions | `orgId`, `abac:read` |
697
+ | | `setUserAttribute(userId, slug, value)` | `void` | `orgId`, `abac:write`, `abac.manage` |
698
+ | | `setResourceAttribute(type, id, slug, value)` | `void` | `orgId`, `abac:write`, `abac.manage` |
699
+ | `auth` | `buildAuthorizationUrl({ redirectUri, scope?, extraParams? })` | `{ url, codeVerifier, state }` | `orgId`, `clientId` |
700
+ | | `exchangeCodeForTokens({ code, codeVerifier, redirectUri, clientSecret? })` | `TokenResponse` | `orgId`, `clientId` |
701
+ | | `refreshToken(refreshToken)` | `TokenResponse` | `orgId`, `clientId` |
702
+ | | `revokeToken(token, accessToken?)` | `void` | `orgId`, `clientId` |
703
+ | | `getUserInfo(accessToken)` | `UserInfo` | `orgId` |
704
+ | | `checkEmailExists(email)` | `EmailCheckResult` | `orgId` |
705
+ | | `requestMagicLink({ email, redirectUri? })` | `{ sent: true }` | `orgId` |
706
+ | | `loginWithPassword({ email, password })` | `{ status, challengeUrl? }` | `orgId` |
707
+ | | `passwordGrant(username, password, …)` | `TokenResponse` | older grant; the organization must allow it |
708
+ | `agents` | `ask(action, context?)` / `isAllowed(action, context?)` | decision / `boolean` | `orgId` |
709
+ | | `me()` / `getCurrentAgent()` / `capabilities()` | identity / `string[]` | `orgId` |
710
+ | | `budget()` | budget policy | `orgId`, agent token |
711
+ | | `register(request)` | registration | `orgId`, `admin:agents:write` |
712
+ | `approvals` | `getStatus(token)` / `wait(token, options?)` | `ApprovalResult` | `orgId` |
713
+ | client | `clearCache()` | `void` | none |
714
+
715
+ ## Troubleshooting
716
+
717
+ | Symptom | Cause | Fix |
718
+ |---|---|---|
719
+ | `LumoAuthConfigError: Refusing to use a LumoAuth tenant API key` | You passed an `lmk_…` key as `token` in a browser. | Move the code to your server and use `@lumoauth/backend`. |
720
+ | `403` with `requiredScopes: ['authz:read']` on `list()` or `listSlugs()` | The user's token lacks `authz:read`. | Allow the scope on the OAuth client and add it to `scope` at sign-in. |
721
+ | `403` with `requiredScopes: ['abac:read']` on an ABAC call | The user's token lacks `abac:read`. | Request `abac:read`, or `abac:write` for writes. |
722
+ | `401` on ABAC, agent or approval calls with an API key | API keys work only on the admin API, client registration and the permission-check routes. | Use a user access token or an agent credential. |
723
+ | `agents.me()` returns `capabilities: []` | A user token without `authz:read` gets an empty list. | Request `authz:read`. For an agent, call it with the agent's credential. |
724
+ | The token exchange fails with a CORS error | Your origin is not in the OAuth client's allowed origins. | Add the origin to the client in the LumoAuth dashboard. |
725
+ | A refresh succeeds once, then the user is signed out | The old refresh token was used again. LumoAuth rotates refresh tokens. | Save the new `refresh_token` from every refresh, or use `LumoAuthSession`. |
726
+ | `LumoAuthRateLimitError` | Too many requests | Wait for `retryAfter` seconds, then retry. |
727
+ | A permission change does not show up | The cached answer has not expired yet. | Call `client.clearCache()`. |
728
+
729
+ ## Versioning and compatibility
730
+
731
+ This package is version 1.0.0. It needs LumoAuth server API 1.0.0 or newer. Every
732
+ `@lumoauth/*` package in this repository is currently at 1.0.0.
733
+
734
+ To run the tests, see [Development](../../README.md) in the workspace README.
735
+
736
+ ## Related packages
737
+
738
+ | Package | Relationship |
739
+ |---|---|
740
+ | [`@lumoauth/react`](../react/README.md) | Provider, components and hooks built on this package |
741
+ | [`@lumoauth/nextjs`](../nextjs/README.md) | Next.js App Router integration, with an httpOnly-cookie session |
742
+ | [`@lumoauth/backend`](../backend/README.md) | Server code that holds an organization credential |
743
+ | [`@lumoauth/express`](../express/README.md) | Sign-in routes and route guards for Express |
744
+ | [`@lumoauth/agent`](../agent/README.md) | AI agents that act as themselves |
745
+ | [`@lumoauth/shared`](../shared/README.md) | The core modules that this package re-exports |
746
+ | [Workspace README](../../README.md) | How the packages fit together |
747
+
748
+ More: [SDK overview](https://docs.lumoauth.dev/developer/sdks/),
749
+ [React quickstart](https://docs.lumoauth.dev/quickstarts/react/),
750
+ [Vue quickstart](https://docs.lumoauth.dev/quickstarts/vue/), and the
751
+ [example app](../../examples/nextjs/README.md), which has `/storage` and `/cross-tab` pages.
752
+
753
+ ## Licence
754
+
755
+ [MIT](./LICENSE)