export function parseCookies (header) { const out = Object.create(null); if (!header) { return out; } for (const part of String(header).split(";")) { const trimmed = part.trim(); if (!trimmed) { continue; } const eq = trimmed.indexOf("="); if (eq <= 0) { continue; } const key = trimmed.slice(0, eq); const value = trimmed.slice(eq + 1); out[key] = decodeURIComponent(value); } return out; } export function publicOrigin (req) { const host = req.headers["x-forwarded-host"] ?? req.headers.host ?? "localhost"; const proto = req.headers["x-forwarded-proto"] ?? "http"; return `${proto}://${host}`; } export function isSecureRequest (req) { const proto = req.headers["x-forwarded-proto"]; if (proto) { return proto === "https"; } return false; } export function setCookie (res, name, value, { maxAgeSec, httpOnly = true, sameSite = "Lax", secure = false, path = "/" } = {}) { const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${path}`, `SameSite=${sameSite}`]; if (httpOnly) { parts.push("HttpOnly"); } if (secure) { parts.push("Secure"); } if (maxAgeSec != null) { parts.push(`Max-Age=${maxAgeSec}`); } res.appendHeader("Set-Cookie", parts.join("; ")); } export function clearCookie (res, name, { secure = false, path = "/" } = {}) { const parts = [`${name}=`, `Path=${path}`, "Max-Age=0", "SameSite=Lax"]; parts.push("HttpOnly"); if (secure) { parts.push("Secure"); } res.appendHeader("Set-Cookie", parts.join("; ")); }