this repo has no description
1use axum::{ 2 Json, 3 extract::State, 4 http::{HeaderMap, StatusCode}, 5 response::{IntoResponse, Response}, 6}; 7use bcrypt::{DEFAULT_COST, hash}; 8use chrono::{Duration, Utc}; 9use jacquard::types::{integer::LimitedU32, string::Tid}; 10use jacquard_repo::{mst::Mst, storage::BlockStore}; 11use rand::Rng; 12use serde::{Deserialize, Serialize}; 13use serde_json::json; 14use std::sync::Arc; 15use tracing::{debug, error, info, warn}; 16use uuid::Uuid; 17 18use crate::api::repo::record::utils::create_signed_commit; 19use crate::auth::{ServiceTokenVerifier, extract_bearer_token_from_header, is_service_token}; 20use crate::state::{AppState, RateLimitKind}; 21use crate::validation::validate_password; 22 23fn extract_client_ip(headers: &HeaderMap) -> String { 24 if let Some(forwarded) = headers.get("x-forwarded-for") 25 && let Ok(value) = forwarded.to_str() 26 && let Some(first_ip) = value.split(',').next() 27 { 28 return first_ip.trim().to_string(); 29 } 30 if let Some(real_ip) = headers.get("x-real-ip") 31 && let Ok(value) = real_ip.to_str() 32 { 33 return value.trim().to_string(); 34 } 35 "unknown".to_string() 36} 37 38fn generate_setup_token() -> String { 39 let mut rng = rand::thread_rng(); 40 (0..32) 41 .map(|_| { 42 let idx = rng.gen_range(0..36); 43 if idx < 10 { 44 (b'0' + idx) as char 45 } else { 46 (b'a' + idx - 10) as char 47 } 48 }) 49 .collect() 50} 51 52fn generate_app_password() -> String { 53 let chars: &[u8] = b"abcdefghijklmnopqrstuvwxyz234567"; 54 let mut rng = rand::thread_rng(); 55 let segments: Vec<String> = (0..4) 56 .map(|_| { 57 (0..4) 58 .map(|_| chars[rng.gen_range(0..chars.len())] as char) 59 .collect() 60 }) 61 .collect(); 62 segments.join("-") 63} 64 65#[derive(Deserialize)] 66#[serde(rename_all = "camelCase")] 67pub struct CreatePasskeyAccountInput { 68 pub handle: String, 69 pub email: Option<String>, 70 pub invite_code: Option<String>, 71 pub did: Option<String>, 72 pub did_type: Option<String>, 73 pub signing_key: Option<String>, 74 pub verification_channel: Option<String>, 75 pub discord_id: Option<String>, 76 pub telegram_username: Option<String>, 77 pub signal_number: Option<String>, 78} 79 80#[derive(Serialize)] 81#[serde(rename_all = "camelCase")] 82pub struct CreatePasskeyAccountResponse { 83 pub did: String, 84 pub handle: String, 85 pub setup_token: String, 86 pub setup_expires_at: chrono::DateTime<Utc>, 87 #[serde(skip_serializing_if = "Option::is_none")] 88 pub access_jwt: Option<String>, 89} 90 91pub async fn create_passkey_account( 92 State(state): State<AppState>, 93 headers: HeaderMap, 94 Json(input): Json<CreatePasskeyAccountInput>, 95) -> Response { 96 let client_ip = extract_client_ip(&headers); 97 if !state 98 .check_rate_limit(RateLimitKind::AccountCreation, &client_ip) 99 .await 100 { 101 warn!(ip = %client_ip, "Account creation rate limit exceeded"); 102 return ( 103 StatusCode::TOO_MANY_REQUESTS, 104 Json(json!({ 105 "error": "RateLimitExceeded", 106 "message": "Too many account creation attempts. Please try again later." 107 })), 108 ) 109 .into_response(); 110 } 111 112 let byod_auth = if let Some(token) = 113 extract_bearer_token_from_header(headers.get("Authorization").and_then(|h| h.to_str().ok())) 114 { 115 if is_service_token(&token) { 116 let verifier = ServiceTokenVerifier::new(); 117 match verifier 118 .verify_service_token(&token, Some("com.atproto.server.createAccount")) 119 .await 120 { 121 Ok(claims) => { 122 debug!( 123 "Service token verified for BYOD did:web: iss={}", 124 claims.iss 125 ); 126 Some(claims.iss) 127 } 128 Err(e) => { 129 error!("Service token verification failed: {:?}", e); 130 return ( 131 StatusCode::UNAUTHORIZED, 132 Json(json!({ 133 "error": "AuthenticationFailed", 134 "message": format!("Service token verification failed: {}", e) 135 })), 136 ) 137 .into_response(); 138 } 139 } 140 } else { 141 None 142 } 143 } else { 144 None 145 }; 146 147 let is_byod_did_web = byod_auth.is_some() 148 && input 149 .did 150 .as_ref() 151 .map(|d| d.starts_with("did:web:")) 152 .unwrap_or(false); 153 154 let hostname = std::env::var("PDS_HOSTNAME").unwrap_or_else(|_| "localhost".to_string()); 155 let pds_suffix = format!(".{}", hostname); 156 157 let handle = if !input.handle.contains('.') || input.handle.ends_with(&pds_suffix) { 158 let handle_to_validate = if input.handle.ends_with(&pds_suffix) { 159 input 160 .handle 161 .strip_suffix(&pds_suffix) 162 .unwrap_or(&input.handle) 163 } else { 164 &input.handle 165 }; 166 match crate::api::validation::validate_short_handle(handle_to_validate) { 167 Ok(h) => format!("{}.{}", h, hostname), 168 Err(e) => { 169 return ( 170 StatusCode::BAD_REQUEST, 171 Json(json!({"error": "InvalidHandle", "message": e.to_string()})), 172 ) 173 .into_response(); 174 } 175 } 176 } else { 177 input.handle.to_lowercase() 178 }; 179 180 let email = input 181 .email 182 .as_ref() 183 .map(|e| e.trim().to_string()) 184 .filter(|e| !e.is_empty()); 185 if let Some(ref email) = email 186 && !crate::api::validation::is_valid_email(email) 187 { 188 return ( 189 StatusCode::BAD_REQUEST, 190 Json(json!({"error": "InvalidEmail", "message": "Invalid email format"})), 191 ) 192 .into_response(); 193 } 194 195 if let Some(ref code) = input.invite_code { 196 let valid = sqlx::query_scalar!( 197 "SELECT available_uses > 0 AND NOT disabled FROM invite_codes WHERE code = $1", 198 code 199 ) 200 .fetch_optional(&state.db) 201 .await 202 .ok() 203 .flatten() 204 .unwrap_or(Some(false)); 205 206 if valid != Some(true) { 207 return ( 208 StatusCode::BAD_REQUEST, 209 Json(json!({"error": "InvalidInviteCode", "message": "Invalid or expired invite code"})), 210 ) 211 .into_response(); 212 } 213 } else { 214 let invite_required = std::env::var("INVITE_CODE_REQUIRED") 215 .map(|v| v == "true" || v == "1") 216 .unwrap_or(false); 217 if invite_required { 218 return ( 219 StatusCode::BAD_REQUEST, 220 Json(json!({"error": "InviteCodeRequired", "message": "An invite code is required to create an account"})), 221 ) 222 .into_response(); 223 } 224 } 225 226 let verification_channel = input.verification_channel.as_deref().unwrap_or("email"); 227 let verification_recipient = match verification_channel { 228 "email" => match &email { 229 Some(e) if !e.is_empty() => e.clone(), 230 _ => return ( 231 StatusCode::BAD_REQUEST, 232 Json(json!({"error": "MissingEmail", "message": "Email is required when using email verification"})), 233 ).into_response(), 234 }, 235 "discord" => match &input.discord_id { 236 Some(id) if !id.trim().is_empty() => id.trim().to_string(), 237 _ => return ( 238 StatusCode::BAD_REQUEST, 239 Json(json!({"error": "MissingDiscordId", "message": "Discord ID is required when using Discord verification"})), 240 ).into_response(), 241 }, 242 "telegram" => match &input.telegram_username { 243 Some(username) if !username.trim().is_empty() => username.trim().to_string(), 244 _ => return ( 245 StatusCode::BAD_REQUEST, 246 Json(json!({"error": "MissingTelegramUsername", "message": "Telegram username is required when using Telegram verification"})), 247 ).into_response(), 248 }, 249 "signal" => match &input.signal_number { 250 Some(number) if !number.trim().is_empty() => number.trim().to_string(), 251 _ => return ( 252 StatusCode::BAD_REQUEST, 253 Json(json!({"error": "MissingSignalNumber", "message": "Signal phone number is required when using Signal verification"})), 254 ).into_response(), 255 }, 256 _ => return ( 257 StatusCode::BAD_REQUEST, 258 Json(json!({"error": "InvalidVerificationChannel", "message": "Invalid verification channel"})), 259 ).into_response(), 260 }; 261 262 use k256::ecdsa::SigningKey; 263 use rand::rngs::OsRng; 264 265 let pds_endpoint = format!("https://{}", hostname); 266 let did_type = input.did_type.as_deref().unwrap_or("plc"); 267 268 let (secret_key_bytes, reserved_key_id): (Vec<u8>, Option<Uuid>) = 269 if let Some(signing_key_did) = &input.signing_key { 270 let reserved = sqlx::query!( 271 r#" 272 SELECT id, private_key_bytes 273 FROM reserved_signing_keys 274 WHERE public_key_did_key = $1 275 AND used_at IS NULL 276 AND expires_at > NOW() 277 FOR UPDATE 278 "#, 279 signing_key_did 280 ) 281 .fetch_optional(&state.db) 282 .await; 283 match reserved { 284 Ok(Some(row)) => (row.private_key_bytes, Some(row.id)), 285 Ok(None) => { 286 return ( 287 StatusCode::BAD_REQUEST, 288 Json(json!({ 289 "error": "InvalidSigningKey", 290 "message": "Signing key not found, already used, or expired" 291 })), 292 ) 293 .into_response(); 294 } 295 Err(e) => { 296 error!("Error looking up reserved signing key: {:?}", e); 297 return ( 298 StatusCode::INTERNAL_SERVER_ERROR, 299 Json(json!({"error": "InternalError"})), 300 ) 301 .into_response(); 302 } 303 } 304 } else { 305 let secret_key = k256::SecretKey::random(&mut OsRng); 306 (secret_key.to_bytes().to_vec(), None) 307 }; 308 309 let secret_key = match SigningKey::from_slice(&secret_key_bytes) { 310 Ok(k) => k, 311 Err(e) => { 312 error!("Error creating signing key: {:?}", e); 313 return ( 314 StatusCode::INTERNAL_SERVER_ERROR, 315 Json(json!({"error": "InternalError"})), 316 ) 317 .into_response(); 318 } 319 }; 320 321 let did = match did_type { 322 "web" => { 323 let subdomain_host = format!("{}.{}", input.handle, hostname); 324 let encoded_subdomain = subdomain_host.replace(':', "%3A"); 325 let self_hosted_did = format!("did:web:{}", encoded_subdomain); 326 info!(did = %self_hosted_did, "Creating self-hosted did:web passkey account"); 327 self_hosted_did 328 } 329 "web-external" => { 330 let d = match &input.did { 331 Some(d) if !d.trim().is_empty() => d.trim(), 332 _ => { 333 return ( 334 StatusCode::BAD_REQUEST, 335 Json(json!({"error": "InvalidRequest", "message": "External did:web requires the 'did' field to be provided"})), 336 ) 337 .into_response(); 338 } 339 }; 340 if !d.starts_with("did:web:") { 341 return ( 342 StatusCode::BAD_REQUEST, 343 Json( 344 json!({"error": "InvalidDid", "message": "External DID must be a did:web"}), 345 ), 346 ) 347 .into_response(); 348 } 349 if is_byod_did_web { 350 if let Some(ref auth_did) = byod_auth 351 && d != auth_did 352 { 353 return ( 354 StatusCode::FORBIDDEN, 355 Json(json!({ 356 "error": "AuthorizationError", 357 "message": format!("Service token issuer {} does not match DID {}", auth_did, d) 358 })), 359 ) 360 .into_response(); 361 } 362 info!(did = %d, "Creating external did:web passkey account (BYOD key)"); 363 } else { 364 if let Err(e) = crate::api::identity::did::verify_did_web( 365 d, 366 &hostname, 367 &input.handle, 368 input.signing_key.as_deref(), 369 ) 370 .await 371 { 372 return ( 373 StatusCode::BAD_REQUEST, 374 Json(json!({"error": "InvalidDid", "message": e})), 375 ) 376 .into_response(); 377 } 378 info!(did = %d, "Creating external did:web passkey account (reserved key)"); 379 } 380 d.to_string() 381 } 382 _ => { 383 if let Some(ref auth_did) = byod_auth { 384 if let Some(ref provided_did) = input.did { 385 if provided_did.starts_with("did:plc:") { 386 if provided_did != auth_did { 387 return ( 388 StatusCode::FORBIDDEN, 389 Json(json!({ 390 "error": "AuthorizationError", 391 "message": format!("Service token issuer {} does not match DID {}", auth_did, provided_did) 392 })), 393 ) 394 .into_response(); 395 } 396 info!(did = %provided_did, "Creating BYOD did:plc passkey account (migration)"); 397 provided_did.clone() 398 } else { 399 return ( 400 StatusCode::BAD_REQUEST, 401 Json(json!({ 402 "error": "InvalidRequest", 403 "message": "BYOD migration requires a did:plc or did:web DID" 404 })), 405 ) 406 .into_response(); 407 } 408 } else { 409 return ( 410 StatusCode::BAD_REQUEST, 411 Json(json!({ 412 "error": "InvalidRequest", 413 "message": "BYOD migration requires the 'did' field" 414 })), 415 ) 416 .into_response(); 417 } 418 } else { 419 let rotation_key = std::env::var("PLC_ROTATION_KEY") 420 .unwrap_or_else(|_| crate::plc::signing_key_to_did_key(&secret_key)); 421 422 let genesis_result = match crate::plc::create_genesis_operation( 423 &secret_key, 424 &rotation_key, 425 &handle, 426 &pds_endpoint, 427 ) { 428 Ok(r) => r, 429 Err(e) => { 430 error!("Error creating PLC genesis operation: {:?}", e); 431 return ( 432 StatusCode::INTERNAL_SERVER_ERROR, 433 Json(json!({"error": "InternalError", "message": "Failed to create PLC operation"})), 434 ) 435 .into_response(); 436 } 437 }; 438 439 let plc_client = crate::plc::PlcClient::new(None); 440 if let Err(e) = plc_client 441 .send_operation(&genesis_result.did, &genesis_result.signed_operation) 442 .await 443 { 444 error!("Failed to submit PLC genesis operation: {:?}", e); 445 return ( 446 StatusCode::BAD_GATEWAY, 447 Json(json!({ 448 "error": "UpstreamError", 449 "message": format!("Failed to register DID with PLC directory: {}", e) 450 })), 451 ) 452 .into_response(); 453 } 454 genesis_result.did 455 } 456 } 457 }; 458 459 info!(did = %did, handle = %handle, "Created DID for passkey-only account"); 460 461 let setup_token = generate_setup_token(); 462 let setup_token_hash = match hash(&setup_token, DEFAULT_COST) { 463 Ok(h) => h, 464 Err(e) => { 465 error!("Error hashing setup token: {:?}", e); 466 return ( 467 StatusCode::INTERNAL_SERVER_ERROR, 468 Json(json!({"error": "InternalError"})), 469 ) 470 .into_response(); 471 } 472 }; 473 let setup_expires_at = Utc::now() + Duration::hours(1); 474 475 let mut tx = match state.db.begin().await { 476 Ok(tx) => tx, 477 Err(e) => { 478 error!("Error starting transaction: {:?}", e); 479 return ( 480 StatusCode::INTERNAL_SERVER_ERROR, 481 Json(json!({"error": "InternalError"})), 482 ) 483 .into_response(); 484 } 485 }; 486 487 let is_first_user = sqlx::query_scalar!("SELECT COUNT(*) as count FROM users") 488 .fetch_one(&mut *tx) 489 .await 490 .map(|c| c.unwrap_or(0) == 0) 491 .unwrap_or(false); 492 493 let deactivated_at: Option<chrono::DateTime<Utc>> = if is_byod_did_web { 494 Some(Utc::now()) 495 } else { 496 None 497 }; 498 499 let user_insert: Result<(Uuid,), _> = sqlx::query_as( 500 r#"INSERT INTO users ( 501 handle, email, did, password_hash, password_required, 502 preferred_comms_channel, 503 discord_id, telegram_username, signal_number, 504 recovery_token, recovery_token_expires_at, 505 is_admin, deactivated_at 506 ) VALUES ($1, $2, $3, NULL, FALSE, $4::comms_channel, $5, $6, $7, $8, $9, $10, $11) RETURNING id"#, 507 ) 508 .bind(&handle) 509 .bind(&email) 510 .bind(&did) 511 .bind(verification_channel) 512 .bind( 513 input 514 .discord_id 515 .as_deref() 516 .map(|s| s.trim()) 517 .filter(|s| !s.is_empty()), 518 ) 519 .bind( 520 input 521 .telegram_username 522 .as_deref() 523 .map(|s| s.trim()) 524 .filter(|s| !s.is_empty()), 525 ) 526 .bind( 527 input 528 .signal_number 529 .as_deref() 530 .map(|s| s.trim()) 531 .filter(|s| !s.is_empty()), 532 ) 533 .bind(&setup_token_hash) 534 .bind(setup_expires_at) 535 .bind(is_first_user) 536 .bind(deactivated_at) 537 .fetch_one(&mut *tx) 538 .await; 539 540 let user_id = match user_insert { 541 Ok((id,)) => id, 542 Err(e) => { 543 if let Some(db_err) = e.as_database_error() 544 && db_err.code().as_deref() == Some("23505") 545 { 546 let constraint = db_err.constraint().unwrap_or(""); 547 if constraint.contains("handle") { 548 return ( 549 StatusCode::BAD_REQUEST, 550 Json(json!({"error": "HandleNotAvailable", "message": "Handle already taken"})), 551 ) 552 .into_response(); 553 } else if constraint.contains("email") { 554 return ( 555 StatusCode::BAD_REQUEST, 556 Json( 557 json!({"error": "InvalidEmail", "message": "Email already registered"}), 558 ), 559 ) 560 .into_response(); 561 } 562 } 563 error!("Error inserting user: {:?}", e); 564 return ( 565 StatusCode::INTERNAL_SERVER_ERROR, 566 Json(json!({"error": "InternalError"})), 567 ) 568 .into_response(); 569 } 570 }; 571 572 let encrypted_key_bytes = match crate::config::encrypt_key(&secret_key_bytes) { 573 Ok(bytes) => bytes, 574 Err(e) => { 575 error!("Error encrypting signing key: {:?}", e); 576 return ( 577 StatusCode::INTERNAL_SERVER_ERROR, 578 Json(json!({"error": "InternalError"})), 579 ) 580 .into_response(); 581 } 582 }; 583 584 if let Err(e) = sqlx::query!( 585 "INSERT INTO user_keys (user_id, key_bytes, encryption_version, encrypted_at) VALUES ($1, $2, $3, NOW())", 586 user_id, 587 &encrypted_key_bytes[..], 588 crate::config::ENCRYPTION_VERSION 589 ) 590 .execute(&mut *tx) 591 .await 592 { 593 error!("Error inserting user key: {:?}", e); 594 return ( 595 StatusCode::INTERNAL_SERVER_ERROR, 596 Json(json!({"error": "InternalError"})), 597 ) 598 .into_response(); 599 } 600 601 if let Some(key_id) = reserved_key_id 602 && let Err(e) = sqlx::query!( 603 "UPDATE reserved_signing_keys SET used_at = NOW() WHERE id = $1", 604 key_id 605 ) 606 .execute(&mut *tx) 607 .await 608 { 609 error!("Error marking reserved key as used: {:?}", e); 610 return ( 611 StatusCode::INTERNAL_SERVER_ERROR, 612 Json(json!({"error": "InternalError"})), 613 ) 614 .into_response(); 615 } 616 617 let mst = Mst::new(Arc::new(state.block_store.clone())); 618 let mst_root = match mst.persist().await { 619 Ok(c) => c, 620 Err(e) => { 621 error!("Error persisting MST: {:?}", e); 622 return ( 623 StatusCode::INTERNAL_SERVER_ERROR, 624 Json(json!({"error": "InternalError"})), 625 ) 626 .into_response(); 627 } 628 }; 629 let rev = Tid::now(LimitedU32::MIN); 630 let (commit_bytes, _sig) = 631 match create_signed_commit(&did, mst_root, rev.as_ref(), None, &secret_key) { 632 Ok(result) => result, 633 Err(e) => { 634 error!("Error creating genesis commit: {:?}", e); 635 return ( 636 StatusCode::INTERNAL_SERVER_ERROR, 637 Json(json!({"error": "InternalError"})), 638 ) 639 .into_response(); 640 } 641 }; 642 let commit_cid: cid::Cid = match state.block_store.put(&commit_bytes).await { 643 Ok(c) => c, 644 Err(e) => { 645 error!("Error saving genesis commit: {:?}", e); 646 return ( 647 StatusCode::INTERNAL_SERVER_ERROR, 648 Json(json!({"error": "InternalError"})), 649 ) 650 .into_response(); 651 } 652 }; 653 let commit_cid_str = commit_cid.to_string(); 654 let rev_str = rev.as_ref().to_string(); 655 if let Err(e) = sqlx::query!( 656 "INSERT INTO repos (user_id, repo_root_cid, repo_rev) VALUES ($1, $2, $3)", 657 user_id, 658 commit_cid_str, 659 rev_str 660 ) 661 .execute(&mut *tx) 662 .await 663 { 664 error!("Error inserting repo: {:?}", e); 665 return ( 666 StatusCode::INTERNAL_SERVER_ERROR, 667 Json(json!({"error": "InternalError"})), 668 ) 669 .into_response(); 670 } 671 let genesis_block_cids = vec![mst_root.to_bytes(), commit_cid.to_bytes()]; 672 if let Err(e) = sqlx::query!( 673 r#" 674 INSERT INTO user_blocks (user_id, block_cid) 675 SELECT $1, block_cid FROM UNNEST($2::bytea[]) AS t(block_cid) 676 ON CONFLICT (user_id, block_cid) DO NOTHING 677 "#, 678 user_id, 679 &genesis_block_cids 680 ) 681 .execute(&mut *tx) 682 .await 683 { 684 error!("Error inserting user_blocks: {:?}", e); 685 return ( 686 StatusCode::INTERNAL_SERVER_ERROR, 687 Json(json!({"error": "InternalError"})), 688 ) 689 .into_response(); 690 } 691 692 if let Some(ref code) = input.invite_code { 693 let _ = sqlx::query!( 694 "UPDATE invite_codes SET available_uses = available_uses - 1 WHERE code = $1", 695 code 696 ) 697 .execute(&mut *tx) 698 .await; 699 700 let _ = sqlx::query!( 701 "INSERT INTO invite_code_uses (code, used_by_user) VALUES ($1, $2)", 702 code, 703 user_id 704 ) 705 .execute(&mut *tx) 706 .await; 707 } 708 709 if let Err(e) = tx.commit().await { 710 error!("Error committing transaction: {:?}", e); 711 return ( 712 StatusCode::INTERNAL_SERVER_ERROR, 713 Json(json!({"error": "InternalError"})), 714 ) 715 .into_response(); 716 } 717 718 if !is_byod_did_web { 719 if let Err(e) = 720 crate::api::repo::record::sequence_identity_event(&state, &did, Some(&handle)).await 721 { 722 warn!("Failed to sequence identity event for {}: {}", did, e); 723 } 724 if let Err(e) = 725 crate::api::repo::record::sequence_account_event(&state, &did, true, None).await 726 { 727 warn!("Failed to sequence account event for {}: {}", did, e); 728 } 729 let profile_record = serde_json::json!({ 730 "$type": "app.bsky.actor.profile", 731 "displayName": handle 732 }); 733 if let Err(e) = crate::api::repo::record::create_record_internal( 734 &state, 735 &did, 736 "app.bsky.actor.profile", 737 "self", 738 &profile_record, 739 ) 740 .await 741 { 742 warn!("Failed to create default profile for {}: {}", did, e); 743 } 744 } 745 746 let verification_token = crate::auth::verification_token::generate_signup_token( 747 &did, 748 verification_channel, 749 &verification_recipient, 750 ); 751 let formatted_token = 752 crate::auth::verification_token::format_token_for_display(&verification_token); 753 if let Err(e) = crate::comms::enqueue_signup_verification( 754 &state.db, 755 user_id, 756 verification_channel, 757 &verification_recipient, 758 &formatted_token, 759 None, 760 ) 761 .await 762 { 763 warn!("Failed to enqueue signup verification: {:?}", e); 764 } 765 766 info!(did = %did, handle = %handle, "Passkey-only account created, awaiting setup completion"); 767 768 let access_jwt = if byod_auth.is_some() { 769 match crate::auth::token::create_access_token_with_metadata(&did, &secret_key_bytes) { 770 Ok(token_meta) => { 771 let refresh_jti = uuid::Uuid::new_v4().to_string(); 772 let refresh_expires = chrono::Utc::now() + chrono::Duration::hours(24); 773 let no_scope: Option<String> = None; 774 if let Err(e) = sqlx::query!( 775 "INSERT INTO session_tokens (did, access_jti, refresh_jti, access_expires_at, refresh_expires_at, legacy_login, mfa_verified, scope) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", 776 did, 777 token_meta.jti, 778 refresh_jti, 779 token_meta.expires_at, 780 refresh_expires, 781 false, 782 false, 783 no_scope 784 ) 785 .execute(&state.db) 786 .await 787 { 788 warn!(did = %did, "Failed to insert migration session: {:?}", e); 789 } 790 info!(did = %did, "Generated migration access token for BYOD passkey account"); 791 Some(token_meta.token) 792 } 793 Err(e) => { 794 warn!(did = %did, "Failed to generate migration access token: {:?}", e); 795 None 796 } 797 } 798 } else { 799 None 800 }; 801 802 Json(CreatePasskeyAccountResponse { 803 did, 804 handle, 805 setup_token, 806 setup_expires_at, 807 access_jwt, 808 }) 809 .into_response() 810} 811 812#[derive(Deserialize)] 813#[serde(rename_all = "camelCase")] 814pub struct CompletePasskeySetupInput { 815 pub did: String, 816 pub setup_token: String, 817 pub passkey_credential: serde_json::Value, 818 pub passkey_friendly_name: Option<String>, 819} 820 821#[derive(Serialize)] 822#[serde(rename_all = "camelCase")] 823pub struct CompletePasskeySetupResponse { 824 pub did: String, 825 pub handle: String, 826 pub app_password: String, 827 pub app_password_name: String, 828} 829 830pub async fn complete_passkey_setup( 831 State(state): State<AppState>, 832 Json(input): Json<CompletePasskeySetupInput>, 833) -> Response { 834 let user = sqlx::query!( 835 r#"SELECT id, handle, recovery_token, recovery_token_expires_at, password_required 836 FROM users WHERE did = $1"#, 837 input.did 838 ) 839 .fetch_optional(&state.db) 840 .await; 841 842 let user = match user { 843 Ok(Some(u)) => u, 844 Ok(None) => { 845 return ( 846 StatusCode::NOT_FOUND, 847 Json(json!({"error": "AccountNotFound", "message": "Account not found"})), 848 ) 849 .into_response(); 850 } 851 Err(e) => { 852 error!("DB error: {:?}", e); 853 return ( 854 StatusCode::INTERNAL_SERVER_ERROR, 855 Json(json!({"error": "InternalError"})), 856 ) 857 .into_response(); 858 } 859 }; 860 861 if user.password_required { 862 return ( 863 StatusCode::BAD_REQUEST, 864 Json(json!({"error": "InvalidAccount", "message": "This account is not a passkey-only account"})), 865 ) 866 .into_response(); 867 } 868 869 let token_hash = match &user.recovery_token { 870 Some(h) => h, 871 None => { 872 return ( 873 StatusCode::BAD_REQUEST, 874 Json(json!({"error": "SetupExpired", "message": "Setup has already been completed or expired"})), 875 ) 876 .into_response(); 877 } 878 }; 879 880 if let Some(expires_at) = user.recovery_token_expires_at 881 && expires_at < Utc::now() 882 { 883 return ( 884 StatusCode::BAD_REQUEST, 885 Json(json!({"error": "SetupExpired", "message": "Setup token has expired"})), 886 ) 887 .into_response(); 888 } 889 890 if !bcrypt::verify(&input.setup_token, token_hash).unwrap_or(false) { 891 return ( 892 StatusCode::UNAUTHORIZED, 893 Json(json!({"error": "InvalidToken", "message": "Invalid setup token"})), 894 ) 895 .into_response(); 896 } 897 898 let pds_hostname = std::env::var("PDS_HOSTNAME").unwrap_or_else(|_| "localhost".to_string()); 899 let webauthn = match crate::auth::webauthn::WebAuthnConfig::new(&pds_hostname) { 900 Ok(w) => w, 901 Err(e) => { 902 error!("Failed to create WebAuthn config: {:?}", e); 903 return ( 904 StatusCode::INTERNAL_SERVER_ERROR, 905 Json(json!({"error": "InternalError"})), 906 ) 907 .into_response(); 908 } 909 }; 910 911 let reg_state = match crate::auth::webauthn::load_registration_state(&state.db, &input.did) 912 .await 913 { 914 Ok(Some(s)) => s, 915 Ok(None) => { 916 return ( 917 StatusCode::BAD_REQUEST, 918 Json(json!({"error": "NoChallengeInProgress", "message": "Please start passkey registration first"})), 919 ) 920 .into_response(); 921 } 922 Err(e) => { 923 error!("Error loading registration state: {:?}", e); 924 return ( 925 StatusCode::INTERNAL_SERVER_ERROR, 926 Json(json!({"error": "InternalError"})), 927 ) 928 .into_response(); 929 } 930 }; 931 932 let credential: webauthn_rs::prelude::RegisterPublicKeyCredential = 933 match serde_json::from_value(input.passkey_credential) { 934 Ok(c) => c, 935 Err(e) => { 936 warn!("Failed to parse credential: {:?}", e); 937 return ( 938 StatusCode::BAD_REQUEST, 939 Json( 940 json!({"error": "InvalidCredential", "message": "Failed to parse credential"}), 941 ), 942 ) 943 .into_response(); 944 } 945 }; 946 947 let security_key = match webauthn.finish_registration(&credential, &reg_state) { 948 Ok(sk) => sk, 949 Err(e) => { 950 warn!("Passkey registration failed: {:?}", e); 951 return ( 952 StatusCode::BAD_REQUEST, 953 Json(json!({"error": "RegistrationFailed", "message": "Passkey registration failed"})), 954 ) 955 .into_response(); 956 } 957 }; 958 959 if let Err(e) = crate::auth::webauthn::save_passkey( 960 &state.db, 961 &input.did, 962 &security_key, 963 input.passkey_friendly_name.as_deref(), 964 ) 965 .await 966 { 967 error!("Error saving passkey: {:?}", e); 968 return ( 969 StatusCode::INTERNAL_SERVER_ERROR, 970 Json(json!({"error": "InternalError"})), 971 ) 972 .into_response(); 973 } 974 975 let _ = crate::auth::webauthn::delete_registration_state(&state.db, &input.did).await; 976 977 let app_password = generate_app_password(); 978 let app_password_name = "bsky.app".to_string(); 979 let password_hash = match hash(&app_password, DEFAULT_COST) { 980 Ok(h) => h, 981 Err(e) => { 982 error!("Error hashing app password: {:?}", e); 983 return ( 984 StatusCode::INTERNAL_SERVER_ERROR, 985 Json(json!({"error": "InternalError"})), 986 ) 987 .into_response(); 988 } 989 }; 990 991 if let Err(e) = sqlx::query!( 992 "INSERT INTO app_passwords (user_id, name, password_hash, privileged) VALUES ($1, $2, $3, FALSE)", 993 user.id, 994 app_password_name, 995 password_hash 996 ) 997 .execute(&state.db) 998 .await 999 { 1000 error!("Error creating app password: {:?}", e); 1001 return ( 1002 StatusCode::INTERNAL_SERVER_ERROR, 1003 Json(json!({"error": "InternalError"})), 1004 ) 1005 .into_response(); 1006 } 1007 1008 if let Err(e) = sqlx::query!( 1009 "UPDATE users SET recovery_token = NULL, recovery_token_expires_at = NULL WHERE did = $1", 1010 input.did 1011 ) 1012 .execute(&state.db) 1013 .await 1014 { 1015 error!("Error clearing setup token: {:?}", e); 1016 } 1017 1018 info!(did = %input.did, "Passkey-only account setup completed"); 1019 1020 Json(CompletePasskeySetupResponse { 1021 did: input.did, 1022 handle: user.handle, 1023 app_password, 1024 app_password_name, 1025 }) 1026 .into_response() 1027} 1028 1029pub async fn start_passkey_registration_for_setup( 1030 State(state): State<AppState>, 1031 Json(input): Json<StartPasskeyRegistrationInput>, 1032) -> Response { 1033 let user = sqlx::query!( 1034 r#"SELECT handle, recovery_token, recovery_token_expires_at, password_required 1035 FROM users WHERE did = $1"#, 1036 input.did 1037 ) 1038 .fetch_optional(&state.db) 1039 .await; 1040 1041 let user = match user { 1042 Ok(Some(u)) => u, 1043 Ok(None) => { 1044 return ( 1045 StatusCode::NOT_FOUND, 1046 Json(json!({"error": "AccountNotFound"})), 1047 ) 1048 .into_response(); 1049 } 1050 Err(e) => { 1051 error!("DB error: {:?}", e); 1052 return ( 1053 StatusCode::INTERNAL_SERVER_ERROR, 1054 Json(json!({"error": "InternalError"})), 1055 ) 1056 .into_response(); 1057 } 1058 }; 1059 1060 if user.password_required { 1061 return ( 1062 StatusCode::BAD_REQUEST, 1063 Json(json!({"error": "InvalidAccount"})), 1064 ) 1065 .into_response(); 1066 } 1067 1068 let token_hash = match &user.recovery_token { 1069 Some(h) => h, 1070 None => { 1071 return ( 1072 StatusCode::BAD_REQUEST, 1073 Json(json!({"error": "SetupExpired"})), 1074 ) 1075 .into_response(); 1076 } 1077 }; 1078 1079 if let Some(expires_at) = user.recovery_token_expires_at 1080 && expires_at < Utc::now() 1081 { 1082 return ( 1083 StatusCode::BAD_REQUEST, 1084 Json(json!({"error": "SetupExpired"})), 1085 ) 1086 .into_response(); 1087 } 1088 1089 if !bcrypt::verify(&input.setup_token, token_hash).unwrap_or(false) { 1090 return ( 1091 StatusCode::UNAUTHORIZED, 1092 Json(json!({"error": "InvalidToken"})), 1093 ) 1094 .into_response(); 1095 } 1096 1097 let pds_hostname = std::env::var("PDS_HOSTNAME").unwrap_or_else(|_| "localhost".to_string()); 1098 let webauthn = match crate::auth::webauthn::WebAuthnConfig::new(&pds_hostname) { 1099 Ok(w) => w, 1100 Err(e) => { 1101 error!("Failed to create WebAuthn config: {:?}", e); 1102 return ( 1103 StatusCode::INTERNAL_SERVER_ERROR, 1104 Json(json!({"error": "InternalError"})), 1105 ) 1106 .into_response(); 1107 } 1108 }; 1109 1110 let existing_passkeys = crate::auth::webauthn::get_passkeys_for_user(&state.db, &input.did) 1111 .await 1112 .unwrap_or_default(); 1113 1114 let exclude_credentials: Vec<webauthn_rs::prelude::CredentialID> = existing_passkeys 1115 .iter() 1116 .map(|p| webauthn_rs::prelude::CredentialID::from(p.credential_id.clone())) 1117 .collect(); 1118 1119 let display_name = input.friendly_name.as_deref().unwrap_or(&user.handle); 1120 1121 let (ccr, reg_state) = match webauthn.start_registration( 1122 &input.did, 1123 &user.handle, 1124 display_name, 1125 exclude_credentials, 1126 ) { 1127 Ok(result) => result, 1128 Err(e) => { 1129 error!("Failed to start passkey registration: {:?}", e); 1130 return ( 1131 StatusCode::INTERNAL_SERVER_ERROR, 1132 Json(json!({"error": "InternalError"})), 1133 ) 1134 .into_response(); 1135 } 1136 }; 1137 1138 if let Err(e) = 1139 crate::auth::webauthn::save_registration_state(&state.db, &input.did, &reg_state).await 1140 { 1141 error!("Failed to save registration state: {:?}", e); 1142 return ( 1143 StatusCode::INTERNAL_SERVER_ERROR, 1144 Json(json!({"error": "InternalError"})), 1145 ) 1146 .into_response(); 1147 } 1148 1149 let options = serde_json::to_value(&ccr).unwrap_or(json!({})); 1150 Json(json!({"options": options})).into_response() 1151} 1152 1153#[derive(Deserialize)] 1154#[serde(rename_all = "camelCase")] 1155pub struct StartPasskeyRegistrationInput { 1156 pub did: String, 1157 pub setup_token: String, 1158 pub friendly_name: Option<String>, 1159} 1160 1161#[derive(Deserialize)] 1162#[serde(rename_all = "camelCase")] 1163pub struct RequestPasskeyRecoveryInput { 1164 #[serde(alias = "identifier")] 1165 pub email: String, 1166} 1167 1168pub async fn request_passkey_recovery( 1169 State(state): State<AppState>, 1170 headers: HeaderMap, 1171 Json(input): Json<RequestPasskeyRecoveryInput>, 1172) -> Response { 1173 let client_ip = extract_client_ip(&headers); 1174 if !state 1175 .check_rate_limit(RateLimitKind::PasswordReset, &client_ip) 1176 .await 1177 { 1178 return ( 1179 StatusCode::TOO_MANY_REQUESTS, 1180 Json(json!({"error": "RateLimitExceeded"})), 1181 ) 1182 .into_response(); 1183 } 1184 1185 let pds_hostname = std::env::var("PDS_HOSTNAME").unwrap_or_else(|_| "localhost".to_string()); 1186 let identifier = input.email.trim().to_lowercase(); 1187 let identifier = identifier.strip_prefix('@').unwrap_or(&identifier); 1188 let normalized_handle = if identifier.contains('@') || identifier.contains('.') { 1189 identifier.to_string() 1190 } else { 1191 format!("{}.{}", identifier, pds_hostname) 1192 }; 1193 1194 let user = sqlx::query!( 1195 "SELECT id, did, handle, password_required FROM users WHERE LOWER(email) = $1 OR handle = $2", 1196 identifier, 1197 normalized_handle 1198 ) 1199 .fetch_optional(&state.db) 1200 .await; 1201 1202 let user = match user { 1203 Ok(Some(u)) if !u.password_required => u, 1204 _ => { 1205 return Json(json!({"success": true})).into_response(); 1206 } 1207 }; 1208 1209 let recovery_token = generate_setup_token(); 1210 let recovery_token_hash = match hash(&recovery_token, DEFAULT_COST) { 1211 Ok(h) => h, 1212 Err(_) => { 1213 return ( 1214 StatusCode::INTERNAL_SERVER_ERROR, 1215 Json(json!({"error": "InternalError"})), 1216 ) 1217 .into_response(); 1218 } 1219 }; 1220 let expires_at = Utc::now() + Duration::hours(1); 1221 1222 if let Err(e) = sqlx::query!( 1223 "UPDATE users SET recovery_token = $1, recovery_token_expires_at = $2 WHERE did = $3", 1224 recovery_token_hash, 1225 expires_at, 1226 user.did 1227 ) 1228 .execute(&state.db) 1229 .await 1230 { 1231 error!("Error updating recovery token: {:?}", e); 1232 return ( 1233 StatusCode::INTERNAL_SERVER_ERROR, 1234 Json(json!({"error": "InternalError"})), 1235 ) 1236 .into_response(); 1237 } 1238 1239 let hostname = std::env::var("PDS_HOSTNAME").unwrap_or_else(|_| "localhost".to_string()); 1240 let recovery_url = format!( 1241 "https://{}/#/recover-passkey?did={}&token={}", 1242 hostname, 1243 urlencoding::encode(&user.did), 1244 urlencoding::encode(&recovery_token) 1245 ); 1246 1247 let _ = 1248 crate::comms::enqueue_passkey_recovery(&state.db, user.id, &recovery_url, &hostname).await; 1249 1250 info!(did = %user.did, "Passkey recovery requested"); 1251 Json(json!({"success": true})).into_response() 1252} 1253 1254#[derive(Deserialize)] 1255#[serde(rename_all = "camelCase")] 1256pub struct RecoverPasskeyAccountInput { 1257 pub did: String, 1258 pub recovery_token: String, 1259 pub new_password: String, 1260} 1261 1262pub async fn recover_passkey_account( 1263 State(state): State<AppState>, 1264 Json(input): Json<RecoverPasskeyAccountInput>, 1265) -> Response { 1266 if let Err(e) = validate_password(&input.new_password) { 1267 return ( 1268 StatusCode::BAD_REQUEST, 1269 Json(json!({ 1270 "error": "InvalidPassword", 1271 "message": e.to_string() 1272 })), 1273 ) 1274 .into_response(); 1275 } 1276 1277 let user = sqlx::query!( 1278 "SELECT id, did, recovery_token, recovery_token_expires_at FROM users WHERE did = $1", 1279 input.did 1280 ) 1281 .fetch_optional(&state.db) 1282 .await; 1283 1284 let user = match user { 1285 Ok(Some(u)) => u, 1286 _ => { 1287 return ( 1288 StatusCode::NOT_FOUND, 1289 Json(json!({"error": "InvalidRecoveryLink"})), 1290 ) 1291 .into_response(); 1292 } 1293 }; 1294 1295 let token_hash = match &user.recovery_token { 1296 Some(h) => h, 1297 None => { 1298 return ( 1299 StatusCode::BAD_REQUEST, 1300 Json(json!({"error": "InvalidRecoveryLink"})), 1301 ) 1302 .into_response(); 1303 } 1304 }; 1305 1306 if let Some(expires_at) = user.recovery_token_expires_at 1307 && expires_at < Utc::now() 1308 { 1309 return ( 1310 StatusCode::BAD_REQUEST, 1311 Json(json!({"error": "RecoveryLinkExpired"})), 1312 ) 1313 .into_response(); 1314 } 1315 1316 if !bcrypt::verify(&input.recovery_token, token_hash).unwrap_or(false) { 1317 return ( 1318 StatusCode::UNAUTHORIZED, 1319 Json(json!({"error": "InvalidRecoveryLink"})), 1320 ) 1321 .into_response(); 1322 } 1323 1324 let password_hash = match hash(&input.new_password, DEFAULT_COST) { 1325 Ok(h) => h, 1326 Err(_) => { 1327 return ( 1328 StatusCode::INTERNAL_SERVER_ERROR, 1329 Json(json!({"error": "InternalError"})), 1330 ) 1331 .into_response(); 1332 } 1333 }; 1334 1335 if let Err(e) = sqlx::query!( 1336 "UPDATE users SET password_hash = $1, password_required = TRUE, recovery_token = NULL, recovery_token_expires_at = NULL WHERE did = $2", 1337 password_hash, 1338 input.did 1339 ) 1340 .execute(&state.db) 1341 .await 1342 { 1343 error!("Error updating password: {:?}", e); 1344 return ( 1345 StatusCode::INTERNAL_SERVER_ERROR, 1346 Json(json!({"error": "InternalError"})), 1347 ) 1348 .into_response(); 1349 } 1350 1351 let deleted = sqlx::query!("DELETE FROM passkeys WHERE did = $1", input.did) 1352 .execute(&state.db) 1353 .await; 1354 match deleted { 1355 Ok(result) => { 1356 if result.rows_affected() > 0 { 1357 info!(did = %input.did, count = result.rows_affected(), "Deleted lost passkeys during account recovery"); 1358 } 1359 } 1360 Err(e) => { 1361 warn!(did = %input.did, "Failed to delete passkeys during recovery: {:?}", e); 1362 } 1363 } 1364 1365 info!(did = %input.did, "Passkey-only account recovered with temporary password"); 1366 Json(json!({"success": true})).into_response() 1367}