Skip to content

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

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