Skip to content

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

149 lines5,568 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 // Someone held out of their workspaces until they meet its policy is
56 // told so, and sent to turn on two-factor authentication, not to make one.
57 (viewer.held ?? []).length === 0 &&
58 !BEFORE_WORKSPACE.includes(pathname) &&
59 !pathname.startsWith("/settings/") &&
60 // An invite to a workspace is how someone without one gets one, and an
61 // invitation to a repository is answered before anything else.
62 !pathname.startsWith("/invite/") &&
63 !/^\/[^/]+\/[^/]+\/invitations\/?$/.test(pathname) &&
64 !pathname.endsWith(".data")
65 ) {
66 const next = pathname === "/" ? "" : `?next=${encodeURIComponent(pathname + search)}`;
67 throw redirect(`/workspaces/new${next}`);
68 }
69};
70
71type Context = Readonly<RouterContextProvider>;
72
73export function getViewer(context: Context): Viewer {
74 return context.get(viewerContext);
75}
76
77/** The viewer's role in a workspace, or null if they are not a member. */
78export function roleIn(viewer: Viewer, slug: string): Role | null {
79 const wanted = slug.toLowerCase();
80 return (
81 viewer?.workspaces?.find((membership) => membership.slug === wanted)?.role ?? null
82 );
83}
84
85/** Whether the viewer may manage a workspace's billing: an owner or a billing manager. */
86export function managesBilling(viewer: Viewer, slug: string): boolean {
87 const membership = viewer?.workspaces?.find((m) => m.slug === slug.toLowerCase());
88 return membership?.role === "owner" || !!membership?.org_roles?.includes("billing_manager");
89}
90
91/** Whether the viewer may manage security across a workspace: an owner or a security manager. */
92export function managesSecurity(viewer: Viewer, slug: string): boolean {
93 const membership = viewer?.workspaces?.find((m) => m.slug === slug.toLowerCase());
94 return membership?.role === "owner" || !!membership?.org_roles?.includes("security_manager");
95}
96
97export function requireUser(context: Context, request: Request): User {
98 const viewer = getViewer(context);
99 if (!viewer) {
100 // Keep the query string: a device sign-in link carries its code there.
101 const { pathname, search } = new URL(request.url);
102 throw redirect(`/login?next=${encodeURIComponent(pathname + search)}`);
103 }
104 return viewer;
105}
106
107/**
108 * Where to go after signing in. Only same-site paths are honoured, so
109 * `next` cannot redirect off g1t.
110 */
111export function nextPath(request: Request): string {
112 return safeNext(new URL(request.url).searchParams.get("next"));
113}
114
115/** `Set-Cookie` value that starts a session. */
116export function startSession(token: string): string {
117 return sessionCookie(token, SESSION_TTL_SECONDS);
118}
119
120/** Ends the session and returns the `Set-Cookie` value that clears it. */
121export async function endSession(request: Request): Promise<string> {
122 const token = sessionToken(request);
123 if (token) await identity.signOut(token);
124 return sessionCookie("", 0);
125}
126
127/** The session token the request carries, for proof of a recent sign-in. */
128export function sessionTokenOf(request: Request): string | null {
129 return sessionToken(request);
130}
131
132/** The visitor's IP address, as Cloudflare saw it, for rate limits. */
133export function clientOf(request: Request): string | null {
134 return request.headers.get("cf-connecting-ip");
135}
136
137/** Rejects cross-site form posts; call at the top of every action. */
138export function assertSameOrigin(request: Request): void {
139 const origin = request.headers.get("origin");
140 if (origin && origin !== new URL(request.url).origin) {
141 throw new Response("Cross-origin request rejected", { status: 403 });
142 }
143}
144
145/** The value of a service result, or the matching HTTP error. */
146export function unwrap<T>(result: Result<T>): T {
147 if (result.ok) return result.value;
148 throw data(result.error.message, { status: httpStatus(result.error) });
149}