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