Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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