flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/apps/web/app/lib/session.server.ts

133 lines4,631 bytesCodeBlame
1import {
2 type MiddlewareFunction,
3 type RouterContextProvider,
4 createContext,
5 data,
6 redirect,
7} from "react-router";
8
9import { type Result, type Role, type User, type Viewer, httpStatus } from "@g1t/contracts";
10
11import { safeNext } from "./next";
12import { identity } from "./services.server";
13
14const SESSION_COOKIE = "g1t_session";
15const SESSION_TTL_SECONDS = 30 * 24 * 60 * 60;
16
17const viewerContext = createContext<Viewer>(null);
18
19function sessionToken(request: Request): string | null {
20 const cookies = request.headers.get("cookie") ?? "";
21 const match = new RegExp(`(?:^|; )${SESSION_COOKIE}=([0-9a-f]{64})`).exec(cookies);
22 return match ? match[1] : null;
23}
24
25function sessionCookie(value: string, maxAge: number): string {
26 return `${SESSION_COOKIE}=${value}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}`;
27}
28
29/** Pages a signed-in person can use before they have a workspace. */
30const BEFORE_WORKSPACE = ["/workspaces/new", "/settings", "/verify", "/logout", "/auth/github", "/auth/github/callback"];
31
32/**
33 * Root middleware: resolves the signed-in user once per request.
34 *
35 * Everything on g1t lives in a workspace, so a confirmed account with none
36 * is sent to create one, from wherever it was going, and returned there
37 * afterwards.
38 */
39export const viewerMiddleware: MiddlewareFunction<Response> = async ({
40 request,
41 context,
42}) => {
43 const token = sessionToken(request);
44 if (!token) return;
45 const viewer = await identity.userForSession(token);
46 context.set(viewerContext, viewer);
47
48 const { pathname, search } = new URL(request.url);
49 if (
50 request.method === "GET" &&
51 viewer?.verified &&
52 (viewer.workspaces ?? []).length === 0 &&
53 // Someone a repository is shared with can use it without a workspace.
54 (viewer.grants ?? []).length === 0 &&
55 !BEFORE_WORKSPACE.includes(pathname) &&
56 // An invite to a workspace is how someone without one gets one, and an
57 // invitation to a repository is answered before anything else.
58 !pathname.startsWith("/invite/") &&
59 !/^\/[^/]+\/[^/]+\/invitations\/?$/.test(pathname) &&
60 !pathname.endsWith(".data")
61 ) {
62 const next = pathname === "/" ? "" : `?next=${encodeURIComponent(pathname + search)}`;
63 throw redirect(`/workspaces/new${next}`);
64 }
65};
66
67type Context = Readonly<RouterContextProvider>;
68
69export function getViewer(context: Context): Viewer {
70 return context.get(viewerContext);
71}
72
73/** The viewer's role in a workspace, or null if they are not a member. */
74export function roleIn(viewer: Viewer, slug: string): Role | null {
75 const wanted = slug.toLowerCase();
76 return (
77 viewer?.workspaces?.find((membership) => membership.slug === wanted)?.role ?? null
78 );
79}
80
81export function requireUser(context: Context, request: Request): User {
82 const viewer = getViewer(context);
83 if (!viewer) {
84 // Keep the query string: a device sign-in link carries its code there.
85 const { pathname, search } = new URL(request.url);
86 throw redirect(`/login?next=${encodeURIComponent(pathname + search)}`);
87 }
88 return viewer;
89}
90
91/**
92 * Where to go after signing in. Only same-site paths are honoured, so
93 * `next` cannot redirect off g1t.
94 */
95export function nextPath(request: Request): string {
96 return safeNext(new URL(request.url).searchParams.get("next"));
97}
98
99/** `Set-Cookie` value that starts a session. */
100export function startSession(token: string): string {
101 return sessionCookie(token, SESSION_TTL_SECONDS);
102}
103
104/** Ends the session and returns the `Set-Cookie` value that clears it. */
105export async function endSession(request: Request): Promise<string> {
106 const token = sessionToken(request);
107 if (token) await identity.signOut(token);
108 return sessionCookie("", 0);
109}
110
111/** The session token the request carries, for proof of a recent sign-in. */
112export function sessionTokenOf(request: Request): string | null {
113 return sessionToken(request);
114}
115
116/** The visitor's IP address, as Cloudflare saw it, for rate limits. */
117export function clientOf(request: Request): string | null {
118 return request.headers.get("cf-connecting-ip");
119}
120
121/** Rejects cross-site form posts; call at the top of every action. */
122export function assertSameOrigin(request: Request): void {
123 const origin = request.headers.get("origin");
124 if (origin && origin !== new URL(request.url).origin) {
125 throw new Response("Cross-origin request rejected", { status: 403 });
126 }
127}
128
129/** The value of a service result, or the matching HTTP error. */
130export function unwrap<T>(result: Result<T>): T {
131 if (result.ok) return result.value;
132 throw data(result.error.message, { status: httpStatus(result.error) });
133}