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