this repo has no description
1use super::did::verify_did_web;
2use crate::plc::{PlcClient, create_genesis_operation, signing_key_to_did_key};
3use crate::state::{AppState, RateLimitKind};
4use axum::{
5 Json,
6 extract::State,
7 http::{HeaderMap, StatusCode},
8 response::{IntoResponse, Response},
9};
10use bcrypt::{DEFAULT_COST, hash};
11use jacquard::types::{did::Did, integer::LimitedU32, string::Tid};
12use jacquard_repo::{commit::Commit, mst::Mst, storage::BlockStore};
13use k256::{SecretKey, ecdsa::SigningKey};
14use rand::rngs::OsRng;
15use serde::{Deserialize, Serialize};
16use serde_json::json;
17use std::sync::Arc;
18use tracing::{error, info, warn};
19
20fn extract_client_ip(headers: &HeaderMap) -> String {
21 if let Some(forwarded) = headers.get("x-forwarded-for")
22 && let Ok(value) = forwarded.to_str()
23 && let Some(first_ip) = value.split(',').next() {
24 return first_ip.trim().to_string();
25 }
26 if let Some(real_ip) = headers.get("x-real-ip")
27 && let Ok(value) = real_ip.to_str() {
28 return value.trim().to_string();
29 }
30 "unknown".to_string()
31}
32
33#[derive(Deserialize)]
34#[serde(rename_all = "camelCase")]
35pub struct CreateAccountInput {
36 pub handle: String,
37 pub email: Option<String>,
38 pub password: String,
39 pub invite_code: Option<String>,
40 pub did: Option<String>,
41 pub signing_key: Option<String>,
42 pub verification_channel: Option<String>,
43 pub discord_id: Option<String>,
44 pub telegram_username: Option<String>,
45 pub signal_number: Option<String>,
46}
47
48#[derive(Serialize)]
49#[serde(rename_all = "camelCase")]
50pub struct CreateAccountOutput {
51 pub handle: String,
52 pub did: String,
53 pub verification_required: bool,
54 pub verification_channel: String,
55}
56
57pub async fn create_account(
58 State(state): State<AppState>,
59 headers: HeaderMap,
60 Json(input): Json<CreateAccountInput>,
61) -> Response {
62 info!("create_account called");
63 let client_ip = extract_client_ip(&headers);
64 if !state
65 .check_rate_limit(RateLimitKind::AccountCreation, &client_ip)
66 .await
67 {
68 warn!(ip = %client_ip, "Account creation rate limit exceeded");
69 return (
70 StatusCode::TOO_MANY_REQUESTS,
71 Json(json!({
72 "error": "RateLimitExceeded",
73 "message": "Too many account creation attempts. Please try again later."
74 })),
75 )
76 .into_response();
77 }
78 if input.handle.contains('!') || input.handle.contains('@') {
79 return (
80 StatusCode::BAD_REQUEST,
81 Json(
82 json!({"error": "InvalidHandle", "message": "Handle contains invalid characters"}),
83 ),
84 )
85 .into_response();
86 }
87 let email: Option<String> = input
88 .email
89 .as_ref()
90 .map(|e| e.trim().to_string())
91 .filter(|e| !e.is_empty());
92 if let Some(ref email) = email
93 && !crate::api::validation::is_valid_email(email) {
94 return (
95 StatusCode::BAD_REQUEST,
96 Json(json!({"error": "InvalidEmail", "message": "Invalid email format"})),
97 )
98 .into_response();
99 }
100 let verification_channel = input.verification_channel.as_deref().unwrap_or("email");
101 let valid_channels = ["email", "discord", "telegram", "signal"];
102 if !valid_channels.contains(&verification_channel) {
103 return (
104 StatusCode::BAD_REQUEST,
105 Json(json!({"error": "InvalidVerificationChannel", "message": "Invalid verification channel. Must be one of: email, discord, telegram, signal"})),
106 )
107 .into_response();
108 }
109 let verification_recipient = match verification_channel {
110 "email" => match &input.email {
111 Some(email) if !email.trim().is_empty() => email.trim().to_string(),
112 _ => return (
113 StatusCode::BAD_REQUEST,
114 Json(json!({"error": "MissingEmail", "message": "Email is required when using email verification"})),
115 ).into_response(),
116 },
117 "discord" => match &input.discord_id {
118 Some(id) if !id.trim().is_empty() => id.trim().to_string(),
119 _ => return (
120 StatusCode::BAD_REQUEST,
121 Json(json!({"error": "MissingDiscordId", "message": "Discord ID is required when using Discord verification"})),
122 ).into_response(),
123 },
124 "telegram" => match &input.telegram_username {
125 Some(username) if !username.trim().is_empty() => username.trim().to_string(),
126 _ => return (
127 StatusCode::BAD_REQUEST,
128 Json(json!({"error": "MissingTelegramUsername", "message": "Telegram username is required when using Telegram verification"})),
129 ).into_response(),
130 },
131 "signal" => match &input.signal_number {
132 Some(number) if !number.trim().is_empty() => number.trim().to_string(),
133 _ => return (
134 StatusCode::BAD_REQUEST,
135 Json(json!({"error": "MissingSignalNumber", "message": "Signal phone number is required when using Signal verification"})),
136 ).into_response(),
137 },
138 _ => return (
139 StatusCode::BAD_REQUEST,
140 Json(json!({"error": "InvalidVerificationChannel", "message": "Invalid verification channel"})),
141 ).into_response(),
142 };
143 let hostname = std::env::var("PDS_HOSTNAME").unwrap_or_else(|_| "localhost".to_string());
144 let pds_endpoint = format!("https://{}", hostname);
145 let suffix = format!(".{}", hostname);
146 let short_handle = if input.handle.ends_with(&suffix) {
147 input.handle.strip_suffix(&suffix).unwrap_or(&input.handle)
148 } else {
149 &input.handle
150 };
151 let full_handle = format!("{}.{}", short_handle, hostname);
152 let (secret_key_bytes, reserved_key_id): (Vec<u8>, Option<uuid::Uuid>) =
153 if let Some(signing_key_did) = &input.signing_key {
154 let reserved = sqlx::query!(
155 r#"
156 SELECT id, private_key_bytes
157 FROM reserved_signing_keys
158 WHERE public_key_did_key = $1
159 AND used_at IS NULL
160 AND expires_at > NOW()
161 FOR UPDATE
162 "#,
163 signing_key_did
164 )
165 .fetch_optional(&state.db)
166 .await;
167 match reserved {
168 Ok(Some(row)) => (row.private_key_bytes, Some(row.id)),
169 Ok(None) => {
170 return (
171 StatusCode::BAD_REQUEST,
172 Json(json!({
173 "error": "InvalidSigningKey",
174 "message": "Signing key not found, already used, or expired"
175 })),
176 )
177 .into_response();
178 }
179 Err(e) => {
180 error!("Error looking up reserved signing key: {:?}", e);
181 return (
182 StatusCode::INTERNAL_SERVER_ERROR,
183 Json(json!({"error": "InternalError"})),
184 )
185 .into_response();
186 }
187 }
188 } else {
189 let secret_key = SecretKey::random(&mut OsRng);
190 (secret_key.to_bytes().to_vec(), None)
191 };
192 let signing_key = match SigningKey::from_slice(&secret_key_bytes) {
193 Ok(k) => k,
194 Err(e) => {
195 error!("Error creating signing key: {:?}", e);
196 return (
197 StatusCode::INTERNAL_SERVER_ERROR,
198 Json(json!({"error": "InternalError"})),
199 )
200 .into_response();
201 }
202 };
203 let did = if let Some(d) = &input.did {
204 if d.trim().is_empty() {
205 let rotation_key = std::env::var("PLC_ROTATION_KEY")
206 .unwrap_or_else(|_| signing_key_to_did_key(&signing_key));
207 let genesis_result = match create_genesis_operation(
208 &signing_key,
209 &rotation_key,
210 &full_handle,
211 &pds_endpoint,
212 ) {
213 Ok(r) => r,
214 Err(e) => {
215 error!("Error creating PLC genesis operation: {:?}", e);
216 return (
217 StatusCode::INTERNAL_SERVER_ERROR,
218 Json(json!({"error": "InternalError", "message": "Failed to create PLC operation"})),
219 )
220 .into_response();
221 }
222 };
223 let plc_client = PlcClient::new(None);
224 if let Err(e) = plc_client
225 .send_operation(&genesis_result.did, &genesis_result.signed_operation)
226 .await
227 {
228 error!("Failed to submit PLC genesis operation: {:?}", e);
229 return (
230 StatusCode::BAD_GATEWAY,
231 Json(json!({
232 "error": "UpstreamError",
233 "message": format!("Failed to register DID with PLC directory: {}", e)
234 })),
235 )
236 .into_response();
237 }
238 info!(did = %genesis_result.did, "Successfully registered DID with PLC directory");
239 genesis_result.did
240 } else if d.starts_with("did:web:") {
241 if let Err(e) = verify_did_web(d, &hostname, &input.handle).await {
242 return (
243 StatusCode::BAD_REQUEST,
244 Json(json!({"error": "InvalidDid", "message": e})),
245 )
246 .into_response();
247 }
248 d.clone()
249 } else {
250 return (
251 StatusCode::BAD_REQUEST,
252 Json(json!({"error": "InvalidDid", "message": "Only did:web DIDs can be provided; leave empty for did:plc"})),
253 )
254 .into_response();
255 }
256 } else {
257 let rotation_key = std::env::var("PLC_ROTATION_KEY")
258 .unwrap_or_else(|_| signing_key_to_did_key(&signing_key));
259 let genesis_result = match create_genesis_operation(
260 &signing_key,
261 &rotation_key,
262 &full_handle,
263 &pds_endpoint,
264 ) {
265 Ok(r) => r,
266 Err(e) => {
267 error!("Error creating PLC genesis operation: {:?}", e);
268 return (
269 StatusCode::INTERNAL_SERVER_ERROR,
270 Json(json!({"error": "InternalError", "message": "Failed to create PLC operation"})),
271 )
272 .into_response();
273 }
274 };
275 let plc_client = PlcClient::new(None);
276 if let Err(e) = plc_client
277 .send_operation(&genesis_result.did, &genesis_result.signed_operation)
278 .await
279 {
280 error!("Failed to submit PLC genesis operation: {:?}", e);
281 return (
282 StatusCode::BAD_GATEWAY,
283 Json(json!({
284 "error": "UpstreamError",
285 "message": format!("Failed to register DID with PLC directory: {}", e)
286 })),
287 )
288 .into_response();
289 }
290 info!(did = %genesis_result.did, "Successfully registered DID with PLC directory");
291 genesis_result.did
292 };
293 let mut tx = match state.db.begin().await {
294 Ok(tx) => tx,
295 Err(e) => {
296 error!("Error starting transaction: {:?}", e);
297 return (
298 StatusCode::INTERNAL_SERVER_ERROR,
299 Json(json!({"error": "InternalError"})),
300 )
301 .into_response();
302 }
303 };
304 let exists_query = sqlx::query!("SELECT 1 as one FROM users WHERE handle = $1", short_handle)
305 .fetch_optional(&mut *tx)
306 .await;
307 match exists_query {
308 Ok(Some(_)) => {
309 return (
310 StatusCode::BAD_REQUEST,
311 Json(json!({"error": "HandleTaken", "message": "Handle already taken"})),
312 )
313 .into_response();
314 }
315 Err(e) => {
316 error!("Error checking handle: {:?}", e);
317 return (
318 StatusCode::INTERNAL_SERVER_ERROR,
319 Json(json!({"error": "InternalError"})),
320 )
321 .into_response();
322 }
323 Ok(None) => {}
324 }
325 if let Some(code) = &input.invite_code {
326 let invite_query = sqlx::query!(
327 "SELECT available_uses FROM invite_codes WHERE code = $1 FOR UPDATE",
328 code
329 )
330 .fetch_optional(&mut *tx)
331 .await;
332 match invite_query {
333 Ok(Some(row)) => {
334 if row.available_uses <= 0 {
335 return (StatusCode::BAD_REQUEST, Json(json!({"error": "InvalidInviteCode", "message": "Invite code exhausted"}))).into_response();
336 }
337 let update_invite = sqlx::query!(
338 "UPDATE invite_codes SET available_uses = available_uses - 1 WHERE code = $1",
339 code
340 )
341 .execute(&mut *tx)
342 .await;
343 if let Err(e) = update_invite {
344 error!("Error updating invite code: {:?}", e);
345 return (
346 StatusCode::INTERNAL_SERVER_ERROR,
347 Json(json!({"error": "InternalError"})),
348 )
349 .into_response();
350 }
351 }
352 Ok(None) => {
353 return (
354 StatusCode::BAD_REQUEST,
355 Json(json!({"error": "InvalidInviteCode", "message": "Invite code not found"})),
356 )
357 .into_response();
358 }
359 Err(e) => {
360 error!("Error checking invite code: {:?}", e);
361 return (
362 StatusCode::INTERNAL_SERVER_ERROR,
363 Json(json!({"error": "InternalError"})),
364 )
365 .into_response();
366 }
367 }
368 }
369 let password_hash = match hash(&input.password, DEFAULT_COST) {
370 Ok(h) => h,
371 Err(e) => {
372 error!("Error hashing password: {:?}", e);
373 return (
374 StatusCode::INTERNAL_SERVER_ERROR,
375 Json(json!({"error": "InternalError"})),
376 )
377 .into_response();
378 }
379 };
380 let verification_code = format!("{:06}", rand::random::<u32>() % 1_000_000);
381 let code_expires_at = chrono::Utc::now() + chrono::Duration::minutes(30);
382 let is_first_user = sqlx::query_scalar!("SELECT COUNT(*) as count FROM users")
383 .fetch_one(&mut *tx)
384 .await
385 .map(|c| c.unwrap_or(0) == 0)
386 .unwrap_or(false);
387 let user_insert: Result<(uuid::Uuid,), _> = sqlx::query_as(
388 r#"INSERT INTO users (
389 handle, email, did, password_hash,
390 preferred_notification_channel,
391 discord_id, telegram_username, signal_number,
392 is_admin
393 ) VALUES ($1, $2, $3, $4, $5::notification_channel, $6, $7, $8, $9) RETURNING id"#,
394 )
395 .bind(short_handle)
396 .bind(&email)
397 .bind(&did)
398 .bind(&password_hash)
399 .bind(verification_channel)
400 .bind(
401 input
402 .discord_id
403 .as_deref()
404 .map(|s| s.trim())
405 .filter(|s| !s.is_empty()),
406 )
407 .bind(
408 input
409 .telegram_username
410 .as_deref()
411 .map(|s| s.trim())
412 .filter(|s| !s.is_empty()),
413 )
414 .bind(
415 input
416 .signal_number
417 .as_deref()
418 .map(|s| s.trim())
419 .filter(|s| !s.is_empty()),
420 )
421 .bind(is_first_user)
422 .fetch_one(&mut *tx)
423 .await;
424 let user_id = match user_insert {
425 Ok((id,)) => id,
426 Err(e) => {
427 if let Some(db_err) = e.as_database_error()
428 && db_err.code().as_deref() == Some("23505") {
429 let constraint = db_err.constraint().unwrap_or("");
430 if constraint.contains("handle") || constraint.contains("users_handle") {
431 return (
432 StatusCode::BAD_REQUEST,
433 Json(json!({
434 "error": "HandleNotAvailable",
435 "message": "Handle already taken"
436 })),
437 )
438 .into_response();
439 } else if constraint.contains("email") || constraint.contains("users_email") {
440 return (
441 StatusCode::BAD_REQUEST,
442 Json(json!({
443 "error": "InvalidEmail",
444 "message": "Email already registered"
445 })),
446 )
447 .into_response();
448 } else if constraint.contains("did") || constraint.contains("users_did") {
449 return (
450 StatusCode::BAD_REQUEST,
451 Json(json!({
452 "error": "AccountAlreadyExists",
453 "message": "An account with this DID already exists"
454 })),
455 )
456 .into_response();
457 }
458 }
459 error!("Error inserting user: {:?}", e);
460 return (
461 StatusCode::INTERNAL_SERVER_ERROR,
462 Json(json!({"error": "InternalError"})),
463 )
464 .into_response();
465 }
466 };
467
468 if let Err(e) = sqlx::query!(
469 "INSERT INTO channel_verifications (user_id, channel, code, pending_identifier, expires_at) VALUES ($1, 'email', $2, $3, $4)",
470 user_id,
471 verification_code,
472 email,
473 code_expires_at
474 )
475 .execute(&mut *tx)
476 .await {
477 error!("Error inserting verification code: {:?}", e);
478 return (
479 StatusCode::INTERNAL_SERVER_ERROR,
480 Json(json!({"error": "InternalError"})),
481 )
482 .into_response();
483 }
484 let encrypted_key_bytes = match crate::config::encrypt_key(&secret_key_bytes) {
485 Ok(enc) => enc,
486 Err(e) => {
487 error!("Error encrypting user key: {:?}", e);
488 return (
489 StatusCode::INTERNAL_SERVER_ERROR,
490 Json(json!({"error": "InternalError"})),
491 )
492 .into_response();
493 }
494 };
495 let key_insert = sqlx::query!(
496 "INSERT INTO user_keys (user_id, key_bytes, encryption_version, encrypted_at) VALUES ($1, $2, $3, NOW())",
497 user_id,
498 &encrypted_key_bytes[..],
499 crate::config::ENCRYPTION_VERSION
500 )
501 .execute(&mut *tx)
502 .await;
503 if let Err(e) = key_insert {
504 error!("Error inserting user key: {:?}", e);
505 return (
506 StatusCode::INTERNAL_SERVER_ERROR,
507 Json(json!({"error": "InternalError"})),
508 )
509 .into_response();
510 }
511 if let Some(key_id) = reserved_key_id {
512 let mark_used = sqlx::query!(
513 "UPDATE reserved_signing_keys SET used_at = NOW() WHERE id = $1",
514 key_id
515 )
516 .execute(&mut *tx)
517 .await;
518 if let Err(e) = mark_used {
519 error!("Error marking reserved key as used: {:?}", e);
520 return (
521 StatusCode::INTERNAL_SERVER_ERROR,
522 Json(json!({"error": "InternalError"})),
523 )
524 .into_response();
525 }
526 }
527 let mst = Mst::new(Arc::new(state.block_store.clone()));
528 let mst_root = match mst.persist().await {
529 Ok(c) => c,
530 Err(e) => {
531 error!("Error persisting MST: {:?}", e);
532 return (
533 StatusCode::INTERNAL_SERVER_ERROR,
534 Json(json!({"error": "InternalError"})),
535 )
536 .into_response();
537 }
538 };
539 let did_obj = match Did::new(&did) {
540 Ok(d) => d,
541 Err(_) => {
542 return (
543 StatusCode::INTERNAL_SERVER_ERROR,
544 Json(json!({"error": "InternalError", "message": "Invalid DID"})),
545 )
546 .into_response();
547 }
548 };
549 let rev = Tid::now(LimitedU32::MIN);
550 let unsigned_commit = Commit::new_unsigned(did_obj, mst_root, rev, None);
551 let signed_commit = match unsigned_commit.sign(&signing_key) {
552 Ok(c) => c,
553 Err(e) => {
554 error!("Error signing genesis commit: {:?}", e);
555 return (
556 StatusCode::INTERNAL_SERVER_ERROR,
557 Json(json!({"error": "InternalError"})),
558 )
559 .into_response();
560 }
561 };
562 let commit_bytes = match signed_commit.to_cbor() {
563 Ok(b) => b,
564 Err(e) => {
565 error!("Error serializing genesis commit: {:?}", e);
566 return (
567 StatusCode::INTERNAL_SERVER_ERROR,
568 Json(json!({"error": "InternalError"})),
569 )
570 .into_response();
571 }
572 };
573 let commit_cid = match state.block_store.put(&commit_bytes).await {
574 Ok(c) => c,
575 Err(e) => {
576 error!("Error saving genesis commit: {:?}", e);
577 return (
578 StatusCode::INTERNAL_SERVER_ERROR,
579 Json(json!({"error": "InternalError"})),
580 )
581 .into_response();
582 }
583 };
584 let commit_cid_str = commit_cid.to_string();
585 let repo_insert = sqlx::query!(
586 "INSERT INTO repos (user_id, repo_root_cid) VALUES ($1, $2)",
587 user_id,
588 commit_cid_str
589 )
590 .execute(&mut *tx)
591 .await;
592 if let Err(e) = repo_insert {
593 error!("Error initializing repo: {:?}", e);
594 return (
595 StatusCode::INTERNAL_SERVER_ERROR,
596 Json(json!({"error": "InternalError"})),
597 )
598 .into_response();
599 }
600 if let Some(code) = &input.invite_code {
601 let use_insert = sqlx::query!(
602 "INSERT INTO invite_code_uses (code, used_by_user) VALUES ($1, $2)",
603 code,
604 user_id
605 )
606 .execute(&mut *tx)
607 .await;
608 if let Err(e) = use_insert {
609 error!("Error recording invite usage: {:?}", e);
610 return (
611 StatusCode::INTERNAL_SERVER_ERROR,
612 Json(json!({"error": "InternalError"})),
613 )
614 .into_response();
615 }
616 }
617 if let Err(e) = tx.commit().await {
618 error!("Error committing transaction: {:?}", e);
619 return (
620 StatusCode::INTERNAL_SERVER_ERROR,
621 Json(json!({"error": "InternalError"})),
622 )
623 .into_response();
624 }
625 if let Err(e) =
626 crate::api::repo::record::sequence_identity_event(&state, &did, Some(&full_handle)).await
627 {
628 warn!("Failed to sequence identity event for {}: {}", did, e);
629 }
630 if let Err(e) = crate::api::repo::record::sequence_account_event(&state, &did, true, None).await
631 {
632 warn!("Failed to sequence account event for {}: {}", did, e);
633 }
634 let profile_record = json!({
635 "$type": "app.bsky.actor.profile",
636 "displayName": input.handle
637 });
638 if let Err(e) = crate::api::repo::record::create_record_internal(
639 &state,
640 &did,
641 "app.bsky.actor.profile",
642 "self",
643 &profile_record,
644 )
645 .await
646 {
647 warn!("Failed to create default profile for {}: {}", did, e);
648 }
649 if let Err(e) = crate::notifications::enqueue_signup_verification(
650 &state.db,
651 user_id,
652 verification_channel,
653 &verification_recipient,
654 &verification_code,
655 )
656 .await
657 {
658 warn!(
659 "Failed to enqueue signup verification notification: {:?}",
660 e
661 );
662 }
663 (
664 StatusCode::OK,
665 Json(CreateAccountOutput {
666 handle: short_handle.to_string(),
667 did,
668 verification_required: true,
669 verification_channel: verification_channel.to_string(),
670 }),
671 )
672 .into_response()
673}