405 lines17,472 bytesCodeBlame
1import { Mail, UserPlus } from "lucide-react";
2import { useEffect, useState } from "react";
3import { Form, Link, useFetcher, useNavigation } from "react-router";
4
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";
19import { Avatar, Button, ErrorText, Field, Input } from "../../components/ui";
20import { 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 const navigation = useNavigation();
218 const adding = navigation.state !== "idle" && navigation.formData?.get("intent") === "add";
219 // Cleared once someone was added, ready for the next.
220 useEffect(() => {
221 if (result?.ok) setKey((k) => k + 1);
222 }, [result]);
223 return (
224 <Form method="post" className="space-y-3 rounded-xl border border-line bg-surface p-4">
225 <input type="hidden" name="intent" value="add" />
226 <div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_11rem_auto] sm:items-end">
227 <Field label="Username or email address">
228 <Input key={key} name="invitee" required maxLength={254} placeholder="username or name@example.com" />
229 </Field>
230 <div>
231 <span className="mb-1.5 block text-sm font-medium text-muted">Role</span>
232 <RoleSelect name="role" label="Role" value={role} onValueChange={(value) => setRole(value as RepoRole)} />
233 </div>
234 <Button type="submit" disabled={adding}>
235 <UserPlus size={15} />
236 {adding ? "Adding…" : "Add"}
237 </Button>
238 </div>
239 <p className="text-xs text-faint">{REPO_ROLE_LABELS[role]}: {roleLine(role)}</p>
240 {result &&
241 (result.ok ? (
242 <p className="flex items-start gap-2 text-sm text-fg" role="status">
243 <Mail size={14} className="mt-0.5 shrink-0 text-accent" />
244 {result.message}
245 </p>
246 ) : (
247 <ErrorText>{result.error}</ErrorText>
248 ))}
249 </Form>
250 );
251}
252
253function roleLine(role: RepoRole): string {
254 return {
255 read: "they can see and clone it, open issues and pull requests, and comment.",
256 triage: "they can also label, assign, close and reopen issues and pull requests.",
257 write: "they can also push, merge and put agents to work.",
258 maintain: "they can also change its settings, branch protection and guardrails.",
259 admin: "they can do everything, including webhooks, secrets, deployments and who has access.",
260 }[role];
261}
262
263/** One person: who they are, how they have access, and their role. */
264function PersonRow({
265 person,
266 manage,
267 base,
268 full,
269}: {
270 person: Collaborator;
271 manage: boolean;
272 base: Parameters<typeof baseRole>[0];
273 full: string;
274}) {
275 const fetcher = useFetcher<Outcome>();
276 const outside = person.workspace_role == null;
277 // A member keeps the base permission whatever role they are given here,
278 // so only higher roles mean anything for them.
279 const floor = outside ? null : baseRole(base);
280 const roles = floor ? REPO_ROLES.filter((role) => REPO_ROLES.indexOf(role) >= REPO_ROLES.indexOf(floor)) : REPO_ROLES;
281 const shown = fetcher.formData?.get("intent") === "role" ? String(fetcher.formData.get("role")) : person.role;
282 const editable = manage && person.source !== "owner";
283 return (
284 <li className="flex flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3">
285 <Avatar name={person.username} image={person.avatar} size={32} />
286 <div className="min-w-0 grow basis-40">
287 <p className="flex flex-wrap items-center gap-x-2 gap-y-1">
288 <Link to={`/u/${person.username}`} className="font-mono text-sm hover:text-accent">
289 {person.username}
290 </Link>
291 {person.name && <span className="truncate text-sm text-muted">{person.name}</span>}
292 {person.source === "owner" && <Badge tone="accent">Owner</Badge>}
293 {outside && <Badge tone="info">Outside collaborator</Badge>}
294 </p>
295 <p className="mt-0.5 text-xs text-faint">
296 {SOURCE[person.source]}
297 {!outside && person.direct != null && person.source !== "direct" ? ` · given ${REPO_ROLE_LABELS[person.direct]} here` : ""}
298 </p>
299 {fetcher.data && !fetcher.data.ok && <ErrorText>{fetcher.data.error}</ErrorText>}
300 </div>
301 <div className="flex shrink-0 items-center gap-2">
302 {editable ? (
303 <RoleSelect
304 size="sm"
305 label={`Role of ${person.username}`}
306 roles={roles}
307 value={shown}
308 className="w-32"
309 disabled={fetcher.state !== "idle"}
310 onValueChange={(role) =>
311 fetcher.submit({ intent: "role", username: person.username, role }, { method: "post" })
312 }
313 />
314 ) : (
315 <span className="inline-flex h-8 w-32 items-center rounded-md border border-line px-2.5 text-[0.8125rem] text-muted">
316 {REPO_ROLE_LABELS[person.role]}
317 </span>
318 )}
319 {/* The same room for Remove on every row, so the roles line up. */}
320 {manage && (
321 <span className="flex w-[5.5rem] justify-end">
322 {editable && person.direct != null && <RemoveButton person={person} full={full} outside={outside} />}
323 </span>
324 )}
325 </div>
326 </li>
327 );
328}
329
330/** Taking someone's role here away, after saying what that means. */
331function RemoveButton({ person, full, outside }: { person: Collaborator; full: string; outside: boolean }) {
332 const fetcher = useFetcher<Outcome>();
333 const [open, setOpen] = useState(false);
334 useEffect(() => {
335 if (fetcher.state === "idle" && fetcher.data?.ok) setOpen(false);
336 }, [fetcher.state, fetcher.data]);
337 return (
338 <AlertDialog open={open} onOpenChange={setOpen}>
339 <Button type="button" variant="quiet" onClick={() => setOpen(true)}>
340 Remove
341 </Button>
342 <AlertDialogContent>
343 <fetcher.Form method="post" className="grid gap-4">
344 <input type="hidden" name="intent" value="remove" />
345 <input type="hidden" name="username" value={person.username} />
346 <AlertDialogHeader>
347 <AlertDialogTitle>
348 Remove {person.username} from {full}?
349 </AlertDialogTitle>
350 <AlertDialogDescription>
351 {outside
352 ? "They lose access to the repository at once, and stop seeing it in Shared with you. Their issues, pull requests and comments stay."
353 : "They lose the role given to them here, and keep what the workspace's base permission gives every member."}
354 </AlertDialogDescription>
355 </AlertDialogHeader>
356 {fetcher.data && !fetcher.data.ok && <ErrorText>{fetcher.data.error}</ErrorText>}
357 <AlertDialogFooter>
358 <AlertDialogCancel type="button">Cancel</AlertDialogCancel>
359 <Button type="submit" variant="danger" disabled={fetcher.state !== "idle"}>
360 {fetcher.state !== "idle" ? "Removing…" : "Remove"}
361 </Button>
362 </AlertDialogFooter>
363 </fetcher.Form>
364 </AlertDialogContent>
365 </AlertDialog>
366 );
367}
368
369function day(at: string): string {
370 return new Date(at).toISOString().slice(0, 10);
371}
372
373/** A pending invitation: to whom, with which role, until when. */
374function InvitationRow({ invitation }: { invitation: RepoInvitation }) {
375 const fetcher = useFetcher<Outcome>();
376 const who = invitation.invitee ?? invitation.email ?? "Someone";
377 return (
378 <li className="flex flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3">
379 {invitation.invitee ? (
380 <Avatar name={invitation.invitee} size={32} />
381 ) : (
382 <span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-raised text-muted ring-1 ring-line">
383 <Mail size={14} />
384 </span>
385 )}
386 <div className="min-w-0 grow basis-40">
387 <p className="flex flex-wrap items-center gap-x-2 gap-y-1">
388 <span className={`min-w-0 truncate text-sm ${invitation.invitee ? "font-mono" : ""}`}>{who}</span>
389 <Badge>{REPO_ROLE_LABELS[invitation.role]}</Badge>
390 </p>
391 <p className="mt-0.5 text-xs text-faint">
392 Invited by {invitation.invited_by ?? "g1t"} on {day(invitation.created_at)} · expires {day(invitation.expires_at)}
393 </p>
394 {fetcher.data && !fetcher.data.ok && <ErrorText>{fetcher.data.error}</ErrorText>}
395 </div>
396 <fetcher.Form method="post" className="shrink-0">
397 <input type="hidden" name="intent" value="revoke" />
398 <input type="hidden" name="id" value={invitation.id} />
399 <Button type="submit" variant="quiet" disabled={fetcher.state !== "idle"}>
400 {fetcher.state !== "idle" ? "Revoking…" : "Revoke"}
401 </Button>
402 </fetcher.Form>
403 </li>
404 );
405}