Skip to main content

stratum_node_core/
lib.rs

1//! Zero-I/O core types for Stratum pod nodes.
2//!
3//! **Pre-release:** this is `0.1.0-alpha`. The API and formats may change
4//! before 0.1.0.
5//!
6//! A Stratum node is administered by a Nostr key. This crate holds the parts
7//! of that model that need no I/O, so the controller, the command-line client
8//! and any other implementation agree byte for byte:
9//!
10//! - **Principals.** [`DidNostr`] is a `did:nostr` identifier over a BIP-340
11//!   x-only public key, convertible to and from hex and NIP-19 `npub`.
12//! - **Identifiers.** [`EventId`], [`Sha256Digest`], [`ChallengeId`],
13//!   [`InvitationId`], [`OperationId`], [`Revision`] and [`UnixTime`] each
14//!   have one canonical
15//!   text form and validate on construction and deserialisation.
16//! - **Events.** [`SignedEvent`] is a NIP-01 event whose ID and signature
17//!   have been verified; [`UnsignedEvent`] is one waiting to be signed by a
18//!   [`NostrSecretKey`].
19//! - **Signed requests.** [`verify_request`] checks an `Authorization: Nostr`
20//!   header against the request the server received, under a profile
21//!   stricter than NIP-98, and returns a [`VerifiedRequest`].
22//!   [`NostrSecretKey::sign_request`] produces such headers, and
23//!   [`NostrSecretKey::sign_request_with_nonce`] adds a random `nonce` tag
24//!   so identical requests signed in one second are distinct events.
25//!   [`verify_request_without_body`] checks everything but the body digest,
26//!   for a proxy that never sees the body, and returns a
27//!   [`BodyUncheckedRequest`]. [`UnverifiedRequest`] parses a header once so
28//!   its claimed author can be looked up before a signature is verified.
29//! - **Bootstrap claims.** [`ClaimBody`] is the immutable body an
30//!   administrator signs to claim a node, kept as the exact bytes issued.
31//! - **Pod paths.** [`PodPath`] is a request path under the pod allow-list
32//!   (`/pods/<pk>/…` or `/pods/<pk>.acl`) and its shape rules, with the
33//!   owner, container and sibling-ACL helpers a client needs;
34//!   [`is_valid_pod_query`] checks a query string.
35//! - **Admission.** [`AdmissionClaim`] is the body a tenant signs to redeem
36//!   an invitation ([`InvitationId`]) after reading
37//!   [`ADMISSION_NOTICE_V1`]; [`MemberState`] names the states a membership
38//!   moves through, with one predicate each for capacity, provisioning and
39//!   the gate's directory. [`DirectoryMemberState`] is the gate's tolerant
40//!   reading of a directory entry, which keeps an unknown state as a
41//!   refused member instead of failing the whole document.
42//! - **Member administration.** [`MemberActionRequest`], [`RemoveRequest`],
43//!   [`SuspendResponse`], [`ResumeResponse`], [`ArchiveResponse`],
44//!   [`RemoveResponse`] and [`MemberView`] are the bodies of the
45//!   administrator's suspend, resume, archive, remove and member-view
46//!   routes; [`Enforcement`] reports whether the gate applies a suspension,
47//!   and [`RemovalArchive`] is an archive reference or a waiver.
48//!   [`ErrorCode`] defines the codes `suspended`, `archive_required` and
49//!   `pod_data_present`.
50//! - **Profile document.** [`profile_card_path`] and [`profile_owner`] give
51//!   the one public path per pod and the gate's byte-exact matcher for it;
52//!   [`profile_card`] and [`profile_acl`] are the document and ACL a client
53//!   writes, and [`card_names_owner`] is `profile init`'s conservative
54//!   check of an existing card.
55//!
56//! The crate never reads a clock, a random source, the environment, the
57//! filesystem or the network. The current time, auxiliary signing
58//! randomness, challenge bytes and the expected request are all parameters,
59//! which keeps every check deterministic and testable.
60//!
61//! Cryptography comes from maintained crates: BIP-340 Schnorr from `k256`,
62//! SHA-256 from `sha2`, bech32 from `bech32`. The signing and verification
63//! paths are tested against the published BIP-340 vectors.
64//!
65//! # Replay protection
66//!
67//! [`verify_request`] proves who signed a request, for which URL, method and
68//! body, and roughly when. It does not make a request single use. A server
69//! must record [`VerifiedRequest::event_id`] durably and refuse a repeat.
70//!
71//! # Example
72//!
73//! ```
74//! use stratum_node_core::{verify_request, ExpectedRequest, NostrSecretKey, RequestPolicy, UnixTime};
75//!
76//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
77//! // Client side: sign a request. Use real randomness for the 32 bytes.
78//! let key = NostrSecretKey::from_nsec(
79//!     "nsec1vl029mgpspedva04g90vltkh6fvh240zqtv9k0t9af8935ke9laqsnlfe5",
80//! )?;
81//! let body = br#"{"node":"did:nostr:...","operation_id":"op-1"}"#;
82//! let request = ExpectedRequest::new("POST", "http://127.0.0.1:7070/api/v1/config/apply", Some(body));
83//! let now = UnixTime::from_secs(1_764_720_000);
84//! let header = key.sign_request(&request, now, &[0x42; 32])?;
85//!
86//! // Server side: verify it against what actually arrived.
87//! let verified = verify_request(&header, &request, now, &RequestPolicy::new())?;
88//! assert_eq!(verified.signer(), key.public());
89//! # Ok(())
90//! # }
91//! ```
92
93mod admission;
94mod claim;
95mod did;
96mod encoding;
97mod error_code;
98mod event;
99mod id;
100mod members;
101mod pod_path;
102mod profile;
103mod request;
104mod schnorr;
105mod secret;
106
107pub use admission::{
108    admission_notice_v1_sha256, AdmissionClaim, AdmissionFields, CheckAdmissionError,
109    DirectoryMemberState, MemberState, ParseAdmissionError, ParseMemberStateError,
110    ADMISSION_CLAIM_PURPOSE, ADMISSION_NOTICE_V1,
111};
112pub use claim::{CheckClaimError, ClaimBody, ClaimFields, ParseClaimError, CLAIM_BODY_VERSION};
113pub use did::{DidNostr, ParseDidError};
114pub use error_code::ErrorCode;
115pub use event::{ParseEventError, SignedEvent, UnsignedEvent};
116pub use id::{
117    ChallengeId, EventId, InvitationId, OperationId, ParseIdError, Revision, Sha256Digest,
118    UnixTime, OPERATION_ID_MAX_LEN,
119};
120pub use members::{
121    ArchiveResponse, Enforcement, MemberActionRequest, MemberView, ParseRemovalArchiveError,
122    RemovalArchive, RemoveRequest, RemoveResponse, ResumeResponse, SuspendResponse,
123};
124pub use pod_path::{is_acl_path, is_valid_pod_query, ParsePodPathError, PodPath};
125pub use profile::{
126    card_names_owner, profile_acl, profile_card, profile_card_path, profile_owner,
127    PROFILE_CARD_RELATIVE, PROFILE_CONTENT_TYPE, PROFILE_MAX_BYTES,
128};
129pub use request::{
130    verify_request, verify_request_without_body, BodyUncheckedRequest, ExpectedRequest,
131    RequestPolicy, RequestPolicyError, RequestTarget, UnverifiedRequest, VerifiedRequest,
132    VerifyRequestError, HTTP_AUTH_KIND,
133};
134pub use secret::{NostrSecretKey, ParseKeyError, SignError};
135
136/// The version of the signed-request profile [`verify_request`] enforces and
137/// [`NostrSecretKey::sign_request`] and
138/// [`NostrSecretKey::sign_request_with_nonce`] produce. The `nonce` tag is
139/// outside the profile, which ignores tags it does not name.
140pub const REQUEST_PROFILE_VERSION: u32 = 1;
141
142/// Compiles and runs the README example as a doctest.
143#[cfg(doctest)]
144#[doc = include_str!("../README.md")]
145struct ReadmeDoctests;