@lumoauth/express 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 +295 -16
- package/dist/index.d.mts +19 -1
- package/dist/index.d.ts +19 -1
- package/dist/index.js +75 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +75 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -1,50 +1,329 @@
|
|
|
1
1
|
# @lumoauth/express
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@lumoauth/express)
|
|
4
|
+
[](./LICENSE)
|
|
5
|
+
|
|
6
|
+
`@lumoauth/express` adds LumoAuth sign-in to an Express app. One middleware adds three routes:
|
|
7
|
+
sign-in, callback and sign-out. It also puts the signed-in user on `req.user`. `requireAuth()`
|
|
8
|
+
then guards the routes that need a user. The package also re-exports the server client and the
|
|
9
|
+
error classes from [`@lumoauth/backend`](../backend/README.md), so an Express app needs only this
|
|
10
|
+
one install.
|
|
11
|
+
|
|
12
|
+
It is part of the [LumoAuth JavaScript SDK](../../README.md).
|
|
13
|
+
|
|
14
|
+
## Contents
|
|
15
|
+
|
|
16
|
+
- [Is this the right package?](#is-this-the-right-package)
|
|
17
|
+
- [Requirements](#requirements)
|
|
18
|
+
- [Install](#install)
|
|
19
|
+
- [Quick start](#quick-start)
|
|
20
|
+
- [Core concepts](#core-concepts)
|
|
21
|
+
- [Configuration](#configuration)
|
|
22
|
+
- [Guides](#guides)
|
|
23
|
+
- [How sign-in works](#how-sign-in-works)
|
|
24
|
+
- [Guard routes with requireAuth()](#guard-routes-with-requireauth)
|
|
25
|
+
- [Check access inside a handler](#check-access-inside-a-handler)
|
|
26
|
+
- [Run behind a proxy](#run-behind-a-proxy)
|
|
27
|
+
- [Errors](#errors)
|
|
28
|
+
- [API reference](#api-reference)
|
|
29
|
+
- [Troubleshooting](#troubleshooting)
|
|
30
|
+
- [Limitations](#limitations)
|
|
31
|
+
- [Versioning and compatibility](#versioning-and-compatibility)
|
|
32
|
+
- [Related packages](#related-packages)
|
|
33
|
+
- [Licence](#licence)
|
|
34
|
+
|
|
35
|
+
## Is this the right package?
|
|
36
|
+
|
|
37
|
+
| You are running… | Use |
|
|
38
|
+
|---|---|
|
|
39
|
+
| Express 4.18+ with `express-session` | **This package** |
|
|
40
|
+
| Fastify, Hono, Koa or a plain Node service | [`@lumoauth/backend`](../backend/README.md) |
|
|
41
|
+
| Next.js | [`@lumoauth/nextjs`](../nextjs/README.md) |
|
|
42
|
+
| A browser app that calls your Express API | [`@lumoauth/react`](../react/README.md) or [`@lumoauth/client`](../client/README.md) in the browser |
|
|
43
|
+
|
|
44
|
+
## Requirements
|
|
45
|
+
|
|
46
|
+
- Node 18 or newer
|
|
47
|
+
- `express` 4.18 or newer and `express-session` 1.17 or newer (peer dependencies)
|
|
48
|
+
- A LumoAuth organization and an OAuth client. Register `<your origin>/auth/callback` as a
|
|
49
|
+
redirect URI. A confidential client also needs its client secret.
|
|
7
50
|
|
|
8
51
|
## Install
|
|
9
52
|
|
|
10
|
-
```
|
|
53
|
+
```bash
|
|
11
54
|
npm install @lumoauth/express express-session
|
|
12
55
|
```
|
|
13
56
|
|
|
14
|
-
##
|
|
57
|
+
## Quick start
|
|
15
58
|
|
|
16
59
|
```ts
|
|
17
60
|
import express from 'express';
|
|
18
61
|
import session from 'express-session';
|
|
19
|
-
import { lumoAuthMiddleware, requireAuth
|
|
62
|
+
import { lumoAuthMiddleware, requireAuth } from '@lumoauth/express';
|
|
20
63
|
|
|
21
64
|
const app = express();
|
|
65
|
+
|
|
66
|
+
// 1. Mount sessions first. LumoAuth stores the sign-in state and the tokens in the session.
|
|
22
67
|
app.use(session({ secret: process.env.SESSION_SECRET!, resave: false, saveUninitialized: false }));
|
|
68
|
+
|
|
69
|
+
// 2. Mount LumoAuth once. This adds /auth/login, /auth/callback and /auth/logout,
|
|
70
|
+
// and sets req.user on every request that has a signed-in session.
|
|
23
71
|
app.use(
|
|
24
72
|
lumoAuthMiddleware({
|
|
25
|
-
baseUrl:
|
|
73
|
+
baseUrl: 'https://app.lumoauth.dev', // EU region: https://eu.app.lumoauth.dev
|
|
26
74
|
organization: 'acme-corp',
|
|
27
75
|
clientId: process.env.LUMOAUTH_CLIENT_ID!,
|
|
28
|
-
clientSecret: process.env.LUMOAUTH_CLIENT_SECRET,
|
|
76
|
+
clientSecret: process.env.LUMOAUTH_CLIENT_SECRET, // leave out for a public client with PKCE
|
|
29
77
|
}),
|
|
30
78
|
);
|
|
31
79
|
|
|
80
|
+
// 3. Guard the routes that need a signed-in user.
|
|
32
81
|
app.get('/dashboard', requireAuth(), (req, res) => {
|
|
33
82
|
res.json({ hello: req.user!.email });
|
|
34
83
|
});
|
|
84
|
+
|
|
85
|
+
app.listen(3000);
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Send users to `/auth/login` to sign in, and to `/auth/logout` to sign out.
|
|
89
|
+
|
|
90
|
+
## Core concepts
|
|
91
|
+
|
|
92
|
+
**The session is server-side.** The PKCE verifier, the `state` value and the tokens are stored in your
|
|
93
|
+
`express-session` store. They never appear in a URL or in browser storage. Use a production
|
|
94
|
+
session store, such as Redis, instead of the default memory store.
|
|
95
|
+
|
|
96
|
+
**`req.user` is the user's profile.** After sign-in, the middleware loads the user's profile from
|
|
97
|
+
the OIDC UserInfo endpoint. It stores the profile in the session and restores it on each request.
|
|
98
|
+
|
|
99
|
+
**Guards check the session, not LumoAuth.** `requireAuth()` checks that `req.user` exists and,
|
|
100
|
+
optionally, that the token was granted certain scopes. To check a permission, call LumoAuth
|
|
101
|
+
inside an `authorize` hook or the handler.
|
|
102
|
+
|
|
103
|
+
Credentials and scopes are explained in the [client README](../client/README.md#core-concepts).
|
|
104
|
+
|
|
105
|
+
## Configuration
|
|
106
|
+
|
|
107
|
+
`lumoAuthMiddleware(options)` takes these options:
|
|
108
|
+
|
|
109
|
+
| Option | Type | Default | Description |
|
|
110
|
+
|---|---|---|---|
|
|
111
|
+
| `baseUrl` | `string` | required | Root URL of LumoAuth |
|
|
112
|
+
| `organization` | `string` | required | Organization slug that owns the OAuth client |
|
|
113
|
+
| `clientId` | `string` | required | OAuth client ID |
|
|
114
|
+
| `clientSecret` | `string` | none | Needed for a confidential client. A public client leaves it out and relies on PKCE. |
|
|
115
|
+
| `prefix` | `string` | `'/auth'` | Where the three routes are mounted |
|
|
116
|
+
| `postLoginRedirect` | `string` | `'/'` | Where to go after sign-in when there is no `return_to` |
|
|
117
|
+
| `postLogoutRedirect` | `string` | `'/'` | Where to go after sign-out. Use an absolute URL that is registered as a post-logout redirect URI on the OAuth client, so that sign-out also ends the LumoAuth session. A relative path only clears the local session. |
|
|
118
|
+
| `autoRefresh` | `boolean` | `true` | Refresh the access token when it expires in less than 60 seconds |
|
|
119
|
+
| `endSessionOnLogout` | `boolean` | `true` | On sign-out, revoke the refresh token and end the LumoAuth session. `false` only clears the local session. |
|
|
120
|
+
| `scope` | `string` | `'openid profile email'` | OAuth scopes to request. Add `authz:read` if the app lists the user's permissions, or `abac:read` for ABAC checks. The OAuth client must allow them. |
|
|
121
|
+
| `fetch` | `typeof fetch` | global `fetch` | A custom `fetch`, for tests or a proxy |
|
|
122
|
+
|
|
123
|
+
`req.user` has this type, added to Express's `Request` for you:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
interface SessionUser {
|
|
127
|
+
sub: string;
|
|
128
|
+
email?: string;
|
|
129
|
+
email_verified?: boolean;
|
|
130
|
+
name?: string;
|
|
131
|
+
picture?: string;
|
|
132
|
+
[key: string]: unknown; // any other UserInfo claim
|
|
133
|
+
}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Guides
|
|
137
|
+
|
|
138
|
+
### How sign-in works
|
|
139
|
+
|
|
140
|
+
| Route | Method | What happens |
|
|
141
|
+
|---|---|---|
|
|
142
|
+
| `/auth/login` | GET | Builds an authorization URL with PKCE, saves the verifier and `state` in the session, and redirects to LumoAuth. Accepts `?return_to=/path`; only paths on your own site are accepted. |
|
|
143
|
+
| `/auth/callback` | GET | Checks `state`, exchanges the code for tokens, loads the profile, gives the session a new ID, saves the tokens and profile, and redirects to `return_to` |
|
|
144
|
+
| `/auth/logout` | GET or POST | Removes the LumoAuth data from the session, revokes the refresh token, and redirects through the LumoAuth end-session endpoint to `postLogoutRedirect` |
|
|
145
|
+
| any other path | any | Refreshes the access token when needed, restores `req.user` from the session, then calls `next()` |
|
|
146
|
+
|
|
147
|
+
The new session ID after sign-in prevents session fixation. Sign-out keeps your other session
|
|
148
|
+
data. Call `req.session.destroy()` yourself if you want to remove everything.
|
|
149
|
+
|
|
150
|
+
If `express-session` is not mounted first, every request fails with `500`
|
|
151
|
+
`session_middleware_missing`.
|
|
152
|
+
|
|
153
|
+
### Guard routes with requireAuth()
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
import { requireAuth } from '@lumoauth/express';
|
|
157
|
+
|
|
158
|
+
// Any signed-in user
|
|
159
|
+
app.get('/profile', requireAuth(), handler);
|
|
160
|
+
|
|
161
|
+
// Scopes that the user's token must have
|
|
162
|
+
app.get('/billing', requireAuth({ scopes: ['billing:read'] }), handler);
|
|
163
|
+
|
|
164
|
+
// Your own check; return false to answer 403
|
|
165
|
+
app.get(
|
|
166
|
+
'/admin',
|
|
167
|
+
requireAuth({ authorize: (user) => user.email?.endsWith('@acme.com') ?? false }),
|
|
168
|
+
handler,
|
|
169
|
+
);
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
| Option | Type | Description |
|
|
173
|
+
|---|---|---|
|
|
174
|
+
| `scopes` | `string[]` | Every scope must be in the token's granted `scope`. A missing scope answers `403` with `insufficient_scope`. |
|
|
175
|
+
| `authorize` | `(user, req) => boolean \| Promise<boolean>` | Your own check. `false` answers `403` with `forbidden`. |
|
|
176
|
+
| `unauthorizedStatus` | `number` | Replaces the status code. The defaults are `401` without a user and `403` for a failed check. |
|
|
177
|
+
|
|
178
|
+
Without a signed-in user, `requireAuth()` answers `401` with `{ "error": "unauthenticated" }`.
|
|
179
|
+
|
|
180
|
+
### Check access inside a handler
|
|
181
|
+
|
|
182
|
+
`LumoAuthBackend` is re-exported from [`@lumoauth/backend`](../backend/README.md). It calls
|
|
183
|
+
LumoAuth with a server credential.
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
import { LumoAuthBackend } from '@lumoauth/express';
|
|
187
|
+
|
|
188
|
+
const lumo = new LumoAuthBackend({
|
|
189
|
+
baseUrl: 'https://app.lumoauth.dev',
|
|
190
|
+
orgId: 'acme-corp',
|
|
191
|
+
secretKey: process.env.LUMOAUTH_API_KEY!, // lmk_…, with the authz:check scope
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
app.post('/documents/:id', requireAuth(), async (req, res) => {
|
|
195
|
+
// RBAC: does the signed-in user hold the permission?
|
|
196
|
+
const mayEdit = await lumo.permissions.check('document.edit', undefined, { userId: req.user!.sub });
|
|
197
|
+
if (!mayEdit) return res.status(403).json({ error: 'forbidden' });
|
|
198
|
+
res.json(await saveDocument(req.params.id, req.body));
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
app.get('/documents/:id', requireAuth(), async (req, res) => {
|
|
202
|
+
// ReBAC: is the signed-in user a viewer of this document?
|
|
203
|
+
const allowed = await lumo.zanzibar.check({
|
|
204
|
+
object: `document:${req.params.id}`,
|
|
205
|
+
relation: 'viewer',
|
|
206
|
+
subject: `user:${req.user!.sub}`,
|
|
207
|
+
});
|
|
208
|
+
if (!allowed) return res.status(403).json({ error: 'forbidden' });
|
|
209
|
+
res.json(await loadDocument(req.params.id));
|
|
210
|
+
});
|
|
35
211
|
```
|
|
36
212
|
|
|
37
|
-
|
|
213
|
+
`LumoAuthBackend` sends an organization API key (`lmk_…`) in the `X-API-Key` header. Checks run
|
|
214
|
+
as the credential's owner unless you name a subject. To ask about the signed-in user, pass
|
|
215
|
+
`{ userId: req.user.sub }` to a permission check, or `user:<sub>` as the subject of a Zanzibar
|
|
216
|
+
check. The `sub` claim is the user's LumoAuth id. A check about another subject needs the
|
|
217
|
+
`authz:check` scope on the key, or the `authz.check` permission.
|
|
218
|
+
|
|
219
|
+
### Run behind a proxy
|
|
220
|
+
|
|
221
|
+
The middleware builds the callback URL from the request's protocol and `Host` header. Behind a
|
|
222
|
+
load balancer or a reverse proxy, call `app.set('trust proxy', true)`. Express then reads the
|
|
223
|
+
`X-Forwarded-*` headers, and the callback URL matches the one that you registered.
|
|
224
|
+
|
|
225
|
+
## Errors
|
|
226
|
+
|
|
227
|
+
The sign-in routes answer with JSON errors:
|
|
228
|
+
|
|
229
|
+
| Status | `error` | Cause |
|
|
230
|
+
|---|---|---|
|
|
231
|
+
| 500 | `session_middleware_missing` | `express-session` is not mounted before this middleware. |
|
|
232
|
+
| 400 | `invalid_request` | The callback has no `code` or `state`, or no sign-in is in progress. |
|
|
233
|
+
| 400 | `invalid_state` | The `state` does not match the saved value. |
|
|
234
|
+
| 400 | the provider's error | LumoAuth returned an error to the callback, such as `access_denied`. |
|
|
235
|
+
| 502, or LumoAuth's status | `token_exchange_failed` | The code exchange failed. |
|
|
236
|
+
|
|
237
|
+
`LumoAuthBackend` throws the SDK error classes, which this package re-exports:
|
|
238
|
+
`LumoAuthError`, `LumoAuthApiError`, `LumoAuthAuthenticationError`,
|
|
239
|
+
`LumoAuthPermissionDeniedError` (with `requiredScopes`), `LumoAuthNotFoundError`,
|
|
240
|
+
`LumoAuthRateLimitError` (with `retryAfter`), `LumoAuthValidationError`, `LumoAuthConfigError`,
|
|
241
|
+
`LumoAuthNetworkError`, `LumoAuthApprovalDeniedError`, `LumoAuthApprovalTimeoutError` and
|
|
242
|
+
`LumoAuthBudgetExceededError`. The [client README](../client/README.md#errors) describes them.
|
|
38
243
|
|
|
39
244
|
```ts
|
|
40
|
-
|
|
41
|
-
|
|
245
|
+
import { LumoAuthApiError } from '@lumoauth/express';
|
|
246
|
+
|
|
247
|
+
app.use((err, req, res, next) => {
|
|
248
|
+
if (err instanceof LumoAuthApiError) {
|
|
249
|
+
return res.status(err.statusCode ?? 502).json({ error: err.code });
|
|
250
|
+
}
|
|
251
|
+
next(err);
|
|
252
|
+
});
|
|
42
253
|
```
|
|
43
254
|
|
|
44
|
-
##
|
|
255
|
+
## API reference
|
|
256
|
+
|
|
257
|
+
| Export | Description |
|
|
258
|
+
|---|---|
|
|
259
|
+
| `lumoAuthMiddleware(options)` | Adds the sign-in routes and restores `req.user` |
|
|
260
|
+
| `requireAuth(options?)` | Guard that needs a signed-in user, with optional scope and custom checks |
|
|
261
|
+
| `LumoAuthBackend` | The server client from `@lumoauth/backend` |
|
|
262
|
+
| Error classes | The SDK error classes, listed in [Errors](#errors) |
|
|
263
|
+
| Types | `LumoAuthMiddlewareOptions`, `RequireAuthOptions`, `SessionUser`, `LumoAuthRequestHandler`, `LumoAuthBackendConfig` |
|
|
264
|
+
|
|
265
|
+
## Troubleshooting
|
|
266
|
+
|
|
267
|
+
| Symptom | Cause | Fix |
|
|
268
|
+
|---|---|---|
|
|
269
|
+
| `500 session_middleware_missing` | `express-session` is mounted after LumoAuth, or not at all. | Mount it first. |
|
|
270
|
+
| The callback answers `400 invalid_state` | The session was lost between sign-in and callback. This happens with a new memory store after a restart, a cookie that the browser did not send back, or several servers without a shared store. | Use a shared session store. Check the session cookie's `secure` and `sameSite` settings. |
|
|
271
|
+
| LumoAuth rejects the redirect URI | The callback URL that was built does not match a registered one. This is common behind a proxy. | Set `app.set('trust proxy', true)` and register the exact URL. |
|
|
272
|
+
| `403 insufficient_scope` from `requireAuth({ scopes })` | The token was not granted that scope. | Add the scope to the middleware's `scope` option, allow it on the client, and sign in again. |
|
|
273
|
+
| `LumoAuthBackend` calls fail with `401` while using an `lmk_…` key | Organization API keys only work on the admin API, client registration and the authorization checks. ABAC, agent and JIT routes reject them. | Use the key for permission and Zanzibar checks only. |
|
|
274
|
+
| A permission check in a handler answers for the wrong user | No subject was named, so the check answered for the credential's owner. | Pass `{ userId: req.user.sub }` as the third argument. |
|
|
275
|
+
| A check with `userId` gets `403` `INSUFFICIENT_PERMISSIONS` | The key lacks the `authz:check` scope. | Add the scope to the key. |
|
|
276
|
+
|
|
277
|
+
### Token refresh
|
|
278
|
+
|
|
279
|
+
Before a request reaches your handlers, the middleware checks the stored access token. When it
|
|
280
|
+
expires in less than 60 seconds and a refresh token is stored, the middleware gets a new one
|
|
281
|
+
with the `refresh_token` grant. It saves the new tokens in the session. If the server sends no
|
|
282
|
+
new refresh token, the old one is kept. Parallel requests on one session share a single refresh.
|
|
283
|
+
|
|
284
|
+
If the refresh fails, the middleware removes `user` and the tokens from the session. The request
|
|
285
|
+
then counts as signed out, so `requireAuth()` answers `401`. Set `autoRefresh: false` to turn
|
|
286
|
+
this off.
|
|
287
|
+
|
|
288
|
+
### Sign-out
|
|
289
|
+
|
|
290
|
+
`/auth/logout` clears the LumoAuth data from the session. Then it does two more things:
|
|
291
|
+
|
|
292
|
+
1. It revokes the refresh token (RFC 7009). This also revokes the access tokens issued with it.
|
|
293
|
+
Errors are ignored, so sign-out always completes.
|
|
294
|
+
2. It redirects to the LumoAuth end-session endpoint with `id_token_hint` and
|
|
295
|
+
`post_logout_redirect_uri`. LumoAuth ends its own session and sends the user back to
|
|
296
|
+
`postLogoutRedirect`.
|
|
297
|
+
|
|
298
|
+
The end-session step needs an absolute `postLogoutRedirect`, such as
|
|
299
|
+
`https://app.example.com/`. Register it as a post-logout redirect URI on the OAuth client. With a
|
|
300
|
+
relative path, the middleware still revokes the token, but it redirects straight to that path.
|
|
301
|
+
The LumoAuth session then stays open, so the next sign-in may skip the login screen.
|
|
302
|
+
Set `endSessionOnLogout: false` to only clear the local session.
|
|
303
|
+
|
|
304
|
+
## Limitations
|
|
305
|
+
|
|
306
|
+
- There is no session endpoint for `cookieStorageAdapter` from `@lumoauth/client`. If a browser
|
|
307
|
+
app needs the token, add a same-origin route that returns `{ accessToken, idToken, expiresAt }`.
|
|
308
|
+
|
|
309
|
+
## Versioning and compatibility
|
|
310
|
+
|
|
311
|
+
This package is version 1.0.0. It needs LumoAuth server API 1.0.0 or newer, Express 4.18 or
|
|
312
|
+
newer, and `express-session` 1.17 or newer.
|
|
313
|
+
|
|
314
|
+
## Related packages
|
|
315
|
+
|
|
316
|
+
| Package | Relationship |
|
|
317
|
+
|---|---|
|
|
318
|
+
| [`@lumoauth/backend`](../backend/README.md) | The server client that this package re-exports |
|
|
319
|
+
| [`@lumoauth/client`](../client/README.md) | Checks as a user, from a browser or a server |
|
|
320
|
+
| [`@lumoauth/react`](../react/README.md) | Browser components and hooks |
|
|
321
|
+
| [`@lumoauth/nextjs`](../nextjs/README.md) | The same job for Next.js, including token refresh and a session endpoint |
|
|
322
|
+
| [Workspace README](../../README.md) | How the packages fit together |
|
|
45
323
|
|
|
46
|
-
https://docs.lumoauth.dev
|
|
324
|
+
More: [Node.js and Express quickstart](https://docs.lumoauth.dev/quickstarts/node/) and the
|
|
325
|
+
[SDK overview](https://docs.lumoauth.dev/developer/sdks/).
|
|
47
326
|
|
|
48
|
-
##
|
|
327
|
+
## Licence
|
|
49
328
|
|
|
50
|
-
MIT
|
|
329
|
+
[MIT](./LICENSE)
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { LumoAuthApiError, LumoAuthApprovalDeniedError, LumoAuthApprovalTimeoutError, LumoAuthAuthError, LumoAuthAuthenticationError, LumoAuthBackend, LumoAuthBackendConfig, LumoAuthBudgetExceededError, LumoAuthConfigError, LumoAuthError, LumoAuthNetworkError, LumoAuthNotFoundError, LumoAuthPermissionDeniedError, LumoAuthRateLimitError, LumoAuthValidationError } from '@lumoauth/backend';
|
|
1
|
+
export { LumoAuthApiError, LumoAuthApprovalDeniedError, LumoAuthApprovalNotDeliveredError, LumoAuthApprovalTimeoutError, LumoAuthAuthError, LumoAuthAuthenticationError, LumoAuthBackend, LumoAuthBackendConfig, LumoAuthBudgetExceededError, LumoAuthConfigError, LumoAuthError, LumoAuthNetworkError, LumoAuthNotFoundError, LumoAuthPermissionDeniedError, LumoAuthRateLimitError, LumoAuthValidationError } from '@lumoauth/backend';
|
|
2
2
|
|
|
3
3
|
type Req = {
|
|
4
4
|
url: string;
|
|
@@ -52,8 +52,26 @@ interface LumoAuthMiddlewareOptions {
|
|
|
52
52
|
postLoginRedirect?: string;
|
|
53
53
|
/**
|
|
54
54
|
* Where to redirect the user after sign-out. Default: `/`.
|
|
55
|
+
*
|
|
56
|
+
* Use an absolute URL (for example `https://app.example.com/`) that is
|
|
57
|
+
* registered as a post-logout redirect URI on the OAuth client. Then
|
|
58
|
+
* sign-out also ends the LumoAuth session (see `endSessionOnLogout`). A
|
|
59
|
+
* relative path only clears the local session.
|
|
55
60
|
*/
|
|
56
61
|
postLogoutRedirect?: string;
|
|
62
|
+
/**
|
|
63
|
+
* Refresh the session's access token when it expires in less than 60
|
|
64
|
+
* seconds and a refresh token is stored. When the refresh fails, the
|
|
65
|
+
* request is treated as signed out. Default: `true`.
|
|
66
|
+
*/
|
|
67
|
+
autoRefresh?: boolean;
|
|
68
|
+
/**
|
|
69
|
+
* On sign-out, revoke the refresh token (RFC 7009) and redirect through
|
|
70
|
+
* the OIDC end-session endpoint, so the LumoAuth session ends too. The
|
|
71
|
+
* end-session step needs an absolute `postLogoutRedirect`. Set `false` to
|
|
72
|
+
* only clear the local session. Default: `true`.
|
|
73
|
+
*/
|
|
74
|
+
endSessionOnLogout?: boolean;
|
|
57
75
|
/**
|
|
58
76
|
* OAuth scopes to request. Default: `'openid profile email'`.
|
|
59
77
|
*/
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { LumoAuthApiError, LumoAuthApprovalDeniedError, LumoAuthApprovalTimeoutError, LumoAuthAuthError, LumoAuthAuthenticationError, LumoAuthBackend, LumoAuthBackendConfig, LumoAuthBudgetExceededError, LumoAuthConfigError, LumoAuthError, LumoAuthNetworkError, LumoAuthNotFoundError, LumoAuthPermissionDeniedError, LumoAuthRateLimitError, LumoAuthValidationError } from '@lumoauth/backend';
|
|
1
|
+
export { LumoAuthApiError, LumoAuthApprovalDeniedError, LumoAuthApprovalNotDeliveredError, LumoAuthApprovalTimeoutError, LumoAuthAuthError, LumoAuthAuthenticationError, LumoAuthBackend, LumoAuthBackendConfig, LumoAuthBudgetExceededError, LumoAuthConfigError, LumoAuthError, LumoAuthNetworkError, LumoAuthNotFoundError, LumoAuthPermissionDeniedError, LumoAuthRateLimitError, LumoAuthValidationError } from '@lumoauth/backend';
|
|
2
2
|
|
|
3
3
|
type Req = {
|
|
4
4
|
url: string;
|
|
@@ -52,8 +52,26 @@ interface LumoAuthMiddlewareOptions {
|
|
|
52
52
|
postLoginRedirect?: string;
|
|
53
53
|
/**
|
|
54
54
|
* Where to redirect the user after sign-out. Default: `/`.
|
|
55
|
+
*
|
|
56
|
+
* Use an absolute URL (for example `https://app.example.com/`) that is
|
|
57
|
+
* registered as a post-logout redirect URI on the OAuth client. Then
|
|
58
|
+
* sign-out also ends the LumoAuth session (see `endSessionOnLogout`). A
|
|
59
|
+
* relative path only clears the local session.
|
|
55
60
|
*/
|
|
56
61
|
postLogoutRedirect?: string;
|
|
62
|
+
/**
|
|
63
|
+
* Refresh the session's access token when it expires in less than 60
|
|
64
|
+
* seconds and a refresh token is stored. When the refresh fails, the
|
|
65
|
+
* request is treated as signed out. Default: `true`.
|
|
66
|
+
*/
|
|
67
|
+
autoRefresh?: boolean;
|
|
68
|
+
/**
|
|
69
|
+
* On sign-out, revoke the refresh token (RFC 7009) and redirect through
|
|
70
|
+
* the OIDC end-session endpoint, so the LumoAuth session ends too. The
|
|
71
|
+
* end-session step needs an absolute `postLogoutRedirect`. Set `false` to
|
|
72
|
+
* only clear the local session. Default: `true`.
|
|
73
|
+
*/
|
|
74
|
+
endSessionOnLogout?: boolean;
|
|
57
75
|
/**
|
|
58
76
|
* OAuth scopes to request. Default: `'openid profile email'`.
|
|
59
77
|
*/
|
package/dist/index.js
CHANGED
|
@@ -22,6 +22,7 @@ var index_exports = {};
|
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
LumoAuthApiError: () => import_backend.LumoAuthApiError,
|
|
24
24
|
LumoAuthApprovalDeniedError: () => import_backend.LumoAuthApprovalDeniedError,
|
|
25
|
+
LumoAuthApprovalNotDeliveredError: () => import_backend.LumoAuthApprovalNotDeliveredError,
|
|
25
26
|
LumoAuthApprovalTimeoutError: () => import_backend.LumoAuthApprovalTimeoutError,
|
|
26
27
|
LumoAuthAuthError: () => import_backend.LumoAuthAuthError,
|
|
27
28
|
LumoAuthAuthenticationError: () => import_backend.LumoAuthAuthenticationError,
|
|
@@ -45,6 +46,17 @@ function lumoAuthMiddleware(opts) {
|
|
|
45
46
|
const postLoginRedirect = opts.postLoginRedirect ?? "/";
|
|
46
47
|
const postLogoutRedirect = opts.postLogoutRedirect ?? "/";
|
|
47
48
|
const scope = opts.scope ?? "openid profile email";
|
|
49
|
+
const autoRefresh = opts.autoRefresh ?? true;
|
|
50
|
+
const endSessionOnLogout = opts.endSessionOnLogout ?? true;
|
|
51
|
+
const inflight = /* @__PURE__ */ new Map();
|
|
52
|
+
const refresh = (refreshToken) => {
|
|
53
|
+
let pending = inflight.get(refreshToken);
|
|
54
|
+
if (!pending) {
|
|
55
|
+
pending = auth.refreshToken(refreshToken, { clientSecret: opts.clientSecret }).finally(() => inflight.delete(refreshToken));
|
|
56
|
+
inflight.set(refreshToken, pending);
|
|
57
|
+
}
|
|
58
|
+
return pending;
|
|
59
|
+
};
|
|
48
60
|
const auth = new import_shared.AuthModule({
|
|
49
61
|
baseUrl: opts.baseUrl,
|
|
50
62
|
orgId: opts.organization,
|
|
@@ -60,10 +72,14 @@ function lumoAuthMiddleware(opts) {
|
|
|
60
72
|
return;
|
|
61
73
|
}
|
|
62
74
|
const sessionState = req.session.__lumoAuth ?? {};
|
|
75
|
+
const path = req.path ?? req.url.split("?")[0];
|
|
76
|
+
const isAuthRoute = path === `${prefix}/login` || path === `${prefix}/callback` || path === `${prefix}/logout`;
|
|
77
|
+
if (autoRefresh && !isAuthRoute) {
|
|
78
|
+
await refreshIfNeeded(req, sessionState, refresh);
|
|
79
|
+
}
|
|
63
80
|
if (sessionState.user) {
|
|
64
81
|
req.user = sessionState.user;
|
|
65
82
|
}
|
|
66
|
-
const path = req.path ?? req.url.split("?")[0];
|
|
67
83
|
if (req.method === "GET" && path === `${prefix}/login`) {
|
|
68
84
|
await handleLogin(req, res, auth, prefix, scope, sessionState, postLoginRedirect);
|
|
69
85
|
return;
|
|
@@ -73,7 +89,10 @@ function lumoAuthMiddleware(opts) {
|
|
|
73
89
|
return;
|
|
74
90
|
}
|
|
75
91
|
if ((req.method === "GET" || req.method === "POST") && path === `${prefix}/logout`) {
|
|
76
|
-
await handleLogout(req, res, sessionState, postLogoutRedirect
|
|
92
|
+
await handleLogout(req, res, auth, sessionState, postLogoutRedirect, {
|
|
93
|
+
endSession: endSessionOnLogout,
|
|
94
|
+
clientSecret: opts.clientSecret
|
|
95
|
+
});
|
|
77
96
|
return;
|
|
78
97
|
}
|
|
79
98
|
next();
|
|
@@ -146,12 +165,63 @@ async function handleCallback(req, res, auth, sessionState, clientSecret) {
|
|
|
146
165
|
res.status(status).json({ error: "token_exchange_failed", error_description: message });
|
|
147
166
|
}
|
|
148
167
|
}
|
|
149
|
-
async function handleLogout(req, res, sessionState, postLogoutRedirect) {
|
|
168
|
+
async function handleLogout(req, res, auth, sessionState, postLogoutRedirect, options) {
|
|
169
|
+
const tokens = sessionState.tokens;
|
|
150
170
|
delete sessionState.user;
|
|
151
171
|
delete sessionState.tokens;
|
|
152
172
|
delete sessionState.flow;
|
|
153
173
|
saveSession(req, sessionState);
|
|
154
|
-
|
|
174
|
+
req.user = void 0;
|
|
175
|
+
if (!options.endSession) {
|
|
176
|
+
res.redirect(postLogoutRedirect);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const revocable = tokens?.refresh_token ?? tokens?.access_token;
|
|
180
|
+
if (revocable) {
|
|
181
|
+
try {
|
|
182
|
+
await auth.revokeToken(revocable, void 0, {
|
|
183
|
+
clientSecret: options.clientSecret,
|
|
184
|
+
tokenTypeHint: tokens?.refresh_token ? "refresh_token" : "access_token"
|
|
185
|
+
});
|
|
186
|
+
} catch {
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (!isAbsoluteHttpUrl(postLogoutRedirect)) {
|
|
190
|
+
res.redirect(postLogoutRedirect);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
res.redirect(
|
|
194
|
+
auth.buildEndSessionUrl({
|
|
195
|
+
idTokenHint: tokens?.id_token,
|
|
196
|
+
postLogoutRedirectUri: postLogoutRedirect
|
|
197
|
+
})
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
var REFRESH_LEEWAY_SECONDS = 60;
|
|
201
|
+
async function refreshIfNeeded(req, sessionState, refresh) {
|
|
202
|
+
const tokens = sessionState.tokens;
|
|
203
|
+
if (!tokens?.refresh_token) return;
|
|
204
|
+
if (tokens.expires_at - nowSeconds() >= REFRESH_LEEWAY_SECONDS) return;
|
|
205
|
+
try {
|
|
206
|
+
const fresh = await refresh(tokens.refresh_token);
|
|
207
|
+
sessionState.tokens = {
|
|
208
|
+
access_token: fresh.access_token,
|
|
209
|
+
// Keep the old refresh token when the server does not rotate it.
|
|
210
|
+
refresh_token: fresh.refresh_token ?? tokens.refresh_token,
|
|
211
|
+
id_token: fresh.id_token ?? tokens.id_token,
|
|
212
|
+
token_type: fresh.token_type ?? tokens.token_type ?? "Bearer",
|
|
213
|
+
expires_at: nowSeconds() + (fresh.expires_in ?? 3600),
|
|
214
|
+
scope: fresh.scope ?? tokens.scope
|
|
215
|
+
};
|
|
216
|
+
} catch {
|
|
217
|
+
delete sessionState.user;
|
|
218
|
+
delete sessionState.tokens;
|
|
219
|
+
req.user = void 0;
|
|
220
|
+
}
|
|
221
|
+
saveSession(req, sessionState);
|
|
222
|
+
}
|
|
223
|
+
function isAbsoluteHttpUrl(value) {
|
|
224
|
+
return /^https?:\/\//i.test(value);
|
|
155
225
|
}
|
|
156
226
|
function requireAuth(options = {}) {
|
|
157
227
|
return async function requireAuthHandler(req, res, next) {
|
|
@@ -217,6 +287,7 @@ function regenerateSession(req) {
|
|
|
217
287
|
0 && (module.exports = {
|
|
218
288
|
LumoAuthApiError,
|
|
219
289
|
LumoAuthApprovalDeniedError,
|
|
290
|
+
LumoAuthApprovalNotDeliveredError,
|
|
220
291
|
LumoAuthApprovalTimeoutError,
|
|
221
292
|
LumoAuthAuthError,
|
|
222
293
|
LumoAuthAuthenticationError,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Express middleware for LumoAuth.\n *\n * Wires three routes onto the host app — `/auth/login`, `/auth/callback`,\n * `/auth/logout` (the prefix is configurable) — and exposes:\n *\n * - `lumoAuthMiddleware(opts)` — must be `app.use()`'d for the routes\n * to register; also populates `req.user`\n * on every request from the session.\n * - `requireAuth([opts])` — gate handler that 401s when there's\n * no `req.user`, with optional scope /\n * permission checks.\n *\n * Sessions are stored via Express's session middleware (the host app is\n * expected to mount `express-session` before this middleware). The PKCE\n * verifier and `state` for an in-flight authorization round-trip live on\n * the session under `__lumoAuth.flow` so they survive the redirect to the\n * IDP and back without exposing them to the URL or local storage.\n */\nimport {\n AuthModule,\n type TokenResponse,\n type UserInfo,\n LumoAuthError,\n LumoAuthApiError,\n} from '@lumoauth/shared';\n\n// Re-exported so an Express app needs only this one install: the server\n// client for imperative checks inside handlers, and the shared error\n// taxonomy for instanceof checks in error middleware.\nexport {\n LumoAuthBackend,\n type LumoAuthBackendConfig,\n LumoAuthError,\n LumoAuthApiError,\n LumoAuthAuthenticationError,\n LumoAuthAuthError,\n LumoAuthPermissionDeniedError,\n LumoAuthNotFoundError,\n LumoAuthRateLimitError,\n LumoAuthValidationError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n LumoAuthApprovalDeniedError,\n LumoAuthApprovalTimeoutError,\n LumoAuthBudgetExceededError,\n} from '@lumoauth/backend';\n\n// Express types are loose to avoid a direct dependency on @types/express —\n// callers bring their own types. We only need the subset we use.\ntype Req = {\n url: string;\n path?: string;\n method?: string;\n query: Record<string, string | string[] | undefined>;\n session?: Record<string, unknown> & {\n __lumoAuth?: LumoAuthSessionState;\n };\n user?: SessionUser | undefined;\n // express-style helpers we touch\n [key: string]: unknown;\n};\n\ntype Res = {\n redirect(url: string): unknown;\n status(code: number): Res;\n json(payload: unknown): unknown;\n send(payload: unknown): unknown;\n setHeader(name: string, value: string): unknown;\n};\n\ntype Next = (err?: unknown) => void;\n\n/**\n * Structural match for express's `RequestHandler`. The exported middleware\n * factories are annotated with this so `app.use(lumoAuthMiddleware(...))` and\n * `app.get(path, requireAuth(), handler)` typecheck for TypeScript consumers\n * without this package taking a hard dependency on `@types/express`. Express's\n * own `Request`/`Response` are assignable to `any`, so the handler is accepted\n * by `app.use()`/`app.get()`/`app.METHOD()` overloads.\n */\nexport type LumoAuthRequestHandler = (\n req: any, // eslint-disable-line @typescript-eslint/no-explicit-any\n res: any, // eslint-disable-line @typescript-eslint/no-explicit-any\n next: (err?: unknown) => void,\n) => void | Promise<void>;\n\ndeclare global {\n // Augment express's Request so `req.user` is typed for consumers using\n // lumoAuthMiddleware(). Merges with @types/express when present; harmless\n // (creates the namespace) otherwise.\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n user?: SessionUser;\n }\n }\n}\n\nexport interface LumoAuthMiddlewareOptions {\n /** e.g. \"https://app.lumoauth.dev\" */\n baseUrl: string;\n /** The tenant slug that owns the OAuth client. */\n organization: string;\n /** OAuth client id registered for this app. */\n clientId: string;\n /**\n * Confidential clients require a secret on the token exchange. Public\n * (browser-facing) clients should omit this and rely on PKCE.\n */\n clientSecret?: string;\n /**\n * Path under which the three auth routes mount. Default: `/auth`.\n * Resulting routes: `/auth/login`, `/auth/callback`, `/auth/logout`.\n */\n prefix?: string;\n /**\n * Where to redirect the user after sign-in. Default: `/`.\n */\n postLoginRedirect?: string;\n /**\n * Where to redirect the user after sign-out. Default: `/`.\n */\n postLogoutRedirect?: string;\n /**\n * OAuth scopes to request. Default: `'openid profile email'`.\n */\n scope?: string;\n /**\n * Optional fetch override (for tests, instrumentation, custom proxies).\n */\n fetch?: typeof globalThis.fetch;\n}\n\nexport interface SessionUser {\n sub: string;\n email?: string;\n email_verified?: boolean;\n name?: string;\n picture?: string;\n [key: string]: unknown;\n}\n\ninterface LumoAuthSessionState {\n flow?: {\n codeVerifier: string;\n state: string;\n redirectUri: string;\n returnTo: string;\n };\n tokens?: {\n access_token: string;\n refresh_token?: string;\n id_token?: string;\n token_type: string;\n expires_at: number; // epoch seconds\n scope?: string;\n };\n user?: SessionUser;\n}\n\nexport interface RequireAuthOptions {\n /** Optional list of scopes that must all be present in the session token. */\n scopes?: string[];\n /**\n * Hook for programmatic checks (e.g. role / permission lookup against the\n * AuthorizationModule). Return false to deny.\n */\n authorize?: (user: SessionUser, req: Req) => boolean | Promise<boolean>;\n /**\n * Status code to return when unauthorized. Default 401 for missing user,\n * 403 for an `authorize` hook that returns false.\n */\n unauthorizedStatus?: number;\n}\n\n/**\n * Mount the LumoAuth Express middleware. Call this once on the app —\n * subsequent requests will:\n *\n * 1. Hit the three auth routes (login/callback/logout) under the prefix.\n * 2. Populate `req.user` from the session for every other request.\n */\nexport function lumoAuthMiddleware(opts: LumoAuthMiddlewareOptions): LumoAuthRequestHandler {\n const prefix = (opts.prefix ?? '/auth').replace(/\\/+$/, '');\n const postLoginRedirect = opts.postLoginRedirect ?? '/';\n const postLogoutRedirect = opts.postLogoutRedirect ?? '/';\n const scope = opts.scope ?? 'openid profile email';\n\n const auth = new AuthModule({\n baseUrl: opts.baseUrl,\n orgId: opts.organization,\n clientId: opts.clientId,\n fetch: opts.fetch,\n });\n\n // The host app is expected to mount this middleware once on app.use(),\n // so it runs on EVERY request. We hand-route the three auth paths and\n // pass everything else through after attaching `req.user`.\n return async function lumoAuth(req: Req, res: Res, next: Next): Promise<void> {\n if (!req.session) {\n // Hard fail with a clear message — silently letting requests through\n // when the host forgot to mount express-session would mask bugs at\n // the moment users try to sign in.\n res.status(500).json({\n error: 'session_middleware_missing',\n error_description:\n 'lumoAuthMiddleware requires express-session (or compatible) to be mounted before it.',\n });\n return;\n }\n\n // Restore `req.user` from session so downstream handlers always see it.\n const sessionState: LumoAuthSessionState = (req.session.__lumoAuth ?? {}) as LumoAuthSessionState;\n if (sessionState.user) {\n req.user = sessionState.user;\n }\n\n const path = req.path ?? req.url.split('?')[0];\n\n if (req.method === 'GET' && path === `${prefix}/login`) {\n await handleLogin(req, res, auth, prefix, scope, sessionState, postLoginRedirect);\n return;\n }\n if (req.method === 'GET' && path === `${prefix}/callback`) {\n await handleCallback(req, res, auth, sessionState, opts.clientSecret);\n return;\n }\n if (\n (req.method === 'GET' || req.method === 'POST') &&\n path === `${prefix}/logout`\n ) {\n await handleLogout(req, res, sessionState, postLogoutRedirect);\n return;\n }\n\n next();\n };\n}\n\nasync function handleLogin(\n req: Req,\n res: Res,\n auth: AuthModule,\n prefix: string,\n scope: string,\n sessionState: LumoAuthSessionState,\n defaultReturnTo: string,\n): Promise<void> {\n const redirectUri = absoluteUrl(req, `${prefix}/callback`);\n const returnTo = sanitizeReturnTo(req.query.return_to, defaultReturnTo);\n\n const flow = await auth.buildAuthorizationUrl({\n redirectUri,\n scope,\n });\n\n // Persist what we'll need on callback. SameSite session cookie is the\n // canonical store; never reflect any of this in the URL.\n sessionState.flow = {\n codeVerifier: flow.codeVerifier,\n state: flow.state,\n redirectUri,\n returnTo,\n };\n saveSession(req, sessionState);\n\n res.redirect(flow.url);\n}\n\nasync function handleCallback(\n req: Req,\n res: Res,\n auth: AuthModule,\n sessionState: LumoAuthSessionState,\n clientSecret: string | undefined,\n): Promise<void> {\n const code = stringQuery(req.query.code);\n const state = stringQuery(req.query.state);\n const oauthError = stringQuery(req.query.error);\n\n if (oauthError) {\n res.status(400).json({\n error: oauthError,\n error_description: stringQuery(req.query.error_description) ?? '',\n });\n return;\n }\n if (!code || !state) {\n res.status(400).json({ error: 'invalid_request', error_description: 'Missing code or state' });\n return;\n }\n const flow = sessionState.flow;\n if (!flow) {\n res.status(400).json({ error: 'invalid_request', error_description: 'No login in progress' });\n return;\n }\n if (state !== flow.state) {\n res.status(400).json({ error: 'invalid_state', error_description: 'CSRF state mismatch' });\n return;\n }\n\n try {\n const tokens: TokenResponse = await auth.exchangeCodeForTokens({\n code,\n redirectUri: flow.redirectUri,\n codeVerifier: flow.codeVerifier,\n clientSecret,\n });\n\n const user = await fetchUserInfo(auth, tokens.access_token);\n\n sessionState.tokens = {\n access_token: tokens.access_token,\n refresh_token: tokens.refresh_token,\n id_token: tokens.id_token,\n token_type: tokens.token_type ?? 'Bearer',\n expires_at: nowSeconds() + (tokens.expires_in ?? 3600),\n scope: tokens.scope,\n };\n sessionState.user = user;\n delete sessionState.flow;\n\n // Migrate the session id on auth — defends against fixation attacks.\n regenerateSession(req);\n saveSession(req, sessionState);\n\n res.redirect(flow.returnTo);\n } catch (err) {\n const message = err instanceof LumoAuthError ? err.message : 'Token exchange failed';\n const status =\n err instanceof LumoAuthApiError ? err.statusCode ?? 502 : 502;\n res.status(status).json({ error: 'token_exchange_failed', error_description: message });\n }\n}\n\nasync function handleLogout(\n req: Req,\n res: Res,\n sessionState: LumoAuthSessionState,\n postLogoutRedirect: string,\n): Promise<void> {\n // Wipe LumoAuth-specific state. We DON'T destroy the whole session\n // because the host app may store unrelated data on it. Hosts that want\n // a hard logout should call `req.session.destroy()` themselves.\n delete sessionState.user;\n delete sessionState.tokens;\n delete sessionState.flow;\n saveSession(req, sessionState);\n res.redirect(postLogoutRedirect);\n}\n\n/**\n * Gate handler that requires a logged-in `req.user`. Combine with optional\n * scope / authorize hooks for finer-grained access control.\n */\nexport function requireAuth(options: RequireAuthOptions = {}): LumoAuthRequestHandler {\n return async function requireAuthHandler(req: Req, res: Res, next: Next): Promise<void> {\n const user = req.user;\n if (!user) {\n res.status(options.unauthorizedStatus ?? 401).json({ error: 'unauthenticated' });\n return;\n }\n\n if (options.scopes?.length) {\n const session = (req.session?.__lumoAuth ?? {}) as LumoAuthSessionState;\n const granted = (session.tokens?.scope ?? '').split(/\\s+/).filter(Boolean);\n const missing = options.scopes.filter((s) => !granted.includes(s));\n if (missing.length) {\n res\n .status(options.unauthorizedStatus ?? 403)\n .json({ error: 'insufficient_scope', error_description: `Missing: ${missing.join(', ')}` });\n return;\n }\n }\n\n if (options.authorize) {\n const ok = await options.authorize(user, req);\n if (!ok) {\n res.status(options.unauthorizedStatus ?? 403).json({ error: 'forbidden' });\n return;\n }\n }\n\n next();\n };\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────\n\nasync function fetchUserInfo(auth: AuthModule, accessToken: string): Promise<SessionUser> {\n // We hit the OIDC `/userinfo` endpoint. AuthModule exposes `getUserInfo`\n // which is the canonical wrapper.\n const info: UserInfo = await auth.getUserInfo(accessToken);\n return { ...info } as SessionUser;\n}\n\nfunction absoluteUrl(req: Req, path: string): string {\n // Honour standard reverse-proxy headers when present so the redirect URI\n // matches what the registered OAuth client allows. The host app is\n // expected to set `app.set('trust proxy', true)` if behind one.\n const reqWithProto = req as Req & { protocol?: string; get?: (h: string) => string | undefined };\n const proto = reqWithProto.protocol ?? 'https';\n const host = reqWithProto.get?.('host') ?? '';\n return `${proto}://${host}${path}`;\n}\n\nfunction sanitizeReturnTo(raw: unknown, fallback: string): string {\n // Open-redirect defence: only allow same-origin paths beginning with `/`\n // and not starting with `//` (protocol-relative).\n if (typeof raw !== 'string') return fallback;\n if (!raw.startsWith('/') || raw.startsWith('//')) return fallback;\n return raw;\n}\n\nfunction stringQuery(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (Array.isArray(value) && typeof value[0] === 'string') return value[0];\n return undefined;\n}\n\nfunction nowSeconds(): number {\n return Math.floor(Date.now() / 1000);\n}\n\nfunction saveSession(req: Req, state: LumoAuthSessionState): void {\n if (!req.session) return;\n req.session.__lumoAuth = state;\n // express-session writes on response end; we don't force a flush here.\n}\n\nfunction regenerateSession(req: Req): void {\n // express-session exposes `regenerate(cb)` — call it if available so we\n // get a fresh session id post-auth (mitigates session fixation).\n const sess = req.session as unknown as { regenerate?: (cb: (err?: unknown) => void) => void };\n if (typeof sess?.regenerate === 'function') {\n // Synchronous-style usage; we don't await because express-session's\n // regenerate is callback-based and most apps don't need the new id\n // until the next response. The session.save() that express-session\n // calls on res.end() will pick up the new state.\n sess.regenerate(() => {});\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmBA,oBAMO;AAKP,qBAgBO;AAyIA,SAAS,mBAAmB,MAAyD;AAC1F,QAAM,UAAU,KAAK,UAAU,SAAS,QAAQ,QAAQ,EAAE;AAC1D,QAAM,oBAAoB,KAAK,qBAAqB;AACpD,QAAM,qBAAqB,KAAK,sBAAsB;AACtD,QAAM,QAAQ,KAAK,SAAS;AAE5B,QAAM,OAAO,IAAI,yBAAW;AAAA,IAC1B,SAAS,KAAK;AAAA,IACd,OAAO,KAAK;AAAA,IACZ,UAAU,KAAK;AAAA,IACf,OAAO,KAAK;AAAA,EACd,CAAC;AAKD,SAAO,eAAe,SAAS,KAAU,KAAU,MAA2B;AAC5E,QAAI,CAAC,IAAI,SAAS;AAIhB,UAAI,OAAO,GAAG,EAAE,KAAK;AAAA,QACnB,OAAO;AAAA,QACP,mBACE;AAAA,MACJ,CAAC;AACD;AAAA,IACF;AAGA,UAAM,eAAsC,IAAI,QAAQ,cAAc,CAAC;AACvE,QAAI,aAAa,MAAM;AACrB,UAAI,OAAO,aAAa;AAAA,IAC1B;AAEA,UAAM,OAAO,IAAI,QAAQ,IAAI,IAAI,MAAM,GAAG,E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WAAW,IAAI,EAAG,QAAO;AACzD,SAAO;AACT;AAEA,SAAS,YAAY,OAAoC;AACvD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,MAAM,QAAQ,KAAK,KAAK,OAAO,MAAM,CAAC,MAAM,SAAU,QAAO,MAAM,CAAC;AACxE,SAAO;AACT;AAEA,SAAS,aAAqB;AAC5B,SAAO,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AACrC;AAEA,SAAS,YAAY,KAAU,OAAmC;AAChE,MAAI,CAAC,IAAI,QAAS;AAClB,MAAI,QAAQ,aAAa;AAE3B;AAEA,SAAS,kBAAkB,KAAgB;AAGzC,QAAM,OAAO,IAAI;AACjB,MAAI,OAAO,MAAM,eAAe,YAAY;AAK1C,SAAK,WAAW,MAAM;AAAA,IAAC,CAAC;AAAA,EAC1B;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Express middleware for LumoAuth.\n *\n * Wires three routes onto the host app — `/auth/login`, `/auth/callback`,\n * `/auth/logout` (the prefix is configurable) — and exposes:\n *\n * - `lumoAuthMiddleware(opts)` — must be `app.use()`'d for the routes\n * to register; also populates `req.user`\n * on every request from the session.\n * - `requireAuth([opts])` — gate handler that 401s when there's\n * no `req.user`, with optional scope /\n * permission checks.\n *\n * Sessions are stored via Express's session middleware (the host app is\n * expected to mount `express-session` before this middleware). The PKCE\n * verifier and `state` for an in-flight authorization round-trip live on\n * the session under `__lumoAuth.flow` so they survive the redirect to the\n * IDP and back without exposing them to the URL or local storage.\n */\nimport {\n AuthModule,\n type TokenResponse,\n type UserInfo,\n LumoAuthError,\n LumoAuthApiError,\n} from '@lumoauth/shared';\n\n// Re-exported so an Express app needs only this one install: the server\n// client for imperative checks inside handlers, and the shared error\n// taxonomy for instanceof checks in error middleware.\nexport {\n LumoAuthBackend,\n type LumoAuthBackendConfig,\n LumoAuthError,\n LumoAuthApiError,\n LumoAuthAuthenticationError,\n LumoAuthAuthError,\n LumoAuthPermissionDeniedError,\n LumoAuthNotFoundError,\n LumoAuthRateLimitError,\n LumoAuthValidationError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n LumoAuthApprovalDeniedError,\n LumoAuthApprovalTimeoutError,\n LumoAuthApprovalNotDeliveredError,\n LumoAuthBudgetExceededError,\n} from '@lumoauth/backend';\n\n// Express types are loose to avoid a direct dependency on @types/express —\n// callers bring their own types. We only need the subset we use.\ntype Req = {\n url: string;\n path?: string;\n method?: string;\n query: Record<string, string | string[] | undefined>;\n session?: Record<string, unknown> & {\n __lumoAuth?: LumoAuthSessionState;\n };\n user?: SessionUser | undefined;\n // express-style helpers we touch\n [key: string]: unknown;\n};\n\ntype Res = {\n redirect(url: string): unknown;\n status(code: number): Res;\n json(payload: unknown): unknown;\n send(payload: unknown): unknown;\n setHeader(name: string, value: string): unknown;\n};\n\ntype Next = (err?: unknown) => void;\n\n/**\n * Structural match for express's `RequestHandler`. The exported middleware\n * factories are annotated with this so `app.use(lumoAuthMiddleware(...))` and\n * `app.get(path, requireAuth(), handler)` typecheck for TypeScript consumers\n * without this package taking a hard dependency on `@types/express`. Express's\n * own `Request`/`Response` are assignable to `any`, so the handler is accepted\n * by `app.use()`/`app.get()`/`app.METHOD()` overloads.\n */\nexport type LumoAuthRequestHandler = (\n req: any, // eslint-disable-line @typescript-eslint/no-explicit-any\n res: any, // eslint-disable-line @typescript-eslint/no-explicit-any\n next: (err?: unknown) => void,\n) => void | Promise<void>;\n\ndeclare global {\n // Augment express's Request so `req.user` is typed for consumers using\n // lumoAuthMiddleware(). Merges with @types/express when present; harmless\n // (creates the namespace) otherwise.\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n user?: SessionUser;\n }\n }\n}\n\nexport interface LumoAuthMiddlewareOptions {\n /** e.g. \"https://app.lumoauth.dev\" */\n baseUrl: string;\n /** The tenant slug that owns the OAuth client. */\n organization: string;\n /** OAuth client id registered for this app. */\n clientId: string;\n /**\n * Confidential clients require a secret on the token exchange. Public\n * (browser-facing) clients should omit this and rely on PKCE.\n */\n clientSecret?: string;\n /**\n * Path under which the three auth routes mount. Default: `/auth`.\n * Resulting routes: `/auth/login`, `/auth/callback`, `/auth/logout`.\n */\n prefix?: string;\n /**\n * Where to redirect the user after sign-in. Default: `/`.\n */\n postLoginRedirect?: string;\n /**\n * Where to redirect the user after sign-out. Default: `/`.\n *\n * Use an absolute URL (for example `https://app.example.com/`) that is\n * registered as a post-logout redirect URI on the OAuth client. Then\n * sign-out also ends the LumoAuth session (see `endSessionOnLogout`). A\n * relative path only clears the local session.\n */\n postLogoutRedirect?: string;\n /**\n * Refresh the session's access token when it expires in less than 60\n * seconds and a refresh token is stored. When the refresh fails, the\n * request is treated as signed out. Default: `true`.\n */\n autoRefresh?: boolean;\n /**\n * On sign-out, revoke the refresh token (RFC 7009) and redirect through\n * the OIDC end-session endpoint, so the LumoAuth session ends too. The\n * end-session step needs an absolute `postLogoutRedirect`. Set `false` to\n * only clear the local session. Default: `true`.\n */\n endSessionOnLogout?: boolean;\n /**\n * OAuth scopes to request. Default: `'openid profile email'`.\n */\n scope?: string;\n /**\n * Optional fetch override (for tests, instrumentation, custom proxies).\n */\n fetch?: typeof globalThis.fetch;\n}\n\nexport interface SessionUser {\n sub: string;\n email?: string;\n email_verified?: boolean;\n name?: string;\n picture?: string;\n [key: string]: unknown;\n}\n\ninterface LumoAuthSessionState {\n flow?: {\n codeVerifier: string;\n state: string;\n redirectUri: string;\n returnTo: string;\n };\n tokens?: {\n access_token: string;\n refresh_token?: string;\n id_token?: string;\n token_type: string;\n expires_at: number; // epoch seconds\n scope?: string;\n };\n user?: SessionUser;\n}\n\nexport interface RequireAuthOptions {\n /** Optional list of scopes that must all be present in the session token. */\n scopes?: string[];\n /**\n * Hook for programmatic checks (e.g. role / permission lookup against the\n * AuthorizationModule). Return false to deny.\n */\n authorize?: (user: SessionUser, req: Req) => boolean | Promise<boolean>;\n /**\n * Status code to return when unauthorized. Default 401 for missing user,\n * 403 for an `authorize` hook that returns false.\n */\n unauthorizedStatus?: number;\n}\n\n/**\n * Mount the LumoAuth Express middleware. Call this once on the app —\n * subsequent requests will:\n *\n * 1. Hit the three auth routes (login/callback/logout) under the prefix.\n * 2. Populate `req.user` from the session for every other request.\n */\nexport function lumoAuthMiddleware(opts: LumoAuthMiddlewareOptions): LumoAuthRequestHandler {\n const prefix = (opts.prefix ?? '/auth').replace(/\\/+$/, '');\n const postLoginRedirect = opts.postLoginRedirect ?? '/';\n const postLogoutRedirect = opts.postLogoutRedirect ?? '/';\n const scope = opts.scope ?? 'openid profile email';\n const autoRefresh = opts.autoRefresh ?? true;\n const endSessionOnLogout = opts.endSessionOnLogout ?? true;\n\n // One refresh per refresh token at a time. Parallel requests on the same\n // session share it, so a rotating refresh token is redeemed only once.\n const inflight = new Map<string, Promise<TokenResponse>>();\n const refresh = (refreshToken: string): Promise<TokenResponse> => {\n let pending = inflight.get(refreshToken);\n if (!pending) {\n pending = auth\n .refreshToken(refreshToken, { clientSecret: opts.clientSecret })\n .finally(() => inflight.delete(refreshToken));\n inflight.set(refreshToken, pending);\n }\n return pending;\n };\n\n const auth = new AuthModule({\n baseUrl: opts.baseUrl,\n orgId: opts.organization,\n clientId: opts.clientId,\n fetch: opts.fetch,\n });\n\n // The host app is expected to mount this middleware once on app.use(),\n // so it runs on EVERY request. We hand-route the three auth paths and\n // pass everything else through after attaching `req.user`.\n return async function lumoAuth(req: Req, res: Res, next: Next): Promise<void> {\n if (!req.session) {\n // Hard fail with a clear message — silently letting requests through\n // when the host forgot to mount express-session would mask bugs at\n // the moment users try to sign in.\n res.status(500).json({\n error: 'session_middleware_missing',\n error_description:\n 'lumoAuthMiddleware requires express-session (or compatible) to be mounted before it.',\n });\n return;\n }\n\n const sessionState: LumoAuthSessionState = (req.session.__lumoAuth ?? {}) as LumoAuthSessionState;\n const path = req.path ?? req.url.split('?')[0];\n const isAuthRoute =\n path === `${prefix}/login` || path === `${prefix}/callback` || path === `${prefix}/logout`;\n\n // Refresh a token that is about to expire before anything reads it.\n if (autoRefresh && !isAuthRoute) {\n await refreshIfNeeded(req, sessionState, refresh);\n }\n\n // Restore `req.user` from session so downstream handlers always see it.\n if (sessionState.user) {\n req.user = sessionState.user;\n }\n\n if (req.method === 'GET' && path === `${prefix}/login`) {\n await handleLogin(req, res, auth, prefix, scope, sessionState, postLoginRedirect);\n return;\n }\n if (req.method === 'GET' && path === `${prefix}/callback`) {\n await handleCallback(req, res, auth, sessionState, opts.clientSecret);\n return;\n }\n if (\n (req.method === 'GET' || req.method === 'POST') &&\n path === `${prefix}/logout`\n ) {\n await handleLogout(req, res, auth, sessionState, postLogoutRedirect, {\n endSession: endSessionOnLogout,\n clientSecret: opts.clientSecret,\n });\n return;\n }\n\n next();\n };\n}\n\nasync function handleLogin(\n req: Req,\n res: Res,\n auth: AuthModule,\n prefix: string,\n scope: string,\n sessionState: LumoAuthSessionState,\n defaultReturnTo: string,\n): Promise<void> {\n const redirectUri = absoluteUrl(req, `${prefix}/callback`);\n const returnTo = sanitizeReturnTo(req.query.return_to, defaultReturnTo);\n\n const flow = await auth.buildAuthorizationUrl({\n redirectUri,\n scope,\n });\n\n // Persist what we'll need on callback. SameSite session cookie is the\n // canonical store; never reflect any of this in the URL.\n sessionState.flow = {\n codeVerifier: flow.codeVerifier,\n state: flow.state,\n redirectUri,\n returnTo,\n };\n saveSession(req, sessionState);\n\n res.redirect(flow.url);\n}\n\nasync function handleCallback(\n req: Req,\n res: Res,\n auth: AuthModule,\n sessionState: LumoAuthSessionState,\n clientSecret: string | undefined,\n): Promise<void> {\n const code = stringQuery(req.query.code);\n const state = stringQuery(req.query.state);\n const oauthError = stringQuery(req.query.error);\n\n if (oauthError) {\n res.status(400).json({\n error: oauthError,\n error_description: stringQuery(req.query.error_description) ?? '',\n });\n return;\n }\n if (!code || !state) {\n res.status(400).json({ error: 'invalid_request', error_description: 'Missing code or state' });\n return;\n }\n const flow = sessionState.flow;\n if (!flow) {\n res.status(400).json({ error: 'invalid_request', error_description: 'No login in progress' });\n return;\n }\n if (state !== flow.state) {\n res.status(400).json({ error: 'invalid_state', error_description: 'CSRF state mismatch' });\n return;\n }\n\n try {\n const tokens: TokenResponse = await auth.exchangeCodeForTokens({\n code,\n redirectUri: flow.redirectUri,\n codeVerifier: flow.codeVerifier,\n clientSecret,\n });\n\n const user = await fetchUserInfo(auth, tokens.access_token);\n\n sessionState.tokens = {\n access_token: tokens.access_token,\n refresh_token: tokens.refresh_token,\n id_token: tokens.id_token,\n token_type: tokens.token_type ?? 'Bearer',\n expires_at: nowSeconds() + (tokens.expires_in ?? 3600),\n scope: tokens.scope,\n };\n sessionState.user = user;\n delete sessionState.flow;\n\n // Migrate the session id on auth — defends against fixation attacks.\n regenerateSession(req);\n saveSession(req, sessionState);\n\n res.redirect(flow.returnTo);\n } catch (err) {\n const message = err instanceof LumoAuthError ? err.message : 'Token exchange failed';\n const status =\n err instanceof LumoAuthApiError ? err.statusCode ?? 502 : 502;\n res.status(status).json({ error: 'token_exchange_failed', error_description: message });\n }\n}\n\nasync function handleLogout(\n req: Req,\n res: Res,\n auth: AuthModule,\n sessionState: LumoAuthSessionState,\n postLogoutRedirect: string,\n options: { endSession: boolean; clientSecret?: string },\n): Promise<void> {\n const tokens = sessionState.tokens;\n\n // Wipe LumoAuth-specific state. We DON'T destroy the whole session\n // because the host app may store unrelated data on it. Hosts that want\n // a hard logout should call `req.session.destroy()` themselves.\n delete sessionState.user;\n delete sessionState.tokens;\n delete sessionState.flow;\n saveSession(req, sessionState);\n req.user = undefined;\n\n if (!options.endSession) {\n res.redirect(postLogoutRedirect);\n return;\n }\n\n // Revoke the refresh token (this also revokes the access tokens issued\n // with it). Best-effort: a failure must not block sign-out.\n const revocable = tokens?.refresh_token ?? tokens?.access_token;\n if (revocable) {\n try {\n await auth.revokeToken(revocable, undefined, {\n clientSecret: options.clientSecret,\n tokenTypeHint: tokens?.refresh_token ? 'refresh_token' : 'access_token',\n });\n } catch {\n // ignored\n }\n }\n\n // End the LumoAuth session too. Otherwise the next /authorize signs the\n // user straight back in. The end-session endpoint needs an absolute\n // post-logout redirect URI, so a relative one keeps the local redirect.\n if (!isAbsoluteHttpUrl(postLogoutRedirect)) {\n res.redirect(postLogoutRedirect);\n return;\n }\n res.redirect(\n auth.buildEndSessionUrl({\n idTokenHint: tokens?.id_token,\n postLogoutRedirectUri: postLogoutRedirect,\n }),\n );\n}\n\n/** Seconds before expiry at which the access token is refreshed. */\nconst REFRESH_LEEWAY_SECONDS = 60;\n\nasync function refreshIfNeeded(\n req: Req,\n sessionState: LumoAuthSessionState,\n refresh: (refreshToken: string) => Promise<TokenResponse>,\n): Promise<void> {\n const tokens = sessionState.tokens;\n if (!tokens?.refresh_token) return;\n if (tokens.expires_at - nowSeconds() >= REFRESH_LEEWAY_SECONDS) return;\n\n try {\n const fresh = await refresh(tokens.refresh_token);\n sessionState.tokens = {\n access_token: fresh.access_token,\n // Keep the old refresh token when the server does not rotate it.\n refresh_token: fresh.refresh_token ?? tokens.refresh_token,\n id_token: fresh.id_token ?? tokens.id_token,\n token_type: fresh.token_type ?? tokens.token_type ?? 'Bearer',\n expires_at: nowSeconds() + (fresh.expires_in ?? 3600),\n scope: fresh.scope ?? tokens.scope,\n };\n } catch {\n // The refresh token is no longer good: treat the request as signed out.\n delete sessionState.user;\n delete sessionState.tokens;\n req.user = undefined;\n }\n saveSession(req, sessionState);\n}\n\nfunction isAbsoluteHttpUrl(value: string): boolean {\n return /^https?:\\/\\//i.test(value);\n}\n\n/**\n * Gate handler that requires a logged-in `req.user`. Combine with optional\n * scope / authorize hooks for finer-grained access control.\n */\nexport function requireAuth(options: RequireAuthOptions = {}): LumoAuthRequestHandler {\n return async function requireAuthHandler(req: Req, res: Res, next: Next): Promise<void> {\n const user = req.user;\n if (!user) {\n res.status(options.unauthorizedStatus ?? 401).json({ error: 'unauthenticated' });\n return;\n }\n\n if (options.scopes?.length) {\n const session = (req.session?.__lumoAuth ?? {}) as LumoAuthSessionState;\n const granted = (session.tokens?.scope ?? '').split(/\\s+/).filter(Boolean);\n const missing = options.scopes.filter((s) => !granted.includes(s));\n if (missing.length) {\n res\n .status(options.unauthorizedStatus ?? 403)\n .json({ error: 'insufficient_scope', error_description: `Missing: ${missing.join(', ')}` });\n return;\n }\n }\n\n if (options.authorize) {\n const ok = await options.authorize(user, req);\n if (!ok) {\n res.status(options.unauthorizedStatus ?? 403).json({ error: 'forbidden' });\n return;\n }\n }\n\n next();\n };\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────\n\nasync function fetchUserInfo(auth: AuthModule, accessToken: string): Promise<SessionUser> {\n // We hit the OIDC `/userinfo` endpoint. AuthModule exposes `getUserInfo`\n // which is the canonical wrapper.\n const info: UserInfo = await auth.getUserInfo(accessToken);\n return { ...info } as SessionUser;\n}\n\nfunction absoluteUrl(req: Req, path: string): string {\n // Honour standard reverse-proxy headers when present so the redirect URI\n // matches what the registered OAuth client allows. The host app is\n // expected to set `app.set('trust proxy', true)` if behind one.\n const reqWithProto = req as Req & { protocol?: string; get?: (h: string) => string | undefined };\n const proto = reqWithProto.protocol ?? 'https';\n const host = reqWithProto.get?.('host') ?? '';\n return `${proto}://${host}${path}`;\n}\n\nfunction sanitizeReturnTo(raw: unknown, fallback: string): string {\n // Open-redirect defence: only allow same-origin paths beginning with `/`\n // and not starting with `//` (protocol-relative).\n if (typeof raw !== 'string') return fallback;\n if (!raw.startsWith('/') || raw.startsWith('//')) return fallback;\n return raw;\n}\n\nfunction stringQuery(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (Array.isArray(value) && typeof value[0] === 'string') return value[0];\n return undefined;\n}\n\nfunction nowSeconds(): number {\n return Math.floor(Date.now() / 1000);\n}\n\nfunction saveSession(req: Req, state: LumoAuthSessionState): void {\n if (!req.session) return;\n req.session.__lumoAuth = state;\n // express-session writes on response end; we don't force a flush here.\n}\n\nfunction regenerateSession(req: Req): void {\n // express-session exposes `regenerate(cb)` — call it if available so we\n // get a fresh session id post-auth (mitigates session fixation).\n const sess = req.session as unknown as { regenerate?: (cb: (err?: unknown) => void) => void };\n if (typeof sess?.regenerate === 'function') {\n // Synchronous-style usage; we don't await because express-session's\n // regenerate is callback-based and most apps don't need the new id\n // until the next response. The session.save() that express-session\n // calls on res.end() will pick up the new state.\n sess.regenerate(() => {});\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmBA,oBAMO;AAKP,qBAiBO;AA2JA,SAAS,mBAAmB,MAAyD;AAC1F,QAAM,UAAU,KAAK,UAAU,SAAS,QAAQ,QAAQ,EAAE;AAC1D,QAAM,oBAAoB,KAAK,qBAAqB;AACpD,QAAM,qBAAqB,KAAK,sBAAsB;AACtD,QAAM,QAAQ,KAAK,SAAS;AAC5B,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,qBAAqB,KAAK,sBAAsB;AAItD,QAAM,WAAW,oBAAI,IAAoC;AACzD,QAAM,UAAU,CAAC,iBAAiD;AAChE,QAAI,UAAU,SAAS,IAAI,YAAY;AACvC,QAAI,CAAC,SAAS;AACZ,gBAAU,KACP,aAAa,cAAc,EAAE,cAAc,KAAK,aAAa,CAAC,EAC9D,QAAQ,MAAM,SAAS,OAAO,YAAY,CAAC;AAC9C,eAAS,IAAI,cAAc,OAAO;AAAA,IACpC;AACA,WAAO;AAAA,EACT;AAEA,QAAM,OAAO,IAAI,yBAAW;AAAA,IAC1B,SAAS,KAAK;AAAA,IACd,OAAO,KAAK;AAAA,IACZ,UAAU,KAAK;AAAA,IACf,OAAO,KAAK;AAAA,EACd,CAAC;AAKD,SAAO,eAAe,SAAS,KAAU,KAAU,MAA2B;AAC5E,QAAI,CAAC,IAAI,SAAS;AAIhB,UAAI,OAAO,GAAG,EAAE,KAAK;AAAA,QACnB,OAAO;AAAA,QACP,mBACE;A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F,QAAM,OAAiB,MAAM,KAAK,YAAY,WAAW;AACzD,SAAO,EAAE,GAAG,KAAK;AACnB;AAEA,SAAS,YAAY,KAAU,MAAsB;AAInD,QAAM,eAAe;AACrB,QAAM,QAAQ,aAAa,YAAY;AACvC,QAAM,OAAO,aAAa,MAAM,MAAM,KAAK;AAC3C,SAAO,GAAG,KAAK,MAAM,IAAI,GAAG,IAAI;AAClC;AAEA,SAAS,iBAAiB,KAAc,UAA0B;AAGhE,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,MAAI,CAAC,IAAI,WAAW,GAAG,KAAK,IAAI,WAAW,IAAI,EAAG,QAAO;AACzD,SAAO;AACT;AAEA,SAAS,YAAY,OAAoC;AACvD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,MAAM,QAAQ,KAAK,KAAK,OAAO,MAAM,CAAC,MAAM,SAAU,QAAO,MAAM,CAAC;AACxE,SAAO;AACT;AAEA,SAAS,aAAqB;AAC5B,SAAO,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AACrC;AAEA,SAAS,YAAY,KAAU,OAAmC;AAChE,MAAI,CAAC,IAAI,QAAS;AAClB,MAAI,QAAQ,aAAa;AAE3B;AAEA,SAAS,kBAAkB,KAAgB;AAGzC,QAAM,OAAO,IAAI;AACjB,MAAI,OAAO,MAAM,eAAe,YAAY;AAK1C,SAAK,WAAW,MAAM;AAAA,IAAC,CAAC;AAAA,EAC1B;AACF;","names":[]}
|
package/dist/index.mjs
CHANGED
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
LumoAuthNetworkError,
|
|
19
19
|
LumoAuthApprovalDeniedError,
|
|
20
20
|
LumoAuthApprovalTimeoutError,
|
|
21
|
+
LumoAuthApprovalNotDeliveredError,
|
|
21
22
|
LumoAuthBudgetExceededError
|
|
22
23
|
} from "@lumoauth/backend";
|
|
23
24
|
function lumoAuthMiddleware(opts) {
|
|
@@ -25,6 +26,17 @@ function lumoAuthMiddleware(opts) {
|
|
|
25
26
|
const postLoginRedirect = opts.postLoginRedirect ?? "/";
|
|
26
27
|
const postLogoutRedirect = opts.postLogoutRedirect ?? "/";
|
|
27
28
|
const scope = opts.scope ?? "openid profile email";
|
|
29
|
+
const autoRefresh = opts.autoRefresh ?? true;
|
|
30
|
+
const endSessionOnLogout = opts.endSessionOnLogout ?? true;
|
|
31
|
+
const inflight = /* @__PURE__ */ new Map();
|
|
32
|
+
const refresh = (refreshToken) => {
|
|
33
|
+
let pending = inflight.get(refreshToken);
|
|
34
|
+
if (!pending) {
|
|
35
|
+
pending = auth.refreshToken(refreshToken, { clientSecret: opts.clientSecret }).finally(() => inflight.delete(refreshToken));
|
|
36
|
+
inflight.set(refreshToken, pending);
|
|
37
|
+
}
|
|
38
|
+
return pending;
|
|
39
|
+
};
|
|
28
40
|
const auth = new AuthModule({
|
|
29
41
|
baseUrl: opts.baseUrl,
|
|
30
42
|
orgId: opts.organization,
|
|
@@ -40,10 +52,14 @@ function lumoAuthMiddleware(opts) {
|
|
|
40
52
|
return;
|
|
41
53
|
}
|
|
42
54
|
const sessionState = req.session.__lumoAuth ?? {};
|
|
55
|
+
const path = req.path ?? req.url.split("?")[0];
|
|
56
|
+
const isAuthRoute = path === `${prefix}/login` || path === `${prefix}/callback` || path === `${prefix}/logout`;
|
|
57
|
+
if (autoRefresh && !isAuthRoute) {
|
|
58
|
+
await refreshIfNeeded(req, sessionState, refresh);
|
|
59
|
+
}
|
|
43
60
|
if (sessionState.user) {
|
|
44
61
|
req.user = sessionState.user;
|
|
45
62
|
}
|
|
46
|
-
const path = req.path ?? req.url.split("?")[0];
|
|
47
63
|
if (req.method === "GET" && path === `${prefix}/login`) {
|
|
48
64
|
await handleLogin(req, res, auth, prefix, scope, sessionState, postLoginRedirect);
|
|
49
65
|
return;
|
|
@@ -53,7 +69,10 @@ function lumoAuthMiddleware(opts) {
|
|
|
53
69
|
return;
|
|
54
70
|
}
|
|
55
71
|
if ((req.method === "GET" || req.method === "POST") && path === `${prefix}/logout`) {
|
|
56
|
-
await handleLogout(req, res, sessionState, postLogoutRedirect
|
|
72
|
+
await handleLogout(req, res, auth, sessionState, postLogoutRedirect, {
|
|
73
|
+
endSession: endSessionOnLogout,
|
|
74
|
+
clientSecret: opts.clientSecret
|
|
75
|
+
});
|
|
57
76
|
return;
|
|
58
77
|
}
|
|
59
78
|
next();
|
|
@@ -126,12 +145,63 @@ async function handleCallback(req, res, auth, sessionState, clientSecret) {
|
|
|
126
145
|
res.status(status).json({ error: "token_exchange_failed", error_description: message });
|
|
127
146
|
}
|
|
128
147
|
}
|
|
129
|
-
async function handleLogout(req, res, sessionState, postLogoutRedirect) {
|
|
148
|
+
async function handleLogout(req, res, auth, sessionState, postLogoutRedirect, options) {
|
|
149
|
+
const tokens = sessionState.tokens;
|
|
130
150
|
delete sessionState.user;
|
|
131
151
|
delete sessionState.tokens;
|
|
132
152
|
delete sessionState.flow;
|
|
133
153
|
saveSession(req, sessionState);
|
|
134
|
-
|
|
154
|
+
req.user = void 0;
|
|
155
|
+
if (!options.endSession) {
|
|
156
|
+
res.redirect(postLogoutRedirect);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const revocable = tokens?.refresh_token ?? tokens?.access_token;
|
|
160
|
+
if (revocable) {
|
|
161
|
+
try {
|
|
162
|
+
await auth.revokeToken(revocable, void 0, {
|
|
163
|
+
clientSecret: options.clientSecret,
|
|
164
|
+
tokenTypeHint: tokens?.refresh_token ? "refresh_token" : "access_token"
|
|
165
|
+
});
|
|
166
|
+
} catch {
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (!isAbsoluteHttpUrl(postLogoutRedirect)) {
|
|
170
|
+
res.redirect(postLogoutRedirect);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
res.redirect(
|
|
174
|
+
auth.buildEndSessionUrl({
|
|
175
|
+
idTokenHint: tokens?.id_token,
|
|
176
|
+
postLogoutRedirectUri: postLogoutRedirect
|
|
177
|
+
})
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
var REFRESH_LEEWAY_SECONDS = 60;
|
|
181
|
+
async function refreshIfNeeded(req, sessionState, refresh) {
|
|
182
|
+
const tokens = sessionState.tokens;
|
|
183
|
+
if (!tokens?.refresh_token) return;
|
|
184
|
+
if (tokens.expires_at - nowSeconds() >= REFRESH_LEEWAY_SECONDS) return;
|
|
185
|
+
try {
|
|
186
|
+
const fresh = await refresh(tokens.refresh_token);
|
|
187
|
+
sessionState.tokens = {
|
|
188
|
+
access_token: fresh.access_token,
|
|
189
|
+
// Keep the old refresh token when the server does not rotate it.
|
|
190
|
+
refresh_token: fresh.refresh_token ?? tokens.refresh_token,
|
|
191
|
+
id_token: fresh.id_token ?? tokens.id_token,
|
|
192
|
+
token_type: fresh.token_type ?? tokens.token_type ?? "Bearer",
|
|
193
|
+
expires_at: nowSeconds() + (fresh.expires_in ?? 3600),
|
|
194
|
+
scope: fresh.scope ?? tokens.scope
|
|
195
|
+
};
|
|
196
|
+
} catch {
|
|
197
|
+
delete sessionState.user;
|
|
198
|
+
delete sessionState.tokens;
|
|
199
|
+
req.user = void 0;
|
|
200
|
+
}
|
|
201
|
+
saveSession(req, sessionState);
|
|
202
|
+
}
|
|
203
|
+
function isAbsoluteHttpUrl(value) {
|
|
204
|
+
return /^https?:\/\//i.test(value);
|
|
135
205
|
}
|
|
136
206
|
function requireAuth(options = {}) {
|
|
137
207
|
return async function requireAuthHandler(req, res, next) {
|
|
@@ -196,6 +266,7 @@ function regenerateSession(req) {
|
|
|
196
266
|
export {
|
|
197
267
|
LumoAuthApiError2 as LumoAuthApiError,
|
|
198
268
|
LumoAuthApprovalDeniedError,
|
|
269
|
+
LumoAuthApprovalNotDeliveredError,
|
|
199
270
|
LumoAuthApprovalTimeoutError,
|
|
200
271
|
LumoAuthAuthError,
|
|
201
272
|
LumoAuthAuthenticationError,
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Express middleware for LumoAuth.\n *\n * Wires three routes onto the host app — `/auth/login`, `/auth/callback`,\n * `/auth/logout` (the prefix is configurable) — and exposes:\n *\n * - `lumoAuthMiddleware(opts)` — must be `app.use()`'d for the routes\n * to register; also populates `req.user`\n * on every request from the session.\n * - `requireAuth([opts])` — gate handler that 401s when there's\n * no `req.user`, with optional scope /\n * permission checks.\n *\n * Sessions are stored via Express's session middleware (the host app is\n * expected to mount `express-session` before this middleware). The PKCE\n * verifier and `state` for an in-flight authorization round-trip live on\n * the session under `__lumoAuth.flow` so they survive the redirect to the\n * IDP and back without exposing them to the URL or local storage.\n */\nimport {\n AuthModule,\n type TokenResponse,\n type UserInfo,\n LumoAuthError,\n LumoAuthApiError,\n} from '@lumoauth/shared';\n\n// Re-exported so an Express app needs only this one install: the server\n// client for imperative checks inside handlers, and the shared error\n// taxonomy for instanceof checks in error middleware.\nexport {\n LumoAuthBackend,\n type LumoAuthBackendConfig,\n LumoAuthError,\n LumoAuthApiError,\n LumoAuthAuthenticationError,\n LumoAuthAuthError,\n LumoAuthPermissionDeniedError,\n LumoAuthNotFoundError,\n LumoAuthRateLimitError,\n LumoAuthValidationError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n LumoAuthApprovalDeniedError,\n LumoAuthApprovalTimeoutError,\n LumoAuthBudgetExceededError,\n} from '@lumoauth/backend';\n\n// Express types are loose to avoid a direct dependency on @types/express —\n// callers bring their own types. We only need the subset we use.\ntype Req = {\n url: string;\n path?: string;\n method?: string;\n query: Record<string, string | string[] | undefined>;\n session?: Record<string, unknown> & {\n __lumoAuth?: LumoAuthSessionState;\n };\n user?: SessionUser | undefined;\n // express-style helpers we touch\n [key: string]: unknown;\n};\n\ntype Res = {\n redirect(url: string): unknown;\n status(code: number): Res;\n json(payload: unknown): unknown;\n send(payload: unknown): unknown;\n setHeader(name: string, value: string): unknown;\n};\n\ntype Next = (err?: unknown) => void;\n\n/**\n * Structural match for express's `RequestHandler`. The exported middleware\n * factories are annotated with this so `app.use(lumoAuthMiddleware(...))` and\n * `app.get(path, requireAuth(), handler)` typecheck for TypeScript consumers\n * without this package taking a hard dependency on `@types/express`. Express's\n * own `Request`/`Response` are assignable to `any`, so the handler is accepted\n * by `app.use()`/`app.get()`/`app.METHOD()` overloads.\n */\nexport type LumoAuthRequestHandler = (\n req: any, // eslint-disable-line @typescript-eslint/no-explicit-any\n res: any, // eslint-disable-line @typescript-eslint/no-explicit-any\n next: (err?: unknown) => void,\n) => void | Promise<void>;\n\ndeclare global {\n // Augment express's Request so `req.user` is typed for consumers using\n // lumoAuthMiddleware(). Merges with @types/express when present; harmless\n // (creates the namespace) otherwise.\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n user?: SessionUser;\n }\n }\n}\n\nexport interface LumoAuthMiddlewareOptions {\n /** e.g. \"https://app.lumoauth.dev\" */\n baseUrl: string;\n /** The tenant slug that owns the OAuth client. */\n organization: string;\n /** OAuth client id registered for this app. */\n clientId: string;\n /**\n * Confidential clients require a secret on the token exchange. Public\n * (browser-facing) clients should omit this and rely on PKCE.\n */\n clientSecret?: string;\n /**\n * Path under which the three auth routes mount. Default: `/auth`.\n * Resulting routes: `/auth/login`, `/auth/callback`, `/auth/logout`.\n */\n prefix?: string;\n /**\n * Where to redirect the user after sign-in. Default: `/`.\n */\n postLoginRedirect?: string;\n /**\n * Where to redirect the user after sign-out. Default: `/`.\n */\n postLogoutRedirect?: string;\n /**\n * OAuth scopes to request. Default: `'openid profile email'`.\n */\n scope?: string;\n /**\n * Optional fetch override (for tests, instrumentation, custom proxies).\n */\n fetch?: typeof globalThis.fetch;\n}\n\nexport interface SessionUser {\n sub: string;\n email?: string;\n email_verified?: boolean;\n name?: string;\n picture?: string;\n [key: string]: unknown;\n}\n\ninterface LumoAuthSessionState {\n flow?: {\n codeVerifier: string;\n state: string;\n redirectUri: string;\n returnTo: string;\n };\n tokens?: {\n access_token: string;\n refresh_token?: string;\n id_token?: string;\n token_type: string;\n expires_at: number; // epoch seconds\n scope?: string;\n };\n user?: SessionUser;\n}\n\nexport interface RequireAuthOptions {\n /** Optional list of scopes that must all be present in the session token. */\n scopes?: string[];\n /**\n * Hook for programmatic checks (e.g. role / permission lookup against the\n * AuthorizationModule). Return false to deny.\n */\n authorize?: (user: SessionUser, req: Req) => boolean | Promise<boolean>;\n /**\n * Status code to return when unauthorized. Default 401 for missing user,\n * 403 for an `authorize` hook that returns false.\n */\n unauthorizedStatus?: number;\n}\n\n/**\n * Mount the LumoAuth Express middleware. Call this once on the app —\n * subsequent requests will:\n *\n * 1. Hit the three auth routes (login/callback/logout) under the prefix.\n * 2. Populate `req.user` from the session for every other request.\n */\nexport function lumoAuthMiddleware(opts: LumoAuthMiddlewareOptions): LumoAuthRequestHandler {\n const prefix = (opts.prefix ?? '/auth').replace(/\\/+$/, '');\n const postLoginRedirect = opts.postLoginRedirect ?? '/';\n const postLogoutRedirect = opts.postLogoutRedirect ?? '/';\n const scope = opts.scope ?? 'openid profile email';\n\n const auth = new AuthModule({\n baseUrl: opts.baseUrl,\n orgId: opts.organization,\n clientId: opts.clientId,\n fetch: opts.fetch,\n });\n\n // The host app is expected to mount this middleware once on app.use(),\n // so it runs on EVERY request. We hand-route the three auth paths and\n // pass everything else through after attaching `req.user`.\n return async function lumoAuth(req: Req, res: Res, next: Next): Promise<void> {\n if (!req.session) {\n // Hard fail with a clear message — silently letting requests through\n // when the host forgot to mount express-session would mask bugs at\n // the moment users try to sign in.\n res.status(500).json({\n error: 'session_middleware_missing',\n error_description:\n 'lumoAuthMiddleware requires express-session (or compatible) to be mounted before it.',\n });\n return;\n }\n\n // Restore `req.user` from session so downstream handlers always see it.\n const sessionState: LumoAuthSessionState = (req.session.__lumoAuth ?? {}) as LumoAuthSessionState;\n if (sessionState.user) {\n req.user = sessionState.user;\n }\n\n const path = req.path ?? req.url.split('?')[0];\n\n if (req.method === 'GET' && path === `${prefix}/login`) {\n await handleLogin(req, res, auth, prefix, scope, sessionState, postLoginRedirect);\n return;\n }\n if (req.method === 'GET' && path === `${prefix}/callback`) {\n await handleCallback(req, res, auth, sessionState, opts.clientSecret);\n return;\n }\n if (\n (req.method === 'GET' || req.method === 'POST') &&\n path === `${prefix}/logout`\n ) {\n await handleLogout(req, res, sessionState, postLogoutRedirect);\n return;\n }\n\n next();\n };\n}\n\nasync function handleLogin(\n req: Req,\n res: Res,\n auth: AuthModule,\n prefix: string,\n scope: string,\n sessionState: LumoAuthSessionState,\n defaultReturnTo: string,\n): Promise<void> {\n const redirectUri = absoluteUrl(req, `${prefix}/callback`);\n const returnTo = sanitizeReturnTo(req.query.return_to, defaultReturnTo);\n\n const flow = await auth.buildAuthorizationUrl({\n redirectUri,\n scope,\n });\n\n // Persist what we'll need on callback. SameSite session cookie is the\n // canonical store; never reflect any of this in the URL.\n sessionState.flow = {\n codeVerifier: flow.codeVerifier,\n state: flow.state,\n redirectUri,\n returnTo,\n };\n saveSession(req, sessionState);\n\n res.redirect(flow.url);\n}\n\nasync function handleCallback(\n req: Req,\n res: Res,\n auth: AuthModule,\n sessionState: LumoAuthSessionState,\n clientSecret: string | undefined,\n): Promise<void> {\n const code = stringQuery(req.query.code);\n const state = stringQuery(req.query.state);\n const oauthError = stringQuery(req.query.error);\n\n if (oauthError) {\n res.status(400).json({\n error: oauthError,\n error_description: stringQuery(req.query.error_description) ?? '',\n });\n return;\n }\n if (!code || !state) {\n res.status(400).json({ error: 'invalid_request', error_description: 'Missing code or state' });\n return;\n }\n const flow = sessionState.flow;\n if (!flow) {\n res.status(400).json({ error: 'invalid_request', error_description: 'No login in progress' });\n return;\n }\n if (state !== flow.state) {\n res.status(400).json({ error: 'invalid_state', error_description: 'CSRF state mismatch' });\n return;\n }\n\n try {\n const tokens: TokenResponse = await auth.exchangeCodeForTokens({\n code,\n redirectUri: flow.redirectUri,\n codeVerifier: flow.codeVerifier,\n clientSecret,\n });\n\n const user = await fetchUserInfo(auth, tokens.access_token);\n\n sessionState.tokens = {\n access_token: tokens.access_token,\n refresh_token: tokens.refresh_token,\n id_token: tokens.id_token,\n token_type: tokens.token_type ?? 'Bearer',\n expires_at: nowSeconds() + (tokens.expires_in ?? 3600),\n scope: tokens.scope,\n };\n sessionState.user = user;\n delete sessionState.flow;\n\n // Migrate the session id on auth — defends against fixation attacks.\n regenerateSession(req);\n saveSession(req, sessionState);\n\n res.redirect(flow.returnTo);\n } catch (err) {\n const message = err instanceof LumoAuthError ? err.message : 'Token exchange failed';\n const status =\n err instanceof LumoAuthApiError ? err.statusCode ?? 502 : 502;\n res.status(status).json({ error: 'token_exchange_failed', error_description: message });\n }\n}\n\nasync function handleLogout(\n req: Req,\n res: Res,\n sessionState: LumoAuthSessionState,\n postLogoutRedirect: string,\n): Promise<void> {\n // Wipe LumoAuth-specific state. We DON'T destroy the whole session\n // because the host app may store unrelated data on it. Hosts that want\n // a hard logout should call `req.session.destroy()` themselves.\n delete sessionState.user;\n delete sessionState.tokens;\n delete sessionState.flow;\n saveSession(req, sessionState);\n res.redirect(postLogoutRedirect);\n}\n\n/**\n * Gate handler that requires a logged-in `req.user`. Combine with optional\n * scope / authorize hooks for finer-grained access control.\n */\nexport function requireAuth(options: RequireAuthOptions = {}): LumoAuthRequestHandler {\n return async function requireAuthHandler(req: Req, res: Res, next: Next): Promise<void> {\n const user = req.user;\n if (!user) {\n res.status(options.unauthorizedStatus ?? 401).json({ error: 'unauthenticated' });\n return;\n }\n\n if (options.scopes?.length) {\n const session = (req.session?.__lumoAuth ?? {}) as LumoAuthSessionState;\n const granted = (session.tokens?.scope ?? '').split(/\\s+/).filter(Boolean);\n const missing = options.scopes.filter((s) => !granted.includes(s));\n if (missing.length) {\n res\n .status(options.unauthorizedStatus ?? 403)\n .json({ error: 'insufficient_scope', error_description: `Missing: ${missing.join(', ')}` });\n return;\n }\n }\n\n if (options.authorize) {\n const ok = await options.authorize(user, req);\n if (!ok) {\n res.status(options.unauthorizedStatus ?? 403).json({ error: 'forbidden' });\n return;\n }\n }\n\n next();\n };\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────\n\nasync function fetchUserInfo(auth: AuthModule, accessToken: string): Promise<SessionUser> {\n // We hit the OIDC `/userinfo` endpoint. AuthModule exposes `getUserInfo`\n // which is the canonical wrapper.\n const info: UserInfo = await auth.getUserInfo(accessToken);\n return { ...info } as SessionUser;\n}\n\nfunction absoluteUrl(req: Req, path: string): string {\n // Honour standard reverse-proxy headers when present so the redirect URI\n // matches what the registered OAuth client allows. The host app is\n // expected to set `app.set('trust proxy', true)` if behind one.\n const reqWithProto = req as Req & { protocol?: string; get?: (h: string) => string | undefined };\n const proto = reqWithProto.protocol ?? 'https';\n const host = reqWithProto.get?.('host') ?? '';\n return `${proto}://${host}${path}`;\n}\n\nfunction sanitizeReturnTo(raw: unknown, fallback: string): string {\n // Open-redirect defence: only allow same-origin paths beginning with `/`\n // and not starting with `//` (protocol-relative).\n if (typeof raw !== 'string') return fallback;\n if (!raw.startsWith('/') || raw.startsWith('//')) return fallback;\n return raw;\n}\n\nfunction stringQuery(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (Array.isArray(value) && typeof value[0] === 'string') return value[0];\n return undefined;\n}\n\nfunction nowSeconds(): number {\n return Math.floor(Date.now() / 1000);\n}\n\nfunction saveSession(req: Req, state: LumoAuthSessionState): void {\n if (!req.session) return;\n req.session.__lumoAuth = state;\n // express-session writes on response end; we don't force a flush here.\n}\n\nfunction regenerateSession(req: Req): void {\n // express-session exposes `regenerate(cb)` — call it if available so we\n // get a fresh session id post-auth (mitigates session fixation).\n const sess = req.session as unknown as { regenerate?: (cb: (err?: unknown) => void) => void };\n if (typeof sess?.regenerate === 'function') {\n // Synchronous-style usage; we don't await because express-session's\n // regenerate is callback-based and most apps don't need the new id\n // until the next response. The session.save() that express-session\n // calls on res.end() will pick up the new state.\n sess.regenerate(() => {});\n }\n}\n"],"mappings":";AAmBA;AAAA,EACI;AAAA,EAGA;AAAA,EACA;AAAA,OACG;AAKP;AAAA,EACI;AAAA,EAEA,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;AAGzC,QAAM,OAAO,IAAI;AACjB,MAAI,OAAO,MAAM,eAAe,YAAY;AAK1C,SAAK,WAAW,MAAM;AAAA,IAAC,CAAC;AAAA,EAC1B;AACF;","names":["LumoAuthError","LumoAuthApiError"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Express middleware for LumoAuth.\n *\n * Wires three routes onto the host app — `/auth/login`, `/auth/callback`,\n * `/auth/logout` (the prefix is configurable) — and exposes:\n *\n * - `lumoAuthMiddleware(opts)` — must be `app.use()`'d for the routes\n * to register; also populates `req.user`\n * on every request from the session.\n * - `requireAuth([opts])` — gate handler that 401s when there's\n * no `req.user`, with optional scope /\n * permission checks.\n *\n * Sessions are stored via Express's session middleware (the host app is\n * expected to mount `express-session` before this middleware). The PKCE\n * verifier and `state` for an in-flight authorization round-trip live on\n * the session under `__lumoAuth.flow` so they survive the redirect to the\n * IDP and back without exposing them to the URL or local storage.\n */\nimport {\n AuthModule,\n type TokenResponse,\n type UserInfo,\n LumoAuthError,\n LumoAuthApiError,\n} from '@lumoauth/shared';\n\n// Re-exported so an Express app needs only this one install: the server\n// client for imperative checks inside handlers, and the shared error\n// taxonomy for instanceof checks in error middleware.\nexport {\n LumoAuthBackend,\n type LumoAuthBackendConfig,\n LumoAuthError,\n LumoAuthApiError,\n LumoAuthAuthenticationError,\n LumoAuthAuthError,\n LumoAuthPermissionDeniedError,\n LumoAuthNotFoundError,\n LumoAuthRateLimitError,\n LumoAuthValidationError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n LumoAuthApprovalDeniedError,\n LumoAuthApprovalTimeoutError,\n LumoAuthApprovalNotDeliveredError,\n LumoAuthBudgetExceededError,\n} from '@lumoauth/backend';\n\n// Express types are loose to avoid a direct dependency on @types/express —\n// callers bring their own types. We only need the subset we use.\ntype Req = {\n url: string;\n path?: string;\n method?: string;\n query: Record<string, string | string[] | undefined>;\n session?: Record<string, unknown> & {\n __lumoAuth?: LumoAuthSessionState;\n };\n user?: SessionUser | undefined;\n // express-style helpers we touch\n [key: string]: unknown;\n};\n\ntype Res = {\n redirect(url: string): unknown;\n status(code: number): Res;\n json(payload: unknown): unknown;\n send(payload: unknown): unknown;\n setHeader(name: string, value: string): unknown;\n};\n\ntype Next = (err?: unknown) => void;\n\n/**\n * Structural match for express's `RequestHandler`. The exported middleware\n * factories are annotated with this so `app.use(lumoAuthMiddleware(...))` and\n * `app.get(path, requireAuth(), handler)` typecheck for TypeScript consumers\n * without this package taking a hard dependency on `@types/express`. Express's\n * own `Request`/`Response` are assignable to `any`, so the handler is accepted\n * by `app.use()`/`app.get()`/`app.METHOD()` overloads.\n */\nexport type LumoAuthRequestHandler = (\n req: any, // eslint-disable-line @typescript-eslint/no-explicit-any\n res: any, // eslint-disable-line @typescript-eslint/no-explicit-any\n next: (err?: unknown) => void,\n) => void | Promise<void>;\n\ndeclare global {\n // Augment express's Request so `req.user` is typed for consumers using\n // lumoAuthMiddleware(). Merges with @types/express when present; harmless\n // (creates the namespace) otherwise.\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n user?: SessionUser;\n }\n }\n}\n\nexport interface LumoAuthMiddlewareOptions {\n /** e.g. \"https://app.lumoauth.dev\" */\n baseUrl: string;\n /** The tenant slug that owns the OAuth client. */\n organization: string;\n /** OAuth client id registered for this app. */\n clientId: string;\n /**\n * Confidential clients require a secret on the token exchange. Public\n * (browser-facing) clients should omit this and rely on PKCE.\n */\n clientSecret?: string;\n /**\n * Path under which the three auth routes mount. Default: `/auth`.\n * Resulting routes: `/auth/login`, `/auth/callback`, `/auth/logout`.\n */\n prefix?: string;\n /**\n * Where to redirect the user after sign-in. Default: `/`.\n */\n postLoginRedirect?: string;\n /**\n * Where to redirect the user after sign-out. Default: `/`.\n *\n * Use an absolute URL (for example `https://app.example.com/`) that is\n * registered as a post-logout redirect URI on the OAuth client. Then\n * sign-out also ends the LumoAuth session (see `endSessionOnLogout`). A\n * relative path only clears the local session.\n */\n postLogoutRedirect?: string;\n /**\n * Refresh the session's access token when it expires in less than 60\n * seconds and a refresh token is stored. When the refresh fails, the\n * request is treated as signed out. Default: `true`.\n */\n autoRefresh?: boolean;\n /**\n * On sign-out, revoke the refresh token (RFC 7009) and redirect through\n * the OIDC end-session endpoint, so the LumoAuth session ends too. The\n * end-session step needs an absolute `postLogoutRedirect`. Set `false` to\n * only clear the local session. Default: `true`.\n */\n endSessionOnLogout?: boolean;\n /**\n * OAuth scopes to request. Default: `'openid profile email'`.\n */\n scope?: string;\n /**\n * Optional fetch override (for tests, instrumentation, custom proxies).\n */\n fetch?: typeof globalThis.fetch;\n}\n\nexport interface SessionUser {\n sub: string;\n email?: string;\n email_verified?: boolean;\n name?: string;\n picture?: string;\n [key: string]: unknown;\n}\n\ninterface LumoAuthSessionState {\n flow?: {\n codeVerifier: string;\n state: string;\n redirectUri: string;\n returnTo: string;\n };\n tokens?: {\n access_token: string;\n refresh_token?: string;\n id_token?: string;\n token_type: string;\n expires_at: number; // epoch seconds\n scope?: string;\n };\n user?: SessionUser;\n}\n\nexport interface RequireAuthOptions {\n /** Optional list of scopes that must all be present in the session token. */\n scopes?: string[];\n /**\n * Hook for programmatic checks (e.g. role / permission lookup against the\n * AuthorizationModule). Return false to deny.\n */\n authorize?: (user: SessionUser, req: Req) => boolean | Promise<boolean>;\n /**\n * Status code to return when unauthorized. Default 401 for missing user,\n * 403 for an `authorize` hook that returns false.\n */\n unauthorizedStatus?: number;\n}\n\n/**\n * Mount the LumoAuth Express middleware. Call this once on the app —\n * subsequent requests will:\n *\n * 1. Hit the three auth routes (login/callback/logout) under the prefix.\n * 2. Populate `req.user` from the session for every other request.\n */\nexport function lumoAuthMiddleware(opts: LumoAuthMiddlewareOptions): LumoAuthRequestHandler {\n const prefix = (opts.prefix ?? '/auth').replace(/\\/+$/, '');\n const postLoginRedirect = opts.postLoginRedirect ?? '/';\n const postLogoutRedirect = opts.postLogoutRedirect ?? '/';\n const scope = opts.scope ?? 'openid profile email';\n const autoRefresh = opts.autoRefresh ?? true;\n const endSessionOnLogout = opts.endSessionOnLogout ?? true;\n\n // One refresh per refresh token at a time. Parallel requests on the same\n // session share it, so a rotating refresh token is redeemed only once.\n const inflight = new Map<string, Promise<TokenResponse>>();\n const refresh = (refreshToken: string): Promise<TokenResponse> => {\n let pending = inflight.get(refreshToken);\n if (!pending) {\n pending = auth\n .refreshToken(refreshToken, { clientSecret: opts.clientSecret })\n .finally(() => inflight.delete(refreshToken));\n inflight.set(refreshToken, pending);\n }\n return pending;\n };\n\n const auth = new AuthModule({\n baseUrl: opts.baseUrl,\n orgId: opts.organization,\n clientId: opts.clientId,\n fetch: opts.fetch,\n });\n\n // The host app is expected to mount this middleware once on app.use(),\n // so it runs on EVERY request. We hand-route the three auth paths and\n // pass everything else through after attaching `req.user`.\n return async function lumoAuth(req: Req, res: Res, next: Next): Promise<void> {\n if (!req.session) {\n // Hard fail with a clear message — silently letting requests through\n // when the host forgot to mount express-session would mask bugs at\n // the moment users try to sign in.\n res.status(500).json({\n error: 'session_middleware_missing',\n error_description:\n 'lumoAuthMiddleware requires express-session (or compatible) to be mounted before it.',\n });\n return;\n }\n\n const sessionState: LumoAuthSessionState = (req.session.__lumoAuth ?? {}) as LumoAuthSessionState;\n const path = req.path ?? req.url.split('?')[0];\n const isAuthRoute =\n path === `${prefix}/login` || path === `${prefix}/callback` || path === `${prefix}/logout`;\n\n // Refresh a token that is about to expire before anything reads it.\n if (autoRefresh && !isAuthRoute) {\n await refreshIfNeeded(req, sessionState, refresh);\n }\n\n // Restore `req.user` from session so downstream handlers always see it.\n if (sessionState.user) {\n req.user = sessionState.user;\n }\n\n if (req.method === 'GET' && path === `${prefix}/login`) {\n await handleLogin(req, res, auth, prefix, scope, sessionState, postLoginRedirect);\n return;\n }\n if (req.method === 'GET' && path === `${prefix}/callback`) {\n await handleCallback(req, res, auth, sessionState, opts.clientSecret);\n return;\n }\n if (\n (req.method === 'GET' || req.method === 'POST') &&\n path === `${prefix}/logout`\n ) {\n await handleLogout(req, res, auth, sessionState, postLogoutRedirect, {\n endSession: endSessionOnLogout,\n clientSecret: opts.clientSecret,\n });\n return;\n }\n\n next();\n };\n}\n\nasync function handleLogin(\n req: Req,\n res: Res,\n auth: AuthModule,\n prefix: string,\n scope: string,\n sessionState: LumoAuthSessionState,\n defaultReturnTo: string,\n): Promise<void> {\n const redirectUri = absoluteUrl(req, `${prefix}/callback`);\n const returnTo = sanitizeReturnTo(req.query.return_to, defaultReturnTo);\n\n const flow = await auth.buildAuthorizationUrl({\n redirectUri,\n scope,\n });\n\n // Persist what we'll need on callback. SameSite session cookie is the\n // canonical store; never reflect any of this in the URL.\n sessionState.flow = {\n codeVerifier: flow.codeVerifier,\n state: flow.state,\n redirectUri,\n returnTo,\n };\n saveSession(req, sessionState);\n\n res.redirect(flow.url);\n}\n\nasync function handleCallback(\n req: Req,\n res: Res,\n auth: AuthModule,\n sessionState: LumoAuthSessionState,\n clientSecret: string | undefined,\n): Promise<void> {\n const code = stringQuery(req.query.code);\n const state = stringQuery(req.query.state);\n const oauthError = stringQuery(req.query.error);\n\n if (oauthError) {\n res.status(400).json({\n error: oauthError,\n error_description: stringQuery(req.query.error_description) ?? '',\n });\n return;\n }\n if (!code || !state) {\n res.status(400).json({ error: 'invalid_request', error_description: 'Missing code or state' });\n return;\n }\n const flow = sessionState.flow;\n if (!flow) {\n res.status(400).json({ error: 'invalid_request', error_description: 'No login in progress' });\n return;\n }\n if (state !== flow.state) {\n res.status(400).json({ error: 'invalid_state', error_description: 'CSRF state mismatch' });\n return;\n }\n\n try {\n const tokens: TokenResponse = await auth.exchangeCodeForTokens({\n code,\n redirectUri: flow.redirectUri,\n codeVerifier: flow.codeVerifier,\n clientSecret,\n });\n\n const user = await fetchUserInfo(auth, tokens.access_token);\n\n sessionState.tokens = {\n access_token: tokens.access_token,\n refresh_token: tokens.refresh_token,\n id_token: tokens.id_token,\n token_type: tokens.token_type ?? 'Bearer',\n expires_at: nowSeconds() + (tokens.expires_in ?? 3600),\n scope: tokens.scope,\n };\n sessionState.user = user;\n delete sessionState.flow;\n\n // Migrate the session id on auth — defends against fixation attacks.\n regenerateSession(req);\n saveSession(req, sessionState);\n\n res.redirect(flow.returnTo);\n } catch (err) {\n const message = err instanceof LumoAuthError ? err.message : 'Token exchange failed';\n const status =\n err instanceof LumoAuthApiError ? err.statusCode ?? 502 : 502;\n res.status(status).json({ error: 'token_exchange_failed', error_description: message });\n }\n}\n\nasync function handleLogout(\n req: Req,\n res: Res,\n auth: AuthModule,\n sessionState: LumoAuthSessionState,\n postLogoutRedirect: string,\n options: { endSession: boolean; clientSecret?: string },\n): Promise<void> {\n const tokens = sessionState.tokens;\n\n // Wipe LumoAuth-specific state. We DON'T destroy the whole session\n // because the host app may store unrelated data on it. Hosts that want\n // a hard logout should call `req.session.destroy()` themselves.\n delete sessionState.user;\n delete sessionState.tokens;\n delete sessionState.flow;\n saveSession(req, sessionState);\n req.user = undefined;\n\n if (!options.endSession) {\n res.redirect(postLogoutRedirect);\n return;\n }\n\n // Revoke the refresh token (this also revokes the access tokens issued\n // with it). Best-effort: a failure must not block sign-out.\n const revocable = tokens?.refresh_token ?? tokens?.access_token;\n if (revocable) {\n try {\n await auth.revokeToken(revocable, undefined, {\n clientSecret: options.clientSecret,\n tokenTypeHint: tokens?.refresh_token ? 'refresh_token' : 'access_token',\n });\n } catch {\n // ignored\n }\n }\n\n // End the LumoAuth session too. Otherwise the next /authorize signs the\n // user straight back in. The end-session endpoint needs an absolute\n // post-logout redirect URI, so a relative one keeps the local redirect.\n if (!isAbsoluteHttpUrl(postLogoutRedirect)) {\n res.redirect(postLogoutRedirect);\n return;\n }\n res.redirect(\n auth.buildEndSessionUrl({\n idTokenHint: tokens?.id_token,\n postLogoutRedirectUri: postLogoutRedirect,\n }),\n );\n}\n\n/** Seconds before expiry at which the access token is refreshed. */\nconst REFRESH_LEEWAY_SECONDS = 60;\n\nasync function refreshIfNeeded(\n req: Req,\n sessionState: LumoAuthSessionState,\n refresh: (refreshToken: string) => Promise<TokenResponse>,\n): Promise<void> {\n const tokens = sessionState.tokens;\n if (!tokens?.refresh_token) return;\n if (tokens.expires_at - nowSeconds() >= REFRESH_LEEWAY_SECONDS) return;\n\n try {\n const fresh = await refresh(tokens.refresh_token);\n sessionState.tokens = {\n access_token: fresh.access_token,\n // Keep the old refresh token when the server does not rotate it.\n refresh_token: fresh.refresh_token ?? tokens.refresh_token,\n id_token: fresh.id_token ?? tokens.id_token,\n token_type: fresh.token_type ?? tokens.token_type ?? 'Bearer',\n expires_at: nowSeconds() + (fresh.expires_in ?? 3600),\n scope: fresh.scope ?? tokens.scope,\n };\n } catch {\n // The refresh token is no longer good: treat the request as signed out.\n delete sessionState.user;\n delete sessionState.tokens;\n req.user = undefined;\n }\n saveSession(req, sessionState);\n}\n\nfunction isAbsoluteHttpUrl(value: string): boolean {\n return /^https?:\\/\\//i.test(value);\n}\n\n/**\n * Gate handler that requires a logged-in `req.user`. Combine with optional\n * scope / authorize hooks for finer-grained access control.\n */\nexport function requireAuth(options: RequireAuthOptions = {}): LumoAuthRequestHandler {\n return async function requireAuthHandler(req: Req, res: Res, next: Next): Promise<void> {\n const user = req.user;\n if (!user) {\n res.status(options.unauthorizedStatus ?? 401).json({ error: 'unauthenticated' });\n return;\n }\n\n if (options.scopes?.length) {\n const session = (req.session?.__lumoAuth ?? {}) as LumoAuthSessionState;\n const granted = (session.tokens?.scope ?? '').split(/\\s+/).filter(Boolean);\n const missing = options.scopes.filter((s) => !granted.includes(s));\n if (missing.length) {\n res\n .status(options.unauthorizedStatus ?? 403)\n .json({ error: 'insufficient_scope', error_description: `Missing: ${missing.join(', ')}` });\n return;\n }\n }\n\n if (options.authorize) {\n const ok = await options.authorize(user, req);\n if (!ok) {\n res.status(options.unauthorizedStatus ?? 403).json({ error: 'forbidden' });\n return;\n }\n }\n\n next();\n };\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────\n\nasync function fetchUserInfo(auth: AuthModule, accessToken: string): Promise<SessionUser> {\n // We hit the OIDC `/userinfo` endpoint. AuthModule exposes `getUserInfo`\n // which is the canonical wrapper.\n const info: UserInfo = await auth.getUserInfo(accessToken);\n return { ...info } as SessionUser;\n}\n\nfunction absoluteUrl(req: Req, path: string): string {\n // Honour standard reverse-proxy headers when present so the redirect URI\n // matches what the registered OAuth client allows. The host app is\n // expected to set `app.set('trust proxy', true)` if behind one.\n const reqWithProto = req as Req & { protocol?: string; get?: (h: string) => string | undefined };\n const proto = reqWithProto.protocol ?? 'https';\n const host = reqWithProto.get?.('host') ?? '';\n return `${proto}://${host}${path}`;\n}\n\nfunction sanitizeReturnTo(raw: unknown, fallback: string): string {\n // Open-redirect defence: only allow same-origin paths beginning with `/`\n // and not starting with `//` (protocol-relative).\n if (typeof raw !== 'string') return fallback;\n if (!raw.startsWith('/') || raw.startsWith('//')) return fallback;\n return raw;\n}\n\nfunction stringQuery(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (Array.isArray(value) && typeof value[0] === 'string') return value[0];\n return undefined;\n}\n\nfunction nowSeconds(): number {\n return Math.floor(Date.now() / 1000);\n}\n\nfunction saveSession(req: Req, state: LumoAuthSessionState): void {\n if (!req.session) return;\n req.session.__lumoAuth = state;\n // express-session writes on response end; we don't force a flush here.\n}\n\nfunction regenerateSession(req: Req): void {\n // express-session exposes `regenerate(cb)` — call it if available so we\n // get a fresh session id post-auth (mitigates session fixation).\n const sess = req.session as unknown as { regenerate?: (cb: (err?: unknown) => void) => void };\n if (typeof sess?.regenerate === 'function') {\n // Synchronous-style usage; we don't await because express-session's\n // regenerate is callback-based and most apps don't need the new id\n // until the next response. The session.save() that express-session\n // calls on res.end() will pick up the new state.\n sess.regenerate(() => {});\n }\n}\n"],"mappings":";AAmBA;AAAA,EACI;AAAA,EAGA;AAAA,EACA;AAAA,OACG;AAKP;AAAA,EACI;AAAA,EAEA,iBAAAA;AAAA,EACA,oBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AA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AAQ,SAAU,QAAO;AACpC,MAAI,CAAC,IAAI,WAAW,GAAG,KAAK,IAAI,WAAW,IAAI,EAAG,QAAO;AACzD,SAAO;AACT;AAEA,SAAS,YAAY,OAAoC;AACvD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,MAAM,QAAQ,KAAK,KAAK,OAAO,MAAM,CAAC,MAAM,SAAU,QAAO,MAAM,CAAC;AACxE,SAAO;AACT;AAEA,SAAS,aAAqB;AAC5B,SAAO,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AACrC;AAEA,SAAS,YAAY,KAAU,OAAmC;AAChE,MAAI,CAAC,IAAI,QAAS;AAClB,MAAI,QAAQ,aAAa;AAE3B;AAEA,SAAS,kBAAkB,KAAgB;AAGzC,QAAM,OAAO,IAAI;AACjB,MAAI,OAAO,MAAM,eAAe,YAAY;AAK1C,SAAK,WAAW,MAAM;AAAA,IAAC,CAAC;AAAA,EAC1B;AACF;","names":["LumoAuthError","LumoAuthApiError"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lumoauth/express",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Express middleware for LumoAuth
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "Express middleware for LumoAuth — login, callback, and logout routes plus requireAuth().",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "LumoAuth",
|
|
7
7
|
"publishConfig": {
|
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
"build": "tsup",
|
|
28
28
|
"dev": "tsup --watch",
|
|
29
29
|
"typecheck": "tsc --noEmit",
|
|
30
|
+
"test": "npm run build && node --test tests/*.test.mjs",
|
|
30
31
|
"prepublishOnly": "npm run build"
|
|
31
32
|
},
|
|
32
33
|
"keywords": [
|