export type AdminRole = 'manager' | 'admin' | 'super_admin' export interface AdminSession { email: string role: AdminRole token: string loginAt: string expiresAt: number } const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/ export function requireAdminSessionSecret(): string { const value = process.env.ADMIN_SESSION_SECRET?.trim() if (!value || new TextEncoder().encode(value).byteLength < 32) { throw new Error('ADMIN_SESSION_SECRET must contain at least 32 bytes') } return value } export function parseAdminSession(value: unknown, now = Date.now()): AdminSession | null { if (!value || typeof value !== 'object' || Array.isArray(value)) return null const candidate = value as Record const email = typeof candidate.email === 'string' ? candidate.email.trim().toLowerCase() : '' const role = candidate.role const token = candidate.token const loginAt = candidate.loginAt const expiresAt = candidate.expiresAt if (!email || email.length > 150 || !email.includes('@')) return null if (role !== 'manager' && role !== 'admin' && role !== 'super_admin') return null if (typeof token !== 'string' || token.length < 80 || token.length > 8_192) return null if (typeof loginAt !== 'string' || !Number.isFinite(Date.parse(loginAt))) return null if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt) || expiresAt <= now) return null return { email, role, token, loginAt, expiresAt } } export function decodeBase64Url(value: string): Uint8Array | null { if (!value || !BASE64URL_PATTERN.test(value)) return null try { const padding = '='.repeat((4 - (value.length % 4)) % 4) const binary = atob(value.replace(/-/g, '+').replace(/_/g, '/') + padding) const bytes = new Uint8Array(binary.length) for (let index = 0; index < binary.length; index += 1) { bytes[index] = binary.charCodeAt(index) } return bytes } catch { return null } } export function decodeAdminSessionPayload(encodedPayload: string): AdminSession | null { const bytes = decodeBase64Url(encodedPayload) if (!bytes || bytes.byteLength === 0 || bytes.byteLength > 16_384) return null try { return parseAdminSession(JSON.parse(new TextDecoder().decode(bytes))) } catch { return null } } // ADMIN_COOKIE_SECURE=false: TLS 종료 프록시 없이 LAN HTTP(예: http://NAS_IP:3001)로 // 직접 접속하는 배포에서만 사용. Secure 쿠키는 HTTP에서 브라우저가 버려 로그인이 유지되지 않는다. export function adminCookieSecure(): boolean { if (process.env.ADMIN_COOKIE_SECURE === 'false') return false return process.env.NODE_ENV === 'production' }