@lumoauth/nextjs 1.3.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.mjs
CHANGED
|
@@ -5,31 +5,52 @@ import "server-only";
|
|
|
5
5
|
import { cookies, headers } from "next/headers";
|
|
6
6
|
import { AuthModule } from "@lumoauth/shared";
|
|
7
7
|
|
|
8
|
+
// src/defaults.ts
|
|
9
|
+
var DEFAULT_DOMAIN = "https://app.lumoauth.dev";
|
|
10
|
+
var CALLBACK_PATH = "/api/auth/callback";
|
|
11
|
+
var LOGIN_PATH = "/api/auth/login";
|
|
12
|
+
|
|
8
13
|
// src/config.ts
|
|
14
|
+
var REQUIRED = [
|
|
15
|
+
["orgId", "NEXT_PUBLIC_LUMOAUTH_ORG_ID"],
|
|
16
|
+
["clientId", "NEXT_PUBLIC_LUMOAUTH_CLIENT_ID"],
|
|
17
|
+
["secret", "LUMOAUTH_SECRET"]
|
|
18
|
+
];
|
|
9
19
|
function resolveConfig(overrides = {}) {
|
|
10
20
|
const env = process.env;
|
|
11
21
|
const cfg = {
|
|
12
|
-
domain: overrides.domain
|
|
13
|
-
orgId: overrides.orgId
|
|
14
|
-
clientId: overrides.clientId
|
|
15
|
-
clientSecret: overrides.clientSecret
|
|
16
|
-
secret: overrides.secret
|
|
17
|
-
redirectUri: overrides.redirectUri
|
|
22
|
+
domain: (overrides.domain || env.NEXT_PUBLIC_LUMOAUTH_DOMAIN || DEFAULT_DOMAIN).replace(/\/+$/, ""),
|
|
23
|
+
orgId: overrides.orgId || env.NEXT_PUBLIC_LUMOAUTH_ORG_ID || "",
|
|
24
|
+
clientId: overrides.clientId || env.NEXT_PUBLIC_LUMOAUTH_CLIENT_ID || "",
|
|
25
|
+
clientSecret: overrides.clientSecret || env.LUMOAUTH_CLIENT_SECRET || void 0,
|
|
26
|
+
secret: overrides.secret || env.LUMOAUTH_SECRET || "",
|
|
27
|
+
redirectUri: overrides.redirectUri || env.NEXT_PUBLIC_REDIRECT_URI || void 0,
|
|
18
28
|
afterSignOutUrl: overrides.afterSignOutUrl ?? "/",
|
|
19
29
|
afterSignInUrl: overrides.afterSignInUrl ?? "/",
|
|
20
30
|
scope: overrides.scope ?? "openid profile email",
|
|
21
31
|
sessionMaxAge: overrides.sessionMaxAge ?? 60 * 60 * 24 * 30
|
|
22
32
|
};
|
|
23
|
-
const missing = [
|
|
24
|
-
(k) => !cfg[k]
|
|
25
|
-
);
|
|
33
|
+
const missing = REQUIRED.filter(([key]) => !cfg[key]);
|
|
26
34
|
if (missing.length) {
|
|
27
35
|
throw new Error(
|
|
28
|
-
`@lumoauth/nextjs is missing required config: ${missing.join(", ")}. Set
|
|
36
|
+
`@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({ ... }).`
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
if (cfg.redirectUri && !isAbsoluteHttpUrl(cfg.redirectUri)) {
|
|
40
|
+
throw new Error(
|
|
41
|
+
`@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.`
|
|
29
42
|
);
|
|
30
43
|
}
|
|
31
44
|
return cfg;
|
|
32
45
|
}
|
|
46
|
+
function isAbsoluteHttpUrl(value) {
|
|
47
|
+
try {
|
|
48
|
+
const { protocol } = new URL(value);
|
|
49
|
+
return protocol === "https:" || protocol === "http:";
|
|
50
|
+
} catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
33
54
|
|
|
34
55
|
// src/session-cookie.ts
|
|
35
56
|
var SESSION_COOKIE = "lumo_session";
|
|
@@ -157,7 +178,7 @@ async function protectPage(opts = {}) {
|
|
|
157
178
|
if (!result.isSignedIn) {
|
|
158
179
|
const { redirect } = await import("next/navigation");
|
|
159
180
|
const qs = opts.returnTo ? `?return_to=${encodeURIComponent(opts.returnTo)}` : "";
|
|
160
|
-
redirect(
|
|
181
|
+
redirect(`${LOGIN_PATH}${qs}`);
|
|
161
182
|
}
|
|
162
183
|
return result;
|
|
163
184
|
}
|
|
@@ -171,6 +192,30 @@ import {
|
|
|
171
192
|
ROUTES,
|
|
172
193
|
buildPath
|
|
173
194
|
} from "@lumoauth/shared";
|
|
195
|
+
|
|
196
|
+
// src/origin.ts
|
|
197
|
+
var HOST = /^(?:[a-z0-9.-]+|\[[0-9a-f:.]+\])(?::\d{1,5})?$/i;
|
|
198
|
+
function firstValue(header) {
|
|
199
|
+
return (header ?? "").split(",")[0].trim();
|
|
200
|
+
}
|
|
201
|
+
function appOrigin(request, cfg) {
|
|
202
|
+
if (cfg.redirectUri) return new URL(cfg.redirectUri).origin;
|
|
203
|
+
const url = new URL(request.url);
|
|
204
|
+
const host = firstValue(request.headers.get("x-forwarded-host")) || firstValue(request.headers.get("host"));
|
|
205
|
+
if (!host || !HOST.test(host)) return url.origin;
|
|
206
|
+
const forwarded = firstValue(request.headers.get("x-forwarded-proto")).toLowerCase();
|
|
207
|
+
const protocol = forwarded === "https" || forwarded === "http" ? forwarded : url.protocol.slice(0, -1);
|
|
208
|
+
try {
|
|
209
|
+
return new URL(`${protocol}://${host}`).origin;
|
|
210
|
+
} catch {
|
|
211
|
+
return url.origin;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
function callbackUrl(origin, cfg) {
|
|
215
|
+
return cfg.redirectUri || origin + CALLBACK_PATH;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// src/route-handler.ts
|
|
174
219
|
function authModule(cfg) {
|
|
175
220
|
return new AuthModule2({ baseUrl: cfg.domain, orgId: cfg.orgId, clientId: cfg.clientId });
|
|
176
221
|
}
|
|
@@ -189,8 +234,10 @@ function createRouteHandler(overrides = {}) {
|
|
|
189
234
|
const cfg = getCfg();
|
|
190
235
|
const action = (await segments(context))[0];
|
|
191
236
|
const url = new URL(request.url);
|
|
192
|
-
const
|
|
237
|
+
const origin = appOrigin(request, cfg);
|
|
238
|
+
const secure = origin.startsWith("https:");
|
|
193
239
|
if (action === "login") {
|
|
240
|
+
const redirectUri = callbackUrl(origin, cfg);
|
|
194
241
|
const codeVerifier = generateCodeVerifier();
|
|
195
242
|
const state = generateState();
|
|
196
243
|
const codeChallenge = await generateCodeChallenge(codeVerifier);
|
|
@@ -199,7 +246,7 @@ function createRouteHandler(overrides = {}) {
|
|
|
199
246
|
);
|
|
200
247
|
authorize.searchParams.set("response_type", "code");
|
|
201
248
|
authorize.searchParams.set("client_id", cfg.clientId);
|
|
202
|
-
authorize.searchParams.set("redirect_uri",
|
|
249
|
+
authorize.searchParams.set("redirect_uri", redirectUri);
|
|
203
250
|
authorize.searchParams.set("scope", cfg.scope);
|
|
204
251
|
authorize.searchParams.set("code_challenge", codeChallenge);
|
|
205
252
|
authorize.searchParams.set("code_challenge_method", "S256");
|
|
@@ -207,7 +254,10 @@ function createRouteHandler(overrides = {}) {
|
|
|
207
254
|
const pkce = {
|
|
208
255
|
codeVerifier,
|
|
209
256
|
state,
|
|
210
|
-
returnTo: safeReturnTo(url.searchParams.get("return_to"), cfg.afterSignInUrl)
|
|
257
|
+
returnTo: safeReturnTo(url.searchParams.get("return_to"), cfg.afterSignInUrl),
|
|
258
|
+
// The token request must repeat the redirect_uri of the
|
|
259
|
+
// authorization request exactly, so keep the one that was sent.
|
|
260
|
+
redirectUri
|
|
211
261
|
};
|
|
212
262
|
const res = Response.redirect(authorize.toString(), 302);
|
|
213
263
|
return withCookie(
|
|
@@ -220,16 +270,16 @@ function createRouteHandler(overrides = {}) {
|
|
|
220
270
|
const returnedState = url.searchParams.get("state");
|
|
221
271
|
const pkce = await unseal(readCookie(request, PKCE_COOKIE), cfg.secret);
|
|
222
272
|
if (!code || !returnedState || !pkce) {
|
|
223
|
-
return redirectTo(
|
|
273
|
+
return redirectTo(origin + cfg.afterSignOutUrl, [clearCookie(PKCE_COOKIE, secure)]);
|
|
224
274
|
}
|
|
225
275
|
if (returnedState !== pkce.state) {
|
|
226
|
-
return redirectTo(
|
|
276
|
+
return redirectTo(origin + cfg.afterSignOutUrl, [clearCookie(PKCE_COOKIE, secure)]);
|
|
227
277
|
}
|
|
228
278
|
try {
|
|
229
279
|
const tokens = await authModule(cfg).exchangeCodeForTokens({
|
|
230
280
|
code,
|
|
231
281
|
codeVerifier: pkce.codeVerifier,
|
|
232
|
-
redirectUri:
|
|
282
|
+
redirectUri: pkce.redirectUri ?? callbackUrl(origin, cfg),
|
|
233
283
|
...cfg.clientSecret ? { clientSecret: cfg.clientSecret } : {}
|
|
234
284
|
});
|
|
235
285
|
const session = {
|
|
@@ -242,12 +292,12 @@ function createRouteHandler(overrides = {}) {
|
|
|
242
292
|
// passes, however many access tokens come and go.
|
|
243
293
|
sessionExpiresAt: Date.now() + cfg.sessionMaxAge * 1e3
|
|
244
294
|
};
|
|
245
|
-
return redirectTo(
|
|
295
|
+
return redirectTo(origin + pkce.returnTo, [
|
|
246
296
|
`${SESSION_COOKIE}=${await seal(session, cfg.secret)}; ${serialize(cookieOptions(cfg.sessionMaxAge, secure))}`,
|
|
247
297
|
clearCookie(PKCE_COOKIE, secure)
|
|
248
298
|
]);
|
|
249
299
|
} catch {
|
|
250
|
-
return redirectTo(
|
|
300
|
+
return redirectTo(origin + cfg.afterSignOutUrl, [clearCookie(PKCE_COOKIE, secure)]);
|
|
251
301
|
}
|
|
252
302
|
}
|
|
253
303
|
if (action === "session") {
|
|
@@ -261,17 +311,17 @@ function createRouteHandler(overrides = {}) {
|
|
|
261
311
|
expiresAt: session.expiresAt
|
|
262
312
|
});
|
|
263
313
|
}
|
|
264
|
-
if (action === "logout") return doLogout(cfg,
|
|
314
|
+
if (action === "logout") return doLogout(cfg, origin, request, secure);
|
|
265
315
|
return new Response("Not found", { status: 404 });
|
|
266
316
|
}
|
|
267
317
|
async function POST(request, context) {
|
|
268
318
|
const cfg = getCfg();
|
|
269
319
|
const action = (await segments(context))[0];
|
|
270
|
-
const
|
|
271
|
-
if (action === "logout") return doLogout(cfg,
|
|
320
|
+
const origin = appOrigin(request, cfg);
|
|
321
|
+
if (action === "logout") return doLogout(cfg, origin, request, origin.startsWith("https:"));
|
|
272
322
|
return new Response("Not found", { status: 404 });
|
|
273
323
|
}
|
|
274
|
-
async function doLogout(cfg,
|
|
324
|
+
async function doLogout(cfg, origin, request, secure) {
|
|
275
325
|
const session = await unseal(readCookie(request, SESSION_COOKIE), cfg.secret);
|
|
276
326
|
if (session?.accessToken) {
|
|
277
327
|
await authModule(cfg).revokeToken(session.accessToken, session.accessToken).catch(() => {
|
|
@@ -280,7 +330,7 @@ function createRouteHandler(overrides = {}) {
|
|
|
280
330
|
const logout = new URL(
|
|
281
331
|
`${cfg.domain.replace(/\/+$/, "")}${buildPath(ROUTES["oauth.logout"].path, { orgId: cfg.orgId })}`
|
|
282
332
|
);
|
|
283
|
-
logout.searchParams.set("post_logout_redirect_uri",
|
|
333
|
+
logout.searchParams.set("post_logout_redirect_uri", origin + cfg.afterSignOutUrl);
|
|
284
334
|
if (session?.idToken) logout.searchParams.set("id_token_hint", session.idToken);
|
|
285
335
|
return redirectTo(logout.toString(), [clearCookie(SESSION_COOKIE, secure)]);
|
|
286
336
|
}
|
|
@@ -328,6 +378,7 @@ function lumoAuthMiddleware(options = {}) {
|
|
|
328
378
|
return async function middleware(req) {
|
|
329
379
|
const isProtected = typeof protect === "function" ? protect(req) : protect.map(toMatcher).some((m) => m.test(req.nextUrl.pathname));
|
|
330
380
|
const cfg = resolveConfig(configOverrides);
|
|
381
|
+
const origin = appOrigin(req, cfg);
|
|
331
382
|
const rawCookie = req.cookies.get(SESSION_COOKIE)?.value;
|
|
332
383
|
const session = await unseal(rawCookie, cfg.secret);
|
|
333
384
|
if (!isSessionLive(session)) {
|
|
@@ -337,7 +388,7 @@ function lumoAuthMiddleware(options = {}) {
|
|
|
337
388
|
res2.cookies.delete(SESSION_COOKIE);
|
|
338
389
|
return res2;
|
|
339
390
|
}
|
|
340
|
-
const login = new URL(
|
|
391
|
+
const login = new URL(LOGIN_PATH, origin);
|
|
341
392
|
login.searchParams.set("return_to", req.nextUrl.pathname + req.nextUrl.search);
|
|
342
393
|
const res = NextResponse.redirect(login);
|
|
343
394
|
if (rawCookie) res.cookies.delete(SESSION_COOKIE);
|
|
@@ -346,7 +397,7 @@ function lumoAuthMiddleware(options = {}) {
|
|
|
346
397
|
if (!refresh || !isTokenStale(session)) return NextResponse.next();
|
|
347
398
|
if (!session.refreshToken) {
|
|
348
399
|
if (!isProtected) return NextResponse.next();
|
|
349
|
-
const login = new URL(
|
|
400
|
+
const login = new URL(LOGIN_PATH, origin);
|
|
350
401
|
login.searchParams.set("return_to", req.nextUrl.pathname + req.nextUrl.search);
|
|
351
402
|
return NextResponse.redirect(login);
|
|
352
403
|
}
|
|
@@ -371,11 +422,11 @@ function lumoAuthMiddleware(options = {}) {
|
|
|
371
422
|
const headers2 = new Headers(req.headers);
|
|
372
423
|
headers2.set(REFRESHED_SESSION_HEADER, sealed);
|
|
373
424
|
const res = NextResponse.next({ request: { headers: headers2 } });
|
|
374
|
-
const opts = cookieOptions(cfg.sessionMaxAge,
|
|
425
|
+
const opts = cookieOptions(cfg.sessionMaxAge, origin.startsWith("https:"));
|
|
375
426
|
res.cookies.set(SESSION_COOKIE, sealed, opts);
|
|
376
427
|
return res;
|
|
377
428
|
} catch {
|
|
378
|
-
const res = isProtected ? NextResponse.redirect(new URL(
|
|
429
|
+
const res = isProtected ? NextResponse.redirect(new URL(LOGIN_PATH, origin)) : NextResponse.next();
|
|
379
430
|
res.cookies.delete(SESSION_COOKIE);
|
|
380
431
|
return res;
|
|
381
432
|
}
|
package/dist/server.mjs.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":";AAKA,OAAO;;;ACLP,SAAS,SAAS,eAAe;AACjC,SAAS,kBAAiC;;;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,CAAC,UAAU,SAAS,YAAY,UAAU,aAAa,EAAY;AAAA,IAChF,CAAC,MAAM,CAAC,IAAI,CAAC;AAAA,EACjB;AACA,MAAI,QAAQ,QAAQ;AAChB,UAAM,IAAI;AAAA,MACN,gDAAgD,QAAQ,KAAK,IAAI,CA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,SAAS,MAAM,KAAK,MAAM,IAAI,MAAM;AAG1C,YAAMC,WAAU,IAAI,QAAQ,IAAI,OAAO;AACvC,MAAAA,SAAQ,IAAI,0BAA0B,MAAM;AAC5C,YAAM,MAAM,aAAa,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,aAAa,SAAS,IAAI,IAAI,mBAAmB,IAAI,QAAQ,MAAM,CAAC,IACpE,aAAa,KAAK;AACxB,UAAI,QAAQ,OAAO,cAAc;AACjC,aAAO;AAAA,IACX;AAAA,EACJ;AACJ;","names":["AuthModule","AuthModule","cookies","headers","AuthModule","res","AuthModule","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(LOGIN_PATH, origin))\n : NextResponse.next();\n res.cookies.delete(SESSION_COOKIE);\n return res;\n }\n };\n}\n"],"mappings":";AAKA,OAAO;;;ACLP,S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,aAAO;AAAA,IACX,QAAQ;AAIJ,YAAM,MAAM,cACN,aAAa,SAAS,IAAI,IAAI,YAAY,MAAM,CAAC,IACjD,aAAa,KAAK;AACxB,UAAI,QAAQ,OAAO,cAAc;AACjC,aAAO;AAAA,IACX;AAAA,EACJ;AACJ;","names":["AuthModule","AuthModule","cookies","headers","AuthModule","res","AuthModule","headers"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lumoauth/nextjs",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.1",
|
|
4
4
|
"description": "LumoAuth for Next.js — server-side auth() for App Router, route protection middleware, and a backend-for-frontend that keeps tokens out of the browser.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "LumoAuth",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"dev": "tsup --watch",
|
|
34
34
|
"typecheck": "tsc --noEmit",
|
|
35
35
|
"prepublishOnly": "npm run build",
|
|
36
|
-
"test": "npm run build && tsup src/session-cookie.ts --format esm -d tests/.build --silent && node --test tests/*.test.mjs"
|
|
36
|
+
"test": "npm run build && tsup src/session-cookie.ts src/config.ts src/origin.ts src/route-handler.ts --format esm -d tests/.build --silent && node --test tests/*.test.mjs"
|
|
37
37
|
},
|
|
38
38
|
"keywords": [
|
|
39
39
|
"lumoauth",
|