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