Skip to main content

hashtree_cli/server/
mod.rs

1mod auth;
2mod blob_read;
3pub mod blossom;
4mod handlers;
5mod ingest_filter;
6mod mime;
7mod nostr_query;
8mod peer_status;
9mod request_paths;
10mod status_metrics;
11#[cfg(feature = "p2p")]
12pub mod stun;
13mod ui;
14pub mod ws_relay;
15
16use crate::nostr_relay::NostrRelay;
17use crate::socialgraph;
18use crate::storage::HashtreeStore;
19use crate::webrtc::WebRTCState;
20use anyhow::Result;
21use axum::{
22    body::Body,
23    extract::DefaultBodyLimit,
24    http::Request,
25    middleware,
26    response::Response,
27    routing::{get, post, put},
28    Router,
29};
30use futures::{future::poll_fn, pin_mut, FutureExt};
31use hyper::body::Incoming;
32use hyper_util::{
33    rt::{TokioExecutor, TokioIo, TokioTimer},
34    server::conn::auto::Builder as HyperBuilder,
35    service::TowerToHyperService,
36};
37use socket2::{SockRef, TcpKeepalive};
38use std::collections::{HashMap, HashSet};
39use std::convert::Infallible;
40use std::future;
41use std::io;
42use std::net::SocketAddr;
43use std::sync::{Arc, OnceLock, RwLock};
44use std::time::Duration;
45use tokio::sync::watch;
46use tower::{Service, ServiceExt as _};
47use tower_http::cors::CorsLayer;
48use tracing::{debug, error, trace};
49
50pub use auth::{new_lookup_cache, AppState, AuthCredentials, CachedTreeRootEntry};
51
52static VIRTUAL_TREE_HOSTS: OnceLock<RwLock<HashMap<String, String>>> = OnceLock::new();
53const DEFAULT_OPTIMISTIC_UPLOAD_QUEUE_BYTES: usize = 512 * 1024 * 1024;
54
55#[cfg(not(test))]
56const HTTP1_HEADER_READ_TIMEOUT: Duration = Duration::from_secs(30);
57#[cfg(test)]
58const HTTP1_HEADER_READ_TIMEOUT: Duration = Duration::from_millis(200);
59const HTTP2_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(30);
60const HTTP2_KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(10);
61const TCP_KEEPALIVE_TIME: Duration = Duration::from_secs(60);
62const TCP_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
63
64fn virtual_tree_hosts() -> &'static RwLock<HashMap<String, String>> {
65    VIRTUAL_TREE_HOSTS.get_or_init(|| RwLock::new(HashMap::new()))
66}
67
68fn normalize_virtual_tree_host(host: &str) -> Option<String> {
69    let trimmed = host.trim().trim_end_matches('.').to_ascii_lowercase();
70    if trimmed.is_empty() {
71        return None;
72    }
73
74    if let Some(stripped) = trimmed
75        .strip_prefix('[')
76        .and_then(|value| value.split_once(']'))
77    {
78        let host_only = stripped.0.trim();
79        if host_only.is_empty() {
80            return None;
81        }
82        return Some(host_only.to_string());
83    }
84
85    if let Some((host_only, port)) = trimmed.rsplit_once(':') {
86        if !host_only.is_empty() && !port.is_empty() && port.chars().all(|ch| ch.is_ascii_digit()) {
87            return Some(host_only.to_string());
88        }
89    }
90
91    Some(trimmed)
92}
93
94pub fn register_virtual_tree_host(host: &str, internal_root: &str) {
95    let Some(normalized_host) = normalize_virtual_tree_host(host) else {
96        return;
97    };
98
99    let normalized_root = internal_root.trim().trim_end_matches('/');
100    if normalized_root.is_empty() {
101        return;
102    }
103
104    if let Ok(mut hosts) = virtual_tree_hosts().write() {
105        hosts.insert(normalized_host, normalized_root.to_string());
106    }
107}
108
109pub fn resolve_virtual_tree_host(host: &str) -> Option<String> {
110    let normalized_host = normalize_virtual_tree_host(host)?;
111    virtual_tree_hosts()
112        .read()
113        .ok()
114        .and_then(|hosts| hosts.get(&normalized_host).cloned())
115}
116
117#[cfg(test)]
118pub fn clear_virtual_tree_hosts_for_test() {
119    if let Ok(mut hosts) = virtual_tree_hosts().write() {
120        hosts.clear();
121    }
122}
123
124pub struct HashtreeServer {
125    state: AppState,
126    addr: String,
127    extra_routes: Option<Router<AppState>>,
128    cors: Option<CorsLayer>,
129}
130
131impl HashtreeServer {
132    pub fn new(store: Arc<HashtreeStore>, addr: String) -> Self {
133        Self {
134            state: AppState {
135                store,
136                auth: None,
137                daemon_started_at: current_unix_secs(),
138                peer_mode: crate::config::ServerMode::Normal,
139                hash_get_enabled: true,
140                http_webrtc_fetch: true,
141                webrtc_peers: None,
142                fips_transport: None,
143                fetch_from_fips_peers: true,
144                ws_relay: Arc::new(auth::WsRelayState::new()),
145                max_upload_bytes: 5 * 1024 * 1024, // 5 MB default
146                public_writes: true,               // Allow anyone with valid Nostr auth by default
147                require_random_untrusted_ingest: true,
148                optimistic_blossom_uploads: false,
149                optimistic_upload_queue_bytes: DEFAULT_OPTIMISTIC_UPLOAD_QUEUE_BYTES,
150                optimistic_upload_queue: Arc::new(tokio::sync::Semaphore::new(
151                    DEFAULT_OPTIMISTIC_UPLOAD_QUEUE_BYTES,
152                )),
153                allowed_pubkeys: HashSet::new(), // No pubkeys allowed by default (use public_writes)
154                upstream_blossom: Vec::new(),
155                social_graph: None,
156                social_graph_store: None,
157                social_graph_root: None,
158                socialgraph_snapshot_public: false,
159                nostr_relay: None,
160                nostr_relay_urls: Vec::new(),
161                tree_root_cache: Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
162                inflight_blob_fetches: Arc::new(tokio::sync::Mutex::new(
163                    std::collections::HashMap::new(),
164                )),
165                inflight_blob_reads: Arc::new(tokio::sync::Mutex::new(
166                    std::collections::HashMap::new(),
167                )),
168                blob_cache: Arc::new(crate::blob_cache::BlobCache::from_env()),
169                directory_listing_cache: Arc::new(std::sync::Mutex::new(new_lookup_cache())),
170                resolved_path_cache: Arc::new(std::sync::Mutex::new(new_lookup_cache())),
171                thumbnail_path_cache: Arc::new(std::sync::Mutex::new(new_lookup_cache())),
172                cid_size_cache: Arc::new(std::sync::Mutex::new(new_lookup_cache())),
173            },
174            addr,
175            extra_routes: None,
176            cors: None,
177        }
178    }
179
180    /// Set maximum upload size for Blossom uploads
181    pub fn with_max_upload_bytes(mut self, bytes: usize) -> Self {
182        self.state.max_upload_bytes = bytes;
183        self
184    }
185
186    /// Set whether to allow public writes (anyone with valid Nostr auth)
187    /// When false, only social graph members can write
188    pub fn with_public_writes(mut self, public: bool) -> Self {
189        self.state.public_writes = public;
190        self
191    }
192
193    pub fn with_require_random_untrusted_ingest(mut self, require: bool) -> Self {
194        self.state.require_random_untrusted_ingest = require;
195        self
196    }
197
198    pub fn with_optimistic_blossom_uploads(mut self, enabled: bool) -> Self {
199        self.state.optimistic_blossom_uploads = enabled;
200        self
201    }
202
203    pub fn with_server_mode(mut self, mode: crate::config::ServerMode) -> Self {
204        self.state.peer_mode = mode;
205        self
206    }
207
208    pub fn with_hash_get_enabled(mut self, enabled: bool) -> Self {
209        self.state.hash_get_enabled = enabled;
210        self
211    }
212
213    pub fn with_http_webrtc_fetch(mut self, enabled: bool) -> Self {
214        self.state.http_webrtc_fetch = enabled;
215        self
216    }
217
218    pub fn with_fetch_from_fips_peers(mut self, enabled: bool) -> Self {
219        self.state.fetch_from_fips_peers = enabled;
220        self
221    }
222
223    pub fn with_fips_transport(
224        mut self,
225        transport: Arc<crate::fips_transport::DaemonFipsTransport>,
226    ) -> Self {
227        self.state.fips_transport = Some(transport);
228        self
229    }
230
231    /// Set WebRTC state for P2P peer queries
232    pub fn with_webrtc_peers(mut self, webrtc_state: Arc<WebRTCState>) -> Self {
233        self.state.webrtc_peers = Some(webrtc_state);
234        self
235    }
236
237    pub fn with_auth(mut self, username: String, password: String) -> Self {
238        self.state.auth = Some(AuthCredentials { username, password });
239        self
240    }
241
242    /// Set allowed pubkeys for blossom write access (hex format)
243    pub fn with_allowed_pubkeys(mut self, pubkeys: HashSet<String>) -> Self {
244        self.state.allowed_pubkeys = pubkeys;
245        self
246    }
247
248    /// Set upstream Blossom servers for cascade fetching
249    pub fn with_upstream_blossom(mut self, servers: Vec<String>) -> Self {
250        self.state.upstream_blossom = servers;
251        self
252    }
253
254    /// Set social graph access control
255    pub fn with_social_graph(mut self, sg: Arc<socialgraph::SocialGraphAccessControl>) -> Self {
256        self.state.social_graph = Some(sg);
257        self
258    }
259
260    /// Configure social graph snapshot export (store handle + root)
261    pub fn with_socialgraph_snapshot(
262        mut self,
263        store: Arc<dyn socialgraph::SocialGraphBackend>,
264        root: [u8; 32],
265        public: bool,
266    ) -> Self {
267        self.state.social_graph_store = Some(store);
268        self.state.social_graph_root = Some(root);
269        self.state.socialgraph_snapshot_public = public;
270        self
271    }
272
273    /// Set Nostr relay state (shared for /ws and WebRTC)
274    pub fn with_nostr_relay(mut self, relay: Arc<NostrRelay>) -> Self {
275        self.state.nostr_relay = Some(relay);
276        self
277    }
278
279    /// Set active upstream Nostr relays for HTTP resolver operations.
280    pub fn with_nostr_relay_urls(mut self, relays: Vec<String>) -> Self {
281        self.state.nostr_relay_urls = relays;
282        self
283    }
284
285    /// Merge extra routes into the daemon router (e.g. Tauri embeds /nip07).
286    pub fn with_extra_routes(mut self, routes: Router<AppState>) -> Self {
287        self.extra_routes = Some(routes);
288        self
289    }
290
291    /// Apply a CORS layer to all routes (used by embedded clients like Tauri).
292    pub fn with_cors(mut self, cors: CorsLayer) -> Self {
293        self.cors = Some(cors);
294        self
295    }
296
297    pub async fn run(self) -> Result<()> {
298        let listener = tokio::net::TcpListener::bind(&self.addr).await?;
299        let _ = self.run_with_listener(listener).await?;
300        Ok(())
301    }
302
303    pub async fn run_with_listener(self, listener: tokio::net::TcpListener) -> Result<u16> {
304        self.run_with_listener_until(listener, future::pending::<()>())
305            .await
306    }
307
308    pub async fn run_with_listener_until<F>(
309        self,
310        listener: tokio::net::TcpListener,
311        shutdown: F,
312    ) -> Result<u16>
313    where
314        F: std::future::Future<Output = ()> + Send + 'static,
315    {
316        let local_addr = listener.local_addr()?;
317
318        // Public endpoints (no auth required)
319        // Note: /:id serves both CID and blossom SHA256 hash lookups
320        // The handler differentiates based on hash format (64 char hex = blossom)
321        let state = self.state.clone();
322        let public_routes = Router::new()
323            .route("/", get(handlers::serve_root_or_virtual_host))
324            .route("/ws", get(ws_relay::ws_data))
325            .route("/ws/", get(ws_relay::ws_data))
326            .route(
327                "/htree/test",
328                get(handlers::htree_test).head(handlers::htree_test),
329            )
330            // /htree/nhash1...[/path] - content-addressed (immutable)
331            .route("/htree/nhash1:nhash", get(handlers::htree_nhash))
332            .route("/htree/nhash1:nhash/", get(handlers::htree_nhash))
333            .route("/htree/nhash1:nhash/*path", get(handlers::htree_nhash_path))
334            // /htree/npub1.../tree[/path] - mutable (resolver-backed)
335            .route("/htree/npub1:npub/:treename", get(handlers::htree_npub))
336            .route("/htree/npub1:npub/:treename/", get(handlers::htree_npub))
337            .route(
338                "/htree/npub1:npub/:treename/*path",
339                get(handlers::htree_npub_path),
340            )
341            // Nostr resolver endpoints - resolve npub/treename to content
342            .route("/n/:pubkey/:treename", get(handlers::resolve_and_serve))
343            // Direct npub route (clients should parse nhash and request by hex hash)
344            .route("/npub1:rest", get(handlers::serve_npub))
345            // Blossom endpoints (BUD-01, BUD-02)
346            .route(
347                "/:id",
348                get(handlers::serve_content_or_blob)
349                    .head(blossom::head_blob)
350                    .delete(blossom::delete_blob)
351                    .options(blossom::cors_preflight),
352            )
353            .route(
354                "/upload",
355                put(blossom::upload_blob).options(blossom::cors_preflight),
356            )
357            .route(
358                "/upload/batch",
359                post(blossom::upload_blob_batch).options(blossom::cors_preflight),
360            )
361            .route(
362                "/list/:pubkey",
363                get(blossom::list_blobs).options(blossom::cors_preflight),
364            )
365            // Hashtree API endpoints
366            .route("/health", get(handlers::health_check))
367            .route("/api/pins", get(handlers::list_pins))
368            .route("/api/stats", get(handlers::storage_stats))
369            .route("/api/peers", get(handlers::webrtc_peers))
370            .route("/api/status", get(handlers::daemon_status))
371            .route("/api/p2p/signal", post(handlers::p2p_signal))
372            .route("/api/socialgraph", get(handlers::socialgraph_stats))
373            .route(
374                "/api/socialgraph/snapshot",
375                get(handlers::socialgraph_snapshot),
376            )
377            .route(
378                "/api/socialgraph/distance/:pubkey",
379                get(handlers::follow_distance),
380            )
381            // Resolver API endpoints
382            .route(
383                "/api/resolve/:pubkey/:treename",
384                get(handlers::resolve_to_hash),
385            )
386            .route(
387                "/api/nostr/resolve/:pubkey/:treename",
388                get(handlers::resolve_to_hash),
389            )
390            .route("/api/nostr/profile/:pubkey", get(handlers::nostr_profile))
391            .route("/api/cache-tree-root", post(handlers::cache_tree_root))
392            .route(
393                "/api/clear-tree-root-cache",
394                post(handlers::clear_tree_root_cache),
395            )
396            .route("/api/trees/:pubkey", get(handlers::list_trees))
397            .fallback(get(handlers::serve_virtual_host_fallback))
398            .with_state(state.clone());
399
400        // Protected endpoints (require auth if enabled)
401        let protected_routes = Router::new()
402            .route("/upload", post(handlers::upload_file))
403            .route("/api/pin/:cid", post(handlers::pin_cid))
404            .route("/api/unpin/:cid", post(handlers::unpin_cid))
405            .route("/api/gc", post(handlers::garbage_collect))
406            .layer(middleware::from_fn_with_state(
407                state.clone(),
408                auth::auth_middleware,
409            ))
410            .with_state(state.clone());
411
412        let mut app = public_routes
413            .merge(protected_routes)
414            .layer(DefaultBodyLimit::max(10 * 1024 * 1024 * 1024)) // 10GB limit
415            .layer(middleware::from_fn(status_metrics::record_http_status));
416
417        if let Some(extra) = self.extra_routes {
418            app = app.merge(extra.with_state(state));
419        }
420
421        if let Some(cors) = self.cors {
422            app = app.layer(cors);
423        }
424
425        let make_service = app.into_make_service_with_connect_info::<std::net::SocketAddr>();
426        serve_with_connection_limits(listener, make_service, shutdown).await?;
427
428        Ok(local_addr.port())
429    }
430
431    pub fn addr(&self) -> &str {
432        &self.addr
433    }
434}
435
436async fn serve_with_connection_limits<M, S, F>(
437    listener: tokio::net::TcpListener,
438    mut make_service: M,
439    shutdown: F,
440) -> io::Result<()>
441where
442    M: Service<SocketAddr, Error = Infallible, Response = S> + Send + 'static,
443    M::Future: Send,
444    S: Service<Request<Body>, Response = Response, Error = Infallible> + Clone + Send + 'static,
445    S::Future: Send,
446    F: std::future::Future<Output = ()> + Send + 'static,
447{
448    let (signal_tx, signal_rx) = watch::channel(());
449    let signal_tx = Arc::new(signal_tx);
450    tokio::spawn(async move {
451        shutdown.await;
452        trace!("received graceful shutdown signal; stopping daemon listener");
453        drop(signal_rx);
454    });
455
456    let (close_tx, close_rx) = watch::channel(());
457
458    loop {
459        let (tcp_stream, remote_addr) = tokio::select! {
460            accepted = accept_tcp(&listener) => {
461                match accepted {
462                    Some(connection) => connection,
463                    None => continue,
464                }
465            }
466            _ = signal_tx.closed() => {
467                trace!("shutdown signal received; no longer accepting daemon connections");
468                break;
469            }
470        };
471
472        configure_tcp_stream(&tcp_stream);
473        let tcp_stream = TokioIo::new(tcp_stream);
474
475        poll_fn(|cx| make_service.poll_ready(cx))
476            .await
477            .unwrap_or_else(|err| match err {});
478
479        let tower_service = make_service
480            .call(remote_addr)
481            .await
482            .unwrap_or_else(|err| match err {})
483            .map_request(|req: Request<Incoming>| req.map(Body::new));
484        let hyper_service = TowerToHyperService::new(tower_service);
485
486        let signal_tx = Arc::clone(&signal_tx);
487        let close_rx = close_rx.clone();
488
489        tokio::spawn(async move {
490            let mut builder = HyperBuilder::new(TokioExecutor::new());
491            builder
492                .http1()
493                .timer(TokioTimer::new())
494                .header_read_timeout(HTTP1_HEADER_READ_TIMEOUT);
495            builder
496                .http2()
497                .timer(TokioTimer::new())
498                .keep_alive_interval(Some(HTTP2_KEEPALIVE_INTERVAL))
499                .keep_alive_timeout(HTTP2_KEEPALIVE_TIMEOUT);
500
501            let conn = builder.serve_connection_with_upgrades(tcp_stream, hyper_service);
502            pin_mut!(conn);
503
504            let signal_closed = signal_tx.closed().fuse();
505            pin_mut!(signal_closed);
506
507            loop {
508                tokio::select! {
509                    result = conn.as_mut() => {
510                        if let Err(err) = result {
511                            trace!("daemon connection closed with error: {err:#}");
512                        }
513                        break;
514                    }
515                    _ = &mut signal_closed => {
516                        trace!("shutdown signal received by connection task");
517                        conn.as_mut().graceful_shutdown();
518                    }
519                }
520            }
521
522            drop(close_rx);
523        });
524    }
525
526    drop(close_rx);
527    drop(listener);
528    close_tx.closed().await;
529
530    Ok(())
531}
532
533fn configure_tcp_stream(tcp_stream: &tokio::net::TcpStream) {
534    if let Err(err) = tcp_stream.set_nodelay(true) {
535        debug!("failed to set TCP_NODELAY on daemon connection: {err:#}");
536    }
537
538    let socket = SockRef::from(tcp_stream);
539    if let Err(err) = socket.set_tcp_keepalive(
540        &TcpKeepalive::new()
541            .with_time(TCP_KEEPALIVE_TIME)
542            .with_interval(TCP_KEEPALIVE_INTERVAL),
543    ) {
544        debug!("failed to set TCP keepalive on daemon connection: {err:#}");
545    }
546}
547
548async fn accept_tcp(
549    listener: &tokio::net::TcpListener,
550) -> Option<(tokio::net::TcpStream, SocketAddr)> {
551    match listener.accept().await {
552        Ok(connection) => Some(connection),
553        Err(err) => {
554            if is_connection_error(&err) {
555                return None;
556            }
557            error!("daemon accept error: {err}");
558            tokio::time::sleep(Duration::from_secs(1)).await;
559            None
560        }
561    }
562}
563
564fn is_connection_error(err: &io::Error) -> bool {
565    matches!(
566        err.kind(),
567        io::ErrorKind::ConnectionRefused
568            | io::ErrorKind::ConnectionAborted
569            | io::ErrorKind::ConnectionReset
570    )
571}
572
573fn current_unix_secs() -> u64 {
574    std::time::SystemTime::now()
575        .duration_since(std::time::UNIX_EPOCH)
576        .unwrap_or(std::time::Duration::ZERO)
577        .as_secs()
578}
579
580#[cfg(test)]
581mod tests {
582    use super::*;
583    use crate::nostr_relay::{NostrRelay, NostrRelayConfig};
584    use crate::storage::HashtreeStore;
585    use hashtree_core::{from_hex, nhash_encode, DirEntry, HashTree, HashTreeConfig, LinkType};
586    use nostr::{EventBuilder, Keys, Kind, Timestamp};
587    use serde_json::json;
588    use tempfile::TempDir;
589
590    #[tokio::test]
591    async fn test_server_serve_file() -> Result<()> {
592        let temp_dir = TempDir::new()?;
593        let store = Arc::new(HashtreeStore::new(temp_dir.path().join("db"))?);
594
595        // Create and upload a test file
596        let test_file = temp_dir.path().join("test.txt");
597        std::fs::write(&test_file, b"Hello, Hashtree!")?;
598
599        let cid = store.upload_file(&test_file)?;
600        let hash = from_hex(&cid)?;
601
602        // Verify we can get it
603        let content = store.get_file(&hash)?;
604        assert!(content.is_some());
605        assert_eq!(content.unwrap(), b"Hello, Hashtree!");
606
607        Ok(())
608    }
609
610    #[tokio::test]
611    async fn test_server_list_pins() -> Result<()> {
612        let temp_dir = TempDir::new()?;
613        let store = Arc::new(HashtreeStore::new(temp_dir.path().join("db"))?);
614
615        let test_file = temp_dir.path().join("test.txt");
616        std::fs::write(&test_file, b"Test")?;
617
618        let cid = store.upload_file(&test_file)?;
619        let hash = from_hex(&cid)?;
620
621        let pins = store.list_pins_raw()?;
622        assert_eq!(pins.len(), 1);
623        assert_eq!(pins[0], hash);
624
625        Ok(())
626    }
627
628    async fn spawn_test_server(
629        store: Arc<HashtreeStore>,
630    ) -> Result<(u16, tokio::task::JoinHandle<Result<()>>)> {
631        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
632        let port = listener.local_addr()?.port();
633        let server = HashtreeServer::new(store, "127.0.0.1:0".to_string());
634        let handle =
635            tokio::spawn(async move { server.run_with_listener(listener).await.map(|_| ()) });
636        Ok((port, handle))
637    }
638
639    async fn spawn_test_server_with_nostr_relay(
640        store: Arc<HashtreeStore>,
641        relay: Arc<NostrRelay>,
642    ) -> Result<(u16, tokio::task::JoinHandle<Result<()>>)> {
643        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
644        let port = listener.local_addr()?.port();
645        let server = HashtreeServer::new(store, "127.0.0.1:0".to_string()).with_nostr_relay(relay);
646        let handle =
647            tokio::spawn(async move { server.run_with_listener(listener).await.map(|_| ()) });
648        Ok((port, handle))
649    }
650
651    #[tokio::test]
652    async fn virtual_tree_hosts_serve_root_assets_and_spa_fallbacks() -> Result<()> {
653        clear_virtual_tree_hosts_for_test();
654
655        let temp_dir = TempDir::new()?;
656        let store = Arc::new(HashtreeStore::new(temp_dir.path().join("db"))?);
657        let tree = HashTree::new(HashTreeConfig::new(store.store_arc()).public());
658
659        let (index_cid, _) = tree
660            .put(b"<!doctype html><title>Virtual host ok</title>")
661            .await?;
662        let (favicon_cid, _) = tree.put(b"ico").await?;
663        let (main_js_cid, _) = tree.put(b"console.log('ok');").await?;
664        let assets_dir = tree
665            .put_directory(vec![
666                DirEntry::from_cid("main.js", &main_js_cid).with_link_type(LinkType::File)
667            ])
668            .await?;
669        let root_cid = tree
670            .put_directory(vec![
671                DirEntry::from_cid("index.html", &index_cid).with_link_type(LinkType::File),
672                DirEntry::from_cid("favicon.ico", &favicon_cid).with_link_type(LinkType::File),
673                DirEntry::from_cid("assets", &assets_dir).with_link_type(LinkType::Dir),
674            ])
675            .await?;
676        let nhash = nhash_encode(&root_cid.hash)?;
677        let host = "tree-test.htree.localhost";
678        register_virtual_tree_host(host, &format!("/htree/{nhash}"));
679
680        let (port, handle) = spawn_test_server(store).await?;
681        let base_url = format!("http://127.0.0.1:{port}");
682        let host_header = format!("{host}:{port}");
683        let client = reqwest::Client::new();
684
685        let root_response = client
686            .get(format!("{base_url}/"))
687            .header("Host", &host_header)
688            .header("Accept", "text/html")
689            .send()
690            .await?;
691        assert_eq!(root_response.status(), reqwest::StatusCode::OK);
692        assert_eq!(
693            root_response.bytes().await?.as_ref(),
694            b"<!doctype html><title>Virtual host ok</title>"
695        );
696
697        let favicon_response = client
698            .get(format!("{base_url}/favicon.ico"))
699            .header("Host", &host_header)
700            .send()
701            .await?;
702        assert_eq!(favicon_response.status(), reqwest::StatusCode::OK);
703        assert_eq!(favicon_response.bytes().await?.as_ref(), b"ico");
704
705        let js_response = client
706            .get(format!("{base_url}/assets/main.js"))
707            .header("Host", &host_header)
708            .send()
709            .await?;
710        assert_eq!(js_response.status(), reqwest::StatusCode::OK);
711        assert_eq!(js_response.bytes().await?.as_ref(), b"console.log('ok');");
712
713        let profile_response = client
714            .get(format!("{base_url}/users/npub1example"))
715            .header("Host", &host_header)
716            .header("Accept", "text/html")
717            .send()
718            .await?;
719        assert_eq!(profile_response.status(), reqwest::StatusCode::OK);
720        assert_eq!(
721            profile_response.bytes().await?.as_ref(),
722            b"<!doctype html><title>Virtual host ok</title>"
723        );
724
725        handle.abort();
726        clear_virtual_tree_hosts_for_test();
727
728        Ok(())
729    }
730
731    #[tokio::test]
732    async fn nostr_profile_route_returns_latest_metadata_event() -> Result<()> {
733        let temp_dir = TempDir::new()?;
734        let store = Arc::new(HashtreeStore::new(temp_dir.path().join("db"))?);
735        let graph_store = {
736            let _guard = crate::socialgraph::test_lock();
737            crate::socialgraph::open_social_graph_store_with_mapsize(
738                &temp_dir.path().join("relay-db"),
739                Some(128 * 1024 * 1024),
740            )?
741        };
742        let backend: Arc<dyn crate::socialgraph::SocialGraphBackend> = graph_store;
743        let relay = Arc::new(NostrRelay::new(
744            backend,
745            temp_dir.path().to_path_buf(),
746            HashSet::new(),
747            None,
748            NostrRelayConfig {
749                spambox_db_max_bytes: 0,
750                ..Default::default()
751            },
752        )?);
753
754        let author = Keys::generate();
755        let older = EventBuilder::new(
756            Kind::Metadata,
757            json!({ "name": "older", "about": "before" }).to_string(),
758            [],
759        )
760        .custom_created_at(Timestamp::from_secs(10))
761        .to_event(&author)?;
762        let newer = EventBuilder::new(
763            Kind::Metadata,
764            json!({ "name": "newer", "about": "after" }).to_string(),
765            [],
766        )
767        .custom_created_at(Timestamp::from_secs(20))
768        .to_event(&author)?;
769
770        relay.ingest_trusted_event(older).await?;
771        relay.ingest_trusted_event(newer.clone()).await?;
772
773        let (port, handle) = spawn_test_server_with_nostr_relay(store, relay).await?;
774        let response = reqwest::get(format!(
775            "http://127.0.0.1:{port}/api/nostr/profile/{}",
776            author.public_key().to_hex()
777        ))
778        .await?;
779
780        assert_eq!(response.status(), reqwest::StatusCode::OK);
781        let payload: serde_json::Value = response.json().await?;
782        assert_eq!(payload["profile"]["name"].as_str(), Some("newer"),);
783        assert_eq!(payload["profile"]["about"].as_str(), Some("after"));
784        assert_eq!(payload["created_at"].as_u64(), Some(20));
785        let expected_event_id = newer.id.to_hex();
786        assert_eq!(
787            payload["event_id"].as_str(),
788            Some(expected_event_id.as_str())
789        );
790
791        handle.abort();
792        Ok(())
793    }
794}