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