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 redesign | 1 | //! 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 | ||
| 6 | mod crypto; | |
| Email verification, password reset, and Git for AI scale positioning | 7 | mod email; |
| API and MCP server, Rust identity service, registration, site redesign | 8 | |
| 9 | use g1t_contracts::identity::*; | |
| 10 | use g1t_contracts::{FailureCode, Outcome, User, Viewer, is_valid_namespace, new_id}; | |
| 11 | use g1t_kit::{args, now_ms, reply, rpc_method}; | |
| 12 | use serde::Deserialize; | |
| 13 | use worker::wasm_bindgen::JsValue; | |
| 14 | use worker::{Context, D1Database, Env, Request, Response, Result, event}; | |
| 15 | ||
| 16 | const SESSION_TTL_SECONDS: u32 = 30 * 24 * 60 * 60; | |
| Email verification, password reset, and Git for AI scale positioning | 17 | const VERIFY_TTL_SECONDS: u32 = 24 * 60 * 60; |
| 18 | const RESET_TTL_SECONDS: u32 = 60 * 60; | |
| API and MCP server, Rust identity service, registration, site redesign | 19 | const TOKEN_PREFIX: &str = "g1t_"; |
| 20 | const MIN_PASSWORD_LENGTH: usize = 10; | |
| Email verification, password reset, and Git for AI scale positioning | 21 | const PASSWORD_TOO_SHORT: &str = "Use a password of at least 10 characters."; |
| 22 | ||
| 23 | /// A user as selected from the database; `verified` arrives as 0 or 1. | |
| 24 | #[derive(Deserialize)] | |
| 25 | struct Account { | |
| 26 | id: String, | |
| 27 | username: String, | |
| 28 | verified: u8, | |
| 29 | } | |
| 30 | ||
| 31 | impl From<Account> for User { | |
| 32 | fn from(row: Account) -> Self { | |
| 33 | User { | |
| 34 | id: row.id, | |
| 35 | username: row.username, | |
| 36 | verified: row.verified != 0, | |
| 37 | } | |
| 38 | } | |
| 39 | } | |
| API and MCP server, Rust identity service, registration, site redesign | 40 | |
| 41 | #[derive(Deserialize)] | |
| 42 | struct UserRow { | |
| 43 | id: String, | |
| 44 | username: String, | |
| 45 | password_hash: String, | |
| Email verification, password reset, and Git for AI scale positioning | 46 | verified: u8, |
| API and MCP server, Rust identity service, registration, site redesign | 47 | } |
| 48 | ||
| Email verification, password reset, and Git for AI scale positioning | 49 | /// The owner of an emailed token. |
| API and MCP server, Rust identity service, registration, site redesign | 50 | #[derive(Deserialize)] |
| Email verification, password reset, and Git for AI scale positioning | 51 | struct TokenOwner { |
| 52 | id: String, | |
| 53 | username: String, | |
| 54 | email: Option<String>, | |
| 55 | } | |
| 56 | ||
| 57 | #[derive(Deserialize)] | |
| API and MCP server, Rust identity service, registration, site redesign | 58 | struct KeyRow { |
| 59 | id: String, | |
| 60 | title: String, | |
| 61 | fingerprint: String, | |
| 62 | created_at: u64, | |
| 63 | } | |
| 64 | ||
| 65 | impl From<KeyRow> for SshKey { | |
| 66 | fn from(row: KeyRow) -> Self { | |
| 67 | SshKey { | |
| 68 | id: row.id, | |
| 69 | title: row.title, | |
| 70 | fingerprint: row.fingerprint, | |
| 71 | created_at: row.created_at * 1000, | |
| 72 | } | |
| 73 | } | |
| 74 | } | |
| 75 | ||
| 76 | #[derive(Deserialize)] | |
| 77 | struct TokenRow { | |
| 78 | id: String, | |
| 79 | name: String, | |
| 80 | created_at: u64, | |
| 81 | } | |
| 82 | ||
| 83 | impl From<TokenRow> for AccessToken { | |
| 84 | fn from(row: TokenRow) -> Self { | |
| 85 | AccessToken { | |
| 86 | id: row.id, | |
| 87 | name: row.name, | |
| 88 | created_at: row.created_at * 1000, | |
| 89 | } | |
| 90 | } | |
| 91 | } | |
| 92 | ||
| 93 | struct Identity { | |
| 94 | db: D1Database, | |
| Email verification, password reset, and Git for AI scale positioning | 95 | env: Env, |
| API and MCP server, Rust identity service, registration, site redesign | 96 | } |
| 97 | ||
| 98 | impl Identity { | |
| 99 | /// Runs a query that returns at most one user. | |
| 100 | async fn find_user(&self, sql: &str, param: &str) -> Result<Viewer> { | |
| Email verification, password reset, and Git for AI scale positioning | 101 | Ok(self |
| 102 | .db | |
| API and MCP server, Rust identity service, registration, site redesign | 103 | .prepare(sql) |
| 104 | .bind(&[JsValue::from(param)])? | |
| Email verification, password reset, and Git for AI scale positioning | 105 | .first::<Account>(None) |
| 106 | .await? | |
| 107 | .map(User::from)) | |
| 108 | } | |
| 109 | ||
| 110 | /// Stores a one-time token of `kind` for the user and returns it. | |
| 111 | async fn issue_email_token(&self, user_id: &str, kind: &str, ttl: u32) -> Result<String> { | |
| 112 | let token = crypto::random_hex(32); | |
| 113 | self.db | |
| 114 | .prepare( | |
| 115 | "INSERT INTO email_tokens (id, user_id, kind, expires_at) | |
| 116 | VALUES (?, ?, ?, unixepoch() + ?)", | |
| 117 | ) | |
| 118 | .bind(&[ | |
| 119 | crypto::sha256_hex(&token).into(), | |
| 120 | user_id.into(), | |
| 121 | kind.into(), | |
| 122 | ttl.into(), | |
| 123 | ])? | |
| 124 | .run() | |
| 125 | .await?; | |
| 126 | Ok(token) | |
| API and MCP server, Rust identity service, registration, site redesign | 127 | } |
| 128 | ||
| Email verification, password reset, and Git for AI scale positioning | 129 | /// Consumes a token of `kind`, returning its owner if it was valid. |
| 130 | async fn redeem_email_token(&self, token: &str, kind: &str) -> Result<Option<TokenOwner>> { | |
| 131 | let id = crypto::sha256_hex(token); | |
| 132 | let owner = self | |
| 133 | .db | |
| 134 | .prepare( | |
| 135 | "SELECT users.id, users.username, users.email FROM email_tokens | |
| 136 | JOIN users ON users.id = email_tokens.user_id | |
| 137 | WHERE email_tokens.id = ? AND email_tokens.kind = ? | |
| 138 | AND email_tokens.expires_at > unixepoch()", | |
| 139 | ) | |
| 140 | .bind(&[id.as_str().into(), kind.into()])? | |
| 141 | .first::<TokenOwner>(None) | |
| 142 | .await?; | |
| 143 | if let Some(owner) = &owner { | |
| 144 | // Every outstanding token of this kind dies with the one used. | |
| 145 | self.db | |
| 146 | .prepare("DELETE FROM email_tokens WHERE user_id = ? AND kind = ?") | |
| 147 | .bind(&[owner.id.as_str().into(), kind.into()])? | |
| 148 | .run() | |
| 149 | .await?; | |
| 150 | } | |
| 151 | Ok(owner) | |
| 152 | } | |
| 153 | ||
| 154 | async fn send_verification(&self, user: &User, email: &str) -> Result<()> { | |
| 155 | let token = self | |
| 156 | .issue_email_token(&user.id, "verify", VERIFY_TTL_SECONDS) | |
| 157 | .await?; | |
| 158 | email::send_verification(&self.env, email, &user.username, &token).await | |
| 159 | } | |
| 160 | ||
| 161 | async fn resend_verification(&self, a: UserArgs) -> Result<Outcome<bool>> { | |
| 162 | let row = self | |
| 163 | .db | |
| 164 | .prepare( | |
| 165 | "SELECT id, username, email FROM users WHERE id = ? AND email_verified_at IS NULL", | |
| 166 | ) | |
| 167 | .bind(&[a.user.id.as_str().into()])? | |
| 168 | .first::<TokenOwner>(None) | |
| 169 | .await?; | |
| 170 | let Some(TokenOwner { | |
| 171 | email: Some(email), .. | |
| 172 | }) = row | |
| 173 | else { | |
| 174 | return Ok(Outcome::fail( | |
| 175 | FailureCode::Conflict, | |
| 176 | "This account's email is already confirmed.", | |
| 177 | )); | |
| 178 | }; | |
| 179 | self.send_verification(&a.user, &email).await?; | |
| 180 | Ok(Outcome::Ok(true)) | |
| 181 | } | |
| 182 | ||
| 183 | async fn verify_email(&self, a: EmailTokenArgs) -> Result<Outcome<User>> { | |
| 184 | let Some(owner) = self.redeem_email_token(&a.token, "verify").await? else { | |
| 185 | return Ok(Outcome::fail( | |
| 186 | FailureCode::Invalid, | |
| 187 | "This confirmation link is not valid or has expired.", | |
| 188 | )); | |
| 189 | }; | |
| 190 | self.db | |
| 191 | .prepare("UPDATE users SET email_verified_at = unixepoch() WHERE id = ?") | |
| 192 | .bind(&[owner.id.as_str().into()])? | |
| 193 | .run() | |
| 194 | .await?; | |
| 195 | Ok(Outcome::Ok(User { | |
| 196 | id: owner.id, | |
| 197 | username: owner.username, | |
| 198 | verified: true, | |
| 199 | })) | |
| 200 | } | |
| 201 | ||
| 202 | async fn request_password_reset(&self, a: EmailArgs) -> Result<bool> { | |
| 203 | let row = self | |
| 204 | .db | |
| 205 | .prepare("SELECT id, username, email FROM users WHERE email = ?") | |
| 206 | .bind(&[a.email.trim().to_lowercase().into()])? | |
| 207 | .first::<TokenOwner>(None) | |
| 208 | .await?; | |
| 209 | if let Some(TokenOwner { | |
| 210 | id, | |
| 211 | username, | |
| 212 | email: Some(email), | |
| 213 | }) = row | |
| 214 | { | |
| 215 | let token = self | |
| 216 | .issue_email_token(&id, "reset", RESET_TTL_SECONDS) | |
| 217 | .await?; | |
| 218 | email::send_password_reset(&self.env, &email, &username, &token).await?; | |
| 219 | } | |
| 220 | // The same answer either way, so addresses cannot be probed. | |
| 221 | Ok(true) | |
| 222 | } | |
| 223 | ||
| 224 | async fn reset_password(&self, a: ResetPasswordArgs) -> Result<Outcome<User>> { | |
| 225 | if a.password.chars().count() < MIN_PASSWORD_LENGTH { | |
| 226 | return Ok(Outcome::fail(FailureCode::Invalid, PASSWORD_TOO_SHORT)); | |
| 227 | } | |
| 228 | let Some(owner) = self.redeem_email_token(&a.token, "reset").await? else { | |
| 229 | return Ok(Outcome::fail( | |
| 230 | FailureCode::Invalid, | |
| 231 | "This reset link is not valid or has expired.", | |
| 232 | )); | |
| 233 | }; | |
| 234 | // Following an emailed link also proves the address. | |
| 235 | self.db | |
| 236 | .prepare( | |
| 237 | "UPDATE users SET password_hash = ?, | |
| 238 | email_verified_at = COALESCE(email_verified_at, unixepoch()) | |
| 239 | WHERE id = ?", | |
| 240 | ) | |
| 241 | .bind(&[ | |
| 242 | crypto::hash_password(&a.password).into(), | |
| 243 | owner.id.as_str().into(), | |
| 244 | ])? | |
| 245 | .run() | |
| 246 | .await?; | |
| 247 | // Anyone signed in with the old password is signed out. | |
| 248 | self.db | |
| 249 | .prepare("DELETE FROM sessions WHERE user_id = ?") | |
| 250 | .bind(&[owner.id.as_str().into()])? | |
| 251 | .run() | |
| 252 | .await?; | |
| 253 | Ok(Outcome::Ok(User { | |
| 254 | id: owner.id, | |
| 255 | username: owner.username, | |
| 256 | verified: true, | |
| 257 | })) | |
| 258 | } | |
| 259 | ||
| API and MCP server, Rust identity service, registration, site redesign | 260 | async fn user_for_password(&self, username: &str, password: &str) -> Result<Viewer> { |
| 261 | let row = self | |
| 262 | .db | |
| Email verification, password reset, and Git for AI scale positioning | 263 | .prepare("SELECT id, username, password_hash, email_verified_at IS NOT NULL AS verified FROM users WHERE username = ?") |
| API and MCP server, Rust identity service, registration, site redesign | 264 | .bind(&[JsValue::from(username.to_lowercase())])? |
| 265 | .first::<UserRow>(None) | |
| 266 | .await?; | |
| 267 | Ok(row | |
| 268 | .filter(|row| crypto::verify_password(password, &row.password_hash)) | |
| 269 | .map(|row| User { | |
| 270 | id: row.id, | |
| 271 | username: row.username, | |
| Email verification, password reset, and Git for AI scale positioning | 272 | verified: row.verified != 0, |
| API and MCP server, Rust identity service, registration, site redesign | 273 | })) |
| 274 | } | |
| 275 | ||
| 276 | async fn register(&self, a: RegisterArgs) -> Result<Outcome<SignedIn>> { | |
| 277 | let username = a.username.trim().to_lowercase(); | |
| 278 | let email = a.email.trim().to_lowercase(); | |
| 279 | let invalid = |message: &str| Ok(Outcome::fail(FailureCode::Invalid, message)); | |
| 280 | if !is_valid_namespace(&username) { | |
| 281 | return invalid( | |
| 282 | "Usernames use lowercase letters, digits and single hyphens, up to 39 characters.", | |
| 283 | ); | |
| 284 | } | |
| 285 | let well_formed_email = email | |
| 286 | .split_once('@') | |
| 287 | .is_some_and(|(local, domain)| !local.is_empty() && domain.contains('.')) | |
| 288 | && !email.contains(char::is_whitespace); | |
| 289 | if !well_formed_email { | |
| 290 | return invalid("Enter a valid email address."); | |
| 291 | } | |
| 292 | if a.password.chars().count() < MIN_PASSWORD_LENGTH { | |
| Email verification, password reset, and Git for AI scale positioning | 293 | return invalid(PASSWORD_TOO_SHORT); |
| API and MCP server, Rust identity service, registration, site redesign | 294 | } |
| 295 | let taken = self | |
| 296 | .db | |
| 297 | .prepare("SELECT username FROM users WHERE username = ? OR email = ?") | |
| 298 | .bind(&[username.as_str().into(), email.as_str().into()])? | |
| 299 | .first::<serde_json::Value>(None) | |
| 300 | .await?; | |
| 301 | if taken.is_some() { | |
| 302 | return Ok(Outcome::fail( | |
| 303 | FailureCode::Conflict, | |
| 304 | "That username or email is already registered.", | |
| 305 | )); | |
| 306 | } | |
| 307 | let user = User { | |
| 308 | id: new_id("usr", now_ms()), | |
| 309 | username, | |
| Email verification, password reset, and Git for AI scale positioning | 310 | verified: false, |
| API and MCP server, Rust identity service, registration, site redesign | 311 | }; |
| 312 | self.db | |
| 313 | .prepare("INSERT INTO users (id, username, email, password_hash) VALUES (?, ?, ?, ?)") | |
| 314 | .bind(&[ | |
| 315 | user.id.as_str().into(), | |
| 316 | user.username.as_str().into(), | |
| Email verification, password reset, and Git for AI scale positioning | 317 | email.as_str().into(), |
| API and MCP server, Rust identity service, registration, site redesign | 318 | crypto::hash_password(&a.password).into(), |
| 319 | ])? | |
| 320 | .run() | |
| 321 | .await?; | |
| Email verification, password reset, and Git for AI scale positioning | 322 | // The account exists either way; the email can be sent again later. |
| 323 | if let Err(error) = self.send_verification(&user, &email).await { | |
| 324 | worker::console_error!("verification email failed: {error}"); | |
| 325 | } | |
| API and MCP server, Rust identity service, registration, site redesign | 326 | self.start_session(user).await |
| 327 | } | |
| 328 | ||
| 329 | async fn sign_in(&self, a: SignInArgs) -> Result<Outcome<SignedIn>> { | |
| 330 | let Some(user) = self.user_for_password(&a.username, &a.password).await? else { | |
| 331 | return Ok(Outcome::fail( | |
| 332 | FailureCode::Unauthenticated, | |
| 333 | "Incorrect username or password.", | |
| 334 | )); | |
| 335 | }; | |
| 336 | self.start_session(user).await | |
| 337 | } | |
| 338 | ||
| 339 | async fn start_session(&self, user: User) -> Result<Outcome<SignedIn>> { | |
| 340 | let session_token = crypto::random_hex(32); | |
| 341 | self.db | |
| 342 | .prepare( | |
| 343 | "INSERT INTO sessions (id, user_id, expires_at) VALUES (?, ?, unixepoch() + ?)", | |
| 344 | ) | |
| 345 | .bind(&[ | |
| 346 | crypto::sha256_hex(&session_token).into(), | |
| 347 | user.id.as_str().into(), | |
| 348 | SESSION_TTL_SECONDS.into(), | |
| 349 | ])? | |
| 350 | .run() | |
| 351 | .await?; | |
| 352 | Ok(Outcome::Ok(SignedIn { | |
| 353 | user, | |
| 354 | session_token, | |
| 355 | })) | |
| 356 | } | |
| 357 | ||
| 358 | async fn sign_out(&self, a: SessionArgs) -> Result<()> { | |
| 359 | self.db | |
| 360 | .prepare("DELETE FROM sessions WHERE id = ?") | |
| 361 | .bind(&[crypto::sha256_hex(&a.session_token).into()])? | |
| 362 | .run() | |
| 363 | .await?; | |
| 364 | Ok(()) | |
| 365 | } | |
| 366 | ||
| 367 | async fn user_for_session(&self, a: SessionArgs) -> Result<Viewer> { | |
| 368 | self.find_user( | |
| Email verification, password reset, and Git for AI scale positioning | 369 | "SELECT users.id, users.username, users.email_verified_at IS NOT NULL AS verified FROM sessions |
| API and MCP server, Rust identity service, registration, site redesign | 370 | JOIN users ON users.id = sessions.user_id |
| 371 | WHERE sessions.id = ? AND sessions.expires_at > unixepoch()", | |
| 372 | &crypto::sha256_hex(&a.session_token), | |
| 373 | ) | |
| 374 | .await | |
| 375 | } | |
| 376 | ||
| 377 | async fn user_for_access_token(&self, token: &str) -> Result<Viewer> { | |
| 378 | if !token.starts_with(TOKEN_PREFIX) { | |
| 379 | return Ok(None); | |
| 380 | } | |
| 381 | self.find_user( | |
| Email verification, password reset, and Git for AI scale positioning | 382 | "SELECT users.id, users.username, users.email_verified_at IS NOT NULL AS verified FROM access_tokens |
| API and MCP server, Rust identity service, registration, site redesign | 383 | JOIN users ON users.id = access_tokens.user_id |
| Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed) | 384 | WHERE token_hash = ? |
| 385 | AND (access_tokens.expires_at IS NULL OR access_tokens.expires_at > unixepoch())", | |
| API and MCP server, Rust identity service, registration, site redesign | 386 | &crypto::sha256_hex(token), |
| 387 | ) | |
| 388 | .await | |
| 389 | } | |
| 390 | ||
| 391 | async fn user_for_git_credentials(&self, a: GitCredentialsArgs) -> Result<Viewer> { | |
| 392 | // Like GitHub, a token alone identifies its user. | |
| 393 | if a.secret.starts_with(TOKEN_PREFIX) { | |
| 394 | self.user_for_access_token(&a.secret).await | |
| 395 | } else { | |
| 396 | self.user_for_password(&a.username, &a.secret).await | |
| 397 | } | |
| 398 | } | |
| 399 | ||
| 400 | async fn user_for_ssh_key(&self, a: FingerprintArgs) -> Result<Viewer> { | |
| 401 | self.find_user( | |
| Email verification, password reset, and Git for AI scale positioning | 402 | "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 redesign | 403 | JOIN users ON users.id = ssh_keys.user_id |
| 404 | WHERE fingerprint = ?", | |
| 405 | &a.fingerprint, | |
| 406 | ) | |
| 407 | .await | |
| 408 | } | |
| 409 | ||
| 410 | async fn user_by_username(&self, a: UsernameArgs) -> Result<Viewer> { | |
| 411 | self.find_user( | |
| Email verification, password reset, and Git for AI scale positioning | 412 | "SELECT id, username, email_verified_at IS NOT NULL AS verified FROM users WHERE username = ?", |
| API and MCP server, Rust identity service, registration, site redesign | 413 | &a.username.to_lowercase(), |
| 414 | ) | |
| 415 | .await | |
| 416 | } | |
| 417 | ||
| 418 | async fn list_ssh_keys(&self, a: UserArgs) -> Result<Vec<SshKey>> { | |
| 419 | let rows = self | |
| 420 | .db | |
| 421 | .prepare("SELECT id, title, fingerprint, created_at FROM ssh_keys WHERE user_id = ? ORDER BY id") | |
| 422 | .bind(&[a.user.id.into()])? | |
| 423 | .all() | |
| 424 | .await? | |
| 425 | .results::<KeyRow>()?; | |
| 426 | Ok(rows.into_iter().map(SshKey::from).collect()) | |
| 427 | } | |
| 428 | ||
| 429 | async fn add_ssh_key(&self, a: AddSshKeyArgs) -> Result<Outcome<SshKey>> { | |
| 430 | let Some(key) = crypto::parse_ssh_key(&a.public_key) else { | |
| 431 | return Ok(Outcome::fail( | |
| 432 | FailureCode::Invalid, | |
| 433 | "That is not a valid OpenSSH public key.", | |
| 434 | )); | |
| 435 | }; | |
| 436 | let taken = self | |
| 437 | .db | |
| 438 | .prepare("SELECT id FROM ssh_keys WHERE fingerprint = ?") | |
| 439 | .bind(&[key.fingerprint.as_str().into()])? | |
| 440 | .first::<serde_json::Value>(None) | |
| 441 | .await?; | |
| 442 | if taken.is_some() { | |
| 443 | return Ok(Outcome::fail( | |
| 444 | FailureCode::Conflict, | |
| 445 | "That key is already registered.", | |
| 446 | )); | |
| 447 | } | |
| 448 | let now = now_ms(); | |
| 449 | let title = [a.title.trim(), key.comment.as_str(), "SSH key"] | |
| 450 | .into_iter() | |
| 451 | .find(|candidate| !candidate.is_empty()) | |
| 452 | .unwrap_or_default() | |
| 453 | .to_owned(); | |
| 454 | let row = KeyRow { | |
| 455 | id: new_id("key", now), | |
| 456 | title, | |
| 457 | fingerprint: key.fingerprint, | |
| 458 | created_at: now / 1000, | |
| 459 | }; | |
| 460 | self.db | |
| 461 | .prepare( | |
| 462 | "INSERT INTO ssh_keys (id, user_id, title, public_key, fingerprint, created_at) | |
| 463 | VALUES (?, ?, ?, ?, ?, ?)", | |
| 464 | ) | |
| 465 | .bind(&[ | |
| 466 | row.id.as_str().into(), | |
| 467 | a.user.id.into(), | |
| 468 | row.title.as_str().into(), | |
| 469 | key.public_key.into(), | |
| 470 | row.fingerprint.as_str().into(), | |
| 471 | (row.created_at as f64).into(), | |
| 472 | ])? | |
| 473 | .run() | |
| 474 | .await?; | |
| 475 | Ok(Outcome::Ok(row.into())) | |
| 476 | } | |
| 477 | ||
| 478 | async fn list_access_tokens(&self, a: UserArgs) -> Result<Vec<AccessToken>> { | |
| 479 | let rows = self | |
| 480 | .db | |
| Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed) | 481 | // Expiring tokens belong to hosted attempts, not to the user's list. |
| 482 | .prepare( | |
| 483 | "SELECT id, name, created_at FROM access_tokens | |
| 484 | WHERE user_id = ? AND expires_at IS NULL ORDER BY id", | |
| 485 | ) | |
| API and MCP server, Rust identity service, registration, site redesign | 486 | .bind(&[a.user.id.into()])? |
| 487 | .all() | |
| 488 | .await? | |
| 489 | .results::<TokenRow>()?; | |
| 490 | Ok(rows.into_iter().map(AccessToken::from).collect()) | |
| 491 | } | |
| 492 | ||
| 493 | async fn create_access_token(&self, a: CreateAccessTokenArgs) -> Result<CreatedAccessToken> { | |
| 494 | let token = format!("{TOKEN_PREFIX}{}", crypto::random_hex(20)); | |
| 495 | let now = now_ms(); | |
| 496 | let name = match a.name.trim() { | |
| 497 | "" => "Access token", | |
| 498 | name => name, | |
| 499 | }; | |
| 500 | let row = TokenRow { | |
| 501 | id: new_id("tok", now), | |
| 502 | name: name.to_owned(), | |
| 503 | created_at: now / 1000, | |
| 504 | }; | |
| 505 | self.db | |
| 506 | .prepare( | |
| Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed) | 507 | "INSERT INTO access_tokens (id, user_id, name, token_hash, created_at, expires_at) |
| 508 | VALUES (?, ?, ?, ?, ?, ?)", | |
| API and MCP server, Rust identity service, registration, site redesign | 509 | ) |
| 510 | .bind(&[ | |
| 511 | row.id.as_str().into(), | |
| 512 | a.user.id.into(), | |
| 513 | row.name.as_str().into(), | |
| 514 | crypto::sha256_hex(&token).into(), | |
| 515 | (row.created_at as f64).into(), | |
| Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed) | 516 | a.ttl_seconds |
| 517 | .map_or(JsValue::NULL, |ttl| ((row.created_at + ttl) as f64).into()), | |
| API and MCP server, Rust identity service, registration, site redesign | 518 | ])? |
| 519 | .run() | |
| 520 | .await?; | |
| 521 | Ok(CreatedAccessToken { | |
| 522 | token, | |
| 523 | info: row.into(), | |
| 524 | }) | |
| 525 | } | |
| 526 | ||
| 527 | /// Deletes a row the user owns from `table`. | |
| 528 | async fn remove(&self, table: &str, a: RemoveArgs) -> Result<()> { | |
| 529 | self.db | |
| 530 | .prepare(format!("DELETE FROM {table} WHERE id = ? AND user_id = ?")) | |
| 531 | .bind(&[a.id.into(), a.user.id.into()])? | |
| 532 | .run() | |
| 533 | .await?; | |
| 534 | Ok(()) | |
| 535 | } | |
| 536 | } | |
| 537 | ||
| 538 | #[event(fetch)] | |
| 539 | async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> { | |
| 540 | let Some(method) = rpc_method(&request) else { | |
| 541 | return Response::error("Not found", 404); | |
| 542 | }; | |
| 543 | let body: serde_json::Value = request.json().await?; | |
| Email verification, password reset, and Git for AI scale positioning | 544 | let identity = Identity { |
| 545 | db: env.d1("DB")?, | |
| 546 | env, | |
| 547 | }; | |
| API and MCP server, Rust identity service, registration, site redesign | 548 | |
| 549 | match method.as_str() { | |
| 550 | "register" => reply(&identity.register(args(body)?).await?), | |
| 551 | "sign_in" => reply(&identity.sign_in(args(body)?).await?), | |
| Email verification, password reset, and Git for AI scale positioning | 552 | "resend_verification" => reply(&identity.resend_verification(args(body)?).await?), |
| 553 | "verify_email" => reply(&identity.verify_email(args(body)?).await?), | |
| 554 | "request_password_reset" => reply(&identity.request_password_reset(args(body)?).await?), | |
| 555 | "reset_password" => reply(&identity.reset_password(args(body)?).await?), | |
| API and MCP server, Rust identity service, registration, site redesign | 556 | "sign_out" => reply(&identity.sign_out(args(body)?).await?), |
| 557 | "user_for_session" => reply(&identity.user_for_session(args(body)?).await?), | |
| 558 | "user_for_git_credentials" => reply(&identity.user_for_git_credentials(args(body)?).await?), | |
| 559 | "user_for_access_token" => { | |
| 560 | let a: TokenArgs = args(body)?; | |
| 561 | reply(&identity.user_for_access_token(&a.token).await?) | |
| 562 | } | |
| 563 | "user_for_ssh_key" => reply(&identity.user_for_ssh_key(args(body)?).await?), | |
| 564 | "user_by_username" => reply(&identity.user_by_username(args(body)?).await?), | |
| 565 | "list_ssh_keys" => reply(&identity.list_ssh_keys(args(body)?).await?), | |
| 566 | "add_ssh_key" => reply(&identity.add_ssh_key(args(body)?).await?), | |
| 567 | "remove_ssh_key" => reply(&identity.remove("ssh_keys", args(body)?).await?), | |
| 568 | "list_access_tokens" => reply(&identity.list_access_tokens(args(body)?).await?), | |
| 569 | "create_access_token" => reply(&identity.create_access_token(args(body)?).await?), | |
| 570 | "remove_access_token" => reply(&identity.remove("access_tokens", args(body)?).await?), | |
| 571 | _ => Response::error("Unknown method", 404), | |
| 572 | } | |
| 573 | } |