Skip to main content

hyprstream_rpc/
lib.rs

1//! RPC infrastructure for hyprstream services.
2//!
3//! This crate provides:
4//! - `ToCapnp` / `FromCapnp` traits and derive macros for Cap'n Proto serialization
5//! - ZMTP framing over UDS/QUIC/iroh transports
6//! - Service dispatch helpers
7//! - Ed25519 signed envelopes for request authentication
8//! - DH key exchange + HMAC for streaming response authentication
9//!
10//! # Security Model
11//!
12//! All RPC messages are wrapped in signed envelopes:
13//! - **Transport layer**: TLS 1.3 (QUIC) or UDS peer credentials (IPC)
14//! - **Application layer**: Ed25519 signatures (survives message forwarding)
15//!
16//! Streaming responses use HMAC-SHA256 derived from DH shared secrets.
17//!
18//! # Feature Flags
19//!
20//! - Default: Ristretto255 for DH key exchange (prime-order group, no cofactor issues)
21//! - `fips`: ECDH P-256 for FIPS 140-2 compliance
22//!
23//! # Example
24//!
25//! ```ignore
26//! use hyprstream_rpc::prelude::*;
27//!
28//! #[derive(FromCapnp)]
29//! #[capnp(my_schema_capnp::my_response)]
30//! pub struct MyResponse {
31//!     pub result: String,
32//! }
33//!
34//! // Client method becomes a one-liner
35//! async fn get_result(&self) -> Result<MyResponse> {
36//!     self.rpc.call(GetResultRequest).await
37//! }
38//! ```
39
40// ============================================================================
41// Modules available on ALL targets (including wasm32)
42// ============================================================================
43
44// Cap'n Proto generated modules
45pub mod common_capnp {
46    #![allow(dead_code, unused_imports)]
47    #![allow(
48        clippy::all,
49        clippy::unwrap_used,
50        clippy::expect_used,
51        clippy::match_same_arms
52    )]
53    #![allow(
54        clippy::semicolon_if_nothing_returned,
55        clippy::doc_markdown,
56        clippy::indexing_slicing
57    )]
58    #![allow(
59        clippy::cast_possible_truncation,
60        clippy::cast_sign_loss,
61        clippy::cast_possible_wrap
62    )]
63    include!(concat!(env!("OUT_DIR"), "/common_capnp.rs"));
64}
65
66pub mod events_capnp {
67    #![allow(dead_code, unused_imports)]
68    #![allow(
69        clippy::all,
70        clippy::unwrap_used,
71        clippy::expect_used,
72        clippy::match_same_arms
73    )]
74    #![allow(
75        clippy::semicolon_if_nothing_returned,
76        clippy::doc_markdown,
77        clippy::indexing_slicing
78    )]
79    #![allow(
80        clippy::cast_possible_truncation,
81        clippy::cast_sign_loss,
82        clippy::cast_possible_wrap
83    )]
84    include!(concat!(env!("OUT_DIR"), "/events_capnp.rs"));
85}
86
87pub mod nine_capnp {
88    #![allow(dead_code, unused_imports)]
89    #![allow(
90        clippy::all,
91        clippy::unwrap_used,
92        clippy::expect_used,
93        clippy::match_same_arms
94    )]
95    #![allow(
96        clippy::semicolon_if_nothing_returned,
97        clippy::doc_markdown,
98        clippy::indexing_slicing
99    )]
100    #![allow(
101        clippy::cast_possible_truncation,
102        clippy::cast_sign_loss,
103        clippy::cast_possible_wrap
104    )]
105    include!(concat!(env!("OUT_DIR"), "/nine_capnp.rs"));
106}
107
108pub mod streaming_capnp {
109    #![allow(dead_code, unused_imports)]
110    #![allow(
111        clippy::all,
112        clippy::unwrap_used,
113        clippy::expect_used,
114        clippy::match_same_arms
115    )]
116    #![allow(
117        clippy::semicolon_if_nothing_returned,
118        clippy::doc_markdown,
119        clippy::indexing_slicing
120    )]
121    #![allow(
122        clippy::cast_possible_truncation,
123        clippy::cast_sign_loss,
124        clippy::cast_possible_wrap
125    )]
126    include!(concat!(env!("OUT_DIR"), "/streaming_capnp.rs"));
127}
128
129pub mod annotations_capnp {
130    #![allow(dead_code, unused_imports)]
131    #![allow(
132        clippy::all,
133        clippy::unwrap_used,
134        clippy::expect_used,
135        clippy::match_same_arms
136    )]
137    #![allow(
138        clippy::semicolon_if_nothing_returned,
139        clippy::doc_markdown,
140        clippy::indexing_slicing
141    )]
142    #![allow(
143        clippy::cast_possible_truncation,
144        clippy::cast_sign_loss,
145        clippy::cast_possible_wrap
146    )]
147    include!(concat!(env!("OUT_DIR"), "/annotations_capnp.rs"));
148}
149
150pub mod optional_capnp {
151    #![allow(dead_code, unused_imports)]
152    #![allow(
153        clippy::all,
154        clippy::unwrap_used,
155        clippy::expect_used,
156        clippy::match_same_arms
157    )]
158    #![allow(
159        clippy::semicolon_if_nothing_returned,
160        clippy::doc_markdown,
161        clippy::indexing_slicing
162    )]
163    #![allow(
164        clippy::cast_possible_truncation,
165        clippy::cast_sign_loss,
166        clippy::cast_possible_wrap
167    )]
168    include!(concat!(env!("OUT_DIR"), "/optional_capnp.rs"));
169}
170
171pub mod common_types {
172    #![allow(dead_code, unused_imports, unused_variables)]
173    #![allow(clippy::all)]
174    extern crate self as hyprstream_rpc;
175    hyprstream_rpc_derive::generate_rpc_service!("common");
176}
177
178/// Code-generated streaming data types (#273): `StreamInfo`, `StreamOpt`, and the
179/// five QoS axis unions (`Ordering`/`Delivery`/`Completion`/`Retention`/
180/// `OverflowPolicy`). Re-exported through `stream_info` (the canonical hub) so
181/// service codegen and call sites keep resolving `hyprstream_rpc::stream_info::*`.
182///
183/// NOTE: this module also generates the wire types (`StreamBlock`, `StreamPayload`,
184/// `StreamControl`, etc.). Those are NOT re-exported — `streaming.rs` remains the
185/// authoritative hand-written implementation for the wire path; the generated
186/// duplicates live here unused (`#![allow(dead_code)]`).
187pub mod streaming_types {
188    #![allow(dead_code, unused_imports, unused_variables)]
189    #![allow(clippy::all)]
190    extern crate self as hyprstream_rpc;
191    hyprstream_rpc_derive::generate_rpc_service!("streaming");
192}
193
194pub mod authorization_witness;
195pub mod capnp;
196pub mod cid;
197pub mod crypto;
198pub mod envelope;
199pub mod error;
200pub mod platform;
201pub mod proof;
202pub mod rpc_client;
203pub mod sensitive;
204pub mod stream_epoch;
205pub mod stream_info;
206pub mod zmtp_framing;
207// #324/N1 intentionally stops at a crate-internal data contract. The allow is
208// removed when the first reassembly/transport consumer lands.
209#[allow(dead_code)]
210pub(crate) mod activation_envelope;
211
212// ============================================================================
213// Cross-platform modules (available on all targets including wasm32)
214// ============================================================================
215
216/// Schema introspection metadata types — used by proc macro codegen on all targets.
217pub mod metadata {
218    /// Re-export of the `inventory` crate so generated code (`generate_rpc_service!`)
219    /// can submit `VfsNodeTable` entries without forcing every consumer crate to
220    /// declare an `inventory` dependency — `hyprstream_rpc::metadata::inventory`
221    /// resolves wherever `hyprstream-rpc` is a dependency (same pattern the crate
222    /// already uses internally for `ScopeDefinition`).
223    ///
224    /// Native-only (#1305): `inventory`'s link-time section registration does not
225    /// work on wasm32, so the dep lives under `cfg(not(target_arch = "wasm32"))`
226    /// and the codegen emits the `submit!` behind the same cfg. On wasm32 the
227    /// generated `vfs_nodes()` table fn remains directly callable — that is the
228    /// wasm-compatible path; nothing in the browser client consumes the
229    /// link-time registry (the only iterator is the native genesis gate).
230    #[cfg(not(target_arch = "wasm32"))]
231    pub use inventory;
232
233    pub use crate::_metadata::*;
234}
235mod _metadata;
236
237// ============================================================================
238// Transport traits (available on ALL targets)
239pub mod stream_consumer;
240pub mod transport_traits;
241
242// Native-only modules (not compiled for wasm32)
243// ============================================================================
244
245pub mod auth;
246#[cfg(not(target_arch = "wasm32"))]
247pub mod dial;
248#[cfg(not(target_arch = "wasm32"))]
249pub mod event_subject;
250#[cfg(not(target_arch = "wasm32"))]
251pub mod events;
252#[cfg(not(target_arch = "wasm32"))]
253pub mod latch;
254#[cfg(not(target_arch = "wasm32"))]
255pub mod moq_authz;
256#[cfg(not(target_arch = "wasm32"))]
257pub mod moq_event;
258#[cfg(not(target_arch = "wasm32"))]
259pub mod moq_stream;
260#[cfg(not(target_arch = "wasm32"))]
261pub mod registry;
262#[cfg(not(target_arch = "wasm32"))]
263pub mod resolver;
264#[cfg(not(target_arch = "wasm32"))]
265pub mod service;
266#[cfg(not(target_arch = "wasm32"))]
267pub mod service_entry;
268#[cfg(not(target_arch = "wasm32"))]
269pub mod stream_provenance;
270#[cfg(not(target_arch = "wasm32"))]
271pub mod streaming;
272#[cfg(not(target_arch = "wasm32"))]
273pub mod transport;
274// Shared `did:key` (Ed25519) codec — now the single canonical home in the light
275// `hyprstream-crypto` crate (#916). Re-exported so existing `crate::did_key::…`
276// and external `hyprstream_rpc::did_key::…` paths keep compiling unchanged; the
277// native `did_web` resolver and explicit DID consumers share this implementation.
278// wasm iroh reach APIs do not convert NodeId to or from `did:key` (#1031).
279pub use hyprstream_crypto::did_key;
280#[cfg(not(target_arch = "wasm32"))]
281pub mod did_web;
282// did:plc federation intake (#1161): configurable PLC directory, egress-
283// allowlisted fetch, TTL cache, subject binding, and no write API.
284#[cfg(not(target_arch = "wasm32"))]
285pub mod did_plc;
286// Pure DID URL parser + inert dereference plan (#906, at9p epic #880 G1).
287// Available on every target and intentionally independent of DID resolution,
288// transport decoding, dial targets, admission, and carrier possession.
289#[cfg(not(target_arch = "wasm32"))]
290pub mod admission;
291pub mod did_url;
292// Additive, session-scoped PQ binding overlay: trust-on-first-use continuity
293// for dynamically-identified clients, with out-of-band promotion. Consulted by
294// the envelope verify path after the admin-anchored store misses; never mutates
295// that store.
296#[cfg(not(target_arch = "wasm32"))]
297pub mod session_pq_overlay;
298// The real, method-dispatched `IdentityResolver` (#579). Native-only: the
299// did:web arm depends on `did_web`'s DID-document helpers.
300#[cfg(not(target_arch = "wasm32"))]
301pub mod identity_resolver;
302#[cfg(not(target_arch = "wasm32"))]
303pub mod notify;
304#[cfg(not(target_arch = "wasm32"))]
305pub mod paths;
306#[cfg(not(target_arch = "wasm32"))]
307pub mod socket;
308
309// ============================================================================
310// WASM-bindgen API (wasm32 target only)
311// ============================================================================
312
313#[cfg(target_arch = "wasm32")]
314pub mod wasm_api;
315#[cfg(target_arch = "wasm32")]
316pub mod web_transport;
317// #409 Path A: browser counterpart to native `dial`. Compiles only on wasm32;
318// see `dial_wasm.rs` for why this is a separate module rather than an arm in
319// native `dial()` (which is itself `#[cfg(not(target_arch = "wasm32"))]`).
320pub mod browser_provisioning;
321#[cfg(target_arch = "wasm32")]
322pub mod dial_wasm;
323/// Browser-side RFC 8693 token-exchange (#1314) for the wasm client. Pure
324/// parsing helpers compile on all targets (unit-tested on native); the browser
325/// `fetch` glue is `wasm32`-only.
326pub mod wasm_token_exchange;
327// Iroh carrier reach + pkarr helpers for wasm32. NodeId is exposed only as an
328// endpoint address/diagnostic; no DID or application-identity conversion exists.
329#[cfg(target_arch = "wasm32")]
330pub mod iroh_peer;
331
332// ============================================================================
333// Re-exports available on ALL targets
334// ============================================================================
335
336pub use capnp::{serialize_message, FromCapnp, ToCapnp};
337pub use rpc_client::{
338    CallOptions, PreSealGuard, RequestBuilder, RpcClient, RpcClientImpl, RpcClientProvider,
339};
340pub use transport_traits::{PublishSink, Signer, Transport};
341#[cfg(not(target_arch = "wasm32"))]
342pub mod federated_identity;
343pub mod identity;
344pub mod node_identity;
345pub mod signer;
346pub use crypto::{
347    generate_signing_keypair, signing_key_from_bytes, verifying_key_from_bytes, DefaultKeyExchange,
348    KeyExchange, SharedSecret, SigningKey, StreamHmacState, VerifyingKey,
349};
350pub use stream_info::StreamInfo;
351
352#[cfg(not(feature = "fips"))]
353pub use crypto::{generate_ephemeral_keypair, ristretto_dh, RistrettoPublic, RistrettoSecret};
354
355#[cfg(not(target_arch = "wasm32"))]
356pub use envelope::unwrap_envelope;
357pub use envelope::{
358    unwrap_and_verify, Authorization, EnvelopeVerification, FederatedToken, InMemoryNonceCache,
359    KeyedPqTrustStore, NonceCache, PqTrustStore, RequestEnvelope, ResponseEnvelope, SignedEnvelope,
360    Subject, TokenClaims, UnwrapOptions, MAX_CLOCK_SKEW_MS, MAX_TIMESTAMP_AGE_MS,
361};
362pub use error::{EnvelopeError, EnvelopeResult, Result, RpcError};
363
364// ============================================================================
365// Native-only re-exports
366// ============================================================================
367
368#[cfg(not(target_arch = "wasm32"))]
369pub use hyprstream_rpc_derive::{authorize, service_factory, FromCapnp, ToCapnp};
370
371#[cfg(not(target_arch = "wasm32"))]
372pub use resolver::{NetworkDiscoveryResolver, Resolver, ResolverProfile, ServiceQuery};
373
374#[cfg(all(not(target_arch = "wasm32"), test))]
375pub use resolver::{
376    retry_validated_candidates, select_service_candidate, select_service_candidates,
377    AcceptedStateEvidence, AnchoredKemRecipient, CandidateDecision, ResolutionEvidence,
378    SelectedService, ServiceCandidate,
379};
380
381#[cfg(not(target_arch = "wasm32"))]
382pub use registry::SocketKind;
383
384#[cfg(not(target_arch = "wasm32"))]
385pub use service::{Continuation, EnvelopeContext, RequestService, ServiceHandle, Spawnable};
386
387#[cfg(not(target_arch = "wasm32"))]
388pub use streaming::{
389    derive_client_stream_keys, progress_channel, ChannelProgressReporter, ProgressUpdate,
390    ResponseStream, StreamChannel, StreamContext, StreamPayload, StreamPayloadData, StreamVerifier,
391};
392
393// ============================================================================
394// Prelude (native only — too many native-only types)
395// ============================================================================
396
397#[cfg(not(target_arch = "wasm32"))]
398pub mod prelude {
399    pub use crate::{
400        // Crypto
401        generate_signing_keypair,
402        // Serialization
403        serialize_message,
404        signing_key_from_bytes,
405        unwrap_and_verify,
406        // Envelope
407        unwrap_envelope,
408        verifying_key_from_bytes,
409        Authorization,
410        DefaultKeyExchange,
411        // Service (transport)
412        EnvelopeContext,
413        // Error
414        EnvelopeError,
415        EnvelopeResult,
416        EnvelopeVerification,
417        FromCapnp,
418        InMemoryNonceCache,
419        KeyExchange,
420        NonceCache,
421        RequestEnvelope,
422        RequestService,
423        ResponseEnvelope,
424        Result,
425        RpcError,
426        ServiceHandle,
427        SharedSecret,
428        SignedEnvelope,
429        SigningKey,
430        // Streaming
431        StreamContext,
432        StreamHmacState,
433        Subject,
434        ToCapnp,
435        UnwrapOptions,
436        VerifyingKey,
437        MAX_CLOCK_SKEW_MS,
438        MAX_TIMESTAMP_AGE_MS,
439    };
440
441    #[cfg(not(feature = "fips"))]
442    pub use crate::{generate_ephemeral_keypair, ristretto_dh, RistrettoPublic, RistrettoSecret};
443
444    // Registry (with renamed imports for convenience)
445    pub use crate::registry::{
446        global as registry_global, init as registry_init, try_global as registry_try_global,
447        EndpointMode, EndpointRegistry, IpcResolver, LocalInprocResolver, ServiceEntry,
448        ServiceRegistration,
449    };
450
451    // Transport
452    pub use crate::transport::TransportConfig;
453}
454
455// ============================================================================
456// Systemd helpers (native only)
457// ============================================================================
458
459#[cfg(all(not(target_arch = "wasm32"), feature = "systemd"))]
460pub fn has_systemd() -> bool {
461    systemd::daemon::booted().unwrap_or(false)
462}
463
464#[cfg(all(not(target_arch = "wasm32"), not(feature = "systemd")))]
465pub fn has_systemd() -> bool {
466    false
467}