Skip to content

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.sh
188 linesCodeBlameRaw
1import { Form, Link, data, redirect } from "react-router";
2
3import type { Route } from "./+types/github-setup";
4import { AuthCard } from "../components/auth-card";
5import { GithubMark } from "../components/github";
6import { ErrorText, SubmitButton } from "../components/ui";
7import { INSTALL_COOKIE, cookie, installWorkspace, installationSummary, readCookie, setupChoices } from "../lib/github";
8import { githubApp } from "../lib/github.server";
9import { page } from "../lib/meta";
10import { assertSameOrigin, requireUser, roleIn } from "../lib/session.server";
11
12export function meta(args: Route.MetaArgs) {
13 return page(args, { title: "Connecting GitHub · g1t" });
14}
15
16type Problem = { kind: "error"; error: string; workspace: string | null; link: string | null };
17type Choice = {
18 kind: "choose";
19 installation: { id: number; account: string; summary: string };
20 workspaces: { slug: string; name: string; added: boolean }[];
21};
22
23/**
24 * The app's Setup URL: GitHub returns here after an installation with
25 * `installation_id`, `setup_action` and the state. The installation is
26 * recorded against the workspace it was started for, after integrations
27 * checks with the person's own GitHub token that they can see it.
28 *
29 * Without g1t's state (the app was installed on GitHub directly, from
30 * another browser, or the cookie was lost), it is added to the workspace
31 * the person owns, or with several they choose which, checked the same
32 * way; a GitHub account not linked yet is linked on the way.
33 */
34export async function loader({ request, context }: Route.LoaderArgs) {
35 const user = requireUser(context, request);
36 const url = new URL(request.url);
37 const clear = { "set-cookie": cookie(INSTALL_COOKIE, "", 0) };
38 const workspace = installWorkspace(readCookie(request.headers.get("cookie"), INSTALL_COOKIE), url.searchParams.get("state"));
39 const action = url.searchParams.get("setup_action");
40 const installation = Number(url.searchParams.get("installation_id"));
41 const problem = (error: string, at: string | null = workspace, link: string | null = null) =>
42 data<Problem | Choice>({ kind: "error", error, workspace: at, link }, { headers: clear });
43 // GitHub not linked, or its access ended: link it and come back here,
44 // once; a link that did not take shows the problem instead.
45 const relink = (code: string) => {
46 if (code !== "not_found" && code !== "unauthenticated") return null;
47 const back = new URL(url);
48 back.searchParams.set("linked", "1");
49 const link = `/auth/github?link=1&next=${encodeURIComponent(`${back.pathname}${back.search}`)}`;
50 if (url.searchParams.get("linked") !== "1") throw redirect(link);
51 return link;
52 };
53 // Repositories chosen again on GitHub: nothing to record, the picker
54 // lists what the installation can see now.
55 if (!workspace && action === "update") throw redirect("/new/github", { headers: clear });
56 // An organization member asked an owner to approve: nothing to record yet.
57 if (action === "request") {
58 const back = workspace ? `/new/github?workspace=${encodeURIComponent(workspace)}&` : "/new/github?";
59 throw redirect(`${back}requested=1`, { headers: clear });
60 }
61 if (!Number.isSafeInteger(installation) || installation <= 0) {
62 return problem("GitHub did not say which installation was made.");
63 }
64 if (workspace) {
65 const added = await githubApp.addInstallation(user, workspace, installation);
66 if (!added.ok) return problem(added.error.message, workspace, relink(added.error.code));
67 throw redirect(`/new/github?workspace=${encodeURIComponent(workspace)}&installation=${installation}`, { headers: clear });
68 }
69 const owned = (user.workspaces ?? []).filter((membership) => membership.role === "owner");
70 if (owned.length === 0) {
71 return problem("Only a workspace owner can add a GitHub account. Ask an owner of your workspace to add it from Import from GitHub.", null);
72 }
73 const visible = await githubApp.visibleInstallations(user);
74 if (!visible.ok) return problem(visible.error.message, null, relink(visible.error.code));
75 const found = visible.value.find((item) => item.id === installation);
76 if (!found) {
77 return problem(
78 "Your GitHub account cannot see that installation. Install the app from your own GitHub account or an organization you manage.",
79 null,
80 );
81 }
82 // One workspace of theirs: there is nothing to choose.
83 if (owned.length === 1) {
84 const only = owned[0].slug;
85 if (!found.recordedIn.includes(only)) {
86 const added = await githubApp.addInstallation(user, only, installation);
87 if (!added.ok) return problem(added.error.message, only);
88 }
89 throw redirect(`/new/github?workspace=${encodeURIComponent(only)}&installation=${installation}`, { headers: clear });
90 }
91 return data<Problem | Choice>(
92 {
93 kind: "choose",
94 installation: { id: found.id, account: found.account, summary: installationSummary(found) },
95 workspaces: setupChoices(owned, found),
96 },
97 { headers: clear },
98 );
99}
100
101export async function action({ request, context }: Route.ActionArgs) {
102 assertSameOrigin(request);
103 const user = requireUser(context, request);
104 const form = await request.formData();
105 const workspace = String(form.get("workspace") ?? "").toLowerCase();
106 const installation = Number(form.get("installation"));
107 if (roleIn(user, workspace) !== "owner") return { error: "Only an owner of the workspace can add GitHub accounts to it." };
108 if (!Number.isSafeInteger(installation) || installation <= 0) return { error: "Choose an installation to add." };
109 const added = await githubApp.addInstallation(user, workspace, installation);
110 if (!added.ok) return { error: added.error.message };
111 throw redirect(`/new/github?workspace=${encodeURIComponent(workspace)}&installation=${installation}`);
112}
113
114export default function GithubSetup({ loaderData, actionData }: Route.ComponentProps) {
115 if (loaderData.kind === "choose") {
116 const { installation, workspaces } = loaderData;
117 return (
118 <AuthCard
119 title="Add a GitHub account"
120 subtitle={`Add the installation on ${installation.account} to which workspace?`}
121 footer={
122 <Link to="/new/github" className="text-fg underline underline-offset-4">
123 Not now
124 </Link>
125 }
126 >
127 <div className="flex items-center gap-3 rounded-md border border-line px-4 py-3">
128 <GithubMark className="size-5 shrink-0" />
129 <div className="min-w-0">
130 <p className="truncate font-mono text-sm">{installation.account}</p>
131 <p className="text-xs text-faint">{installation.summary}</p>
132 </div>
133 </div>
134 <ul className="mt-4 divide-y divide-line rounded-md border border-line">
135 {workspaces.map((option) => (
136 <li key={option.slug} className="flex items-center gap-3 px-4 py-2.5">
137 <div className="min-w-0">
138 <p className="truncate text-sm">{option.name}</p>
139 {option.name !== option.slug && <p className="truncate font-mono text-xs text-faint">{option.slug}</p>}
140 </div>
141 <span className="ml-auto shrink-0">
142 {option.added ? (
143 <Link to={`/new/github?workspace=${option.slug}&installation=${installation.id}`} className="text-sm text-muted hover:text-fg">
144 Added · Open
145 </Link>
146 ) : (
147 <Form method="post">
148 <input type="hidden" name="installation" value={installation.id} />
149 <SubmitButton name="workspace" value={option.slug} pending="Adding…">
150 Add
151 </SubmitButton>
152 </Form>
153 )}
154 </span>
155 </li>
156 ))}
157 </ul>
158 <ErrorText>{actionData?.error}</ErrorText>
159 </AuthCard>
160 );
161 }
162 return (
163 <AuthCard
164 title="Connecting GitHub"
165 subtitle="That did not work"
166 footer={
167 <Link
168 to={loaderData.workspace ? `/new/github?workspace=${loaderData.workspace}` : "/new/github"}
169 className="text-fg underline underline-offset-4"
170 >
171 Back to Import from GitHub
172 </Link>
173 }
174 >
175 <p className="text-sm text-danger" role="alert">
176 {loaderData.error}
177 </p>
178 {loaderData.link && (
179 <a
180 href={loaderData.link}
181 className="mt-4 inline-flex w-full items-center justify-center gap-2 rounded-md bg-fg px-3.5 py-2 text-sm font-medium text-bg hover:bg-fg-hover"
182 >
183 <GithubMark /> Link your GitHub account
184 </a>
185 )}
186 </AuthCard>
187 );
188}