Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
c71d0da
feat(relay): count every live socket in ConnectionCap::live_total
chappie-daemon Nov 21, 2026
f51dddf
feat(relay): build the NIP-11 document from settings
chappie-daemon Nov 21, 2026
215a63a
feat(admin): assemble the relay status document and read it back
chappie-daemon Nov 21, 2026
c9efd97
feat(daemon): publish the relay status document every five seconds
chappie-daemon Nov 21, 2026
0382661
style: apply rustfmt to the new modules and cases
chappie-daemon Nov 21, 2026
af40773
feat(mcp): add the relay_status tool over the published document and …
chappie-daemon Nov 21, 2026
fcd6ed3
test(mcp): audit the relay_status dispatch in call order
chappie-daemon Nov 21, 2026
53c9c59
docs(adr): record the relay status document and the NIP-11 field set
chappie-daemon Nov 21, 2026
f6a09d2
docs(adr): cite ADR 0014's single-writer decision without a cross-rec…
chappie-daemon Nov 21, 2026
3bdba83
fix(admin): create the status document's directory and prove the repl…
chappie-daemon Nov 21, 2026
b9dba7a
fix(relay): advertise the difficulty the event handler enforces
chappie-daemon Nov 21, 2026
a6f8eb7
fix(nostreamd): name relay_status in the stdio help
chappie-daemon Nov 21, 2026
460c751
fix(daemon): publish one status document at start, not two
chappie-daemon Nov 21, 2026
bae2d0d
style: apply rustfmt to the status cases
chappie-daemon Nov 21, 2026
f1b9cd6
docs(adr): the audit vocabulary gains one mcp.* name per tool, not four
chappie-daemon Nov 21, 2026
3885d38
test(relay): prove the advertised difficulty and the enforced one are…
chappie-daemon Nov 21, 2026
d6747d8
feat(admin): carry the relay's own key in the published document
chappie-daemon Nov 21, 2026
91366c6
fix(admin): name the field when generatedAt cannot be read
chappie-daemon Nov 21, 2026
87598db
docs(adr): restore D1's file-over-route cost and name the record it c…
chappie-daemon Nov 21, 2026
50f49e3
fix(relay): take nip11 self from the published key alone
chappie-daemon Nov 21, 2026
f6f3201
docs(adr): record self's single source
chappie-daemon Nov 21, 2026
22bc16e
docs: NIP-11 self is the relay's published key, not info.self
chappie-daemon Nov 21, 2026
9425f25
docs(adr): D1 names the document's fifth key
chappie-daemon Nov 21, 2026
263c3cb
test(mcp): a stale document names no identity either
chappie-daemon Nov 21, 2026
1c90022
docs(cli): NIP-11 self is the derived key, not info.self
chappie-daemon Nov 21, 2026
ab0a8cc
docs: an unset info.self skips the invite check rather than failing it
chappie-daemon Nov 21, 2026
0aeab52
docs: the status document has five keys, and info.self no longer clai…
chappie-daemon Nov 21, 2026
db8ff8c
docs(settings): the self rule differs by implementation, so say both
chappie-daemon Nov 21, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .changeset/relay-status-tool.md
Original file line number Diff line number Diff line change
@@ -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
`<config>/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.
2 changes: 1 addition & 1 deletion CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
2 changes: 2 additions & 0 deletions Cargo.lock

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

7 changes: 5 additions & 2 deletions crates/nostream-admin/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/nostream-admin/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
163 changes: 163 additions & 0 deletions crates/nostream-admin/src/utils/status.rs
Original file line number Diff line number Diff line change
@@ -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<Pubkey>,
pub workers: Vec<WorkerRow>,
}

/// 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: `<config_base_dir>/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<Pubkey>,
active_connections: u64,
) -> Result<StatusDocument, AdminError> {
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)?;
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
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<Published, StatusError> {
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`: `<file>.tmp`.
fn staging_path(path: &Path) -> PathBuf {
let mut name = path.as_os_str().to_owned();

name.push(".tmp");

PathBuf::from(name)
}
8 changes: 5 additions & 3 deletions crates/nostream-admin/src/utils/workers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand All @@ -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,
Expand Down
Loading
Loading