// sign-session-cookies (F32): the session cookie is HMAC-SHA256 signed, so its flags (reset required, country, the // absolute cap, ...) cannot be edited by whoever holds it. Web Crypto only: runs in the middleware and in Node. // // Shape: the existing URL-encoded JSON (sessionCodec) with one extra last field, `sig`, the base64url HMAC of the JSON // payload without it. Key: a per-portal label plus SESSION_SECRET, else plus the server-only MOBILE_API_KEY. No key: sealing throws and // nothing opens (fail closed). import { decodeSession, encodeSession, type SessionData } from "./sessionCodec"; // Per-portal label (review): a cookie signed for one portal never verifies on the other, even with a shared secret. const KEY_LABEL = "bb-admin-session-v1:"; const encoder = new TextEncoder(); const keyCache = new Map>(); function secret(): string { const base = process.env.SESSION_SECRET || process.env.MOBILE_API_KEY || ""; return base ? KEY_LABEL + base : ""; } function hmacKey(value: string): Promise { let key = keyCache.get(value); if (!key) { key = crypto.subtle.importKey("raw", encoder.encode(value), { name: "HMAC", hash: "SHA-256" }, false, [ "sign", "verify", ]); keyCache.set(value, key); } return key; } function toBase64Url(bytes: Uint8Array): string { let binary = ""; for (const b of bytes) binary += String.fromCharCode(b); return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } function fromBase64Url(text: string): Uint8Array | null { if (!/^[A-Za-z0-9_-]+$/.test(text)) return null; const base64 = text.replace(/-/g, "+").replace(/_/g, "/"); const binary = atob(base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=")); return Uint8Array.from(binary, c => c.charCodeAt(0)); } /** The cookie value for `data`: its JSON plus a signature. Throws when no signing key is configured. */ export async function sealSession(data: SessionData): Promise { const value = secret(); if (!value) throw new Error("Session signing key is not configured (SESSION_SECRET or MOBILE_API_KEY)"); const payload = JSON.parse(decodeURIComponent(encodeSession(data))) as Record; const signature = await crypto.subtle.sign("HMAC", await hmacKey(value), encoder.encode(JSON.stringify(payload))); return encodeURIComponent(JSON.stringify({ ...payload, sig: toBase64Url(new Uint8Array(signature)) })); } /** The session in a cookie value, or null when it is absent, malformed, unsigned or its signature does not verify. */ export async function openSession(raw: string | undefined | null): Promise { const value = secret(); if (!raw || !value) return null; try { const obj = JSON.parse(decodeURIComponent(raw)) as Record; if (!obj || typeof obj !== "object" || typeof obj.sig !== "string") return null; const signature = fromBase64Url(obj.sig); if (!signature) return null; delete obj.sig; const payload = JSON.stringify(obj); const valid = await crypto.subtle.verify("HMAC", await hmacKey(value), signature as BufferSource, encoder.encode(payload)); return valid ? decodeSession(encodeURIComponent(payload)) : null; } catch { return null; } }