README.md (22630B)
1 # radroots_transport_nostr 2 3 `radroots_transport_nostr` is the concrete, signer-free Nostr implementation 4 of the generic [`radroots_transport::EventSource`], 5 [`radroots_transport::EventSubscriber`], and [`radroots_transport::EventSink`] 6 interfaces. It validates relay configuration and network policy, performs 7 bounded fetch, live-subscription, and delivery attempts, exposes explicit 8 host-mediated NIP-42 authentication, and normalizes relay outcomes and passive 9 status. 10 11 The crate does not own event ingestion, persistence, outbox claiming, 12 projection refresh, durable retry scheduling, or a process runtime. Those 13 policies belong to `radroots_sync` and host applications. It does own bounded 14 relay profiles, per-relay reconnect suppression, and evidence-based status. 15 16 The authoritative package charter is the 17 [`radroots_transport_nostr` section of the Release V1 specification](../../contracts/crates/release_v1/radroots_crates_release_v1.toml). 18 The reviewed Rust surface is recorded in the 19 [public API baseline](../../contracts/api_baselines/radroots_transport_nostr.txt). 20 21 Shared fetch, delivery and subscription timing uses a private host boundary. 22 Native execution retains Tokio's monotonic deadlines and system observation 23 clock. The browser implementation uses browser monotonic and wall clocks and 24 the pinned upstream sleep with a separate local cancellation owner. The owner 25 measures the original deadline when it starts, without renewing its budget. 26 Fractional waits round up, long waits use bounded signed-delay chunks, and 27 each wake rechecks the deadline before reporting expiry. 28 Its isolated 29 page/worker fixture lives in `tests/browser_time`; this does not qualify the 30 complete browser connector or ordinary client. Native socket ownership belongs 31 to `radroots_transport_nostr_native`; shared protocol state stays here. 32 33 ## Configure without connecting 34 35 Configuration is explicit, validated, and inert. Constructing 36 [`NostrTransport`] creates no socket and performs no DNS lookup: 37 38 ```rust 39 use radroots_transport::{EventSink, EventSource, EventSubscriber}; 40 use radroots_transport_nostr::{ 41 Config, NostrTransport, RelayAccess, RelayEndpoint, RelayProfile, 42 RelayProfileKind, RelayUrlPolicy, 43 }; 44 45 # fn configure(host: std::sync::Arc<dyn radroots_transport::host::websocket::Connector>) 46 # -> Result<(), Box<dyn std::error::Error>> { 47 let endpoint = RelayEndpoint::new( 48 "wss://relay.example.com", 49 RelayUrlPolicy::Public, 50 RelayAccess::ReadWrite, 51 )?; 52 let profile = RelayProfile::explicit(RelayProfileKind::Public, [endpoint])?; 53 let config = Config::from_profile(profile).with_timeouts(5_000, 20_000, 2_000)?; 54 let transport = NostrTransport::new(config, host); 55 56 let source: &dyn EventSource = &transport; 57 let subscriber: &dyn EventSubscriber = &transport; 58 let sink: &dyn EventSink = &transport; 59 drop(source.status()); 60 let _ = subscriber; 61 drop(sink.status()); 62 # Ok(()) 63 # } 64 ``` 65 66 A runnable version is available at 67 [`examples/configure_transport.rs`](examples/configure_transport.rs). 68 The composing host constructs bounded `FetchRequest`, `SubscriptionRequest`, 69 and `DeliveryRequest` values from `radroots_transport`, polls the returned 70 futures on its executor, and applies any retry or scheduling policy outside 71 this crate. 72 73 ## Explicit pool shutdown 74 75 Await [`NostrTransport::shutdown`] before disposing an owned session. Clones 76 share closed admission; new fetch, subscription, delivery and AUTH effects 77 are refused, and pending AUTH challenges are disposed. Delivery refusal keeps 78 one exact unattempted observation for every requested target. An unpolled 79 shutdown future is inert; await shutdown again after interrupted cleanup. 80 Already-started work still requires its owner to await and retain obtained 81 results. Upstream pool shutdown signals its relay tasks; it does not itself 82 establish that every internal task joined. [`NostrTransport::admission_is_closed`] 83 reports admission, rather than complete session cleanup or business rollback. 84 85 Owners replacing a profile may call [`NostrTransport::close_admission`] while 86 retaining the pool for already-started calls. Their registered relay handles 87 disconnect synchronously when the last call completes or is cancelled, so 88 idle reconnect work does not survive retirement. The owner must still await 89 explicit pool shutdown. [`NostrTransport::has_in_flight_operations`] reports 90 source, delivery, subscription-setup and AUTH calls; it does not count passive 91 status inspection or represent live subscription handles or complete session 92 worker joining. No cleanup worker or post-observation await is introduced. 93 94 ## Prepared delivery boundary 95 96 [`NostrTransport::prepare_delivery`] validates the exact request, writable 97 relay bindings, and signed-event conversion without reading a clock, polling 98 status, or performing relay I/O. It returns a sealed [`PreparedDelivery`] 99 whose ordinary `Debug` is redacted. The composing host may bind the retained 100 request to durable Submitted state and then pass the capability to 101 [`NostrTransport::execute_prepared_delivery`], which consumes it and is the 102 only half of this boundary that may contact relays. Executing a capability 103 through a differently configured transport fails closed. 104 105 The prepared event retains its signed raw JSON. Delivery wraps those exact 106 bytes in the Nostr `EVENT` frame without parsing and serializing them again; 107 whitespace, field order, and admitted extension fields remain unchanged. The 108 frame must fit the existing 512 KiB wire bound. Publication shares the existing 109 hardened connection writer with SDK authentication and subscription messages. 110 It requires a matching event-ID `OK` with `accepted=true` from that relay before 111 recording acceptance. Duplicate-event acceptance also requires `true`, as 112 defined by [NIP-01](https://github.com/nostr-protocol/nips/blob/master/01.md). 113 A negative acknowledgement or untyped error remains unsuccessful regardless 114 of message text, including `duplicate` or `already have`. 115 Closed or replaced connections do not grant fresh send authority to a retained 116 writer. Missing acknowledgements remain unknown or unavailable evidence. 117 118 Inbound `EVENT` identifiers, public keys and signatures, and `OK` event IDs, 119 must have their canonical lowercase hexadecimal lengths on the original wire. 120 The hardened connector refuses invalid fields before the SDK can normalize 121 them. A longer identifier sharing a valid prefix grants no acceptance. 122 Every inbound event also passes complete ID and signature verification through 123 the client's private admission policy, including repeated IDs already present 124 in the upstream verification cache. 125 126 Callers cannot forge or mutate prepared authority: 127 128 ```compile_fail 129 use radroots_transport_nostr::PreparedDelivery; 130 131 let _forged = PreparedDelivery { 132 request: panic!(), 133 config: panic!(), 134 event: panic!(), 135 authorized: panic!(), 136 skipped: panic!(), 137 }; 138 ``` 139 140 `prepare_delivery_selected` and `EventSink::deliver_selected` further constrain 141 an attempt to an exact subset of the original targets. The retained request, 142 signed bytes and full receipt binding do not change. Unselected targets receive 143 unattempted, retryable `target_not_selected` rows before configuration or I/O 144 admission. Selected targets still require writable configuration and backoff 145 admission. This adapter does not choose application eligibility policy. 146 147 ## Public surface 148 149 - [`RelayProfile`] defines public, loopback-simulator, and physical-device 150 profiles with independent read-only/read-write authority per endpoint. 151 - [`Config`] retains the validated profile plus bounded connection, request, 152 status, concurrency, and reconnect limits. 153 - [`RelayUrl`] is a canonical Nostr relay URL that converts to and from the 154 generic `radroots_transport::Target` model. 155 - [`RelayUrlPolicy`] selects public-Internet, exact-loopback, or explicitly 156 typed private-device destination rules. 157 - [`RelayCursor`] provides the equal-timestamp-safe event ordering primitive 158 used by scoped fetch continuation cursors. 159 - [`NostrTransport`] implements all three transport SPIs, exposes passive typed 160 per-relay evidence, and provides explicit NIP-42 challenge lifecycle methods. 161 - [`PreparedDelivery`] is the non-forgeable, consuming boundary between inert 162 adapter validation and relay execution. 163 - [`Error`] contains only package-owned validation and authentication errors; 164 upstream failures are normalized before crossing the public boundary. 165 166 All source modules are private implementation details. The crate root contains 167 only reviewed adapter-owned exports and does not expose an upstream client, 168 relay pool, Tokio handle, signer, storage handle, or retry worker. 169 170 ## Relay and network security 171 172 Profiles never inject a relay or infer destination policy. The caller supplies 173 every endpoint together with its public-Internet, exact-loopback, or typed 174 private-device policy and independent read-only/read-write authority. Public 175 profiles admit only public endpoints, simulator profiles admit only exact 176 loopback endpoints, and physical-device profiles admit public endpoints or 177 literal RFC1918 IPv4 and ULA IPv6 endpoints. 178 179 `RelayUrlPolicy::Public` accepts TLS WebSocket URLs with public hostnames or 180 global addresses. `Local` accepts exact loopback destinations and permits 181 plaintext WebSocket only for that class. `PrivateNetwork` accepts only literal RFC1918 IPv4 or ULA IPv6 destinations 182 and permits plaintext WebSocket for that explicit device-network class. It 183 rejects names, public, loopback, link-local, 184 unspecified, and multicast destinations before DNS or socket I/O. 185 186 Before opening a socket, the live connector resolves at most 32 addresses, 187 validates the entire answer set against the selected policy, and connects to a 188 validated address directly. The original hostname remains the TLS SNI and 189 certificate-verification identity. Proxy and Tor connection modes are denied; 190 there is no certificate, hostname, DNS-policy, or fallback bypass. 191 192 Callers that resolve addresses outside the adapter may use 193 [`RelayUrl::validate_resolved_addresses`] to apply the same destination-class 194 check before handing control to another network boundary. 195 196 ## Fetch, live subscription, delivery, and outcome behavior 197 198 Fetch accepts only configured readable Nostr targets, translates 199 transport-neutral kind, author, exact indexed single-letter tag, and event-time 200 selectors into Nostr filters, reapplies those selectors defensively, applies 201 the request page bound, deduplicates events by event ID, preserves per-relay 202 provenance, and emits an opaque versioned cursor bound to the exact target set 203 and selector when more collected results remain. Equal timestamps are ordered 204 by event ID so all received peers can be paged without timestamp-only loss. 205 Malformed relay events 206 are ignored and reported as a partial target outcome rather than admitted. 207 Fetch reports `Complete` only after the exact subscription receives EOSE 208 strictly before its absolute deadline. Deadline expiry is `Cancelled`, and a 209 relay result that exceeds the bounded inventory is `Partial`; neither state is 210 rewritten as completion even when it carries admissible events. 211 212 One fetch shares an 8 MiB incoming-byte budget, a 4,096-data-message attempt 213 limit and an 8,192-frame work limit across all selected relays and connection 214 generations. Accounting precedes WebSocket message assembly and Nostr decoding: 215 it includes decrypted HTTP upgrade bytes, frame headers and payloads, malformed 216 and discarded messages, duplicate events, unsolicited traffic, control frames, 217 and empty continuation frames. Text and binary message starts conservatively 218 consume data attempts without inspecting their JSON. The HTTP upgrade response 219 is also limited to 16 KiB. Each relay retains at most 1,000 events. Original 220 event objects from the network are limited to64KiB; the existing general 221 canonical decoder's256KiB ceiling cannot enlarge network admission. The WebSocket connector explicitly limits both frames and 222 complete messages to 512 KiB. SDK notification and canonical event collection 223 retain independent limits of 8,192 notifications, 4,096 events and 8 MiB. 224 Exhaustion is sticky and wakes all affected fetch collectors; later EOSE cannot 225 turn it into completion. At most64 fetch/live scopes may hold ingress registrations 226 on one transport; additional setup fails with partial evidence or a source error. 227 The meter reads into a fixed 4 KiB plaintext scratch buffer before admission; 228 at most that scratch capacity can be read beyond the remaining allowance and 229 discarded without reaching WebSocket assembly or Nostr parsing. This bound 230 does not claim control over kernel or TLS implementation buffers. 231 Shared canonical decoding rechecks the event, aggregate-byte and inventory 232 bounds before candidate collection. A fetch returns at most the caller's 233 validated 1,000-event page limit. EOSE describes only the requested relay 234 subscription and never proves complete global history. A response reaching the 235 1,000-event cap is `Partial` even when EOSE follows: the relay may still conceal 236 other events at the same timestamp or older history. Capped EOSE proves relay 237 availability and does not start connection-failure backoff. 238 239 After all collected candidates have been paged, a capped window returns 240 `NextPage::Cancelled` with an optional opaque older-window continuation. Shared 241 pull yields control at that boundary. Callers must disclose the partial 242 coverage before explicitly continuing older discovery; additional same-time 243 events remain unproven and are not declared recovered. The continuation moves 244 strictly before the capped timestamp using the same exact target/selector scope. 245 Malformed-only or out-of-bound results cannot invent a continuation; timestamp 246 zero cannot underflow. Ordinary `nostr-v2` event cursors remain supported; the 247 additive `nostr-until-v1` form is interpreted only by this concrete adapter. 248 No automatic retry, unlimited scan, new protocol or global completeness claim 249 is implied by either form. 250 251 Fetch and live observations retain the original signed event object before 252 upstream decoding. A shared queue bounds pending originals to256 events and4MiB, 253 including its reserved entry storage and retained object bytes. Exact relay, 254 subscription and registration ownership prevents cross-scope reuse. A digest 255 of the pinned decoder's representation correlates notifications without granting 256 authenticity or replacing original bytes. `SignedEvent::raw_json` retains those 257 originals for subsequent protected admission. Missing originals and saturation 258 produce incomplete fetch evidence or a live source error; no normalized fallback 259 is used. Live scope disposal preserves other live scopes and does not inherit 260 a finite fetch's cumulative work budget. Original data remains untrusted until 261 its owning signature/profile/participant checks. The owning contract is 262 [`source_original.v1.json`](../../contracts/protocol/source_original.v1.json). 263 264 Successor fetch/live decoding applies the same64KiB original-event cap to 265 content, individual tag fields and total tag bytes using explicit wire limits. 266 This permits complete listing profiles above the legacy4KiB tag ceiling while 267 retaining exact originals and separate signature/profile admission. Historical 268 general decoder defaults remain unchanged. 269 270 Live subscriptions use the same explicit readable targets and selector 271 translation. A caller checkpoint is scoped to one exact target and selector; 272 the adapter reconnects with Nostr's inclusive `since` timestamp, suppresses 273 older timestamps and the exact checkpoint event, and permits at-least-once 274 replay of other events from the checkpoint second. Within one subscription it 275 deduplicates exact event IDs, accepts same-second events in relay arrival order, 276 and never regresses the canonical target checkpoint. Each emitted event carries 277 exact relay provenance and that current checkpoint. 278 Event limits, absolute deadlines, explicit cancellation, source closure, and 279 stable repeated terminal results follow the generic subscription contract. 280 281 Delivery validates an already signed Radroots event and sends its retained JSON, 282 admits at most one attempt per configured writable target, and returns one 283 normalized receipt entry per requested target. Relay rejection, authentication 284 requirements, quota refusals, rate limits, timeouts, connection failures, missing results, and partial acceptance remain 285 explicit; this crate never retries, falls back to another transport, or 286 rewrites an unknown result as success. 287 288 An explicit quota refusal has the stable `quota_exceeded` code, a redacted 289 message and terminal rejection classification. It suppresses retries of the 290 unchanged request. Resolving the quota and authorizing further work belong to 291 the host; the adapter does not discard durable intent or recorded effects. 292 Rate limiting remains distinct from quota exhaustion. 293 294 Source and sink status are passive in-memory observations. A configured relay 295 starts unobserved and never appears available before successful read or write 296 evidence. Read and write evidence, failure counters, retry classes, and 297 next-attempt times are independent. Aggregate status distinguishes configured, 298 connecting, read-only, writable, degraded, offline, and terminally failed 299 states. Reading status does not connect to a relay, refresh DNS, or begin fetch 300 or delivery work. 301 302 ## Deadlines, cancellation, and commit points 303 304 The absolute deadline in each generic request bounds the complete operation. 305 The configured connection and request timeouts are upper bounds within that 306 remaining budget. An already-expired request performs no relay work. 307 Queued relay batches consume that same frozen deadline; they never receive a 308 new timeout after an earlier relay stalls. Bounded local normalization retains 309 the events and distinct outcomes already collected when network work ends, so 310 one timed-out relay cannot erase another relay's earlier successful evidence. 311 An expired queued target remains unattempted. The attempted flag records entry 312 into connection/publication work, not proof that bytes reached the wire or that 313 a remote effect occurred. A skipped target cannot report acceptance; missing 314 results cannot prove that an attempt was absent. 315 316 Dropping an unpolled fetch, subscription-start, or delivery future performs no 317 I/O. Once polled, cancellation is best effort at the socket boundary. For 318 delivery, submission to a relay is the remote commit point: after a relay 319 accepts the event, dropping the future cannot retract it. A missing final 320 response is therefore reported as unavailable or unknown evidence, never as 321 proof that no publication occurred. Fetch and live observation have no local 322 durable commit point. 323 324 A cancelled, timed-out or resource-limited fetch invalidates its selected 325 connection generations and signals SDK disconnection with reconnect disabled. 326 This includes connections whose earlier relay batch already completed; their 327 collected evidence remains intact. Receive admission stops at the generation 328 boundary, while ordinary SDK task teardown is asynchronous. These authenticated 329 sockets are shared with subscriptions, delivery and authentication, so those 330 overlapping operations can also observe disconnection. A successful fetch 331 removes its registration and preserves the shared connections. A later explicit 332 operation may establish a fresh connection and receives a fresh fetch budget; 333 closed generations never regain receive authority. 334 335 Dropping a pending subscription `next` or `cancel` future records a 336 cancellation request in the retained capability; its next operation awaits 337 relay unsubscription and returns the stable cancelled terminal result. 338 Dropping the capability itself cannot await network cleanup. Every published 339 relay subscription therefore also carries an upstream auto-close deadline 340 bounded by the request's absolute deadline, so remote work cannot continue 341 indefinitely. 342 343 NIP-42 authentication is explicit. [`NostrTransport::begin_authentication`] 344 records one bounded relay challenge and returns the exact host signing input. 345 The host signs outside this crate, then calls 346 [`NostrTransport::complete_authentication`] once. Relay submission is the AUTH 347 commit point. Rejecting a challenge consumes it without network access, and a 348 challenge is never retried or silently replaced. 349 350 ## Serialization and diagnostics 351 352 This package defines no public serialization feature or stable serialized 353 configuration format. Persist relay profiles in a host-owned, versioned 354 contract and reconstruct [`Config`] through its validating constructors. 355 Generic requests, pages, receipts, targets, and status values follow the 356 serialization contract of `radroots_transport`. 357 358 Public diagnostics are bounded and secret-safe. Raw upstream client errors, 359 relay URLs and resolved addresses, relay challenge payloads, signed 360 authentication events, credentials, and transport internals are not retained 361 in public errors, status, or normalized outcomes. 362 Applications should still avoid logging relay authentication inputs or signed 363 event JSON. 364 365 ## Features and runtime requirements 366 367 The package has no Cargo features. It is the standard-library shared protocol 368 adapter. Its constructor requires an explicit socket host through 369 `radroots_transport::host::websocket`. Native callers use 370 `radroots_transport_nostr_native::create_transport`; the browser provider is 371 separately governed. Concrete DNS, TCP, TLS and plaintext WebSocket metering do 372 not live in this package. The upstream Nostr relay client remains private. 373 The crate never creates an executor, installs a runtime, launches an 374 adapter-owned worker, installs a tracing subscriber, or owns process lifecycle. 375 The host must poll operations from a compatible executor and provide 376 clock/deadline policy through the generic requests. After an explicit operation 377 begins, the private upstream relay client owns its ordinary socket tasks and 378 the bounded auto-close timer for live relay subscriptions. 379 380 ## Intended consumers 381 382 - `radroots_sync` composes this source, subscriber, and sink with verification, 383 storage, projection, outbox, and explicit retry decisions. 384 - `radroots_sdk` selects and configures the adapter for advanced applications. 385 - Native services may compose it directly behind the generic transport SPIs. 386 387 Ordinary applications should normally use `radroots` or `radroots_sdk`. 388 Adapter authors and advanced hosts should depend on `radroots_transport` for 389 the generic contract and use this package only when Nostr relay I/O is needed. 390 391 ## Copyright 392 393 Except as otherwise noted, all files in the `radroots_transport_nostr` 394 distribution are copyright (c) 2025 Tyson Lupul. See `LICENSE` for usage, 395 redistribution, and warranty terms.