/** * Session 與 cookie 工具(OAuth 登入用)。 * * - 不自存密碼(登入走 OAuth),故這裡只負責「登入後的 session token」與 cookie 讀寫。 * - session token = 32 bytes 隨機值(不可猜),存後端、放進 httpOnly cookie;JS 讀不到 → 防 XSS 竊取。 * - cookie 手動序列化/解析(OAuth state 與 session 皆為隨機值,毋須簽章),不引入額外相依。 */ import { randomBytes, timingSafeEqual } from "node:crypto"; export const SESSION_COOKIE = "wcg_session"; export const STATE_COOKIE = "wcg_oauth_state"; /** 登入後要返回的站內路徑(短效,與 state 同生命週期)。 */ export const NEXT_COOKIE = "wcg_oauth_next"; /** session 有效期:30 天。 */ export const SESSION_TTL_SEC = 60 * 60 * 24 * 30; /** OAuth state cookie 短效期:30 分鐘(夠走完授權往返;使用者在 Google 同意頁逗留也不易過期)。 */ export const STATE_TTL_SEC = 60 * 30; /** 產生不可猜的隨機 token(base64url,無需 URL 編碼)。 */ export function newToken(): string { return randomBytes(32).toString("base64url"); } export interface CookieOpts { maxAgeSec?: number; httpOnly?: boolean; secure?: boolean; sameSite?: "Strict" | "Lax" | "None"; path?: string; } /** 序列化成單一 Set-Cookie 字串。 */ export function serializeCookie(name: string, value: string, opts: CookieOpts = {}): string { const parts = [`${name}=${encodeURIComponent(value)}`]; if (opts.maxAgeSec !== undefined) parts.push(`Max-Age=${Math.floor(opts.maxAgeSec)}`); parts.push(`Path=${opts.path ?? "/"}`); if (opts.httpOnly) parts.push("HttpOnly"); if (opts.secure) parts.push("Secure"); if (opts.sameSite) parts.push(`SameSite=${opts.sameSite}`); return parts.join("; "); } /** 立即過期的 cookie(登出/清 state 用)。 */ export function clearCookie(name: string, secure: boolean): string { return serializeCookie(name, "", { maxAgeSec: 0, httpOnly: true, secure, sameSite: "Lax" }); } /** 解析 Cookie 請求標頭成 name→value。 */ export function parseCookies(header: string | undefined): Record { const out: Record = {}; if (!header) return out; for (const part of header.split(";")) { const idx = part.indexOf("="); if (idx < 0) continue; const k = part.slice(0, idx).trim(); if (!k) continue; try { out[k] = decodeURIComponent(part.slice(idx + 1).trim()); } catch { // 壞的 percent-encoding 不該讓任一 auth/admin 路由噴 500;忽略該 cookie 即可。 } } return out; } /** 從 Authorization 標頭取 Bearer token(Activity 用,無 cookie 時的身分憑證);無則 null。 */ export function parseBearer(header: string | undefined): string | null { if (!header) return null; const m = /^Bearer\s+(.+)$/i.exec(header.trim()); return m ? m[1]!.trim() : null; } /** 定速字串比對(防 token 比對的時序側信道);長度不同直接 false。 */ export function safeEqual(a: string, b: string): boolean { const ab = Buffer.from(a, "utf8"); const bb = Buffer.from(b, "utf8"); if (ab.length !== bb.length) return false; return timingSafeEqual(ab, bb); }