Skip to content
1,828 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 /// The `proof` from the invite email's link. When it is the invite's
249 /// own and `email` is the address the invite was sent to, the account
250 /// starts with that address confirmed; otherwise it is ignored.
251 #[serde(default)]
252 pub email_proof: Option<String>,
253 /// Who is asking, such as the visitor's IP address, for rate limits.
254 #[serde(default)]
255 pub client: Option<String>,
256}
257
258/// `verify_email`: the token from the emailed link. Returns `Outcome<User>`.
259#[derive(Debug, Serialize, Deserialize)]
260pub struct EmailTokenArgs {
261 pub token: String,
262}
263
264/// `request_password_reset`. Always succeeds, so it cannot be used to find
265/// out which addresses have accounts. Any confirmed address of an account
266/// works: the link goes to the address given, and the primary (and the
267/// backup) are told a reset was asked for. A few requests an hour per
268/// address and per `client`; past that, nothing is sent.
269#[derive(Debug, Serialize, Deserialize)]
270pub struct EmailArgs {
271 pub email: String,
272 /// Who is asking, such as the visitor's IP address, for rate limits.
273 #[serde(default)]
274 pub client: Option<String>,
275}
276
277/// `reset_password`: sets a new password and ends every session.
278/// Returns `Outcome<User>`.
279#[derive(Debug, Serialize, Deserialize)]
280pub struct ResetPasswordArgs {
281 pub token: String,
282 pub password: String,
283}
284
285/// `device_start`: begins a device sign-in. Returns `DeviceStart`.
286#[derive(Debug, Serialize, Deserialize)]
287#[serde(rename_all = "camelCase")]
288pub struct DeviceStartArgs {
289 /// What is asking, shown to the person approving, e.g. "Claude Code".
290 pub client_name: String,
291}
292
293#[derive(Debug, Serialize, Deserialize)]
294#[serde(rename_all = "camelCase")]
295pub struct DeviceStart {
296 /// Secret held by the tool and exchanged for a token once approved.
297 pub device_code: String,
298 /// Short code shown to the person, e.g. `WDJB-MJHT`.
299 pub user_code: String,
300 /// Seconds until both codes stop working.
301 pub expires_in: u32,
302 /// Seconds the tool should wait between polls.
303 pub interval: u32,
304}
305
306/// `device_lookup`: what a user code is asking for, or null if it is not
307/// valid. Returns `Option<DeviceRequest>`.
308#[derive(Debug, Serialize, Deserialize)]
309#[serde(rename_all = "camelCase")]
310pub struct DeviceLookupArgs {
311 pub user_code: String,
312}
313
314#[derive(Debug, Serialize, Deserialize)]
315#[serde(rename_all = "camelCase")]
316pub struct DeviceRequest {
317 pub user_code: String,
318 pub client_name: String,
319}
320
321/// `device_resolve`: the signed-in person approves or denies a request.
322/// Returns `Outcome<bool>`.
323#[derive(Debug, Serialize, Deserialize)]
324#[serde(rename_all = "camelCase")]
325pub struct DeviceResolveArgs {
326 pub user_code: String,
327 pub user: User,
328 pub approve: bool,
329}
330
331/// `device_claim`: the tool asks whether its request was approved.
332#[derive(Debug, Serialize, Deserialize)]
333#[serde(rename_all = "camelCase")]
334pub struct DeviceClaimArgs {
335 pub device_code: String,
336}
337
338/// The answer to a `device_claim`.
339#[derive(Debug, Serialize, Deserialize)]
340#[serde(tag = "status", rename_all = "snake_case")]
341pub enum DeviceClaim {
342 /// Nobody has approved or denied it yet; ask again after the interval.
343 Pending,
344 Denied,
345 /// The code was never issued, has expired, or was already used.
346 Expired,
347 /// The access token, returned once.
348 Approved {
349 token: String,
350 user: User,
351 },
352}
353
354/// A workspace: the owner of repositories, and the first segment of their
355/// URLs. A person's own space and a team's are the same thing.
356#[derive(Clone, Debug, Serialize, Deserialize)]
357#[serde(rename_all = "camelCase")]
358pub struct Workspace {
359 pub id: String,
360 pub slug: String,
361 pub name: String,
362 /// One line saying what the workspace is for.
363 pub description: Option<String>,
364 /// RFC 3339.
365 pub created_at: String,
366 pub member_count: u32,
367 /// The workspace's uploaded icon: the SHA-256 of its bytes, served at
368 /// `/avatars/<avatar>`. Null means the generated letter avatar.
369 #[serde(default)]
370 pub avatar: Option<String>,
371 /// What every member gets on each of its repositories; owners have
372 /// Admin. See [`crate::access`].
373 #[serde(default)]
374 pub base_permission: crate::access::BasePermission,
375 /// Who may create its teams. See [`crate::teams::TeamCreation`].
376 #[serde(default)]
377 pub team_creation: crate::teams::TeamCreation,
378 /// What members may do, by GitHub's names for each
379 /// (`members_can_create_public_repositories`...), at the top level as
380 /// GitHub's organization has them. See [`crate::MemberPrivileges`].
381 #[serde(flatten)]
382 pub privileges: crate::MemberPrivileges,
383 /// Whether members and outside collaborators need two-factor
384 /// authentication to use it.
385 #[serde(default)]
386 pub two_factor_requirement_enabled: bool,
387}
388
389#[derive(Clone, Debug, Serialize, Deserialize)]
390pub struct Member {
391 pub username: String,
392 pub role: crate::Role,
393 /// The roles they hold besides `role`.
394 #[serde(default)]
395 pub org_roles: Vec<crate::OrgRole>,
396 /// Whether they have two-factor authentication on. Shown to owners
397 /// only; null for anyone else.
398 #[serde(default)]
399 pub two_factor: Option<bool>,
400 /// Their display name, when they set one.
401 #[serde(default)]
402 pub name: Option<String>,
403 /// Their uploaded avatar: the SHA-256 of its bytes, served at
404 /// `/avatars/<avatar>`. None means the generated letter avatar.
405 #[serde(default)]
406 pub avatar: Option<String>,
407}
408
409/// Where a workspace keeps its repositories' git data: anywhere g1t
410/// stores it (the default), or in the EU only. It applies to repositories
411/// made after it is set; the repos service reads it when it places a new
412/// one (`storage_options` says whether the EU can be chosen).
413#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
414#[serde(rename_all = "lowercase")]
415pub enum DataResidency {
416 #[default]
417 Anywhere,
418 Eu,
419}
420
421impl DataResidency {
422 pub fn as_str(self) -> &'static str {
423 match self {
424 DataResidency::Anywhere => "anywhere",
425 DataResidency::Eu => "eu",
426 }
427 }
428
429 pub fn parse(text: &str) -> Option<Self> {
430 match text.trim().to_ascii_lowercase().as_str() {
431 "anywhere" => Some(DataResidency::Anywhere),
432 "eu" => Some(DataResidency::Eu),
433 _ => None,
434 }
435 }
436}
437
438/// `workspace_residency` takes [`SlugArgs`] and returns
439/// `Option<DataResidency>` (null when there is no such workspace).
440/// `set_workspace_residency`: owners only. Returns `Outcome<DataResidency>`.
441#[derive(Debug, Serialize, Deserialize)]
442pub struct SetResidencyArgs {
443 pub actor: User,
444 pub slug: String,
445 pub residency: DataResidency,
446}
447
448/// `create_workspace`. Returns `Outcome<Workspace>`.
449#[derive(Debug, Serialize, Deserialize)]
450pub struct CreateWorkspaceArgs {
451 pub user: User,
452 pub slug: String,
453 #[serde(default)]
454 pub name: String,
455}
456
457/// `get_workspace`: public details, or null. Returns `Option<Workspace>`.
458#[derive(Debug, Serialize, Deserialize)]
459pub struct SlugArgs {
460 pub slug: String,
461}
462
463/// `list_members`: members only. Owners also see each member's
464/// `two_factor`. Returns `Outcome<Vec<Member>>`.
465#[derive(Debug, Serialize, Deserialize)]
466pub struct ListMembersArgs {
467 pub slug: String,
468 pub viewer: crate::Viewer,
469}
470
471/// `add_member` and `remove_member`: owners only. `add_member` never adds a
472/// person at once: it sends them a workspace invitation to accept or
473/// decline, as `invite_member` with a username does. Only g1t's own agent
474/// is added at once. Removing yourself is
475/// leaving (`members::LeaveWorkspaceArgs`); removing an owner is refused
476/// when they are the last. Each returns `Outcome<bool>`.
477#[derive(Debug, Serialize, Deserialize)]
478pub struct MemberArgs {
479 pub actor: User,
480 pub slug: String,
481 pub username: String,
482 #[serde(default)]
483 pub surface: Option<crate::audit::Surface>,
484}
485
486/// `update_workspace`: owners only. An empty name falls back to the slug;
487/// an empty description clears it. Returns `Outcome<Workspace>`.
488#[derive(Debug, Serialize, Deserialize)]
489pub struct UpdateWorkspaceArgs {
490 pub actor: User,
491 pub slug: String,
492 pub name: String,
493 pub description: String,
494}
495
496/// `rename_workspace`: owners only. Changes the workspace's slug, the first
497/// segment of its URLs, to `new_slug`; the display name is untouched. The
498/// old slug redirects to the new one, and is held for this workspace, for
499/// [`SLUG_HOLD_DAYS`]. Publishes `workspace.renamed`. Returns
500/// `Outcome<Workspace>`.
501///
502/// `check_workspace_rename` takes the same arguments and answers whether
503/// the rename would be allowed, changing nothing. Returns `Outcome<bool>`.
504#[derive(Debug, Serialize, Deserialize)]
505#[serde(rename_all = "camelCase")]
506pub struct RenameWorkspaceArgs {
507 pub actor: User,
508 pub slug: String,
509 pub new_slug: String,
510}
511
512/// `delete_workspace`: owners only, and only a person. `confirm` must be
513/// the workspace's slug, typed out. Refused for a protected workspace
514/// ([`protected_names`]), whoever asks, and while billing cannot settle it
515/// (`close_workspace`). Everything in it goes with it at once: nobody can
516/// reach it, its tokens stop working, its pages are not found, and its
517/// repositories, projects and apps are deleted with it. It is kept for
518/// [`WORKSPACE_RESTORE_DAYS`] so g1t's staff can restore it, then purged:
519/// its memberships, access tokens and old-slug redirects go, and billing's
520/// ledger and the audit log keep its history. The slug is never given to
521/// another workspace; the person whose username it is may make a workspace
522/// of that name again once it is purged. Publishes `workspace.deleting`,
523/// and `workspace.deleted` at the purge. Returns `Outcome<bool>`.
524///
525/// `check_workspace_deletion` takes the same arguments (with `confirm`
526/// ignored) and says what would go and whether anything stands in the way,
527/// changing nothing. Returns `Outcome<WorkspaceDeletion>`.
528#[derive(Debug, Serialize, Deserialize)]
529pub struct DeleteWorkspaceArgs {
530 pub actor: User,
531 pub slug: String,
532 #[serde(default)]
533 pub confirm: String,
534 /// Where the request came in, for the audit log; g1t.sh when absent.
535 #[serde(default)]
536 pub surface: Option<crate::audit::Surface>,
537}
538
539/// What deleting a workspace takes with it, and what stands in the way.
540/// Nothing does when `billing` is null and it is not `protected`.
541#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
542pub struct WorkspaceDeletion {
543 /// Its live repositories, which are deleted with it.
544 pub repositories: u32,
545 /// Its projects, hidden with it.
546 pub projects: u32,
547 #[serde(default)]
548 pub members: u32,
549 /// Why billing cannot close the workspace yet, in words for its owner.
550 pub billing: Option<String>,
551 /// It can never be deleted, by anyone ([`protected_names`]).
552 #[serde(default)]
553 pub protected: bool,
554}
555
556impl WorkspaceDeletion {
557 pub fn blocked(&self) -> bool {
558 self.protected || self.billing.is_some()
559 }
560
561 /// Why the workspace cannot be deleted, as one sentence, or `None`.
562 pub fn reason(&self, slug: &str) -> Option<String> {
563 if self.protected {
564 return Some(protected_refusal(slug));
565 }
566 self.billing.clone()
567 }
568}
569
570/// How long a deleted workspace is kept, for staff to restore, before it is
571/// purged.
572pub const WORKSPACE_RESTORE_DAYS: u64 = 30;
573
574/// Workspaces nobody can delete, whatever identity's `PROTECTED_WORKSPACES`
575/// says: Flagon's, which runs g1t.
576pub const ALWAYS_PROTECTED: &[&str] = &["flagon-io"];
577
578/// The protected workspaces: `configured` (comma-separated slugs or
579/// workspace ids, as identity's `PROTECTED_WORKSPACES` holds them), and
580/// [`ALWAYS_PROTECTED`] whatever it says, so an empty or missing variable
581/// still protects them. Lowercased, without duplicates.
582pub fn protected_names(configured: Option<&str>) -> Vec<String> {
583 let mut names: Vec<String> = Vec::new();
584 let given = configured.unwrap_or_default().split(',');
585 for name in ALWAYS_PROTECTED.iter().copied().chain(given) {
586 let name = name.trim().to_lowercase();
587 if !name.is_empty() && !names.contains(&name) {
588 names.push(name);
589 }
590 }
591 names
592}
593
594/// Why a protected workspace is not deleted, purged or acted on.
595pub fn protected_refusal(slug: &str) -> String {
596 format!("{slug} is protected and can never be deleted.")
597}
598
599/// `admin_deleted_workspaces` takes no arguments (`{}`) and returns
600/// `Vec<DeletedWorkspace>`, newest first. Staff only.
601///
602/// A workspace an owner deleted, kept until `purge_after` for staff to
603/// restore.
604#[derive(Clone, Debug, Serialize, Deserialize)]
605#[serde(rename_all = "camelCase")]
606pub struct DeletedWorkspace {
607 pub workspace_id: String,
608 pub slug: String,
609 pub name: String,
610 /// RFC 3339.
611 pub deleted_at: String,
612 /// The username of the owner who deleted it, or the staff member (by
613 /// email) who deleted it with the account that was its only owner.
614 pub deleted_by: String,
615 /// RFC 3339: when it is purged unless restored first.
616 pub purge_after: String,
617 /// What went with it, counted when it was deleted.
618 pub went: WorkspaceDeletion,
619 /// Whether staff can still restore it.
620 pub restorable: bool,
621}
622
623/// `admin_restore_workspace` and `admin_purge_workspace`: staff restore a
624/// deleted workspace within [`WORKSPACE_RESTORE_DAYS`], or purge it now.
625/// `staff` is who, for the audit logs. Purging needs `confirm`, the slug
626/// typed out, and is refused for a protected workspace. Restoring publishes
627/// `workspace.restored`; purging, `workspace.deleted`. Both return
628/// `Outcome<bool>`.
629#[derive(Debug, Serialize, Deserialize)]
630#[serde(rename_all = "camelCase")]
631pub struct AdminDeletedWorkspaceArgs {
632 pub workspace_id: String,
633 pub staff: String,
634 #[serde(default)]
635 pub confirm: String,
636}
637
638/// `transfer_repo_scopes`: a repository moved from `from` to `to`; the
639/// tokens of agents at work on it are kept pointing at it. For repos'
640/// `transfer`. Returns `bool`.
641#[derive(Debug, Serialize, Deserialize)]
642pub struct TransferRepoScopesArgs {
643 pub from: crate::repos::RepoPath,
644 pub to: crate::repos::RepoPath,
645}
646
647/// How long a workspace's old slug keeps redirecting to it, and stays
648/// reserved for it, after a rename.
649pub const SLUG_HOLD_DAYS: u64 = 90;
650
651/// How long a workspace must wait between renames.
652pub const RENAME_COOLDOWN_HOURS: u64 = 24;
653
654// `resolve_slug` takes `SlugArgs` and returns `Option<String>`: the
655// workspace's current slug when `slug` is one it was renamed from within
656// the last `SLUG_HOLD_DAYS`, and null otherwise (including for a slug that
657// is in use), or the workspace's slug when `slug` is one of its aliases.
658
659// `resolve_alias` takes `SlugArgs` and returns `Option<String>`: the slug
660// now of the workspace `slug` is an alias of, and null when it is none.
661// Aliases are set by g1t's staff only: `g1t` is Flagon, Inc.'s `flagon-io`.
662// An alias follows its workspace through renames.
663
664/// `admin_aliases` takes no arguments (`{}`) and returns
665/// `Vec<WorkspaceAlias>`, by alias. Staff only.
666///
667/// A name staff point at a workspace, so that its addresses (pages, git,
668/// the API, packages) lead to the workspace under its own name.
669#[derive(Clone, Debug, Serialize, Deserialize)]
670#[serde(rename_all = "camelCase")]
671pub struct WorkspaceAlias {
672 pub alias: String,
673 pub workspace_id: String,
674 /// The workspace's slug and name now.
675 pub workspace: String,
676 pub workspace_name: String,
677 /// Why it exists, as staff wrote it.
678 pub note: String,
679 /// The staff member who set it, or `migration`.
680 pub created_by: String,
681 /// RFC 3339.
682 pub created_at: String,
683}
684
685/// `admin_set_alias`: points `alias` at the workspace whose slug is
686/// `workspace`. The alias must have a namespace's shape, must not be one of
687/// the site's routes, and must not be anyone's username, a workspace's slug
688/// (deleted, or held after a rename) or another alias. `note` is required:
689/// it is the reason, kept with the alias and in sudo's audit log. Staff
690/// only. Returns `Outcome<WorkspaceAlias>`.
691#[derive(Debug, Serialize, Deserialize)]
692#[serde(rename_all = "camelCase")]
693pub struct AdminSetAliasArgs {
694 pub alias: String,
695 pub workspace: String,
696 pub note: String,
697 pub staff: String,
698}
699
700/// `admin_remove_alias`: the alias stops leading anywhere, and the name is
701/// nobody's again unless it is reserved. `reason` goes in sudo's audit log.
702/// Staff only. Returns `Outcome<bool>`.
703#[derive(Debug, Serialize, Deserialize)]
704#[serde(rename_all = "camelCase")]
705pub struct AdminRemoveAliasArgs {
706 pub alias: String,
707 pub reason: String,
708 pub staff: String,
709}
710
711/// `set_workspace_avatar`: owners only. `image` is the file's bytes in
712/// base64: PNG, JPEG, WebP or GIF, at most `MAX_AVATAR_BYTES`. Null removes
713/// the icon. Returns `Outcome<Workspace>`.
714#[derive(Debug, Serialize, Deserialize)]
715pub struct SetWorkspaceAvatarArgs {
716 pub actor: User,
717 pub slug: String,
718 pub image: Option<String>,
719}
720
721/// `set_user_avatar`: a person's own avatar, as `SetWorkspaceAvatarArgs`.
722/// Returns `Outcome<Option<String>>`: the new avatar, or null once removed.
723#[derive(Debug, Serialize, Deserialize)]
724pub struct SetUserAvatarArgs {
725 pub user: User,
726 pub image: Option<String>,
727}
728
729/// The largest avatar that can be uploaded, in bytes.
730pub const MAX_AVATAR_BYTES: usize = 1024 * 1024;
731
732/// `list_workspace_tokens`: members only. Returns
733/// `Outcome<Vec<AccessToken>>`.
734#[derive(Debug, Serialize, Deserialize)]
735pub struct WorkspaceTokensArgs {
736 pub slug: String,
737 pub viewer: crate::Viewer,
738}
739
740/// `create_workspace_token`: owners only. The token belongs to the
741/// workspace, acts as it, and keeps working when the member who made it
742/// leaves. Returns `Outcome<CreatedAccessToken>`.
743#[derive(Debug, Serialize, Deserialize)]
744pub struct CreateWorkspaceTokenArgs {
745 pub actor: User,
746 pub slug: String,
747 pub name: String,
748 /// Its scopes; null for full access.
749 #[serde(default)]
750 pub scopes: Option<Vec<String>>,
751 /// When set, the token stops working after this many seconds. It is
752 /// listed with the workspace's tokens either way. Null: no expiry.
753 #[serde(default)]
754 pub ttl_seconds: Option<u64>,
755 /// Admin on the workspace's repositories, rather than Write: given by
756 /// the owner on purpose, when making it.
757 #[serde(default)]
758 pub admin: bool,
759}
760
761/// `remove_workspace_token`: owners only. Returns `Outcome<bool>`.
762#[derive(Debug, Serialize, Deserialize)]
763pub struct RemoveWorkspaceTokenArgs {
764 pub actor: User,
765 pub slug: String,
766 pub id: String,
767}
768
769/// `oauth_authorize`: the signed-in person approved an application. The
770/// caller has checked the client and that it may be redirected to
771/// `redirect_uri`. Returns `OAuthCode`.
772#[derive(Debug, Serialize, Deserialize)]
773#[serde(rename_all = "camelCase")]
774pub struct OAuthAuthorizeArgs {
775 pub user: User,
776 pub client_id: String,
777 /// Shown wherever the application's access is listed.
778 pub client_name: String,
779 pub redirect_uri: String,
780 /// PKCE challenge, method S256.
781 pub code_challenge: String,
782 /// What the person granted, as `resource:level`. Null: full access.
783 #[serde(default)]
784 pub scopes: Option<Vec<String>>,
785}
786
787#[derive(Debug, Serialize, Deserialize)]
788pub struct OAuthCode {
789 pub code: String,
790}
791
792/// `oauth_exchange`: redeems an authorization code.
793/// Returns `Outcome<OAuthTokens>`.
794#[derive(Debug, Serialize, Deserialize)]
795#[serde(rename_all = "camelCase")]
796pub struct OAuthExchangeArgs {
797 pub code: String,
798 pub code_verifier: String,
799 pub client_id: String,
800 pub redirect_uri: String,
801}
802
803/// `oauth_refresh`: trades a refresh token for new tokens.
804/// Returns `Outcome<OAuthTokens>`.
805#[derive(Debug, Serialize, Deserialize)]
806#[serde(rename_all = "camelCase")]
807pub struct OAuthRefreshArgs {
808 pub refresh_token: String,
809 pub client_id: String,
810}
811
812#[derive(Debug, Serialize, Deserialize)]
813#[serde(rename_all = "camelCase")]
814pub struct OAuthTokens {
815 pub access_token: String,
816 /// Works once; using it returns the next one.
817 pub refresh_token: String,
818 /// Seconds until the access token stops working.
819 pub expires_in: u64,
820 /// The scopes granted, space-separated, or `*` for full access.
821 #[serde(default)]
822 pub scope: Option<String>,
823}
824
825/// An application a person has signed in to. Listed by `list_oauth_grants`
826/// and ended by `revoke_oauth_grant`.
827#[derive(Debug, Serialize, Deserialize)]
828#[serde(rename_all = "camelCase")]
829pub struct OAuthGrant {
830 pub id: String,
831 pub client_name: String,
832 /// RFC 3339.
833 pub created_at: String,
834 /// RFC 3339.
835 pub last_used_at: String,
836 /// What the person granted. Null: full access.
837 #[serde(default)]
838 pub scopes: Option<Vec<String>>,
839 /// Signed in before applications were given scopes: full access until
840 /// someone narrows it.
841 #[serde(default)]
842 pub legacy: bool,
843}
844
845/// `update_oauth_grant`: changes what an application the person signed in
846/// to may do, at once and when it refreshes. Returns `Outcome<OAuthGrant>`.
847#[derive(Debug, Serialize, Deserialize)]
848pub struct UpdateOAuthGrantArgs {
849 pub user: User,
850 pub id: String,
851 #[serde(default)]
852 pub scopes: Option<Vec<String>>,
853}
854
855
856/// What an agent's token may do: these operations, in this repository.
857#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
858pub struct AgentScope {
859 pub repo: crate::repos::RepoPath,
860 /// API and MCP operation names, such as `create_issue`.
861 pub operations: Vec<String>,
862 /// Set on a run credential: the run it belongs to, and what it may do
863 /// with git. See [`crate::credentials`].
864 #[serde(default, skip_serializing_if = "Option::is_none")]
865 pub run: Option<crate::credentials::RunBinding>,
866}
867
868/// `create_agent_token`: a token for a g1t agent working on someone's
869/// behalf. It acts as `g1t`, a member of the repository's workspace,
870/// and only for the operations in `scope`. Returns `CreatedAccessToken`.
871#[derive(Debug, Serialize, Deserialize)]
872#[serde(rename_all = "camelCase")]
873pub struct CreateAgentTokenArgs {
874 /// The person the agent works for; the token is recorded as theirs.
875 pub on_behalf_of: User,
876 pub scope: AgentScope,
877 pub ttl_seconds: u64,
878}
879
880// `agent_scope` takes `TokenArgs` and returns `Option<AgentScope>`: what an
881// agent's token may do, or null for any other token.
882
883/// The id g1t's agent acts under. Only ever stored, never shown: it keeps
884/// the agent's work apart from g1t's own ([`crate::system::ID`]) where
885/// that matters, such as whether its approval counts.
886pub const AGENT_ID: &str = "usr_g1t_agent";
887/// The name g1t's agent is shown by: g1t's own, [`crate::system::USERNAME`].
888/// Everything it does, people see g1t do.
889pub const AGENT_NAME: &str = crate::system::USERNAME;
890
891// --- Staff ---------------------------------------------------------------
892//
893// Staff-only methods, for sudo.g1t.sh. They take no viewer and check no
894// membership: only sudo calls them, over its service binding, after it has
895// verified a Cloudflare Access sign-in and its staff list. Nothing a
896// customer can reach should ever forward to them.
897
898/// `notify_owners`: emails a short notice, with one link, to each owner of
899/// a workspace with a confirmed address. Called by other services (billing
900/// warns owners near their usage limit), never on a person's behalf.
901/// Returns how many were sent.
902#[derive(Clone, Debug, Serialize, Deserialize)]
903pub struct NotifyOwnersArgs {
904 pub workspace: String,
905 pub subject: String,
906 /// One or two sentences: what happened and what it means.
907 pub intro: String,
908 /// The button's words, such as `Open billing`.
909 pub action: String,
910 /// Where the button goes; must be on g1t.sh.
911 pub link: String,
912 /// Small print: why they got it.
913 pub footer: String,
914}
915
916/// `admin_workspaces`: every workspace, newest first, at most
917/// [`ADMIN_WORKSPACES_LIMIT`], optionally only those whose slug, name or
918/// an owner's username or email contains `query`. Returns
919/// `Vec<AdminWorkspace>`. Staff only.
920#[derive(Debug, Default, Serialize, Deserialize)]
921pub struct AdminWorkspacesArgs {
922 #[serde(default)]
923 pub query: Option<String>,
924}
925
926/// The most workspaces one `admin_workspaces` call returns.
927pub const ADMIN_WORKSPACES_LIMIT: usize = 500;
928
929/// An owner of a workspace, as staff see them.
930#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
931pub struct AdminOwner {
932 pub username: String,
933 pub email: Option<String>,
934}
935
936/// A workspace as staff see it: who owns it and how many belong to it.
937#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
938#[serde(rename_all = "camelCase")]
939pub struct AdminWorkspace {
940 pub slug: String,
941 pub name: String,
942 /// RFC 3339.
943 pub created_at: String,
944 pub owners: Vec<AdminOwner>,
945 pub member_count: u32,
946}
947
948/// `admin_workspace`: one workspace with every member, or null. Takes
949/// `SlugArgs`; returns `Option<AdminWorkspaceDetail>`. Staff only.
950#[derive(Clone, Debug, Serialize, Deserialize)]
951#[serde(rename_all = "camelCase")]
952pub struct AdminWorkspaceDetail {
953 pub slug: String,
954 pub name: String,
955 pub description: Option<String>,
956 /// RFC 3339.
957 pub created_at: String,
958 /// Owners first, then by username.
959 pub members: Vec<AdminMember>,
960 /// It can never be deleted ([`protected_names`]).
961 #[serde(default)]
962 pub protected: bool,
963}
964
965/// A member of a workspace, as staff see them.
966#[derive(Clone, Debug, Serialize, Deserialize)]
967pub struct AdminMember {
968 pub username: String,
969 pub email: Option<String>,
970 pub role: crate::Role,
971 /// When they joined the workspace. RFC 3339.
972 pub joined: String,
973}
974
975// --- Profiles ------------------------------------------------------------
976//
977// A person's public page at `g1t.sh/u/<username>`. Everything in a
978// `Profile` is shown to anyone, signed in or not; an email address never is.
979
980/// The most characters each profile field takes.
981pub const MAX_PROFILE_NAME: usize = 80;
982pub const MAX_PROFILE_BIO: usize = 160;
983pub const MAX_PROFILE_LOCATION: usize = 80;
984pub const MAX_PROFILE_WEBSITE: usize = 200;
985pub const MAX_PROFILE_PRONOUNS: usize = 40;
986pub const MAX_PROFILE_TIMEZONE: usize = 64;
987
988/// What anyone may see about a person.
989#[derive(Clone, Debug, Default, Serialize, Deserialize)]
990#[serde(rename_all = "camelCase")]
991pub struct Profile {
992 pub username: String,
993 /// The name they go by, if they gave one.
994 pub name: Option<String>,
995 /// One or two lines about them, at most [`MAX_PROFILE_BIO`] characters.
996 pub bio: Option<String>,
997 pub location: Option<String>,
998 /// An `https://` address.
999 pub website: Option<String>,
1000 pub pronouns: Option<String>,
1001 /// The time zone they are in, an IANA name such as `America/Denver`.
1002 #[serde(default)]
1003 pub timezone: Option<String>,
1004 /// The uploaded avatar's hash, served at `/avatars/<avatar>`.
1005 pub avatar: Option<String>,
1006 /// When the account was made. RFC 3339.
1007 pub created_at: String,
1008}
1009
1010// `profile` takes `UsernameArgs` and returns `Option<Profile>`: null for
1011// an account that does not exist.
1012
1013/// `update_profile`: a person changes their own profile. Every field is
1014/// replaced; an empty one is cleared. Returns `Outcome<Profile>`.
1015#[derive(Debug, Default, Serialize, Deserialize)]
1016#[serde(rename_all = "camelCase")]
1017pub struct UpdateProfileArgs {
1018 pub actor: User,
1019 #[serde(default)]
1020 pub name: String,
1021 #[serde(default)]
1022 pub bio: String,
1023 #[serde(default)]
1024 pub location: String,
1025 #[serde(default)]
1026 pub website: String,
1027 #[serde(default)]
1028 pub pronouns: String,
1029 /// An IANA time zone name, such as `America/Denver`.
1030 #[serde(default)]
1031 pub timezone: String,
1032}
1033
1034/// `profile_workspaces`: the workspaces shown on a person's profile, as
1035/// `viewer` may see them. A membership is shown only when it is no secret
1036/// from the viewer: a workspace the viewer belongs to as well, or one of
1037/// `public`, the workspaces the caller found the person has made a public
1038/// project in (whose page shows that already). Returns
1039/// `Vec<ProfileWorkspace>`; empty for an account that does not exist.
1040#[derive(Debug, Serialize, Deserialize)]
1041pub struct ProfileWorkspacesArgs {
1042 pub username: String,
1043 pub viewer: crate::Viewer,
1044 #[serde(default)]
1045 pub public: Vec<String>,
1046}
1047
1048/// A workspace on a person's profile.
1049#[derive(Clone, Debug, Serialize, Deserialize)]
1050pub struct ProfileWorkspace {
1051 pub slug: String,
1052 pub name: String,
1053 pub avatar: Option<String>,
1054}
1055
1056/// `directory`: every account or every workspace, as their public pages
1057/// show them, a page at a time in name order. For services that index
1058/// them, such as search; nothing private is in it. Returns
1059/// `DirectoryPage`.
1060#[derive(Debug, Default, Serialize, Deserialize)]
1061pub struct DirectoryArgs {
1062 /// `user` or `workspace`.
1063 pub kind: String,
1064 /// Names after this one.
1065 #[serde(default)]
1066 pub after: Option<String>,
1067 pub limit: u32,
1068}
1069
1070/// One account or workspace in the directory.
1071#[derive(Clone, Debug, Serialize, Deserialize)]
1072#[serde(rename_all = "camelCase")]
1073pub struct DirectoryEntry {
1074 /// The account's or workspace's id.
1075 pub id: String,
1076 /// A username or a workspace's slug.
1077 pub slug: String,
1078 /// A person's display name or a workspace's name.
1079 pub name: Option<String>,
1080 /// A person's bio or a workspace's description.
1081 pub bio: Option<String>,
1082 pub avatar: Option<String>,
1083 /// RFC 3339.
1084 pub created_at: String,
1085}
1086
1087#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1088pub struct DirectoryPage {
1089 pub entries: Vec<DirectoryEntry>,
1090 /// Where the next page starts; null on the last.
1091 pub next: Option<String>,
1092}
1093
1094// --- Invites ---------------------------------------------------------------
1095//
1096// While registration is invite-only, every new account (with a password or
1097// through GitHub) needs an invite code. Each person may have
1098// `INVITES_PER_USER` invites out at a time; staff grant more to a person or
1099// to a workspace, whose owners share them. Inviting an email with no
1100// account into a workspace makes an invite bound to that address, which
1101// registers and joins in one step. See services/identity/src/invites.rs.
1102
1103/// Whether anyone may make an account, or only someone with an invite. Set
1104/// by identity's `REGISTRATION_MODE` var; anything but `open`, including
1105/// leaving it unset, is `invite`, so a missing setting never opens sign-up.
1106#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1107#[serde(rename_all = "snake_case")]
1108pub enum RegistrationMode {
1109 #[default]
1110 Invite,
1111 Open,
1112}
1113
1114impl RegistrationMode {
1115 pub fn parse(text: Option<&str>) -> RegistrationMode {
1116 match text.map(|text| text.trim().to_ascii_lowercase()).as_deref() {
1117 Some("open") => RegistrationMode::Open,
1118 _ => RegistrationMode::Invite,
1119 }
1120 }
1121}
1122
1123/// How many invites a person may have out at once, unless identity's
1124/// `INVITES_PER_USER` var says otherwise.
1125pub const INVITES_PER_USER: u32 = 5;
1126
1127/// How long an invite works, unless identity's `INVITE_TTL_DAYS` var says
1128/// otherwise.
1129pub const INVITE_TTL_DAYS: u64 = 30;
1130
1131/// Where an invite stands. Only a pending invite can be used. A pending
1132/// invite can be revoked, and so can one awaiting confirmation. An expired
1133/// or revoked invite that was never used gives its inviter the invite back.
1134#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1135#[serde(rename_all = "snake_case")]
1136pub enum InviteStatus {
1137 Pending,
1138 /// Used to make an account that has not confirmed its email address
1139 /// yet. The code is spent; the workspace (or repository) it gives is
1140 /// joined when the address is confirmed, unless it is revoked first.
1141 AwaitingConfirmation,
1142 /// Used to make an account that has confirmed its address, for a
1143 /// workspace it has not yet joined or declined: the workspace
1144 /// invitation waits for the person's answer (`accept_invitation`).
1145 AwaitingAnswer,
1146 Redeemed,
1147 /// Its person declined the workspace it invited them to.
1148 Declined,
1149 Expired,
1150 Revoked,
1151}
1152
1153/// What using an invite does.
1154#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1155#[serde(rename_all = "snake_case")]
1156pub enum InviteKind {
1157 /// Makes a new account, and joins `workspace` when one is set.
1158 Account,
1159 /// An existing account joins `workspace`. Never makes an account.
1160 Workspace,
1161}
1162
1163/// Whose allowance an invite uses.
1164#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1165#[serde(rename_all = "snake_case")]
1166pub enum InviteCharge {
1167 /// Its inviter's own.
1168 User,
1169 /// The workspace's, granted by staff and shared by its owners.
1170 Workspace,
1171 /// Nobody's: staff minted it, or it invites an existing account.
1172 None,
1173}
1174
1175/// One invite, as the person who made it sees it.
1176#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1177#[serde(rename_all = "camelCase")]
1178pub struct Invite {
1179 pub id: String,
1180 /// The code, such as `g1t-k7m2-q9xd-…`: returned once when the invite
1181 /// is made, and afterwards to whoever made it while it is pending.
1182 /// Null otherwise.
1183 pub code: Option<String>,
1184 /// The code's first group, such as `g1t-k7m2`, to recognise it by.
1185 pub hint: String,
1186 /// Only an account with this address can use it. Null: anyone with
1187 /// the code.
1188 pub email: Option<String>,
1189 pub kind: InviteKind,
1190 /// The workspace it joins, by slug.
1191 pub workspace: Option<String>,
1192 pub status: InviteStatus,
1193 pub charged_to: InviteCharge,
1194 /// Who made it, by username. Null when g1t staff did.
1195 pub invited_by: Option<String>,
1196 /// The account that used it, by username.
1197 pub redeemed_by: Option<String>,
1198 /// RFC 3339.
1199 pub created_at: String,
1200 /// RFC 3339.
1201 pub expires_at: String,
1202 /// RFC 3339.
1203 pub redeemed_at: Option<String>,
1204 /// RFC 3339.
1205 pub revoked_at: Option<String>,
1206 /// The account a workspace invitation is for, by username: someone
1207 /// invited by username, or the account the invite made.
1208 #[serde(default)]
1209 pub invitee: Option<String>,
1210 /// The role `workspace` is joined with. Null when it names none.
1211 #[serde(default)]
1212 pub role: Option<crate::Role>,
1213 /// The staff member who minted it. Only in staff views.
1214 #[serde(default, skip_serializing_if = "Option::is_none")]
1215 pub staff: Option<String>,
1216}
1217
1218/// How many invites someone may have out, and how many they have.
1219#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1220pub struct Allowance {
1221 /// Null: no limit.
1222 pub limit: Option<u32>,
1223 /// Pending and used invites; revoked and expired ones are not counted.
1224 pub used: u32,
1225 /// Null: no limit.
1226 pub remaining: Option<u32>,
1227}
1228
1229impl Allowance {
1230 pub fn new(limit: Option<u32>, used: u32) -> Allowance {
1231 Allowance {
1232 limit,
1233 used,
1234 remaining: limit.map(|limit| limit.saturating_sub(used)),
1235 }
1236 }
1237
1238 pub fn exhausted(&self) -> bool {
1239 self.remaining == Some(0)
1240 }
1241}
1242
1243/// A workspace's shared invites, for one of its owners.
1244#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1245pub struct WorkspaceAllowance {
1246 pub slug: String,
1247 pub allowance: Allowance,
1248}
1249
1250/// `list_invites` (takes `UserArgs`): a person's invites, newest first,
1251/// and what they have left. Returns `InvitesOverview`.
1252#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1253pub struct InvitesOverview {
1254 pub mode: RegistrationMode,
1255 pub allowance: Allowance,
1256 /// Workspaces the person owns that staff granted invites to.
1257 pub workspaces: Vec<WorkspaceAllowance>,
1258 pub invites: Vec<Invite>,
1259}
1260
1261/// `create_invite`: a person makes an invite, optionally for one email
1262/// address. People only; never an agent or a workspace's token, and not
1263/// before their email is confirmed. Uses one of the person's invites, or,
1264/// with `workspace`, one of the invites staff granted that workspace (its
1265/// owners only). Emails the address when one is given. Returns
1266/// `Outcome<Invite>`, with the code.
1267///
1268/// `revoke_invite` (takes `RemoveArgs`): its maker revokes a pending
1269/// invite; a workspace's owners may revoke one made for the workspace.
1270/// The invite comes back to whoever it was charged to. Returns
1271/// `Outcome<Invite>`.
1272#[derive(Debug, Serialize, Deserialize)]
1273pub struct CreateInviteArgs {
1274 pub user: User,
1275 #[serde(default)]
1276 pub email: Option<String>,
1277 /// Use this workspace's granted invites, by slug.
1278 #[serde(default)]
1279 pub workspace: Option<String>,
1280 /// The workspace the new account is invited to, by slug: one the
1281 /// person owns that can add members (not on the free plan). Once the
1282 /// account is confirmed it gets a workspace invitation to accept, as a
1283 /// member, and no workspace of its own is made for it.
1284 #[serde(default)]
1285 pub join: Option<String>,
1286 /// Where the request came in, for the audit log; g1t.sh when absent.
1287 #[serde(default)]
1288 pub surface: Option<crate::audit::Surface>,
1289}
1290
1291/// `check_invite`: what an invite code is for, before using it. Returns
1292/// `Outcome<InvitePreview>`; a code that is unknown, used, revoked or
1293/// expired gets the same answer, so codes cannot be probed. With
1294/// `any_status`, a real code that can no longer be used is described
1295/// instead (its `status` says why), so the page can say whom to ask for a
1296/// new one; an unknown code still gets the one answer.
1297#[derive(Debug, Serialize, Deserialize)]
1298pub struct InviteCodeArgs {
1299 pub code: String,
1300 /// Who is asking, such as the visitor's IP address, for rate limits.
1301 #[serde(default)]
1302 pub client: Option<String>,
1303 /// Who is looking, if signed in: sets `InvitePreview::for_viewer`.
1304 #[serde(default)]
1305 pub viewer: Option<User>,
1306 #[serde(default)]
1307 pub any_status: bool,
1308 /// The `proof` from the invite email's link, if the page was opened
1309 /// from it: sets `InvitePreview::email_proven`.
1310 #[serde(default)]
1311 pub email_proof: Option<String>,
1312}
1313
1314/// Someone shown on an invite.
1315#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1316pub struct InviteFrom {
1317 pub username: String,
1318 pub name: Option<String>,
1319 pub avatar: Option<String>,
1320}
1321
1322/// A repository an invite code was sent with: using the code accepts the
1323/// invitation to collaborate on it.
1324#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1325pub struct InviteRepository {
1326 /// `workspace/repo`.
1327 pub name: String,
1328 /// The role it gives, such as `write`.
1329 pub role: String,
1330}
1331
1332/// What a valid invite code is for.
1333#[derive(Clone, Debug, Serialize, Deserialize)]
1334#[serde(rename_all = "camelCase")]
1335pub struct InvitePreview {
1336 pub kind: InviteKind,
1337 /// Pending, unless `any_status` asked about a code that is spent.
1338 pub status: InviteStatus,
1339 /// Null when g1t staff sent it.
1340 pub invited_by: Option<InviteFrom>,
1341 pub workspace: Option<ProfileWorkspace>,
1342 /// The repository it accepts an invitation to, if it was sent with one.
1343 pub repository: Option<InviteRepository>,
1344 /// The address it is for, partly hidden, such as `a•••@example.com`.
1345 pub email: Option<String>,
1346 /// The address in full, while it is pending: whoever holds the code
1347 /// was sent it there. Fills in and locks the sign-up form.
1348 pub address: Option<String>,
1349 /// Whether the address it is for has a g1t account already, so the
1350 /// page asks them to sign in rather than sign up.
1351 pub has_account: bool,
1352 /// With a viewer: whether the invite is theirs (it is for one of their
1353 /// confirmed addresses, or they used it). Null without a viewer or,
1354 /// for a pending invite, when it is for anyone with the code.
1355 pub for_viewer: Option<bool>,
1356 /// RFC 3339.
1357 pub expires_at: String,
1358 /// For a shared invite link ([`SharedInvite`]): the group it was made
1359 /// for, such as `Cloudflare judges`. Not secret; the sign-up page shows
1360 /// it. Null for a one-person invite.
1361 #[serde(default)]
1362 pub shared_label: Option<String>,
1363 /// For a shared invite link limited to some email domains: those
1364 /// domains, such as `["cloudflare.com"]`. Empty for any address.
1365 #[serde(default)]
1366 pub shared_domains: Vec<String>,
1367 /// Whether `email_proof` was this pending invite's own, from the email
1368 /// it was sent in: the account made with it starts with `address`
1369 /// confirmed. False without a proof, with a wrong one, and for an
1370 /// invite bound to no address.
1371 #[serde(default)]
1372 pub email_proven: bool,
1373}
1374
1375/// `accept_invite`: a signed-in person uses a workspace invite made for
1376/// their confirmed address, and joins the workspace, or an invite sent with
1377/// a repository invitation, and accepts it. Returns `Outcome<String>`: the
1378/// workspace's slug, or `workspace/repo`.
1379#[derive(Debug, Serialize, Deserialize)]
1380pub struct AcceptInviteArgs {
1381 pub user: User,
1382 pub code: String,
1383}
1384
1385/// `invite_member`: an owner invites an email address into a workspace.
1386/// It always makes an invite bound to that address and emails it, so the
1387/// answer never says whether the address has an account. Without one, the
1388/// invite registers and joins in one step, and uses one of the workspace's
1389/// granted invites or else one of the owner's own. With one, it costs
1390/// nothing. Returns `Outcome<Invite>`, with the code.
1391#[derive(Debug, Serialize, Deserialize)]
1392pub struct InviteMemberArgs {
1393 pub actor: User,
1394 pub slug: String,
1395 /// An email address. Give this or `username`.
1396 #[serde(default)]
1397 pub email: String,
1398 /// A g1t username: that account gets a workspace invitation to accept
1399 /// or decline, in its inbox and by email. Nobody joins without saying
1400 /// yes.
1401 #[serde(default)]
1402 pub username: Option<String>,
1403 /// The role they join with; member when absent.
1404 #[serde(default)]
1405 pub role: Option<crate::Role>,
1406 /// Where the request came in, for the audit log; g1t.sh when absent.
1407 #[serde(default)]
1408 pub surface: Option<crate::audit::Surface>,
1409}
1410
1411/// A workspace invitation waiting for its person's answer, as they see it.
1412/// `list_invitations` (takes `UserArgs`) returns `Vec<WorkspaceInvitation>`,
1413/// newest first: pending ones only, never expired, revoked or answered.
1414#[derive(Clone, Debug, Serialize, Deserialize)]
1415#[serde(rename_all = "camelCase")]
1416pub struct WorkspaceInvitation {
1417 pub id: String,
1418 pub workspace: ProfileWorkspace,
1419 /// The role accepting joins with.
1420 pub role: crate::Role,
1421 /// Null when g1t staff sent it.
1422 pub invited_by: Option<InviteFrom>,
1423 /// RFC 3339.
1424 pub created_at: String,
1425 /// RFC 3339.
1426 pub expires_at: String,
1427}
1428
1429/// `accept_invitation`: the person it is for joins the workspace with the
1430/// role it names. Returns `Outcome<String>`, the workspace's slug.
1431///
1432/// `decline_invitation`: they say no; whoever sent it is told in their
1433/// inbox. Returns `Outcome<bool>`.
1434#[derive(Debug, Serialize, Deserialize)]
1435pub struct InvitationArgs {
1436 pub user: User,
1437 pub id: String,
1438 /// Where the request came in, for the audit log; g1t.sh when absent.
1439 #[serde(default)]
1440 pub surface: Option<crate::audit::Surface>,
1441}
1442
1443/// `find_people`: accounts whose username starts with `query`, or whose
1444/// name contains it, for picking someone to invite. Only what a profile
1445/// shows: a username, a name and an avatar, never an email address.
1446/// Returns `Vec<InviteFrom>`, at most `limit` (10 at most, 8 when absent).
1447#[derive(Debug, Serialize, Deserialize)]
1448pub struct FindPeopleArgs {
1449 pub query: String,
1450 #[serde(default)]
1451 pub limit: Option<u32>,
1452}
1453
1454/// `workspace_invites` (takes `ListMembersArgs`): a workspace's invites,
1455/// newest first. Owners only. Returns `Outcome<Vec<Invite>>`.
1456///
1457/// `revoke_workspace_invite`: owners only. Returns `Outcome<Invite>`.
1458#[derive(Debug, Serialize, Deserialize)]
1459pub struct WorkspaceInviteArgs {
1460 pub actor: User,
1461 pub slug: String,
1462 pub id: String,
1463}
1464
1465/// `request_access`: someone without an invite asks for one. Kept on the
1466/// waitlist, one entry per address. Answers the same way whether or not
1467/// the address is already on it. Returns `Outcome<bool>`.
1468#[derive(Debug, Default, Serialize, Deserialize)]
1469pub struct RequestAccessArgs {
1470 pub email: String,
1471 /// What they will build, if they said.
1472 #[serde(default)]
1473 pub about: String,
1474 /// Who is asking, such as the visitor's IP address, for rate limits.
1475 #[serde(default)]
1476 pub client: Option<String>,
1477}
1478
1479/// The most characters `RequestAccessArgs::about` keeps.
1480pub const MAX_WAITLIST_ABOUT: usize = 1000;
1481
1482// `registration` takes `{}` and returns `RegistrationMode`.
1483
1484// --- Invites, staff only ---
1485
1486#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1487#[serde(rename_all = "snake_case")]
1488pub enum WaitlistStatus {
1489 Waiting,
1490 Invited,
1491 Dismissed,
1492}
1493
1494impl WaitlistStatus {
1495 pub fn as_str(self) -> &'static str {
1496 match self {
1497 WaitlistStatus::Waiting => "waiting",
1498 WaitlistStatus::Invited => "invited",
1499 WaitlistStatus::Dismissed => "dismissed",
1500 }
1501 }
1502}
1503
1504/// Someone who asked for access.
1505#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1506#[serde(rename_all = "camelCase")]
1507pub struct WaitlistEntry {
1508 pub id: String,
1509 pub email: String,
1510 pub about: Option<String>,
1511 pub status: WaitlistStatus,
1512 pub invite_id: Option<String>,
1513 pub decided_by: Option<String>,
1514 /// RFC 3339.
1515 pub decided_at: Option<String>,
1516 /// What staff wrote when approving; it went in the invite email.
1517 #[serde(default)]
1518 pub note: Option<String>,
1519 /// The account made with the invite, once it was used.
1520 #[serde(default)]
1521 pub joined_as: Option<String>,
1522 /// When they first asked. RFC 3339.
1523 pub created_at: String,
1524 /// When they last asked. RFC 3339.
1525 pub updated_at: String,
1526}
1527
1528/// `admin_waitlist`: the waitlist, newest first, at most
1529/// [`ADMIN_INVITES_LIMIT`]. Returns `Vec<WaitlistEntry>`.
1530///
1531/// `admin_waitlist_pending` takes `{}` and returns the number of requests
1532/// still waiting, for sudo's navigation.
1533#[derive(Debug, Default, Serialize, Deserialize)]
1534pub struct AdminWaitlistArgs {
1535 /// Part of an email address or of what they said.
1536 #[serde(default)]
1537 pub query: Option<String>,
1538 /// Null: every status.
1539 #[serde(default)]
1540 pub status: Option<WaitlistStatus>,
1541}
1542
1543/// The most rows one staff listing of invites or the waitlist returns.
1544pub const ADMIN_INVITES_LIMIT: usize = 500;
1545
1546/// `admin_decide_waitlist`: approving mints an invite bound to the
1547/// address, charged to nobody, and emails it, with `note` if given;
1548/// dismissing only marks the entry. Returns `Outcome<WaitlistEntry>`.
1549#[derive(Debug, Serialize, Deserialize)]
1550pub struct AdminDecideWaitlistArgs {
1551 pub id: String,
1552 pub approve: bool,
1553 /// The staff member, by email.
1554 pub staff: String,
1555 /// A line for the invite email, up to [`MAX_WAITLIST_NOTE`] characters.
1556 #[serde(default)]
1557 pub note: Option<String>,
1558}
1559
1560/// The most characters an approval's note keeps.
1561pub const MAX_WAITLIST_NOTE: usize = 500;
1562
1563/// `admin_invites`: every invite, newest first, at most
1564/// [`ADMIN_INVITES_LIMIT`], optionally only those whose code starts with
1565/// `query`, or whose email, inviter or redeemer contains it. Returns
1566/// `Vec<Invite>`.
1567#[derive(Debug, Default, Serialize, Deserialize)]
1568pub struct AdminInvitesArgs {
1569 #[serde(default)]
1570 pub query: Option<String>,
1571}
1572
1573/// `admin_revoke_invite`: revokes any pending invite. Returns
1574/// `Outcome<Invite>`.
1575#[derive(Debug, Serialize, Deserialize)]
1576pub struct AdminRevokeInviteArgs {
1577 pub id: String,
1578 pub staff: String,
1579}
1580
1581/// `admin_mint_invite`: staff make an invite that uses nobody's
1582/// allowance, optionally bound to (and emailed to) an address. Returns
1583/// `Outcome<Invite>`, with the code.
1584#[derive(Debug, Serialize, Deserialize)]
1585pub struct AdminMintInviteArgs {
1586 #[serde(default)]
1587 pub email: Option<String>,
1588 pub staff: String,
1589}
1590
1591/// Who staff grant invites to.
1592#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1593#[serde(rename_all = "snake_case")]
1594pub enum GrantTarget {
1595 User,
1596 Workspace,
1597}
1598
1599impl GrantTarget {
1600 pub fn as_str(self) -> &'static str {
1601 match self {
1602 GrantTarget::User => "user",
1603 GrantTarget::Workspace => "workspace",
1604 }
1605 }
1606}
1607
1608/// `admin_grant_invites`: gives a person (by username) or a workspace (by
1609/// slug) `amount` more invites; a negative amount takes some back. Returns
1610/// `Outcome<Allowance>`: theirs afterwards.
1611#[derive(Debug, Serialize, Deserialize)]
1612pub struct AdminGrantInvitesArgs {
1613 pub target: GrantTarget,
1614 pub name: String,
1615 pub amount: i32,
1616 #[serde(default)]
1617 pub note: String,
1618 pub staff: String,
1619}
1620
1621/// The most invites one grant gives or takes back.
1622pub const MAX_INVITE_GRANT: i32 = 1000;
1623
1624/// Invites staff granted.
1625#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1626#[serde(rename_all = "camelCase")]
1627pub struct InviteGrant {
1628 pub amount: i32,
1629 pub note: Option<String>,
1630 pub granted_by: String,
1631 /// RFC 3339.
1632 pub created_at: String,
1633}
1634
1635/// Someone a person invited, and whom they invited in turn.
1636#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1637#[serde(rename_all = "camelCase")]
1638pub struct InviteTreeNode {
1639 pub username: String,
1640 /// When they used the invite. RFC 3339.
1641 pub joined_at: String,
1642 pub invited: Vec<InviteTreeNode>,
1643}
1644
1645/// `admin_invite_tree` (takes `UsernameArgs`): where a person came from
1646/// and whom they brought, for tracing abuse. Returns `Option<InviteTree>`.
1647///
1648/// `admin_workspace_invites` (takes `SlugArgs`): a workspace's granted
1649/// invites, grants and invites. Returns `Option<InviteTree>` with
1650/// `username` the slug and no `invited_by`.
1651#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1652#[serde(rename_all = "camelCase")]
1653pub struct InviteTree {
1654 pub username: String,
1655 /// Who invited them, then who invited that person, and so on. Empty
1656 /// for an account made without an invite.
1657 pub invited_by: Vec<String>,
1658 /// The staff member who minted their invite, when staff did.
1659 pub staff: Option<String>,
1660 pub allowance: Allowance,
1661 pub grants: Vec<InviteGrant>,
1662 /// Their invites, newest first.
1663 pub invites: Vec<Invite>,
1664 /// Whom they invited, three levels down.
1665 pub invited: Vec<InviteTreeNode>,
1666 /// The shared invite link the account was made with, if it was.
1667 #[serde(default)]
1668 pub shared: Option<SharedInviteSource>,
1669}
1670
1671// --- Shared invite links, staff only ---
1672//
1673// One link for a group (a conference's judges, a post, a community): up
1674// to `max_uses` new accounts, until it expires or staff revoke it,
1675// optionally only for addresses at some domains. Each use makes a new
1676// account, which then makes its own workspace; a shared link never joins
1677// anyone to an existing workspace, and uses nobody's allowance. Its code
1678// looks and is stored like any invite code (only a hash, and a sealed copy
1679// staff can copy again while it is live); the link is
1680// `https://g1t.sh/register?invite=<code>`. See
1681// services/identity/src/shared_invites.rs.
1682
1683/// How long a shared invite link works when staff give no date.
1684pub const SHARED_INVITE_TTL_DAYS: u64 = 14;
1685/// The furthest ahead a shared invite link's last day may be set.
1686pub const SHARED_INVITE_MAX_DAYS: u64 = 365;
1687/// The most accounts one shared invite link makes.
1688pub const MAX_SHARED_INVITE_USES: u32 = 1000;
1689/// The most characters a shared invite link's label keeps.
1690pub const MAX_SHARED_INVITE_LABEL: usize = 80;
1691/// The most email domains one shared invite link may be limited to.
1692pub const MAX_SHARED_INVITE_DOMAINS: usize = 10;
1693
1694/// Where a shared invite link stands. Only a live one makes accounts.
1695#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1696#[serde(rename_all = "snake_case")]
1697pub enum SharedInviteStatus {
1698 Live,
1699 /// Every use is taken.
1700 UsedUp,
1701 Expired,
1702 Revoked,
1703}
1704
1705/// The shared invite link an account was made with.
1706#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1707pub struct SharedInviteSource {
1708 pub id: String,
1709 pub label: String,
1710}
1711
1712/// An account made with a shared invite link.
1713#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1714#[serde(rename_all = "camelCase")]
1715pub struct SharedInviteAccount {
1716 /// Null once the account is purged.
1717 pub username: Option<String>,
1718 /// When it was made with the link. RFC 3339.
1719 pub joined_at: String,
1720}
1721
1722/// One shared invite link, as staff see it.
1723#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1724#[serde(rename_all = "camelCase")]
1725pub struct SharedInvite {
1726 /// `sinv_…`.
1727 pub id: String,
1728 /// Whom it is for, such as `Cloudflare judges`.
1729 pub label: String,
1730 /// The code, while it is live (and IDENTITY_KEY is set).
1731 pub code: Option<String>,
1732 /// The code's first group, such as `g1t-k7m2`.
1733 pub hint: String,
1734 pub max_uses: u32,
1735 /// Accounts made with it so far.
1736 pub uses: u32,
1737 /// Only addresses at these domains may use it; empty for any.
1738 pub domains: Vec<String>,
1739 pub status: SharedInviteStatus,
1740 /// The staff member who made it, by email.
1741 pub staff: String,
1742 /// RFC 3339.
1743 pub created_at: String,
1744 /// RFC 3339.
1745 pub expires_at: String,
1746 pub revoked_at: Option<String>,
1747 pub revoked_by: Option<String>,
1748 /// The accounts made with it, oldest first.
1749 pub accounts: Vec<SharedInviteAccount>,
1750}
1751
1752/// `admin_shared_invites` takes `{}`: shared invite links, newest first,
1753/// at most 200, each with the accounts it made. Returns
1754/// `Vec<SharedInvite>`.
1755///
1756/// `admin_create_shared_invite`: staff make a shared invite link. Recorded
1757/// in sudo's audit log. Returns `Outcome<SharedInvite>`, with the code.
1758#[derive(Debug, Default, Serialize, Deserialize)]
1759pub struct AdminCreateSharedInviteArgs {
1760 /// Required, up to [`MAX_SHARED_INVITE_LABEL`] characters.
1761 pub label: String,
1762 /// 1 to [`MAX_SHARED_INVITE_USES`].
1763 pub max_uses: u32,
1764 /// The last day it works, `YYYY-MM-DD` (UTC; it works until the end of
1765 /// that day), at most [`SHARED_INVITE_MAX_DAYS`] ahead. Null for
1766 /// [`SHARED_INVITE_TTL_DAYS`] from now.
1767 #[serde(default)]
1768 pub expires_on: Option<String>,
1769 /// Email domains it is limited to, such as `cloudflare.com`; empty for
1770 /// any address. Up to [`MAX_SHARED_INVITE_DOMAINS`].
1771 #[serde(default)]
1772 pub domains: Vec<String>,
1773 /// The staff member, by email.
1774 pub staff: String,
1775}
1776
1777/// `admin_revoke_shared_invite`: stops a shared invite link making any
1778/// more accounts. Those it made stay. Recorded in sudo's audit log.
1779/// Returns `Outcome<SharedInvite>`.
1780#[derive(Debug, Serialize, Deserialize)]
1781pub struct AdminRevokeSharedInviteArgs {
1782 pub id: String,
1783 pub staff: String,
1784}
1785
1786#[cfg(test)]
1787mod deletion_tests {
1788 use super::{WorkspaceDeletion, protected_names};
1789
1790 #[test]
1791 fn only_billing_or_protection_stands_in_the_way() {
1792 let clear = WorkspaceDeletion {
1793 repositories: 2,
1794 projects: 1,
1795 members: 3,
1796 ..WorkspaceDeletion::default()
1797 };
1798 assert!(!clear.blocked());
1799 assert_eq!(clear.reason("acme"), None);
1800 let owing = WorkspaceDeletion {
1801 billing: Some("Pay first.".into()),
1802 ..WorkspaceDeletion::default()
1803 };
1804 assert!(owing.blocked());
1805 assert_eq!(owing.reason("acme").as_deref(), Some("Pay first."));
1806 let protected = WorkspaceDeletion {
1807 billing: Some("Pay first.".into()),
1808 protected: true,
1809 ..WorkspaceDeletion::default()
1810 };
1811 assert!(protected.blocked());
1812 assert_eq!(
1813 protected.reason("flagon-io").as_deref(),
1814 Some("flagon-io is protected and can never be deleted.")
1815 );
1816 }
1817
1818 #[test]
1819 fn flagon_is_protected_whatever_the_variable_says() {
1820 assert_eq!(protected_names(None), ["flagon-io"]);
1821 assert_eq!(protected_names(Some("")), ["flagon-io"]);
1822 assert_eq!(protected_names(Some(" , ")), ["flagon-io"]);
1823 assert_eq!(
1824 protected_names(Some("Flagon-IO, acme ,wsp_1")),
1825 ["flagon-io", "acme", "wsp_1"]
1826 );
1827 }
1828}