@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 +21 -0
- package/README.md +328 -2
- package/dist/index.d.mts +137 -0
- package/dist/index.d.ts +137 -0
- package/dist/index.js +306 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +285 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +56 -5
package/dist/index.js
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
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
|
+
LumoAuthApprovalNotDeliveredError: () => import_backend.LumoAuthApprovalNotDeliveredError,
|
|
26
|
+
LumoAuthApprovalTimeoutError: () => import_backend.LumoAuthApprovalTimeoutError,
|
|
27
|
+
LumoAuthAuthError: () => import_backend.LumoAuthAuthError,
|
|
28
|
+
LumoAuthAuthenticationError: () => import_backend.LumoAuthAuthenticationError,
|
|
29
|
+
LumoAuthBackend: () => import_backend.LumoAuthBackend,
|
|
30
|
+
LumoAuthBudgetExceededError: () => import_backend.LumoAuthBudgetExceededError,
|
|
31
|
+
LumoAuthConfigError: () => import_backend.LumoAuthConfigError,
|
|
32
|
+
LumoAuthError: () => import_backend.LumoAuthError,
|
|
33
|
+
LumoAuthNetworkError: () => import_backend.LumoAuthNetworkError,
|
|
34
|
+
LumoAuthNotFoundError: () => import_backend.LumoAuthNotFoundError,
|
|
35
|
+
LumoAuthPermissionDeniedError: () => import_backend.LumoAuthPermissionDeniedError,
|
|
36
|
+
LumoAuthRateLimitError: () => import_backend.LumoAuthRateLimitError,
|
|
37
|
+
LumoAuthValidationError: () => import_backend.LumoAuthValidationError,
|
|
38
|
+
lumoAuthMiddleware: () => lumoAuthMiddleware,
|
|
39
|
+
requireAuth: () => requireAuth
|
|
40
|
+
});
|
|
41
|
+
module.exports = __toCommonJS(index_exports);
|
|
42
|
+
var import_shared = require("@lumoauth/shared");
|
|
43
|
+
var import_backend = require("@lumoauth/backend");
|
|
44
|
+
function lumoAuthMiddleware(opts) {
|
|
45
|
+
const prefix = (opts.prefix ?? "/auth").replace(/\/+$/, "");
|
|
46
|
+
const postLoginRedirect = opts.postLoginRedirect ?? "/";
|
|
47
|
+
const postLogoutRedirect = opts.postLogoutRedirect ?? "/";
|
|
48
|
+
const scope = opts.scope ?? "openid profile email";
|
|
49
|
+
const autoRefresh = opts.autoRefresh ?? true;
|
|
50
|
+
const endSessionOnLogout = opts.endSessionOnLogout ?? true;
|
|
51
|
+
const inflight = /* @__PURE__ */ new Map();
|
|
52
|
+
const refresh = (refreshToken) => {
|
|
53
|
+
let pending = inflight.get(refreshToken);
|
|
54
|
+
if (!pending) {
|
|
55
|
+
pending = auth.refreshToken(refreshToken, { clientSecret: opts.clientSecret }).finally(() => inflight.delete(refreshToken));
|
|
56
|
+
inflight.set(refreshToken, pending);
|
|
57
|
+
}
|
|
58
|
+
return pending;
|
|
59
|
+
};
|
|
60
|
+
const auth = new import_shared.AuthModule({
|
|
61
|
+
baseUrl: opts.baseUrl,
|
|
62
|
+
orgId: opts.organization,
|
|
63
|
+
clientId: opts.clientId,
|
|
64
|
+
fetch: opts.fetch
|
|
65
|
+
});
|
|
66
|
+
return async function lumoAuth(req, res, next) {
|
|
67
|
+
if (!req.session) {
|
|
68
|
+
res.status(500).json({
|
|
69
|
+
error: "session_middleware_missing",
|
|
70
|
+
error_description: "lumoAuthMiddleware requires express-session (or compatible) to be mounted before it."
|
|
71
|
+
});
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const sessionState = req.session.__lumoAuth ?? {};
|
|
75
|
+
const path = req.path ?? req.url.split("?")[0];
|
|
76
|
+
const isAuthRoute = path === `${prefix}/login` || path === `${prefix}/callback` || path === `${prefix}/logout`;
|
|
77
|
+
if (autoRefresh && !isAuthRoute) {
|
|
78
|
+
await refreshIfNeeded(req, sessionState, refresh);
|
|
79
|
+
}
|
|
80
|
+
if (sessionState.user) {
|
|
81
|
+
req.user = sessionState.user;
|
|
82
|
+
}
|
|
83
|
+
if (req.method === "GET" && path === `${prefix}/login`) {
|
|
84
|
+
await handleLogin(req, res, auth, prefix, scope, sessionState, postLoginRedirect);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (req.method === "GET" && path === `${prefix}/callback`) {
|
|
88
|
+
await handleCallback(req, res, auth, sessionState, opts.clientSecret);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
if ((req.method === "GET" || req.method === "POST") && path === `${prefix}/logout`) {
|
|
92
|
+
await handleLogout(req, res, auth, sessionState, postLogoutRedirect, {
|
|
93
|
+
endSession: endSessionOnLogout,
|
|
94
|
+
clientSecret: opts.clientSecret
|
|
95
|
+
});
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
next();
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
async function handleLogin(req, res, auth, prefix, scope, sessionState, defaultReturnTo) {
|
|
102
|
+
const redirectUri = absoluteUrl(req, `${prefix}/callback`);
|
|
103
|
+
const returnTo = sanitizeReturnTo(req.query.return_to, defaultReturnTo);
|
|
104
|
+
const flow = await auth.buildAuthorizationUrl({
|
|
105
|
+
redirectUri,
|
|
106
|
+
scope
|
|
107
|
+
});
|
|
108
|
+
sessionState.flow = {
|
|
109
|
+
codeVerifier: flow.codeVerifier,
|
|
110
|
+
state: flow.state,
|
|
111
|
+
redirectUri,
|
|
112
|
+
returnTo
|
|
113
|
+
};
|
|
114
|
+
saveSession(req, sessionState);
|
|
115
|
+
res.redirect(flow.url);
|
|
116
|
+
}
|
|
117
|
+
async function handleCallback(req, res, auth, sessionState, clientSecret) {
|
|
118
|
+
const code = stringQuery(req.query.code);
|
|
119
|
+
const state = stringQuery(req.query.state);
|
|
120
|
+
const oauthError = stringQuery(req.query.error);
|
|
121
|
+
if (oauthError) {
|
|
122
|
+
res.status(400).json({
|
|
123
|
+
error: oauthError,
|
|
124
|
+
error_description: stringQuery(req.query.error_description) ?? ""
|
|
125
|
+
});
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (!code || !state) {
|
|
129
|
+
res.status(400).json({ error: "invalid_request", error_description: "Missing code or state" });
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const flow = sessionState.flow;
|
|
133
|
+
if (!flow) {
|
|
134
|
+
res.status(400).json({ error: "invalid_request", error_description: "No login in progress" });
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (state !== flow.state) {
|
|
138
|
+
res.status(400).json({ error: "invalid_state", error_description: "CSRF state mismatch" });
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
try {
|
|
142
|
+
const tokens = await auth.exchangeCodeForTokens({
|
|
143
|
+
code,
|
|
144
|
+
redirectUri: flow.redirectUri,
|
|
145
|
+
codeVerifier: flow.codeVerifier,
|
|
146
|
+
clientSecret
|
|
147
|
+
});
|
|
148
|
+
const user = await fetchUserInfo(auth, tokens.access_token);
|
|
149
|
+
sessionState.tokens = {
|
|
150
|
+
access_token: tokens.access_token,
|
|
151
|
+
refresh_token: tokens.refresh_token,
|
|
152
|
+
id_token: tokens.id_token,
|
|
153
|
+
token_type: tokens.token_type ?? "Bearer",
|
|
154
|
+
expires_at: nowSeconds() + (tokens.expires_in ?? 3600),
|
|
155
|
+
scope: tokens.scope
|
|
156
|
+
};
|
|
157
|
+
sessionState.user = user;
|
|
158
|
+
delete sessionState.flow;
|
|
159
|
+
regenerateSession(req);
|
|
160
|
+
saveSession(req, sessionState);
|
|
161
|
+
res.redirect(flow.returnTo);
|
|
162
|
+
} catch (err) {
|
|
163
|
+
const message = err instanceof import_shared.LumoAuthError ? err.message : "Token exchange failed";
|
|
164
|
+
const status = err instanceof import_shared.LumoAuthApiError ? err.statusCode ?? 502 : 502;
|
|
165
|
+
res.status(status).json({ error: "token_exchange_failed", error_description: message });
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
async function handleLogout(req, res, auth, sessionState, postLogoutRedirect, options) {
|
|
169
|
+
const tokens = sessionState.tokens;
|
|
170
|
+
delete sessionState.user;
|
|
171
|
+
delete sessionState.tokens;
|
|
172
|
+
delete sessionState.flow;
|
|
173
|
+
saveSession(req, sessionState);
|
|
174
|
+
req.user = void 0;
|
|
175
|
+
if (!options.endSession) {
|
|
176
|
+
res.redirect(postLogoutRedirect);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const revocable = tokens?.refresh_token ?? tokens?.access_token;
|
|
180
|
+
if (revocable) {
|
|
181
|
+
try {
|
|
182
|
+
await auth.revokeToken(revocable, void 0, {
|
|
183
|
+
clientSecret: options.clientSecret,
|
|
184
|
+
tokenTypeHint: tokens?.refresh_token ? "refresh_token" : "access_token"
|
|
185
|
+
});
|
|
186
|
+
} catch {
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (!isAbsoluteHttpUrl(postLogoutRedirect)) {
|
|
190
|
+
res.redirect(postLogoutRedirect);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
res.redirect(
|
|
194
|
+
auth.buildEndSessionUrl({
|
|
195
|
+
idTokenHint: tokens?.id_token,
|
|
196
|
+
postLogoutRedirectUri: postLogoutRedirect
|
|
197
|
+
})
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
var REFRESH_LEEWAY_SECONDS = 60;
|
|
201
|
+
async function refreshIfNeeded(req, sessionState, refresh) {
|
|
202
|
+
const tokens = sessionState.tokens;
|
|
203
|
+
if (!tokens?.refresh_token) return;
|
|
204
|
+
if (tokens.expires_at - nowSeconds() >= REFRESH_LEEWAY_SECONDS) return;
|
|
205
|
+
try {
|
|
206
|
+
const fresh = await refresh(tokens.refresh_token);
|
|
207
|
+
sessionState.tokens = {
|
|
208
|
+
access_token: fresh.access_token,
|
|
209
|
+
// Keep the old refresh token when the server does not rotate it.
|
|
210
|
+
refresh_token: fresh.refresh_token ?? tokens.refresh_token,
|
|
211
|
+
id_token: fresh.id_token ?? tokens.id_token,
|
|
212
|
+
token_type: fresh.token_type ?? tokens.token_type ?? "Bearer",
|
|
213
|
+
expires_at: nowSeconds() + (fresh.expires_in ?? 3600),
|
|
214
|
+
scope: fresh.scope ?? tokens.scope
|
|
215
|
+
};
|
|
216
|
+
} catch {
|
|
217
|
+
delete sessionState.user;
|
|
218
|
+
delete sessionState.tokens;
|
|
219
|
+
req.user = void 0;
|
|
220
|
+
}
|
|
221
|
+
saveSession(req, sessionState);
|
|
222
|
+
}
|
|
223
|
+
function isAbsoluteHttpUrl(value) {
|
|
224
|
+
return /^https?:\/\//i.test(value);
|
|
225
|
+
}
|
|
226
|
+
function requireAuth(options = {}) {
|
|
227
|
+
return async function requireAuthHandler(req, res, next) {
|
|
228
|
+
const user = req.user;
|
|
229
|
+
if (!user) {
|
|
230
|
+
res.status(options.unauthorizedStatus ?? 401).json({ error: "unauthenticated" });
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
if (options.scopes?.length) {
|
|
234
|
+
const session = req.session?.__lumoAuth ?? {};
|
|
235
|
+
const granted = (session.tokens?.scope ?? "").split(/\s+/).filter(Boolean);
|
|
236
|
+
const missing = options.scopes.filter((s) => !granted.includes(s));
|
|
237
|
+
if (missing.length) {
|
|
238
|
+
res.status(options.unauthorizedStatus ?? 403).json({ error: "insufficient_scope", error_description: `Missing: ${missing.join(", ")}` });
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (options.authorize) {
|
|
243
|
+
const ok = await options.authorize(user, req);
|
|
244
|
+
if (!ok) {
|
|
245
|
+
res.status(options.unauthorizedStatus ?? 403).json({ error: "forbidden" });
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
next();
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
async function fetchUserInfo(auth, accessToken) {
|
|
253
|
+
const info = await auth.getUserInfo(accessToken);
|
|
254
|
+
return { ...info };
|
|
255
|
+
}
|
|
256
|
+
function absoluteUrl(req, path) {
|
|
257
|
+
const reqWithProto = req;
|
|
258
|
+
const proto = reqWithProto.protocol ?? "https";
|
|
259
|
+
const host = reqWithProto.get?.("host") ?? "";
|
|
260
|
+
return `${proto}://${host}${path}`;
|
|
261
|
+
}
|
|
262
|
+
function sanitizeReturnTo(raw, fallback) {
|
|
263
|
+
if (typeof raw !== "string") return fallback;
|
|
264
|
+
if (!raw.startsWith("/") || raw.startsWith("//")) return fallback;
|
|
265
|
+
return raw;
|
|
266
|
+
}
|
|
267
|
+
function stringQuery(value) {
|
|
268
|
+
if (typeof value === "string") return value;
|
|
269
|
+
if (Array.isArray(value) && typeof value[0] === "string") return value[0];
|
|
270
|
+
return void 0;
|
|
271
|
+
}
|
|
272
|
+
function nowSeconds() {
|
|
273
|
+
return Math.floor(Date.now() / 1e3);
|
|
274
|
+
}
|
|
275
|
+
function saveSession(req, state) {
|
|
276
|
+
if (!req.session) return;
|
|
277
|
+
req.session.__lumoAuth = state;
|
|
278
|
+
}
|
|
279
|
+
function regenerateSession(req) {
|
|
280
|
+
const sess = req.session;
|
|
281
|
+
if (typeof sess?.regenerate === "function") {
|
|
282
|
+
sess.regenerate(() => {
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
287
|
+
0 && (module.exports = {
|
|
288
|
+
LumoAuthApiError,
|
|
289
|
+
LumoAuthApprovalDeniedError,
|
|
290
|
+
LumoAuthApprovalNotDeliveredError,
|
|
291
|
+
LumoAuthApprovalTimeoutError,
|
|
292
|
+
LumoAuthAuthError,
|
|
293
|
+
LumoAuthAuthenticationError,
|
|
294
|
+
LumoAuthBackend,
|
|
295
|
+
LumoAuthBudgetExceededError,
|
|
296
|
+
LumoAuthConfigError,
|
|
297
|
+
LumoAuthError,
|
|
298
|
+
LumoAuthNetworkError,
|
|
299
|
+
LumoAuthNotFoundError,
|
|
300
|
+
LumoAuthPermissionDeniedError,
|
|
301
|
+
LumoAuthRateLimitError,
|
|
302
|
+
LumoAuthValidationError,
|
|
303
|
+
lumoAuthMiddleware,
|
|
304
|
+
requireAuth
|
|
305
|
+
});
|
|
306
|
+
//# 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 LumoAuthApprovalNotDeliveredError,\n LumoAuthBudgetExceededError,\n} from '@lumoauth/backend';\n\n// Express types are loose to avoid a direct dependency on @types/express —\n// callers bring their own types. We only need the subset we use.\ntype Req = {\n url: string;\n path?: string;\n method?: string;\n query: Record<string, string | string[] | undefined>;\n session?: Record<string, unknown> & {\n __lumoAuth?: LumoAuthSessionState;\n };\n user?: SessionUser | undefined;\n // express-style helpers we touch\n [key: string]: unknown;\n};\n\ntype Res = {\n redirect(url: string): unknown;\n status(code: number): Res;\n json(payload: unknown): unknown;\n send(payload: unknown): unknown;\n setHeader(name: string, value: string): unknown;\n};\n\ntype Next = (err?: unknown) => void;\n\n/**\n * Structural match for express's `RequestHandler`. The exported middleware\n * factories are annotated with this so `app.use(lumoAuthMiddleware(...))` and\n * `app.get(path, requireAuth(), handler)` typecheck for TypeScript consumers\n * without this package taking a hard dependency on `@types/express`. Express's\n * own `Request`/`Response` are assignable to `any`, so the handler is accepted\n * by `app.use()`/`app.get()`/`app.METHOD()` overloads.\n */\nexport type LumoAuthRequestHandler = (\n req: any, // eslint-disable-line @typescript-eslint/no-explicit-any\n res: any, // eslint-disable-line @typescript-eslint/no-explicit-any\n next: (err?: unknown) => void,\n) => void | Promise<void>;\n\ndeclare global {\n // Augment express's Request so `req.user` is typed for consumers using\n // lumoAuthMiddleware(). Merges with @types/express when present; harmless\n // (creates the namespace) otherwise.\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n user?: SessionUser;\n }\n }\n}\n\nexport interface LumoAuthMiddlewareOptions {\n /** e.g. \"https://app.lumoauth.dev\" */\n baseUrl: string;\n /** The tenant slug that owns the OAuth client. */\n organization: string;\n /** OAuth client id registered for this app. */\n clientId: string;\n /**\n * Confidential clients require a secret on the token exchange. Public\n * (browser-facing) clients should omit this and rely on PKCE.\n */\n clientSecret?: string;\n /**\n * Path under which the three auth routes mount. Default: `/auth`.\n * Resulting routes: `/auth/login`, `/auth/callback`, `/auth/logout`.\n */\n prefix?: string;\n /**\n * Where to redirect the user after sign-in. Default: `/`.\n */\n postLoginRedirect?: string;\n /**\n * Where to redirect the user after sign-out. Default: `/`.\n *\n * Use an absolute URL (for example `https://app.example.com/`) that is\n * registered as a post-logout redirect URI on the OAuth client. Then\n * sign-out also ends the LumoAuth session (see `endSessionOnLogout`). A\n * relative path only clears the local session.\n */\n postLogoutRedirect?: string;\n /**\n * Refresh the session's access token when it expires in less than 60\n * seconds and a refresh token is stored. When the refresh fails, the\n * request is treated as signed out. Default: `true`.\n */\n autoRefresh?: boolean;\n /**\n * On sign-out, revoke the refresh token (RFC 7009) and redirect through\n * the OIDC end-session endpoint, so the LumoAuth session ends too. The\n * end-session step needs an absolute `postLogoutRedirect`. Set `false` to\n * only clear the local session. Default: `true`.\n */\n endSessionOnLogout?: boolean;\n /**\n * OAuth scopes to request. Default: `'openid profile email'`.\n */\n scope?: string;\n /**\n * Optional fetch override (for tests, instrumentation, custom proxies).\n */\n fetch?: typeof globalThis.fetch;\n}\n\nexport interface SessionUser {\n sub: string;\n email?: string;\n email_verified?: boolean;\n name?: string;\n picture?: string;\n [key: string]: unknown;\n}\n\ninterface LumoAuthSessionState {\n flow?: {\n codeVerifier: string;\n state: string;\n redirectUri: string;\n returnTo: string;\n };\n tokens?: {\n access_token: string;\n refresh_token?: string;\n id_token?: string;\n token_type: string;\n expires_at: number; // epoch seconds\n scope?: string;\n };\n user?: SessionUser;\n}\n\nexport interface RequireAuthOptions {\n /** Optional list of scopes that must all be present in the session token. */\n scopes?: string[];\n /**\n * Hook for programmatic checks (e.g. role / permission lookup against the\n * AuthorizationModule). Return false to deny.\n */\n authorize?: (user: SessionUser, req: Req) => boolean | Promise<boolean>;\n /**\n * Status code to return when unauthorized. Default 401 for missing user,\n * 403 for an `authorize` hook that returns false.\n */\n unauthorizedStatus?: number;\n}\n\n/**\n * Mount the LumoAuth Express middleware. Call this once on the app —\n * subsequent requests will:\n *\n * 1. Hit the three auth routes (login/callback/logout) under the prefix.\n * 2. Populate `req.user` from the session for every other request.\n */\nexport function lumoAuthMiddleware(opts: LumoAuthMiddlewareOptions): LumoAuthRequestHandler {\n const prefix = (opts.prefix ?? '/auth').replace(/\\/+$/, '');\n const postLoginRedirect = opts.postLoginRedirect ?? '/';\n const postLogoutRedirect = opts.postLogoutRedirect ?? '/';\n const scope = opts.scope ?? 'openid profile email';\n const autoRefresh = opts.autoRefresh ?? true;\n const endSessionOnLogout = opts.endSessionOnLogout ?? true;\n\n // One refresh per refresh token at a time. Parallel requests on the same\n // session share it, so a rotating refresh token is redeemed only once.\n const inflight = new Map<string, Promise<TokenResponse>>();\n const refresh = (refreshToken: string): Promise<TokenResponse> => {\n let pending = inflight.get(refreshToken);\n if (!pending) {\n pending = auth\n .refreshToken(refreshToken, { clientSecret: opts.clientSecret })\n .finally(() => inflight.delete(refreshToken));\n inflight.set(refreshToken, pending);\n }\n return pending;\n };\n\n const auth = new AuthModule({\n baseUrl: opts.baseUrl,\n orgId: opts.organization,\n clientId: opts.clientId,\n fetch: opts.fetch,\n });\n\n // The host app is expected to mount this middleware once on app.use(),\n // so it runs on EVERY request. We hand-route the three auth paths and\n // pass everything else through after attaching `req.user`.\n return async function lumoAuth(req: Req, res: Res, next: Next): Promise<void> {\n if (!req.session) {\n // Hard fail with a clear message — silently letting requests through\n // when the host forgot to mount express-session would mask bugs at\n // the moment users try to sign in.\n res.status(500).json({\n error: 'session_middleware_missing',\n error_description:\n 'lumoAuthMiddleware requires express-session (or compatible) to be mounted before it.',\n });\n return;\n }\n\n const sessionState: LumoAuthSessionState = (req.session.__lumoAuth ?? {}) as LumoAuthSessionState;\n const path = req.path ?? req.url.split('?')[0];\n const isAuthRoute =\n path === `${prefix}/login` || path === `${prefix}/callback` || path === `${prefix}/logout`;\n\n // Refresh a token that is about to expire before anything reads it.\n if (autoRefresh && !isAuthRoute) {\n await refreshIfNeeded(req, sessionState, refresh);\n }\n\n // Restore `req.user` from session so downstream handlers always see it.\n if (sessionState.user) {\n req.user = sessionState.user;\n }\n\n if (req.method === 'GET' && path === `${prefix}/login`) {\n await handleLogin(req, res, auth, prefix, scope, sessionState, postLoginRedirect);\n return;\n }\n if (req.method === 'GET' && path === `${prefix}/callback`) {\n await handleCallback(req, res, auth, sessionState, opts.clientSecret);\n return;\n }\n if (\n (req.method === 'GET' || req.method === 'POST') &&\n path === `${prefix}/logout`\n ) {\n await handleLogout(req, res, auth, sessionState, postLogoutRedirect, {\n endSession: endSessionOnLogout,\n clientSecret: opts.clientSecret,\n });\n return;\n }\n\n next();\n };\n}\n\nasync function handleLogin(\n req: Req,\n res: Res,\n auth: AuthModule,\n prefix: string,\n scope: string,\n sessionState: LumoAuthSessionState,\n defaultReturnTo: string,\n): Promise<void> {\n const redirectUri = absoluteUrl(req, `${prefix}/callback`);\n const returnTo = sanitizeReturnTo(req.query.return_to, defaultReturnTo);\n\n const flow = await auth.buildAuthorizationUrl({\n redirectUri,\n scope,\n });\n\n // Persist what we'll need on callback. SameSite session cookie is the\n // canonical store; never reflect any of this in the URL.\n sessionState.flow = {\n codeVerifier: flow.codeVerifier,\n state: flow.state,\n redirectUri,\n returnTo,\n };\n saveSession(req, sessionState);\n\n res.redirect(flow.url);\n}\n\nasync function handleCallback(\n req: Req,\n res: Res,\n auth: AuthModule,\n sessionState: LumoAuthSessionState,\n clientSecret: string | undefined,\n): Promise<void> {\n const code = stringQuery(req.query.code);\n const state = stringQuery(req.query.state);\n const oauthError = stringQuery(req.query.error);\n\n if (oauthError) {\n res.status(400).json({\n error: oauthError,\n error_description: stringQuery(req.query.error_description) ?? '',\n });\n return;\n }\n if (!code || !state) {\n res.status(400).json({ error: 'invalid_request', error_description: 'Missing code or state' });\n return;\n }\n const flow = sessionState.flow;\n if (!flow) {\n res.status(400).json({ error: 'invalid_request', error_description: 'No login in progress' });\n return;\n }\n if (state !== flow.state) {\n res.status(400).json({ error: 'invalid_state', error_description: 'CSRF state mismatch' });\n return;\n }\n\n try {\n const tokens: TokenResponse = await auth.exchangeCodeForTokens({\n code,\n redirectUri: flow.redirectUri,\n codeVerifier: flow.codeVerifier,\n clientSecret,\n });\n\n const user = await fetchUserInfo(auth, tokens.access_token);\n\n sessionState.tokens = {\n access_token: tokens.access_token,\n refresh_token: tokens.refresh_token,\n id_token: tokens.id_token,\n token_type: tokens.token_type ?? 'Bearer',\n expires_at: nowSeconds() + (tokens.expires_in ?? 3600),\n scope: tokens.scope,\n };\n sessionState.user = user;\n delete sessionState.flow;\n\n // Migrate the session id on auth — defends against fixation attacks.\n regenerateSession(req);\n saveSession(req, sessionState);\n\n res.redirect(flow.returnTo);\n } catch (err) {\n const message = err instanceof LumoAuthError ? err.message : 'Token exchange failed';\n const status =\n err instanceof LumoAuthApiError ? err.statusCode ?? 502 : 502;\n res.status(status).json({ error: 'token_exchange_failed', error_description: message });\n }\n}\n\nasync function handleLogout(\n req: Req,\n res: Res,\n auth: AuthModule,\n sessionState: LumoAuthSessionState,\n postLogoutRedirect: string,\n options: { endSession: boolean; clientSecret?: string },\n): Promise<void> {\n const tokens = sessionState.tokens;\n\n // Wipe LumoAuth-specific state. We DON'T destroy the whole session\n // because the host app may store unrelated data on it. Hosts that want\n // a hard logout should call `req.session.destroy()` themselves.\n delete sessionState.user;\n delete sessionState.tokens;\n delete sessionState.flow;\n saveSession(req, sessionState);\n req.user = undefined;\n\n if (!options.endSession) {\n res.redirect(postLogoutRedirect);\n return;\n }\n\n // Revoke the refresh token (this also revokes the access tokens issued\n // with it). Best-effort: a failure must not block sign-out.\n const revocable = tokens?.refresh_token ?? tokens?.access_token;\n if (revocable) {\n try {\n await auth.revokeToken(revocable, undefined, {\n clientSecret: options.clientSecret,\n tokenTypeHint: tokens?.refresh_token ? 'refresh_token' : 'access_token',\n });\n } catch {\n // ignored\n }\n }\n\n // End the LumoAuth session too. Otherwise the next /authorize signs the\n // user straight back in. The end-session endpoint needs an absolute\n // post-logout redirect URI, so a relative one keeps the local redirect.\n if (!isAbsoluteHttpUrl(postLogoutRedirect)) {\n res.redirect(postLogoutRedirect);\n return;\n }\n res.redirect(\n auth.buildEndSessionUrl({\n idTokenHint: tokens?.id_token,\n postLogoutRedirectUri: postLogoutRedirect,\n }),\n );\n}\n\n/** Seconds before expiry at which the access token is refreshed. */\nconst REFRESH_LEEWAY_SECONDS = 60;\n\nasync function refreshIfNeeded(\n req: Req,\n sessionState: LumoAuthSessionState,\n refresh: (refreshToken: string) => Promise<TokenResponse>,\n): Promise<void> {\n const tokens = sessionState.tokens;\n if (!tokens?.refresh_token) return;\n if (tokens.expires_at - nowSeconds() >= REFRESH_LEEWAY_SECONDS) return;\n\n try {\n const fresh = await refresh(tokens.refresh_token);\n sessionState.tokens = {\n access_token: fresh.access_token,\n // Keep the old refresh token when the server does not rotate it.\n refresh_token: fresh.refresh_token ?? tokens.refresh_token,\n id_token: fresh.id_token ?? tokens.id_token,\n token_type: fresh.token_type ?? tokens.token_type ?? 'Bearer',\n expires_at: nowSeconds() + (fresh.expires_in ?? 3600),\n scope: fresh.scope ?? tokens.scope,\n };\n } catch {\n // The refresh token is no longer good: treat the request as signed out.\n delete sessionState.user;\n delete sessionState.tokens;\n req.user = undefined;\n }\n saveSession(req, sessionState);\n}\n\nfunction isAbsoluteHttpUrl(value: string): boolean {\n return /^https?:\\/\\//i.test(value);\n}\n\n/**\n * Gate handler that requires a logged-in `req.user`. Combine with optional\n * scope / authorize hooks for finer-grained access control.\n */\nexport function requireAuth(options: RequireAuthOptions = {}): LumoAuthRequestHandler {\n return async function requireAuthHandler(req: Req, res: Res, next: Next): Promise<void> {\n const user = req.user;\n if (!user) {\n res.status(options.unauthorizedStatus ?? 401).json({ error: 'unauthenticated' });\n return;\n }\n\n if (options.scopes?.length) {\n const session = (req.session?.__lumoAuth ?? {}) as LumoAuthSessionState;\n const granted = (session.tokens?.scope ?? '').split(/\\s+/).filter(Boolean);\n const missing = options.scopes.filter((s) => !granted.includes(s));\n if (missing.length) {\n res\n .status(options.unauthorizedStatus ?? 403)\n .json({ error: 'insufficient_scope', error_description: `Missing: ${missing.join(', ')}` });\n return;\n }\n }\n\n if (options.authorize) {\n const ok = await options.authorize(user, req);\n if (!ok) {\n res.status(options.unauthorizedStatus ?? 403).json({ error: 'forbidden' });\n return;\n }\n }\n\n next();\n };\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────\n\nasync function fetchUserInfo(auth: AuthModule, accessToken: string): Promise<SessionUser> {\n // We hit the OIDC `/userinfo` endpoint. AuthModule exposes `getUserInfo`\n // which is the canonical wrapper.\n const info: UserInfo = await auth.getUserInfo(accessToken);\n return { ...info } as SessionUser;\n}\n\nfunction absoluteUrl(req: Req, path: string): string {\n // Honour standard reverse-proxy headers when present so the redirect URI\n // matches what the registered OAuth client allows. The host app is\n // expected to set `app.set('trust proxy', true)` if behind one.\n const reqWithProto = req as Req & { protocol?: string; get?: (h: string) => string | undefined };\n const proto = reqWithProto.protocol ?? 'https';\n const host = reqWithProto.get?.('host') ?? '';\n return `${proto}://${host}${path}`;\n}\n\nfunction sanitizeReturnTo(raw: unknown, fallback: string): string {\n // Open-redirect defence: only allow same-origin paths beginning with `/`\n // and not starting with `//` (protocol-relative).\n if (typeof raw !== 'string') return fallback;\n if (!raw.startsWith('/') || raw.startsWith('//')) return fallback;\n return raw;\n}\n\nfunction stringQuery(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (Array.isArray(value) && typeof value[0] === 'string') return value[0];\n return undefined;\n}\n\nfunction nowSeconds(): number {\n return Math.floor(Date.now() / 1000);\n}\n\nfunction saveSession(req: Req, state: LumoAuthSessionState): void {\n if (!req.session) return;\n req.session.__lumoAuth = state;\n // express-session writes on response end; we don't force a flush here.\n}\n\nfunction regenerateSession(req: Req): void {\n // express-session exposes `regenerate(cb)` — call it if available so we\n // get a fresh session id post-auth (mitigates session fixation).\n const sess = req.session as unknown as { regenerate?: (cb: (err?: unknown) => void) => void };\n if (typeof sess?.regenerate === 'function') {\n // Synchronous-style usage; we don't await because express-session's\n // regenerate is callback-based and most apps don't need the new id\n // until the next response. The session.save() that express-session\n // calls on res.end() will pick up the new state.\n sess.regenerate(() => {});\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmBA,oBAMO;AAKP,qBAiBO;AA2JA,SAAS,mBAAmB,MAAyD;AAC1F,QAAM,UAAU,KAAK,UAAU,SAAS,QAAQ,QAAQ,EAAE;AAC1D,QAAM,oBAAoB,KAAK,qBAAqB;AACpD,QAAM,qBAAqB,KAAK,sBAAsB;AACtD,QAAM,QAAQ,KAAK,SAAS;AAC5B,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,qBAAqB,KAAK,sBAAsB;AAItD,QAAM,WAAW,oBAAI,IAAoC;AACzD,QAAM,UAAU,CAAC,iBAAiD;AAChE,QAAI,UAAU,SAAS,IAAI,YAAY;AACvC,QAAI,CAAC,SAAS;AACZ,gBAAU,KACP,aAAa,cAAc,EAAE,cAAc,KAAK,aAAa,CAAC,EAC9D,QAAQ,MAAM,S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W,MAAM;AAAA,IAAC,CAAC;AAAA,EAC1B;AACF;","names":[]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
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
|
+
LumoAuthApprovalNotDeliveredError,
|
|
22
|
+
LumoAuthBudgetExceededError
|
|
23
|
+
} from "@lumoauth/backend";
|
|
24
|
+
function lumoAuthMiddleware(opts) {
|
|
25
|
+
const prefix = (opts.prefix ?? "/auth").replace(/\/+$/, "");
|
|
26
|
+
const postLoginRedirect = opts.postLoginRedirect ?? "/";
|
|
27
|
+
const postLogoutRedirect = opts.postLogoutRedirect ?? "/";
|
|
28
|
+
const scope = opts.scope ?? "openid profile email";
|
|
29
|
+
const autoRefresh = opts.autoRefresh ?? true;
|
|
30
|
+
const endSessionOnLogout = opts.endSessionOnLogout ?? true;
|
|
31
|
+
const inflight = /* @__PURE__ */ new Map();
|
|
32
|
+
const refresh = (refreshToken) => {
|
|
33
|
+
let pending = inflight.get(refreshToken);
|
|
34
|
+
if (!pending) {
|
|
35
|
+
pending = auth.refreshToken(refreshToken, { clientSecret: opts.clientSecret }).finally(() => inflight.delete(refreshToken));
|
|
36
|
+
inflight.set(refreshToken, pending);
|
|
37
|
+
}
|
|
38
|
+
return pending;
|
|
39
|
+
};
|
|
40
|
+
const auth = new AuthModule({
|
|
41
|
+
baseUrl: opts.baseUrl,
|
|
42
|
+
orgId: opts.organization,
|
|
43
|
+
clientId: opts.clientId,
|
|
44
|
+
fetch: opts.fetch
|
|
45
|
+
});
|
|
46
|
+
return async function lumoAuth(req, res, next) {
|
|
47
|
+
if (!req.session) {
|
|
48
|
+
res.status(500).json({
|
|
49
|
+
error: "session_middleware_missing",
|
|
50
|
+
error_description: "lumoAuthMiddleware requires express-session (or compatible) to be mounted before it."
|
|
51
|
+
});
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const sessionState = req.session.__lumoAuth ?? {};
|
|
55
|
+
const path = req.path ?? req.url.split("?")[0];
|
|
56
|
+
const isAuthRoute = path === `${prefix}/login` || path === `${prefix}/callback` || path === `${prefix}/logout`;
|
|
57
|
+
if (autoRefresh && !isAuthRoute) {
|
|
58
|
+
await refreshIfNeeded(req, sessionState, refresh);
|
|
59
|
+
}
|
|
60
|
+
if (sessionState.user) {
|
|
61
|
+
req.user = sessionState.user;
|
|
62
|
+
}
|
|
63
|
+
if (req.method === "GET" && path === `${prefix}/login`) {
|
|
64
|
+
await handleLogin(req, res, auth, prefix, scope, sessionState, postLoginRedirect);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (req.method === "GET" && path === `${prefix}/callback`) {
|
|
68
|
+
await handleCallback(req, res, auth, sessionState, opts.clientSecret);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if ((req.method === "GET" || req.method === "POST") && path === `${prefix}/logout`) {
|
|
72
|
+
await handleLogout(req, res, auth, sessionState, postLogoutRedirect, {
|
|
73
|
+
endSession: endSessionOnLogout,
|
|
74
|
+
clientSecret: opts.clientSecret
|
|
75
|
+
});
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
next();
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
async function handleLogin(req, res, auth, prefix, scope, sessionState, defaultReturnTo) {
|
|
82
|
+
const redirectUri = absoluteUrl(req, `${prefix}/callback`);
|
|
83
|
+
const returnTo = sanitizeReturnTo(req.query.return_to, defaultReturnTo);
|
|
84
|
+
const flow = await auth.buildAuthorizationUrl({
|
|
85
|
+
redirectUri,
|
|
86
|
+
scope
|
|
87
|
+
});
|
|
88
|
+
sessionState.flow = {
|
|
89
|
+
codeVerifier: flow.codeVerifier,
|
|
90
|
+
state: flow.state,
|
|
91
|
+
redirectUri,
|
|
92
|
+
returnTo
|
|
93
|
+
};
|
|
94
|
+
saveSession(req, sessionState);
|
|
95
|
+
res.redirect(flow.url);
|
|
96
|
+
}
|
|
97
|
+
async function handleCallback(req, res, auth, sessionState, clientSecret) {
|
|
98
|
+
const code = stringQuery(req.query.code);
|
|
99
|
+
const state = stringQuery(req.query.state);
|
|
100
|
+
const oauthError = stringQuery(req.query.error);
|
|
101
|
+
if (oauthError) {
|
|
102
|
+
res.status(400).json({
|
|
103
|
+
error: oauthError,
|
|
104
|
+
error_description: stringQuery(req.query.error_description) ?? ""
|
|
105
|
+
});
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (!code || !state) {
|
|
109
|
+
res.status(400).json({ error: "invalid_request", error_description: "Missing code or state" });
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const flow = sessionState.flow;
|
|
113
|
+
if (!flow) {
|
|
114
|
+
res.status(400).json({ error: "invalid_request", error_description: "No login in progress" });
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (state !== flow.state) {
|
|
118
|
+
res.status(400).json({ error: "invalid_state", error_description: "CSRF state mismatch" });
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const tokens = await auth.exchangeCodeForTokens({
|
|
123
|
+
code,
|
|
124
|
+
redirectUri: flow.redirectUri,
|
|
125
|
+
codeVerifier: flow.codeVerifier,
|
|
126
|
+
clientSecret
|
|
127
|
+
});
|
|
128
|
+
const user = await fetchUserInfo(auth, tokens.access_token);
|
|
129
|
+
sessionState.tokens = {
|
|
130
|
+
access_token: tokens.access_token,
|
|
131
|
+
refresh_token: tokens.refresh_token,
|
|
132
|
+
id_token: tokens.id_token,
|
|
133
|
+
token_type: tokens.token_type ?? "Bearer",
|
|
134
|
+
expires_at: nowSeconds() + (tokens.expires_in ?? 3600),
|
|
135
|
+
scope: tokens.scope
|
|
136
|
+
};
|
|
137
|
+
sessionState.user = user;
|
|
138
|
+
delete sessionState.flow;
|
|
139
|
+
regenerateSession(req);
|
|
140
|
+
saveSession(req, sessionState);
|
|
141
|
+
res.redirect(flow.returnTo);
|
|
142
|
+
} catch (err) {
|
|
143
|
+
const message = err instanceof LumoAuthError ? err.message : "Token exchange failed";
|
|
144
|
+
const status = err instanceof LumoAuthApiError ? err.statusCode ?? 502 : 502;
|
|
145
|
+
res.status(status).json({ error: "token_exchange_failed", error_description: message });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
async function handleLogout(req, res, auth, sessionState, postLogoutRedirect, options) {
|
|
149
|
+
const tokens = sessionState.tokens;
|
|
150
|
+
delete sessionState.user;
|
|
151
|
+
delete sessionState.tokens;
|
|
152
|
+
delete sessionState.flow;
|
|
153
|
+
saveSession(req, sessionState);
|
|
154
|
+
req.user = void 0;
|
|
155
|
+
if (!options.endSession) {
|
|
156
|
+
res.redirect(postLogoutRedirect);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const revocable = tokens?.refresh_token ?? tokens?.access_token;
|
|
160
|
+
if (revocable) {
|
|
161
|
+
try {
|
|
162
|
+
await auth.revokeToken(revocable, void 0, {
|
|
163
|
+
clientSecret: options.clientSecret,
|
|
164
|
+
tokenTypeHint: tokens?.refresh_token ? "refresh_token" : "access_token"
|
|
165
|
+
});
|
|
166
|
+
} catch {
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (!isAbsoluteHttpUrl(postLogoutRedirect)) {
|
|
170
|
+
res.redirect(postLogoutRedirect);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
res.redirect(
|
|
174
|
+
auth.buildEndSessionUrl({
|
|
175
|
+
idTokenHint: tokens?.id_token,
|
|
176
|
+
postLogoutRedirectUri: postLogoutRedirect
|
|
177
|
+
})
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
var REFRESH_LEEWAY_SECONDS = 60;
|
|
181
|
+
async function refreshIfNeeded(req, sessionState, refresh) {
|
|
182
|
+
const tokens = sessionState.tokens;
|
|
183
|
+
if (!tokens?.refresh_token) return;
|
|
184
|
+
if (tokens.expires_at - nowSeconds() >= REFRESH_LEEWAY_SECONDS) return;
|
|
185
|
+
try {
|
|
186
|
+
const fresh = await refresh(tokens.refresh_token);
|
|
187
|
+
sessionState.tokens = {
|
|
188
|
+
access_token: fresh.access_token,
|
|
189
|
+
// Keep the old refresh token when the server does not rotate it.
|
|
190
|
+
refresh_token: fresh.refresh_token ?? tokens.refresh_token,
|
|
191
|
+
id_token: fresh.id_token ?? tokens.id_token,
|
|
192
|
+
token_type: fresh.token_type ?? tokens.token_type ?? "Bearer",
|
|
193
|
+
expires_at: nowSeconds() + (fresh.expires_in ?? 3600),
|
|
194
|
+
scope: fresh.scope ?? tokens.scope
|
|
195
|
+
};
|
|
196
|
+
} catch {
|
|
197
|
+
delete sessionState.user;
|
|
198
|
+
delete sessionState.tokens;
|
|
199
|
+
req.user = void 0;
|
|
200
|
+
}
|
|
201
|
+
saveSession(req, sessionState);
|
|
202
|
+
}
|
|
203
|
+
function isAbsoluteHttpUrl(value) {
|
|
204
|
+
return /^https?:\/\//i.test(value);
|
|
205
|
+
}
|
|
206
|
+
function requireAuth(options = {}) {
|
|
207
|
+
return async function requireAuthHandler(req, res, next) {
|
|
208
|
+
const user = req.user;
|
|
209
|
+
if (!user) {
|
|
210
|
+
res.status(options.unauthorizedStatus ?? 401).json({ error: "unauthenticated" });
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
if (options.scopes?.length) {
|
|
214
|
+
const session = req.session?.__lumoAuth ?? {};
|
|
215
|
+
const granted = (session.tokens?.scope ?? "").split(/\s+/).filter(Boolean);
|
|
216
|
+
const missing = options.scopes.filter((s) => !granted.includes(s));
|
|
217
|
+
if (missing.length) {
|
|
218
|
+
res.status(options.unauthorizedStatus ?? 403).json({ error: "insufficient_scope", error_description: `Missing: ${missing.join(", ")}` });
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
if (options.authorize) {
|
|
223
|
+
const ok = await options.authorize(user, req);
|
|
224
|
+
if (!ok) {
|
|
225
|
+
res.status(options.unauthorizedStatus ?? 403).json({ error: "forbidden" });
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
next();
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
async function fetchUserInfo(auth, accessToken) {
|
|
233
|
+
const info = await auth.getUserInfo(accessToken);
|
|
234
|
+
return { ...info };
|
|
235
|
+
}
|
|
236
|
+
function absoluteUrl(req, path) {
|
|
237
|
+
const reqWithProto = req;
|
|
238
|
+
const proto = reqWithProto.protocol ?? "https";
|
|
239
|
+
const host = reqWithProto.get?.("host") ?? "";
|
|
240
|
+
return `${proto}://${host}${path}`;
|
|
241
|
+
}
|
|
242
|
+
function sanitizeReturnTo(raw, fallback) {
|
|
243
|
+
if (typeof raw !== "string") return fallback;
|
|
244
|
+
if (!raw.startsWith("/") || raw.startsWith("//")) return fallback;
|
|
245
|
+
return raw;
|
|
246
|
+
}
|
|
247
|
+
function stringQuery(value) {
|
|
248
|
+
if (typeof value === "string") return value;
|
|
249
|
+
if (Array.isArray(value) && typeof value[0] === "string") return value[0];
|
|
250
|
+
return void 0;
|
|
251
|
+
}
|
|
252
|
+
function nowSeconds() {
|
|
253
|
+
return Math.floor(Date.now() / 1e3);
|
|
254
|
+
}
|
|
255
|
+
function saveSession(req, state) {
|
|
256
|
+
if (!req.session) return;
|
|
257
|
+
req.session.__lumoAuth = state;
|
|
258
|
+
}
|
|
259
|
+
function regenerateSession(req) {
|
|
260
|
+
const sess = req.session;
|
|
261
|
+
if (typeof sess?.regenerate === "function") {
|
|
262
|
+
sess.regenerate(() => {
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
export {
|
|
267
|
+
LumoAuthApiError2 as LumoAuthApiError,
|
|
268
|
+
LumoAuthApprovalDeniedError,
|
|
269
|
+
LumoAuthApprovalNotDeliveredError,
|
|
270
|
+
LumoAuthApprovalTimeoutError,
|
|
271
|
+
LumoAuthAuthError,
|
|
272
|
+
LumoAuthAuthenticationError,
|
|
273
|
+
LumoAuthBackend,
|
|
274
|
+
LumoAuthBudgetExceededError,
|
|
275
|
+
LumoAuthConfigError,
|
|
276
|
+
LumoAuthError2 as LumoAuthError,
|
|
277
|
+
LumoAuthNetworkError,
|
|
278
|
+
LumoAuthNotFoundError,
|
|
279
|
+
LumoAuthPermissionDeniedError,
|
|
280
|
+
LumoAuthRateLimitError,
|
|
281
|
+
LumoAuthValidationError,
|
|
282
|
+
lumoAuthMiddleware,
|
|
283
|
+
requireAuth
|
|
284
|
+
};
|
|
285
|
+
//# sourceMappingURL=index.mjs.map
|