commit 7e81581f79cdff774ea51cb01bd9c07fe1290f9a parent d5a8ff3856f98aaa4906341ea00df975d15d25ea Author: triesap <tyson@radroots.org> Date: Tue, 20 Oct 2026 12:34:21 +0000 execution: Retain typed public signing plans in the shared journal - Capture bounded exact listing preimages and explicit public plan metadata - Share replay declarations and plan ownership while preserving chat bytes - Confirm encrypted native T1 recovery and refuse unsupported private effects - Verify native and browser workflows, generated APIs and dependency guards Diffstat:
52 files changed, 1053 insertions(+), 228 deletions(-)
diff --git a/contracts/api_baselines/radroots_protocol.txt b/contracts/api_baselines/radroots_protocol.txt @@ -63,10 +63,6 @@ pub const radroots_protocol::capability::v1::SCHEMAS: &[radroots_protocol::schem pub fn radroots_protocol::capability::v1::schema_registry() -> core::result::Result<radroots_protocol::schema::Registry, radroots_protocol::schema::Error> pub fn radroots_protocol::capability::v1::validate_catalog(&[radroots_protocol::capability::v1::TransportDescriptor]) -> core::result::Result<(), radroots_protocol::capability::v1::Error> pub mod radroots_protocol::chat -pub enum radroots_protocol::chat::ChatReplay -pub radroots_protocol::chat::ChatReplay::ExactReplayByRequestId -pub radroots_protocol::chat::ChatReplay::LocalReplaySafe -pub radroots_protocol::chat::ChatReplay::NonReplayable pub struct radroots_protocol::chat::CapturedDmRoute impl radroots_protocol::chat::CapturedDmRoute pub fn radroots_protocol::chat::CapturedDmRoute::from_observed_descriptor(radroots_identity::key::PublicKey, radroots_domain::identifier::EnvelopeEventId, &str, &[alloc::string::String]) -> core::result::Result<Self, radroots_protocol::nip01::WireError> @@ -111,13 +107,15 @@ pub const fn radroots_protocol::chat::ChatSigningPlan::command_digest(&self) -> pub const fn radroots_protocol::chat::ChatSigningPlan::created_at(&self) -> radroots_domain::context::UnixSeconds pub const fn radroots_protocol::chat::ChatSigningPlan::digest(&self) -> &[u8; 32] pub const fn radroots_protocol::chat::ChatSigningPlan::message_id(&self) -> radroots_domain::identifier::MessageId -pub fn radroots_protocol::chat::ChatSigningPlan::new(&radroots_protocol::command::CapturedChatCommand, radroots_domain::context::UnixSeconds, alloc::vec::Vec<radroots_protocol::chat::ChatSeal>, alloc::vec::Vec<radroots_protocol::chat::CapturedDmRoute>, radroots_protocol::chat::ChatReplay) -> core::result::Result<Self, radroots_protocol::nip01::WireError> +pub fn radroots_protocol::chat::ChatSigningPlan::new(&radroots_protocol::command::CapturedChatCommand, radroots_domain::context::UnixSeconds, alloc::vec::Vec<radroots_protocol::chat::ChatSeal>, alloc::vec::Vec<radroots_protocol::chat::CapturedDmRoute>, radroots_protocol::plan::SigningReplay) -> core::result::Result<Self, radroots_protocol::nip01::WireError> pub const fn radroots_protocol::chat::ChatSigningPlan::operation_id(&self) -> radroots_domain::identifier::OperationId pub fn radroots_protocol::chat::ChatSigningPlan::parse(&radroots_protocol::command::CapturedChatCommand, &[u8]) -> core::result::Result<Self, radroots_protocol::nip01::WireError> pub fn radroots_protocol::chat::ChatSigningPlan::protected_wire(&self) -> &[u8] -pub const fn radroots_protocol::chat::ChatSigningPlan::replay(&self) -> radroots_protocol::chat::ChatReplay +pub const fn radroots_protocol::chat::ChatSigningPlan::replay(&self) -> radroots_protocol::plan::SigningReplay pub fn radroots_protocol::chat::ChatSigningPlan::routes(&self) -> &[radroots_protocol::chat::CapturedDmRoute] pub fn radroots_protocol::chat::ChatSigningPlan::seals(&self) -> &[radroots_protocol::chat::ChatSeal] +impl core::convert::From<radroots_protocol::chat::ChatSigningPlan> for radroots_protocol::plan::CapturedSigningPlan +pub fn radroots_protocol::plan::CapturedSigningPlan::from(radroots_protocol::chat::ChatSigningPlan) -> Self impl core::fmt::Debug for radroots_protocol::chat::ChatSigningPlan pub fn radroots_protocol::chat::ChatSigningPlan::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_protocol::chat::DmRelayAdvertisement @@ -514,6 +512,22 @@ pub fn radroots_protocol::listing::ListingEvent::fields(&self) -> radroots_proto pub fn radroots_protocol::listing::ListingEvent::new(&radroots_protocol::listing::PublishInput, radroots_identity::key::PublicKey, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_protocol::nip01::WireError> impl core::fmt::Debug for radroots_protocol::listing::ListingEvent pub fn radroots_protocol::listing::ListingEvent::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_protocol::listing::PublicSigningPlan +impl radroots_protocol::listing::PublicSigningPlan +pub fn radroots_protocol::listing::PublicSigningPlan::capture(&radroots_protocol::listing::CapturedListingCommand, radroots_domain::context::UnixSeconds, &[alloc::string::String], radroots_protocol::plan::SigningReplay) -> core::result::Result<Self, radroots_protocol::nip01::WireError> +pub const fn radroots_protocol::listing::PublicSigningPlan::command_digest(&self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_protocol::listing::PublicSigningPlan::created_at(&self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_protocol::listing::PublicSigningPlan::digest(&self) -> &[u8; 32] +pub const fn radroots_protocol::listing::PublicSigningPlan::event(&self) -> &radroots_protocol::listing::ListingEvent +pub const fn radroots_protocol::listing::PublicSigningPlan::operation_id(&self) -> radroots_domain::identifier::OperationId +pub fn radroots_protocol::listing::PublicSigningPlan::parse(&radroots_protocol::listing::CapturedListingCommand, &[u8]) -> core::result::Result<Self, radroots_protocol::nip01::WireError> +pub fn radroots_protocol::listing::PublicSigningPlan::protected_wire(&self) -> &[u8] +pub const fn radroots_protocol::listing::PublicSigningPlan::replay(&self) -> radroots_protocol::plan::SigningReplay +pub fn radroots_protocol::listing::PublicSigningPlan::selected_targets(&self) -> &[alloc::boxed::Box<str>] +impl core::convert::From<radroots_protocol::listing::PublicSigningPlan> for radroots_protocol::plan::CapturedSigningPlan +pub fn radroots_protocol::plan::CapturedSigningPlan::from(radroots_protocol::listing::PublicSigningPlan) -> Self +impl core::fmt::Debug for radroots_protocol::listing::PublicSigningPlan +pub fn radroots_protocol::listing::PublicSigningPlan::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_protocol::listing::PublishInput impl radroots_protocol::listing::PublishInput pub const fn radroots_protocol::listing::PublishInput::id(&self) -> radroots_domain::listing::ListingId @@ -551,6 +565,30 @@ pub fn radroots_protocol::nip01::UnsignedEvent::fmt(&self, &mut core::fmt::Forma pub fn radroots_protocol::nip01::canonical_preimage(&radroots_protocol::nip01::EventFields<'_>) -> alloc::string::String pub fn radroots_protocol::nip01::preimage_len(&radroots_protocol::nip01::EventFields<'_>, usize) -> core::result::Result<usize, radroots_protocol::nip01::WireError> pub fn radroots_protocol::nip01::signed_json_len(&radroots_protocol::nip01::EventFields<'_>, usize) -> core::result::Result<usize, radroots_protocol::nip01::WireError> +pub mod radroots_protocol::plan +pub enum radroots_protocol::plan::CapturedSigningPlan +pub radroots_protocol::plan::CapturedSigningPlan::Chat(radroots_protocol::chat::ChatSigningPlan) +pub radroots_protocol::plan::CapturedSigningPlan::Listing(radroots_protocol::listing::PublicSigningPlan) +impl radroots_protocol::plan::CapturedSigningPlan +pub const fn radroots_protocol::plan::CapturedSigningPlan::chat(&self) -> core::option::Option<&radroots_protocol::chat::ChatSigningPlan> +pub const fn radroots_protocol::plan::CapturedSigningPlan::command_digest(&self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_protocol::plan::CapturedSigningPlan::created_at(&self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_protocol::plan::CapturedSigningPlan::digest(&self) -> &[u8; 32] +pub const fn radroots_protocol::plan::CapturedSigningPlan::listing(&self) -> core::option::Option<&radroots_protocol::listing::PublicSigningPlan> +pub const fn radroots_protocol::plan::CapturedSigningPlan::operation_id(&self) -> radroots_domain::identifier::OperationId +pub fn radroots_protocol::plan::CapturedSigningPlan::parse(&radroots_protocol::command::CapturedCommand, &[u8]) -> core::result::Result<Self, radroots_protocol::nip01::WireError> +pub fn radroots_protocol::plan::CapturedSigningPlan::protected_wire(&self) -> &[u8] +pub const fn radroots_protocol::plan::CapturedSigningPlan::replay(&self) -> radroots_protocol::plan::SigningReplay +impl core::convert::From<radroots_protocol::chat::ChatSigningPlan> for radroots_protocol::plan::CapturedSigningPlan +pub fn radroots_protocol::plan::CapturedSigningPlan::from(radroots_protocol::chat::ChatSigningPlan) -> Self +impl core::convert::From<radroots_protocol::listing::PublicSigningPlan> for radroots_protocol::plan::CapturedSigningPlan +pub fn radroots_protocol::plan::CapturedSigningPlan::from(radroots_protocol::listing::PublicSigningPlan) -> Self +impl core::fmt::Debug for radroots_protocol::plan::CapturedSigningPlan +pub fn radroots_protocol::plan::CapturedSigningPlan::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub enum radroots_protocol::plan::SigningReplay +pub radroots_protocol::plan::SigningReplay::ExactReplayByRequestId +pub radroots_protocol::plan::SigningReplay::LocalReplaySafe +pub radroots_protocol::plan::SigningReplay::NonReplayable pub mod radroots_protocol::radrootsd pub mod radroots_protocol::radrootsd::transport_publish pub mod radroots_protocol::radrootsd::transport_publish::v5 diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -757,12 +757,13 @@ pub fn radroots_storage::memory::MemoryStorage::transition_backup(&self, radroot pub fn radroots_storage::memory::MemoryStorage::transition_restore(&self, radroots_storage::backup::BackupId, radroots_storage::backup::ReliabilityRevision, radroots_storage::backup::RestoreTransition, u64) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::backup::RestoreOperation, radroots_storage::Error>> pub fn radroots_storage::memory::MemoryStorage::verify_backup(&self, radroots_storage::backup::BackupPlan, radroots_storage::backup::BackupManifest) -> radroots_transport::source::BoxFuture<'_, core::result::Result<(), radroots_storage::backup::BackupCapabilityError>> pub mod radroots_storage::command +pub use radroots_storage::command::CapturedSigningPlan pub use radroots_storage::command::ChatSigningPlan pub mod radroots_storage::command::protected pub mod radroots_storage::command::protected::issuance pub struct radroots_storage::command::protected::issuance::ClaimRecord(_) impl radroots_storage::command::protected::issuance::ClaimRecord -pub fn radroots_storage::command::protected::issuance::ClaimRecord::capture(&radroots_storage::command::SigningAttempt) -> Self +pub fn radroots_storage::command::protected::issuance::ClaimRecord::capture(&radroots_storage::command::SigningAttempt) -> core::result::Result<Self, radroots_storage::command::OperationError> pub fn radroots_storage::command::protected::issuance::ClaimRecord::decode(&[u8], radroots_storage::command::BoundSigningPlan, radroots_identity::key::PublicKey) -> core::result::Result<radroots_storage::command::SigningAttempt, radroots_storage::command::OperationError> pub fn radroots_storage::command::protected::issuance::ClaimRecord::encode(&self) -> core::result::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>, radroots_storage::command::OperationError> pub struct radroots_storage::command::protected::issuance::EvidenceManifest(_) @@ -780,10 +781,10 @@ pub fn radroots_storage::command::protected::issuance::EvidenceManifest::verify( pub mod radroots_storage::command::protected::plan pub struct radroots_storage::command::protected::plan::PlanManifest(_) impl radroots_storage::command::protected::plan::PlanManifest -pub fn radroots_storage::command::protected::plan::PlanManifest::bind(self, radroots_storage::command::PreparedOperation, radroots_protocol::chat::plan::ChatSigningPlan) -> core::result::Result<radroots_storage::command::BoundSigningPlan, radroots_storage::command::OperationError> +pub fn radroots_storage::command::protected::plan::PlanManifest::bind(self, radroots_storage::command::PreparedOperation, radroots_protocol::plan::CapturedSigningPlan) -> core::result::Result<radroots_storage::command::BoundSigningPlan, radroots_storage::command::OperationError> pub const fn radroots_storage::command::protected::plan::PlanManifest::bound_at(&self) -> radroots_domain::context::UnixSeconds pub const fn radroots_storage::command::protected::plan::PlanManifest::byte_count(&self) -> usize -pub fn radroots_storage::command::protected::plan::PlanManifest::capture(&radroots_storage::command::PreparedOperation, &radroots_protocol::chat::plan::ChatSigningPlan, radroots_domain::identifier::TransactionId, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage::command::protected::plan::PlanManifest::capture(&radroots_storage::command::PreparedOperation, &radroots_protocol::plan::CapturedSigningPlan, radroots_domain::identifier::TransactionId, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::command::OperationError> pub fn radroots_storage::command::protected::plan::PlanManifest::decode(&[u8], &radroots_storage::command::PreparedOperation) -> core::result::Result<Self, radroots_storage::command::OperationError> pub fn radroots_storage::command::protected::plan::PlanManifest::encode(&self) -> core::result::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>, radroots_storage::command::OperationError> pub const fn radroots_storage::command::protected::plan::PlanManifest::part_count(&self) -> usize @@ -885,9 +886,10 @@ pub fn radroots_storage::command::AdmissionRequest::fmt(&self, &mut core::fmt::F pub struct radroots_storage::command::BoundSigningPlan impl radroots_storage::command::BoundSigningPlan pub const fn radroots_storage::command::BoundSigningPlan::bound_at(&self) -> radroots_domain::context::UnixSeconds -pub fn radroots_storage::command::BoundSigningPlan::from_committed_store(radroots_storage::command::PreparedOperation, radroots_protocol::chat::plan::ChatSigningPlan, radroots_domain::identifier::TransactionId, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::command::OperationError> -pub fn radroots_storage::command::BoundSigningPlan::into_parts(self) -> (radroots_storage::command::PreparedOperation, radroots_protocol::chat::plan::ChatSigningPlan) -pub const fn radroots_storage::command::BoundSigningPlan::plan(&self) -> &radroots_protocol::chat::plan::ChatSigningPlan +pub fn radroots_storage::command::BoundSigningPlan::chat_plan(&self) -> core::result::Result<&radroots_protocol::chat::plan::ChatSigningPlan, radroots_storage::command::OperationError> +pub fn radroots_storage::command::BoundSigningPlan::from_committed_store(radroots_storage::command::PreparedOperation, impl core::convert::Into<radroots_protocol::plan::CapturedSigningPlan>, radroots_domain::identifier::TransactionId, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage::command::BoundSigningPlan::into_parts(self) -> (radroots_storage::command::PreparedOperation, radroots_protocol::plan::CapturedSigningPlan) +pub const fn radroots_storage::command::BoundSigningPlan::plan(&self) -> &radroots_protocol::plan::CapturedSigningPlan pub const fn radroots_storage::command::BoundSigningPlan::prepared(&self) -> &radroots_storage::command::PreparedOperation pub const fn radroots_storage::command::BoundSigningPlan::transaction_id(&self) -> radroots_domain::identifier::TransactionId impl core::fmt::Debug for radroots_storage::command::BoundSigningPlan @@ -932,7 +934,7 @@ pub const fn radroots_storage::command::ClaimSnapshot::attempt_id(self) -> radro pub const fn radroots_storage::command::ClaimSnapshot::claimed_at(self) -> radroots_domain::context::UnixSeconds pub const fn radroots_storage::command::ClaimSnapshot::command_digest(self) -> radroots_domain::identifier::CommandDigest pub const fn radroots_storage::command::ClaimSnapshot::event_id(self) -> radroots_domain::identifier::EnvelopeEventId -pub fn radroots_storage::command::ClaimSnapshot::from_store_report(&radroots_storage::command::SigningAttempt) -> Self +pub fn radroots_storage::command::ClaimSnapshot::from_store_report(&radroots_storage::command::SigningAttempt) -> core::result::Result<Self, radroots_storage::command::OperationError> pub const fn radroots_storage::command::ClaimSnapshot::intent(self) -> radroots_protocol::intent::IntentBinding pub const fn radroots_storage::command::ClaimSnapshot::operation_id(self) -> radroots_domain::identifier::OperationId pub const fn radroots_storage::command::ClaimSnapshot::plan_digest(&self) -> &[u8; 32] @@ -1135,13 +1137,13 @@ pub const fn radroots_storage::command::SigningAttempt::deadline_unix_ms(&self) pub fn radroots_storage::command::SigningAttempt::from_committed_store(radroots_storage::command::BoundSigningPlan, radroots_identity::key::PublicKey, radroots_domain::identifier::SigningAttemptId, radroots_domain::identifier::TransactionId, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::command::OperationError> pub fn radroots_storage::command::SigningAttempt::identity(&self) -> radroots_storage::command::CommitAttempt pub fn radroots_storage::command::SigningAttempt::into_bound_plan(self) -> radroots_storage::command::BoundSigningPlan -pub fn radroots_storage::command::SigningAttempt::seal(&self) -> &radroots_protocol::chat::ChatSeal +pub fn radroots_storage::command::SigningAttempt::seal(&self) -> core::result::Result<&radroots_protocol::chat::ChatSeal, radroots_storage::command::OperationError> pub const fn radroots_storage::command::SigningAttempt::transaction_id(&self) -> radroots_domain::identifier::TransactionId impl core::fmt::Debug for radroots_storage::command::SigningAttempt pub fn radroots_storage::command::SigningAttempt::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub trait radroots_storage::command::OperationJournal: radroots_storage::workspace::WorkspaceStore pub fn radroots_storage::command::OperationJournal::admit_command_and_hold(&self, radroots_storage::command::AdmissionRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::AdmissionOutcome, radroots_storage::command::OperationError>> -pub fn radroots_storage::command::OperationJournal::bind_signing_intents(&self, radroots_storage::workspace::WorkspaceBinding, radroots_protocol::chat::plan::ChatSigningPlan, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::PlanBindingOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage::command::OperationJournal::bind_signing_intents(&self, radroots_storage::workspace::WorkspaceBinding, radroots_protocol::plan::CapturedSigningPlan, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::PlanBindingOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::capture_evidence<'a>(&'a self, radroots_storage::workspace::AttachmentInput, &'a radroots_storage::workspace::AttachmentProof, &'a radroots_storage::command::SealEvidence) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::command::EvidenceCaptureOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::claim_attempt(&self, radroots_storage::command::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::ClaimAttemptOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::delivery_attempt(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_identity::key::PublicKey, radroots_transport::sink::DeliveryRequestId, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::DeliveryAttempt>, radroots_storage::command::OperationError>> diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -378,7 +378,7 @@ impl core::fmt::Debug for radroots_storage_sqlite::workspace::NativeWorkspace pub fn radroots_storage_sqlite::workspace::NativeWorkspace::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl radroots_storage::command::OperationJournal for radroots_storage_sqlite::workspace::NativeWorkspace pub fn radroots_storage_sqlite::workspace::NativeWorkspace::admit_command_and_hold(&self, radroots_storage::command::AdmissionRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::AdmissionOutcome, radroots_storage::command::OperationError>> -pub fn radroots_storage_sqlite::workspace::NativeWorkspace::bind_signing_intents(&self, radroots_storage::workspace::WorkspaceBinding, radroots_protocol::chat::plan::ChatSigningPlan, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::PlanBindingOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::bind_signing_intents(&self, radroots_storage::workspace::WorkspaceBinding, radroots_protocol::plan::CapturedSigningPlan, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::PlanBindingOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::capture_evidence<'a>(&'a self, radroots_storage::workspace::AttachmentInput, &'a radroots_storage::workspace::AttachmentProof, &'a radroots_storage::command::issuance::SealEvidence) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::command::issuance::EvidenceCaptureOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::claim_attempt(&self, radroots_storage::command::issuance::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::issuance::ClaimAttemptOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::delivery_attempt(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_identity::key::PublicKey, radroots_transport::sink::DeliveryRequestId, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::delivery::DeliveryAttempt>, radroots_storage::command::OperationError>> diff --git a/crates/execution/src/session/inquiry.rs b/crates/execution/src/session/inquiry.rs @@ -7,7 +7,8 @@ use super::{HostBound, HostFuture, Shared, SignerSession}; use alloc::{string::String, vec::Vec}; use core::num::NonZeroU64; use radroots_domain::{PublicKey, UnixSeconds}; -use radroots_protocol::chat::{CapturedDmRoute, ChatReplay, ChatRumor, ChatSeal, ChatSigningPlan}; +use radroots_protocol::chat::{CapturedDmRoute, ChatRumor, ChatSeal, ChatSigningPlan}; +use radroots_protocol::plan::SigningReplay; use radroots_signing::{ issuance::{OutcomeKind, SigningIntent}, provider::{PrivateCiphertext, PrivateText, ProviderCall}, @@ -209,7 +210,7 @@ impl InquiryRuntime { let signer = signer.as_ref().ok_or(OperationError::Unauthorized)?; let plan = self.plan(&prepared, signer).await?; match journal - .bind_signing_intents(binding.clone(), plan, copy(proof)?) + .bind_signing_intents(binding.clone(), plan.into(), copy(proof)?) .await? { PlanBindingOutcome::Committed(bound) => bound, @@ -282,13 +283,13 @@ impl InquiryRuntime { .ok_or(OperationError::Unauthorized)? { radroots_signing::recovery::ReplayCapability::NonReplayable => { - ChatReplay::NonReplayable + SigningReplay::NonReplayable } radroots_signing::recovery::ReplayCapability::LocalReplaySafe => { - ChatReplay::LocalReplaySafe + SigningReplay::LocalReplaySafe } radroots_signing::recovery::ReplayCapability::ExactReplayByRequestId => { - ChatReplay::ExactReplayByRequestId + SigningReplay::ExactReplayByRequestId } _ => return Err(OperationError::Unauthorized), }; @@ -340,7 +341,7 @@ impl InquiryRuntime { ) -> Result<(), OperationError> { let prepared = bound.prepared(); let binding = prepared.request().binding(); - for seal in bound.plan().seals() { + for seal in bound.chat_plan()?.seals() { let select = || { ClaimAttemptRequest::new( binding.clone(), @@ -379,9 +380,9 @@ impl InquiryRuntime { let intent = SigningIntent::from_chat_seal( prepared.identity().operation_id(), prepared.identity().command_digest(), - attempt.seal(), + attempt.seal()?, ProviderCall::new( - attempt.seal().fields().author, + attempt.seal()?.fields().author, attempt.deadline_unix_ms(), CancellationSignal::new(), ), @@ -454,7 +455,7 @@ impl InquiryRuntime { } let recipient = work.evidence().recipient(); let route = bound - .plan() + .chat_plan()? .routes() .iter() .find(|route| route.participant() == recipient) diff --git a/crates/execution/tests/support/workspace_commands.rs b/crates/execution/tests/support/workspace_commands.rs @@ -193,7 +193,7 @@ impl OperationJournal for Journal { fn bind_signing_intents( &self, _binding: WorkspaceBinding, - _plan: ChatSigningPlan, + _plan: CapturedSigningPlan, _proof: AttachmentProof, ) -> BoxFuture<'_, Result<PlanBindingOutcome, OperationError>> { panic!("unexpected journal effect") diff --git a/crates/protocol/src/chat.rs b/crates/protocol/src/chat.rs @@ -22,7 +22,7 @@ const MAX_TIME: u64 = 253_402_300_799; const RANDOMIZED_PAST_SECONDS: u64 = 172_800; mod plan; -pub use plan::{ChatReplay, ChatSigningPlan, PLAN_MAX_BYTES}; +pub use plan::{ChatSigningPlan, PLAN_MAX_BYTES}; mod routes; pub use routes::{CapturedDmRoute, DmRelayAdvertisement}; mod gift_wrap; diff --git a/crates/protocol/src/chat/plan.rs b/crates/protocol/src/chat/plan.rs @@ -1,5 +1,6 @@ //! Immutable complete known-kind signing data, without execution authority. use super::{CapturedDmRoute, ChatRumor, ChatSeal}; +use crate::plan::SigningReplay; use crate::{command::CapturedChatCommand, nip01::WireError}; use alloc::{boxed::Box, collections::BTreeSet, string::String, vec::Vec}; use core::fmt; @@ -13,15 +14,6 @@ use zeroize::Zeroizing; pub const PLAN_MAX_BYTES: usize = 384 * 1024; const MAGIC: &[u8] = b"radroots.chat.signing_plan.v1\0"; -/// Captured provider declaration. Data never establishes a provider guarantee -/// or permits reissue after an uncertain effect; execution revalidates support. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum ChatReplay { - NonReplayable, - LocalReplaySafe, - ExactReplayByRequestId, -} - /// Complete sorted recipient set, exact seal preimages and retained route /// observations. Construction verifies structural provenance only: encryption /// authentication, signed route verification, network approval, provider @@ -31,7 +23,7 @@ pub struct ChatSigningPlan { command_digest: CommandDigest, message_id: MessageId, created_at: UnixSeconds, - replay: ChatReplay, + replay: SigningReplay, seals: Box<[ChatSeal]>, routes: Box<[CapturedDmRoute]>, wire: Zeroizing<Vec<u8>>, @@ -45,7 +37,7 @@ impl ChatSigningPlan { created_at: UnixSeconds, seals: Vec<ChatSeal>, routes: Vec<CapturedDmRoute>, - replay: ChatReplay, + replay: SigningReplay, ) -> Result<Self, WireError> { let rumor = ChatRumor::from_command(command, created_at)?; if seals.len() != rumor.recipients().len() || routes.len() != seals.len() { @@ -99,9 +91,9 @@ impl ChatSigningPlan { wire.extend_from_slice(rumor.message_id().as_bytes()); wire.extend_from_slice(&created_at.get().to_be_bytes()); wire.push(match replay { - ChatReplay::NonReplayable => 0, - ChatReplay::LocalReplaySafe => 1, - ChatReplay::ExactReplayByRequestId => 2, + SigningReplay::NonReplayable => 0, + SigningReplay::LocalReplaySafe => 1, + SigningReplay::ExactReplayByRequestId => 2, }); wire.push(seals.len() as u8); for (seal, route) in seals.iter().zip(&routes) { @@ -154,9 +146,9 @@ impl ChatSigningPlan { return Err(WireError::InvalidInput); } let replay = match input.byte()? { - 0 => ChatReplay::NonReplayable, - 1 => ChatReplay::LocalReplaySafe, - 2 => ChatReplay::ExactReplayByRequestId, + 0 => SigningReplay::NonReplayable, + 1 => SigningReplay::LocalReplaySafe, + 2 => SigningReplay::ExactReplayByRequestId, _ => return Err(WireError::InvalidInput), }; if usize::from(input.byte()?) != rumor.recipients().len() { @@ -221,7 +213,7 @@ impl ChatSigningPlan { pub const fn created_at(&self) -> UnixSeconds { self.created_at } - pub const fn replay(&self) -> ChatReplay { + pub const fn replay(&self) -> SigningReplay { self.replay } pub fn seals(&self) -> &[ChatSeal] { diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs @@ -26,6 +26,11 @@ pub mod chat; #[cfg(feature = "listing")] pub mod listing; +/// Complete typed signing plans. Retention and provider declarations create no +/// signing authority, signature, installed result or publication evidence. +#[cfg(any(feature = "chat", feature = "listing"))] +pub mod plan; + #[cfg(all(test, not(feature = "std")))] extern crate std; diff --git a/crates/protocol/src/listing.rs b/crates/protocol/src/listing.rs @@ -19,7 +19,9 @@ use sha2::{Digest, Sha256}; mod command; mod input; +mod plan; pub use command::CapturedListingCommand; +pub use plan::PublicSigningPlan; /// Assigned NIP-99 addressable classified-listing kind. pub const LISTING_KIND: u32 = 30402; diff --git a/crates/protocol/src/listing/plan.rs b/crates/protocol/src/listing/plan.rs @@ -0,0 +1,203 @@ +//! Exact public T1 data. No signature, route approval or durable fact is minted. +use super::{CapturedListingCommand, LISTING_EVENT_MAX_BYTES, ListingEvent}; +use crate::{ + nip01::{self, WireError}, + plan::SigningReplay, +}; +use alloc::{boxed::Box, collections::BTreeSet, string::String, vec::Vec}; +use core::fmt; +use radroots_domain::{CommandDigest, OperationId, UnixSeconds}; +use sha2::{Digest, Sha256}; +use zeroize::Zeroizing; +const MAGIC: &[u8] = b"radroots.listing.signing_plan.v1\0"; +const MAX_BYTES: usize = 128 * 1024; + +/// Complete original public artifact and bounded write-target descriptors. +/// Actual URI syntax, current destination approval and signer guarantees stay +/// executor-owned. Public data has no private peer, seal or message identity. +pub struct PublicSigningPlan { + operation: OperationId, + command: CommandDigest, + created_at: UnixSeconds, + replay: SigningReplay, + event: ListingEvent, + targets: Box<[Box<str>]>, + wire: Zeroizing<Vec<u8>>, + digest: [u8; 32], +} +impl PublicSigningPlan { + /// Captures the exact known preimage and explicit selected write targets. + pub fn capture( + command: &CapturedListingCommand, + created_at: UnixSeconds, + targets: &[String], + replay: SigningReplay, + ) -> Result<Self, WireError> { + if targets.len() > 16 { + return Err(WireError::LimitExceeded); + } + if targets.is_empty() { + return Err(WireError::InvalidInput); + } + let mut seen = BTreeSet::new(); + for target in targets { + if target.len() > 2048 { + return Err(WireError::LimitExceeded); + } + if !(target.starts_with("wss://") || target.starts_with("ws://")) + || target.trim() != target + || target.chars().any(char::is_control) + || !seen.insert(target) + { + return Err(WireError::InvalidInput); + } + } + let event = ListingEvent::new( + command.input(), + command.context().actor().participant(), + created_at, + )?; + let preimage = nip01::bounded_preimage(&event.fields(), LISTING_EVENT_MAX_BYTES)?; + let length = MAGIC.len() + + 32 * 3 + + 8 + + 4 + + 4 + + preimage.len() + + targets.iter().map(|s| 4 + s.len()).sum::<usize>(); + if length > MAX_BYTES { + return Err(WireError::LimitExceeded); + } + let mut wire = Zeroizing::new(Vec::with_capacity(length)); + wire.extend_from_slice(MAGIC); + wire.extend_from_slice(command.context().operation_id().as_bytes()); + wire.extend_from_slice(command.digest().as_bytes()); + wire.extend_from_slice(&created_at.get().to_be_bytes()); + wire.push(replay.code()); + wire.push(0); // PublicEvent artifact role. + wire.push(0); // No recipient, including no invented self recipient. + wire.extend_from_slice(event.event_id()); + put(&mut wire, preimage.as_bytes()); + wire.push(targets.len() as u8); + for target in targets { + put(&mut wire, target.as_bytes()); + } + let digest = Sha256::digest(wire.as_slice()).into(); + Ok(Self { + operation: command.context().operation_id(), + command: command.digest(), + created_at, + replay, + event, + targets: targets.iter().map(|s| Box::from(s.as_str())).collect(), + wire, + digest, + }) + } + /// Reconstructs the full original listing from the retained command and + /// compares every encoded preimage field, role, target and framing byte. + pub fn parse(command: &CapturedListingCommand, wire: &[u8]) -> Result<Self, WireError> { + if wire.len() > MAX_BYTES { + return Err(WireError::LimitExceeded); + } + let mut input = Input(wire); + if input.take(MAGIC.len())? != MAGIC + || input.take(32)? != command.context().operation_id().as_bytes() + || input.take(32)? != command.digest().as_bytes() + { + return Err(WireError::InvalidInput); + } + let time = UnixSeconds::new(u64::from_be_bytes(input.array()?)) + .map_err(|_| WireError::InvalidInput)?; + let replay = SigningReplay::from_code(input.array::<1>()?[0])?; + if input.array::<2>()? != [0, 0] { + return Err(WireError::InvalidInput); + } + let event_id: [u8; 32] = input.array()?; + let preimage = input.text(LISTING_EVENT_MAX_BYTES)?; + let count = usize::from(input.array::<1>()?[0]); + if count == 0 || count > 16 { + return Err(WireError::InvalidInput); + } + let mut targets = Vec::with_capacity(count); + for _ in 0..count { + targets.push(String::from(input.text(2048)?)); + } + if !input.0.is_empty() { + return Err(WireError::InvalidInput); + } + let plan = Self::capture(command, time, &targets, replay)?; + let expected = nip01::bounded_preimage(&plan.event.fields(), LISTING_EVENT_MAX_BYTES)?; + if plan.event.event_id() != &event_id + || expected.as_str() != preimage + || plan.protected_wire() != wire + { + return Err(WireError::InvalidInput); + } + Ok(plan) + } + /// Exact original operation identity. + pub const fn operation_id(&self) -> OperationId { + self.operation + } + /// Exact original semantic command commitment. + pub const fn command_digest(&self) -> CommandDigest { + self.command + } + /// Exact retained public timestamp. + pub const fn created_at(&self) -> UnixSeconds { + self.created_at + } + /// Captured declaration, without a provider guarantee. + pub const fn replay(&self) -> SigningReplay { + self.replay + } + /// Exact unsigned public event, with no signature or installation claim. + pub const fn event(&self) -> &ListingEvent { + &self.event + } + /// Original bounded write-target descriptors in retained order. + pub fn selected_targets(&self) -> &[Box<str>] { + &self.targets + } + /// Complete protected representation, distinct from chat plan bytes. + pub fn protected_wire(&self) -> &[u8] { + &self.wire + } + /// Commitment to the entire retained representation. + pub const fn digest(&self) -> &[u8; 32] { + &self.digest + } +} +impl fmt::Debug for PublicSigningPlan { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("PublicSigningPlan(<redacted>)") + } +} +fn put(out: &mut Vec<u8>, value: &[u8]) { + out.extend_from_slice(&(value.len() as u32).to_be_bytes()); + out.extend_from_slice(value); +} +struct Input<'a>(&'a [u8]); +impl<'a> Input<'a> { + fn take(&mut self, size: usize) -> Result<&'a [u8], WireError> { + let (a, b) = self + .0 + .split_at_checked(size) + .ok_or(WireError::InvalidInput)?; + self.0 = b; + Ok(a) + } + fn array<const N: usize>(&mut self) -> Result<[u8; N], WireError> { + self.take(N)? + .try_into() + .map_err(|_| WireError::InvalidInput) + } + fn text(&mut self, max: usize) -> Result<&'a str, WireError> { + let size = u32::from_be_bytes(self.array()?) as usize; + if size > max { + return Err(WireError::LimitExceeded); + } + core::str::from_utf8(self.take(size)?).map_err(|_| WireError::InvalidInput) + } +} diff --git a/crates/protocol/src/plan.rs b/crates/protocol/src/plan.rs @@ -0,0 +1,150 @@ +//! Common immutable signing-plan data, with explicit artifact families. +use crate::{command::CapturedCommand, nip01::WireError}; +use core::fmt; +use radroots_domain::{CommandDigest, OperationId, UnixSeconds}; + +/// Captured provider declaration. Execution must independently verify current +/// support before any reissue; this data authenticates no provider guarantee. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SigningReplay { + /// Uncertain invocation requires reconciliation, never automatic reissue. + NonReplayable, + /// The actual local provider independently qualifies safe exact reissue. + LocalReplaySafe, + /// The actual provider independently binds exact replay to request identity. + ExactReplayByRequestId, +} +impl SigningReplay { + pub(crate) const fn code(self) -> u8 { + match self { + Self::NonReplayable => 0, + Self::LocalReplaySafe => 1, + Self::ExactReplayByRequestId => 2, + } + } + pub(crate) fn from_code(code: u8) -> Result<Self, WireError> { + match code { + 0 => Ok(Self::NonReplayable), + 1 => Ok(Self::LocalReplaySafe), + 2 => Ok(Self::ExactReplayByRequestId), + _ => Err(WireError::InvalidInput), + } + } +} + +/// Exact complete plan data. No public artifact is represented as a chat seal, +/// and no optional recipient is filled with a synthetic participant. +pub enum CapturedSigningPlan { + /// Original private profile, preserving its established binary bytes. + #[cfg(feature = "chat")] + Chat(crate::chat::ChatSigningPlan), + /// Exact known-kind public listing preimage and selected target descriptors. + #[cfg(feature = "listing")] + Listing(crate::listing::PublicSigningPlan), +} +impl CapturedSigningPlan { + /// Reconstructs only the family of the independently retained command. + pub fn parse(command: &CapturedCommand, wire: &[u8]) -> Result<Self, WireError> { + match command { + #[cfg(feature = "chat")] + CapturedCommand::Chat(command) => { + crate::chat::ChatSigningPlan::parse(command, wire).map(Self::Chat) + } + #[cfg(feature = "listing")] + CapturedCommand::Listing(command) => { + crate::listing::PublicSigningPlan::parse(command, wire).map(Self::Listing) + } + #[cfg(not(feature = "chat"))] + CapturedCommand::Chat(_) => Err(WireError::InvalidInput), + } + } + /// Original operation identity. + pub const fn operation_id(&self) -> OperationId { + match self { + #[cfg(feature = "chat")] + Self::Chat(p) => p.operation_id(), + #[cfg(feature = "listing")] + Self::Listing(p) => p.operation_id(), + } + } + /// Exact command commitment. + pub const fn command_digest(&self) -> CommandDigest { + match self { + #[cfg(feature = "chat")] + Self::Chat(p) => p.command_digest(), + #[cfg(feature = "listing")] + Self::Listing(p) => p.command_digest(), + } + } + /// Original business event time. + pub const fn created_at(&self) -> UnixSeconds { + match self { + #[cfg(feature = "chat")] + Self::Chat(p) => p.created_at(), + #[cfg(feature = "listing")] + Self::Listing(p) => p.created_at(), + } + } + /// Historical declaration, without permission to reissue. + pub const fn replay(&self) -> SigningReplay { + match self { + #[cfg(feature = "chat")] + Self::Chat(p) => p.replay(), + #[cfg(feature = "listing")] + Self::Listing(p) => p.replay(), + } + } + /// Complete immutable protected representation. + pub fn protected_wire(&self) -> &[u8] { + match self { + #[cfg(feature = "chat")] + Self::Chat(p) => p.protected_wire(), + #[cfg(feature = "listing")] + Self::Listing(p) => p.protected_wire(), + } + } + /// Commitment to every retained field. + pub const fn digest(&self) -> &[u8; 32] { + match self { + #[cfg(feature = "chat")] + Self::Chat(p) => p.digest(), + #[cfg(feature = "listing")] + Self::Listing(p) => p.digest(), + } + } + /// Borrows actual private preimages only. + #[cfg(feature = "chat")] + pub const fn chat(&self) -> Option<&crate::chat::ChatSigningPlan> { + match self { + Self::Chat(p) => Some(p), + #[cfg(feature = "listing")] + Self::Listing(_) => None, + } + } + /// Borrows actual public data only. + #[cfg(feature = "listing")] + pub const fn listing(&self) -> Option<&crate::listing::PublicSigningPlan> { + match self { + Self::Listing(p) => Some(p), + #[cfg(feature = "chat")] + Self::Chat(_) => None, + } + } +} +#[cfg(feature = "chat")] +impl From<crate::chat::ChatSigningPlan> for CapturedSigningPlan { + fn from(p: crate::chat::ChatSigningPlan) -> Self { + Self::Chat(p) + } +} +#[cfg(feature = "listing")] +impl From<crate::listing::PublicSigningPlan> for CapturedSigningPlan { + fn from(p: crate::listing::PublicSigningPlan) -> Self { + Self::Listing(p) + } +} +impl fmt::Debug for CapturedSigningPlan { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CapturedSigningPlan(<redacted>)") + } +} diff --git a/crates/protocol/tests/chat_wire.rs b/crates/protocol/tests/chat_wire.rs @@ -1,7 +1,7 @@ #![cfg(feature = "chat")] use radroots_domain::{PublicKey, UnixSeconds}; -use radroots_protocol::{chat::*, command::CapturedChatCommand, nip01::*}; +use radroots_protocol::{chat::*, command::CapturedChatCommand, nip01::*, plan::SigningReplay}; use serde_json::Value; fn vectors() -> Value { @@ -273,9 +273,9 @@ fn complete_plan_roundtrip_preserves_all_exact_descriptors_and_refuses_truncatio for row in vectors()["vectors"].as_array().unwrap() { let command = CapturedChatCommand::parse(text(row, "wire").as_bytes()).unwrap(); for replay in [ - ChatReplay::NonReplayable, - ChatReplay::LocalReplaySafe, - ChatReplay::ExactReplayByRequestId, + SigningReplay::NonReplayable, + SigningReplay::LocalReplaySafe, + SigningReplay::ExactReplayByRequestId, ] { let (seals, routes) = plan_parts(row, &command); let plan = @@ -317,7 +317,7 @@ fn complete_plan_roundtrip_preserves_all_exact_descriptors_and_refuses_truncatio time(1_700_000_000), seals, routes, - ChatReplay::NonReplayable + SigningReplay::NonReplayable ) .is_err() ); @@ -329,7 +329,7 @@ fn complete_plan_roundtrip_preserves_all_exact_descriptors_and_refuses_truncatio time(1_700_000_000), seals, routes, - ChatReplay::NonReplayable + SigningReplay::NonReplayable ) .is_err() ); @@ -342,7 +342,7 @@ fn complete_plan_roundtrip_preserves_all_exact_descriptors_and_refuses_truncatio time(1_700_000_000), seals, routes, - ChatReplay::NonReplayable + SigningReplay::NonReplayable ) .is_err() ); @@ -429,7 +429,7 @@ fn complete_plan_refuses_individual_provenance_field_and_combined_route_substitu time(1_700_000_000), seals, routes, - ChatReplay::NonReplayable + SigningReplay::NonReplayable ) .is_err() ); @@ -443,7 +443,7 @@ fn complete_plan_refuses_individual_provenance_field_and_combined_route_substitu time(1_700_000_000), seals, routes, - ChatReplay::NonReplayable + SigningReplay::NonReplayable ) .is_err() ); @@ -454,7 +454,7 @@ fn complete_plan_refuses_individual_provenance_field_and_combined_route_substitu time(1_700_000_001), seals, routes, - ChatReplay::NonReplayable + SigningReplay::NonReplayable ) .is_err() ); @@ -466,7 +466,7 @@ fn complete_plan_refuses_individual_provenance_field_and_combined_route_substitu time(1_700_000_000), seals, routes, - ChatReplay::NonReplayable + SigningReplay::NonReplayable ) .is_err() ); @@ -492,7 +492,7 @@ fn complete_plan_refuses_individual_provenance_field_and_combined_route_substitu time(1_700_000_000), seals, routes, - ChatReplay::NonReplayable + SigningReplay::NonReplayable ), Err(WireError::LimitExceeded) )); @@ -502,7 +502,7 @@ fn complete_plan_refuses_individual_provenance_field_and_combined_route_substitu time(1_700_000_000), seals, routes, - ChatReplay::NonReplayable, + SigningReplay::NonReplayable, ) .unwrap(); let count = b"radroots.chat.signing_plan.v1\0".len() + 32 * 3 + 8 + 1; diff --git a/crates/protocol/tests/public_command.rs b/crates/protocol/tests/public_command.rs @@ -182,3 +182,121 @@ fn unsupported_full_profile_features_are_refused_without_silent_quote_or_media_f ); } } + +#[test] +fn exact_public_plan_reconstructs_original_event_and_refuses_changed_framing_or_command() { + use radroots_protocol::{ + listing::PublicSigningPlan, + plan::{CapturedSigningPlan, SigningReplay}, + }; + let public = CapturedListingCommand::capture( + context(), + PublishInput::parse(&serde_json::to_vec(&input()).unwrap()).unwrap(), + ) + .unwrap(); + let targets = vec![ + "wss://listing.fixture.example/a".to_string(), + "wss://listing.fixture.example/b".to_string(), + ]; + let plan = PublicSigningPlan::capture( + &public, + UnixSeconds::new(100).unwrap(), + &targets, + SigningReplay::NonReplayable, + ) + .unwrap(); + let wire = plan.protected_wire().to_vec(); + let digest = *plan.digest(); + let event_id = *plan.event().event_id(); + assert_eq!( + plan.selected_targets() + .iter() + .map(|s| s.as_ref()) + .collect::<Vec<_>>(), + targets + ); + let common = CapturedCommand::from(public); + let retained = CapturedSigningPlan::parse(&common, &wire).unwrap(); + assert_eq!(retained.protected_wire(), wire); + assert_eq!(retained.digest(), &digest); + assert_eq!(retained.listing().unwrap().event().event_id(), &event_id); + #[cfg(feature = "chat")] + assert!(retained.chat().is_none()); + assert!(!format!("{retained:?}").contains("Carrots")); + let changed = PublicSigningPlan::capture( + common.listing().unwrap(), + UnixSeconds::new(101).unwrap(), + &targets, + SigningReplay::NonReplayable, + ) + .unwrap(); + assert_ne!(changed.digest(), &digest); + for replay in [ + SigningReplay::LocalReplaySafe, + SigningReplay::ExactReplayByRequestId, + ] { + let changed = PublicSigningPlan::capture( + common.listing().unwrap(), + UnixSeconds::new(100).unwrap(), + &targets, + replay, + ) + .unwrap(); + assert_ne!(changed.digest(), &digest); + assert_eq!( + PublicSigningPlan::parse(common.listing().unwrap(), changed.protected_wire()) + .unwrap() + .replay(), + replay + ); + } + let prefix = b"radroots.listing.signing_plan.v1\0".len(); + for offset in [ + 0, + prefix, + prefix + 32, + prefix + 64 + 8, + prefix + 64 + 9, + prefix + 64 + 10, + ] { + let mut changed = wire.clone(); + changed[offset] ^= 0x80; + assert!(CapturedSigningPlan::parse(&common, &changed).is_err()); + } + let mut changed = wire.clone(); + let offset = changed.windows(7).position(|w| w == b"Carrots").unwrap(); + changed[offset] = b'P'; + assert!(CapturedSigningPlan::parse(&common, &changed).is_err()); + let mut changed = wire.clone(); + changed.push(0); + assert!(CapturedSigningPlan::parse(&common, &changed).is_err()); + for end in [0, 1, prefix, prefix + 32, wire.len() - 1] { + assert!(CapturedSigningPlan::parse(&common, &wire[..end]).is_err()); + } + let chat = CapturedCommand::from( + CapturedChatCommand::inquire( + context(), + InquireInput::new(ThreadId::from_bytes([6; 32]), key(), None, "Private").unwrap(), + ) + .unwrap(), + ); + assert!(CapturedSigningPlan::parse(&chat, &wire).is_err()); + assert!( + PublicSigningPlan::capture( + common.listing().unwrap(), + UnixSeconds::new(100).unwrap(), + &[], + SigningReplay::NonReplayable + ) + .is_err() + ); + assert!( + PublicSigningPlan::capture( + common.listing().unwrap(), + UnixSeconds::new(100).unwrap(), + &vec![targets[0].clone(); 2], + SigningReplay::NonReplayable + ) + .is_err() + ); +} diff --git a/crates/radroots/tests/support/receipt_delivery.rs b/crates/radroots/tests/support/receipt_delivery.rs @@ -96,7 +96,7 @@ impl Ready { let recipient = prepared.request().chat_command().unwrap().peer(); bound( store - .bind_signing_intents(binding.clone(), plan, copy(&proof)) + .bind_signing_intents(binding.clone(), (plan).into(), copy(&proof)) .await .unwrap(), ); @@ -119,7 +119,7 @@ impl Ready { let intent = SigningIntent::from_chat_seal( claim.binding().operation_id(), prepared.identity().command_digest(), - claim.seal(), + claim.seal().unwrap(), ProviderCall::new(key(), claim.deadline_unix_ms(), CancellationSignal::new()), ) .unwrap(); diff --git a/crates/radroots/tests/support/receipt_delivery_admission.rs b/crates/radroots/tests/support/receipt_delivery_admission.rs @@ -57,10 +57,10 @@ async fn self_copy_delivery_refuses_the_original_peer_as_temporary_author() { .await .unwrap(), ); - let fields = claim.seal().fields(); + let fields = claim.seal().unwrap().fields(); let participant = keys(1); let signed = nostr::UnsignedEvent { - id: Some(nostr::EventId::from_slice(&claim.seal().event_id()).unwrap()), + id: Some(nostr::EventId::from_slice(&claim.seal().unwrap().event_id()).unwrap()), pubkey: participant.public_key(), created_at: nostr::Timestamp::from_secs(fields.created_at), kind: nostr::Kind::Custom(13), diff --git a/crates/radroots/tests/support/receipt_issuance.rs b/crates/radroots/tests/support/receipt_issuance.rs @@ -83,7 +83,7 @@ pub(super) async fn prepare( let recipients = plan.seals().iter().map(|seal| seal.recipient()).collect(); bound( store - .bind_signing_intents(binding.clone(), plan, copy(proof)) + .bind_signing_intents(binding.clone(), (plan).into(), copy(proof)) .await .unwrap(), ); @@ -110,7 +110,7 @@ pub(super) async fn obtain(attempt: &SigningAttempt, missing: bool) -> SealEvide let intent = SigningIntent::from_chat_seal( attempt.binding().operation_id(), attempt.bound_plan().prepared().identity().command_digest(), - attempt.seal(), + attempt.seal().unwrap(), ProviderCall::new(key(), attempt.deadline_unix_ms(), CancellationSignal::new()), ) .unwrap(); diff --git a/crates/radroots/tests/support/receipt_plans.rs b/crates/radroots/tests/support/receipt_plans.rs @@ -10,7 +10,8 @@ mod snapshots; use super::*; use nostr::{JsonUtil, nips::nip44}; use radroots_domain::EnvelopeEventId; -use radroots_protocol::chat::{CapturedDmRoute, ChatReplay, ChatRumor, ChatSeal, ChatSigningPlan}; +use radroots_protocol::chat::{CapturedDmRoute, ChatRumor, ChatSeal, ChatSigningPlan}; +use radroots_protocol::plan::SigningReplay; use radroots_storage::command::{BoundSigningPlan, PlanBindingOutcome}; fn keys(last: u8) -> nostr::Keys { let mut bytes = [0; 32]; @@ -99,7 +100,7 @@ fn plan_with_routes( UnixSeconds::new(created).unwrap(), seals, routes, - ChatReplay::NonReplayable, + SigningReplay::NonReplayable, ) .unwrap() } diff --git a/crates/radroots/tests/support/receipt_recovery.rs b/crates/radroots/tests/support/receipt_recovery.rs @@ -108,7 +108,7 @@ async fn original_capture_recovery_retries_known_rollback_without_reissuing_and_ &issued.binding, issued.attempt.bound_plan().prepared(), *issued.attempt.bound_plan().plan().digest(), - issued.attempt.seal().recipient(), + issued.attempt.seal().unwrap().recipient(), ), copy(&issued.proof), ) @@ -206,7 +206,7 @@ async fn unknown_capture_recovery_preserves_writer_during_refused_preflight_and_ &issued.binding, issued.attempt.bound_plan().prepared(), *issued.attempt.bound_plan().plan().digest(), - issued.attempt.seal().recipient(), + issued.attempt.seal().unwrap().recipient(), ), copy(&issued.proof), ) diff --git a/crates/radroots/tests/support/receipt_snapshots.rs b/crates/radroots/tests/support/receipt_snapshots.rs @@ -335,10 +335,13 @@ async fn full_receipts_keep_obtained_and_unknown_recipients_separate_and_bind_or original.role(), radroots_protocol::intent::ArtifactRole::BusinessSeal ); - assert_eq!(original.recipient(), Some(first.seal().recipient())); + assert_eq!( + original.recipient(), + Some(first.seal().unwrap().recipient()) + ); assert_eq!( original.expected_event().unwrap().as_bytes(), - &first.seal().event_id() + &first.seal().unwrap().event_id() ); assert_eq!(original.attempt_id(), Some(first.attempt_id())); assert_eq!( @@ -464,7 +467,7 @@ async fn coherent_snapshots_retain_t0_t1_and_independent_recipient_claim_and_cap let message = plan.message_id(); let plan_receipt = bound( store - .bind_signing_intents(binding.clone(), plan, copy(&proof)) + .bind_signing_intents(binding.clone(), (plan).into(), copy(&proof)) .await .unwrap(), ); diff --git a/crates/storage/src/command.rs b/crates/storage/src/command.rs @@ -9,6 +9,7 @@ use radroots_domain::{ }; pub use radroots_protocol::chat::ChatSigningPlan; use radroots_protocol::command::{CapturedChatCommand, CapturedCommand}; +pub use radroots_protocol::plan::CapturedSigningPlan; use radroots_transport::BoxFuture; #[cfg(feature = "protected_outbox")] @@ -413,7 +414,7 @@ pub trait OperationJournal: WorkspaceStore { fn bind_signing_intents( &self, binding: WorkspaceBinding, - plan: ChatSigningPlan, + plan: CapturedSigningPlan, proof: AttachmentProof, ) -> BoxFuture<'_, Result<PlanBindingOutcome, OperationError>>; /// Queries original complete plan bytes under current access, including @@ -448,7 +449,7 @@ pub trait OperationJournal: WorkspaceStore { /// A custom adapter's structural report does not qualify durable execution. pub struct BoundSigningPlan { prepared: PreparedOperation, - plan: ChatSigningPlan, + plan: Box<CapturedSigningPlan>, transaction_id: TransactionId, bound_at: radroots_domain::UnixSeconds, } @@ -456,10 +457,11 @@ impl BoundSigningPlan { /// Compares exact original command and fixed first-issue window. pub fn from_committed_store( prepared: PreparedOperation, - plan: ChatSigningPlan, + plan: impl Into<CapturedSigningPlan>, transaction_id: TransactionId, bound_at: radroots_domain::UnixSeconds, ) -> Result<Self, OperationError> { + let plan = plan.into(); if plan.operation_id() != prepared.identity().operation_id() || plan.command_digest() != prepared.identity().command_digest() || bound_at < prepared.issuance_window().prepared_at() @@ -472,25 +474,30 @@ impl BoundSigningPlan { // Reconstruct against the actually retained command, rather than trust // a matching digest descriptor attached to unrelated plan fields. let checked = - ChatSigningPlan::parse(prepared.request().chat_command()?, plan.protected_wire()) + CapturedSigningPlan::parse(prepared.request().command(), plan.protected_wire()) .map_err(|_| OperationError::RecoveryRequired)?; Ok(Self { prepared, - plan: checked, + plan: Box::new(checked), transaction_id, bound_at, }) } /// Transfers retained command and exact plan without changing their identities. - pub fn into_parts(self) -> (PreparedOperation, ChatSigningPlan) { - (self.prepared, self.plan) + pub fn into_parts(self) -> (PreparedOperation, CapturedSigningPlan) { + (self.prepared, *self.plan) } pub const fn prepared(&self) -> &PreparedOperation { &self.prepared } - pub const fn plan(&self) -> &ChatSigningPlan { + pub const fn plan(&self) -> &CapturedSigningPlan { &self.plan } + /// Borrows actual private preimages only; public plans never acquire an + /// invented seal, peer or message through a private effect port. + pub fn chat_plan(&self) -> Result<&ChatSigningPlan, OperationError> { + self.plan.chat().ok_or(OperationError::UnsupportedOperation) + } pub const fn transaction_id(&self) -> TransactionId { self.transaction_id } diff --git a/crates/storage/src/command/installation.rs b/crates/storage/src/command/installation.rs @@ -92,7 +92,7 @@ impl ChatInstallation { } Ok(Self { plan: *bound.plan().digest(), - message: bound.plan().message_id(), + message: bound.chat_plan()?.message_id(), preparation_transaction: bound.prepared().transaction_id(), plan_transaction: bound.transaction_id(), transaction, @@ -173,7 +173,7 @@ impl PublicationWork { || installation.operation_id() != evidence.operation_id() || installation.command_digest() != evidence.command_digest() || installation.plan_digest() != bound.plan().digest() - || installation.message_id() != bound.plan().message_id() + || installation.message_id() != bound.chat_plan()?.message_id() || installation.preparation_transaction_id() != bound.prepared().transaction_id() || installation.plan_transaction_id() != bound.transaction_id() || queued_at < installation.installed_at() @@ -238,7 +238,7 @@ fn check_evidence( ) -> Result<(), OperationError> { let identity = bound.prepared().identity(); let seal = bound - .plan() + .chat_plan()? .seals() .iter() .find(|seal| seal.recipient() == evidence.recipient()) diff --git a/crates/storage/src/command/issuance.rs b/crates/storage/src/command/issuance.rs @@ -102,12 +102,12 @@ impl SigningAttempt { return Err(OperationError::RecoveryRequired); } let recipient_index = bound - .plan() + .chat_plan()? .seals() .iter() .position(|seal| seal.recipient() == recipient) .ok_or(OperationError::InvalidCommand)?; - let seal = &bound.plan().seals()[recipient_index]; + let seal = &bound.chat_plan()?.seals()[recipient_index]; let deadline = NonZeroU64::new( window .first_issue_not_after() @@ -162,8 +162,12 @@ impl SigningAttempt { } /// Borrows the exact retained seal. The private index is validated once /// against the immutable complete plan by the structural constructor. - pub fn seal(&self) -> &ChatSeal { - &self.bound.plan().seals()[self.recipient_index] + pub fn seal(&self) -> Result<&ChatSeal, OperationError> { + self.bound + .chat_plan()? + .seals() + .get(self.recipient_index) + .ok_or(OperationError::RecoveryRequired) } pub const fn attempt_id(&self) -> SigningAttemptId { self.attempt_id @@ -252,7 +256,7 @@ impl SealEvidence { }; let wire = Nip01EventWire::parse_json_exact_with_limits(raw, limits) .map_err(|_| OperationError::InvalidEvidence)?; - let seal = attempt.seal(); + let seal = attempt.seal()?; let fields = seal.fields(); let event_id = EnvelopeEventId::from_bytes(seal.event_id()); if wire.id != event_id.to_string() @@ -303,14 +307,17 @@ impl SealEvidence { } } pub fn matches_attempt(&self, attempt: &SigningAttempt) -> bool { + let Ok(seal) = attempt.seal() else { + return false; + }; self.workspace_id == attempt.bound_plan().prepared().identity().workspace_id() && self.attempt_id == attempt.attempt_id() && self.intent == attempt.binding() && self.operation_id == attempt.bound_plan().prepared().identity().operation_id() && self.command_digest == attempt.bound_plan().prepared().identity().command_digest() && &self.plan_digest == attempt.bound_plan().plan().digest() - && self.recipient == attempt.seal().recipient() - && self.event_id.as_bytes() == &attempt.seal().event_id() + && self.recipient == seal.recipient() + && self.event_id.as_bytes() == &seal.event_id() } pub const fn workspace_id(&self) -> WorkspaceId { self.workspace_id diff --git a/crates/storage/src/command/protected/issuance.rs b/crates/storage/src/command/protected/issuance.rs @@ -30,17 +30,17 @@ struct ClaimWire { expected_event: EnvelopeEventId, } impl ClaimWire { - fn new(attempt: &SigningAttempt) -> Self { + fn new(attempt: &SigningAttempt) -> Result<Self, OperationError> { let plan = attempt.bound_plan(); let prepared = plan.prepared(); let identity = prepared.identity(); - Self { + Ok(Self { version: 1, workspace: identity.workspace_id(), operation_id: identity.operation_id(), command_digest: identity.command_digest(), plan_digest: *plan.plan().digest(), - recipient: attempt.seal().recipient(), + recipient: attempt.seal()?.recipient(), attempt_id: attempt.attempt_id(), transaction_id: attempt.transaction_id(), claimed_at: attempt.claimed_at(), @@ -49,16 +49,16 @@ impl ClaimWire { preparation_transaction: prepared.transaction_id(), plan_transaction: plan.transaction_id(), grant_id: prepared.request().binding().input().grant_id(), - expected_event: EnvelopeEventId::from_bytes(attempt.seal().event_id()), - } + expected_event: EnvelopeEventId::from_bytes(attempt.seal()?.event_id()), + }) } } /// Closed v1 claim codec. The concrete host still verifies its retained indexes /// and acknowledges actual completion before reporting a newly claimed attempt. pub struct ClaimRecord(ClaimWire); impl ClaimRecord { - pub fn capture(attempt: &SigningAttempt) -> Self { - Self(ClaimWire::new(attempt)) + pub fn capture(attempt: &SigningAttempt) -> Result<Self, OperationError> { + Ok(Self(ClaimWire::new(attempt)?)) } pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>, OperationError> { encode(&self.0) @@ -80,7 +80,7 @@ impl ClaimRecord { wire.transaction_id, wire.claimed_at, )?; - if wire != ClaimWire::new(&attempt) { + if wire != ClaimWire::new(&attempt)? { return Err(OperationError::RecoveryRequired); } Ok(attempt) @@ -158,11 +158,11 @@ impl EvidenceManifest { || w.operation_id != identity.operation_id() || w.command_digest != identity.command_digest() || &w.plan_digest != bound.plan().digest() - || w.recipient != attempt.seal().recipient() + || w.recipient != attempt.seal()?.recipient() || w.attempt_id != attempt.attempt_id() || w.claim_transaction != attempt.transaction_id() || &w.intent_digest != attempt.binding().digest() - || w.event_id.as_bytes() != &attempt.seal().event_id() + || w.event_id.as_bytes() != &attempt.seal()?.event_id() || !(1..=65536).contains(&w.byte_count) || !(1..=4).contains(&w.part_count) || w.byte_count.div_ceil(PART_BYTES) != w.part_count diff --git a/crates/storage/src/command/protected/plan.rs b/crates/storage/src/command/protected/plan.rs @@ -1,7 +1,7 @@ //! Validated historical T1 metadata shared by concrete protected hosts. //! This codec establishes neither a commit nor current issuance authority. use super::{OperationError, PreparedOperation}; -use crate::command::{BoundSigningPlan, ChatSigningPlan}; +use crate::command::{BoundSigningPlan, CapturedSigningPlan}; use radroots_domain::{CommandDigest, OperationId, TransactionId, UnixSeconds, WorkspaceId}; use serde::{Deserialize, Serialize}; use zeroize::Zeroizing; @@ -35,7 +35,7 @@ impl PlanManifest { /// must still authenticate current access and confirm its actual transaction. pub fn capture( prepared: &PreparedOperation, - plan: &ChatSigningPlan, + plan: &CapturedSigningPlan, transaction: TransactionId, bound_at: UnixSeconds, ) -> Result<Self, OperationError> { @@ -121,7 +121,7 @@ impl PlanManifest { pub fn bind( self, prepared: PreparedOperation, - plan: ChatSigningPlan, + plan: CapturedSigningPlan, ) -> Result<BoundSigningPlan, OperationError> { self.validate(&prepared)?; if plan.digest() != self.plan_digest().as_bytes() @@ -141,9 +141,11 @@ impl PlanManifest { #[cfg(test)] mod tests { use super::*; + use crate::command::ChatSigningPlan; use crate::command::protected::tests::request; use radroots_domain::{EnvelopeEventId, IssuanceWindow, Sequence}; - use radroots_protocol::chat::{CapturedDmRoute, ChatReplay, ChatRumor, ChatSeal}; + use radroots_protocol::chat::{CapturedDmRoute, ChatRumor, ChatSeal}; + use radroots_protocol::plan::SigningReplay; use serde_json::json; fn make_prepared() -> PreparedOperation { @@ -159,7 +161,7 @@ mod tests { ) .unwrap() } - fn make_plan(prepared: &PreparedOperation, created: u64) -> ChatSigningPlan { + fn make_plan(prepared: &PreparedOperation, created: u64) -> CapturedSigningPlan { // These are structural descriptors for pure codec tests. They supply // neither authenticated ciphertext nor a verified relay advertisement. let command = prepared.request().chat_command().unwrap(); @@ -185,9 +187,10 @@ mod tests { now, vec![seal], vec![route], - ChatReplay::NonReplayable, + SigningReplay::NonReplayable, ) .unwrap() + .into() } #[test] fn manifest_binds_original_preparation_plan_and_window_without_minting_authority() { diff --git a/crates/storage/src/command/snapshot.rs b/crates/storage/src/command/snapshot.rs @@ -35,20 +35,20 @@ pub struct ClaimSnapshot { impl ClaimSnapshot { /// Copies a structural store report; no backend claim or nonissuance proof /// is created by this conversion. - pub fn from_store_report(attempt: &SigningAttempt) -> Self { + pub fn from_store_report(attempt: &SigningAttempt) -> Result<Self, OperationError> { let identity = attempt.bound_plan().prepared().identity(); - Self { + Ok(Self { workspace: identity.workspace_id(), operation: identity.operation_id(), command: identity.command_digest(), plan: *attempt.bound_plan().plan().digest(), - recipient: attempt.seal().recipient(), + recipient: attempt.seal()?.recipient(), attempt: attempt.attempt_id(), transaction: attempt.transaction_id(), claimed_at: attempt.claimed_at(), - event: EnvelopeEventId::from_bytes(attempt.seal().event_id()), + event: EnvelopeEventId::from_bytes(attempt.seal()?.event_id()), intent: attempt.binding(), - } + }) } /// Original workspace identity. pub const fn workspace_id(self) -> WorkspaceId { @@ -362,7 +362,7 @@ impl OperationSnapshot { continue; }; let seal = bound - .plan() + .chat_plan()? .seals() .iter() .find(|seal| seal.recipient() == expected) @@ -676,7 +676,9 @@ impl OperationSnapshot { } /// Exact original logical message identity, separate from seal event IDs. pub fn message_id(&self) -> Option<MessageId> { - self.bound_plan().map(|bound| bound.plan().message_id()) + self.bound_plan() + .and_then(|bound| bound.plan().chat()) + .map(|plan| plan.message_id()) } /// Complete sorted unique recipient set and independent outcomes. pub fn recipients(&self) -> &[RecipientSnapshot] { diff --git a/crates/storage_indexeddb/src/workspace/delivery/graph.rs b/crates/storage_indexeddb/src/workspace/delivery/graph.rs @@ -77,7 +77,7 @@ impl Graph { result.slots[recipient as usize] = ordinal; let bound = original.bound().ok_or(OperationError::RecoveryRequired)?; let participant = bound - .plan() + .chat_plan()? .seals() .get(recipient as usize) .ok_or(OperationError::RecoveryRequired)? diff --git a/crates/storage_indexeddb/src/workspace/delivery/mod.rs b/crates/storage_indexeddb/src/workspace/delivery/mod.rs @@ -63,7 +63,7 @@ fn routes( ) -> Result<(), OperationError> { let mut selected = None; for route in bound - .plan() + .chat_plan()? .routes() .iter() .filter(|route| route.participant() == recipient) diff --git a/crates/storage_indexeddb/src/workspace/delivery/operations.rs b/crates/storage_indexeddb/src/workspace/delivery/operations.rs @@ -113,7 +113,7 @@ impl BrowserWorkspace { .bound_plan() .ok_or(OperationError::RecoveryRequired)?; let recipient = bound - .plan() + .chat_plan()? .seals() .iter() .position(|seal| seal.recipient() == evidence.recipient()) diff --git a/crates/storage_indexeddb/src/workspace/installation.rs b/crates/storage_indexeddb/src/workspace/installation.rs @@ -30,7 +30,7 @@ fn context( .chain_update(bound.plan().digest()); let schema = if let Some(index) = recipient { let seal = bound - .plan() + .chat_plan()? .seals() .get(index as usize) .ok_or(OperationError::RecoveryRequired)?; @@ -83,7 +83,7 @@ impl Records { }; let mut work = Vec::with_capacity(2); if let Some(bound) = graph.bound() { - for (index, seal) in bound.plan().seals().iter().enumerate() { + for (index, seal) in bound.chat_plan()?.seals().iter().enumerate() { if let Some(raw) = state .read_view_key( view, @@ -224,7 +224,7 @@ impl BrowserWorkspace { } for evidence in missing { let index = bound - .plan() + .chat_plan()? .seals() .iter() .position(|seal| seal.recipient() == evidence.recipient()) diff --git a/crates/storage_indexeddb/src/workspace/issuance.rs b/crates/storage_indexeddb/src/workspace/issuance.rs @@ -25,18 +25,18 @@ pub(super) enum Claim { Absent(BoundSigningPlan, u8), Present(SigningAttempt), } -fn position(bound: &BoundSigningPlan, recipient: PublicKey) -> Option<u8> { - bound - .plan() +fn position(bound: &BoundSigningPlan, recipient: PublicKey) -> Result<Option<u8>, OperationError> { + Ok(bound + .chat_plan()? .seals() .iter() .position(|seal| seal.recipient() == recipient) - .and_then(|i| u8::try_from(i).ok()) + .and_then(|i| u8::try_from(i).ok())) } fn base(state: &State, bound: &BoundSigningPlan, index: u8) -> Result<Sha256, OperationError> { let identity = bound.prepared().identity(); let recipient = bound - .plan() + .chat_plan()? .seals() .get(index as usize) .ok_or(OperationError::InvalidCommand)? @@ -270,7 +270,7 @@ impl BrowserWorkspace { return Err(OperationError::IdempotencyConflict); } let index = - position(&bound, request.recipient()).ok_or(OperationError::InvalidCommand)?; + position(&bound, request.recipient())?.ok_or(OperationError::InvalidCommand)?; let (attempt, fresh, extra) = match state .claim(&view, bound, request.recipient(), index) .await? @@ -300,7 +300,7 @@ impl BrowserWorkspace { TransactionId::from_bytes(*crypto::random::<32>()?), now, )?; - let encoded = ClaimRecord::capture(&attempt).encode()?; + let encoded = ClaimRecord::capture(&attempt)?.encode()?; let protected = crypto::seal_bound( state.provider.as_ref(), &state.reference, @@ -370,7 +370,7 @@ impl BrowserWorkspace { if bound.plan().digest() != request.plan_digest() { return Err(OperationError::IdempotencyConflict); } - if let Some(index) = position(&bound, request.recipient()) { + if let Some(index) = position(&bound, request.recipient())? { match state .claim(&view, bound, request.recipient(), index) .await? @@ -437,7 +437,7 @@ impl BrowserWorkspace { .await? .ok_or(OperationError::RecoveryRequired)?; let index = - position(&bound, supplied.recipient()).ok_or(OperationError::InvalidEvidence)?; + position(&bound, supplied.recipient())?.ok_or(OperationError::InvalidEvidence)?; let attempt = match state .claim(&view, bound, supplied.recipient(), index) .await? @@ -533,7 +533,7 @@ impl BrowserWorkspace { if bound.plan().digest() != request.plan_digest() { return Err(OperationError::IdempotencyConflict); } - if let Some(index) = position(&bound, request.recipient()) { + if let Some(index) = position(&bound, request.recipient())? { match state .claim(&view, bound, request.recipient(), index) .await? diff --git a/crates/storage_indexeddb/src/workspace/plans.rs b/crates/storage_indexeddb/src/workspace/plans.rs @@ -8,7 +8,7 @@ use radroots_secrets::context::{ }; use radroots_storage::{ command::{ - BoundSigningPlan, ChatSigningPlan, CommitAttempt, OperationError, PlanBindingOutcome, + BoundSigningPlan, CapturedSigningPlan, CommitAttempt, OperationError, PlanBindingOutcome, PreparedOperation, protected::{ self, @@ -112,7 +112,7 @@ impl State { &self, prepared: &PreparedOperation, records: &Records, - ) -> Result<Option<(PlanManifest, ChatSigningPlan)>, OperationError> { + ) -> Result<Option<(PlanManifest, CapturedSigningPlan)>, OperationError> { let Some(manifest) = &records[0] else { if records.iter().any(Option::is_some) { return Err(OperationError::RecoveryRequired); @@ -155,7 +155,7 @@ impl State { Ok(()) })?; } - let plan = ChatSigningPlan::parse(prepared.request().chat_command()?, &wire) + let plan = CapturedSigningPlan::parse(prepared.request().command(), &wire) .map_err(|_| OperationError::RecoveryRequired)?; if plan.digest() != manifest.plan_digest().as_bytes() { return Err(OperationError::RecoveryRequired); @@ -166,7 +166,7 @@ impl State { &self, operation: OperationId, manifest: &PlanManifest, - plan: &ChatSigningPlan, + plan: &CapturedSigningPlan, ) -> Result<Records, OperationError> { let mut records = Vec::with_capacity(SLOTS); let bytes = manifest.encode()?; @@ -200,7 +200,7 @@ impl BrowserWorkspace { pub async fn bind_signing_intents( &self, binding: WorkspaceBinding, - supplied: ChatSigningPlan, + supplied: CapturedSigningPlan, proof: AttachmentProof, ) -> Result<PlanBindingOutcome, OperationError> { let fallback = CommitAttempt::new( @@ -213,6 +213,9 @@ impl BrowserWorkspace { let state = self.state.clone(); let result = owned(work, async move { let access = state.operation_access(&binding, proof).await?; + if supplied.listing().is_some() { + return Err(OperationError::UnsupportedOperation); + } let operation = supplied.operation_id(); let view = state.read_view(operation).await?; let t0 = state.operation_records(&view, operation).await?; @@ -247,8 +250,8 @@ impl BrowserWorkspace { if observed >= window.first_issue_not_after() { return Err(OperationError::DeadlineExceeded); } - let checked = ChatSigningPlan::parse( - prepared.request().chat_command()?, + let checked = CapturedSigningPlan::parse( + prepared.request().command(), supplied.protected_wire(), ) .map_err(|_| OperationError::InvalidCommand)?; diff --git a/crates/storage_indexeddb/src/workspace/ports.rs b/crates/storage_indexeddb/src/workspace/ports.rs @@ -3,7 +3,7 @@ use super::BrowserWorkspace; use radroots_domain::{CommandDigest, OperationId, PublicKey}; use radroots_storage::{ command::{ - AdmissionOutcome, AdmissionRequest, BoundSigningPlan, CapturedSeal, ChatSigningPlan, + AdmissionOutcome, AdmissionRequest, BoundSigningPlan, CapturedSeal, CapturedSigningPlan, ClaimAttemptOutcome, ClaimAttemptRequest, DeliveryAttempt, DeliveryAttemptOutcome, DeliveryAttemptRequest, DeliveryObservation, DeliveryObservationOutcome, EnvelopeCandidate, EvidenceCaptureOutcome, InstallationOutcome, InstallationRequest, OperationError, @@ -128,7 +128,7 @@ impl OperationJournal for BrowserWorkspace { fn bind_signing_intents( &self, binding: WorkspaceBinding, - plan: ChatSigningPlan, + plan: CapturedSigningPlan, proof: AttachmentProof, ) -> BoxFuture<'_, Result<PlanBindingOutcome, OperationError>> { Box::pin(BrowserWorkspace::bind_signing_intents( diff --git a/crates/storage_indexeddb/src/workspace/retained.rs b/crates/storage_indexeddb/src/workspace/retained.rs @@ -38,8 +38,11 @@ pub(super) async fn header( }; for key in view.keys() { let (kind, recipient, _) = address::fields(key)?; - if kind >= address::CLAIM && recipient as usize >= plan.seals().len() { - return Err(OperationError::RecoveryRequired); + if kind >= address::CLAIM { + let chat = plan.chat().ok_or(OperationError::UnsupportedOperation)?; + if recipient as usize >= chat.seals().len() { + return Err(OperationError::RecoveryRequired); + } } } Ok(Some(RetainedOperation::Planned(Box::new( @@ -68,14 +71,14 @@ impl Graph { Some(RetainedOperation::Planned(bound)) => { let mut bound = *bound; let keys = bound - .plan() + .chat_plan()? .seals() .iter() .map(|seal| seal.recipient()) .collect::<Vec<_>>(); for (index, recipient) in keys.into_iter().enumerate() { let expected = - EnvelopeEventId::from_bytes(bound.plan().seals()[index].event_id()); + EnvelopeEventId::from_bytes(bound.chat_plan()?.seals()[index].event_id()); match state.claim(view, bound, recipient, index as u8).await? { Claim::Absent(returned, _) => { recipients.push(RecipientSnapshot::from_store_report( @@ -87,7 +90,7 @@ impl Graph { bound = returned; } Claim::Present(attempt) => { - let claim = ClaimSnapshot::from_store_report(&attempt); + let claim = ClaimSnapshot::from_store_report(&attempt)?; // Verify one bounded exact seal at a time; retaining a // receipt does not duplicate private plan/raw bodies. let obtained = state.evidence(view, &attempt, index as u8).await?; diff --git a/crates/storage_indexeddb/tests/browser/seller.mjs b/crates/storage_indexeddb/tests/browser/seller.mjs @@ -21,18 +21,24 @@ async function workflow({WorkspaceFixture}, previous) { const old = await previous.WorkspaceFixture.create(244); const oldFingerprint = old.fingerprint(), oldSelection = old.selection(), oldProof = old.proof(); const original = Array.from(await old.admit(243, false)); + const originalPlanWire = Uint8Array.from(await old.new_plan(243)); + const originalPlan = Array.from(await old.bind_plan(243, originalPlanWire)); await old.close(); const current = await WorkspaceFixture.open(244, oldFingerprint, oldSelection, oldProof); check(!await current.is_seller()); check(JSON.stringify(Array.from(await current.query(243))) === JSON.stringify(original)); check(JSON.stringify(Array.from(await current.admit(243, false))) === JSON.stringify(original)); + check(JSON.stringify(Array.from(await current.plan_query(243))) === JSON.stringify(originalPlan)); + check(JSON.stringify(Array.from(await current.bind_plan(243, originalPlanWire))) === JSON.stringify(originalPlan)); await current.close(); - tests.push('original published buyer preparation reopens and replays without replacement'); + tests.push('original published buyer preparation and signing plan reopen and replay without replacement'); const seller = await WorkspaceFixture.create_seller(245); check(await seller.is_seller()); check(await seller.authenticate() === 1); await refuses(() => seller.wrong_proof(), 'unauthorized'); await refuses(() => seller.admit_public(244), 'capability_unavailable'); + await refuses(() => seller.bind_public(244), 'capability_unavailable'); + check((await seller.plan_query(244)).length === 0); check((await seller.query(244)).length === 0); tests.push('explicit protected seller scope, exact credential and unsupported public refusal without a row'); const fingerprint = seller.fingerprint(), selection = seller.selection(), proof = seller.proof(); diff --git a/crates/storage_indexeddb/tests/browser/src/workspace.rs b/crates/storage_indexeddb/tests/browser/src/workspace.rs @@ -148,28 +148,28 @@ impl WorkspaceFixture { } } pub async fn admit_public(&self, n: u8) -> Result<(), JsValue> { - let request = self.request(n, false).await?; - let input = serde_json::json!({"id":"01".repeat(16),"title":"Carrots","summary":"Quote required", - "description_markdown":"Public terms","published_at":"1000","profile":{ - "profile":"radroots.listing","version":1,"state":"active", - "product":{"name":"Carrots","description":"","producer":null,"origin_summary":null}, - "default_option":"02".repeat(32),"options":[{"id":"02".repeat(32),"label":"One bunch", - "unit":{"type":"package","label":"bunch","contents":{"type":"unspecified"}}, - "increment":"1","minimum":"1","price":{"type":"quote_required"}, - "supply":{"type":"unknown"},"lead_seconds":"0"}], - "fulfillment":{"modes":["pickup"],"area":"Example region","lead_seconds":"0"}, - "authority":null,"media":[]}}); - let wire = serde_json::to_vec(&serde_json::json!({"type":"listing.publish", - "context":request.command().context(),"input":input})) - .unwrap(); - let public = AdmissionRequest::from_protected_wire(request.binding().clone(), &wire) - .map_err(|e| JsValue::from_str(e.code()))?; + let public = self.public_request(n).await?; self.journal() .admit_command_and_hold(public, copied(&self.proof)) .await .map_err(|e| JsValue::from_str(e.code()))?; Err(JsValue::from_str("unexpected_public_commit")) } + pub async fn bind_public(&self, n: u8) -> Result<(), JsValue> { + let public = self.public_request(n).await?; + let plan = radroots_protocol::listing::PublicSigningPlan::capture( + public.command().listing().unwrap(), + UnixSeconds::new(1000).unwrap(), + &["wss://public-plan.fixture.example/a".to_string()], + radroots_protocol::plan::SigningReplay::NonReplayable, + ) + .unwrap(); + self.journal() + .bind_signing_intents(public.binding().clone(), plan.into(), copied(&self.proof)) + .await + .map_err(|e| JsValue::from_str(e.code()))?; + Err(JsValue::from_str("unexpected_public_plan")) + } pub async fn query(&self, n: u8) -> Result<Vec<u8>, JsValue> { let binding = self .owner @@ -439,6 +439,25 @@ impl WorkspaceFixture { clock, }) } + async fn public_request(&self, n: u8) -> Result<AdmissionRequest, JsValue> { + let request = self.request(n, false).await?; + let input = serde_json::json!({"id":"01".repeat(16),"title":"Carrots","summary":"Quote required", + "description_markdown":"Public terms","published_at":"1000","profile":{ + "profile":"radroots.listing","version":1,"state":"active", + "product":{"name":"Carrots","description":"","producer":null,"origin_summary":null}, + "default_option":"02".repeat(32),"options":[{"id":"02".repeat(32),"label":"One bunch", + "unit":{"type":"package","label":"bunch","contents":{"type":"unspecified"}}, + "increment":"1","minimum":"1","price":{"type":"quote_required"}, + "supply":{"type":"unknown"},"lead_seconds":"0"}], + "fulfillment":{"modes":["pickup"],"area":"Example region","lead_seconds":"0"}, + "authority":null,"media":[]}}); + let wire = serde_json::to_vec(&serde_json::json!({"type":"listing.publish", + "context":request.command().context(),"input":input})) + .unwrap(); + let public = AdmissionRequest::from_protected_wire(request.binding().clone(), &wire) + .map_err(|e| JsValue::from_str(e.code()))?; + Ok(public) + } async fn request(&self, n: u8, changed: bool) -> Result<AdmissionRequest, JsValue> { let binding = self .owner diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/delivery.rs b/crates/storage_indexeddb/tests/browser/src/workspace/delivery.rs @@ -148,7 +148,8 @@ impl WorkspaceFixture { let recipient = snapshot .bound_plan() .unwrap() - .plan() + .chat_plan() + .unwrap() .seals() .get(index as usize) .ok_or(JsValue::from_str("invalid_recipient"))? diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/issuance.rs b/crates/storage_indexeddb/tests/browser/src/workspace/issuance.rs @@ -15,7 +15,7 @@ fn summary(attempt: &SigningAttempt) -> Vec<u8> { raw.extend_from_slice(attempt.binding().digest()); raw.extend_from_slice(&attempt.claimed_at().get().to_be_bytes()); raw.extend_from_slice(&attempt.deadline_unix_ms().get().to_be_bytes()); - raw.extend_from_slice(&attempt.seal().event_id()); + raw.extend_from_slice(&attempt.seal().unwrap().event_id()); raw } fn receipt(value: EvidenceReceipt) -> Vec<u8> { @@ -35,7 +35,7 @@ fn signed_output( attempt: &SigningAttempt, observed: Option<NonZeroU64>, ) -> Result<SealEvidence, JsValue> { - let fields = attempt.seal().fields(); + let fields = attempt.seal().unwrap().fields(); let context = nostr::secp256k1::Secp256k1::new(); let mut scalar = [0; 32]; scalar[31] = 1; @@ -102,7 +102,8 @@ impl WorkspaceFixture { .map_err(|e| JsValue::from_str(e.code()))? .ok_or(JsValue::from_str("missing_plan"))?; let recipient = bound - .plan() + .chat_plan() + .unwrap() .seals() .get(index as usize) .ok_or(JsValue::from_str("invalid_recipient"))? @@ -128,7 +129,7 @@ impl WorkspaceFixture { identity.operation_id(), identity.command_digest(), *bound.plan().digest(), - original.attempt.seal().recipient(), + original.attempt.seal().unwrap().recipient(), ); self.journal() .obtained_evidence(request, copied(&self.proof)) diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/plans.rs b/crates/storage_indexeddb/tests/browser/src/workspace/plans.rs @@ -8,7 +8,8 @@ use nostr::{ prelude::rand::{CryptoRng, Error, RngCore}, }; use radroots_domain::{EnvelopeEventId, UnixSeconds}; -use radroots_protocol::chat::{CapturedDmRoute, ChatReplay, ChatRumor, ChatSeal, ChatSigningPlan}; +use radroots_protocol::chat::{CapturedDmRoute, ChatRumor, ChatSeal, ChatSigningPlan}; +use radroots_protocol::plan::SigningReplay; use radroots_storage::command::{BoundSigningPlan, PlanBindingOutcome}; use radroots_storage::workspace::WorkspaceStore; use wasm_bindgen::{JsCast, prelude::*}; @@ -143,7 +144,7 @@ impl WorkspaceFixture { ); } Ok( - ChatSigningPlan::new(command, time, seals, routes, ChatReplay::NonReplayable) + ChatSigningPlan::new(command, time, seals, routes, SigningReplay::NonReplayable) .unwrap() .protected_wire() .to_vec(), @@ -175,7 +176,11 @@ impl WorkspaceFixture { hook.call0(&JsValue::NULL)?; match self .journal() - .bind_signing_intents(request.binding().clone(), plan, copied(&self.proof)) + .bind_signing_intents( + request.binding().clone(), + (plan).into(), + copied(&self.proof), + ) .await .map_err(|e| JsValue::from_str(e.code()))? { @@ -205,7 +210,7 @@ impl WorkspaceFixture { .map_err(super::fail)?; let result = self .journal() - .bind_signing_intents(foreign, plan, copied(&self.proof)) + .bind_signing_intents(foreign, (plan).into(), copied(&self.proof)) .await; sibling.close().await?; result.map(|_| ()).map_err(|e| JsValue::from_str(e.code())) @@ -227,7 +232,11 @@ impl WorkspaceFixture { let plan = ChatSigningPlan::parse(request.chat_command().unwrap(), &wire).unwrap(); if self .journal() - .bind_signing_intents(request.binding().clone(), plan, copied(&self.proof)) + .bind_signing_intents( + request.binding().clone(), + (plan).into(), + copied(&self.proof), + ) .now_or_never() .is_some() { @@ -265,7 +274,11 @@ impl WorkspaceFixture { } let outcome = self .journal() - .bind_signing_intents(request.binding().clone(), plan, copied(&self.proof)) + .bind_signing_intents( + request.binding().clone(), + (plan).into(), + copied(&self.proof), + ) .await .map_err(|e| JsValue::from_str(e.code()))?; match outcome { diff --git a/crates/storage_sqlite/src/workspace/admission.rs b/crates/storage_sqlite/src/workspace/admission.rs @@ -4,7 +4,7 @@ use super::{ }; use radroots_domain::{CommandDigest, IssuanceWindow, OperationId, TransactionId}; use radroots_storage::command::{ - AdmissionOutcome, AdmissionRequest, BoundSigningPlan, ChatSigningPlan, CommitAttempt, + AdmissionOutcome, AdmissionRequest, BoundSigningPlan, CapturedSigningPlan, CommitAttempt, OperationError, PlanBindingOutcome, PreparedOperation, }; use sqlx::{Connection, Sqlite, SqliteConnection, Transaction}; @@ -47,7 +47,7 @@ impl Journal<'_> { pub(super) async fn bind_plan( &mut self, binding: WorkspaceBinding, - supplied: ChatSigningPlan, + supplied: CapturedSigningPlan, proof: AttachmentProof, ) -> Result<PlanBindingOutcome, OperationError> { let (record, grant, current) = self.access(&binding, &proof).await?; @@ -78,8 +78,8 @@ impl Journal<'_> { if current.observed_at() >= window.first_issue_not_after() { return Err(OperationError::DeadlineExceeded); } - let supplied = ChatSigningPlan::parse( - prepared.request().chat_command()?, + let supplied = CapturedSigningPlan::parse( + prepared.request().command(), supplied.protected_wire(), ) .map_err(|_| OperationError::InvalidCommand)?; diff --git a/crates/storage_sqlite/src/workspace/attempt.rs b/crates/storage_sqlite/src/workspace/attempt.rs @@ -13,23 +13,23 @@ pub(super) const ID_INDEX: &str = "CREATE UNIQUE INDEX signing_attempt_identity ON signing_attempts(workspace,attempt_id)"; pub(super) const TX_INDEX: &str = "CREATE UNIQUE INDEX signing_attempt_transaction_identity ON signing_attempts(workspace,transaction_id)"; -pub(super) fn scope(attempt: &SigningAttempt) -> IssuanceScope { +pub(super) fn scope(attempt: &SigningAttempt) -> Result<IssuanceScope, OperationError> { let identity = attempt.bound_plan().prepared().identity(); - IssuanceScope { + Ok(IssuanceScope { workspace: identity.workspace_id(), operation: identity.operation_id(), plan_digest: *attempt.bound_plan().plan().digest(), attempt: attempt.attempt_id(), - recipient: attempt.seal().recipient(), - } + recipient: attempt.seal()?.recipient(), + }) } pub(super) async fn protect( attempt: &SigningAttempt, crypto: &WorkspaceCrypto, ) -> Result<Vec<u8>, OperationError> { - let bytes = ClaimRecord::capture(attempt).encode()?; + let bytes = ClaimRecord::capture(attempt)?.encode()?; Ok(crypto - .seal_issuance(scope(attempt), IssuancePayload::Attempt, 0, &bytes) + .seal_issuance(scope(attempt)?, IssuancePayload::Attempt, 0, &bytes) .await?) } /// Returns the complete original plan on absence as well as a verified retained @@ -105,7 +105,7 @@ pub(super) async fn insert( ) -> Result<(), OperationError> { let identity = attempt.bound_plan().prepared().identity(); sqlx::query("INSERT INTO signing_attempts(workspace,operation_id,recipient,attempt_id,transaction_id,plan_digest,intent_digest,protected) VALUES(?,?,?,?,?,?,?,?)") - .bind(identity.workspace_id().as_bytes().as_slice()).bind(identity.operation_id().as_bytes().as_slice()).bind(attempt.seal().recipient().as_bytes().as_slice()).bind(attempt.attempt_id().as_bytes().as_slice()).bind(attempt.transaction_id().as_bytes().as_slice()).bind(attempt.bound_plan().plan().digest().as_slice()).bind(attempt.binding().digest().as_slice()).bind(protected).execute(connection).await.map_err(|_|OperationError::StorageFailure)?; + .bind(identity.workspace_id().as_bytes().as_slice()).bind(identity.operation_id().as_bytes().as_slice()).bind(attempt.seal()?.recipient().as_bytes().as_slice()).bind(attempt.attempt_id().as_bytes().as_slice()).bind(attempt.transaction_id().as_bytes().as_slice()).bind(attempt.bound_plan().plan().digest().as_slice()).bind(attempt.binding().digest().as_slice()).bind(protected).execute(connection).await.map_err(|_|OperationError::StorageFailure)?; Ok(()) } pub(super) async fn unchanged( @@ -115,7 +115,7 @@ pub(super) async fn unchanged( ) -> Result<(), OperationError> { unchanged_snapshot( connection, - ClaimSnapshot::from_store_report(attempt), + ClaimSnapshot::from_store_report(attempt)?, protected, ) .await diff --git a/crates/storage_sqlite/src/workspace/delivery/graph.rs b/crates/storage_sqlite/src/workspace/delivery/graph.rs @@ -40,7 +40,7 @@ fn allowed_routes( ) -> Result<BTreeMap<PublicKey, BTreeSet<String>>, OperationError> { let mut result = BTreeMap::new(); for route in bound - .plan() + .chat_plan()? .routes() .iter() .filter(|route| route.participant() == recipient) diff --git a/crates/storage_sqlite/src/workspace/delivery/graph_tests.rs b/crates/storage_sqlite/src/workspace/delivery/graph_tests.rs @@ -15,7 +15,8 @@ mod cases { ) -> BoundSigningPlan { let transaction = original.transaction_id(); let time = original.bound_at(); - let (prepared, plan) = original.into_parts(); + let (prepared, captured) = original.into_parts(); + let plan = captured.chat().unwrap(); let command = prepared.request().chat_command().unwrap(); let rumor = ChatRumor::from_command(command, plan.created_at()).unwrap(); let seals = plan diff --git a/crates/storage_sqlite/src/workspace/evidence.rs b/crates/storage_sqlite/src/workspace/evidence.rs @@ -33,7 +33,7 @@ pub(super) async fn protect( let receipt = EvidenceReceipt::from_committed_store(evidence, transaction); let manifest = EvidenceManifest::capture(attempt, evidence, transaction)?; let plaintext = manifest.encode()?; - let scope = attempt::scope(attempt); + let scope = attempt::scope(attempt)?; let manifest = crypto .seal_issuance(scope, IssuancePayload::Evidence, 0, &plaintext) .await?; @@ -61,7 +61,7 @@ pub(super) async fn read( attempt: &SigningAttempt, crypto: &WorkspaceCrypto, ) -> Result<Option<(SealEvidence, ProtectedEvidence)>, OperationError> { - let scope = attempt::scope(attempt); + let scope = attempt::scope(attempt)?; let row=sqlx::query("SELECT CASE WHEN length(attempt_id)=32 THEN attempt_id END,CASE WHEN length(event_id)=32 THEN event_id END,CASE WHEN length(evidence_digest)=32 THEN evidence_digest END,CASE WHEN length(transaction_id)=32 THEN transaction_id END,part_count,byte_count,CASE WHEN length(protected)>0 AND length(protected)<=262144 THEN protected END FROM seal_evidence WHERE workspace=? AND operation_id=? AND recipient=?") .bind(scope.workspace.as_bytes().as_slice()).bind(scope.operation.as_bytes().as_slice()).bind(scope.recipient.as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; let Some(row) = row else { @@ -178,7 +178,7 @@ pub(super) async fn unchanged( attempt: &SigningAttempt, value: Option<&ProtectedEvidence>, ) -> Result<(), OperationError> { - unchanged_scope(connection, attempt::scope(attempt), value).await + unchanged_scope(connection, attempt::scope(attempt)?, value).await } pub(super) async fn unchanged_scope( connection: &mut SqliteConnection, diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -309,7 +309,7 @@ impl radroots_storage::command::OperationJournal for NativeWorkspace { fn bind_signing_intents( &self, binding: WorkspaceBinding, - plan: radroots_storage::command::ChatSigningPlan, + plan: radroots_storage::command::CapturedSigningPlan, proof: AttachmentProof, ) -> BoxFuture< '_, diff --git a/crates/storage_sqlite/src/workspace/plan.rs b/crates/storage_sqlite/src/workspace/plan.rs @@ -5,7 +5,7 @@ use super::{ }; use radroots_domain::{TransactionId, UnixSeconds}; use radroots_storage::command::protected::plan::PlanManifest; -use radroots_storage::command::{ChatSigningPlan, OperationError, PreparedOperation}; +use radroots_storage::command::{CapturedSigningPlan, OperationError, PreparedOperation}; use sqlx::{Row, SqliteConnection}; use zeroize::Zeroizing; @@ -21,7 +21,7 @@ pub(super) struct ProtectedPlan { } pub(super) async fn protect( prepared: &PreparedOperation, - plan: &ChatSigningPlan, + plan: &CapturedSigningPlan, transaction: TransactionId, bound_at: UnixSeconds, crypto: &WorkspaceCrypto, @@ -74,7 +74,12 @@ pub(super) async fn read( ) -> Result< ( PreparedOperation, - Option<(ChatSigningPlan, TransactionId, UnixSeconds, ProtectedPlan)>, + Option<( + CapturedSigningPlan, + TransactionId, + UnixSeconds, + ProtectedPlan, + )>, ), OperationError, > { @@ -180,7 +185,7 @@ pub(super) async fn read( })?; parts.push(protected); } - let plan = ChatSigningPlan::parse(prepared.request().chat_command()?, &wire) + let plan = CapturedSigningPlan::parse(prepared.request().command(), &wire) .map_err(|_| OperationError::RecoveryRequired)?; if plan.digest() != &digest { return Err(OperationError::RecoveryRequired); diff --git a/crates/storage_sqlite/src/workspace/snapshot.rs b/crates/storage_sqlite/src/workspace/snapshot.rs @@ -64,7 +64,7 @@ impl RetainedGraph { let mut bound = BoundSigningPlan::from_committed_store(prepared, plan, transaction, time)?; let keys: Vec<PublicKey> = bound - .plan() + .chat_plan()? .seals() .iter() .map(|seal| seal.recipient()) @@ -73,7 +73,7 @@ impl RetainedGraph { let (returned, claim) = attempt::read(connection, selected, bound, recipient, crypto).await?; let expected = returned - .plan() + .chat_plan()? .seals() .iter() .find(|seal| seal.recipient() == recipient) @@ -88,7 +88,7 @@ impl RetainedGraph { time, )?; let captured = evidence::read(connection, &attempt, crypto).await?; - let claim = ClaimSnapshot::from_store_report(&attempt); + let claim = ClaimSnapshot::from_store_report(&attempt)?; let (obtained, evidence, original) = match captured { Some((value, protected)) => { (Some(protected.receipt), Some(protected), Some(value)) diff --git a/crates/storage_sqlite/src/workspace/tests/issuance_records.rs b/crates/storage_sqlite/src/workspace/tests/issuance_records.rs @@ -8,8 +8,9 @@ use radroots_domain::{ CommandContextData, EnvelopeEventId, OperationId, SigningAttemptId, TransactionId, }; use radroots_protocol::{ - chat::{CapturedDmRoute, ChatReplay, ChatRumor, ChatSeal, ChatSigningPlan}, + chat::{CapturedDmRoute, ChatRumor, ChatSeal, ChatSigningPlan}, command::{CapturedChatCommand, InquireInput}, + plan::SigningReplay, }; use radroots_storage::command::{ AdmissionOutcome, AdmissionRequest, BoundSigningPlan, ClaimAttemptOutcome, ClaimAttemptRequest, @@ -214,7 +215,7 @@ impl Issued { UnixSeconds::new(100).unwrap(), vec![seal], vec![route], - ChatReplay::NonReplayable, + SigningReplay::NonReplayable, ) .unwrap(); let digest = *plan.digest(); @@ -233,7 +234,7 @@ impl Issued { )); assert!(matches!( store - .bind_signing_intents(binding.clone(), plan, copied()) + .bind_signing_intents(binding.clone(), (plan).into(), copied()) .await .unwrap(), PlanBindingOutcome::Committed(_) @@ -249,9 +250,9 @@ impl Issued { ClaimAttemptOutcome::Claimed(value) => value, _ => panic!("first claim must confirm"), }; - let fields = attempt.seal().fields(); + let fields = attempt.seal().unwrap().fields(); let signed = nostr::UnsignedEvent { - id: Some(nostr::EventId::from_slice(&attempt.seal().event_id()).unwrap()), + id: Some(nostr::EventId::from_slice(&attempt.seal().unwrap().event_id()).unwrap()), pubkey: keys.public_key(), created_at: nostr::Timestamp::from_secs(fields.created_at), kind: nostr::Kind::Custom(13), @@ -320,7 +321,7 @@ async fn authenticated_attempt_headers_and_all_indexed_facts_are_checked_without let issued = Issued::new().await; let mut database = issued.database().await; let crypto = issued.fixture.crypto(); - let scope = attempt_store::scope(&issued.attempt); + let scope = attempt_store::scope(&issued.attempt).unwrap(); let original: Vec<u8> = sqlx::query_scalar("SELECT protected FROM signing_attempts") .fetch_one(&mut database) .await @@ -447,7 +448,7 @@ async fn authenticated_evidence_manifests_parts_and_exact_original_observations_ let issued = Issued::new().await; let mut database = issued.database().await; let crypto = issued.fixture.crypto(); - let scope = attempt_store::scope(&issued.attempt); + let scope = attempt_store::scope(&issued.attempt).unwrap(); let original: Vec<u8> = sqlx::query_scalar("SELECT protected FROM seal_evidence") .fetch_one(&mut database) .await diff --git a/crates/storage_sqlite/src/workspace/tests/plan_records.rs b/crates/storage_sqlite/src/workspace/tests/plan_records.rs @@ -3,8 +3,9 @@ use crate::workspace::{operation, plan as plan_store}; use nostr::{JsonUtil, nips::nip44}; use radroots_domain::{CommandContextData, EnvelopeEventId, OperationId}; use radroots_protocol::{ - chat::{CapturedDmRoute, ChatReplay, ChatRumor, ChatSeal, ChatSigningPlan}, + chat::{CapturedDmRoute, ChatRumor, ChatSeal, ChatSigningPlan}, command::{CapturedChatCommand, InquireInput}, + plan::SigningReplay, }; use radroots_storage::command::{ AdmissionOutcome, AdmissionRequest, OperationJournal, PlanBindingOutcome, @@ -111,7 +112,7 @@ async fn authenticated_plan_manifest_parts_and_transaction_comparisons_refuse_ea UnixSeconds::new(100).unwrap(), vec![seal], vec![route], - ChatReplay::NonReplayable, + SigningReplay::NonReplayable, ) .unwrap(); let digest = *plan.digest(); @@ -132,7 +133,7 @@ async fn authenticated_plan_manifest_parts_and_transaction_comparisons_refuse_ea clock.0.store(90, Ordering::SeqCst); assert!(matches!( store - .bind_signing_intents(binding.clone(), rollback_plan, copied()) + .bind_signing_intents(binding.clone(), (rollback_plan).into(), copied()) .await, Err(radroots_storage::command::OperationError::Workspace( WorkspaceError::Unavailable @@ -155,7 +156,7 @@ async fn authenticated_plan_manifest_parts_and_transaction_comparisons_refuse_ea clock.0.store(100, Ordering::SeqCst); assert!(matches!( store - .bind_signing_intents(binding, plan, copied()) + .bind_signing_intents(binding, (plan).into(), copied()) .await .unwrap(), PlanBindingOutcome::Committed(_) diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -5,7 +5,7 @@ use super::{ }; use radroots_domain::{CommandDigest, OperationId, PublicKey}; use radroots_storage::command::{ - AdmissionOutcome, AdmissionRequest, BoundSigningPlan, CapturedSeal, ChatSigningPlan, + AdmissionOutcome, AdmissionRequest, BoundSigningPlan, CapturedSeal, CapturedSigningPlan, ClaimAttemptOutcome, ClaimAttemptRequest, CommitAttempt, DeliveryAttempt, DeliveryAttemptOutcome, DeliveryAttemptRequest, DeliveryObservation, DeliveryObservationOutcome, EnvelopeCandidate, EvidenceCaptureOutcome, InstallationOutcome, @@ -107,7 +107,7 @@ enum Job { ), BindPlan( Box<WorkspaceBinding>, - ChatSigningPlan, + CapturedSigningPlan, AttachmentProof, Reply<PlanBindingOutcome, OperationError>, ), @@ -815,7 +815,7 @@ impl Handle { pub(super) async fn bind_plan( &self, binding: WorkspaceBinding, - plan: ChatSigningPlan, + plan: CapturedSigningPlan, proof: AttachmentProof, ) -> Result<PlanBindingOutcome, OperationError> { let anchor = CommitAttempt::new( diff --git a/crates/storage_sqlite/tests/support/public_admission.rs b/crates/storage_sqlite/tests/support/public_admission.rs @@ -1,5 +1,234 @@ //! Actual encrypted T0 only. No signature, installation or delivery is claimed. use super::*; +use radroots_protocol::{listing::PublicSigningPlan, plan::SigningReplay}; +use radroots_storage::command::{BoundSigningPlan, ClaimAttemptRequest, PlanBindingOutcome}; + +fn public_plan(prepared: &PreparedOperation, time: u64, targets: &[String]) -> PublicSigningPlan { + PublicSigningPlan::capture( + prepared.request().command().listing().unwrap(), + UnixSeconds::new(time).unwrap(), + targets, + SigningReplay::NonReplayable, + ) + .unwrap() +} +fn planned(outcome: PlanBindingOutcome) -> BoundSigningPlan { + match outcome { + PlanBindingOutcome::Committed(plan) => plan, + PlanBindingOutcome::Unknown(_) => panic!("unexpected unknown T1"), + } +} + +#[tokio::test] +async fn public_t1_retains_exact_encrypted_plan_reopens_and_replays_without_fresh_deadline() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_scoped(200, true).await; + let prepared = committed( + store + .admit_command_and_hold( + public_request(&binding, 80, "original public T1", "first"), + copy(&proof), + ) + .await + .unwrap(), + ); + let targets = vec!["wss://public-plan.fixture.example/a".to_string()]; + fixture.clock.now.store(110, Ordering::SeqCst); + let plan = public_plan(&prepared, 101, &targets); + let wire = plan.protected_wire().to_vec(); + let digest = *plan.digest(); + let event = *plan.event().event_id(); + let retained = planned( + store + .bind_signing_intents(binding.clone(), plan.into(), copy(&proof)) + .await + .unwrap(), + ); + let transaction = retained.transaction_id(); + assert_eq!(retained.bound_at().get(), 110); + assert_eq!(retained.plan().digest(), &digest); + assert_eq!( + retained.plan().listing().unwrap().event().event_id(), + &event + ); + assert_eq!( + retained.chat_plan().err(), + Some(OperationError::UnsupportedOperation) + ); + assert!(matches!( + store + .claim_attempt( + ClaimAttemptRequest::new( + binding.clone(), + prepared.identity().operation_id(), + prepared.identity().command_digest(), + digest, + key() + ), + copy(&proof) + ) + .await, + Err(OperationError::UnsupportedOperation) + )); + let mut db = fixture.database().await; + let attempts: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_attempts") + .fetch_one(&mut db) + .await + .unwrap(); + assert_eq!(attempts, 0); + db.close().await.unwrap(); + store.close().await.unwrap(); + for name in ["execution_v1.sqlite", "execution_v1.sqlite-wal"] { + if let Ok(bytes) = std::fs::read(fixture.path.join(name)) { + assert!( + !bytes + .windows(targets[0].len()) + .any(|w| w == targets[0].as_bytes()) + ); + } + } + fixture.clock.now.store(160, Ordering::SeqCst); + let reopened = fixture.reopen(input).await; + let queried = reopened + .signing_plan( + binding.clone(), + prepared.identity().operation_id(), + prepared.identity().command_digest(), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(queried.transaction_id(), transaction); + assert_eq!(queried.plan().protected_wire(), wire); + let replay = planned( + reopened + .bind_signing_intents( + binding.clone(), + public_plan(&prepared, 101, &targets).into(), + copy(&proof), + ) + .await + .unwrap(), + ); + assert_eq!(replay.transaction_id(), transaction); + assert_eq!(replay.plan().protected_wire(), wire); + let other = vec!["wss://public-plan.fixture.example/other".to_string()]; + assert!(matches!( + reopened + .bind_signing_intents( + binding, + public_plan(&prepared, 101, &other).into(), + copy(&proof) + ) + .await, + Err(OperationError::IdempotencyConflict) + )); + reopened.close().await.unwrap(); +} + +#[tokio::test] +async fn public_t1_refuses_wrong_proof_and_fresh_expiry_without_creating_a_plan() { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create_scoped(200, true).await; + let prepared = committed( + store + .admit_command_and_hold( + public_request(&binding, 81, "fresh public T1", "first"), + copy(&proof), + ) + .await + .unwrap(), + ); + let targets = vec!["wss://public-plan.fixture.example/a".to_string()]; + assert!(matches!( + store + .bind_signing_intents( + binding.clone(), + public_plan(&prepared, 100, &targets).into(), + AttachmentProof::from_protected_input(&[0; 32]).unwrap() + ) + .await, + Err(OperationError::Workspace(WorkspaceError::Unauthorized)) + )); + fixture.clock.now.store(150, Ordering::SeqCst); + assert!(matches!( + store + .bind_signing_intents( + binding.clone(), + public_plan(&prepared, 100, &targets).into(), + copy(&proof) + ) + .await, + Err(OperationError::DeadlineExceeded) + )); + assert!( + store + .signing_plan( + binding, + prepared.identity().operation_id(), + prepared.identity().command_digest(), + copy(&proof) + ) + .await + .unwrap() + .is_none() + ); + let mut db = fixture.database().await; + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_plans") + .fetch_one(&mut db) + .await + .unwrap(); + assert_eq!(count, 0); + db.close().await.unwrap(); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn accepted_public_t1_survives_observer_loss_and_close_drains_the_original_plan() { + use futures::FutureExt; + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_scoped(200, true).await; + let prepared = committed( + store + .admit_command_and_hold( + public_request(&binding, 82, "owned public T1", "first"), + copy(&proof), + ) + .await + .unwrap(), + ); + let plan = public_plan( + &prepared, + 100, + &["wss://public-plan.fixture.example/a".to_string()], + ); + let wire = plan.protected_wire().to_vec(); + let (arrived, resume) = fixture.clock.arm(0); + assert!( + store + .bind_signing_intents(binding.clone(), plan.into(), copy(&proof)) + .now_or_never() + .is_none() + ); + reached(arrived).await; + resume.send(()).unwrap(); + store.close().await.unwrap(); + let reopened = fixture.reopen(input).await; + let retained = reopened + .signing_plan( + binding, + prepared.identity().operation_id(), + prepared.identity().command_digest(), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(retained.plan().protected_wire(), wire); + assert!(retained.plan().listing().is_some()); + reopened.close().await.unwrap(); +} fn public_request( binding: &WorkspaceBinding, diff --git a/crates/storage_sqlite/tests/support/workspace_issuance.rs b/crates/storage_sqlite/tests/support/workspace_issuance.rs @@ -82,7 +82,7 @@ async fn prepare( let recipients = plan.seals().iter().map(|seal| seal.recipient()).collect(); bound( store - .bind_signing_intents(binding.clone(), plan, copy(proof)) + .bind_signing_intents(binding.clone(), (plan).into(), copy(proof)) .await .unwrap(), ); @@ -109,7 +109,7 @@ async fn obtain(attempt: &SigningAttempt, missing: bool) -> SealEvidence { let intent = SigningIntent::from_chat_seal( attempt.binding().operation_id(), attempt.bound_plan().prepared().identity().command_digest(), - attempt.seal(), + attempt.seal().unwrap(), ProviderCall::new(key(), attempt.deadline_unix_ms(), CancellationSignal::new()), ) .unwrap(); @@ -335,7 +335,12 @@ async fn one_recipient_obtained_does_not_invent_the_other_and_failed_capture_kee assert!(matches!( store .claim_attempt( - selection(&binding, &prepared, digest, second.seal().recipient()), + selection( + &binding, + &prepared, + digest, + second.seal().unwrap().recipient() + ), copy(&proof) ) .await @@ -671,7 +676,7 @@ async fn missing_preparation_plan_and_attempt_are_distinct_from_wrong_plan_ident let digest = *retained.digest(); bound( store - .bind_signing_intents(binding.clone(), retained, copy(&proof)) + .bind_signing_intents(binding.clone(), (retained).into(), copy(&proof)) .await .unwrap(), ); diff --git a/crates/storage_sqlite/tests/support/workspace_plans.rs b/crates/storage_sqlite/tests/support/workspace_plans.rs @@ -4,7 +4,8 @@ mod issuance; use super::*; use nostr::{JsonUtil, nips::nip44}; use radroots_domain::EnvelopeEventId; -use radroots_protocol::chat::{CapturedDmRoute, ChatReplay, ChatRumor, ChatSeal, ChatSigningPlan}; +use radroots_protocol::chat::{CapturedDmRoute, ChatRumor, ChatSeal, ChatSigningPlan}; +use radroots_protocol::plan::SigningReplay; use radroots_storage::command::{BoundSigningPlan, PlanBindingOutcome}; fn keys(last: u8) -> nostr::Keys { let mut bytes = [0; 32]; @@ -78,7 +79,7 @@ fn plan( UnixSeconds::new(created).unwrap(), seals, routes, - ChatReplay::NonReplayable, + SigningReplay::NonReplayable, ) .unwrap() } @@ -111,11 +112,11 @@ async fn complete_private_plan_commits_reopens_and_replays_exact_original_bytes_ ); let retained = bound( store - .bind_signing_intents(binding.clone(), original, copy(&proof)) + .bind_signing_intents(binding.clone(), (original).into(), copy(&proof)) .await .unwrap(), ); - assert_eq!(retained.plan().seals().len(), 2); + assert_eq!(retained.chat_plan().unwrap().seals().len(), 2); assert_eq!(retained.plan().protected_wire(), wire); assert_eq!( retained.prepared().transaction_id(), @@ -125,7 +126,7 @@ async fn complete_private_plan_commits_reopens_and_replays_exact_original_bytes_ let altered = plan(prepared.request().chat_command().unwrap(), 100, "changed"); assert!(matches!( store - .bind_signing_intents(binding.clone(), altered, copy(&proof)) + .bind_signing_intents(binding.clone(), (altered).into(), copy(&proof)) .await, Err(OperationError::IdempotencyConflict) )); @@ -134,7 +135,7 @@ async fn complete_private_plan_commits_reopens_and_replays_exact_original_bytes_ assert_eq!( bound( store - .bind_signing_intents(binding.clone(), replay, copy(&proof)) + .bind_signing_intents(binding.clone(), (replay).into(), copy(&proof)) .await .unwrap() ) @@ -193,7 +194,7 @@ async fn no_new_plan_commits_after_window_or_after_current_grant_revocation() { fixture.clock.now.store(150, Ordering::SeqCst); } let result = store - .bind_signing_intents(binding, supplied, copy(&proof)) + .bind_signing_intents(binding, (supplied).into(), copy(&proof)) .await; assert!(if revoked { matches!( @@ -229,11 +230,12 @@ async fn admitted_plan_outlives_its_observer_and_byte_budget_refuses_unadmitted_ let (arrived, resume) = fixture.clock.arm(0); let mut first = store.bind_signing_intents( binding.clone(), - plan( + (plan( preparations[0].request().chat_command().unwrap(), 100, "one", - ), + )) + .into(), copy(&proof), ); assert!(futures::poll!(first.as_mut()).is_pending()); @@ -243,7 +245,7 @@ async fn admitted_plan_outlives_its_observer_and_byte_budget_refuses_unadmitted_ for prepared in &preparations[1..4] { let mut next = store.bind_signing_intents( binding.clone(), - plan(prepared.request().chat_command().unwrap(), 100, "one"), + (plan(prepared.request().chat_command().unwrap(), 100, "one")).into(), copy(&proof), ); assert!(futures::poll!(next.as_mut()).is_pending()); @@ -253,11 +255,12 @@ async fn admitted_plan_outlives_its_observer_and_byte_budget_refuses_unadmitted_ store .bind_signing_intents( binding.clone(), - plan( + (plan( preparations[4].request().chat_command().unwrap(), 100, "one" - ), + )) + .into(), copy(&proof) ) .await, @@ -312,7 +315,7 @@ async fn expiry_during_protection_and_known_sql_rollback_preserve_unbound_prepar sqlx::raw_sql("CREATE TRIGGER reject_plan BEFORE INSERT ON signing_plan_parts WHEN NEW.part=2 BEGIN SELECT RAISE(ABORT,'synthetic storage failure'); END").execute(&mut database).await.unwrap(); } let (arrived, resume) = fixture.clock.arm(1); - let mut call = store.bind_signing_intents(binding.clone(), supplied, copy(&proof)); + let mut call = store.bind_signing_intents(binding.clone(), (supplied).into(), copy(&proof)); assert!(futures::poll!(call.as_mut()).is_pending()); reached(arrived).await; if expire { @@ -367,7 +370,7 @@ async fn unknown_plan_completion_latches_until_reopen_and_preserves_original_ope let mut database = fixture.database().await; sqlx::raw_sql("CREATE TRIGGER unknown_plan BEFORE INSERT ON signing_plan_parts WHEN NEW.part=2 BEGIN SELECT RAISE(ROLLBACK,'synthetic unknown completion'); END").execute(&mut database).await.unwrap(); let outcome = store - .bind_signing_intents(binding.clone(), supplied, copy(&proof)) + .bind_signing_intents(binding.clone(), (supplied).into(), copy(&proof)) .await .unwrap(); match outcome { @@ -428,7 +431,7 @@ async fn retained_plan_refuses_index_manifest_and_part_substitution_without_repa store .bind_signing_intents( binding.clone(), - plan(prepared.request().chat_command().unwrap(), 100, "one"), + (plan(prepared.request().chat_command().unwrap(), 100, "one")).into(), copy(&proof), ) .await