@lumoauth/nextjs 1.1.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server.js +3 -3
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +3 -3
- package/dist/server.mjs.map +1 -1
- package/package.json +4 -4
package/dist/server.js
CHANGED
|
@@ -164,13 +164,13 @@ function decodeSub(accessToken) {
|
|
|
164
164
|
}
|
|
165
165
|
}
|
|
166
166
|
async function auth(overrides = {}) {
|
|
167
|
-
const cfg = resolveConfig(overrides);
|
|
168
167
|
const hdrs = await (0, import_headers.headers)();
|
|
168
|
+
const jar = await (0, import_headers.cookies)();
|
|
169
|
+
const cfg = resolveConfig(overrides);
|
|
169
170
|
const fromHeader = await unseal(
|
|
170
171
|
hdrs.get(REFRESHED_SESSION_HEADER) ?? void 0,
|
|
171
172
|
cfg.secret
|
|
172
173
|
);
|
|
173
|
-
const jar = await (0, import_headers.cookies)();
|
|
174
174
|
const session = fromHeader ?? await unseal(jar.get(SESSION_COOKIE)?.value, cfg.secret);
|
|
175
175
|
if (!isSessionLive(session)) return SIGNED_OUT;
|
|
176
176
|
const stale = isTokenStale(session);
|
|
@@ -183,11 +183,11 @@ async function auth(overrides = {}) {
|
|
|
183
183
|
};
|
|
184
184
|
}
|
|
185
185
|
async function currentUser(overrides = {}) {
|
|
186
|
-
const cfg = resolveConfig(overrides);
|
|
187
186
|
const { getToken, isSignedIn } = await auth(overrides);
|
|
188
187
|
if (!isSignedIn) return null;
|
|
189
188
|
const token = getToken();
|
|
190
189
|
if (!token) return null;
|
|
190
|
+
const cfg = resolveConfig(overrides);
|
|
191
191
|
try {
|
|
192
192
|
const mod = new import_shared.AuthModule({ baseUrl: cfg.domain, orgId: cfg.orgId, clientId: cfg.clientId });
|
|
193
193
|
return await mod.getUserInfo(token);
|
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 const cfg = resolveConfig(overrides);\n\n // Prefer the header: if middleware refreshed during THIS request, the\n // request cookie still holds the pre-refresh value.\n const hdrs = await headers();\n const fromHeader = await unseal<ServerSession>(\n hdrs.get(REFRESHED_SESSION_HEADER) ?? undefined,\n cfg.secret,\n );\n const jar = await cookies();\n const session =\n fromHeader ?? (await unseal<ServerSession>(jar.get(SESSION_COOKIE)?.value, cfg.secret));\n\n if (!isSessionLive(session)) return SIGNED_OUT;\n\n const stale = isTokenStale(session);\n return {\n userId: decodeSub(session.accessToken),\n isSignedIn: true,\n getToken: () => (stale ? null : session.accessToken),\n expiresAt: session.expiresAt,\n isStale: stale,\n };\n}\n\n/**\n * The signed-in user's profile, or null.\n *\n * This makes a network call to the OIDC `/userinfo` endpoint on every\n * invocation, so prefer `auth()` when the subject is all you need.\n */\nexport async function currentUser(\n overrides: Partial<LumoAuthNextConfig> = {},\n): Promise<UserInfo | null> {\n const cfg = resolveConfig(overrides);\n const { getToken, isSignedIn } = await auth(overrides);\n if (!isSignedIn) return null;\n\n const token = getToken();\n if (!token) return null;\n\n try {\n const mod = new AuthModule({ baseUrl: cfg.domain, orgId: cfg.orgId, clientId: cfg.clientId });\n return await mod.getUserInfo(token);\n } catch {\n // A failed /userinfo does not invalidate the session — treat it as\n // \"profile unavailable\" rather than signing the user out mid-render.\n return null;\n }\n}\n\n/**\n * Redirect signed-out visitors to sign in. Call at the top of a protected\n * server component.\n *\n * ```tsx\n * export default async function Page() {\n * await protectPage();\n * ...\n * }\n * ```\n */\nexport async function protectPage(opts: { returnTo?: string } = {}): Promise<AuthObject> {\n const result = await auth();\n if (!result.isSignedIn) {\n const { redirect } = await import('next/navigation');\n const qs = opts.returnTo ? `?return_to=${encodeURIComponent(opts.returnTo)}` : '';\n redirect(`/api/auth/login${qs}`);\n }\n return result;\n}\n","export interface LumoAuthNextConfig {\n /** Base URL of your LumoAuth instance. */\n domain: string;\n /** Organization slug. */\n orgId: string;\n /** OAuth client id. */\n clientId: string;\n /** Client secret, for confidential clients. Public + PKCE clients omit it. */\n clientSecret?: string;\n /** Secret used to seal the session cookie. At least 32 characters. */\n secret: string;\n /** Absolute redirect URI registered with the OAuth client. */\n redirectUri: string;\n /** Where to send a signed-out user. @default '/' */\n afterSignOutUrl?: string;\n /** Where to send a freshly signed-in user. @default '/' */\n afterSignInUrl?: string;\n /** OAuth scopes. @default 'openid profile email' */\n scope?: string;\n /** Session cookie lifetime in seconds. @default 30 days */\n sessionMaxAge?: number;\n}\n\n/**\n * Resolve config from the environment.\n *\n * The public values are read from `NEXT_PUBLIC_*` so the same names work in\n * both the client provider and the server. `LUMOAUTH_SECRET` and\n * `LUMOAUTH_CLIENT_SECRET` are deliberately NOT public — a `NEXT_PUBLIC_`\n * prefix would inline them into the browser bundle.\n */\nexport function resolveConfig(overrides: Partial<LumoAuthNextConfig> = {}): LumoAuthNextConfig {\n const env = process.env;\n const cfg: LumoAuthNextConfig = {\n domain: overrides.domain ?? env.NEXT_PUBLIC_LUMOAUTH_DOMAIN ?? '',\n orgId: overrides.orgId ?? env.NEXT_PUBLIC_LUMOAUTH_ORG_ID ?? '',\n clientId: overrides.clientId ?? env.NEXT_PUBLIC_LUMOAUTH_CLIENT_ID ?? '',\n clientSecret: overrides.clientSecret ?? env.LUMOAUTH_CLIENT_SECRET,\n secret: overrides.secret ?? env.LUMOAUTH_SECRET ?? '',\n redirectUri: overrides.redirectUri ?? env.NEXT_PUBLIC_REDIRECT_URI ?? '',\n afterSignOutUrl: overrides.afterSignOutUrl ?? '/',\n afterSignInUrl: overrides.afterSignInUrl ?? '/',\n scope: overrides.scope ?? 'openid profile email',\n sessionMaxAge: overrides.sessionMaxAge ?? 60 * 60 * 24 * 30,\n };\n\n const missing = (['domain', 'orgId', 'clientId', 'secret', 'redirectUri'] as const).filter(\n (k) => !cfg[k],\n );\n if (missing.length) {\n throw new Error(\n `@lumoauth/nextjs is missing required config: ${missing.join(', ')}. ` +\n 'Set NEXT_PUBLIC_LUMOAUTH_DOMAIN, NEXT_PUBLIC_LUMOAUTH_ORG_ID, ' +\n 'NEXT_PUBLIC_LUMOAUTH_CLIENT_ID, NEXT_PUBLIC_REDIRECT_URI and LUMOAUTH_SECRET, ' +\n 'or pass them to createRouteHandler({ ... }).',\n );\n }\n return cfg;\n}\n","/**\n * The server-side session, sealed into an httpOnly cookie.\n *\n * This is the trust boundary for everything else in the package: `auth()`\n * believes what is in here, so it must be unforgeable. The cookie is encrypted\n * AND authenticated with AES-256-GCM, so a client can neither read the tokens\n * nor alter the payload without the auth tag failing.\n *\n * Encrypting rather than merely signing matters because the payload holds the\n * refresh token, which must never be readable by the browser.\n *\n * Implemented with Web Crypto rather than `node:crypto` because these helpers\n * run in three different places: route handlers (Node runtime), `auth()` in a\n * server component (Node), and `lumoAuthMiddleware` (edge runtime, where\n * `node:crypto` does not exist). Web Crypto is the one API present in all of\n * them. The cost is that seal/unseal are async.\n */\n\nexport const SESSION_COOKIE = 'lumo_session';\nexport const PKCE_COOKIE = 'lumo_pkce';\n\n/**\n * Two different lifetimes live in here, and conflating them is the classic\n * bug: an access token lasts ~1 hour, a session lasts weeks.\n *\n * `expiresAt` is when the ACCESS TOKEN goes stale — routine, expected, and\n * fixed by a refresh.\n * `sessionExpiresAt` is when the SESSION itself ends and the user must sign in\n * again.\n *\n * A user whose access token expired five minutes ago is still signed in.\n */\nexport interface ServerSession {\n accessToken: string;\n refreshToken: string | null;\n idToken: string | null;\n /** Access-token expiry, epoch milliseconds. */\n expiresAt: number;\n /** Session expiry, epoch milliseconds. Absent on cookies written before this field existed. */\n sessionExpiresAt?: number;\n}\n\n/**\n * Header used to hand a freshly refreshed session from middleware to the\n * server component rendering the same request.\n *\n * Middleware writes the new cookie on the RESPONSE, but the component reads\n * REQUEST cookies — which still hold the stale value. Without this header the\n * refresh would only take effect on the following request.\n */\nexport const REFRESHED_SESSION_HEADER = 'x-lumo-session';\n\n/** Refresh once the access token is within this window of expiring. */\nexport const REFRESH_WINDOW_MS = 60_000;\n\n/** True when the session itself is still valid, regardless of token staleness. */\nexport function isSessionLive(session: ServerSession | null): session is ServerSession {\n if (!session) return false;\n if (session.sessionExpiresAt && session.sessionExpiresAt <= Date.now()) return false;\n // A live session is one we can still get a token for: either the current\n // access token is good, or we hold a refresh token to obtain a new one.\n return !!session.refreshToken || session.expiresAt > Date.now();\n}\n\n/** True when the access token needs replacing before it can be used. */\nexport function isTokenStale(session: ServerSession): boolean {\n return session.expiresAt - Date.now() < REFRESH_WINDOW_MS;\n}\n\nexport interface PkceState {\n codeVerifier: string;\n state: string;\n /** Where to send the user once the exchange completes. */\n returnTo: string;\n}\n\nconst IV_BYTES = 12;\n\n/**\n * TS 5.7 made Uint8Array generic over its backing buffer, so\n * Uint8Array<ArrayBufferLike> no longer structurally satisfies BufferSource\n * (which wants an ArrayBuffer, not a SharedArrayBuffer). Every value we pass to\n * Web Crypto here is a plain ArrayBuffer at runtime.\n */\nfunction buf(u: Uint8Array): BufferSource {\n return u as unknown as BufferSource;\n}\n\nfunction b64urlEncode(bytes: Uint8Array): string {\n let s = '';\n for (const b of bytes) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction b64urlDecode(text: string): Uint8Array {\n const padded = text.replace(/-/g, '+').replace(/_/g, '/');\n const bin = atob(padded + '='.repeat((4 - (padded.length % 4)) % 4));\n return Uint8Array.from(bin, (c) => c.charCodeAt(0));\n}\n\nasync function importKey(secret: string): Promise<CryptoKey> {\n if (!secret || secret.length < 32) {\n throw new Error(\n 'LUMOAUTH_SECRET must be set to at least 32 characters. Generate one with: openssl rand -hex 32',\n );\n }\n // SHA-256 the secret: it is arbitrary-length text and AES-256 needs exactly\n // 32 bytes.\n const digest = await crypto.subtle.digest('SHA-256', buf(new TextEncoder().encode(secret)));\n return crypto.subtle.importKey('raw', digest, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);\n}\n\nexport async function seal(payload: unknown, secret: string): Promise<string> {\n const key = await importKey(secret);\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const data = new TextEncoder().encode(JSON.stringify(payload));\n const sealed = new Uint8Array(\n await crypto.subtle.encrypt({ name: 'AES-GCM', iv: buf(iv) }, key, buf(data)),\n );\n // Web Crypto appends the auth tag to the ciphertext, so two parts suffice.\n return `${b64urlEncode(iv)}.${b64urlEncode(sealed)}`;\n}\n\nexport async function unseal<T>(value: string | undefined, secret: string): Promise<T | null> {\n if (!value) return null;\n const parts = value.split('.');\n if (parts.length !== 2) return null;\n try {\n const iv = b64urlDecode(parts[0]);\n const body = b64urlDecode(parts[1]);\n const key = await importKey(secret);\n const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: buf(iv) }, key, buf(body));\n return JSON.parse(new TextDecoder().decode(plain)) as T;\n } catch {\n // A tampered, truncated, or stale-key cookie is simply not a session.\n // Returning null signs the user out rather than throwing into a render.\n return null;\n }\n}\n\n/** Cookie attributes shared by every cookie this package sets. */\nexport function cookieOptions(maxAgeSeconds: number, secure: boolean) {\n return {\n httpOnly: true,\n // Lax, not Strict: the OAuth callback is a cross-site top-level\n // navigation back from the identity provider, and Strict would withhold\n // the PKCE cookie exactly then.\n sameSite: 'lax' as const,\n secure,\n path: '/',\n maxAge: maxAgeSeconds,\n };\n}\n","import {\n AuthModule,\n generateCodeVerifier,\n generateCodeChallenge,\n generateState,\n ROUTES,\n buildPath,\n} from '@lumoauth/shared';\nimport { resolveConfig, type LumoAuthNextConfig } from './config';\nimport {\n SESSION_COOKIE,\n PKCE_COOKIE,\n cookieOptions,\n isSessionLive,\n seal,\n unseal,\n type PkceState,\n type ServerSession,\n} from './session-cookie';\n\n/**\n * Backend-for-frontend route handlers.\n *\n * Mount once, at `app/api/auth/[...lumoauth]/route.ts`:\n *\n * ```ts\n * import { createRouteHandler } from '@lumoauth/nextjs/server';\n * export const { GET, POST } = createRouteHandler();\n * ```\n *\n * The server owns the whole OAuth exchange, so tokens live in an httpOnly\n * cookie and never reach JavaScript. That is what makes `auth()` work in a\n * server component — and therefore what makes a signed-in page render\n * server-side with no loading flash.\n */\n\n// Next 15 types route context params as a Promise and validates the handler\n// signature against it, so the union form is rejected at build time. Typed as\n// Next 15 expects; Next 14 passes a plain object, which `await` handles too.\ntype Ctx = { params: Promise<{ lumoauth?: string[] }> };\n\nfunction authModule(cfg: LumoAuthNextConfig): AuthModule {\n return new AuthModule({ baseUrl: cfg.domain, orgId: cfg.orgId, clientId: cfg.clientId });\n}\n\n/** Same-origin relative paths only — never trust a caller-supplied absolute URL. */\nfunction safeReturnTo(raw: string | null, fallback: string): string {\n if (!raw) return fallback;\n if (!raw.startsWith('/') || raw.startsWith('//')) return fallback;\n return raw;\n}\n\nexport function createRouteHandler(overrides: Partial<LumoAuthNextConfig> = {}) {\n const getCfg = () => resolveConfig(overrides);\n\n async function segments(context: Ctx): Promise<string[]> {\n const p = await context.params;\n return p?.lumoauth ?? [];\n }\n\n async function GET(request: Request, context: Ctx): Promise<Response> {\n const cfg = getCfg();\n const action = (await segments(context))[0];\n const url = new URL(request.url);\n const secure = url.protocol === 'https:';\n\n if (action === 'login') {\n const codeVerifier = generateCodeVerifier();\n const state = generateState();\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n\n const authorize = new URL(\n `${cfg.domain.replace(/\\/+$/, '')}${buildPath(ROUTES['oauth.authorize'].path, { orgId: cfg.orgId })}`,\n );\n authorize.searchParams.set('response_type', 'code');\n authorize.searchParams.set('client_id', cfg.clientId);\n authorize.searchParams.set('redirect_uri', cfg.redirectUri);\n authorize.searchParams.set('scope', cfg.scope!);\n authorize.searchParams.set('code_challenge', codeChallenge);\n authorize.searchParams.set('code_challenge_method', 'S256');\n authorize.searchParams.set('state', state);\n\n const pkce: PkceState = {\n codeVerifier,\n state,\n returnTo: safeReturnTo(url.searchParams.get('return_to'), cfg.afterSignInUrl!),\n };\n\n const res = Response.redirect(authorize.toString(), 302);\n // Response.redirect() produces an immutable Response, so rebuild it\n // to attach the cookie.\n return withCookie(\n res,\n `${PKCE_COOKIE}=${await seal(pkce, cfg.secret)}; ${serialize(cookieOptions(600, secure))}`,\n );\n }\n\n if (action === 'callback') {\n const code = url.searchParams.get('code');\n const returnedState = url.searchParams.get('state');\n const pkce = await unseal<PkceState>(readCookie(request, PKCE_COOKIE), cfg.secret);\n\n if (!code || !returnedState || !pkce) {\n return redirectTo(url.origin + cfg.afterSignOutUrl!, [clearCookie(PKCE_COOKIE, secure)]);\n }\n // CSRF: the state we issued must match the one that came back.\n if (returnedState !== pkce.state) {\n return redirectTo(url.origin + cfg.afterSignOutUrl!, [clearCookie(PKCE_COOKIE, secure)]);\n }\n\n try {\n const tokens = await authModule(cfg).exchangeCodeForTokens({\n code,\n codeVerifier: pkce.codeVerifier,\n redirectUri: cfg.redirectUri,\n ...(cfg.clientSecret ? { clientSecret: cfg.clientSecret } : {}),\n });\n const session: ServerSession = {\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token ?? null,\n idToken: tokens.id_token ?? null,\n // Access-token expiry: short, refreshed in the background.\n expiresAt: Date.now() + tokens.expires_in * 1000,\n // Session expiry: long. The user stays signed in until this\n // passes, however many access tokens come and go.\n sessionExpiresAt: Date.now() + cfg.sessionMaxAge! * 1000,\n };\n return redirectTo(url.origin + pkce.returnTo, [\n `${SESSION_COOKIE}=${await seal(session, cfg.secret)}; ${serialize(cookieOptions(cfg.sessionMaxAge!, secure))}`,\n clearCookie(PKCE_COOKIE, secure),\n ]);\n } catch {\n return redirectTo(url.origin + cfg.afterSignOutUrl!, [clearCookie(PKCE_COOKIE, secure)]);\n }\n }\n\n if (action === 'session') {\n // Read endpoint for `cookieStorageAdapter`. Returns the access token\n // only — the refresh token must never leave the server.\n const session = await unseal<ServerSession>(readCookie(request, SESSION_COOKIE), cfg.secret);\n // Judged on the SESSION, not the access token: reporting \"no\n // session\" for a merely stale token would sign the client out every\n // hour despite a perfectly good session.\n if (!isSessionLive(session)) {\n return Response.json({ accessToken: null, expiresAt: null });\n }\n return Response.json({\n accessToken: session.accessToken,\n idToken: session.idToken,\n expiresAt: session.expiresAt,\n });\n }\n\n if (action === 'logout') return doLogout(cfg, url, request, secure);\n\n return new Response('Not found', { status: 404 });\n }\n\n async function POST(request: Request, context: Ctx): Promise<Response> {\n const cfg = getCfg();\n const action = (await segments(context))[0];\n const url = new URL(request.url);\n if (action === 'logout') return doLogout(cfg, url, request, url.protocol === 'https:');\n return new Response('Not found', { status: 404 });\n }\n\n async function doLogout(\n cfg: LumoAuthNextConfig,\n url: URL,\n request: Request,\n secure: boolean,\n ): Promise<Response> {\n const session = await unseal<ServerSession>(readCookie(request, SESSION_COOKIE), cfg.secret);\n\n // Best-effort revoke before dropping the cookie. A failure here must not\n // block sign-out — the local session is going away regardless.\n if (session?.accessToken) {\n await authModule(cfg)\n .revokeToken(session.accessToken, session.accessToken)\n .catch(() => {});\n }\n\n // End the IdP session too, otherwise the next /authorize silently\n // re-issues a code and the user is never really signed out.\n const logout = new URL(\n `${cfg.domain.replace(/\\/+$/, '')}${buildPath(ROUTES['oauth.logout'].path, { orgId: cfg.orgId })}`,\n );\n logout.searchParams.set('post_logout_redirect_uri', url.origin + cfg.afterSignOutUrl!);\n if (session?.idToken) logout.searchParams.set('id_token_hint', session.idToken);\n\n return redirectTo(logout.toString(), [clearCookie(SESSION_COOKIE, secure)]);\n }\n\n return { GET, POST };\n}\n\n// ── Small cookie/response helpers ────────────────────────────────────\n\nfunction serialize(o: ReturnType<typeof cookieOptions>): string {\n return [\n `Path=${o.path}`,\n `Max-Age=${o.maxAge}`,\n `SameSite=${o.sameSite === 'lax' ? 'Lax' : o.sameSite}`,\n o.httpOnly ? 'HttpOnly' : '',\n o.secure ? 'Secure' : '',\n ]\n .filter(Boolean)\n .join('; ');\n}\n\nfunction clearCookie(name: string, secure: boolean): string {\n return `${name}=; Path=/; Max-Age=0; SameSite=Lax; HttpOnly${secure ? '; Secure' : ''}`;\n}\n\nfunction readCookie(request: Request, name: string): string | undefined {\n const header = request.headers.get('cookie');\n if (!header) return undefined;\n const hit = header.split('; ').find((c) => c.startsWith(`${name}=`));\n return hit?.slice(name.length + 1);\n}\n\nfunction redirectTo(location: string, cookies: string[]): Response {\n const headers = new Headers({ Location: location });\n cookies.forEach((c) => headers.append('Set-Cookie', c));\n return new Response(null, { status: 302, headers });\n}\n\nfunction withCookie(res: Response, cookie: string): Response {\n const headers = new Headers(res.headers);\n headers.append('Set-Cookie', cookie);\n return new Response(res.body, { status: res.status, headers });\n}\n","import { NextResponse, type NextRequest } from 'next/server';\nimport { AuthModule } from '@lumoauth/shared';\nimport { resolveConfig, type LumoAuthNextConfig } from './config';\nimport {\n SESSION_COOKIE,\n REFRESHED_SESSION_HEADER,\n cookieOptions,\n isSessionLive,\n isTokenStale,\n seal,\n unseal,\n type ServerSession,\n} from './session-cookie';\n\nexport interface MiddlewareOptions extends Partial<LumoAuthNextConfig> {\n /**\n * Paths requiring a session. Accepts globs (`/dashboard/:path*`), regexes,\n * or a predicate. Everything else is public.\n */\n protect?: Array<string | RegExp> | ((req: NextRequest) => boolean);\n /**\n * Keep the access token fresh automatically. @default true\n *\n * Turning this off means `auth().getToken()` returns null once the token\n * goes stale, because nothing else in the request pipeline is able to\n * persist a refreshed one.\n */\n refresh?: boolean;\n}\n\n/** Turn `/dashboard/:path*` into a RegExp. */\nfunction toMatcher(pattern: string | RegExp): RegExp {\n if (pattern instanceof RegExp) return pattern;\n const source = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\/:path\\*/g, '(?:/.*)?')\n .replace(/\\*/g, '.*');\n return new RegExp(`^${source}$`);\n}\n\n/**\n * Session refresh and route protection.\n *\n * ```ts\n * // middleware.ts\n * import { lumoAuthMiddleware } from '@lumoauth/nextjs/server';\n *\n * export default lumoAuthMiddleware({ protect: ['/dashboard/:path*'] });\n * export const config = { matcher: ['/((?!_next|.*\\\\..*).*)'] };\n * ```\n *\n * ## Why refresh belongs here\n *\n * An access token lasts about an hour; a session lasts weeks. Something has to\n * trade the refresh token for a new access token, and in Next.js that can only\n * happen where cookies are writable: middleware, route handlers, and server\n * actions. Server components cannot set cookies, so they can never persist a\n * refresh.\n *\n * That distinction is not cosmetic. LumoAuth rotates refresh tokens and revokes\n * the old one on use, so refreshing somewhere that cannot persist the result\n * would spend the token and break the session on the next request. Middleware\n * runs before the page renders and can write the response cookie, so it is the\n * correct place.\n *\n * Because middleware writes the cookie on the *response* while the page reads\n * the *request*, the fresh session is also forwarded on a request header that\n * `auth()` prefers — otherwise the refresh would not take effect until the\n * following request.\n */\nexport function lumoAuthMiddleware(options: MiddlewareOptions = {}) {\n const { protect = [], refresh = true, ...configOverrides } = options;\n\n return async function middleware(req: NextRequest) {\n const isProtected =\n typeof protect === 'function'\n ? protect(req)\n : protect.map(toMatcher).some((m) => m.test(req.nextUrl.pathname));\n\n const cfg = resolveConfig(configOverrides);\n const rawCookie = req.cookies.get(SESSION_COOKIE)?.value;\n const session = await unseal<ServerSession>(rawCookie, cfg.secret);\n\n // ── No live session ──────────────────────────────────────────\n if (!isSessionLive(session)) {\n if (!isProtected) {\n if (!rawCookie) return NextResponse.next();\n const res = NextResponse.next();\n res.cookies.delete(SESSION_COOKIE);\n return res;\n }\n const login = new URL('/api/auth/login', req.nextUrl.origin);\n login.searchParams.set('return_to', req.nextUrl.pathname + req.nextUrl.search);\n const res = NextResponse.redirect(login);\n // Drop the cookie whenever one was sent but is unusable — expired,\n // tampered with, or sealed under a rotated secret. Keying this on a\n // successfully parsed session would skip exactly the case that\n // needs clearing, and the browser would resend it forever.\n if (rawCookie) res.cookies.delete(SESSION_COOKIE);\n return res;\n }\n\n // ── Live session, token still good ───────────────────────────\n if (!refresh || !isTokenStale(session)) return NextResponse.next();\n\n // ── Live session, stale token: refresh and persist ───────────\n if (!session.refreshToken) {\n // Nothing to refresh with. The session is only as live as the\n // access token, which has just gone stale.\n if (!isProtected) return NextResponse.next();\n const login = new URL('/api/auth/login', req.nextUrl.origin);\n login.searchParams.set('return_to', req.nextUrl.pathname + req.nextUrl.search);\n return NextResponse.redirect(login);\n }\n\n try {\n const mod = new AuthModule({\n baseUrl: cfg.domain,\n orgId: cfg.orgId,\n clientId: cfg.clientId,\n });\n const tokens = await mod.refreshToken(session.refreshToken);\n\n const next: ServerSession = {\n accessToken: tokens.access_token,\n // Keep the existing token when the server does not rotate;\n // losing it here would silently end the session at the next\n // refresh.\n refreshToken: tokens.refresh_token ?? session.refreshToken,\n idToken: tokens.id_token ?? session.idToken,\n expiresAt: Date.now() + tokens.expires_in * 1000,\n sessionExpiresAt: session.sessionExpiresAt,\n };\n const sealed = await seal(next, cfg.secret);\n\n // Forward to the page rendering THIS request...\n const headers = new Headers(req.headers);\n headers.set(REFRESHED_SESSION_HEADER, sealed);\n const res = NextResponse.next({ request: { headers } });\n\n // ...and persist for the next one.\n const opts = cookieOptions(cfg.sessionMaxAge!, req.nextUrl.protocol === 'https:');\n res.cookies.set(SESSION_COOKIE, sealed, opts);\n return res;\n } catch {\n // The refresh token was rejected — revoked, rotated away, or the\n // session ended server-side. Treat it as signed out rather than\n // leaving a cookie that can never succeed.\n const res = isProtected\n ? NextResponse.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AI;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/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,CAAC,UAAU,SAAS,YAAY,UAAU,aAAa,EAAY;AAAA,IAChF,CAAC,MAAM,CAAC,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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"]}
|
package/dist/server.mjs
CHANGED
|
@@ -121,13 +121,13 @@ function decodeSub(accessToken) {
|
|
|
121
121
|
}
|
|
122
122
|
}
|
|
123
123
|
async function auth(overrides = {}) {
|
|
124
|
-
const cfg = resolveConfig(overrides);
|
|
125
124
|
const hdrs = await headers();
|
|
125
|
+
const jar = await cookies();
|
|
126
|
+
const cfg = resolveConfig(overrides);
|
|
126
127
|
const fromHeader = await unseal(
|
|
127
128
|
hdrs.get(REFRESHED_SESSION_HEADER) ?? void 0,
|
|
128
129
|
cfg.secret
|
|
129
130
|
);
|
|
130
|
-
const jar = await cookies();
|
|
131
131
|
const session = fromHeader ?? await unseal(jar.get(SESSION_COOKIE)?.value, cfg.secret);
|
|
132
132
|
if (!isSessionLive(session)) return SIGNED_OUT;
|
|
133
133
|
const stale = isTokenStale(session);
|
|
@@ -140,11 +140,11 @@ async function auth(overrides = {}) {
|
|
|
140
140
|
};
|
|
141
141
|
}
|
|
142
142
|
async function currentUser(overrides = {}) {
|
|
143
|
-
const cfg = resolveConfig(overrides);
|
|
144
143
|
const { getToken, isSignedIn } = await auth(overrides);
|
|
145
144
|
if (!isSignedIn) return null;
|
|
146
145
|
const token = getToken();
|
|
147
146
|
if (!token) return null;
|
|
147
|
+
const cfg = resolveConfig(overrides);
|
|
148
148
|
try {
|
|
149
149
|
const mod = new AuthModule({ baseUrl: cfg.domain, orgId: cfg.orgId, clientId: cfg.clientId });
|
|
150
150
|
return await mod.getUserInfo(token);
|
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 const cfg = resolveConfig(overrides);\n\n // Prefer the header: if middleware refreshed during THIS request, the\n // request cookie still holds the pre-refresh value.\n const hdrs = await headers();\n const fromHeader = await unseal<ServerSession>(\n hdrs.get(REFRESHED_SESSION_HEADER) ?? undefined,\n cfg.secret,\n );\n const jar = await cookies();\n const session =\n fromHeader ?? (await unseal<ServerSession>(jar.get(SESSION_COOKIE)?.value, cfg.secret));\n\n if (!isSessionLive(session)) return SIGNED_OUT;\n\n const stale = isTokenStale(session);\n return {\n userId: decodeSub(session.accessToken),\n isSignedIn: true,\n getToken: () => (stale ? null : session.accessToken),\n expiresAt: session.expiresAt,\n isStale: stale,\n };\n}\n\n/**\n * The signed-in user's profile, or null.\n *\n * This makes a network call to the OIDC `/userinfo` endpoint on every\n * invocation, so prefer `auth()` when the subject is all you need.\n */\nexport async function currentUser(\n overrides: Partial<LumoAuthNextConfig> = {},\n): Promise<UserInfo | null> {\n const cfg = resolveConfig(overrides);\n const { getToken, isSignedIn } = await auth(overrides);\n if (!isSignedIn) return null;\n\n const token = getToken();\n if (!token) return null;\n\n try {\n const mod = new AuthModule({ baseUrl: cfg.domain, orgId: cfg.orgId, clientId: cfg.clientId });\n return await mod.getUserInfo(token);\n } catch {\n // A failed /userinfo does not invalidate the session — treat it as\n // \"profile unavailable\" rather than signing the user out mid-render.\n return null;\n }\n}\n\n/**\n * Redirect signed-out visitors to sign in. Call at the top of a protected\n * server component.\n *\n * ```tsx\n * export default async function Page() {\n * await protectPage();\n * ...\n * }\n * ```\n */\nexport async function protectPage(opts: { returnTo?: string } = {}): Promise<AuthObject> {\n const result = await auth();\n if (!result.isSignedIn) {\n const { redirect } = await import('next/navigation');\n const qs = opts.returnTo ? `?return_to=${encodeURIComponent(opts.returnTo)}` : '';\n redirect(`/api/auth/login${qs}`);\n }\n return result;\n}\n","export interface LumoAuthNextConfig {\n /** Base URL of your LumoAuth instance. */\n domain: string;\n /** Organization slug. */\n orgId: string;\n /** OAuth client id. */\n clientId: string;\n /** Client secret, for confidential clients. Public + PKCE clients omit it. */\n clientSecret?: string;\n /** Secret used to seal the session cookie. At least 32 characters. */\n secret: string;\n /** Absolute redirect URI registered with the OAuth client. */\n redirectUri: string;\n /** Where to send a signed-out user. @default '/' */\n afterSignOutUrl?: string;\n /** Where to send a freshly signed-in user. @default '/' */\n afterSignInUrl?: string;\n /** OAuth scopes. @default 'openid profile email' */\n scope?: string;\n /** Session cookie lifetime in seconds. @default 30 days */\n sessionMaxAge?: number;\n}\n\n/**\n * Resolve config from the environment.\n *\n * The public values are read from `NEXT_PUBLIC_*` so the same names work in\n * both the client provider and the server. `LUMOAUTH_SECRET` and\n * `LUMOAUTH_CLIENT_SECRET` are deliberately NOT public — a `NEXT_PUBLIC_`\n * prefix would inline them into the browser bundle.\n */\nexport function resolveConfig(overrides: Partial<LumoAuthNextConfig> = {}): LumoAuthNextConfig {\n const env = process.env;\n const cfg: LumoAuthNextConfig = {\n domain: overrides.domain ?? env.NEXT_PUBLIC_LUMOAUTH_DOMAIN ?? '',\n orgId: overrides.orgId ?? env.NEXT_PUBLIC_LUMOAUTH_ORG_ID ?? '',\n clientId: overrides.clientId ?? env.NEXT_PUBLIC_LUMOAUTH_CLIENT_ID ?? '',\n clientSecret: overrides.clientSecret ?? env.LUMOAUTH_CLIENT_SECRET,\n secret: overrides.secret ?? env.LUMOAUTH_SECRET ?? '',\n redirectUri: overrides.redirectUri ?? env.NEXT_PUBLIC_REDIRECT_URI ?? '',\n afterSignOutUrl: overrides.afterSignOutUrl ?? '/',\n afterSignInUrl: overrides.afterSignInUrl ?? '/',\n scope: overrides.scope ?? 'openid profile email',\n sessionMaxAge: overrides.sessionMaxAge ?? 60 * 60 * 24 * 30,\n };\n\n const missing = (['domain', 'orgId', 'clientId', 'secret', 'redirectUri'] as const).filter(\n (k) => !cfg[k],\n );\n if (missing.length) {\n throw new Error(\n `@lumoauth/nextjs is missing required config: ${missing.join(', ')}. ` +\n 'Set NEXT_PUBLIC_LUMOAUTH_DOMAIN, NEXT_PUBLIC_LUMOAUTH_ORG_ID, ' +\n 'NEXT_PUBLIC_LUMOAUTH_CLIENT_ID, NEXT_PUBLIC_REDIRECT_URI and LUMOAUTH_SECRET, ' +\n 'or pass them to createRouteHandler({ ... }).',\n );\n }\n return cfg;\n}\n","/**\n * The server-side session, sealed into an httpOnly cookie.\n *\n * This is the trust boundary for everything else in the package: `auth()`\n * believes what is in here, so it must be unforgeable. The cookie is encrypted\n * AND authenticated with AES-256-GCM, so a client can neither read the tokens\n * nor alter the payload without the auth tag failing.\n *\n * Encrypting rather than merely signing matters because the payload holds the\n * refresh token, which must never be readable by the browser.\n *\n * Implemented with Web Crypto rather than `node:crypto` because these helpers\n * run in three different places: route handlers (Node runtime), `auth()` in a\n * server component (Node), and `lumoAuthMiddleware` (edge runtime, where\n * `node:crypto` does not exist). Web Crypto is the one API present in all of\n * them. The cost is that seal/unseal are async.\n */\n\nexport const SESSION_COOKIE = 'lumo_session';\nexport const PKCE_COOKIE = 'lumo_pkce';\n\n/**\n * Two different lifetimes live in here, and conflating them is the classic\n * bug: an access token lasts ~1 hour, a session lasts weeks.\n *\n * `expiresAt` is when the ACCESS TOKEN goes stale — routine, expected, and\n * fixed by a refresh.\n * `sessionExpiresAt` is when the SESSION itself ends and the user must sign in\n * again.\n *\n * A user whose access token expired five minutes ago is still signed in.\n */\nexport interface ServerSession {\n accessToken: string;\n refreshToken: string | null;\n idToken: string | null;\n /** Access-token expiry, epoch milliseconds. */\n expiresAt: number;\n /** Session expiry, epoch milliseconds. Absent on cookies written before this field existed. */\n sessionExpiresAt?: number;\n}\n\n/**\n * Header used to hand a freshly refreshed session from middleware to the\n * server component rendering the same request.\n *\n * Middleware writes the new cookie on the RESPONSE, but the component reads\n * REQUEST cookies — which still hold the stale value. Without this header the\n * refresh would only take effect on the following request.\n */\nexport const REFRESHED_SESSION_HEADER = 'x-lumo-session';\n\n/** Refresh once the access token is within this window of expiring. */\nexport const REFRESH_WINDOW_MS = 60_000;\n\n/** True when the session itself is still valid, regardless of token staleness. */\nexport function isSessionLive(session: ServerSession | null): session is ServerSession {\n if (!session) return false;\n if (session.sessionExpiresAt && session.sessionExpiresAt <= Date.now()) return false;\n // A live session is one we can still get a token for: either the current\n // access token is good, or we hold a refresh token to obtain a new one.\n return !!session.refreshToken || session.expiresAt > Date.now();\n}\n\n/** True when the access token needs replacing before it can be used. */\nexport function isTokenStale(session: ServerSession): boolean {\n return session.expiresAt - Date.now() < REFRESH_WINDOW_MS;\n}\n\nexport interface PkceState {\n codeVerifier: string;\n state: string;\n /** Where to send the user once the exchange completes. */\n returnTo: string;\n}\n\nconst IV_BYTES = 12;\n\n/**\n * TS 5.7 made Uint8Array generic over its backing buffer, so\n * Uint8Array<ArrayBufferLike> no longer structurally satisfies BufferSource\n * (which wants an ArrayBuffer, not a SharedArrayBuffer). Every value we pass to\n * Web Crypto here is a plain ArrayBuffer at runtime.\n */\nfunction buf(u: Uint8Array): BufferSource {\n return u as unknown as BufferSource;\n}\n\nfunction b64urlEncode(bytes: Uint8Array): string {\n let s = '';\n for (const b of bytes) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction b64urlDecode(text: string): Uint8Array {\n const padded = text.replace(/-/g, '+').replace(/_/g, '/');\n const bin = atob(padded + '='.repeat((4 - (padded.length % 4)) % 4));\n return Uint8Array.from(bin, (c) => c.charCodeAt(0));\n}\n\nasync function importKey(secret: string): Promise<CryptoKey> {\n if (!secret || secret.length < 32) {\n throw new Error(\n 'LUMOAUTH_SECRET must be set to at least 32 characters. Generate one with: openssl rand -hex 32',\n );\n }\n // SHA-256 the secret: it is arbitrary-length text and AES-256 needs exactly\n // 32 bytes.\n const digest = await crypto.subtle.digest('SHA-256', buf(new TextEncoder().encode(secret)));\n return crypto.subtle.importKey('raw', digest, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);\n}\n\nexport async function seal(payload: unknown, secret: string): Promise<string> {\n const key = await importKey(secret);\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const data = new TextEncoder().encode(JSON.stringify(payload));\n const sealed = new Uint8Array(\n await crypto.subtle.encrypt({ name: 'AES-GCM', iv: buf(iv) }, key, buf(data)),\n );\n // Web Crypto appends the auth tag to the ciphertext, so two parts suffice.\n return `${b64urlEncode(iv)}.${b64urlEncode(sealed)}`;\n}\n\nexport async function unseal<T>(value: string | undefined, secret: string): Promise<T | null> {\n if (!value) return null;\n const parts = value.split('.');\n if (parts.length !== 2) return null;\n try {\n const iv = b64urlDecode(parts[0]);\n const body = b64urlDecode(parts[1]);\n const key = await importKey(secret);\n const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: buf(iv) }, key, buf(body));\n return JSON.parse(new TextDecoder().decode(plain)) as T;\n } catch {\n // A tampered, truncated, or stale-key cookie is simply not a session.\n // Returning null signs the user out rather than throwing into a render.\n return null;\n }\n}\n\n/** Cookie attributes shared by every cookie this package sets. */\nexport function cookieOptions(maxAgeSeconds: number, secure: boolean) {\n return {\n httpOnly: true,\n // Lax, not Strict: the OAuth callback is a cross-site top-level\n // navigation back from the identity provider, and Strict would withhold\n // the PKCE cookie exactly then.\n sameSite: 'lax' as const,\n secure,\n path: '/',\n maxAge: maxAgeSeconds,\n };\n}\n","import {\n AuthModule,\n generateCodeVerifier,\n generateCodeChallenge,\n generateState,\n ROUTES,\n buildPath,\n} from '@lumoauth/shared';\nimport { resolveConfig, type LumoAuthNextConfig } from './config';\nimport {\n SESSION_COOKIE,\n PKCE_COOKIE,\n cookieOptions,\n isSessionLive,\n seal,\n unseal,\n type PkceState,\n type ServerSession,\n} from './session-cookie';\n\n/**\n * Backend-for-frontend route handlers.\n *\n * Mount once, at `app/api/auth/[...lumoauth]/route.ts`:\n *\n * ```ts\n * import { createRouteHandler } from '@lumoauth/nextjs/server';\n * export const { GET, POST } = createRouteHandler();\n * ```\n *\n * The server owns the whole OAuth exchange, so tokens live in an httpOnly\n * cookie and never reach JavaScript. That is what makes `auth()` work in a\n * server component — and therefore what makes a signed-in page render\n * server-side with no loading flash.\n */\n\n// Next 15 types route context params as a Promise and validates the handler\n// signature against it, so the union form is rejected at build time. Typed as\n// Next 15 expects; Next 14 passes a plain object, which `await` handles too.\ntype Ctx = { params: Promise<{ lumoauth?: string[] }> };\n\nfunction authModule(cfg: LumoAuthNextConfig): AuthModule {\n return new AuthModule({ baseUrl: cfg.domain, orgId: cfg.orgId, clientId: cfg.clientId });\n}\n\n/** Same-origin relative paths only — never trust a caller-supplied absolute URL. */\nfunction safeReturnTo(raw: string | null, fallback: string): string {\n if (!raw) return fallback;\n if (!raw.startsWith('/') || raw.startsWith('//')) return fallback;\n return raw;\n}\n\nexport function createRouteHandler(overrides: Partial<LumoAuthNextConfig> = {}) {\n const getCfg = () => resolveConfig(overrides);\n\n async function segments(context: Ctx): Promise<string[]> {\n const p = await context.params;\n return p?.lumoauth ?? [];\n }\n\n async function GET(request: Request, context: Ctx): Promise<Response> {\n const cfg = getCfg();\n const action = (await segments(context))[0];\n const url = new URL(request.url);\n const secure = url.protocol === 'https:';\n\n if (action === 'login') {\n const codeVerifier = generateCodeVerifier();\n const state = generateState();\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n\n const authorize = new URL(\n `${cfg.domain.replace(/\\/+$/, '')}${buildPath(ROUTES['oauth.authorize'].path, { orgId: cfg.orgId })}`,\n );\n authorize.searchParams.set('response_type', 'code');\n authorize.searchParams.set('client_id', cfg.clientId);\n authorize.searchParams.set('redirect_uri', cfg.redirectUri);\n authorize.searchParams.set('scope', cfg.scope!);\n authorize.searchParams.set('code_challenge', codeChallenge);\n authorize.searchParams.set('code_challenge_method', 'S256');\n authorize.searchParams.set('state', state);\n\n const pkce: PkceState = {\n codeVerifier,\n state,\n returnTo: safeReturnTo(url.searchParams.get('return_to'), cfg.afterSignInUrl!),\n };\n\n const res = Response.redirect(authorize.toString(), 302);\n // Response.redirect() produces an immutable Response, so rebuild it\n // to attach the cookie.\n return withCookie(\n res,\n `${PKCE_COOKIE}=${await seal(pkce, cfg.secret)}; ${serialize(cookieOptions(600, secure))}`,\n );\n }\n\n if (action === 'callback') {\n const code = url.searchParams.get('code');\n const returnedState = url.searchParams.get('state');\n const pkce = await unseal<PkceState>(readCookie(request, PKCE_COOKIE), cfg.secret);\n\n if (!code || !returnedState || !pkce) {\n return redirectTo(url.origin + cfg.afterSignOutUrl!, [clearCookie(PKCE_COOKIE, secure)]);\n }\n // CSRF: the state we issued must match the one that came back.\n if (returnedState !== pkce.state) {\n return redirectTo(url.origin + cfg.afterSignOutUrl!, [clearCookie(PKCE_COOKIE, secure)]);\n }\n\n try {\n const tokens = await authModule(cfg).exchangeCodeForTokens({\n code,\n codeVerifier: pkce.codeVerifier,\n redirectUri: cfg.redirectUri,\n ...(cfg.clientSecret ? { clientSecret: cfg.clientSecret } : {}),\n });\n const session: ServerSession = {\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token ?? null,\n idToken: tokens.id_token ?? null,\n // Access-token expiry: short, refreshed in the background.\n expiresAt: Date.now() + tokens.expires_in * 1000,\n // Session expiry: long. The user stays signed in until this\n // passes, however many access tokens come and go.\n sessionExpiresAt: Date.now() + cfg.sessionMaxAge! * 1000,\n };\n return redirectTo(url.origin + pkce.returnTo, [\n `${SESSION_COOKIE}=${await seal(session, cfg.secret)}; ${serialize(cookieOptions(cfg.sessionMaxAge!, secure))}`,\n clearCookie(PKCE_COOKIE, secure),\n ]);\n } catch {\n return redirectTo(url.origin + cfg.afterSignOutUrl!, [clearCookie(PKCE_COOKIE, secure)]);\n }\n }\n\n if (action === 'session') {\n // Read endpoint for `cookieStorageAdapter`. Returns the access token\n // only — the refresh token must never leave the server.\n const session = await unseal<ServerSession>(readCookie(request, SESSION_COOKIE), cfg.secret);\n // Judged on the SESSION, not the access token: reporting \"no\n // session\" for a merely stale token would sign the client out every\n // hour despite a perfectly good session.\n if (!isSessionLive(session)) {\n return Response.json({ accessToken: null, expiresAt: null });\n }\n return Response.json({\n accessToken: session.accessToken,\n idToken: session.idToken,\n expiresAt: session.expiresAt,\n });\n }\n\n if (action === 'logout') return doLogout(cfg, url, request, secure);\n\n return new Response('Not found', { status: 404 });\n }\n\n async function POST(request: Request, context: Ctx): Promise<Response> {\n const cfg = getCfg();\n const action = (await segments(context))[0];\n const url = new URL(request.url);\n if (action === 'logout') return doLogout(cfg, url, request, url.protocol === 'https:');\n return new Response('Not found', { status: 404 });\n }\n\n async function doLogout(\n cfg: LumoAuthNextConfig,\n url: URL,\n request: Request,\n secure: boolean,\n ): Promise<Response> {\n const session = await unseal<ServerSession>(readCookie(request, SESSION_COOKIE), cfg.secret);\n\n // Best-effort revoke before dropping the cookie. A failure here must not\n // block sign-out — the local session is going away regardless.\n if (session?.accessToken) {\n await authModule(cfg)\n .revokeToken(session.accessToken, session.accessToken)\n .catch(() => {});\n }\n\n // End the IdP session too, otherwise the next /authorize silently\n // re-issues a code and the user is never really signed out.\n const logout = new URL(\n `${cfg.domain.replace(/\\/+$/, '')}${buildPath(ROUTES['oauth.logout'].path, { orgId: cfg.orgId })}`,\n );\n logout.searchParams.set('post_logout_redirect_uri', url.origin + cfg.afterSignOutUrl!);\n if (session?.idToken) logout.searchParams.set('id_token_hint', session.idToken);\n\n return redirectTo(logout.toString(), [clearCookie(SESSION_COOKIE, secure)]);\n }\n\n return { GET, POST };\n}\n\n// ── Small cookie/response helpers ────────────────────────────────────\n\nfunction serialize(o: ReturnType<typeof cookieOptions>): string {\n return [\n `Path=${o.path}`,\n `Max-Age=${o.maxAge}`,\n `SameSite=${o.sameSite === 'lax' ? 'Lax' : o.sameSite}`,\n o.httpOnly ? 'HttpOnly' : '',\n o.secure ? 'Secure' : '',\n ]\n .filter(Boolean)\n .join('; ');\n}\n\nfunction clearCookie(name: string, secure: boolean): string {\n return `${name}=; Path=/; Max-Age=0; SameSite=Lax; HttpOnly${secure ? '; Secure' : ''}`;\n}\n\nfunction readCookie(request: Request, name: string): string | undefined {\n const header = request.headers.get('cookie');\n if (!header) return undefined;\n const hit = header.split('; ').find((c) => c.startsWith(`${name}=`));\n return hit?.slice(name.length + 1);\n}\n\nfunction redirectTo(location: string, cookies: string[]): Response {\n const headers = new Headers({ Location: location });\n cookies.forEach((c) => headers.append('Set-Cookie', c));\n return new Response(null, { status: 302, headers });\n}\n\nfunction withCookie(res: Response, cookie: string): Response {\n const headers = new Headers(res.headers);\n headers.append('Set-Cookie', cookie);\n return new Response(res.body, { status: res.status, headers });\n}\n","import { NextResponse, type NextRequest } from 'next/server';\nimport { AuthModule } from '@lumoauth/shared';\nimport { resolveConfig, type LumoAuthNextConfig } from './config';\nimport {\n SESSION_COOKIE,\n REFRESHED_SESSION_HEADER,\n cookieOptions,\n isSessionLive,\n isTokenStale,\n seal,\n unseal,\n type ServerSession,\n} from './session-cookie';\n\nexport interface MiddlewareOptions extends Partial<LumoAuthNextConfig> {\n /**\n * Paths requiring a session. Accepts globs (`/dashboard/:path*`), regexes,\n * or a predicate. Everything else is public.\n */\n protect?: Array<string | RegExp> | ((req: NextRequest) => boolean);\n /**\n * Keep the access token fresh automatically. @default true\n *\n * Turning this off means `auth().getToken()` returns null once the token\n * goes stale, because nothing else in the request pipeline is able to\n * persist a refreshed one.\n */\n refresh?: boolean;\n}\n\n/** Turn `/dashboard/:path*` into a RegExp. */\nfunction toMatcher(pattern: string | RegExp): RegExp {\n if (pattern instanceof RegExp) return pattern;\n const source = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\/:path\\*/g, '(?:/.*)?')\n .replace(/\\*/g, '.*');\n return new RegExp(`^${source}$`);\n}\n\n/**\n * Session refresh and route protection.\n *\n * ```ts\n * // middleware.ts\n * import { lumoAuthMiddleware } from '@lumoauth/nextjs/server';\n *\n * export default lumoAuthMiddleware({ protect: ['/dashboard/:path*'] });\n * export const config = { matcher: ['/((?!_next|.*\\\\..*).*)'] };\n * ```\n *\n * ## Why refresh belongs here\n *\n * An access token lasts about an hour; a session lasts weeks. Something has to\n * trade the refresh token for a new access token, and in Next.js that can only\n * happen where cookies are writable: middleware, route handlers, and server\n * actions. Server components cannot set cookies, so they can never persist a\n * refresh.\n *\n * That distinction is not cosmetic. LumoAuth rotates refresh tokens and revokes\n * the old one on use, so refreshing somewhere that cannot persist the result\n * would spend the token and break the session on the next request. Middleware\n * runs before the page renders and can write the response cookie, so it is the\n * correct place.\n *\n * Because middleware writes the cookie on the *response* while the page reads\n * the *request*, the fresh session is also forwarded on a request header that\n * `auth()` prefers — otherwise the refresh would not take effect until the\n * following request.\n */\nexport function lumoAuthMiddleware(options: MiddlewareOptions = {}) {\n const { protect = [], refresh = true, ...configOverrides } = options;\n\n return async function middleware(req: NextRequest) {\n const isProtected =\n typeof protect === 'function'\n ? protect(req)\n : protect.map(toMatcher).some((m) => m.test(req.nextUrl.pathname));\n\n const cfg = resolveConfig(configOverrides);\n const rawCookie = req.cookies.get(SESSION_COOKIE)?.value;\n const session = await unseal<ServerSession>(rawCookie, cfg.secret);\n\n // ── No live session ──────────────────────────────────────────\n if (!isSessionLive(session)) {\n if (!isProtected) {\n if (!rawCookie) return NextResponse.next();\n const res = NextResponse.next();\n res.cookies.delete(SESSION_COOKIE);\n return res;\n }\n const login = new URL('/api/auth/login', req.nextUrl.origin);\n login.searchParams.set('return_to', req.nextUrl.pathname + req.nextUrl.search);\n const res = NextResponse.redirect(login);\n // Drop the cookie whenever one was sent but is unusable — expired,\n // tampered with, or sealed under a rotated secret. Keying this on a\n // successfully parsed session would skip exactly the case that\n // needs clearing, and the browser would resend it forever.\n if (rawCookie) res.cookies.delete(SESSION_COOKIE);\n return res;\n }\n\n // ── Live session, token still good ───────────────────────────\n if (!refresh || !isTokenStale(session)) return NextResponse.next();\n\n // ── Live session, stale token: refresh and persist ───────────\n if (!session.refreshToken) {\n // Nothing to refresh with. The session is only as live as the\n // access token, which has just gone stale.\n if (!isProtected) return NextResponse.next();\n const login = new URL('/api/auth/login', req.nextUrl.origin);\n login.searchParams.set('return_to', req.nextUrl.pathname + req.nextUrl.search);\n return NextResponse.redirect(login);\n }\n\n try {\n const mod = new AuthModule({\n baseUrl: cfg.domain,\n orgId: cfg.orgId,\n clientId: cfg.clientId,\n });\n const tokens = await mod.refreshToken(session.refreshToken);\n\n const next: ServerSession = {\n accessToken: tokens.access_token,\n // Keep the existing token when the server does not rotate;\n // losing it here would silently end the session at the next\n // refresh.\n refreshToken: tokens.refresh_token ?? session.refreshToken,\n idToken: tokens.id_token ?? session.idToken,\n expiresAt: Date.now() + tokens.expires_in * 1000,\n sessionExpiresAt: session.sessionExpiresAt,\n };\n const sealed = await seal(next, cfg.secret);\n\n // Forward to the page rendering THIS request...\n const headers = new Headers(req.headers);\n headers.set(REFRESHED_SESSION_HEADER, sealed);\n const res = NextResponse.next({ request: { headers } });\n\n // ...and persist for the next one.\n const opts = cookieOptions(cfg.sessionMaxAge!, req.nextUrl.protocol === 'https:');\n res.cookies.set(SESSION_COOKIE, sealed, opts);\n return res;\n } catch {\n // The refresh token was rejected — revoked, rotated away, or the\n // session ended server-side. Treat it as signed out rather than\n // leaving a cookie that can never succeed.\n const res = isProtected\n ? NextResponse.redirect(new URL('/api/auth/login', req.nextUrl.origin))\n : NextResponse.next();\n res.cookies.delete(SESSION_COOKIE);\n return res;\n }\n };\n}\n"],"mappings":";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,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,YAAM,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/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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;AAAA,QACX,UAAU,IAAI;AAAA,MAClB,CAAC;AACD,YAAM,SAAS,MAAM,IAAI,aAAa,QAAQ,YAAY;AAE1D,YAAM,OAAsB;AAAA,QACxB,aAAa,OAAO;AAAA;AAAA;AAAA;AAAA,QAIpB,cAAc,OAAO,iBAAiB,QAAQ;AAAA,QAC9C,SAAS,OAAO,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,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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lumoauth/nextjs",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
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",
|
|
@@ -56,9 +56,9 @@
|
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
58
|
"@types/node": "^20.19.43",
|
|
59
|
-
"@types/react": "^
|
|
60
|
-
"next": "^
|
|
61
|
-
"react": "^
|
|
59
|
+
"@types/react": "^19.3.0",
|
|
60
|
+
"next": "^16.4.4",
|
|
61
|
+
"react": "^19.3.0",
|
|
62
62
|
"tsup": "^8.0.0",
|
|
63
63
|
"typescript": "^5.5.0"
|
|
64
64
|
},
|