// Pure, edge-safe session serialization (no `next/headers`, no Buffer) so it can // be used from both server route handlers and the edge middleware. // // Deliberately narrow: the admin session cookie carries only the JWT, the // resetPasswordRequired flag, and the absolute session cap (epoch seconds). It // MUST NOT carry `aclMenu` (too large for a cookie) or `roles` — both are // re-fetched via session hydration (`/api/auth/session` -> `/api/admin/me`) // instead. See admin-portal-auth spec, "The Admin JWT Lives Only In An httpOnly // Cookie". export interface SessionData { token: string; resetPasswordRequired?: boolean; /** Absolute session cap (epoch seconds): the sliding refresh must stop at this point. */ absoluteExpiry?: number; /** enforce-session-timeouts: original sign-in (epoch seconds); the cap is measured from here. */ signedInAt?: number; /** enforce-session-timeouts: last click/tap/key press reported by keepalive (epoch seconds). */ lastActivity?: number; /** enforce-session-timeouts: the idle limit in force (seconds), from the saved session policy. */ idleTtl?: number; } const num = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) ? v : undefined); /** * True once the session is past its idle limit or its cap (enforce-session-timeouts). A cookie written before that * change carries no activity time and never ends here; keepalive gives it times on its first call. */ export function sessionEnded(data: SessionData, nowSeconds: number): boolean { if (data.lastActivity == null) return false; if (data.idleTtl != null && nowSeconds - data.lastActivity > data.idleTtl) return true; return data.absoluteExpiry != null && nowSeconds >= data.absoluteExpiry; } export function encodeSession(data: SessionData): string { return encodeURIComponent(JSON.stringify(data)); } export function decodeSession(raw: string | undefined | null): SessionData | null { if (!raw) return null; try { const obj = JSON.parse(decodeURIComponent(raw)) as Partial; if (obj && typeof obj.token === "string") { // Backward-compatible: older cookies predate resetPasswordRequired / absoluteExpiry. return { token: obj.token, resetPasswordRequired: !!obj.resetPasswordRequired, absoluteExpiry: typeof obj.absoluteExpiry === "number" ? obj.absoluteExpiry : undefined, signedInAt: num(obj.signedInAt), lastActivity: num(obj.lastActivity), idleTtl: num(obj.idleTtl), }; } return null; } catch { return null; } } /** * The JWT's `exp` claim (epoch seconds), decoded without any crypto — the payload is plain * base64url JSON and the signature is validated by the services, not here. Returns null for a * malformed/unparseable token. The session cookie's maxAge is derived from this so the cookie * never outlives the token it carries (spec: "The Admin Cookie Lifetime Is Aligned To The Token * Lifetime"). */ export function tokenExpirySeconds(token: string): number | null { if (!token) return null; const parts = token.split("."); if (parts.length < 2) return null; try { const payloadJson = decodeBase64Url(parts[1]); const payload = JSON.parse(payloadJson) as { exp?: unknown }; return typeof payload.exp === "number" && Number.isFinite(payload.exp) ? payload.exp : null; } catch { return null; } } function decodeBase64Url(segment: string): string { const base64 = segment.replace(/-/g, "+").replace(/_/g, "/"); const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "="); // Node's Buffer is available in the server runtime (route handlers); the middleware // (edge) also supports atob. Prefer Buffer, fall back to atob. if (typeof Buffer !== "undefined") { return Buffer.from(padded, "base64").toString("utf-8"); } return atob(padded); }