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,566 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}
973
974/// A member of a workspace, as staff see them.
975#[derive(Clone, Debug, Serialize, Deserialize)]
976pub struct AdminMember {
977 pub username: String,
978 pub email: Option<String>,
979 pub role: crate::Role,
980 /// When they joined the workspace. RFC 3339.
981 pub joined: String,
982}
983
984// --- Profiles ------------------------------------------------------------
985//
986// A person's public page at `g1t.sh/u/<username>`. Everything in a
987// `Profile` is shown to anyone, signed in or not; an email address never is.
988
989/// The most characters each profile field takes.
990pub const MAX_PROFILE_NAME: usize = 80;
991pub const MAX_PROFILE_BIO: usize = 160;
992pub const MAX_PROFILE_LOCATION: usize = 80;
993pub const MAX_PROFILE_WEBSITE: usize = 200;
994pub const MAX_PROFILE_PRONOUNS: usize = 40;
995pub const MAX_PROFILE_TIMEZONE: usize = 64;
996
997/// What anyone may see about a person.
998#[derive(Clone, Debug, Default, Serialize, Deserialize)]
999#[serde(rename_all = "camelCase")]
1000pub struct Profile {
1001 /// Lowercased: what the profile is found and linked by.
1002 pub username: String,
1003 /// The username as its owner wrote it, when that differs: what the page shows.
1004 #[serde(default, skip_serializing_if = "Option::is_none")]
1005 pub display_username: Option<String>,
1006 /// The name they go by, if they gave one.
1007 pub name: Option<String>,
1008 /// One or two lines about them, at most [`MAX_PROFILE_BIO`] characters.
1009 pub bio: Option<String>,
1010 pub location: Option<String>,
1011 /// An `https://` address.
1012 pub website: Option<String>,
1013 pub pronouns: Option<String>,
1014 /// The time zone they are in, an IANA name such as `America/Denver`.
1015 #[serde(default)]
1016 pub timezone: Option<String>,
1017 /// The uploaded avatar's hash, served at `/avatars/<avatar>`.
1018 pub avatar: Option<String>,
1019 /// When the account was made. RFC 3339.
1020 pub created_at: String,
1021}
1022
1023// `profile` takes `UsernameArgs` and returns `Option<Profile>`: null for
1024// an account that does not exist.
1025
1026/// `update_profile`: a person changes their own profile. Every field is
1027/// replaced; an empty one is cleared. Returns `Outcome<Profile>`.
1028#[derive(Debug, Default, Serialize, Deserialize)]
1029#[serde(rename_all = "camelCase")]
1030pub struct UpdateProfileArgs {
1031 pub actor: User,
1032 #[serde(default)]
1033 pub name: String,
1034 #[serde(default)]
1035 pub bio: String,
1036 #[serde(default)]
1037 pub location: String,
1038 #[serde(default)]
1039 pub website: String,
1040 #[serde(default)]
1041 pub pronouns: String,
1042 /// An IANA time zone name, such as `America/Denver`.
1043 #[serde(default)]
1044 pub timezone: String,
1045}
1046
1047/// `profile_workspaces`: the workspaces shown on a person's profile, as
1048/// `viewer` may see them. A membership is shown only when it is no secret
1049/// from the viewer: a workspace the viewer belongs to as well, or one of
1050/// `public`, the workspaces the caller found the person has made a public
1051/// project in (whose page shows that already). Returns
1052/// `Vec<ProfileWorkspace>`; empty for an account that does not exist.
1053#[derive(Debug, Serialize, Deserialize)]
1054pub struct ProfileWorkspacesArgs {
1055 pub username: String,
1056 pub viewer: crate::Viewer,
1057 #[serde(default)]
1058 pub public: Vec<String>,
1059}
1060
1061/// A workspace on a person's profile.
1062#[derive(Clone, Debug, Serialize, Deserialize)]
1063pub struct ProfileWorkspace {
1064 pub slug: String,
1065 pub name: String,
1066 pub avatar: Option<String>,
1067}
1068
1069// --- Dock pins -------------------------------------------------------------
1070//
1071// The apps a person pins to their dock in a workspace, kept with their
1072// account so the dock follows them to every device. Each person's own:
1073// nobody else reads or sets them.
1074
1075/// The most apps a person pins in one workspace.
1076pub const MAX_DOCK_PINS: usize = 24;
1077/// The most characters an app key takes.
1078pub const MAX_DOCK_APP_KEY: usize = 32;
1079
1080/// `dock_pins`: the apps `user` pinned in the workspace `workspace` (a
1081/// slug), in the order they set. Returns `Option<Vec<String>>`: null when
1082/// they never saved any there, or are not one of its members.
1083#[derive(Debug, Default, Serialize, Deserialize)]
1084#[serde(rename_all = "camelCase")]
1085pub struct DockPinsArgs {
1086 pub user: User,
1087 pub workspace: String,
1088}
1089
1090/// `set_dock_pins`: replaces `user`'s pins in `workspace` with `apps`, in
1091/// that order. Each key is lowercase letters, digits and hyphens, at most
1092/// [`MAX_DOCK_APP_KEY`] characters; a repeat is dropped; at most
1093/// [`MAX_DOCK_PINS`]. Which keys name real apps is the web app's to say.
1094/// Returns `Outcome<Vec<String>>`: the pins as saved.
1095#[derive(Debug, Default, Serialize, Deserialize)]
1096#[serde(rename_all = "camelCase")]
1097pub struct SetDockPinsArgs {
1098 pub user: User,
1099 pub workspace: String,
1100 #[serde(default)]
1101 pub apps: Vec<String>,
1102}
1103
1104// --- Sounds and desktop notifications --------------------------------------
1105//
1106// What a person hears when chat moves, kept with their account so a phone,
1107// a laptop and the desktop app all sound the same. Which sound plays when
1108// is the web app's rule (apps/web/app/lib/chat-sounds.ts); identity keeps
1109// the choices. Do not disturb is not here: it is the person's presence
1110// (`dnd_until`, services/notify), which also silences pop-ups and pushes.
1111// Mirrors `SoundSettings` in packages/contracts/src/identity.ts.
1112
1113/// The sets of sounds a person can choose from.
1114pub const SOUND_SETS: [&str; 2] = ["soft", "bright"];
1115/// The cues a person can turn on and off. `call` is reserved and has no setting.
1116pub const SOUND_CUES: [&str; 5] = ["message", "direct", "mention", "agent_done", "sent"];
1117/// Before anyone changes them: every cue but the tick as you send.
1118pub const SOUND_CUES_OFF_BY_DEFAULT: [&str; 1] = ["sent"];
1119pub const DEFAULT_SOUND_SET: &str = "soft";
1120pub const DEFAULT_SOUND_VOLUME: u8 = 60;
1121
1122/// A person's sound settings, as kept and as answered. Wire fields are
1123/// snake_case, as the site's JSON is.
1124#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1125pub struct SoundSettings {
1126 /// Whether anything plays at all.
1127 pub sounds_enabled: bool,
1128 /// One of [`SOUND_SETS`].
1129 pub sound_set: String,
1130 /// 0 to 100.
1131 pub sound_volume: u8,
1132 /// Each cue on or off, by name; a cue left out is on, except `sent`.
1133 #[serde(default)]
1134 pub sound_cues: std::collections::BTreeMap<String, bool>,
1135 /// Whether an open tab shows a system notification for a message to
1136 /// you while its window is not in front.
1137 pub desktop_toasts: bool,
1138}
1139
1140impl Default for SoundSettings {
1141 fn default() -> Self {
1142 SoundSettings {
1143 sounds_enabled: true,
1144 sound_set: DEFAULT_SOUND_SET.to_owned(),
1145 sound_volume: DEFAULT_SOUND_VOLUME,
1146 sound_cues: SOUND_CUES
1147 .iter()
1148 .map(|cue| ((*cue).to_owned(), !SOUND_CUES_OFF_BY_DEFAULT.contains(cue)))
1149 .collect(),
1150 desktop_toasts: false,
1151 }
1152 }
1153}
1154
1155/// A change to them: only what is sent changes; `sound_cues` merges by cue.
1156#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1157pub struct SoundSettingsChange {
1158 #[serde(default)]
1159 pub sounds_enabled: Option<bool>,
1160 #[serde(default)]
1161 pub sound_set: Option<String>,
1162 #[serde(default)]
1163 pub sound_volume: Option<i64>,
1164 #[serde(default)]
1165 pub sound_cues: Option<std::collections::BTreeMap<String, bool>>,
1166 #[serde(default)]
1167 pub desktop_toasts: Option<bool>,
1168}
1169
1170/// `sound_settings`: `user`'s own, or the defaults when they never changed
1171/// them. Returns `SoundSettings`. People only.
1172#[derive(Debug, Default, Serialize, Deserialize)]
1173#[serde(rename_all = "camelCase")]
1174pub struct SoundSettingsArgs {
1175 pub user: User,
1176}
1177
1178/// `set_sound_settings`: changes `user`'s own. Returns
1179/// `Outcome<SoundSettings>`: the settings as kept, or `invalid` for a set
1180/// or cue g1t does not have, or a volume outside 0 to 100.
1181#[derive(Debug, Default, Serialize, Deserialize)]
1182#[serde(rename_all = "camelCase")]
1183pub struct SetSoundSettingsArgs {
1184 pub user: User,
1185 #[serde(default)]
1186 pub change: SoundSettingsChange,
1187}
1188
1189/// `directory`: every account or every workspace, as their public pages
1190/// show them, a page at a time in name order. For services that index
1191/// them, such as search; nothing private is in it. Returns
1192/// `DirectoryPage`.
1193#[derive(Debug, Default, Serialize, Deserialize)]
1194pub struct DirectoryArgs {
1195 /// `user` or `workspace`.
1196 pub kind: String,
1197 /// Names after this one.
1198 #[serde(default)]
1199 pub after: Option<String>,
1200 pub limit: u32,
1201}
1202
1203/// One account or workspace in the directory.
1204#[derive(Clone, Debug, Serialize, Deserialize)]
1205#[serde(rename_all = "camelCase")]
1206pub struct DirectoryEntry {
1207 /// The account's or workspace's id.
1208 pub id: String,
1209 /// A username or a workspace's slug.
1210 pub slug: String,
1211 /// A person's display name or a workspace's name.
1212 pub name: Option<String>,
1213 /// A person's bio or a workspace's description.
1214 pub bio: Option<String>,
1215 pub avatar: Option<String>,
1216 /// RFC 3339.
1217 pub created_at: String,
1218}
1219
1220#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1221pub struct DirectoryPage {
1222 pub entries: Vec<DirectoryEntry>,
1223 /// Where the next page starts; null on the last.
1224 pub next: Option<String>,
1225}
1226
1227// --- Invites ---------------------------------------------------------------
1228//
1229// An invitation into a workspace or onto a repository, sent to an address
1230// without an account, carries an invite code: registering with it applies
1231// the invitation once the address is confirmed. Anyone may register
1232// without one. See services/identity/src/invites.rs.
1233
1234/// How long an invite works, unless identity's `INVITE_TTL_DAYS` var says
1235/// otherwise.
1236pub const INVITE_TTL_DAYS: u64 = 30;
1237
1238/// Where an invite stands. Only a pending invite can be used. A pending
1239/// invite can be revoked, and so can one awaiting confirmation.
1240#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1241#[serde(rename_all = "snake_case")]
1242pub enum InviteStatus {
1243 Pending,
1244 /// Used to make an account that has not confirmed its email address
1245 /// yet. The code is spent; the workspace (or repository) it gives is
1246 /// joined when the address is confirmed, unless it is revoked first.
1247 AwaitingConfirmation,
1248 /// Used to make an account that has confirmed its address, for a
1249 /// workspace it has not yet joined or declined: the workspace
1250 /// invitation waits for the person's answer (`accept_invitation`).
1251 AwaitingAnswer,
1252 Redeemed,
1253 /// Its person declined the workspace it invited them to.
1254 Declined,
1255 Expired,
1256 Revoked,
1257}
1258
1259/// What using an invite does.
1260#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1261#[serde(rename_all = "snake_case")]
1262pub enum InviteKind {
1263 /// Makes a new account, and joins `workspace` when one is set.
1264 Account,
1265 /// An existing account joins `workspace`. Never makes an account.
1266 Workspace,
1267}
1268
1269/// One invite, as the person who made it sees it.
1270#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1271#[serde(rename_all = "camelCase")]
1272pub struct Invite {
1273 pub id: String,
1274 /// The code, such as `g1t-k7m2-q9xd-…`: returned once when the invite
1275 /// is made, and afterwards to whoever made it while it is pending.
1276 /// Null otherwise.
1277 pub code: Option<String>,
1278 /// The code's first group, such as `g1t-k7m2`, to recognise it by.
1279 pub hint: String,
1280 /// Only an account with this address can use it. Null: anyone with
1281 /// the code.
1282 pub email: Option<String>,
1283 pub kind: InviteKind,
1284 /// The workspace it joins, by slug.
1285 pub workspace: Option<String>,
1286 pub status: InviteStatus,
1287 /// Who made it, by username. Null when g1t staff did.
1288 pub invited_by: Option<String>,
1289 /// The account that used it, by username.
1290 pub redeemed_by: Option<String>,
1291 /// RFC 3339.
1292 pub created_at: String,
1293 /// RFC 3339.
1294 pub expires_at: String,
1295 /// RFC 3339.
1296 pub redeemed_at: Option<String>,
1297 /// RFC 3339.
1298 pub revoked_at: Option<String>,
1299 /// The account a workspace invitation is for, by username: someone
1300 /// invited by username, or the account the invite made.
1301 #[serde(default)]
1302 pub invitee: Option<String>,
1303 /// The role `workspace` is joined with. Null when it names none.
1304 #[serde(default)]
1305 pub role: Option<crate::Role>,
1306 /// The staff member who minted it. Only in staff views.
1307 #[serde(default, skip_serializing_if = "Option::is_none")]
1308 pub staff: Option<String>,
1309}
1310
1311/// `check_invite`: what an invite code is for, before using it. Returns
1312/// `Outcome<InvitePreview>`; a code that is unknown, used, revoked or
1313/// expired gets the same answer, so codes cannot be probed. With
1314/// `any_status`, a real code that can no longer be used is described
1315/// instead (its `status` says why), so the page can say whom to ask for a
1316/// new one; an unknown code still gets the one answer.
1317#[derive(Debug, Serialize, Deserialize)]
1318pub struct InviteCodeArgs {
1319 pub code: String,
1320 /// Who is asking, such as the visitor's IP address, for rate limits.
1321 #[serde(default)]
1322 pub client: Option<String>,
1323 /// Who is looking, if signed in: sets `InvitePreview::for_viewer`.
1324 #[serde(default)]
1325 pub viewer: Option<User>,
1326 #[serde(default)]
1327 pub any_status: bool,
1328 /// The `proof` from the invite email's link, if the page was opened
1329 /// from it: sets `InvitePreview::email_proven`.
1330 #[serde(default)]
1331 pub email_proof: Option<String>,
1332}
1333
1334/// Someone shown on an invite.
1335#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1336pub struct InviteFrom {
1337 pub username: String,
1338 pub name: Option<String>,
1339 pub avatar: Option<String>,
1340}
1341
1342/// A repository an invite code was sent with: using the code accepts the
1343/// invitation to collaborate on it.
1344#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1345pub struct InviteRepository {
1346 /// `workspace/repo`.
1347 pub name: String,
1348 /// The role it gives, such as `write`.
1349 pub role: String,
1350}
1351
1352/// What a valid invite code is for.
1353#[derive(Clone, Debug, Serialize, Deserialize)]
1354#[serde(rename_all = "camelCase")]
1355pub struct InvitePreview {
1356 pub kind: InviteKind,
1357 /// Pending, unless `any_status` asked about a code that is spent.
1358 pub status: InviteStatus,
1359 /// Null when g1t staff sent it.
1360 pub invited_by: Option<InviteFrom>,
1361 pub workspace: Option<ProfileWorkspace>,
1362 /// The repository it accepts an invitation to, if it was sent with one.
1363 pub repository: Option<InviteRepository>,
1364 /// The address it is for, partly hidden, such as `a•••@example.com`.
1365 pub email: Option<String>,
1366 /// The address in full, while it is pending: whoever holds the code
1367 /// was sent it there. Fills in and locks the sign-up form.
1368 pub address: Option<String>,
1369 /// Whether the address it is for has a g1t account already, so the
1370 /// page asks them to sign in rather than sign up.
1371 pub has_account: bool,
1372 /// With a viewer: whether the invite is theirs (it is for one of their
1373 /// confirmed addresses, or they used it). Null without a viewer or,
1374 /// for a pending invite, when it is for anyone with the code.
1375 pub for_viewer: Option<bool>,
1376 /// RFC 3339.
1377 pub expires_at: String,
1378 /// Whether `email_proof` was this pending invite's own, from the email
1379 /// it was sent in: the account made with it starts with `address`
1380 /// confirmed. False without a proof, with a wrong one, and for an
1381 /// invite bound to no address.
1382 #[serde(default)]
1383 pub email_proven: bool,
1384}
1385
1386/// `accept_invite`: a signed-in person uses a workspace invite made for
1387/// their confirmed address, and joins the workspace, or an invite sent with
1388/// a repository invitation, and accepts it. Returns `Outcome<String>`: the
1389/// workspace's slug, or `workspace/repo`.
1390#[derive(Debug, Serialize, Deserialize)]
1391pub struct AcceptInviteArgs {
1392 pub user: User,
1393 pub code: String,
1394}
1395
1396/// `invite_member`: an owner invites an email address into a workspace.
1397/// It always makes an invite bound to that address and emails it, so the
1398/// answer never says whether the address has an account. Without one, the
1399/// invite registers and joins in one step. Returns `Outcome<Invite>`, with
1400/// the code.
1401#[derive(Debug, Serialize, Deserialize)]
1402pub struct InviteMemberArgs {
1403 pub actor: User,
1404 pub slug: String,
1405 /// An email address. Give this or `username`.
1406 #[serde(default)]
1407 pub email: String,
1408 /// A g1t username: that account gets a workspace invitation to accept
1409 /// or decline, in its inbox and by email. Nobody joins without saying
1410 /// yes.
1411 #[serde(default)]
1412 pub username: Option<String>,
1413 /// The role they join with; member when absent.
1414 #[serde(default)]
1415 pub role: Option<crate::Role>,
1416 /// A note from whoever invites, quoted in the invitation email. Up to
1417 /// [`MAX_INVITE_MESSAGE`] characters; longer is cut, blank is none.
1418 #[serde(default)]
1419 pub message: Option<String>,
1420 /// Where the request came in, for the audit log; g1t.sh when absent.
1421 #[serde(default)]
1422 pub surface: Option<crate::audit::Surface>,
1423}
1424
1425/// The most characters an invitation's note keeps.
1426pub const MAX_INVITE_MESSAGE: usize = 500;
1427
1428/// A workspace invitation waiting for its person's answer, as they see it.
1429/// `list_invitations` (takes `UserArgs`) returns `Vec<WorkspaceInvitation>`,
1430/// newest first: pending ones only, never expired, revoked or answered.
1431#[derive(Clone, Debug, Serialize, Deserialize)]
1432#[serde(rename_all = "camelCase")]
1433pub struct WorkspaceInvitation {
1434 pub id: String,
1435 pub workspace: ProfileWorkspace,
1436 /// The role accepting joins with.
1437 pub role: crate::Role,
1438 /// Null when g1t staff sent it.
1439 pub invited_by: Option<InviteFrom>,
1440 /// RFC 3339.
1441 pub created_at: String,
1442 /// RFC 3339.
1443 pub expires_at: String,
1444}
1445
1446/// `accept_invitation`: the person it is for joins the workspace with the
1447/// role it names. Returns `Outcome<String>`, the workspace's slug.
1448///
1449/// `decline_invitation`: they say no; whoever sent it is told in their
1450/// inbox. Returns `Outcome<bool>`.
1451#[derive(Debug, Serialize, Deserialize)]
1452pub struct InvitationArgs {
1453 pub user: User,
1454 pub id: String,
1455 /// Where the request came in, for the audit log; g1t.sh when absent.
1456 #[serde(default)]
1457 pub surface: Option<crate::audit::Surface>,
1458}
1459
1460/// `find_people`: accounts whose username starts with `query`, or whose
1461/// name contains it, for picking someone to invite. Only what a profile
1462/// shows: a username, a name and an avatar, never an email address.
1463/// Returns `Vec<InviteFrom>`, at most `limit` (10 at most, 8 when absent).
1464#[derive(Debug, Serialize, Deserialize)]
1465pub struct FindPeopleArgs {
1466 pub query: String,
1467 #[serde(default)]
1468 pub limit: Option<u32>,
1469}
1470
1471/// `workspace_invites` (takes `ListMembersArgs`): a workspace's invites,
1472/// newest first. Owners only. Returns `Outcome<Vec<Invite>>`.
1473///
1474/// `revoke_workspace_invite`: owners only. Returns `Outcome<Invite>`.
1475///
1476/// `resend_workspace_invite`: owners only. Sends a pending invitation
1477/// again, by email to the address it is bound to or the invited account's
1478/// confirmed address, and again in that account's inbox. The invitation
1479/// itself is unchanged: same code, same day it stops working. Returns
1480/// `Outcome<Invite>`; one that is not pending answers `409`.
1481#[derive(Debug, Serialize, Deserialize)]
1482pub struct WorkspaceInviteArgs {
1483 pub actor: User,
1484 pub slug: String,
1485 pub id: String,
1486}
1487
1488// --- Invites, staff only ---
1489
1490/// The most rows one staff listing of invites returns.
1491pub const ADMIN_INVITES_LIMIT: usize = 500;
1492
1493/// `admin_invites`: every invite, newest first, at most
1494/// [`ADMIN_INVITES_LIMIT`], optionally only those whose code starts with
1495/// `query`, or whose email, inviter or redeemer contains it. Returns
1496/// `Vec<Invite>`.
1497#[derive(Debug, Default, Serialize, Deserialize)]
1498pub struct AdminInvitesArgs {
1499 #[serde(default)]
1500 pub query: Option<String>,
1501}
1502
1503/// `admin_revoke_invite`: revokes any pending invite. Returns
1504/// `Outcome<Invite>`.
1505#[derive(Debug, Serialize, Deserialize)]
1506pub struct AdminRevokeInviteArgs {
1507 pub id: String,
1508 pub staff: String,
1509}
1510
1511// --- Shared invite links ---
1512//
1513// Before registration opened, staff handed groups shared invite links.
1514// None are made or used any more; staff still see which one an account
1515// was made with.
1516
1517/// The shared invite link an account was made with.
1518#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1519pub struct SharedInviteSource {
1520 pub id: String,
1521 pub label: String,
1522}
1523
1524#[cfg(test)]
1525mod deletion_tests {
1526 use super::{WorkspaceDeletion, protected_names};
1527
1528 #[test]
1529 fn only_billing_or_protection_stands_in_the_way() {
1530 let clear = WorkspaceDeletion {
1531 repositories: 2,
1532 projects: 1,
1533 members: 3,
1534 ..WorkspaceDeletion::default()
1535 };
1536 assert!(!clear.blocked());
1537 assert_eq!(clear.reason("acme"), None);
1538 let owing = WorkspaceDeletion {
1539 billing: Some("Pay first.".into()),
1540 ..WorkspaceDeletion::default()
1541 };
1542 assert!(owing.blocked());
1543 assert_eq!(owing.reason("acme").as_deref(), Some("Pay first."));
1544 let protected = WorkspaceDeletion {
1545 billing: Some("Pay first.".into()),
1546 protected: true,
1547 ..WorkspaceDeletion::default()
1548 };
1549 assert!(protected.blocked());
1550 assert_eq!(
1551 protected.reason("flagon-io").as_deref(),
1552 Some("flagon-io is protected and can never be deleted.")
1553 );
1554 }
1555
1556 #[test]
1557 fn flagon_is_protected_whatever_the_variable_says() {
1558 assert_eq!(protected_names(None), ["flagon-io"]);
1559 assert_eq!(protected_names(Some("")), ["flagon-io"]);
1560 assert_eq!(protected_names(Some(" , ")), ["flagon-io"]);
1561 assert_eq!(
1562 protected_names(Some("Flagon-IO, acme ,wsp_1")),
1563 ["flagon-io", "acme", "wsp_1"]
1564 );
1565 }
1566}