hashtree_cli/server/
blossom.rs

1//! Blossom protocol implementation (BUD-01, BUD-02)
2//!
3//! Implements blob storage endpoints with Nostr-based authentication.
4//! See: https://github.com/hzrd149/blossom
5
6use axum::{
7    body::Body,
8    extract::{Path, Query, State},
9    http::{header, HeaderMap, Response, StatusCode},
10    response::IntoResponse,
11};
12use base64::Engine;
13use hashtree_core::from_hex;
14use serde::{Deserialize, Serialize};
15use sha2::{Digest, Sha256};
16use std::time::{SystemTime, UNIX_EPOCH};
17
18use super::auth::AppState;
19use super::mime::get_mime_type;
20
21/// Blossom authorization event kind (NIP-98 style)
22const BLOSSOM_AUTH_KIND: u16 = 24242;
23
24/// Cache-Control header for immutable content-addressed data (1 year)
25const IMMUTABLE_CACHE_CONTROL: &str = "public, max-age=31536000, immutable";
26
27/// Default maximum upload size in bytes (5 MB)
28pub const DEFAULT_MAX_UPLOAD_SIZE: usize = 5 * 1024 * 1024;
29
30/// Check if a pubkey has write access based on allowed_npubs config
31/// Returns Ok(()) if allowed, Err with JSON error body if denied
32fn check_write_access(state: &AppState, pubkey: &str) -> Result<(), Response<Body>> {
33    // Check if pubkey is in the allowed list (converted from npub to hex)
34    if state.allowed_pubkeys.contains(pubkey) {
35        tracing::debug!("Blossom write allowed for {}... (allowed npub)", &pubkey[..8.min(pubkey.len())]);
36        return Ok(());
37    }
38
39    // Not in allowed list
40    tracing::info!("Blossom write denied for {}... (not in allowed_npubs)", &pubkey[..8.min(pubkey.len())]);
41    Err(Response::builder()
42        .status(StatusCode::FORBIDDEN)
43        .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
44        .header(header::CONTENT_TYPE, "application/json")
45        .body(Body::from(r#"{"error":"Write access denied. Your pubkey is not in the allowed list."}"#))
46        .unwrap())
47}
48
49/// Blob descriptor returned by upload and list endpoints
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct BlobDescriptor {
52    pub url: String,
53    pub sha256: String,
54    pub size: u64,
55    #[serde(rename = "type")]
56    pub mime_type: String,
57    pub uploaded: u64,
58}
59
60/// Query parameters for list endpoint
61#[derive(Debug, Deserialize)]
62pub struct ListQuery {
63    pub since: Option<u64>,
64    pub until: Option<u64>,
65    pub limit: Option<usize>,
66    pub cursor: Option<String>,
67}
68
69/// Parsed Nostr authorization event
70#[derive(Debug)]
71pub struct BlossomAuth {
72    pub pubkey: String,
73    pub kind: u16,
74    pub created_at: u64,
75    pub expiration: Option<u64>,
76    pub action: Option<String>,       // "upload", "delete", "list", "get"
77    pub blob_hashes: Vec<String>,     // x tags
78    pub server: Option<String>,       // server tag
79}
80
81/// Parse and verify Nostr authorization from header
82/// Returns the verified auth or an error response
83pub fn verify_blossom_auth(
84    headers: &HeaderMap,
85    required_action: &str,
86    required_hash: Option<&str>,
87) -> Result<BlossomAuth, (StatusCode, &'static str)> {
88    let auth_header = headers
89        .get(header::AUTHORIZATION)
90        .and_then(|v| v.to_str().ok())
91        .ok_or((StatusCode::UNAUTHORIZED, "Missing Authorization header"))?;
92
93    let nostr_event = auth_header
94        .strip_prefix("Nostr ")
95        .ok_or((StatusCode::UNAUTHORIZED, "Invalid auth scheme, expected 'Nostr'"))?;
96
97    // Decode base64 event
98    let engine = base64::engine::general_purpose::STANDARD;
99    let event_bytes = engine
100        .decode(nostr_event)
101        .map_err(|_| (StatusCode::BAD_REQUEST, "Invalid base64 in auth header"))?;
102
103    let event_json: serde_json::Value = serde_json::from_slice(&event_bytes)
104        .map_err(|_| (StatusCode::BAD_REQUEST, "Invalid JSON in auth event"))?;
105
106    // Extract event fields
107    let kind = event_json["kind"]
108        .as_u64()
109        .ok_or((StatusCode::BAD_REQUEST, "Missing kind in event"))?;
110
111    if kind != BLOSSOM_AUTH_KIND as u64 {
112        return Err((StatusCode::BAD_REQUEST, "Invalid event kind, expected 24242"));
113    }
114
115    let pubkey = event_json["pubkey"]
116        .as_str()
117        .ok_or((StatusCode::BAD_REQUEST, "Missing pubkey in event"))?
118        .to_string();
119
120    let created_at = event_json["created_at"]
121        .as_u64()
122        .ok_or((StatusCode::BAD_REQUEST, "Missing created_at in event"))?;
123
124    let sig = event_json["sig"]
125        .as_str()
126        .ok_or((StatusCode::BAD_REQUEST, "Missing signature in event"))?;
127
128    // Verify signature
129    if !verify_nostr_signature(&event_json, &pubkey, sig) {
130        return Err((StatusCode::UNAUTHORIZED, "Invalid signature"));
131    }
132
133    // Parse tags
134    let tags = event_json["tags"]
135        .as_array()
136        .ok_or((StatusCode::BAD_REQUEST, "Missing tags in event"))?;
137
138    let mut expiration: Option<u64> = None;
139    let mut action: Option<String> = None;
140    let mut blob_hashes: Vec<String> = Vec::new();
141    let mut server: Option<String> = None;
142
143    for tag in tags {
144        let tag_arr = tag.as_array();
145        if let Some(arr) = tag_arr {
146            if arr.len() >= 2 {
147                let tag_name = arr[0].as_str().unwrap_or("");
148                let tag_value = arr[1].as_str().unwrap_or("");
149
150                match tag_name {
151                    "t" => action = Some(tag_value.to_string()),
152                    "x" => blob_hashes.push(tag_value.to_lowercase()),
153                    "expiration" => expiration = tag_value.parse().ok(),
154                    "server" => server = Some(tag_value.to_string()),
155                    _ => {}
156                }
157            }
158        }
159    }
160
161    // Validate expiration
162    let now = SystemTime::now()
163        .duration_since(UNIX_EPOCH)
164        .unwrap()
165        .as_secs();
166
167    if let Some(exp) = expiration {
168        if exp < now {
169            return Err((StatusCode::UNAUTHORIZED, "Authorization expired"));
170        }
171    }
172
173    // Validate created_at is not in the future (with 60s tolerance)
174    if created_at > now + 60 {
175        return Err((StatusCode::BAD_REQUEST, "Event created_at is in the future"));
176    }
177
178    // Validate action matches
179    if let Some(ref act) = action {
180        if act != required_action {
181            return Err((StatusCode::FORBIDDEN, "Action mismatch"));
182        }
183    } else {
184        return Err((StatusCode::BAD_REQUEST, "Missing 't' tag for action"));
185    }
186
187    // Validate hash if required
188    if let Some(hash) = required_hash {
189        if !blob_hashes.is_empty() && !blob_hashes.contains(&hash.to_lowercase()) {
190            return Err((StatusCode::FORBIDDEN, "Blob hash not authorized"));
191        }
192    }
193
194    Ok(BlossomAuth {
195        pubkey,
196        kind: kind as u16,
197        created_at,
198        expiration,
199        action,
200        blob_hashes,
201        server,
202    })
203}
204
205/// Verify Nostr event signature using secp256k1
206fn verify_nostr_signature(event: &serde_json::Value, pubkey: &str, sig: &str) -> bool {
207    use secp256k1::{Message, Secp256k1, schnorr::Signature, XOnlyPublicKey};
208
209    // Compute event ID (sha256 of serialized event)
210    let content = event["content"].as_str().unwrap_or("");
211    let full_serialized = format!(
212        "[0,\"{}\",{},{},{},\"{}\"]",
213        pubkey,
214        event["created_at"],
215        event["kind"],
216        event["tags"],
217        escape_json_string(content),
218    );
219
220    let mut hasher = Sha256::new();
221    hasher.update(full_serialized.as_bytes());
222    let event_id = hasher.finalize();
223
224    // Parse pubkey and signature
225    let pubkey_bytes = match hex::decode(pubkey) {
226        Ok(b) => b,
227        Err(_) => return false,
228    };
229
230    let sig_bytes = match hex::decode(sig) {
231        Ok(b) => b,
232        Err(_) => return false,
233    };
234
235    let secp = Secp256k1::verification_only();
236
237    let xonly_pubkey = match XOnlyPublicKey::from_slice(&pubkey_bytes) {
238        Ok(pk) => pk,
239        Err(_) => return false,
240    };
241
242    let signature = match Signature::from_slice(&sig_bytes) {
243        Ok(s) => s,
244        Err(_) => return false,
245    };
246
247    let message = match Message::from_digest_slice(&event_id) {
248        Ok(m) => m,
249        Err(_) => return false,
250    };
251
252    secp.verify_schnorr(&signature, &message, &xonly_pubkey).is_ok()
253}
254
255/// Escape string for JSON serialization
256fn escape_json_string(s: &str) -> String {
257    let mut result = String::new();
258    for c in s.chars() {
259        match c {
260            '"' => result.push_str("\\\""),
261            '\\' => result.push_str("\\\\"),
262            '\n' => result.push_str("\\n"),
263            '\r' => result.push_str("\\r"),
264            '\t' => result.push_str("\\t"),
265            c if c.is_control() => {
266                result.push_str(&format!("\\u{:04x}", c as u32));
267            }
268            c => result.push(c),
269        }
270    }
271    result
272}
273
274/// CORS preflight handler for all Blossom endpoints
275/// Echoes back Access-Control-Request-Headers to allow any headers
276pub async fn cors_preflight(headers: HeaderMap) -> impl IntoResponse {
277    // Echo back requested headers, or use sensible defaults that cover common Blossom headers
278    let allowed_headers = headers
279        .get(header::ACCESS_CONTROL_REQUEST_HEADERS)
280        .and_then(|v| v.to_str().ok())
281        .unwrap_or("Authorization, Content-Type, X-SHA-256, x-sha-256");
282
283    // Always include common headers in addition to what was requested
284    let full_allowed = format!(
285        "{}, Authorization, Content-Type, X-SHA-256, x-sha-256, Accept, Cache-Control",
286        allowed_headers
287    );
288
289    Response::builder()
290        .status(StatusCode::NO_CONTENT)
291        .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
292        .header(header::ACCESS_CONTROL_ALLOW_METHODS, "GET, HEAD, PUT, DELETE, OPTIONS")
293        .header(header::ACCESS_CONTROL_ALLOW_HEADERS, full_allowed)
294        .header(header::ACCESS_CONTROL_MAX_AGE, "86400")
295        .body(Body::empty())
296        .unwrap()
297}
298
299/// HEAD /<sha256> - Check if blob exists
300pub async fn head_blob(
301    State(state): State<AppState>,
302    Path(id): Path<String>,
303) -> impl IntoResponse {
304    let (hash_part, ext) = parse_hash_and_extension(&id);
305
306    if !is_valid_sha256(&hash_part) {
307        return Response::builder()
308            .status(StatusCode::BAD_REQUEST)
309            .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
310            .header("X-Reason", "Invalid SHA256 hash")
311            .body(Body::empty())
312            .unwrap();
313    }
314
315    let sha256_hex = hash_part.to_lowercase();
316    let sha256_bytes: [u8; 32] = match from_hex(&sha256_hex) {
317        Ok(b) => b,
318        Err(_) => return Response::builder()
319            .status(StatusCode::BAD_REQUEST)
320            .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
321            .header("X-Reason", "Invalid SHA256 format")
322            .body(Body::empty())
323            .unwrap(),
324    };
325
326    // Blossom only serves raw blobs (not merkle tree structures)
327    match state.store.get_blob(&sha256_bytes) {
328        Ok(Some(data)) => {
329            let mime_type = ext
330                .map(|e| get_mime_type(&format!("file{}", e)))
331                .unwrap_or("application/octet-stream");
332
333            Response::builder()
334                .status(StatusCode::OK)
335                .header(header::CONTENT_TYPE, mime_type)
336                .header(header::CONTENT_LENGTH, data.len())
337                .header(header::ACCEPT_RANGES, "bytes")
338                .header(header::CACHE_CONTROL, IMMUTABLE_CACHE_CONTROL)
339                .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
340                .body(Body::empty())
341                .unwrap()
342        }
343        Ok(None) => Response::builder()
344            .status(StatusCode::NOT_FOUND)
345            .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
346            .header("X-Reason", "Blob not found")
347            .body(Body::empty())
348            .unwrap(),
349        Err(_) => Response::builder()
350            .status(StatusCode::INTERNAL_SERVER_ERROR)
351            .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
352            .body(Body::empty())
353            .unwrap(),
354    }
355}
356
357/// PUT /upload - Upload a new blob (BUD-02)
358pub async fn upload_blob(
359    State(state): State<AppState>,
360    headers: HeaderMap,
361    body: axum::body::Bytes,
362) -> impl IntoResponse {
363    // Check size limit first (before auth to save resources)
364    let max_size = state.max_upload_bytes;
365    if body.len() > max_size {
366        return Response::builder()
367            .status(StatusCode::PAYLOAD_TOO_LARGE)
368            .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
369            .header(header::CONTENT_TYPE, "application/json")
370            .body(Body::from(format!(
371                r#"{{"error":"Upload size {} bytes exceeds maximum {} bytes ({} MB)"}}"#,
372                body.len(),
373                max_size,
374                max_size / 1024 / 1024
375            )))
376            .unwrap();
377    }
378
379    // Verify authorization
380    let auth = match verify_blossom_auth(&headers, "upload", None) {
381        Ok(a) => a,
382        Err((status, reason)) => {
383            return Response::builder()
384                .status(status)
385                .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
386                .header("X-Reason", reason)
387                .header(header::CONTENT_TYPE, "application/json")
388                .body(Body::from(format!(r#"{{"error":"{}"}}"#, reason)))
389                .unwrap();
390        }
391    };
392
393    // Get content type from header
394    let content_type = headers
395        .get(header::CONTENT_TYPE)
396        .and_then(|v| v.to_str().ok())
397        .unwrap_or("application/octet-stream")
398        .to_string();
399
400    // Check write access: either in allowed_npubs list OR public_writes is enabled
401    let is_allowed = check_write_access(&state, &auth.pubkey).is_ok();
402    let can_upload = is_allowed || state.public_writes;
403
404    if !can_upload {
405        return Response::builder()
406            .status(StatusCode::FORBIDDEN)
407            .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
408            .header(header::CONTENT_TYPE, "application/json")
409            .body(Body::from(r#"{"error":"Write access denied. Your pubkey is not in the allowed list and public writes are disabled."}"#))
410            .unwrap();
411    }
412
413    // Compute SHA256 of uploaded data
414    let mut hasher = Sha256::new();
415    hasher.update(&body);
416    let sha256_hash: [u8; 32] = hasher.finalize().into();
417    let sha256_hex = hex::encode(sha256_hash);
418
419    // If auth has x tags, verify hash matches
420    if !auth.blob_hashes.is_empty() && !auth.blob_hashes.contains(&sha256_hex) {
421        return Response::builder()
422            .status(StatusCode::FORBIDDEN)
423            .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
424            .header("X-Reason", "Uploaded blob hash does not match authorized hash")
425            .header(header::CONTENT_TYPE, "application/json")
426            .body(Body::from(r#"{"error":"Hash mismatch"}"#))
427            .unwrap();
428    }
429
430    // Convert pubkey hex to bytes
431    let pubkey_bytes = match from_hex(&auth.pubkey) {
432        Ok(b) => b,
433        Err(_) => {
434            return Response::builder()
435                .status(StatusCode::BAD_REQUEST)
436                .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
437                .header("X-Reason", "Invalid pubkey format")
438                .body(Body::empty())
439                .unwrap();
440        }
441    };
442
443    let size = body.len() as u64;
444
445    // Store the blob (only track ownership if user is in allowed list)
446    let store_result = store_blossom_blob(&state, &body, &sha256_hash, &pubkey_bytes, is_allowed);
447
448    match store_result {
449        Ok(()) => {
450            let now = SystemTime::now()
451                .duration_since(UNIX_EPOCH)
452                .unwrap()
453                .as_secs();
454
455            // Determine file extension from content type
456            let ext = mime_to_extension(&content_type);
457
458            let descriptor = BlobDescriptor {
459                url: format!("/{}{}", sha256_hex, ext),
460                sha256: sha256_hex,
461                size,
462                mime_type: content_type,
463                uploaded: now,
464            };
465
466            Response::builder()
467                .status(StatusCode::OK)
468                .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
469                .header(header::CONTENT_TYPE, "application/json")
470                .body(Body::from(serde_json::to_string(&descriptor).unwrap()))
471                .unwrap()
472        }
473        Err(e) => Response::builder()
474            .status(StatusCode::INTERNAL_SERVER_ERROR)
475            .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
476            .header("X-Reason", "Storage error")
477            .header(header::CONTENT_TYPE, "application/json")
478            .body(Body::from(format!(r#"{{"error":"{}"}}"#, e)))
479            .unwrap(),
480    }
481}
482
483/// DELETE /<sha256> - Delete a blob (BUD-02)
484/// Note: Blob is only fully deleted when ALL owners have removed it
485pub async fn delete_blob(
486    State(state): State<AppState>,
487    Path(id): Path<String>,
488    headers: HeaderMap,
489) -> impl IntoResponse {
490    let (hash_part, _) = parse_hash_and_extension(&id);
491
492    if !is_valid_sha256(&hash_part) {
493        return Response::builder()
494            .status(StatusCode::BAD_REQUEST)
495            .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
496            .header("X-Reason", "Invalid SHA256 hash")
497            .body(Body::empty())
498            .unwrap();
499    }
500
501    let sha256_hex = hash_part.to_lowercase();
502
503    // Convert hash to bytes
504    let sha256_bytes = match from_hex(&sha256_hex) {
505        Ok(b) => b,
506        Err(_) => {
507            return Response::builder()
508                .status(StatusCode::BAD_REQUEST)
509                .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
510                .header("X-Reason", "Invalid SHA256 hash format")
511                .body(Body::empty())
512                .unwrap();
513        }
514    };
515
516    // Verify authorization with hash requirement
517    let auth = match verify_blossom_auth(&headers, "delete", Some(&sha256_hex)) {
518        Ok(a) => a,
519        Err((status, reason)) => {
520            return Response::builder()
521                .status(status)
522                .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
523                .header("X-Reason", reason)
524                .body(Body::empty())
525                .unwrap();
526        }
527    };
528
529    // Convert pubkey hex to bytes
530    let pubkey_bytes = match from_hex(&auth.pubkey) {
531        Ok(b) => b,
532        Err(_) => {
533            return Response::builder()
534                .status(StatusCode::BAD_REQUEST)
535                .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
536                .header("X-Reason", "Invalid pubkey format")
537                .body(Body::empty())
538                .unwrap();
539        }
540    };
541
542    // Check ownership - user must be one of the owners (O(1) lookup with composite key)
543    match state.store.is_blob_owner(&sha256_bytes, &pubkey_bytes) {
544        Ok(true) => {
545            // User is an owner, proceed with delete
546        }
547        Ok(false) => {
548            // Check if blob exists at all (for proper error message)
549            match state.store.blob_has_owners(&sha256_bytes) {
550                Ok(true) => {
551                    return Response::builder()
552                        .status(StatusCode::FORBIDDEN)
553                        .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
554                        .header("X-Reason", "Not a blob owner")
555                        .body(Body::empty())
556                        .unwrap();
557                }
558                Ok(false) => {
559                    return Response::builder()
560                        .status(StatusCode::NOT_FOUND)
561                        .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
562                        .header("X-Reason", "Blob not found")
563                        .body(Body::empty())
564                        .unwrap();
565                }
566                Err(_) => {
567                    return Response::builder()
568                        .status(StatusCode::INTERNAL_SERVER_ERROR)
569                        .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
570                        .body(Body::empty())
571                        .unwrap();
572                }
573            }
574        }
575        Err(_) => {
576            return Response::builder()
577                .status(StatusCode::INTERNAL_SERVER_ERROR)
578                .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
579                .body(Body::empty())
580                .unwrap();
581        }
582    }
583
584    // Remove this user's ownership (blob only deleted when no owners remain)
585    match state.store.delete_blossom_blob(&sha256_bytes, &pubkey_bytes) {
586        Ok(fully_deleted) => {
587            // Return 200 OK whether blob was fully deleted or just removed from user's list
588            // The client doesn't need to know if other owners still exist
589            Response::builder()
590                .status(StatusCode::OK)
591                .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
592                .header("X-Blob-Deleted", if fully_deleted { "true" } else { "false" })
593                .body(Body::empty())
594                .unwrap()
595        }
596        Err(_) => Response::builder()
597            .status(StatusCode::INTERNAL_SERVER_ERROR)
598            .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
599            .body(Body::empty())
600            .unwrap(),
601    }
602}
603
604/// GET /list/<pubkey> - List blobs for a pubkey (BUD-02)
605pub async fn list_blobs(
606    State(state): State<AppState>,
607    Path(pubkey): Path<String>,
608    Query(query): Query<ListQuery>,
609    headers: HeaderMap,
610) -> impl IntoResponse {
611    // Validate pubkey format (64 hex chars)
612    if pubkey.len() != 64 || !pubkey.chars().all(|c| c.is_ascii_hexdigit()) {
613        return Response::builder()
614            .status(StatusCode::BAD_REQUEST)
615            .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
616            .header("X-Reason", "Invalid pubkey format")
617            .header(header::CONTENT_TYPE, "application/json")
618            .body(Body::from("[]"))
619            .unwrap();
620    }
621
622    let pubkey_hex = pubkey.to_lowercase();
623    let pubkey_bytes: [u8; 32] = match from_hex(&pubkey_hex) {
624        Ok(b) => b,
625        Err(_) => return Response::builder()
626            .status(StatusCode::BAD_REQUEST)
627            .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
628            .header("X-Reason", "Invalid pubkey format")
629            .header(header::CONTENT_TYPE, "application/json")
630            .body(Body::from("[]"))
631            .unwrap(),
632    };
633
634    // Optional auth verification for list
635    let _auth = verify_blossom_auth(&headers, "list", None).ok();
636
637    // Get blobs for this pubkey
638    match state.store.list_blobs_by_pubkey(&pubkey_bytes) {
639        Ok(blobs) => {
640            // Apply filters
641            let mut filtered: Vec<_> = blobs
642                .into_iter()
643                .filter(|b| {
644                    if let Some(since) = query.since {
645                        if b.uploaded < since {
646                            return false;
647                        }
648                    }
649                    if let Some(until) = query.until {
650                        if b.uploaded > until {
651                            return false;
652                        }
653                    }
654                    true
655                })
656                .collect();
657
658            // Sort by uploaded descending (most recent first)
659            filtered.sort_by(|a, b| b.uploaded.cmp(&a.uploaded));
660
661            // Apply limit
662            let limit = query.limit.unwrap_or(100).min(1000);
663            filtered.truncate(limit);
664
665            Response::builder()
666                .status(StatusCode::OK)
667                .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
668                .header(header::CONTENT_TYPE, "application/json")
669                .body(Body::from(serde_json::to_string(&filtered).unwrap()))
670                .unwrap()
671        }
672        Err(_) => Response::builder()
673            .status(StatusCode::INTERNAL_SERVER_ERROR)
674            .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
675            .header(header::CONTENT_TYPE, "application/json")
676            .body(Body::from("[]"))
677            .unwrap(),
678    }
679}
680
681// Helper functions
682
683fn parse_hash_and_extension(id: &str) -> (&str, Option<&str>) {
684    if let Some(dot_pos) = id.rfind('.') {
685        (&id[..dot_pos], Some(&id[dot_pos..]))
686    } else {
687        (id, None)
688    }
689}
690
691fn is_valid_sha256(s: &str) -> bool {
692    s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit())
693}
694
695fn store_blossom_blob(
696    state: &AppState,
697    data: &[u8],
698    sha256: &[u8; 32],
699    pubkey: &[u8; 32],
700    track_ownership: bool,
701) -> anyhow::Result<()> {
702    // Store as raw blob only - no tree creation needed for blossom
703    // This avoids sync_block_on which can deadlock under load
704    state.store.put_blob(data)?;
705
706    // Only track ownership for social graph members
707    // Non-members can upload (if public_writes=true) but can't delete
708    if track_ownership {
709        state.store.set_blob_owner(sha256, pubkey)?;
710    }
711
712    Ok(())
713}
714
715fn mime_to_extension(mime: &str) -> &'static str {
716    match mime {
717        "image/png" => ".png",
718        "image/jpeg" => ".jpg",
719        "image/gif" => ".gif",
720        "image/webp" => ".webp",
721        "image/svg+xml" => ".svg",
722        "video/mp4" => ".mp4",
723        "video/webm" => ".webm",
724        "audio/mpeg" => ".mp3",
725        "audio/ogg" => ".ogg",
726        "application/pdf" => ".pdf",
727        "text/plain" => ".txt",
728        "text/html" => ".html",
729        "application/json" => ".json",
730        _ => "",
731    }
732}
733
734#[cfg(test)]
735mod tests {
736    use super::*;
737
738    #[test]
739    fn test_is_valid_sha256() {
740        assert!(is_valid_sha256("e2bab35b5296ec2242ded0a01f6d6723a5cd921239280c0a5f0b5589303336b6"));
741        assert!(is_valid_sha256("0000000000000000000000000000000000000000000000000000000000000000"));
742
743        // Too short
744        assert!(!is_valid_sha256("e2bab35b5296ec2242ded0a01f6d6723"));
745        // Too long
746        assert!(!is_valid_sha256("e2bab35b5296ec2242ded0a01f6d6723a5cd921239280c0a5f0b5589303336b6aa"));
747        // Invalid chars
748        assert!(!is_valid_sha256("zzbab35b5296ec2242ded0a01f6d6723a5cd921239280c0a5f0b5589303336b6"));
749        // Empty
750        assert!(!is_valid_sha256(""));
751    }
752
753    #[test]
754    fn test_parse_hash_and_extension() {
755        let (hash, ext) = parse_hash_and_extension("abc123.png");
756        assert_eq!(hash, "abc123");
757        assert_eq!(ext, Some(".png"));
758
759        let (hash2, ext2) = parse_hash_and_extension("abc123");
760        assert_eq!(hash2, "abc123");
761        assert_eq!(ext2, None);
762
763        let (hash3, ext3) = parse_hash_and_extension("abc.123.jpg");
764        assert_eq!(hash3, "abc.123");
765        assert_eq!(ext3, Some(".jpg"));
766    }
767
768    #[test]
769    fn test_mime_to_extension() {
770        assert_eq!(mime_to_extension("image/png"), ".png");
771        assert_eq!(mime_to_extension("image/jpeg"), ".jpg");
772        assert_eq!(mime_to_extension("video/mp4"), ".mp4");
773        assert_eq!(mime_to_extension("application/octet-stream"), "");
774        assert_eq!(mime_to_extension("unknown/type"), "");
775    }
776}