Skip to content
1,109 linesCodeBlameRaw
1import type { AccessClient, BasePermission, RepoGrant } from "./access";
2import type { Permissions, ScopeLevel, ScopeResource } from "./scopes";
3import type { MemberPrivileges, OrgRole, PolicyHold } from "./members";
4import type { Acting, CreateRunCredentialInput, RunBinding } from "./audit";
5import type { RepoPath } from "./repos";
6import type { Result } from "./result";
7import type { TeamCreation, TeamsClient } from "./teams";
8import type { DeployKeysClient } from "./deploy-keys";
9import type { EmailConfirmed } from "./accounts";
10
11export type User = {
12 id: string;
13 /** Lowercased: what the person is found, linked and mentioned by. */
14 username: string;
15 /**
16 * The username as its owner wrote it (`Ana`), when that differs from
17 * `username`: what pages show (`shownUsername`). Set on the signed-in
18 * person and on people looked up by name.
19 */
20 display_username?: string;
21 /**
22 * `workspace` when a workspace is acting through one of its own access
23 * tokens: `id` is then the workspace's and `username` its slug. `system`
24 * is g1t itself doing platform work, such as a security update
25 * (`username` `g1t`). Absent means `user`.
26 */
27 kind?: "user" | "workspace" | "agent" | "system";
28 /**
29 * Whether the account's email address is confirmed. Only set on users
30 * resolved from credentials. An account that has not confirmed it can
31 * only confirm it: see `awaitsConfirmation`.
32 */
33 verified?: boolean;
34 /**
35 * The workspaces this user belongs to. Set on users resolved from
36 * credentials, so any service can authorize from it.
37 */
38 workspaces?: Membership[];
39 /**
40 * The person's uploaded avatar: the SHA-256 of its bytes, served at
41 * `/avatars/<avatar>`. Only set on the signed-in person; absent means
42 * the generated letter avatar.
43 */
44 avatar?: string;
45 /**
46 * Set on an agent resolved from its token: who it acts for ("g1t
47 * on behalf of syntaqx"), with which credential, and what it may do.
48 */
49 acting?: Acting;
50 /**
51 * The repositories this user has a role on directly, whether or not they
52 * belong to its workspace. Set with `workspaces`; see `access.ts`.
53 */
54 grants?: RepoGrant[];
55 /**
56 * Set on a user resolved from an access token: its scopes (null for full
57 * access) and the workspaces or repositories it reaches. See scopes.ts.
58 */
59 token?: {
60 token_id: string;
61 scopes?: string[] | null;
62 legacy?: boolean;
63 /** The token's name, as its owner gave it. */
64 name?: string;
65 /**
66 * A token narrowed to one workspace (or none): its workspace and
67 * repositories. The key is kept from before tokens were one kind.
68 */
69 fine_grained?: {
70 workspace?: string | null;
71 repositories?: "all" | "selected" | "public";
72 repo_ids?: string[];
73 };
74 /** A workspace's own token with Repositories: admin. */
75 admin?: boolean;
76 /** Set on what a deploy key resolves to. */
77 deploy_key?: string;
78 /** The one repository a job's token or a deploy key reaches. */
79 repo?: string;
80 /** Set on a workflow job's token (`G1T_TOKEN`): the run and job it was made for. */
81 job?: { run_id: string; job_id: string; pull_requests?: boolean };
82 };
83 /**
84 * Workspaces the person belongs to but cannot use until they meet its
85 * policy, such as turning on two-factor authentication. Left out of
86 * `workspaces` and `grants` meanwhile.
87 */
88 held?: PolicyHold[];
89};
90
91/** What a member may do: an owner also manages the workspace's members. */
92export type Role = "owner" | "member";
93
94export type Membership = {
95 /** The workspace's name in URLs: `g1t.sh/<slug>`. */
96 slug: string;
97 role: Role;
98 /** Its display name. Set on users resolved from credentials. */
99 name?: string;
100 /** Its uploaded icon, as `Workspace.avatar`. */
101 avatar?: string;
102 /** The workspace's base permission: what members get on every repository. Absent means `write`. */
103 base_permission?: BasePermission;
104 /** Who may create its teams. Absent means any member. */
105 team_creation?: TeamCreation;
106 /** The roles held besides owner or member. */
107 org_roles?: OrgRole[];
108 /** What the workspace lets its members do. Absent means the defaults. */
109 privileges?: MemberPrivileges;
110 /**
111 * Whether this member uses Code: repositories, issues, pull requests,
112 * checks, deploys. False for people who only use Chat, Docs and agents
113 * (support, sales, finance): they see no repository, whatever the base
114 * permission, and agents treat them as unable to change code. Absent
115 * means true.
116 */
117 code_access?: boolean;
118};
119
120/** Whether a member uses Code. See `Membership.code_access`. */
121export function hasCodeAccess(membership: Pick<Membership, "code_access"> | null | undefined): boolean {
122 return membership?.code_access !== false;
123}
124
125/** How long an old workspace slug redirects, and stays reserved for it, after a rename. */
126export const SLUG_HOLD_DAYS = 90;
127
128/** How long a workspace must wait between renames. */
129export const RENAME_COOLDOWN_HOURS = 24;
130
131/** The largest avatar that can be uploaded, in bytes. */
132export const MAX_AVATAR_BYTES = 1024 * 1024;
133
134/**
135 * Where a workspace keeps its repositories' git data: anywhere g1t stores
136 * it (the default), or in the EU only. It applies to repositories made
137 * after it is set.
138 */
139export type DataResidency = "anywhere" | "eu";
140
141/**
142 * A workspace: the owner of repositories, and the first segment of their
143 * URLs. A person's own space and a team's are the same thing.
144 */
145export type Workspace = {
146 id: string;
147 slug: string;
148 name: string;
149 /** One line saying what the workspace is for. */
150 description: string | null;
151 /** RFC 3339. */
152 createdAt: string;
153 memberCount: number;
154 /**
155 * The workspace's uploaded icon: the SHA-256 of its bytes, served at
156 * `/avatars/<avatar>`. Null means the generated letter avatar.
157 */
158 avatar: string | null;
159 /** What every member gets on each repository; owners have Admin. */
160 basePermission?: BasePermission;
161 /** Who may create its teams. Absent means any member. */
162 teamCreation?: TeamCreation;
163 /** Whether members and outside collaborators need two-factor authentication. */
164 twoFactorRequirementEnabled?: boolean;
165} & Partial<MemberPrivileges>;
166
167export type Member = {
168 username: string;
169 /** The username as its owner wrote it (`Ana`), when that differs from `username`. */
170 display_username?: string;
171 role: Role;
172 /** The roles they hold besides `role`. */
173 org_roles?: OrgRole[];
174 /** Whether two-factor authentication is on; owners only, null for anyone else. */
175 two_factor?: boolean | null;
176 /** Their display name, when they set one. */
177 name?: string | null;
178 /** Their uploaded avatar's hash, served at `/avatars/<avatar>`; null for the generated letter avatar. */
179 avatar?: string | null;
180};
181
182/** An owner of a workspace, as staff see them. */
183export type AdminOwner = { username: string; email: string | null };
184
185/** A workspace as staff see it. Mirrors `AdminWorkspace` in `crates/contracts/src/identity.rs`. */
186export type AdminWorkspace = {
187 slug: string;
188 name: string;
189 /** RFC 3339. */
190 createdAt: string;
191 owners: AdminOwner[];
192 memberCount: number;
193};
194
195/** A member of a workspace, as staff see them. */
196export type AdminMember = { username: string; email: string | null; role: Role; /** RFC 3339. */ joined: string };
197
198export type AdminWorkspaceDetail = {
199 slug: string;
200 name: string;
201 description: string | null;
202 /** RFC 3339. */
203 createdAt: string;
204 /** Owners first, then by username. */
205 members: AdminMember[];
206 /** It can never be deleted, by anyone (identity's `PROTECTED_WORKSPACES`). */
207 protected: boolean;
208};
209
210/** The most workspaces one `workspaces` call returns. */
211export const ADMIN_WORKSPACES_LIMIT = 500;
212
213/**
214 * Whether anyone may make an account, or only someone with an invite.
215 * Identity's `REGISTRATION_MODE`; unset means `invite`.
216 */
217export type RegistrationMode = "invite" | "open";
218
219/** How many invites a person may have out at once, unless identity's `INVITES_PER_USER` says otherwise. */
220export const INVITES_PER_USER = 5;
221/** How long an invite works, unless identity's `INVITE_TTL_DAYS` says otherwise. */
222export const INVITE_TTL_DAYS = 30;
223
224/** Only a pending invite can be used or revoked. Revoked and expired ones never used give the invite back. */
225/**
226 * `awaiting_confirmation`: used to make an account that has not confirmed its
227 * email address yet; what it gives is joined when the address is confirmed,
228 * unless it is revoked first.
229 */
230/**
231 * `awaiting_answer`: the account it made is confirmed, and the workspace it
232 * names waits for the person to accept or decline. `declined`: they said no.
233 */
234export type InviteStatus =
235 | "pending"
236 | "awaiting_confirmation"
237 | "awaiting_answer"
238 | "redeemed"
239 | "declined"
240 | "expired"
241 | "revoked";
242
243/** One invite. Mirrors `Invite` in `crates/contracts/src/identity.rs`. */
244export type Invite = {
245 id: string;
246 /** `g1t-k7m2-…`: returned when it is made, and to its maker while pending. */
247 code: string | null;
248 /** The code's first group, such as `g1t-k7m2`. */
249 hint: string;
250 /** Only this address can use it. */
251 email: string | null;
252 /** `account` makes an account; `workspace` joins an existing one to `workspace`. */
253 kind: "account" | "workspace";
254 /** The workspace using it joins. */
255 workspace: string | null;
256 status: InviteStatus;
257 /** Whose allowance it used. */
258 chargedTo: "user" | "workspace" | "none";
259 /** Its maker's username; null when g1t staff made it. */
260 invitedBy: string | null;
261 /** The account that used it. */
262 redeemedBy: string | null;
263 /** RFC 3339. */
264 createdAt: string;
265 /** RFC 3339. */
266 expiresAt: string;
267 redeemedAt: string | null;
268 revokedAt: string | null;
269 /** The account a workspace invitation is for, by username: someone invited by username, or the account the invite made. */
270 invitee?: string | null;
271 /** The role `workspace` is joined with; null when it names none. */
272 role?: Role | null;
273 /** The staff member who minted it; only in staff views. */
274 staff?: string | null;
275};
276
277/**
278 * A workspace invitation waiting for its person's answer, as they see it.
279 * Mirrors `WorkspaceInvitation` in `crates/contracts/src/identity.rs`.
280 */
281export type WorkspaceInvitation = {
282 id: string;
283 workspace: ProfileWorkspace;
284 /** The role accepting joins with. */
285 role: Role;
286 /** Null when g1t staff sent it. */
287 invitedBy: { username: string; name: string | null; avatar: string | null } | null;
288 createdAt: string;
289 expiresAt: string;
290};
291
292/** Someone to invite, as `findPeople` finds them: never an email address. */
293export type PersonMatch = { username: string; name: string | null; avatar: string | null };
294
295/** How many invites someone may have out. `limit` and `remaining` are null for no limit. */
296export type Allowance = { limit: number | null; used: number; remaining: number | null };
297
298export type InvitesOverview = {
299 mode: RegistrationMode;
300 allowance: Allowance;
301 /** Workspaces the person owns that were granted invites to share. */
302 workspaces: { slug: string; allowance: Allowance }[];
303 invites: Invite[];
304};
305
306/** What a valid code is for, before it is used. */
307export type InvitePreview = {
308 kind: "account" | "workspace";
309 /** Pending, unless `anyStatus` asked about a code that is spent. */
310 status: InviteStatus;
311 /** Null when g1t staff sent it. */
312 invitedBy: { username: string; name: string | null; avatar: string | null } | null;
313 workspace: ProfileWorkspace | null;
314 /** The repository it accepts an invitation to, such as `{ name: "flagon-io/g1t", role: "write" }`. */
315 repository: { name: string; role: string } | null;
316 /** Partly hidden, such as `a•••@example.com`. */
317 email: string | null;
318 /** The bound address in full, while the invite is pending: it fills in and locks the sign-up form. */
319 address: string | null;
320 /** Whether the bound address has a g1t account already: sign in to accept. */
321 hasAccount: boolean;
322 /** With a viewer: whether it is theirs (for one of their confirmed addresses, or used by them). */
323 forViewer: boolean | null;
324 expiresAt: string;
325 /** A shared invite link's group, such as `Cloudflare judges`; null for a one-person invite. Not secret. */
326 sharedLabel: string | null;
327 /** The email domains a shared invite link is limited to; empty for any address. */
328 sharedDomains: string[];
329 /**
330 * Whether the page was opened from this pending invite's own email (its
331 * `proof` checked out): the account made with it starts with `address`
332 * confirmed. False without a proof, with a wrong one, or for an invite
333 * bound to no address.
334 */
335 emailProven: boolean;
336};
337
338export type WaitlistStatus = "waiting" | "invited" | "dismissed";
339
340export type WaitlistEntry = {
341 id: string;
342 email: string;
343 about: string | null;
344 status: WaitlistStatus;
345 inviteId: string | null;
346 decidedBy: string | null;
347 decidedAt: string | null;
348 /** What staff wrote when approving; it went in the invite email. */
349 note: string | null;
350 /** The account made with the invite, once it was used. */
351 joinedAs: string | null;
352 /** When they first asked. */
353 createdAt: string;
354 /** When they last asked. */
355 updatedAt: string;
356};
357
358export type InviteGrant = { amount: number; note: string | null; grantedBy: string; createdAt: string };
359export type InviteTreeNode = { username: string; joinedAt: string; invited: InviteTreeNode[] };
360
361/** Where a person came from and whom they brought. For a workspace, `username` is its slug. */
362export type InviteTree = {
363 username: string;
364 /** Who invited them, then who invited that person, and so on. */
365 invitedBy: string[];
366 /** The staff member who minted their invite, when staff did. */
367 staff: string | null;
368 allowance: Allowance;
369 grants: InviteGrant[];
370 invites: Invite[];
371 /** Whom they invited, three levels down. */
372 invited: InviteTreeNode[];
373 /** The shared invite link the account was made with, if it was. */
374 shared: SharedInviteSource | null;
375};
376
377// --- Shared invite links, staff only ---------------------------------------------------
378//
379// One link for a group (a conference's judges, a post, a community): up to
380// `maxUses` new accounts, until it expires or staff revoke it, optionally only
381// for addresses at some domains. Each use makes a new account, which makes its
382// own workspace; it never joins an existing one and uses nobody's allowance.
383// The link is `https://g1t.sh/register?invite=<code>`. Mirrors the shared
384// invite types in `crates/contracts/src/identity.rs`.
385
386/** How long a shared invite link works when staff give no date. */
387export const SHARED_INVITE_TTL_DAYS = 14;
388/** The furthest ahead a shared invite link's last day may be set. */
389export const SHARED_INVITE_MAX_DAYS = 365;
390/** The most accounts one shared invite link makes. */
391export const MAX_SHARED_INVITE_USES = 1000;
392/** The most characters a shared invite link's label keeps. */
393export const MAX_SHARED_INVITE_LABEL = 80;
394/** The most email domains one shared invite link may be limited to. */
395export const MAX_SHARED_INVITE_DOMAINS = 10;
396
397/** Only a live link makes accounts; `used_up`: every use is taken. */
398export type SharedInviteStatus = "live" | "used_up" | "expired" | "revoked";
399
400/** The shared invite link an account was made with. */
401export type SharedInviteSource = { id: string; label: string };
402
403/** One shared invite link, as staff see it. */
404export type SharedInvite = {
405 /** `sinv_…`. */
406 id: string;
407 /** Whom it is for, such as `Cloudflare judges`. */
408 label: string;
409 /** The code, while it is live. */
410 code: string | null;
411 /** The code's first group, such as `g1t-k7m2`. */
412 hint: string;
413 maxUses: number;
414 /** Accounts made with it so far. */
415 uses: number;
416 /** Only addresses at these domains may use it; empty for any. */
417 domains: string[];
418 status: SharedInviteStatus;
419 /** The staff member who made it, by email. */
420 staff: string;
421 createdAt: string;
422 expiresAt: string;
423 revokedAt: string | null;
424 revokedBy: string | null;
425 /** The accounts made with it, oldest first; `username` is null once one is purged. */
426 accounts: { username: string | null; joinedAt: string }[];
427};
428
429/** What staff make a shared invite link from. */
430export type NewSharedInvite = {
431 label: string;
432 /** 1 to 1000. */
433 maxUses: number;
434 /** The last day it works, `YYYY-MM-DD` (UTC); null for 14 days from now. */
435 expiresOn: string | null;
436 /** Email domains it is limited to, such as `cloudflare.com`; empty for any address. */
437 domains: string[];
438};
439
440/** The most rows one staff listing of invites or the waitlist returns. */
441export const ADMIN_INVITES_LIMIT = 500;
442
443/**
444 * Staff-only identity, for sudo.g1t.sh. It takes no viewer and checks no
445 * membership: only sudo calls it, over its service binding, once Cloudflare
446 * Access and its staff list have let someone in. Never call it on behalf of
447 * a customer.
448 */
449export interface IdentityAdminApi {
450 /** Every workspace, newest first, at most 500; `query` matches slug, name, or an owner's username or email. */
451 workspaces(query?: string): Promise<AdminWorkspace[]>;
452 /** One workspace with all its members, or null. */
453 workspace(slug: string): Promise<AdminWorkspaceDetail | null>;
454
455 /** The waitlist, newest first; `query` matches the address or what they said. */
456 waitlist(query?: string | null, status?: WaitlistStatus | null): Promise<WaitlistEntry[]>;
457 /** How many requests are waiting, for the navigation's badge. */
458 waitlistPending(): Promise<number>;
459 /**
460 * Approving mints an invite bound to the address and emails it, with
461 * `note` (up to 500 characters) if given; dismissing only marks it.
462 */
463 decideWaitlist(id: string, approve: boolean, staff: string, note?: string | null): Promise<Result<WaitlistEntry>>;
464 /** Invites, newest first; `query` is a code's start, or part of an email, inviter or redeemer. */
465 invites(query?: string | null): Promise<Invite[]>;
466 revokeInvite(id: string, staff: string): Promise<Result<Invite>>;
467 /** An invite that uses nobody's allowance, optionally bound to (and emailed to) `email`. */
468 mintInvite(email: string | null, staff: string): Promise<Result<Invite>>;
469 /** More invites (or fewer, with a negative amount) for a person or a workspace. */
470 grantInvites(
471 target: "user" | "workspace",
472 name: string,
473 amount: number,
474 note: string,
475 staff: string,
476 ): Promise<Result<Allowance>>;
477 /** Where a person came from and whom they brought, or null. */
478 inviteTree(username: string): Promise<InviteTree | null>;
479 /** A workspace's granted invites and the invites made for it, or null. */
480 workspaceInvites(slug: string): Promise<InviteTree | null>;
481 /** Shared invite links, newest first, each with the accounts it made. */
482 sharedInvites(): Promise<SharedInvite[]>;
483 /** Makes a shared invite link; the result carries its code. Recorded in the audit log. */
484 createSharedInvite(link: NewSharedInvite, staff: string): Promise<Result<SharedInvite>>;
485 /** Stops a shared invite link making more accounts; those it made stay. Recorded in the audit log. */
486 revokeSharedInvite(id: string, staff: string): Promise<Result<SharedInvite>>;
487
488 /** Workspaces owners deleted that are not purged yet, newest first. */
489 deletedWorkspaces(): Promise<DeletedWorkspace[]>;
490 /**
491 * Brings a deleted workspace back, with its members, tokens and what went
492 * with it, while it is still restorable. Publishes `workspace.restored`.
493 */
494 restoreWorkspace(workspaceId: string, staff: string): Promise<Result<boolean>>;
495 /**
496 * Purges a deleted workspace now rather than at `purgeAfter`. `confirm` is
497 * its slug, typed out. Refused for a protected workspace. Publishes
498 * `workspace.deleted`.
499 */
500 purgeWorkspace(workspaceId: string, staff: string, confirm: string): Promise<Result<boolean>>;
501
502 /** Every workspace alias, by name. */
503 aliases(): Promise<WorkspaceAlias[]>;
504 /**
505 * Points `alias` at the workspace whose slug is `workspace`. Refused for
506 * one of the site's routes, anyone's username, a workspace's slug (deleted
507 * or held after a rename) and an existing alias. `note` says why.
508 */
509 setAlias(alias: string, workspace: string, note: string, staff: string): Promise<Result<WorkspaceAlias>>;
510 /** Removes an alias; `reason` goes in sudo's audit log. */
511 removeAlias(alias: string, reason: string, staff: string): Promise<Result<boolean>>;
512}
513
514/**
515 * A name g1t's staff point at a workspace, so its addresses lead there under
516 * the workspace's own name: `g1t`, the product, leads to `flagon-io`, Flagon,
517 * Inc. Staff-managed only; it follows the workspace through renames.
518 */
519export type WorkspaceAlias = {
520 alias: string;
521 workspaceId: string;
522 /** The workspace's slug and name now. */
523 workspace: string;
524 workspaceName: string;
525 /** Why it exists. */
526 note: string;
527 /** The staff member who set it, or `migration`. */
528 createdBy: string;
529 /** RFC 3339. */
530 createdAt: string;
531};
532
533/** Who is asking. Every read and write in every service takes one. */
534export type Viewer = User | null;
535
536/**
537 * Whether this is a person whose account has not confirmed its email
538 * address. Such an account can only confirm it, change it, or sign out.
539 */
540export function awaitsConfirmation(user: Pick<User, "kind" | "verified"> | null | undefined): boolean {
541 return !!user && (user.kind ?? "user") === "user" && !user.verified;
542}
543
544export type SshKey = {
545 id: string;
546 title: string;
547 fingerprint: string;
548 /** RFC 3339. */
549 createdAt: string;
550 /** When it last signed in over SSH, RFC 3339, to within 5 minutes; null when it never has. */
551 lastUsedAt: string | null;
552};
553
554export type AccessToken = {
555 id: string;
556 name: string;
557 /** RFC 3339. */
558 createdAt: string;
559 /** RFC 3339, to within a few minutes. Null until it is first used. */
560 lastUsedAt: string | null;
561 /**
562 * For a workspace's token, the username of the member who made it. Null
563 * once that account is gone, and on personal tokens.
564 */
565 createdBy: string | null;
566 /** Its scopes, as `resource:level`, the highest of each resource. Null: full access. */
567 scopes: string[] | null;
568 /** Made before tokens had scopes: full access until someone narrows it. */
569 legacy: boolean;
570 /** RFC 3339. Null: it does not expire. */
571 expiresAt: string | null;
572 /** Its scopes as permissions: each resource it may use, at the highest level. */
573 permissions?: Permissions;
574 /** What it is for, as its owner wrote it. */
575 description?: string | null;
576 /**
577 * A personal token's reach: the workspace it is made for; null for every
578 * workspace you belong to (or, with `repositorySelection` public, none).
579 * Null on a workspace's own token, which reaches its workspace.
580 */
581 workspace?: string | null;
582 /** Which repositories of that workspace it reaches. */
583 repositorySelection?: RepositorySelection;
584 /** With `selected`: the repositories, as `owner/name`, that you can see. */
585 repositories?: string[];
586 /** Whether a token made for a workspace that approves tokens may be used there yet. */
587 status?: TokenStatus;
588 /** Why an owner denied or revoked it. */
589 reviewReason?: string | null;
590 /** A workspace's own token, acting as the workspace. */
591 workspaceOwned?: boolean;
592 /** A workspace's own token with Repositories: admin, an admin of its repositories. */
593 admin?: boolean;
594};
595
596/** Which repositories a token reaches in its workspace: all, the selected ones, or public ones only. */
597export type RepositorySelection = "all" | "selected" | "public";
598
599/** Whether a token made for a workspace may be used there yet. */
600export type TokenStatus = "active" | "pending" | "denied" | "revoked";
601
602/** A new access token: a person's, or (with `owner`) a workspace's. */
603export type TokenInput = {
604 /** A workspace's slug to make that workspace's token; null for your own. */
605 owner?: string | null;
606 name: string;
607 description?: string | null;
608 /** 1 to 366 days; null for no expiry, where the workspaces it reaches allow that. */
609 ttlSeconds: number | null;
610 /**
611 * A personal token's reach: a workspace's slug, or null for every
612 * workspace you belong to (with `repositorySelection` public: none).
613 */
614 workspace: string | null;
615 repositorySelection: RepositorySelection;
616 /** With `selected`: `owner/name` or names in the workspace. */
617 repositories: string[];
618 /** Each resource's level; left out is no access. */
619 permissions: Partial<Record<ScopeResource, ScopeLevel>>;
620};
621
622/** A change to a token; what is left out stays. */
623export type TokenChange = Partial<Pick<TokenInput, "name" | "description" | "repositorySelection" | "repositories" | "permissions">>;
624
625/** A workspace's rules for personal access tokens. */
626export type TokenPolicy = {
627 /** A token made for every workspace of its owner reaches this one. */
628 allowTokensForAllWorkspaces: boolean;
629 /** A token may be made for this workspace alone. */
630 allowTokensForThisWorkspace: boolean;
631 /** A token made for this workspace waits for an owner's approval. */
632 requireApproval: boolean;
633 /** Null: no limit. */
634 maxLifetimeDays: number | null;
635 forbidNoExpiry: boolean;
636 updatedBy?: string | null;
637 updatedAt?: string | null;
638};
639
640/** A member's personal token that reaches a workspace, as its owners see it. */
641export type MemberToken = {
642 owner: string;
643 token: AccessToken;
644 /** Whether it reaches the workspace now. */
645 reaches: boolean;
646 /** Why not: pending approval, denied, revoked, tokens for all workspaces not allowed, tokens made for this workspace not allowed, lasts too long, never expires. */
647 blockedBy?: string | null;
648};
649
650/** What a new or changed token may do. */
651export type TokenGrant = {
652 /** Null: full access. */
653 scopes: string[] | null;
654};
655
656export type DeviceStart = {
657 /** Secret held by the tool and exchanged for a token once approved. */
658 deviceCode: string;
659 /** Short code shown to the person, e.g. `WDJB-MJHT`. */
660 userCode: string;
661 /** Seconds until both codes stop working. */
662 expiresIn: number;
663 /** Seconds the tool should wait between polls. */
664 interval: number;
665};
666
667export type DeviceRequest = { userCode: string; clientName: string };
668
669export type DeviceClaim =
670 | { status: "pending" | "denied" | "expired" }
671 | { status: "approved"; token: string; user: User };
672
673/** What the site passes on once a person has approved an application. */
674export type OAuthApproval = {
675 clientId: string;
676 /** Shown wherever the application's access is listed. */
677 clientName: string;
678 redirectUri: string;
679 /** PKCE challenge, method S256. */
680 codeChallenge: string;
681 /** What the person granted. Null: full access. */
682 scopes: string[] | null;
683};
684
685export type OAuthTokens = {
686 accessToken: string;
687 /** Works once; using it returns the next one. */
688 refreshToken: string;
689 /** Seconds until the access token stops working. */
690 expiresIn: number;
691 /** The scopes granted, space-separated, or `*` for full access. */
692 scope?: string | null;
693};
694
695/** An application a person has signed in to. */
696export type OAuthGrant = {
697 id: string;
698 clientName: string;
699 /** RFC 3339. */
700 createdAt: string;
701 /** RFC 3339. */
702 lastUsedAt: string;
703 /** What the person granted. Null: full access. */
704 scopes: string[] | null;
705 /** Signed in before applications had scopes: full access until narrowed. */
706 legacy: boolean;
707};
708
709/** Accounts, credentials and sessions. */
710/**
711 * What deleting a workspace takes with it, and what stands in the way:
712 * nothing does while `billing` is null and it is not `protected`.
713 */
714export type WorkspaceDeletion = {
715 /** Its live repositories, deleted with it. */
716 repositories: number;
717 /** Its projects, hidden with it. */
718 projects: number;
719 members: number;
720 /** Why billing cannot close it yet, in words for its owner. */
721 billing: string | null;
722 /** It can never be deleted, by anyone. */
723 protected: boolean;
724};
725
726/** How long a deleted workspace is kept, for g1t's staff to restore, before it is purged. */
727export const WORKSPACE_RESTORE_DAYS = 30;
728
729/**
730 * Workspaces nobody can delete, whatever identity's `PROTECTED_WORKSPACES`
731 * says: Flagon's, which runs g1t. Services that act on `workspace.deleting`
732 * check it too, so one published for it by mistake changes nothing.
733 */
734export const ALWAYS_PROTECTED_WORKSPACES: readonly string[] = ["flagon-io"];
735
736/** Whether `slug` is one of `ALWAYS_PROTECTED_WORKSPACES`, in any case. */
737export function isProtectedWorkspace(slug: string): boolean {
738 return ALWAYS_PROTECTED_WORKSPACES.includes(slug.trim().toLowerCase());
739}
740
741/** A workspace an owner deleted, kept until `purgeAfter` for staff to restore. */
742export type DeletedWorkspace = {
743 workspaceId: string;
744 slug: string;
745 name: string;
746 /** RFC 3339. */
747 deletedAt: string;
748 /** The username of the owner who deleted it, or the staff member who deleted it with the account that alone owned it. */
749 deletedBy: string;
750 /** RFC 3339: when it is purged unless restored first. */
751 purgeAfter: string;
752 /** What went with it, counted when it was deleted. */
753 went: WorkspaceDeletion;
754 /** Whether staff can still restore it. */
755 restorable: boolean;
756};
757
758export interface IdentityApi extends AccessClient, TeamsClient, DeployKeysClient {
759 /**
760 * Creates an account and signs it in. While registration is invite-only,
761 * `inviteCode` must be an unused, unexpired invite (and, when it names an
762 * email, that address); it is ignored while registration is open.
763 */
764 register(
765 username: string,
766 email: string,
767 password: string,
768 inviteCode?: string | null,
769 /** Who is asking, such as the visitor's IP address, for rate limits. */
770 client?: string | null,
771 /**
772 * The `proof` from the invite email's link. When it is the invite's own
773 * and `email` is the address it was sent to, the account starts with that
774 * address confirmed; otherwise it is ignored.
775 */
776 emailProof?: string | null,
777 ): Promise<Result<{ user: User; sessionToken: string }>>;
778 /** Verifies a username and password for website sign-in. */
779 /**
780 * Verifies a username, or any confirmed address of the account, and its
781 * password. Wrong passwords are counted against the account and `client`
782 * (the visitor's IP address); past a limit nothing is checked for a while.
783 */
784 signIn(
785 username: string,
786 password: string,
787 client?: string | null,
788 ): Promise<Result<{ user: User; sessionToken: string; twoFactorChallenge?: string | null }>>;
789 /**
790 * The second step of signing in, for an account with two-factor
791 * authentication: the challenge `signIn` returned, and a code from the
792 * app or a recovery code.
793 */
794 twoFactorSignIn(challenge: string, code: string, client?: string | null): Promise<Result<{ user: User; sessionToken: string }>>;
795 signOut(sessionToken: string): Promise<void>;
796
797 /**
798 * Sends a new confirmation code and link to the primary of an account
799 * that has not confirmed it, at most once a minute.
800 */
801 resendVerification(user: User): Promise<Result<boolean>>;
802 /** Confirms the address the emailed link was sent to, signed in or not; ends the code sent with it. */
803 verifyEmail(token: string): Promise<Result<EmailConfirmed>>;
804 /** Emails a reset link if the address has an account. Always resolves. */
805 /**
806 * Any confirmed address of an account works; the link goes to it, and the
807 * primary and backup are told. A few an hour per address and per `client`.
808 */
809 requestPasswordReset(email: string, client?: string | null): Promise<boolean>;
810 /** Sets a new password from an emailed token and ends every session. */
811 resetPassword(token: string, password: string): Promise<Result<User>>;
812
813 /**
814 * Device sign-in (RFC 8628). A tool starts a request, a person approves
815 * its short code in a browser, and the tool claims an access token.
816 */
817 deviceStart(clientName: string): Promise<DeviceStart>;
818 /** What a user code is asking for, or null if it is not valid. */
819 deviceLookup(userCode: string): Promise<DeviceRequest | null>;
820 deviceResolve(userCode: string, user: User, approve: boolean): Promise<Result<boolean>>;
821 deviceClaim(deviceCode: string): Promise<DeviceClaim>;
822
823 /**
824 * OAuth 2.1 for applications that sign a person in through the browser.
825 * The caller has checked the client and its redirect address; this
826 * returns the one-time code the application exchanges for tokens.
827 */
828 oauthAuthorize(user: User, approval: OAuthApproval): Promise<{ code: string }>;
829 /** Redeems a code. It works once, for that client, with the PKCE verifier. */
830 oauthExchange(code: string, codeVerifier: string, clientId: string, redirectUri: string): Promise<Result<OAuthTokens>>;
831 /** Trades a refresh token for new tokens; the old ones stop working. */
832 oauthRefresh(refreshToken: string, clientId: string): Promise<Result<OAuthTokens>>;
833 /** Applications the user has signed in to, most recently used first. */
834 listOAuthGrants(user: User): Promise<OAuthGrant[]>;
835 /** Signs an application out. */
836 revokeOAuthGrant(user: User, id: string): Promise<void>;
837 /** Changes what an application may do, at once and when it refreshes. */
838 updateOAuthGrant(user: User, id: string, grant: TokenGrant): Promise<Result<OAuthGrant>>;
839
840 createWorkspace(user: User, slug: string, name: string): Promise<Result<Workspace>>;
841 /** Public details of a workspace, or null. */
842 getWorkspace(slug: string): Promise<Workspace | null>;
843 /** Where a workspace keeps its repositories' git data; null when there is no such workspace. */
844 workspaceResidency(slug: string): Promise<DataResidency | null>;
845 /**
846 * Owners only. Applies to repositories made from then on. Offer `eu`
847 * only when the repos service's `storageOptions()` says it is available.
848 */
849 setWorkspaceResidency(actor: User, slug: string, residency: DataResidency): Promise<Result<DataResidency>>;
850 /** Members only. */
851 listMembers(slug: string, viewer: Viewer): Promise<Result<Member[]>>;
852 /** Owners only. */
853 addMember(actor: User, slug: string, username: string): Promise<Result<boolean>>;
854 /** Owners only; your own username is leaving. Never the last owner. */
855 removeMember(actor: User, slug: string, username: string): Promise<Result<boolean>>;
856 /** Owners only: owner or member, and the roles held besides it. Never leaves no owner. */
857 updateMember(actor: User, slug: string, username: string, change: { role?: Role; org_roles?: OrgRole[] }): Promise<Result<Member>>;
858 /** Owners only: `username` becomes an owner, and you a member. */
859 transferOwnership(actor: User, slug: string, username: string): Promise<Result<boolean>>;
860 /** You leave the workspace. Never the last owner. */
861 leaveWorkspace(user: User, slug: string): Promise<Result<boolean>>;
862 /** Owners only: change some member privileges; returns all of them. */
863 setMemberPrivileges(actor: User, slug: string, change: Partial<MemberPrivileges>): Promise<Result<MemberPrivileges>>;
864 /** Owners only, with two-factor on themselves: require it of everyone. */
865 setTwoFactorRequirement(actor: User, slug: string, required: boolean): Promise<Result<boolean>>;
866 /** Owners only. An empty name falls back to the slug. */
867 updateWorkspace(actor: User, slug: string, details: { name: string; description: string }): Promise<Result<Workspace>>;
868 /**
869 * Owners only. Changes the slug, the first segment of the workspace's
870 * URLs; the display name is untouched. The old slug redirects to the new
871 * one, and stays reserved for this workspace, for `SLUG_HOLD_DAYS`.
872 * Publishes `workspace.renamed`.
873 */
874 renameWorkspace(actor: User, slug: string, newSlug: string): Promise<Result<Workspace>>;
875 /** Whether `renameWorkspace` would be allowed, changing nothing. */
876 checkWorkspaceRename(actor: User, slug: string, newSlug: string): Promise<Result<boolean>>;
877 /**
878 * The workspace's current slug when `slug` is one it was renamed from
879 * within `SLUG_HOLD_DAYS`, or when `slug` is an alias staff set for it
880 * (`WorkspaceAlias`); null otherwise, including for a slug in use.
881 */
882 resolveSlug(slug: string): Promise<string | null>;
883 /**
884 * Owners only, a person only. `confirm` is the slug, typed out. Refused
885 * for a protected workspace, and while billing cannot settle it. Its
886 * repositories, projects and apps go with it; it is kept for
887 * `WORKSPACE_RESTORE_DAYS`, when g1t's staff can restore it, then purged.
888 * Its slug is never given to anyone else; the person whose username it is
889 * may make it again once it is purged. Publishes `workspace.deleting`.
890 */
891 deleteWorkspace(actor: User, slug: string, confirm: string): Promise<Result<boolean>>;
892 /** What `deleteWorkspace` would take with it, and what stands in its way, changing nothing. */
893 checkWorkspaceDeletion(actor: User, slug: string): Promise<Result<WorkspaceDeletion>>;
894 /**
895 * Owners only. `image` is the file in base64: PNG, JPEG, WebP or GIF, at
896 * most `MAX_AVATAR_BYTES`, checked by its bytes. Null removes the icon.
897 */
898 setWorkspaceAvatar(actor: User, slug: string, image: string | null): Promise<Result<Workspace>>;
899 /** A person's own avatar, as `setWorkspaceAvatar`: the new one, or null. */
900 setUserAvatar(user: User, image: string | null): Promise<Result<string | null>>;
901
902 /**
903 * A workspace's own access tokens. They belong to the workspace, act as
904 * it, and keep working when the member who made one leaves. Members only.
905 */
906 listWorkspaceTokens(slug: string, viewer: Viewer): Promise<Result<AccessToken[]>>;
907 /** Owners only. */
908 removeWorkspaceToken(actor: User, slug: string, id: string): Promise<Result<boolean>>;
909
910 /**
911 * An access token: yours, or (with `input.owner`, owners only) a
912 * workspace's. People only, signed in. The plaintext token is returned
913 * once and never stored. A personal token made for a workspace that asks
914 * for approval starts pending unless you are an owner there.
915 */
916 createToken(actor: User, input: TokenInput): Promise<Result<{ token: string; info: AccessToken }>>;
917 /**
918 * Changes a token of yours, or (with `owner`, owners only) a
919 * workspace's; what is left out stays. Widening a token made for a
920 * workspace that approves tokens asks for approval again.
921 */
922 updateToken(actor: User, id: string, change: TokenChange, owner?: string | null): Promise<Result<AccessToken>>;
923 /** A workspace's rules for personal access tokens. Members only. */
924 getTokenPolicy(slug: string, viewer: Viewer): Promise<Result<TokenPolicy>>;
925 /** Owners only, as people. `maxLifetimeDays` of 0 removes the limit. */
926 setTokenPolicy(
927 actor: User,
928 slug: string,
929 change: Partial<Omit<TokenPolicy, "updatedBy" | "updatedAt">>,
930 ): Promise<Result<TokenPolicy>>;
931 /** The members' tokens that can reach a workspace. Owners only. */
932 listMemberTokens(
933 actor: User,
934 slug: string,
935 filter?: { status?: TokenStatus },
936 ): Promise<Result<MemberToken[]>>;
937 /** Approve or deny a token waiting for approval. Owners only. */
938 reviewTokenRequest(actor: User, slug: string, id: string, approve: boolean, reason?: string | null): Promise<Result<MemberToken>>;
939 /** Take a member's token out of the workspace. Owners only. */
940 revokeMemberToken(actor: User, slug: string, id: string, reason?: string | null): Promise<Result<boolean>>;
941
942 userForSession(sessionToken: string): Promise<Viewer>;
943
944 /** Whether registration is invite-only. */
945 registration(): Promise<RegistrationMode>;
946 /** A person's invites and what they have left. */
947 listInvites(user: User): Promise<InvitesOverview>;
948 /**
949 * A person makes an invite, optionally for one address (emailed to it),
950 * using one of theirs or, with `workspace`, one the workspace was granted.
951 * People only: never an agent or a workspace's token.
952 */
953 createInvite(
954 user: User,
955 options?: { email?: string | null; workspace?: string | null; join?: string | null; joinRole?: "owner" | "member" | null },
956 ): Promise<Result<Invite>>;
957 /** Its maker, or an owner of its workspace, revokes a pending invite; the invite comes back. */
958 revokeInvite(user: User, id: string): Promise<Result<Invite>>;
959 /**
960 * What a code is for. Unknown, used, revoked and expired codes all get the
961 * same answer, unless `anyStatus`: then a real code that is spent is
962 * described, with its `status`. `viewer` sets `forViewer`; `emailProof`,
963 * the `proof` from the invite email's link, sets `emailProven`.
964 */
965 checkInvite(
966 code: string,
967 client?: string | null,
968 options?: { viewer?: User | null; anyStatus?: boolean; emailProof?: string | null },
969 ): Promise<Result<InvitePreview>>;
970 /**
971 * A signed-in person uses a workspace invite sent to their address, or one
972 * sent with a repository invitation; returns the workspace's slug, or
973 * `workspace/repo`.
974 */
975 acceptInvite(user: User, code: string): Promise<Result<string>>;
976 /**
977 * Owners only. Invites someone into a workspace by address (always with an
978 * invite bound to it) or by `username`: a workspace invitation they accept
979 * or decline. Nobody joins without saying yes. `role` is what they join as.
980 */
981 inviteMember(
982 actor: User,
983 slug: string,
984 who: { email?: string | null; username?: string | null; role?: Role | null },
985 ): Promise<Result<Invite>>;
986 /** The workspace invitations waiting for the person's answer, newest first. */
987 listInvitations(user: User): Promise<WorkspaceInvitation[]>;
988 /** Joins the invitation's workspace with its role; returns the workspace's slug. */
989 acceptInvitation(user: User, id: string): Promise<Result<string>>;
990 /** Declines it; whoever sent it is told in their inbox. */
991 declineInvitation(user: User, id: string): Promise<Result<boolean>>;
992 /** People to invite, by username prefix or name: a username, a name and an avatar each. */
993 findPeople(query: string, limit?: number): Promise<PersonMatch[]>;
994 /** Owners only: the workspace's invites, newest first. */
995 workspaceInvites(slug: string, viewer: Viewer): Promise<Result<Invite[]>>;
996 /** Owners only. */
997 revokeWorkspaceInvite(actor: User, slug: string, id: string): Promise<Result<Invite>>;
998 /** Someone without an invite asks for one. Always the same answer for a valid address. */
999 requestAccess(email: string, about: string, client?: string | null): Promise<Result<boolean>>;
1000
1001 /** Verifies git credentials: the account password or an access token. */
1002 userForGitCredentials(username: string, secret: string): Promise<Viewer>;
1003 /** Resolves a `g1t_…` access token, as sent to the API and MCP server. */
1004 userForAccessToken(token: string): Promise<Viewer>;
1005 userForSshKey(fingerprint: string): Promise<Viewer>;
1006 userByUsername(username: string): Promise<Viewer>;
1007 /** The names behind account and workspace ids; unknown ids are left out. */
1008 usernames(ids: string[]): Promise<Record<string, string>>;
1009 /**
1010 * Internal: the people behind these ids (at most 50) with their
1011 * workspaces, roles and repository grants, as a signed-in viewer has
1012 * them. For the agents service's audience checks only. Ids of no live
1013 * account are left out.
1014 */
1015 usersForAudience(ids: string[]): Promise<User[]>;
1016
1017 /** A person's public profile, or null if there is no such account. Never an email address. */
1018 profile(username: string): Promise<Profile | null>;
1019 /** A person changes their own profile. Every field is replaced; an empty one is cleared. */
1020 updateProfile(actor: User, fields: ProfileFields): Promise<Result<Profile>>;
1021 /**
1022 * The workspaces a profile shows `viewer`: those the viewer belongs to
1023 * as well, and those of `publicIn` (where the person made a public
1024 * project) that the person really belongs to. Nothing else.
1025 */
1026 profileWorkspaces(username: string, viewer: Viewer, publicIn: string[]): Promise<ProfileWorkspace[]>;
1027
1028 listSshKeys(user: User): Promise<SshKey[]>;
1029 /** Takes one line in OpenSSH public key format. */
1030 addSshKey(user: User, title: string, publicKey: string): Promise<Result<SshKey>>;
1031 removeSshKey(user: User, id: string): Promise<void>;
1032
1033 listAccessTokens(user: User): Promise<AccessToken[]>;
1034 /**
1035 * A credential minted for a person or workspace by another service. The
1036 * plaintext token is returned once and never stored. With `ttlSeconds`
1037 * the token expires and is left out of token lists; that form is used
1038 * for hosted agents. Tokens people make use `createToken`.
1039 */
1040 createAccessToken(
1041 user: User,
1042 name: string,
1043 ttlSeconds?: number,
1044 grant?: TokenGrant & { listed?: boolean },
1045 ): Promise<{ token: string; info: AccessToken }>;
1046 /**
1047 * A token for a g1t agent working for `onBehalfOf`: it acts as
1048 * `g1t`, in `scope.repo` only, and only for `scope.operations`.
1049 */
1050 createAgentToken(
1051 onBehalfOf: User,
1052 scope: AgentScope,
1053 ttlSeconds: number,
1054 ): Promise<{ token: string; info: AccessToken }>;
1055 removeAccessToken(user: User, id: string): Promise<void>;
1056 /**
1057 * A token for one sandbox run: it acts as the agent on behalf of
1058 * `onBehalfOf`, can do only what the run's kind needs in `repo`, and
1059 * expires after `ttlSeconds`. See `audit.ts`.
1060 */
1061 createRunCredential(input: CreateRunCredentialInput): Promise<{ token: string; info: AccessToken }>;
1062 /** Ties tokens, by the SHA-256 of their text in hex, to the agent run their sandbox recorded. */
1063 bindRunCredentials(tokenHashes: string[], runId: string): Promise<boolean>;
1064 /** Ends a sandbox's run credentials, by hash or by run. Never touches another token. */
1065 revokeRunCredentials(target: { tokenHashes?: string[]; runId?: string | null }): Promise<boolean>;
1066}
1067
1068
1069/** What an agent's token may do: these operations, in this repository. */
1070export type AgentScope = { repo: RepoPath; operations: string[]; run?: RunBinding };
1071
1072/** The most characters each profile field takes. Mirrors `crates/contracts/src/identity.rs`. */
1073export const PROFILE_LIMITS = { name: 80, bio: 160, location: 80, website: 200, pronouns: 40, timezone: 64 } as const;
1074
1075/** What anyone may see about a person, at `g1t.sh/u/<username>`. */
1076export type Profile = {
1077 /** Lowercased: what the profile is found and linked by. */
1078 username: string;
1079 /** The username as its owner wrote it (`Ana`), when that differs: what the page shows. */
1080 displayUsername?: string | null;
1081 /** The name they go by, if they gave one. */
1082 name: string | null;
1083 bio: string | null;
1084 location: string | null;
1085 /** Always an `https://` address. */
1086 website: string | null;
1087 pronouns: string | null;
1088 /** The time zone they are in, an IANA name such as `America/Denver`. */
1089 timezone: string | null;
1090 /** The uploaded avatar's hash, served at `/avatars/<avatar>`. */
1091 avatar: string | null;
1092 /** When the account was made. RFC 3339. */
1093 createdAt: string;
1094};
1095
1096/** What a person may change on their profile. Empty clears a field. */
1097export type ProfileFields = {
1098 name: string;
1099 bio: string;
1100 location: string;
1101 /** `https://…`; a bare `example.com` is taken as `https://example.com`. */
1102 website: string;
1103 pronouns: string;
1104 /** An IANA time zone name, such as `America/Denver`; empty clears it. */
1105 timezone: string;
1106};
1107
1108/** A workspace on a person's profile. */
1109export type ProfileWorkspace = { slug: string; name: string; avatar: string | null };