Skip to content
2,735 linesCodeBlameRaw

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1//! Invite-only registration: invite codes, allowances, the waitlist, and
2//! the one place every new account is made.
3//!
4//! [`Identity::create_account`] is the only way an account comes to exist.
5//! While `REGISTRATION_MODE` is `invite` (or unset), it needs an invite
6//! code: unknown, used, revoked and expired codes all get the same answer,
7//! an email-bound code works only with that address, and the code is spent
8//! in the same transaction that makes the account, so two people racing
9//! with one code cannot both get in.
10//!
11//! A code is 160 random bits in Crockford base32, shown as `g1t-` and eight
12//! groups of four. Only its SHA-256 is kept to find it, with a copy sealed
13//! under IDENTITY_KEY so whoever made it can copy the link again while it
14//! is pending.
15//!
16//! Each person may have `INVITES_PER_USER` (5) invites out: pending and
17//! used ones count, and a revoked or expired one that was never used comes
18//! back. Staff grant more in sudo, to a person or to a workspace, whose
19//! owners share them. Owners of the workspaces in
20//! `INVITE_STAFF_WORKSPACES` (g1t's own) have no limit. Inviting an address
Merge two kinds of invite, kept apart: an invite to g1t (Settings, invite-only only, no workspace unless asked) and an invitation to a workspace (its People page)21//! into a workspace always makes an invite bound to it, and, while g1t is
22//! invite-only, costs one only when the address has no account (the
23//! invitation then lets it make one), so the answer never says which.
24//! Once registration is open it costs nothing.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look25//!
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)26//! A code may instead be a shared invite link's, which staff hand to a
27//! group: it makes up to a set number of accounts, each its own, and is
28//! checked and spent here the same way (shared_invites.rs).
29//!
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look30//! Vars: REGISTRATION_MODE (`invite` | `open`), INVITES_PER_USER,
31//! INVITE_TTL_DAYS, INVITE_STAFF_WORKSPACES (comma separated slugs).
32
33use g1t_contracts::audit::{AuditActor, AuditOutcome, AuditTarget, NewAuditEntry, RecordAuditArgs, Surface};
34use g1t_contracts::events::{InviteCreated, InviteRedeemed, WaitlistRequested};
35use g1t_contracts::identity::*;
36use g1t_contracts::time::{SQL_NOW, rfc3339};
37use g1t_contracts::{FailureCode, Outcome, PrincipalKind, Role, User, new_id};
38use g1t_kit::now_ms;
39use g1t_secrets::Sealer;
40use serde::Deserialize;
41use worker::Result;
42use worker::wasm_bindgen::JsValue;
43
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)44use crate::shared_invites::{SharedAdmits, shared_admits, wrong_domain};
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look45use crate::{Identity, crypto};
46
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)47mod invitations;
48
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look49/// Crockford base32, as ids use: no i, l, o or u.
50const ALPHABET: &[u8; 32] = b"0123456789abcdefghjkmnpqrstvwxyz";
51/// 32 characters of 5 bits: 160 random bits.
52const CODE_LENGTH: usize = 32;
53const GROUP: usize = 4;
54
55pub const INVALID: &str =
56 "That invite code is not valid. It may have been used, revoked or expired; ask whoever invited you for a new one.";
57pub const WRONG_EMAIL: &str = "This invite is for a different email address. Use the address it was sent to.";
58pub const MISSING: &str = "g1t is invite-only for now. Enter your invite code, or request access.";
59const TOO_MANY: &str = "Too many attempts. Try again in an hour.";
60const PEOPLE_ONLY: &str = "Only a person can make invites, not an agent or a workspace's token.";
61const CONFIRM_FIRST: &str = "Confirm your email address before inviting anyone.";
62const BAD_EMAIL: &str = "Enter a valid email address.";
63
64const HOUR_MS: u64 = 60 * 60 * 1000;
65/// Invites one person may make in an hour, whatever their allowance.
66const CREATES_PER_HOUR: u32 = 20;
67/// Wrong codes one client may try in an hour before being turned away.
68const FAILURES_PER_HOUR: u32 = 20;
69/// Access requests from one client in an hour.
70const REQUESTS_PER_HOUR: u32 = 5;
71/// Access requests from clients that sent no address, together, in an hour.
72const ANONYMOUS_REQUESTS_PER_HOUR: u32 = 200;
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas73/// Confirmations of access requests, to everyone together, in an hour.
74const CONFIRMATIONS_PER_HOUR: u32 = 300;
75/// The least time between two summaries of new requests to staff.
76const SUMMARY_EVERY_MS: u64 = 15 * 60 * 1000;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look77/// The most invites a person's or workspace's list shows.
78const LIST_LIMIT: u32 = 200;
79/// How far down the invite tree staff see.
80const TREE_DEPTH: usize = 3;
81
82// --- Codes ------------------------------------------------------------------
83
84/// The 32 characters of a code from 20 random bytes.
85fn encode(bytes: &[u8; 20]) -> String {
86 let mut out = String::with_capacity(CODE_LENGTH);
87 let (mut buffer, mut bits) = (0u32, 0u32);
88 for &byte in bytes {
89 buffer = (buffer << 8) | u32::from(byte);
90 bits += 8;
91 while bits >= 5 {
92 bits -= 5;
93 out.push(ALPHABET[((buffer >> bits) & 31) as usize] as char);
94 }
95 buffer &= (1 << bits) - 1;
96 }
97 out
98}
99
100/// A new code's 32 characters.
101pub fn new_code_body() -> String {
102 let mut bytes = [0u8; 20];
103 getrandom::getrandom(&mut bytes).expect("no source of randomness");
104 encode(&bytes)
105}
106
107/// How a code is shown: `g1t-` and groups of four.
108pub fn format_code(body: &str) -> String {
109 let groups: Vec<&str> = body
110 .as_bytes()
111 .chunks(GROUP)
112 .map(|chunk| std::str::from_utf8(chunk).unwrap_or_default())
113 .collect();
114 format!("g1t-{}", groups.join("-"))
115}
116
117/// A code's 32 characters from however it was typed or pasted: any case,
118/// with or without `g1t-`, hyphens or spaces, or a whole invite link.
119/// Letters easily misread are read as Crockford reads them.
120pub fn normalize_code(input: &str) -> Option<String> {
121 let mut text = input.trim().to_ascii_lowercase();
122 // A pasted link: the last path segment, or the `invite` parameter.
123 if let Some(at) = text.find("invite=") {
124 text = text[at + "invite=".len()..].split('&').next().unwrap_or_default().to_owned();
125 } else if let Some(at) = text.rfind('/') {
126 text = text[at + 1..].to_owned();
127 }
128 let text = text.strip_prefix("g1t").unwrap_or(&text);
129 let mut body = String::with_capacity(CODE_LENGTH);
130 for c in text.chars() {
131 let c = match c {
132 '-' | ' ' | '_' => continue,
133 'i' | 'l' => '1',
134 'o' => '0',
135 c if ALPHABET.contains(&(c as u8)) && c.is_ascii() => c,
136 _ => return None,
137 };
138 body.push(c);
139 }
140 (body.len() == CODE_LENGTH).then_some(body)
141}
142
143/// What is stored to find a code.
144pub fn code_hash(body: &str) -> String {
145 crypto::sha256_hex(body)
146}
147
148/// The code's first group, kept to recognise it: 20 of its 160 bits.
149pub fn code_hint(body: &str) -> String {
150 format!("g1t-{}", &body[..GROUP])
151}
152
153// --- Rules --------------------------------------------------------------------
154
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)155/// Where an invite stands at `now`, from its row. A used invite whose
156/// account has not confirmed its address yet is awaiting confirmation
157/// (`applied_at` is null); revoking it then stops it joining anything.
158pub fn status_of(
159 revoked_at: Option<&str>,
160 redeemed_at: Option<&str>,
161 applied_at: Option<&str>,
162 expires_at: &str,
163 now: &str,
164) -> InviteStatus {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look165 if redeemed_at.is_some() {
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)166 if revoked_at.is_some() {
167 InviteStatus::Revoked
168 } else if applied_at.is_some() {
169 InviteStatus::Redeemed
170 } else {
171 InviteStatus::AwaitingConfirmation
172 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look173 } else if revoked_at.is_some() {
174 InviteStatus::Revoked
175 } else if expires_at <= now {
176 InviteStatus::Expired
177 } else {
178 InviteStatus::Pending
179 }
180}
181
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)182/// Where an invite stands once the workspace invitation in it is counted:
183/// `base` from [`status_of`]. A declined one is declined; an account
184/// invite whose account is confirmed but has not answered the workspace it
185/// names (`names_workspace`: one that still exists) awaits that answer
186/// until it expires.
187pub fn answered_status(
188 base: InviteStatus,
189 kind: &str,
190 names_workspace: bool,
191 accepted_at: Option<&str>,
192 declined_at: Option<&str>,
193 expires_at: &str,
194 now: &str,
195) -> InviteStatus {
196 if declined_at.is_some() && base != InviteStatus::Revoked {
197 return InviteStatus::Declined;
198 }
199 if base == InviteStatus::Redeemed && kind == "account" && names_workspace && accepted_at.is_none() {
200 return if expires_at <= now { InviteStatus::Expired } else { InviteStatus::AwaitingAnswer };
201 }
202 base
203}
204
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look205/// Whether an invite in this state uses up one of an allowance: pending
206/// and used ones do; a revoked or expired one never used gives it back.
207#[cfg(test)]
208pub fn counts_against_allowance(status: InviteStatus) -> bool {
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)209 matches!(
210 status,
211 InviteStatus::Pending | InviteStatus::AwaitingConfirmation | InviteStatus::AwaitingAnswer | InviteStatus::Redeemed
212 )
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look213}
214
215/// The SQL condition that matches [`counts_against_allowance`] for rows of
216/// `invites` aliased `i`.
217fn counted_sql() -> String {
218 format!("(i.redeemed_at IS NOT NULL OR (i.revoked_at IS NULL AND i.expires_at > {SQL_NOW}))")
219}
220
221/// How many invites someone may have out: the default plus staff grants,
222/// never below zero; None for no limit.
223pub fn limit_for(default: u32, granted: i64, unlimited: bool) -> Option<u32> {
224 if unlimited {
225 return None;
226 }
227 Some((i64::from(default) + granted).clamp(0, i64::from(u32::MAX)) as u32)
228}
229
230/// Why an invite cannot make an account.
231#[derive(Debug, PartialEq, Eq)]
232pub enum Refusal {
233 /// Unknown, used, revoked, expired, or not for making accounts. One
234 /// answer for all, so codes cannot be probed.
235 Invalid,
236 /// It is bound to another address.
237 WrongEmail,
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)238 /// A shared invite link limited to email domains the address is not
239 /// at (shared_invites.rs).
240 WrongDomain,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look241}
242
243/// The parts of an invite that decide whether it admits someone.
244#[derive(Debug)]
245pub struct Admits<'a> {
246 pub kind: &'a str,
247 pub email: Option<&'a str>,
248 pub status: InviteStatus,
249}
250
251/// Whether an invite lets `email` make an account (`for_account`) or join
252/// its workspace with an existing one.
253pub fn admits(invite: Option<&Admits>, email: &str, for_account: bool) -> std::result::Result<(), Refusal> {
254 let Some(invite) = invite else {
255 return Err(Refusal::Invalid);
256 };
257 if invite.status != InviteStatus::Pending || (for_account && invite.kind != "account") {
258 return Err(Refusal::Invalid);
259 }
260 match invite.email {
261 Some(bound) if !bound.eq_ignore_ascii_case(email.trim()) => Err(Refusal::WrongEmail),
262 _ => Ok(()),
263 }
264}
265
Merge invite emails that confirm the address: the emailed link carries a proof only that email has, so signing up from it needs no code; shared links and typed codes still confirm266/// The proof for an invite's email link, or None when there is none to
267/// make: no key (a development setup), or no address the invite is bound
268/// to. See [`crypto::invite_proof`].
269pub fn email_proof(key: &[u8], invite_id: &str, bound: Option<&str>) -> Option<String> {
270 let bound = bound.map(str::trim).filter(|bound| !bound.is_empty())?;
271 (!key.is_empty()).then(|| crypto::invite_proof(key, invite_id, bound))
272}
273
274/// Whether `proof` shows that whoever brings it followed the invite's own
275/// email: it is the proof for this invite and the address it is bound to,
276/// and `email`, the address the account is made with, is that address.
277/// Anything else (no proof, a wrong or altered one, another invite's, an
278/// invite bound to no address, a different address) proves nothing, and
279/// the address is confirmed as any other is.
280pub fn proves_email(key: &[u8], invite_id: &str, bound: Option<&str>, email: &str, proof: Option<&str>) -> bool {
281 let (Some(expected), Some(proof)) = (email_proof(key, invite_id, bound), proof.map(str::trim)) else {
282 return false;
283 };
284 let same_address = bound.is_some_and(|bound| bound.trim().to_lowercase() == email.trim().to_lowercase());
285 same_address && crypto::same(&expected, &proof.to_ascii_lowercase())
286}
287
288/// Whether a new account starts with its address confirmed: GitHub
289/// confirmed it (`verified`), or `invite`, the one-person invite that
290/// admitted it, was followed from its own email with `proof` and `email` is
291/// the address it was sent to. A shared link, a code typed in or passed on,
292/// or an invite bound to no address: confirmed as any other is.
293pub fn starts_confirmed(key: &[u8], verified: bool, invite: Option<&InviteRow>, email: &str, proof: Option<&str>) -> bool {
294 verified
295 || invite.is_some_and(|row| row.kind == "account" && proves_email(key, &row.id, row.email.as_deref(), email, proof))
296}
297
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)298/// What an invite used to sign up does once its account confirms its
299/// address.
300#[derive(Clone, Debug, PartialEq, Eq)]
301pub enum AwaitingJoin {
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)302 /// It invites the account to this workspace: a workspace invitation
303 /// now waits for its answer. Nothing is joined without one.
304 Invited { workspace_id: String, slug: String },
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)305 /// It names no workspace; repository invitations sent with it are
306 /// accepted.
307 Nothing,
308 /// It no longer applies, and why, as the person is told.
309 Lapsed(String),
310}
311
312/// [`AwaitingJoin`] for an invite's row at `now`. `row.workspace` is the
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)313/// workspace's slug, None once it was deleted. A workspace on the free
314/// plan still invites: accepting waits until it starts the plan (paid.rs).
315pub fn awaiting_join(row: &InviteRow, now: &str) -> AwaitingJoin {
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)316 let what = match &row.workspace {
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)317 Some(slug) => format!("no longer invites you to {slug}"),
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)318 None => "no longer applies".to_owned(),
319 };
320 if row.revoked_at.is_some() {
321 return AwaitingJoin::Lapsed(format!(
322 "Your email address is confirmed. The invite you signed up with was revoked while you were confirming it, so it {what}."
323 ));
324 }
325 if row.expires_at.as_str() <= now {
326 return AwaitingJoin::Lapsed(format!(
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)327 "Your email address is confirmed. The invite you signed up with expired before you confirmed it, so it {what}. Ask whoever invited you to invite you again."
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)328 ));
329 }
330 match (&row.workspace_id, &row.workspace) {
331 (None, _) => AwaitingJoin::Nothing,
332 (Some(_), None) => AwaitingJoin::Lapsed(
333 "Your email address is confirmed. The workspace your invite was for has been deleted, so the invite no longer applies.".to_owned(),
334 ),
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)335 (Some(workspace_id), Some(slug)) => AwaitingJoin::Invited { workspace_id: workspace_id.clone(), slug: slug.clone() },
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)336 }
337}
338
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look339/// A trimmed, lowercased address, if it looks like one.
340pub fn normalize_email(email: &str) -> Option<String> {
341 let email = email.trim().to_lowercase();
342 let well_formed = email.len() <= 254
343 && email
344 .split_once('@')
345 .is_some_and(|(local, domain)| !local.is_empty() && domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.') && !domain.contains('@'))
346 && !email.contains(char::is_whitespace);
347 well_formed.then_some(email)
348}
349
350/// An address with most of its local part hidden: `a•••@example.com`.
351pub fn mask_email(email: &str) -> String {
352 match email.split_once('@') {
353 Some((local, domain)) => {
354 let first: String = local.chars().take(1).collect();
355 format!("{first}•••@{domain}")
356 }
357 None => "•••".to_owned(),
358 }
359}
360
361/// The fixed window a moment falls in.
362pub fn bucket(now_ms: u64, window_ms: u64) -> u64 {
363 now_ms / window_ms
364}
365
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas366/// Whether staff may be sent a summary of new requests: none was sent yet,
367/// or the last went before `since` (15 minutes ago). RFC 3339 times.
368pub fn summary_due(last: Option<&str>, since: &str) -> bool {
369 last.is_none_or(|last| last <= since)
370}
371
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look372// --- Rows ---------------------------------------------------------------------
373
374const COLUMNS: &str = "i.id, i.hint, i.sealed_code, i.email, i.kind, i.workspace_id, w.slug AS workspace,
375 i.inviter_id, iu.username AS inviter, i.staff, i.charged_to, i.charged_workspace_id, i.created_at, i.expires_at,
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)376 i.revoked_at, i.redeemed_by, ru.username AS redeemer, i.redeemed_at, i.applied_at,
377 i.invitee_id, vu.username AS invitee, i.role, i.accepted_at, i.declined_at
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look378 FROM invites i
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member379 LEFT JOIN workspaces w ON w.id = i.workspace_id AND w.deleted_at IS NULL
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look380 LEFT JOIN users iu ON iu.id = i.inviter_id
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)381 LEFT JOIN users ru ON ru.id = i.redeemed_by
382 LEFT JOIN users vu ON vu.id = i.invitee_id";
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look383
384#[derive(Debug, Deserialize)]
385pub struct InviteRow {
386 pub id: String,
387 pub hint: String,
388 pub sealed_code: Option<String>,
389 pub email: Option<String>,
390 pub kind: String,
391 pub workspace_id: Option<String>,
392 pub workspace: Option<String>,
393 pub inviter_id: Option<String>,
394 pub inviter: Option<String>,
395 pub staff: Option<String>,
396 pub charged_to: String,
397 pub created_at: String,
398 pub expires_at: String,
399 pub revoked_at: Option<String>,
400 pub redeemer: Option<String>,
401 pub redeemed_at: Option<String>,
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)402 #[serde(default)]
403 pub applied_at: Option<String>,
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)404 /// The account a workspace invitation is for (invitations.rs).
405 #[serde(default)]
406 pub invitee_id: Option<String>,
407 #[serde(default)]
408 pub invitee: Option<String>,
409 /// `owner` or `member`; null is member.
410 #[serde(default)]
411 pub role: Option<String>,
412 #[serde(default)]
413 pub accepted_at: Option<String>,
414 #[serde(default)]
415 pub declined_at: Option<String>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look416}
417
418impl InviteRow {
419 pub fn status(&self, now: &str) -> InviteStatus {
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)420 answered_status(
421 status_of(
422 self.revoked_at.as_deref(),
423 self.redeemed_at.as_deref(),
424 self.applied_at.as_deref(),
425 &self.expires_at,
426 now,
427 ),
428 &self.kind,
429 self.workspace.is_some(),
430 self.accepted_at.as_deref(),
431 self.declined_at.as_deref(),
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)432 &self.expires_at,
433 now,
434 )
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look435 }
436
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)437 /// The role accepting it joins with.
438 pub fn joins_as(&self) -> Role {
439 if self.role.as_deref() == Some("owner") { Role::Owner } else { Role::Member }
440 }
441
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look442 fn admits(&self, now: &str) -> Admits<'_> {
443 Admits {
444 kind: &self.kind,
445 email: self.email.as_deref(),
446 status: self.status(now),
447 }
448 }
449}
450
451fn kind_of(kind: &str) -> InviteKind {
452 if kind == "workspace" { InviteKind::Workspace } else { InviteKind::Account }
453}
454
455fn charge_of(charged_to: &str) -> InviteCharge {
456 match charged_to {
457 "user" => InviteCharge::User,
458 "workspace" => InviteCharge::Workspace,
459 _ => InviteCharge::None,
460 }
461}
462
463#[derive(Deserialize)]
464struct Count {
465 n: f64,
466}
467
468#[derive(Deserialize)]
469struct Id {
470 id: String,
471}
472
473#[derive(Deserialize)]
474struct WaitlistRow {
475 id: String,
476 email: String,
477 about: Option<String>,
478 status: String,
479 invite_id: Option<String>,
480 decided_by: Option<String>,
481 decided_at: Option<String>,
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas482 #[serde(default)]
483 note: Option<String>,
484 #[serde(default)]
485 joined_as: Option<String>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look486 created_at: String,
487 updated_at: String,
488}
489
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas490const WAITLIST_COLUMNS: &str = "wl.id, wl.email, wl.about, wl.status, wl.invite_id, wl.decided_by, wl.decided_at, wl.note,
491 ju.username AS joined_as, wl.created_at, wl.updated_at
492 FROM waitlist wl
493 LEFT JOIN invites wi ON wi.id = wl.invite_id
494 LEFT JOIN users ju ON ju.id = wi.redeemed_by";
495
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look496impl From<WaitlistRow> for WaitlistEntry {
497 fn from(row: WaitlistRow) -> Self {
498 WaitlistEntry {
499 id: row.id,
500 email: row.email,
501 about: row.about,
502 status: match row.status.as_str() {
503 "invited" => WaitlistStatus::Invited,
504 "dismissed" => WaitlistStatus::Dismissed,
505 _ => WaitlistStatus::Waiting,
506 },
507 invite_id: row.invite_id,
508 decided_by: row.decided_by,
509 decided_at: row.decided_at,
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas510 note: row.note,
511 joined_as: row.joined_as,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look512 created_at: row.created_at,
513 updated_at: row.updated_at,
514 }
515 }
516}
517
518/// What a new account is made from.
519pub struct NewAccount<'a> {
520 /// Checked by the caller: valid, and free.
521 pub username: &'a str,
522 /// Lowercased and checked by the caller.
523 pub email: &'a str,
524 /// Empty for an account with no password (made through GitHub).
525 pub password_hash: &'a str,
526 /// Whether the address is confirmed already (GitHub's verified email).
527 pub verified: bool,
528 pub invite_code: Option<&'a str>,
Merge invite emails that confirm the address: the emailed link carries a proof only that email has, so signing up from it needs no code; shared links and typed codes still confirm529 /// The proof from the invite email's link ([`proves_email`]): when it
530 /// is the invite's and `email` is the address the invite was sent to,
531 /// the account starts with that address confirmed.
532 pub email_proof: Option<&'a str>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look533 /// Who is asking, for rate limits.
534 pub client: Option<&'a str>,
535}
536
537/// What an invite was made for.
538struct Draft<'a> {
539 email: Option<&'a str>,
540 kind: &'a str,
541 /// The workspace using it joins.
542 workspace_id: Option<&'a str>,
543 inviter: Option<&'a User>,
544 staff: Option<&'a str>,
545 /// `user`, `workspace` or `none`; the workspace for `workspace`; and
546 /// the limit when there is one.
547 charged_to: &'a str,
548 charged_workspace_id: Option<&'a str>,
549 limit: Option<u32>,
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)550 /// The account a workspace invitation is for, when it has one already.
551 invitee_id: Option<&'a str>,
552 /// The role joining `workspace_id` gives: `member` or `owner`.
553 role: Option<&'a str>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look554}
555
556impl Identity {
557 // --- Settings ---
558
559 pub fn registration_mode(&self) -> RegistrationMode {
560 RegistrationMode::parse(self.env.var("REGISTRATION_MODE").ok().map(|v| v.to_string()).as_deref())
561 }
562
563 /// Whether new accounts need an invite code.
564 pub fn invites_required(&self) -> bool {
565 self.registration_mode() == RegistrationMode::Invite
566 }
567
568 fn var_number(&self, name: &str) -> Option<u64> {
569 self.env.var(name).ok()?.to_string().trim().parse().ok()
570 }
571
572 fn invites_per_user(&self) -> u32 {
573 self.var_number("INVITES_PER_USER").map_or(INVITES_PER_USER, |n| n.min(u64::from(u32::MAX)) as u32)
574 }
575
576 fn invite_ttl_days(&self) -> u64 {
577 self.var_number("INVITE_TTL_DAYS").filter(|days| (1..=365).contains(days)).unwrap_or(INVITE_TTL_DAYS)
578 }
579
580 /// The workspaces whose owners invite without limit: g1t's own.
581 fn staff_workspaces(&self) -> Vec<String> {
582 self.env
583 .var("INVITE_STAFF_WORKSPACES")
584 .map(|v| v.to_string())
585 .unwrap_or_default()
586 .split(',')
587 .map(|slug| slug.trim().to_lowercase())
588 .filter(|slug| !slug.is_empty())
589 .collect()
590 }
591
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)592 pub(crate) fn invite_sealer(&self) -> Option<Sealer> {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look593 Sealer::new(&self.env.secret("IDENTITY_KEY").ok()?.to_string())
594 }
595
Merge invite emails that confirm the address: the emailed link carries a proof only that email has, so signing up from it needs no code; shared links and typed codes still confirm596 /// The key invite email proofs are made under: IDENTITY_KEY, or none
597 /// in a development setup without one (then no proof is made, and none
598 /// is accepted).
599 fn proof_key(&self) -> Vec<u8> {
600 self.env.secret("IDENTITY_KEY").map(|key| key.to_string().into_bytes()).unwrap_or_default()
601 }
602
603 /// The proof for the link of an invite emailed to `to`, the address it
604 /// is bound to; never shown anywhere but in that email.
605 pub(crate) fn email_proof_for(&self, invite_id: &str, to: &str) -> Option<String> {
606 email_proof(&self.proof_key(), invite_id, Some(to))
607 }
608
609 /// Whether `proof` shows the invite in `row` was followed from its own
610 /// email, by someone making an account with `email`.
611 fn proven(&self, row: &InviteRow, email: &str, proof: Option<&str>) -> bool {
612 starts_confirmed(&self.proof_key(), false, Some(row), email, proof)
613 }
614
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look615 // --- Rate limits ---
616
617 /// Counts one more hit on `key` this hour; false once past `limit`.
618 async fn hit(&self, key: &str, limit: u32) -> Result<bool> {
619 let now = bucket(now_ms(), HOUR_MS);
620 let hits = self
621 .db
622 .prepare(
623 "INSERT INTO rate_limits (key, bucket, hits) VALUES (?1, ?2, 1)
624 ON CONFLICT (key) DO UPDATE SET
625 hits = CASE WHEN rate_limits.bucket = excluded.bucket THEN rate_limits.hits + 1 ELSE 1 END,
626 bucket = excluded.bucket
627 RETURNING hits AS n",
628 )
629 .bind(&[key.into(), (now as f64).into()])?
630 .first::<Count>(None)
631 .await?
632 .map_or(1.0, |count| count.n);
633 if hits <= 1.0 {
634 // A new window: forget windows gone by.
635 self.db
636 .prepare("DELETE FROM rate_limits WHERE bucket < ?")
637 .bind(&[((now.saturating_sub(1)) as f64).into()])?
638 .run()
639 .await?;
640 }
641 Ok(hits <= f64::from(limit))
642 }
643
644 /// Hits on `key` this hour, without adding one.
645 async fn hits(&self, key: &str) -> Result<u32> {
646 Ok(self
647 .db
648 .prepare("SELECT hits AS n FROM rate_limits WHERE key = ? AND bucket = ?")
649 .bind(&[key.into(), (bucket(now_ms(), HOUR_MS) as f64).into()])?
650 .first::<Count>(None)
651 .await?
652 .map_or(0, |count| count.n as u32))
653 }
654
655 /// Whether `client` has tried too many wrong codes this hour.
656 async fn turned_away(&self, client: Option<&str>) -> Result<bool> {
657 Ok(match client {
658 Some(client) => self.hits(&format!("invite.fail:{}", crypto::sha256_hex(client))).await? >= FAILURES_PER_HOUR,
659 None => false,
660 })
661 }
662
663 async fn count_failure(&self, client: Option<&str>) -> Result<()> {
664 if let Some(client) = client {
665 self.hit(&format!("invite.fail:{}", crypto::sha256_hex(client)), FAILURES_PER_HOUR).await?;
666 }
667 Ok(())
668 }
669
670 // --- Reading ---
671
672 async fn invite_by_code(&self, code: &str) -> Result<Option<InviteRow>> {
673 let Some(body) = normalize_code(code) else {
674 return Ok(None);
675 };
676 self.db
677 .prepare(format!("SELECT {COLUMNS} WHERE i.code_hash = ?"))
678 .bind(&[code_hash(&body).into()])?
679 .first::<InviteRow>(None)
680 .await
681 }
682
683 async fn invite_by_id(&self, id: &str) -> Result<Option<InviteRow>> {
684 self.db
685 .prepare(format!("SELECT {COLUMNS} WHERE i.id = ?"))
686 .bind(&[id.into()])?
687 .first::<InviteRow>(None)
688 .await
689 }
690
691 /// An invite as shown, with its code when `reveal` and it is pending.
692 fn shown(&self, row: InviteRow, reveal: bool, staff_view: bool) -> Invite {
693 let now = rfc3339(now_ms());
694 let status = row.status(&now);
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)695 let role = row.workspace_id.is_some().then(|| row.joins_as());
696 // An invite sent to an address never says which account has it,
697 // until that account uses it.
698 let invitee = row.invitee.clone().filter(|_| row.email.is_none() || row.redeemed_at.is_some());
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look699 let code = if reveal && status == InviteStatus::Pending {
700 row.sealed_code
701 .as_deref()
702 .and_then(|sealed| self.invite_sealer()?.open(sealed, &row.id))
703 } else {
704 None
705 };
706 Invite {
707 id: row.id,
708 code,
709 hint: row.hint,
710 email: row.email,
711 kind: kind_of(&row.kind),
712 workspace: row.workspace,
713 status,
714 charged_to: charge_of(&row.charged_to),
715 invited_by: row.inviter,
716 redeemed_by: row.redeemer,
717 created_at: row.created_at,
718 expires_at: row.expires_at,
719 redeemed_at: row.redeemed_at,
720 revoked_at: row.revoked_at,
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)721 invitee,
722 role,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look723 staff: if staff_view { row.staff } else { None },
724 }
725 }
726
727 async fn rows(&self, filter: &str, binds: &[JsValue], limit: u32) -> Result<Vec<InviteRow>> {
728 self.db
729 .prepare(format!("SELECT {COLUMNS} {filter} ORDER BY i.created_at DESC, i.id DESC LIMIT {limit}"))
730 .bind(binds)?
731 .all()
732 .await?
733 .results::<InviteRow>()
734 }
735
736 async fn granted(&self, target: GrantTarget, id: &str) -> Result<i64> {
737 Ok(self
738 .db
739 .prepare("SELECT COALESCE(SUM(amount), 0) AS n FROM invite_grants WHERE target_kind = ? AND target_id = ?")
740 .bind(&[target.as_str().into(), id.into()])?
741 .first::<Count>(None)
742 .await?
743 .map_or(0, |count| count.n as i64))
744 }
745
746 async fn is_invite_staff(&self, user_id: &str) -> Result<bool> {
747 let staff = self.staff_workspaces();
748 if staff.is_empty() {
749 return Ok(false);
750 }
751 let marks = vec!["?"; staff.len()].join(", ");
752 let mut binds: Vec<JsValue> = vec![user_id.into()];
753 binds.extend(staff.iter().map(|slug| JsValue::from(slug.as_str())));
754 Ok(self
755 .db
756 .prepare(format!(
757 "SELECT count(*) AS n FROM workspace_members m JOIN workspaces w ON w.id = m.workspace_id
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member758 WHERE m.user_id = ? AND m.role = 'owner' AND w.deleted_at IS NULL AND w.slug IN ({marks})"
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look759 ))
760 .bind(&binds)?
761 .first::<Count>(None)
762 .await?
763 .is_some_and(|count| count.n > 0.0))
764 }
765
766 async fn used(&self, column: &'static str, id: &str, charged_to: &str) -> Result<u32> {
767 Ok(self
768 .db
769 .prepare(format!(
770 "SELECT count(*) AS n FROM invites i WHERE i.{column} = ? AND i.charged_to = ? AND {}",
771 counted_sql()
772 ))
773 .bind(&[id.into(), charged_to.into()])?
774 .first::<Count>(None)
775 .await?
776 .map_or(0, |count| count.n as u32))
777 }
778
779 /// A person's own allowance.
780 pub async fn user_allowance(&self, user_id: &str) -> Result<Allowance> {
781 let unlimited = self.is_invite_staff(user_id).await?;
782 let granted = self.granted(GrantTarget::User, user_id).await?;
783 let used = self.used("inviter_id", user_id, "user").await?;
784 Ok(Allowance::new(limit_for(self.invites_per_user(), granted, unlimited), used))
785 }
786
787 /// A workspace's shared allowance: only what staff granted it.
788 async fn workspace_allowance(&self, workspace_id: &str) -> Result<Allowance> {
789 let granted = self.granted(GrantTarget::Workspace, workspace_id).await?;
790 let used = self.used("charged_workspace_id", workspace_id, "workspace").await?;
791 Ok(Allowance::new(limit_for(0, granted, false), used))
792 }
793
794 async fn workspace_id(&self, slug: &str) -> Result<Option<String>> {
795 Ok(self
796 .db
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member797 .prepare("SELECT id FROM workspaces WHERE slug = ? AND deleted_at IS NULL")
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look798 .bind(&[slug.trim().to_lowercase().into()])?
799 .first::<Id>(None)
800 .await?
801 .map(|row| row.id))
802 }
803
804 /// Whether an address is any account's: confirmed on one, or the
805 /// address a new account signed up with (emails.rs).
806 async fn email_has_account(&self, email: &str) -> Result<bool> {
807 self.email_in_use(email).await
808 }
809
810 // --- The gate ---
811
812 /// Makes an account: the only place one is made. While registration is
813 /// invite-only, `invite_code` must admit `email`; the code is spent in
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)814 /// the same transaction as the account is made. What the invite gives
815 /// (a workspace, repository invitations) is applied once the address
Merge invite emails that confirm the address: the emailed link carries a proof only that email has, so signing up from it needs no code; shared links and typed codes still confirm816 /// is confirmed: at once for an address GitHub has confirmed or one
817 /// proven by the invite email's link ([`proves_email`]), otherwise
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)818 /// in the transaction that confirms it (emails.rs, `confirm_address`).
819 /// In open mode a code is used if it is good and otherwise ignored.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look820 pub async fn create_account(&self, new: NewAccount<'_>) -> Result<Outcome<User>> {
821 let required = self.invites_required();
822 let code = new.invite_code.map(str::trim).filter(|code| !code.is_empty());
823 let mut invite = None;
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)824 // A shared invite link's code instead (shared_invites.rs).
825 let mut shared = None;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look826 match code {
827 None if required => return Ok(Outcome::fail(FailureCode::Forbidden, MISSING)),
828 None => {}
829 Some(code) => {
830 if required && self.turned_away(new.client).await? {
831 return Ok(Outcome::fail(FailureCode::Conflict, TOO_MANY));
832 }
833 let row = self.invite_by_code(code).await?;
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)834 let link = match row {
835 None => self.shared_by_code(code).await?,
836 Some(_) => None,
837 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look838 let now = rfc3339(now_ms());
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)839 let verdict = match &link {
840 Some(link) => {
841 let domains = link.domains();
842 let admits = SharedAdmits { status: link.status(&now), domains: &domains };
843 shared_admits(Some(&admits), new.email)
844 }
845 None => admits(row.as_ref().map(|row| row.admits(&now)).as_ref(), new.email, true),
846 };
847 match verdict {
848 Ok(()) => (invite, shared) = (row, link),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look849 Err(_) if !required => {}
850 Err(refusal) => {
851 self.count_failure(new.client).await?;
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)852 let message = match refusal {
853 Refusal::WrongEmail => WRONG_EMAIL.to_owned(),
854 Refusal::WrongDomain => wrong_domain(&link.map(|link| link.domains()).unwrap_or_default()),
855 Refusal::Invalid => INVALID.to_owned(),
856 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look857 return Ok(Outcome::fail(FailureCode::Forbidden, message));
858 }
859 }
860 }
861 }
862
Merge invite emails that confirm the address: the emailed link carries a proof only that email has, so signing up from it needs no code; shared links and typed codes still confirm863 // An address GitHub has confirmed starts confirmed, and so does the
864 // address an invite was emailed to, when the link followed was the
865 // email's own: its proof is in no code the inviter sees or shares.
866 // The code alone proves nothing (it can be passed on), so without
867 // the proof the new account confirms the address like any other.
868 let verified = starts_confirmed(&self.proof_key(), new.verified, invite.as_ref(), new.email, new.email_proof);
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look869 let user = User {
870 id: new_id("usr", now_ms()),
871 username: new.username.to_owned(),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas872 verified,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look873 ..User::default()
874 };
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas875 let verified_at = if verified { SQL_NOW } else { "NULL" };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look876 let values = [
877 JsValue::from(user.id.as_str()),
878 new.username.into(),
879 new.email.into(),
880 new.password_hash.into(),
881 ];
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)882 let made = match (&invite, &shared) {
883 // Take a use of the shared link, then make the account only if
884 // this request took it: one transaction, counted in the
885 // statement that takes it, so racing past its uses is
886 // impossible.
887 (None, Some(link)) => self
888 .db
889 .batch(self.shared_account_statements(link, &values, verified_at)?)
890 .await
891 .map(|_| ()),
892 (None, None) => {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look893 self.db
894 .prepare(format!(
895 "INSERT INTO users (id, username, email, password_hash, email_verified_at)
896 VALUES (?, ?, ?, ?, {verified_at})"
897 ))
898 .bind(&values)?
899 .run()
900 .await
901 .map(|_| ())
902 }
903 // Spend the code, then make the account only if this request
904 // spent it: one transaction, so a second use finds it gone.
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)905 (Some(row), _) => {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look906 let mut insert = values.to_vec();
907 insert.extend([JsValue::from(row.id.as_str()), user.id.as_str().into()]);
908 self.db
909 .batch(vec![
910 self.db
911 .prepare(format!(
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)912 "UPDATE invites SET redeemed_by = ?1, invitee_id = ?1, redeemed_at = {SQL_NOW}, sealed_code = NULL
913 WHERE id = ?2 AND kind = 'account' AND redeemed_at IS NULL AND revoked_at IS NULL
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look914 AND expires_at > {SQL_NOW}"
915 ))
916 .bind(&[user.id.as_str().into(), row.id.as_str().into()])?,
917 self.db
918 .prepare(format!(
919 "INSERT INTO users (id, username, email, password_hash, email_verified_at)
920 SELECT ?, ?, ?, ?, {verified_at}
921 WHERE EXISTS (SELECT 1 FROM invites WHERE id = ? AND redeemed_by = ?)"
922 ))
923 .bind(&insert)?,
924 ])
925 .await
926 .map(|_| ())
927 }
928 };
929 if let Err(error) = made {
930 // Someone took the username or email a moment ago; nothing
931 // was written, the code included.
932 if error.to_string().contains("UNIQUE") {
933 return Ok(Outcome::fail(FailureCode::Conflict, "That username or email is already registered."));
934 }
935 return Err(error);
936 }
937 let exists = self
938 .db
939 .prepare("SELECT id FROM users WHERE id = ?")
940 .bind(&[user.id.as_str().into()])?
941 .first::<Id>(None)
942 .await?
943 .is_some();
944 if !exists {
945 // Another sign-up spent the code first.
946 self.count_failure(new.client).await?;
947 return Ok(Outcome::fail(FailureCode::Forbidden, INVALID));
948 }
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)949 // Nobody is left without a workspace: one of its own, unless its
950 // invite brings it into one (invitations.rs).
951 self.give_own_workspace(&user, invite.as_ref()).await;
952 // Confirmed already (GitHub, or the invite email): what the invite
953 // gives, now: a workspace it names is an invitation to accept,
954 // never joined without saying yes. Otherwise
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)955 // it waits, spent, for the address to be confirmed.
956 if let Some(row) = invite
957 && user.verified
958 {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look959 self.after_redeemed(&row, &user, true).await?;
960 }
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)961 // A shared link gives nothing to wait for: the account makes its
962 // own workspace.
963 if let Some(link) = shared {
964 self.announce(
965 "invite.redeemed",
966 Some(&user.id),
967 InviteRedeemed {
968 invite_id: link.id,
969 user_id: user.id.clone(),
970 inviter_id: None,
971 workspace_id: None,
972 created_account: true,
973 },
974 )
975 .await;
976 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look977 Ok(Outcome::Ok(user))
978 }
979
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)980 /// What using an invite gives, once its account is confirmed, and tells
981 /// the event log and audit log. A new account (`created_account`) is
982 /// invited to the workspace the invite names, to accept or decline
983 /// (invitations.rs): nobody joins a workspace without saying yes. An
984 /// existing account that opened the invite and accepted it
985 /// (`accept_invite`) joins now, with the role it names.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look986 async fn after_redeemed(&self, row: &InviteRow, user: &User, created_account: bool) -> Result<()> {
987 let mut joined = None;
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)988 if let (Some(workspace_id), Some(slug)) = (&row.workspace_id, &row.workspace) {
989 if created_account {
990 self.db
991 .prepare("UPDATE invites SET expires_at = max(expires_at, ?) WHERE id = ? AND accepted_at IS NULL")
992 .bind(&[self.answer_by().into(), row.id.as_str().into()])?
993 .run()
994 .await?;
995 self.invitation_sent(row, &user.username).await;
996 } else {
997 let role = if row.joins_as() == Role::Owner { "owner" } else { "member" };
998 self.db
999 .batch(vec![
1000 self.db
1001 .prepare(
1002 "INSERT OR IGNORE INTO workspace_members (workspace_id, user_id, role, created_at)
1003 VALUES (?, ?, ?, ?)",
1004 )
1005 .bind(&[workspace_id.as_str().into(), user.id.as_str().into(), role.into(), rfc3339(now_ms()).into()])?,
1006 self.db
1007 .prepare(format!("UPDATE invites SET accepted_at = {SQL_NOW} WHERE id = ? AND accepted_at IS NULL"))
1008 .bind(&[row.id.as_str().into()])?,
1009 ])
1010 .await?;
1011 joined = Some(slug.clone());
1012 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1013 }
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1014 self.db
1015 .prepare(format!("UPDATE invites SET applied_at = {SQL_NOW} WHERE id = ? AND applied_at IS NULL"))
1016 .bind(&[row.id.as_str().into()])?
1017 .run()
1018 .await?;
1019 self.settled(row, user, created_account, joined).await;
1020 Ok(())
1021 }
1022
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1023 /// When a workspace invitation made now, or handed to a new account
1024 /// now, stops working: the invite TTL from now, RFC 3339.
1025 pub(crate) fn answer_by(&self) -> String {
1026 rfc3339(now_ms() + self.invite_ttl_days() * 24 * HOUR_MS)
1027 }
1028
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1029 /// What follows an invite's workspace being joined (`joined`, by slug)
1030 /// or not: repository invitations sent with its code are accepted, and
1031 /// the event log and the workspace's audit log are told.
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1032 pub(crate) async fn settled(&self, row: &InviteRow, user: &User, created_account: bool, joined: Option<String>) {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1033 // A code sent with an invitation to collaborate on a repository:
1034 // using it accepts (access.rs).
1035 if let Err(error) = self.accept_invitations_of_code(&row.id, user).await {
1036 worker::console_error!("repository invitations for {} not accepted: {error}", row.id);
1037 }
1038 self.announce(
1039 "invite.redeemed",
1040 Some(&user.id),
1041 InviteRedeemed {
1042 invite_id: row.id.clone(),
1043 user_id: user.id.clone(),
1044 inviter_id: row.inviter_id.clone(),
1045 workspace_id: row.workspace_id.clone(),
1046 created_account,
1047 },
1048 )
1049 .await;
1050 if let Some(slug) = joined {
1051 let message = match &row.inviter {
1052 Some(inviter) => format!("Joined with an invite from {inviter}"),
1053 None => "Joined with an invite from g1t".to_owned(),
1054 };
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1055 let role = if row.joins_as() == Role::Owner { "an owner" } else { "a member" };
Merge main (membership, two-factor, GitHub repo roles) into tokens1056 self.audit_invites(user, "invite.redeemed", vec![slug.clone()], Surface::Web, message).await;
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1057 self.audit_invites(user, "member.added", vec![slug], Surface::Web, format!("{} joined as {role}", user.username)).await;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1058 }
1059 }
1060
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1061 /// The invite an account signed up with, while it waits for the account
1062 /// to confirm its address: spent, not yet applied.
1063 pub(crate) async fn awaiting_invite(&self, user_id: &str) -> Result<Option<InviteRow>> {
1064 Ok(self
1065 .rows(
1066 "WHERE i.redeemed_by = ? AND i.kind = 'account' AND i.redeemed_at IS NOT NULL AND i.applied_at IS NULL",
1067 &[user_id.into()],
1068 1,
1069 )
1070 .await?
1071 .into_iter()
1072 .next())
1073 }
1074
1075 /// What an awaiting invite does now that its account is being
1076 /// confirmed, worked out before the batch that confirms it (which
1077 /// checks the same again).
1078 pub(crate) async fn awaiting_join(&self, row: &InviteRow) -> AwaitingJoin {
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1079 awaiting_join(row, &rfc3339(now_ms()))
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1080 }
1081
1082 /// The statements that apply an awaiting invite, for the batch that
1083 /// confirms `user_id`'s address, after the statement that marks the
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1084 /// account confirmed: give a workspace invitation the invite TTL from
1085 /// now to be answered in, only if the account is confirmed now; then
1086 /// mark the invite settled, whatever it gave. Nothing is joined here:
1087 /// the person accepts the invitation (invitations.rs).
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1088 pub(crate) fn apply_invite_statements(
1089 &self,
1090 user_id: &str,
1091 row: &InviteRow,
1092 join: &AwaitingJoin,
1093 ) -> Result<Vec<worker::D1PreparedStatement>> {
1094 let confirmed = "EXISTS (SELECT 1 FROM users WHERE id = ?1 AND email_verified_at IS NOT NULL)";
1095 let mut statements = Vec::new();
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1096 if let AwaitingJoin::Invited { .. } = join {
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1097 statements.push(
1098 self.db
1099 .prepare(format!(
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1100 "UPDATE invites SET expires_at = max(expires_at, ?3)
1101 WHERE id = ?2 AND redeemed_by = ?1 AND applied_at IS NULL AND revoked_at IS NULL AND {confirmed}"
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1102 ))
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1103 .bind(&[user_id.into(), row.id.as_str().into(), self.answer_by().into()])?,
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1104 );
1105 }
1106 statements.push(
1107 self.db
1108 .prepare(format!(
1109 "UPDATE invites SET applied_at = {SQL_NOW}
1110 WHERE id = ?2 AND redeemed_by = ?1 AND applied_at IS NULL AND {confirmed}"
1111 ))
1112 .bind(&[user_id.into(), row.id.as_str().into()])?,
1113 );
1114 Ok(statements)
1115 }
1116
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1117 /// After the batch: the workspace the account is invited to, by slug,
1118 /// if the invitation still waits for its answer (and it is told in
1119 /// its inbox); and, unless the invite lapsed, the repository
1120 /// invitations, event and audit entries that follow using it.
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1121 pub(crate) async fn after_applied(&self, row: &InviteRow, user: &User, join: &AwaitingJoin) -> Result<Option<String>> {
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1122 let invited = match join {
1123 AwaitingJoin::Invited { slug, .. } => self
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1124 .db
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1125 .prepare(format!(
1126 "SELECT 1 AS n FROM invites WHERE id = ? AND applied_at IS NOT NULL AND revoked_at IS NULL
1127 AND accepted_at IS NULL AND declined_at IS NULL AND expires_at > {SQL_NOW}"
1128 ))
1129 .bind(&[row.id.as_str().into()])?
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1130 .first::<Count>(None)
1131 .await?
1132 .map(|_| slug.clone()),
1133 _ => None,
1134 };
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1135 if invited.is_some() {
1136 self.invitation_sent(row, &user.username).await;
1137 }
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1138 if !matches!(join, AwaitingJoin::Lapsed(_)) {
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1139 self.settled(row, user, true, None).await;
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1140 }
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1141 Ok(invited)
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1142 }
1143
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1144 // --- People's invites ---
1145
1146 fn draft_allowed(user: &User) -> Option<&'static str> {
1147 if user.kind != PrincipalKind::User || user.acting.is_some() {
1148 return Some(PEOPLE_ONLY);
1149 }
1150 if !user.verified {
1151 return Some(CONFIRM_FIRST);
1152 }
1153 None
1154 }
1155
1156 /// Stores a new invite and returns it with its code, or None when the
1157 /// allowance ran out between reading it and writing.
1158 async fn insert_invite(&self, draft: Draft<'_>) -> Result<Option<Invite>> {
1159 let body = new_code_body();
1160 let code = format_code(&body);
1161 let now = now_ms();
1162 let id = new_id("inv", now);
1163 let sealed = self.invite_sealer().map(|sealer| sealer.seal(&code, &id));
1164 let expires_at = rfc3339(now + self.invite_ttl_days() * 24 * HOUR_MS);
1165 let created_at = rfc3339(now);
1166 let opt = |value: Option<&str>| value.map_or(JsValue::NULL, JsValue::from);
1167 let mut binds = vec![
1168 JsValue::from(id.as_str()),
1169 code_hash(&body).into(),
1170 code_hint(&body).into(),
1171 opt(sealed.as_deref()),
1172 opt(draft.email),
1173 draft.kind.into(),
1174 opt(draft.workspace_id),
1175 opt(draft.inviter.map(|user| user.id.as_str())),
1176 opt(draft.staff),
1177 draft.charged_to.into(),
1178 opt(draft.charged_workspace_id),
1179 created_at.as_str().into(),
1180 expires_at.as_str().into(),
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1181 opt(draft.invitee_id),
1182 opt(draft.role),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1183 ];
1184 // The allowance is checked in the insert itself, so two invites made
1185 // at once cannot both take the last one.
1186 let guard = match (draft.charged_to, draft.limit) {
1187 ("user", Some(limit)) => {
1188 binds.extend([opt(draft.inviter.map(|user| user.id.as_str())), f64::from(limit).into()]);
1189 format!(
1190 "WHERE (SELECT count(*) FROM invites i WHERE i.inviter_id = ? AND i.charged_to = 'user' AND {}) < ?",
1191 counted_sql()
1192 )
1193 }
1194 ("workspace", Some(limit)) => {
1195 binds.extend([opt(draft.charged_workspace_id), f64::from(limit).into()]);
1196 format!(
1197 "WHERE (SELECT count(*) FROM invites i WHERE i.charged_workspace_id = ? AND i.charged_to = 'workspace' AND {}) < ?",
1198 counted_sql()
1199 )
1200 }
1201 _ => String::new(),
1202 };
1203 let inserted = self
1204 .db
1205 .prepare(format!(
1206 "INSERT INTO invites (id, code_hash, hint, sealed_code, email, kind, workspace_id, inviter_id,
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1207 staff, charged_to, charged_workspace_id, created_at, expires_at, invitee_id, role)
1208 SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? {guard}
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1209 RETURNING id"
1210 ))
1211 .bind(&binds)?
1212 .first::<Id>(None)
1213 .await?;
1214 if inserted.is_none() {
1215 return Ok(None);
1216 }
1217 self.announce(
1218 "invite.created",
1219 draft.inviter.map(|user| user.id.as_str()),
1220 InviteCreated {
1221 invite_id: id.clone(),
1222 inviter_id: draft.inviter.map(|user| user.id.clone()),
1223 workspace_id: draft.workspace_id.map(str::to_owned),
1224 bound: draft.email.is_some(),
1225 },
1226 )
1227 .await;
1228 let Some(row) = self.invite_by_id(&id).await? else {
1229 return Ok(None);
1230 };
1231 let mut invite = self.shown(row, false, false);
1232 invite.code = Some(code);
1233 Ok(Some(invite))
1234 }
1235
1236 fn out_of_invites() -> Outcome<Invite> {
1237 Outcome::fail(
1238 FailureCode::Limit,
1239 "You have no invites left. Need more? Contact us at hey@flagon.io with the subject [g1t Invites].",
1240 )
1241 }
1242
1243 pub async fn create_invite(&self, a: CreateInviteArgs) -> Result<Outcome<Invite>> {
1244 if let Some(reason) = Self::draft_allowed(&a.user) {
1245 return Ok(Outcome::fail(FailureCode::Forbidden, reason));
1246 }
1247 let email = match a.email.as_deref().map(str::trim).filter(|email| !email.is_empty()) {
1248 Some(email) => match normalize_email(email) {
1249 Some(email) => Some(email),
1250 None => return Ok(Outcome::fail(FailureCode::Invalid, BAD_EMAIL)),
1251 },
1252 None => None,
1253 };
1254 if !self.hit(&format!("invite.create:{}", a.user.id), CREATES_PER_HOUR).await? {
1255 return Ok(Outcome::fail(FailureCode::Conflict, TOO_MANY));
1256 }
1257 if let Some(email) = &email {
1258 if self.email_has_account(email).await? {
1259 return Ok(Outcome::fail(
1260 FailureCode::Conflict,
1261 "That address already has a g1t account. Add them to a workspace from its People page instead.",
1262 ));
1263 }
1264 let pending = self
1265 .rows(
1266 &format!(
1267 "WHERE i.inviter_id = ? AND i.email = ? AND i.redeemed_at IS NULL AND i.revoked_at IS NULL AND i.expires_at > {SQL_NOW}"
1268 ),
1269 &[a.user.id.as_str().into(), email.as_str().into()],
1270 1,
1271 )
1272 .await?;
1273 if !pending.is_empty() {
1274 return Ok(Outcome::fail(
1275 FailureCode::Conflict,
1276 "You already have a pending invite for that address. Revoke it to send a new one.",
1277 ));
1278 }
1279 }
1280 // A workspace's granted invites, for its owners.
1281 let (workspace_id, charged_to, limit) = match a.workspace.as_deref().map(str::trim).filter(|slug| !slug.is_empty()) {
1282 Some(slug) => {
1283 let slug = slug.to_lowercase();
1284 if a.user.role_in(&slug) != Some(Role::Owner) {
1285 return Ok(Outcome::fail(FailureCode::Forbidden, "Only a workspace's owners can use its invites."));
1286 }
1287 let Some(id) = self.workspace_id(&slug).await? else {
1288 return Ok(Outcome::fail(FailureCode::NotFound, "Workspace not found."));
1289 };
1290 let allowance = self.workspace_allowance(&id).await?;
1291 if allowance.exhausted() {
1292 return Ok(Outcome::fail(
1293 FailureCode::Limit,
1294 format!("{slug} has no invites left. Need more? Contact us at hey@flagon.io with the subject [g1t Invites]."),
1295 ));
1296 }
1297 (Some(id), "workspace", allowance.limit)
1298 }
1299 None => {
1300 let allowance = self.user_allowance(&a.user.id).await?;
1301 if allowance.exhausted() {
1302 return Ok(Self::out_of_invites());
1303 }
1304 (None, "user", allowance.limit)
1305 }
1306 };
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1307 // The workspace it brings them into, if any (invitations.rs).
1308 let joins = match self.joinable_workspace(&a.user, a.join.as_deref()).await? {
1309 Outcome::Ok(joins) => joins,
1310 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
1311 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1312 let draft = Draft {
1313 email: email.as_deref(),
1314 kind: "account",
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1315 workspace_id: joins.as_ref().map(|(id, _)| id.as_str()),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1316 inviter: Some(&a.user),
1317 staff: None,
1318 charged_to,
1319 charged_workspace_id: workspace_id.as_deref(),
1320 limit,
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1321 invitee_id: None,
Merge two kinds of invite, kept apart: an invite to g1t (Settings, invite-only only, no workspace unless asked) and an invitation to a workspace (its People page)1322 role: joins.as_ref().map(|_| if a.join_role == Some(Role::Owner) { "owner" } else { "member" }),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1323 };
1324 let Some(invite) = self.insert_invite(draft).await? else {
1325 return Ok(Self::out_of_invites());
1326 };
1327 if let (Some(email), Some(code)) = (&email, &invite.code) {
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1328 let from = self.display_name(&a.user).await;
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1329 let workspace = match &joins {
1330 Some((id, slug)) => Some(self.workspace_name(id, slug).await),
1331 None => None,
1332 };
1333 self.send_invite_email(email, Some(&from), workspace.as_deref(), false, code, &invite.id, None).await;
1334 }
1335 let mut logs: Vec<String> = a.user.workspaces.iter().map(|membership| membership.slug.clone()).collect();
1336 if let Some((_, slug)) = &joins {
1337 logs = vec![slug.clone()];
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1338 }
1339 self.audit_invites(&a.user, "invite.created", logs, a.surface.unwrap_or(Surface::Web), format!("Created invite {}", invite.hint))
1340 .await;
1341 Ok(Outcome::Ok(invite))
1342 }
1343
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1344 async fn send_invite_email(
1345 &self,
1346 to: &str,
1347 from: Option<&str>,
1348 workspace: Option<&str>,
1349 existing: bool,
1350 code: &str,
Merge invite emails that confirm the address: the emailed link carries a proof only that email has, so signing up from it needs no code; shared links and typed codes still confirm1351 invite_id: &str,
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1352 note: Option<&str>,
1353 ) {
Merge invite emails that confirm the address: the emailed link carries a proof only that email has, so signing up from it needs no code; shared links and typed codes still confirm1354 // An invite that makes an account carries the proof that the link
1355 // came from this email; one for an existing account has nothing
1356 // to prove.
1357 let proof = if existing { None } else { self.email_proof_for(invite_id, to) };
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1358 let invite = crate::email::InviteEmail {
1359 to,
1360 from,
1361 workspace,
1362 joins_existing_account: existing,
1363 code,
Merge invite emails that confirm the address: the emailed link carries a proof only that email has, so signing up from it needs no code; shared links and typed codes still confirm1364 proof: proof.as_deref(),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1365 days: self.invite_ttl_days(),
1366 note,
1367 };
1368 if let Err(error) = crate::email::send_invite(&self.env, &invite).await {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1369 worker::console_error!("invite email failed: {error}");
1370 }
1371 }
1372
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1373 /// How an invite names the person who sent it: their name, else their
1374 /// username.
1375 async fn display_name(&self, user: &User) -> String {
1376 self.name_of("SELECT display_name AS name FROM users WHERE id = ?", &user.id)
1377 .await
1378 .unwrap_or_else(|| user.username.clone())
1379 }
1380
1381 /// A workspace's name, as an invite shows it; its slug if it has none.
1382 async fn workspace_name(&self, workspace_id: &str, slug: &str) -> String {
1383 self.name_of("SELECT name FROM workspaces WHERE id = ?", workspace_id)
1384 .await
1385 .unwrap_or_else(|| slug.to_owned())
1386 }
1387
1388 /// A name `sql` selects for `id`, if it has one. Only for wording an
1389 /// email, so a failed read is no name.
1390 async fn name_of(&self, sql: &str, id: &str) -> Option<String> {
1391 #[derive(Deserialize)]
1392 struct Name {
1393 name: Option<String>,
1394 }
1395 let read = async { self.db.prepare(sql).bind(&[id.into()])?.first::<Name>(None).await };
1396 read.await
1397 .ok()
1398 .flatten()
1399 .and_then(|row| row.name)
1400 .map(|name| name.trim().to_owned())
1401 .filter(|name| !name.is_empty())
1402 }
1403
1404 /// The address a pending invite is bound to, if it is: signing up with
1405 /// GitHub uses it when GitHub has confirmed it too (github.rs).
1406 pub(crate) async fn bound_email_of(&self, code: &str) -> Result<Option<String>> {
1407 let now = rfc3339(now_ms());
1408 Ok(self
1409 .invite_by_code(code)
1410 .await?
1411 .filter(|row| row.status(&now) == InviteStatus::Pending)
1412 .and_then(|row| row.email))
1413 }
1414
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1415 pub async fn list_invites(&self, a: UserArgs) -> Result<InvitesOverview> {
1416 let invites: Vec<Invite> = self
1417 .rows("WHERE i.inviter_id = ?", &[a.user.id.as_str().into()], LIST_LIMIT)
1418 .await?
1419 .into_iter()
1420 .map(|row| self.shown(row, true, false))
1421 .collect();
1422 let mut workspaces = Vec::new();
1423 for membership in a.user.workspaces.iter().filter(|membership| membership.role == Role::Owner) {
1424 if let Some(id) = self.workspace_id(&membership.slug).await?
1425 && self.granted(GrantTarget::Workspace, &id).await? != 0
1426 {
1427 workspaces.push(WorkspaceAllowance {
1428 slug: membership.slug.clone(),
1429 allowance: self.workspace_allowance(&id).await?,
1430 });
1431 }
1432 }
1433 Ok(InvitesOverview {
1434 mode: self.registration_mode(),
1435 allowance: self.user_allowance(&a.user.id).await?,
1436 workspaces,
1437 invites,
1438 })
1439 }
1440
1441 /// Revokes a pending invite the person made, or one made for (or
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1442 /// charged to) a workspace they own. An invite used to sign up whose
1443 /// account has not confirmed its address yet can be revoked too: the
1444 /// account stays, and joins nothing when it confirms.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1445 pub async fn revoke_invite(&self, a: RemoveArgs) -> Result<Outcome<Invite>> {
1446 if a.user.kind != PrincipalKind::User || a.user.acting.is_some() {
1447 return Ok(Outcome::fail(FailureCode::Forbidden, PEOPLE_ONLY));
1448 }
1449 let revoked = self
1450 .db
1451 .prepare(format!(
1452 "UPDATE invites SET revoked_at = {SQL_NOW}, sealed_code = NULL
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1453 WHERE id = ?2 AND revoked_at IS NULL AND declined_at IS NULL
1454 AND (redeemed_at IS NULL OR applied_at IS NULL
1455 -- A workspace invitation not yet answered.
1456 OR (workspace_id IS NOT NULL AND accepted_at IS NULL))
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1457 AND (inviter_id = ?1
1458 OR workspace_id IN (SELECT workspace_id FROM workspace_members WHERE user_id = ?1 AND role = 'owner')
1459 OR charged_workspace_id IN (SELECT workspace_id FROM workspace_members WHERE user_id = ?1 AND role = 'owner'))
1460 RETURNING id"
1461 ))
1462 .bind(&[a.user.id.as_str().into(), a.id.as_str().into()])?
1463 .first::<Id>(None)
1464 .await?;
1465 let Some(Id { id }) = revoked else {
1466 return Ok(Outcome::fail(FailureCode::NotFound, "There is no pending invite of yours with that id."));
1467 };
1468 let Some(row) = self.invite_by_id(&id).await? else {
1469 return Ok(Outcome::fail(FailureCode::NotFound, "Invite not found."));
1470 };
1471 let logs = match &row.workspace {
1472 Some(slug) => vec![slug.clone()],
1473 None => a.user.workspaces.iter().map(|membership| membership.slug.clone()).collect(),
1474 };
1475 self.audit_invites(&a.user, "invite.revoked", logs, Surface::Web, format!("Revoked invite {}", row.hint)).await;
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1476 self.invitation_revoked(&a.user, &row).await;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1477 Ok(Outcome::Ok(self.shown(row, false, false)))
1478 }
1479
1480 /// What an invite code is for: who sent it, and which workspace it
1481 /// joins. Any code that cannot be used gets the same answer.
1482 pub async fn check_invite(&self, a: InviteCodeArgs) -> Result<Outcome<InvitePreview>> {
1483 if self.turned_away(a.client.as_deref()).await? {
1484 return Ok(Outcome::fail(FailureCode::Conflict, TOO_MANY));
1485 }
1486 let now = rfc3339(now_ms());
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)1487 let found = self.invite_by_code(&a.code).await?;
1488 // A shared invite link's code, while it is live: its label and
1489 // domains are for the sign-up page. Expired, revoked and used up
1490 // get the one answer below, whatever `any_status` asks.
1491 if found.is_none()
1492 && let Some(link) = self.shared_by_code(&a.code).await?
1493 && link.status(&now) == SharedInviteStatus::Live
1494 {
1495 return Ok(Outcome::Ok(self.shared_preview(&link)));
1496 }
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1497 // A spent code is still a real one (160 random bits): saying what
1498 // became of it tells a guesser nothing.
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)1499 let row = found.filter(|row| a.any_status || row.status(&now) == InviteStatus::Pending);
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1500 let Some(row) = row else {
1501 self.count_failure(a.client.as_deref()).await?;
1502 return Ok(Outcome::fail(FailureCode::NotFound, INVALID));
1503 };
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1504 let status = row.status(&now);
1505 let pending = status == InviteStatus::Pending;
1506 // Whether it is the viewer's: for one of their confirmed addresses,
1507 // or, once used, used by them.
1508 let for_viewer = match &a.viewer {
1509 Some(viewer) if viewer.kind == PrincipalKind::User => match (&row.email, status) {
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)1510 (_, InviteStatus::Redeemed | InviteStatus::AwaitingConfirmation) => {
1511 Some(row.redeemer.as_deref() == Some(viewer.username.as_str()))
1512 }
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1513 (Some(bound), _) => {
1514 let mine = self.verified_emails(&viewer.id).await?;
1515 Some(mine.iter().any(|address| address.eq_ignore_ascii_case(bound.trim())))
1516 }
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1517 // An invitation to someone by username is theirs alone.
1518 (None, _) => row.invitee_id.as_ref().map(|invitee| *invitee == viewer.id),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1519 },
1520 _ => None,
1521 };
1522 let has_account = match (&row.email, pending) {
1523 (Some(bound), true) => self.email_has_account(bound).await?,
1524 _ => false,
1525 };
1526 let repository = self.repository_of_code(&row.id).await?;
Merge invite emails that confirm the address: the emailed link carries a proof only that email has, so signing up from it needs no code; shared links and typed codes still confirm1527 // Opened from the invite's own email: the account it makes starts
1528 // with the address confirmed. Said only while it can make one.
1529 let email_proven = pending
1530 && !has_account
1531 && row.email.as_deref().is_some_and(|bound| self.proven(&row, bound, a.email_proof.as_deref()));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1532 #[derive(Deserialize)]
1533 struct From {
1534 username: String,
1535 name: Option<String>,
1536 avatar: Option<String>,
1537 }
1538 let invited_by = match &row.inviter_id {
1539 Some(id) => self
1540 .db
1541 .prepare("SELECT username, display_name AS name, avatar FROM users WHERE id = ?")
1542 .bind(&[id.as_str().into()])?
1543 .first::<From>(None)
1544 .await?
1545 .map(|from| InviteFrom {
1546 username: from.username,
1547 name: from.name,
1548 avatar: from.avatar,
1549 }),
1550 None => None,
1551 };
1552 let workspace = match &row.workspace_id {
1553 Some(id) => self
1554 .db
1555 .prepare("SELECT slug, name, avatar FROM workspaces WHERE id = ?")
1556 .bind(&[id.as_str().into()])?
1557 .first::<ProfileWorkspace>(None)
1558 .await?,
1559 None => None,
1560 };
1561 Ok(Outcome::Ok(InvitePreview {
1562 kind: kind_of(&row.kind),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1563 status,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1564 invited_by,
1565 workspace,
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1566 repository,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1567 email: row.email.as_deref().map(mask_email),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1568 address: row.email.clone().filter(|_| pending),
1569 has_account,
1570 for_viewer,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1571 expires_at: row.expires_at,
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)1572 shared_label: None,
1573 shared_domains: Vec::new(),
Merge invite emails that confirm the address: the emailed link carries a proof only that email has, so signing up from it needs no code; shared links and typed codes still confirm1574 email_proven,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1575 }))
1576 }
1577
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1578 /// A signed-in person uses a workspace invite sent to their address,
1579 /// or one sent with a repository invitation.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1580 pub async fn accept_invite(&self, a: AcceptInviteArgs) -> Result<Outcome<String>> {
1581 if a.user.kind != PrincipalKind::User || a.user.acting.is_some() {
1582 return Ok(Outcome::fail(FailureCode::Forbidden, "Only a person can accept an invite."));
1583 }
1584 // Any of the person's confirmed addresses can match an invite bound
1585 // to one (emails.rs); the primary otherwise.
1586 let verified = self.verified_emails(&a.user.id).await?;
1587 let Some(primary) = verified.first().cloned() else {
1588 return Ok(Outcome::fail(FailureCode::Forbidden, "Confirm your email address first, then open the invite again."));
1589 };
1590 let now = rfc3339(now_ms());
1591 let row = self.invite_by_code(&a.code).await?;
1592 let email = row
1593 .as_ref()
1594 .and_then(|row| row.email.as_deref())
1595 .and_then(|bound| verified.iter().find(|address| address.eq_ignore_ascii_case(bound.trim())).cloned())
1596 .unwrap_or(primary);
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1597 // What using it gives an account that exists: a workspace, or a
1598 // repository it was sent with.
1599 let repository = match &row {
1600 Some(row) => self.repository_of_code(&row.id).await?,
1601 None => None,
1602 };
1603 let joins = row.as_ref().is_some_and(joins_workspace) || repository.is_some();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1604 if let Err(refusal) = admits(row.as_ref().map(|row| row.admits(&now)).as_ref(), &email, false) {
1605 return Ok(Outcome::fail(
1606 FailureCode::Forbidden,
1607 if refusal == Refusal::WrongEmail { WRONG_EMAIL } else { INVALID },
1608 ));
1609 }
1610 let Some(row) = row.filter(|_| joins) else {
1611 return Ok(Outcome::fail(
1612 FailureCode::Conflict,
1613 "You already have a g1t account, so this invite has nothing more to give you. Pass it on to someone who needs it.",
1614 ));
1615 };
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1616 // An invitation to one account works for that account only.
1617 if row.invitee_id.as_deref().is_some_and(|invitee| invitee != a.user.id) {
1618 return Ok(Outcome::fail(
1619 FailureCode::Forbidden,
1620 "This invitation is for a different g1t account. Sign in as the account it was sent to.",
1621 ));
1622 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1623 // What the workspace asks of its members (security.rs); nothing yet.
1624 if let Some(slug) = row.workspace.as_deref()
1625 && let Some(why) = self.policy_refusal(&a.user.id, slug).await?
1626 {
1627 return Ok(Outcome::fail(FailureCode::Forbidden, why));
1628 }
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1629 // An invite sent before the workspace was free waits until it
1630 // starts the plan (paid.rs); the code is not used up.
1631 let joins_slug = row.workspace.clone().or_else(|| {
1632 repository.as_ref().and_then(|r| r.name.split_once('/').map(|(workspace, _)| workspace.to_owned()))
1633 });
1634 if let Some(slug) = joins_slug.as_deref()
1635 && let Some(refused) = self.free_workspace_refusal(slug).await?
1636 {
1637 return Ok(refused);
1638 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1639 let claimed = self
1640 .db
1641 .prepare(format!(
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1642 "UPDATE invites SET redeemed_by = ?1, invitee_id = COALESCE(invitee_id, ?1), redeemed_at = {SQL_NOW}, sealed_code = NULL
1643 WHERE id = ?2 AND redeemed_at IS NULL AND revoked_at IS NULL AND declined_at IS NULL AND expires_at > {SQL_NOW}
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1644 RETURNING id"
1645 ))
1646 .bind(&[a.user.id.as_str().into(), row.id.as_str().into()])?
1647 .first::<Id>(None)
1648 .await?;
1649 if claimed.is_none() {
1650 return Ok(Outcome::fail(FailureCode::Forbidden, INVALID));
1651 }
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1652 let lands = row
1653 .workspace
1654 .clone()
1655 .or_else(|| repository.map(|repository| repository.name))
1656 .unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1657 self.after_redeemed(&row, &a.user, false).await?;
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1658 Ok(Outcome::Ok(lands))
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1659 }
1660
1661 // --- Workspace invitations ---
1662
1663 pub async fn invite_member(&self, a: InviteMemberArgs) -> Result<Outcome<Invite>> {
1664 let slug = a.slug.trim().to_lowercase();
1665 if let Some(reason) = Self::draft_allowed(&a.actor) {
1666 return Ok(Outcome::fail(FailureCode::Forbidden, reason));
1667 }
1668 if a.actor.role_in(&slug) != Some(Role::Owner) {
1669 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can invite people to a workspace."));
1670 }
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1671 // A username, or an address; an address typed in the username's
1672 // place is an address.
1673 let username = a
1674 .username
1675 .as_deref()
1676 .map(|name| name.trim().trim_start_matches('@').to_lowercase())
1677 .filter(|name| !name.is_empty() && !name.contains('@'));
1678 let email = match (&username, normalize_email(a.username.as_deref().unwrap_or(&a.email))) {
1679 (Some(_), _) => None,
1680 (None, Some(email)) => Some(email),
1681 (None, None) => return Ok(Outcome::fail(FailureCode::Invalid, "Enter a g1t username or a valid email address.")),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1682 };
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1683 let role = a.role.unwrap_or(Role::Member);
1684 let role_name = if role == Role::Owner { "owner" } else { "member" };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1685 let Some(workspace_id) = self.workspace_id(&slug).await? else {
1686 return Ok(Outcome::fail(FailureCode::NotFound, "Workspace not found."));
1687 };
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1688 // A free workspace invites no one until it starts the plan (paid.rs).
1689 if let Some(refused) = self.free_workspace_refusal(&slug).await? {
1690 return Ok(refused);
1691 }
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1692 let surface = a.surface.unwrap_or(Surface::Web);
1693 // Someone on g1t, by username: an invitation to accept or decline
1694 // (invites/invitations.rs).
1695 let Some(email) = email else {
1696 let username = username.unwrap_or_default();
1697 return self.invite_account(&a.actor, &slug, &workspace_id, &username, role, surface).await;
1698 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1699 if !self.hit(&format!("invite.create:{}", a.actor.id), CREATES_PER_HOUR).await? {
1700 return Ok(Outcome::fail(FailureCode::Conflict, TOO_MANY));
1701 }
1702 let pending = self
1703 .rows(
1704 &format!(
1705 "WHERE i.workspace_id = ? AND i.email = ?
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1706 AND i.redeemed_at IS NULL AND i.revoked_at IS NULL AND i.declined_at IS NULL AND i.expires_at > {SQL_NOW}"
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1707 ),
1708 &[workspace_id.as_str().into(), email.as_str().into()],
1709 1,
1710 )
1711 .await?;
1712 if !pending.is_empty() {
1713 return Ok(Outcome::fail(
1714 FailureCode::Conflict,
1715 "There is already a pending invite for that address. Revoke it to send a new one.",
1716 ));
1717 }
1718 let has_account = self.email_has_account(&email).await?;
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1719 // The account that has confirmed the address, which the invitation
1720 // is for. Never shown to the inviter: the answer does not say
1721 // whether the address has an account.
1722 let invitee = self.user_with_verified_email(&email).await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1723 let draft = if has_account {
1724 // Costs nothing: the person is on g1t already.
1725 Draft {
1726 email: Some(&email),
1727 kind: "workspace",
1728 workspace_id: Some(&workspace_id),
1729 inviter: Some(&a.actor),
1730 staff: None,
1731 charged_to: "none",
1732 charged_workspace_id: None,
1733 limit: None,
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1734 invitee_id: invitee.as_deref(),
1735 role: Some(role_name),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1736 }
1737 } else {
Merge two kinds of invite, kept apart: an invite to g1t (Settings, invite-only only, no workspace unless asked) and an invitation to a workspace (its People page)1738 // While g1t is invite-only, the invitation also lets the address
1739 // make its account, so it costs an invite: the workspace's shared
1740 // ones first, then the owner's own. Once anyone can sign up, an
1741 // account needs no invite and it costs nothing.
1742 let (charged_to, charged_workspace_id, limit) = if self.invites_required() {
1743 let shared = self.workspace_allowance(&workspace_id).await?;
1744 if shared.remaining.is_some_and(|left| left > 0) {
1745 ("workspace", Some(workspace_id.as_str()), shared.limit)
1746 } else {
1747 let own = self.user_allowance(&a.actor.id).await?;
1748 if own.exhausted() {
1749 return Ok(Self::out_of_invites());
1750 }
1751 ("user", None, own.limit)
1752 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1753 } else {
Merge two kinds of invite, kept apart: an invite to g1t (Settings, invite-only only, no workspace unless asked) and an invitation to a workspace (its People page)1754 ("none", None, None)
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1755 };
1756 Draft {
1757 email: Some(&email),
1758 kind: "account",
1759 workspace_id: Some(&workspace_id),
1760 inviter: Some(&a.actor),
1761 staff: None,
1762 charged_to,
1763 charged_workspace_id,
1764 limit,
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1765 invitee_id: None,
1766 role: Some(role_name),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1767 }
1768 };
1769 let Some(invite) = self.insert_invite(draft).await? else {
1770 return Ok(Self::out_of_invites());
1771 };
1772 if let Some(code) = &invite.code {
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1773 let from = self.display_name(&a.actor).await;
1774 let workspace = self.workspace_name(&workspace_id, &slug).await;
Merge invite emails that confirm the address: the emailed link carries a proof only that email has, so signing up from it needs no code; shared links and typed codes still confirm1775 self.send_invite_email(&email, Some(&from), Some(&workspace), has_account, code, &invite.id, None).await;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1776 }
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1777 // Someone on g1t hears of it in their inbox too.
1778 if invitee.is_some()
1779 && let Some(row) = self.invite_by_id(&invite.id).await?
1780 && let Some(username) = row.invitee.clone()
1781 {
1782 self.invitation_sent(&row, &username).await;
1783 }
1784 self.audit_invites(&a.actor, "invite.created", vec![slug.clone()], surface, format!("Invited {email} to {slug} as {role_name}"))
1785 .await;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1786 Ok(Outcome::Ok(invite))
1787 }
1788
1789 /// An invite code for an address without an account, invited to
1790 /// collaborate on one repository of `workspace_id` (access.rs). Charged
1791 /// as a workspace invite is: the workspace's shared invites first, then
1792 /// the inviter's own. The code joins no workspace; redeeming it accepts
1793 /// the repository invitation that names it.
1794 pub(crate) async fn repo_invite_code(&self, actor: &User, email: &str, workspace_id: &str) -> Result<Outcome<Invite>> {
1795 if let Some(reason) = Self::draft_allowed(actor) {
1796 return Ok(Outcome::fail(FailureCode::Forbidden, reason));
1797 }
1798 if !self.hit(&format!("invite.create:{}", actor.id), CREATES_PER_HOUR).await? {
1799 return Ok(Outcome::fail(FailureCode::Conflict, TOO_MANY));
1800 }
1801 let shared = self.workspace_allowance(workspace_id).await?;
1802 let (charged_to, charged_workspace_id, limit) = if shared.remaining.is_some_and(|left| left > 0) {
1803 ("workspace", Some(workspace_id), shared.limit)
1804 } else {
1805 let own = self.user_allowance(&actor.id).await?;
1806 if own.exhausted() {
1807 return Ok(Self::out_of_invites());
1808 }
1809 ("user", None, own.limit)
1810 };
1811 let draft = Draft {
1812 email: Some(email),
1813 kind: "account",
1814 workspace_id: None,
1815 inviter: Some(actor),
1816 staff: None,
1817 charged_to,
1818 charged_workspace_id,
1819 limit,
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)1820 invitee_id: None,
1821 role: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1822 };
1823 Ok(match self.insert_invite(draft).await? {
1824 Some(invite) => Outcome::Ok(invite),
1825 None => Self::out_of_invites(),
1826 })
1827 }
1828
1829 /// Revokes an invite code made for a repository invitation, when that
1830 /// invitation is revoked. Only a pending code changes.
1831 pub(crate) async fn revoke_code(&self, invite_id: &str) -> Result<()> {
1832 self.db
1833 .prepare(format!(
1834 "UPDATE invites SET revoked_at = {SQL_NOW}, sealed_code = NULL
1835 WHERE id = ? AND redeemed_at IS NULL AND revoked_at IS NULL"
1836 ))
1837 .bind(&[invite_id.into()])?
1838 .run()
1839 .await?;
1840 Ok(())
1841 }
1842
1843 pub async fn workspace_invites(&self, a: ListMembersArgs) -> Result<Outcome<Vec<Invite>>> {
1844 let slug = a.slug.trim().to_lowercase();
1845 if !a.viewer.as_ref().is_some_and(|viewer| viewer.role_in(&slug) == Some(Role::Owner)) {
1846 return Ok(Outcome::fail(FailureCode::Forbidden, "Only owners can see a workspace's invites."));
1847 }
1848 let Some(workspace_id) = self.workspace_id(&slug).await? else {
1849 return Ok(Outcome::fail(FailureCode::NotFound, "Workspace not found."));
1850 };
1851 let rows = self.rows("WHERE i.workspace_id = ?", &[workspace_id.as_str().into()], LIST_LIMIT).await?;
1852 Ok(Outcome::Ok(rows.into_iter().map(|row| self.shown(row, true, false)).collect()))
1853 }
1854
1855 pub async fn revoke_workspace_invite(&self, a: WorkspaceInviteArgs) -> Result<Outcome<Invite>> {
1856 let slug = a.slug.trim().to_lowercase();
1857 if a.actor.kind != PrincipalKind::User || a.actor.role_in(&slug) != Some(Role::Owner) {
1858 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can revoke a workspace's invites."));
1859 }
1860 self.revoke_invite(RemoveArgs { user: a.actor, id: a.id }).await
1861 }
1862
1863 // --- The waitlist ---
1864
1865 pub async fn request_access(&self, a: RequestAccessArgs) -> Result<Outcome<bool>> {
1866 let Some(email) = normalize_email(&a.email) else {
1867 return Ok(Outcome::fail(FailureCode::Invalid, BAD_EMAIL));
1868 };
1869 let allowed = match a.client.as_deref().filter(|client| !client.is_empty()) {
1870 Some(client) => self.hit(&format!("waitlist:{}", crypto::sha256_hex(client)), REQUESTS_PER_HOUR).await?,
1871 None => self.hit("waitlist:anonymous", ANONYMOUS_REQUESTS_PER_HOUR).await?,
1872 };
1873 if !allowed {
1874 return Ok(Outcome::fail(FailureCode::Conflict, TOO_MANY));
1875 }
1876 let about: String = a.about.trim().chars().take(MAX_WAITLIST_ABOUT).collect();
1877 let now = rfc3339(now_ms());
1878 #[derive(Deserialize)]
1879 struct Upserted {
1880 id: String,
1881 created_at: String,
1882 }
1883 let row = self
1884 .db
1885 .prepare(
1886 "INSERT INTO waitlist (id, email, about, status, created_at, updated_at)
1887 VALUES (?1, ?2, ?3, 'waiting', ?4, ?4)
1888 ON CONFLICT (email) DO UPDATE SET
1889 about = COALESCE(excluded.about, waitlist.about), updated_at = excluded.updated_at
1890 RETURNING id, created_at",
1891 )
1892 .bind(&[
1893 new_id("wl", now_ms()).into(),
1894 email.as_str().into(),
1895 if about.is_empty() { JsValue::NULL } else { about.as_str().into() },
1896 now.as_str().into(),
1897 ])?
1898 .first::<Upserted>(None)
1899 .await?;
1900 if let Some(row) = row.filter(|row| row.created_at == now) {
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1901 self.announce("waitlist.requested", None, WaitlistRequested { entry_id: row.id.clone() }).await;
1902 self.acknowledge_request(&row.id, &email).await?;
1903 self.notify_staff_of_requests().await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1904 }
1905 Ok(Outcome::Ok(true))
1906 }
1907
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1908 /// The one confirmation an address gets for asking: claimed in the
1909 /// database first, so a repeat request (or two at once) never sends a
1910 /// second, and capped across everyone, since anyone can type any
1911 /// address.
1912 async fn acknowledge_request(&self, id: &str, email: &str) -> Result<()> {
1913 if !self.hit("waitlist.ack", CONFIRMATIONS_PER_HOUR).await? {
1914 return Ok(());
1915 }
1916 let claimed = self
1917 .db
1918 .prepare(format!(
1919 "UPDATE waitlist SET acknowledged_at = {SQL_NOW} WHERE id = ? AND acknowledged_at IS NULL RETURNING id"
1920 ))
1921 .bind(&[id.into()])?
1922 .first::<Id>(None)
1923 .await?;
1924 if claimed.is_none() {
1925 return Ok(());
1926 }
1927 if let Err(error) = crate::email::send_waitlist_confirmation(&self.env, email).await {
1928 worker::console_error!("waitlist confirmation failed: {error}");
1929 // Not sent: leave it unclaimed, so staff can see it was not.
1930 self.db
1931 .prepare("UPDATE waitlist SET acknowledged_at = NULL WHERE id = ?")
1932 .bind(&[id.into()])?
1933 .run()
1934 .await?;
1935 }
1936 Ok(())
1937 }
1938
1939 /// Where staff hear about new requests: WAITLIST_NOTIFY_EMAIL, unset or
1940 /// empty for nobody.
1941 fn waitlist_notify_email(&self) -> Option<String> {
1942 let to = self.env.var("WAITLIST_NOTIFY_EMAIL").ok()?.to_string();
1943 normalize_email(&to)
1944 }
1945
1946 /// Tells staff about every request they have not heard about, unless a
1947 /// summary went in the last 15 minutes: then the next request after
1948 /// that brings them all in one. The rows are claimed before sending, so
1949 /// two requests at once send one summary.
1950 pub(crate) async fn notify_staff_of_requests(&self) -> Result<()> {
1951 let Some(to) = self.waitlist_notify_email() else {
1952 return Ok(());
1953 };
1954 #[derive(Deserialize)]
1955 struct Last {
1956 at: Option<String>,
1957 }
1958 let last = self
1959 .db
1960 .prepare("SELECT max(notified_at) AS at FROM waitlist")
1961 .first::<Last>(None)
1962 .await?
1963 .and_then(|last| last.at);
1964 let now = now_ms();
1965 if !summary_due(last.as_deref(), &rfc3339(now.saturating_sub(SUMMARY_EVERY_MS))) {
1966 return Ok(());
1967 }
1968 let stamp = rfc3339(now);
1969 #[derive(Deserialize)]
1970 struct New {
1971 email: String,
1972 about: Option<String>,
1973 created_at: String,
1974 }
1975 let mut new = self
1976 .db
1977 .prepare(
1978 "UPDATE waitlist SET notified_at = ? WHERE notified_at IS NULL AND status = 'waiting'
1979 RETURNING email, about, created_at",
1980 )
1981 .bind(&[stamp.as_str().into()])?
1982 .all()
1983 .await?
1984 .results::<New>()?;
1985 if new.is_empty() {
1986 return Ok(());
1987 }
1988 new.sort_by(|a, b| a.created_at.cmp(&b.created_at));
1989 let waiting = self
1990 .db
1991 .prepare("SELECT count(*) AS n FROM waitlist WHERE status = 'waiting'")
1992 .first::<Count>(None)
1993 .await?
1994 .map_or(0, |count| count.n as u32);
1995 let new: Vec<crate::email::Requested> = new
1996 .into_iter()
1997 .map(|row| crate::email::Requested { email: row.email, about: row.about })
1998 .collect();
1999 if let Err(error) = crate::email::send_waitlist_summary(&self.env, &to, &new, waiting).await {
2000 worker::console_error!("waitlist summary failed: {error}");
2001 // Not sent: the next request tries again with these too.
2002 self.db
2003 .prepare("UPDATE waitlist SET notified_at = NULL WHERE notified_at = ?")
2004 .bind(&[stamp.as_str().into()])?
2005 .run()
2006 .await?;
2007 }
2008 Ok(())
2009 }
2010
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2011 // --- Staff ---
2012
2013 pub async fn admin_waitlist(&self, a: AdminWaitlistArgs) -> Result<Vec<WaitlistEntry>> {
2014 let mut filters = Vec::new();
2015 let mut binds: Vec<JsValue> = Vec::new();
2016 if let Some(status) = a.status {
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas2017 filters.push("wl.status = ?".to_owned());
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2018 binds.push(status.as_str().into());
2019 }
2020 if let Some(pattern) = crate::admin::like_pattern(a.query.as_deref()) {
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas2021 filters.push("(wl.email LIKE ? ESCAPE '\\' OR lower(wl.about) LIKE ? ESCAPE '\\')".to_owned());
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2022 binds.push(pattern.as_str().into());
2023 binds.push(pattern.as_str().into());
2024 }
2025 let filter = if filters.is_empty() { String::new() } else { format!("WHERE {}", filters.join(" AND ")) };
2026 Ok(self
2027 .db
2028 .prepare(format!(
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas2029 "SELECT {WAITLIST_COLUMNS} {filter} ORDER BY wl.created_at DESC, wl.id DESC LIMIT {ADMIN_INVITES_LIMIT}"
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2030 ))
2031 .bind(&binds)?
2032 .all()
2033 .await?
2034 .results::<WaitlistRow>()?
2035 .into_iter()
2036 .map(WaitlistEntry::from)
2037 .collect())
2038 }
2039
2040 async fn waitlist_entry(&self, id: &str) -> Result<Option<WaitlistRow>> {
2041 self.db
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas2042 .prepare(format!("SELECT {WAITLIST_COLUMNS} WHERE wl.id = ?"))
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2043 .bind(&[id.into()])?
2044 .first::<WaitlistRow>(None)
2045 .await
2046 }
2047
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas2048 /// How many requests are waiting, for sudo's navigation.
2049 pub async fn admin_waitlist_pending(&self) -> Result<u32> {
2050 Ok(self
2051 .db
2052 .prepare("SELECT count(*) AS n FROM waitlist WHERE status = 'waiting'")
2053 .first::<Count>(None)
2054 .await?
2055 .map_or(0, |count| count.n as u32))
2056 }
2057
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2058 pub async fn admin_decide_waitlist(&self, a: AdminDecideWaitlistArgs) -> Result<Outcome<WaitlistEntry>> {
2059 let Some(entry) = self.waitlist_entry(&a.id).await? else {
2060 return Ok(Outcome::fail(FailureCode::NotFound, "That request is not on the waitlist."));
2061 };
2062 let staff = a.staff.trim();
2063 if staff.is_empty() {
2064 return Ok(Outcome::fail(FailureCode::Forbidden, "Say which staff member decided."));
2065 }
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas2066 if entry.status != "waiting" {
2067 return Ok(Outcome::fail(
2068 FailureCode::Conflict,
2069 format!("{} was already {} by {}.", entry.email, entry.status, entry.decided_by.as_deref().unwrap_or("staff")),
2070 ));
2071 }
2072 let note: String = a.note.as_deref().unwrap_or_default().trim().chars().take(MAX_WAITLIST_NOTE).collect();
2073 let note = (!note.is_empty()).then_some(note);
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2074 let mut invite_id = JsValue::NULL;
2075 if a.approve {
2076 if self.email_has_account(&entry.email).await? {
2077 return Ok(Outcome::fail(FailureCode::Conflict, "That address already has a g1t account."));
2078 }
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas2079 let minted = match self.mint_staff_invite(Some(entry.email.clone()), staff, note.as_deref()).await? {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2080 Outcome::Ok(invite) => invite,
2081 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
2082 };
2083 invite_id = minted.id.as_str().into();
2084 }
2085 self.db
2086 .prepare(format!(
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas2087 "UPDATE waitlist SET status = ?, invite_id = COALESCE(?, invite_id), decided_by = ?, decided_at = {SQL_NOW},
2088 note = ?, notified_at = COALESCE(notified_at, {SQL_NOW})
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2089 WHERE id = ?"
2090 ))
2091 .bind(&[
2092 if a.approve { "invited" } else { "dismissed" }.into(),
2093 invite_id,
2094 staff.into(),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas2095 note.as_deref().map_or(JsValue::NULL, JsValue::from),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2096 entry.id.as_str().into(),
2097 ])?
2098 .run()
2099 .await?;
2100 Ok(match self.waitlist_entry(&entry.id).await? {
2101 Some(row) => Outcome::Ok(row.into()),
2102 None => Outcome::fail(FailureCode::NotFound, "That request is not on the waitlist."),
2103 })
2104 }
2105
2106 pub async fn admin_invites(&self, a: AdminInvitesArgs) -> Result<Vec<Invite>> {
2107 let query = a.query.as_deref().map(str::trim).filter(|query| !query.is_empty());
2108 let rows = match query {
2109 None => self.rows("", &[], ADMIN_INVITES_LIMIT as u32).await?,
2110 Some(query) => {
2111 // A code, or its start: matched by its hint.
2112 let prefix = query.to_lowercase();
2113 let prefix = prefix.strip_prefix("g1t-").unwrap_or(&prefix).replace('-', "");
2114 let hint = (prefix.len() >= GROUP && prefix.chars().all(|c| ALPHABET.contains(&(c as u8))))
2115 .then(|| code_hint(&prefix));
2116 let pattern = crate::admin::like_pattern(Some(query)).unwrap_or_default();
2117 let mut binds: Vec<JsValue> = vec![pattern.as_str().into(), pattern.as_str().into(), pattern.as_str().into()];
2118 let mut filter = "WHERE (lower(i.email) LIKE ? ESCAPE '\\' OR iu.username LIKE ? ESCAPE '\\' OR ru.username LIKE ? ESCAPE '\\'".to_owned();
2119 if let Some(hint) = hint {
2120 filter.push_str(" OR i.hint = ?");
2121 binds.push(hint.into());
2122 }
2123 filter.push(')');
2124 self.rows(&filter, &binds, ADMIN_INVITES_LIMIT as u32).await?
2125 }
2126 };
2127 Ok(rows.into_iter().map(|row| self.shown(row, false, true)).collect())
2128 }
2129
2130 pub async fn admin_revoke_invite(&self, a: AdminRevokeInviteArgs) -> Result<Outcome<Invite>> {
2131 let revoked = self
2132 .db
2133 .prepare(format!(
2134 "UPDATE invites SET revoked_at = {SQL_NOW}, sealed_code = NULL
2135 WHERE id = ? AND redeemed_at IS NULL AND revoked_at IS NULL RETURNING id"
2136 ))
2137 .bind(&[a.id.as_str().into()])?
2138 .first::<Id>(None)
2139 .await?;
2140 if revoked.is_none() {
2141 return Ok(Outcome::fail(FailureCode::Conflict, "Only a pending invite can be revoked."));
2142 }
2143 worker::console_log!("invite {} revoked by staff {}", a.id, a.staff);
2144 Ok(match self.invite_by_id(&a.id).await? {
2145 Some(row) => Outcome::Ok(self.shown(row, false, true)),
2146 None => Outcome::fail(FailureCode::NotFound, "Invite not found."),
2147 })
2148 }
2149
2150 pub async fn admin_mint_invite(&self, a: AdminMintInviteArgs) -> Result<Outcome<Invite>> {
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas2151 self.mint_staff_invite(a.email, &a.staff, None).await
2152 }
2153
2154 /// An invite staff make, emailed with `note` when it is for an address.
2155 async fn mint_staff_invite(&self, email: Option<String>, staff: &str, note: Option<&str>) -> Result<Outcome<Invite>> {
2156 let staff = staff.trim();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2157 if staff.is_empty() {
2158 return Ok(Outcome::fail(FailureCode::Forbidden, "Say which staff member is minting it."));
2159 }
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas2160 let email = match email.as_deref().map(str::trim).filter(|email| !email.is_empty()) {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2161 Some(email) => match normalize_email(email) {
2162 Some(email) => Some(email),
2163 None => return Ok(Outcome::fail(FailureCode::Invalid, BAD_EMAIL)),
2164 },
2165 None => None,
2166 };
2167 let draft = Draft {
2168 email: email.as_deref(),
2169 kind: "account",
2170 workspace_id: None,
2171 inviter: None,
2172 staff: Some(staff),
2173 charged_to: "none",
2174 charged_workspace_id: None,
2175 limit: None,
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)2176 invitee_id: None,
2177 role: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2178 };
2179 let Some(mut invite) = self.insert_invite(draft).await? else {
2180 return Ok(Outcome::fail(FailureCode::Conflict, "The invite could not be made. Try again."));
2181 };
2182 if let (Some(email), Some(code)) = (&email, &invite.code) {
Merge invite emails that confirm the address: the emailed link carries a proof only that email has, so signing up from it needs no code; shared links and typed codes still confirm2183 self.send_invite_email(email, None, None, false, code, &invite.id, note).await;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2184 }
2185 invite.staff = Some(staff.to_owned());
2186 Ok(Outcome::Ok(invite))
2187 }
2188
2189 pub async fn admin_grant_invites(&self, a: AdminGrantInvitesArgs) -> Result<Outcome<Allowance>> {
2190 if a.amount == 0 || a.amount.abs() > MAX_INVITE_GRANT {
2191 return Ok(Outcome::fail(FailureCode::Invalid, format!("Grant between 1 and {MAX_INVITE_GRANT} invites, or take some back with a negative number.")));
2192 }
2193 let staff = a.staff.trim();
2194 if staff.is_empty() {
2195 return Ok(Outcome::fail(FailureCode::Forbidden, "Say which staff member granted them."));
2196 }
2197 let name = a.name.trim().to_lowercase();
2198 let target_id = match a.target {
2199 GrantTarget::User => self
2200 .db
2201 .prepare("SELECT id FROM users WHERE username = ?")
2202 .bind(&[name.as_str().into()])?
2203 .first::<Id>(None)
2204 .await?
2205 .map(|row| row.id),
2206 GrantTarget::Workspace => self.workspace_id(&name).await?,
2207 };
2208 let Some(target_id) = target_id else {
2209 return Ok(Outcome::fail(FailureCode::NotFound, format!("There is no {} named {name}.", a.target.as_str())));
2210 };
2211 let note = a.note.trim();
2212 self.db
2213 .prepare(
2214 "INSERT INTO invite_grants (id, target_kind, target_id, amount, note, granted_by, created_at)
2215 VALUES (?, ?, ?, ?, ?, ?, ?)",
2216 )
2217 .bind(&[
2218 new_id("igr", now_ms()).into(),
2219 a.target.as_str().into(),
2220 target_id.as_str().into(),
2221 f64::from(a.amount).into(),
2222 if note.is_empty() { JsValue::NULL } else { note.into() },
2223 staff.into(),
2224 rfc3339(now_ms()).into(),
2225 ])?
2226 .run()
2227 .await?;
2228 Ok(Outcome::Ok(match a.target {
2229 GrantTarget::User => self.user_allowance(&target_id).await?,
2230 GrantTarget::Workspace => self.workspace_allowance(&target_id).await?,
2231 }))
2232 }
2233
2234 async fn grants(&self, target: GrantTarget, id: &str) -> Result<Vec<InviteGrant>> {
2235 #[derive(Deserialize)]
2236 struct Row {
2237 amount: f64,
2238 note: Option<String>,
2239 granted_by: String,
2240 created_at: String,
2241 }
2242 Ok(self
2243 .db
2244 .prepare(
2245 "SELECT amount, note, granted_by, created_at FROM invite_grants
2246 WHERE target_kind = ? AND target_id = ? ORDER BY created_at DESC LIMIT 100",
2247 )
2248 .bind(&[target.as_str().into(), id.into()])?
2249 .all()
2250 .await?
2251 .results::<Row>()?
2252 .into_iter()
2253 .map(|row| InviteGrant {
2254 amount: row.amount as i32,
2255 note: row.note,
2256 granted_by: row.granted_by,
2257 created_at: row.created_at,
2258 })
2259 .collect())
2260 }
2261
2262 /// Whom `user_id` invited, `depth` levels down.
2263 async fn invited_by_user(&self, user_id: &str, depth: usize) -> Result<Vec<InviteTreeNode>> {
2264 #[derive(Deserialize)]
2265 struct Row {
2266 id: String,
2267 username: String,
2268 redeemed_at: String,
2269 }
2270 let rows = self
2271 .db
2272 .prepare(
2273 "SELECT u.id, u.username, i.redeemed_at FROM invites i JOIN users u ON u.id = i.redeemed_by
2274 WHERE i.inviter_id = ? AND i.kind = 'account' ORDER BY i.redeemed_at LIMIT 200",
2275 )
2276 .bind(&[user_id.into()])?
2277 .all()
2278 .await?
2279 .results::<Row>()?;
2280 let mut nodes = Vec::with_capacity(rows.len());
2281 for row in rows {
2282 let invited = if depth > 1 { Box::pin(self.invited_by_user(&row.id, depth - 1)).await? } else { Vec::new() };
2283 nodes.push(InviteTreeNode {
2284 username: row.username,
2285 joined_at: row.redeemed_at,
2286 invited,
2287 });
2288 }
2289 Ok(nodes)
2290 }
2291
2292 pub async fn admin_invite_tree(&self, a: UsernameArgs) -> Result<Option<InviteTree>> {
2293 let name = a.username.trim().to_lowercase();
2294 let Some(user) = self
2295 .db
2296 .prepare("SELECT id FROM users WHERE username = ?")
2297 .bind(&[name.as_str().into()])?
2298 .first::<Id>(None)
2299 .await?
2300 else {
2301 return Ok(None);
2302 };
2303 // Up the tree: who invited them, and who invited that person.
2304 #[derive(Deserialize)]
2305 struct Parent {
2306 inviter_id: Option<String>,
2307 inviter: Option<String>,
2308 staff: Option<String>,
2309 }
2310 let mut invited_by = Vec::new();
2311 let mut staff = None;
2312 let mut current = user.id.clone();
2313 for _ in 0..20 {
2314 let parent = self
2315 .db
2316 .prepare(
2317 "SELECT i.inviter_id, u.username AS inviter, i.staff FROM invites i
2318 LEFT JOIN users u ON u.id = i.inviter_id
2319 WHERE i.redeemed_by = ? AND i.kind = 'account' LIMIT 1",
2320 )
2321 .bind(&[current.as_str().into()])?
2322 .first::<Parent>(None)
2323 .await?;
2324 let Some(parent) = parent else { break };
2325 if invited_by.is_empty() {
2326 staff = parent.staff.clone();
2327 }
2328 match (parent.inviter_id, parent.inviter) {
2329 (Some(id), Some(username)) if !invited_by.contains(&username) => {
2330 invited_by.push(username);
2331 current = id;
2332 }
2333 _ => break,
2334 }
2335 }
2336 let invites = self
2337 .rows("WHERE i.inviter_id = ?", &[user.id.as_str().into()], LIST_LIMIT)
2338 .await?
2339 .into_iter()
2340 .map(|row| self.shown(row, false, true))
2341 .collect();
2342 Ok(Some(InviteTree {
2343 username: name,
2344 invited_by,
2345 staff,
2346 allowance: self.user_allowance(&user.id).await?,
2347 grants: self.grants(GrantTarget::User, &user.id).await?,
2348 invites,
2349 invited: self.invited_by_user(&user.id, TREE_DEPTH).await?,
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)2350 shared: self.shared_source(&user.id).await?,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2351 }))
2352 }
2353
2354 pub async fn admin_workspace_invites(&self, a: SlugArgs) -> Result<Option<InviteTree>> {
2355 let slug = a.slug.trim().to_lowercase();
2356 let Some(id) = self.workspace_id(&slug).await? else {
2357 return Ok(None);
2358 };
2359 let invites = self
2360 .rows("WHERE i.workspace_id = ?1 OR i.charged_workspace_id = ?1", &[id.as_str().into()], LIST_LIMIT)
2361 .await?
2362 .into_iter()
2363 .map(|row| self.shown(row, false, true))
2364 .collect();
2365 Ok(Some(InviteTree {
2366 username: slug,
2367 invited_by: Vec::new(),
2368 staff: None,
2369 allowance: self.workspace_allowance(&id).await?,
2370 grants: self.grants(GrantTarget::Workspace, &id).await?,
2371 invites,
2372 invited: Vec::new(),
Merge shared invite links: label, uses, expiry, domains; joined through recorded (identity 0038)2373 shared: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2374 }))
2375 }
2376
2377 // --- Audit ---
2378
2379 async fn audit_invites(&self, actor: &User, action: &str, workspaces: Vec<String>, surface: Surface, message: String) {
2380 let Ok(events) = self.env.service("EVENTS") else {
2381 return;
2382 };
2383 let entries: Vec<NewAuditEntry> = workspaces
2384 .into_iter()
2385 .map(|workspace| NewAuditEntry {
2386 actor: AuditActor::of(actor),
2387 action: action.to_owned(),
2388 surface,
2389 target: AuditTarget {
2390 workspace,
2391 ..AuditTarget::default()
2392 },
2393 outcome: AuditOutcome::Allowed,
2394 rule: "invite".to_owned(),
2395 result: Some("ok".to_owned()),
2396 message: Some(message.clone()),
2397 request_id: new_id("req", now_ms()),
2398 })
2399 .collect();
2400 if entries.is_empty() {
2401 return;
2402 }
2403 let recorded: Result<u32> = g1t_kit::call(&events, "audit_record", &RecordAuditArgs { entries }).await;
2404 if let Err(error) = recorded {
2405 worker::console_error!("{action} not recorded: {error}");
2406 }
2407 }
2408}
2409
2410/// Whether using the invite joins a workspace.
2411fn joins_workspace(row: &InviteRow) -> bool {
2412 row.workspace_id.is_some()
2413}
2414
2415#[cfg(test)]
2416mod tests {
2417 use super::*;
2418
2419 #[test]
2420 fn codes_carry_160_bits_in_eight_groups() {
2421 assert_eq!(encode(&[0u8; 20]), "0".repeat(32));
2422 assert_eq!(encode(&[0xff; 20]), "z".repeat(32));
2423 let body = new_code_body();
2424 assert_eq!(body.len(), CODE_LENGTH);
2425 assert!(body.bytes().all(|b| ALPHABET.contains(&b)));
2426 let code = format_code(&body);
2427 assert!(code.starts_with("g1t-"));
2428 assert_eq!(code.split('-').count(), 9);
2429 assert_eq!(code.len(), 4 + 32 + 7);
2430 // Every bit is used: one bit set shows in exactly one character.
2431 let mut bytes = [0u8; 20];
2432 bytes[19] = 1;
2433 assert_eq!(encode(&bytes), format!("{}1", "0".repeat(31)));
2434 }
2435
2436 #[test]
2437 fn codes_are_not_repeated() {
2438 let codes: std::collections::HashSet<String> = (0..2000).map(|_| new_code_body()).collect();
2439 assert_eq!(codes.len(), 2000);
2440 }
2441
2442 #[test]
2443 fn a_code_reads_however_it_is_typed_or_pasted() {
2444 let body = "k7m2q9xd4hpwabcd0123456789efghjk";
2445 let shown = format_code(body);
2446 for typed in [
2447 shown.clone(),
2448 shown.to_uppercase(),
2449 body.to_owned(),
2450 format!(" {} ", shown.replace('-', " ")),
2451 format!("https://g1t.sh/invite/{shown}"),
2452 format!("https://g1t.sh/register?invite={shown}&next=/"),
2453 ] {
2454 assert_eq!(normalize_code(&typed).as_deref(), Some(body), "{typed}");
2455 }
2456 // Letters people misread are read as Crockford reads them.
2457 assert_eq!(normalize_code(&"o".repeat(32)), Some("0".repeat(32)));
2458 assert_eq!(normalize_code(&"il".repeat(16)), Some("1".repeat(32)));
2459 assert_eq!(normalize_code("g1t-k7m2"), None);
2460 assert_eq!(normalize_code(&format!("{body}0")), None);
2461 assert_eq!(normalize_code(&"u".repeat(32)), None);
2462 assert_eq!(normalize_code(""), None);
2463 }
2464
2465 #[test]
2466 fn only_the_hash_and_a_short_hint_are_kept() {
2467 let body = "k7m2q9xd4hpwabcd0123456789efghjk";
2468 assert_eq!(code_hash(body), crypto::sha256_hex(body));
2469 assert_eq!(code_hash(body).len(), 64);
2470 assert_ne!(code_hash(body), code_hash(&body.replace('k', "m")));
2471 assert_eq!(code_hint(body), "g1t-k7m2");
2472 // The same code typed differently finds the same row.
2473 let typed = normalize_code(&format_code(body).to_uppercase()).unwrap();
2474 assert_eq!(code_hash(&typed), code_hash(body));
2475 }
2476
2477 const NOW: &str = "2026-10-05T12:00:00.000Z";
2478 const LATER: &str = "2026-11-04T12:00:00.000Z";
2479 const EARLIER: &str = "2026-10-01T12:00:00.000Z";
2480
2481 #[test]
2482 fn an_invite_is_pending_until_used_revoked_or_expired() {
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)2483 assert_eq!(status_of(None, None, None, LATER, NOW), InviteStatus::Pending);
2484 assert_eq!(status_of(None, None, None, EARLIER, NOW), InviteStatus::Expired);
2485 assert_eq!(status_of(None, None, None, NOW, NOW), InviteStatus::Expired);
2486 assert_eq!(status_of(Some(EARLIER), None, None, LATER, NOW), InviteStatus::Revoked);
2487 assert_eq!(status_of(None, Some(EARLIER), Some(EARLIER), EARLIER, NOW), InviteStatus::Redeemed);
2488 }
2489
2490 #[test]
2491 fn an_invite_used_to_sign_up_awaits_the_account_confirming_its_address() {
2492 // Spent, not applied: waiting, even past its expiry.
2493 assert_eq!(status_of(None, Some(EARLIER), None, LATER, NOW), InviteStatus::AwaitingConfirmation);
2494 assert_eq!(status_of(None, Some(EARLIER), None, EARLIER, NOW), InviteStatus::AwaitingConfirmation);
2495 // Revoked while waiting: revoked, whatever happens when it settles.
2496 assert_eq!(status_of(Some(NOW), Some(EARLIER), None, LATER, NOW), InviteStatus::Revoked);
2497 assert_eq!(status_of(Some(NOW), Some(EARLIER), Some(NOW), LATER, NOW), InviteStatus::Revoked);
2498 // A spent invite still counts against the allowance while it waits,
2499 // and cannot be used again.
2500 assert!(counts_against_allowance(InviteStatus::AwaitingConfirmation));
2501 let waiting = invite("account", None, InviteStatus::AwaitingConfirmation);
2502 assert_eq!(admits(Some(&waiting), "anyone@example.com", true), Err(Refusal::Invalid));
2503 }
2504
2505 fn row(workspace: Option<(&str, Option<&str>)>, revoked: bool, expires_at: &str) -> InviteRow {
2506 InviteRow {
2507 id: "inv_1".into(),
2508 hint: "g1t-k7m2".into(),
2509 sealed_code: None,
2510 email: Some("ada@example.com".into()),
2511 kind: "account".into(),
2512 workspace_id: workspace.map(|(id, _)| id.to_owned()),
2513 workspace: workspace.and_then(|(_, slug)| slug.map(str::to_owned)),
2514 inviter_id: Some("usr_owner".into()),
2515 inviter: Some("bo".into()),
2516 staff: None,
2517 charged_to: "user".into(),
2518 created_at: EARLIER.into(),
2519 expires_at: expires_at.into(),
2520 revoked_at: revoked.then(|| NOW.to_owned()),
2521 redeemer: Some("ada".into()),
2522 redeemed_at: Some(EARLIER.into()),
2523 applied_at: None,
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)2524 invitee_id: Some("usr_ada".into()),
2525 invitee: Some("ada".into()),
2526 role: None,
2527 accepted_at: None,
2528 declined_at: None,
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)2529 }
2530 }
2531
2532 #[test]
2533 fn confirming_joins_the_workspace_the_invite_named_while_it_still_applies() {
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)2534 // Confirming no longer joins anything by itself: the workspace the
2535 // invite named becomes an invitation the person accepts or declines
2536 // (invites/invitations.rs), and accepting joins it.
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)2537 let good = row(Some(("wsp_1", Some("acme"))), false, LATER);
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)2538 assert_eq!(awaiting_join(&good, NOW), AwaitingJoin::Invited { workspace_id: "wsp_1".into(), slug: "acme".into() });
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)2539 // No workspace: nothing to join, and what came with it is accepted.
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)2540 assert_eq!(awaiting_join(&row(None, false, LATER), NOW), AwaitingJoin::Nothing);
2541 // Confirmed and not yet answered: awaiting the answer.
2542 let confirmed = InviteRow { applied_at: Some(NOW.into()), ..good };
2543 assert_eq!(confirmed.status(NOW), InviteStatus::AwaitingAnswer);
2544 // Accepted: used.
2545 let accepted = InviteRow { accepted_at: Some(NOW.into()), ..confirmed };
2546 assert_eq!(accepted.status(NOW), InviteStatus::Redeemed);
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)2547 }
2548
2549 #[test]
2550 fn a_revoked_or_expired_invite_or_a_deleted_workspace_lapses_and_the_address_is_confirmed_anyway() {
2551 let lapsed = |join: AwaitingJoin| match join {
2552 AwaitingJoin::Lapsed(why) => why,
2553 other => panic!("expected a lapse, got {other:?}"),
2554 };
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)2555 let revoked = lapsed(awaiting_join(&row(Some(("wsp_1", Some("acme"))), true, LATER), NOW));
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)2556 assert!(revoked.starts_with("Your email address is confirmed."));
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)2557 assert!(revoked.contains("was revoked") && revoked.contains("no longer invites you to acme"));
2558 let expired = lapsed(awaiting_join(&row(Some(("wsp_1", Some("acme"))), false, EARLIER), NOW));
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)2559 assert!(expired.contains("expired before you confirmed it"));
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)2560 assert!(lapsed(awaiting_join(&row(Some(("wsp_1", Some("acme"))), false, NOW), NOW)).contains("expired"));
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)2561 // The workspace was deleted: its row no longer joins a slug.
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)2562 let deleted = lapsed(awaiting_join(&row(Some(("wsp_1", None)), false, LATER), NOW));
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)2563 assert!(deleted.contains("has been deleted"));
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)2564 // A free workspace still invites; accepting waits for its plan.
2565 assert!(matches!(awaiting_join(&row(Some(("wsp_1", Some("acme"))), false, LATER), NOW), AwaitingJoin::Invited { .. }));
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)2566 // Revoked beats expired; an invite without a workspace lapses too.
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)2567 assert!(lapsed(awaiting_join(&row(None, true, EARLIER), NOW)).contains("no longer applies"));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2568 }
2569
2570 #[test]
2571 fn revoked_and_expired_invites_give_the_allowance_back() {
2572 assert!(counts_against_allowance(InviteStatus::Pending));
2573 assert!(counts_against_allowance(InviteStatus::Redeemed));
2574 assert!(!counts_against_allowance(InviteStatus::Revoked));
2575 assert!(!counts_against_allowance(InviteStatus::Expired));
2576 // The SQL says the same: used, or neither revoked nor expired.
2577 let sql = counted_sql();
2578 assert!(sql.contains("i.redeemed_at IS NOT NULL OR (i.revoked_at IS NULL AND i.expires_at >"));
2579 }
2580
2581 #[test]
2582 fn allowances_are_five_plus_grants_or_unlimited_for_staff() {
2583 assert_eq!(limit_for(INVITES_PER_USER, 0, false), Some(5));
2584 assert_eq!(limit_for(5, 10, false), Some(15));
2585 assert_eq!(limit_for(5, -3, false), Some(2));
2586 assert_eq!(limit_for(5, -30, false), Some(0));
2587 assert_eq!(limit_for(5, 0, true), None);
2588 // A workspace has only what staff granted it.
2589 assert_eq!(limit_for(0, 0, false), Some(0));
2590 assert_eq!(limit_for(0, 25, false), Some(25));
2591 let full = Allowance::new(Some(5), 5);
2592 assert!(full.exhausted());
2593 assert_eq!(full.remaining, Some(0));
2594 let over = Allowance::new(Some(2), 4);
2595 assert_eq!(over.remaining, Some(0));
2596 let open = Allowance::new(None, 400);
2597 assert!(!open.exhausted());
2598 assert_eq!(open.remaining, None);
2599 assert_eq!(Allowance::new(Some(5), 3).remaining, Some(2));
2600 }
2601
2602 fn invite(kind: &'static str, email: Option<&'static str>, status: InviteStatus) -> Admits<'static> {
2603 Admits { kind, email, status }
2604 }
2605
2606 #[test]
2607 fn an_invite_admits_only_its_address_while_pending() {
2608 let open = invite("account", None, InviteStatus::Pending);
2609 assert_eq!(admits(Some(&open), "anyone@example.com", true), Ok(()));
2610 let bound = invite("account", Some("ada@example.com"), InviteStatus::Pending);
2611 assert_eq!(admits(Some(&bound), "ada@example.com", true), Ok(()));
2612 assert_eq!(admits(Some(&bound), " ADA@Example.com ", true), Ok(()));
2613 assert_eq!(admits(Some(&bound), "eve@example.com", true), Err(Refusal::WrongEmail));
2614 for status in [InviteStatus::Redeemed, InviteStatus::Revoked, InviteStatus::Expired] {
2615 assert_eq!(admits(Some(&invite("account", None, status)), "a@example.com", true), Err(Refusal::Invalid));
2616 // A dead code says nothing about whom it was for.
2617 assert_eq!(
2618 admits(Some(&invite("account", Some("ada@example.com"), status)), "eve@example.com", true),
2619 Err(Refusal::Invalid)
2620 );
2621 }
2622 assert_eq!(admits(None, "a@example.com", true), Err(Refusal::Invalid));
2623 }
2624
2625 #[test]
2626 fn a_workspace_invite_never_makes_an_account() {
2627 let join = invite("workspace", Some("ada@example.com"), InviteStatus::Pending);
2628 assert_eq!(admits(Some(&join), "ada@example.com", true), Err(Refusal::Invalid));
2629 assert_eq!(admits(Some(&join), "ada@example.com", false), Ok(()));
2630 assert_eq!(admits(Some(&join), "eve@example.com", false), Err(Refusal::WrongEmail));
2631 // An account invite for a workspace can be accepted by the address
2632 // once it has an account.
2633 let account = invite("account", Some("ada@example.com"), InviteStatus::Pending);
2634 assert_eq!(admits(Some(&account), "ada@example.com", false), Ok(()));
2635 }
2636
Merge invite emails that confirm the address: the emailed link carries a proof only that email has, so signing up from it needs no code; shared links and typed codes still confirm2637 const KEY: &[u8] = b"identity key";
2638
2639 #[test]
2640 fn an_invite_emails_proof_is_for_its_invite_and_address_only() {
2641 let proof = email_proof(KEY, "inv_1", Some("ada@example.com")).unwrap();
2642 assert_eq!(proof.len(), 64);
2643 let proves = |id: &str, bound: Option<&str>, email: &str, proof: Option<&str>| proves_email(KEY, id, bound, email, proof);
2644 // The right invite and address, however the address is written.
2645 assert!(proves("inv_1", Some("ada@example.com"), "ada@example.com", Some(&proof)));
2646 assert!(proves("inv_1", Some("Ada@Example.com"), " ADA@example.com ", Some(&proof)));
2647 assert!(proves("inv_1", Some("ada@example.com"), "ada@example.com", Some(&proof.to_uppercase())));
2648 // Another address: the account confirms that one itself.
2649 assert!(!proves("inv_1", Some("ada@example.com"), "eve@example.com", Some(&proof)));
2650 // Another invite's proof, even for the same address.
2651 assert!(!proves("inv_2", Some("ada@example.com"), "ada@example.com", Some(&proof)));
2652 // Tampered, cut short, empty or missing.
2653 let mut tampered = proof.clone().into_bytes();
2654 tampered[10] = if tampered[10] == b'0' { b'1' } else { b'0' };
2655 let tampered = String::from_utf8(tampered).unwrap();
2656 assert!(!proves("inv_1", Some("ada@example.com"), "ada@example.com", Some(&tampered)));
2657 assert!(!proves("inv_1", Some("ada@example.com"), "ada@example.com", Some(&proof[..32])));
2658 assert!(!proves("inv_1", Some("ada@example.com"), "ada@example.com", Some("")));
2659 assert!(!proves("inv_1", Some("ada@example.com"), "ada@example.com", None));
2660 // An invite bound to no address has no proof to give.
2661 assert_eq!(email_proof(KEY, "inv_1", None), None);
2662 assert!(!proves("inv_1", None, "ada@example.com", Some(&proof)));
2663 // Made under another key: not ours.
2664 let foreign = email_proof(b"another key", "inv_1", Some("ada@example.com")).unwrap();
2665 assert!(!proves("inv_1", Some("ada@example.com"), "ada@example.com", Some(&foreign)));
2666 // Without a key (development) none is made, and none is taken.
2667 assert_eq!(email_proof(b"", "inv_1", Some("ada@example.com")), None);
2668 let unkeyed = crypto::invite_proof(b"", "inv_1", "ada@example.com");
2669 assert!(!proves_email(b"", "inv_1", Some("ada@example.com"), "ada@example.com", Some(&unkeyed)));
2670 }
2671
2672 #[test]
2673 fn an_account_starts_confirmed_only_from_the_invite_email_to_its_address() {
2674 let invite = row(None, false, LATER);
2675 let proof = email_proof(KEY, &invite.id, invite.email.as_deref()).unwrap();
2676 // From the invite email, with the address it was sent to.
2677 assert!(starts_confirmed(KEY, false, Some(&invite), "ada@example.com", Some(&proof)));
2678 // The code alone (typed in, or a link passed on), or a bad proof.
2679 assert!(!starts_confirmed(KEY, false, Some(&invite), "ada@example.com", None));
2680 assert!(!starts_confirmed(KEY, false, Some(&invite), "ada@example.com", Some("0123")));
2681 // A different address than the invite's.
2682 assert!(!starts_confirmed(KEY, false, Some(&invite), "eve@example.com", Some(&proof)));
2683 // No invite (open registration, or a shared link), or one bound to no address.
2684 assert!(!starts_confirmed(KEY, false, None, "ada@example.com", Some(&proof)));
2685 let unbound = InviteRow { email: None, ..row(None, false, LATER) };
2686 assert!(!starts_confirmed(KEY, false, Some(&unbound), "ada@example.com", Some(&proof)));
2687 // A workspace invite makes no account.
2688 let join = InviteRow { kind: "workspace".into(), ..row(None, false, LATER) };
2689 assert!(!starts_confirmed(KEY, false, Some(&join), "ada@example.com", Some(&proof)));
2690 // GitHub's confirmed address, whatever else.
2691 assert!(starts_confirmed(KEY, true, None, "ada@example.com", None));
2692 }
2693
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2694 #[test]
2695 fn addresses_are_checked_and_masked() {
2696 assert_eq!(normalize_email(" Ada@Example.COM ").as_deref(), Some("ada@example.com"));
2697 for bad in ["", "ada", "ada@", "@example.com", "ada@example", "a b@example.com", "ada@.com", "ada@example.", "a@b@c.com"] {
2698 assert_eq!(normalize_email(bad), None, "{bad}");
2699 }
2700 assert_eq!(mask_email("ada@example.com"), "a•••@example.com");
2701 assert_eq!(mask_email("x@example.com"), "x•••@example.com");
2702 }
2703
2704 #[test]
2705 fn rate_limits_count_in_hour_long_windows() {
2706 assert_eq!(bucket(0, HOUR_MS), 0);
2707 assert_eq!(bucket(HOUR_MS - 1, HOUR_MS), 0);
2708 assert_eq!(bucket(HOUR_MS, HOUR_MS), 1);
2709 // The limits stop guessing long before a code could be found, and
2710 // leave room for people who mistype.
2711 assert!((5..=100).contains(&FAILURES_PER_HOUR));
2712 const { assert!(CREATES_PER_HOUR >= INVITES_PER_USER) };
2713 const { assert!(REQUESTS_PER_HOUR >= 1) };
2714 }
2715
2716 #[test]
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas2717 fn staff_hear_about_requests_at_most_every_15_minutes() {
2718 assert_eq!(SUMMARY_EVERY_MS, 15 * 60 * 1000);
2719 let since = "2026-10-05T11:45:00.000Z";
2720 assert!(summary_due(None, since));
2721 assert!(summary_due(Some("2026-10-05T11:30:00.000Z"), since));
2722 assert!(summary_due(Some(since), since));
2723 assert!(!summary_due(Some("2026-10-05T11:50:00.000Z"), since));
2724 const { assert!(CONFIRMATIONS_PER_HOUR >= ANONYMOUS_REQUESTS_PER_HOUR) };
2725 }
2726
2727 #[test]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2728 fn registration_is_invite_only_unless_opened() {
2729 assert_eq!(RegistrationMode::parse(None), RegistrationMode::Invite);
2730 assert_eq!(RegistrationMode::parse(Some("invite")), RegistrationMode::Invite);
2731 assert_eq!(RegistrationMode::parse(Some("")), RegistrationMode::Invite);
2732 assert_eq!(RegistrationMode::parse(Some("opne")), RegistrationMode::Invite);
2733 assert_eq!(RegistrationMode::parse(Some(" Open ")), RegistrationMode::Open);
2734 }
2735}

This file's history is long; its oldest lines are credited to the oldest commit read.