this repo has no description
at 1fb0691cba47c2fbaf3253591c2c40619611e2d7 75 lines 2.0 kB view raw
1import type { Context } from "hono"; 2import { deleteCookie, getCookie, setCookie } from "hono/cookie"; 3 4const SESSION_COOKIE_NAME = "session_id"; 5const RETURN_TO_COOKIE_NAME = "login_return_to"; 6const SESSION_TTL = 60 * 60 * 24 * 14; // 14 days in seconds 7const RETURN_TO_TTL = 600; // 10 minutes in seconds 8 9function baseCookieOptions(clientUrl: string) { 10 const isLocalhost = clientUrl.includes("localhost"); 11 return { 12 httpOnly: true as const, 13 sameSite: "Lax" as const, 14 path: "/", 15 ...(isLocalhost ? {} : { domain: ".sequoia.pub", secure: true }), 16 }; 17} 18 19/** 20 * Get DID from session cookie 21 */ 22export function getSessionDid(c: Context): string | null { 23 const value = getCookie(c, SESSION_COOKIE_NAME); 24 return value ? decodeURIComponent(value) : null; 25} 26 27/** 28 * Set session cookie with the user's DID 29 */ 30export function setSessionCookie( 31 c: Context, 32 did: string, 33 clientUrl: string, 34): void { 35 setCookie(c, SESSION_COOKIE_NAME, encodeURIComponent(did), { 36 ...baseCookieOptions(clientUrl), 37 maxAge: SESSION_TTL, 38 }); 39} 40 41/** 42 * Clear session cookie 43 */ 44export function clearSessionCookie(c: Context, clientUrl: string): void { 45 deleteCookie(c, SESSION_COOKIE_NAME, baseCookieOptions(clientUrl)); 46} 47 48/** 49 * Get the post-OAuth return-to URL from the short-lived cookie 50 */ 51export function getReturnToCookie(c: Context): string | null { 52 const value = getCookie(c, RETURN_TO_COOKIE_NAME); 53 return value ? decodeURIComponent(value) : null; 54} 55 56/** 57 * Set a short-lived cookie that redirects back after OAuth completes 58 */ 59export function setReturnToCookie( 60 c: Context, 61 returnTo: string, 62 clientUrl: string, 63): void { 64 setCookie(c, RETURN_TO_COOKIE_NAME, encodeURIComponent(returnTo), { 65 ...baseCookieOptions(clientUrl), 66 maxAge: RETURN_TO_TTL, 67 }); 68} 69 70/** 71 * Clear the return-to cookie 72 */ 73export function clearReturnToCookie(c: Context, clientUrl: string): void { 74 deleteCookie(c, RETURN_TO_COOKIE_NAME, baseCookieOptions(clientUrl)); 75}