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 user_insert: Result<(uuid::Uuid,), _> = sqlx::query_as(
383 r#"INSERT INTO users (
384 handle, email, did, password_hash,
385 email_confirmation_code, email_confirmation_code_expires_at,
386 preferred_notification_channel,
387 discord_id, telegram_username, signal_number
388 ) VALUES ($1, $2, $3, $4, $5, $6, $7::notification_channel, $8, $9, $10) RETURNING id"#,
389 )
390 .bind(short_handle)
391 .bind(&email)
392 .bind(&did)
393 .bind(&password_hash)
394 .bind(&verification_code)
395 .bind(code_expires_at)
396 .bind(verification_channel)
397 .bind(
398 input
399 .discord_id
400 .as_deref()
401 .map(|s| s.trim())
402 .filter(|s| !s.is_empty()),
403 )
404 .bind(
405 input
406 .telegram_username
407 .as_deref()
408 .map(|s| s.trim())
409 .filter(|s| !s.is_empty()),
410 )
411 .bind(
412 input
413 .signal_number
414 .as_deref()
415 .map(|s| s.trim())
416 .filter(|s| !s.is_empty()),
417 )
418 .fetch_one(&mut *tx)
419 .await;
420 let user_id = match user_insert {
421 Ok((id,)) => id,
422 Err(e) => {
423 if let Some(db_err) = e.as_database_error()
424 && db_err.code().as_deref() == Some("23505") {
425 let constraint = db_err.constraint().unwrap_or("");
426 if constraint.contains("handle") || constraint.contains("users_handle") {
427 return (
428 StatusCode::BAD_REQUEST,
429 Json(json!({
430 "error": "HandleNotAvailable",
431 "message": "Handle already taken"
432 })),
433 )
434 .into_response();
435 } else if constraint.contains("email") || constraint.contains("users_email") {
436 return (
437 StatusCode::BAD_REQUEST,
438 Json(json!({
439 "error": "InvalidEmail",
440 "message": "Email already registered"
441 })),
442 )
443 .into_response();
444 } else if constraint.contains("did") || constraint.contains("users_did") {
445 return (
446 StatusCode::BAD_REQUEST,
447 Json(json!({
448 "error": "AccountAlreadyExists",
449 "message": "An account with this DID already exists"
450 })),
451 )
452 .into_response();
453 }
454 }
455 error!("Error inserting user: {:?}", e);
456 return (
457 StatusCode::INTERNAL_SERVER_ERROR,
458 Json(json!({"error": "InternalError"})),
459 )
460 .into_response();
461 }
462 };
463 let encrypted_key_bytes = match crate::config::encrypt_key(&secret_key_bytes) {
464 Ok(enc) => enc,
465 Err(e) => {
466 error!("Error encrypting user key: {:?}", e);
467 return (
468 StatusCode::INTERNAL_SERVER_ERROR,
469 Json(json!({"error": "InternalError"})),
470 )
471 .into_response();
472 }
473 };
474 let key_insert = sqlx::query!(
475 "INSERT INTO user_keys (user_id, key_bytes, encryption_version, encrypted_at) VALUES ($1, $2, $3, NOW())",
476 user_id,
477 &encrypted_key_bytes[..],
478 crate::config::ENCRYPTION_VERSION
479 )
480 .execute(&mut *tx)
481 .await;
482 if let Err(e) = key_insert {
483 error!("Error inserting user key: {:?}", e);
484 return (
485 StatusCode::INTERNAL_SERVER_ERROR,
486 Json(json!({"error": "InternalError"})),
487 )
488 .into_response();
489 }
490 if let Some(key_id) = reserved_key_id {
491 let mark_used = sqlx::query!(
492 "UPDATE reserved_signing_keys SET used_at = NOW() WHERE id = $1",
493 key_id
494 )
495 .execute(&mut *tx)
496 .await;
497 if let Err(e) = mark_used {
498 error!("Error marking reserved key as used: {:?}", e);
499 return (
500 StatusCode::INTERNAL_SERVER_ERROR,
501 Json(json!({"error": "InternalError"})),
502 )
503 .into_response();
504 }
505 }
506 let mst = Mst::new(Arc::new(state.block_store.clone()));
507 let mst_root = match mst.persist().await {
508 Ok(c) => c,
509 Err(e) => {
510 error!("Error persisting MST: {:?}", e);
511 return (
512 StatusCode::INTERNAL_SERVER_ERROR,
513 Json(json!({"error": "InternalError"})),
514 )
515 .into_response();
516 }
517 };
518 let did_obj = match Did::new(&did) {
519 Ok(d) => d,
520 Err(_) => {
521 return (
522 StatusCode::INTERNAL_SERVER_ERROR,
523 Json(json!({"error": "InternalError", "message": "Invalid DID"})),
524 )
525 .into_response();
526 }
527 };
528 let rev = Tid::now(LimitedU32::MIN);
529 let unsigned_commit = Commit::new_unsigned(did_obj, mst_root, rev, None);
530 let signed_commit = match unsigned_commit.sign(&signing_key) {
531 Ok(c) => c,
532 Err(e) => {
533 error!("Error signing genesis commit: {:?}", e);
534 return (
535 StatusCode::INTERNAL_SERVER_ERROR,
536 Json(json!({"error": "InternalError"})),
537 )
538 .into_response();
539 }
540 };
541 let commit_bytes = match signed_commit.to_cbor() {
542 Ok(b) => b,
543 Err(e) => {
544 error!("Error serializing genesis commit: {:?}", e);
545 return (
546 StatusCode::INTERNAL_SERVER_ERROR,
547 Json(json!({"error": "InternalError"})),
548 )
549 .into_response();
550 }
551 };
552 let commit_cid = match state.block_store.put(&commit_bytes).await {
553 Ok(c) => c,
554 Err(e) => {
555 error!("Error saving genesis commit: {:?}", e);
556 return (
557 StatusCode::INTERNAL_SERVER_ERROR,
558 Json(json!({"error": "InternalError"})),
559 )
560 .into_response();
561 }
562 };
563 let commit_cid_str = commit_cid.to_string();
564 let repo_insert = sqlx::query!(
565 "INSERT INTO repos (user_id, repo_root_cid) VALUES ($1, $2)",
566 user_id,
567 commit_cid_str
568 )
569 .execute(&mut *tx)
570 .await;
571 if let Err(e) = repo_insert {
572 error!("Error initializing repo: {:?}", e);
573 return (
574 StatusCode::INTERNAL_SERVER_ERROR,
575 Json(json!({"error": "InternalError"})),
576 )
577 .into_response();
578 }
579 if let Some(code) = &input.invite_code {
580 let use_insert = sqlx::query!(
581 "INSERT INTO invite_code_uses (code, used_by_user) VALUES ($1, $2)",
582 code,
583 user_id
584 )
585 .execute(&mut *tx)
586 .await;
587 if let Err(e) = use_insert {
588 error!("Error recording invite usage: {:?}", e);
589 return (
590 StatusCode::INTERNAL_SERVER_ERROR,
591 Json(json!({"error": "InternalError"})),
592 )
593 .into_response();
594 }
595 }
596 if let Err(e) = tx.commit().await {
597 error!("Error committing transaction: {:?}", e);
598 return (
599 StatusCode::INTERNAL_SERVER_ERROR,
600 Json(json!({"error": "InternalError"})),
601 )
602 .into_response();
603 }
604 if let Err(e) =
605 crate::api::repo::record::sequence_identity_event(&state, &did, Some(&full_handle)).await
606 {
607 warn!("Failed to sequence identity event for {}: {}", did, e);
608 }
609 if let Err(e) = crate::api::repo::record::sequence_account_event(&state, &did, true, None).await
610 {
611 warn!("Failed to sequence account event for {}: {}", did, e);
612 }
613 let profile_record = json!({
614 "$type": "app.bsky.actor.profile",
615 "displayName": input.handle
616 });
617 if let Err(e) = crate::api::repo::record::create_record_internal(
618 &state,
619 &did,
620 "app.bsky.actor.profile",
621 "self",
622 &profile_record,
623 )
624 .await
625 {
626 warn!("Failed to create default profile for {}: {}", did, e);
627 }
628 if let Err(e) = crate::notifications::enqueue_signup_verification(
629 &state.db,
630 user_id,
631 verification_channel,
632 &verification_recipient,
633 &verification_code,
634 )
635 .await
636 {
637 warn!(
638 "Failed to enqueue signup verification notification: {:?}",
639 e
640 );
641 }
642 (
643 StatusCode::OK,
644 Json(CreateAccountOutput {
645 handle: short_handle.to_string(),
646 did,
647 verification_required: true,
648 verification_channel: verification_channel.to_string(),
649 }),
650 )
651 .into_response()
652}