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