@lumoauth/nextjs 1.4.0 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -14
- package/dist/index.d.mts +7 -2
- package/dist/index.d.ts +7 -2
- package/dist/index.js +12 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +11 -1
- package/dist/index.mjs.map +1 -1
- package/dist/server.d.mts +23 -3
- package/dist/server.d.ts +23 -3
- package/dist/server.js +79 -28
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +79 -28
- package/dist/server.mjs.map +1 -1
- package/package.json +2 -2
package/dist/server.js
CHANGED
|
@@ -48,31 +48,52 @@ var import_server_only = require("server-only");
|
|
|
48
48
|
var import_headers = require("next/headers");
|
|
49
49
|
var import_shared = require("@lumoauth/shared");
|
|
50
50
|
|
|
51
|
+
// src/defaults.ts
|
|
52
|
+
var DEFAULT_DOMAIN = "https://app.lumoauth.dev";
|
|
53
|
+
var CALLBACK_PATH = "/api/auth/callback";
|
|
54
|
+
var LOGIN_PATH = "/api/auth/login";
|
|
55
|
+
|
|
51
56
|
// src/config.ts
|
|
57
|
+
var REQUIRED = [
|
|
58
|
+
["orgId", "NEXT_PUBLIC_LUMOAUTH_ORG_ID"],
|
|
59
|
+
["clientId", "NEXT_PUBLIC_LUMOAUTH_CLIENT_ID"],
|
|
60
|
+
["secret", "LUMOAUTH_SECRET"]
|
|
61
|
+
];
|
|
52
62
|
function resolveConfig(overrides = {}) {
|
|
53
63
|
const env = process.env;
|
|
54
64
|
const cfg = {
|
|
55
|
-
domain: overrides.domain
|
|
56
|
-
orgId: overrides.orgId
|
|
57
|
-
clientId: overrides.clientId
|
|
58
|
-
clientSecret: overrides.clientSecret
|
|
59
|
-
secret: overrides.secret
|
|
60
|
-
redirectUri: overrides.redirectUri
|
|
65
|
+
domain: (overrides.domain || env.NEXT_PUBLIC_LUMOAUTH_DOMAIN || DEFAULT_DOMAIN).replace(/\/+$/, ""),
|
|
66
|
+
orgId: overrides.orgId || env.NEXT_PUBLIC_LUMOAUTH_ORG_ID || "",
|
|
67
|
+
clientId: overrides.clientId || env.NEXT_PUBLIC_LUMOAUTH_CLIENT_ID || "",
|
|
68
|
+
clientSecret: overrides.clientSecret || env.LUMOAUTH_CLIENT_SECRET || void 0,
|
|
69
|
+
secret: overrides.secret || env.LUMOAUTH_SECRET || "",
|
|
70
|
+
redirectUri: overrides.redirectUri || env.NEXT_PUBLIC_REDIRECT_URI || void 0,
|
|
61
71
|
afterSignOutUrl: overrides.afterSignOutUrl ?? "/",
|
|
62
72
|
afterSignInUrl: overrides.afterSignInUrl ?? "/",
|
|
63
73
|
scope: overrides.scope ?? "openid profile email",
|
|
64
74
|
sessionMaxAge: overrides.sessionMaxAge ?? 60 * 60 * 24 * 30
|
|
65
75
|
};
|
|
66
|
-
const missing = [
|
|
67
|
-
(k) => !cfg[k]
|
|
68
|
-
);
|
|
76
|
+
const missing = REQUIRED.filter(([key]) => !cfg[key]);
|
|
69
77
|
if (missing.length) {
|
|
70
78
|
throw new Error(
|
|
71
|
-
`@lumoauth/nextjs is missing required config: ${missing.join(", ")}. Set
|
|
79
|
+
`@lumoauth/nextjs is missing required config: ${missing.map(([, name]) => name).join(", ")}. Set NEXT_PUBLIC_LUMOAUTH_ORG_ID, NEXT_PUBLIC_LUMOAUTH_CLIENT_ID and LUMOAUTH_SECRET (NEXT_PUBLIC_LUMOAUTH_DOMAIN only for the EU region: https://eu.app.lumoauth.dev), or pass them to createRouteHandler({ ... }).`
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
if (cfg.redirectUri && !isAbsoluteHttpUrl(cfg.redirectUri)) {
|
|
83
|
+
throw new Error(
|
|
84
|
+
`@lumoauth/nextjs: NEXT_PUBLIC_REDIRECT_URI must be an absolute URL such as https://app.example.com/api/auth/callback. Leave it unset to use the address of each request.`
|
|
72
85
|
);
|
|
73
86
|
}
|
|
74
87
|
return cfg;
|
|
75
88
|
}
|
|
89
|
+
function isAbsoluteHttpUrl(value) {
|
|
90
|
+
try {
|
|
91
|
+
const { protocol } = new URL(value);
|
|
92
|
+
return protocol === "https:" || protocol === "http:";
|
|
93
|
+
} catch {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
76
97
|
|
|
77
98
|
// src/session-cookie.ts
|
|
78
99
|
var SESSION_COOKIE = "lumo_session";
|
|
@@ -200,13 +221,37 @@ async function protectPage(opts = {}) {
|
|
|
200
221
|
if (!result.isSignedIn) {
|
|
201
222
|
const { redirect } = await import("next/navigation");
|
|
202
223
|
const qs = opts.returnTo ? `?return_to=${encodeURIComponent(opts.returnTo)}` : "";
|
|
203
|
-
redirect(
|
|
224
|
+
redirect(`${LOGIN_PATH}${qs}`);
|
|
204
225
|
}
|
|
205
226
|
return result;
|
|
206
227
|
}
|
|
207
228
|
|
|
208
229
|
// src/route-handler.ts
|
|
209
230
|
var import_shared2 = require("@lumoauth/shared");
|
|
231
|
+
|
|
232
|
+
// src/origin.ts
|
|
233
|
+
var HOST = /^(?:[a-z0-9.-]+|\[[0-9a-f:.]+\])(?::\d{1,5})?$/i;
|
|
234
|
+
function firstValue(header) {
|
|
235
|
+
return (header ?? "").split(",")[0].trim();
|
|
236
|
+
}
|
|
237
|
+
function appOrigin(request, cfg) {
|
|
238
|
+
if (cfg.redirectUri) return new URL(cfg.redirectUri).origin;
|
|
239
|
+
const url = new URL(request.url);
|
|
240
|
+
const host = firstValue(request.headers.get("x-forwarded-host")) || firstValue(request.headers.get("host"));
|
|
241
|
+
if (!host || !HOST.test(host)) return url.origin;
|
|
242
|
+
const forwarded = firstValue(request.headers.get("x-forwarded-proto")).toLowerCase();
|
|
243
|
+
const protocol = forwarded === "https" || forwarded === "http" ? forwarded : url.protocol.slice(0, -1);
|
|
244
|
+
try {
|
|
245
|
+
return new URL(`${protocol}://${host}`).origin;
|
|
246
|
+
} catch {
|
|
247
|
+
return url.origin;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
function callbackUrl(origin, cfg) {
|
|
251
|
+
return cfg.redirectUri || origin + CALLBACK_PATH;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// src/route-handler.ts
|
|
210
255
|
function authModule(cfg) {
|
|
211
256
|
return new import_shared2.AuthModule({ baseUrl: cfg.domain, orgId: cfg.orgId, clientId: cfg.clientId });
|
|
212
257
|
}
|
|
@@ -225,8 +270,10 @@ function createRouteHandler(overrides = {}) {
|
|
|
225
270
|
const cfg = getCfg();
|
|
226
271
|
const action = (await segments(context))[0];
|
|
227
272
|
const url = new URL(request.url);
|
|
228
|
-
const
|
|
273
|
+
const origin = appOrigin(request, cfg);
|
|
274
|
+
const secure = origin.startsWith("https:");
|
|
229
275
|
if (action === "login") {
|
|
276
|
+
const redirectUri = callbackUrl(origin, cfg);
|
|
230
277
|
const codeVerifier = (0, import_shared2.generateCodeVerifier)();
|
|
231
278
|
const state = (0, import_shared2.generateState)();
|
|
232
279
|
const codeChallenge = await (0, import_shared2.generateCodeChallenge)(codeVerifier);
|
|
@@ -235,7 +282,7 @@ function createRouteHandler(overrides = {}) {
|
|
|
235
282
|
);
|
|
236
283
|
authorize.searchParams.set("response_type", "code");
|
|
237
284
|
authorize.searchParams.set("client_id", cfg.clientId);
|
|
238
|
-
authorize.searchParams.set("redirect_uri",
|
|
285
|
+
authorize.searchParams.set("redirect_uri", redirectUri);
|
|
239
286
|
authorize.searchParams.set("scope", cfg.scope);
|
|
240
287
|
authorize.searchParams.set("code_challenge", codeChallenge);
|
|
241
288
|
authorize.searchParams.set("code_challenge_method", "S256");
|
|
@@ -243,7 +290,10 @@ function createRouteHandler(overrides = {}) {
|
|
|
243
290
|
const pkce = {
|
|
244
291
|
codeVerifier,
|
|
245
292
|
state,
|
|
246
|
-
returnTo: safeReturnTo(url.searchParams.get("return_to"), cfg.afterSignInUrl)
|
|
293
|
+
returnTo: safeReturnTo(url.searchParams.get("return_to"), cfg.afterSignInUrl),
|
|
294
|
+
// The token request must repeat the redirect_uri of the
|
|
295
|
+
// authorization request exactly, so keep the one that was sent.
|
|
296
|
+
redirectUri
|
|
247
297
|
};
|
|
248
298
|
const res = Response.redirect(authorize.toString(), 302);
|
|
249
299
|
return withCookie(
|
|
@@ -256,16 +306,16 @@ function createRouteHandler(overrides = {}) {
|
|
|
256
306
|
const returnedState = url.searchParams.get("state");
|
|
257
307
|
const pkce = await unseal(readCookie(request, PKCE_COOKIE), cfg.secret);
|
|
258
308
|
if (!code || !returnedState || !pkce) {
|
|
259
|
-
return redirectTo(
|
|
309
|
+
return redirectTo(origin + cfg.afterSignOutUrl, [clearCookie(PKCE_COOKIE, secure)]);
|
|
260
310
|
}
|
|
261
311
|
if (returnedState !== pkce.state) {
|
|
262
|
-
return redirectTo(
|
|
312
|
+
return redirectTo(origin + cfg.afterSignOutUrl, [clearCookie(PKCE_COOKIE, secure)]);
|
|
263
313
|
}
|
|
264
314
|
try {
|
|
265
315
|
const tokens = await authModule(cfg).exchangeCodeForTokens({
|
|
266
316
|
code,
|
|
267
317
|
codeVerifier: pkce.codeVerifier,
|
|
268
|
-
redirectUri:
|
|
318
|
+
redirectUri: pkce.redirectUri ?? callbackUrl(origin, cfg),
|
|
269
319
|
...cfg.clientSecret ? { clientSecret: cfg.clientSecret } : {}
|
|
270
320
|
});
|
|
271
321
|
const session = {
|
|
@@ -278,12 +328,12 @@ function createRouteHandler(overrides = {}) {
|
|
|
278
328
|
// passes, however many access tokens come and go.
|
|
279
329
|
sessionExpiresAt: Date.now() + cfg.sessionMaxAge * 1e3
|
|
280
330
|
};
|
|
281
|
-
return redirectTo(
|
|
331
|
+
return redirectTo(origin + pkce.returnTo, [
|
|
282
332
|
`${SESSION_COOKIE}=${await seal(session, cfg.secret)}; ${serialize(cookieOptions(cfg.sessionMaxAge, secure))}`,
|
|
283
333
|
clearCookie(PKCE_COOKIE, secure)
|
|
284
334
|
]);
|
|
285
335
|
} catch {
|
|
286
|
-
return redirectTo(
|
|
336
|
+
return redirectTo(origin + cfg.afterSignOutUrl, [clearCookie(PKCE_COOKIE, secure)]);
|
|
287
337
|
}
|
|
288
338
|
}
|
|
289
339
|
if (action === "session") {
|
|
@@ -297,17 +347,17 @@ function createRouteHandler(overrides = {}) {
|
|
|
297
347
|
expiresAt: session.expiresAt
|
|
298
348
|
});
|
|
299
349
|
}
|
|
300
|
-
if (action === "logout") return doLogout(cfg,
|
|
350
|
+
if (action === "logout") return doLogout(cfg, origin, request, secure);
|
|
301
351
|
return new Response("Not found", { status: 404 });
|
|
302
352
|
}
|
|
303
353
|
async function POST(request, context) {
|
|
304
354
|
const cfg = getCfg();
|
|
305
355
|
const action = (await segments(context))[0];
|
|
306
|
-
const
|
|
307
|
-
if (action === "logout") return doLogout(cfg,
|
|
356
|
+
const origin = appOrigin(request, cfg);
|
|
357
|
+
if (action === "logout") return doLogout(cfg, origin, request, origin.startsWith("https:"));
|
|
308
358
|
return new Response("Not found", { status: 404 });
|
|
309
359
|
}
|
|
310
|
-
async function doLogout(cfg,
|
|
360
|
+
async function doLogout(cfg, origin, request, secure) {
|
|
311
361
|
const session = await unseal(readCookie(request, SESSION_COOKIE), cfg.secret);
|
|
312
362
|
if (session?.accessToken) {
|
|
313
363
|
await authModule(cfg).revokeToken(session.accessToken, session.accessToken).catch(() => {
|
|
@@ -316,7 +366,7 @@ function createRouteHandler(overrides = {}) {
|
|
|
316
366
|
const logout = new URL(
|
|
317
367
|
`${cfg.domain.replace(/\/+$/, "")}${(0, import_shared2.buildPath)(import_shared2.ROUTES["oauth.logout"].path, { orgId: cfg.orgId })}`
|
|
318
368
|
);
|
|
319
|
-
logout.searchParams.set("post_logout_redirect_uri",
|
|
369
|
+
logout.searchParams.set("post_logout_redirect_uri", origin + cfg.afterSignOutUrl);
|
|
320
370
|
if (session?.idToken) logout.searchParams.set("id_token_hint", session.idToken);
|
|
321
371
|
return redirectTo(logout.toString(), [clearCookie(SESSION_COOKIE, secure)]);
|
|
322
372
|
}
|
|
@@ -364,6 +414,7 @@ function lumoAuthMiddleware(options = {}) {
|
|
|
364
414
|
return async function middleware(req) {
|
|
365
415
|
const isProtected = typeof protect === "function" ? protect(req) : protect.map(toMatcher).some((m) => m.test(req.nextUrl.pathname));
|
|
366
416
|
const cfg = resolveConfig(configOverrides);
|
|
417
|
+
const origin = appOrigin(req, cfg);
|
|
367
418
|
const rawCookie = req.cookies.get(SESSION_COOKIE)?.value;
|
|
368
419
|
const session = await unseal(rawCookie, cfg.secret);
|
|
369
420
|
if (!isSessionLive(session)) {
|
|
@@ -373,7 +424,7 @@ function lumoAuthMiddleware(options = {}) {
|
|
|
373
424
|
res2.cookies.delete(SESSION_COOKIE);
|
|
374
425
|
return res2;
|
|
375
426
|
}
|
|
376
|
-
const login = new URL(
|
|
427
|
+
const login = new URL(LOGIN_PATH, origin);
|
|
377
428
|
login.searchParams.set("return_to", req.nextUrl.pathname + req.nextUrl.search);
|
|
378
429
|
const res = import_server.NextResponse.redirect(login);
|
|
379
430
|
if (rawCookie) res.cookies.delete(SESSION_COOKIE);
|
|
@@ -382,7 +433,7 @@ function lumoAuthMiddleware(options = {}) {
|
|
|
382
433
|
if (!refresh || !isTokenStale(session)) return import_server.NextResponse.next();
|
|
383
434
|
if (!session.refreshToken) {
|
|
384
435
|
if (!isProtected) return import_server.NextResponse.next();
|
|
385
|
-
const login = new URL(
|
|
436
|
+
const login = new URL(LOGIN_PATH, origin);
|
|
386
437
|
login.searchParams.set("return_to", req.nextUrl.pathname + req.nextUrl.search);
|
|
387
438
|
return import_server.NextResponse.redirect(login);
|
|
388
439
|
}
|
|
@@ -407,11 +458,11 @@ function lumoAuthMiddleware(options = {}) {
|
|
|
407
458
|
const headers2 = new Headers(req.headers);
|
|
408
459
|
headers2.set(REFRESHED_SESSION_HEADER, sealed);
|
|
409
460
|
const res = import_server.NextResponse.next({ request: { headers: headers2 } });
|
|
410
|
-
const opts = cookieOptions(cfg.sessionMaxAge,
|
|
461
|
+
const opts = cookieOptions(cfg.sessionMaxAge, origin.startsWith("https:"));
|
|
411
462
|
res.cookies.set(SESSION_COOKIE, sealed, opts);
|
|
412
463
|
return res;
|
|
413
464
|
} catch {
|
|
414
|
-
const res = isProtected ? import_server.NextResponse.redirect(new URL(
|
|
465
|
+
const res = isProtected ? import_server.NextResponse.redirect(new URL(LOGIN_PATH, origin)) : import_server.NextResponse.next();
|
|
415
466
|
res.cookies.delete(SESSION_COOKIE);
|
|
416
467
|
return res;
|
|
417
468
|
}
|
package/dist/server.js.map
CHANGED
|
@@ -1 +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 // Prefer the header: if middleware refreshed during THIS request, the\n // request cookie still holds the pre-refresh value.\n // Call headers()/cookies() before resolveConfig() so Next.js detects\n // dynamic usage during `next build` without requiring runtime secrets\n // at build time.\n const hdrs = await headers();\n const jar = await cookies();\n const cfg = resolveConfig(overrides);\n const fromHeader = await unseal<ServerSession>(\n hdrs.get(REFRESHED_SESSION_HEADER) ?? undefined,\n cfg.secret,\n );\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 { getToken, isSignedIn } = await auth(overrides);\n if (!isSignedIn) return null;\n\n const token = getToken();\n if (!token) return null;\n\n const cfg = resolveConfig(overrides);\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,cAAc,YAAyC,CAAC,GAAuB;AAC3F,QAAM,MAAM,QAAQ;AACpB,QAAM,MAA0B;AAAA,IAC5B,QAAQ,UAAU,UAAU,IAAI,+BAA+B;AAAA,IAC/D,OAAO,UAAU,SAAS,IAAI,+BAA+B;AAAA,IAC7D,UAAU,UAAU,YAAY,IAAI,kCAAkC;AAAA,IACtE,cAAc,UAAU,gBAAgB,IAAI;AAAA,IAC5C,QAAQ,UAAU,UAAU,IAAI,mBAAmB;AAAA,IACnD,aAAa,UAAU,eAAe,IAAI,4BAA4B;AAAA,IACtE,iBAAiB,UAAU,mBAAmB;AAAA,IAC9C,gBAAgB,UAAU,kBAAkB;AAAA,IAC5C,OAAO,UAAU,SAAS;AAAA,IAC1B,eAAe,UAAU,iBAAiB,KAAK,KAAK,KAAK;AAAA,EAC7D;AAEA,QAAM,UAAW,C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AO,YAAY,QAAQ;AAAA,QACpC,WAAW,KAAK,IAAI,IAAI,OAAO,aAAa;AAAA,QAC5C,kBAAkB,QAAQ;AAAA,MAC9B;AACA,YAAM,SAAS,MAAM,KAAK,MAAM,IAAI,MAAM;AAG1C,YAAMC,WAAU,IAAI,QAAQ,IAAI,OAAO;AACvC,MAAAA,SAAQ,IAAI,0BAA0B,MAAM;AAC5C,YAAM,MAAM,2BAAa,KAAK,EAAE,SAAS,EAAE,SAAAA,SAAQ,EAAE,CAAC;AAGtD,YAAM,OAAO,cAAc,IAAI,eAAgB,IAAI,QAAQ,aAAa,QAAQ;AAChF,UAAI,QAAQ,IAAI,gBAAgB,QAAQ,IAAI;AAC5C,aAAO;AAAA,IACX,QAAQ;AAIJ,YAAM,MAAM,cACN,2BAAa,SAAS,IAAI,IAAI,mBAAmB,IAAI,QAAQ,MAAM,CAAC,IACpE,2BAAa,KAAK;AACxB,UAAI,QAAQ,OAAO,cAAc;AACjC,aAAO;AAAA,IACX;AAAA,EACJ;AACJ;","names":["import_shared","cookies","headers","import_shared","res","headers"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/auth.ts","../src/defaults.ts","../src/config.ts","../src/session-cookie.ts","../src/route-handler.ts","../src/origin.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 { LOGIN_PATH } from './defaults';\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 // Prefer the header: if middleware refreshed during THIS request, the\n // request cookie still holds the pre-refresh value.\n // Call headers()/cookies() before resolveConfig() so Next.js detects\n // dynamic usage during `next build` without requiring runtime secrets\n // at build time.\n const hdrs = await headers();\n const jar = await cookies();\n const cfg = resolveConfig(overrides);\n const fromHeader = await unseal<ServerSession>(\n hdrs.get(REFRESHED_SESSION_HEADER) ?? undefined,\n cfg.secret,\n );\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 { getToken, isSignedIn } = await auth(overrides);\n if (!isSignedIn) return null;\n\n const token = getToken();\n if (!token) return null;\n\n const cfg = resolveConfig(overrides);\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(`${LOGIN_PATH}${qs}`);\n }\n return result;\n}\n","// Shared by the client and the server entry, so it must not import anything\n// server-only.\n\n/** US region. EU organizations set NEXT_PUBLIC_LUMOAUTH_DOMAIN=https://eu.app.lumoauth.dev. */\nexport const DEFAULT_DOMAIN = 'https://app.lumoauth.dev';\n\n/**\n * Where `createRouteHandler()` receives the authorization response. Fixed,\n * like the login path that the middleware and `protectPage()` redirect to,\n * so the URL to register is always `{app origin}/api/auth/callback`.\n */\nexport const CALLBACK_PATH = '/api/auth/callback';\n\n/** The login route of `createRouteHandler()`. */\nexport const LOGIN_PATH = '/api/auth/login';\n","import { DEFAULT_DOMAIN } from './defaults';\n\nexport interface LumoAuthNextConfig {\n /**\n * Base URL of the LumoAuth region of the organization.\n * @default 'https://app.lumoauth.dev' (US). EU: 'https://eu.app.lumoauth.dev'.\n */\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 /**\n * Absolute redirect URI registered with the OAuth client.\n *\n * Optional. By default each sign-in uses `{origin}/api/auth/callback`,\n * where `{origin}` is the public address of the request (the\n * `X-Forwarded-Host` / `Host` header), so the same build works on\n * localhost, on preview deployments and in production. Set it only to pin\n * the app to one address; its origin then also becomes the origin of\n * every redirect back to the app.\n */\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/** Environment variable behind each required value, for the error message. */\nconst REQUIRED: Array<[keyof LumoAuthNextConfig, string]> = [\n ['orgId', 'NEXT_PUBLIC_LUMOAUTH_ORG_ID'],\n ['clientId', 'NEXT_PUBLIC_LUMOAUTH_CLIENT_ID'],\n ['secret', 'LUMOAUTH_SECRET'],\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 *\n * An empty variable counts as unset: hosting dashboards and app builders\n * often create a variable with an empty value.\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 || DEFAULT_DOMAIN).replace(/\\/+$/, ''),\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 || undefined,\n secret: overrides.secret || env.LUMOAUTH_SECRET || '',\n redirectUri: overrides.redirectUri || env.NEXT_PUBLIC_REDIRECT_URI || undefined,\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 = REQUIRED.filter(([key]) => !cfg[key]);\n if (missing.length) {\n throw new Error(\n `@lumoauth/nextjs is missing required config: ${missing.map(([, name]) => name).join(', ')}. ` +\n 'Set NEXT_PUBLIC_LUMOAUTH_ORG_ID, NEXT_PUBLIC_LUMOAUTH_CLIENT_ID and LUMOAUTH_SECRET ' +\n '(NEXT_PUBLIC_LUMOAUTH_DOMAIN only for the EU region: https://eu.app.lumoauth.dev), ' +\n 'or pass them to createRouteHandler({ ... }).',\n );\n }\n if (cfg.redirectUri && !isAbsoluteHttpUrl(cfg.redirectUri)) {\n throw new Error(\n `@lumoauth/nextjs: NEXT_PUBLIC_REDIRECT_URI must be an absolute URL such as ` +\n `https://app.example.com/api/auth/callback. Leave it unset to use the address of each request.`,\n );\n }\n return cfg;\n}\n\n// Not URL.canParse(): it needs Node 18.17, and the package supports Node 18.0.\nfunction isAbsoluteHttpUrl(value: string): boolean {\n try {\n const { protocol } = new URL(value);\n return protocol === 'https:' || protocol === 'http:';\n } catch {\n return false;\n }\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 * The redirect_uri of the authorization request. The token request repeats\n * it. Missing in a cookie that an older version of this package wrote.\n */\n redirectUri?: 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 { appOrigin, callbackUrl } from './origin';\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 * Register `{app origin}/api/auth/callback` as a redirect URI of the\n * application, for every address the app runs on (localhost, previews,\n * production). The handler builds that URL from each request, so no\n * environment variable names it.\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 // The address that the browser used, not the one that Next.js\n // listens on. See appOrigin().\n const origin = appOrigin(request, cfg);\n const secure = origin.startsWith('https:');\n\n if (action === 'login') {\n const redirectUri = callbackUrl(origin, cfg);\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', 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 // The token request must repeat the redirect_uri of the\n // authorization request exactly, so keep the one that was sent.\n redirectUri,\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(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(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: pkce.redirectUri ?? callbackUrl(origin, cfg),\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(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(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, origin, 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 origin = appOrigin(request, cfg);\n if (action === 'logout') return doLogout(cfg, origin, request, origin.startsWith('https:'));\n return new Response('Not found', { status: 404 });\n }\n\n async function doLogout(\n cfg: LumoAuthNextConfig,\n origin: string,\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', 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 type { LumoAuthNextConfig } from './config';\nimport { CALLBACK_PATH } from './defaults';\n\n// host or host:port, or a bracketed IPv6 literal. Anything else (a path, a\n// user-info part, whitespace) is not a host and is ignored.\nconst HOST = /^(?:[a-z0-9.-]+|\\[[0-9a-f:.]+\\])(?::\\d{1,5})?$/i;\n\nfunction firstValue(header: string | null): string {\n return (header ?? '').split(',')[0].trim();\n}\n\n/**\n * The public origin of the app, for this request.\n *\n * `request.url` is not enough. A `next dev` or `next start` server that runs\n * behind a proxy (a preview sandbox, a container platform, a load balancer)\n * builds `request.url` from the address that it listens on, such as\n * `http://localhost:3000`. Next.js sets `X-Forwarded-Host` and\n * `X-Forwarded-Proto` on every request, from the proxy or from `Host`, so\n * those headers carry the address that the browser used. Auth.js and\n * nextjs-auth0 read the same headers.\n *\n * Trusting them is safe here: LumoAuth accepts a redirect URI or a\n * post-logout redirect URI only when it is registered on the application, so\n * a forged header cannot send a code anywhere new. The other redirects that\n * use the origin go back to the browser that sent the forged header.\n *\n * A configured `redirectUri` pins the origin and wins over the headers.\n */\nexport function appOrigin(\n request: { url: string; headers: Headers },\n cfg: Pick<LumoAuthNextConfig, 'redirectUri'>,\n): string {\n if (cfg.redirectUri) return new URL(cfg.redirectUri).origin;\n\n const url = new URL(request.url);\n const host =\n firstValue(request.headers.get('x-forwarded-host')) || firstValue(request.headers.get('host'));\n if (!host || !HOST.test(host)) return url.origin;\n\n const forwarded = firstValue(request.headers.get('x-forwarded-proto')).toLowerCase();\n const protocol = forwarded === 'https' || forwarded === 'http' ? forwarded : url.protocol.slice(0, -1);\n try {\n // Through URL so that a default port (:443, :80) is dropped and the\n // host is lower-cased, the same as a registered URI.\n return new URL(`${protocol}://${host}`).origin;\n } catch {\n return url.origin;\n }\n}\n\n/** The redirect URI that a sign-in from `origin` sends to LumoAuth. */\nexport function callbackUrl(origin: string, cfg: Pick<LumoAuthNextConfig, 'redirectUri'>): string {\n return cfg.redirectUri || origin + CALLBACK_PATH;\n}\n","import { NextResponse, type NextRequest } from 'next/server';\nimport { AuthModule } from '@lumoauth/shared';\nimport { resolveConfig, type LumoAuthNextConfig } from './config';\nimport { LOGIN_PATH } from './defaults';\nimport { appOrigin } from './origin';\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 // req.nextUrl.origin is the address Next.js listens on, which behind a\n // proxy is not the one the browser used. See appOrigin().\n const origin = appOrigin(req, cfg);\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(LOGIN_PATH, 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(LOGIN_PATH, 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!, origin.startsWith('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(LO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