File
Blob: src/worker/services/cookies.ts
| 1 | import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from "hono/cookie"; |
| 2 | import type { CookieOptions } from "hono/utils/cookie"; |
| 3 | import type { AppContext } from "@/worker/types"; |
| 4 | |
| 5 | export const AUTH_COOKIE_PREFIX = "host"; |
| 6 | export const ADMIN_COOKIE_NAME = "flamemail-admin"; |
| 7 | export const OIDC_TRANSACTION_COOKIE_NAME = "flamemail-oidc"; |
| 8 | export const ADMIN_COOKIE_HEADER_NAME = `__Host-${ADMIN_COOKIE_NAME}`; |
| 9 | export const OIDC_TRANSACTION_COOKIE_HEADER_NAME = `__Host-${OIDC_TRANSACTION_COOKIE_NAME}`; |
| 10 | |
| 11 | const OIDC_TRANSACTION_MAX_AGE_SECONDS = 5 * 60; |
| 12 | |
| 13 | const SHARED_COOKIE_OPTIONS = { |
| 14 | httpOnly: true, |
| 15 | sameSite: "Lax", |
| 16 | prefix: AUTH_COOKIE_PREFIX, |
| 17 | } as const satisfies CookieOptions; |
| 18 | |
| 19 | export type SignedCookieReadResult = |
| 20 | | { kind: "ok"; value: string } |
| 21 | | { kind: "missing" } |
| 22 | | { kind: "invalid_signature" }; |
| 23 | export type CookieSigningSecret = BufferSource; |
| 24 | |
| 25 | export function setAdminCookie(c: AppContext, token: string, ttlSeconds: number) { |
| 26 | setCookie(c, ADMIN_COOKIE_NAME, token, { |
| 27 | ...SHARED_COOKIE_OPTIONS, |
| 28 | maxAge: Math.max(60, Math.floor(ttlSeconds)), |
| 29 | }); |
| 30 | } |
| 31 | |
| 32 | export function getAdminCookie(c: AppContext): string | undefined { |
| 33 | return getCookie(c, ADMIN_COOKIE_NAME, AUTH_COOKIE_PREFIX); |
| 34 | } |
| 35 | |
| 36 | export function clearAdminCookie(c: AppContext) { |
| 37 | deleteCookie(c, ADMIN_COOKIE_NAME, SHARED_COOKIE_OPTIONS); |
| 38 | } |
| 39 | |
| 40 | export async function setOidcTransactionCookie( |
| 41 | c: AppContext, |
| 42 | value: string, |
| 43 | secret: CookieSigningSecret, |
| 44 | ): Promise<void> { |
| 45 | await setSignedCookie(c, OIDC_TRANSACTION_COOKIE_NAME, value, secret, { |
| 46 | ...SHARED_COOKIE_OPTIONS, |
| 47 | maxAge: OIDC_TRANSACTION_MAX_AGE_SECONDS, |
| 48 | }); |
| 49 | } |
| 50 | |
| 51 | export async function getOidcTransactionCookie( |
| 52 | c: AppContext, |
| 53 | secret: CookieSigningSecret, |
| 54 | ): Promise<SignedCookieReadResult> { |
| 55 | const rawValue = getCookie(c, OIDC_TRANSACTION_COOKIE_NAME, AUTH_COOKIE_PREFIX); |
| 56 | if (rawValue === undefined) { |
| 57 | return { kind: "missing" }; |
| 58 | } |
| 59 | |
| 60 | const value = await getSignedCookie(c, secret, OIDC_TRANSACTION_COOKIE_NAME, AUTH_COOKIE_PREFIX); |
| 61 | if (value === undefined || value === false) { |
| 62 | return { kind: "invalid_signature" }; |
| 63 | } |
| 64 | |
| 65 | return { kind: "ok", value }; |
| 66 | } |
| 67 | |
| 68 | export function clearOidcTransactionCookie(c: AppContext) { |
| 69 | deleteCookie(c, OIDC_TRANSACTION_COOKIE_NAME, SHARED_COOKIE_OPTIONS); |
| 70 | } |