pr_01m47d24b0e6n91zwymwxg0vpx/packages/contracts/src/identity.ts

572 lines23,682 bytesCodeBlame
1import type { AccessClient, BasePermission, RepoGrant } from "./access";
2import type { Acting, CreateRunCredentialInput, RunBinding } from "./audit";
3import type { RepoPath } from "./repos";
4import type { Result } from "./result";
5
6export type User = {
7 id: string;
8 username: string;
9 /**
10 * `workspace` when a workspace is acting through one of its own access
11 * tokens: `id` is then the workspace's and `username` its slug. Absent
12 * means `user`.
13 */
14 kind?: "user" | "workspace" | "agent";
15 /**
16 * Whether the account's email address is confirmed. Only set on users
17 * resolved from credentials; unverified accounts cannot change anything.
18 */
19 verified?: boolean;
20 /**
21 * The workspaces this user belongs to. Set on users resolved from
22 * credentials, so any service can authorize from it.
23 */
24 workspaces?: Membership[];
25 /**
26 * The person's uploaded avatar: the SHA-256 of its bytes, served at
27 * `/avatars/<avatar>`. Only set on the signed-in person; absent means
28 * the generated letter avatar.
29 */
30 avatar?: string;
31 /**
32 * Set on an agent resolved from its token: who it acts for ("g1t-agent
33 * on behalf of syntaqx"), with which credential, and what it may do.
34 */
35 acting?: Acting;
36 /**
37 * The repositories this user has a role on directly, whether or not they
38 * belong to its workspace. Set with `workspaces`; see `access.ts`.
39 */
40 grants?: RepoGrant[];
41};
42
43/** What a member may do: an owner also manages the workspace's members. */
44export type Role = "owner" | "member";
45
46export type Membership = {
47 /** The workspace's name in URLs: `g1t.sh/<slug>`. */
48 slug: string;
49 role: Role;
50 /** Its display name. Set on users resolved from credentials. */
51 name?: string;
52 /** Its uploaded icon, as `Workspace.avatar`. */
53 avatar?: string;
54 /** The workspace's base permission: what members get on every repository. Absent means `write`. */
55 base_permission?: BasePermission;
56};
57
58/** How long an old workspace slug redirects, and stays reserved for it, after a rename. */
59export const SLUG_HOLD_DAYS = 90;
60
61/** How long a workspace must wait between renames. */
62export const RENAME_COOLDOWN_HOURS = 24;
63
64/** The largest avatar that can be uploaded, in bytes. */
65export const MAX_AVATAR_BYTES = 1024 * 1024;
66
67/**
68 * A workspace: the owner of repositories, and the first segment of their
69 * URLs. A person's own space and a team's are the same thing.
70 */
71export type Workspace = {
72 id: string;
73 slug: string;
74 name: string;
75 /** One line saying what the workspace is for. */
76 description: string | null;
77 /** RFC 3339. */
78 createdAt: string;
79 memberCount: number;
80 /**
81 * The workspace's uploaded icon: the SHA-256 of its bytes, served at
82 * `/avatars/<avatar>`. Null means the generated letter avatar.
83 */
84 avatar: string | null;
85 /** What every member gets on each repository; owners have Admin. */
86 basePermission?: BasePermission;
87};
88
89export type Member = {
90 username: string;
91 role: Role;
92 /** Their display name, when they set one. */
93 name?: string | null;
94 /** Their uploaded avatar's hash, served at `/avatars/<avatar>`; null for the generated letter avatar. */
95 avatar?: string | null;
96};
97
98/** An owner of a workspace, as staff see them. */
99export type AdminOwner = { username: string; email: string | null };
100
101/** A workspace as staff see it. Mirrors `AdminWorkspace` in `crates/contracts/src/identity.rs`. */
102export type AdminWorkspace = {
103 slug: string;
104 name: string;
105 /** RFC 3339. */
106 createdAt: string;
107 owners: AdminOwner[];
108 memberCount: number;
109};
110
111/** A member of a workspace, as staff see them. */
112export type AdminMember = { username: string; email: string | null; role: Role; /** RFC 3339. */ joined: string };
113
114export type AdminWorkspaceDetail = {
115 slug: string;
116 name: string;
117 description: string | null;
118 /** RFC 3339. */
119 createdAt: string;
120 /** Owners first, then by username. */
121 members: AdminMember[];
122};
123
124/** The most workspaces one `workspaces` call returns. */
125export const ADMIN_WORKSPACES_LIMIT = 500;
126
127/**
128 * Whether anyone may make an account, or only someone with an invite.
129 * Identity's `REGISTRATION_MODE`; unset means `invite`.
130 */
131export type RegistrationMode = "invite" | "open";
132
133/** How many invites a person may have out at once, unless identity's `INVITES_PER_USER` says otherwise. */
134export const INVITES_PER_USER = 5;
135/** How long an invite works, unless identity's `INVITE_TTL_DAYS` says otherwise. */
136export const INVITE_TTL_DAYS = 30;
137
138/** Only a pending invite can be used or revoked. Revoked and expired ones never used give the invite back. */
139export type InviteStatus = "pending" | "redeemed" | "expired" | "revoked";
140
141/** One invite. Mirrors `Invite` in `crates/contracts/src/identity.rs`. */
142export type Invite = {
143 id: string;
144 /** `g1t-k7m2-…`: returned when it is made, and to its maker while pending. */
145 code: string | null;
146 /** The code's first group, such as `g1t-k7m2`. */
147 hint: string;
148 /** Only this address can use it. */
149 email: string | null;
150 /** `account` makes an account; `workspace` joins an existing one to `workspace`. */
151 kind: "account" | "workspace";
152 /** The workspace using it joins. */
153 workspace: string | null;
154 status: InviteStatus;
155 /** Whose allowance it used. */
156 chargedTo: "user" | "workspace" | "none";
157 /** Its maker's username; null when g1t staff made it. */
158 invitedBy: string | null;
159 /** The account that used it. */
160 redeemedBy: string | null;
161 /** RFC 3339. */
162 createdAt: string;
163 /** RFC 3339. */
164 expiresAt: string;
165 redeemedAt: string | null;
166 revokedAt: string | null;
167 /** The staff member who minted it; only in staff views. */
168 staff?: string | null;
169};
170
171/** How many invites someone may have out. `limit` and `remaining` are null for no limit. */
172export type Allowance = { limit: number | null; used: number; remaining: number | null };
173
174export type InvitesOverview = {
175 mode: RegistrationMode;
176 allowance: Allowance;
177 /** Workspaces the person owns that were granted invites to share. */
178 workspaces: { slug: string; allowance: Allowance }[];
179 invites: Invite[];
180};
181
182/** What a valid code is for, before it is used. */
183export type InvitePreview = {
184 kind: "account" | "workspace";
185 /** Null when g1t staff sent it. */
186 invitedBy: { username: string; name: string | null; avatar: string | null } | null;
187 workspace: ProfileWorkspace | null;
188 /** Partly hidden, such as `a•••@example.com`. */
189 email: string | null;
190 expiresAt: string;
191};
192
193export type WaitlistStatus = "waiting" | "invited" | "dismissed";
194
195export type WaitlistEntry = {
196 id: string;
197 email: string;
198 about: string | null;
199 status: WaitlistStatus;
200 inviteId: string | null;
201 decidedBy: string | null;
202 decidedAt: string | null;
203 /** When they first asked. */
204 createdAt: string;
205 /** When they last asked. */
206 updatedAt: string;
207};
208
209export type InviteGrant = { amount: number; note: string | null; grantedBy: string; createdAt: string };
210export type InviteTreeNode = { username: string; joinedAt: string; invited: InviteTreeNode[] };
211
212/** Where a person came from and whom they brought. For a workspace, `username` is its slug. */
213export type InviteTree = {
214 username: string;
215 /** Who invited them, then who invited that person, and so on. */
216 invitedBy: string[];
217 /** The staff member who minted their invite, when staff did. */
218 staff: string | null;
219 allowance: Allowance;
220 grants: InviteGrant[];
221 invites: Invite[];
222 /** Whom they invited, three levels down. */
223 invited: InviteTreeNode[];
224};
225
226/** The most rows one staff listing of invites or the waitlist returns. */
227export const ADMIN_INVITES_LIMIT = 500;
228
229/**
230 * Staff-only identity, for sudo.g1t.sh. It takes no viewer and checks no
231 * membership: only sudo calls it, over its service binding, once Cloudflare
232 * Access and its staff list have let someone in. Never call it on behalf of
233 * a customer.
234 */
235export interface IdentityAdminApi {
236 /** Every workspace, newest first, at most 500; `query` matches slug, name, or an owner's username or email. */
237 workspaces(query?: string): Promise<AdminWorkspace[]>;
238 /** One workspace with all its members, or null. */
239 workspace(slug: string): Promise<AdminWorkspaceDetail | null>;
240
241 /** The waitlist, oldest first; `query` matches the address or what they said. */
242 waitlist(query?: string | null, status?: WaitlistStatus | null): Promise<WaitlistEntry[]>;
243 /** Approving mints an invite bound to the address and emails it; dismissing only marks it. */
244 decideWaitlist(id: string, approve: boolean, staff: string): Promise<Result<WaitlistEntry>>;
245 /** Invites, newest first; `query` is a code's start, or part of an email, inviter or redeemer. */
246 invites(query?: string | null): Promise<Invite[]>;
247 revokeInvite(id: string, staff: string): Promise<Result<Invite>>;
248 /** An invite that uses nobody's allowance, optionally bound to (and emailed to) `email`. */
249 mintInvite(email: string | null, staff: string): Promise<Result<Invite>>;
250 /** More invites (or fewer, with a negative amount) for a person or a workspace. */
251 grantInvites(
252 target: "user" | "workspace",
253 name: string,
254 amount: number,
255 note: string,
256 staff: string,
257 ): Promise<Result<Allowance>>;
258 /** Where a person came from and whom they brought, or null. */
259 inviteTree(username: string): Promise<InviteTree | null>;
260 /** A workspace's granted invites and the invites made for it, or null. */
261 workspaceInvites(slug: string): Promise<InviteTree | null>;
262}
263
264/** Who is asking. Every read and write in every service takes one. */
265export type Viewer = User | null;
266
267export type SshKey = {
268 id: string;
269 title: string;
270 fingerprint: string;
271 /** RFC 3339. */
272 createdAt: string;
273};
274
275export type AccessToken = {
276 id: string;
277 name: string;
278 /** RFC 3339. */
279 createdAt: string;
280 /** RFC 3339, to within a few minutes. Null until it is first used. */
281 lastUsedAt: string | null;
282 /**
283 * For a workspace's token, the username of the member who made it. Null
284 * once that account is gone, and on personal tokens.
285 */
286 createdBy: string | null;
287};
288
289export type DeviceStart = {
290 /** Secret held by the tool and exchanged for a token once approved. */
291 deviceCode: string;
292 /** Short code shown to the person, e.g. `WDJB-MJHT`. */
293 userCode: string;
294 /** Seconds until both codes stop working. */
295 expiresIn: number;
296 /** Seconds the tool should wait between polls. */
297 interval: number;
298};
299
300export type DeviceRequest = { userCode: string; clientName: string };
301
302export type DeviceClaim =
303 | { status: "pending" | "denied" | "expired" }
304 | { status: "approved"; token: string; user: User };
305
306/** What the site passes on once a person has approved an application. */
307export type OAuthApproval = {
308 clientId: string;
309 /** Shown wherever the application's access is listed. */
310 clientName: string;
311 redirectUri: string;
312 /** PKCE challenge, method S256. */
313 codeChallenge: string;
314};
315
316export type OAuthTokens = {
317 accessToken: string;
318 /** Works once; using it returns the next one. */
319 refreshToken: string;
320 /** Seconds until the access token stops working. */
321 expiresIn: number;
322};
323
324/** An application a person has signed in to. */
325export type OAuthGrant = {
326 id: string;
327 clientName: string;
328 /** RFC 3339. */
329 createdAt: string;
330 /** RFC 3339. */
331 lastUsedAt: string;
332};
333
334/** Accounts, credentials and sessions. */
335/** What stands between a workspace and its deletion; nothing when both counts are 0 and `billing` is null. */
336export type WorkspaceDeletion = {
337 repositories: number;
338 projects: number;
339 /** Why billing cannot close it yet, in words for its owner. */
340 billing: string | null;
341};
342
343export interface IdentityApi extends AccessClient {
344 /**
345 * Creates an account and signs it in. While registration is invite-only,
346 * `inviteCode` must be an unused, unexpired invite (and, when it names an
347 * email, that address); it is ignored while registration is open.
348 */
349 register(
350 username: string,
351 email: string,
352 password: string,
353 inviteCode?: string | null,
354 /** Who is asking, such as the visitor's IP address, for rate limits. */
355 client?: string | null,
356 ): Promise<Result<{ user: User; sessionToken: string }>>;
357 /** Verifies a username and password for website sign-in. */
358 /**
359 * Verifies a username, or any confirmed address of the account, and its
360 * password. Wrong passwords are counted against the account and `client`
361 * (the visitor's IP address); past a limit nothing is checked for a while.
362 */
363 signIn(username: string, password: string, client?: string | null): Promise<Result<{ user: User; sessionToken: string }>>;
364 signOut(sessionToken: string): Promise<void>;
365
366 /** Sends the confirmation email again. */
367 resendVerification(user: User): Promise<Result<boolean>>;
368 /** Confirms the address the emailed token was sent to. */
369 verifyEmail(token: string): Promise<Result<User>>;
370 /** Emails a reset link if the address has an account. Always resolves. */
371 /**
372 * Any confirmed address of an account works; the link goes to it, and the
373 * primary and backup are told. A few an hour per address and per `client`.
374 */
375 requestPasswordReset(email: string, client?: string | null): Promise<boolean>;
376 /** Sets a new password from an emailed token and ends every session. */
377 resetPassword(token: string, password: string): Promise<Result<User>>;
378
379 /**
380 * Device sign-in (RFC 8628). A tool starts a request, a person approves
381 * its short code in a browser, and the tool claims an access token.
382 */
383 deviceStart(clientName: string): Promise<DeviceStart>;
384 /** What a user code is asking for, or null if it is not valid. */
385 deviceLookup(userCode: string): Promise<DeviceRequest | null>;
386 deviceResolve(userCode: string, user: User, approve: boolean): Promise<Result<boolean>>;
387 deviceClaim(deviceCode: string): Promise<DeviceClaim>;
388
389 /**
390 * OAuth 2.1 for applications that sign a person in through the browser.
391 * The caller has checked the client and its redirect address; this
392 * returns the one-time code the application exchanges for tokens.
393 */
394 oauthAuthorize(user: User, approval: OAuthApproval): Promise<{ code: string }>;
395 /** Redeems a code. It works once, for that client, with the PKCE verifier. */
396 oauthExchange(code: string, codeVerifier: string, clientId: string, redirectUri: string): Promise<Result<OAuthTokens>>;
397 /** Trades a refresh token for new tokens; the old ones stop working. */
398 oauthRefresh(refreshToken: string, clientId: string): Promise<Result<OAuthTokens>>;
399 /** Applications the user has signed in to, most recently used first. */
400 listOAuthGrants(user: User): Promise<OAuthGrant[]>;
401 /** Signs an application out. */
402 revokeOAuthGrant(user: User, id: string): Promise<void>;
403
404 createWorkspace(user: User, slug: string, name: string): Promise<Result<Workspace>>;
405 /** Public details of a workspace, or null. */
406 getWorkspace(slug: string): Promise<Workspace | null>;
407 /** Members only. */
408 listMembers(slug: string, viewer: Viewer): Promise<Result<Member[]>>;
409 /** Owners only. */
410 addMember(actor: User, slug: string, username: string): Promise<Result<boolean>>;
411 /** Owners only. */
412 removeMember(actor: User, slug: string, username: string): Promise<Result<boolean>>;
413 /** Owners only. An empty name falls back to the slug. */
414 updateWorkspace(actor: User, slug: string, details: { name: string; description: string }): Promise<Result<Workspace>>;
415 /**
416 * Owners only. Changes the slug, the first segment of the workspace's
417 * URLs; the display name is untouched. The old slug redirects to the new
418 * one, and stays reserved for this workspace, for `SLUG_HOLD_DAYS`.
419 * Publishes `workspace.renamed`.
420 */
421 renameWorkspace(actor: User, slug: string, newSlug: string): Promise<Result<Workspace>>;
422 /** Whether `renameWorkspace` would be allowed, changing nothing. */
423 checkWorkspaceRename(actor: User, slug: string, newSlug: string): Promise<Result<boolean>>;
424 /**
425 * The workspace's current slug when `slug` is one it was renamed from
426 * within `SLUG_HOLD_DAYS`; null otherwise, including for a slug in use.
427 */
428 resolveSlug(slug: string): Promise<string | null>;
429 /**
430 * Owners only, a person only. `confirm` is the slug, typed out. Refused
431 * while the workspace holds repositories or projects, or billing cannot
432 * settle it. Its slug is never given to anyone else; the person whose
433 * username it is may make it again. Publishes `workspace.deleted`.
434 */
435 deleteWorkspace(actor: User, slug: string, confirm: string): Promise<Result<boolean>>;
436 /** What stands in the way of `deleteWorkspace`, changing nothing. */
437 checkWorkspaceDeletion(actor: User, slug: string): Promise<Result<WorkspaceDeletion>>;
438 /**
439 * Owners only. `image` is the file in base64: PNG, JPEG, WebP or GIF, at
440 * most `MAX_AVATAR_BYTES`, checked by its bytes. Null removes the icon.
441 */
442 setWorkspaceAvatar(actor: User, slug: string, image: string | null): Promise<Result<Workspace>>;
443 /** A person's own avatar, as `setWorkspaceAvatar`: the new one, or null. */
444 setUserAvatar(user: User, image: string | null): Promise<Result<string | null>>;
445
446 /**
447 * A workspace's own access tokens. They belong to the workspace, act as
448 * it, and keep working when the member who made one leaves. Members only.
449 */
450 listWorkspaceTokens(slug: string, viewer: Viewer): Promise<Result<AccessToken[]>>;
451 /** Owners only. The plaintext token is returned once and never stored. */
452 createWorkspaceToken(actor: User, slug: string, name: string): Promise<Result<{ token: string; info: AccessToken }>>;
453 /** Owners only. */
454 removeWorkspaceToken(actor: User, slug: string, id: string): Promise<Result<boolean>>;
455
456 userForSession(sessionToken: string): Promise<Viewer>;
457
458 /** Whether registration is invite-only. */
459 registration(): Promise<RegistrationMode>;
460 /** A person's invites and what they have left. */
461 listInvites(user: User): Promise<InvitesOverview>;
462 /**
463 * A person makes an invite, optionally for one address (emailed to it),
464 * using one of theirs or, with `workspace`, one the workspace was granted.
465 * People only: never an agent or a workspace's token.
466 */
467 createInvite(user: User, options?: { email?: string | null; workspace?: string | null }): Promise<Result<Invite>>;
468 /** Its maker, or an owner of its workspace, revokes a pending invite; the invite comes back. */
469 revokeInvite(user: User, id: string): Promise<Result<Invite>>;
470 /** What a code is for. Unknown, used, revoked and expired codes all get the same answer. */
471 checkInvite(code: string, client?: string | null): Promise<Result<InvitePreview>>;
472 /** A signed-in person uses a workspace invite sent to their address; returns the workspace's slug. */
473 acceptInvite(user: User, code: string): Promise<Result<string>>;
474 /** Owners only. Invites an address into a workspace, always with an invite bound to it. */
475 inviteMember(actor: User, slug: string, email: string): Promise<Result<Invite>>;
476 /** Owners only: the workspace's invites, newest first. */
477 workspaceInvites(slug: string, viewer: Viewer): Promise<Result<Invite[]>>;
478 /** Owners only. */
479 revokeWorkspaceInvite(actor: User, slug: string, id: string): Promise<Result<Invite>>;
480 /** Someone without an invite asks for one. Always the same answer for a valid address. */
481 requestAccess(email: string, about: string, client?: string | null): Promise<Result<boolean>>;
482
483 /** Verifies git credentials: the account password or an access token. */
484 userForGitCredentials(username: string, secret: string): Promise<Viewer>;
485 /** Resolves a `g1t_…` access token, as sent to the API and MCP server. */
486 userForAccessToken(token: string): Promise<Viewer>;
487 userForSshKey(fingerprint: string): Promise<Viewer>;
488 userByUsername(username: string): Promise<Viewer>;
489 /** The names behind account and workspace ids; unknown ids are left out. */
490 usernames(ids: string[]): Promise<Record<string, string>>;
491
492 /** A person's public profile, or null if there is no such account. Never an email address. */
493 profile(username: string): Promise<Profile | null>;
494 /** A person changes their own profile. Every field is replaced; an empty one is cleared. */
495 updateProfile(actor: User, fields: ProfileFields): Promise<Result<Profile>>;
496 /**
497 * The workspaces a profile shows `viewer`: those the viewer belongs to
498 * as well, and those of `publicIn` (where the person made a public
499 * project) that the person really belongs to. Nothing else.
500 */
501 profileWorkspaces(username: string, viewer: Viewer, publicIn: string[]): Promise<ProfileWorkspace[]>;
502
503 listSshKeys(user: User): Promise<SshKey[]>;
504 /** Takes one line in OpenSSH public key format. */
505 addSshKey(user: User, title: string, publicKey: string): Promise<Result<SshKey>>;
506 removeSshKey(user: User, id: string): Promise<void>;
507
508 listAccessTokens(user: User): Promise<AccessToken[]>;
509 /**
510 * The plaintext token is returned once and never stored. With
511 * `ttlSeconds` the token expires and is left out of token lists; that
512 * form is used for hosted agents. A token made for a workspace acting
513 * through a token of its own belongs to that workspace too.
514 */
515 createAccessToken(user: User, name: string, ttlSeconds?: number): Promise<{ token: string; info: AccessToken }>;
516 /**
517 * A token for a g1t agent working for `onBehalfOf`: it acts as
518 * `g1t-agent`, in `scope.repo` only, and only for `scope.operations`.
519 */
520 createAgentToken(
521 onBehalfOf: User,
522 scope: AgentScope,
523 ttlSeconds: number,
524 ): Promise<{ token: string; info: AccessToken }>;
525 removeAccessToken(user: User, id: string): Promise<void>;
526 /**
527 * A token for one sandbox run: it acts as the agent on behalf of
528 * `onBehalfOf`, can do only what the run's kind needs in `repo`, and
529 * expires after `ttlSeconds`. See `audit.ts`.
530 */
531 createRunCredential(input: CreateRunCredentialInput): Promise<{ token: string; info: AccessToken }>;
532 /** Ties tokens, by the SHA-256 of their text in hex, to the agent run their sandbox recorded. */
533 bindRunCredentials(tokenHashes: string[], runId: string): Promise<boolean>;
534 /** Ends a sandbox's run credentials, by hash or by run. Never touches another token. */
535 revokeRunCredentials(target: { tokenHashes?: string[]; runId?: string | null }): Promise<boolean>;
536}
537
538
539/** What an agent's token may do: these operations, in this repository. */
540export type AgentScope = { repo: RepoPath; operations: string[]; run?: RunBinding };
541
542/** The most characters each profile field takes. Mirrors `crates/contracts/src/identity.rs`. */
543export const PROFILE_LIMITS = { name: 80, bio: 160, location: 80, website: 200, pronouns: 40 } as const;
544
545/** What anyone may see about a person, at `g1t.sh/u/<username>`. */
546export type Profile = {
547 username: string;
548 /** The name they go by, if they gave one. */
549 name: string | null;
550 bio: string | null;
551 location: string | null;
552 /** Always an `https://` address. */
553 website: string | null;
554 pronouns: string | null;
555 /** The uploaded avatar's hash, served at `/avatars/<avatar>`. */
556 avatar: string | null;
557 /** When the account was made. RFC 3339. */
558 createdAt: string;
559};
560
561/** What a person may change on their profile. Empty clears a field. */
562export type ProfileFields = {
563 name: string;
564 bio: string;
565 location: string;
566 /** `https://…`; a bare `example.com` is taken as `https://example.com`. */
567 website: string;
568 pronouns: string;
569};
570
571/** A workspace on a person's profile. */
572export type ProfileWorkspace = { slug: string; name: string; avatar: string | null };