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