adler_server/lib.rs
1//! HTTP server for the [Adler](https://github.com/commit3296/adler)
2//! OSINT username-search engine.
3//!
4//! This crate hosts the JSON API and embedded `SolidJS` web UI for
5//! Adler. It is a thin shell around [`adler_core`]: scans run through
6//! the same [`adler_core::executor`] the CLI uses, and the same
7//! [`adler_core::Client`] is shared across all in-process scans.
8//!
9//! ## Quick start
10//!
11//! ```no_run
12//! use std::net::SocketAddr;
13//! use adler_core::{Client, Registry};
14//! use adler_server::{AppConfig, serve};
15//!
16//! # #[tokio::main]
17//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
18//! let registry = Registry::default_embedded()?;
19//! // Use the caller's filtering rules — the CLI already exposes
20//! // --only/--tag/--exclude, so the server just runs whatever site
21//! // list it's handed.
22//! let filter = adler_core::SiteFilter::default();
23//! let sites = registry.filter_with(&filter);
24//! let catalog = registry.matches_with(&filter);
25//! let client = Client::builder().build()?;
26//! let config = AppConfig {
27//! bind: "127.0.0.1:8765".parse::<SocketAddr>()?,
28//! scan_capacity: 32,
29//! scans_dir: None, // or Some(adler_server::default_scans_dir())
30//! };
31//! serve(sites, catalog, client, config).await?;
32//! # Ok(())
33//! # }
34//! ```
35//!
36//! ## Routes
37//!
38//! | Route | Method | Purpose |
39//! |------------------------------------|--------|--------------------------------------|
40//! | `/api/health` | GET | liveness |
41//! | `/api/sites` | GET | site catalogue |
42//! | `/api/scan` | POST | start a scan, returns a `scan_id` |
43//! | `/api/scan/{id}` | GET | poll status / final aggregate |
44//! | `/api/scan/{id}/stream` | GET | Server-Sent Events |
45//! | `/api/scan/{id}/retry` | POST | retry one site in a scan |
46//! | `/api/scan/{id}/refilter` | POST | cancel and restart with new filters |
47//! | `/api/scans` | GET | recent scan history |
48//! | `/api/access` | GET | read-only access-engine summary |
49//! | `/` | GET | embedded `SolidJS` SPA |
50//!
51//! ## Threading and shutdown
52//!
53//! [`serve`] binds the TCP listener, installs a `SIGINT` / `SIGTERM`
54//! graceful-shutdown signal, and runs until the listener closes. All
55//! state (registry, client, in-flight scans) lives in an [`AppState`]
56//! cloned into each handler — no global mutables.
57
58#![warn(missing_docs)]
59
60use std::net::SocketAddr;
61use std::path::PathBuf;
62
63use adler_core::{Client, Site};
64use tokio::net::TcpListener;
65use tokio::signal;
66
67mod api;
68mod assets;
69mod error;
70mod persist;
71mod scan;
72mod state;
73
74pub use api::router;
75pub use error::{Error, Result};
76pub use persist::{
77 EvidenceChange, PersistedScan, ScanDiff, ScanTimeline, TimelineEvent, TimelineEventKind,
78 TimelineProfile, VerdictChange, build_scan_timeline, default_dir as default_scans_dir,
79 diff_scans,
80};
81pub use scan::{FinishedScan, ScanHandle, ScanId, Summary};
82pub use state::AppState;
83
84/// Server configuration.
85///
86/// `bind` is the TCP socket the server listens on; defaults are
87/// imposed by the caller (the CLI binds `127.0.0.1:8765` and refuses
88/// to bind a non-loopback address unless explicitly told to — there
89/// is no authentication on the API).
90#[derive(Debug, Clone)]
91pub struct AppConfig {
92 /// Address to bind the HTTP listener.
93 pub bind: SocketAddr,
94 /// Maximum number of recent scans retained in memory.
95 pub scan_capacity: usize,
96 /// Directory for on-disk scan history. `None` disables persistence.
97 /// The CLI defaults to [`default_scans_dir`].
98 pub scans_dir: Option<PathBuf>,
99}
100
101impl Default for AppConfig {
102 fn default() -> Self {
103 Self {
104 bind: SocketAddr::from(([127, 0, 0, 1], 8765)),
105 scan_capacity: 32,
106 scans_dir: None,
107 }
108 }
109}
110
111/// Run the server until the listener closes or a shutdown signal arrives.
112///
113/// `sites` is the pre-filtered enabled site list every scan dispatched
114/// through this server runs against. `catalog` is the same startup filter
115/// including disabled/parked entries so API/UI surfaces can explain why a
116/// site is unavailable. `client` is the pre-built HTTP client (so
117/// configuration like proxy, throttle, and browser backend flows from the
118/// CLI flags through here unchanged).
119pub async fn serve(
120 sites: Vec<Site>,
121 catalog: Vec<Site>,
122 client: Client,
123 config: AppConfig,
124) -> Result<()> {
125 let mut state = AppState::with_catalog(sites, catalog, client, config.scan_capacity);
126 if let Some(dir) = config.scans_dir.clone() {
127 state = state.with_scans_dir(dir);
128 }
129 let app = assets::attach(router(state));
130
131 let listener = TcpListener::bind(config.bind)
132 .await
133 .map_err(|source| Error::Bind {
134 addr: config.bind.to_string(),
135 source,
136 })?;
137 tracing::debug!(bind = %config.bind, "adler-server listening");
138
139 axum::serve(listener, app)
140 .with_graceful_shutdown(shutdown_signal())
141 .await
142 .map_err(Error::Server)?;
143 Ok(())
144}
145
146async fn shutdown_signal() {
147 let ctrl_c = async {
148 if let Err(err) = signal::ctrl_c().await {
149 tracing::warn!(error = %err, "failed to install Ctrl-C handler");
150 }
151 };
152
153 #[cfg(unix)]
154 let terminate = async {
155 match signal::unix::signal(signal::unix::SignalKind::terminate()) {
156 Ok(mut sig) => {
157 sig.recv().await;
158 }
159 Err(err) => tracing::warn!(error = %err, "failed to install SIGTERM handler"),
160 }
161 };
162
163 #[cfg(not(unix))]
164 let terminate = std::future::pending::<()>();
165
166 tokio::select! {
167 () = ctrl_c => {}
168 () = terminate => {}
169 }
170 tracing::info!("shutdown signal received");
171}