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.

182 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("Your GitHub account cannot see that installation. Install the app from your own GitHub account or an organization you manage.", null);
78 }
79 // One workspace of theirs: there is nothing to choose.
80 if (owned.length === 1) {
81 const only = owned[0].slug;
82 if (!found.recordedIn.includes(only)) {
83 const added = await githubApp.addInstallation(user, only, installation);
84 if (!added.ok) return problem(added.error.message, only);
85 }
86 throw redirect(`/new/github?workspace=${encodeURIComponent(only)}&installation=${installation}`, { headers: clear });
87 }
88 return data<Problem | Choice>(
89 {
90 kind: "choose",
91 installation: { id: found.id, account: found.account, summary: installationSummary(found) },
92 workspaces: setupChoices(owned, found),
93 },
94 { headers: clear },
95 );
96}
97
98export async function action({ request, context }: Route.ActionArgs) {
99 assertSameOrigin(request);
100 const user = requireUser(context, request);
101 const form = await request.formData();
102 const workspace = String(form.get("workspace") ?? "").toLowerCase();
103 const installation = Number(form.get("installation"));
104 if (roleIn(user, workspace) !== "owner") return { error: "Only an owner of the workspace can add GitHub accounts to it." };
105 if (!Number.isSafeInteger(installation) || installation <= 0) return { error: "Choose an installation to add." };
106 const added = await githubApp.addInstallation(user, workspace, installation);
107 if (!added.ok) return { error: added.error.message };
108 throw redirect(`/new/github?workspace=${encodeURIComponent(workspace)}&installation=${installation}`);
109}
110
111export default function GithubSetup({ loaderData, actionData }: Route.ComponentProps) {
112 if (loaderData.kind === "choose") {
113 const { installation, workspaces } = loaderData;
114 return (
115 <AuthCard
116 title="Add a GitHub account"
117 subtitle={`Add the installation on ${installation.account} to which workspace?`}
118 footer={
119 <Link to="/new/github" className="text-fg underline underline-offset-4">
120 Not now
121 </Link>
122 }
123 >
124 <div className="flex items-center gap-3 rounded-md border border-line px-4 py-3">
125 <GithubMark className="size-5 shrink-0" />
126 <div className="min-w-0">
127 <p className="truncate font-mono text-sm">{installation.account}</p>
128 <p className="text-xs text-faint">{installation.summary}</p>
129 </div>
130 </div>
131 <ul className="mt-4 divide-y divide-line rounded-md border border-line">
132 {workspaces.map((option) => (
133 <li key={option.slug} className="flex items-center gap-3 px-4 py-2.5">
134 <div className="min-w-0">
135 <p className="truncate text-sm">{option.name}</p>
136 {option.name !== option.slug && <p className="truncate font-mono text-xs text-faint">{option.slug}</p>}
137 </div>
138 <span className="ml-auto shrink-0">
139 {option.added ? (
140 <Link to={`/new/github?workspace=${option.slug}&installation=${installation.id}`} className="text-sm text-muted hover:text-fg">
141 Added · Open
142 </Link>
143 ) : (
144 <Form method="post">
145 <input type="hidden" name="installation" value={installation.id} />
146 <SubmitButton name="workspace" value={option.slug} pending="Adding…">
147 Add
148 </SubmitButton>
149 </Form>
150 )}
151 </span>
152 </li>
153 ))}
154 </ul>
155 <ErrorText>{actionData?.error}</ErrorText>
156 </AuthCard>
157 );
158 }
159 return (
160 <AuthCard
161 title="Connecting GitHub"
162 subtitle="That did not work"
163 footer={
164 <Link to={loaderData.workspace ? `/new/github?workspace=${loaderData.workspace}` : "/new/github"} className="text-fg underline underline-offset-4">
165 Back to Import from GitHub
166 </Link>
167 }
168 >
169 <p className="text-sm text-danger" role="alert">
170 {loaderData.error}
171 </p>
172 {loaderData.link && (
173 <a
174 href={loaderData.link}
175 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"
176 >
177 <GithubMark /> Link your GitHub account
178 </a>
179 )}
180 </AuthCard>
181 );
182}