README.md (15985B)
1 # radroots_signing 2 3 `radroots_signing` is the protocol-neutral host SPI for authorizing and signing 4 exact Radroots authored-event plans. It owns actor provenance, signer capabilities and 5 status, bounded signing requests, verified receipts, progress, and normalized 6 secret-safe errors. 7 8 The crate is `no_std` with `alloc`. It does not own secret keys, keyrings, 9 network clients, NIP-46 sessions, SQL, UI prompts, or an async executor. 10 Concrete local Nostr signing belongs in `radroots_nostr`; remote protocol state 11 belongs in `radroots_nostr_connect`; applications compose those adapters in 12 `radroots_sdk` or their own host layer. 13 14 The authoritative package charter is the 15 [`radroots_signing` section of the Release V1 specification](../../contracts/crates/release_v1/radroots_crates_release_v1.toml). 16 17 ## Typical flow 18 19 1. A host resolves public actor provenance and roles into an [`Actor`]. 20 2. Event-codec code creates an immutable `AuthoredEventPlan`. 21 3. The host combines stable operation/artifact identity, actor, plan, deadline, and 22 cancellation policy into a [`SignRequest`]. Construction validates the 23 current authorization, required author role, public key, and provenance. 24 4. A dyn-compatible [`Signer`] implementation signs locally, delegates to a 25 remote device/service, or mediates explicit host interaction. 26 5. The implementation creates a [`SignReceipt`] from the originating request. 27 Receipt construction rejects plan drift and invalid Schnorr signatures. 28 29 The same SPI supports a purpose-tagged, HTTP-only 30 `BlossomAuthorizationPlan`. `SigningPurpose` keeps that BUD-11 credential 31 distinct from registry-authored relay events, while receipt verification still 32 binds the exact author, timestamp, kind, tags, content, event ID, deadline, and 33 cancellation signal. 34 35 [`Actor`]: crate::Actor 36 [`Signer`]: crate::Signer 37 [`SignRequest`]: crate::SignRequest 38 [`SignReceipt`]: crate::SignReceipt 39 40 ```rust 41 use radroots_event::{GenericEventDraft, contract::AuthorRole}; 42 use radroots_event_codec::authoring::AuthoredEventPlan; 43 use radroots_identity::PublicKey; 44 use radroots_protocol::runtime::v1::OperationId; 45 use radroots_signing::{ 46 Actor, AuthoredArtifactId, SignRequest, SigningIntentId, SigningOperationId, 47 actor::ActorSource, 48 request::{CancellationPolicy, SignPolicy}, 49 }; 50 51 let public_key = PublicKey::from_hex( 52 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 53 ) 54 .expect("canonical public key"); 55 let actor = Actor::new( 56 public_key, 57 ActorSource::ExplicitPublicKey, 58 [AuthorRole::Any], 59 ) 60 .expect("validated actor"); 61 let draft = GenericEventDraft::new( 62 "radroots.social.geochat.v1", 63 20_000, 64 1_700_000_000, 65 Vec::new(), 66 "hello from Radroots", 67 public_key.to_hex(), 68 ) 69 .expect("validated generic draft"); 70 let plan = AuthoredEventPlan::from_generic(draft).expect("exact plan"); 71 let intent_id = SigningIntentId::new( 72 SigningOperationId::new([1; 16]).expect("operation ID"), 73 AuthoredArtifactId::new([2; 16]).expect("artifact ID"), 74 ); 75 let policy = SignPolicy::new( 76 1_700_000_030_000, 77 CancellationPolicy::PreservePublishedRequest, 78 ) 79 .expect("bounded policy"); 80 let request = SignRequest::new(OperationId::SyncPush, intent_id, actor, plan, policy) 81 .expect("authorized signing request"); 82 83 assert_eq!(request.operation_kind(), OperationId::SyncPush); 84 ``` 85 86 The complete externally implementable SPI example is 87 [`examples/host_signer.rs`](examples/host_signer.rs). 88 89 ## Host SPI contract 90 91 The `provider` module adds a participant identity observation and separate 92 NIP-44 encryption/decryption capabilities. `ParticipantProvider` retains key 93 custody and exposes no secret key. `ProviderCall` freezes the observed key, 94 deadline and cancellation input without claiming authenticated command admission. 95 Private text is bounded before copying, zeroized when dropped and redacted in 96 diagnostics. The caller authenticates message carriers and applies the stricter 97 chat, record, rumor and complete-event limits before using these primitives. 98 Capability and replay observations do not replace actual provider qualification 99 or permit reissue of retained uncertain work. 100 101 `ParticipantProvider::recover_exact` is a separate original-intent boundary. 102 `ExactRecoveryRequest` retains the complete original intent and a distinct 103 recovery-call budget. The executor must check captured T1 replay policy, current 104 authorization and the actual adapter's documented method. Unsupported adapters 105 return original-bound indeterminate state without calling legacy or first-issue 106 signing. `ExactRecoveryOutcome` has no proven-unissued variant: refusal, expiry 107 or cancellation of this invocation proves nothing about the earlier invocation. 108 Obtained bytes are independently verified against the original fields/binding 109 and must remain owned through append-only durable capture. Provider capability 110 observations, request construction and outcome metadata confer no authority. 111 112 `SignerHandle` pairs a provider with its exact `SignerCallbacks` host scope. 113 The lower signing port owns this contract so adapters do not depend on an 114 executor. A composing lifecycle owner must quiesce dispatch, drain observers, 115 await callback closure and release roots on the required host thread. Neither 116 construction nor an identity observation grants a workspace or command role. 117 118 ```compile_fail 119 use radroots_signing::provider::PrivateText; 120 let text = PrivateText::new("private inquiry").unwrap(); 121 let duplicate = text.clone(); 122 ``` 123 124 ```compile_fail 125 use radroots_signing::provider::PrivateText; 126 let text = PrivateText::new("private inquiry").unwrap(); 127 let wire = serde_json::to_string(&text); 128 ``` 129 130 `Signer` is externally implementable and object-safe. Native hosts retain 131 `Send + Sync` and boxed `Future + Send`; WASM hosts and futures may remain local. 132 `host::Shared` selects native `Arc` or browser `Rc` for signer and progress 133 callback ownership. These target bounds let the host choose its executor; 134 the SPI does not select an async runtime or require an async-trait macro. 135 136 - `status` is observational and must not create a signing request or another 137 durable side effect. 138 - `sign` receives an owned, already-authorized request. Implementations must 139 honor its deadline and cancellation policy for the entire operation and must 140 create success only through `SignReceipt::from_signed_event`. 141 - Implementations must not install an executor or spawn hidden workers. The 142 composing host owns polling, scheduling, and process lifecycle. 143 - Every concrete adapter must document the exact point at which a request 144 becomes durable. Dropping the future before that point must leave no durable 145 effect; dropping it afterward does not imply rollback. 146 - Concrete backend failures are normalized to `radroots_signing::Error`. 147 Native sources may be retained with `std`, but display, debug, and versioned 148 protocol reports never copy source text. 149 150 ## Deadlines, cancellation, and commit points 151 152 `SignPolicy` carries an absolute Unix-millisecond deadline. A signer must reject work once 153 that deadline is reached; request construction does not read a clock. 154 155 `CancellationPolicy::LocalCooperative` is for local-only work that may stop 156 when cancellation is observed. `PreservePublishedRequest` is for operations 157 that may publish a durable remote request: cancellation before publication may 158 stop the operation, while cancellation after publication must preserve and 159 report the final remote state explicitly. Cancellation never silently converts 160 an unknown or committed remote state into success or rollback. 161 162 The SPI defines those rules but performs no I/O itself. Commit points belong to 163 the concrete adapter and must be visible in that adapter's documentation and 164 status/progress behavior. 165 166 ## Retained authored evidence 167 168 `AuthoredSignEvidence` records a cryptographically verified authored event even 169 when an already-started signer finishes after the caller's deadline or 170 cancellation. It binds exact event bytes, operation, artifact and signer request 171 identity to a positive injected observation time. That time records observation, 172 not proof of the instant of signing. `revalidate` checks the retained request 173 identity and all cryptographic fields again with the caller's own clock. 174 175 `Signer::sign_authored_evidence` is an optional hook. Its default delegates to 176 `sign`, verifies receipt identity and promotes the receipt; already-cancelled 177 requests are rejected before invoking the adapter. Existing adapters 178 compile unchanged. Adapters that discard late output need an override to retain 179 it. Overrides must still prevent new work after deadline or cancellation. The 180 host owns polling, lifecycle and durable reconciliation; the SPI adds no worker. 181 182 Evidence is a fact, not an active success receipt or authority to schedule new 183 signing, admission or delivery. `SignReceipt` remains deadline/cancellation 184 checked. The evidence constructor and default hook reject Blossom requests; 185 expiring BUD-11 authorization continues to use the strict active receipt path. 186 187 ## Serialization contract 188 189 Native `Actor` and `SignRequest` values are runtime-local and are not 190 serializable. `SignReceipt` and `AuthoredSignEvidence` can be serialized with 191 `serde` but cannot be 192 deserialized without the originating request; this prevents callers from 193 bypassing authorization and exact-draft verification. 194 195 The `serde` feature provides stable representations for passive policies, 196 capabilities, status, progress, challenges, and receipts. Versioned 197 cross-process error data is produced through `Error::to_report` and owned by 198 `radroots_protocol`. An authentication challenge URI is deliberately 199 host-displayable and serializable, so adapters must not embed credentials or 200 secret material in it. 201 202 ## Security and side effects 203 204 - Request construction separates current authorization from historical plan integrity before role, key, and provenance 205 authorization and never invokes a signer on failure. 206 - A successful receipt proves exact equality of author, timestamp, kind, tags, 207 content, and event ID with the exact request plan, plus a valid signature. 208 - Callers at a persistence or HTTP boundary must revalidate an untrusted host 209 signer's returned event against their retained request and locally observed 210 completion time before committing or transmitting it. 211 - `Error` display/debug output and protocol reports are redacted. Under `std`, 212 a caller may explicitly inspect a preserved native error source locally. 213 - `AuthChallenge` debug output redacts its URI; the value accepts only bounded 214 control-free HTTPS URIs and remains untrusted navigation input for hosts. 215 - This crate forbids unsafe code and contains no secret-key type, persistence, 216 network transport, global state, timer, or runtime initialization. 217 218 ## Features 219 220 | Feature | Default | Contract | 221 | --- | --- | --- | 222 | `std` | yes | Uses `std` collections and permits preserved native error sources; no runtime, I/O, or global initialization is added. | 223 | `serde` | yes | Adds serialization for explicitly passive public values and deserialization only where validated reconstruction is safe. | 224 | `chat` | no | Adds bounded chat-seal conversion and authenticated DM advertisements. | 225 | `commerce` | no | Adds exact structured-commerce seal conversion, authenticated DM advertisements and complete original plan verification. | 226 | `artifacts` | no | Adds captured chat/public-listing artifact conversion. | 227 228 Features are additive. `--no-default-features` provides the `no_std + alloc` 229 core, and `serde` is supported independently of `std`. 230 231 ## Intended consumers 232 233 - `radroots_nostr` implements concrete local signing. 234 - `radroots_nostr_connect` supplies remote protocol state without owning this 235 SPI's host composition. 236 - `radroots_sync` and `radroots_sdk` orchestrate authorized requests and 237 consume verified receipts. 238 - CLI, Studio, mobile/FFI, and service hosts resolve actor provenance, choose 239 adapters, display authentication challenges, and own cancellation/runtime 240 behavior. 241 242 Applications that only need ordinary Radroots operations should normally use 243 `radroots` or `radroots_sdk`; implement this package directly when providing a 244 new signer adapter or advanced host composition. 245 246 ## Exact issuance and obtained results 247 248 `issuance::SigningIntent` binds the canonical 256-bit domain operation ID, 249 command digest, exact authored preimage, role/recipient and captured deadline. 250 `issuance::ArtifactRole` and `issuance::IntentBinding` reexport the portable 251 Protocol data definitions; the exact v1 commitment bytes remain unchanged. 252 Constructing a binding proves no retained claim or dispatch authority. 253 Its generic complete-event limit is 64 KiB, including escaped content, tags, 254 keys and signature. Executor chat/record/rumor limits remain tighter. Values and 255 bindings are neither authenticated command contexts nor durable admission. 256 257 `ParticipantProvider::sign_exact` has no fallback to the legacy signer method. 258 An unsupported provider reports unavailable. `ProviderState::exact_issuance` 259 is observed separately from legacy replay metadata. The concrete local adapter 260 reports non-replayable exact issuance; no durable retrieval or safe uncertain 261 reissue is inferred from custody of the key or a stable event ID. 262 263 `SigningOutcome` binds every classification to the original intent. Obtained 264 bytes are verified against every signed field and signature, own their original 265 representation, and carry optional observation time. A failed, expired or 266 cancelled completion observation cannot discard valid bytes. Rejected output 267 has fixed forensic metadata; prefix digests report their actual coverage. No 268 classification claims that T0/T1/S/T2/D ran, and rejection is not proof that 269 issuance never happened. The executor owns polling and durable capture through 270 its safe journal boundary; dropping an observer cannot erase that responsibility. 271 272 The legacy request/evidence API retains its existing callers while the 273 successor workers and providers migrate. Its sixteen-byte identities and 274 mandatory observation clock do not qualify the new execution contract. 275 276 277 With `chat`, `issuance::VerifiedDmRelayAdvertisement` checks bounded exact 278 kind-10050 fields, event ID, Schnorr signature and expected participant while 279 retaining original bytes. Capturing an explicit advertised subset preserves 280 that source observation; it establishes no global freshness, configured or 281 available transport, workspace grant, consent or signing permission. Missing DM 282 information supplies no fallback target. Exact seal conversion also compares the 283 originating captured operation and command commitment before creating an intent. 284 Recovery outcomes enforce the original callback binding with the same bounded 285 rejection/fingerprint policy as issuance outcomes. A mismatched callback cannot 286 be promoted to the expected operation; a correctly bound obtained artifact is 287 retained unchanged. Callback rejection remains distinct from nonissuance. 288 289 With `commerce`, `commerce::VerifiedCommerceSigningPlan::verify` qualifies both 290 original peer/self ciphertexts against their captured rumor and verifies signed 291 DM advertisements, selected route subsets and the actual provider's replay and 292 private-crypto capabilities. It observes identity and capabilities around each 293 decryption, signs nothing and retains the original call deadline. The proof 294 grants no workspace consent, T1 commit, dispatch, stock or network authority. 295 This portable verifier is shared by scoped execution and concrete native T1; 296 the predecessor Nostr export is removed without an alias. 297 298 `issuance::ExactIssuer` is the narrow target-aware exact-signature IO port. 299 Participant providers delegate to their existing exact method; an observed 300 execution scope can supply the same port while retaining identity, capability 301 and callback lifecycle checks. The port grants no first-dispatch authority or 302 adapter qualification. A caller-created outcome is not proof of an original 303 invocation: the concrete executor must own its fresh permit through that call.