@lumoauth/express 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +49 -2
- package/dist/index.d.mts +119 -0
- package/dist/index.d.ts +119 -0
- package/dist/index.js +235 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +214 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +55 -5
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,50 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lumoauth/express
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Express middleware for LumoAuth: mounts `/auth/login`, `/auth/callback`, and
|
|
4
|
+
`/auth/logout`, populates `req.user` from the session, and gates routes with
|
|
5
|
+
`requireAuth()`. Re-exports `LumoAuthBackend` and the shared error classes, so
|
|
6
|
+
this is the only LumoAuth install an Express app needs.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npm install @lumoauth/express express-session
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Example
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import express from 'express';
|
|
18
|
+
import session from 'express-session';
|
|
19
|
+
import { lumoAuthMiddleware, requireAuth, LumoAuthBackend } from '@lumoauth/express';
|
|
20
|
+
|
|
21
|
+
const app = express();
|
|
22
|
+
app.use(session({ secret: process.env.SESSION_SECRET!, resave: false, saveUninitialized: false }));
|
|
23
|
+
app.use(
|
|
24
|
+
lumoAuthMiddleware({
|
|
25
|
+
baseUrl: process.env.LUMOAUTH_URL!,
|
|
26
|
+
organization: 'acme-corp',
|
|
27
|
+
clientId: process.env.LUMOAUTH_CLIENT_ID!,
|
|
28
|
+
clientSecret: process.env.LUMOAUTH_CLIENT_SECRET,
|
|
29
|
+
}),
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
app.get('/dashboard', requireAuth(), (req, res) => {
|
|
33
|
+
res.json({ hello: req.user!.email });
|
|
34
|
+
});
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Server-side checks inside handlers use the re-exported backend client:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
const lumo = new LumoAuthBackend({ baseUrl, secretKey: process.env.LUMOAUTH_SECRET_KEY!, orgId: 'acme-corp' });
|
|
41
|
+
const canEdit = await lumo.permissions.check('documents.edit');
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Docs
|
|
45
|
+
|
|
46
|
+
https://docs.lumoauth.dev
|
|
47
|
+
|
|
48
|
+
## License
|
|
49
|
+
|
|
50
|
+
MIT
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
export { LumoAuthApiError, LumoAuthApprovalDeniedError, 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
|
+
postLogoutRedirect?: string;
|
|
57
|
+
/**
|
|
58
|
+
* OAuth scopes to request. Default: `'openid profile email'`.
|
|
59
|
+
*/
|
|
60
|
+
scope?: string;
|
|
61
|
+
/**
|
|
62
|
+
* Optional fetch override (for tests, instrumentation, custom proxies).
|
|
63
|
+
*/
|
|
64
|
+
fetch?: typeof globalThis.fetch;
|
|
65
|
+
}
|
|
66
|
+
interface SessionUser {
|
|
67
|
+
sub: string;
|
|
68
|
+
email?: string;
|
|
69
|
+
email_verified?: boolean;
|
|
70
|
+
name?: string;
|
|
71
|
+
picture?: string;
|
|
72
|
+
[key: string]: unknown;
|
|
73
|
+
}
|
|
74
|
+
interface LumoAuthSessionState {
|
|
75
|
+
flow?: {
|
|
76
|
+
codeVerifier: string;
|
|
77
|
+
state: string;
|
|
78
|
+
redirectUri: string;
|
|
79
|
+
returnTo: string;
|
|
80
|
+
};
|
|
81
|
+
tokens?: {
|
|
82
|
+
access_token: string;
|
|
83
|
+
refresh_token?: string;
|
|
84
|
+
id_token?: string;
|
|
85
|
+
token_type: string;
|
|
86
|
+
expires_at: number;
|
|
87
|
+
scope?: string;
|
|
88
|
+
};
|
|
89
|
+
user?: SessionUser;
|
|
90
|
+
}
|
|
91
|
+
interface RequireAuthOptions {
|
|
92
|
+
/** Optional list of scopes that must all be present in the session token. */
|
|
93
|
+
scopes?: string[];
|
|
94
|
+
/**
|
|
95
|
+
* Hook for programmatic checks (e.g. role / permission lookup against the
|
|
96
|
+
* AuthorizationModule). Return false to deny.
|
|
97
|
+
*/
|
|
98
|
+
authorize?: (user: SessionUser, req: Req) => boolean | Promise<boolean>;
|
|
99
|
+
/**
|
|
100
|
+
* Status code to return when unauthorized. Default 401 for missing user,
|
|
101
|
+
* 403 for an `authorize` hook that returns false.
|
|
102
|
+
*/
|
|
103
|
+
unauthorizedStatus?: number;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Mount the LumoAuth Express middleware. Call this once on the app —
|
|
107
|
+
* subsequent requests will:
|
|
108
|
+
*
|
|
109
|
+
* 1. Hit the three auth routes (login/callback/logout) under the prefix.
|
|
110
|
+
* 2. Populate `req.user` from the session for every other request.
|
|
111
|
+
*/
|
|
112
|
+
declare function lumoAuthMiddleware(opts: LumoAuthMiddlewareOptions): LumoAuthRequestHandler;
|
|
113
|
+
/**
|
|
114
|
+
* Gate handler that requires a logged-in `req.user`. Combine with optional
|
|
115
|
+
* scope / authorize hooks for finer-grained access control.
|
|
116
|
+
*/
|
|
117
|
+
declare function requireAuth(options?: RequireAuthOptions): LumoAuthRequestHandler;
|
|
118
|
+
|
|
119
|
+
export { type LumoAuthMiddlewareOptions, type LumoAuthRequestHandler, type RequireAuthOptions, type SessionUser, lumoAuthMiddleware, requireAuth };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
export { LumoAuthApiError, LumoAuthApprovalDeniedError, 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
|
+
postLogoutRedirect?: string;
|
|
57
|
+
/**
|
|
58
|
+
* OAuth scopes to request. Default: `'openid profile email'`.
|
|
59
|
+
*/
|
|
60
|
+
scope?: string;
|
|
61
|
+
/**
|
|
62
|
+
* Optional fetch override (for tests, instrumentation, custom proxies).
|
|
63
|
+
*/
|
|
64
|
+
fetch?: typeof globalThis.fetch;
|
|
65
|
+
}
|
|
66
|
+
interface SessionUser {
|
|
67
|
+
sub: string;
|
|
68
|
+
email?: string;
|
|
69
|
+
email_verified?: boolean;
|
|
70
|
+
name?: string;
|
|
71
|
+
picture?: string;
|
|
72
|
+
[key: string]: unknown;
|
|
73
|
+
}
|
|
74
|
+
interface LumoAuthSessionState {
|
|
75
|
+
flow?: {
|
|
76
|
+
codeVerifier: string;
|
|
77
|
+
state: string;
|
|
78
|
+
redirectUri: string;
|
|
79
|
+
returnTo: string;
|
|
80
|
+
};
|
|
81
|
+
tokens?: {
|
|
82
|
+
access_token: string;
|
|
83
|
+
refresh_token?: string;
|
|
84
|
+
id_token?: string;
|
|
85
|
+
token_type: string;
|
|
86
|
+
expires_at: number;
|
|
87
|
+
scope?: string;
|
|
88
|
+
};
|
|
89
|
+
user?: SessionUser;
|
|
90
|
+
}
|
|
91
|
+
interface RequireAuthOptions {
|
|
92
|
+
/** Optional list of scopes that must all be present in the session token. */
|
|
93
|
+
scopes?: string[];
|
|
94
|
+
/**
|
|
95
|
+
* Hook for programmatic checks (e.g. role / permission lookup against the
|
|
96
|
+
* AuthorizationModule). Return false to deny.
|
|
97
|
+
*/
|
|
98
|
+
authorize?: (user: SessionUser, req: Req) => boolean | Promise<boolean>;
|
|
99
|
+
/**
|
|
100
|
+
* Status code to return when unauthorized. Default 401 for missing user,
|
|
101
|
+
* 403 for an `authorize` hook that returns false.
|
|
102
|
+
*/
|
|
103
|
+
unauthorizedStatus?: number;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Mount the LumoAuth Express middleware. Call this once on the app —
|
|
107
|
+
* subsequent requests will:
|
|
108
|
+
*
|
|
109
|
+
* 1. Hit the three auth routes (login/callback/logout) under the prefix.
|
|
110
|
+
* 2. Populate `req.user` from the session for every other request.
|
|
111
|
+
*/
|
|
112
|
+
declare function lumoAuthMiddleware(opts: LumoAuthMiddlewareOptions): LumoAuthRequestHandler;
|
|
113
|
+
/**
|
|
114
|
+
* Gate handler that requires a logged-in `req.user`. Combine with optional
|
|
115
|
+
* scope / authorize hooks for finer-grained access control.
|
|
116
|
+
*/
|
|
117
|
+
declare function requireAuth(options?: RequireAuthOptions): LumoAuthRequestHandler;
|
|
118
|
+
|
|
119
|
+
export { type LumoAuthMiddlewareOptions, type LumoAuthRequestHandler, type RequireAuthOptions, type SessionUser, lumoAuthMiddleware, requireAuth };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
LumoAuthApiError: () => import_backend.LumoAuthApiError,
|
|
24
|
+
LumoAuthApprovalDeniedError: () => import_backend.LumoAuthApprovalDeniedError,
|
|
25
|
+
LumoAuthApprovalTimeoutError: () => import_backend.LumoAuthApprovalTimeoutError,
|
|
26
|
+
LumoAuthAuthError: () => import_backend.LumoAuthAuthError,
|
|
27
|
+
LumoAuthAuthenticationError: () => import_backend.LumoAuthAuthenticationError,
|
|
28
|
+
LumoAuthBackend: () => import_backend.LumoAuthBackend,
|
|
29
|
+
LumoAuthBudgetExceededError: () => import_backend.LumoAuthBudgetExceededError,
|
|
30
|
+
LumoAuthConfigError: () => import_backend.LumoAuthConfigError,
|
|
31
|
+
LumoAuthError: () => import_backend.LumoAuthError,
|
|
32
|
+
LumoAuthNetworkError: () => import_backend.LumoAuthNetworkError,
|
|
33
|
+
LumoAuthNotFoundError: () => import_backend.LumoAuthNotFoundError,
|
|
34
|
+
LumoAuthPermissionDeniedError: () => import_backend.LumoAuthPermissionDeniedError,
|
|
35
|
+
LumoAuthRateLimitError: () => import_backend.LumoAuthRateLimitError,
|
|
36
|
+
LumoAuthValidationError: () => import_backend.LumoAuthValidationError,
|
|
37
|
+
lumoAuthMiddleware: () => lumoAuthMiddleware,
|
|
38
|
+
requireAuth: () => requireAuth
|
|
39
|
+
});
|
|
40
|
+
module.exports = __toCommonJS(index_exports);
|
|
41
|
+
var import_shared = require("@lumoauth/shared");
|
|
42
|
+
var import_backend = require("@lumoauth/backend");
|
|
43
|
+
function lumoAuthMiddleware(opts) {
|
|
44
|
+
const prefix = (opts.prefix ?? "/auth").replace(/\/+$/, "");
|
|
45
|
+
const postLoginRedirect = opts.postLoginRedirect ?? "/";
|
|
46
|
+
const postLogoutRedirect = opts.postLogoutRedirect ?? "/";
|
|
47
|
+
const scope = opts.scope ?? "openid profile email";
|
|
48
|
+
const auth = new import_shared.AuthModule({
|
|
49
|
+
baseUrl: opts.baseUrl,
|
|
50
|
+
orgId: opts.organization,
|
|
51
|
+
clientId: opts.clientId,
|
|
52
|
+
fetch: opts.fetch
|
|
53
|
+
});
|
|
54
|
+
return async function lumoAuth(req, res, next) {
|
|
55
|
+
if (!req.session) {
|
|
56
|
+
res.status(500).json({
|
|
57
|
+
error: "session_middleware_missing",
|
|
58
|
+
error_description: "lumoAuthMiddleware requires express-session (or compatible) to be mounted before it."
|
|
59
|
+
});
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const sessionState = req.session.__lumoAuth ?? {};
|
|
63
|
+
if (sessionState.user) {
|
|
64
|
+
req.user = sessionState.user;
|
|
65
|
+
}
|
|
66
|
+
const path = req.path ?? req.url.split("?")[0];
|
|
67
|
+
if (req.method === "GET" && path === `${prefix}/login`) {
|
|
68
|
+
await handleLogin(req, res, auth, prefix, scope, sessionState, postLoginRedirect);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (req.method === "GET" && path === `${prefix}/callback`) {
|
|
72
|
+
await handleCallback(req, res, auth, sessionState, opts.clientSecret);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if ((req.method === "GET" || req.method === "POST") && path === `${prefix}/logout`) {
|
|
76
|
+
await handleLogout(req, res, sessionState, postLogoutRedirect);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
next();
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
async function handleLogin(req, res, auth, prefix, scope, sessionState, defaultReturnTo) {
|
|
83
|
+
const redirectUri = absoluteUrl(req, `${prefix}/callback`);
|
|
84
|
+
const returnTo = sanitizeReturnTo(req.query.return_to, defaultReturnTo);
|
|
85
|
+
const flow = await auth.buildAuthorizationUrl({
|
|
86
|
+
redirectUri,
|
|
87
|
+
scope
|
|
88
|
+
});
|
|
89
|
+
sessionState.flow = {
|
|
90
|
+
codeVerifier: flow.codeVerifier,
|
|
91
|
+
state: flow.state,
|
|
92
|
+
redirectUri,
|
|
93
|
+
returnTo
|
|
94
|
+
};
|
|
95
|
+
saveSession(req, sessionState);
|
|
96
|
+
res.redirect(flow.url);
|
|
97
|
+
}
|
|
98
|
+
async function handleCallback(req, res, auth, sessionState, clientSecret) {
|
|
99
|
+
const code = stringQuery(req.query.code);
|
|
100
|
+
const state = stringQuery(req.query.state);
|
|
101
|
+
const oauthError = stringQuery(req.query.error);
|
|
102
|
+
if (oauthError) {
|
|
103
|
+
res.status(400).json({
|
|
104
|
+
error: oauthError,
|
|
105
|
+
error_description: stringQuery(req.query.error_description) ?? ""
|
|
106
|
+
});
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (!code || !state) {
|
|
110
|
+
res.status(400).json({ error: "invalid_request", error_description: "Missing code or state" });
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const flow = sessionState.flow;
|
|
114
|
+
if (!flow) {
|
|
115
|
+
res.status(400).json({ error: "invalid_request", error_description: "No login in progress" });
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (state !== flow.state) {
|
|
119
|
+
res.status(400).json({ error: "invalid_state", error_description: "CSRF state mismatch" });
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
const tokens = await auth.exchangeCodeForTokens({
|
|
124
|
+
code,
|
|
125
|
+
redirectUri: flow.redirectUri,
|
|
126
|
+
codeVerifier: flow.codeVerifier,
|
|
127
|
+
clientSecret
|
|
128
|
+
});
|
|
129
|
+
const user = await fetchUserInfo(auth, tokens.access_token);
|
|
130
|
+
sessionState.tokens = {
|
|
131
|
+
access_token: tokens.access_token,
|
|
132
|
+
refresh_token: tokens.refresh_token,
|
|
133
|
+
id_token: tokens.id_token,
|
|
134
|
+
token_type: tokens.token_type ?? "Bearer",
|
|
135
|
+
expires_at: nowSeconds() + (tokens.expires_in ?? 3600),
|
|
136
|
+
scope: tokens.scope
|
|
137
|
+
};
|
|
138
|
+
sessionState.user = user;
|
|
139
|
+
delete sessionState.flow;
|
|
140
|
+
regenerateSession(req);
|
|
141
|
+
saveSession(req, sessionState);
|
|
142
|
+
res.redirect(flow.returnTo);
|
|
143
|
+
} catch (err) {
|
|
144
|
+
const message = err instanceof import_shared.LumoAuthError ? err.message : "Token exchange failed";
|
|
145
|
+
const status = err instanceof import_shared.LumoAuthApiError ? err.statusCode ?? 502 : 502;
|
|
146
|
+
res.status(status).json({ error: "token_exchange_failed", error_description: message });
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
async function handleLogout(req, res, sessionState, postLogoutRedirect) {
|
|
150
|
+
delete sessionState.user;
|
|
151
|
+
delete sessionState.tokens;
|
|
152
|
+
delete sessionState.flow;
|
|
153
|
+
saveSession(req, sessionState);
|
|
154
|
+
res.redirect(postLogoutRedirect);
|
|
155
|
+
}
|
|
156
|
+
function requireAuth(options = {}) {
|
|
157
|
+
return async function requireAuthHandler(req, res, next) {
|
|
158
|
+
const user = req.user;
|
|
159
|
+
if (!user) {
|
|
160
|
+
res.status(options.unauthorizedStatus ?? 401).json({ error: "unauthenticated" });
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (options.scopes?.length) {
|
|
164
|
+
const session = req.session?.__lumoAuth ?? {};
|
|
165
|
+
const granted = (session.tokens?.scope ?? "").split(/\s+/).filter(Boolean);
|
|
166
|
+
const missing = options.scopes.filter((s) => !granted.includes(s));
|
|
167
|
+
if (missing.length) {
|
|
168
|
+
res.status(options.unauthorizedStatus ?? 403).json({ error: "insufficient_scope", error_description: `Missing: ${missing.join(", ")}` });
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (options.authorize) {
|
|
173
|
+
const ok = await options.authorize(user, req);
|
|
174
|
+
if (!ok) {
|
|
175
|
+
res.status(options.unauthorizedStatus ?? 403).json({ error: "forbidden" });
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
next();
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
async function fetchUserInfo(auth, accessToken) {
|
|
183
|
+
const info = await auth.getUserInfo(accessToken);
|
|
184
|
+
return { ...info };
|
|
185
|
+
}
|
|
186
|
+
function absoluteUrl(req, path) {
|
|
187
|
+
const reqWithProto = req;
|
|
188
|
+
const proto = reqWithProto.protocol ?? "https";
|
|
189
|
+
const host = reqWithProto.get?.("host") ?? "";
|
|
190
|
+
return `${proto}://${host}${path}`;
|
|
191
|
+
}
|
|
192
|
+
function sanitizeReturnTo(raw, fallback) {
|
|
193
|
+
if (typeof raw !== "string") return fallback;
|
|
194
|
+
if (!raw.startsWith("/") || raw.startsWith("//")) return fallback;
|
|
195
|
+
return raw;
|
|
196
|
+
}
|
|
197
|
+
function stringQuery(value) {
|
|
198
|
+
if (typeof value === "string") return value;
|
|
199
|
+
if (Array.isArray(value) && typeof value[0] === "string") return value[0];
|
|
200
|
+
return void 0;
|
|
201
|
+
}
|
|
202
|
+
function nowSeconds() {
|
|
203
|
+
return Math.floor(Date.now() / 1e3);
|
|
204
|
+
}
|
|
205
|
+
function saveSession(req, state) {
|
|
206
|
+
if (!req.session) return;
|
|
207
|
+
req.session.__lumoAuth = state;
|
|
208
|
+
}
|
|
209
|
+
function regenerateSession(req) {
|
|
210
|
+
const sess = req.session;
|
|
211
|
+
if (typeof sess?.regenerate === "function") {
|
|
212
|
+
sess.regenerate(() => {
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
217
|
+
0 && (module.exports = {
|
|
218
|
+
LumoAuthApiError,
|
|
219
|
+
LumoAuthApprovalDeniedError,
|
|
220
|
+
LumoAuthApprovalTimeoutError,
|
|
221
|
+
LumoAuthAuthError,
|
|
222
|
+
LumoAuthAuthenticationError,
|
|
223
|
+
LumoAuthBackend,
|
|
224
|
+
LumoAuthBudgetExceededError,
|
|
225
|
+
LumoAuthConfigError,
|
|
226
|
+
LumoAuthError,
|
|
227
|
+
LumoAuthNetworkError,
|
|
228
|
+
LumoAuthNotFoundError,
|
|
229
|
+
LumoAuthPermissionDeniedError,
|
|
230
|
+
LumoAuthRateLimitError,
|
|
231
|
+
LumoAuthValidationError,
|
|
232
|
+
lumoAuthMiddleware,
|
|
233
|
+
requireAuth
|
|
234
|
+
});
|
|
235
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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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,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
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import {
|
|
3
|
+
AuthModule,
|
|
4
|
+
LumoAuthError,
|
|
5
|
+
LumoAuthApiError
|
|
6
|
+
} from "@lumoauth/shared";
|
|
7
|
+
import {
|
|
8
|
+
LumoAuthBackend,
|
|
9
|
+
LumoAuthError as LumoAuthError2,
|
|
10
|
+
LumoAuthApiError as LumoAuthApiError2,
|
|
11
|
+
LumoAuthAuthenticationError,
|
|
12
|
+
LumoAuthAuthError,
|
|
13
|
+
LumoAuthPermissionDeniedError,
|
|
14
|
+
LumoAuthNotFoundError,
|
|
15
|
+
LumoAuthRateLimitError,
|
|
16
|
+
LumoAuthValidationError,
|
|
17
|
+
LumoAuthConfigError,
|
|
18
|
+
LumoAuthNetworkError,
|
|
19
|
+
LumoAuthApprovalDeniedError,
|
|
20
|
+
LumoAuthApprovalTimeoutError,
|
|
21
|
+
LumoAuthBudgetExceededError
|
|
22
|
+
} from "@lumoauth/backend";
|
|
23
|
+
function lumoAuthMiddleware(opts) {
|
|
24
|
+
const prefix = (opts.prefix ?? "/auth").replace(/\/+$/, "");
|
|
25
|
+
const postLoginRedirect = opts.postLoginRedirect ?? "/";
|
|
26
|
+
const postLogoutRedirect = opts.postLogoutRedirect ?? "/";
|
|
27
|
+
const scope = opts.scope ?? "openid profile email";
|
|
28
|
+
const auth = new AuthModule({
|
|
29
|
+
baseUrl: opts.baseUrl,
|
|
30
|
+
orgId: opts.organization,
|
|
31
|
+
clientId: opts.clientId,
|
|
32
|
+
fetch: opts.fetch
|
|
33
|
+
});
|
|
34
|
+
return async function lumoAuth(req, res, next) {
|
|
35
|
+
if (!req.session) {
|
|
36
|
+
res.status(500).json({
|
|
37
|
+
error: "session_middleware_missing",
|
|
38
|
+
error_description: "lumoAuthMiddleware requires express-session (or compatible) to be mounted before it."
|
|
39
|
+
});
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const sessionState = req.session.__lumoAuth ?? {};
|
|
43
|
+
if (sessionState.user) {
|
|
44
|
+
req.user = sessionState.user;
|
|
45
|
+
}
|
|
46
|
+
const path = req.path ?? req.url.split("?")[0];
|
|
47
|
+
if (req.method === "GET" && path === `${prefix}/login`) {
|
|
48
|
+
await handleLogin(req, res, auth, prefix, scope, sessionState, postLoginRedirect);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (req.method === "GET" && path === `${prefix}/callback`) {
|
|
52
|
+
await handleCallback(req, res, auth, sessionState, opts.clientSecret);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if ((req.method === "GET" || req.method === "POST") && path === `${prefix}/logout`) {
|
|
56
|
+
await handleLogout(req, res, sessionState, postLogoutRedirect);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
next();
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
async function handleLogin(req, res, auth, prefix, scope, sessionState, defaultReturnTo) {
|
|
63
|
+
const redirectUri = absoluteUrl(req, `${prefix}/callback`);
|
|
64
|
+
const returnTo = sanitizeReturnTo(req.query.return_to, defaultReturnTo);
|
|
65
|
+
const flow = await auth.buildAuthorizationUrl({
|
|
66
|
+
redirectUri,
|
|
67
|
+
scope
|
|
68
|
+
});
|
|
69
|
+
sessionState.flow = {
|
|
70
|
+
codeVerifier: flow.codeVerifier,
|
|
71
|
+
state: flow.state,
|
|
72
|
+
redirectUri,
|
|
73
|
+
returnTo
|
|
74
|
+
};
|
|
75
|
+
saveSession(req, sessionState);
|
|
76
|
+
res.redirect(flow.url);
|
|
77
|
+
}
|
|
78
|
+
async function handleCallback(req, res, auth, sessionState, clientSecret) {
|
|
79
|
+
const code = stringQuery(req.query.code);
|
|
80
|
+
const state = stringQuery(req.query.state);
|
|
81
|
+
const oauthError = stringQuery(req.query.error);
|
|
82
|
+
if (oauthError) {
|
|
83
|
+
res.status(400).json({
|
|
84
|
+
error: oauthError,
|
|
85
|
+
error_description: stringQuery(req.query.error_description) ?? ""
|
|
86
|
+
});
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (!code || !state) {
|
|
90
|
+
res.status(400).json({ error: "invalid_request", error_description: "Missing code or state" });
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const flow = sessionState.flow;
|
|
94
|
+
if (!flow) {
|
|
95
|
+
res.status(400).json({ error: "invalid_request", error_description: "No login in progress" });
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (state !== flow.state) {
|
|
99
|
+
res.status(400).json({ error: "invalid_state", error_description: "CSRF state mismatch" });
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
const tokens = await auth.exchangeCodeForTokens({
|
|
104
|
+
code,
|
|
105
|
+
redirectUri: flow.redirectUri,
|
|
106
|
+
codeVerifier: flow.codeVerifier,
|
|
107
|
+
clientSecret
|
|
108
|
+
});
|
|
109
|
+
const user = await fetchUserInfo(auth, tokens.access_token);
|
|
110
|
+
sessionState.tokens = {
|
|
111
|
+
access_token: tokens.access_token,
|
|
112
|
+
refresh_token: tokens.refresh_token,
|
|
113
|
+
id_token: tokens.id_token,
|
|
114
|
+
token_type: tokens.token_type ?? "Bearer",
|
|
115
|
+
expires_at: nowSeconds() + (tokens.expires_in ?? 3600),
|
|
116
|
+
scope: tokens.scope
|
|
117
|
+
};
|
|
118
|
+
sessionState.user = user;
|
|
119
|
+
delete sessionState.flow;
|
|
120
|
+
regenerateSession(req);
|
|
121
|
+
saveSession(req, sessionState);
|
|
122
|
+
res.redirect(flow.returnTo);
|
|
123
|
+
} catch (err) {
|
|
124
|
+
const message = err instanceof LumoAuthError ? err.message : "Token exchange failed";
|
|
125
|
+
const status = err instanceof LumoAuthApiError ? err.statusCode ?? 502 : 502;
|
|
126
|
+
res.status(status).json({ error: "token_exchange_failed", error_description: message });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async function handleLogout(req, res, sessionState, postLogoutRedirect) {
|
|
130
|
+
delete sessionState.user;
|
|
131
|
+
delete sessionState.tokens;
|
|
132
|
+
delete sessionState.flow;
|
|
133
|
+
saveSession(req, sessionState);
|
|
134
|
+
res.redirect(postLogoutRedirect);
|
|
135
|
+
}
|
|
136
|
+
function requireAuth(options = {}) {
|
|
137
|
+
return async function requireAuthHandler(req, res, next) {
|
|
138
|
+
const user = req.user;
|
|
139
|
+
if (!user) {
|
|
140
|
+
res.status(options.unauthorizedStatus ?? 401).json({ error: "unauthenticated" });
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (options.scopes?.length) {
|
|
144
|
+
const session = req.session?.__lumoAuth ?? {};
|
|
145
|
+
const granted = (session.tokens?.scope ?? "").split(/\s+/).filter(Boolean);
|
|
146
|
+
const missing = options.scopes.filter((s) => !granted.includes(s));
|
|
147
|
+
if (missing.length) {
|
|
148
|
+
res.status(options.unauthorizedStatus ?? 403).json({ error: "insufficient_scope", error_description: `Missing: ${missing.join(", ")}` });
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (options.authorize) {
|
|
153
|
+
const ok = await options.authorize(user, req);
|
|
154
|
+
if (!ok) {
|
|
155
|
+
res.status(options.unauthorizedStatus ?? 403).json({ error: "forbidden" });
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
next();
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
async function fetchUserInfo(auth, accessToken) {
|
|
163
|
+
const info = await auth.getUserInfo(accessToken);
|
|
164
|
+
return { ...info };
|
|
165
|
+
}
|
|
166
|
+
function absoluteUrl(req, path) {
|
|
167
|
+
const reqWithProto = req;
|
|
168
|
+
const proto = reqWithProto.protocol ?? "https";
|
|
169
|
+
const host = reqWithProto.get?.("host") ?? "";
|
|
170
|
+
return `${proto}://${host}${path}`;
|
|
171
|
+
}
|
|
172
|
+
function sanitizeReturnTo(raw, fallback) {
|
|
173
|
+
if (typeof raw !== "string") return fallback;
|
|
174
|
+
if (!raw.startsWith("/") || raw.startsWith("//")) return fallback;
|
|
175
|
+
return raw;
|
|
176
|
+
}
|
|
177
|
+
function stringQuery(value) {
|
|
178
|
+
if (typeof value === "string") return value;
|
|
179
|
+
if (Array.isArray(value) && typeof value[0] === "string") return value[0];
|
|
180
|
+
return void 0;
|
|
181
|
+
}
|
|
182
|
+
function nowSeconds() {
|
|
183
|
+
return Math.floor(Date.now() / 1e3);
|
|
184
|
+
}
|
|
185
|
+
function saveSession(req, state) {
|
|
186
|
+
if (!req.session) return;
|
|
187
|
+
req.session.__lumoAuth = state;
|
|
188
|
+
}
|
|
189
|
+
function regenerateSession(req) {
|
|
190
|
+
const sess = req.session;
|
|
191
|
+
if (typeof sess?.regenerate === "function") {
|
|
192
|
+
sess.regenerate(() => {
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
export {
|
|
197
|
+
LumoAuthApiError2 as LumoAuthApiError,
|
|
198
|
+
LumoAuthApprovalDeniedError,
|
|
199
|
+
LumoAuthApprovalTimeoutError,
|
|
200
|
+
LumoAuthAuthError,
|
|
201
|
+
LumoAuthAuthenticationError,
|
|
202
|
+
LumoAuthBackend,
|
|
203
|
+
LumoAuthBudgetExceededError,
|
|
204
|
+
LumoAuthConfigError,
|
|
205
|
+
LumoAuthError2 as LumoAuthError,
|
|
206
|
+
LumoAuthNetworkError,
|
|
207
|
+
LumoAuthNotFoundError,
|
|
208
|
+
LumoAuthPermissionDeniedError,
|
|
209
|
+
LumoAuthRateLimitError,
|
|
210
|
+
LumoAuthValidationError,
|
|
211
|
+
lumoAuthMiddleware,
|
|
212
|
+
requireAuth
|
|
213
|
+
};
|
|
214
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +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,iBAAAA;AAAA,EACA,oBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;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,WAAW;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,Q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AAS,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":["LumoAuthError","LumoAuthApiError"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@lumoauth/express",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Express middleware for LumoAuth \u2014 login, callback, and logout routes plus requireAuth().",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "LumoAuth",
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"access": "public",
|
|
9
|
+
"provenance": true
|
|
10
|
+
},
|
|
11
|
+
"main": "dist/index.js",
|
|
12
|
+
"module": "dist/index.mjs",
|
|
13
|
+
"types": "dist/index.d.ts",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"import": "./dist/index.mjs",
|
|
18
|
+
"require": "./dist/index.js"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist",
|
|
23
|
+
"README.md",
|
|
24
|
+
"LICENSE"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "tsup",
|
|
28
|
+
"dev": "tsup --watch",
|
|
29
|
+
"typecheck": "tsc --noEmit",
|
|
30
|
+
"prepublishOnly": "npm run build"
|
|
31
|
+
},
|
|
32
|
+
"keywords": [
|
|
33
|
+
"lumoauth",
|
|
34
|
+
"express",
|
|
35
|
+
"middleware"
|
|
36
|
+
],
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"@lumoauth/backend": "^1.0.0",
|
|
39
|
+
"@lumoauth/shared": "^1.0.0"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@types/node": "^20.19.43",
|
|
43
|
+
"tsup": "^8.0.0",
|
|
44
|
+
"typescript": "^5.5.0",
|
|
45
|
+
"@types/express": "^4.17.21",
|
|
46
|
+
"@types/express-session": "^1.18.0"
|
|
47
|
+
},
|
|
48
|
+
"engines": {
|
|
49
|
+
"node": ">=18.0.0"
|
|
50
|
+
},
|
|
51
|
+
"sideEffects": false,
|
|
52
|
+
"peerDependencies": {
|
|
53
|
+
"express": ">=4.18.0",
|
|
54
|
+
"express-session": ">=1.17.0"
|
|
55
|
+
}
|
|
56
|
+
}
|