feather_reader/lib.rs
1//! **FeatherReader** — a minimalist, atproto-native RSS/Atom feed reader.
2//!
3//! Your feed subscriptions live in your own [atproto](https://atproto.com) PDS
4//! (via the open `community.lexicon.rss.*` community lexicon), so your reading
5//! list follows you across any compatible reader — you own your data, not the
6//! app. Minimalist by design.
7//!
8//! This crate ships as a single server binary (`featherreader`) plus this small
9//! library, which declares the module tree and the shared types the binary and
10//! its subsystems build on. The heavy lifting lives in sibling modules:
11//!
12//! - [`config`] — env-driven runtime configuration (`FEATHERREADER_*`).
13//! - [`lexicon`] — the `community.lexicon.rss.*` record schemas (subscription,
14//! folder, saved, readState) as serde types.
15//! - [`store`] — the per-DID SQLite cache + read-state working copy (sqlx,
16//! runtime queries).
17//! - [`feed`] — polite fetching (conditional GET, backoff), feed-rs parsing,
18//! and ammonia sanitization.
19//! - [`atproto`] — the atproto identity + PDS record layer (subscriptions,
20//! folders, saved, batched read-state sync), including the Node sidecar's
21//! client ([`atproto::SidecarClient`]).
22//! - [`oauth`] — the Rust-native atproto OAuth client (the `rust` repo
23//! backend, which production runs).
24//! - [`repo`] — the one dispatcher every `com.atproto.repo.*` call goes
25//! through, choosing the sidecar or the Rust client by
26//! `FEATHERREADER_REPO_BACKEND`.
27//! - [`standard_site`] — reading standard.site publications from their
28//! authors' repos.
29//! - [`network`] — read-only queries against the *public* atproto network (the
30//! relay adoption probe). A projection, never a source of truth, and never on
31//! a reader path.
32//! - [`web`] — the axum router + askama server-rendered views.
33//!
34//! **Status:** experimental / pre-1.0. See <https://feather-reader.com>.
35
36// The module tree; the layout owns the wiring between subsystems.
37pub mod atproto;
38pub mod config;
39pub mod feed;
40pub mod lexicon;
41pub mod metrics;
42pub mod net;
43pub mod network;
44pub mod oauth;
45pub mod readstate;
46pub mod repo;
47pub mod runtime_health;
48pub mod safe_link;
49pub mod standard_site;
50pub mod store;
51pub mod vetted;
52pub mod web;
53
54use std::collections::HashMap;
55use std::sync::{Arc, RwLock};
56
57use atproto::SidecarClient;
58use config::Config;
59use store::Pool;
60
61/// One logged-in identity, resolved from the OAuth sidecar and keyed by DID.
62///
63/// The DID is the primary key for everything local; the handle is carried for
64/// display. This is what the signed session cookie resolves to.
65#[derive(Clone, Debug)]
66pub struct Session {
67 /// The account DID (the primary key for all per-user local state).
68 pub did: String,
69 /// The account handle at login time (display only).
70 pub handle: Option<String>,
71}
72
73/// In-memory session registry: **opaque random session-id → [`Session`]**.
74///
75/// The signed cookie carries a random, server-minted session id (`sid`), *not*
76/// the DID: the DID is never attacker-supplied, so a session cookie cannot be
77/// forged by resolving a victim's DID — an attacker would need both the server's
78/// HMAC secret *and* to guess a 256-bit random sid that only exists server-side.
79/// Sessions are therefore also **revocable** (drop the sid → the cookie is dead)
80/// and are cleared on restart (every client re-logs in; the durable OAuth
81/// session still lives in the sidecar's store).
82#[derive(Clone, Default)]
83pub struct SessionRegistry {
84 inner: Arc<RwLock<HashMap<String, Session>>>,
85}
86
87impl SessionRegistry {
88 /// A fresh, empty registry.
89 pub fn new() -> Self {
90 Self::default()
91 }
92
93 /// Create a new session for `session`, returning its freshly-minted random
94 /// session id (the value the signed cookie carries).
95 pub fn create(&self, session: Session) -> String {
96 let sid = new_session_id();
97 if let Ok(mut map) = self.inner.write() {
98 map.insert(sid.clone(), session);
99 }
100 sid
101 }
102
103 /// Look up a session by its opaque session id.
104 pub fn get(&self, sid: &str) -> Option<Session> {
105 self.inner.read().ok().and_then(|m| m.get(sid).cloned())
106 }
107
108 /// Drop a session by its session id (logout / revoke).
109 pub fn remove(&self, sid: &str) {
110 if let Ok(mut map) = self.inner.write() {
111 map.remove(sid);
112 }
113 }
114}
115
116/// Mint a fresh, unguessable session id: 32 random bytes (256 bits) as URL-safe
117/// hex. Sourced from the OS CSPRNG via `getrandom` (pulled in transitively);
118/// falls back to a time+address-seeded mix only if the OS RNG is unavailable,
119/// which never happens on the supported platforms.
120fn new_session_id() -> String {
121 let mut bytes = [0u8; 32];
122 if getrandom::fill(&mut bytes).is_err() {
123 // Extremely defensive fallback: mix a few entropy-ish sources. Not used
124 // on any supported platform (getrandom uses the OS CSPRNG).
125 use std::time::{SystemTime, UNIX_EPOCH};
126 let nanos = SystemTime::now()
127 .duration_since(UNIX_EPOCH)
128 .map(|d| d.as_nanos())
129 .unwrap_or(0);
130 let seed = nanos as u64 ^ (&bytes as *const _ as u64);
131 let mut x = seed | 1;
132 for b in bytes.iter_mut() {
133 // xorshift64 — only reached if the OS CSPRNG is unavailable.
134 x ^= x << 13;
135 x ^= x >> 7;
136 x ^= x << 17;
137 *b = (x & 0xff) as u8;
138 }
139 }
140 let mut s = String::with_capacity(64);
141 for b in bytes {
142 use std::fmt::Write;
143 let _ = write!(s, "{b:02x}");
144 }
145 s
146}
147
148/// Shared application state handed to every axum handler.
149///
150/// Holds the resolved [`Config`], the SQLite pool, a shared `reqwest::Client`
151/// (feed fetch + sidecar calls), the [`SidecarClient`] (the live atproto
152/// `com.atproto.repo.*` path), and the in-memory [`SessionRegistry`] (DID ↔
153/// handle, resolved via the sidecar's `/internal/session`). It is `Clone` (cheap
154/// — everything is behind `Arc`/handles) and is cloned into each request. It
155/// lives in the library so both [`web`] and the `featherreader` binary share it.
156#[derive(Clone)]
157pub struct AppState {
158 /// Immutable runtime configuration.
159 pub config: Arc<Config>,
160 /// The per-DID SQLite cache pool.
161 pub db: Pool,
162 /// Shared HTTP client (feed fetch + sidecar internal API).
163 pub http: reqwest::Client,
164 /// The atproto OAuth sidecar client — the repo-op path when
165 /// [`Config::repo_backend`] selects `Sidecar`. Production selects `Rust`.
166 pub sidecar: SidecarClient,
167 /// DID ↔ handle session registry (cookie-resolved identity).
168 pub sessions: SessionRegistry,
169 /// Repo-op latency for BOTH backends, for reading the two side by side
170 /// across a cutover flip.
171 pub metrics: Arc<metrics::RepoMetrics>,
172 /// The Rust OAuth client's runtime. `None` when it could not be built —
173 /// tolerated only while the sidecar is the selected backend, and refused at
174 /// startup otherwise.
175 pub oauth: Option<Arc<oauth::runtime::OauthRuntime>>,
176 /// What the background loops are doing right now — the poll heartbeat and
177 /// the watermark pause. Written by the scheduler, read by `/health` and
178 /// `/stats`. See [`runtime_health`] for why these two states needed a home
179 /// outside the log stream.
180 pub runtime_health: Arc<runtime_health::RuntimeHealth>,
181}
182
183impl AppState {
184 /// Assemble the shared state from config + an initialized store pool.
185 ///
186 /// Builds the shared HTTP client and the [`SidecarClient`] from the config's
187 /// [`crate::config::SidecarConfig`], and starts with an empty session
188 /// registry. The binary's `main` calls this after opening the store.
189 pub fn new(config: Config, db: Pool) -> anyhow::Result<Self> {
190 let http = build_http_client()?;
191
192 // Built whatever the backend, so a bad OAuth config is caught on every
193 // deploy rather than at the moment the switch is thrown. With the
194 // sidecar selected a failure is only a warning; with the Rust backend
195 // selected it is fatal, because there would be nothing to serve with.
196 let oauth = match oauth::runtime::OauthRuntime::new(&config) {
197 Ok(runtime) => Some(Arc::new(runtime)),
198 Err(err) if config.repo_backend == metrics::Backend::Sidecar => {
199 tracing::warn!(
200 %err,
201 "the Rust OAuth runtime could not be built; the sidecar backend is \
202 unaffected, but FEATHERREADER_REPO_BACKEND=rust would refuse to start"
203 );
204 None
205 }
206 Err(err) => return Err(err.context(
207 "FEATHERREADER_REPO_BACKEND=rust, but the Rust OAuth runtime could not be built",
208 )),
209 };
210 let sidecar = SidecarClient::new(
211 http.clone(),
212 config.sidecar.public_url.clone(),
213 config.sidecar.internal_url.clone(),
214 config.sidecar.internal_secret.clone(),
215 );
216 Ok(Self {
217 config: Arc::new(config),
218 db,
219 http,
220 sidecar,
221 sessions: SessionRegistry::new(),
222 metrics: Arc::new(metrics::RepoMetrics::new()),
223 oauth,
224 runtime_health: Arc::new(runtime_health::RuntimeHealth::new()),
225 })
226 }
227}
228
229/// The shared HTTP client [`AppState`] carries, also used by the binary's
230/// maintenance commands (`--revoke-all-sessions`) so they reach the network
231/// exactly as the serving app does.
232///
233/// `.no_proxy()` for the same reason as `net::build_pinned_client` and
234/// `feed::build_client`: ambient `HTTP_PROXY` would route this client's traffic
235/// through a proxy that resolves hostnames itself, out from under the SSRF
236/// guard's address checks.
237pub fn build_http_client() -> reqwest::Result<reqwest::Client> {
238 reqwest::Client::builder()
239 .user_agent(USER_AGENT)
240 .no_proxy()
241 .build()
242}
243
244/// The crate version — surfaced for the server's `--version` / health output.
245pub const VERSION: &str = env!("CARGO_PKG_VERSION");
246
247/// The `User-Agent` FeatherReader identifies itself with when fetching feeds.
248///
249/// Being a polite, identifiable client is a feed-hygiene requirement (§5 of the
250/// design): publishers ask readers to say who they are so they can be reached or
251/// rate-limited sanely rather than silently blocked.
252pub const USER_AGENT: &str = concat!(
253 "featherreader/",
254 env!("CARGO_PKG_VERSION"),
255 " (+https://feather-reader.com)"
256);