@lumoauth/express 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LumoAuth LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,329 @@
1
- # Temporary Holding Version
1
+ # @lumoauth/express
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@lumoauth/express.svg)](https://www.npmjs.com/package/@lumoauth/express)
4
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./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.
50
+
51
+ ## Install
52
+
53
+ ```bash
54
+ npm install @lumoauth/express express-session
55
+ ```
56
+
57
+ ## Quick start
58
+
59
+ ```ts
60
+ import express from 'express';
61
+ import session from 'express-session';
62
+ import { lumoAuthMiddleware, requireAuth } from '@lumoauth/express';
63
+
64
+ const app = express();
65
+
66
+ // 1. Mount sessions first. LumoAuth stores the sign-in state and the tokens in the session.
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.
71
+ app.use(
72
+ lumoAuthMiddleware({
73
+ baseUrl: 'https://app.lumoauth.dev', // EU region: https://eu.app.lumoauth.dev
74
+ organization: 'acme-corp',
75
+ clientId: process.env.LUMOAUTH_CLIENT_ID!,
76
+ clientSecret: process.env.LUMOAUTH_CLIENT_SECRET, // leave out for a public client with PKCE
77
+ }),
78
+ );
79
+
80
+ // 3. Guard the routes that need a signed-in user.
81
+ app.get('/dashboard', requireAuth(), (req, res) => {
82
+ res.json({ hello: req.user!.email });
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
+ });
211
+ ```
212
+
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.
243
+
244
+ ```ts
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
+ });
253
+ ```
254
+
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 |
323
+
324
+ More: [Node.js and Express quickstart](https://docs.lumoauth.dev/quickstarts/node/) and the
325
+ [SDK overview](https://docs.lumoauth.dev/developer/sdks/).
326
+
327
+ ## Licence
328
+
329
+ [MIT](./LICENSE)
@@ -0,0 +1,137 @@
1
+ export { LumoAuthApiError, LumoAuthApprovalDeniedError, LumoAuthApprovalNotDeliveredError, LumoAuthApprovalTimeoutError, LumoAuthAuthError, LumoAuthAuthenticationError, LumoAuthBackend, LumoAuthBackendConfig, LumoAuthBudgetExceededError, LumoAuthConfigError, LumoAuthError, LumoAuthNetworkError, LumoAuthNotFoundError, LumoAuthPermissionDeniedError, LumoAuthRateLimitError, LumoAuthValidationError } from '@lumoauth/backend';
2
+
3
+ type Req = {
4
+ url: string;
5
+ path?: string;
6
+ method?: string;
7
+ query: Record<string, string | string[] | undefined>;
8
+ session?: Record<string, unknown> & {
9
+ __lumoAuth?: LumoAuthSessionState;
10
+ };
11
+ user?: SessionUser | undefined;
12
+ [key: string]: unknown;
13
+ };
14
+ /**
15
+ * Structural match for express's `RequestHandler`. The exported middleware
16
+ * factories are annotated with this so `app.use(lumoAuthMiddleware(...))` and
17
+ * `app.get(path, requireAuth(), handler)` typecheck for TypeScript consumers
18
+ * without this package taking a hard dependency on `@types/express`. Express's
19
+ * own `Request`/`Response` are assignable to `any`, so the handler is accepted
20
+ * by `app.use()`/`app.get()`/`app.METHOD()` overloads.
21
+ */
22
+ type LumoAuthRequestHandler = (req: any, // eslint-disable-line @typescript-eslint/no-explicit-any
23
+ res: any, // eslint-disable-line @typescript-eslint/no-explicit-any
24
+ next: (err?: unknown) => void) => void | Promise<void>;
25
+ declare global {
26
+ namespace Express {
27
+ interface Request {
28
+ user?: SessionUser;
29
+ }
30
+ }
31
+ }
32
+ interface LumoAuthMiddlewareOptions {
33
+ /** e.g. "https://app.lumoauth.dev" */
34
+ baseUrl: string;
35
+ /** The tenant slug that owns the OAuth client. */
36
+ organization: string;
37
+ /** OAuth client id registered for this app. */
38
+ clientId: string;
39
+ /**
40
+ * Confidential clients require a secret on the token exchange. Public
41
+ * (browser-facing) clients should omit this and rely on PKCE.
42
+ */
43
+ clientSecret?: string;
44
+ /**
45
+ * Path under which the three auth routes mount. Default: `/auth`.
46
+ * Resulting routes: `/auth/login`, `/auth/callback`, `/auth/logout`.
47
+ */
48
+ prefix?: string;
49
+ /**
50
+ * Where to redirect the user after sign-in. Default: `/`.
51
+ */
52
+ postLoginRedirect?: string;
53
+ /**
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.
60
+ */
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;
75
+ /**
76
+ * OAuth scopes to request. Default: `'openid profile email'`.
77
+ */
78
+ scope?: string;
79
+ /**
80
+ * Optional fetch override (for tests, instrumentation, custom proxies).
81
+ */
82
+ fetch?: typeof globalThis.fetch;
83
+ }
84
+ interface SessionUser {
85
+ sub: string;
86
+ email?: string;
87
+ email_verified?: boolean;
88
+ name?: string;
89
+ picture?: string;
90
+ [key: string]: unknown;
91
+ }
92
+ interface LumoAuthSessionState {
93
+ flow?: {
94
+ codeVerifier: string;
95
+ state: string;
96
+ redirectUri: string;
97
+ returnTo: string;
98
+ };
99
+ tokens?: {
100
+ access_token: string;
101
+ refresh_token?: string;
102
+ id_token?: string;
103
+ token_type: string;
104
+ expires_at: number;
105
+ scope?: string;
106
+ };
107
+ user?: SessionUser;
108
+ }
109
+ interface RequireAuthOptions {
110
+ /** Optional list of scopes that must all be present in the session token. */
111
+ scopes?: string[];
112
+ /**
113
+ * Hook for programmatic checks (e.g. role / permission lookup against the
114
+ * AuthorizationModule). Return false to deny.
115
+ */
116
+ authorize?: (user: SessionUser, req: Req) => boolean | Promise<boolean>;
117
+ /**
118
+ * Status code to return when unauthorized. Default 401 for missing user,
119
+ * 403 for an `authorize` hook that returns false.
120
+ */
121
+ unauthorizedStatus?: number;
122
+ }
123
+ /**
124
+ * Mount the LumoAuth Express middleware. Call this once on the app —
125
+ * subsequent requests will:
126
+ *
127
+ * 1. Hit the three auth routes (login/callback/logout) under the prefix.
128
+ * 2. Populate `req.user` from the session for every other request.
129
+ */
130
+ declare function lumoAuthMiddleware(opts: LumoAuthMiddlewareOptions): LumoAuthRequestHandler;
131
+ /**
132
+ * Gate handler that requires a logged-in `req.user`. Combine with optional
133
+ * scope / authorize hooks for finer-grained access control.
134
+ */
135
+ declare function requireAuth(options?: RequireAuthOptions): LumoAuthRequestHandler;
136
+
137
+ export { type LumoAuthMiddlewareOptions, type LumoAuthRequestHandler, type RequireAuthOptions, type SessionUser, lumoAuthMiddleware, requireAuth };
@@ -0,0 +1,137 @@
1
+ export { LumoAuthApiError, LumoAuthApprovalDeniedError, LumoAuthApprovalNotDeliveredError, LumoAuthApprovalTimeoutError, LumoAuthAuthError, LumoAuthAuthenticationError, LumoAuthBackend, LumoAuthBackendConfig, LumoAuthBudgetExceededError, LumoAuthConfigError, LumoAuthError, LumoAuthNetworkError, LumoAuthNotFoundError, LumoAuthPermissionDeniedError, LumoAuthRateLimitError, LumoAuthValidationError } from '@lumoauth/backend';
2
+
3
+ type Req = {
4
+ url: string;
5
+ path?: string;
6
+ method?: string;
7
+ query: Record<string, string | string[] | undefined>;
8
+ session?: Record<string, unknown> & {
9
+ __lumoAuth?: LumoAuthSessionState;
10
+ };
11
+ user?: SessionUser | undefined;
12
+ [key: string]: unknown;
13
+ };
14
+ /**
15
+ * Structural match for express's `RequestHandler`. The exported middleware
16
+ * factories are annotated with this so `app.use(lumoAuthMiddleware(...))` and
17
+ * `app.get(path, requireAuth(), handler)` typecheck for TypeScript consumers
18
+ * without this package taking a hard dependency on `@types/express`. Express's
19
+ * own `Request`/`Response` are assignable to `any`, so the handler is accepted
20
+ * by `app.use()`/`app.get()`/`app.METHOD()` overloads.
21
+ */
22
+ type LumoAuthRequestHandler = (req: any, // eslint-disable-line @typescript-eslint/no-explicit-any
23
+ res: any, // eslint-disable-line @typescript-eslint/no-explicit-any
24
+ next: (err?: unknown) => void) => void | Promise<void>;
25
+ declare global {
26
+ namespace Express {
27
+ interface Request {
28
+ user?: SessionUser;
29
+ }
30
+ }
31
+ }
32
+ interface LumoAuthMiddlewareOptions {
33
+ /** e.g. "https://app.lumoauth.dev" */
34
+ baseUrl: string;
35
+ /** The tenant slug that owns the OAuth client. */
36
+ organization: string;
37
+ /** OAuth client id registered for this app. */
38
+ clientId: string;
39
+ /**
40
+ * Confidential clients require a secret on the token exchange. Public
41
+ * (browser-facing) clients should omit this and rely on PKCE.
42
+ */
43
+ clientSecret?: string;
44
+ /**
45
+ * Path under which the three auth routes mount. Default: `/auth`.
46
+ * Resulting routes: `/auth/login`, `/auth/callback`, `/auth/logout`.
47
+ */
48
+ prefix?: string;
49
+ /**
50
+ * Where to redirect the user after sign-in. Default: `/`.
51
+ */
52
+ postLoginRedirect?: string;
53
+ /**
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.
60
+ */
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;
75
+ /**
76
+ * OAuth scopes to request. Default: `'openid profile email'`.
77
+ */
78
+ scope?: string;
79
+ /**
80
+ * Optional fetch override (for tests, instrumentation, custom proxies).
81
+ */
82
+ fetch?: typeof globalThis.fetch;
83
+ }
84
+ interface SessionUser {
85
+ sub: string;
86
+ email?: string;
87
+ email_verified?: boolean;
88
+ name?: string;
89
+ picture?: string;
90
+ [key: string]: unknown;
91
+ }
92
+ interface LumoAuthSessionState {
93
+ flow?: {
94
+ codeVerifier: string;
95
+ state: string;
96
+ redirectUri: string;
97
+ returnTo: string;
98
+ };
99
+ tokens?: {
100
+ access_token: string;
101
+ refresh_token?: string;
102
+ id_token?: string;
103
+ token_type: string;
104
+ expires_at: number;
105
+ scope?: string;
106
+ };
107
+ user?: SessionUser;
108
+ }
109
+ interface RequireAuthOptions {
110
+ /** Optional list of scopes that must all be present in the session token. */
111
+ scopes?: string[];
112
+ /**
113
+ * Hook for programmatic checks (e.g. role / permission lookup against the
114
+ * AuthorizationModule). Return false to deny.
115
+ */
116
+ authorize?: (user: SessionUser, req: Req) => boolean | Promise<boolean>;
117
+ /**
118
+ * Status code to return when unauthorized. Default 401 for missing user,
119
+ * 403 for an `authorize` hook that returns false.
120
+ */
121
+ unauthorizedStatus?: number;
122
+ }
123
+ /**
124
+ * Mount the LumoAuth Express middleware. Call this once on the app —
125
+ * subsequent requests will:
126
+ *
127
+ * 1. Hit the three auth routes (login/callback/logout) under the prefix.
128
+ * 2. Populate `req.user` from the session for every other request.
129
+ */
130
+ declare function lumoAuthMiddleware(opts: LumoAuthMiddlewareOptions): LumoAuthRequestHandler;
131
+ /**
132
+ * Gate handler that requires a logged-in `req.user`. Combine with optional
133
+ * scope / authorize hooks for finer-grained access control.
134
+ */
135
+ declare function requireAuth(options?: RequireAuthOptions): LumoAuthRequestHandler;
136
+
137
+ export { type LumoAuthMiddlewareOptions, type LumoAuthRequestHandler, type RequireAuthOptions, type SessionUser, lumoAuthMiddleware, requireAuth };