Skip to content
refs
83 lines · 3.0 KBRaw
1import { data, redirect } from "react-router";
2import type { RouterContextProvider } from "react-router";
3import { NAMESPACE_COOKIE, SESSION_COOKIE, refsErrorCode, type Gate, type Problem, type Refs, type Session } from "@refs/backend/contract";
4import { refsContext, requestContext } from "../context";
5
6type Context = Readonly<RouterContextProvider>;
7
8const PROBLEM_STATUS: Record<Problem["code"], number> = { invalid: 400, conflict: 409, rate_limited: 429, unavailable: 502 };
9
10export function readCookie(request: Request, name: string): string | null {
11 for (const part of (request.headers.get("cookie") ?? "").split(";")) {
12 const [key, ...value] = part.trim().split("=");
13 if (key === name) return value.join("=");
14 }
15 return null;
16}
17
18export function sessionToken(request: Request): string | null {
19 return readCookie(request, SESSION_COOKIE);
20}
21
22export function sessionCookie(session: Session): string {
23 return `${SESSION_COOKIE}=${session.token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${session.maxAge}`;
24}
25
26export function namespaceCookie(slug: string): string {
27 return `${NAMESPACE_COOKIE}=${slug}; Path=/; Secure; SameSite=Lax; Max-Age=31536000`;
28}
29
30export function clearedSessionCookie(): string {
31 return `${SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`;
32}
33
34export function gate(context: Context): Gate {
35 return context.get(requestContext).backend.gate();
36}
37
38export function refs(context: Context): Refs {
39 const handle = context.get(refsContext);
40 if (!handle) throw new Error("The refs handle is opened by the root middleware.");
41 return handle;
42}
43
44/** The handle for a signed-in actor; anonymous visitors are sent to sign in. */
45export function signedIn(context: Context): Refs {
46 const handle = refs(context);
47 if (!handle.viewer.person) throw redirect("/login");
48 return handle;
49}
50
51/** Turns the backend's thrown failures into HTTP responses: missing things become 404s and anonymous access becomes a sign-in redirect. */
52export async function found<T>(promise: Promise<T>): Promise<T> {
53 try {
54 return await promise;
55 } catch (error) {
56 const code = refsErrorCode(error);
57 if (code === "not_found") throw data(null, { status: 404 });
58 if (code === "sign_in_required") throw redirect("/login");
59 throw error;
60 }
61}
62
63export function failed<T extends object>(problem: Problem, extra: T) {
64 return data({ ...extra, error: problem.message }, { status: PROBLEM_STATUS[problem.code] });
65}
66
67export function fullName(params: { readonly ns?: string; readonly repo?: string }): string {
68 return `${params.ns}/${params.repo}`;
69}
70
71export function formText(form: FormData, name: string): string {
72 const value = form.get(name);
73 return typeof value === "string" ? value.trim() : "";
74}
75
76export function formList(form: FormData, name: string): string[] {
77 return form.getAll(name).filter((value): value is string => typeof value === "string");
78}
79
80/** The current time in seconds, the unit every timestamp from the backend uses. */
81export function nowSeconds(): number {
82 return Math.floor(Date.now() / 1000);
83}