~james/core

core/web/src/lib/server/github/cookies.ts -rw-r--r-- 1.1 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import type { Cookies } from "@sveltejs/kit";
import { isSecureRequest } from "#lib/server/github/http.ts";

export const GITHUB_TOKEN_COOKIE = "tangled.github.token";
export const GITHUB_STATE_COOKIE = "tangled.github.state";

const PATH = "/_internal/github";
const STATE_TTL_SECONDS = 600;
export const TOKEN_TTL_SECONDS = 3600;

interface CookieJar {
	read(): string | undefined;
	write(value: string): void;
	clear(): void;
}

const jar = (cookies: Cookies, name: string, ttl: number, secure: boolean): CookieJar => {
	const options = (maxAge: number) => ({
		httpOnly: true,
		secure,
		sameSite: "lax" as const,
		path: PATH,
		maxAge
	});
	return {
		read: () => cookies.get(name),
		write: (value) => cookies.set(name, value, options(ttl)),
		clear: () => cookies.delete(name, options(0))
	};
};

export const githubCookies = (cookies: Cookies, url: URL, headers: Headers) => {
	const secure = isSecureRequest(url, headers);
	return {
		state: jar(cookies, GITHUB_STATE_COOKIE, STATE_TTL_SECONDS, secure),
		token: jar(cookies, GITHUB_TOKEN_COOKIE, TOKEN_TTL_SECONDS, secure)
	};
};