6 Commits

Author SHA1 Message Date
Razvan Dimescu
c1d425069f bump version to 0.5.0
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:41:07 +02:00
Razvan Dimescu
d274500308 feat: DNS-over-HTTPS (DoH) upstream forwarding (#14)
* feat: DNS-over-HTTPS upstream forwarding

Encrypt upstream queries via DoH — ISPs see HTTPS traffic on port 443,
not plaintext DNS on port 53. URL scheme determines transport:
https:// = DoH, bare IP = plain UDP. Falls back to Quad9 DoH when
system resolver cannot be detected.

- Upstream enum (Udp/Doh) with Display and PartialEq
- BytePacketBuffer::from_bytes constructor
- reqwest http2 feature for DoH server compatibility
- network_watch_loop guards against DoH→UDP silent downgrade
- 5 new tests (mock DoH server, HTTP errors, timeout)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* style: cargo fmt

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: add DoH to README — Why Numa, comparison table, roadmap

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 00:39:58 +02:00
Razvan Dimescu
9c313ef06a docs: reorder README for launch — lead with unique features, add install methods
Comparison table and "Why Numa" reordered so unique capabilities (service proxy,
path routing, LAN discovery) appear first. Added brew/cargo install to Quick Start.
Removed unshipped "Self-sovereign DNS" row from comparison table. Named hickory-dns
and trust-dns in "How It Works" to signal deliberate architectural choice.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 21:16:50 +02:00
Razvan Dimescu
0d25fae4cf Merge pull request #13 from razvandimescu/fix/tls-hot-reload
fix: TLS cert hot-reload when services change
2026-03-23 19:46:05 +02:00
Razvan Dimescu
1ae2e23bb6 fix: regenerate TLS cert when services change (hot-reload via ArcSwap)
HTTPS proxy certs were generated once at startup. Services added at
runtime via API or LAN discovery got "not secure" in the browser
because their SAN wasn't in the cert. Now the cert is regenerated
on every service add/remove and swapped atomically via ArcSwap.
In-flight connections are unaffected.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 16:14:06 +02:00
Razvan Dimescu
fe784addd2 release: auto-publish to crates.io on tag push
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 14:41:21 +02:00
14 changed files with 430 additions and 72 deletions

View File

@@ -79,8 +79,21 @@ jobs:
${{ matrix.name }}.zip
${{ matrix.name }}.zip.sha256
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- name: Publish to crates.io
run: cargo publish
env:
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
release:
needs: build
needs: [build, publish]
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v4

39
Cargo.lock generated
View File

@@ -67,6 +67,15 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "arc-swap"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a07d1f37ff60921c83bdfc7407723bdefe89b44b98a9b772f225c8f9d67141a6"
dependencies = [
"rustversion",
]
[[package]]
name = "asn1-rs"
version = "0.6.2"
@@ -384,6 +393,12 @@ dependencies = [
"miniz_oxide",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
@@ -514,6 +529,25 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "h2"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"
dependencies = [
"atomic-waker",
"bytes",
"fnv",
"futures-core",
"futures-sink",
"http",
"indexmap",
"slab",
"tokio",
"tokio-util",
"tracing",
]
[[package]]
name = "hashbrown"
version = "0.16.1"
@@ -575,6 +609,7 @@ dependencies = [
"bytes",
"futures-channel",
"futures-core",
"h2",
"http",
"http-body",
"httparse",
@@ -932,8 +967,9 @@ dependencies = [
[[package]]
name = "numa"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"arc-swap",
"axum",
"env_logger",
"futures",
@@ -1201,6 +1237,7 @@ dependencies = [
"base64",
"bytes",
"futures-core",
"h2",
"http",
"http-body",
"http-body-util",

View File

@@ -1,6 +1,6 @@
[package]
name = "numa"
version = "0.4.0"
version = "0.5.0"
authors = ["razvandimescu <razvan@dimescu.com>"]
edition = "2021"
description = "Ephemeral DNS overrides for development and testing. Point any hostname to any endpoint. Auto-revert when you're done."
@@ -17,7 +17,7 @@ serde_json = "1"
toml = "0.8"
log = "0.4"
env_logger = "0.11"
reqwest = { version = "0.12", features = ["rustls-tls", "gzip"], default-features = false }
reqwest = { version = "0.12", features = ["rustls-tls", "gzip", "http2"], default-features = false }
hyper = { version = "1", features = ["client", "http1", "server"] }
hyper-util = { version = "0.1", features = ["client-legacy", "http1", "tokio"] }
http-body-util = "0.1"
@@ -27,3 +27,4 @@ rcgen = { version = "0.13", features = ["pem", "x509-parser"] }
time = "0.3"
rustls = "0.23"
tokio-rustls = "0.26"
arc-swap = "1"

View File

@@ -15,7 +15,9 @@ Built from scratch in Rust. Zero DNS libraries. RFC 1035 wire protocol parsed by
## Quick Start
```bash
# Install
# Install (pick one)
brew install razvandimescu/tap/numa
cargo install numa
curl -fsSL https://raw.githubusercontent.com/razvandimescu/numa/main/install.sh | sh
# Run (port 53 requires root)
@@ -37,11 +39,12 @@ sudo ./target/release/numa
## Why Numa
- **Ad blocking that travels with you** — 385K+ domains blocked via [Hagezi Pro](https://github.com/hagezi/dns-blocklists). Works on any network: coffee shops, hotels, airports.
- **Local service proxy** — `https://frontend.numa` instead of `localhost:5173`. Auto-generated TLS certs, WebSocket support for HMR. Like `/etc/hosts` but with a dashboard and auto-revert.
- **Local service proxy** — `https://frontend.numa` instead of `localhost:5173`. Auto-generated TLS certs, WebSocket support for HMR. Like `/etc/hosts` but with auto TLS, a REST API, LAN discovery, and auto-revert.
- **Path-based routing** — `app.numa/api → :5001`, `app.numa/auth → :5002`. Route URL paths to different backends with optional prefix stripping. Like nginx location blocks, zero config files.
- **LAN service discovery** — Numa instances on the same network find each other automatically via mDNS. Access a teammate's `api.numa` from your machine. Opt-in via `[lan] enabled = true`.
- **Developer overrides** — point any hostname to any IP, auto-reverts after N minutes. REST API with 25+ endpoints. Built-in diagnostics: `curl localhost:5380/diagnose/example.com` tells you exactly how any domain resolves.
- **DNS-over-HTTPS** — upstream queries encrypted via DoH. Your ISP sees HTTPS traffic, not DNS queries. Set `address = "https://9.9.9.9/dns-query"` in `[upstream]` or any DoH provider.
- **Ad blocking that travels with you** — 385K+ domains blocked via [Hagezi Pro](https://github.com/hagezi/dns-blocklists). Works on any network: coffee shops, hotels, airports.
- **Sub-millisecond caching** — cached lookups in 0ms. Faster than any public resolver.
- **Live dashboard** — real-time stats, query log, blocking controls, service management. LAN accessibility badges show which services are reachable from other devices.
- **macOS + Linux** — `numa install` configures system DNS, `numa service start` runs as launchd/systemd service.
@@ -128,15 +131,15 @@ bind_addr = "0.0.0.0:53"
| | Pi-hole | AdGuard Home | NextDNS | Cloudflare | Numa |
|---|---|---|---|---|---|
| Ad blocking | Yes | Yes | Yes | Limited | 385K+ domains |
| Portable (travels with laptop) | No (appliance) | No (appliance) | Cloud only | Cloud only | Single binary |
| Developer overrides | No | No | No | No | REST API + auto-expiry |
| Local service proxy | No | No | No | No | `.numa` + HTTPS + WS |
| Path-based routing | No | No | No | No | Prefix match + strip |
| LAN service discovery | No | No | No | No | mDNS, opt-in |
| Data stays local | Yes | Yes | Cloud | Cloud | 100% local |
| Developer overrides | No | No | No | No | REST API + auto-expiry |
| Encrypted upstream (DoH) | No (needs cloudflared) | Yes | Cloud only | Cloud only | Native, single binary |
| Portable (travels with laptop) | No (appliance) | No (appliance) | Cloud only | Cloud only | Single binary |
| Zero config | Complex | Docker/setup | Yes | Yes | Works out of the box |
| Self-sovereign DNS | No | No | No | No | pkarr/DHT roadmap |
| Ad blocking | Yes | Yes | Yes | Limited | 385K+ domains |
| Data stays local | Yes | Yes | Cloud | Cloud | 100% local |
## How It Works
@@ -144,7 +147,7 @@ bind_addr = "0.0.0.0:53"
Query → Overrides → .numa TLD → Blocklist → Local Zones → Cache → Upstream
```
No DNS libraries. The wire protocol — headers, labels, compression pointers, record types — is parsed and serialized by hand. Runs on `tokio` + `axum`, async per-query task spawning.
No DNS libraries — no `hickory-dns`, no `trust-dns`. The wire protocol — headers, labels, compression pointers, record types — is parsed and serialized by hand. Runs on `tokio` + `axum`, async per-query task spawning.
[Configuration reference](numa.toml)
@@ -157,6 +160,7 @@ No DNS libraries. The wire protocol — headers, labels, compression pointers, r
- [x] Local service proxy — `.numa` domains, HTTP/HTTPS proxy, auto TLS, WebSocket
- [x] Path-based routing — URL prefix routing with optional strip, REST API
- [x] LAN service discovery — mDNS auto-discovery (opt-in), cross-machine DNS + proxy
- [x] DNS-over-HTTPS — encrypted upstream via DoH (Quad9, Cloudflare, any provider)
- [ ] pkarr integration — self-sovereign DNS via Mainline DHT (15M nodes)
- [ ] Global `.numa` names — self-publish, DHT-backed, first-come-first-served

View File

@@ -5,8 +5,10 @@ api_port = 5380
# [upstream]
# address = "" # auto-detect from system resolver (default)
# address = "9.9.9.9" # or set explicitly
# port = 53
# address = "https://dns.quad9.net/dns-query" # DNS-over-HTTPS (encrypted)
# address = "https://cloudflare-dns.com/dns-query" # Cloudflare DoH
# address = "9.9.9.9" # plain UDP
# port = 53 # only used for plain UDP
# timeout_ms = 3000
# [blocking]

View File

@@ -9,7 +9,7 @@ use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use crate::ctx::ServerCtx;
use crate::forward::forward_query;
use crate::forward::{forward_query, Upstream};
use crate::query_log::QueryLogFilter;
use crate::question::QueryType;
use crate::stats::QueryPath;
@@ -355,9 +355,9 @@ async fn diagnose(
}
// Check upstream (async, no locks held)
let upstream = *ctx.upstream.lock().unwrap();
let upstream = ctx.upstream.lock().unwrap().clone();
let (upstream_matched, upstream_detail) =
forward_query_for_diagnose(&domain_lower, upstream, ctx.timeout).await;
forward_query_for_diagnose(&domain_lower, &upstream, ctx.timeout).await;
steps.push(DiagnoseStep {
source: "upstream".to_string(),
matched: upstream_matched,
@@ -373,7 +373,7 @@ async fn diagnose(
async fn forward_query_for_diagnose(
domain: &str,
upstream: std::net::SocketAddr,
upstream: &Upstream,
timeout: std::time::Duration,
) -> (bool, String) {
use crate::packet::DnsPacket;
@@ -711,7 +711,11 @@ async fn create_service(
}
let tld = &ctx.proxy_tld;
let is_new = !ctx.services.lock().unwrap().has_name(&name);
ctx.services.lock().unwrap().insert(&name, req.target_port);
if is_new {
crate::tls::regenerate_tls(&ctx);
}
let localhost = std::net::SocketAddr::from(([127, 0, 0, 1], req.target_port));
let lan_addr =
@@ -740,8 +744,9 @@ async fn remove_service(State(ctx): State<Arc<ServerCtx>>, Path(name): Path<Stri
if name.eq_ignore_ascii_case("numa") {
return StatusCode::FORBIDDEN;
}
let mut store = ctx.services.lock().unwrap();
if store.remove(&name) {
let removed = ctx.services.lock().unwrap().remove(&name);
if removed {
crate::tls::regenerate_tls(&ctx);
StatusCode::NO_CONTENT
} else {
StatusCode::NOT_FOUND

View File

@@ -21,6 +21,13 @@ impl BytePacketBuffer {
}
}
pub fn from_bytes(data: &[u8]) -> Self {
let mut buf = Self::new();
let len = data.len().min(BUF_SIZE);
buf.buf[..len].copy_from_slice(&data[..len]);
buf
}
pub fn pos(&self) -> usize {
self.pos
}

View File

@@ -3,14 +3,16 @@ use std::path::PathBuf;
use std::sync::Mutex;
use std::time::{Duration, Instant, SystemTime};
use arc_swap::ArcSwap;
use log::{debug, error, info, warn};
use rustls::ServerConfig;
use tokio::net::UdpSocket;
use crate::blocklist::BlocklistStore;
use crate::buffer::BytePacketBuffer;
use crate::cache::DnsCache;
use crate::config::ZoneMap;
use crate::forward::forward_query;
use crate::forward::{forward_query, Upstream};
use crate::header::ResultCode;
use crate::lan::PeerStore;
use crate::override_store::OverrideStore;
@@ -33,7 +35,7 @@ pub struct ServerCtx {
pub services: Mutex<ServiceStore>,
pub lan_peers: Mutex<PeerStore>,
pub forwarding_rules: Vec<ForwardingRule>,
pub upstream: Mutex<SocketAddr>,
pub upstream: Mutex<Upstream>,
pub upstream_auto: bool,
pub upstream_port: u16,
pub lan_ip: Mutex<std::net::Ipv4Addr>,
@@ -45,6 +47,7 @@ pub struct ServerCtx {
pub config_found: bool,
pub config_dir: PathBuf,
pub data_dir: PathBuf,
pub tls_config: Option<ArcSwap<ServerConfig>>,
}
pub async fn handle_query(
@@ -140,9 +143,11 @@ pub async fn handle_query(
(resp, QueryPath::Cached)
} else {
let upstream =
crate::system_dns::match_forwarding_rule(&qname, &ctx.forwarding_rules)
.unwrap_or_else(|| *ctx.upstream.lock().unwrap());
match forward_query(&query, upstream, ctx.timeout).await {
match crate::system_dns::match_forwarding_rule(&qname, &ctx.forwarding_rules) {
Some(addr) => Upstream::Udp(addr),
None => ctx.upstream.lock().unwrap().clone(),
};
match forward_query(&query, &upstream, ctx.timeout).await {
Ok(resp) => {
ctx.cache.lock().unwrap().insert(&qname, qtype, &resp);
(resp, QueryPath::Forwarded)

View File

@@ -1,3 +1,4 @@
use std::fmt;
use std::net::SocketAddr;
use std::time::Duration;
@@ -8,7 +9,46 @@ use crate::buffer::BytePacketBuffer;
use crate::packet::DnsPacket;
use crate::Result;
#[derive(Clone)]
pub enum Upstream {
Udp(SocketAddr),
Doh {
url: String,
client: reqwest::Client,
},
}
impl PartialEq for Upstream {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Udp(a), Self::Udp(b)) => a == b,
(Self::Doh { url: a, .. }, Self::Doh { url: b, .. }) => a == b,
_ => false,
}
}
}
impl fmt::Display for Upstream {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Upstream::Udp(addr) => write!(f, "{}", addr),
Upstream::Doh { url, .. } => f.write_str(url),
}
}
}
pub async fn forward_query(
query: &DnsPacket,
upstream: &Upstream,
timeout_duration: Duration,
) -> Result<DnsPacket> {
match upstream {
Upstream::Udp(addr) => forward_udp(query, *addr, timeout_duration).await,
Upstream::Doh { url, client } => forward_doh(query, url, client, timeout_duration).await,
}
}
async fn forward_udp(
query: &DnsPacket,
upstream: SocketAddr,
timeout_duration: Duration,
@@ -33,3 +73,174 @@ pub async fn forward_query(
DnsPacket::from_buffer(&mut recv_buffer)
}
async fn forward_doh(
query: &DnsPacket,
url: &str,
client: &reqwest::Client,
timeout_duration: Duration,
) -> Result<DnsPacket> {
let mut send_buffer = BytePacketBuffer::new();
query.write(&mut send_buffer)?;
let resp = timeout(
timeout_duration,
client
.post(url)
.header("content-type", "application/dns-message")
.header("accept", "application/dns-message")
.body(send_buffer.filled().to_vec())
.send(),
)
.await??
.error_for_status()?;
let bytes = resp.bytes().await?;
log::debug!("DoH response: {} bytes", bytes.len());
let mut recv_buffer = BytePacketBuffer::from_bytes(&bytes);
DnsPacket::from_buffer(&mut recv_buffer)
}
#[cfg(test)]
mod tests {
use super::*;
use std::future::IntoFuture;
use crate::header::ResultCode;
use crate::question::{DnsQuestion, QueryType};
use crate::record::DnsRecord;
#[test]
fn upstream_display_udp() {
let u = Upstream::Udp("9.9.9.9:53".parse().unwrap());
assert_eq!(u.to_string(), "9.9.9.9:53");
}
#[test]
fn upstream_display_doh() {
let u = Upstream::Doh {
url: "https://dns.quad9.net/dns-query".to_string(),
client: reqwest::Client::new(),
};
assert_eq!(u.to_string(), "https://dns.quad9.net/dns-query");
}
fn make_query() -> DnsPacket {
let mut q = DnsPacket::new();
q.header.id = 0xABCD;
q.header.recursion_desired = true;
q.questions
.push(DnsQuestion::new("example.com".to_string(), QueryType::A));
q
}
fn make_response(query: &DnsPacket) -> DnsPacket {
let mut resp = DnsPacket::response_from(query, ResultCode::NOERROR);
resp.answers.push(DnsRecord::A {
domain: "example.com".to_string(),
addr: "93.184.216.34".parse().unwrap(),
ttl: 300,
});
resp
}
fn to_wire(pkt: &DnsPacket) -> Vec<u8> {
let mut buf = BytePacketBuffer::new();
pkt.write(&mut buf).unwrap();
buf.filled().to_vec()
}
#[tokio::test]
async fn doh_mock_server_resolves() {
let query = make_query();
let response_bytes = to_wire(&make_response(&query));
let app = axum::Router::new().route(
"/dns-query",
axum::routing::post(move || {
let body = response_bytes.clone();
async move {
(
[(axum::http::header::CONTENT_TYPE, "application/dns-message")],
body,
)
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(axum::serve(listener, app).into_future());
let upstream = Upstream::Doh {
url: format!("http://{}/dns-query", addr),
client: reqwest::Client::new(),
};
let result = forward_query(&query, &upstream, Duration::from_secs(2))
.await
.expect("DoH forward should succeed");
assert_eq!(result.header.id, 0xABCD);
assert!(result.header.response);
assert_eq!(result.header.rescode, ResultCode::NOERROR);
assert_eq!(result.answers.len(), 1);
match &result.answers[0] {
DnsRecord::A { domain, addr, ttl } => {
assert_eq!(domain, "example.com");
assert_eq!(
*addr,
"93.184.216.34".parse::<std::net::Ipv4Addr>().unwrap()
);
assert_eq!(*ttl, 300);
}
other => panic!("expected A record, got {:?}", other),
}
}
#[tokio::test]
async fn doh_http_error_propagates() {
let app = axum::Router::new().route(
"/dns-query",
axum::routing::post(|| async {
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, "bad")
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(axum::serve(listener, app).into_future());
let upstream = Upstream::Doh {
url: format!("http://{}/dns-query", addr),
client: reqwest::Client::new(),
};
let result = forward_query(&make_query(), &upstream, Duration::from_secs(2)).await;
assert!(result.is_err());
}
#[tokio::test]
async fn doh_timeout() {
let app = axum::Router::new().route(
"/dns-query",
axum::routing::post(|| async {
tokio::time::sleep(Duration::from_secs(10)).await;
"never"
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(axum::serve(listener, app).into_future());
let upstream = Upstream::Doh {
url: format!("http://{}/dns-query", addr),
client: reqwest::Client::new(),
};
let result = forward_query(&make_query(), &upstream, Duration::from_millis(100)).await;
assert!(result.is_err());
}
}

View File

@@ -33,11 +33,18 @@ impl PeerStore {
}
}
pub fn update(&mut self, host: IpAddr, services: &[(String, u16)]) {
/// Returns true if a previously-unseen name was inserted.
pub fn update(&mut self, host: IpAddr, services: &[(String, u16)]) -> bool {
let now = Instant::now();
let mut changed = false;
for (name, port) in services {
self.peers.insert(name.to_lowercase(), (host, *port, now));
let key = name.to_lowercase();
if !self.peers.contains_key(&key) {
changed = true;
}
self.peers.insert(key, (host, *port, now));
}
changed
}
pub fn lookup(&mut self, name: &str) -> Option<(IpAddr, u16)> {
@@ -67,6 +74,13 @@ impl PeerStore {
.collect()
}
pub fn names(&mut self) -> Vec<String> {
let now = Instant::now();
self.peers
.retain(|_, (_, _, seen)| now.duration_since(*seen) < self.timeout);
self.peers.keys().cloned().collect()
}
pub fn clear(&mut self) {
self.peers.clear();
}
@@ -189,10 +203,14 @@ pub async fn start_lan_discovery(ctx: Arc<ServerCtx>, config: &LanConfig) {
continue;
}
if !ann.services.is_empty() {
ctx.lan_peers
let changed = ctx
.lan_peers
.lock()
.unwrap()
.update(ann.peer_ip, &ann.services);
if changed {
crate::tls::regenerate_tls(&ctx);
}
debug!(
"LAN: {} services from {} (mDNS)",
ann.services.len(),

View File

@@ -2,6 +2,7 @@ use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use arc_swap::ArcSwap;
use log::{error, info};
use tokio::net::UdpSocket;
@@ -10,6 +11,7 @@ use numa::buffer::BytePacketBuffer;
use numa::cache::DnsCache;
use numa::config::{build_zone_map, load_config, ConfigLoad};
use numa::ctx::{handle_query, ServerCtx};
use numa::forward::Upstream;
use numa::override_store::OverrideStore;
use numa::query_log::QueryLog;
use numa::service_store::ServiceStore;
@@ -110,13 +112,27 @@ async fn main() -> numa::Result<()> {
.default_upstream
.or_else(numa::system_dns::detect_dhcp_dns)
.unwrap_or_else(|| {
info!("could not detect system DNS, falling back to 9.9.9.9 (Quad9)");
"9.9.9.9".to_string()
info!("could not detect system DNS, falling back to Quad9 DoH");
"https://dns.quad9.net/dns-query".to_string()
})
} else {
config.upstream.address.clone()
};
let upstream: SocketAddr = format!("{}:{}", upstream_addr, config.upstream.port).parse()?;
let upstream: Upstream = if upstream_addr.starts_with("https://") {
let client = reqwest::Client::builder()
.use_rustls_tls()
.build()
.unwrap_or_default();
Upstream::Doh {
url: upstream_addr,
client,
}
} else {
let addr: SocketAddr = format!("{}:{}", upstream_addr, config.upstream.port).parse()?;
Upstream::Udp(addr)
};
let upstream_label = upstream.to_string();
let api_port = config.server.api_port;
let mut blocklist = BlocklistStore::new();
@@ -137,6 +153,20 @@ async fn main() -> numa::Result<()> {
let forwarding_rules = system_dns.forwarding_rules;
// Build initial TLS config before ServerCtx (so ArcSwap is ready at construction)
let initial_tls = if config.proxy.enabled && config.proxy.tls_port > 0 {
let service_names = service_store.names();
match numa::tls::build_tls_config(&config.proxy.tld, &service_names) {
Ok(tls_config) => Some(ArcSwap::from(tls_config)),
Err(e) => {
log::warn!("TLS setup failed, HTTPS proxy disabled: {}", e);
None
}
}
} else {
None
};
let ctx = Arc::new(ServerCtx {
socket: UdpSocket::bind(&config.server.bind_addr).await?,
zone_map: build_zone_map(&config.zones)?,
@@ -168,6 +198,7 @@ async fn main() -> numa::Result<()> {
config_found,
config_dir: numa::config_dir(),
data_dir: numa::data_dir(),
tls_config: initial_tls,
});
let zone_count: usize = ctx.zone_map.values().map(|m| m.len()).sum();
@@ -201,7 +232,7 @@ async fn main() -> numa::Result<()> {
let val_w = [
config.server.bind_addr.len(),
api_url.len(),
upstream.to_string().len(),
upstream_label.len(),
config_label.len(),
data_label.len(),
services_label.len(),
@@ -245,7 +276,7 @@ async fn main() -> numa::Result<()> {
row("DNS", g, &config.server.bind_addr);
row("API", g, &api_url);
row("Dashboard", g, &api_url);
row("Upstream", g, &upstream.to_string());
row("Upstream", g, &upstream_label);
row("Zones", g, &format!("{} records", zone_count));
row(
"Cache",
@@ -282,7 +313,7 @@ async fn main() -> numa::Result<()> {
info!(
"numa listening on {}, upstream {}, {} zone records, cache max {}, API on port {}",
config.server.bind_addr, upstream, zone_count, config.cache.max_entries, api_port,
config.server.bind_addr, upstream_label, zone_count, config.cache.max_entries, api_port,
);
// Download blocklists on startup
@@ -336,28 +367,13 @@ async fn main() -> numa::Result<()> {
}
// Spawn HTTPS reverse proxy with TLS termination
if config.proxy.enabled && config.proxy.tls_port > 0 {
let service_names: Vec<String> = ctx
.services
.lock()
.unwrap()
.list()
.iter()
.map(|e| e.name.clone())
.collect();
match numa::tls::build_tls_config(&config.proxy.tld, &service_names) {
Ok(tls_config) => {
if config.proxy.enabled && config.proxy.tls_port > 0 && ctx.tls_config.is_some() {
let proxy_ctx = Arc::clone(&ctx);
let tls_port = config.proxy.tls_port;
tokio::spawn(async move {
numa::proxy::start_proxy_tls(proxy_ctx, tls_port, proxy_bind, tls_config).await;
numa::proxy::start_proxy_tls(proxy_ctx, tls_port, proxy_bind).await;
});
}
Err(e) => {
log::warn!("TLS setup failed, HTTPS proxy disabled: {}", e);
}
}
}
// Spawn network change watcher (upstream re-detection, LAN IP update, peer flush)
{
@@ -412,20 +428,24 @@ async fn network_watch_loop(ctx: Arc<numa::ctx::ServerCtx>) {
}
}
// Check upstream change every 30s or immediately on LAN IP change
// (heavier — spawns scutil/ipconfig, only when auto-detected)
if ctx.upstream_auto && (changed || tick.is_multiple_of(6)) {
// Re-detect upstream every 30s or on LAN IP change (UDP only —
// DoH upstreams are explicitly configured via URL, not auto-detected)
if ctx.upstream_auto
&& matches!(*ctx.upstream.lock().unwrap(), Upstream::Udp(_))
&& (changed || tick.is_multiple_of(6))
{
let dns_info = numa::system_dns::discover_system_dns();
let new_addr = dns_info
.default_upstream
.or_else(numa::system_dns::detect_dhcp_dns)
.unwrap_or_else(|| "9.9.9.9".to_string());
if let Ok(new_upstream) =
if let Ok(new_sock) =
format!("{}:{}", new_addr, ctx.upstream_port).parse::<SocketAddr>()
{
let new_upstream = Upstream::Udp(new_sock);
let mut upstream = ctx.upstream.lock().unwrap();
if new_upstream != *upstream {
info!("upstream changed: {} → {}", *upstream, new_upstream);
if *upstream != new_upstream {
info!("upstream changed: {} → {}", upstream, new_upstream);
*upstream = new_upstream;
changed = true;
}

View File

@@ -11,7 +11,6 @@ use hyper::StatusCode;
use hyper_util::client::legacy::Client;
use hyper_util::rt::TokioExecutor;
use log::{debug, error, info, warn};
use rustls::ServerConfig;
use tokio::io::copy_bidirectional;
use tokio_rustls::TlsAcceptor;
@@ -50,12 +49,7 @@ pub async fn start_proxy(ctx: Arc<ServerCtx>, port: u16, bind_addr: Ipv4Addr) {
axum::serve(listener, app).await.unwrap();
}
pub async fn start_proxy_tls(
ctx: Arc<ServerCtx>,
port: u16,
bind_addr: Ipv4Addr,
tls_config: Arc<ServerConfig>,
) {
pub async fn start_proxy_tls(ctx: Arc<ServerCtx>, port: u16, bind_addr: Ipv4Addr) {
let addr: SocketAddr = (bind_addr, port).into();
let listener = match tokio::net::TcpListener::bind(addr).await {
Ok(l) => l,
@@ -69,11 +63,17 @@ pub async fn start_proxy_tls(
};
info!("HTTPS proxy listening on {}", addr);
let acceptor = TlsAcceptor::from(tls_config);
if ctx.tls_config.is_none() {
warn!("proxy: no TLS config — HTTPS proxy disabled");
return;
}
let client: HttpClient = Client::builder(TokioExecutor::new())
.http1_preserve_header_case(true)
.build_http();
// Hold a separate Arc so we can access tls_config after ctx moves into ProxyState
let tls_holder = Arc::clone(&ctx);
let state = ProxyState { ctx, client };
let app = Router::new().fallback(any(proxy_handler)).with_state(state);
@@ -87,7 +87,10 @@ pub async fn start_proxy_tls(
}
};
let acceptor = acceptor.clone();
// Load the latest TLS config on each connection (picks up new service certs)
// unwrap safe: guarded by is_none() check above
let acceptor =
TlsAcceptor::from(Arc::clone(&*tls_holder.tls_config.as_ref().unwrap().load()));
let app = app.clone();
tokio::spawn(async move {

View File

@@ -154,6 +154,15 @@ impl ServiceStore {
entries
}
pub fn names(&self) -> Vec<String> {
self.entries.keys().cloned().collect()
}
/// Returns true if the name is new (not already registered).
pub fn has_name(&self, name: &str) -> bool {
self.entries.contains_key(&name.to_lowercase())
}
/// Load user-defined services from ~/.config/numa/services.json
pub fn load_persisted(&mut self) {
if !self.persist_path.exists() {

View File

@@ -1,7 +1,10 @@
use std::collections::HashSet;
use std::path::Path;
use std::sync::Arc;
use log::{info, warn};
use crate::ctx::ServerCtx;
use rcgen::{BasicConstraints, CertificateParams, DnType, IsCa, KeyPair, KeyUsagePurpose, SanType};
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
use rustls::ServerConfig;
@@ -10,6 +13,26 @@ use time::{Duration, OffsetDateTime};
const CA_VALIDITY_DAYS: i64 = 3650; // 10 years
const CERT_VALIDITY_DAYS: i64 = 365; // 1 year
/// Collect all service + LAN peer names and regenerate the TLS cert.
pub fn regenerate_tls(ctx: &ServerCtx) {
let tls = match &ctx.tls_config {
Some(t) => t,
None => return,
};
let mut names: HashSet<String> = ctx.services.lock().unwrap().names().into_iter().collect();
names.extend(ctx.lan_peers.lock().unwrap().names());
let names: Vec<String> = names.into_iter().collect();
match build_tls_config(&ctx.proxy_tld, &names) {
Ok(new_config) => {
tls.store(new_config);
info!("TLS cert regenerated for {} services", names.len());
}
Err(e) => warn!("TLS regeneration failed: {}", e),
}
}
/// Build a TLS config with a cert covering all provided service names.
/// Wildcards under single-label TLDs (*.numa) are rejected by browsers,
/// so we list each service explicitly as a SAN.