Skip to main content

hashtree_cli/server/
mod.rs

1mod auth;
2pub mod blossom;
3mod handlers;
4mod mime;
5#[cfg(feature = "p2p")]
6pub mod stun;
7mod ui;
8mod ws_relay;
9
10use crate::nostr_relay::NostrRelay;
11use crate::socialgraph;
12use crate::storage::HashtreeStore;
13use crate::webrtc::WebRTCState;
14use anyhow::Result;
15use axum::{
16    extract::DefaultBodyLimit,
17    middleware,
18    routing::{get, post, put},
19    Router,
20};
21use std::collections::HashSet;
22use std::sync::Arc;
23use tower_http::cors::CorsLayer;
24
25pub use auth::{AppState, AuthCredentials};
26
27pub struct HashtreeServer {
28    state: AppState,
29    addr: String,
30    extra_routes: Option<Router<AppState>>,
31    cors: Option<CorsLayer>,
32}
33
34impl HashtreeServer {
35    pub fn new(store: Arc<HashtreeStore>, addr: String) -> Self {
36        Self {
37            state: AppState {
38                store,
39                auth: None,
40                webrtc_peers: None,
41                ws_relay: Arc::new(auth::WsRelayState::new()),
42                max_upload_bytes: 5 * 1024 * 1024, // 5 MB default
43                public_writes: true,               // Allow anyone with valid Nostr auth by default
44                allowed_pubkeys: HashSet::new(), // No pubkeys allowed by default (use public_writes)
45                upstream_blossom: Vec::new(),
46                social_graph: None,
47                social_graph_ndb: None,
48                social_graph_root: None,
49                socialgraph_snapshot_public: false,
50                nostr_relay: None,
51            },
52            addr,
53            extra_routes: None,
54            cors: None,
55        }
56    }
57
58    /// Set maximum upload size for Blossom uploads
59    pub fn with_max_upload_bytes(mut self, bytes: usize) -> Self {
60        self.state.max_upload_bytes = bytes;
61        self
62    }
63
64    /// Set whether to allow public writes (anyone with valid Nostr auth)
65    /// When false, only social graph members can write
66    pub fn with_public_writes(mut self, public: bool) -> Self {
67        self.state.public_writes = public;
68        self
69    }
70
71    /// Set WebRTC state for P2P peer queries
72    pub fn with_webrtc_peers(mut self, webrtc_state: Arc<WebRTCState>) -> Self {
73        self.state.webrtc_peers = Some(webrtc_state);
74        self
75    }
76
77    pub fn with_auth(mut self, username: String, password: String) -> Self {
78        self.state.auth = Some(AuthCredentials { username, password });
79        self
80    }
81
82    /// Set allowed pubkeys for blossom write access (hex format)
83    pub fn with_allowed_pubkeys(mut self, pubkeys: HashSet<String>) -> Self {
84        self.state.allowed_pubkeys = pubkeys;
85        self
86    }
87
88    /// Set upstream Blossom servers for cascade fetching
89    pub fn with_upstream_blossom(mut self, servers: Vec<String>) -> Self {
90        self.state.upstream_blossom = servers;
91        self
92    }
93
94    /// Set social graph access control
95    pub fn with_social_graph(mut self, sg: Arc<socialgraph::SocialGraphAccessControl>) -> Self {
96        self.state.social_graph = Some(sg);
97        self
98    }
99
100    /// Configure social graph snapshot export (nostrdb handle + root)
101    pub fn with_socialgraph_snapshot(
102        mut self,
103        ndb: Arc<socialgraph::Ndb>,
104        root: [u8; 32],
105        public: bool,
106    ) -> Self {
107        self.state.social_graph_ndb = Some(ndb);
108        self.state.social_graph_root = Some(root);
109        self.state.socialgraph_snapshot_public = public;
110        self
111    }
112
113    /// Set Nostr relay state (shared for /ws and WebRTC)
114    pub fn with_nostr_relay(mut self, relay: Arc<NostrRelay>) -> Self {
115        self.state.nostr_relay = Some(relay);
116        self
117    }
118
119    /// Merge extra routes into the daemon router (e.g. Tauri embeds /nip07).
120    pub fn with_extra_routes(mut self, routes: Router<AppState>) -> Self {
121        self.extra_routes = Some(routes);
122        self
123    }
124
125    /// Apply a CORS layer to all routes (used by embedded clients like Tauri).
126    pub fn with_cors(mut self, cors: CorsLayer) -> Self {
127        self.cors = Some(cors);
128        self
129    }
130
131    pub async fn run(self) -> Result<()> {
132        let listener = tokio::net::TcpListener::bind(&self.addr).await?;
133        let _ = self.run_with_listener(listener).await?;
134        Ok(())
135    }
136
137    pub async fn run_with_listener(self, listener: tokio::net::TcpListener) -> Result<u16> {
138        let local_addr = listener.local_addr()?;
139
140        // Public endpoints (no auth required)
141        // Note: /:id serves both CID and blossom SHA256 hash lookups
142        // The handler differentiates based on hash format (64 char hex = blossom)
143        let state = self.state.clone();
144        let public_routes = Router::new()
145            .route("/", get(handlers::serve_root))
146            .route("/ws", get(ws_relay::ws_data))
147            .route(
148                "/htree/test",
149                get(handlers::htree_test).head(handlers::htree_test),
150            )
151            // /htree/nhash1...[/path] - content-addressed (immutable)
152            .route("/htree/nhash1:nhash", get(handlers::htree_nhash))
153            .route("/htree/nhash1:nhash/*path", get(handlers::htree_nhash_path))
154            // /htree/npub1.../tree[/path] - mutable (resolver-backed)
155            .route("/htree/npub1:npub/:treename", get(handlers::htree_npub))
156            .route(
157                "/htree/npub1:npub/:treename/*path",
158                get(handlers::htree_npub_path),
159            )
160            // Nostr resolver endpoints - resolve npub/treename to content
161            .route("/n/:pubkey/:treename", get(handlers::resolve_and_serve))
162            // Direct npub route (clients should parse nhash and request by hex hash)
163            .route("/npub1:rest", get(handlers::serve_npub))
164            // Blossom endpoints (BUD-01, BUD-02)
165            .route(
166                "/:id",
167                get(handlers::serve_content_or_blob)
168                    .head(blossom::head_blob)
169                    .delete(blossom::delete_blob)
170                    .options(blossom::cors_preflight),
171            )
172            .route(
173                "/upload",
174                put(blossom::upload_blob).options(blossom::cors_preflight),
175            )
176            .route(
177                "/list/:pubkey",
178                get(blossom::list_blobs).options(blossom::cors_preflight),
179            )
180            // Hashtree API endpoints
181            .route("/health", get(handlers::health_check))
182            .route("/api/pins", get(handlers::list_pins))
183            .route("/api/stats", get(handlers::storage_stats))
184            .route("/api/peers", get(handlers::webrtc_peers))
185            .route("/api/status", get(handlers::daemon_status))
186            .route("/api/socialgraph", get(handlers::socialgraph_stats))
187            .route(
188                "/api/socialgraph/snapshot",
189                get(handlers::socialgraph_snapshot),
190            )
191            .route(
192                "/api/socialgraph/distance/:pubkey",
193                get(handlers::follow_distance),
194            )
195            // Resolver API endpoints
196            .route(
197                "/api/resolve/:pubkey/:treename",
198                get(handlers::resolve_to_hash),
199            )
200            .route("/api/trees/:pubkey", get(handlers::list_trees))
201            .with_state(state.clone());
202
203        // Protected endpoints (require auth if enabled)
204        let protected_routes = Router::new()
205            .route("/upload", post(handlers::upload_file))
206            .route("/api/pin/:cid", post(handlers::pin_cid))
207            .route("/api/unpin/:cid", post(handlers::unpin_cid))
208            .route("/api/gc", post(handlers::garbage_collect))
209            .layer(middleware::from_fn_with_state(
210                state.clone(),
211                auth::auth_middleware,
212            ))
213            .with_state(state.clone());
214
215        let mut app = public_routes
216            .merge(protected_routes)
217            .layer(DefaultBodyLimit::max(10 * 1024 * 1024 * 1024)); // 10GB limit
218
219        if let Some(extra) = self.extra_routes {
220            app = app.merge(extra.with_state(state));
221        }
222
223        if let Some(cors) = self.cors {
224            app = app.layer(cors);
225        }
226
227        axum::serve(
228            listener,
229            app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
230        )
231        .await?;
232
233        Ok(local_addr.port())
234    }
235
236    pub fn addr(&self) -> &str {
237        &self.addr
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244    use crate::storage::HashtreeStore;
245    use hashtree_core::from_hex;
246    use tempfile::TempDir;
247
248    #[tokio::test]
249    async fn test_server_serve_file() -> Result<()> {
250        let temp_dir = TempDir::new()?;
251        let store = Arc::new(HashtreeStore::new(temp_dir.path().join("db"))?);
252
253        // Create and upload a test file
254        let test_file = temp_dir.path().join("test.txt");
255        std::fs::write(&test_file, b"Hello, Hashtree!")?;
256
257        let cid = store.upload_file(&test_file)?;
258        let hash = from_hex(&cid)?;
259
260        // Verify we can get it
261        let content = store.get_file(&hash)?;
262        assert!(content.is_some());
263        assert_eq!(content.unwrap(), b"Hello, Hashtree!");
264
265        Ok(())
266    }
267
268    #[tokio::test]
269    async fn test_server_list_pins() -> Result<()> {
270        let temp_dir = TempDir::new()?;
271        let store = Arc::new(HashtreeStore::new(temp_dir.path().join("db"))?);
272
273        let test_file = temp_dir.path().join("test.txt");
274        std::fs::write(&test_file, b"Test")?;
275
276        let cid = store.upload_file(&test_file)?;
277        let hash = from_hex(&cid)?;
278
279        let pins = store.list_pins_raw()?;
280        assert_eq!(pins.len(), 1);
281        assert_eq!(pins[0], hash);
282
283        Ok(())
284    }
285}