Skip to content
1,599 linesCodeBlameRaw
1//! The identity service: accounts, credentials and sessions.
2//!
3//! Each `*Args` struct is the argument of the method of the same name,
4//! served at `POST /rpc/<method>`.
5
6use serde::{Deserialize, Serialize};
7
8use crate::User;
9
10#[derive(Clone, Debug, Serialize, Deserialize)]
11#[serde(rename_all = "camelCase")]
12pub struct SshKey {
13 pub id: String,
14 pub title: String,
15 pub fingerprint: String,
16 /// RFC 3339.
17 pub created_at: String,
18 /// When it was last used to sign in over SSH, RFC 3339, to within 5
19 /// minutes; null when it never was.
20 #[serde(default)]
21 pub last_used_at: Option<String>,
22}
23
24#[derive(Clone, Debug, Default, Serialize, Deserialize)]
25#[serde(rename_all = "camelCase")]
26pub struct AccessToken {
27 pub id: String,
28 pub name: String,
29 /// RFC 3339.
30 pub created_at: String,
31 /// RFC 3339, to within a few minutes. Null until it is first used.
32 pub last_used_at: Option<String>,
33 /// For a workspace's token, the username of the member who made it.
34 /// Null once that account is gone, and on personal tokens.
35 pub created_by: Option<String>,
36 /// Its scopes, as `resource:level`. Null: full access.
37 #[serde(default)]
38 pub scopes: Option<Vec<String>>,
39 /// Made before tokens had scopes: full access until someone narrows it.
40 #[serde(default)]
41 pub legacy: bool,
42 /// RFC 3339. Null: it does not expire.
43 #[serde(default)]
44 pub expires_at: Option<String>,
45 /// Classic, fine-grained, or a workspace's own.
46 #[serde(default)]
47 pub kind: crate::tokens::TokenKind,
48 /// What it is for, as its owner wrote it.
49 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub description: Option<String>,
51 /// A fine-grained token's resource owner, repositories, permissions and
52 /// status.
53 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub fine_grained: Option<crate::tokens::FineGrainedDetails>,
55 /// A workspace's own token an owner gave Admin when making it.
56 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
57 pub admin: bool,
58}
59
60/// `sign_in`: verifies a username, or any confirmed email address of the
61/// account, and its password, for website sign-in. Wrong passwords are
62/// counted against the account and `client`, and past a limit nothing is
63/// checked for a while (see identity's `throttle.rs`).
64/// Returns `Outcome<SignedIn>`.
65#[derive(Debug, Serialize, Deserialize)]
66pub struct SignInArgs {
67 pub username: String,
68 pub password: String,
69 /// Who is asking, such as the visitor's IP address, for rate limits.
70 #[serde(default)]
71 pub client: Option<String>,
72}
73
74#[derive(Debug, Serialize, Deserialize)]
75#[serde(rename_all = "camelCase")]
76pub struct SignedIn {
77 pub user: User,
78 /// Empty while `two_factor_challenge` is set: no session is made until
79 /// the code is given.
80 pub session_token: String,
81 /// Set when the account has two-factor authentication on: the token to
82 /// pass to `two_factor_sign_in` with a code. Valid for
83 /// `accounts::TWO_FACTOR_CHALLENGE_SECONDS`.
84 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub two_factor_challenge: Option<String>,
86}
87
88/// `sign_out` and `user_for_session`.
89#[derive(Debug, Serialize, Deserialize)]
90#[serde(rename_all = "camelCase")]
91pub struct SessionArgs {
92 pub session_token: String,
93}
94
95/// `user_for_git_credentials`: the account password or an access token.
96#[derive(Debug, Serialize, Deserialize)]
97pub struct GitCredentialsArgs {
98 pub username: String,
99 pub secret: String,
100}
101
102/// `user_for_access_token`.
103#[derive(Debug, Serialize, Deserialize)]
104pub struct TokenArgs {
105 pub token: String,
106}
107
108/// `user_for_ssh_key`, and `principal_for_ssh_key` (see [`crate::deploy_keys`]).
109#[derive(Debug, Serialize, Deserialize)]
110pub struct FingerprintArgs {
111 pub fingerprint: String,
112}
113
114/// `user_by_username`.
115#[derive(Debug, Serialize, Deserialize)]
116pub struct UsernameArgs {
117 pub username: String,
118}
119
120/// `usernames`: the names behind account and workspace ids, as events and
121/// other records store them. Returns a map from id to name; ids it does
122/// not know are left out. Also `accounts`: the accounts behind user ids,
123/// each with its username and avatar (`HashMap<String, accounts::EmailOwner>`).
124#[derive(Debug, Serialize, Deserialize)]
125pub struct UsernamesArgs {
126 pub ids: Vec<String>,
127}
128
129/// `list_ssh_keys` and `list_access_tokens`.
130#[derive(Debug, Serialize, Deserialize)]
131pub struct UserArgs {
132 pub user: User,
133}
134
135/// `ssh_key_owners`: services only. The account (user id) that registered
136/// each key, by fingerprint (`SHA256:…`, as `ssh-keygen -lf` prints it),
137/// for verifying commits signed with SSH keys. Returns a map of the
138/// fingerprints found to user ids.
139#[derive(Debug, Serialize, Deserialize)]
140pub struct SshKeyOwnersArgs {
141 pub fingerprints: Vec<String>,
142}
143
144/// `add_ssh_key`: `public_key` is one line in OpenSSH format.
145/// Returns `Outcome<SshKey>`.
146#[derive(Debug, Serialize, Deserialize)]
147#[serde(rename_all = "camelCase")]
148pub struct AddSshKeyArgs {
149 pub user: User,
150 pub title: String,
151 pub public_key: String,
152}
153
154/// `remove_ssh_key` and `remove_access_token`.
155#[derive(Debug, Serialize, Deserialize)]
156pub struct RemoveArgs {
157 pub user: User,
158 pub id: String,
159}
160
161/// `create_access_token`: a token that acts as `user`. For a workspace
162/// acting through a token of its own, the new token belongs to that
163/// workspace too.
164#[derive(Debug, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase")]
166pub struct CreateAccessTokenArgs {
167 pub user: User,
168 pub name: String,
169 /// When set, the token stops working after this many seconds and is
170 /// left out of the user's token list, unless `listed`. Used for hosted
171 /// attempts.
172 #[serde(default)]
173 pub ttl_seconds: Option<u64>,
174 /// Its scopes, as `resource:level`; unknown names are left out. Null:
175 /// full access.
176 #[serde(default)]
177 pub scopes: Option<Vec<String>>,
178 /// Listed with the person's tokens although it expires: one they made
179 /// themselves, with an expiry.
180 #[serde(default)]
181 pub listed: bool,
182}
183
184/// `create_job_token`: a workflow job's `G1T_TOKEN`. It acts as the
185/// repository's workspace, reaches that repository only, holds `scopes`
186/// (from the job's `permissions`), and is never listed. The actions service
187/// revokes it when the job ends (`revoke_job_tokens`); `ttl_seconds` is a
188/// backstop. Returns `CreatedAccessToken`.
189#[derive(Debug, Serialize, Deserialize)]
190#[serde(rename_all = "camelCase")]
191pub struct CreateJobTokenArgs {
192 /// The workspace the repository belongs to, as its own principal.
193 pub workspace: User,
194 pub repo: crate::repos::RepoPath,
195 pub run_id: String,
196 pub job_id: String,
197 /// What the token is listed as in logs: `G1T_TOKEN for acme/web run 4`.
198 pub name: String,
199 pub ttl_seconds: u64,
200 /// As `resource:level`; unknown names are left out.
201 pub scopes: Vec<String>,
202 /// Whether it may open and approve pull requests (`JobToken::pull_requests`).
203 #[serde(default)]
204 pub pull_requests: bool,
205}
206
207/// `revoke_job_tokens`: ends a workflow job's tokens at once, when the job
208/// finishes or is cancelled. Only job tokens are touched. Returns `bool`.
209#[derive(Debug, Default, Serialize, Deserialize)]
210#[serde(rename_all = "camelCase")]
211pub struct RevokeJobTokensArgs {
212 pub job_id: String,
213}
214
215/// `update_access_token`: changes what one of a person's tokens may do.
216/// The token itself is unchanged. Returns `Outcome<AccessToken>`.
217#[derive(Debug, Serialize, Deserialize)]
218pub struct UpdateAccessTokenArgs {
219 pub user: User,
220 pub id: String,
221 /// Null: full access.
222 #[serde(default)]
223 pub scopes: Option<Vec<String>>,
224}
225
226/// The plaintext token is returned once and never stored.
227#[derive(Debug, Serialize, Deserialize)]
228pub struct CreatedAccessToken {
229 pub token: String,
230 pub info: AccessToken,
231}
232
233/// `register`: creates an account and signs it in.
234/// Returns `Outcome<SignedIn>`.
235///
236/// While registration is invite-only (`REGISTRATION_MODE=invite`), every
237/// new account needs `invite_code`: an unused, unexpired invite, and, when
238/// the invite names an email, that address. See [`CreateInviteArgs`].
239#[derive(Debug, Serialize, Deserialize)]
240pub struct RegisterArgs {
241 pub username: String,
242 pub email: String,
243 pub password: String,
244 /// An invite code such as `g1t-k7m2-q9xd-4hpw-…`. Ignored while
245 /// registration is open.
246 #[serde(default)]
247 pub invite_code: Option<String>,
248 /// Who is asking, such as the visitor's IP address, for rate limits.
249 #[serde(default)]
250 pub client: Option<String>,
251}
252
253/// `verify_email`: the token from the emailed link. Returns `Outcome<User>`.
254#[derive(Debug, Serialize, Deserialize)]
255pub struct EmailTokenArgs {
256 pub token: String,
257}
258
259/// `request_password_reset`. Always succeeds, so it cannot be used to find
260/// out which addresses have accounts. Any confirmed address of an account
261/// works: the link goes to the address given, and the primary (and the
262/// backup) are told a reset was asked for. A few requests an hour per
263/// address and per `client`; past that, nothing is sent.
264#[derive(Debug, Serialize, Deserialize)]
265pub struct EmailArgs {
266 pub email: String,
267 /// Who is asking, such as the visitor's IP address, for rate limits.
268 #[serde(default)]
269 pub client: Option<String>,
270}
271
272/// `reset_password`: sets a new password and ends every session.
273/// Returns `Outcome<User>`.
274#[derive(Debug, Serialize, Deserialize)]
275pub struct ResetPasswordArgs {
276 pub token: String,
277 pub password: String,
278}
279
280/// `device_start`: begins a device sign-in. Returns `DeviceStart`.
281#[derive(Debug, Serialize, Deserialize)]
282#[serde(rename_all = "camelCase")]
283pub struct DeviceStartArgs {
284 /// What is asking, shown to the person approving, e.g. "Claude Code".
285 pub client_name: String,
286}
287
288#[derive(Debug, Serialize, Deserialize)]
289#[serde(rename_all = "camelCase")]
290pub struct DeviceStart {
291 /// Secret held by the tool and exchanged for a token once approved.
292 pub device_code: String,
293 /// Short code shown to the person, e.g. `WDJB-MJHT`.
294 pub user_code: String,
295 /// Seconds until both codes stop working.
296 pub expires_in: u32,
297 /// Seconds the tool should wait between polls.
298 pub interval: u32,
299}
300
301/// `device_lookup`: what a user code is asking for, or null if it is not
302/// valid. Returns `Option<DeviceRequest>`.
303#[derive(Debug, Serialize, Deserialize)]
304#[serde(rename_all = "camelCase")]
305pub struct DeviceLookupArgs {
306 pub user_code: String,
307}
308
309#[derive(Debug, Serialize, Deserialize)]
310#[serde(rename_all = "camelCase")]
311pub struct DeviceRequest {
312 pub user_code: String,
313 pub client_name: String,
314}
315
316/// `device_resolve`: the signed-in person approves or denies a request.
317/// Returns `Outcome<bool>`.
318#[derive(Debug, Serialize, Deserialize)]
319#[serde(rename_all = "camelCase")]
320pub struct DeviceResolveArgs {
321 pub user_code: String,
322 pub user: User,
323 pub approve: bool,
324}
325
326/// `device_claim`: the tool asks whether its request was approved.
327#[derive(Debug, Serialize, Deserialize)]
328#[serde(rename_all = "camelCase")]
329pub struct DeviceClaimArgs {
330 pub device_code: String,
331}
332
333/// The answer to a `device_claim`.
334#[derive(Debug, Serialize, Deserialize)]
335#[serde(tag = "status", rename_all = "snake_case")]
336pub enum DeviceClaim {
337 /// Nobody has approved or denied it yet; ask again after the interval.
338 Pending,
339 Denied,
340 /// The code was never issued, has expired, or was already used.
341 Expired,
342 /// The access token, returned once.
343 Approved {
344 token: String,
345 user: User,
346 },
347}
348
349/// A workspace: the owner of repositories, and the first segment of their
350/// URLs. A person's own space and a team's are the same thing.
351#[derive(Clone, Debug, Serialize, Deserialize)]
352#[serde(rename_all = "camelCase")]
353pub struct Workspace {
354 pub id: String,
355 pub slug: String,
356 pub name: String,
357 /// One line saying what the workspace is for.
358 pub description: Option<String>,
359 /// RFC 3339.
360 pub created_at: String,
361 pub member_count: u32,
362 /// The workspace's uploaded icon: the SHA-256 of its bytes, served at
363 /// `/avatars/<avatar>`. Null means the generated letter avatar.
364 #[serde(default)]
365 pub avatar: Option<String>,
366 /// What every member gets on each of its repositories; owners have
367 /// Admin. See [`crate::access`].
368 #[serde(default)]
369 pub base_permission: crate::access::BasePermission,
370 /// Who may create its teams. See [`crate::teams::TeamCreation`].
371 #[serde(default)]
372 pub team_creation: crate::teams::TeamCreation,
373 /// What members may do, by GitHub's names for each
374 /// (`members_can_create_public_repositories`...), at the top level as
375 /// GitHub's organization has them. See [`crate::MemberPrivileges`].
376 #[serde(flatten)]
377 pub privileges: crate::MemberPrivileges,
378 /// Whether members and outside collaborators need two-factor
379 /// authentication to use it.
380 #[serde(default)]
381 pub two_factor_requirement_enabled: bool,
382}
383
384#[derive(Clone, Debug, Serialize, Deserialize)]
385pub struct Member {
386 pub username: String,
387 pub role: crate::Role,
388 /// The roles they hold besides `role`.
389 #[serde(default)]
390 pub org_roles: Vec<crate::OrgRole>,
391 /// Whether they have two-factor authentication on. Shown to owners
392 /// only; null for anyone else.
393 #[serde(default)]
394 pub two_factor: Option<bool>,
395 /// Their display name, when they set one.
396 #[serde(default)]
397 pub name: Option<String>,
398 /// Their uploaded avatar: the SHA-256 of its bytes, served at
399 /// `/avatars/<avatar>`. None means the generated letter avatar.
400 #[serde(default)]
401 pub avatar: Option<String>,
402}
403
404/// Where a workspace keeps its repositories' git data: anywhere g1t
405/// stores it (the default), or in the EU only. It applies to repositories
406/// made after it is set; the repos service reads it when it places a new
407/// one (`storage_options` says whether the EU can be chosen).
408#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
409#[serde(rename_all = "lowercase")]
410pub enum DataResidency {
411 #[default]
412 Anywhere,
413 Eu,
414}
415
416impl DataResidency {
417 pub fn as_str(self) -> &'static str {
418 match self {
419 DataResidency::Anywhere => "anywhere",
420 DataResidency::Eu => "eu",
421 }
422 }
423
424 pub fn parse(text: &str) -> Option<Self> {
425 match text.trim().to_ascii_lowercase().as_str() {
426 "anywhere" => Some(DataResidency::Anywhere),
427 "eu" => Some(DataResidency::Eu),
428 _ => None,
429 }
430 }
431}
432
433/// `workspace_residency` takes [`SlugArgs`] and returns
434/// `Option<DataResidency>` (null when there is no such workspace).
435/// `set_workspace_residency`: owners only. Returns `Outcome<DataResidency>`.
436#[derive(Debug, Serialize, Deserialize)]
437pub struct SetResidencyArgs {
438 pub actor: User,
439 pub slug: String,
440 pub residency: DataResidency,
441}
442
443/// `create_workspace`. Returns `Outcome<Workspace>`.
444#[derive(Debug, Serialize, Deserialize)]
445pub struct CreateWorkspaceArgs {
446 pub user: User,
447 pub slug: String,
448 #[serde(default)]
449 pub name: String,
450}
451
452/// `get_workspace`: public details, or null. Returns `Option<Workspace>`.
453#[derive(Debug, Serialize, Deserialize)]
454pub struct SlugArgs {
455 pub slug: String,
456}
457
458/// `list_members`: members only. Owners also see each member's
459/// `two_factor`. Returns `Outcome<Vec<Member>>`.
460#[derive(Debug, Serialize, Deserialize)]
461pub struct ListMembersArgs {
462 pub slug: String,
463 pub viewer: crate::Viewer,
464}
465
466/// `add_member` and `remove_member`: owners only. Removing yourself is
467/// leaving (`members::LeaveWorkspaceArgs`); removing an owner is refused
468/// when they are the last. Each returns `Outcome<bool>`.
469#[derive(Debug, Serialize, Deserialize)]
470pub struct MemberArgs {
471 pub actor: User,
472 pub slug: String,
473 pub username: String,
474 #[serde(default)]
475 pub surface: Option<crate::audit::Surface>,
476}
477
478/// `update_workspace`: owners only. An empty name falls back to the slug;
479/// an empty description clears it. Returns `Outcome<Workspace>`.
480#[derive(Debug, Serialize, Deserialize)]
481pub struct UpdateWorkspaceArgs {
482 pub actor: User,
483 pub slug: String,
484 pub name: String,
485 pub description: String,
486}
487
488/// `rename_workspace`: owners only. Changes the workspace's slug, the first
489/// segment of its URLs, to `new_slug`; the display name is untouched. The
490/// old slug redirects to the new one, and is held for this workspace, for
491/// [`SLUG_HOLD_DAYS`]. Publishes `workspace.renamed`. Returns
492/// `Outcome<Workspace>`.
493///
494/// `check_workspace_rename` takes the same arguments and answers whether
495/// the rename would be allowed, changing nothing. Returns `Outcome<bool>`.
496#[derive(Debug, Serialize, Deserialize)]
497#[serde(rename_all = "camelCase")]
498pub struct RenameWorkspaceArgs {
499 pub actor: User,
500 pub slug: String,
501 pub new_slug: String,
502}
503
504/// `delete_workspace`: owners only, and only a person. `confirm` must be
505/// the workspace's slug, typed out. Refused for a protected workspace
506/// ([`protected_names`]), whoever asks, and while billing cannot settle it
507/// (`close_workspace`). Everything in it goes with it at once: nobody can
508/// reach it, its tokens stop working, its pages are not found, and its
509/// repositories, projects and apps are deleted with it. It is kept for
510/// [`WORKSPACE_RESTORE_DAYS`] so g1t's staff can restore it, then purged:
511/// its memberships, access tokens and old-slug redirects go, and billing's
512/// ledger and the audit log keep its history. The slug is never given to
513/// another workspace; the person whose username it is may make a workspace
514/// of that name again once it is purged. Publishes `workspace.deleting`,
515/// and `workspace.deleted` at the purge. Returns `Outcome<bool>`.
516///
517/// `check_workspace_deletion` takes the same arguments (with `confirm`
518/// ignored) and says what would go and whether anything stands in the way,
519/// changing nothing. Returns `Outcome<WorkspaceDeletion>`.
520#[derive(Debug, Serialize, Deserialize)]
521pub struct DeleteWorkspaceArgs {
522 pub actor: User,
523 pub slug: String,
524 #[serde(default)]
525 pub confirm: String,
526 /// Where the request came in, for the audit log; g1t.sh when absent.
527 #[serde(default)]
528 pub surface: Option<crate::audit::Surface>,
529}
530
531/// What deleting a workspace takes with it, and what stands in the way.
532/// Nothing does when `billing` is null and it is not `protected`.
533#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
534pub struct WorkspaceDeletion {
535 /// Its live repositories, which are deleted with it.
536 pub repositories: u32,
537 /// Its projects, hidden with it.
538 pub projects: u32,
539 #[serde(default)]
540 pub members: u32,
541 /// Why billing cannot close the workspace yet, in words for its owner.
542 pub billing: Option<String>,
543 /// It can never be deleted, by anyone ([`protected_names`]).
544 #[serde(default)]
545 pub protected: bool,
546}
547
548impl WorkspaceDeletion {
549 pub fn blocked(&self) -> bool {
550 self.protected || self.billing.is_some()
551 }
552
553 /// Why the workspace cannot be deleted, as one sentence, or `None`.
554 pub fn reason(&self, slug: &str) -> Option<String> {
555 if self.protected {
556 return Some(protected_refusal(slug));
557 }
558 self.billing.clone()
559 }
560}
561
562/// How long a deleted workspace is kept, for staff to restore, before it is
563/// purged.
564pub const WORKSPACE_RESTORE_DAYS: u64 = 30;
565
566/// Workspaces nobody can delete, whatever identity's `PROTECTED_WORKSPACES`
567/// says: Flagon's, which runs g1t.
568pub const ALWAYS_PROTECTED: &[&str] = &["flagon-io"];
569
570/// The protected workspaces: `configured` (comma-separated slugs or
571/// workspace ids, as identity's `PROTECTED_WORKSPACES` holds them), and
572/// [`ALWAYS_PROTECTED`] whatever it says, so an empty or missing variable
573/// still protects them. Lowercased, without duplicates.
574pub fn protected_names(configured: Option<&str>) -> Vec<String> {
575 let mut names: Vec<String> = Vec::new();
576 let given = configured.unwrap_or_default().split(',');
577 for name in ALWAYS_PROTECTED.iter().copied().chain(given) {
578 let name = name.trim().to_lowercase();
579 if !name.is_empty() && !names.contains(&name) {
580 names.push(name);
581 }
582 }
583 names
584}
585
586/// Why a protected workspace is not deleted, purged or acted on.
587pub fn protected_refusal(slug: &str) -> String {
588 format!("{slug} is protected and can never be deleted.")
589}
590
591/// `admin_deleted_workspaces` takes no arguments (`{}`) and returns
592/// `Vec<DeletedWorkspace>`, newest first. Staff only.
593///
594/// A workspace an owner deleted, kept until `purge_after` for staff to
595/// restore.
596#[derive(Clone, Debug, Serialize, Deserialize)]
597#[serde(rename_all = "camelCase")]
598pub struct DeletedWorkspace {
599 pub workspace_id: String,
600 pub slug: String,
601 pub name: String,
602 /// RFC 3339.
603 pub deleted_at: String,
604 /// The username of the owner who deleted it.
605 pub deleted_by: String,
606 /// RFC 3339: when it is purged unless restored first.
607 pub purge_after: String,
608 /// What went with it, counted when it was deleted.
609 pub went: WorkspaceDeletion,
610 /// Whether staff can still restore it.
611 pub restorable: bool,
612}
613
614/// `admin_restore_workspace` and `admin_purge_workspace`: staff restore a
615/// deleted workspace within [`WORKSPACE_RESTORE_DAYS`], or purge it now.
616/// `staff` is who, for the audit logs. Purging needs `confirm`, the slug
617/// typed out, and is refused for a protected workspace. Restoring publishes
618/// `workspace.restored`; purging, `workspace.deleted`. Both return
619/// `Outcome<bool>`.
620#[derive(Debug, Serialize, Deserialize)]
621#[serde(rename_all = "camelCase")]
622pub struct AdminDeletedWorkspaceArgs {
623 pub workspace_id: String,
624 pub staff: String,
625 #[serde(default)]
626 pub confirm: String,
627}
628
629/// `transfer_repo_scopes`: a repository moved from `from` to `to`; the
630/// tokens of agents at work on it are kept pointing at it. For repos'
631/// `transfer`. Returns `bool`.
632#[derive(Debug, Serialize, Deserialize)]
633pub struct TransferRepoScopesArgs {
634 pub from: crate::repos::RepoPath,
635 pub to: crate::repos::RepoPath,
636}
637
638/// How long a workspace's old slug keeps redirecting to it, and stays
639/// reserved for it, after a rename.
640pub const SLUG_HOLD_DAYS: u64 = 90;
641
642/// How long a workspace must wait between renames.
643pub const RENAME_COOLDOWN_HOURS: u64 = 24;
644
645// `resolve_slug` takes `SlugArgs` and returns `Option<String>`: the
646// workspace's current slug when `slug` is one it was renamed from within
647// the last `SLUG_HOLD_DAYS`, and null otherwise (including for a slug that
648// is in use), or the workspace's slug when `slug` is one of its aliases.
649
650// `resolve_alias` takes `SlugArgs` and returns `Option<String>`: the slug
651// now of the workspace `slug` is an alias of, and null when it is none.
652// Aliases are set by g1t's staff only: `g1t` is Flagon, Inc.'s `flagon-io`.
653// An alias follows its workspace through renames.
654
655/// `admin_aliases` takes no arguments (`{}`) and returns
656/// `Vec<WorkspaceAlias>`, by alias. Staff only.
657///
658/// A name staff point at a workspace, so that its addresses (pages, git,
659/// the API, packages) lead to the workspace under its own name.
660#[derive(Clone, Debug, Serialize, Deserialize)]
661#[serde(rename_all = "camelCase")]
662pub struct WorkspaceAlias {
663 pub alias: String,
664 pub workspace_id: String,
665 /// The workspace's slug and name now.
666 pub workspace: String,
667 pub workspace_name: String,
668 /// Why it exists, as staff wrote it.
669 pub note: String,
670 /// The staff member who set it, or `migration`.
671 pub created_by: String,
672 /// RFC 3339.
673 pub created_at: String,
674}
675
676/// `admin_set_alias`: points `alias` at the workspace whose slug is
677/// `workspace`. The alias must have a namespace's shape, must not be one of
678/// the site's routes, and must not be anyone's username, a workspace's slug
679/// (deleted, or held after a rename) or another alias. `note` is required:
680/// it is the reason, kept with the alias and in sudo's audit log. Staff
681/// only. Returns `Outcome<WorkspaceAlias>`.
682#[derive(Debug, Serialize, Deserialize)]
683#[serde(rename_all = "camelCase")]
684pub struct AdminSetAliasArgs {
685 pub alias: String,
686 pub workspace: String,
687 pub note: String,
688 pub staff: String,
689}
690
691/// `admin_remove_alias`: the alias stops leading anywhere, and the name is
692/// nobody's again unless it is reserved. `reason` goes in sudo's audit log.
693/// Staff only. Returns `Outcome<bool>`.
694#[derive(Debug, Serialize, Deserialize)]
695#[serde(rename_all = "camelCase")]
696pub struct AdminRemoveAliasArgs {
697 pub alias: String,
698 pub reason: String,
699 pub staff: String,
700}
701
702/// `set_workspace_avatar`: owners only. `image` is the file's bytes in
703/// base64: PNG, JPEG, WebP or GIF, at most `MAX_AVATAR_BYTES`. Null removes
704/// the icon. Returns `Outcome<Workspace>`.
705#[derive(Debug, Serialize, Deserialize)]
706pub struct SetWorkspaceAvatarArgs {
707 pub actor: User,
708 pub slug: String,
709 pub image: Option<String>,
710}
711
712/// `set_user_avatar`: a person's own avatar, as `SetWorkspaceAvatarArgs`.
713/// Returns `Outcome<Option<String>>`: the new avatar, or null once removed.
714#[derive(Debug, Serialize, Deserialize)]
715pub struct SetUserAvatarArgs {
716 pub user: User,
717 pub image: Option<String>,
718}
719
720/// The largest avatar that can be uploaded, in bytes.
721pub const MAX_AVATAR_BYTES: usize = 1024 * 1024;
722
723/// `list_workspace_tokens`: members only. Returns
724/// `Outcome<Vec<AccessToken>>`.
725#[derive(Debug, Serialize, Deserialize)]
726pub struct WorkspaceTokensArgs {
727 pub slug: String,
728 pub viewer: crate::Viewer,
729}
730
731/// `create_workspace_token`: owners only. The token belongs to the
732/// workspace, acts as it, and keeps working when the member who made it
733/// leaves. Returns `Outcome<CreatedAccessToken>`.
734#[derive(Debug, Serialize, Deserialize)]
735pub struct CreateWorkspaceTokenArgs {
736 pub actor: User,
737 pub slug: String,
738 pub name: String,
739 /// Its scopes; null for full access.
740 #[serde(default)]
741 pub scopes: Option<Vec<String>>,
742 /// When set, the token stops working after this many seconds. It is
743 /// listed with the workspace's tokens either way. Null: no expiry.
744 #[serde(default)]
745 pub ttl_seconds: Option<u64>,
746 /// Admin on the workspace's repositories, rather than Write: given by
747 /// the owner on purpose, when making it.
748 #[serde(default)]
749 pub admin: bool,
750}
751
752/// `remove_workspace_token`: owners only. Returns `Outcome<bool>`.
753#[derive(Debug, Serialize, Deserialize)]
754pub struct RemoveWorkspaceTokenArgs {
755 pub actor: User,
756 pub slug: String,
757 pub id: String,
758}
759
760/// `oauth_authorize`: the signed-in person approved an application. The
761/// caller has checked the client and that it may be redirected to
762/// `redirect_uri`. Returns `OAuthCode`.
763#[derive(Debug, Serialize, Deserialize)]
764#[serde(rename_all = "camelCase")]
765pub struct OAuthAuthorizeArgs {
766 pub user: User,
767 pub client_id: String,
768 /// Shown wherever the application's access is listed.
769 pub client_name: String,
770 pub redirect_uri: String,
771 /// PKCE challenge, method S256.
772 pub code_challenge: String,
773 /// What the person granted, as `resource:level`. Null: full access.
774 #[serde(default)]
775 pub scopes: Option<Vec<String>>,
776}
777
778#[derive(Debug, Serialize, Deserialize)]
779pub struct OAuthCode {
780 pub code: String,
781}
782
783/// `oauth_exchange`: redeems an authorization code.
784/// Returns `Outcome<OAuthTokens>`.
785#[derive(Debug, Serialize, Deserialize)]
786#[serde(rename_all = "camelCase")]
787pub struct OAuthExchangeArgs {
788 pub code: String,
789 pub code_verifier: String,
790 pub client_id: String,
791 pub redirect_uri: String,
792}
793
794/// `oauth_refresh`: trades a refresh token for new tokens.
795/// Returns `Outcome<OAuthTokens>`.
796#[derive(Debug, Serialize, Deserialize)]
797#[serde(rename_all = "camelCase")]
798pub struct OAuthRefreshArgs {
799 pub refresh_token: String,
800 pub client_id: String,
801}
802
803#[derive(Debug, Serialize, Deserialize)]
804#[serde(rename_all = "camelCase")]
805pub struct OAuthTokens {
806 pub access_token: String,
807 /// Works once; using it returns the next one.
808 pub refresh_token: String,
809 /// Seconds until the access token stops working.
810 pub expires_in: u64,
811 /// The scopes granted, space-separated, or `*` for full access.
812 #[serde(default)]
813 pub scope: Option<String>,
814}
815
816/// An application a person has signed in to. Listed by `list_oauth_grants`
817/// and ended by `revoke_oauth_grant`.
818#[derive(Debug, Serialize, Deserialize)]
819#[serde(rename_all = "camelCase")]
820pub struct OAuthGrant {
821 pub id: String,
822 pub client_name: String,
823 /// RFC 3339.
824 pub created_at: String,
825 /// RFC 3339.
826 pub last_used_at: String,
827 /// What the person granted. Null: full access.
828 #[serde(default)]
829 pub scopes: Option<Vec<String>>,
830 /// Signed in before applications were given scopes: full access until
831 /// someone narrows it.
832 #[serde(default)]
833 pub legacy: bool,
834}
835
836/// `update_oauth_grant`: changes what an application the person signed in
837/// to may do, at once and when it refreshes. Returns `Outcome<OAuthGrant>`.
838#[derive(Debug, Serialize, Deserialize)]
839pub struct UpdateOAuthGrantArgs {
840 pub user: User,
841 pub id: String,
842 #[serde(default)]
843 pub scopes: Option<Vec<String>>,
844}
845
846
847/// What an agent's token may do: these operations, in this repository.
848#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
849pub struct AgentScope {
850 pub repo: crate::repos::RepoPath,
851 /// API and MCP operation names, such as `create_issue`.
852 pub operations: Vec<String>,
853 /// Set on a run credential: the run it belongs to, and what it may do
854 /// with git. See [`crate::credentials`].
855 #[serde(default, skip_serializing_if = "Option::is_none")]
856 pub run: Option<crate::credentials::RunBinding>,
857}
858
859/// `create_agent_token`: a token for a g1t agent working on someone's
860/// behalf. It acts as `g1t`, a member of the repository's workspace,
861/// and only for the operations in `scope`. Returns `CreatedAccessToken`.
862#[derive(Debug, Serialize, Deserialize)]
863#[serde(rename_all = "camelCase")]
864pub struct CreateAgentTokenArgs {
865 /// The person the agent works for; the token is recorded as theirs.
866 pub on_behalf_of: User,
867 pub scope: AgentScope,
868 pub ttl_seconds: u64,
869}
870
871// `agent_scope` takes `TokenArgs` and returns `Option<AgentScope>`: what an
872// agent's token may do, or null for any other token.
873
874/// The id g1t's agent acts under. Only ever stored, never shown: it keeps
875/// the agent's work apart from g1t's own ([`crate::system::ID`]) where
876/// that matters, such as whether its approval counts.
877pub const AGENT_ID: &str = "usr_g1t_agent";
878/// The name g1t's agent is shown by: g1t's own, [`crate::system::USERNAME`].
879/// Everything it does, people see g1t do.
880pub const AGENT_NAME: &str = crate::system::USERNAME;
881
882// --- Staff ---------------------------------------------------------------
883//
884// Staff-only methods, for sudo.g1t.sh. They take no viewer and check no
885// membership: only sudo calls them, over its service binding, after it has
886// verified a Cloudflare Access sign-in and its staff list. Nothing a
887// customer can reach should ever forward to them.
888
889/// `notify_owners`: emails a short notice, with one link, to each owner of
890/// a workspace with a confirmed address. Called by other services (billing
891/// warns owners near their usage limit), never on a person's behalf.
892/// Returns how many were sent.
893#[derive(Clone, Debug, Serialize, Deserialize)]
894pub struct NotifyOwnersArgs {
895 pub workspace: String,
896 pub subject: String,
897 /// One or two sentences: what happened and what it means.
898 pub intro: String,
899 /// The button's words, such as `Open billing`.
900 pub action: String,
901 /// Where the button goes; must be on g1t.sh.
902 pub link: String,
903 /// Small print: why they got it.
904 pub footer: String,
905}
906
907/// `admin_workspaces`: every workspace, newest first, at most
908/// [`ADMIN_WORKSPACES_LIMIT`], optionally only those whose slug, name or
909/// an owner's username or email contains `query`. Returns
910/// `Vec<AdminWorkspace>`. Staff only.
911#[derive(Debug, Default, Serialize, Deserialize)]
912pub struct AdminWorkspacesArgs {
913 #[serde(default)]
914 pub query: Option<String>,
915}
916
917/// The most workspaces one `admin_workspaces` call returns.
918pub const ADMIN_WORKSPACES_LIMIT: usize = 500;
919
920/// An owner of a workspace, as staff see them.
921#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
922pub struct AdminOwner {
923 pub username: String,
924 pub email: Option<String>,
925}
926
927/// A workspace as staff see it: who owns it and how many belong to it.
928#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
929#[serde(rename_all = "camelCase")]
930pub struct AdminWorkspace {
931 pub slug: String,
932 pub name: String,
933 /// RFC 3339.
934 pub created_at: String,
935 pub owners: Vec<AdminOwner>,
936 pub member_count: u32,
937}
938
939/// `admin_workspace`: one workspace with every member, or null. Takes
940/// `SlugArgs`; returns `Option<AdminWorkspaceDetail>`. Staff only.
941#[derive(Clone, Debug, Serialize, Deserialize)]
942#[serde(rename_all = "camelCase")]
943pub struct AdminWorkspaceDetail {
944 pub slug: String,
945 pub name: String,
946 pub description: Option<String>,
947 /// RFC 3339.
948 pub created_at: String,
949 /// Owners first, then by username.
950 pub members: Vec<AdminMember>,
951 /// It can never be deleted ([`protected_names`]).
952 #[serde(default)]
953 pub protected: bool,
954}
955
956/// A member of a workspace, as staff see them.
957#[derive(Clone, Debug, Serialize, Deserialize)]
958pub struct AdminMember {
959 pub username: String,
960 pub email: Option<String>,
961 pub role: crate::Role,
962 /// When they joined the workspace. RFC 3339.
963 pub joined: String,
964}
965
966// --- Profiles ------------------------------------------------------------
967//
968// A person's public page at `g1t.sh/u/<username>`. Everything in a
969// `Profile` is shown to anyone, signed in or not; an email address never is.
970
971/// The most characters each profile field takes.
972pub const MAX_PROFILE_NAME: usize = 80;
973pub const MAX_PROFILE_BIO: usize = 160;
974pub const MAX_PROFILE_LOCATION: usize = 80;
975pub const MAX_PROFILE_WEBSITE: usize = 200;
976pub const MAX_PROFILE_PRONOUNS: usize = 40;
977
978/// What anyone may see about a person.
979#[derive(Clone, Debug, Default, Serialize, Deserialize)]
980#[serde(rename_all = "camelCase")]
981pub struct Profile {
982 pub username: String,
983 /// The name they go by, if they gave one.
984 pub name: Option<String>,
985 /// One or two lines about them, at most [`MAX_PROFILE_BIO`] characters.
986 pub bio: Option<String>,
987 pub location: Option<String>,
988 /// An `https://` address.
989 pub website: Option<String>,
990 pub pronouns: Option<String>,
991 /// The uploaded avatar's hash, served at `/avatars/<avatar>`.
992 pub avatar: Option<String>,
993 /// When the account was made. RFC 3339.
994 pub created_at: String,
995}
996
997// `profile` takes `UsernameArgs` and returns `Option<Profile>`: null for
998// an account that does not exist.
999
1000/// `update_profile`: a person changes their own profile. Every field is
1001/// replaced; an empty one is cleared. Returns `Outcome<Profile>`.
1002#[derive(Debug, Default, Serialize, Deserialize)]
1003#[serde(rename_all = "camelCase")]
1004pub struct UpdateProfileArgs {
1005 pub actor: User,
1006 #[serde(default)]
1007 pub name: String,
1008 #[serde(default)]
1009 pub bio: String,
1010 #[serde(default)]
1011 pub location: String,
1012 #[serde(default)]
1013 pub website: String,
1014 #[serde(default)]
1015 pub pronouns: String,
1016}
1017
1018/// `profile_workspaces`: the workspaces shown on a person's profile, as
1019/// `viewer` may see them. A membership is shown only when it is no secret
1020/// from the viewer: a workspace the viewer belongs to as well, or one of
1021/// `public`, the workspaces the caller found the person has made a public
1022/// project in (whose page shows that already). Returns
1023/// `Vec<ProfileWorkspace>`; empty for an account that does not exist.
1024#[derive(Debug, Serialize, Deserialize)]
1025pub struct ProfileWorkspacesArgs {
1026 pub username: String,
1027 pub viewer: crate::Viewer,
1028 #[serde(default)]
1029 pub public: Vec<String>,
1030}
1031
1032/// A workspace on a person's profile.
1033#[derive(Clone, Debug, Serialize, Deserialize)]
1034pub struct ProfileWorkspace {
1035 pub slug: String,
1036 pub name: String,
1037 pub avatar: Option<String>,
1038}
1039
1040/// `directory`: every account or every workspace, as their public pages
1041/// show them, a page at a time in name order. For services that index
1042/// them, such as search; nothing private is in it. Returns
1043/// `DirectoryPage`.
1044#[derive(Debug, Default, Serialize, Deserialize)]
1045pub struct DirectoryArgs {
1046 /// `user` or `workspace`.
1047 pub kind: String,
1048 /// Names after this one.
1049 #[serde(default)]
1050 pub after: Option<String>,
1051 pub limit: u32,
1052}
1053
1054/// One account or workspace in the directory.
1055#[derive(Clone, Debug, Serialize, Deserialize)]
1056#[serde(rename_all = "camelCase")]
1057pub struct DirectoryEntry {
1058 /// The account's or workspace's id.
1059 pub id: String,
1060 /// A username or a workspace's slug.
1061 pub slug: String,
1062 /// A person's display name or a workspace's name.
1063 pub name: Option<String>,
1064 /// A person's bio or a workspace's description.
1065 pub bio: Option<String>,
1066 pub avatar: Option<String>,
1067 /// RFC 3339.
1068 pub created_at: String,
1069}
1070
1071#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1072pub struct DirectoryPage {
1073 pub entries: Vec<DirectoryEntry>,
1074 /// Where the next page starts; null on the last.
1075 pub next: Option<String>,
1076}
1077
1078// --- Invites ---------------------------------------------------------------
1079//
1080// While registration is invite-only, every new account (with a password or
1081// through GitHub) needs an invite code. Each person may have
1082// `INVITES_PER_USER` invites out at a time; staff grant more to a person or
1083// to a workspace, whose owners share them. Inviting an email with no
1084// account into a workspace makes an invite bound to that address, which
1085// registers and joins in one step. See services/identity/src/invites.rs.
1086
1087/// Whether anyone may make an account, or only someone with an invite. Set
1088/// by identity's `REGISTRATION_MODE` var; anything but `open`, including
1089/// leaving it unset, is `invite`, so a missing setting never opens sign-up.
1090#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1091#[serde(rename_all = "snake_case")]
1092pub enum RegistrationMode {
1093 #[default]
1094 Invite,
1095 Open,
1096}
1097
1098impl RegistrationMode {
1099 pub fn parse(text: Option<&str>) -> RegistrationMode {
1100 match text.map(|text| text.trim().to_ascii_lowercase()).as_deref() {
1101 Some("open") => RegistrationMode::Open,
1102 _ => RegistrationMode::Invite,
1103 }
1104 }
1105}
1106
1107/// How many invites a person may have out at once, unless identity's
1108/// `INVITES_PER_USER` var says otherwise.
1109pub const INVITES_PER_USER: u32 = 5;
1110
1111/// How long an invite works, unless identity's `INVITE_TTL_DAYS` var says
1112/// otherwise.
1113pub const INVITE_TTL_DAYS: u64 = 30;
1114
1115/// Where an invite stands. Only a pending invite can be used or revoked.
1116/// An expired or revoked invite that was never used gives its inviter the
1117/// invite back.
1118#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1119#[serde(rename_all = "snake_case")]
1120pub enum InviteStatus {
1121 Pending,
1122 Redeemed,
1123 Expired,
1124 Revoked,
1125}
1126
1127/// What using an invite does.
1128#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1129#[serde(rename_all = "snake_case")]
1130pub enum InviteKind {
1131 /// Makes a new account, and joins `workspace` when one is set.
1132 Account,
1133 /// An existing account joins `workspace`. Never makes an account.
1134 Workspace,
1135}
1136
1137/// Whose allowance an invite uses.
1138#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1139#[serde(rename_all = "snake_case")]
1140pub enum InviteCharge {
1141 /// Its inviter's own.
1142 User,
1143 /// The workspace's, granted by staff and shared by its owners.
1144 Workspace,
1145 /// Nobody's: staff minted it, or it invites an existing account.
1146 None,
1147}
1148
1149/// One invite, as the person who made it sees it.
1150#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1151#[serde(rename_all = "camelCase")]
1152pub struct Invite {
1153 pub id: String,
1154 /// The code, such as `g1t-k7m2-q9xd-…`: returned once when the invite
1155 /// is made, and afterwards to whoever made it while it is pending.
1156 /// Null otherwise.
1157 pub code: Option<String>,
1158 /// The code's first group, such as `g1t-k7m2`, to recognise it by.
1159 pub hint: String,
1160 /// Only an account with this address can use it. Null: anyone with
1161 /// the code.
1162 pub email: Option<String>,
1163 pub kind: InviteKind,
1164 /// The workspace it joins, by slug.
1165 pub workspace: Option<String>,
1166 pub status: InviteStatus,
1167 pub charged_to: InviteCharge,
1168 /// Who made it, by username. Null when g1t staff did.
1169 pub invited_by: Option<String>,
1170 /// The account that used it, by username.
1171 pub redeemed_by: Option<String>,
1172 /// RFC 3339.
1173 pub created_at: String,
1174 /// RFC 3339.
1175 pub expires_at: String,
1176 /// RFC 3339.
1177 pub redeemed_at: Option<String>,
1178 /// RFC 3339.
1179 pub revoked_at: Option<String>,
1180 /// The staff member who minted it. Only in staff views.
1181 #[serde(default, skip_serializing_if = "Option::is_none")]
1182 pub staff: Option<String>,
1183}
1184
1185/// How many invites someone may have out, and how many they have.
1186#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1187pub struct Allowance {
1188 /// Null: no limit.
1189 pub limit: Option<u32>,
1190 /// Pending and used invites; revoked and expired ones are not counted.
1191 pub used: u32,
1192 /// Null: no limit.
1193 pub remaining: Option<u32>,
1194}
1195
1196impl Allowance {
1197 pub fn new(limit: Option<u32>, used: u32) -> Allowance {
1198 Allowance {
1199 limit,
1200 used,
1201 remaining: limit.map(|limit| limit.saturating_sub(used)),
1202 }
1203 }
1204
1205 pub fn exhausted(&self) -> bool {
1206 self.remaining == Some(0)
1207 }
1208}
1209
1210/// A workspace's shared invites, for one of its owners.
1211#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1212pub struct WorkspaceAllowance {
1213 pub slug: String,
1214 pub allowance: Allowance,
1215}
1216
1217/// `list_invites` (takes `UserArgs`): a person's invites, newest first,
1218/// and what they have left. Returns `InvitesOverview`.
1219#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1220pub struct InvitesOverview {
1221 pub mode: RegistrationMode,
1222 pub allowance: Allowance,
1223 /// Workspaces the person owns that staff granted invites to.
1224 pub workspaces: Vec<WorkspaceAllowance>,
1225 pub invites: Vec<Invite>,
1226}
1227
1228/// `create_invite`: a person makes an invite, optionally for one email
1229/// address. People only; never an agent or a workspace's token, and not
1230/// before their email is confirmed. Uses one of the person's invites, or,
1231/// with `workspace`, one of the invites staff granted that workspace (its
1232/// owners only). Emails the address when one is given. Returns
1233/// `Outcome<Invite>`, with the code.
1234///
1235/// `revoke_invite` (takes `RemoveArgs`): its maker revokes a pending
1236/// invite; a workspace's owners may revoke one made for the workspace.
1237/// The invite comes back to whoever it was charged to. Returns
1238/// `Outcome<Invite>`.
1239#[derive(Debug, Serialize, Deserialize)]
1240pub struct CreateInviteArgs {
1241 pub user: User,
1242 #[serde(default)]
1243 pub email: Option<String>,
1244 /// Use this workspace's granted invites, by slug.
1245 #[serde(default)]
1246 pub workspace: Option<String>,
1247 /// Where the request came in, for the audit log; g1t.sh when absent.
1248 #[serde(default)]
1249 pub surface: Option<crate::audit::Surface>,
1250}
1251
1252/// `check_invite`: what an invite code is for, before using it. Returns
1253/// `Outcome<InvitePreview>`; a code that is unknown, used, revoked or
1254/// expired gets the same answer, so codes cannot be probed. With
1255/// `any_status`, a real code that can no longer be used is described
1256/// instead (its `status` says why), so the page can say whom to ask for a
1257/// new one; an unknown code still gets the one answer.
1258#[derive(Debug, Serialize, Deserialize)]
1259pub struct InviteCodeArgs {
1260 pub code: String,
1261 /// Who is asking, such as the visitor's IP address, for rate limits.
1262 #[serde(default)]
1263 pub client: Option<String>,
1264 /// Who is looking, if signed in: sets `InvitePreview::for_viewer`.
1265 #[serde(default)]
1266 pub viewer: Option<User>,
1267 #[serde(default)]
1268 pub any_status: bool,
1269}
1270
1271/// Someone shown on an invite.
1272#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1273pub struct InviteFrom {
1274 pub username: String,
1275 pub name: Option<String>,
1276 pub avatar: Option<String>,
1277}
1278
1279/// A repository an invite code was sent with: using the code accepts the
1280/// invitation to collaborate on it.
1281#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1282pub struct InviteRepository {
1283 /// `workspace/repo`.
1284 pub name: String,
1285 /// The role it gives, such as `write`.
1286 pub role: String,
1287}
1288
1289/// What a valid invite code is for.
1290#[derive(Clone, Debug, Serialize, Deserialize)]
1291#[serde(rename_all = "camelCase")]
1292pub struct InvitePreview {
1293 pub kind: InviteKind,
1294 /// Pending, unless `any_status` asked about a code that is spent.
1295 pub status: InviteStatus,
1296 /// Null when g1t staff sent it.
1297 pub invited_by: Option<InviteFrom>,
1298 pub workspace: Option<ProfileWorkspace>,
1299 /// The repository it accepts an invitation to, if it was sent with one.
1300 pub repository: Option<InviteRepository>,
1301 /// The address it is for, partly hidden, such as `a•••@example.com`.
1302 pub email: Option<String>,
1303 /// The address in full, while it is pending: whoever holds the code
1304 /// was sent it there. Fills in and locks the sign-up form.
1305 pub address: Option<String>,
1306 /// Whether the address it is for has a g1t account already, so the
1307 /// page asks them to sign in rather than sign up.
1308 pub has_account: bool,
1309 /// With a viewer: whether the invite is theirs (it is for one of their
1310 /// confirmed addresses, or they used it). Null without a viewer or,
1311 /// for a pending invite, when it is for anyone with the code.
1312 pub for_viewer: Option<bool>,
1313 /// RFC 3339.
1314 pub expires_at: String,
1315}
1316
1317/// `accept_invite`: a signed-in person uses a workspace invite made for
1318/// their confirmed address, and joins the workspace, or an invite sent with
1319/// a repository invitation, and accepts it. Returns `Outcome<String>`: the
1320/// workspace's slug, or `workspace/repo`.
1321#[derive(Debug, Serialize, Deserialize)]
1322pub struct AcceptInviteArgs {
1323 pub user: User,
1324 pub code: String,
1325}
1326
1327/// `invite_member`: an owner invites an email address into a workspace.
1328/// It always makes an invite bound to that address and emails it, so the
1329/// answer never says whether the address has an account. Without one, the
1330/// invite registers and joins in one step, and uses one of the workspace's
1331/// granted invites or else one of the owner's own. With one, it costs
1332/// nothing. Returns `Outcome<Invite>`, with the code.
1333#[derive(Debug, Serialize, Deserialize)]
1334pub struct InviteMemberArgs {
1335 pub actor: User,
1336 pub slug: String,
1337 pub email: String,
1338 /// Where the request came in, for the audit log; g1t.sh when absent.
1339 #[serde(default)]
1340 pub surface: Option<crate::audit::Surface>,
1341}
1342
1343/// `workspace_invites` (takes `ListMembersArgs`): a workspace's invites,
1344/// newest first. Owners only. Returns `Outcome<Vec<Invite>>`.
1345///
1346/// `revoke_workspace_invite`: owners only. Returns `Outcome<Invite>`.
1347#[derive(Debug, Serialize, Deserialize)]
1348pub struct WorkspaceInviteArgs {
1349 pub actor: User,
1350 pub slug: String,
1351 pub id: String,
1352}
1353
1354/// `request_access`: someone without an invite asks for one. Kept on the
1355/// waitlist, one entry per address. Answers the same way whether or not
1356/// the address is already on it. Returns `Outcome<bool>`.
1357#[derive(Debug, Default, Serialize, Deserialize)]
1358pub struct RequestAccessArgs {
1359 pub email: String,
1360 /// What they will build, if they said.
1361 #[serde(default)]
1362 pub about: String,
1363 /// Who is asking, such as the visitor's IP address, for rate limits.
1364 #[serde(default)]
1365 pub client: Option<String>,
1366}
1367
1368/// The most characters `RequestAccessArgs::about` keeps.
1369pub const MAX_WAITLIST_ABOUT: usize = 1000;
1370
1371// `registration` takes `{}` and returns `RegistrationMode`.
1372
1373// --- Invites, staff only ---
1374
1375#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1376#[serde(rename_all = "snake_case")]
1377pub enum WaitlistStatus {
1378 Waiting,
1379 Invited,
1380 Dismissed,
1381}
1382
1383impl WaitlistStatus {
1384 pub fn as_str(self) -> &'static str {
1385 match self {
1386 WaitlistStatus::Waiting => "waiting",
1387 WaitlistStatus::Invited => "invited",
1388 WaitlistStatus::Dismissed => "dismissed",
1389 }
1390 }
1391}
1392
1393/// Someone who asked for access.
1394#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1395#[serde(rename_all = "camelCase")]
1396pub struct WaitlistEntry {
1397 pub id: String,
1398 pub email: String,
1399 pub about: Option<String>,
1400 pub status: WaitlistStatus,
1401 pub invite_id: Option<String>,
1402 pub decided_by: Option<String>,
1403 /// RFC 3339.
1404 pub decided_at: Option<String>,
1405 /// What staff wrote when approving; it went in the invite email.
1406 #[serde(default)]
1407 pub note: Option<String>,
1408 /// The account made with the invite, once it was used.
1409 #[serde(default)]
1410 pub joined_as: Option<String>,
1411 /// When they first asked. RFC 3339.
1412 pub created_at: String,
1413 /// When they last asked. RFC 3339.
1414 pub updated_at: String,
1415}
1416
1417/// `admin_waitlist`: the waitlist, newest first, at most
1418/// [`ADMIN_INVITES_LIMIT`]. Returns `Vec<WaitlistEntry>`.
1419///
1420/// `admin_waitlist_pending` takes `{}` and returns the number of requests
1421/// still waiting, for sudo's navigation.
1422#[derive(Debug, Default, Serialize, Deserialize)]
1423pub struct AdminWaitlistArgs {
1424 /// Part of an email address or of what they said.
1425 #[serde(default)]
1426 pub query: Option<String>,
1427 /// Null: every status.
1428 #[serde(default)]
1429 pub status: Option<WaitlistStatus>,
1430}
1431
1432/// The most rows one staff listing of invites or the waitlist returns.
1433pub const ADMIN_INVITES_LIMIT: usize = 500;
1434
1435/// `admin_decide_waitlist`: approving mints an invite bound to the
1436/// address, charged to nobody, and emails it, with `note` if given;
1437/// dismissing only marks the entry. Returns `Outcome<WaitlistEntry>`.
1438#[derive(Debug, Serialize, Deserialize)]
1439pub struct AdminDecideWaitlistArgs {
1440 pub id: String,
1441 pub approve: bool,
1442 /// The staff member, by email.
1443 pub staff: String,
1444 /// A line for the invite email, up to [`MAX_WAITLIST_NOTE`] characters.
1445 #[serde(default)]
1446 pub note: Option<String>,
1447}
1448
1449/// The most characters an approval's note keeps.
1450pub const MAX_WAITLIST_NOTE: usize = 500;
1451
1452/// `admin_invites`: every invite, newest first, at most
1453/// [`ADMIN_INVITES_LIMIT`], optionally only those whose code starts with
1454/// `query`, or whose email, inviter or redeemer contains it. Returns
1455/// `Vec<Invite>`.
1456#[derive(Debug, Default, Serialize, Deserialize)]
1457pub struct AdminInvitesArgs {
1458 #[serde(default)]
1459 pub query: Option<String>,
1460}
1461
1462/// `admin_revoke_invite`: revokes any pending invite. Returns
1463/// `Outcome<Invite>`.
1464#[derive(Debug, Serialize, Deserialize)]
1465pub struct AdminRevokeInviteArgs {
1466 pub id: String,
1467 pub staff: String,
1468}
1469
1470/// `admin_mint_invite`: staff make an invite that uses nobody's
1471/// allowance, optionally bound to (and emailed to) an address. Returns
1472/// `Outcome<Invite>`, with the code.
1473#[derive(Debug, Serialize, Deserialize)]
1474pub struct AdminMintInviteArgs {
1475 #[serde(default)]
1476 pub email: Option<String>,
1477 pub staff: String,
1478}
1479
1480/// Who staff grant invites to.
1481#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1482#[serde(rename_all = "snake_case")]
1483pub enum GrantTarget {
1484 User,
1485 Workspace,
1486}
1487
1488impl GrantTarget {
1489 pub fn as_str(self) -> &'static str {
1490 match self {
1491 GrantTarget::User => "user",
1492 GrantTarget::Workspace => "workspace",
1493 }
1494 }
1495}
1496
1497/// `admin_grant_invites`: gives a person (by username) or a workspace (by
1498/// slug) `amount` more invites; a negative amount takes some back. Returns
1499/// `Outcome<Allowance>`: theirs afterwards.
1500#[derive(Debug, Serialize, Deserialize)]
1501pub struct AdminGrantInvitesArgs {
1502 pub target: GrantTarget,
1503 pub name: String,
1504 pub amount: i32,
1505 #[serde(default)]
1506 pub note: String,
1507 pub staff: String,
1508}
1509
1510/// The most invites one grant gives or takes back.
1511pub const MAX_INVITE_GRANT: i32 = 1000;
1512
1513/// Invites staff granted.
1514#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1515#[serde(rename_all = "camelCase")]
1516pub struct InviteGrant {
1517 pub amount: i32,
1518 pub note: Option<String>,
1519 pub granted_by: String,
1520 /// RFC 3339.
1521 pub created_at: String,
1522}
1523
1524/// Someone a person invited, and whom they invited in turn.
1525#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1526#[serde(rename_all = "camelCase")]
1527pub struct InviteTreeNode {
1528 pub username: String,
1529 /// When they used the invite. RFC 3339.
1530 pub joined_at: String,
1531 pub invited: Vec<InviteTreeNode>,
1532}
1533
1534/// `admin_invite_tree` (takes `UsernameArgs`): where a person came from
1535/// and whom they brought, for tracing abuse. Returns `Option<InviteTree>`.
1536///
1537/// `admin_workspace_invites` (takes `SlugArgs`): a workspace's granted
1538/// invites, grants and invites. Returns `Option<InviteTree>` with
1539/// `username` the slug and no `invited_by`.
1540#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1541#[serde(rename_all = "camelCase")]
1542pub struct InviteTree {
1543 pub username: String,
1544 /// Who invited them, then who invited that person, and so on. Empty
1545 /// for an account made without an invite.
1546 pub invited_by: Vec<String>,
1547 /// The staff member who minted their invite, when staff did.
1548 pub staff: Option<String>,
1549 pub allowance: Allowance,
1550 pub grants: Vec<InviteGrant>,
1551 /// Their invites, newest first.
1552 pub invites: Vec<Invite>,
1553 /// Whom they invited, three levels down.
1554 pub invited: Vec<InviteTreeNode>,
1555}
1556
1557#[cfg(test)]
1558mod deletion_tests {
1559 use super::{WorkspaceDeletion, protected_names};
1560
1561 #[test]
1562 fn only_billing_or_protection_stands_in_the_way() {
1563 let clear = WorkspaceDeletion {
1564 repositories: 2,
1565 projects: 1,
1566 members: 3,
1567 ..WorkspaceDeletion::default()
1568 };
1569 assert!(!clear.blocked());
1570 assert_eq!(clear.reason("acme"), None);
1571 let owing = WorkspaceDeletion {
1572 billing: Some("Pay first.".into()),
1573 ..WorkspaceDeletion::default()
1574 };
1575 assert!(owing.blocked());
1576 assert_eq!(owing.reason("acme").as_deref(), Some("Pay first."));
1577 let protected = WorkspaceDeletion {
1578 billing: Some("Pay first.".into()),
1579 protected: true,
1580 ..WorkspaceDeletion::default()
1581 };
1582 assert!(protected.blocked());
1583 assert_eq!(
1584 protected.reason("flagon-io").as_deref(),
1585 Some("flagon-io is protected and can never be deleted.")
1586 );
1587 }
1588
1589 #[test]
1590 fn flagon_is_protected_whatever_the_variable_says() {
1591 assert_eq!(protected_names(None), ["flagon-io"]);
1592 assert_eq!(protected_names(Some("")), ["flagon-io"]);
1593 assert_eq!(protected_names(Some(" , ")), ["flagon-io"]);
1594 assert_eq!(
1595 protected_names(Some("Flagon-IO, acme ,wsp_1")),
1596 ["flagon-io", "acme", "wsp_1"]
1597 );
1598 }
1599}