Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/nip05-egress-proxy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
---

feat(config): verify NIP-05 names through an egress proxy with a pinned address

`nip05.proxy` returns with its two modes: `disabled` (the default) connects directly and ignores `HTTPS_PROXY`, and `pin` reaches the HTTP or HTTPS proxy in `HTTPS_PROXY` with `CONNECT <address>:<port>` naming the address the relay checked, so the proxy never resolves the host; TLS runs through the tunnel with the host name as `servername`, one redirect is followed per hop with fresh pinning, and a refused CONNECT, a private address, a name mismatch or a deadline fails the verification closed.
6 changes: 6 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,12 @@ resolver 3:
`reqwest` (`default-features = false` with `rustls-tls`, so no new TLS stack) behind the
`HttpClient` seam, and tokio's `process`/`fs` for the DVM worker pipes, the onion key file
and the operator CLI's spawn seam (ADR 0015, D11). Nothing else may take those features.
`nostream-services` also owns the NIP-05 egress tunnel: `hyper`'s `client` connection,
`hyper-util`'s `TokioIo`, `http-body-util`, `rustls` + `tokio-rustls` (`ring`, no
`aws-lc-rs`) and `webpki-roots` — the same TLS stack reqwest already uses, taken directly
because reqwest's tunnel writes the host name into the CONNECT line and the port must pin
the resolved address instead (ADR 0023); `percent-encoding` and `base64` decode the
proxy URL's credentials.
The branch's other third-party additions are `aes` and `cbc`, in `nostream-core`, for the
NIP-04 body NIP-47 encrypts (ADR 0010, A23); `bech32` in `nostream-core` for NIP-19 `npub`
decoding; and `flate2` and `xz2` in `nostream-cli` for `export`'s two codecs (ADR 0015, D6).
Expand Down
6 changes: 4 additions & 2 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,8 @@ The settings below are listed in alphabetical order by name. Please keep this ta
| nip05.domainBlacklist | List of domains blocked from NIP-05 verification. Authors with NIP-05 at these domains will be rejected. |
| nip05.domainWhitelist | List of domains allowed for NIP-05 verification. If set, only authors verified at these domains can publish. |
| nip05.maxConsecutiveFailures | Number of consecutive verification failures before giving up on an author. Defaults to 20. |
| nip05.mode | NIP-05 verification mode: `enabled` requires verification, `passive` verifies without blocking, `disabled` does nothing. Defaults to `disabled`. |
| nip05.mode | NIP-05 verification mode: `enabled` requires verification, `passive` verifies without blocking, `disabled` does nothing. Defaults to `disabled`. Verification requests go out directly over HTTPS and ignore `HTTPS_PROXY` unless `nip05.proxy` is `pin`, so the relay needs direct outbound HTTPS or `nip05.proxy`; a domain or redirect target that resolves to a loopback, private or link-local address is not contacted. A change takes effect after a restart. |
| nip05.proxy | How NIP-05 verification requests reach the internet: `disabled` (default) connects directly and ignores `HTTPS_PROXY`; `pin` goes through the HTTP or HTTPS proxy in `HTTPS_PROXY` (`NO_PROXY` is not read). The relay resolves the host itself, refuses a private address, and asks the proxy for `CONNECT <address>:443` with the address it checked, then checks the certificate against the host name, a redirect target included. A proxy that refuses the `CONNECT` makes the verification fail with a reason naming the proxy and the host. With `pin` and no `HTTPS_PROXY` the connection is direct. A change to `nip05.proxy` or `HTTPS_PROXY` takes effect after a restart. |
| nip05.verifyExpiration | Time in milliseconds before a successful NIP-05 verification expires and needs re-checking. Defaults to 604800000 (1 week). |
| nip05.verifyUpdateFrequency | Minimum interval in milliseconds between re-verification attempts for a given author. Defaults to 86400000 (24 hours). |
| nip42.authRequired | When true, clients must NIP-42 AUTH as the event author before publishing events. Advertised in NIP-11 as `limitation.restricted_writes` (not `auth_required`, which means AUTH before any connection action). Defaults to false. |
Expand Down Expand Up @@ -324,7 +325,8 @@ The settings below are listed in alphabetical order by name. Please keep this ta
| nip05.domainBlacklist | List of domains blocked from NIP-05 verification. Authors with NIP-05 at these domains will be rejected. |
| nip05.domainWhitelist | List of domains allowed for NIP-05 verification. If set, only authors verified at these domains can publish. |
| nip05.maxConsecutiveFailures | Number of consecutive verification failures before giving up on an author. Defaults to 20. |
| nip05.mode | NIP-05 verification mode: `enabled` requires verification, `passive` verifies without blocking, `disabled` does nothing. Defaults to `disabled`. |
| nip05.mode | NIP-05 verification mode: `enabled` requires verification, `passive` verifies without blocking, `disabled` does nothing. Defaults to `disabled`. Verification requests go out directly over HTTPS and ignore `HTTPS_PROXY` unless `nip05.proxy` is `pin`, so the relay needs direct outbound HTTPS or `nip05.proxy`; a domain or redirect target that resolves to a loopback, private or link-local address is not contacted. A change takes effect after a restart. |
| nip05.proxy | How NIP-05 verification requests reach the internet: `disabled` (default) connects directly and ignores `HTTPS_PROXY`; `pin` goes through the HTTP or HTTPS proxy in `HTTPS_PROXY` (`NO_PROXY` is not read). The relay resolves the host itself, refuses a private address, and asks the proxy for `CONNECT <address>:443` with the address it checked, then checks the certificate against the host name, a redirect target included. A proxy that refuses the `CONNECT` makes the verification fail with a reason naming the proxy and the host. With `pin` and no `HTTPS_PROXY` the connection is direct. A change to `nip05.proxy` or `HTTPS_PROXY` takes effect after a restart. |
| nip05.verifyExpiration | Time in milliseconds before a successful NIP-05 verification expires and needs re-checking. Defaults to 604800000 (1 week). |
| nip05.verifyUpdateFrequency | Minimum interval in milliseconds between re-verification attempts for a given author. Defaults to 86400000 (24 hours). |
| paymentProcessors.lnbits.baseURL | Base URL of your Lnbits instance. |
Expand Down
9 changes: 9 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 7 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@ futures-util = "0.3"
getrandom = "0.3"
heed = { version = "0.20", features = ["read-txn-no-tls"] }
hex = "0.4.3"
hyper = { version = "1", features = ["server", "http1"] }
hyper-util = { version = "0.1", features = ["tokio", "service"] }
hkdf = "0.13.0"
hmac = "0.13.0"
http-body-util = "0.1.5"
hyper = { version = "1", features = ["server", "http1", "client"] }
hyper-util = { version = "0.1", features = ["tokio", "service"] }
negentropy = "0.5.2"
nostream-admin = { path = "crates/nostream-admin" }
nostream-cli = { path = "crates/nostream-cli" }
Expand All @@ -43,8 +44,10 @@ nostreamd = { path = "crates/nostreamd" }
opentelemetry = "0.33.1"
opentelemetry-otlp = { version = "0.33.1", default-features = false, features = ["trace", "grpc-tonic"] }
opentelemetry_sdk = { version = "0.33.1", default-features = false, features = ["trace", "rt-tokio"] }
percent-encoding = "2.3.2"
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
rmcp = { version = "3.11", features = ["server", "transport-io", "transport-async-rw"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
scrypt = "0.11"
secp256k1 = "0.33.1"
serde = { version = "1", features = ["derive"] }
Expand All @@ -55,12 +58,14 @@ sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio",
tempfile = "3"
thiserror = "2"
tokio = { version = "1", features = ["fs", "io-util", "macros", "net", "process", "rt-multi-thread", "signal", "sync", "time"] }
tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12", "logging"] }
tokio-tungstenite = { version = "0.30", features = ["connect", "handshake", "rustls-tls-webpki-roots"] }
tracing = "0.1"
tracing-opentelemetry = "0.34"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
url = "2"
uuid = { version = "1", features = ["v4"] }
webpki-roots = "1"
xz2 = "0.1"

# Nothing reads debug info here. The 66 integration-test binaries this workspace links are
Expand Down
3 changes: 3 additions & 0 deletions crates/nostream-admin/tests/route_shapes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,9 @@ async fn get_settings_answers_the_settings() {
assert_eq!(response.status, 200);
assert_json(&response);
assert_keys(&response, &["settings"]);
// Value 52 keeps a key only when the shipped defaults carry it; `nip05.proxy` is now one
// of them (job 052), so the admin view exposes it.
assert_eq!(response.json()["settings"]["nip05"]["proxy"], "disabled");
}

#[tokio::test]
Expand Down
11 changes: 11 additions & 0 deletions crates/nostream-config/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,14 @@ pub enum Nip05Mode {
Disabled,
}

/// `nip05.proxy` (`src/@types/settings.ts` `Nip05Proxy`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Nip05Proxy {
Disabled,
Pin,
}

/// `nip45` (`src/@types/settings.ts` `Nip45Settings`).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Nip45Settings {
Expand Down Expand Up @@ -708,6 +716,9 @@ pub struct Nip05Settings {
pub domain_whitelist: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub domain_blacklist: Option<Vec<String>>,
/// How verification requests reach the internet; `None` is `disabled`.
#[serde(skip_serializing_if = "Option::is_none")]
pub proxy: Option<Nip05Proxy>,
}

/// `admin.nip98` (`src/@types/settings.ts` `AdminNip98Settings`).
Expand Down
19 changes: 15 additions & 4 deletions crates/nostream-config/src/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,13 @@ pub fn validate_document(candidate: &Value, defaults: &Value) -> Vec<Issue> {
);
}

// Wrong types are the shape walk's to report; this rule is about the value.
if let Some(Value::String(proxy)) = key_path(candidate, &["nip05", "proxy"])
&& !matches!(proxy.as_str(), "disabled" | "pin")
{
issues.push(Issue::new("nip05.proxy", "proxy must be disabled or pin"));
}

// `nip66` retention, `nip77` caps, subscription plans and peering are modelled by the
// typed settings above but were not validated: the document is shared with the
// TypeScript app, which rejects these documents, so `config validate` blessing them
Expand Down Expand Up @@ -599,10 +606,14 @@ fn validate_shape(
}
_ => {
if matches!(candidate, Value::Null) && !matches!(schema, Value::Null) {
issues.push(Issue::new(
rendered,
format!("Expected {}, got null", js_typeof(schema)),
));
// `nip05.proxy: null` is unset, exactly as an absent key is (ADR 0023, D4):
// a v3 document may write it, and the typed field is `None`.
if rendered != "nip05.proxy" {
issues.push(Issue::new(
rendered,
format!("Expected {}, got null", js_typeof(schema)),
));
}
return;
}
if !matches!(schema, Value::Null) && js_typeof(schema) != js_typeof(candidate) {
Expand Down
18 changes: 18 additions & 0 deletions crates/nostream-config/tests/defaults_parity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::fs;

use nostream_config::load::merge;
use nostream_config::path::get_by_path;
use nostream_config::settings::{Nip05Proxy, Settings};
use serde_yaml::Value;

fn defaults() -> Value {
Expand Down Expand Up @@ -182,3 +183,20 @@ fn a_nip56_user_block_overrides_the_defaults() {
Value::String("a".repeat(64)),
);
}

#[test]
fn nip05_proxy_defaults_to_disabled() {
let defaults = defaults();
assert_value(
&defaults,
"nip05.proxy",
Value::String("disabled".to_owned()),
);

let settings: Settings =
serde_yaml::from_value(defaults).expect("the defaults fit the typed schema");
assert_eq!(
settings.nip05.and_then(|nip05| nip05.proxy),
Some(Nip05Proxy::Disabled)
);
}
78 changes: 78 additions & 0 deletions crates/nostream-config/tests/load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use std::path::{Path, PathBuf};

use nostream_config::load::{fit, load, load_user_settings, merge};
use nostream_config::path::get_by_path;
use nostream_config::settings::Nip05Proxy;
use nostream_config::{ConfigError, SettingsPaths, load_defaults, validate_document};
use serde_yaml::Value;
use tempfile::TempDir;
Expand Down Expand Up @@ -498,6 +499,83 @@ fn a_legacy_json_directory_is_reported_the_same_way() {
assert!(matches!(error, ConfigError::NotAFile { .. }));
}

#[test]
fn nip05_proxy_pin_loads_and_validates() {
let config_dir = TempDir::new().expect("tempdir");
write(
config_dir.path(),
"settings.yaml",
"nip05:\n mode: enabled\n proxy: pin\n",
);
let outcome = load(&paths(config_dir.path())).expect("the settings load");

assert_eq!(outcome.issues, Vec::new());
assert!(!outcome.used_defaults);
assert_eq!(
outcome.settings.nip05.and_then(|nip05| nip05.proxy),
Some(Nip05Proxy::Pin)
);
}

#[test]
fn nip05_proxy_disabled_loads_and_validates() {
let config_dir = TempDir::new().expect("tempdir");
write(
config_dir.path(),
"settings.yaml",
"nip05:\n mode: enabled\n proxy: disabled\n",
);
let outcome = load(&paths(config_dir.path())).expect("the settings load");

assert_eq!(outcome.issues, Vec::new());
assert!(!outcome.used_defaults);
assert_eq!(
outcome.settings.nip05.and_then(|nip05| nip05.proxy),
Some(Nip05Proxy::Disabled)
);
}

#[test]
fn nip05_proxy_unknown_mode_discards_the_document() {
let config_dir = TempDir::new().expect("tempdir");
write(
config_dir.path(),
"settings.yaml",
"nip05:\n mode: enabled\n proxy: env\n",
);
let outcome = load(&paths(config_dir.path())).expect("the settings load");

assert!(outcome.used_defaults);
assert_eq!(
outcome
.issues
.iter()
.map(|issue| issue.to_string())
.collect::<Vec<_>>(),
vec!["nip05.proxy: proxy must be disabled or pin"]
);
assert_eq!(
outcome.settings.nip05.and_then(|nip05| nip05.proxy),
Some(Nip05Proxy::Disabled),
"the fallback is the typed default"
);
}

#[test]
fn nip05_proxy_null_is_unset() {
let config_dir = TempDir::new().expect("tempdir");
write(
config_dir.path(),
"settings.yaml",
"nip05:\n mode: enabled\n proxy: null\n",
);
let outcome = load(&paths(config_dir.path())).expect("the settings load");

assert_eq!(outcome.issues, Vec::new());
assert!(!outcome.used_defaults);
assert_eq!(outcome.settings.nip05.expect("the section").proxy, None);
}

#[test]
fn every_float_field_is_declared_to_the_numeric_walk() {
// The walk reads a field's type off the serialized defaults, where `serialize_js_number`
Expand Down
21 changes: 21 additions & 0 deletions crates/nostream-config/tests/validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -774,6 +774,27 @@ fn accepts_a_well_formed_http_target() {
assert_eq!(issues(&document), Vec::<String>::new());
}

#[test]
fn nip05_proxy_rules() {
for patch in [
"nip05:\n mode: enabled\n proxy: disabled\n",
"nip05:\n mode: enabled\n proxy: pin\n",
"nip05:\n mode: enabled\n proxy: null\n",
"nip05:\n mode: enabled\n",
] {
assert_eq!(issues(&patched(patch)), Vec::<String>::new(), "{patch}");
}

assert_eq!(
issues(&patched("nip05:\n mode: enabled\n proxy: env\n")),
vec!["nip05.proxy: proxy must be disabled or pin"]
);
assert_eq!(
issues(&patched("nip05:\n mode: enabled\n proxy: 5\n")),
vec!["nip05.proxy: Expected string, got number"]
);
}

#[test]
fn merge_deep_right_replaces_arrays_and_null() {
let defaults: Value =
Expand Down
2 changes: 2 additions & 0 deletions crates/nostream-relay/tests/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,7 @@ async fn nip05_gates_publication() {
max_consecutive_failures: None,
domain_whitelist: Some(vec!["allowed.example".to_owned()]),
domain_blacklist: None,
proxy: None,
});

let server = start(Fixture::new(settings)).await;
Expand Down Expand Up @@ -864,6 +865,7 @@ async fn a_nip05_store_error_is_reported_as_a_failure_and_not_as_a_refusal() {
max_consecutive_failures: None,
domain_whitelist: None,
domain_blacklist: None,
proxy: None,
});

let fixture = Fixture::new(enabled);
Expand Down
8 changes: 8 additions & 0 deletions crates/nostream-services/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,26 @@ nostream-core.workspace = true
nostream-relay.workspace = true
nostream-scan.workspace = true
nostream-storage.workspace = true
base64.workspace = true
chrono.workspace = true
futures-util.workspace = true
hex.workspace = true
hmac.workspace = true
http-body-util.workspace = true
hyper.workspace = true
hyper-util.workspace = true
percent-encoding.workspace = true
reqwest.workspace = true
rustls.workspace = true
serde_json.workspace = true
sha2.workspace = true
thiserror.workspace = true
tokio.workspace = true
tokio-rustls.workspace = true
tokio-tungstenite.workspace = true
tracing.workspace = true
url.workspace = true
webpki-roots.workspace = true

[dev-dependencies]
serde_yaml.workspace = true
Expand Down
Loading
Loading