g1t/packages/contracts/src/access.ts

243 lines10,600 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 look1/**
2 * Who may do what in a repository: repository roles, the capabilities each
3 * one carries, and how a person's permission is worked out.
4 *
5 * Mirrors `crates/contracts/src/access.rs`, which holds the one permission
6 * table; a test there reads `CAPABILITIES` and `OWNER_ONLY` below and fails
7 * when the two differ. Keep each row on one line.
8 */
9import type { Membership, Role, User } from "./identity";
10import type { Result } from "./result";
11
12/** What someone may do in one repository, from least to most. */
13export type RepoRole = "read" | "triage" | "write" | "maintain" | "admin";
14
15export const REPO_ROLES: readonly RepoRole[] = ["read", "triage", "write", "maintain", "admin"];
16
17export const REPO_ROLE_LABELS: Record<RepoRole, string> = {
18 read: "Read",
19 triage: "Triage",
20 write: "Write",
21 maintain: "Maintain",
22 admin: "Admin",
23};
24
25/** One line on what each role is for, as role pickers show it. */
26export const REPO_ROLE_SUMMARIES: Record<RepoRole, string> = {
27 read: "Read and clone; open issues and pull requests, and comment.",
28 triage: "Read, and manage issues and pull requests: label, assign, close.",
29 write: "Triage, and push, merge, and put agents to work.",
30 maintain: "Write, and manage settings and branch protection.",
31 admin: "Everything: webhooks, secrets, deployments, access, name and visibility.",
32};
33
34/** What every member of a workspace gets on each of its repositories. */
35export type BasePermission = "none" | "read" | "write" | "admin";
36
37export const BASE_PERMISSIONS: readonly BasePermission[] = ["none", "read", "write", "admin"];
38
39/** Unless an owner changes it: what members could do before roles. */
40export const DEFAULT_BASE_PERMISSION: BasePermission = "write";
41
42export const BASE_PERMISSION_LABELS: Record<BasePermission, string> = {
43 none: "No permission",
44 read: "Read",
45 write: "Write",
46 admin: "Admin",
47};
48
49export type Capability =
50 | "read"
51 | "participate"
52 | "triage"
53 | "push"
54 | "merge"
55 | "run"
56 | "manage_settings"
57 | "manage_protection"
58 | "manage_integrations"
59 | "manage_access"
60 | "administer"
61 | "delete";
62
63/** The permission table: the least role for each capability. */
64export const CAPABILITIES = [
65 { capability: "read", role: "read", about: "See code, issues and pull requests; clone and fetch" },
66 { capability: "participate", role: "read", about: "Open issues and pull requests, and comment" },
67 { capability: "triage", role: "triage", about: "Label, assign, close and reopen issues and pull requests" },
68 { capability: "push", role: "write", about: "Push to branches that are not protected" },
69 { capability: "merge", role: "write", about: "Merge pull requests and use the merge queue" },
70 { capability: "run", role: "write", about: "Assign agents and start runs, plans and workflows" },
71 { capability: "manage_settings", role: "maintain", about: "Change the description, topics, and pull request and agent settings" },
72 { capability: "manage_protection", role: "maintain", about: "Change branch protection and guardrails" },
73 { capability: "manage_integrations", role: "admin", about: "Manage webhooks, secrets, variables, deployments and domains" },
74 { capability: "manage_access", role: "admin", about: "Manage who has access, and invitations" },
75 { capability: "administer", role: "admin", about: "Rename, archive, change visibility and the default branch" },
76 { capability: "delete", role: "admin", about: "Transfer or delete the repository (owners of the workspace only)" },
77] as const satisfies readonly { capability: Capability; role: RepoRole; about: string }[];
78
79/** Capabilities that also need an owner of the repository's workspace. */
80export const OWNER_ONLY = ["delete"] as const satisfies readonly Capability[];
81
82/** A person's role on one repository, given directly. */
83export type RepoGrant = { repo_id: string; workspace: string; role: RepoRole };
84
85/** What `permission` needs to know about a repository. */
86export type RepoRef = { id: string; namespace: string; isPrivate: boolean };
87
88const rank = (role: RepoRole): number => REPO_ROLES.indexOf(role);
89
90/** The higher of two roles; null is lower than any. */
91export function maxRole(a: RepoRole | null | undefined, b: RepoRole | null | undefined): RepoRole | null {
92 if (!a) return b ?? null;
93 if (!b) return a;
94 return rank(a) >= rank(b) ? a : b;
95}
96
97export function leastRole(capability: Capability): RepoRole {
98 return CAPABILITIES.find((row) => row.capability === capability)?.role ?? "admin";
99}
100
101/** Whether `role` has `capability`, going by the table alone. */
102export function allows(role: RepoRole | null | undefined, capability: Capability): boolean {
103 return role != null && rank(role) >= rank(leastRole(capability));
104}
105
106export function baseRole(base: BasePermission | null | undefined): RepoRole | null {
107 const value = base ?? DEFAULT_BASE_PERMISSION;
108 return value === "none" ? null : value;
109}
110
111function membershipRole(user: User, membership: Membership): RepoRole | null {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily112 // A workspace's own token, and g1t acting in the workspace, do what an
113 // owner can on its repositories.
114 if (user.kind === "workspace" || user.kind === "system") return "admin";
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look115 return membership.role === "owner" ? "admin" : baseRole(membership.base_permission);
116}
117
118/** The user's role on the repository, not counting that it may be public. */
119export function granted(user: User, repo: RepoRef): RepoRole | null {
120 const namespace = repo.namespace.toLowerCase();
121 const membership = user.workspaces?.find((m) => m.slug.toLowerCase() === namespace);
122 let role = membership ? membershipRole(user, membership) : null;
123 for (const grant of user.grants ?? []) {
124 if (grant.repo_id === repo.id) role = maxRole(role, grant.role);
125 }
126 return role;
127}
128
129/** The viewer's effective role on a repository; null means they may not see it. */
130export function permission(viewer: User | null | undefined, repo: RepoRef): RepoRole | null {
131 const role = viewer ? granted(viewer, repo) : null;
132 return repo.isPrivate ? role : maxRole(role, "read");
133}
134
135/** Whether the viewer may do `capability` in the repository. */
136export function can(viewer: User | null | undefined, repo: RepoRef, capability: Capability): boolean {
137 if (!allows(permission(viewer, repo), capability)) return false;
138 if ((OWNER_ONLY as readonly Capability[]).includes(capability)) {
139 const namespace = repo.namespace.toLowerCase();
140 return viewer?.workspaces?.find((m) => m.slug.toLowerCase() === namespace)?.role === "owner";
141 }
142 return true;
143}
144
145/** Every capability, true or false, for one viewer and repository: what pages pass to their components. */
146export type Abilities = Record<Capability, boolean>;
147
148export function abilities(viewer: User | null | undefined, repo: RepoRef): Abilities {
149 return Object.fromEntries(CAPABILITIES.map((row) => [row.capability, can(viewer, repo, row.capability)])) as Abilities;
150}
151
152/** The sentence shown beside something the viewer cannot use. */
153export function needs(capability: Capability): string {
154 if ((OWNER_ONLY as readonly Capability[]).includes(capability)) return "Only an owner of the workspace can do this.";
155 return `Needs the ${REPO_ROLE_LABELS[leastRole(capability)]} role or higher.`;
156}
157
158/** Whether the user belongs to the workspace or has a role on one of its repositories. */
159export function hasAccessIn(user: User | null | undefined, namespace: string): boolean {
160 const slug = namespace.toLowerCase();
161 return !!user && (!!user.workspaces?.some((m) => m.slug.toLowerCase() === slug) || !!user.grants?.some((g) => g.workspace.toLowerCase() === slug));
162}
163
164/** The workspaces where the user has repositories shared with them without being a member. */
165export function sharedWorkspaces(user: User | null | undefined): string[] {
166 if (!user) return [];
167 const member = new Set((user.workspaces ?? []).map((m) => m.slug));
168 return [...new Set((user.grants ?? []).map((g) => g.workspace).filter((slug) => !member.has(slug)))];
169}
170
171// --- Who has access ----------------------------------------------------------
172
173export type AccessSource = "owner" | "base" | "direct";
174
175export type Collaborator = {
176 username: string;
177 name: string | null;
178 avatar: string | null;
179 role: RepoRole;
180 source: AccessSource;
181 direct: RepoRole | null;
182 /** Null for an outside collaborator. */
183 workspace_role: Role | null;
184};
185
186export type RepoInvitationStatus = "pending" | "accepted" | "declined" | "revoked" | "expired";
187
188export type RepoInvitation = {
189 id: string;
190 /** `workspace/name`. */
191 repo: string;
192 repo_id: string;
193 invitee: string | null;
194 email: string | null;
195 role: RepoRole;
196 invited_by: string | null;
197 /** The inviter's avatar hash, served at `/avatars/<avatar>`; null for the generated letter avatar. */
198 inviter_avatar?: string | null;
199 status: RepoInvitationStatus;
200 created_at: string;
201 expires_at: string;
202};
203
204export type RepoAccess = {
205 repo: string;
206 base_permission: BasePermission;
207 people: Collaborator[];
208 invitations: RepoInvitation[];
209 viewer_role: RepoRole | null;
210 can_manage: boolean;
211};
212
213export type Added =
214 | { result: "granted"; collaborator: Collaborator }
215 | { result: "invited"; invitation: RepoInvitation };
216
217export type PermissionInfo = {
218 username: string;
219 role: RepoRole | null;
220 source: AccessSource | null;
221 capabilities: Capability[];
222};
223
224export type OutsideCollaborator = {
225 username: string;
226 name: string | null;
227 avatar: string | null;
228 repos: { repo: string; role: RepoRole }[];
229};
230
231/** Identity's access methods, by repository path. */
232export interface AccessClient {
233 repoAccess(owner: string, name: string, viewer: User | null): Promise<Result<RepoAccess>>;
234 addCollaborator(actor: User, owner: string, name: string, invitee: string, role: RepoRole): Promise<Result<Added>>;
235 setCollaboratorRole(actor: User, owner: string, name: string, username: string, role: RepoRole): Promise<Result<Collaborator>>;
236 removeCollaborator(actor: User, owner: string, name: string, username: string): Promise<Result<boolean>>;
237 collaboratorPermission(viewer: User | null, owner: string, name: string, username: string): Promise<Result<PermissionInfo>>;
238 myRepoInvitations(user: User): Promise<RepoInvitation[]>;
239 respondRepoInvitation(user: User, id: string, accept: boolean): Promise<Result<RepoInvitation>>;
240 revokeRepoInvitation(actor: User, owner: string, name: string, id: string): Promise<Result<RepoInvitation>>;
241 setBasePermission(actor: User, slug: string, base: BasePermission): Promise<Result<BasePermission>>;
242 outsideCollaborators(viewer: User | null, slug: string): Promise<Result<OutsideCollaborator[]>>;
243}