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)
};
};