docs/src/lib/session.ts 1.9 K raw
1
import type { Context } from "hono";
2
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
3
4
const SESSION_COOKIE_NAME = "session_id";
5
const RETURN_TO_COOKIE_NAME = "login_return_to";
6
const SESSION_TTL = 60 * 60 * 24 * 14; // 14 days in seconds
7
const RETURN_TO_TTL = 600; // 10 minutes in seconds
8
9
function 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
 */
22
export 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
 */
30
export 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
 */
44
export 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
 */
51
export 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
 */
59
export 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
 */
73
export function clearReturnToCookie(c: Context, clientUrl: string): void {
74
	deleteCookie(c, RETURN_TO_COOKIE_NAME, baseCookieOptions(clientUrl));
75
}