@lumoauth/nextjs 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 +462 -2
- package/dist/index.d.mts +19 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +110 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +72 -0
- package/dist/index.mjs.map +1 -0
- package/dist/server.d.mts +232 -0
- package/dist/server.d.ts +232 -0
- package/dist/server.js +433 -0
- package/dist/server.js.map +1 -0
- package/dist/server.mjs +396 -0
- package/dist/server.mjs.map +1 -0
- package/package.json +67 -4
package/dist/server.js
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/server.ts
|
|
31
|
+
var server_exports = {};
|
|
32
|
+
__export(server_exports, {
|
|
33
|
+
REFRESHED_SESSION_HEADER: () => REFRESHED_SESSION_HEADER,
|
|
34
|
+
SESSION_COOKIE: () => SESSION_COOKIE,
|
|
35
|
+
auth: () => auth,
|
|
36
|
+
createRouteHandler: () => createRouteHandler,
|
|
37
|
+
currentUser: () => currentUser,
|
|
38
|
+
isSessionLive: () => isSessionLive,
|
|
39
|
+
isTokenStale: () => isTokenStale,
|
|
40
|
+
lumoAuthMiddleware: () => lumoAuthMiddleware,
|
|
41
|
+
protectPage: () => protectPage,
|
|
42
|
+
resolveConfig: () => resolveConfig
|
|
43
|
+
});
|
|
44
|
+
module.exports = __toCommonJS(server_exports);
|
|
45
|
+
var import_server_only = require("server-only");
|
|
46
|
+
|
|
47
|
+
// src/auth.ts
|
|
48
|
+
var import_headers = require("next/headers");
|
|
49
|
+
var import_shared = require("@lumoauth/shared");
|
|
50
|
+
|
|
51
|
+
// src/config.ts
|
|
52
|
+
function resolveConfig(overrides = {}) {
|
|
53
|
+
const env = process.env;
|
|
54
|
+
const cfg = {
|
|
55
|
+
domain: overrides.domain ?? env.NEXT_PUBLIC_LUMOAUTH_DOMAIN ?? "",
|
|
56
|
+
orgId: overrides.orgId ?? env.NEXT_PUBLIC_LUMOAUTH_ORG_ID ?? "",
|
|
57
|
+
clientId: overrides.clientId ?? env.NEXT_PUBLIC_LUMOAUTH_CLIENT_ID ?? "",
|
|
58
|
+
clientSecret: overrides.clientSecret ?? env.LUMOAUTH_CLIENT_SECRET,
|
|
59
|
+
secret: overrides.secret ?? env.LUMOAUTH_SECRET ?? "",
|
|
60
|
+
redirectUri: overrides.redirectUri ?? env.NEXT_PUBLIC_REDIRECT_URI ?? "",
|
|
61
|
+
afterSignOutUrl: overrides.afterSignOutUrl ?? "/",
|
|
62
|
+
afterSignInUrl: overrides.afterSignInUrl ?? "/",
|
|
63
|
+
scope: overrides.scope ?? "openid profile email",
|
|
64
|
+
sessionMaxAge: overrides.sessionMaxAge ?? 60 * 60 * 24 * 30
|
|
65
|
+
};
|
|
66
|
+
const missing = ["domain", "orgId", "clientId", "secret", "redirectUri"].filter(
|
|
67
|
+
(k) => !cfg[k]
|
|
68
|
+
);
|
|
69
|
+
if (missing.length) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
`@lumoauth/nextjs is missing required config: ${missing.join(", ")}. Set NEXT_PUBLIC_LUMOAUTH_DOMAIN, NEXT_PUBLIC_LUMOAUTH_ORG_ID, NEXT_PUBLIC_LUMOAUTH_CLIENT_ID, NEXT_PUBLIC_REDIRECT_URI and LUMOAUTH_SECRET, or pass them to createRouteHandler({ ... }).`
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
return cfg;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// src/session-cookie.ts
|
|
78
|
+
var SESSION_COOKIE = "lumo_session";
|
|
79
|
+
var PKCE_COOKIE = "lumo_pkce";
|
|
80
|
+
var REFRESHED_SESSION_HEADER = "x-lumo-session";
|
|
81
|
+
var REFRESH_WINDOW_MS = 6e4;
|
|
82
|
+
function isSessionLive(session) {
|
|
83
|
+
if (!session) return false;
|
|
84
|
+
if (session.sessionExpiresAt && session.sessionExpiresAt <= Date.now()) return false;
|
|
85
|
+
return !!session.refreshToken || session.expiresAt > Date.now();
|
|
86
|
+
}
|
|
87
|
+
function isTokenStale(session) {
|
|
88
|
+
return session.expiresAt - Date.now() < REFRESH_WINDOW_MS;
|
|
89
|
+
}
|
|
90
|
+
var IV_BYTES = 12;
|
|
91
|
+
function buf(u) {
|
|
92
|
+
return u;
|
|
93
|
+
}
|
|
94
|
+
function b64urlEncode(bytes) {
|
|
95
|
+
let s = "";
|
|
96
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
97
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
98
|
+
}
|
|
99
|
+
function b64urlDecode(text) {
|
|
100
|
+
const padded = text.replace(/-/g, "+").replace(/_/g, "/");
|
|
101
|
+
const bin = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
|
|
102
|
+
return Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
103
|
+
}
|
|
104
|
+
async function importKey(secret) {
|
|
105
|
+
if (!secret || secret.length < 32) {
|
|
106
|
+
throw new Error(
|
|
107
|
+
"LUMOAUTH_SECRET must be set to at least 32 characters. Generate one with: openssl rand -hex 32"
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
const digest = await crypto.subtle.digest("SHA-256", buf(new TextEncoder().encode(secret)));
|
|
111
|
+
return crypto.subtle.importKey("raw", digest, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
|
|
112
|
+
}
|
|
113
|
+
async function seal(payload, secret) {
|
|
114
|
+
const key = await importKey(secret);
|
|
115
|
+
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
|
|
116
|
+
const data = new TextEncoder().encode(JSON.stringify(payload));
|
|
117
|
+
const sealed = new Uint8Array(
|
|
118
|
+
await crypto.subtle.encrypt({ name: "AES-GCM", iv: buf(iv) }, key, buf(data))
|
|
119
|
+
);
|
|
120
|
+
return `${b64urlEncode(iv)}.${b64urlEncode(sealed)}`;
|
|
121
|
+
}
|
|
122
|
+
async function unseal(value, secret) {
|
|
123
|
+
if (!value) return null;
|
|
124
|
+
const parts = value.split(".");
|
|
125
|
+
if (parts.length !== 2) return null;
|
|
126
|
+
try {
|
|
127
|
+
const iv = b64urlDecode(parts[0]);
|
|
128
|
+
const body = b64urlDecode(parts[1]);
|
|
129
|
+
const key = await importKey(secret);
|
|
130
|
+
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: buf(iv) }, key, buf(body));
|
|
131
|
+
return JSON.parse(new TextDecoder().decode(plain));
|
|
132
|
+
} catch {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function cookieOptions(maxAgeSeconds, secure) {
|
|
137
|
+
return {
|
|
138
|
+
httpOnly: true,
|
|
139
|
+
// Lax, not Strict: the OAuth callback is a cross-site top-level
|
|
140
|
+
// navigation back from the identity provider, and Strict would withhold
|
|
141
|
+
// the PKCE cookie exactly then.
|
|
142
|
+
sameSite: "lax",
|
|
143
|
+
secure,
|
|
144
|
+
path: "/",
|
|
145
|
+
maxAge: maxAgeSeconds
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// src/auth.ts
|
|
150
|
+
var SIGNED_OUT = {
|
|
151
|
+
userId: null,
|
|
152
|
+
isSignedIn: false,
|
|
153
|
+
getToken: () => null,
|
|
154
|
+
expiresAt: null,
|
|
155
|
+
isStale: false
|
|
156
|
+
};
|
|
157
|
+
function decodeSub(accessToken) {
|
|
158
|
+
try {
|
|
159
|
+
const [, payload] = accessToken.split(".");
|
|
160
|
+
const json = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
161
|
+
return typeof json.sub === "string" ? json.sub : null;
|
|
162
|
+
} catch {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
async function auth(overrides = {}) {
|
|
167
|
+
const cfg = resolveConfig(overrides);
|
|
168
|
+
const hdrs = await (0, import_headers.headers)();
|
|
169
|
+
const fromHeader = await unseal(
|
|
170
|
+
hdrs.get(REFRESHED_SESSION_HEADER) ?? void 0,
|
|
171
|
+
cfg.secret
|
|
172
|
+
);
|
|
173
|
+
const jar = await (0, import_headers.cookies)();
|
|
174
|
+
const session = fromHeader ?? await unseal(jar.get(SESSION_COOKIE)?.value, cfg.secret);
|
|
175
|
+
if (!isSessionLive(session)) return SIGNED_OUT;
|
|
176
|
+
const stale = isTokenStale(session);
|
|
177
|
+
return {
|
|
178
|
+
userId: decodeSub(session.accessToken),
|
|
179
|
+
isSignedIn: true,
|
|
180
|
+
getToken: () => stale ? null : session.accessToken,
|
|
181
|
+
expiresAt: session.expiresAt,
|
|
182
|
+
isStale: stale
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
async function currentUser(overrides = {}) {
|
|
186
|
+
const cfg = resolveConfig(overrides);
|
|
187
|
+
const { getToken, isSignedIn } = await auth(overrides);
|
|
188
|
+
if (!isSignedIn) return null;
|
|
189
|
+
const token = getToken();
|
|
190
|
+
if (!token) return null;
|
|
191
|
+
try {
|
|
192
|
+
const mod = new import_shared.AuthModule({ baseUrl: cfg.domain, orgId: cfg.orgId, clientId: cfg.clientId });
|
|
193
|
+
return await mod.getUserInfo(token);
|
|
194
|
+
} catch {
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
async function protectPage(opts = {}) {
|
|
199
|
+
const result = await auth();
|
|
200
|
+
if (!result.isSignedIn) {
|
|
201
|
+
const { redirect } = await import("next/navigation");
|
|
202
|
+
const qs = opts.returnTo ? `?return_to=${encodeURIComponent(opts.returnTo)}` : "";
|
|
203
|
+
redirect(`/api/auth/login${qs}`);
|
|
204
|
+
}
|
|
205
|
+
return result;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// src/route-handler.ts
|
|
209
|
+
var import_shared2 = require("@lumoauth/shared");
|
|
210
|
+
function authModule(cfg) {
|
|
211
|
+
return new import_shared2.AuthModule({ baseUrl: cfg.domain, orgId: cfg.orgId, clientId: cfg.clientId });
|
|
212
|
+
}
|
|
213
|
+
function safeReturnTo(raw, fallback) {
|
|
214
|
+
if (!raw) return fallback;
|
|
215
|
+
if (!raw.startsWith("/") || raw.startsWith("//")) return fallback;
|
|
216
|
+
return raw;
|
|
217
|
+
}
|
|
218
|
+
function createRouteHandler(overrides = {}) {
|
|
219
|
+
const getCfg = () => resolveConfig(overrides);
|
|
220
|
+
async function segments(context) {
|
|
221
|
+
const p = await context.params;
|
|
222
|
+
return p?.lumoauth ?? [];
|
|
223
|
+
}
|
|
224
|
+
async function GET(request, context) {
|
|
225
|
+
const cfg = getCfg();
|
|
226
|
+
const action = (await segments(context))[0];
|
|
227
|
+
const url = new URL(request.url);
|
|
228
|
+
const secure = url.protocol === "https:";
|
|
229
|
+
if (action === "login") {
|
|
230
|
+
const codeVerifier = (0, import_shared2.generateCodeVerifier)();
|
|
231
|
+
const state = (0, import_shared2.generateState)();
|
|
232
|
+
const codeChallenge = await (0, import_shared2.generateCodeChallenge)(codeVerifier);
|
|
233
|
+
const authorize = new URL(
|
|
234
|
+
`${cfg.domain.replace(/\/+$/, "")}${(0, import_shared2.buildPath)(import_shared2.ROUTES["oauth.authorize"].path, { orgId: cfg.orgId })}`
|
|
235
|
+
);
|
|
236
|
+
authorize.searchParams.set("response_type", "code");
|
|
237
|
+
authorize.searchParams.set("client_id", cfg.clientId);
|
|
238
|
+
authorize.searchParams.set("redirect_uri", cfg.redirectUri);
|
|
239
|
+
authorize.searchParams.set("scope", cfg.scope);
|
|
240
|
+
authorize.searchParams.set("code_challenge", codeChallenge);
|
|
241
|
+
authorize.searchParams.set("code_challenge_method", "S256");
|
|
242
|
+
authorize.searchParams.set("state", state);
|
|
243
|
+
const pkce = {
|
|
244
|
+
codeVerifier,
|
|
245
|
+
state,
|
|
246
|
+
returnTo: safeReturnTo(url.searchParams.get("return_to"), cfg.afterSignInUrl)
|
|
247
|
+
};
|
|
248
|
+
const res = Response.redirect(authorize.toString(), 302);
|
|
249
|
+
return withCookie(
|
|
250
|
+
res,
|
|
251
|
+
`${PKCE_COOKIE}=${await seal(pkce, cfg.secret)}; ${serialize(cookieOptions(600, secure))}`
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
if (action === "callback") {
|
|
255
|
+
const code = url.searchParams.get("code");
|
|
256
|
+
const returnedState = url.searchParams.get("state");
|
|
257
|
+
const pkce = await unseal(readCookie(request, PKCE_COOKIE), cfg.secret);
|
|
258
|
+
if (!code || !returnedState || !pkce) {
|
|
259
|
+
return redirectTo(url.origin + cfg.afterSignOutUrl, [clearCookie(PKCE_COOKIE, secure)]);
|
|
260
|
+
}
|
|
261
|
+
if (returnedState !== pkce.state) {
|
|
262
|
+
return redirectTo(url.origin + cfg.afterSignOutUrl, [clearCookie(PKCE_COOKIE, secure)]);
|
|
263
|
+
}
|
|
264
|
+
try {
|
|
265
|
+
const tokens = await authModule(cfg).exchangeCodeForTokens({
|
|
266
|
+
code,
|
|
267
|
+
codeVerifier: pkce.codeVerifier,
|
|
268
|
+
redirectUri: cfg.redirectUri,
|
|
269
|
+
...cfg.clientSecret ? { clientSecret: cfg.clientSecret } : {}
|
|
270
|
+
});
|
|
271
|
+
const session = {
|
|
272
|
+
accessToken: tokens.access_token,
|
|
273
|
+
refreshToken: tokens.refresh_token ?? null,
|
|
274
|
+
idToken: tokens.id_token ?? null,
|
|
275
|
+
// Access-token expiry: short, refreshed in the background.
|
|
276
|
+
expiresAt: Date.now() + tokens.expires_in * 1e3,
|
|
277
|
+
// Session expiry: long. The user stays signed in until this
|
|
278
|
+
// passes, however many access tokens come and go.
|
|
279
|
+
sessionExpiresAt: Date.now() + cfg.sessionMaxAge * 1e3
|
|
280
|
+
};
|
|
281
|
+
return redirectTo(url.origin + pkce.returnTo, [
|
|
282
|
+
`${SESSION_COOKIE}=${await seal(session, cfg.secret)}; ${serialize(cookieOptions(cfg.sessionMaxAge, secure))}`,
|
|
283
|
+
clearCookie(PKCE_COOKIE, secure)
|
|
284
|
+
]);
|
|
285
|
+
} catch {
|
|
286
|
+
return redirectTo(url.origin + cfg.afterSignOutUrl, [clearCookie(PKCE_COOKIE, secure)]);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (action === "session") {
|
|
290
|
+
const session = await unseal(readCookie(request, SESSION_COOKIE), cfg.secret);
|
|
291
|
+
if (!isSessionLive(session)) {
|
|
292
|
+
return Response.json({ accessToken: null, expiresAt: null });
|
|
293
|
+
}
|
|
294
|
+
return Response.json({
|
|
295
|
+
accessToken: session.accessToken,
|
|
296
|
+
idToken: session.idToken,
|
|
297
|
+
expiresAt: session.expiresAt
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
if (action === "logout") return doLogout(cfg, url, request, secure);
|
|
301
|
+
return new Response("Not found", { status: 404 });
|
|
302
|
+
}
|
|
303
|
+
async function POST(request, context) {
|
|
304
|
+
const cfg = getCfg();
|
|
305
|
+
const action = (await segments(context))[0];
|
|
306
|
+
const url = new URL(request.url);
|
|
307
|
+
if (action === "logout") return doLogout(cfg, url, request, url.protocol === "https:");
|
|
308
|
+
return new Response("Not found", { status: 404 });
|
|
309
|
+
}
|
|
310
|
+
async function doLogout(cfg, url, request, secure) {
|
|
311
|
+
const session = await unseal(readCookie(request, SESSION_COOKIE), cfg.secret);
|
|
312
|
+
if (session?.accessToken) {
|
|
313
|
+
await authModule(cfg).revokeToken(session.accessToken, session.accessToken).catch(() => {
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
const logout = new URL(
|
|
317
|
+
`${cfg.domain.replace(/\/+$/, "")}${(0, import_shared2.buildPath)(import_shared2.ROUTES["oauth.logout"].path, { orgId: cfg.orgId })}`
|
|
318
|
+
);
|
|
319
|
+
logout.searchParams.set("post_logout_redirect_uri", url.origin + cfg.afterSignOutUrl);
|
|
320
|
+
if (session?.idToken) logout.searchParams.set("id_token_hint", session.idToken);
|
|
321
|
+
return redirectTo(logout.toString(), [clearCookie(SESSION_COOKIE, secure)]);
|
|
322
|
+
}
|
|
323
|
+
return { GET, POST };
|
|
324
|
+
}
|
|
325
|
+
function serialize(o) {
|
|
326
|
+
return [
|
|
327
|
+
`Path=${o.path}`,
|
|
328
|
+
`Max-Age=${o.maxAge}`,
|
|
329
|
+
`SameSite=${o.sameSite === "lax" ? "Lax" : o.sameSite}`,
|
|
330
|
+
o.httpOnly ? "HttpOnly" : "",
|
|
331
|
+
o.secure ? "Secure" : ""
|
|
332
|
+
].filter(Boolean).join("; ");
|
|
333
|
+
}
|
|
334
|
+
function clearCookie(name, secure) {
|
|
335
|
+
return `${name}=; Path=/; Max-Age=0; SameSite=Lax; HttpOnly${secure ? "; Secure" : ""}`;
|
|
336
|
+
}
|
|
337
|
+
function readCookie(request, name) {
|
|
338
|
+
const header = request.headers.get("cookie");
|
|
339
|
+
if (!header) return void 0;
|
|
340
|
+
const hit = header.split("; ").find((c) => c.startsWith(`${name}=`));
|
|
341
|
+
return hit?.slice(name.length + 1);
|
|
342
|
+
}
|
|
343
|
+
function redirectTo(location, cookies2) {
|
|
344
|
+
const headers2 = new Headers({ Location: location });
|
|
345
|
+
cookies2.forEach((c) => headers2.append("Set-Cookie", c));
|
|
346
|
+
return new Response(null, { status: 302, headers: headers2 });
|
|
347
|
+
}
|
|
348
|
+
function withCookie(res, cookie) {
|
|
349
|
+
const headers2 = new Headers(res.headers);
|
|
350
|
+
headers2.append("Set-Cookie", cookie);
|
|
351
|
+
return new Response(res.body, { status: res.status, headers: headers2 });
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// src/middleware.ts
|
|
355
|
+
var import_server = require("next/server");
|
|
356
|
+
var import_shared3 = require("@lumoauth/shared");
|
|
357
|
+
function toMatcher(pattern) {
|
|
358
|
+
if (pattern instanceof RegExp) return pattern;
|
|
359
|
+
const source = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\/:path\*/g, "(?:/.*)?").replace(/\*/g, ".*");
|
|
360
|
+
return new RegExp(`^${source}$`);
|
|
361
|
+
}
|
|
362
|
+
function lumoAuthMiddleware(options = {}) {
|
|
363
|
+
const { protect = [], refresh = true, ...configOverrides } = options;
|
|
364
|
+
return async function middleware(req) {
|
|
365
|
+
const isProtected = typeof protect === "function" ? protect(req) : protect.map(toMatcher).some((m) => m.test(req.nextUrl.pathname));
|
|
366
|
+
const cfg = resolveConfig(configOverrides);
|
|
367
|
+
const rawCookie = req.cookies.get(SESSION_COOKIE)?.value;
|
|
368
|
+
const session = await unseal(rawCookie, cfg.secret);
|
|
369
|
+
if (!isSessionLive(session)) {
|
|
370
|
+
if (!isProtected) {
|
|
371
|
+
if (!rawCookie) return import_server.NextResponse.next();
|
|
372
|
+
const res2 = import_server.NextResponse.next();
|
|
373
|
+
res2.cookies.delete(SESSION_COOKIE);
|
|
374
|
+
return res2;
|
|
375
|
+
}
|
|
376
|
+
const login = new URL("/api/auth/login", req.nextUrl.origin);
|
|
377
|
+
login.searchParams.set("return_to", req.nextUrl.pathname + req.nextUrl.search);
|
|
378
|
+
const res = import_server.NextResponse.redirect(login);
|
|
379
|
+
if (rawCookie) res.cookies.delete(SESSION_COOKIE);
|
|
380
|
+
return res;
|
|
381
|
+
}
|
|
382
|
+
if (!refresh || !isTokenStale(session)) return import_server.NextResponse.next();
|
|
383
|
+
if (!session.refreshToken) {
|
|
384
|
+
if (!isProtected) return import_server.NextResponse.next();
|
|
385
|
+
const login = new URL("/api/auth/login", req.nextUrl.origin);
|
|
386
|
+
login.searchParams.set("return_to", req.nextUrl.pathname + req.nextUrl.search);
|
|
387
|
+
return import_server.NextResponse.redirect(login);
|
|
388
|
+
}
|
|
389
|
+
try {
|
|
390
|
+
const mod = new import_shared3.AuthModule({
|
|
391
|
+
baseUrl: cfg.domain,
|
|
392
|
+
orgId: cfg.orgId,
|
|
393
|
+
clientId: cfg.clientId
|
|
394
|
+
});
|
|
395
|
+
const tokens = await mod.refreshToken(session.refreshToken);
|
|
396
|
+
const next = {
|
|
397
|
+
accessToken: tokens.access_token,
|
|
398
|
+
// Keep the existing token when the server does not rotate;
|
|
399
|
+
// losing it here would silently end the session at the next
|
|
400
|
+
// refresh.
|
|
401
|
+
refreshToken: tokens.refresh_token ?? session.refreshToken,
|
|
402
|
+
idToken: tokens.id_token ?? session.idToken,
|
|
403
|
+
expiresAt: Date.now() + tokens.expires_in * 1e3,
|
|
404
|
+
sessionExpiresAt: session.sessionExpiresAt
|
|
405
|
+
};
|
|
406
|
+
const sealed = await seal(next, cfg.secret);
|
|
407
|
+
const headers2 = new Headers(req.headers);
|
|
408
|
+
headers2.set(REFRESHED_SESSION_HEADER, sealed);
|
|
409
|
+
const res = import_server.NextResponse.next({ request: { headers: headers2 } });
|
|
410
|
+
const opts = cookieOptions(cfg.sessionMaxAge, req.nextUrl.protocol === "https:");
|
|
411
|
+
res.cookies.set(SESSION_COOKIE, sealed, opts);
|
|
412
|
+
return res;
|
|
413
|
+
} catch {
|
|
414
|
+
const res = isProtected ? import_server.NextResponse.redirect(new URL("/api/auth/login", req.nextUrl.origin)) : import_server.NextResponse.next();
|
|
415
|
+
res.cookies.delete(SESSION_COOKIE);
|
|
416
|
+
return res;
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
421
|
+
0 && (module.exports = {
|
|
422
|
+
REFRESHED_SESSION_HEADER,
|
|
423
|
+
SESSION_COOKIE,
|
|
424
|
+
auth,
|
|
425
|
+
createRouteHandler,
|
|
426
|
+
currentUser,
|
|
427
|
+
isSessionLive,
|
|
428
|
+
isTokenStale,
|
|
429
|
+
lumoAuthMiddleware,
|
|
430
|
+
protectPage,
|
|
431
|
+
resolveConfig
|
|
432
|
+
});
|
|
433
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/auth.ts","../src/config.ts","../src/session-cookie.ts","../src/route-handler.ts","../src/middleware.ts"],"sourcesContent":["// @lumoauth/nextjs/server — server-only entry.\n//\n// Holds the OAuth client secret and the cookie-sealing secret, so it must\n// never reach the browser. Importing this from a client component is a build\n// error in Next.js thanks to the `server-only` marker below.\nimport 'server-only';\n\nexport { auth, currentUser, protectPage, type AuthObject } from './auth';\nexport { createRouteHandler } from './route-handler';\nexport { lumoAuthMiddleware, type MiddlewareOptions } from './middleware';\nexport { resolveConfig, type LumoAuthNextConfig } from './config';\nexport {\n SESSION_COOKIE,\n REFRESHED_SESSION_HEADER,\n isSessionLive,\n isTokenStale,\n type ServerSession,\n} from './session-cookie';\n","import { cookies, headers } from 'next/headers';\nimport { AuthModule, type UserInfo } from '@lumoauth/shared';\nimport { resolveConfig, type LumoAuthNextConfig } from './config';\nimport {\n SESSION_COOKIE,\n REFRESHED_SESSION_HEADER,\n isSessionLive,\n isTokenStale,\n unseal,\n type ServerSession,\n} from './session-cookie';\n\nexport interface AuthObject {\n /** OIDC subject of the signed-in user, or null. */\n userId: string | null;\n /**\n * Whether the user has a live SESSION — not whether the access token is\n * currently fresh. A stale access token with a valid refresh token is still\n * a signed-in user.\n */\n isSignedIn: boolean;\n /**\n * The access token, or null if it is stale and nothing refreshed it.\n *\n * Returns null rather than refreshing, because a server component cannot\n * persist the result: LumoAuth rotates and revokes refresh tokens on use,\n * so an unpersisted refresh would burn the token and break the session on\n * the very next request. Add `lumoAuthMiddleware()` and the token is always\n * fresh by the time this runs.\n */\n getToken: () => string | null;\n /** Access-token expiry, epoch milliseconds. */\n expiresAt: number | null;\n /**\n * True when the session is live but the access token needs replacing.\n * Only possible when middleware is not installed on this route.\n */\n isStale: boolean;\n}\n\nconst SIGNED_OUT: AuthObject = {\n userId: null,\n isSignedIn: false,\n getToken: () => null,\n expiresAt: null,\n isStale: false,\n};\n\nfunction decodeSub(accessToken: string): string | null {\n try {\n const [, payload] = accessToken.split('.');\n const json = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));\n return typeof json.sub === 'string' ? json.sub : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Read the session in a server component, route handler, or server action.\n *\n * Because the session lives in an httpOnly cookie the server can read directly,\n * a page can decide what to render *before* it responds — no client round-trip,\n * and therefore none of the signed-out-then-signed-in flash that a purely\n * client-side provider produces on every load.\n *\n * ```tsx\n * export default async function Page() {\n * const { isSignedIn, userId } = await auth();\n * if (!isSignedIn) redirect('/api/auth/login');\n * return <p>Hello {userId}</p>;\n * }\n * ```\n *\n * The session is trusted because it is sealed with AES-256-GCM using\n * `LUMOAUTH_SECRET`: the browser can neither read nor forge it. This does not\n * re-verify the access token's signature against the issuer's JWKS — the token\n * is only ever accepted here because *we* put it in the cookie after a\n * successful exchange.\n */\nexport async function auth(overrides: Partial<LumoAuthNextConfig> = {}): Promise<AuthObject> {\n const cfg = resolveConfig(overrides);\n\n // Prefer the header: if middleware refreshed during THIS request, the\n // request cookie still holds the pre-refresh value.\n const hdrs = await headers();\n const fromHeader = await unseal<ServerSession>(\n hdrs.get(REFRESHED_SESSION_HEADER) ?? undefined,\n cfg.secret,\n );\n const jar = await cookies();\n const session =\n fromHeader ?? (await unseal<ServerSession>(jar.get(SESSION_COOKIE)?.value, cfg.secret));\n\n if (!isSessionLive(session)) return SIGNED_OUT;\n\n const stale = isTokenStale(session);\n return {\n userId: decodeSub(session.accessToken),\n isSignedIn: true,\n getToken: () => (stale ? null : session.accessToken),\n expiresAt: session.expiresAt,\n isStale: stale,\n };\n}\n\n/**\n * The signed-in user's profile, or null.\n *\n * This makes a network call to the OIDC `/userinfo` endpoint on every\n * invocation, so prefer `auth()` when the subject is all you need.\n */\nexport async function currentUser(\n overrides: Partial<LumoAuthNextConfig> = {},\n): Promise<UserInfo | null> {\n const cfg = resolveConfig(overrides);\n const { getToken, isSignedIn } = await auth(overrides);\n if (!isSignedIn) return null;\n\n const token = getToken();\n if (!token) return null;\n\n try {\n const mod = new AuthModule({ baseUrl: cfg.domain, orgId: cfg.orgId, clientId: cfg.clientId });\n return await mod.getUserInfo(token);\n } catch {\n // A failed /userinfo does not invalidate the session — treat it as\n // \"profile unavailable\" rather than signing the user out mid-render.\n return null;\n }\n}\n\n/**\n * Redirect signed-out visitors to sign in. Call at the top of a protected\n * server component.\n *\n * ```tsx\n * export default async function Page() {\n * await protectPage();\n * ...\n * }\n * ```\n */\nexport async function protectPage(opts: { returnTo?: string } = {}): Promise<AuthObject> {\n const result = await auth();\n if (!result.isSignedIn) {\n const { redirect } = await import('next/navigation');\n const qs = opts.returnTo ? `?return_to=${encodeURIComponent(opts.returnTo)}` : '';\n redirect(`/api/auth/login${qs}`);\n }\n return result;\n}\n","export interface LumoAuthNextConfig {\n /** Base URL of your LumoAuth instance. */\n domain: string;\n /** Organization slug. */\n orgId: string;\n /** OAuth client id. */\n clientId: string;\n /** Client secret, for confidential clients. Public + PKCE clients omit it. */\n clientSecret?: string;\n /** Secret used to seal the session cookie. At least 32 characters. */\n secret: string;\n /** Absolute redirect URI registered with the OAuth client. */\n redirectUri: string;\n /** Where to send a signed-out user. @default '/' */\n afterSignOutUrl?: string;\n /** Where to send a freshly signed-in user. @default '/' */\n afterSignInUrl?: string;\n /** OAuth scopes. @default 'openid profile email' */\n scope?: string;\n /** Session cookie lifetime in seconds. @default 30 days */\n sessionMaxAge?: number;\n}\n\n/**\n * Resolve config from the environment.\n *\n * The public values are read from `NEXT_PUBLIC_*` so the same names work in\n * both the client provider and the server. `LUMOAUTH_SECRET` and\n * `LUMOAUTH_CLIENT_SECRET` are deliberately NOT public — a `NEXT_PUBLIC_`\n * prefix would inline them into the browser bundle.\n */\nexport function resolveConfig(overrides: Partial<LumoAuthNextConfig> = {}): LumoAuthNextConfig {\n const env = process.env;\n const cfg: LumoAuthNextConfig = {\n domain: overrides.domain ?? env.NEXT_PUBLIC_LUMOAUTH_DOMAIN ?? '',\n orgId: overrides.orgId ?? env.NEXT_PUBLIC_LUMOAUTH_ORG_ID ?? '',\n clientId: overrides.clientId ?? env.NEXT_PUBLIC_LUMOAUTH_CLIENT_ID ?? '',\n clientSecret: overrides.clientSecret ?? env.LUMOAUTH_CLIENT_SECRET,\n secret: overrides.secret ?? env.LUMOAUTH_SECRET ?? '',\n redirectUri: overrides.redirectUri ?? env.NEXT_PUBLIC_REDIRECT_URI ?? '',\n afterSignOutUrl: overrides.afterSignOutUrl ?? '/',\n afterSignInUrl: overrides.afterSignInUrl ?? '/',\n scope: overrides.scope ?? 'openid profile email',\n sessionMaxAge: overrides.sessionMaxAge ?? 60 * 60 * 24 * 30,\n };\n\n const missing = (['domain', 'orgId', 'clientId', 'secret', 'redirectUri'] as const).filter(\n (k) => !cfg[k],\n );\n if (missing.length) {\n throw new Error(\n `@lumoauth/nextjs is missing required config: ${missing.join(', ')}. ` +\n 'Set NEXT_PUBLIC_LUMOAUTH_DOMAIN, NEXT_PUBLIC_LUMOAUTH_ORG_ID, ' +\n 'NEXT_PUBLIC_LUMOAUTH_CLIENT_ID, NEXT_PUBLIC_REDIRECT_URI and LUMOAUTH_SECRET, ' +\n 'or pass them to createRouteHandler({ ... }).',\n );\n }\n return cfg;\n}\n","/**\n * The server-side session, sealed into an httpOnly cookie.\n *\n * This is the trust boundary for everything else in the package: `auth()`\n * believes what is in here, so it must be unforgeable. The cookie is encrypted\n * AND authenticated with AES-256-GCM, so a client can neither read the tokens\n * nor alter the payload without the auth tag failing.\n *\n * Encrypting rather than merely signing matters because the payload holds the\n * refresh token, which must never be readable by the browser.\n *\n * Implemented with Web Crypto rather than `node:crypto` because these helpers\n * run in three different places: route handlers (Node runtime), `auth()` in a\n * server component (Node), and `lumoAuthMiddleware` (edge runtime, where\n * `node:crypto` does not exist). Web Crypto is the one API present in all of\n * them. The cost is that seal/unseal are async.\n */\n\nexport const SESSION_COOKIE = 'lumo_session';\nexport const PKCE_COOKIE = 'lumo_pkce';\n\n/**\n * Two different lifetimes live in here, and conflating them is the classic\n * bug: an access token lasts ~1 hour, a session lasts weeks.\n *\n * `expiresAt` is when the ACCESS TOKEN goes stale — routine, expected, and\n * fixed by a refresh.\n * `sessionExpiresAt` is when the SESSION itself ends and the user must sign in\n * again.\n *\n * A user whose access token expired five minutes ago is still signed in.\n */\nexport interface ServerSession {\n accessToken: string;\n refreshToken: string | null;\n idToken: string | null;\n /** Access-token expiry, epoch milliseconds. */\n expiresAt: number;\n /** Session expiry, epoch milliseconds. Absent on cookies written before this field existed. */\n sessionExpiresAt?: number;\n}\n\n/**\n * Header used to hand a freshly refreshed session from middleware to the\n * server component rendering the same request.\n *\n * Middleware writes the new cookie on the RESPONSE, but the component reads\n * REQUEST cookies — which still hold the stale value. Without this header the\n * refresh would only take effect on the following request.\n */\nexport const REFRESHED_SESSION_HEADER = 'x-lumo-session';\n\n/** Refresh once the access token is within this window of expiring. */\nexport const REFRESH_WINDOW_MS = 60_000;\n\n/** True when the session itself is still valid, regardless of token staleness. */\nexport function isSessionLive(session: ServerSession | null): session is ServerSession {\n if (!session) return false;\n if (session.sessionExpiresAt && session.sessionExpiresAt <= Date.now()) return false;\n // A live session is one we can still get a token for: either the current\n // access token is good, or we hold a refresh token to obtain a new one.\n return !!session.refreshToken || session.expiresAt > Date.now();\n}\n\n/** True when the access token needs replacing before it can be used. */\nexport function isTokenStale(session: ServerSession): boolean {\n return session.expiresAt - Date.now() < REFRESH_WINDOW_MS;\n}\n\nexport interface PkceState {\n codeVerifier: string;\n state: string;\n /** Where to send the user once the exchange completes. */\n returnTo: string;\n}\n\nconst IV_BYTES = 12;\n\n/**\n * TS 5.7 made Uint8Array generic over its backing buffer, so\n * Uint8Array<ArrayBufferLike> no longer structurally satisfies BufferSource\n * (which wants an ArrayBuffer, not a SharedArrayBuffer). Every value we pass to\n * Web Crypto here is a plain ArrayBuffer at runtime.\n */\nfunction buf(u: Uint8Array): BufferSource {\n return u as unknown as BufferSource;\n}\n\nfunction b64urlEncode(bytes: Uint8Array): string {\n let s = '';\n for (const b of bytes) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction b64urlDecode(text: string): Uint8Array {\n const padded = text.replace(/-/g, '+').replace(/_/g, '/');\n const bin = atob(padded + '='.repeat((4 - (padded.length % 4)) % 4));\n return Uint8Array.from(bin, (c) => c.charCodeAt(0));\n}\n\nasync function importKey(secret: string): Promise<CryptoKey> {\n if (!secret || secret.length < 32) {\n throw new Error(\n 'LUMOAUTH_SECRET must be set to at least 32 characters. Generate one with: openssl rand -hex 32',\n );\n }\n // SHA-256 the secret: it is arbitrary-length text and AES-256 needs exactly\n // 32 bytes.\n const digest = await crypto.subtle.digest('SHA-256', buf(new TextEncoder().encode(secret)));\n return crypto.subtle.importKey('raw', digest, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);\n}\n\nexport async function seal(payload: unknown, secret: string): Promise<string> {\n const key = await importKey(secret);\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const data = new TextEncoder().encode(JSON.stringify(payload));\n const sealed = new Uint8Array(\n await crypto.subtle.encrypt({ name: 'AES-GCM', iv: buf(iv) }, key, buf(data)),\n );\n // Web Crypto appends the auth tag to the ciphertext, so two parts suffice.\n return `${b64urlEncode(iv)}.${b64urlEncode(sealed)}`;\n}\n\nexport async function unseal<T>(value: string | undefined, secret: string): Promise<T | null> {\n if (!value) return null;\n const parts = value.split('.');\n if (parts.length !== 2) return null;\n try {\n const iv = b64urlDecode(parts[0]);\n const body = b64urlDecode(parts[1]);\n const key = await importKey(secret);\n const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: buf(iv) }, key, buf(body));\n return JSON.parse(new TextDecoder().decode(plain)) as T;\n } catch {\n // A tampered, truncated, or stale-key cookie is simply not a session.\n // Returning null signs the user out rather than throwing into a render.\n return null;\n }\n}\n\n/** Cookie attributes shared by every cookie this package sets. */\nexport function cookieOptions(maxAgeSeconds: number, secure: boolean) {\n return {\n httpOnly: true,\n // Lax, not Strict: the OAuth callback is a cross-site top-level\n // navigation back from the identity provider, and Strict would withhold\n // the PKCE cookie exactly then.\n sameSite: 'lax' as const,\n secure,\n path: '/',\n maxAge: maxAgeSeconds,\n };\n}\n","import {\n AuthModule,\n generateCodeVerifier,\n generateCodeChallenge,\n generateState,\n ROUTES,\n buildPath,\n} from '@lumoauth/shared';\nimport { resolveConfig, type LumoAuthNextConfig } from './config';\nimport {\n SESSION_COOKIE,\n PKCE_COOKIE,\n cookieOptions,\n isSessionLive,\n seal,\n unseal,\n type PkceState,\n type ServerSession,\n} from './session-cookie';\n\n/**\n * Backend-for-frontend route handlers.\n *\n * Mount once, at `app/api/auth/[...lumoauth]/route.ts`:\n *\n * ```ts\n * import { createRouteHandler } from '@lumoauth/nextjs/server';\n * export const { GET, POST } = createRouteHandler();\n * ```\n *\n * The server owns the whole OAuth exchange, so tokens live in an httpOnly\n * cookie and never reach JavaScript. That is what makes `auth()` work in a\n * server component — and therefore what makes a signed-in page render\n * server-side with no loading flash.\n */\n\n// Next 15 types route context params as a Promise and validates the handler\n// signature against it, so the union form is rejected at build time. Typed as\n// Next 15 expects; Next 14 passes a plain object, which `await` handles too.\ntype Ctx = { params: Promise<{ lumoauth?: string[] }> };\n\nfunction authModule(cfg: LumoAuthNextConfig): AuthModule {\n return new AuthModule({ baseUrl: cfg.domain, orgId: cfg.orgId, clientId: cfg.clientId });\n}\n\n/** Same-origin relative paths only — never trust a caller-supplied absolute URL. */\nfunction safeReturnTo(raw: string | null, fallback: string): string {\n if (!raw) return fallback;\n if (!raw.startsWith('/') || raw.startsWith('//')) return fallback;\n return raw;\n}\n\nexport function createRouteHandler(overrides: Partial<LumoAuthNextConfig> = {}) {\n const getCfg = () => resolveConfig(overrides);\n\n async function segments(context: Ctx): Promise<string[]> {\n const p = await context.params;\n return p?.lumoauth ?? [];\n }\n\n async function GET(request: Request, context: Ctx): Promise<Response> {\n const cfg = getCfg();\n const action = (await segments(context))[0];\n const url = new URL(request.url);\n const secure = url.protocol === 'https:';\n\n if (action === 'login') {\n const codeVerifier = generateCodeVerifier();\n const state = generateState();\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n\n const authorize = new URL(\n `${cfg.domain.replace(/\\/+$/, '')}${buildPath(ROUTES['oauth.authorize'].path, { orgId: cfg.orgId })}`,\n );\n authorize.searchParams.set('response_type', 'code');\n authorize.searchParams.set('client_id', cfg.clientId);\n authorize.searchParams.set('redirect_uri', cfg.redirectUri);\n authorize.searchParams.set('scope', cfg.scope!);\n authorize.searchParams.set('code_challenge', codeChallenge);\n authorize.searchParams.set('code_challenge_method', 'S256');\n authorize.searchParams.set('state', state);\n\n const pkce: PkceState = {\n codeVerifier,\n state,\n returnTo: safeReturnTo(url.searchParams.get('return_to'), cfg.afterSignInUrl!),\n };\n\n const res = Response.redirect(authorize.toString(), 302);\n // Response.redirect() produces an immutable Response, so rebuild it\n // to attach the cookie.\n return withCookie(\n res,\n `${PKCE_COOKIE}=${await seal(pkce, cfg.secret)}; ${serialize(cookieOptions(600, secure))}`,\n );\n }\n\n if (action === 'callback') {\n const code = url.searchParams.get('code');\n const returnedState = url.searchParams.get('state');\n const pkce = await unseal<PkceState>(readCookie(request, PKCE_COOKIE), cfg.secret);\n\n if (!code || !returnedState || !pkce) {\n return redirectTo(url.origin + cfg.afterSignOutUrl!, [clearCookie(PKCE_COOKIE, secure)]);\n }\n // CSRF: the state we issued must match the one that came back.\n if (returnedState !== pkce.state) {\n return redirectTo(url.origin + cfg.afterSignOutUrl!, [clearCookie(PKCE_COOKIE, secure)]);\n }\n\n try {\n const tokens = await authModule(cfg).exchangeCodeForTokens({\n code,\n codeVerifier: pkce.codeVerifier,\n redirectUri: cfg.redirectUri,\n ...(cfg.clientSecret ? { clientSecret: cfg.clientSecret } : {}),\n });\n const session: ServerSession = {\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token ?? null,\n idToken: tokens.id_token ?? null,\n // Access-token expiry: short, refreshed in the background.\n expiresAt: Date.now() + tokens.expires_in * 1000,\n // Session expiry: long. The user stays signed in until this\n // passes, however many access tokens come and go.\n sessionExpiresAt: Date.now() + cfg.sessionMaxAge! * 1000,\n };\n return redirectTo(url.origin + pkce.returnTo, [\n `${SESSION_COOKIE}=${await seal(session, cfg.secret)}; ${serialize(cookieOptions(cfg.sessionMaxAge!, secure))}`,\n clearCookie(PKCE_COOKIE, secure),\n ]);\n } catch {\n return redirectTo(url.origin + cfg.afterSignOutUrl!, [clearCookie(PKCE_COOKIE, secure)]);\n }\n }\n\n if (action === 'session') {\n // Read endpoint for `cookieStorageAdapter`. Returns the access token\n // only — the refresh token must never leave the server.\n const session = await unseal<ServerSession>(readCookie(request, SESSION_COOKIE), cfg.secret);\n // Judged on the SESSION, not the access token: reporting \"no\n // session\" for a merely stale token would sign the client out every\n // hour despite a perfectly good session.\n if (!isSessionLive(session)) {\n return Response.json({ accessToken: null, expiresAt: null });\n }\n return Response.json({\n accessToken: session.accessToken,\n idToken: session.idToken,\n expiresAt: session.expiresAt,\n });\n }\n\n if (action === 'logout') return doLogout(cfg, url, request, secure);\n\n return new Response('Not found', { status: 404 });\n }\n\n async function POST(request: Request, context: Ctx): Promise<Response> {\n const cfg = getCfg();\n const action = (await segments(context))[0];\n const url = new URL(request.url);\n if (action === 'logout') return doLogout(cfg, url, request, url.protocol === 'https:');\n return new Response('Not found', { status: 404 });\n }\n\n async function doLogout(\n cfg: LumoAuthNextConfig,\n url: URL,\n request: Request,\n secure: boolean,\n ): Promise<Response> {\n const session = await unseal<ServerSession>(readCookie(request, SESSION_COOKIE), cfg.secret);\n\n // Best-effort revoke before dropping the cookie. A failure here must not\n // block sign-out — the local session is going away regardless.\n if (session?.accessToken) {\n await authModule(cfg)\n .revokeToken(session.accessToken, session.accessToken)\n .catch(() => {});\n }\n\n // End the IdP session too, otherwise the next /authorize silently\n // re-issues a code and the user is never really signed out.\n const logout = new URL(\n `${cfg.domain.replace(/\\/+$/, '')}${buildPath(ROUTES['oauth.logout'].path, { orgId: cfg.orgId })}`,\n );\n logout.searchParams.set('post_logout_redirect_uri', url.origin + cfg.afterSignOutUrl!);\n if (session?.idToken) logout.searchParams.set('id_token_hint', session.idToken);\n\n return redirectTo(logout.toString(), [clearCookie(SESSION_COOKIE, secure)]);\n }\n\n return { GET, POST };\n}\n\n// ── Small cookie/response helpers ────────────────────────────────────\n\nfunction serialize(o: ReturnType<typeof cookieOptions>): string {\n return [\n `Path=${o.path}`,\n `Max-Age=${o.maxAge}`,\n `SameSite=${o.sameSite === 'lax' ? 'Lax' : o.sameSite}`,\n o.httpOnly ? 'HttpOnly' : '',\n o.secure ? 'Secure' : '',\n ]\n .filter(Boolean)\n .join('; ');\n}\n\nfunction clearCookie(name: string, secure: boolean): string {\n return `${name}=; Path=/; Max-Age=0; SameSite=Lax; HttpOnly${secure ? '; Secure' : ''}`;\n}\n\nfunction readCookie(request: Request, name: string): string | undefined {\n const header = request.headers.get('cookie');\n if (!header) return undefined;\n const hit = header.split('; ').find((c) => c.startsWith(`${name}=`));\n return hit?.slice(name.length + 1);\n}\n\nfunction redirectTo(location: string, cookies: string[]): Response {\n const headers = new Headers({ Location: location });\n cookies.forEach((c) => headers.append('Set-Cookie', c));\n return new Response(null, { status: 302, headers });\n}\n\nfunction withCookie(res: Response, cookie: string): Response {\n const headers = new Headers(res.headers);\n headers.append('Set-Cookie', cookie);\n return new Response(res.body, { status: res.status, headers });\n}\n","import { NextResponse, type NextRequest } from 'next/server';\nimport { AuthModule } from '@lumoauth/shared';\nimport { resolveConfig, type LumoAuthNextConfig } from './config';\nimport {\n SESSION_COOKIE,\n REFRESHED_SESSION_HEADER,\n cookieOptions,\n isSessionLive,\n isTokenStale,\n seal,\n unseal,\n type ServerSession,\n} from './session-cookie';\n\nexport interface MiddlewareOptions extends Partial<LumoAuthNextConfig> {\n /**\n * Paths requiring a session. Accepts globs (`/dashboard/:path*`), regexes,\n * or a predicate. Everything else is public.\n */\n protect?: Array<string | RegExp> | ((req: NextRequest) => boolean);\n /**\n * Keep the access token fresh automatically. @default true\n *\n * Turning this off means `auth().getToken()` returns null once the token\n * goes stale, because nothing else in the request pipeline is able to\n * persist a refreshed one.\n */\n refresh?: boolean;\n}\n\n/** Turn `/dashboard/:path*` into a RegExp. */\nfunction toMatcher(pattern: string | RegExp): RegExp {\n if (pattern instanceof RegExp) return pattern;\n const source = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\/:path\\*/g, '(?:/.*)?')\n .replace(/\\*/g, '.*');\n return new RegExp(`^${source}$`);\n}\n\n/**\n * Session refresh and route protection.\n *\n * ```ts\n * // middleware.ts\n * import { lumoAuthMiddleware } from '@lumoauth/nextjs/server';\n *\n * export default lumoAuthMiddleware({ protect: ['/dashboard/:path*'] });\n * export const config = { matcher: ['/((?!_next|.*\\\\..*).*)'] };\n * ```\n *\n * ## Why refresh belongs here\n *\n * An access token lasts about an hour; a session lasts weeks. Something has to\n * trade the refresh token for a new access token, and in Next.js that can only\n * happen where cookies are writable: middleware, route handlers, and server\n * actions. Server components cannot set cookies, so they can never persist a\n * refresh.\n *\n * That distinction is not cosmetic. LumoAuth rotates refresh tokens and revokes\n * the old one on use, so refreshing somewhere that cannot persist the result\n * would spend the token and break the session on the next request. Middleware\n * runs before the page renders and can write the response cookie, so it is the\n * correct place.\n *\n * Because middleware writes the cookie on the *response* while the page reads\n * the *request*, the fresh session is also forwarded on a request header that\n * `auth()` prefers — otherwise the refresh would not take effect until the\n * following request.\n */\nexport function lumoAuthMiddleware(options: MiddlewareOptions = {}) {\n const { protect = [], refresh = true, ...configOverrides } = options;\n\n return async function middleware(req: NextRequest) {\n const isProtected =\n typeof protect === 'function'\n ? protect(req)\n : protect.map(toMatcher).some((m) => m.test(req.nextUrl.pathname));\n\n const cfg = resolveConfig(configOverrides);\n const rawCookie = req.cookies.get(SESSION_COOKIE)?.value;\n const session = await unseal<ServerSession>(rawCookie, cfg.secret);\n\n // ── No live session ──────────────────────────────────────────\n if (!isSessionLive(session)) {\n if (!isProtected) {\n if (!rawCookie) return NextResponse.next();\n const res = NextResponse.next();\n res.cookies.delete(SESSION_COOKIE);\n return res;\n }\n const login = new URL('/api/auth/login', req.nextUrl.origin);\n login.searchParams.set('return_to', req.nextUrl.pathname + req.nextUrl.search);\n const res = NextResponse.redirect(login);\n // Drop the cookie whenever one was sent but is unusable — expired,\n // tampered with, or sealed under a rotated secret. Keying this on a\n // successfully parsed session would skip exactly the case that\n // needs clearing, and the browser would resend it forever.\n if (rawCookie) res.cookies.delete(SESSION_COOKIE);\n return res;\n }\n\n // ── Live session, token still good ───────────────────────────\n if (!refresh || !isTokenStale(session)) return NextResponse.next();\n\n // ── Live session, stale token: refresh and persist ───────────\n if (!session.refreshToken) {\n // Nothing to refresh with. The session is only as live as the\n // access token, which has just gone stale.\n if (!isProtected) return NextResponse.next();\n const login = new URL('/api/auth/login', req.nextUrl.origin);\n login.searchParams.set('return_to', req.nextUrl.pathname + req.nextUrl.search);\n return NextResponse.redirect(login);\n }\n\n try {\n const mod = new AuthModule({\n baseUrl: cfg.domain,\n orgId: cfg.orgId,\n clientId: cfg.clientId,\n });\n const tokens = await mod.refreshToken(session.refreshToken);\n\n const next: ServerSession = {\n accessToken: tokens.access_token,\n // Keep the existing token when the server does not rotate;\n // losing it here would silently end the session at the next\n // refresh.\n refreshToken: tokens.refresh_token ?? session.refreshToken,\n idToken: tokens.id_token ?? session.idToken,\n expiresAt: Date.now() + tokens.expires_in * 1000,\n sessionExpiresAt: session.sessionExpiresAt,\n };\n const sealed = await seal(next, cfg.secret);\n\n // Forward to the page rendering THIS request...\n const headers = new Headers(req.headers);\n headers.set(REFRESHED_SESSION_HEADER, sealed);\n const res = NextResponse.next({ request: { headers } });\n\n // ...and persist for the next one.\n const opts = cookieOptions(cfg.sessionMaxAge!, req.nextUrl.protocol === 'https:');\n res.cookies.set(SESSION_COOKIE, sealed, opts);\n return res;\n } catch {\n // The refresh token was rejected — revoked, rotated away, or the\n // session ended server-side. Treat it as signed out rather than\n // leaving a cookie that can never succeed.\n const res = isProtected\n ? NextResponse.redirect(new URL('/api/auth/login', req.nextUrl.origin))\n : NextResponse.next();\n res.cookies.delete(SESSION_COOKIE);\n return res;\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,yBAAO;;;ACLP,qBAAiC;AACjC,oBAA0C;;;AC8BnC,SAAS,cA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