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