flagon-io/g1t

public

Git for AI scale: a forge for thousands of agents working on the same code at once.

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

117 lines3,868 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Initial g1t: services, event bus, intents and attempts1import {
2 type MiddlewareFunction,
3 type RouterContextProvider,
4 createContext,
5 data,
6 redirect,
7} from "react-router";
8
Agents as a team: lifecycle, merge queue, billing and a new shell9import { type Result, type Role, type User, type Viewer, httpStatus } from "@g1t/contracts";
Initial g1t: services, event bus, intents and attempts10
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put11import { safeNext } from "./next";
API and MCP server, Rust identity service, registration, site redesign12import { identity } from "./services.server";
13
Initial g1t: services, event bus, intents and attempts14const 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
Agents as a team: lifecycle, merge queue, billing and a new shell29/** Pages a signed-in person can use before they have a workspace. */
30const BEFORE_WORKSPACE = ["/workspaces/new", "/settings", "/verify", "/logout"];
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 */
Initial g1t: services, event bus, intents and attempts39export const viewerMiddleware: MiddlewareFunction<Response> = async ({
40 request,
41 context,
42}) => {
43 const token = sessionToken(request);
Agents as a team: lifecycle, merge queue, billing and a new shell44 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 !BEFORE_WORKSPACE.includes(pathname) &&
54 !pathname.endsWith(".data")
55 ) {
56 const next = pathname === "/" ? "" : `?next=${encodeURIComponent(pathname + search)}`;
57 throw redirect(`/workspaces/new${next}`);
Initial g1t: services, event bus, intents and attempts58 }
59};
60
61type Context = Readonly<RouterContextProvider>;
62
63export function getViewer(context: Context): Viewer {
64 return context.get(viewerContext);
65}
66
Agents as a team: lifecycle, merge queue, billing and a new shell67/** The viewer's role in a workspace, or null if they are not a member. */
68export function roleIn(viewer: Viewer, slug: string): Role | null {
69 const wanted = slug.toLowerCase();
70 return (
71 viewer?.workspaces?.find((membership) => membership.slug === wanted)?.role ?? null
72 );
73}
74
Initial g1t: services, event bus, intents and attempts75export function requireUser(context: Context, request: Request): User {
76 const viewer = getViewer(context);
77 if (!viewer) {
Device sign-in replaces registering and minting tokens over the API78 // Keep the query string: a device sign-in link carries its code there.
79 const { pathname, search } = new URL(request.url);
80 throw redirect(`/login?next=${encodeURIComponent(pathname + search)}`);
Initial g1t: services, event bus, intents and attempts81 }
82 return viewer;
83}
84
API and MCP server, Rust identity service, registration, site redesign85/**
86 * Where to go after signing in. Only same-site paths are honoured, so
87 * `next` cannot redirect off g1t.
88 */
89export function nextPath(request: Request): string {
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put90 return safeNext(new URL(request.url).searchParams.get("next"));
API and MCP server, Rust identity service, registration, site redesign91}
92
Initial g1t: services, event bus, intents and attempts93/** `Set-Cookie` value that starts a session. */
94export function startSession(token: string): string {
95 return sessionCookie(token, SESSION_TTL_SECONDS);
96}
97
98/** Ends the session and returns the `Set-Cookie` value that clears it. */
99export async function endSession(request: Request): Promise<string> {
100 const token = sessionToken(request);
API and MCP server, Rust identity service, registration, site redesign101 if (token) await identity.signOut(token);
Initial g1t: services, event bus, intents and attempts102 return sessionCookie("", 0);
103}
104
105/** Rejects cross-site form posts; call at the top of every action. */
106export function assertSameOrigin(request: Request): void {
107 const origin = request.headers.get("origin");
108 if (origin && origin !== new URL(request.url).origin) {
109 throw new Response("Cross-origin request rejected", { status: 403 });
110 }
111}
112
113/** The value of a service result, or the matching HTTP error. */
114export function unwrap<T>(result: Result<T>): T {
115 if (result.ok) return result.value;
116 throw data(result.error.message, { status: httpStatus(result.error) });
117}