flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/services/identity/src/lib.rs

821 lines36,349 bytesCodeBlame

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.

API and MCP server, Rust identity service, registration, site redesign1//! The identity service: accounts, sessions, SSH keys and access tokens.
2//!
3//! Reached only through service bindings; see `g1t_contracts::identity` for
4//! the methods and their arguments.
5
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look6mod access;
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace7mod admin;
Workspace names and icons, and a component kit for every control8mod avatars;
API and MCP server, Rust identity service, registration, site redesign9mod crypto;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look10mod deletion;
Device sign-in replaces registering and minting tokens over the API11mod device;
Search across all of g1t, Explore, and a command palette12mod directory;
Email verification, password reset, and Git for AI scale positioning13mod email;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look14mod emails;
15mod github;
16mod invites;
OAuth 2.1 sign-in for MCP clients and other applications17mod oauth;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains18mod profiles;
19mod rename;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API20mod run_credentials;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look21mod security;
22mod throttle;
Agents as a team: lifecycle, merge queue, billing and a new shell23mod tokens;
Workspaces own repositories24mod workspaces;
API and MCP server, Rust identity service, registration, site redesign25
26use g1t_contracts::identity::*;
RFC 3339 timestamps in identity and repos27use g1t_contracts::time::{SQL_NOW, rfc3339, sql_after};
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent28use g1t_contracts::{FailureCode, Outcome, User, Viewer, claimable_namespace, new_id};
API and MCP server, Rust identity service, registration, site redesign29use g1t_kit::{args, now_ms, reply, rpc_method};
30use serde::Deserialize;
Agents as a team: lifecycle, merge queue, billing and a new shell31use tokens::TOKEN_PREFIX;
API and MCP server, Rust identity service, registration, site redesign32use worker::wasm_bindgen::JsValue;
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas33use worker::{Context, D1Database, Env, Request, Response, Result, ScheduleContext, ScheduledEvent, event};
API and MCP server, Rust identity service, registration, site redesign34
RFC 3339 timestamps in identity and repos35const SESSION_TTL_SECONDS: u64 = 30 * 24 * 60 * 60;
36const VERIFY_TTL_SECONDS: u64 = 24 * 60 * 60;
37const RESET_TTL_SECONDS: u64 = 60 * 60;
API and MCP server, Rust identity service, registration, site redesign38const MIN_PASSWORD_LENGTH: usize = 10;
Email verification, password reset, and Git for AI scale positioning39const PASSWORD_TOO_SHORT: &str = "Use a password of at least 10 characters.";
40
41/// A user as selected from the database; `verified` arrives as 0 or 1.
42#[derive(Deserialize)]
43struct Account {
44 id: String,
45 username: String,
46 verified: u8,
Workspace names and icons, and a component kit for every control47 /// Selected only where the person is being shown to themselves.
48 #[serde(default)]
49 avatar: Option<String>,
Email verification, password reset, and Git for AI scale positioning50}
51
52impl From<Account> for User {
53 fn from(row: Account) -> Self {
54 User {
55 id: row.id,
56 username: row.username,
57 verified: row.verified != 0,
Workspace names and icons, and a component kit for every control58 avatar: row.avatar,
Agents as a team: lifecycle, merge queue, billing and a new shell59 ..User::default()
Email verification, password reset, and Git for AI scale positioning60 }
61 }
62}
API and MCP server, Rust identity service, registration, site redesign63
64#[derive(Deserialize)]
65struct UserRow {
66 id: String,
67 username: String,
68 password_hash: String,
Email verification, password reset, and Git for AI scale positioning69 verified: u8,
API and MCP server, Rust identity service, registration, site redesign70}
71
Email verification, password reset, and Git for AI scale positioning72/// The owner of an emailed token.
API and MCP server, Rust identity service, registration, site redesign73#[derive(Deserialize)]
Email verification, password reset, and Git for AI scale positioning74struct TokenOwner {
75 id: String,
76 username: String,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look77 /// The address a link was sent to; null on links from before accounts
78 /// had several, which are for the primary.
79 #[serde(default)]
80 email_id: Option<String>,
Email verification, password reset, and Git for AI scale positioning81}
82
83#[derive(Deserialize)]
API and MCP server, Rust identity service, registration, site redesign84struct KeyRow {
85 id: String,
86 title: String,
87 fingerprint: String,
RFC 3339 timestamps in identity and repos88 created_at: String,
API and MCP server, Rust identity service, registration, site redesign89}
90
91impl From<KeyRow> for SshKey {
92 fn from(row: KeyRow) -> Self {
93 SshKey {
94 id: row.id,
95 title: row.title,
96 fingerprint: row.fingerprint,
RFC 3339 timestamps in identity and repos97 created_at: row.created_at,
API and MCP server, Rust identity service, registration, site redesign98 }
99 }
100}
101
102struct Identity {
103 db: D1Database,
Email verification, password reset, and Git for AI scale positioning104 env: Env,
API and MCP server, Rust identity service, registration, site redesign105}
106
107impl Identity {
Workspaces own repositories108 /// Runs a query that returns at most one user, for showing to others:
109 /// without their workspaces.
110 async fn find_public_user(&self, sql: &str, param: &str) -> Result<Viewer> {
Email verification, password reset, and Git for AI scale positioning111 Ok(self
112 .db
API and MCP server, Rust identity service, registration, site redesign113 .prepare(sql)
114 .bind(&[JsValue::from(param)])?
Email verification, password reset, and Git for AI scale positioning115 .first::<Account>(None)
116 .await?
117 .map(User::from))
118 }
119
Workspaces own repositories120 /// Attaches the workspaces a user belongs to, so that any service can
121 /// authorize them without asking again.
122 async fn with_workspaces(&self, user: Viewer) -> Result<Viewer> {
123 let Some(mut user) = user else {
124 return Ok(None);
125 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look126 let memberships = self.memberships(&user.id).await?;
127 // Access to a workspace is used only within its policy; see security.rs.
128 user.workspaces = self.within_policy(&user.id, memberships).await?;
129 // Roles on single repositories, under the same policy (access.rs).
130 let grants = self.grants_of(&user.id).await?;
131 user.grants = self.grants_within_policy(&user.id, grants).await?;
Workspaces own repositories132 Ok(Some(user))
133 }
134
135 /// Runs a query that resolves credentials to at most one user.
136 async fn find_user(&self, sql: &str, param: &str) -> Result<Viewer> {
137 let user = self.find_public_user(sql, param).await?;
138 self.with_workspaces(user).await
139 }
140
Email verification, password reset, and Git for AI scale positioning141 /// Stores a one-time token of `kind` for the user and returns it.
RFC 3339 timestamps in identity and repos142 async fn issue_email_token(&self, user_id: &str, kind: &str, ttl: u64) -> Result<String> {
Email verification, password reset, and Git for AI scale positioning143 let token = crypto::random_hex(32);
144 self.db
RFC 3339 timestamps in identity and repos145 .prepare(format!(
Email verification, password reset, and Git for AI scale positioning146 "INSERT INTO email_tokens (id, user_id, kind, expires_at)
RFC 3339 timestamps in identity and repos147 VALUES (?, ?, ?, {})",
148 sql_after(ttl)
149 ))
Email verification, password reset, and Git for AI scale positioning150 .bind(&[
151 crypto::sha256_hex(&token).into(),
152 user_id.into(),
153 kind.into(),
154 ])?
155 .run()
156 .await?;
157 Ok(token)
API and MCP server, Rust identity service, registration, site redesign158 }
159
Email verification, password reset, and Git for AI scale positioning160 /// Consumes a token of `kind`, returning its owner if it was valid.
161 async fn redeem_email_token(&self, token: &str, kind: &str) -> Result<Option<TokenOwner>> {
162 let id = crypto::sha256_hex(token);
163 let owner = self
164 .db
RFC 3339 timestamps in identity and repos165 .prepare(format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look166 "SELECT users.id, users.username, email_tokens.email_id FROM email_tokens
Email verification, password reset, and Git for AI scale positioning167 JOIN users ON users.id = email_tokens.user_id
168 WHERE email_tokens.id = ? AND email_tokens.kind = ?
RFC 3339 timestamps in identity and repos169 AND email_tokens.expires_at > {SQL_NOW}"
170 ))
Email verification, password reset, and Git for AI scale positioning171 .bind(&[id.as_str().into(), kind.into()])?
172 .first::<TokenOwner>(None)
173 .await?;
174 if let Some(owner) = &owner {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look175 // Every outstanding token of this kind dies with the one used:
176 // every reset link, and every confirmation link for the same
177 // address (another address's links still work).
Email verification, password reset, and Git for AI scale positioning178 self.db
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look179 .prepare(
180 "DELETE FROM email_tokens WHERE user_id = ?1 AND kind = ?2
181 AND (?2 = 'reset' OR email_id IS ?3)",
182 )
183 .bind(&[
184 owner.id.as_str().into(),
185 kind.into(),
186 owner.email_id.as_deref().map_or(JsValue::NULL, Into::into),
187 ])?
Email verification, password reset, and Git for AI scale positioning188 .run()
189 .await?;
190 }
191 Ok(owner)
192 }
193
194 async fn send_verification(&self, user: &User, email: &str) -> Result<()> {
195 let token = self
196 .issue_email_token(&user.id, "verify", VERIFY_TTL_SECONDS)
197 .await?;
198 email::send_verification(&self.env, email, &user.username, &token).await
199 }
200
201 async fn resend_verification(&self, a: UserArgs) -> Result<Outcome<bool>> {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look202 if !self.allow(throttle::CONFIRM_ACCOUNT, &a.user.id).await? {
203 return Ok(Outcome::fail(FailureCode::Conflict, "Too many confirmation emails this hour. Check your inbox, or try again later."));
204 }
205 self.resend_primary(&a.user).await
Email verification, password reset, and Git for AI scale positioning206 }
207
208 async fn verify_email(&self, a: EmailTokenArgs) -> Result<Outcome<User>> {
209 let Some(owner) = self.redeem_email_token(&a.token, "verify").await? else {
210 return Ok(Outcome::fail(
211 FailureCode::Invalid,
212 "This confirmation link is not valid or has expired.",
213 ));
214 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look215 if let Outcome::Fail(failure) = self.confirm_address(&owner.id, owner.email_id.as_deref()).await? {
216 return Ok(Outcome::Fail(failure));
217 }
218 // Whether the account is confirmed: whether its primary is.
219 let verified = self
220 .find_public_user(
221 "SELECT id, username, email_verified_at IS NOT NULL AS verified FROM users WHERE id = ?",
222 &owner.id,
223 )
224 .await?
225 .is_some_and(|user| user.verified);
Email verification, password reset, and Git for AI scale positioning226 Ok(Outcome::Ok(User {
227 id: owner.id,
228 username: owner.username,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look229 verified,
Workspaces own repositories230 ..User::default()
Email verification, password reset, and Git for AI scale positioning231 }))
232 }
233
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look234 /// Any confirmed address of an account can ask for a reset; so can the
235 /// unconfirmed address a new account signed up with. See emails.rs.
Email verification, password reset, and Git for AI scale positioning236 async fn request_password_reset(&self, a: EmailArgs) -> Result<bool> {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look237 let allowed = self.allow(throttle::RESET_EMAIL, &a.email).await?
238 && match a.client.as_deref() {
239 Some(client) => self.allow(throttle::RESET_CLIENT, client).await?,
240 None => true,
241 };
242 if allowed && let Some(target) = self.reset_target(&a.email).await? {
243 let token = crypto::random_hex(32);
244 self.db
245 .prepare(format!(
246 "INSERT INTO email_tokens (id, user_id, kind, expires_at, email_id)
247 VALUES (?, ?, 'reset', {}, ?)",
248 sql_after(RESET_TTL_SECONDS)
249 ))
250 .bind(&[
251 crypto::sha256_hex(&token).into(),
252 target.user_id.as_str().into(),
253 target.email_id.as_str().into(),
254 ])?
255 .run()
Email verification, password reset, and Git for AI scale positioning256 .await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look257 email::send_password_reset(&self.env, &target.display, &target.username, &token).await?;
258 // The primary and the backup hear of it when it went elsewhere.
259 let elsewhere = self.notice_recipients(&target.user_id, false).await?;
260 for address in elsewhere.iter().filter(|address| !address.eq_ignore_ascii_case(&target.display)) {
261 let change = format!("A password reset was asked for through {}", target.display);
262 if let Err(error) = email::send_security_notice(&self.env, address, &target.username, &change).await {
263 worker::console_error!("security notice failed: {error}");
264 }
265 }
Email verification, password reset, and Git for AI scale positioning266 }
267 // The same answer either way, so addresses cannot be probed.
268 Ok(true)
269 }
270
271 async fn reset_password(&self, a: ResetPasswordArgs) -> Result<Outcome<User>> {
272 if a.password.chars().count() < MIN_PASSWORD_LENGTH {
273 return Ok(Outcome::fail(FailureCode::Invalid, PASSWORD_TOO_SHORT));
274 }
275 let Some(owner) = self.redeem_email_token(&a.token, "reset").await? else {
276 return Ok(Outcome::fail(
277 FailureCode::Invalid,
278 "This reset link is not valid or has expired.",
279 ));
280 };
281 self.db
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look282 .prepare("UPDATE users SET password_hash = ? WHERE id = ?")
Email verification, password reset, and Git for AI scale positioning283 .bind(&[
284 crypto::hash_password(&a.password).into(),
285 owner.id.as_str().into(),
286 ])?
287 .run()
288 .await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look289 // Following an emailed link also proves the address it went to
290 // (unless another account confirmed it first).
291 let _ = self.confirm_address(&owner.id, owner.email_id.as_deref()).await?;
292 // Anyone signed in with the old password is signed out, and nobody
293 // stays locked out by the wrong guesses before it.
Email verification, password reset, and Git for AI scale positioning294 self.db
295 .prepare("DELETE FROM sessions WHERE user_id = ?")
296 .bind(&[owner.id.as_str().into()])?
297 .run()
298 .await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look299 self.clear(&throttle::key(throttle::PASSWORD_ACCOUNT, &owner.id)).await?;
300 self.log_security(&owner.id, "password_changed", None, None).await;
301 self.tell_primary_and_backup(&owner.id, &owner.username, "Your password was changed").await;
302 let verified = self
303 .find_public_user(
304 "SELECT id, username, email_verified_at IS NOT NULL AS verified FROM users WHERE id = ?",
305 &owner.id,
306 )
307 .await?
308 .is_some_and(|user| user.verified);
Email verification, password reset, and Git for AI scale positioning309 Ok(Outcome::Ok(User {
310 id: owner.id,
311 username: owner.username,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look312 verified,
Workspaces own repositories313 ..User::default()
Email verification, password reset, and Git for AI scale positioning314 }))
315 }
316
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look317 /// The account a login names: a username, or any confirmed address.
318 async fn password_row(&self, login: &str) -> Result<Option<UserRow>> {
319 let login = login.trim().to_lowercase();
320 let (column, value) = if login.contains('@') {
321 match self.user_with_verified_email(&login).await? {
322 Some(id) => ("id", id),
323 None => return Ok(None),
324 }
325 } else {
326 ("username", login)
327 };
328 self.db
329 .prepare(format!(
330 "SELECT id, username, password_hash, email_verified_at IS NOT NULL AS verified FROM users WHERE {column} = ?"
331 ))
332 .bind(&[JsValue::from(value)])?
API and MCP server, Rust identity service, registration, site redesign333 .first::<UserRow>(None)
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look334 .await
335 }
336
337 /// Checks a password for a login, throttled (see throttle.rs). The
338 /// refusal is one of two messages, the same for every account.
339 async fn checked_password(
340 &self,
341 login: &str,
342 password: &str,
343 client: Option<&str>,
344 ) -> Result<std::result::Result<User, &'static str>> {
345 let row = self.password_row(login).await?;
346 let subject = row.as_ref().map_or_else(|| login.trim().to_lowercase(), |row| row.id.clone());
347 let (account_key, client_key) = Identity::password_keys(&subject, client);
348 if self.password_locked(&account_key, client_key.as_deref()).await? {
349 return Ok(Err(throttle::THROTTLED));
350 }
351 let owner = row.as_ref().map(|row| (row.id.clone(), row.username.clone()));
352 match row.filter(|row| !row.password_hash.is_empty() && crypto::verify_password(password, &row.password_hash)) {
353 Some(row) => {
354 self.clear(&account_key).await?;
355 Ok(Ok(User {
356 id: row.id,
357 username: row.username,
358 verified: row.verified != 0,
359 ..User::default()
360 }))
361 }
362 None => {
363 let owner = owner.as_ref().map(|(id, name)| (id.as_str(), name.as_str()));
364 self.password_failed(&account_key, client_key.as_deref(), owner).await?;
365 Ok(Err("Incorrect username or password."))
366 }
367 }
368 }
369
370 async fn user_for_password(&self, login: &str, password: &str) -> Result<Viewer> {
371 let user = self.checked_password(login, password, None).await?.ok();
Workspaces own repositories372 self.with_workspaces(user).await
API and MCP server, Rust identity service, registration, site redesign373 }
374
375 async fn register(&self, a: RegisterArgs) -> Result<Outcome<SignedIn>> {
376 let username = a.username.trim().to_lowercase();
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent377 let claimable = claimable_namespace(&username).is_some();
API and MCP server, Rust identity service, registration, site redesign378 let email = a.email.trim().to_lowercase();
379 let invalid = |message: &str| Ok(Outcome::fail(FailureCode::Invalid, message));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look380 let invite_code = a.invite_code.as_deref().map(str::trim).filter(|code| !code.is_empty());
381 // The invite first: without one, nothing else on the form matters.
382 if self.invites_required() && invite_code.is_none() {
383 return Ok(Outcome::fail(FailureCode::Forbidden, invites::MISSING));
384 }
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent385 if !claimable {
API and MCP server, Rust identity service, registration, site redesign386 return invalid(
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent387 "Usernames use lowercase letters, digits and single hyphens, up to 39 characters, and cannot be a reserved word.",
API and MCP server, Rust identity service, registration, site redesign388 );
389 }
390 let well_formed_email = email
391 .split_once('@')
392 .is_some_and(|(local, domain)| !local.is_empty() && domain.contains('.'))
393 && !email.contains(char::is_whitespace);
394 if !well_formed_email {
395 return invalid("Enter a valid email address.");
396 }
397 if a.password.chars().count() < MIN_PASSWORD_LENGTH {
Email verification, password reset, and Git for AI scale positioning398 return invalid(PASSWORD_TOO_SHORT);
API and MCP server, Rust identity service, registration, site redesign399 }
400 let taken = self
401 .db
Agents as a team: lifecycle, merge queue, billing and a new shell402 // Usernames and workspaces share one namespace, so that a name
403 // means the same thing wherever it appears.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look404 // An address is taken once an account has confirmed it; an
405 // unconfirmed one goes to whoever confirms it first (emails.rs).
Agents as a team: lifecycle, merge queue, billing and a new shell406 .prepare(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look407 "SELECT username FROM users WHERE username = ?
408 UNION ALL SELECT email FROM user_emails WHERE email = ? AND verified_at IS NOT NULL
Agents as a team: lifecycle, merge queue, billing and a new shell409 UNION ALL SELECT slug FROM workspaces WHERE slug = ?",
410 )
411 .bind(&[
412 username.as_str().into(),
413 email.as_str().into(),
414 username.as_str().into(),
415 ])?
API and MCP server, Rust identity service, registration, site redesign416 .first::<serde_json::Value>(None)
417 .await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look418 // A renamed workspace's old slug stays reserved for it a while, and
419 // a deleted workspace's for good.
420 if taken.is_some() || self.slug_held(&username).await? || self.slug_deleted(&username).await? {
API and MCP server, Rust identity service, registration, site redesign421 return Ok(Outcome::fail(
422 FailureCode::Conflict,
423 "That username or email is already registered.",
424 ));
425 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look426 let password_hash = crypto::hash_password(&a.password);
427 let user = match self
428 .create_account(invites::NewAccount {
429 username: &username,
430 email: &email,
431 password_hash: &password_hash,
432 verified: false,
433 invite_code,
434 client: a.client.as_deref(),
435 })
436 .await?
437 {
438 Outcome::Ok(user) => user,
439 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
API and MCP server, Rust identity service, registration, site redesign440 };
Email verification, password reset, and Git for AI scale positioning441 // The account exists either way; the email can be sent again later.
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas442 // An invite sent to this address confirmed it already (invites.rs).
443 if !user.verified
444 && let Err(error) = self.send_verification(&user, &email).await
445 {
Email verification, password reset, and Git for AI scale positioning446 worker::console_error!("verification email failed: {error}");
447 }
API and MCP server, Rust identity service, registration, site redesign448 self.start_session(user).await
449 }
450
451 async fn sign_in(&self, a: SignInArgs) -> Result<Outcome<SignedIn>> {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look452 let user = match self.checked_password(&a.username, &a.password, a.client.as_deref()).await? {
453 Ok(user) => user,
454 Err(message) => return Ok(Outcome::fail(FailureCode::Unauthenticated, message)),
API and MCP server, Rust identity service, registration, site redesign455 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look456 let user = self.with_workspaces(Some(user)).await?.unwrap_or_default();
API and MCP server, Rust identity service, registration, site redesign457 self.start_session(user).await
458 }
459
460 async fn start_session(&self, user: User) -> Result<Outcome<SignedIn>> {
461 let session_token = crypto::random_hex(32);
462 self.db
RFC 3339 timestamps in identity and repos463 .prepare(format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look464 // Signing in is proof it is the person: see security.rs.
465 "INSERT INTO sessions (id, user_id, expires_at, authenticated_at) VALUES (?, ?, {}, {SQL_NOW})",
RFC 3339 timestamps in identity and repos466 sql_after(SESSION_TTL_SECONDS)
467 ))
API and MCP server, Rust identity service, registration, site redesign468 .bind(&[
469 crypto::sha256_hex(&session_token).into(),
470 user.id.as_str().into(),
471 ])?
472 .run()
473 .await?;
474 Ok(Outcome::Ok(SignedIn {
475 user,
476 session_token,
477 }))
478 }
479
480 async fn sign_out(&self, a: SessionArgs) -> Result<()> {
481 self.db
482 .prepare("DELETE FROM sessions WHERE id = ?")
483 .bind(&[crypto::sha256_hex(&a.session_token).into()])?
484 .run()
485 .await?;
486 Ok(())
487 }
488
489 async fn user_for_session(&self, a: SessionArgs) -> Result<Viewer> {
490 self.find_user(
RFC 3339 timestamps in identity and repos491 &format!(
Workspace names and icons, and a component kit for every control492 "SELECT users.id, users.username, users.email_verified_at IS NOT NULL AS verified,
493 users.avatar
RFC 3339 timestamps in identity and repos494 FROM sessions JOIN users ON users.id = sessions.user_id
495 WHERE sessions.id = ? AND sessions.expires_at > {SQL_NOW}"
496 ),
API and MCP server, Rust identity service, registration, site redesign497 &crypto::sha256_hex(&a.session_token),
498 )
499 .await
500 }
501
502 async fn user_for_git_credentials(&self, a: GitCredentialsArgs) -> Result<Viewer> {
503 // Like GitHub, a token alone identifies its user.
504 if a.secret.starts_with(TOKEN_PREFIX) {
505 self.user_for_access_token(&a.secret).await
506 } else {
507 self.user_for_password(&a.username, &a.secret).await
508 }
509 }
510
511 async fn user_for_ssh_key(&self, a: FingerprintArgs) -> Result<Viewer> {
512 self.find_user(
Email verification, password reset, and Git for AI scale positioning513 "SELECT users.id, users.username, users.email_verified_at IS NOT NULL AS verified FROM ssh_keys
API and MCP server, Rust identity service, registration, site redesign514 JOIN users ON users.id = ssh_keys.user_id
515 WHERE fingerprint = ?",
516 &a.fingerprint,
517 )
518 .await
519 }
520
521 async fn user_by_username(&self, a: UsernameArgs) -> Result<Viewer> {
Workspaces own repositories522 self.find_public_user(
Email verification, password reset, and Git for AI scale positioning523 "SELECT id, username, email_verified_at IS NOT NULL AS verified FROM users WHERE username = ?",
API and MCP server, Rust identity service, registration, site redesign524 &a.username.to_lowercase(),
525 )
526 .await
527 }
528
What happened across an outcome, as a feed beside its graph529 async fn usernames(&self, a: UsernamesArgs) -> Result<std::collections::HashMap<String, String>> {
530 #[derive(serde::Deserialize)]
531 struct Named {
532 id: String,
533 name: String,
534 }
535 let ids: Vec<String> = a.ids.into_iter().take(200).collect();
536 let mut names = std::collections::HashMap::new();
537 if ids.is_empty() {
538 return Ok(names);
539 }
540 let marks = vec!["?"; ids.len()].join(", ");
541 let bind: Vec<worker::wasm_bindgen::JsValue> = ids.iter().map(|id| id.as_str().into()).collect();
542 for sql in [
543 format!("SELECT id, username AS name FROM users WHERE id IN ({marks})"),
544 format!("SELECT id, slug AS name FROM workspaces WHERE id IN ({marks})"),
545 ] {
546 for row in self.db.prepare(sql).bind(&bind)?.all().await?.results::<Named>()? {
547 names.insert(row.id, row.name);
548 }
549 }
550 Ok(names)
551 }
552
API and MCP server, Rust identity service, registration, site redesign553 async fn list_ssh_keys(&self, a: UserArgs) -> Result<Vec<SshKey>> {
554 let rows = self
555 .db
556 .prepare("SELECT id, title, fingerprint, created_at FROM ssh_keys WHERE user_id = ? ORDER BY id")
557 .bind(&[a.user.id.into()])?
558 .all()
559 .await?
560 .results::<KeyRow>()?;
561 Ok(rows.into_iter().map(SshKey::from).collect())
562 }
563
564 async fn add_ssh_key(&self, a: AddSshKeyArgs) -> Result<Outcome<SshKey>> {
565 let Some(key) = crypto::parse_ssh_key(&a.public_key) else {
566 return Ok(Outcome::fail(
567 FailureCode::Invalid,
568 "That is not a valid OpenSSH public key.",
569 ));
570 };
571 let taken = self
572 .db
573 .prepare("SELECT id FROM ssh_keys WHERE fingerprint = ?")
574 .bind(&[key.fingerprint.as_str().into()])?
575 .first::<serde_json::Value>(None)
576 .await?;
577 if taken.is_some() {
578 return Ok(Outcome::fail(
579 FailureCode::Conflict,
580 "That key is already registered.",
581 ));
582 }
583 let now = now_ms();
584 let title = [a.title.trim(), key.comment.as_str(), "SSH key"]
585 .into_iter()
586 .find(|candidate| !candidate.is_empty())
587 .unwrap_or_default()
588 .to_owned();
589 let row = KeyRow {
590 id: new_id("key", now),
591 title,
592 fingerprint: key.fingerprint,
RFC 3339 timestamps in identity and repos593 created_at: rfc3339(now),
API and MCP server, Rust identity service, registration, site redesign594 };
595 self.db
596 .prepare(
597 "INSERT INTO ssh_keys (id, user_id, title, public_key, fingerprint, created_at)
598 VALUES (?, ?, ?, ?, ?, ?)",
599 )
600 .bind(&[
601 row.id.as_str().into(),
602 a.user.id.into(),
603 row.title.as_str().into(),
604 key.public_key.into(),
605 row.fingerprint.as_str().into(),
RFC 3339 timestamps in identity and repos606 row.created_at.as_str().into(),
API and MCP server, Rust identity service, registration, site redesign607 ])?
608 .run()
609 .await?;
610 Ok(Outcome::Ok(row.into()))
611 }
612
613 /// Deletes a row the user owns from `table`.
614 async fn remove(&self, table: &str, a: RemoveArgs) -> Result<()> {
615 self.db
616 .prepare(format!("DELETE FROM {table} WHERE id = ? AND user_id = ?"))
617 .bind(&[a.id.into(), a.user.id.into()])?
618 .run()
619 .await?;
620 Ok(())
621 }
622}
623
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas624/// Every 15 minutes: staff hear about waitlist requests that arrived while
625/// the last summary's window was still open, so none waits on a later one.
626#[event(scheduled)]
627async fn scheduled(_event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
628 let Ok(db) = env.d1("DB") else { return };
629 let identity = Identity { db, env };
630 if let Err(error) = identity.notify_staff_of_requests().await {
631 worker::console_error!("waitlist summary: {error}");
632 }
633}
634
API and MCP server, Rust identity service, registration, site redesign635#[event(fetch)]
636async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
637 let Some(method) = rpc_method(&request) else {
638 return Response::error("Not found", 404);
639 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents640 // A replica near the caller when it asks for one (crates/kit/src/d1.rs).
641 let (db, served) = g1t_kit::d1::open(&env, "DB", &request)?;
API and MCP server, Rust identity service, registration, site redesign642 let body: serde_json::Value = request.json().await?;
Fast pages, required checks on the branch, self-hosted runners, honest incidents643 let identity = Identity { db, env };
API and MCP server, Rust identity service, registration, site redesign644
Fast pages, required checks on the branch, self-hosted runners, honest incidents645 let answered = match method.as_str() {
Search across all of g1t, Explore, and a command palette646 "register" => {
647 let outcome = identity.register(args(body)?).await?;
648 if let Outcome::Ok(signed_in) = &outcome {
649 identity.announce_user(&signed_in.user.username, Some(&signed_in.user.id)).await;
650 }
651 reply(&outcome)
652 }
API and MCP server, Rust identity service, registration, site redesign653 "sign_in" => reply(&identity.sign_in(args(body)?).await?),
Search across all of g1t, Explore, and a command palette654 "create_workspace" => {
655 let outcome = identity.create_workspace(args(body)?).await?;
656 if let Outcome::Ok(workspace) = &outcome {
657 identity.announce_workspace(&workspace.id, &workspace.slug, None).await;
658 }
659 reply(&outcome)
660 }
Workspaces own repositories661 "get_workspace" => reply(&identity.get_workspace(args(body)?).await?),
662 "list_members" => reply(&identity.list_members(args(body)?).await?),
663 "add_member" => reply(&identity.add_member(args(body)?).await?),
664 "remove_member" => reply(&identity.remove_member(args(body)?).await?),
Search across all of g1t, Explore, and a command palette665 "update_workspace" => {
666 let outcome = identity.update_workspace(args(body)?).await?;
667 if let Outcome::Ok(workspace) = &outcome {
668 identity.announce_workspace(&workspace.id, &workspace.slug, None).await;
669 }
670 reply(&outcome)
671 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains672 "rename_workspace" => reply(&identity.rename_workspace(args(body)?).await?),
673 "check_workspace_rename" => reply(&identity.check_workspace_rename(args(body)?).await?),
674 "resolve_slug" => reply(&identity.resolve_slug(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look675 "check_workspace_deletion" => reply(&identity.check_workspace_deletion(args(body)?).await?),
676 "delete_workspace" => reply(&identity.delete_workspace(args(body)?).await?),
677 "transfer_repo_scopes" => reply(&identity.transfer_repo_scopes(args(body)?).await?),
Search across all of g1t, Explore, and a command palette678 "set_workspace_avatar" => {
679 let outcome = identity.set_workspace_avatar(args(body)?).await?;
680 if let Outcome::Ok(workspace) = &outcome {
681 identity.announce_workspace(&workspace.id, &workspace.slug, None).await;
682 }
683 reply(&outcome)
684 }
685 "set_user_avatar" => {
686 let a: SetUserAvatarArgs = args(body)?;
687 let (username, id) = (a.user.username.clone(), a.user.id.clone());
688 let outcome = identity.set_user_avatar(a).await?;
689 if matches!(outcome, Outcome::Ok(_)) {
690 identity.announce_user(&username, Some(&id)).await;
691 }
692 reply(&outcome)
693 }
Agents as a team: lifecycle, merge queue, billing and a new shell694 "list_workspace_tokens" => reply(&identity.list_workspace_tokens(args(body)?).await?),
695 "create_workspace_token" => reply(&identity.create_workspace_token(args(body)?).await?),
696 "remove_workspace_token" => reply(&identity.remove_workspace_token(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look697 // Signing in with GitHub; see github.rs.
698 "github_enabled" => reply(&identity.github_enabled()),
699 "github_start" => reply(&identity.github_start(args(body)?).await?),
700 "github_finish" => reply(&identity.github_finish(args(body)?).await?),
701 "github_pending" => reply(&identity.github_pending(args(body)?).await?),
702 "github_sign_up" => reply(&identity.github_sign_up(args(body)?).await?),
703 "github_claim" => reply(&identity.github_claim(args(body)?).await?),
704 "github_account" => reply(&identity.github_account(args(body)?).await?),
705 "github_unlink" => reply(&identity.github_unlink(args(body)?).await?),
706 "github_user_token" => reply(&identity.github_user_token(args(body)?).await?),
707 "github_revoked" => reply(&identity.github_revoked(args(body)?).await?),
708 "github_usernames" => reply(&identity.github_usernames(args(body)?).await?),
OAuth 2.1 sign-in for MCP clients and other applications709 "oauth_authorize" => reply(&identity.oauth_authorize(args(body)?).await?),
710 "oauth_exchange" => reply(&identity.oauth_exchange(args(body)?).await?),
711 "oauth_refresh" => reply(&identity.oauth_refresh(args(body)?).await?),
712 "list_oauth_grants" => reply(&identity.list_oauth_grants(args(body)?).await?),
713 "revoke_oauth_grant" => reply(&identity.revoke_oauth_grant(args(body)?).await?),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step714 "update_oauth_grant" => reply(&identity.update_oauth_grant(args(body)?).await?),
Device sign-in replaces registering and minting tokens over the API715 "device_start" => reply(&identity.device_start(args(body)?).await?),
716 "device_lookup" => reply(&identity.device_lookup(args(body)?).await?),
717 "device_resolve" => reply(&identity.device_resolve(args(body)?).await?),
718 "device_claim" => reply(&identity.device_claim(args(body)?).await?),
Email verification, password reset, and Git for AI scale positioning719 "resend_verification" => reply(&identity.resend_verification(args(body)?).await?),
720 "verify_email" => reply(&identity.verify_email(args(body)?).await?),
721 "request_password_reset" => reply(&identity.request_password_reset(args(body)?).await?),
722 "reset_password" => reply(&identity.reset_password(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look723 // A person's email addresses; see emails.rs and security.rs.
724 "list_emails" => reply(&identity.list_emails(args(body)?).await?),
725 "add_email" => reply(&identity.add_email(args(body)?).await?),
726 "remove_email" => reply(&identity.remove_email(args(body)?).await?),
727 "resend_email_verification" => reply(&identity.resend_email_verification(args(body)?).await?),
728 "update_email_settings" => reply(&identity.update_email_settings(args(body)?).await?),
729 "reauthenticate" => reply(&identity.reauthenticate(args(body)?).await?),
730 "security_log" => reply(&identity.security_log(args(body)?).await?),
731 "email_owners" => reply(&identity.email_owners(args(body)?).await?),
732 "commit_identity" => reply(&identity.commit_identity(args(body)?).await?),
733 "push_email_guard" => reply(&identity.push_email_guard(args(body)?).await?),
734 "admin_user" => reply(&identity.admin_user(args(body)?).await?),
735 "admin_remove_email" => reply(&identity.admin_remove_email(args(body)?).await?),
API and MCP server, Rust identity service, registration, site redesign736 "sign_out" => reply(&identity.sign_out(args(body)?).await?),
737 "user_for_session" => reply(&identity.user_for_session(args(body)?).await?),
738 "user_for_git_credentials" => reply(&identity.user_for_git_credentials(args(body)?).await?),
739 "user_for_access_token" => {
740 let a: TokenArgs = args(body)?;
741 reply(&identity.user_for_access_token(&a.token).await?)
742 }
743 "user_for_ssh_key" => reply(&identity.user_for_ssh_key(args(body)?).await?),
744 "user_by_username" => reply(&identity.user_by_username(args(body)?).await?),
What happened across an outcome, as a feed beside its graph745 "usernames" => reply(&identity.usernames(args(body)?).await?),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains746 "profile" => reply(&identity.profile(args(body)?).await?),
Search across all of g1t, Explore, and a command palette747 "update_profile" => {
748 let outcome = identity.update_profile(args(body)?).await?;
749 if let Outcome::Ok(profile) = &outcome {
750 identity.announce_user(&profile.username, None).await;
751 }
752 reply(&outcome)
753 }
754 "directory" => reply(&identity.directory(args(body)?).await?),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains755 "profile_workspaces" => reply(&identity.profile_workspaces(args(body)?).await?),
API and MCP server, Rust identity service, registration, site redesign756 "list_ssh_keys" => reply(&identity.list_ssh_keys(args(body)?).await?),
757 "add_ssh_key" => reply(&identity.add_ssh_key(args(body)?).await?),
758 "remove_ssh_key" => reply(&identity.remove("ssh_keys", args(body)?).await?),
759 "list_access_tokens" => reply(&identity.list_access_tokens(args(body)?).await?),
760 "create_access_token" => reply(&identity.create_access_token(args(body)?).await?),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step761 "update_access_token" => reply(&identity.update_access_token(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell762 "create_agent_token" => reply(&identity.create_agent_token(args(body)?).await?),
763 "agent_scope" => reply(&identity.agent_scope(args(body)?).await?),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API764 "create_run_credential" => reply(&identity.create_run_credential(args(body)?).await?),
765 "bind_run_credentials" => reply(&identity.bind_run_credentials(args(body)?).await?),
766 "revoke_run_credentials" => reply(&identity.revoke_run_credentials(args(body)?).await?),
API and MCP server, Rust identity service, registration, site redesign767 "remove_access_token" => reply(&identity.remove("access_tokens", args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look768 // Invites and the waitlist; see invites.rs.
769 "registration" => reply(&identity.registration_mode()),
770 "list_invites" => reply(&identity.list_invites(args(body)?).await?),
771 "create_invite" => reply(&identity.create_invite(args(body)?).await?),
772 "revoke_invite" => reply(&identity.revoke_invite(args(body)?).await?),
773 "check_invite" => reply(&identity.check_invite(args(body)?).await?),
774 "accept_invite" => reply(&identity.accept_invite(args(body)?).await?),
775 "invite_member" => reply(&identity.invite_member(args(body)?).await?),
776 "workspace_invites" => reply(&identity.workspace_invites(args(body)?).await?),
777 "revoke_workspace_invite" => reply(&identity.revoke_workspace_invite(args(body)?).await?),
778 "request_access" => reply(&identity.request_access(args(body)?).await?),
779 // Who has access to a repository; see access.rs.
780 "repo_access" => reply(&identity.repo_access(args(body)?).await?),
781 "add_collaborator" => reply(&identity.add_collaborator(args(body)?).await?),
782 "set_collaborator_role" => reply(&identity.set_collaborator_role(args(body)?).await?),
783 "remove_collaborator" => reply(&identity.remove_collaborator(args(body)?).await?),
784 "collaborator_permission" => reply(&identity.collaborator_permission(args(body)?).await?),
785 "my_repo_invitations" => reply(&identity.my_repo_invitations(args(body)?).await?),
786 "respond_repo_invitation" => reply(&identity.respond_repo_invitation(args(body)?).await?),
787 "revoke_repo_invitation" => reply(&identity.revoke_repo_invitation(args(body)?).await?),
788 "set_base_permission" => reply(&identity.set_base_permission(args(body)?).await?),
789 "outside_collaborators" => reply(&identity.outside_collaborators(args(body)?).await?),
790 "forget_repo_access" => reply(&identity.forget_repo_access(args(body)?).await?),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace791 // Staff only: sudo.g1t.sh, over its service binding. See admin.rs.
792 "notify_owners" => reply(&identity.notify_owners(args(body)?).await?),
793 "admin_workspaces" => reply(&identity.admin_workspaces(args(body)?).await?),
794 "admin_workspace" => reply(&identity.admin_workspace(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look795 "admin_waitlist" => reply(&identity.admin_waitlist(args(body)?).await?),
796 "admin_decide_waitlist" => reply(&identity.admin_decide_waitlist(args(body)?).await?),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas797 "admin_waitlist_pending" => reply(&identity.admin_waitlist_pending().await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look798 "admin_invites" => reply(&identity.admin_invites(args(body)?).await?),
799 "admin_revoke_invite" => reply(&identity.admin_revoke_invite(args(body)?).await?),
800 "admin_mint_invite" => reply(&identity.admin_mint_invite(args(body)?).await?),
801 "admin_grant_invites" => reply(&identity.admin_grant_invites(args(body)?).await?),
802 "admin_invite_tree" => reply(&identity.admin_invite_tree(args(body)?).await?),
803 "admin_workspace_invites" => reply(&identity.admin_workspace_invites(args(body)?).await?),
API and MCP server, Rust identity service, registration, site redesign804 _ => Response::error("Unknown method", 404),
Fast pages, required checks on the branch, self-hosted runners, honest incidents805 };
806 served.finish(answered)
API and MCP server, Rust identity service, registration, site redesign807}
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent808
809#[cfg(test)]
810mod register_tests {
811 use super::*;
812
813 #[test]
814 fn nobody_registers_as_g1t() {
815 // What register checks the username with, whatever its case.
816 for username in ["g1t", "G1T", "g1t-agent", "G1t-Agent"] {
817 assert_eq!(claimable_namespace(username), None, "{username}");
818 }
819 assert_eq!(claimable_namespace("ana").as_deref(), Some("ana"));
820 }
821}