diff --git a/.changeset/relay-status-tool.md b/.changeset/relay-status-tool.md new file mode 100644 index 000000000..65bb4deeb --- /dev/null +++ b/.changeset/relay-status-tool.md @@ -0,0 +1,25 @@ +--- +--- + +feat(mcp): `relay_status`, slice 2 — the published status document and the NIP-11 builder + +A fifth MCP tool answers the relay's status: the software version, the relay process's uptime, +its live connection count, its worker rows and the NIP-11 document it advertises. The facts only +the relay process can know are not invented by the answering process — `nostreamd` publishes +`/relay-status.json` every 5 s (a 30 s freshness bound, written through a sibling `.tmp` +and a rename so no reader sees a half-written document) and the tool reads it per call. When the +document is absent, unreadable or older than the bound those values are `null` with a reason +naming the file, never `0`: a zero would read as "nothing is connected". `ConnectionCap` gains +`live_total()`, the socket count the document carries. The document also carries `relayPubkey`, +the key the daemon signs with, so the tool's NIP-11 `self` is the relay's identity rather than one +the answering process derived from its own environment. + +The NIP-11 document is built by `nostream_relay::nip11` from the settings, and every key's +presence is decided there: `supported_nip_extensions`, `supported_mips`, `payments_url`, +`peering`, `limitation.min_prefix`, `limitation.max_event_tags` and `fees.subscription` are +dropped with their reasons, `supported_nips` loses 43/50 when their switches are off and 77 +always, and `restricted_writes` folds the arms the event handler enforces. Nothing serves it +over HTTP and `nostream-cli info` is unchanged. The decisions are ADR 0016 D1–D7, which closes +`docs/rewrite/nip-parity.md` item 11. + +Rust only: no published package changes, so this entry carries no version bump. diff --git a/CLI.md b/CLI.md index f59068820..687f62fad 100644 --- a/CLI.md +++ b/CLI.md @@ -126,7 +126,7 @@ nostream info | grep 'Signing pubkey' nostream info --json # same value under relay.signingPubkey ``` -Leave `info.self` unset in settings to have this value advertised automatically. Set it only if you want to pin it explicitly, and set it to exactly this value — a mismatch disables kind 28935 invite requests. +The NIP-11 document advertises the relay's own derived signing pubkey — the value this command prints — and takes it from the daemon's status document, so it is absent while that document is missing or stale. `info.self` does not change what is advertised: it gates kind 28935 invite requests, and a configured, non-empty value must match the key the relay signs with — leaving it unset skips that check. ## Removed Legacy Wrappers diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 08269283c..764cd8dbd 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -201,7 +201,7 @@ The settings below are listed in alphabetical order by name. Please keep this ta | info.name | Public name of your relay. (e.g. TBG's Public Relay) | | info.pubkey | Relay operator's Nostr pubkey in hex format. | | info.relay_url | Public-facing URL of your relay. (e.g. wss://relay.your-domain.com) | -| info.self | Optional. The relay's own signing pubkey (hex or `npub1...`), published as `self` in the relay information document. NIP-43 clients verify relay-signed events against it, so it must match the key the relay signs with. Leave unset to derive it from `SECRET`; run `nostream info` to print the derived value. A configured value that does not match disables kind 28935 invite requests. | +| info.self | Optional. The relay's own signing pubkey (hex or `npub1...`), used to gate kind 28935 invite requests: a configured, non-empty value that does not match the key the relay signs with disables them; unset or empty skips the check. It is **not** what NIP-11 publishes — the document's `self` is the relay's derived signing pubkey, read from the daemon's status document. Run `nostream info` to print the derived value. | | info.terms_of_service | Public URL to relay terms of service. | | limits.admissionCheck.ipWhitelist | List of IPs (IPv4 or IPv6) to ignore rate limits. | | limits.admissionCheck.rateLimits[].period | Rate limit period in milliseconds. | diff --git a/Cargo.lock b/Cargo.lock index 7bb6a24d6..fb3b7f6c6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1532,6 +1532,7 @@ dependencies = [ "nostream-admin", "nostream-config", "nostream-core", + "nostream-relay", "nostream-services", "nostream-storage", "rmcp", @@ -1556,6 +1557,7 @@ dependencies = [ "nostream-config", "nostream-core", "nostream-storage", + "serde", "serde_json", "serde_yaml", "sha2 0.11.1", diff --git a/crates/nostream-admin/src/state.rs b/crates/nostream-admin/src/state.rs index 1c3921706..2149a1943 100644 --- a/crates/nostream-admin/src/state.rs +++ b/crates/nostream-admin/src/state.rs @@ -19,7 +19,7 @@ use nostream_core::nip05::Nip05Fetch; use nostream_core::random::{RandomSource, SystemRandom}; use nostream_relay::limits::{RateLimitConfig, RateLimiter, strategy_from_settings}; use nostream_services::{HttpClient, ServiceStores}; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::error::AdminError; @@ -48,7 +48,10 @@ pub const MAX_CONCURRENT_LOGIN_VERIFICATIONS: usize = 4; pub const SETTINGS_CHANGED: &str = "settings.changed"; /// One worker heartbeat (`AdminOpsWorkerHeartbeat`, `src/@types/admin-ops.ts:1-8`). -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +/// +/// `Deserialize` is the status document's reader: it validates a published heartbeat rather +/// than trusting it, and no serialized field changes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WorkerHeartbeat { pub r#type: String, diff --git a/crates/nostream-admin/src/utils/mod.rs b/crates/nostream-admin/src/utils/mod.rs index 78da01855..447641d60 100644 --- a/crates/nostream-admin/src/utils/mod.rs +++ b/crates/nostream-admin/src/utils/mod.rs @@ -13,5 +13,6 @@ pub mod nip05; pub mod password; pub mod rate_limit; pub mod session; +pub mod status; pub mod storage; pub mod workers; diff --git a/crates/nostream-admin/src/utils/status.rs b/crates/nostream-admin/src/utils/status.rs new file mode 100644 index 000000000..1d27a5238 --- /dev/null +++ b/crates/nostream-admin/src/utils/status.rs @@ -0,0 +1,163 @@ +//! The relay status document: the daemon publishes it, the MCP door reads it (ADR 0016 D1). +//! +//! It is the one artifact carrying the relay process's own facts — its uptime, its live +//! connection count, its worker rows and the key it signs with — to a process that hosts no +//! relay: heartbeats are process memory and `AdminState` holds no `Relay` handle, so a tool +//! answering from its own process would report a running relay as idle, and one deriving the +//! identity from its own environment would report a key the relay never signs with. The daemon +//! is its only writer and the MCP door its only reader, which is not ADR 0014 D18's +//! second-writer hazard — that is about `admin-audit.jsonl` and the settings write, and neither +//! is this file. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use nostream_config::SettingsPaths; +use nostream_core::Pubkey; +use serde::{Deserialize, Serialize}; + +use crate::error::AdminError; +use crate::state::{AdminState, iso8601}; +use crate::utils::workers::{self, WorkerRow}; + +/// The document's name under the config base directory. +pub const STATUS_FILE: &str = "relay-status.json"; + +/// How often the daemon rewrites the document: six writes inside the freshness bound, so one +/// missed write is still fresh, and 5 s is the coarsest cadence that makes a connection count +/// worth reading. +pub const STATUS_INTERVAL: Duration = Duration::from_millis(5_000); + +/// How old a document may be and still be reported: 30 s is fresh, 31 s is not. +pub const STATUS_TTL_SECONDS: u64 = 30; + +/// The document's keys, camelCase like the console's own `uptimeSeconds`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StatusDocument { + pub generated_at: String, + pub uptime_seconds: u64, + pub active_connections: u64, + /// The key the relay signs with, resolved by the daemon where the environment is read, so + /// the MCP door reads the relay's identity here instead of deriving one of its own. Omitted + /// when the daemon has no key source. + #[serde(skip_serializing_if = "Option::is_none")] + pub relay_pubkey: Option, + pub workers: Vec, +} + +/// A document fresh enough to report, and how old it was. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Published { + pub document: StatusDocument, + pub age_seconds: u64, +} + +/// Why there is no document to report. The reason is the caller's whole message: every one of +/// them names the file, so a reader can tell what to look at. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StatusError { + pub reason: String, +} + +/// The file's path: `/relay-status.json`, beside `admin-audit.jsonl`. +pub fn path(paths: &SettingsPaths) -> PathBuf { + paths.config_base_dir.join(STATUS_FILE) +} + +/// Assembles the document from the implementations that already exist and nothing else: the +/// state's own uptime, its clock, the console's worker rows and the identity the caller resolved. +pub fn collect( + state: &AdminState, + relay_pubkey: Option, + active_connections: u64, +) -> Result { + let settings = state.settings()?; + + Ok(StatusDocument { + generated_at: iso8601(state.clock().now_ms()), + uptime_seconds: state.uptime_seconds(), + active_connections, + relay_pubkey, + workers: workers::rows(state, &settings), + }) +} + +/// Replaces the file atomically: a sibling `.tmp` write then a rename, so a reader never sees +/// a half-written document and no `.tmp` survives a successful write. +/// +/// The parent directory is created first: the settings loader deliberately does not create it +/// (only the mutating callers do), so a daemon started against an absent config directory would +/// otherwise warn on every write and serve no document at all. The rule is the audit log's. +pub fn write(path: &Path, document: &StatusDocument) -> std::io::Result<()> { + let body = serde_json::to_vec(document).map_err(std::io::Error::other)?; + + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + + let staging = staging_path(path); + + std::fs::write(&staging, body)?; + std::fs::rename(&staging, path) +} + +/// Reads the document, at most [`STATUS_TTL_SECONDS`] old. Nothing caches it: the read happens +/// per call, so a rewrite or a deletion is in force by the next one. +pub fn read(paths: &SettingsPaths, now_ms: u64) -> Result { + let path = path(paths); + let unreadable = |error: &dyn std::fmt::Display| StatusError { + reason: format!( + "the relay status document at {} could not be read: {error}", + path.display() + ), + }; + + let raw = std::fs::read_to_string(&path).map_err(|error| { + if error.kind() == std::io::ErrorKind::NotFound { + StatusError { + reason: format!("no relay status document at {}", path.display()), + } + } else { + unreadable(&error) + } + })?; + + let document: StatusDocument = + serde_json::from_str(&raw).map_err(|error| unreadable(&error))?; + // The stamp is the reader's clock source, so its failure names the field and the value: a + // complete document with a bad stamp reported as `premature end of input` reads like a + // truncated file and sends an operator looking for the wrong thing. + let generated = chrono::DateTime::parse_from_rfc3339(&document.generated_at).map_err(|_| { + unreadable(&format_args!( + "generatedAt {:?} is not a timestamp", + document.generated_at + )) + })?; + let generated_ms = u64::try_from(generated.timestamp_millis()).unwrap_or(0); + let age_seconds = now_ms.saturating_sub(generated_ms) / 1000; + + if age_seconds > STATUS_TTL_SECONDS { + return Err(StatusError { + reason: format!( + "the relay status document at {} is {age_seconds} seconds old; the bound is \ + {STATUS_TTL_SECONDS}", + path.display() + ), + }); + } + + Ok(Published { + document, + age_seconds, + }) +} + +/// The staging file beside `path`: `.tmp`. +fn staging_path(path: &Path) -> PathBuf { + let mut name = path.as_os_str().to_owned(); + + name.push(".tmp"); + + PathBuf::from(name) +} diff --git a/crates/nostream-admin/src/utils/workers.rs b/crates/nostream-admin/src/utils/workers.rs index d10df088f..a19a631db 100644 --- a/crates/nostream-admin/src/utils/workers.rs +++ b/crates/nostream-admin/src/utils/workers.rs @@ -3,7 +3,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; use nostream_config::Settings; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use crate::state::{AdminState, HEARTBEAT_TTL_SECONDS, WorkerHeartbeat, heartbeat_key}; @@ -23,8 +23,10 @@ pub struct ConfiguredWorker { } /// One row of `GET /ops/workers` (`AdminOpsWorkerRow`). -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] +/// +/// `Deserialize` is the status document's: the MCP door validates a published row rather than +/// trusting it, and no serialized field changes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct WorkerRow { #[serde(rename = "type")] pub worker_type: String, diff --git a/crates/nostream-admin/tests/status.rs b/crates/nostream-admin/tests/status.rs new file mode 100644 index 000000000..6803a441a --- /dev/null +++ b/crates/nostream-admin/tests/status.rs @@ -0,0 +1,279 @@ +//! AC6 — the relay status document's assembly, its atomic write and its reasons. +//! +//! | case | what it proves | +//! |---|---| +//! | `the_document_carries_the_daemons_four_facts` | uptime, the connection count and the identity passed in, and the console's own worker rows | +//! | `a_daemon_without_a_key_publishes_no_identity` | no key source: no `relayPubkey` key at all | +//! | `a_written_document_reads_back` | the round trip at one instant, and no `.tmp` left behind | +//! | `a_document_at_the_bound_is_fresh_and_one_past_it_is_not` | 30 s is fresh, 31 s is not | +//! | `a_missing_document_is_a_reason` | absent: a reason naming the file | +//! | `an_unreadable_document_is_a_reason` | a wrong-typed key: a reason naming the file, not a guess | +//! | `a_malformed_generated_at_names_the_field` | a complete document with a bad stamp: a reason naming `generatedAt` | +//! | `a_missing_config_directory_is_created` | the write creates ``, as the audit log's does | +//! | `a_racing_reader_never_sees_a_partial_document` | every completed read is one whole document while a writer replaces it | + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use common::{NOW_MS, TestServer, repo_root}; +use nostream_admin::state::iso8601; +use nostream_admin::utils::status::{self, STATUS_TTL_SECONDS, StatusDocument}; +use nostream_admin::utils::workers::{self, WorkerRow}; +use nostream_config::SettingsPaths; +use nostream_core::{Clock, Pubkey}; + +/// The identity a daemon with a key source would publish. +fn relay_pubkey() -> Pubkey { + Pubkey::from_byte_array([7; 32]) +} + +#[tokio::test] +async fn the_document_carries_the_daemons_four_facts() { + let server = TestServer::start().await; + server.clock.advance(60_000); + + let document = status::collect(&server.state, Some(relay_pubkey()), 7).expect("a document"); + let settings = server.state.settings().expect("the fixture settings"); + + assert_eq!(document.uptime_seconds, 60, "the state's own age"); + assert_eq!(document.active_connections, 7, "the number passed in"); + assert_eq!( + document.workers, + workers::rows(&server.state, &settings), + "the console's rows, row for row" + ); + assert_eq!(document.generated_at, iso8601(server.clock.now_ms())); + assert_eq!( + document.relay_pubkey, + Some(relay_pubkey()), + "the identity the caller resolved" + ); +} + +/// A daemon with no key source writes no `relayPubkey`, so the reader cannot mistake a key the +/// relay does not have for one it signs with. +#[tokio::test] +async fn a_daemon_without_a_key_publishes_no_identity() { + let server = TestServer::start().await; + let document = status::collect(&server.state, None, 0).expect("a document"); + + assert_eq!(document.relay_pubkey, None); + let value = serde_json::to_value(&document).expect("a document"); + assert!(value.get("relayPubkey").is_none(), "{value}"); +} + +#[tokio::test] +async fn a_written_document_reads_back() { + let server = TestServer::start().await; + let document = status::collect(&server.state, Some(relay_pubkey()), 3).expect("a document"); + let path = status::path(server.state.paths()); + + status::write(&path, &document).expect("a write"); + let published = status::read(server.state.paths(), server.clock.now_ms()).expect("a read"); + + assert_eq!(published.document, document); + assert_eq!(published.age_seconds, 0); + + let names: Vec = std::fs::read_dir(&server.config_dir) + .expect("the config dir") + .map(|entry| { + entry + .expect("an entry") + .file_name() + .to_string_lossy() + .into_owned() + }) + .collect(); + assert!( + !names.iter().any(|name| name.ends_with(".tmp")), + "no staging file survives a successful write: {names:?}" + ); +} + +#[tokio::test] +async fn a_document_at_the_bound_is_fresh_and_one_past_it_is_not() { + let server = TestServer::start().await; + let document = status::collect(&server.state, None, 0).expect("a document"); + status::write(&status::path(server.state.paths()), &document).expect("a write"); + + let at_the_bound = NOW_MS + STATUS_TTL_SECONDS * 1_000; + let published = status::read(server.state.paths(), at_the_bound).expect("30 s is fresh"); + assert_eq!(published.age_seconds, STATUS_TTL_SECONDS); + + let past_it = NOW_MS + (STATUS_TTL_SECONDS + 1) * 1_000; + let error = status::read(server.state.paths(), past_it).expect_err("31 s is not fresh"); + + assert!( + error.reason.contains("relay-status.json"), + "{}", + error.reason + ); + assert!( + error.reason.contains("31 seconds old"), + "the reason states the age: {}", + error.reason + ); +} + +#[tokio::test] +async fn a_missing_document_is_a_reason() { + let server = TestServer::start().await; + + let error = status::read(server.state.paths(), NOW_MS).expect_err("there is no document"); + + assert!( + error.reason.contains("relay-status.json"), + "{}", + error.reason + ); + assert!( + error.reason.starts_with("no relay status document at"), + "{}", + error.reason + ); +} + +#[tokio::test] +async fn an_unreadable_document_is_a_reason() { + let server = TestServer::start().await; + std::fs::write( + status::path(server.state.paths()), + r#"{"activeConnections": "seven"}"#, + ) + .expect("a written file"); + + let error = + status::read(server.state.paths(), NOW_MS).expect_err("the document does not parse"); + + assert!( + error.reason.contains("relay-status.json"), + "{}", + error.reason + ); + assert!( + error.reason.contains("could not be read"), + "{}", + error.reason + ); +} + +/// A complete document whose `generatedAt` is not a stamp: the reason names the field and the +/// value, so an operator who hand-edited the file knows where to look. Reported as +/// `premature end of input` (chrono's text), it would read like a truncated file instead. +#[tokio::test] +async fn a_malformed_generated_at_names_the_field() { + let server = TestServer::start().await; + std::fs::write( + status::path(server.state.paths()), + r#"{"generatedAt":"not-a-timestamp","uptimeSeconds":1,"activeConnections":2,"workers":[]}"#, + ) + .expect("a written file"); + + let error = status::read(server.state.paths(), NOW_MS).expect_err("the stamp does not parse"); + + assert!( + error.reason.contains("relay-status.json"), + "{}", + error.reason + ); + assert!(error.reason.contains("generatedAt"), "{}", error.reason); + assert!( + error.reason.contains("not-a-timestamp"), + "the value an operator typed is quoted back: {}", + error.reason + ); + assert!( + !error.reason.contains("premature end of input"), + "a complete document must not read like a truncated one: {}", + error.reason + ); +} + +#[tokio::test] +async fn a_missing_config_directory_is_created() { + let temp = tempfile::tempdir().expect("a temp dir"); + let config_dir = temp.path().join("config"); + let paths = SettingsPaths::from_config_dir(&repo_root(), &config_dir); + let document = StatusDocument { + generated_at: iso8601(NOW_MS), + uptime_seconds: 1, + active_connections: 2, + relay_pubkey: Some(relay_pubkey()), + workers: Vec::new(), + }; + + assert!( + !config_dir.exists(), + "the fixture starts without a config dir" + ); + status::write(&status::path(&paths), &document).expect("the write creates the directory"); + + assert!(config_dir.is_dir(), "the write created the config dir"); + let published = status::read(&paths, NOW_MS).expect("the document reads back"); + assert_eq!(published.document, document); +} + +/// One `WorkerRow` per index, so a document's body can be made large or small on demand. +fn document_with_workers(rows: usize) -> StatusDocument { + StatusDocument { + generated_at: iso8601(NOW_MS), + uptime_seconds: 1, + active_connections: 2, + relay_pubkey: None, + workers: (0..rows) + .map(|index| WorkerRow { + worker_type: "worker".to_owned(), + index: Some(index.to_string()), + enabled: true, + label: format!("Client worker {index}"), + heartbeat: None, + monitored: false, + stale: false, + }) + .collect(), + } +} + +/// The atomic replace, seen from the outside: a writer alternates a large and a small document +/// while a reader takes every read the file allows, and every completed read is one of the two +/// whole documents. A direct `std::fs::write` truncates before it writes, so the reader meets a +/// partial document and its parse or its equality fails. +#[test] +fn a_racing_reader_never_sees_a_partial_document() { + let temp = tempfile::tempdir().expect("a temp dir"); + let paths = SettingsPaths::from_config_dir(&repo_root(), temp.path().join("config")); + let path = status::path(&paths); + let large = document_with_workers(5_000); + let small = document_with_workers(0); + + status::write(&path, &large).expect("the first document"); + + let writer = { + let path = path.clone(); + let large = large.clone(); + let small = small.clone(); + std::thread::spawn(move || { + for index in 0..400 { + let document = if index % 2 == 0 { &small } else { &large }; + status::write(&path, document).expect("a write"); + } + }) + }; + + let mut reads = 0; + while !writer.is_finished() { + let published = status::read(&paths, NOW_MS).unwrap_or_else(|error| { + panic!("a read failed during a concurrent write: {}", error.reason) + }); + assert!( + published.document == large || published.document == small, + "a read carried a whole document, not a partial one: {} workers", + published.document.workers.len() + ); + reads += 1; + } + writer.join().expect("the writer finishes"); + + assert!(reads > 0, "the reader raced at least one write"); +} diff --git a/crates/nostream-config/tests/defaults_parity.rs b/crates/nostream-config/tests/defaults_parity.rs index 18ad57e06..7cece411b 100644 --- a/crates/nostream-config/tests/defaults_parity.rs +++ b/crates/nostream-config/tests/defaults_parity.rs @@ -73,13 +73,14 @@ fn nip43_invite_rate_limit_is_per_pubkey() { } #[test] -fn info_self_is_left_unset_so_it_is_derived() { +fn info_self_is_left_unset_so_the_invite_check_is_skipped() { let defaults = defaults(); assert!( get_by_path(&defaults, "info.self") .expect("path parses") .is_none(), - "info.self must not be shipped; it is derived from SECRET" + "info.self must not be shipped; unset skips the invite check, and NIP-11's self is the \ + derived key" ); } diff --git a/crates/nostream-core/src/constants.rs b/crates/nostream-core/src/constants.rs index 69081ba6f..729c6dd27 100644 --- a/crates/nostream-core/src/constants.rs +++ b/crates/nostream-core/src/constants.rs @@ -11,9 +11,9 @@ pub const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; /// (`docs/rewrite/nip-parity.md` §2, 33 rows) plus NIP-67, whose hint this tree implements /// (§10, decision D2). Ascending, no duplicates. /// -/// Nothing serves this yet — the workspace has no HTTP listener and no NIP-11 document — so -/// the list is a decision record rather than an answer on the wire (D1). The array length is -/// the second guard: an id added without the type changing does not compile. +/// The list is built into the NIP-11 document by `nostream_relay::nip11` (ADR 0016 D4/D5) and +/// served to no client — the workspace has no HTTP listener (D1). The array length is the second +/// guard: an id added without the type changing does not compile. pub const SUPPORTED_NIPS: [u16; 34] = [ 1, 2, 3, 4, 5, 9, 11, 12, 13, 14, 16, 17, 20, 22, 25, 28, 33, 40, 42, 43, 44, 45, 50, 56, 59, 62, 65, 66, 67, 70, 77, 89, 90, 98, diff --git a/crates/nostream-mcp/Cargo.toml b/crates/nostream-mcp/Cargo.toml index fc7d64264..7a673d2b8 100644 --- a/crates/nostream-mcp/Cargo.toml +++ b/crates/nostream-mcp/Cargo.toml @@ -11,6 +11,7 @@ description = "The admin MCP server: the tool router, the credential gate and th nostream-admin.workspace = true nostream-config.workspace = true nostream-core.workspace = true +nostream-relay.workspace = true nostream-storage.workspace = true rmcp.workspace = true serde.workspace = true diff --git a/crates/nostream-mcp/src/credential.rs b/crates/nostream-mcp/src/credential.rs index 74e26fb0c..ec16fae5b 100644 --- a/crates/nostream-mcp/src/credential.rs +++ b/crates/nostream-mcp/src/credential.rs @@ -64,7 +64,7 @@ pub struct Scopes { } impl Scopes { - /// The grant a document with no `scopes` carries: the three read tools. + /// The grant a document with no `scopes` carries: the four read tools. pub fn read_only() -> Self { Self::default() } diff --git a/crates/nostream-mcp/src/lib.rs b/crates/nostream-mcp/src/lib.rs index 9ae77f90f..2f747cbd1 100644 --- a/crates/nostream-mcp/src/lib.rs +++ b/crates/nostream-mcp/src/lib.rs @@ -1,5 +1,5 @@ -//! `nostream-mcp` owns the admin MCP server: the tool router, the four slice-1 tools, the -//! credential and its scopes, and the audit sink. +//! `nostream-mcp` owns the admin MCP server: the tool router, the five tools, the credential +//! and its scopes, and the audit sink. //! //! It owns no transport and no socket. `nostreamd --mcp-stdio` serves this server on //! stdin/stdout through `rmcp`'s `transport-io`, in a process of its own: the mode composes its @@ -24,8 +24,8 @@ //! `nostream-admin` (used here, not re-implemented); //! - the settings merge, validation, redaction and the guided catalogue — `nostream-config`; //! - the event store and the repositories — `nostream-storage`; -//! - every tool family outside slice 1: `relay_status`, `delete_event`, `user_admin`, -//! `invoices_*`, `reports_*` and `maintenance_*` are later slices of #1183. +//! - every tool family outside this surface: `delete_event`, `user_admin`, `invoices_*`, +//! `reports_*` and `maintenance_*` are later slices of #1183. mod credential; mod error; @@ -38,6 +38,6 @@ pub use error::McpError; pub use server::{ AUDIT_DENIED, AdminMcp, FORBIDDEN, GetEventArgs, ListEventsArgs, MAX_FILTER_TERMS, MAX_ROWS_PER_PAGE, MCP_INSTRUCTIONS, MCP_SERVER_NAME, NOT_FOUND, Requires, SettingsSetArgs, - TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOLS, Tool, - UNAUTHORIZED, arguments_parse, audit_action, required_scope, + TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, + TOOLS, Tool, UNAUTHORIZED, arguments_parse, audit_action, required_scope, }; diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index 8d292af6c..8fe6764cf 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -1,4 +1,4 @@ -//! The MCP server: the four tools, the credential gate and the audit sink. +//! The MCP server: the five tools, the credential gate and the audit sink. //! //! Every tool is a thin handler over a seam that already exists — `AdminState` for the settings, //! `EventRepository` for the events — and nothing here knows what an HTTP status is (R3). The @@ -14,7 +14,9 @@ use std::sync::Arc; use nostream_admin::AdminState; use nostream_admin::controllers::admin_json_body_middleware::settings_patch; use nostream_admin::controllers::patch_settings::{self, SettingsWrite}; +use nostream_admin::utils::status; use nostream_core::{Filter, Kind}; +use nostream_relay::nip11; use nostream_storage::repositories::{EventRecord, collect_page, collect_records}; use rmcp::handler::server::router::tool::ToolRouter; use rmcp::handler::server::tool::ToolCallContext; @@ -44,18 +46,20 @@ pub const MCP_SERVER_NAME: &str = "nostream"; pub const MCP_INSTRUCTIONS: &str = "\ The nostream admin MCP server. Every call is decided by the scoped token document the mode was \ started with — `--admin-token-file ` or `--admin-token-fd `, exactly one, its shape \ -{\"scopes\": [\"write\"]}: the document's presence authorises `settings_get`, `list_events` and \ -`get_event`, and the \"write\" scope authorises `settings_set` (else the call is `Forbidden`). \ +{\"scopes\": [\"write\"]}: the document's presence authorises `settings_get`, `list_events`, \ +`get_event` and `relay_status`, and the \"write\" scope authorises `settings_set` (else the call \ +is `Forbidden`). \ `admin.enabled` must be true in the settings, or every call answers `Not Found`; a document \ that cannot be read answers `Unauthorized`. Each executed call appends one `mcp.` line to \ `/admin-audit.jsonl`, and a call the document's scopes deny appends one `mcp.denied` \ line."; -/// The tool names slice 1 registers (R5). Each is also its audit action's suffix (R9). +/// The tool names this surface registers (R5). Each is also its audit action's suffix (R9). pub const TOOL_SETTINGS_GET: &str = "settings_get"; pub const TOOL_SETTINGS_SET: &str = "settings_set"; pub const TOOL_LIST_EVENTS: &str = "list_events"; pub const TOOL_GET_EVENT: &str = "get_event"; +pub const TOOL_RELAY_STATUS: &str = "relay_status"; /// The most `ids` or `authors` criteria one call may carry. /// @@ -97,7 +101,7 @@ pub fn audit_action(tool: &str) -> String { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Requires { /// Reading: the grant every accepted document carries, so no scope names it and none is - /// asked for at dispatch. The three read tools say this in the table rather than leaving + /// asked for at dispatch. The four read tools say this in the table rather than leaving /// the column empty. Read, /// [`SCOPE_WRITE`]: the one scope a document may add, and the right to call `settings_set`. @@ -179,6 +183,11 @@ pub const TOOLS: &[Tool] = &[ parses: get_event_parses, needs: Requires::Read, }, + Tool { + name: TOOL_RELAY_STATUS, + parses: accepts_any_arguments, + needs: Requires::Read, + }, ]; /// `tool`'s row; `None` when the table does not name it. @@ -360,6 +369,22 @@ impl AdminMcp { } } + /// The relay's status (R9, R10): the composition's version, the facts the daemon publishes + /// and the NIP-11 document this relay advertises. + /// + /// The published document is read per call. When it is absent, unreadable or past its + /// freshness bound, every fact only the relay process can know is `null` with a reason — + /// never `0`, which would read as "nothing is connected". + #[tool( + description = "Read the relay's status: the software version, the relay process's uptime, its live connection count and its worker rows, and the NIP-11 document it advertises. Facts only the relay process can know come from the status document it publishes; when that document is absent, unreadable or older than its freshness bound they are null, and `relay.reason` says which" + )] + async fn relay_status(&self) -> CallToolResult { + match self.status_payload() { + Ok(payload) => tool_ok(payload), + Err(error) => tool_error(&error), + } + } + /// `GET /admin/settings`: the merged document narrowed to the defaults' keys and /// redacted, by the same two functions in the same order the controller uses (R11). #[tool( @@ -425,6 +450,50 @@ impl AdminMcp { Ok(serde_json::to_value(redacted)?) } + /// The `relay_status` payload: `version`, the published `relay` block and `nip11` (R10). + /// + /// The document is read per call, so nothing is cached at start. A failed read is not an + /// error: it is the payload's `reason`, with every fact the relay process alone can know + /// `null`. `nip11.self` is one of them: it is the key the published document names, never + /// one this process derived from its own environment. + fn status_payload(&self) -> Result { + let settings = self.state.settings()?; + let published = status::read(self.state.paths(), self.state.clock().now_ms()); + let signing_pubkey = published + .as_ref() + .ok() + .and_then(|published| published.document.relay_pubkey); + let nip11 = serde_json::to_value(nip11::document( + &settings, + &self.implementation.version, + signing_pubkey, + ))?; + let relay = match published { + Ok(published) => json!({ + "reason": null, + "observedAt": published.document.generated_at, + "ageSeconds": published.age_seconds, + "uptimeSeconds": published.document.uptime_seconds, + "activeConnections": published.document.active_connections, + "workers": published.document.workers, + }), + Err(error) => json!({ + "reason": error.reason, + "observedAt": null, + "ageSeconds": null, + "uptimeSeconds": null, + "activeConnections": null, + "workers": null, + }), + }; + + Ok(json!({ + "version": &self.implementation.version, + "relay": relay, + "nip11": nip11, + })) + } + /// One page, oldest first, and whether it was full. /// /// No `limit` goes to the store, because the store picks its direction from it: a filter diff --git a/crates/nostream-mcp/tests/audit.rs b/crates/nostream-mcp/tests/audit.rs index cb17965c1..1cb3f3aa2 100644 --- a/crates/nostream-mcp/tests/audit.rs +++ b/crates/nostream-mcp/tests/audit.rs @@ -2,7 +2,7 @@ //! //! | case | what it proves | //! |---|---| -//! | `each_call_appends_one_line` | four calls append five lines in call order — the four `mcp.*` lines, then `settings_set`'s own `settings.updated` | +//! | `each_call_appends_one_line` | five calls append six lines in call order — the five `mcp.*` lines, then `settings_set`'s own `settings.updated` | //! | `a_refused_call_appends_nothing` | a call with bad arguments and a call with no credential each leave the file untouched | //! | `every_registered_tool_has_a_table_row` | the table is total over the router's own list, so no tool can execute unaudited or ungated | //! | `the_audit_check_is_no_stricter_than_the_router` | the table's rule is the router's deserialiser, not the schema: a stricter check would fail open | @@ -19,7 +19,8 @@ use std::collections::BTreeSet; use common::{TestMcp, event, id_of, object, text}; use nostream_mcp::{ - TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOLS, audit_action, + TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, + TOOLS, audit_action, }; use serde_json::json; @@ -34,6 +35,7 @@ async fn each_call_appends_one_line() { client.call(TOOL_SETTINGS_GET, json!({})).await; client.call(TOOL_LIST_EVENTS, json!({})).await; client.call(TOOL_GET_EVENT, json!({ "id": id })).await; + client.call(TOOL_RELAY_STATUS, json!({})).await; let written = client .call( TOOL_SETTINGS_SET, @@ -53,6 +55,7 @@ async fn each_call_appends_one_line() { "mcp.settings_get", "mcp.list_events", "mcp.get_event", + "mcp.relay_status", "mcp.settings_set", "settings.updated", ], @@ -63,6 +66,7 @@ async fn each_call_appends_one_line() { TOOL_SETTINGS_GET, TOOL_LIST_EVENTS, TOOL_GET_EVENT, + TOOL_RELAY_STATUS, TOOL_SETTINGS_SET, ]) { assert_eq!(entry["action"], audit_action(tool)); @@ -76,14 +80,19 @@ async fn each_call_appends_one_line() { } assert_eq!( - entries[3]["detail"]["paths"], + entries[3]["detail"]["tool"], + json!(TOOL_RELAY_STATUS), + "the fourth line is the status call's own: {entries:?}" + ); + assert_eq!( + entries[4]["detail"]["paths"], json!(["wot.enabled"]), "the settings write names the paths it asked for, never the values" ); assert!( - entries[3]["detail"].get("value").is_none(), + entries[4]["detail"].get("value").is_none(), "no value is recorded: {}", - entries[3] + entries[4] ); } diff --git a/crates/nostream-mcp/tests/auth.rs b/crates/nostream-mcp/tests/auth.rs index 22c89ffcc..903a3786b 100644 --- a/crates/nostream-mcp/tests/auth.rs +++ b/crates/nostream-mcp/tests/auth.rs @@ -3,13 +3,13 @@ //! //! | case | what it proves | //! |---|---| -//! | `a_revoked_token_refuses_every_tool` | a deleted document answers `Unauthorized` to all four tools, writes nothing, and still lists them | +//! | `a_revoked_token_refuses_every_tool` | a deleted document answers `Unauthorized` to all five tools, writes nothing, and still lists them | //! | `a_read_only_token_is_refused_the_write` | a document with no scope reads and is refused `settings_set`, and the denial is a line in `admin-audit.jsonl` | //! | `a_disabled_surface_is_refused` | `admin.enabled: false` answers `Not Found`, as the console does | //! | `an_unknown_scope_refuses_the_load` | a document naming a scope the door does not know is refused when it is loaded, naming the scope and the accepted set | //! | `a_file_rewrite_changes_the_decision` | rewriting the file on a running server narrows the write, and rewriting it back restores it: the file's lifetime is the credential's | //! | `an_inherited_descriptor_authenticates` | the descriptor form answers `tools/list` and a read, and keeps the grant it was handed when the file it came from changes | -//! | `only_the_writing_tool_needs_a_scope` | the table names every registered tool and declares a scope for each: the three read tools read, `settings_set` needs `write`, and a name the table does not carry needs `write` | +//! | `only_the_writing_tool_needs_a_scope` | the table names every registered tool and declares a scope for each: the four read tools read, `settings_set` needs `write`, and a name the table does not carry needs `write` | //! | `an_unregistered_tool_is_refused_before_the_scopes` | a name the surface does not register is refused with the router's own `-32602` before the scope decision, so a read-only document writes no denial line for it | //! | `a_group_readable_descriptor_refuses_to_start` | a `0644` document on a descriptor is refused as the same file by path is | //! | `a_device_descriptor_refuses_to_start` | a device on the descriptor is refused before a byte is read, so `/dev/zero` cannot hang the start | @@ -31,14 +31,14 @@ use std::os::unix::fs::PermissionsExt; use common::{Fixture, Grant, TestMcp, text, write_token}; use nostream_mcp::{ AUDIT_DENIED, Credential, FORBIDDEN, MAX_TOKEN_DOCUMENT_BYTES, NOT_FOUND, Requires, - TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOLS, UNAUTHORIZED, - audit_action, required_scope, + TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, + TOOLS, UNAUTHORIZED, audit_action, required_scope, }; use serde_json::json; -/// The four tools, each with arguments its schema accepts, so the refusal cannot be a +/// The five tools, each with arguments its schema accepts, so the refusal cannot be a /// deserialisation failure in disguise. -fn calls() -> [(&'static str, serde_json::Value); 4] { +fn calls() -> [(&'static str, serde_json::Value); 5] { [ (TOOL_SETTINGS_GET, json!({})), ( @@ -47,6 +47,7 @@ fn calls() -> [(&'static str, serde_json::Value); 4] { ), (TOOL_LIST_EVENTS, json!({})), (TOOL_GET_EVENT, json!({ "id": "0123456789abcdef" })), + (TOOL_RELAY_STATUS, json!({})), ] } @@ -57,7 +58,7 @@ async fn a_revoked_token_refuses_every_tool() { fixture.revoke(); let client = fixture.client().await; - assert_eq!(client.tools().await.len(), 4, "tools/list is not gated"); + assert_eq!(client.tools().await.len(), 5, "tools/list is not gated"); for (tool, arguments) in calls() { let result = client.call(tool, arguments).await; assert_eq!(result.is_error, Some(true), "{tool}: {}", text(&result)); @@ -226,7 +227,7 @@ async fn an_inherited_descriptor_authenticates() { .iter() .map(|tool| tool.name.to_string()) .collect(); - assert_eq!(names.len(), 4, "{names:?}"); + assert_eq!(names.len(), 5, "{names:?}"); let read = client.call(TOOL_SETTINGS_GET, json!({})).await; assert_eq!(read.is_error, Some(false), "{}", text(&read)); @@ -274,7 +275,12 @@ async fn only_the_writing_tool_needs_a_scope() { writing.sort_unstable(); assert_eq!( reading, - vec![TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET], + vec![ + TOOL_GET_EVENT, + TOOL_LIST_EVENTS, + TOOL_RELAY_STATUS, + TOOL_SETTINGS_GET + ], "reading is the grant every document carries" ); assert_eq!( diff --git a/crates/nostream-mcp/tests/common/mod.rs b/crates/nostream-mcp/tests/common/mod.rs index ba6c0dda7..5c79e6ac5 100644 --- a/crates/nostream-mcp/tests/common/mod.rs +++ b/crates/nostream-mcp/tests/common/mod.rs @@ -70,7 +70,7 @@ pub fn base_settings() -> serde_yaml::Value { /// The scopes the fixture's token document names. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Grant { - /// `{"scopes": ["write"]}`: the three read tools and `settings_set`. + /// `{"scopes": ["write"]}`: the four read tools and `settings_set`. #[default] Write, /// `{"scopes": []}`: the read tools only — the door's default (R28). diff --git a/crates/nostream-mcp/tests/fixtures/tools_list.json b/crates/nostream-mcp/tests/fixtures/tools_list.json index 4fb5cee37..c43c083cc 100644 --- a/crates/nostream-mcp/tests/fixtures/tools_list.json +++ b/crates/nostream-mcp/tests/fixtures/tools_list.json @@ -87,6 +87,14 @@ }, "name": "list_events" }, + { + "description": "Read the relay's status: the software version, the relay process's uptime, its live connection count and its worker rows, and the NIP-11 document it advertises. Facts only the relay process can know come from the status document it publishes; when that document is absent, unreadable or older than its freshness bound they are null, and `relay.reason` says which", + "inputSchema": { + "properties": {}, + "type": "object" + }, + "name": "relay_status" + }, { "description": "Read the merged settings document, narrowed to the defaults' keys and redacted. The document arrives under `settings`", "inputSchema": { diff --git a/crates/nostream-mcp/tests/relay_status.rs b/crates/nostream-mcp/tests/relay_status.rs new file mode 100644 index 000000000..49d83c4fe --- /dev/null +++ b/crates/nostream-mcp/tests/relay_status.rs @@ -0,0 +1,342 @@ +//! AC3 — the `relay_status` oracle: the payload's two sources, the null-with-reason rule, and +//! the version's provenance, through the protocol a client uses. +//! +//! | case | what it proves | +//! |---|---| +//! | `a_published_document_is_reported` | a fresh document's four facts arrive, with `reason: null` | +//! | `no_document_reports_nothing_but_the_version_and_the_document` | no file: five nulls and a reason naming it, never a `0` | +//! | `a_stale_document_is_not_a_current_one` | a document past the 30 s bound is not a fact about the relay, and its key is no identity either | +//! | `a_corrupt_document_is_reported_not_guessed` | a wrong-typed key is a reason, not a panic or an error result | +//! | `a_zero_from_the_document_is_a_number` | a document that says `0` is reported as `0` | +//! | `the_document_is_read_at_call_time` | nothing is cached at start | +//! | `every_call_appends_its_dispatch_line` | one `mcp.relay_status` line, written before the handler | +//! | `a_read_only_document_can_read_the_status` | the row is `Requires::Read` | +//! | `self_follows_the_documents_identity_and_not_the_process` | `nip11.self` is the published key, re-read per call | +//! | `the_nip11_shape_does_not_depend_on_the_document` | present and absent documents differ only in `self` | +//! +//! The harness clock is [`NOW_MS`], so a document generated at that instant is `ageSeconds: 0`. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use std::path::Path; + +use common::{Fixture, Grant, TestMcp, payload, text}; +use nostream_mcp::TOOL_RELAY_STATUS; +use serde_json::{Value, json}; + +/// `NOW_MS` as the document's `generatedAt`. +const GENERATED_AT: &str = "2023-11-14T22:13:20.000Z"; + +/// The five facts only the relay process can know, in the payload's order. +const PUBLISHED: [&str; 5] = [ + "observedAt", + "ageSeconds", + "uptimeSeconds", + "activeConnections", + "workers", +]; + +/// The identity a daemon with a key source publishes, and one no daemon has. +const RELAY_PUBKEY: &str = "0707070707070707070707070707070707070707070707070707070707070707"; +const OTHER_PUBKEY: &str = "0808080808080808080808080808080808080808080808080808080808080808"; + +fn write_document( + config_dir: &Path, + generated_at: &str, + uptime_seconds: u64, + active_connections: u64, + relay_pubkey: Option<&str>, + workers: Value, +) { + let mut document = json!({ + "generatedAt": generated_at, + "uptimeSeconds": uptime_seconds, + "activeConnections": active_connections, + "workers": workers, + }); + if let Some(pubkey) = relay_pubkey { + document["relayPubkey"] = json!(pubkey); + } + + std::fs::write(config_dir.join("relay-status.json"), document.to_string()) + .expect("the document is written"); +} + +fn maintenance_row() -> Value { + json!([{ + "type": "maintenance", + "enabled": true, + "label": "Maintenance", + "monitored": true, + "stale": false, + }]) +} + +#[tokio::test] +async fn a_published_document_is_reported() { + let fixture = TestMcp::start().await; + write_document( + &fixture.config_dir, + GENERATED_AT, + 4_242, + 7, + Some(RELAY_PUBKEY), + maintenance_row(), + ); + let client = fixture.client().await; + + let result = client.call(TOOL_RELAY_STATUS, json!({})).await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let payload = payload(&result); + + assert_eq!(payload["relay"]["reason"], Value::Null); + assert_eq!(payload["relay"]["uptimeSeconds"], json!(4_242)); + assert_eq!(payload["relay"]["activeConnections"], json!(7)); + assert_eq!(payload["relay"]["observedAt"], json!(GENERATED_AT)); + assert_eq!(payload["relay"]["ageSeconds"], json!(0)); + assert_eq!(payload["relay"]["workers"][0]["type"], json!("maintenance")); + assert_eq!( + payload["nip11"]["self"], + json!(RELAY_PUBKEY), + "the identity the document names, not one this process derived: {payload}" + ); +} + +/// R11's shape rule: the `nip11` object does not depend on the document at all, so a present +/// and an absent one differ in `self`'s presence and in nothing else. +#[tokio::test] +async fn the_nip11_shape_does_not_depend_on_the_document() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let absent = payload(&client.call(TOOL_RELAY_STATUS, json!({})).await)["nip11"] + .as_object() + .expect("an object") + .clone(); + assert!( + !absent.contains_key("self"), + "no document, no identity: {absent:?}" + ); + + write_document( + &fixture.config_dir, + GENERATED_AT, + 1, + 0, + Some(RELAY_PUBKEY), + json!([]), + ); + let mut present = payload(&client.call(TOOL_RELAY_STATUS, json!({})).await)["nip11"] + .as_object() + .expect("an object") + .clone(); + assert_eq!( + present.remove("self"), + Some(json!(RELAY_PUBKEY)), + "the document's key, in the same field" + ); + assert_eq!( + absent, present, + "every other key is identical with and without a document" + ); +} + +/// The payload's `self` is the published document's, and it moves when the document does: a +/// process deriving its own key would answer the same value twice. +#[tokio::test] +async fn self_follows_the_documents_identity_and_not_the_process() { + let fixture = TestMcp::start().await; + write_document( + &fixture.config_dir, + GENERATED_AT, + 1, + 1, + Some(RELAY_PUBKEY), + maintenance_row(), + ); + let client = fixture.client().await; + + let first = payload(&client.call(TOOL_RELAY_STATUS, json!({})).await); + assert_eq!(first["nip11"]["self"], json!(RELAY_PUBKEY), "{first}"); + + write_document( + &fixture.config_dir, + GENERATED_AT, + 1, + 1, + Some(OTHER_PUBKEY), + maintenance_row(), + ); + let second = payload(&client.call(TOOL_RELAY_STATUS, json!({})).await); + assert_eq!( + second["nip11"]["self"], + json!(OTHER_PUBKEY), + "read at call time, like the rest of the document: {second}" + ); +} + +#[tokio::test] +async fn no_document_reports_nothing_but_the_version_and_the_document() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let result = client.call(TOOL_RELAY_STATUS, json!({})).await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let payload = payload(&result); + + for key in PUBLISHED { + assert_eq!(payload["relay"][key], Value::Null, "{key} is null"); + } + assert!( + !payload["relay"]["activeConnections"].is_number(), + "a 0 would read as \"nothing is connected\": {payload}" + ); + let reason = payload["relay"]["reason"] + .as_str() + .expect("the payload says why"); + assert!(reason.contains("relay-status.json"), "{reason}"); + assert_eq!(payload["version"], json!(env!("CARGO_PKG_VERSION"))); + assert_eq!(payload["nip11"]["name"], json!("Example")); + assert_eq!( + payload["nip11"].get("self"), + None, + "no document names no identity, and this process derives none of its own: {payload}" + ); +} + +#[tokio::test] +async fn a_stale_document_is_not_a_current_one() { + let fixture = TestMcp::start().await; + write_document( + &fixture.config_dir, + GENERATED_AT, + 4_242, + 7, + Some(RELAY_PUBKEY), + maintenance_row(), + ); + // 40 s: past the bound, and the document names an identity — which a stale one may not. + fixture.clock.advance(40_000); + let client = fixture.client().await; + + let result = client.call(TOOL_RELAY_STATUS, json!({})).await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let payload = payload(&result); + + for key in PUBLISHED { + assert_eq!(payload["relay"][key], Value::Null, "{key} is null"); + } + let reason = payload["relay"]["reason"] + .as_str() + .expect("the payload says why"); + assert!(reason.contains("relay-status.json"), "{reason}"); + assert!( + payload["nip11"].get("self").is_none(), + "a stale document's key is not an identity either: {payload}" + ); +} + +#[tokio::test] +async fn a_corrupt_document_is_reported_not_guessed() { + let fixture = TestMcp::start().await; + std::fs::write( + fixture.config_dir.join("relay-status.json"), + r#"{"activeConnections": "seven"}"#, + ) + .expect("a written file"); + let client = fixture.client().await; + + let result = client.call(TOOL_RELAY_STATUS, json!({})).await; + assert_eq!( + result.is_error, + Some(false), + "a document nobody can read is a reason, not a failure: {}", + text(&result) + ); + let payload = payload(&result); + + for key in PUBLISHED { + assert_eq!(payload["relay"][key], Value::Null, "{key} is null"); + } + assert!(payload["relay"]["reason"].is_string(), "{payload}"); +} + +#[tokio::test] +async fn a_zero_from_the_document_is_a_number() { + let fixture = TestMcp::start().await; + write_document(&fixture.config_dir, GENERATED_AT, 0, 0, None, json!([])); + let client = fixture.client().await; + + let result = client.call(TOOL_RELAY_STATUS, json!({})).await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let payload = payload(&result); + + assert_eq!( + payload["relay"]["activeConnections"], + json!(0), + "the document says zero, so the payload does: {payload}" + ); + assert_eq!(payload["relay"]["ageSeconds"], json!(0)); + assert!(payload["relay"]["activeConnections"].is_number()); +} + +#[tokio::test] +async fn the_document_is_read_at_call_time() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let before = payload(&client.call(TOOL_RELAY_STATUS, json!({})).await); + assert_eq!(before["relay"]["activeConnections"], Value::Null); + + write_document( + &fixture.config_dir, + GENERATED_AT, + 4_242, + 7, + Some(RELAY_PUBKEY), + maintenance_row(), + ); + + let after = payload(&client.call(TOOL_RELAY_STATUS, json!({})).await); + assert_eq!( + after["relay"]["uptimeSeconds"], + json!(4_242), + "nothing was cached at start: {after}" + ); + assert_eq!(after["relay"]["reason"], Value::Null); +} + +#[tokio::test] +async fn every_call_appends_its_dispatch_line() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + client.call(TOOL_RELAY_STATUS, json!({})).await; + + let entries = fixture.audit_entries(); + assert_eq!(entries.len(), 1, "{entries:?}"); + assert_eq!(entries[0]["action"], json!("mcp.relay_status")); + assert_eq!(entries[0]["detail"]["tool"], json!("relay_status")); + assert!( + entries[0].get("remoteAddress").is_none(), + "a stdio caller has no address: {}", + entries[0] + ); +} + +#[tokio::test] +async fn a_read_only_document_can_read_the_status() { + let fixture = TestMcp::start_with(Fixture { + grant: Grant::Read, + ..Fixture::default() + }) + .await; + let client = fixture.client().await; + + let result = client.call(TOOL_RELAY_STATUS, json!({})).await; + + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + assert!(payload(&result)["relay"]["reason"].is_string()); +} diff --git a/crates/nostream-mcp/tests/tools_list.rs b/crates/nostream-mcp/tests/tools_list.rs index 63a82e182..76bcc76f9 100644 --- a/crates/nostream-mcp/tests/tools_list.rs +++ b/crates/nostream-mcp/tests/tools_list.rs @@ -18,7 +18,8 @@ mod common; use common::TestMcp; use nostream_mcp::{ - MAX_ROWS_PER_PAGE, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, + MAX_ROWS_PER_PAGE, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_SETTINGS_GET, + TOOL_SETTINGS_SET, }; use serde_json::{Value, json}; @@ -174,10 +175,11 @@ async fn the_required_parameters_are_typed() { vec![ TOOL_GET_EVENT, TOOL_LIST_EVENTS, + TOOL_RELAY_STATUS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET ], - "the four slice-1 tools, name-sorted" + "the five tools, name-sorted" ); } @@ -212,6 +214,7 @@ async fn initialize_publishes_the_prerequisites() { "admin.enabled", "write", "mcp.denied", + TOOL_RELAY_STATUS, ] { assert!( instructions.contains(needle), diff --git a/crates/nostream-relay/Cargo.toml b/crates/nostream-relay/Cargo.toml index d153dd905..6f96c49b0 100644 --- a/crates/nostream-relay/Cargo.toml +++ b/crates/nostream-relay/Cargo.toml @@ -15,6 +15,7 @@ hmac.workspace = true nostream-config.workspace = true nostream-core.workspace = true nostream-storage.workspace = true +serde.workspace = true serde_json.workspace = true sha2.workspace = true thiserror.workspace = true diff --git a/crates/nostream-relay/src/connection_cap.rs b/crates/nostream-relay/src/connection_cap.rs index 486413935..3b0f946ed 100644 --- a/crates/nostream-relay/src/connection_cap.rs +++ b/crates/nostream-relay/src/connection_cap.rs @@ -56,6 +56,15 @@ impl ConnectionCap { .len() } + /// How many sockets every address holds together: the sum of the per-address counts. + pub fn live_total(&self) -> usize { + self.live + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .values() + .sum() + } + /// How many sockets were refused because their address was at the cap. pub fn refusals(&self) -> u64 { self.refusals.load(Ordering::SeqCst) diff --git a/crates/nostream-relay/src/lib.rs b/crates/nostream-relay/src/lib.rs index cf3446bcc..ea17a4c6f 100644 --- a/crates/nostream-relay/src/lib.rs +++ b/crates/nostream-relay/src/lib.rs @@ -36,8 +36,9 @@ //! may be re-cut). `broadcast.rs` therefore carries no behaviour; the in-process fan-out this //! crate needs is the relay's own broadcast channel. //! -//! Phase 2+ areas this crate does not own: the HTTP surface and NIP-11 document -//! (`nostream-admin`), and the probe family and NIP-66 monitor (`nostream-services`). +//! Phase 2+ areas this crate does not own: the HTTP surface (`nostream-admin`) and the probe +//! family and NIP-66 monitor (`nostream-services`). The NIP-11 document's builder is this +//! crate's ([`nip11`]); nothing serves it yet (D1). //! //! The event acceptance gate this crate owns is the *policy*: the kind-specific tag rules, //! which `created_at` deltas the settings supply, and where the check runs. The pure @@ -52,6 +53,7 @@ pub mod error; pub mod handlers; pub mod hidden_content; pub mod limits; +pub mod nip11; pub mod relay; pub mod relay_key; pub mod sink; diff --git a/crates/nostream-relay/src/nip11.rs b/crates/nostream-relay/src/nip11.rs new file mode 100644 index 000000000..8c05e447f --- /dev/null +++ b/crates/nostream-relay/src/nip11.rs @@ -0,0 +1,366 @@ +//! The NIP-11 relay information document: every key's presence decided here. +//! +//! Mirrors the capture's one object literal +//! (`src/handlers/request-handlers/root-request-handler.ts:116-210`), audited field by field +//! at `docs/rewrite/nip-parity.md:717-767`, with the field-set verdicts recorded in ADR 0016 +//! D4. Nothing serves it: `nostream-cli info` builds its own payload and the HTTP surface is +//! still shut (D1), so this module is the builder a surface will adopt, not a route. +//! `info` keeps its own assembly because its output is pinned byte for byte and carries no +//! document, so sharing this builder would buy it nothing and put the pin at risk. +//! +//! The rule behind the drops is the audit's: advertise what the relay enforces. +//! `max_filters` and `max_filter_values` stay because `subscribe.rs` and `count.rs` check +//! them; `min_prefix` and `max_event_tags` go because nothing does; `supported_nip_extensions`, +//! `supported_mips` and `fees.subscription` have no Rust source at all, and `payments_url` and +//! `peering` name surfaces this relay does not serve. + +use nostream_config::settings::{ContentLimitsOrVec, EventLimits, FeeSchedule, Settings}; +use nostream_core::Pubkey; +use nostream_core::constants::SUPPORTED_NIPS; +use nostream_storage::DEFAULT_PAGE_ROWS; +use serde::Serialize; + +use crate::error::RelayError; + +/// The NIP-11 document, in the capture's key order. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct RelayInformationDocument { + pub name: String, + pub description: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub banner: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub icon: Option, + pub pubkey: String, + /// The key the relay signs with, for NIP-43 clients: the published status document's + /// `relayPubkey`, and absent when no fresh document names one. + #[serde(rename = "self", skip_serializing_if = "Option::is_none")] + pub self_: Option, + pub contact: String, + pub supported_nips: Vec, + pub software: String, + pub version: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub terms_of_service: Option, + pub limitation: Limitation, + pub fees: Fees, +} + +/// The `limitation` block: the bounds this relay enforces, and nothing it does not. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Limitation { + /// `nostream_relay::transport::max_payload_size`: the number the websocket enforces. + pub max_message_length: u64, + /// `limits.client.subscription.*`; a configured `0` means "no cap" to the checks that + /// read it, so it is omitted rather than advertised as "none allowed". + #[serde(skip_serializing_if = "Option::is_none")] + pub max_subscriptions: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub max_filters: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub max_filter_values: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub max_limit: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub max_subid_length: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub max_content_length: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub min_pow_difficulty: Option, + /// The capture's deliberate split: `auth_required` means AUTH before any action, and this + /// relay only gates publishes (`nip42.authRequired`, advertised as `restricted_writes`). + pub auth_required: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_required: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub created_at_lower_limit: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub created_at_upper_limit: Option, + /// The page a limit-less read materialises in both backends. + pub default_limit: u64, + pub restricted_writes: bool, + pub search_supported: bool, +} + +/// The `fees` block: the enabled fee schedules, in msats. `publication` is omitted when the +/// settings omit it; `admission` is always an array. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Fees { + pub admission: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub publication: Option>, +} + +/// One fee entry (`{ amount, unit }`, the capture's shape). +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Fee { + pub amount: i64, + pub unit: String, +} + +/// The document for these settings, this version and the identity the published document names. +/// +/// `relay_pubkey` is the only source of `self`: with no fresh status document there is no +/// identity, and a settings value or the answering process's environment would be a key the +/// relay may not sign with (R11). +pub fn document( + settings: &Settings, + version: &str, + relay_pubkey: Option, +) -> RelayInformationDocument { + let info = &settings.info; + + RelayInformationDocument { + name: info.name.clone(), + description: info.description.clone(), + banner: info.banner.clone(), + icon: info.icon.clone(), + pubkey: hex_or_written(&info.pubkey), + self_: relay_pubkey.map(|pubkey| pubkey.to_string()), + contact: info.contact.clone(), + supported_nips: supported_nips(settings), + software: env!("CARGO_PKG_REPOSITORY").to_owned(), + version: version.to_owned(), + terms_of_service: info.terms_of_service.clone(), + limitation: limitation(settings), + fees: fees(settings), + } +} + +/// `hasWriteRestriction`: the arms the event handler enforces, and no others. +/// +/// The capture's subscription arm is not ported — nothing in the rewrite enforces +/// subscriptions, so a configured plan does not make this true. +pub fn restricted_writes(settings: &Settings) -> bool { + let payments = settings + .payments + .as_ref() + .filter(|payments| payments.enabled); + let admission_fee = payments.is_some_and(|payments| { + payments + .fee_schedules + .admission + .iter() + .any(|schedule| schedule.enabled) + }); + let nip43 = settings.nip43.as_ref().is_some_and(|nip43| nip43.enabled); + let auth_required = settings + .nip42 + .as_ref() + .and_then(|nip42| nip42.auth_required) + .unwrap_or(false); + + let event = settings + .limits + .as_ref() + .and_then(|limits| limits.event.as_ref()); + let event_id_bits = event + .and_then(|event| event.event_id.as_ref()) + .and_then(|event_id| event_id.min_leading_zero_bits) + .unwrap_or(0); + let pubkey_bits = event + .and_then(|event| event.pubkey.as_ref()) + .map_or(0, |pubkey| pubkey.min_leading_zero_bits); + let pow = event + .and_then(|event| event.pow.as_ref()) + .is_some_and(|pow| pow.enabled); + let pubkeys_listed = event + .and_then(|event| event.pubkey.as_ref()) + .is_some_and(|pubkey| { + pubkey + .whitelist + .as_ref() + .is_some_and(|list| !list.is_empty()) + || pubkey + .blacklist + .as_ref() + .is_some_and(|list| !list.is_empty()) + }); + let kinds_listed = event + .and_then(|event| event.kind.as_ref()) + .is_some_and(|kind| { + kind.whitelist.as_ref().is_some_and(|list| !list.is_empty()) + || kind.blacklist.as_ref().is_some_and(|list| !list.is_empty()) + }); + + admission_fee + || nip43 + || auth_required + || event_id_bits > 0 + || pubkey_bits > 0 + || pow + || pubkeys_listed + || kinds_listed +} + +/// `parseRelayPubkey`: 64 hex characters lowercased, an `npub1…` decoded, anything else +/// nothing, and an `npub` that does not decode an error. +pub fn parse_relay_pubkey(value: Option<&str>) -> Result, RelayError> { + let Some(value) = value.filter(|value| !value.is_empty()) else { + return Ok(None); + }; + + if value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return parse_hex(value).map(Some); + } + + if value.to_lowercase().starts_with("npub1") { + let hex = nostream_core::nip19::decode_npub_hex(value).map_err(|error| { + RelayError::Configuration(format!( + "info.self npub did not decode to a 32-byte pubkey: {error}" + )) + })?; + + return parse_hex(&hex).map(Some); + } + + Ok(None) +} + +fn parse_hex(value: &str) -> Result { + value + .to_lowercase() + .parse::() + .map_err(|error| RelayError::Configuration(error.to_string())) +} + +/// `info.pubkey` as the document carries it: hex lowercased, an `npub` decoded, and a value +/// that is neither left exactly as written (the capture's `rawPubkey`). +fn hex_or_written(value: &str) -> String { + match parse_relay_pubkey(Some(value)) { + Ok(Some(pubkey)) => pubkey.to_string(), + _ => value.to_owned(), + } +} + +/// `SUPPORTED_NIPS` in its own order, minus what does not run: 43 without NIP-43 enabled, 50 +/// without NIP-50 enabled, and 77 always (its handler is a stub). +fn supported_nips(settings: &Settings) -> Vec { + let nip43 = settings.nip43.as_ref().is_some_and(|nip43| nip43.enabled); + let nip50 = settings + .nip50 + .as_ref() + .and_then(|nip50| nip50.enabled) + .unwrap_or(false); + + SUPPORTED_NIPS + .iter() + .copied() + .filter(|nip| *nip != 77 && (*nip != 43 || nip43) && (*nip != 50 || nip50)) + .collect() +} + +fn limitation(settings: &Settings) -> Limitation { + let event = settings + .limits + .as_ref() + .and_then(|limits| limits.event.as_ref()); + let subscription = settings + .limits + .as_ref() + .and_then(|limits| limits.client.as_ref()) + .and_then(|client| client.subscription.as_ref()); + + Limitation { + max_message_length: u64::try_from(crate::transport::max_payload_size(settings)) + .unwrap_or(u64::MAX), + max_subscriptions: configured(subscription.and_then(|limits| limits.max_subscriptions)), + max_filters: configured(subscription.and_then(|limits| limits.max_filters)), + max_filter_values: configured(subscription.and_then(|limits| limits.max_filter_values)), + max_limit: configured(subscription.and_then(|limits| limits.max_limit)), + max_subid_length: configured( + subscription.and_then(|limits| limits.max_subscription_id_length), + ), + max_content_length: content_length(event.and_then(|event| event.content.as_ref())), + min_pow_difficulty: min_pow_difficulty(event), + auth_required: false, + payment_required: settings.payments.as_ref().map(|payments| payments.enabled), + created_at_lower_limit: event + .and_then(|event| event.created_at.as_ref()) + .and_then(|created_at| created_at.max_negative_delta), + created_at_upper_limit: event + .and_then(|event| event.created_at.as_ref()) + .and_then(|created_at| created_at.max_positive_delta), + default_limit: DEFAULT_PAGE_ROWS, + restricted_writes: restricted_writes(settings), + search_supported: settings + .nip50 + .as_ref() + .and_then(|nip50| nip50.enabled) + .unwrap_or(false), + } +} + +/// A configured client limit; `0` means "no cap" to the checks that read it, so it is omitted. +fn configured(limit: Option) -> Option { + limit.filter(|limit| *limit > 0) +} + +/// A list of content rules yields its first entry's bound, the capture's own rule. +fn content_length(content: Option<&ContentLimitsOrVec>) -> Option { + match content? { + ContentLimitsOrVec::One(limit) => limit.max_length, + ContentLimitsOrVec::Many(limits) => limits.first().and_then(|limit| limit.max_length), + } +} + +/// The lowest difficulty any client may be accepted at: what `required_difficulty` enforces. +/// +/// That function passes `None` as the WoT distance (`handlers/event.rs:371`) because the graph is +/// `nostream-services`' and no crate supplies one yet, and with no distance +/// `apply_wot_pow_policy` answers the computed difficulty unchanged +/// (`nostream_core::adaptive_pow`), which is `floor_bits` at rest. The capture's +/// `ceil(floor_bits × difficulty_factor)` discount is therefore granted to nobody here: it only +/// applies once a distance exists, so advertising it would promise a bound the handler rejects. +/// With the adaptive check off, the static event-id floor is the enforced one. +fn min_pow_difficulty(event: Option<&EventLimits>) -> Option { + let pow = event + .and_then(|event| event.pow.as_ref()) + .filter(|pow| pow.enabled); + let difficulty = match pow { + Some(pow) => u64::from(pow.floor_bits), + None => u64::from( + event + .and_then(|event| event.event_id.as_ref()) + .and_then(|event_id| event_id.min_leading_zero_bits) + .unwrap_or(0), + ), + }; + + (difficulty > 0).then_some(difficulty) +} + +/// The enabled fee schedules, and only while payments are on — the predicate the admission +/// check applies. +fn fees(settings: &Settings) -> Fees { + let Some(payments) = settings + .payments + .as_ref() + .filter(|payments| payments.enabled) + else { + return Fees { + admission: Vec::new(), + publication: None, + }; + }; + + Fees { + admission: schedule_fees(&payments.fee_schedules.admission), + publication: payments + .fee_schedules + .publication + .as_deref() + .map(schedule_fees), + } +} + +fn schedule_fees(schedules: &[FeeSchedule]) -> Vec { + schedules + .iter() + .filter(|schedule| schedule.enabled) + .map(|schedule| Fee { + amount: schedule.amount, + unit: "msats".to_owned(), + }) + .collect() +} diff --git a/crates/nostream-relay/tests/handlers.rs b/crates/nostream-relay/tests/handlers.rs index 341184649..35b7fbb74 100644 --- a/crates/nostream-relay/tests/handlers.rs +++ b/crates/nostream-relay/tests/handlers.rs @@ -20,9 +20,9 @@ use std::time::Duration; use common::{CLIENT_SECRET, NOW_MS, NOW_SECS, RELAY_SECRET, Server, relay_keys, signed_event}; use nostream_config::settings::{ - ClientLimits, ClientSubscriptionLimits, ConnectionLimits, CreatedAtLimits, EventIdLimits, - EventLimits, EventRateLimit, KindLimits, Limits, MessageLimits, MessageRateLimit, - Nip05Settings, Payments, PubkeyLimits, RateLimit, + AdaptivePowSettings, ClientLimits, ClientSubscriptionLimits, ConnectionLimits, CreatedAtLimits, + EventIdLimits, EventLimits, EventRateLimit, KindLimits, Limits, MessageLimits, + MessageRateLimit, Nip05Settings, Payments, PubkeyLimits, RateLimit, WotPowThreshold, }; use nostream_core::Event; use nostream_core::clock::TestClock; @@ -384,6 +384,46 @@ async fn the_static_proof_of_work_requirements_are_enforced() { ); } +/// The advertised floor and the enforced floor are one value, measured at both ends from one +/// settings document: a WoT discount is configured and there is no distance to grant it at, so +/// the handler requires `floor_bits` and the document advertises the same number. A change to +/// either end alone — the handler learning a distance, or the document reading the factor — +/// reddens this case. +#[tokio::test] +async fn the_advertised_minimum_difficulty_is_the_one_enforced() { + let configured = settings_with(event_limits(EventLimits { + pow: Some(AdaptivePowSettings { + enabled: true, + floor_bits: 16, + ceiling_bits: 32, + target_events_per_second: 50.0, + period_ms: 60_000, + wot_thresholds: Some(vec![WotPowThreshold { + max_distance: 2, + difficulty_factor: 0.5, + }]), + }), + ..Default::default() + })); + let server = start(Fixture::new(configured.clone())).await; + let event = signed_event(&CLIENT_SECRET, 1, vec![], "", NOW_SECS); + + let frame = send_event(&server, &event).await; + + let observed = nostream_core::pow::leading_zero_bits(event.id.as_bytes()); + assert!( + frame.ends_with(&format!(r#"false,"pow: difficulty {observed}<16"]"#)), + "the handler requires the floor, not the capture's discounted 8: {frame}" + ); + + let document = nostream_relay::nip11::document(&configured, "0.1.0", None); + assert_eq!( + serde_json::to_value(document).expect("document json")["limitation"]["min_pow_difficulty"], + serde_json::json!(16), + "the document advertises the number the handler just required" + ); +} + #[tokio::test] async fn pubkey_whitelist_and_blacklist_block() { use nostream_core::SettingsPubkey; diff --git a/crates/nostream-relay/tests/nip11.rs b/crates/nostream-relay/tests/nip11.rs new file mode 100644 index 000000000..cc488cd35 --- /dev/null +++ b/crates/nostream-relay/tests/nip11.rs @@ -0,0 +1,501 @@ +//! AC4 — the NIP-11 document's decided field set, one case per decision. +//! +//! | case | what it proves | +//! |---|---| +//! | `the_key_set_is_the_decided_one` | the nine always-present keys, the four kept-when-set keys, and every dropped key absent | +//! | `supported_nips_is_the_advertised_set_filtered_by_what_runs` | 43/50 follow their switches, 77 never appears, and the order is `SUPPORTED_NIPS`'s | +//! | `the_limitation_block_reports_the_enforced_limits` | the enforced numbers, and a configured `0` omitted | +//! | `restricted_writes_folds_the_arms_the_event_handler_enforces` | each arm alone flips it; the all-off fixture is false; a subscription plan alone does not | +//! | `fees_reports_enabled_schedules_in_msats` | enabled schedules only, `publication` only when configured, empty under `payments.enabled: false` | +//! | `self_is_the_published_identity_or_absent` | the published key wins over `info.self`; no key means no `self` | +//! | `the_version_and_software_are_the_callers` | the version argument, the workspace repository, and a hex `pubkey` | +//! +//! The fixture is the shipped `resources/default-settings.yaml`, typed through the settings +//! loader: its numbers are the ones AC4 names. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::Path; + +use nostream_config::settings::{ + EventIdLimits, FeeSchedule, Settings, SubscriptionPlan, WotPowThreshold, +}; +use nostream_core::constants::SUPPORTED_NIPS; +use nostream_core::{Kind, KindSelector, Pubkey, SettingsPubkey}; +use nostream_relay::nip11; +use serde_json::{Value, json}; + +/// The fixture pair the NIP-19 decoder's own tests use. +const NPUB: &str = "npub1yt5qf5nw694k3k6jt8ncgj0fdk4463jv3arshk37kxnsgeljc7fsmhwffw"; +const HEX: &str = "22e804d26ed16b68db5259e78449e96dab5d464c8f470bda3eb1a70467f2c793"; +/// A second key, so "the configured value wins" is distinguishable from "the signing key". +const OTHER: &str = "9d1e2f3a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f6"; + +fn shipped() -> Settings { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../resources/default-settings.yaml"); + let raw = std::fs::read_to_string(&path) + .unwrap_or_else(|error| panic!("the shipped defaults {}: {error}", path.display())); + let document: serde_yaml::Value = serde_yaml::from_str(&raw).expect("the defaults are YAML"); + nostream_config::fit(&document, &document).expect("the shipped defaults fit their own schema") +} + +/// The shipped settings with the four conditional top-level keys unset. +fn minimal() -> Settings { + let mut settings = shipped(); + settings.info.banner = None; + settings.info.icon = None; + settings.info.self_ = None; + settings.info.terms_of_service = None; + settings +} + +fn value(settings: &Settings, version: &str, relay_pubkey: Option) -> Value { + serde_json::to_value(nip11::document(settings, version, relay_pubkey)).expect("a document") +} + +fn advertised(document: &Value) -> Vec { + document["supported_nips"] + .as_array() + .expect("an array") + .iter() + .map(|nip| u16::try_from(nip.as_u64().expect("a number")).expect("a NIP id")) + .collect() +} + +#[test] +fn the_key_set_is_the_decided_one() { + let document = value(&minimal(), "0.1.0", None); + let mut keys: Vec<&str> = document + .as_object() + .expect("an object") + .keys() + .map(String::as_str) + .collect(); + keys.sort_unstable(); + assert_eq!( + keys, + vec![ + "contact", + "description", + "fees", + "limitation", + "name", + "pubkey", + "software", + "supported_nips", + "version", + ], + "the nine always-present keys: {document}" + ); + + let mut supplied = minimal(); + supplied.info.banner = Some("https://example.com/banner.png".to_owned()); + supplied.info.icon = Some("https://example.com/icon.png".to_owned()); + supplied.info.terms_of_service = Some("https://example.com/terms".to_owned()); + let document = value(&supplied, "0.1.0", Some(OTHER.parse().unwrap())); + + for key in ["banner", "icon", "self", "terms_of_service"] { + assert!( + document.get(key).is_some(), + "{key} is present when the fixture supplies it: {document}" + ); + } + + for key in [ + "supported_nip_extensions", + "supported_mips", + "payments_url", + "peering", + ] { + assert!(document.get(key).is_none(), "{key} is dropped: {document}"); + } + for key in ["max_event_tags", "min_prefix"] { + assert!( + document["limitation"].get(key).is_none(), + "limitation.{key} is dropped: {document}" + ); + } + assert!( + document["fees"].get("subscription").is_none(), + "fees.subscription is dropped: {document}" + ); +} + +#[test] +fn supported_nips_is_the_advertised_set_filtered_by_what_runs() { + let mut settings = shipped(); + settings.nip43.as_mut().expect("the shipped nip43").enabled = true; + settings.nip50.as_mut().expect("the shipped nip50").enabled = Some(true); + + let document = value(&settings, "0.1.0", None); + let list = advertised(&document); + assert!(list.contains(&43), "43 runs: {list:?}"); + assert!(list.contains(&50), "50 runs: {list:?}"); + assert!(!list.contains(&77), "77 is a stub and never advertised"); + let expected: Vec = SUPPORTED_NIPS + .iter() + .copied() + .filter(|nip| *nip != 77) + .collect(); + assert_eq!( + list, expected, + "the advertised list keeps SUPPORTED_NIPS's order" + ); + + let mut settings = shipped(); + settings.nip43.as_mut().expect("the shipped nip43").enabled = false; + settings.nip50.as_mut().expect("the shipped nip50").enabled = Some(false); + + let document = value(&settings, "0.1.0", None); + let list = advertised(&document); + assert!(!list.contains(&43), "43 does not run: {list:?}"); + assert!(!list.contains(&50), "50 does not run: {list:?}"); + assert!(list.contains(&11) && list.contains(&98), "{list:?}"); + let expected: Vec = SUPPORTED_NIPS + .iter() + .copied() + .filter(|nip| !matches!(nip, 43 | 50 | 77)) + .collect(); + assert_eq!(list, expected); +} + +#[test] +fn the_limitation_block_reports_the_enforced_limits() { + let settings = shipped(); + let document = value(&settings, "0.1.0", None); + let limitation = &document["limitation"]; + + assert_eq!( + limitation["max_message_length"], + json!(nostream_relay::transport::max_payload_size(&settings) as u64), + "the number the transport enforces, not a second constant" + ); + assert_eq!(limitation["max_message_length"], json!(524_288)); + assert_eq!(limitation["max_subscriptions"], json!(10)); + assert_eq!(limitation["max_filters"], json!(10)); + assert_eq!(limitation["max_filter_values"], json!(2_500)); + assert_eq!(limitation["max_limit"], json!(5_000)); + assert_eq!(limitation["max_subid_length"], json!(256)); + assert_eq!(limitation["max_content_length"], json!(102_400)); + assert_eq!(limitation["default_limit"], json!(500)); + assert_eq!(limitation["auth_required"], json!(false)); + assert_eq!(limitation["search_supported"], json!(false)); + assert!( + limitation.get("min_pow_difficulty").is_none(), + "a zero floor is not advertised: {limitation}" + ); + + let mut zeroed = shipped(); + zeroed + .limits + .as_mut() + .unwrap() + .client + .as_mut() + .unwrap() + .subscription + .as_mut() + .unwrap() + .max_filters = Some(0); + let document = value(&zeroed, "0.1.0", None); + assert!( + document["limitation"].get("max_filters").is_none(), + "0 means no cap to the checks that read it, so it is omitted: {document}" + ); + + // The difficulty is the handler's answer with no WoT distance, not the capture's discount: + // a floor of 16 with a `maxDistance: 2, difficultyFactor: 0.5` threshold is enforced at 16, + // and `required_difficulty` passes `None` for the distance, so the × factor applies to nobody. + let mut enforced = shipped(); + { + let pow = enforced + .limits + .as_mut() + .unwrap() + .event + .as_mut() + .unwrap() + .pow + .as_mut() + .unwrap(); + pow.enabled = true; + pow.floor_bits = 16; + pow.wot_thresholds = Some(vec![WotPowThreshold { + max_distance: 2, + difficulty_factor: 0.5, + }]); + } + let document = value(&enforced, "0.1.0", None); + assert_eq!( + document["limitation"]["min_pow_difficulty"], + json!(16), + "the floor the handler enforces, not the capture's 8: {document}" + ); +} + +/// The shipped defaults with every write-restriction arm off. +fn all_arms_off() -> Settings { + let mut settings = shipped(); + let event = settings.limits.as_mut().unwrap().event.as_mut().unwrap(); + event.event_id = Some(EventIdLimits { + min_leading_zero_bits: Some(0), + }); + let pubkey = event.pubkey.as_mut().unwrap(); + pubkey.min_leading_zero_bits = 0; + pubkey.whitelist = Some(Vec::new()); + pubkey.blacklist = Some(Vec::new()); + let kind = event.kind.as_mut().unwrap(); + kind.whitelist = Some(Vec::new()); + kind.blacklist = Some(Vec::new()); + event.pow.as_mut().unwrap().enabled = false; + settings +} + +#[test] +fn restricted_writes_folds_the_arms_the_event_handler_enforces() { + assert!( + !nip11::restricted_writes(&all_arms_off()), + "the all-off fixture restricts nothing" + ); + + let mut arms: Vec<(&str, Settings)> = Vec::new(); + + let mut admission = all_arms_off(); + { + let payments = admission.payments.as_mut().unwrap(); + payments.enabled = true; + payments.fee_schedules.admission[0].enabled = true; + } + arms.push(("an enabled admission fee under payments.enabled", admission)); + + let mut nip43 = all_arms_off(); + nip43.nip43.as_mut().unwrap().enabled = true; + arms.push(("nip43.enabled", nip43)); + + let mut auth = all_arms_off(); + auth.nip42.as_mut().unwrap().auth_required = Some(true); + arms.push(("nip42.authRequired", auth)); + + let mut event_id = all_arms_off(); + event_id + .limits + .as_mut() + .unwrap() + .event + .as_mut() + .unwrap() + .event_id = Some(EventIdLimits { + min_leading_zero_bits: Some(1), + }); + arms.push(("eventId.minLeadingZeroBits", event_id)); + + let mut pubkey_bits = all_arms_off(); + pubkey_bits + .limits + .as_mut() + .unwrap() + .event + .as_mut() + .unwrap() + .pubkey + .as_mut() + .unwrap() + .min_leading_zero_bits = 1; + arms.push(("pubkey.minLeadingZeroBits", pubkey_bits)); + + let mut pow = all_arms_off(); + pow.limits + .as_mut() + .unwrap() + .event + .as_mut() + .unwrap() + .pow + .as_mut() + .unwrap() + .enabled = true; + arms.push(("pow.enabled", pow)); + + let mut pubkey_whitelist = all_arms_off(); + pubkey_whitelist + .limits + .as_mut() + .unwrap() + .event + .as_mut() + .unwrap() + .pubkey + .as_mut() + .unwrap() + .whitelist = Some(vec![SettingsPubkey("abc123".to_owned())]); + arms.push(("pubkey.whitelist", pubkey_whitelist)); + + let mut pubkey_blacklist = all_arms_off(); + pubkey_blacklist + .limits + .as_mut() + .unwrap() + .event + .as_mut() + .unwrap() + .pubkey + .as_mut() + .unwrap() + .blacklist = Some(vec![SettingsPubkey("abc123".to_owned())]); + arms.push(("pubkey.blacklist", pubkey_blacklist)); + + let mut kind_whitelist = all_arms_off(); + kind_whitelist + .limits + .as_mut() + .unwrap() + .event + .as_mut() + .unwrap() + .kind + .as_mut() + .unwrap() + .whitelist = Some(vec![KindSelector::Single(Kind(1))]); + arms.push(("kind.whitelist", kind_whitelist)); + + let mut kind_blacklist = all_arms_off(); + kind_blacklist + .limits + .as_mut() + .unwrap() + .event + .as_mut() + .unwrap() + .kind + .as_mut() + .unwrap() + .blacklist = Some(vec![KindSelector::Single(Kind(4))]); + arms.push(("kind.blacklist", kind_blacklist)); + + for (name, settings) in arms { + assert!( + nip11::restricted_writes(&settings), + "{name} alone restricts writes" + ); + } + + // The capture's subscription arm is not ported: nothing here enforces subscriptions. + let mut plans = all_arms_off(); + { + let payments = plans.payments.as_mut().unwrap(); + payments.enabled = true; + payments.subscription_plans = Some(vec![SubscriptionPlan { + id: "basic".to_owned(), + description: None, + amount: 1_000, + interval_seconds: 2_592_000, + grace_seconds: 0, + limits: None, + }]); + } + assert!( + !nip11::restricted_writes(&plans), + "a configured subscription plan alone does not restrict writes" + ); +} + +#[test] +fn fees_reports_enabled_schedules_in_msats() { + let mut settings = shipped(); + { + let payments = settings.payments.as_mut().unwrap(); + payments.enabled = true; + payments.fee_schedules.admission = vec![ + FeeSchedule { + enabled: true, + description: None, + amount: 100, + whitelists: None, + }, + FeeSchedule { + enabled: false, + description: None, + amount: 200, + whitelists: None, + }, + ]; + payments.fee_schedules.publication = None; + } + + let document = value(&settings, "0.1.0", None); + assert_eq!( + document["fees"], + json!({ "admission": [{ "amount": 100, "unit": "msats" }] }), + "the enabled schedule only, and no publication key" + ); + + settings + .payments + .as_mut() + .unwrap() + .fee_schedules + .publication = Some(vec![FeeSchedule { + enabled: true, + description: None, + amount: 50, + whitelists: None, + }]); + let document = value(&settings, "0.1.0", None); + assert_eq!( + document["fees"]["publication"], + json!([{ "amount": 50, "unit": "msats" }]), + "publication appears when the settings carry it" + ); + + settings.payments.as_mut().unwrap().enabled = false; + let document = value(&settings, "0.1.0", None); + assert_eq!( + document["fees"], + json!({ "admission": [] }), + "payments off: an empty admission array and nothing else" + ); +} + +/// The document's `self` is the published identity and nothing else (R11): the key the caller +/// resolved from a fresh status document wins over `info.self`, and with no key — no fresh +/// document — `self` is absent however the settings read. +#[test] +fn self_is_the_published_identity_or_absent() { + let published: Pubkey = OTHER.parse().unwrap(); + + let mut settings = minimal(); + settings.info.self_ = Some(HEX.to_owned()); + assert_eq!( + value(&settings, "0.1.0", Some(published))["self"], + json!(OTHER), + "the published key wins over a configured one: the document is the relay's own word" + ); + + assert!( + value(&settings, "0.1.0", None).get("self").is_none(), + "no published key, no identity — the configured `info.self` does not stand in for it" + ); + + settings.info.self_ = None; + assert_eq!( + value(&settings, "0.1.0", Some(published))["self"], + json!(OTHER), + "the published key is the x-only hex `info.self` uses" + ); +} + +#[test] +fn the_version_and_software_are_the_callers() { + let document = value(&shipped(), "9.9.9", None); + assert_eq!(document["version"], json!("9.9.9")); + assert_eq!(document["software"], json!(env!("CARGO_PKG_REPOSITORY"))); + + let mut settings = minimal(); + settings.info.pubkey = NPUB.to_owned(); + let document = value(&settings, "0.1.0", None); + assert_eq!( + document["pubkey"], + json!(HEX), + "an npub1… info.pubkey is advertised as hex" + ); +} diff --git a/crates/nostream-relay/tests/transport.rs b/crates/nostream-relay/tests/transport.rs index 1258236e5..1c0bc1602 100644 --- a/crates/nostream-relay/tests/transport.rs +++ b/crates/nostream-relay/tests/transport.rs @@ -22,6 +22,7 @@ use common::{ }; use futures_util::SinkExt; use nostream_relay::RelayConfig; +use nostream_relay::connection_cap::ConnectionCap; use nostream_relay::testing::{Fixture, settings}; use nostream_relay::transport::{self, DEFAULT_MAX_PAYLOAD}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -1047,3 +1048,40 @@ async fn a_shared_budget_refusal_closes_the_socket_without_waiting_for_a_tick() ); assert_eq!(server.relay.frame_budget().refusals(), 1); } + +/// The cap's total is the sum of the per-address counts, not the number of addresses: three +/// sockets over two addresses read three, a dropped slot lowers it, and a refused socket does +/// not. +#[test] +fn the_total_counts_every_addresses_sockets() { + let cap = std::sync::Arc::new(ConnectionCap::new(2)); + let first = cap.acquire("10.0.0.1").expect("the first slot"); + let second = cap.acquire("10.0.0.1").expect("the second slot"); + let third = cap + .acquire("10.0.0.2") + .expect("another address has its own slots"); + + assert_eq!(cap.live_total(), 3, "sockets, not addresses"); + assert_eq!(cap.tracked_addresses(), 2); + + drop(third); + + assert_eq!(cap.live_total(), 2, "a released slot leaves the total"); + + let again = cap + .acquire("10.0.0.2") + .expect("the released slot admits again"); + let second_of_two = cap + .acquire("10.0.0.2") + .expect("the cap allows two for one address"); + assert!( + cap.acquire("10.0.0.2").is_none(), + "a third socket for one address is over the cap" + ); + assert_eq!(cap.live_total(), 4, "a refusal is not a socket"); + assert_eq!(cap.refusals(), 1); + + drop((first, second, again, second_of_two)); + + assert_eq!(cap.live_total(), 0); +} diff --git a/crates/nostreamd/src/admin_http.rs b/crates/nostreamd/src/admin_http.rs index 2e5223389..ab455dd91 100644 --- a/crates/nostreamd/src/admin_http.rs +++ b/crates/nostreamd/src/admin_http.rs @@ -109,6 +109,55 @@ pub async fn publish_heartbeats(state: Arc, shutdown: ShutdownState) } } +/// Rewrites the relay status document at start and every +/// [`nostream_admin::utils::status::STATUS_INTERVAL`] until the drain (R6). +/// +/// The document is the relay process's own facts — uptime, the live connection total, the worker +/// rows and the key the relay signs with — published for the MCP door, which runs in another +/// process. A failed assembly +/// or write is one warning carrying the path and the error; the loop continues, and a full +/// disk does not end the daemon. +pub async fn publish_status( + state: Arc, + connections: Arc, + relay_pubkey: Option, + shutdown: ShutdownState, +) { + let path = nostream_admin::utils::status::path(state.paths()); + let mut interval = tokio::time::interval(nostream_admin::utils::status::STATUS_INTERVAL); + // `interval`'s first tick is immediate; consume it, as `publish_heartbeats` does, so the + // loop's own write is the start's single write and the next is one cadence later. + interval.tick().await; + + loop { + let active = u64::try_from(connections.live_total()).unwrap_or(u64::MAX); + + match nostream_admin::utils::status::collect(&state, relay_pubkey, active) { + Ok(document) => { + if let Err(error) = nostream_admin::utils::status::write(&path, &document) { + tracing::warn!( + path = %path.display(), + %error, + "the relay status document was not written" + ); + } + } + Err(error) => { + tracing::warn!( + path = %path.display(), + %error, + "the relay status document was not assembled" + ); + } + } + + tokio::select! { + _ = interval.tick() => {} + _ = shutdown.wait_for_drain() => break, + } + } +} + /// `SECRET` as a value: the crate reads no environment for it (R3, Assumption 9). pub fn secret_from_env() -> Option> { match std::env::var("SECRET") { diff --git a/crates/nostreamd/src/main.rs b/crates/nostreamd/src/main.rs index 6342e9c0f..4746e34a0 100644 --- a/crates/nostreamd/src/main.rs +++ b/crates/nostreamd/src/main.rs @@ -50,7 +50,8 @@ struct Cli { /// start — and at most 4 KiB. /// /// The document is `{"scopes": ["write"]}`; a document with no scopes grants the read tools - /// (`settings_get`, `list_events`, `get_event`), and the "write" scope adds `settings_set`. + /// (`settings_get`, `list_events`, `get_event`, `relay_status`), and the "write" scope adds + /// `settings_set`. /// An unknown scope refuses to start, naming it. The mode also needs `admin.enabled: true` in /// the settings. /// @@ -236,6 +237,9 @@ async fn serve( Arc::clone(&service_stores.events), )); let relay_keys = RelayKeySource::from_env(); + // The relay's identity, resolved once where the environment is read and handed to the + // published document: the door reports it and never derives one of its own. + let relay_public_key = relay_keys.try_public_key(&settings.info.relay_url); let relay = Relay::new( (*settings).clone(), @@ -298,6 +302,9 @@ async fn serve( tracing::info!(at = %acceptor.local_addr(), "the acceptor is listening"); + // R7: the status writer's handle on the cap is taken before the `Arc` moves into + // the accept task. + let status_connections = Arc::clone(relay.connection_cap()); let connection_shutdown = shutdown.clone(); let http_fallback = nostreamd::admin_http::AdminHttp::new(admin_router); let accept_task = @@ -309,6 +316,18 @@ async fn serve( nostreamd::admin_http::publish_heartbeats(heartbeat_state, heartbeat_shutdown).await }); + let status_state = Arc::clone(&admin_state); + let status_shutdown = shutdown.clone(); + let status_task = tokio::spawn(async move { + nostreamd::admin_http::publish_status( + status_state, + status_connections, + relay_public_key, + status_shutdown, + ) + .await + }); + let workers_context = context.clone(); let workers_shutdown = shutdown.clone(); let workers_task = tokio::spawn(async move { @@ -339,11 +358,15 @@ async fn serve( let heartbeat_result = heartbeat_task .await .map_err(|error| DaemonError::Setup(format!("heartbeat task: {error}"))); + let status_result = status_task + .await + .map_err(|error| DaemonError::Setup(format!("status task: {error}"))); for (name, result) in [ ("acceptor", accept_result), ("workers", workers_result), ("tor", tor_result), ("heartbeats", heartbeat_result), + ("status", status_result), ] { if let Err(error) = result { tracing::warn!(task = name, error = %error, "background task ended with an error"); diff --git a/crates/nostreamd/tests/admin_http.rs b/crates/nostreamd/tests/admin_http.rs index 8ee669e12..b46ef810a 100644 --- a/crates/nostreamd/tests/admin_http.rs +++ b/crates/nostreamd/tests/admin_http.rs @@ -4,14 +4,18 @@ //! | case | what it proves | //! |---|---| //! | `the_daemon_serves_the_admin_page_and_the_wire_on_one_port` | `GET /admin/` is HTML, `GET /admin/session` without a cookie is 401, and a WebSocket client's first frame is the NIP-42 challenge | +//! | `the_daemon_publishes_its_status_document` | `/relay-status.json` appears, is rewritten, and carries a fresh `maintenance` row | #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use std::collections::BTreeSet; use std::io::Write; use std::net::{SocketAddr, TcpListener}; use std::process::{Child, Command, Stdio}; use std::time::{Duration, Instant}; +use serde_json::Value; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; @@ -230,3 +234,93 @@ async fn a_login_verification_does_not_stall_the_listener() { "the login completes after the listener answered" ); } + +/// The status document's keys, and whether its `maintenance` row carries a heartbeat the +/// daemon published. +fn published_document(raw: &str) -> Option { + let document: Value = serde_json::from_str(raw).ok()?; + let fresh = document["workers"].as_array()?.iter().any(|row| { + row["type"] == "maintenance" && row["stale"] == false && row["heartbeat"].is_object() + }); + + fresh.then_some(document) +} + +/// R6 and R7 — the only criterion that proves a writer runs: the daemon's own process writes +/// `/relay-status.json` at start, rewrites it on its cadence, and its `maintenance` row +/// is fresh because the heartbeat publisher in the same process published one. +#[tokio::test(flavor = "multi_thread")] +async fn the_daemon_publishes_its_status_document() { + let (daemon, temp) = start_daemon(); + wait_for_daemon(daemon.port).await; + let path = temp.path().join("config").join("relay-status.json"); + + // Three cadences: the writer's first tick cannot race the heartbeat publisher's, so the + // reading is a document whose row is already fresh. + let deadline = Instant::now() + Duration::from_secs(15); + let mut document = None; + while Instant::now() < deadline { + if let Ok(raw) = std::fs::read_to_string(&path) + && let Some(parsed) = published_document(&raw) + { + document = Some(parsed); + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + let document = document.expect("the daemon publishes a status document within 15 s"); + + let keys: BTreeSet<&str> = document + .as_object() + .expect("an object") + .keys() + .map(String::as_str) + .collect(); + assert_eq!( + keys, + BTreeSet::from([ + "generatedAt", + "uptimeSeconds", + "activeConnections", + "relayPubkey", + "workers" + ]), + "the document's five keys: {document}" + ); + // The relay's own identity, so the door reports the key this process signs with. + let relay_pubkey = document["relayPubkey"] + .as_str() + .expect("the document names the relay's key"); + assert_eq!(relay_pubkey.len(), 64, "{relay_pubkey}"); + assert!( + relay_pubkey + .bytes() + .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f')), + "x-only hex: {relay_pubkey}" + ); + assert_eq!( + document["activeConnections"], + serde_json::json!(0), + "nothing is connected to this daemon: {document}" + ); + assert!( + document["uptimeSeconds"].is_number(), + "uptime is a number: {document}" + ); + + // Two writes, not one: the modification time moves within the poll. + let first = std::fs::metadata(&path) + .and_then(|metadata| metadata.modified()) + .expect("the file's modification time"); + let deadline = Instant::now() + Duration::from_secs(15); + let mut rewritten = false; + while Instant::now() < deadline { + let later = std::fs::metadata(&path).and_then(|metadata| metadata.modified()); + if later.is_ok_and(|later| later > first) { + rewritten = true; + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + assert!(rewritten, "the writer rewrites the document on its cadence"); +} diff --git a/crates/nostreamd/tests/mcp_stdio.rs b/crates/nostreamd/tests/mcp_stdio.rs index 74a774f55..62d8b0f9b 100644 --- a/crates/nostreamd/tests/mcp_stdio.rs +++ b/crates/nostreamd/tests/mcp_stdio.rs @@ -18,6 +18,7 @@ //! | `the_mode_needs_one_credential_flag` | neither flag is an error naming both, and both is an error naming both | //! | `an_inherited_descriptor_authenticates` | a document delivered on descriptor 3 answers `tools/list` and a read, with nothing on the command line or in the environment | //! | `a_caller_chosen_name_cannot_size_or_forge_the_log` | the one arm reached before any credential cuts and escapes the caller's name, so the log cannot be sized or forged by it | +//! | `relay_status_reads_the_published_document` | a separate process answers `null` for a fact it cannot know, then the numbers a written document carries | //! //! The dialogue is hand-written JSON-RPC over the child's pipes: this target proves a property //! of the process, so it spawns the binary the way an MCP client does. @@ -402,6 +403,77 @@ async fn settings_get_answers_redacted_over_stdio() { assert!(outcome.status.success(), "{}", outcome.stderr); } +/// The relay's identity is the document's, not this process's: the door started with a +/// `RELAY_PRIVATE_KEY` of its own still reports the key the daemon published, and with no +/// document at all it reports none. A door that derived the key from its environment would +/// answer a key the relay never signs with — the wrong fact ADR 0016 D1 rejects. +#[tokio::test] +async fn the_identity_is_the_documents_not_the_processes() { + // The daemon's key, and one this process holds in its own environment. + let published = "11".repeat(32); + let ambient_secret = "22".repeat(32); + let prepared = Prepared::new(); + // Fresh to the system clock the spawned mode reads, so the document is a fact. + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() + .try_into() + .unwrap(); + std::fs::write( + prepared.config_dir.join("relay-status.json"), + json!({ + "generatedAt": nostream_admin::state::iso8601(now_ms), + "uptimeSeconds": 1, + "activeConnections": 0, + "relayPubkey": published, + "workers": [], + }) + .to_string(), + ) + .expect("a published document"); + + let mut command = base_command(); + command + .args(prepared.arguments(&[])) + .env("RELAY_PRIVATE_KEY", &ambient_secret); + let mut daemon = Daemon::spawn(command); + daemon.initialize().await; + let response = daemon.call("relay_status", json!({})).await; + let outcome = daemon.finish().await; + + let payload = &response["result"]["structuredContent"]; + assert_eq!( + payload["nip11"]["self"], published, + "the document's key, not the ambient one: {response}" + ); + assert!( + !outcome.stderr.contains(&ambient_secret), + "the ambient secret is never reported: {}", + outcome.stderr + ); + assert!(outcome.status.success(), "{}", outcome.stderr); + + // No document: no identity, and the reason says which file is missing. + let prepared = Prepared::new(); + let mut daemon = Daemon::start(&prepared, &[]); + daemon.initialize().await; + let response = daemon.call("relay_status", json!({})).await; + let outcome = daemon.finish().await; + + let payload = &response["result"]["structuredContent"]; + assert_eq!( + payload["nip11"].get("self"), + None, + "no document names no identity: {response}" + ); + let reason = payload["relay"]["reason"] + .as_str() + .expect("the payload says why"); + assert!(reason.contains("relay-status.json"), "{reason}"); + assert!(outcome.status.success(), "{}", outcome.stderr); +} + #[tokio::test] async fn the_mode_binds_no_socket() { // Held open for the whole dialogue: the child never binds it. @@ -416,7 +488,7 @@ async fn the_mode_binds_no_socket() { assert_eq!( listed["result"]["tools"].as_array().map(Vec::len), - Some(4), + Some(5), "{listed}" ); assert!(outcome.status.success(), "{}", outcome.stderr); @@ -476,6 +548,7 @@ async fn the_help_text_names_the_credential() { "scopes", "write", "admin.enabled", + "relay_status", ] { assert!(help.contains(needle), "the help names `{needle}`: {help}"); } @@ -644,7 +717,7 @@ async fn an_inherited_descriptor_authenticates() { assert_eq!( listed["result"]["tools"].as_array().map(Vec::len), - Some(4), + Some(5), "{listed}" ); assert_eq!(read["result"]["isError"], false, "{read}"); @@ -749,3 +822,68 @@ async fn a_caller_chosen_name_cannot_size_or_forge_the_log() { outcome.stderr.lines().max_by_key(|line| line.len()) ); } + +/// The clock reading the status document's `generatedAt` carries, formatted by the crate that +/// writes it: the mode composes a system clock, so the document must be fresh against wall time. +fn now_iso8601() -> String { + nostream_admin::state::iso8601(nostream_admin::utils::workers::system_now_ms()) +} + +/// AC8 — the numbers cross by the file, not by the process. The child is a separate process +/// with no relay in it, so a connection count it reports can only have been written down by +/// someone else — and a fact nobody wrote down is `null`, never `0`. +#[tokio::test] +async fn relay_status_reads_the_published_document() { + let prepared = Prepared::new(); + let mut daemon = Daemon::start(&prepared, &[]); + daemon.initialize().await; + + let before = daemon.call("relay_status", json!({})).await; + assert_eq!(before["result"]["isError"], false, "{before}"); + let relay = &before["result"]["structuredContent"]["relay"]; + assert!( + relay["activeConnections"].is_null(), + "no document: null, never 0: {before}" + ); + let reason = relay["reason"].as_str().unwrap_or_default(); + assert!(reason.contains("relay-status.json"), "{reason}"); + assert_eq!( + before["result"]["structuredContent"]["version"], + env!("CARGO_PKG_VERSION"), + "{before}" + ); + assert_eq!( + before["result"]["structuredContent"]["nip11"]["name"], + json!("Example"), + "{before}" + ); + + let document = json!({ + "generatedAt": now_iso8601(), + "uptimeSeconds": 99, + "activeConnections": 5, + "workers": [{ + "type": "maintenance", + "enabled": true, + "label": "Maintenance", + "monitored": true, + "stale": false, + }], + }); + std::fs::write( + prepared.config_dir.join("relay-status.json"), + document.to_string(), + ) + .expect("the document is written"); + + let after = daemon.call("relay_status", json!({})).await; + let outcome = daemon.finish().await; + + assert_eq!(after["result"]["isError"], false, "{after}"); + let relay = &after["result"]["structuredContent"]["relay"]; + assert_eq!(relay["activeConnections"], json!(5), "{after}"); + assert_eq!(relay["uptimeSeconds"], json!(99), "{after}"); + assert!(relay["reason"].is_null(), "{after}"); + assert_eq!(relay["workers"][0]["type"], json!("maintenance"), "{after}"); + assert!(outcome.status.success(), "{}", outcome.stderr); +} diff --git a/docs/PEERING.md b/docs/PEERING.md index 375b7c702..2d35448f1 100644 --- a/docs/PEERING.md +++ b/docs/PEERING.md @@ -18,9 +18,11 @@ The relay already has a signing key: [CONFIGURATION.md](../CONFIGURATION.md#environment-variables). The private key is never written to `settings.yaml` and never sent to another relay. -`info.self` is optional. When set, it is the pubkey advertised as `self` in the -NIP-11 document and must match the key the relay actually signs with. When unset -or unparseable, NIP-11 advertises the derived signing pubkey instead. Run: +`info.self` is optional and gates kind 28935 invite requests: when set it must +match the key the relay actually signs with, and when it does not those requests +are disabled. It is not what NIP-11 publishes — the document's `self` is always +the relay's derived signing pubkey, read from the daemon's status document, and +absent while that document is missing or stale. Run: ```bash nostream info diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index 507e9048b..9a9cd373a 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -279,8 +279,9 @@ backend, whose query is a real await, that the shape is for. ### D18 — The audit vocabulary gains one `mcp.*` action per tool The MCP server writes its calls to the same `/admin-audit.jsonl` (D9), one line per -executed call, and it extends the recorded action vocabulary by **four names** rather than -reusing one: +executed call, and it extends the recorded action vocabulary by **one name per registered tool** +rather than reusing one. Four names landed with the first slice; `relay_status` adds the fifth, and +each later slice adds its own: | action | written by | |---|---| @@ -288,6 +289,7 @@ reusing one: | `mcp.settings_set` | a dispatched `settings_set` | | `mcp.list_events` | a dispatched `list_events` | | `mcp.get_event` | a dispatched `get_event` | +| `mcp.relay_status` | a dispatched `relay_status` (ADR 0016) | **These extend the capture's nine names; they do not replace them.** The capture's vocabulary is a closed nine-name union (`src/@types/admin-audit.ts:1-10`), and the rewrite's writer takes @@ -325,6 +327,15 @@ directory is outside ADR 0012 D9 — `admin-audit.jsonl` (whose compaction is a rename on a shared staging path, `crates/nostream-admin/src/state.rs:715-733`) and the settings write both assume one writer per configuration. +**The one artifact the two modes do share, and why it is not the hazard.** The MCP mode's +`relay_status` reads `/relay-status.json`, which the daemon rewrites every 5 s +(`nostream_admin::utils::status`, `crates/nostreamd/src/admin_http.rs`'s `publish_status`; ADR +0016 D1). That is **one writer and one reader**: the daemon's task is the file's only writer, and +the MCP process only reads it, so neither `admin-audit.jsonl`'s read-write-rename compaction nor +the settings write gains a second writer, and this slice does not widen what ADR 0012 D9 +supports. A document that is absent, unreadable or older than its 30 s bound is reported as +unavailable with a reason, never as zero. + **The table is total, and it carries both dispatch-time facts.** Every tool the router registers has one row in `crates/nostream-mcp`'s `TOOLS` table: its name, the check that says whether the router can deserialise a call's arguments (R9), and the scope the call needs (R28). The dispatch @@ -401,8 +412,9 @@ serving calls nobody could attribute. **The document declares what it may do.** `{"scopes": ["write"]}`, with `scopes` optional, and the set closed (`deny_unknown_fields`): a document still carrying a session token under `token` is refused for its shape rather than read for less than it says. Reading is not a scope — every -accepted document may call `settings_get`, `list_events` and `get_event` — and `write` is the one -name a document may add, the right to call `settings_set`. A name the door does not know refuses +accepted document may call the read tools — `settings_get`, `list_events`, `get_event` and, since +job 035's slice, `relay_status` — and `write` is the one name a document may add, the right to call +`settings_set`. A name the door does not know refuses the load, naming the scope and the accepted set, because a typo narrowed silently would answer `Forbidden` to calls the operator believed it allowed with the typo nowhere in sight. A call the document's scopes deny is refused **and audited**: action `mcp.denied`, `detail` diff --git a/docs/rewrite/decisions/0016-relay-status-and-nip11.md b/docs/rewrite/decisions/0016-relay-status-and-nip11.md new file mode 100644 index 000000000..753051165 --- /dev/null +++ b/docs/rewrite/decisions/0016-relay-status-and-nip11.md @@ -0,0 +1,200 @@ +# ADR 0016: The relay status document, the `relay_status` tool and the NIP-11 field set + +- **Status:** accepted (job 035, Phase 2) +- **Deciders:** the rewrite team, on the operator's steer recorded in #1183 and this job's spec +- **Date:** 2026-11-21 + +## Context + +Slice 2 of #1183 is one MCP tool, `relay_status`: the software version, the relay process's +uptime, its live connection count, its worker rows, and the NIP-11 document it advertises. Two +facts at the base commit shaped it. + +**The tool answers in a process that hosts no relay.** `nostreamd --mcp-stdio` returns before +the daemon's `serve` loop starts, and the process that serves a tool call holds no `Relay`, no +`ConnectionCap` and no heartbeat publisher (`crates/nostreamd/src/mcp_stdio.rs`, +`crates/nostreamd/src/main.rs`). Heartbeats are process memory +(`crates/nostream-admin/src/state.rs`) and `AdminState` holds no relay handle. A payload built +only from the MCP process would therefore report the *MCP process's* age as the relay's uptime, +every monitored worker row as stale, no connection total at all, and a NIP-11 `self` derived +from that process's environment rather than the relay's — four wrong facts wearing the relay's +name, which is worse than a stub. The document carries the relay's own key for the same reason it +carries the rest: the daemon resolves it where the environment is read, the door reports what the +document says, and with no fresh document there is no `self` at all — a missing identity is +weighable, a wrong one is not. + +**No connection total existed anywhere.** `ConnectionCap` exposed `max_per_ip`, `live(ip)`, +`tracked_addresses()` and `refusals()`, and its map is private: the sum was not reachable from +outside. ADR 0014 D5 records the absence, and `crates/nostream-admin/src/utils/metrics.rs` serves +`activeConnections` as the literal `0` — that key name is the console's and this job keeps it. + +The NIP-11 document did not exist either: `docs/rewrite/nip-parity.md` §10 D1 said so, and its +§9 item 11 deferred the field set to "with the document". This job is the document. + +## Decisions + +### D1 — The daemon publishes a status document; the tool reads it + +`/relay-status.json` is written by one task in the daemon +(`nostreamd::admin_http::publish_status`, spawned in `serve`) and read per call by the tool +(`nostream_admin::utils::status::read`). The file is `StatusDocument`: `generatedAt`, +`uptimeSeconds`, `activeConnections`, `relayPubkey`, `workers`. + +The pricing is part of the decision: **one** writer task, a **5 s** cadence +(`STATUS_INTERVAL`), a **30 s** staleness bound (`STATUS_TTL_SECONDS`), an **atomic replace** (a +sibling `.tmp` write and a rename, so no reader sees a half-written document and no `.tmp` +survives a successful write), and a `reason` on every unavailable value. The cadence is six +times faster than the bound, so one missed write is still fresh; 5 s is the coarsest cadence that +makes a connection count worth reading. + +The payload has three sources: `version` and the settings-derived keys of `nip11` come from the +answering process; `nip11.self` and everything under `relay`'s numbers come from the published +document; and `relay.reason` and `relay.ageSeconds` are the reader's own — the text of the read's +failure and its arithmetic. **Unavailable is never zero.** With +no document, an unreadable one, or one older than the bound, `relay` is +`{reason, observedAt: null, ageSeconds: null, uptimeSeconds: null, activeConnections: null, +workers: null}` and the reason names `relay-status.json`; a `0` in the payload can only come from +a document that says `0`. + +**Cost:** the numbers are up to 5 s old, and a daemon that stops writing is reported as +unavailable after 30 s rather than as stale numbers. The bound is one-sided by construction: +R5's formula is `(now − generated)/1000`, so a document dated ahead of the reader reports +`ageSeconds: 0` and is fresh. A daemon whose clock steps back keeps publishing documents a correct +reader treats as fresh, and a reader more than 30 s ahead of the writer reports a live daemon as +stale; that is inherent to a wall-clock stamp, and the document says when it was written so a +reader can see the skew. The alternative — a route on the daemon's listener — would need ADR 0014 +D1's HTTP surface and an auth model; the file is the cross-process channel the tree already +relies on (`admin-audit.jsonl`), with no new surface. + +**Reading it is not the second-writer hazard ADR 0014 records** (`0014-admin-http-surface.md`, +its decision on the single writer). That decision notes that `admin-audit.jsonl` and the settings +write assume one writer per configuration. This file is one writer (the daemon) and one reader (the +MCP door); the MCP mode never writes it, and ADR 0014 is amended to say so. + +### D2 — The seam is two concrete places, not a trait + +The tree's trait seams invert a dependency: `nostream_relay::dispatch::HttpFallback` and +`nostream_relay::wot::WotGraph` are declared in a lower crate because their implementations can +only live in a higher one. Neither condition holds here — `nostream-mcp` already depends on +`nostream-admin`, which already depends on `nostream-relay`, and the daemon already holds the +type that produces the count. A trait would be an abstraction over one implementation and would +add a field to `AdminStateConfig` at every construction site. + +So the seams are: + +1. `ConnectionCap::live_total(&self) -> usize`, the sum of the guarded map under the same + poison-tolerant lock the three existing accessors take — one lock acquisition per read, + O(addresses), the shape of `tracked_addresses()`. `live(ip)`, `tracked_addresses()` and + `refusals()` keep their signatures and behaviour. +2. The published document above. + +**Cost:** `live_total` is a second lock acquisition where an `AtomicU64` maintained in `acquire` +and in `ConnectionSlot::drop` would be lock-free. The counter was rejected because it adds a +second place that must stay in step with the map, and the total is read once every 5 s. + +### D3 — The document's five keys, and the console's worker rows verbatim + +`StatusDocument` is `generatedAt`, `uptimeSeconds`, `activeConnections`, `relayPubkey`, +`workers`, camelCase because `uptimeSeconds` and `activeConnections` are the console's own names. +`relayPubkey` is the relay's own x-only key — the identity `nip11.self` reports — written from +the daemon's resolved key source and omitted when it has none, so the door never derives a key of +its own from an environment the daemon does not share. Its `workers` is +`Vec` — the rows `GET /ops/workers` already serves, +produced by `workers::rows` — so there is no second staleness judgement: a stale row reads +`stale: true` with an old or absent `heartbeat`, and the tool adds nothing. `WorkerRow` and +`WorkerHeartbeat` gained `Deserialize` so the reader validates a document rather than trusting +it; no serialized field changed. + +`collect` assembles the document from the implementations that already exist and nothing else: +`AdminState::uptime_seconds`, the state clock through `iso8601`, and `workers::rows`. It computes +no staleness of its own. + +**Cost:** a row's shape is the console's, so a change to `WorkerRow` moves the document too. That +is the point: one array, one judgement. + +### D4 — The NIP-11 field set, per key (closing `nip-parity.md` item 11) + +`nostream_relay::nip11` builds the document; every key's presence is decided in that module. +The rule where the capture and an `11.md`-less extension disagree is **advertise what the relay +enforces**. + +Kept, with their sources: `name`, `description`, `contact` (`Info`); `banner`, `icon`, +`terms_of_service` when set; `pubkey` as hex (an `npub1…` decoded, as the capture does); `self` +when the published document names one (its `relayPubkey`, and nothing else — a settings value or +the answering process's environment would be a key the relay may not sign with, so with no fresh +document `self` is absent); `supported_nips`; `software` (the workspace repository, +`env!("CARGO_PKG_REPOSITORY")`); `version` (the caller's); +`limitation.max_message_length` (the transport's own `max_payload_size`); the five client limits +and `max_content_length` when set and, for the client limits, non-zero (`0` means "no cap" to the +checks that read it, and would read as "none allowed"); `min_pow_difficulty` when non-zero, at +the **enforced** value: `floor_bits` while `limits.event.pow.enabled`, else +`limits.event.eventId.minLeadingZeroBits` — `required_difficulty` (`handlers/event.rs`) passes +`None` as the WoT distance, and with no distance `apply_wot_pow_policy` answers the computed +difficulty unchanged, so the capture's `ceil(floor_bits × difficulty_factor)` discount is granted +to nobody here and is not advertised; +`auth_required` as the literal `false` (the capture's deliberate split: publish-only AUTH is +`restricted_writes`); `payment_required` when payments are configured; `created_at_lower_limit` +and `created_at_upper_limit` when set; `default_limit` (`nostream_storage::DEFAULT_PAGE_ROWS`); +`restricted_writes`; `search_supported`; `fees.admission` and `fees.publication`. + +The seven drops, with their reasons: + +| key | why it is dropped | +|---|---| +| `supported_nip_extensions`, `supported_mips` | no Rust source at all (the capture's `package.json` is the only place they exist), and neither name is in `11.md` | +| `payments_url` | the route it names does not exist: `crates/nostream-admin/src/routes/` registers no `invoices` route, and D1 keeps a public HTTP surface shut | +| `peering` | no Rust code serves peer feeds; `peering` appears only in the settings type and the validator | +| `limitation.min_prefix` | `min_prefix_length` is read nowhere in `crates`; the wire's floor is the fixed 4 of `validate_prefixes`, and `nip-parity.md` item 8 already records that it is not advertised | +| `limitation.max_event_tags` | no Rust constant and no admission check anywhere; the audit's own rule is to enforce it or not advertise it | +| `fees.subscription` | no invoice route and no subscription enforcement; it lands with them | + +`nostream-cli info` does **not** adopt the builder: its output is pinned byte for byte and +carries no NIP-11 document, so sharing the builder would buy nothing and risk the pin. The +builder lands in `nostream-relay`, which the CLI already depends on, so a future adoption that +also re-pins its output is a one-line change with no new dependency edge. + +**Cost:** a client that read `max_event_tags` from the capture's document no longer sees it. The +alternative is a document that promises a limit the relay does not keep. + +### D5 — `supported_nips` is `SUPPORTED_NIPS` minus what does not run + +`SUPPORTED_NIPS` in its own order, minus `43` when `nip43.enabled` is not true, minus `50` when +`nip50.enabled` is not true, and minus `77` always — its handler is a stub +(`crates/nostream-relay/src/connection.rs`). This closes the audit's recorded inconsistency +("50 is supported" and "search is off") from the other side: with NIP-50 off, neither the id nor +`search_supported: true` is advertised. + +**Cost:** the advertised list now depends on settings, so two relays on one binary can advertise +different sets. That is what the switches mean. + +### D6 — `restricted_writes` folds the arms the event handler enforces; three capture surfaces stay out + +`restricted_writes` is a pure fold over the settings whose every arm has an enforcing site in +`crates/nostream-relay/src/handlers/event.rs`: an enabled admission fee schedule under +`payments.enabled`; `nip43.enabled`; `nip42.authRequired == Some(true)`; a non-zero +`eventId.minLeadingZeroBits`, `pubkey.minLeadingZeroBits` or `pow.enabled`; a non-empty pubkey +whitelist or blacklist; a non-empty kind whitelist or blacklist. + +The capture's **subscription arm is not ported**, because nothing in the rewrite enforces +subscriptions: a configured plan does not make `restricted_writes` true. For the same reason +`fees.subscription`, `payments_url` and `peering` stay out (D4): each describes a surface or an +enforcement this relay does not have. + +**Cost:** an operator who configured subscription plans sees a document that does not mention +them. When the invoice routes and subscription enforcement land, all four arrive together. + +### D7 — The shapes are the console's, not the CLI's + +- `uptimeSeconds` is a number — `HealthSnapshot`'s name and type — and it is the **relay + process's** age, from `AdminState::uptime_seconds`. `nostream-cli info`'s own uptime comes + from `docker inspect` and describes the container; the two need not agree, and neither changes. + `format_uptime`'s `Nd Nh Nm Ns` string stays a CLI rendering. +- Worker health is the console's `WorkerRow` array (D3), with no second staleness judgement. +- `activeConnections` is the console's key name, and the value is `ConnectionCap::live_total()`: + sockets, not addresses. `/metrics`' own `activeConnections` stays the literal `0` D5 recorded; + re-wiring it is a separate change with its own surface. +- The payload is `structuredContent` only, `version` is the composition's (`serverInfo`'s, never + a crate-local `env!`), and `nip11` is the document of D4 serialised as it stands. + +**Cost:** the tool's payload and the console's rows share a type, so a field added to one is +visible to the other. That is the alternative to a second row shape, and it was chosen. diff --git a/docs/rewrite/nip-parity.md b/docs/rewrite/nip-parity.md index ec80bfa7c..3900b3699 100644 --- a/docs/rewrite/nip-parity.md +++ b/docs/rewrite/nip-parity.md @@ -872,7 +872,7 @@ is a defect, and §10 is the same record in table form. the four untested keys are `min_prefix`, `supported_nip_extensions`, `supported_mips` and `max_event_tags` (§1). NIP-78's two kinds have no test either, and item 7 carries that pair. - - **Status:** deferred — **D1** defers the HTTP surface and the document itself, and the field set is decided with the document; the four untested keys stay untested until then. + - **Status:** done in this job — **ADR 0016 D4** decides the set. Kept: `name`, `description`, `banner`/`icon`/`terms_of_service` (when set), `pubkey` (hex; an `npub` decoded), `self` (the relay's published signing pubkey, from the daemon's status document; absent with no fresh document), `supported_nips`, `software`, `version`, `limitation.max_message_length`, the five client limits and `max_content_length` (each omitted when unset or, for the client limits, `0`), `min_pow_difficulty` (when non-zero), `auth_required` (literal `false`), `payment_required`, `created_at_lower_limit`/`created_at_upper_limit`, `default_limit`, `restricted_writes`, `search_supported`, and `fees.admission`/`fees.publication`. Dropped: `supported_nip_extensions` and `supported_mips` (no Rust source at all), `limitation.max_event_tags` (no constant and no admission check, so it would advertise a limit the relay does not keep), `limitation.min_prefix` (follows item 8's "not advertised"; the wire's floor is the fixed 4), `payments_url` and `fees.subscription` (the invoice route they describe does not exist), and `peering` (no Rust code serves peer feeds). The builder is `nostream_relay::nip11`, with one case per verdict. 12. **NIP-09 `a`-tag deletion.** `DeleteEventStrategy` accepts only `e` tags (`src/handlers/event-strategies/delete-event-strategy.ts:22-31`); a kind-5 event whose tags are `a`-only deletes nothing. The rewrite either implements @@ -961,10 +961,11 @@ capture's wording. **The decisions, by id.** - **D1 — NIP-11's HTTP surface is not the advertisement's job.** `SUPPORTED_NIPS` is - fixed and the wire gap recorded; nothing listens on HTTP and no NIP-11 document is - built. The surface is a dependency decision (no HTTP server crate anywhere in the - workspace), a second bind in `nostreamd`, and a document assembled from `info`, - `limits`, `payments` and `peering`. §9 item 11 carries it. + fixed and the wire gap recorded; nothing listens on HTTP. The document itself **is** + built — `nostream_relay::nip11` assembles it from `info`, `limits` and `payments` for + the MCP door, and no client is served it (ADR 0016 D4). The surface remains a + dependency decision (no HTTP server crate anywhere in the workspace) and a second bind + in `nostreamd`. §9 item 11 carries it. - **D2 — the advertised set is the audit's 33 `must-have` rows plus NIP-67: 34 ids.** 04, 14 and 28 stay as behaviour the generic path satisfies, which costs nothing and avoids a silent parity change; the tombstones 12/16/20/33 stay because nostream diff --git a/resources/default-settings.yaml b/resources/default-settings.yaml index ad463691b..5f3e25a57 100755 --- a/resources/default-settings.yaml +++ b/resources/default-settings.yaml @@ -5,10 +5,13 @@ info: banner: https://nostream.your-domain.com/banner.png icon: https://nostream.your-domain.com/icon.png pubkey: replace-with-your-pubkey-in-hex - # Optional. The relay's own signing pubkey, published as `self` in the NIP-11 - # document. NIP-43 clients verify relay-signed events against it, so it MUST - # match the key the relay signs with. Leave it unset to have it derived from - # SECRET automatically; run `nostream info` to see the derived value. + # Optional. What NIP-11 advertises as `self` differs by implementation: the Rust + # rewrite advertises the relay's derived signing pubkey, read from the daemon's + # status document (absent while that document is missing or stale), while the + # TypeScript relay advertises this value when it parses and the derived key + # otherwise. Both gate kind 28935 invite requests on it: a configured, + # non-empty value MUST match the key the relay signs with, and unset or empty + # skips that check. Run `nostream info` to see the derived value. # self: replace-with-your-relay-pubkey-in-hex contact: mailto:operator@your-domain.com terms_of_service: https://nostream.your-domain.com/terms diff --git a/test/unit/cli/docs.spec.ts b/test/unit/cli/docs.spec.ts index 8f35392c6..becdf8da7 100644 --- a/test/unit/cli/docs.spec.ts +++ b/test/unit/cli/docs.spec.ts @@ -36,7 +36,7 @@ describe('cli documentation alignment', () => { const configurationDoc = fs.readFileSync(path.join(projectRoot, 'CONFIGURATION.md'), 'utf-8') expect(cliDoc).to.include('relay.signingPubkey') - expect(cliDoc).to.include("Leave `info.self` unset") + expect(cliDoc).to.include('takes it from the daemon\'s status document') expect(configurationDoc).to.include('nostream info') })