g1t/apps/web/app/routes/repo/settings-access.tsx

403 lines17,248 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.

Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1import { Mail, UserPlus } from "lucide-react";
2import { useEffect, useState } from "react";
Merge branch 'worktree-agent-a985c01f43538af01'3import { Form, Link, useFetcher } from "react-router";
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look4
5import {
6 BASE_PERMISSION_LABELS,
7 REPO_ROLES,
8 REPO_ROLE_LABELS,
9 type Collaborator,
10 type RepoInvitation,
11 type RepoRole,
12 baseRole,
13} from "@g1t/contracts";
14
15import type { Route } from "./+types/settings-access";
16import { RoleSelect, RolesTable } from "../../components/access";
17import { RepoSettingsHeading } from "../../components/repo-settings-heading";
18import { SettingsSection as Section } from "../../components/settings-section";
Merge branch 'worktree-agent-a985c01f43538af01'19import { Avatar, Button, ErrorText, Field, Input, SubmitButton } from "../../components/ui";
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look20import { Badge } from "../../components/ui/badge";
21import {
22 AlertDialog,
23 AlertDialogCancel,
24 AlertDialogContent,
25 AlertDialogDescription,
26 AlertDialogFooter,
27 AlertDialogHeader,
28 AlertDialogTitle,
29} from "../../components/ui/alert-dialog";
30import { page } from "../../lib/meta";
31import { refusal, requireInsider } from "../../lib/access.server";
32import { identity } from "../../lib/services.server";
33import { assertSameOrigin, requireUser, roleIn, unwrap } from "../../lib/session.server";
34
35export function meta({ params, ...args }: Route.MetaArgs) {
36 return page(args, { title: `Access · ${params.owner}/${params.repo} · g1t` });
37}
38
39export async function loader({ params, context }: Route.LoaderArgs) {
40 // Write and up see who has access; Admins change it. To anyone without a
41 // role here the page does not exist.
42 const { viewer, access } = await requireInsider(context, params, "push");
43 const found = unwrap(await identity.repoAccess(params.owner, params.repo, viewer));
44 return {
45 access: found,
46 manage: access.can.manage_access,
47 // Owners change the base permission, on the workspace's People page.
48 owner: roleIn(viewer, params.owner) === "owner",
49 };
50}
51
52/** What a form on this page came back with. */
53type Outcome = { intent: string; ok: boolean; message: string | null; error: string | null };
54
55const isRole = (value: string): value is RepoRole => (REPO_ROLES as readonly string[]).includes(value);
56
57export async function action({ request, params, context }: Route.ActionArgs): Promise<Outcome> {
58 assertSameOrigin(request);
59 const user = requireUser(context, request);
60 const form = await request.formData();
61 const intent = String(form.get("intent") ?? "");
62 const text = (name: string) => String(form.get(name) ?? "").trim();
63 const failed = (error: string): Outcome => ({ intent, ok: false, message: null, error });
64 const refused = await refusal(context, params, "manage_access");
65 if (refused) return failed(refused);
66 const role = text("role");
67
68 switch (intent) {
69 case "add": {
70 const invitee = text("invitee");
71 if (!invitee) return failed("Enter a username or an email address.");
72 if (!isRole(role)) return failed("Choose a role.");
73 const added = await identity.addCollaborator(user, params.owner, params.repo, invitee, role);
74 if (!added.ok) return failed(added.error.message);
75 const label = REPO_ROLE_LABELS[role];
76 if (added.value.result === "granted") {
77 return { intent, ok: true, error: null, message: `${added.value.collaborator.username} now has the ${label} role.` };
78 }
79 const invitation = added.value.invitation;
80 return {
81 intent,
82 ok: true,
83 error: null,
84 message: invitation.invitee
85 ? `We sent ${invitation.invitee} an invitation. They get the ${label} role when they accept it.`
86 : `We sent an invite to ${invitation.email ?? invitee}. They get the ${label} role once they make an account and join.`,
87 };
88 }
89 case "role": {
90 if (!isRole(role)) return failed("Choose a role.");
91 const changed = await identity.setCollaboratorRole(user, params.owner, params.repo, text("username"), role);
92 return changed.ok
93 ? { intent, ok: true, error: null, message: `${changed.value.username} has the ${REPO_ROLE_LABELS[changed.value.role]} role.` }
94 : failed(changed.error.message);
95 }
96 case "remove": {
97 const removed = await identity.removeCollaborator(user, params.owner, params.repo, text("username"));
98 return removed.ok ? { intent, ok: true, error: null, message: null } : failed(removed.error.message);
99 }
100 case "revoke": {
101 const revoked = await identity.revokeRepoInvitation(user, params.owner, params.repo, text("id"));
102 return revoked.ok ? { intent, ok: true, error: null, message: null } : failed(revoked.error.message);
103 }
104 default:
105 return failed("Unknown request.");
106 }
107}
108
109const SOURCE: Record<Collaborator["source"], string> = {
110 owner: "Owner of the workspace",
111 base: "Member, by the base permission",
112 direct: "Given a role here",
113};
114
115export default function RepoAccessSettings({ loaderData, actionData, params }: Route.ComponentProps) {
116 const { access, manage, owner } = loaderData;
117 const base = `/${params.owner}/${params.repo}`;
118 const full = `${params.owner}/${params.repo}`;
119 const pending = access.invitations.filter((invitation) => invitation.status === "pending");
120 const people = [...access.people].sort(
121 (a, b) => REPO_ROLES.indexOf(b.role) - REPO_ROLES.indexOf(a.role) || a.username.localeCompare(b.username),
122 );
123 const result = actionData?.intent === "add" ? actionData : undefined;
124 return (
125 <>
126 <RepoSettingsHeading base={base} />
127 <div className="max-w-4xl space-y-8">
128 <Section
129 title="Base permission"
130 about={`What every member of ${params.owner} gets on its repositories.`}
131 >
132 <div className="rounded-xl border border-line bg-surface p-4 text-sm">
133 <p>
134 Members have{" "}
135 <span className="font-medium text-fg">
136 {access.base_permission === "none" ? "no permission" : `the ${BASE_PERMISSION_LABELS[access.base_permission]} role`}
137 </span>{" "}
138 on {full}
139 {access.base_permission === "none" ? " unless they are given a role here." : ", or the higher role they are given here."}{" "}
140 Owners of the workspace are Admins on every repository.
141 </p>
142 <p className="mt-2 text-muted">
143 {owner ? (
144 <Link to={`/${params.owner}/-/people#base-permission`} className="text-accent hover:underline">
145 Change the base permission
146 </Link>
147 ) : (
148 "Owners of the workspace choose it."
149 )}
150 </p>
151 </div>
152 </Section>
153
154 {manage && (
155 <Section
156 title="Add people"
157 about="A member of the workspace gets the role at once. Anyone else gets an invitation, by email, and has the role once they accept it."
158 >
159 <AddForm result={result} />
160 </Section>
161 )}
162
163 <Section
164 title="People with access"
165 about={
166 manage
167 ? "Who can see the repository, and what each can do. Outside collaborators are not members of the workspace; they see only the repositories shared with them."
168 : "Who can see the repository, and what each can do. Changing who has access needs the Admin role."
169 }
170 >
171 <ul className="divide-y divide-line rounded-xl border border-line">
172 {people.map((person) => (
173 <PersonRow key={person.username} person={person} manage={manage} base={access.base_permission} full={full} />
174 ))}
175 </ul>
176 {actionData && ["role", "remove"].includes(actionData.intent) && (
177 actionData.ok ? (
178 actionData.message && <p className="text-sm text-muted" role="status">{actionData.message}</p>
179 ) : (
180 <ErrorText>{actionData.error}</ErrorText>
181 )
182 )}
183 </Section>
184
185 {manage && (
186 <Section title="Pending invitations" about="Invitations not yet accepted. Each expires after 7 days.">
187 {pending.length === 0 ? (
188 <p className="rounded-xl border border-dashed border-line px-4 py-6 text-center text-sm text-muted">
189 No invitations are waiting.
190 </p>
191 ) : (
192 <ul className="divide-y divide-line rounded-xl border border-line">
193 {pending.map((invitation) => (
194 <InvitationRow key={invitation.id} invitation={invitation} />
195 ))}
196 </ul>
197 )}
198 {actionData?.intent === "revoke" && !actionData.ok && <ErrorText>{actionData.error}</ErrorText>}
199 </Section>
200 )}
201
202 <Section
203 title="Roles"
204 about="What each role can do. Each role can do everything the one before it can. Transferring and deleting also need an owner of the workspace."
205 >
206 <RolesTable />
207 </Section>
208 </div>
209 </>
210 );
211}
212
213/** A username or an address, and the role to give. */
214function AddForm({ result }: { result: Outcome | undefined }) {
215 const [role, setRole] = useState<RepoRole>("write");
216 const [key, setKey] = useState(0);
217 // Cleared once someone was added, ready for the next.
218 useEffect(() => {
219 if (result?.ok) setKey((k) => k + 1);
220 }, [result]);
221 return (
222 <Form method="post" className="space-y-3 rounded-xl border border-line bg-surface p-4">
223 <input type="hidden" name="intent" value="add" />
224 <div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_11rem_auto] sm:items-end">
225 <Field label="Username or email address">
226 <Input key={key} name="invitee" required maxLength={254} placeholder="username or name@example.com" />
227 </Field>
228 <div>
229 <span className="mb-1.5 block text-sm font-medium text-muted">Role</span>
230 <RoleSelect name="role" label="Role" value={role} onValueChange={(value) => setRole(value as RepoRole)} />
231 </div>
Merge branch 'worktree-agent-a985c01f43538af01'232 <SubmitButton match={{ intent: "add" }} pending="Adding…">
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look233 <UserPlus size={15} />
Merge branch 'worktree-agent-a985c01f43538af01'234 Add
235 </SubmitButton>
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look236 </div>
237 <p className="text-xs text-faint">{REPO_ROLE_LABELS[role]}: {roleLine(role)}</p>
238 {result &&
239 (result.ok ? (
240 <p className="flex items-start gap-2 text-sm text-fg" role="status">
241 <Mail size={14} className="mt-0.5 shrink-0 text-accent" />
242 {result.message}
243 </p>
244 ) : (
245 <ErrorText>{result.error}</ErrorText>
246 ))}
247 </Form>
248 );
249}
250
251function roleLine(role: RepoRole): string {
252 return {
253 read: "they can see and clone it, open issues and pull requests, and comment.",
254 triage: "they can also label, assign, close and reopen issues and pull requests.",
255 write: "they can also push, merge and put agents to work.",
256 maintain: "they can also change its settings, branch protection and guardrails.",
257 admin: "they can do everything, including webhooks, secrets, deployments and who has access.",
258 }[role];
259}
260
261/** One person: who they are, how they have access, and their role. */
262function PersonRow({
263 person,
264 manage,
265 base,
266 full,
267}: {
268 person: Collaborator;
269 manage: boolean;
270 base: Parameters<typeof baseRole>[0];
271 full: string;
272}) {
273 const fetcher = useFetcher<Outcome>();
274 const outside = person.workspace_role == null;
275 // A member keeps the base permission whatever role they are given here,
276 // so only higher roles mean anything for them.
277 const floor = outside ? null : baseRole(base);
278 const roles = floor ? REPO_ROLES.filter((role) => REPO_ROLES.indexOf(role) >= REPO_ROLES.indexOf(floor)) : REPO_ROLES;
279 const shown = fetcher.formData?.get("intent") === "role" ? String(fetcher.formData.get("role")) : person.role;
280 const editable = manage && person.source !== "owner";
281 return (
282 <li className="flex flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3">
283 <Avatar name={person.username} image={person.avatar} size={32} />
284 <div className="min-w-0 grow basis-40">
285 <p className="flex flex-wrap items-center gap-x-2 gap-y-1">
286 <Link to={`/u/${person.username}`} className="font-mono text-sm hover:text-accent">
287 {person.username}
288 </Link>
289 {person.name && <span className="truncate text-sm text-muted">{person.name}</span>}
290 {person.source === "owner" && <Badge tone="accent">Owner</Badge>}
291 {outside && <Badge tone="info">Outside collaborator</Badge>}
292 </p>
293 <p className="mt-0.5 text-xs text-faint">
294 {SOURCE[person.source]}
295 {!outside && person.direct != null && person.source !== "direct" ? ` · given ${REPO_ROLE_LABELS[person.direct]} here` : ""}
296 </p>
297 {fetcher.data && !fetcher.data.ok && <ErrorText>{fetcher.data.error}</ErrorText>}
298 </div>
299 <div className="flex shrink-0 items-center gap-2">
300 {editable ? (
301 <RoleSelect
302 size="sm"
303 label={`Role of ${person.username}`}
304 roles={roles}
305 value={shown}
306 className="w-32"
307 disabled={fetcher.state !== "idle"}
308 onValueChange={(role) =>
309 fetcher.submit({ intent: "role", username: person.username, role }, { method: "post" })
310 }
311 />
312 ) : (
313 <span className="inline-flex h-8 w-32 items-center rounded-md border border-line px-2.5 text-[0.8125rem] text-muted">
314 {REPO_ROLE_LABELS[person.role]}
315 </span>
316 )}
317 {/* The same room for Remove on every row, so the roles line up. */}
318 {manage && (
319 <span className="flex w-[5.5rem] justify-end">
320 {editable && person.direct != null && <RemoveButton person={person} full={full} outside={outside} />}
321 </span>
322 )}
323 </div>
324 </li>
325 );
326}
327
328/** Taking someone's role here away, after saying what that means. */
329function RemoveButton({ person, full, outside }: { person: Collaborator; full: string; outside: boolean }) {
330 const fetcher = useFetcher<Outcome>();
331 const [open, setOpen] = useState(false);
332 useEffect(() => {
333 if (fetcher.state === "idle" && fetcher.data?.ok) setOpen(false);
334 }, [fetcher.state, fetcher.data]);
335 return (
336 <AlertDialog open={open} onOpenChange={setOpen}>
337 <Button type="button" variant="quiet" onClick={() => setOpen(true)}>
338 Remove
339 </Button>
340 <AlertDialogContent>
341 <fetcher.Form method="post" className="grid gap-4">
342 <input type="hidden" name="intent" value="remove" />
343 <input type="hidden" name="username" value={person.username} />
344 <AlertDialogHeader>
345 <AlertDialogTitle>
346 Remove {person.username} from {full}?
347 </AlertDialogTitle>
348 <AlertDialogDescription>
349 {outside
350 ? "They lose access to the repository at once, and stop seeing it in Shared with you. Their issues, pull requests and comments stay."
351 : "They lose the role given to them here, and keep what the workspace's base permission gives every member."}
352 </AlertDialogDescription>
353 </AlertDialogHeader>
354 {fetcher.data && !fetcher.data.ok && <ErrorText>{fetcher.data.error}</ErrorText>}
355 <AlertDialogFooter>
356 <AlertDialogCancel type="button">Cancel</AlertDialogCancel>
Merge branch 'worktree-agent-a985c01f43538af01'357 <SubmitButton variant="danger" fetcher={fetcher} pending="Removing…">
358 Remove
359 </SubmitButton>
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look360 </AlertDialogFooter>
361 </fetcher.Form>
362 </AlertDialogContent>
363 </AlertDialog>
364 );
365}
366
367function day(at: string): string {
368 return new Date(at).toISOString().slice(0, 10);
369}
370
371/** A pending invitation: to whom, with which role, until when. */
372function InvitationRow({ invitation }: { invitation: RepoInvitation }) {
373 const fetcher = useFetcher<Outcome>();
374 const who = invitation.invitee ?? invitation.email ?? "Someone";
375 return (
376 <li className="flex flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3">
377 {invitation.invitee ? (
378 <Avatar name={invitation.invitee} size={32} />
379 ) : (
380 <span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-raised text-muted ring-1 ring-line">
381 <Mail size={14} />
382 </span>
383 )}
384 <div className="min-w-0 grow basis-40">
385 <p className="flex flex-wrap items-center gap-x-2 gap-y-1">
386 <span className={`min-w-0 truncate text-sm ${invitation.invitee ? "font-mono" : ""}`}>{who}</span>
387 <Badge>{REPO_ROLE_LABELS[invitation.role]}</Badge>
388 </p>
389 <p className="mt-0.5 text-xs text-faint">
390 Invited by {invitation.invited_by ?? "g1t"} on {day(invitation.created_at)} · expires {day(invitation.expires_at)}
391 </p>
392 {fetcher.data && !fetcher.data.ok && <ErrorText>{fetcher.data.error}</ErrorText>}
393 </div>
394 <fetcher.Form method="post" className="shrink-0">
395 <input type="hidden" name="intent" value="revoke" />
396 <input type="hidden" name="id" value={invitation.id} />
Merge branch 'worktree-agent-a985c01f43538af01'397 <SubmitButton variant="quiet" fetcher={fetcher} pending="Revoking…">
398 Revoke
399 </SubmitButton>
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look400 </fetcher.Form>
401 </li>
402 );
403}

This file's history is long; its oldest lines are credited to the oldest commit read.