import { environment } from "#environment/config"; import { jwt } from "#environment/jwt"; import type { CookieOptions } from "#types/config"; import type { ExtendedRequest } from "#types/server"; class CookieService { extractToken(request: Request | ExtendedRequest): string | null { return request.headers.get("Cookie")?.match(/session=([^;]+)/)?.[1] || null; } generateCookie( token: string, maxAge = jwt.expiration, options?: CookieOptions, ): string { const { secure = !environment.development, httpOnly = true, sameSite = environment.development ? "Lax" : "None", path = "/", domain, } = options || {}; let cookie = `session=${encodeURIComponent(token)}; Path=${path}; Max-Age=${maxAge}`; if (httpOnly) cookie += "; HttpOnly"; if (secure) cookie += "; Secure"; if (sameSite) cookie += `; SameSite=${sameSite}`; if (domain) cookie += `; Domain=${domain}`; return cookie; } clearCookie(options?: Omit): string { const { sameSite = environment.development ? "Lax" : "None", path = "/", domain, } = options || {}; let cookie = `session=; Path=${path}; Max-Age=0; HttpOnly`; if (!environment.development) cookie += "; Secure"; if (sameSite) cookie += `; SameSite=${sameSite}`; if (domain) cookie += `; Domain=${domain}`; return cookie; } } const cookieService = new CookieService(); export { CookieService, cookieService };