@lumoauth/client 1.0.0 β 1.2.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 +489 -499
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,510 +1,486 @@
|
|
|
1
1
|
# @lumoauth/client
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
##
|
|
18
|
-
|
|
19
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@lumoauth/client)
|
|
4
|
+
[](./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 |
|
|
20
48
|
|---|---|
|
|
21
|
-
|
|
|
22
|
-
|
|
|
23
|
-
|
|
|
24
|
-
|
|
|
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) |
|
|
25
55
|
|
|
26
|
-
##
|
|
56
|
+
## Requirements
|
|
27
57
|
|
|
28
|
-
|
|
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
|
|
29
63
|
|
|
30
64
|
```bash
|
|
31
|
-
# npm
|
|
32
65
|
npm install @lumoauth/client
|
|
33
|
-
|
|
34
|
-
# yarn
|
|
35
|
-
yarn add @lumoauth/client
|
|
36
|
-
|
|
37
|
-
# pnpm
|
|
66
|
+
# or
|
|
38
67
|
pnpm add @lumoauth/client
|
|
68
|
+
yarn add @lumoauth/client
|
|
39
69
|
```
|
|
40
70
|
|
|
41
|
-
|
|
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:
|
|
42
76
|
|
|
43
77
|
```ts
|
|
44
78
|
import { LumoAuth } from '@lumoauth/client';
|
|
45
79
|
|
|
46
80
|
const client = new LumoAuth({
|
|
47
|
-
baseUrl: 'https://
|
|
48
|
-
|
|
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',
|
|
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
|
|
59
84
|
});
|
|
60
85
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
resourceId: 'doc-123',
|
|
65
|
-
action: 'read',
|
|
66
|
-
});
|
|
86
|
+
if (await client.permissions.check('document.edit')) {
|
|
87
|
+
showEditButton();
|
|
88
|
+
}
|
|
67
89
|
```
|
|
68
90
|
|
|
69
|
-
|
|
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).
|
|
70
93
|
|
|
71
|
-
|
|
94
|
+
This package is for users, not agents. For an agent, start with
|
|
95
|
+
[`@lumoauth/agent`](../agent/README.md).
|
|
72
96
|
|
|
73
|
-
|
|
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
|
-
```
|
|
97
|
+
## Core concepts
|
|
86
98
|
|
|
87
|
-
|
|
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.
|
|
88
102
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
token: 'eyJhbGciOi...'
|
|
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.
|
|
92
105
|
|
|
93
|
-
|
|
94
|
-
token: () => req.cookies.access_token
|
|
106
|
+
### Credentials
|
|
95
107
|
|
|
96
|
-
|
|
97
|
-
token: async () => {
|
|
98
|
-
const session = await getSession();
|
|
99
|
-
return session.accessToken;
|
|
100
|
-
}
|
|
108
|
+
LumoAuth accepts three kinds of credential. This package uses only the first.
|
|
101
109
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
```
|
|
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 |
|
|
108
115
|
|
|
109
|
-
|
|
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).
|
|
110
120
|
|
|
111
|
-
|
|
121
|
+
### Scopes
|
|
112
122
|
|
|
113
|
-
|
|
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.
|
|
114
125
|
|
|
115
|
-
|
|
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 |
|
|
116
133
|
|
|
117
|
-
|
|
134
|
+
The blanket `admin` scope satisfies all of them. A Zanzibar check about a subject other than
|
|
135
|
+
the caller needs `authz:check`.
|
|
118
136
|
|
|
119
|
-
|
|
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:
|
|
120
140
|
|
|
121
141
|
```ts
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
const canEditDoc = await client.permissions.check('document.edit', {
|
|
126
|
-
document_id: 456,
|
|
127
|
-
owner_id: 123,
|
|
142
|
+
await client.auth.buildAuthorizationUrl({
|
|
143
|
+
redirectUri: 'https://myapp.example.com/auth/callback',
|
|
144
|
+
scope: 'openid profile email authz:read abac:read',
|
|
128
145
|
});
|
|
129
146
|
```
|
|
130
147
|
|
|
131
|
-
|
|
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 |
|
|
132
163
|
|
|
133
|
-
|
|
164
|
+
Ways to supply the token:
|
|
134
165
|
|
|
135
166
|
```ts
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
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'];
|
|
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)
|
|
145
170
|
```
|
|
146
171
|
|
|
147
|
-
|
|
172
|
+
## Guides
|
|
173
|
+
|
|
174
|
+
### Check permissions (RBAC)
|
|
148
175
|
|
|
149
|
-
|
|
176
|
+
Use permission checks when access depends on the user's roles and groups. A permission is a slug
|
|
177
|
+
such as `document.edit`.
|
|
150
178
|
|
|
151
179
|
```ts
|
|
152
|
-
const
|
|
153
|
-
'document.owner',
|
|
154
|
-
'document.editor',
|
|
155
|
-
'admin.all',
|
|
156
|
-
]);
|
|
157
|
-
```
|
|
180
|
+
const canEdit = await client.permissions.check('document.edit');
|
|
158
181
|
|
|
159
|
-
|
|
182
|
+
// Optional context for policies that read request data
|
|
183
|
+
const canEditThis = await client.permissions.check('document.edit', { document_id: 456 });
|
|
160
184
|
|
|
161
|
-
|
|
185
|
+
// Many permissions in one request
|
|
186
|
+
const { results } = await client.permissions.checkBulk(['document.edit', 'document.delete']);
|
|
187
|
+
deleteButton.hidden = !results['document.delete'];
|
|
162
188
|
|
|
163
|
-
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
'document.publish',
|
|
167
|
-
]);
|
|
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']);
|
|
168
192
|
```
|
|
169
193
|
|
|
170
|
-
|
|
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).
|
|
171
199
|
|
|
172
|
-
|
|
200
|
+
To list every permission that the user holds, the token needs the `authz:read` scope:
|
|
173
201
|
|
|
174
202
|
```ts
|
|
175
|
-
|
|
176
|
-
const { permissions } = await client.permissions.list();
|
|
177
|
-
|
|
178
|
-
// Just slugs as a Set
|
|
179
|
-
const slugs = await client.permissions.listSlugs();
|
|
203
|
+
const slugs = await client.permissions.listSlugs(); // Set<string>
|
|
180
204
|
if (slugs.has('settings.manage')) showSettingsNav();
|
|
181
205
|
```
|
|
182
206
|
|
|
183
|
-
|
|
207
|
+
Without `authz:read`, `list()` and `listSlugs()` throw a `LumoAuthPermissionDeniedError` whose
|
|
208
|
+
`requiredScopes` is `['authz:read']`.
|
|
184
209
|
|
|
185
|
-
|
|
210
|
+
### Check relationships (Zanzibar)
|
|
186
211
|
|
|
187
|
-
|
|
212
|
+
Use relationship checks for sharing, ownership and hierarchies. The question is: does this
|
|
213
|
+
subject have this relation to this object?
|
|
188
214
|
|
|
189
215
|
```ts
|
|
190
|
-
// Direct user check
|
|
191
216
|
const canView = await client.zanzibar.check({
|
|
192
217
|
object: 'document:q4-report',
|
|
193
218
|
relation: 'viewer',
|
|
194
219
|
subject: 'user:carol',
|
|
195
220
|
});
|
|
196
221
|
|
|
197
|
-
//
|
|
198
|
-
|
|
222
|
+
// A subject can also be a set, such as the members of a team
|
|
223
|
+
await client.zanzibar.check({
|
|
199
224
|
object: 'document:api-docs',
|
|
200
225
|
relation: 'viewer',
|
|
201
226
|
subject: 'team:engineering#member',
|
|
202
227
|
});
|
|
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
228
|
|
|
212
|
-
|
|
213
|
-
await client.zanzibar.isViewer('document:readme', 'user:bob');
|
|
214
|
-
await client.zanzibar.isEditor('document:readme', 'user:alice');
|
|
229
|
+
// Shorthands for common relations: isViewer, isEditor, isOwner, isMember, isAdmin
|
|
215
230
|
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
231
|
|
|
220
|
-
|
|
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
|
+
```
|
|
221
235
|
|
|
222
|
-
|
|
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.
|
|
223
239
|
|
|
224
|
-
|
|
240
|
+
### Evaluate attribute policies (ABAC)
|
|
225
241
|
|
|
226
|
-
|
|
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.
|
|
227
246
|
|
|
228
247
|
```ts
|
|
229
248
|
const decision = await client.abac.check({
|
|
230
249
|
resourceType: 'document',
|
|
231
250
|
resourceId: 'doc-123',
|
|
232
251
|
action: 'read',
|
|
233
|
-
context: {
|
|
234
|
-
resource: { classification: 'internal' },
|
|
235
|
-
},
|
|
252
|
+
context: { channel: 'web' }, // environment attributes that policies can read
|
|
236
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
|
|
237
257
|
|
|
238
|
-
|
|
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
|
-
```
|
|
258
|
+
if (await client.abac.isAllowed('document', 'read', 'doc-123')) showDocument();
|
|
252
259
|
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
Check up to 100 resource/action pairs in one request.
|
|
256
|
-
|
|
257
|
-
```ts
|
|
260
|
+
// Up to 100 checks in one request, with one context for all of them
|
|
258
261
|
const { results } = await client.abac.checkBulk({
|
|
259
|
-
|
|
262
|
+
checks: [
|
|
260
263
|
{ resourceType: 'document', resourceId: 'doc-1', action: 'read' },
|
|
261
264
|
{ resourceType: 'document', resourceId: 'doc-2', action: 'write' },
|
|
262
|
-
{ resourceType: 'api', action: 'execute' },
|
|
263
265
|
],
|
|
266
|
+
context: { channel: 'web' },
|
|
264
267
|
});
|
|
268
|
+
// results[i] β { index, resourceType, action, resourceId, allowed, reason, error? }
|
|
265
269
|
```
|
|
266
270
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
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);
|
|
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.
|
|
276
275
|
|
|
277
|
-
|
|
278
|
-
|
|
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`.
|
|
279
280
|
|
|
280
|
-
|
|
281
|
-
await client.abac.setResourceAttribute('document', 'doc-123', 'classification', 'confidential');
|
|
281
|
+
Attribute calls:
|
|
282
282
|
|
|
283
|
-
|
|
284
|
-
|
|
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
|
|
285
289
|
```
|
|
286
290
|
|
|
287
|
-
|
|
291
|
+
Setting attributes also needs the `abac.manage` permission.
|
|
288
292
|
|
|
289
|
-
|
|
293
|
+
### Sign users in (OAuth 2.0 and PKCE)
|
|
290
294
|
|
|
291
|
-
|
|
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.
|
|
292
299
|
|
|
293
|
-
|
|
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.
|
|
294
302
|
|
|
295
303
|
```ts
|
|
296
|
-
|
|
304
|
+
const client = new LumoAuth({ baseUrl, orgId: 'acme-corp', clientId: 'your-client-id' });
|
|
305
|
+
const redirectUri = 'https://myapp.example.com/auth/callback';
|
|
297
306
|
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
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
|
|
302
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!);
|
|
303
330
|
```
|
|
304
331
|
|
|
305
|
-
|
|
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.
|
|
306
335
|
|
|
307
|
-
|
|
336
|
+
`buildAuthorizationUrl` also takes `extraParams`. For example, `{ provider: 'google' }` sends the
|
|
337
|
+
user straight to that social provider.
|
|
308
338
|
|
|
309
|
-
|
|
310
|
-
await auth.requestMagicLink({ email: 'user@example.com' });
|
|
311
|
-
// β { sent: true }
|
|
339
|
+
### Passwordless, email-first and embedded sign-in
|
|
312
340
|
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
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
|
+
}
|
|
318
361
|
```
|
|
319
362
|
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
| `options.email` | `string` | The user's email address |
|
|
323
|
-
| `options.redirectUri` | `string?` | Where to redirect after the link is clicked |
|
|
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.
|
|
324
365
|
|
|
325
|
-
|
|
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.
|
|
326
370
|
|
|
327
|
-
|
|
371
|
+
### Keep the session alive
|
|
328
372
|
|
|
329
|
-
|
|
373
|
+
`LumoAuthSession` manages a browser session without depending on a framework. It handles these
|
|
374
|
+
jobs:
|
|
330
375
|
|
|
331
|
-
|
|
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.
|
|
332
380
|
|
|
333
|
-
|
|
381
|
+
`@lumoauth/react` is built on it. A Vue or Svelte binding can use it in the same way.
|
|
334
382
|
|
|
335
383
|
```ts
|
|
336
|
-
|
|
384
|
+
import { LumoAuthSession, AuthModule, LumoAuth, localStorageAdapter } from '@lumoauth/client';
|
|
337
385
|
|
|
338
|
-
|
|
339
|
-
// Show password field or magic-link option
|
|
340
|
-
} else {
|
|
341
|
-
// Show "no account found" message or sign-up prompt
|
|
342
|
-
}
|
|
343
|
-
```
|
|
386
|
+
const auth = new AuthModule({ baseUrl, orgId: 'acme-corp', clientId: 'your-client-id' });
|
|
344
387
|
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
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
|
+
});
|
|
350
395
|
|
|
351
|
-
|
|
396
|
+
await session.hydrate(); // load saved tokens and schedule the next refresh
|
|
352
397
|
|
|
353
|
-
|
|
354
|
-
|
|
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 }));
|
|
355
402
|
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
redirectUri?: string; // optional post-click redirect
|
|
359
|
-
}
|
|
403
|
+
// Use the session's token for API calls
|
|
404
|
+
const client = new LumoAuth({ baseUrl, orgId: 'acme-corp', token: () => session.getToken().then((t) => t ?? '') });
|
|
360
405
|
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
}
|
|
406
|
+
// React to changes
|
|
407
|
+
const unsubscribe = session.subscribe(() => render(session.getSnapshot()));
|
|
364
408
|
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
}
|
|
409
|
+
// Sign out locally
|
|
410
|
+
await session.clearSession();
|
|
368
411
|
```
|
|
369
412
|
|
|
370
|
-
|
|
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 |
|
|
371
424
|
|
|
372
|
-
|
|
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'`.
|
|
373
428
|
|
|
374
|
-
|
|
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()`.
|
|
375
432
|
|
|
376
|
-
|
|
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
|
-
}
|
|
433
|
+
### Choose where tokens are stored
|
|
403
434
|
|
|
404
|
-
|
|
405
|
-
const client = useContext(LumoAuthContext);
|
|
406
|
-
if (!client) throw new Error('Wrap your app in <LumoAuthProvider>');
|
|
407
|
-
return client;
|
|
408
|
-
}
|
|
435
|
+
Where tokens are stored is a security decision, so the SDK makes you choose it.
|
|
409
436
|
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
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 |
|
|
415
443
|
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
.finally(() => setLoading(false));
|
|
420
|
-
}, [client, permission]);
|
|
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:
|
|
421
447
|
|
|
422
|
-
|
|
423
|
-
|
|
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`) |
|
|
424
452
|
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
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
|
|
432
460
|
|
|
433
|
-
|
|
461
|
+
This client includes two parts of the agent API that are safe in a browser:
|
|
434
462
|
|
|
435
463
|
```ts
|
|
436
|
-
//
|
|
437
|
-
|
|
438
|
-
|
|
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
|
-
```
|
|
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.
|
|
449
468
|
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
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
|
-
}
|
|
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'
|
|
474
472
|
```
|
|
475
473
|
|
|
476
|
-
|
|
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
|
-
}
|
|
474
|
+
`client.approvals` can only read approvals (`getStatus` and `wait`). An agent creates approvals
|
|
475
|
+
on the server with `@lumoauth/agent` or `@lumoauth/backend`.
|
|
500
476
|
|
|
501
|
-
|
|
502
|
-
}
|
|
477
|
+
### Use it from other frameworks
|
|
503
478
|
|
|
504
|
-
|
|
505
|
-
|
|
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.
|
|
506
481
|
|
|
507
|
-
|
|
482
|
+
<details>
|
|
483
|
+
<summary><strong>Vue 3</strong> (Composition API)</summary>
|
|
508
484
|
|
|
509
485
|
```ts
|
|
510
486
|
// composables/useLumoAuth.ts
|
|
@@ -529,17 +505,14 @@ export function usePermission(permission: string) {
|
|
|
529
505
|
const client = useLumoAuth();
|
|
530
506
|
const allowed = ref(false);
|
|
531
507
|
const loading = ref(true);
|
|
532
|
-
|
|
533
508
|
client.permissions.check(permission)
|
|
534
|
-
.then(
|
|
509
|
+
.then((r) => { allowed.value = r; })
|
|
535
510
|
.finally(() => { loading.value = false; });
|
|
536
|
-
|
|
537
511
|
return { allowed, loading };
|
|
538
512
|
}
|
|
539
513
|
```
|
|
540
514
|
|
|
541
515
|
```vue
|
|
542
|
-
<!-- components/EditButton.vue -->
|
|
543
516
|
<script setup>
|
|
544
517
|
import { usePermission } from '@/composables/useLumoAuth';
|
|
545
518
|
const { allowed, loading } = usePermission('document.edit');
|
|
@@ -550,7 +523,10 @@ const { allowed, loading } = usePermission('document.edit');
|
|
|
550
523
|
</template>
|
|
551
524
|
```
|
|
552
525
|
|
|
553
|
-
|
|
526
|
+
</details>
|
|
527
|
+
|
|
528
|
+
<details>
|
|
529
|
+
<summary><strong>Svelte</strong></summary>
|
|
554
530
|
|
|
555
531
|
```ts
|
|
556
532
|
// lib/lumoauth.ts
|
|
@@ -562,20 +538,16 @@ export const lumoAuth = new LumoAuth({
|
|
|
562
538
|
token: () => localStorage.getItem('access_token') ?? '',
|
|
563
539
|
});
|
|
564
540
|
|
|
565
|
-
// Reactive permission store
|
|
566
541
|
export function createPermissionStore(permission: string) {
|
|
567
542
|
const store = writable({ allowed: false, loading: true });
|
|
568
|
-
|
|
569
543
|
lumoAuth.permissions.check(permission)
|
|
570
|
-
.then(allowed => store.set({ allowed, loading: false }))
|
|
544
|
+
.then((allowed) => store.set({ allowed, loading: false }))
|
|
571
545
|
.catch(() => store.set({ allowed: false, loading: false }));
|
|
572
|
-
|
|
573
546
|
return store;
|
|
574
547
|
}
|
|
575
548
|
```
|
|
576
549
|
|
|
577
550
|
```svelte
|
|
578
|
-
<!-- EditButton.svelte -->
|
|
579
551
|
<script>
|
|
580
552
|
import { createPermissionStore } from '$lib/lumoauth';
|
|
581
553
|
const perm = createPermissionStore('document.edit');
|
|
@@ -586,7 +558,14 @@ export function createPermissionStore(permission: string) {
|
|
|
586
558
|
{/if}
|
|
587
559
|
```
|
|
588
560
|
|
|
589
|
-
|
|
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).
|
|
590
569
|
|
|
591
570
|
```ts
|
|
592
571
|
import express from 'express';
|
|
@@ -594,172 +573,183 @@ import { LumoAuth, LumoAuthApiError } from '@lumoauth/client';
|
|
|
594
573
|
|
|
595
574
|
const app = express();
|
|
596
575
|
|
|
597
|
-
// Middleware: attach LumoAuth client to request
|
|
598
576
|
app.use((req, res, next) => {
|
|
599
|
-
const token = req.headers.authorization?.replace(
|
|
600
|
-
if (!token) return res.status(401).json({ error: '
|
|
601
|
-
|
|
602
|
-
req.lumoAuth = new LumoAuth({
|
|
603
|
-
baseUrl: process.env.LUMOAUTH_URL!,
|
|
604
|
-
token,
|
|
605
|
-
});
|
|
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 });
|
|
606
580
|
next();
|
|
607
581
|
});
|
|
608
582
|
|
|
609
|
-
// Helper middleware: require a permission
|
|
610
583
|
function requirePermission(...permissions: string[]) {
|
|
611
|
-
return async (req
|
|
584
|
+
return async (req, res, next) => {
|
|
612
585
|
try {
|
|
613
|
-
|
|
614
|
-
|
|
586
|
+
if (!(await req.lumoAuth.permissions.checkAll(permissions))) {
|
|
587
|
+
return res.status(403).json({ error: 'forbidden' });
|
|
588
|
+
}
|
|
615
589
|
next();
|
|
616
590
|
} catch (err) {
|
|
617
|
-
if (err instanceof LumoAuthApiError) {
|
|
618
|
-
return res.status(err.statusCode).json({ error: err.message });
|
|
619
|
-
}
|
|
591
|
+
if (err instanceof LumoAuthApiError) return res.status(err.statusCode ?? 502).json({ error: err.message });
|
|
620
592
|
next(err);
|
|
621
593
|
}
|
|
622
594
|
};
|
|
623
595
|
}
|
|
624
596
|
|
|
625
|
-
|
|
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
|
-
});
|
|
597
|
+
app.delete('/api/documents/:id', requirePermission('document.delete'), (req, res) => res.json({ deleted: true }));
|
|
630
598
|
```
|
|
631
599
|
|
|
632
|
-
|
|
600
|
+
</details>
|
|
633
601
|
|
|
634
|
-
##
|
|
602
|
+
## Caching
|
|
635
603
|
|
|
636
|
-
|
|
604
|
+
Permission-check results are cached in memory for 5 minutes by default. This removes most
|
|
605
|
+
repeated calls from a user interface.
|
|
637
606
|
|
|
638
607
|
```ts
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
//
|
|
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
|
-
});
|
|
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
|
|
664
611
|
```
|
|
665
612
|
|
|
666
|
-
|
|
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.
|
|
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.
|
|
673
615
|
|
|
674
|
-
|
|
675
|
-
// Disable caching
|
|
676
|
-
const client = new LumoAuth({ baseUrl, token, cache: false });
|
|
616
|
+
## Errors
|
|
677
617
|
|
|
678
|
-
|
|
679
|
-
const client = new LumoAuth({ baseUrl, token, cache: { ttl: 600_000 } });
|
|
618
|
+
Every error is a `LumoAuthError` with a stable `code`. The classes are exported from this package.
|
|
680
619
|
|
|
681
|
-
|
|
682
|
-
|
|
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
|
|
683
634
|
```
|
|
684
635
|
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
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.
|
|
688
639
|
|
|
689
640
|
```ts
|
|
690
641
|
import {
|
|
691
|
-
|
|
642
|
+
LumoAuthAuthenticationError,
|
|
643
|
+
LumoAuthPermissionDeniedError,
|
|
644
|
+
LumoAuthRateLimitError,
|
|
692
645
|
LumoAuthApiError,
|
|
693
|
-
LumoAuthAuthError,
|
|
694
646
|
LumoAuthNetworkError,
|
|
695
|
-
LumoAuthValidationError,
|
|
696
|
-
LumoAuthConfigError,
|
|
697
647
|
} from '@lumoauth/client';
|
|
698
648
|
|
|
699
649
|
try {
|
|
700
|
-
await client.permissions.
|
|
650
|
+
const slugs = await client.permissions.listSlugs();
|
|
701
651
|
} catch (err) {
|
|
702
|
-
if (err instanceof
|
|
703
|
-
// 401
|
|
704
|
-
|
|
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
|
|
705
662
|
} else if (err instanceof LumoAuthApiError) {
|
|
706
|
-
// 4xx/5xx β server error
|
|
707
663
|
console.error(err.code, err.statusCode, err.body);
|
|
708
664
|
} else if (err instanceof LumoAuthNetworkError) {
|
|
709
|
-
// Network failure / timeout
|
|
710
665
|
showOfflineMessage();
|
|
711
|
-
} else
|
|
712
|
-
|
|
713
|
-
console.error('Unexpected API response:', err.issues);
|
|
666
|
+
} else {
|
|
667
|
+
throw err;
|
|
714
668
|
}
|
|
715
669
|
}
|
|
716
670
|
```
|
|
717
671
|
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
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)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lumoauth/client",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "Official LumoAuth browser SDK β OAuth 2.0 PKCE, permissions, Zanzibar (ReBAC), and ABAC for any JavaScript/TypeScript application.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "LumoAuth",
|