commit c7da8dbcc9224f5d582b4a217dc301f2708afc6d parent c8b656e4241ea959fa96001cecd53dab3336e8db Author: triesap <tyson@radroots.org> Date: Mon, 19 Oct 2026 18:04:31 +0000 storage: Persist protected browser signing plans - Share validated original plan metadata across protected hosts. - Bind complete browser plans atomically with current access and original windows. - Preserve uncertain attempts and refuse orphaned native and browser state. - Verify real browser crypto, replay, rollback, corruption and restart behavior. Diffstat:
18 files changed, 1367 insertions(+), 110 deletions(-)
diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -759,6 +759,21 @@ pub fn radroots_storage::memory::MemoryStorage::verify_backup(&self, radroots_st pub mod radroots_storage::command pub use radroots_storage::command::ChatSigningPlan pub mod radroots_storage::command::protected +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 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::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 +pub const fn radroots_storage::command::protected::plan::PlanManifest::plan_digest(&self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_storage::command::protected::plan::PlanManifest::transaction_id(&self) -> radroots_domain::identifier::TransactionId +pub const radroots_storage::command::protected::plan::PARTS_MAX: usize +pub const radroots_storage::command::protected::plan::PART_BYTES: usize +pub const radroots_storage::command::protected::plan::PLAN_BYTES_MAX: usize pub const radroots_storage::command::protected::PREPARED_BYTES_MAX: usize pub fn radroots_storage::command::protected::check_digest(&radroots_storage::command::PreparedOperation, radroots_domain::context::ActorRef, core::option::Option<radroots_domain::identifier::CommandDigest>) -> core::result::Result<(), radroots_storage::command::OperationError> pub fn radroots_storage::command::protected::decode(&[u8], &radroots_storage::workspace::AttachmentInput, radroots_domain::identifier::OperationId) -> core::result::Result<radroots_storage::command::PreparedOperation, radroots_storage::command::OperationError> diff --git a/contracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt b/contracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt @@ -6,6 +6,9 @@ impl radroots_storage_indexeddb::workspace::BrowserWorkspace pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::admit_command_and_hold(&self, radroots_storage::command::AdmissionRequest, radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage::command::AdmissionOutcome, radroots_storage::command::OperationError> pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::query_operation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage::command::PreparedOperation>, radroots_storage::command::OperationError> impl radroots_storage_indexeddb::workspace::BrowserWorkspace +pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::bind_signing_intents(&self, radroots_storage::workspace::WorkspaceBinding, radroots_protocol::chat::plan::ChatSigningPlan, radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage::command::PlanBindingOutcome, radroots_storage::command::OperationError> +pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::query_signing_intents(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage::command::BoundSigningPlan>, radroots_storage::command::OperationError> +impl radroots_storage_indexeddb::workspace::BrowserWorkspace pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::close(&self) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::initialize_local_outbox(radroots_storage::workspace::local_outbox::LocalOutboxConfig, alloc::rc::Rc<dyn radroots_secrets::provider::SecretProvider>, radroots_secrets::id::SecretRef, radroots_secrets::provider::AccessPolicy, alloc::rc::Rc<dyn radroots_storage::workspace::WorkspaceClock>) -> core::result::Result<(Self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof), radroots_storage::workspace::WorkspaceError> pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::open_existing(radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof, alloc::rc::Rc<dyn radroots_secrets::provider::SecretProvider>, radroots_secrets::id::SecretRef, radroots_secrets::provider::AccessPolicy, alloc::rc::Rc<dyn radroots_storage::workspace::WorkspaceClock>) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> diff --git a/contracts/architecture/decisions/browser_workspace.v1.json b/contracts/architecture/decisions/browser_workspace.v1.json @@ -1,7 +1,7 @@ { "schema_version": 1, "contract_id": "radroots.storage.browser_workspace.v1", - "state": "implemented_admission_component", + "state": "implemented_admission_and_plan_components", "owner": "radroots_storage_indexeddb", "feature": "workspace", "target": "wasm32-unknown-unknown", @@ -44,12 +44,14 @@ "resources": { "clear_grant_bytes_max": 16384, "protected_grant_bytes_max": 32768, - "conservative_job_reservation_bytes": 524288, + "conservative_job_reservation_bytes": 4194304, "live_job_bytes_max": 4194304, - "live_jobs_max_per_workspace": 8, + "live_jobs_max_per_workspace": 1, "setup_jobs_max_per_host_thread": 8, "close_observers_max": 32, - "whole_browser_memory_bound_claim": false + "whole_browser_memory_bound_claim": false, + "setup_conservative_reservation_bytes": 524288, + "reservation_revision": "T1 complete 384 KiB plan, owned structural representations and atomic record comparisons share the unchanged 4 MiB workspace live budget; one accepted serial job." }, "qualification": { "browsers": [ @@ -88,6 +90,29 @@ ], "unknown_completion": "retain_original_attempt_stop_admission_exact_reopen", "orphan_or_corrupt_replacement_allowed": false, + "participant_issuance_installation_or_delivery": false, + "absent_t0_compares_plan_slots_atomically": 25 + }, + "shared_plan_codec": "radroots_storage::command::protected::plan::PlanManifest", + "signing_plan_binding": { + "phase": "T1_only", + "complete_plan_clear_bytes_max": 393216, + "private_record_clear_bytes_max": 16384, + "part_count_max": 24, + "fixed_plan_slots_compared_atomically": 25, + "grant_t0_and_t1_batch_records": 31, + "batch_records_max": 32, + "original_preparation_transaction_and_window_retained": true, + "exact_retained_replay_before_fresh_deadline_or_entropy": true, + "independent_context_binds": [ + "workspace", + "operation", + "manifest_or_part_position", + "complete_plan_digest_for_parts" + ], + "unknown_completion": "retain_original_attempt_stop_admission_exact_reopen", + "missing_or_orphan_replacement_allowed": false, + "native_v1_wire_schema_and_context_preserved": true, "participant_issuance_installation_or_delivery": false } } diff --git a/crates/storage/src/command/protected.rs b/crates/storage/src/command/protected.rs @@ -8,6 +8,8 @@ use radroots_domain::{ use serde::{Deserialize, Serialize}; use zeroize::Zeroizing; +pub mod plan; + /// Maximum complete preparation, before a host splits private records. pub const PREPARED_BYTES_MAX: usize = 65_536; @@ -160,7 +162,7 @@ mod tests { use radroots_domain::{CommandContextData, ExecutorId, GrantId, PublicKey, WorkspaceId}; use serde_json::json; - fn request() -> AdmissionRequest { + pub(super) fn request() -> AdmissionRequest { let participant = PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798") .unwrap(); diff --git a/crates/storage/src/command/protected/plan.rs b/crates/storage/src/command/protected/plan.rs @@ -0,0 +1,279 @@ +//! 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 radroots_domain::{CommandDigest, OperationId, TransactionId, UnixSeconds, WorkspaceId}; +use serde::{Deserialize, Serialize}; +use zeroize::Zeroizing; + +/// Maximum plaintext in each private plan record. +pub const PART_BYTES: usize = 16 * 1024; +/// Maximum parts in the complete existing known-kind plan profile. +pub const PARTS_MAX: usize = PLAN_BYTES_MAX / PART_BYTES; +/// Maximum complete retained plan representation. +pub const PLAN_BYTES_MAX: usize = radroots_protocol::chat::PLAN_MAX_BYTES; + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Wire { + version: u8, + workspace: WorkspaceId, + operation_id: OperationId, + command_digest: CommandDigest, + preparation_transaction: TransactionId, + plan_digest: CommandDigest, + transaction_id: TransactionId, + bound_at: UnixSeconds, + part_count: usize, + byte_count: usize, +} + +/// Opaque validated retained metadata; its Serde representation stays private. +pub struct PlanManifest(Wire); +impl PlanManifest { + /// Captures structurally valid original T1 data before protection. The host + /// must still authenticate current access and confirm its actual transaction. + pub fn capture( + prepared: &PreparedOperation, + plan: &ChatSigningPlan, + transaction: TransactionId, + bound_at: UnixSeconds, + ) -> Result<Self, OperationError> { + let anchor = prepared.identity(); + if plan.operation_id() != anchor.operation_id() + || plan.command_digest() != anchor.command_digest() + || plan.created_at() < prepared.issuance_window().prepared_at() + || plan.created_at() > bound_at + { + return Err(OperationError::InvalidCommand); + } + let result = Self(Wire { + version: 1, + workspace: anchor.workspace_id(), + operation_id: anchor.operation_id(), + command_digest: anchor.command_digest(), + preparation_transaction: prepared.transaction_id(), + plan_digest: CommandDigest::from_bytes(*plan.digest()), + transaction_id: transaction, + bound_at, + part_count: plan.protected_wire().len().div_ceil(PART_BYTES), + byte_count: plan.protected_wire().len(), + }); + result.validate(prepared)?; + Ok(result) + } + fn validate(&self, prepared: &PreparedOperation) -> Result<(), OperationError> { + let w = &self.0; + let anchor = prepared.identity(); + let window = prepared.issuance_window(); + if w.version != 1 + || w.workspace != anchor.workspace_id() + || w.operation_id != anchor.operation_id() + || w.command_digest != anchor.command_digest() + || w.preparation_transaction != prepared.transaction_id() + || !(1..=PARTS_MAX).contains(&w.part_count) + || !(1..=PLAN_BYTES_MAX).contains(&w.byte_count) + || w.byte_count.div_ceil(PART_BYTES) != w.part_count + || w.bound_at < window.prepared_at() + || w.bound_at >= window.first_issue_not_after() + { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } + /// Encodes bounded metadata for explicit trusted-host protection. + pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>, OperationError> { + let bytes = Zeroizing::new( + serde_json::to_vec(&self.0).map_err(|_| OperationError::RecoveryRequired)?, + ); + if bytes.len() > PART_BYTES { + return Err(OperationError::RecoveryRequired); + } + Ok(bytes) + } + /// Checks bounded decrypted metadata against the independently retained T0. + pub fn decode(bytes: &[u8], prepared: &PreparedOperation) -> Result<Self, OperationError> { + if bytes.len() > PART_BYTES { + return Err(OperationError::RecoveryRequired); + } + let result = + Self(serde_json::from_slice(bytes).map_err(|_| OperationError::RecoveryRequired)?); + result.validate(prepared)?; + Ok(result) + } + pub const fn plan_digest(&self) -> CommandDigest { + self.0.plan_digest + } + pub const fn transaction_id(&self) -> TransactionId { + self.0.transaction_id + } + pub const fn bound_at(&self) -> UnixSeconds { + self.0.bound_at + } + pub const fn part_count(&self) -> usize { + self.0.part_count + } + pub const fn byte_count(&self) -> usize { + self.0.byte_count + } + /// Checks complete original bytes before constructing a retained T1 report. + /// This is historical data validation; concrete completion remains required. + pub fn bind( + self, + prepared: PreparedOperation, + plan: ChatSigningPlan, + ) -> Result<BoundSigningPlan, OperationError> { + self.validate(&prepared)?; + if plan.digest() != self.plan_digest().as_bytes() + || plan.protected_wire().len() != self.byte_count() + { + return Err(OperationError::RecoveryRequired); + } + BoundSigningPlan::from_committed_store( + prepared, + plan, + self.transaction_id(), + self.bound_at(), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::protected::tests::request; + use radroots_domain::{EnvelopeEventId, IssuanceWindow, Sequence}; + use radroots_protocol::chat::{CapturedDmRoute, ChatReplay, ChatRumor, ChatSeal}; + use serde_json::json; + + fn make_prepared() -> PreparedOperation { + PreparedOperation::from_committed_store( + request(), + TransactionId::from_bytes([7; 32]), + Sequence::new(1).unwrap(), + IssuanceWindow::new( + UnixSeconds::new(100).unwrap(), + UnixSeconds::new(150).unwrap(), + ) + .unwrap(), + ) + .unwrap() + } + fn make_plan(prepared: &PreparedOperation, created: u64) -> ChatSigningPlan { + // These are structural descriptors for pure codec tests. They supply + // neither authenticated ciphertext nor a verified relay advertisement. + let command = prepared.request().command(); + let now = UnixSeconds::new(created).unwrap(); + let rumor = ChatRumor::from_command(command, now).unwrap(); + let recipient = rumor.recipients()[0]; + let size = rumor.budget().rumor_ciphertext_bytes(); + let seal = (0..=2) + .find_map(|pad| { + let text = format!("Ag{}{}", "A".repeat(size - 2 - pad), "=".repeat(pad)); + ChatSeal::new(&rumor, recipient, now, &text).ok() + }) + .unwrap(); + let route = CapturedDmRoute::from_observed_descriptor( + recipient, + EnvelopeEventId::from_bytes([8; 32]), + r#"{"synthetic":"structural codec descriptor"}"#, + &["wss://codec.example/".into()], + ) + .unwrap(); + ChatSigningPlan::new( + command, + now, + vec![seal], + vec![route], + ChatReplay::NonReplayable, + ) + .unwrap() + } + #[test] + fn manifest_binds_original_preparation_plan_and_window_without_minting_authority() { + let prepared = make_prepared(); + let plan = make_plan(&prepared, 100); + let transaction = TransactionId::from_bytes([9; 32]); + let manifest = PlanManifest::capture( + &prepared, + &plan, + transaction, + UnixSeconds::new(100).unwrap(), + ) + .unwrap(); + let bytes = manifest.encode().unwrap(); + let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(manifest.plan_digest().as_bytes(), plan.digest()); + assert_eq!(manifest.transaction_id(), transaction); + assert_eq!(manifest.bound_at().get(), 100); + assert_eq!( + manifest.part_count(), + plan.protected_wire().len().div_ceil(PART_BYTES) + ); + assert_eq!(manifest.byte_count(), plan.protected_wire().len()); + for (pointer, replacement) in [ + ("/version", json!(2)), + ("/workspace", json!("11".repeat(32))), + ("/operation_id", json!("22".repeat(32))), + ("/command_digest", json!("33".repeat(32))), + ("/preparation_transaction", json!("44".repeat(32))), + ("/part_count", json!(0)), + ("/part_count", json!(25)), + ("/part_count", json!(2)), + ("/byte_count", json!(0)), + ("/byte_count", json!(PLAN_BYTES_MAX + 1)), + ("/bound_at", json!("99")), + ("/bound_at", json!("150")), + ] { + let mut damaged = value.clone(); + *damaged.pointer_mut(pointer).unwrap() = replacement; + assert!( + PlanManifest::decode(&serde_json::to_vec(&damaged).unwrap(), &prepared).is_err(), + "{pointer}" + ); + } + assert!(PlanManifest::decode(b"{}", &prepared).is_err()); + assert!(PlanManifest::decode(&vec![0; PART_BYTES + 1], &prepared).is_err()); + let mut foreign = value.clone(); + foreign["plan_digest"] = json!("55".repeat(32)); + let foreign = + PlanManifest::decode(&serde_json::to_vec(&foreign).unwrap(), &prepared).unwrap(); + assert!( + foreign + .bind(make_prepared(), make_plan(&make_prepared(), 100)) + .is_err() + ); + let decoded = PlanManifest::decode(&bytes, &prepared).unwrap(); + let bound = decoded.bind(prepared, plan).unwrap(); + assert_eq!(bound.transaction_id(), transaction); + let late = make_prepared(); + let late_plan = make_plan(&late, 101); + assert!( + PlanManifest::capture( + &late, + &late_plan, + transaction, + UnixSeconds::new(151).unwrap() + ) + .is_err() + ); + assert!( + PlanManifest::capture( + &late, + &late_plan, + transaction, + UnixSeconds::new(100).unwrap() + ) + .is_err() + ); + assert!( + PlanManifest::capture( + &late, + &make_plan(&late, 99), + transaction, + UnixSeconds::new(100).unwrap() + ) + .is_err() + ); + } +} diff --git a/crates/storage_indexeddb/README.md b/crates/storage_indexeddb/README.md @@ -30,14 +30,27 @@ commit atomically, with current access, writer and fresh deadline checks inside active callbacks. Unknown completion retains the original attempt and stops admission until exact reopening. Queries compare the complete fixed record set; missing, orphaned or damaged parts never trigger replacement. These methods -provide T0 only; they do not implement signing, installation or delivery. +provide T0; they do not issue signatures, install messages or deliver them. + +The owner also binds and queries the original complete T1 signing plan, using +the shared native v1 manifest codec. The 384 KiB plan uses at most twenty-four +16 KiB clear parts. Every part binds the workspace, operation, position and +plan digest. One real 31-record transaction compares the grant, all five T0 +slots and all twenty-five T1 slots. Fresh binding rechecks the original issue +window after asynchronous protection; exact retained replay keeps the original +transaction and observation without fresh entropy. Missing, orphaned, foreign +or damaged state refuses, including T0 absence with retained plan records. +Unknown completion retains the original attempt and stops admission. T1 stores +complete captured signing data; participant issuance remains a separate phase. The workspace holds an actual exclusive origin Web Lock. Unavailable or contended acquisition refuses; no in-memory substitute is selected. Accepted jobs remain Rust-owned and serial through cancelled observation. Closing stops admission, drains the jobs, closes IndexedDB, then observes actual lock release. -Its setup/connection queues reserve a conservative 512 KiB per job, accept at -most eight jobs within 4 MiB, and retain at most 32 weak close observations. +Its workspace queue reserves a conservative 4 MiB for one accepted job, +including a complete T1 plan and atomic comparisons. Grant-only setup remains +separately bounded to eight jobs at 512 KiB each; close retains at most 32 weak +observations. These limits cover owned inputs, not browser-internal or whole-process memory. Clear grants are bounded to 16 KiB and their protected representation to 32 KiB. diff --git a/crates/storage_indexeddb/src/workspace/journal.rs b/crates/storage_indexeddb/src/workspace/journal.rs @@ -21,7 +21,24 @@ use zeroize::Zeroizing; const PART_BYTES: usize = 16 * 1024; const PARTS: usize = protected::PREPARED_BYTES_MAX / PART_BYTES; const SLOTS: usize = PARTS + 1; -type Records = Vec<Option<Vec<u8>>>; +pub(super) type Records = Vec<Option<Vec<u8>>>; + +pub(super) struct OperationChange { + pub before: Records, + pub after: Option<Records>, + pub window: Option<IssuanceWindow>, + pub extra: Vec<Mutation>, +} +impl OperationChange { + pub fn observe(before: Records) -> Self { + Self { + before, + after: None, + window: None, + extra: Vec::new(), + } + } +} fn key(operation: OperationId, slot: usize) -> RecordKey { let mut h = Sha256::new(); @@ -61,7 +78,10 @@ fn context( )) } impl State { - async fn operation_records(&self, operation: OperationId) -> Result<Records, OperationError> { + pub(super) async fn operation_records( + &self, + operation: OperationId, + ) -> Result<Records, OperationError> { let mut records = Vec::with_capacity(SLOTS); for slot in 0..SLOTS { let value = self @@ -79,7 +99,7 @@ impl State { } Ok(records) } - async fn preparation( + pub(super) async fn preparation( &self, operation: OperationId, records: &Records, @@ -185,22 +205,23 @@ impl State { Ok(records) } } -fn storage_error(error: Error) -> OperationError { +pub(super) fn storage_error(error: Error) -> OperationError { match error { Error::Capacity => WorkspaceError::Capacity.into(), Error::Closed => WorkspaceError::Closed.into(), + Error::CommitUnknown => WorkspaceError::CommitUnknown.into(), Error::Aborted | Error::Unavailable => OperationError::StorageFailure, _ => OperationError::RecoveryRequired, } } -struct Access { +pub(super) struct Access { grant: LocalOutboxGrant, protected: Vec<u8>, - binding: WorkspaceBinding, + pub binding: WorkspaceBinding, proof: AttachmentProof, } impl State { - async fn operation_access( + pub(super) async fn operation_access( &self, binding: &WorkspaceBinding, proof: AttachmentProof, @@ -214,15 +235,19 @@ impl State { proof, }) } - async fn check_operation( + pub(super) async fn check_operation( &self, access: Access, operation: OperationId, - before: Records, - after: Option<Records>, - window: Option<IssuanceWindow>, + change: OperationChange, ) -> Result<(), OperationError> { - let mut mutations = Vec::with_capacity(SLOTS + 1); + let OperationChange { + before, + after, + window, + extra, + } = change; + let mut mutations = Vec::with_capacity(SLOTS + 1 + extra.len()); mutations.push( Mutation::new( grant_key(), @@ -237,6 +262,7 @@ impl State { .map_or_else(|| old.clone(), |r| r[slot].clone()); mutations.push(Mutation::new(key(operation, slot), old, new).map_err(storage_error)?); } + mutations.extend(extra); let batch = Batch::new(mutations).map_err(storage_error)?; let active = self.active()?; let clock = self.clock.clone(); @@ -308,6 +334,11 @@ impl BrowserWorkspace { let context = request.command().context(); let operation = context.operation_id(); let before = state.operation_records(operation).await?; + let extra = if before.iter().all(Option::is_none) { + state.absent_plans(operation).await? + } else { + Vec::new() + }; let (prepared, after, fresh) = if let Some(existing) = state.preparation(operation, &before).await? { protected::check_digest( @@ -349,9 +380,12 @@ impl BrowserWorkspace { .check_operation( access, operation, - before, - after, - fresh.then(|| prepared.issuance_window()), + OperationChange { + before, + after, + window: fresh.then(|| prepared.issuance_window()), + extra, + }, ) .await { @@ -390,9 +424,11 @@ impl BrowserWorkspace { if let Some(prepared) = &result { protected::check_digest(prepared, binding.actor(), digest)?; } - state - .check_operation(access, operation, records, None, None) - .await?; + let mut change = OperationChange::observe(records); + if result.is_none() { + change.extra = state.absent_plans(operation).await?; + } + state.check_operation(access, operation, change).await?; Ok(result) }) .await diff --git a/crates/storage_indexeddb/src/workspace/mod.rs b/crates/storage_indexeddb/src/workspace/mod.rs @@ -4,6 +4,7 @@ mod crypto; mod journal; mod lease; +mod plans; use super::{Batch, Database, Error, Mutation, Namespace, OpenMode, RecordKey}; use futures::{channel::oneshot, lock::Mutex}; @@ -31,9 +32,10 @@ use std::{ }; use wasm_bindgen_futures::spawn_local; -const JOB_BYTES: usize = 512 * 1024; +const JOB_BYTES: usize = 4 * 1024 * 1024; const LIVE_BYTES: usize = 4 * 1024 * 1024; const JOBS: usize = LIVE_BYTES / JOB_BYTES; +const SETUPS_MAX: usize = 8; const WAITERS: usize = 32; type Signal = RefCell<Option<Waker>>; thread_local! { static SETUPS: Cell<usize> = const { Cell::new(0) }; } @@ -41,7 +43,7 @@ struct Setup; impl Setup { fn admit() -> Result<Self, WorkspaceError> { SETUPS.with(|count| { - if count.get() >= JOBS { + if count.get() >= SETUPS_MAX { return Err(WorkspaceError::Capacity); } count.set(count.get() + 1); diff --git a/crates/storage_indexeddb/src/workspace/plans.rs b/crates/storage_indexeddb/src/workspace/plans.rs @@ -0,0 +1,316 @@ +//! Actual protected T1 storage; no participant issuance or network effects. +use super::journal::{OperationChange, Records, storage_error}; +use super::{BrowserWorkspace, Mutation, RecordKey, State, WorkspaceError, crypto, owned}; +use radroots_domain::{CommandDigest, OperationId, TransactionId}; +use radroots_secrets::context::{ + EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId, +}; +use radroots_storage::{ + command::{ + BoundSigningPlan, ChatSigningPlan, CommitAttempt, OperationError, PlanBindingOutcome, + PreparedOperation, + protected::{ + self, + plan::{PART_BYTES, PARTS_MAX, PlanManifest}, + }, + }, + workspace::{AttachmentProof, WorkspaceBinding}, +}; +use sha2::{Digest, Sha256}; +use zeroize::Zeroizing; + +const SLOTS: usize = PARTS_MAX + 1; +fn key(operation: OperationId, slot: usize) -> RecordKey { + let mut h = Sha256::new(); + h.update(b"radroots.browser.local_outbox.plan.key.v1\0"); + h.update(operation.as_bytes()); + h.update((slot as u32).to_be_bytes()); + RecordKey::new(h.finalize().into()) +} +fn context( + state: &State, + operation: OperationId, + part: Option<(usize, CommandDigest)>, +) -> Result<EnvelopeContext, WorkspaceError> { + let mut h = Sha256::new(); + h.update(b"radroots.browser.local_outbox.plan.context.v1\0"); + h.update(state.selected.workspace_id().as_bytes()); + h.update(operation.as_bytes()); + if let Some((index, digest)) = part { + h.update(b"part\0"); + h.update((index as u32).to_be_bytes()); + h.update(digest.as_bytes()); + } else { + h.update(b"manifest\0"); + } + let subject = h + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect::<String>(); + Ok(EnvelopeContext::new( + EnvelopePurpose::parse("radroots.browser.workspace.plan") + .map_err(|_| WorkspaceError::InvalidInput)?, + EnvelopeSubject::parse("workspace_plan", subject) + .map_err(|_| WorkspaceError::InvalidInput)?, + PayloadSchemaId::parse("radroots.browser.workspace.plan.v1") + .map_err(|_| WorkspaceError::InvalidInput)?, + )) +} +fn comparisons( + operation: OperationId, + before: Records, + after: Option<Records>, +) -> Result<Vec<Mutation>, OperationError> { + before + .into_iter() + .enumerate() + .map(|(slot, old)| { + let new = after + .as_ref() + .map_or_else(|| old.clone(), |values| values[slot].clone()); + Mutation::new(key(operation, slot), old, new).map_err(storage_error) + }) + .collect() +} +impl State { + async fn plan_records(&self, operation: OperationId) -> Result<Records, OperationError> { + let mut records = Vec::with_capacity(SLOTS); + for slot in 0..SLOTS { + let value = self + .db + .get(key(operation, slot)) + .await + .map_err(storage_error)?; + if value + .as_ref() + .is_some_and(|v| v.len() > crypto::PROTECTED_MAX) + { + return Err(OperationError::RecoveryRequired); + } + records.push(value); + } + Ok(records) + } + pub(super) async fn absent_plans( + &self, + operation: OperationId, + ) -> Result<Vec<Mutation>, OperationError> { + let before = self.plan_records(operation).await?; + if before.iter().any(Option::is_some) { + return Err(OperationError::RecoveryRequired); + } + comparisons(operation, before, None) + } + async fn retained_plan( + &self, + prepared: &PreparedOperation, + records: &Records, + ) -> Result<Option<(PlanManifest, ChatSigningPlan)>, OperationError> { + let Some(manifest) = &records[0] else { + if records.iter().any(Option::is_some) { + return Err(OperationError::RecoveryRequired); + } + return Ok(None); + }; + let operation = prepared.identity().operation_id(); + let clear = crypto::open_bound( + self.provider.as_ref(), + &self.reference, + context(self, operation, None)?, + manifest, + ) + .await?; + let manifest = clear.expose_secret(|bytes| PlanManifest::decode(bytes, prepared))?; + let mut wire = Zeroizing::new(Vec::with_capacity(manifest.byte_count())); + for index in 0..PARTS_MAX { + if index >= manifest.part_count() { + if records[index + 1].is_some() { + return Err(OperationError::RecoveryRequired); + } + continue; + } + let protected = records[index + 1] + .as_ref() + .ok_or(OperationError::RecoveryRequired)?; + let bytes = crypto::open_bound( + self.provider.as_ref(), + &self.reference, + context(self, operation, Some((index + 1, manifest.plan_digest())))?, + protected, + ) + .await?; + let expected = (manifest.byte_count() - index * PART_BYTES).min(PART_BYTES); + bytes.expose_secret(|bytes| { + if bytes.len() != expected { + return Err(OperationError::RecoveryRequired); + } + wire.extend_from_slice(bytes); + Ok(()) + })?; + } + let plan = ChatSigningPlan::parse(prepared.request().command(), &wire) + .map_err(|_| OperationError::RecoveryRequired)?; + if plan.digest() != manifest.plan_digest().as_bytes() { + return Err(OperationError::RecoveryRequired); + } + Ok(Some((manifest, plan))) + } + async fn protect_plan( + &self, + operation: OperationId, + manifest: &PlanManifest, + plan: &ChatSigningPlan, + ) -> Result<Records, OperationError> { + let mut records = Vec::with_capacity(SLOTS); + let bytes = manifest.encode()?; + records.push(Some( + crypto::seal_bound( + self.provider.as_ref(), + &self.reference, + context(self, operation, None)?, + &bytes, + ) + .await?, + )); + for (index, part) in plan.protected_wire().chunks(PART_BYTES).enumerate() { + records.push(Some( + crypto::seal_bound( + self.provider.as_ref(), + &self.reference, + context(self, operation, Some((index + 1, manifest.plan_digest())))?, + part, + ) + .await?, + )); + } + records.resize_with(SLOTS, || None); + Ok(records) + } +} +impl BrowserWorkspace { + /// Atomically binds a complete original plan before any participant issuance. + /// Exact retained replay preserves its transaction/observation after expiry. + pub async fn bind_signing_intents( + &self, + binding: WorkspaceBinding, + supplied: ChatSigningPlan, + proof: AttachmentProof, + ) -> Result<PlanBindingOutcome, OperationError> { + let fallback = CommitAttempt::new( + binding.input().workspace_id(), + supplied.operation_id(), + supplied.command_digest(), + None, + ); + let work = self.state.admit()?; + let state = self.state.clone(); + let result = owned(work, async move { + let access = state.operation_access(&binding, proof).await?; + let operation = supplied.operation_id(); + let t0 = state.operation_records(operation).await?; + let prepared = state + .preparation(operation, &t0) + .await? + .ok_or(OperationError::RecoveryRequired)?; + protected::check_digest(&prepared, binding.actor(), Some(supplied.command_digest()))?; + protected::same_binding(prepared.request().binding(), &binding)?; + let before = state.plan_records(operation).await?; + let (manifest, plan, after, fresh) = if let Some((manifest, plan)) = + state.retained_plan(&prepared, &before).await? + { + if plan.protected_wire() != supplied.protected_wire() { + return Err(OperationError::IdempotencyConflict); + } + (manifest, plan, None, false) + } else { + let window = prepared.issuance_window(); + let observed = access.binding.observed_at(); + if observed < window.prepared_at() { + return Err(WorkspaceError::Unavailable.into()); + } + if observed >= window.first_issue_not_after() { + return Err(OperationError::DeadlineExceeded); + } + let checked = + ChatSigningPlan::parse(prepared.request().command(), supplied.protected_wire()) + .map_err(|_| OperationError::InvalidCommand)?; + drop(supplied); + let transaction = TransactionId::from_bytes(*crypto::random::<32>()?); + let manifest = PlanManifest::capture(&prepared, &checked, transaction, observed)?; + let records = state.protect_plan(operation, &manifest, &checked).await?; + (manifest, checked, Some(records), true) + }; + let attempt = CommitAttempt::new( + prepared.identity().workspace_id(), + operation, + prepared.identity().command_digest(), + Some(manifest.transaction_id()), + ); + let change = OperationChange { + before: t0, + after: None, + window: fresh.then(|| prepared.issuance_window()), + extra: comparisons(operation, before, after)?, + }; + match state.check_operation(access, operation, change).await { + Ok(()) => Ok(PlanBindingOutcome::Committed( + manifest.bind(prepared, plan)?, + )), + Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => { + state.stop(); + Ok(PlanBindingOutcome::Unknown(attempt)) + } + Err(error) => Err(error), + } + }) + .await; + match result { + Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => { + self.state.stop(); + Ok(PlanBindingOutcome::Unknown(fallback)) + } + other => other, + } + } + /// Authenticates and confirms the original plan without issuance or replay. + pub async fn query_signing_intents( + &self, + binding: WorkspaceBinding, + operation: OperationId, + digest: CommandDigest, + proof: AttachmentProof, + ) -> Result<Option<BoundSigningPlan>, OperationError> { + let work = self.state.admit()?; + let state = self.state.clone(); + owned(work, async move { + let access = state.operation_access(&binding, proof).await?; + let t0 = state.operation_records(operation).await?; + let prepared = state.preparation(operation, &t0).await?; + let records = state.plan_records(operation).await?; + let retained = if let Some(prepared) = prepared { + protected::check_digest(&prepared, binding.actor(), Some(digest))?; + protected::same_binding(prepared.request().binding(), &binding)?; + let plan = state.retained_plan(&prepared, &records).await?; + Some((prepared, plan)) + } else { + if records.iter().any(Option::is_some) { + return Err(OperationError::RecoveryRequired); + } + None + }; + let change = OperationChange { + before: t0, + after: None, + window: None, + extra: comparisons(operation, records, None)?, + }; + state.check_operation(access, operation, change).await?; + match retained { + Some((prepared, Some((manifest, plan)))) => manifest.bind(prepared, plan).map(Some), + _ => Ok(None), + } + }) + .await + } +} diff --git a/crates/storage_indexeddb/tests/browser/Cargo.lock b/crates/storage_indexeddb/tests/browser/Cargo.lock @@ -31,6 +31,28 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" [[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bech32" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32637268377fc7b10a8c6d51de3e7fba1ce5dd371a96e342b34e6078db558e7f" + +[[package]] +name = "bitcoin_hashes" +version = "0.14.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bca4c7abb40c8817d77403c880988cfd484f23ab2365726afb2f798363e2c4a2" +dependencies = [ + "hex-conservative", + "serde", +] + +[[package]] name = "block-buffer" version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -40,12 +62,30 @@ dependencies = [ ] [[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + +[[package]] name = "bumpalo" version = "3.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" [[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher", +] + +[[package]] name = "cc" version = "1.2.57" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -130,6 +170,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", + "rand_core", "typenum", ] @@ -306,6 +347,19 @@ dependencies = [ ] [[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] name = "group" version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -323,6 +377,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] +name = "hex-conservative" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3fef046dca3ca91ee1408a8c1b80ab777e80a4d308d1bf4e7adb3fcb047e08" +dependencies = [ + "arrayvec", +] + +[[package]] name = "icu_collections" version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -405,6 +468,16 @@ dependencies = [ [[package]] name = "idna" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "idna" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" @@ -430,10 +503,23 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" dependencies = [ + "block-padding", "generic-array", ] [[package]] +name = "instant" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -490,6 +576,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" [[package]] +name = "nostr" +version = "0.44.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7d3d987ea7078dc36947cde532637c472a229426702e4331dd7667325378bd9" +dependencies = [ + "base64", + "bech32", + "bitcoin_hashes", + "cbc", + "chacha20", + "chacha20poly1305", + "getrandom", + "hex", + "instant", + "secp256k1", + "serde", + "serde_json", + "url-fork", +] + +[[package]] name = "num-traits" version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -636,7 +743,9 @@ dependencies = [ "futures", "hex", "js-sys", + "nostr", "radroots_domain", + "radroots_protocol", "radroots_secrets", "radroots_storage", "radroots_storage_indexeddb", @@ -731,10 +840,22 @@ dependencies = [ ] [[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core", +] + +[[package]] name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] [[package]] name = "rust_decimal" @@ -772,7 +893,9 @@ version = "0.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9465315bc9d4566e1724f0fffcbcc446268cb522e60f9a27bcded6b19c108113" dependencies = [ + "rand", "secp256k1-sys", + "serde", ] [[package]] @@ -921,12 +1044,24 @@ dependencies = [ ] [[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] name = "typenum" version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] name = "unicode-general-category" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -939,6 +1074,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] name = "universal-hash" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -955,8 +1099,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" dependencies = [ "form_urlencoded", - "idna", + "idna 1.1.0", + "percent-encoding", +] + +[[package]] +name = "url-fork" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fa3323c39b8e786154d3000b70ae9af0e9bd746c9791456da0d4a1f68ad89d6" +dependencies = [ + "form_urlencoded", + "idna 0.5.0", "percent-encoding", + "serde", ] [[package]] @@ -972,6 +1128,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] name = "wasm-bindgen" version = "0.2.114" source = "registry+https://github.com/rust-lang/crates.io-index" diff --git a/crates/storage_indexeddb/tests/browser/Cargo.toml b/crates/storage_indexeddb/tests/browser/Cargo.toml @@ -14,6 +14,8 @@ crate-type = ["cdylib"] radroots_storage_indexeddb = { path = "../..", features = ["workspace"] } radroots_storage = { path = "../../../storage" } radroots_domain = { path = "../../../domain", features = ["serde", "std"] } +radroots_protocol = { path = "../../../protocol", features = ["chat"] } +nostr = { version = "=0.44.7", default-features = false, features = ["alloc", "nip44"] } serde_json = "=1.0.149" sha2 = "=0.10.9" radroots_secrets = { path = "../../../secrets", features = ["memory", "browser"] } diff --git a/crates/storage_indexeddb/tests/browser/run.mjs b/crates/storage_indexeddb/tests/browser/run.mjs @@ -26,6 +26,7 @@ const server = createServer(async (req,res) => { self.onmessage=async(event)=>{try{ if(event.data?.kind==='workspace_open'||event.data?.kind==='workspace_hold'){const m=event.data;const owner=await WorkspaceFixture.open(m.n,new Uint8Array(m.fingerprint),new Uint8Array(m.selection),new Uint8Array(m.proof));const revision=await owner.authenticate();if(m.kind==='workspace_hold')retainedWorkspace=owner;else await owner.close();self.postMessage({revision});return;} if(event.data?.kind==='journal_query'){const m=event.data;const owner=await WorkspaceFixture.open(m.n,new Uint8Array(m.fingerprint),new Uint8Array(m.selection),new Uint8Array(m.proof));const preparation=Array.from(await owner.query(65));await owner.close();self.postMessage({preparation});return;} + if(event.data?.kind==='plan_query'){const m=event.data;const owner=await WorkspaceFixture.open(m.n,new Uint8Array(m.fingerprint),new Uint8Array(m.selection),new Uint8Array(m.proof));const plan=Array.from(await owner.plan_query(180));await owner.close();self.postMessage({plan});return;} if(event.data?.kind==='persistent_create'){const provider=await Persistent.create(90);const fingerprint=provider.fingerprint();const encoded=await provider.protect(new Uint8Array([90,91,92]));await provider.close();self.postMessage({fingerprint:Array.from(fingerprint),encoded:Array.from(encoded)});return;} if(event.data?.kind==='persistent_open'){const provider=await Persistent.open(90,new Uint8Array(event.data.fingerprint));const plain=await provider.reveal(new Uint8Array(event.data.encoded));await provider.close();self.postMessage({plain:Array.from(plain)});return;} await protected_round_trip(79);const db=await Fixture.open(77,true);await db.write(1,undefined,new Uint8Array([77]));await db.close();const again=await Fixture.open(77,false);const value=await again.read(1);await again.close();self.postMessage({value:Array.from(value)});}catch(error){self.postMessage({error:String(error)});}}; @@ -338,10 +339,89 @@ try { same(originalFallback.length,64);same(originalFallback.slice(0,32),new Array(32).fill(72));await unknownRead.close(); const readReopen=await WorkspaceFixture.open(unknownReadReceipt.n,new Uint8Array(unknownReadReceipt.fingerprint),new Uint8Array(unknownReadReceipt.selection),new Uint8Array(unknownReadReceipt.proof));same(Array.from(await readReopen.query(72)),[]);await readReopen.close(); passed('uncertain original admission read retains the captured operation anchor without inventing a transaction'); + const receiptOf=(owner,n)=>({n,fingerprint:Array.from(owner.fingerprint()),selection:Array.from(owner.selection()),proof:Array.from(owner.proof()),namespace:owner.data_namespace()}); + const openPlanReceipt=r=>WorkspaceFixture.open(r.n,new Uint8Array(r.fingerprint),new Uint8Array(r.selection),new Uint8Array(r.proof)); + const sameRows=(a,b)=>{same(a.keys.map(keyBytes),b.keys.map(keyBytes));same(a.values.map(v=>Array.from(v)),b.values.map(v=>Array.from(v)));}; + const planBox=await WorkspaceFixture.create(180),planReceipt=receiptOf(planBox,180); + await planBox.admit(180,false);same(Array.from(await planBox.plan_query(180)),[]); + const planWire=await planBox.new_plan(180);if(planWire.length<=16384)throw Error('plan did not exercise multipart storage'); + const originalPlan=Array.from(await planBox.bind_plan(180,planWire));same(originalPlan.length,108); + same(new DataView(new Uint8Array(originalPlan).buffer).getUint32(72,false),planWire.length); + same(Array.from(await planBox.plan_query(180)),originalPlan); + const planStored=await workspaceBytes(planReceipt);if(planStored.values.length<8)throw Error('missing actual protected plan parts'); + for(const v of planStored.values)if(v.length>32768)throw Error('oversized protected private plan record'); + passed('actual peer/self NIP44, verified signed routes and atomic complete multipart T1 bind/query'); + await rejects(()=>planBox.bind_plan_foreign(180,planWire),'unauthorized'); + sameRows(await workspaceBytes(planReceipt),planStored); + passed('a valid foreign workspace binding cannot authorize T1 in the original owner'); + planBox.set_time(1600);const oldPlanRandom=Crypto.prototype.getRandomValues; + try{Crypto.prototype.getRandomValues=()=>{throw Error('retained T1 acquired new entropy');};same(Array.from(await planBox.bind_plan(180,planWire)),originalPlan);} + finally{Crypto.prototype.getRandomValues=oldPlanRandom;} + const conflictingPlan=await planBox.new_plan(180);await rejects(()=>planBox.bind_plan(180,conflictingPlan),'idempotency_conflict'); + same(Array.from(await planBox.plan_query(180)),originalPlan); + passed('exact late T1 replay retains original transaction/window without new entropy and refuses conflicting plans'); + planBox.set_time(1000);await planBox.admit(181,false);const expiringPlan=await planBox.new_plan(181); + const beforePlanExpiry=await workspaceBytes(planReceipt);await rejects(()=>planBox.bind_plan_expiring(181,expiringPlan),'deadline_exceeded'); + same(Array.from(await planBox.plan_query(181)),[]);sameRows(await workspaceBytes(planReceipt),beforePlanExpiry); + passed('fresh T1 expiry after actual wrapping rolls back the entire grant/T0/plan comparison batch'); + planBox.set_time(1000);await planBox.admit(182,false);const abortedPlan=await planBox.new_plan(182); + const planKey=async(n,slot)=>new Uint8Array(await crypto.subtle.digest('SHA-256',new Uint8Array([...new TextEncoder().encode('radroots.browser.local_outbox.plan.key.v1\0'),...new Uint8Array(32).fill(n),0,0,0,slot]))); + const abortPlanKey=await planKey(182,1),beforePlanAbort=await workspaceBytes(planReceipt);let planWriteAborted=false; + const actualPlanPut=IDBObjectStore.prototype.put; + try{IDBObjectStore.prototype.put=function(...args){const request=actualPlanPut.apply(this,args);if(this.transaction.db.name===planReceipt.namespace&&JSON.stringify(keyBytes(args[1]))===JSON.stringify(keyBytes(abortPlanKey))){request.addEventListener('success',()=>{planWriteAborted=true;this.transaction.abort();});}return request;};await rejects(()=>planBox.bind_plan(182,abortedPlan),'storage_failure');} + finally{IDBObjectStore.prototype.put=actualPlanPut;} + same(planWriteAborted,true);sameRows(await workspaceBytes(planReceipt),beforePlanAbort);same(Array.from(await planBox.plan_query(182)),[]); + passed('actual T1 part-write success followed by transaction abort never acknowledges or retains partial binding'); + await planBox.abandon_plan(182,abortedPlan);same(planBox.abandon_auths(1),0);planBox.abandon_close();await planBox.close(); + let currentPlanBox=await openPlanReceipt(planReceipt);same((await currentPlanBox.plan_query(182)).length,108);same(Array.from(await currentPlanBox.plan_query(180)),originalPlan); + await currentPlanBox.admit(184,false);await currentPlanBox.close(); + passed('unobserved accepted T1 retains its job reservation and survives cancelled close with original stored result'); + const stablePlans=await workspaceBytes(planReceipt),planKeys=await Promise.all(Array.from({length:25},(_,i)=>planKey(180,i))),foreignPlanKeys=await Promise.all(Array.from({length:25},(_,i)=>planKey(184,i))); + const findPlanBytes=k=>stablePlans.values[stablePlans.keys.findIndex(x=>JSON.stringify(keyBytes(x))===JSON.stringify(keyBytes(k)))]; + for(const mode of ['orphan_manifest','missing_part','tampered','swapped','foreign_operation','missing_t0_query','missing_t0_admit']){ + await changeWorkspace(planReceipt,store=>{ + if(mode==='orphan_manifest')store.delete(planKeys[0]); + if(mode==='missing_part')store.delete(planKeys[1]); + if(mode==='tampered'){const bytes=new Uint8Array(findPlanBytes(planKeys[1]));bytes[bytes.length-1]^=1;store.put(bytes,planKeys[1]);} + if(mode==='swapped'){store.put(findPlanBytes(planKeys[1]),planKeys[2]);store.put(findPlanBytes(planKeys[2]),planKeys[1]);} + if(mode==='foreign_operation')planKeys.forEach((k,i)=>{const v=findPlanBytes(k);if(v)store.put(v,foreignPlanKeys[i]);}); + }); + if(mode.startsWith('missing_t0')){const t0=await Promise.all(Array.from({length:5},(_,i)=>operationKey(180,i)));await changeWorkspace(planReceipt,store=>t0.forEach(k=>store.delete(k)));} + const beforeFailure=await workspaceBytes(planReceipt);currentPlanBox=await openPlanReceipt(planReceipt); + if(mode==='missing_t0_query')await rejects(()=>currentPlanBox.query(180),'recovery_required'); + else if(mode==='missing_t0_admit')await rejects(()=>currentPlanBox.admit(180,false),'recovery_required'); + else await rejects(()=>currentPlanBox.plan_query(mode==='foreign_operation'?184:180),'recovery_required'); + await currentPlanBox.close();sameRows(await workspaceBytes(planReceipt),beforeFailure); + await changeWorkspace(planReceipt,store=>{store.clear();stablePlans.keys.forEach((k,i)=>store.put(stablePlans.values[i],k));}); + } + passed('T1 orphan/missing/tampered/swapped/foreign parts and removed T0 refuse without absence, replacement or repair'); + const unknownPlan=await WorkspaceFixture.create(183),unknownPlanReceipt=receiptOf(unknownPlan,183); + await unknownPlan.admit(183,false);const unknownPlanWire=await unknownPlan.new_plan(183);let planUnknown; + try{IDBTransaction.prototype.abort=function(){if(this.db.name===unknownPlanReceipt.namespace)return;return actualAbort.call(this);};planUnknown=Array.from(await unknownPlan.bind_plan_unknown(183,unknownPlanWire));} + finally{IDBTransaction.prototype.abort=actualAbort;} + same(planUnknown.length,64);same(planUnknown.slice(0,32),new Array(32).fill(183));await unknownPlan.close(); + const unknownPlanState=await workspaceBytes(unknownPlanReceipt);const unknownPlanOpen=await openPlanReceipt(unknownPlanReceipt);await rejects(()=>unknownPlanOpen.plan_query(183),'recovery_required');await unknownPlanOpen.close();sameRows(await workspaceBytes(unknownPlanReceipt),unknownPlanState); + passed('actual T1 completion despite suppressed abort retains original unknown transaction and preserves partial state'); + const unknownPlanRead=await WorkspaceFixture.create(188),unknownPlanReadReceipt=receiptOf(unknownPlanRead,188); + const originalReadT0=Array.from(await unknownPlanRead.admit(188,false)),readPlanWire=await unknownPlanRead.new_plan(188),beforePlanRead=await workspaceBytes(unknownPlanReadReceipt);let planReadGets=0,planReadFallback; + try{planReadFallback=Array.from(await unknownPlanRead.bind_plan_read_unknown(188,readPlanWire,()=>{ + IDBObjectStore.prototype.get=function(...args){if(this.transaction.db.name===unknownPlanReadReceipt.namespace&&++planReadGets===2)throw new DOMException('synthetic retained-record read failure','InvalidStateError');return actualGet.apply(this,args);}; + IDBTransaction.prototype.abort=function(){if(this.db.name===unknownPlanReadReceipt.namespace)return;return actualAbort.call(this);}; + }));}finally{IDBObjectStore.prototype.get=actualGet;IDBTransaction.prototype.abort=actualAbort;} + same(planReadFallback.length,64);same(planReadFallback.slice(0,32),new Array(32).fill(188));await unknownPlanRead.close(); + const restoredRead=await openPlanReceipt(unknownPlanReadReceipt);same(Array.from(await restoredRead.query(188)),originalReadT0);same(Array.from(await restoredRead.plan_query(188)),[]);await restoredRead.close();sameRows(await workspaceBytes(unknownPlanReadReceipt),beforePlanRead); + passed('uncertain retained T1 input read preserves the original ID/digest without inventing a transaction or changing T0'); + for(const mode of ['bad_clock','expired_grant']){ + const n=mode==='bad_clock'?185:186,owner=await WorkspaceFixture.create(n),r=receiptOf(owner,n);await owner.admit(n,false);const wire=await owner.new_plan(n),before=await workspaceBytes(r); + await rejects(()=>mode==='bad_clock'?owner.bind_plan_bad_clock(n,wire):owner.bind_plan_expired_grant(n,wire),mode==='bad_clock'?'workspace_unavailable':'grant_expired');await owner.close();sameRows(await workspaceBytes(r),before); + const restored=await openPlanReceipt(r);same(Array.from(await restored.plan_query(n)),[]);await restored.close(); + } + passed('backwards clock and grant expiry after T1 crypto refuse with unchanged original state'); const workCall=message=>new Promise((resolve,reject)=>{const worker=new Worker('./worker.js',{type:'module'});worker.onmessage=e=>{if(e.data.ready){worker.postMessage(message);return;}worker.terminate();resolve(e.data);};worker.onerror=e=>{worker.terminate();reject(Error(e.message));};}); + same(await workCall({kind:'plan_query',...planReceipt}),{plan:originalPlan});passed('actual worker reopens and confirms the original protected complete T1'); same(await workCall({kind:'journal_query',...journalReceipt}),{preparation:originalPreparation});passed('actual worker reopens and queries the original protected preparation'); same(await workCall({kind:'workspace_open',...workspaceReceipt}),{error:'writer_active'}); - same(outbox.abandon_auths(9),8);for(let n=0;n<64;n++)outbox.abandon_close();await outbox.close(); + same(outbox.abandon_auths(2),1);for(let n=0;n<64;n++)outbox.abandon_close();await outbox.close(); await rejects(()=>outbox.authenticate(),'closed'); same(await workCall({kind:'workspace_open',...workspaceReceipt}),{revision:1}); passed('bounded owned authentication and cancelled close drain before actual cross-worker writer acquisition'); @@ -378,7 +458,7 @@ try { const workerCreated=await workerCall({kind:'persistent_create'}); same(await workerCall({kind:'persistent_open',...workerCreated}),{plain:[90,91,92]}); passed('persistent provider survives actual worker termination and new worker instance'); - return {tests,events:events.reduce((all,event)=>(all[event]=(all[event]??0)+1,all),{}),persistent:{fingerprint,encoded},workspace:workspaceReceipt,journal:{...journalReceipt,preparation:originalPreparation}}; + return {tests,events:events.reduce((all,event)=>(all[event]=(all[event]??0)+1,all),{}),persistent:{fingerprint,encoded},workspace:workspaceReceipt,journal:{...journalReceipt,preparation:originalPreparation},plan:{...planReceipt,originalPlan}}; } finally {IDBDatabase.prototype.transaction=nativeTransaction;} }); await page.reload(); @@ -394,6 +474,7 @@ try { assert.equal(workspaceRestart,1);result.tests.push('authenticated browser workspace survives actual page and WASM restart');delete result.workspace; const preparationRestart=await page.evaluate(async receipt=>{const {default:init,WorkspaceFixture}=await import('./fixture.js');await init();const owner=await WorkspaceFixture.open(receipt.n,new Uint8Array(receipt.fingerprint),new Uint8Array(receipt.selection),new Uint8Array(receipt.proof));const prepared=Array.from(await owner.query(65));await owner.close();return prepared;},result.journal); assert.deepEqual(preparationRestart,result.journal.preparation);result.tests.push('original protected operation survives actual page and WASM restart');delete result.journal; + const planRestart=await page.evaluate(async r=>{const {default:init,WorkspaceFixture}=await import('./fixture.js');await init();const owner=await WorkspaceFixture.open(r.n,new Uint8Array(r.fingerprint),new Uint8Array(r.selection),new Uint8Array(r.proof));const plan=Array.from(await owner.plan_query(180));await owner.close();return plan;},result.plan);assert.deepEqual(planRestart,result.plan.originalPlan);result.tests.push('complete original protected T1 survives actual page and WASM restart');delete result.plan; delete result.persistent; console.log(JSON.stringify({engine,version:browser.version(),...result})); } finally { diff --git a/crates/storage_indexeddb/tests/browser/src/workspace.rs b/crates/storage_indexeddb/tests/browser/src/workspace.rs @@ -1,4 +1,5 @@ //! Synthetic isolated host-effect fixture, never a production custody API. +mod plans; use futures::FutureExt; use radroots_domain::{ ActorRole, CommandContextData, Coverage, OperationId, PublicKey, UnixSeconds, WorkspaceId, @@ -387,11 +388,20 @@ impl WorkspaceFixture { let text = if changed { "changed".to_string() } else { - "\u{0001}".repeat(4096) + // T1 additionally constructs the bounded complete rumor, whose + // JSON framing must fit alongside the escaped text. Preserve the + // earlier T0-only maximum-input cases exactly. + "\u{0001}".repeat(if n >= 180 { 3000 } else { 4096 }) + }; + let peer = if n >= 180 { + PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5") + .unwrap() + } else { + participant() }; let wire = serde_json::to_vec( &serde_json::json!({"type":"inbox.inquire","context":context, - "input":{"thread_id":"66".repeat(32),"peer":participant(),"source":null,"text":text}}), + "input":{"thread_id":"66".repeat(32),"peer":peer,"source":null,"text":text}}), ) .unwrap(); AdmissionRequest::from_protected_wire(binding, &wire) diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/plans.rs b/crates/storage_indexeddb/tests/browser/src/workspace/plans.rs @@ -0,0 +1,259 @@ +//! Real synthetic peer/self NIP-44 and signed route inputs for T1 persistence. +use super::{WorkspaceFixture, copied}; +use futures::FutureExt; +use js_sys::Reflect; +use nostr::{ + JsonUtil, + nips::nip44, + prelude::rand::{CryptoRng, Error, RngCore}, +}; +use radroots_domain::{EnvelopeEventId, UnixSeconds}; +use radroots_protocol::chat::{CapturedDmRoute, ChatReplay, ChatRumor, ChatSeal, ChatSigningPlan}; +use radroots_storage::command::{BoundSigningPlan, PlanBindingOutcome}; +use radroots_storage::workspace::WorkspaceStore; +use wasm_bindgen::{JsCast, prelude::*}; + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(js_namespace = console, js_name = log)] + fn fixture_panic(message: &str); +} + +struct BrowserRng; +impl RngCore for BrowserRng { + fn next_u32(&mut self) -> u32 { + let mut bytes = [0; 4]; + self.fill_bytes(&mut bytes); + u32::from_le_bytes(bytes) + } + fn next_u64(&mut self) -> u64 { + let mut bytes = [0; 8]; + self.fill_bytes(&mut bytes); + u64::from_le_bytes(bytes) + } + fn fill_bytes(&mut self, bytes: &mut [u8]) { + Reflect::get(&js_sys::global(), &JsValue::from_str("crypto")) + .unwrap() + .dyn_into::<web_sys::Crypto>() + .unwrap() + .get_random_values_with_u8_array(bytes) + .unwrap(); + } + fn try_fill_bytes(&mut self, bytes: &mut [u8]) -> Result<(), Error> { + self.fill_bytes(bytes); + Ok(()) + } +} +impl CryptoRng for BrowserRng {} +fn summary(bound: BoundSigningPlan) -> Vec<u8> { + let mut bytes = bound.transaction_id().as_bytes().to_vec(); + bytes.extend_from_slice(bound.plan().digest()); + bytes.extend_from_slice(&bound.bound_at().get().to_be_bytes()); + bytes.extend_from_slice(&(bound.plan().protected_wire().len() as u32).to_be_bytes()); + bytes.extend_from_slice(bound.prepared().transaction_id().as_bytes()); + bytes +} +#[wasm_bindgen] +impl WorkspaceFixture { + pub async fn new_plan(&self, n: u8) -> Result<Vec<u8>, JsValue> { + std::panic::set_hook(Box::new(|info| fixture_panic(&format!("{info}")))); + let request = self.request(n, false).await?; + let command = request.command(); + let time = UnixSeconds::new(1000).unwrap(); + let rumor = ChatRumor::from_command(command, time).unwrap(); + let context = nostr::secp256k1::Secp256k1::new(); + let mut scalar = [0; 32]; + scalar[31] = 1; + let sender = + nostr::Keys::new_with_ctx(&context, nostr::SecretKey::from_slice(&scalar).unwrap()); + let mut seals = Vec::new(); + let mut routes = Vec::new(); + let mut rng = BrowserRng; + for recipient in rumor.recipients() { + let public = nostr::PublicKey::from_slice(recipient.as_bytes()).unwrap(); + let encrypted = nip44::encrypt_with_rng( + &mut rng, + sender.secret_key(), + &public, + rumor.json(), + nip44::Version::V2, + ) + .unwrap(); + scalar[31] = if *recipient == super::participant() { + 1 + } else { + 2 + }; + let receiver = + nostr::Keys::new_with_ctx(&context, nostr::SecretKey::from_slice(&scalar).unwrap()); + assert_eq!(receiver.public_key(), public); + assert_eq!( + nip44::decrypt(receiver.secret_key(), &sender.public_key(), &encrypted).unwrap(), + rumor.json() + ); + seals.push( + ChatSeal::new( + &rumor, + *recipient, + UnixSeconds::new(999).unwrap(), + &encrypted, + ) + .unwrap(), + ); + let relay = "wss://plan.fixture.example/"; + let source = nostr::UnsignedEvent { + id: None, + pubkey: public, + created_at: nostr::Timestamp::from_secs(999), + kind: nostr::Kind::Custom(10050), + tags: nostr::Tags::from_list(vec![nostr::Tag::parse(["relay", relay]).unwrap()]), + content: "synthetic public route metadata ".repeat(1000), + } + .sign_with_ctx(&context, &mut rng, &receiver) + .unwrap(); + source.verify_with_ctx(&context).unwrap(); + routes.push( + CapturedDmRoute::from_observed_descriptor( + *recipient, + EnvelopeEventId::from_bytes(*source.id.as_bytes()), + &source.as_json(), + &[relay.into()], + ) + .unwrap(), + ); + } + Ok( + ChatSigningPlan::new(command, time, seals, routes, ChatReplay::NonReplayable) + .unwrap() + .protected_wire() + .to_vec(), + ) + } + pub async fn bind_plan(&self, n: u8, wire: Vec<u8>) -> Result<Vec<u8>, JsValue> { + self.bind_plan_mode(n, wire, 0).await + } + pub async fn bind_plan_read_unknown( + &self, + n: u8, + wire: Vec<u8>, + hook: js_sys::Function, + ) -> Result<Vec<u8>, JsValue> { + let request = self.request(n, false).await?; + let plan = ChatSigningPlan::parse(request.command(), &wire).unwrap(); + hook.call0(&JsValue::NULL)?; + match self + .owner + .bind_signing_intents(request.binding().clone(), plan, copied(&self.proof)) + .await + .map_err(|e| JsValue::from_str(e.code()))? + { + PlanBindingOutcome::Committed(_) => Err(JsValue::from_str("unexpected_commit")), + PlanBindingOutcome::Unknown(anchor) => { + assert_eq!(anchor.workspace_id(), self.input.workspace_id()); + assert_eq!( + anchor.operation_id(), + request.command().context().operation_id() + ); + assert_eq!(anchor.command_digest(), request.command().digest()); + assert_eq!(anchor.transaction_id(), None); + let mut bytes = anchor.operation_id().as_bytes().to_vec(); + bytes.extend_from_slice(anchor.command_digest().as_bytes()); + Ok(bytes) + } + } + } + pub async fn bind_plan_foreign(&self, n: u8, wire: Vec<u8>) -> Result<(), JsValue> { + let request = self.request(n, false).await?; + let plan = ChatSigningPlan::parse(request.command(), &wire).unwrap(); + let sibling = self.sibling().await?; + let foreign = sibling + .owner + .authenticate(sibling.input.clone(), copied(&sibling.proof)) + .await + .map_err(super::fail)?; + let result = self + .owner + .bind_signing_intents(foreign, plan, copied(&self.proof)) + .await; + sibling.close().await?; + result.map(|_| ()).map_err(|e| JsValue::from_str(e.code())) + } + pub async fn bind_plan_expiring(&self, n: u8, wire: Vec<u8>) -> Result<Vec<u8>, JsValue> { + self.bind_plan_mode(n, wire, 1).await + } + pub async fn bind_plan_unknown(&self, n: u8, wire: Vec<u8>) -> Result<Vec<u8>, JsValue> { + self.bind_plan_mode(n, wire, 2).await + } + pub async fn bind_plan_bad_clock(&self, n: u8, wire: Vec<u8>) -> Result<Vec<u8>, JsValue> { + self.bind_plan_mode(n, wire, 3).await + } + pub async fn bind_plan_expired_grant(&self, n: u8, wire: Vec<u8>) -> Result<Vec<u8>, JsValue> { + self.bind_plan_mode(n, wire, 4).await + } + pub async fn abandon_plan(&self, n: u8, wire: Vec<u8>) -> Result<(), JsValue> { + let request = self.request(n, false).await?; + let plan = ChatSigningPlan::parse(request.command(), &wire).unwrap(); + if self + .owner + .bind_signing_intents(request.binding().clone(), plan, copied(&self.proof)) + .now_or_never() + .is_some() + { + return Err(JsValue::from_str("unexpected_immediate_plan")); + } + Ok(()) + } + pub async fn plan_query(&self, n: u8) -> Result<Vec<u8>, JsValue> { + let request = self.request(n, false).await?; + self.owner + .query_signing_intents( + request.binding().clone(), + request.command().context().operation_id(), + request.command().digest(), + copied(&self.proof), + ) + .await + .map(|bound| bound.map(summary).unwrap_or_default()) + .map_err(|e| JsValue::from_str(e.code())) + } +} +impl WorkspaceFixture { + async fn bind_plan_mode(&self, n: u8, wire: Vec<u8>, mode: u8) -> Result<Vec<u8>, JsValue> { + let request = self.request(n, false).await?; + let plan = ChatSigningPlan::parse(request.command(), &wire) + .map_err(|_| JsValue::from_str("invalid_plan"))?; + if mode == 1 { + self.clock.after.set(Some(1500)); + } + if mode == 2 { + self.clock.countdown.set(Some((8, 1500))); + } + if mode == 3 { + self.clock.after.set(Some(90)); + } + if mode == 4 { + self.clock.after.set(Some(2000)); + } + let outcome = self + .owner + .bind_signing_intents(request.binding().clone(), plan, copied(&self.proof)) + .await + .map_err(|e| JsValue::from_str(e.code()))?; + match outcome { + PlanBindingOutcome::Committed(bound) => Ok(summary(bound)), + PlanBindingOutcome::Unknown(anchor) => { + if mode != 2 { + return Err(JsValue::from_str("commit_unknown")); + } + assert_eq!( + anchor.operation_id(), + request.command().context().operation_id() + ); + assert_eq!(anchor.command_digest(), request.command().digest()); + let mut bytes = anchor.operation_id().as_bytes().to_vec(); + bytes.extend_from_slice(anchor.transaction_id().unwrap().as_bytes()); + Ok(bytes) + } + } + } +} diff --git a/crates/storage_sqlite/src/workspace/admission.rs b/crates/storage_sqlite/src/workspace/admission.rs @@ -187,7 +187,7 @@ impl Journal<'_> { .begin_with("BEGIN IMMEDIATE") .await .map_err(|_| OperationError::StorageFailure)?; - let checked = async { + let checked: Result<(), OperationError> = async { recheck( &mut transaction, self.namespace, @@ -208,17 +208,7 @@ impl Journal<'_> { ) .await?; } else { - let count: i64 = sqlx::query_scalar( - "SELECT (SELECT count(*) FROM operations WHERE workspace=?1 AND operation_id=?2)+(SELECT count(*) FROM signing_plans WHERE workspace=?1 AND operation_id=?2)+(SELECT count(*) FROM signing_plan_parts WHERE workspace=?1 AND operation_id=?2)", - ) - .bind(self.selected.workspace_id().as_bytes().as_slice()) - .bind(operation_id.as_bytes().as_slice()) - .fetch_one(&mut *transaction) - .await - .map_err(|_| OperationError::RecoveryRequired)?; - if count != 0 { - return Err(OperationError::RecoveryRequired); - } + operation::absent(&mut transaction, self.selected, operation_id).await?; } Ok(()) } @@ -257,7 +247,7 @@ impl Journal<'_> { .begin_with("BEGIN IMMEDIATE") .await .map_err(|_| OperationError::StorageFailure)?; - let checked = async { + let checked: Result<(), OperationError> = async { recheck( &mut transaction, self.namespace, @@ -322,6 +312,7 @@ impl Journal<'_> { { return Err(OperationError::DeadlineExceeded); } + operation::absent(&mut transaction, self.selected, operation_id).await?; operation::insert(&mut transaction, &request, transaction_id, &protected).await } .await; @@ -364,7 +355,7 @@ impl Journal<'_> { .begin_with("BEGIN IMMEDIATE") .await .map_err(|_| OperationError::StorageFailure)?; - let checked = async { + let checked: Result<(), OperationError> = async { recheck( &mut transaction, self.namespace, @@ -379,17 +370,7 @@ impl Journal<'_> { if let Some((snapshot, protected)) = &result { operation::unchanged(&mut transaction, snapshot, protected).await?; } else { - let count: i64 = sqlx::query_scalar( - "SELECT count(*) FROM operations WHERE workspace=? AND operation_id=?", - ) - .bind(self.selected.workspace_id().as_bytes().as_slice()) - .bind(operation_id.as_bytes().as_slice()) - .fetch_one(&mut *transaction) - .await - .map_err(|_| OperationError::RecoveryRequired)?; - if count != 0 { - return Err(OperationError::RecoveryRequired); - } + operation::absent(&mut transaction, self.selected, operation_id).await?; } Ok(()) } diff --git a/crates/storage_sqlite/src/workspace/operation.rs b/crates/storage_sqlite/src/workspace/operation.rs @@ -35,6 +35,7 @@ pub(super) async fn read( .bind(selected.workspace_id().as_bytes().as_slice()).bind(operation_id.as_bytes().as_slice()) .fetch_optional(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?; let Some(row) = row else { + absent(connection, selected, operation_id).await?; return Ok(None); }; let bytes = |index| -> Result<Vec<u8>, OperationError> { @@ -118,3 +119,21 @@ pub(super) async fn unchanged( } pub(super) use radroots_storage::command::protected::check_digest; + +/// Confirms complete original-ID absence before a new preparation or absent +/// lookup. Every current operation-owned table has an indexed workspace/ID +/// prefix. EXISTS never materializes an unbounded retained record set. +pub(super) async fn absent( + connection: &mut SqliteConnection, + selected: &AttachmentInput, + operation: OperationId, +) -> Result<(), OperationError> { + let retained: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM operations WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM signing_plans WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM signing_plan_parts WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM signing_attempts WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM seal_evidence WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM seal_evidence_parts WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM chat_messages WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM chat_publication_work WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM chat_delivery_attempts WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM chat_delivery_parts WHERE workspace=?1 AND operation_id=?2) OR EXISTS(SELECT 1 FROM chat_delivery_observations WHERE workspace=?1 AND operation_id=?2)") + .bind(selected.workspace_id().as_bytes().as_slice()) + .bind(operation.as_bytes().as_slice()) + .fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if retained { + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} diff --git a/crates/storage_sqlite/src/workspace/plan.rs b/crates/storage_sqlite/src/workspace/plan.rs @@ -3,31 +3,15 @@ use super::{ AttachmentInput, crypto::{PRIVATE_PAYLOAD_MAX_BYTES, WorkspaceCrypto}, }; -use radroots_domain::{CommandDigest, OperationId, TransactionId, UnixSeconds}; -use radroots_storage::command::{ - BoundSigningPlan, ChatSigningPlan, OperationError, PreparedOperation, -}; -use serde::{Deserialize, Serialize}; +use radroots_domain::{TransactionId, UnixSeconds}; +use radroots_storage::command::protected::plan::PlanManifest; +use radroots_storage::command::{ChatSigningPlan, OperationError, PreparedOperation}; use sqlx::{Row, SqliteConnection}; use zeroize::Zeroizing; pub(super) const TABLE: &str = "CREATE TABLE signing_plans (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, plan_digest BLOB NOT NULL CHECK(length(plan_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), part_count INTEGER NOT NULL CHECK(part_count BETWEEN 1 AND 24), byte_count INTEGER NOT NULL CHECK(byte_count BETWEEN 1 AND 393216), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id), FOREIGN KEY(workspace,operation_id) REFERENCES operations(workspace,operation_id)) STRICT, WITHOUT ROWID"; pub(super) const PARTS: &str = "CREATE TABLE signing_plan_parts (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, part INTEGER NOT NULL CHECK(part BETWEEN 1 AND 24), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id,part), FOREIGN KEY(workspace,operation_id) REFERENCES signing_plans(workspace,operation_id)) STRICT, WITHOUT ROWID"; const MAX_PROTECTED_TOTAL: usize = 2 * 1024 * 1024; -#[derive(Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct Manifest { - version: u8, - workspace: radroots_domain::WorkspaceId, - operation_id: OperationId, - command_digest: CommandDigest, - preparation_transaction: TransactionId, - plan_digest: CommandDigest, - transaction_id: TransactionId, - bound_at: UnixSeconds, - part_count: usize, - byte_count: usize, -} pub(super) struct ProtectedPlan { pub digest: [u8; 32], pub transaction: TransactionId, @@ -44,20 +28,8 @@ pub(super) async fn protect( ) -> Result<ProtectedPlan, OperationError> { let anchor = prepared.identity(); let chunks = plan.protected_wire().chunks(PRIVATE_PAYLOAD_MAX_BYTES); - let manifest = Manifest { - version: 1, - workspace: anchor.workspace_id(), - operation_id: anchor.operation_id(), - command_digest: anchor.command_digest(), - preparation_transaction: prepared.transaction_id(), - plan_digest: CommandDigest::from_bytes(*plan.digest()), - transaction_id: transaction, - bound_at, - part_count: chunks.len(), - byte_count: plan.protected_wire().len(), - }; - let plaintext = - Zeroizing::new(serde_json::to_vec(&manifest).map_err(|_| OperationError::InvalidCommand)?); + let manifest = PlanManifest::capture(prepared, plan, transaction, bound_at)?; + let plaintext = manifest.encode()?; let protected = crypto .seal_plan_part( anchor.workspace_id(), @@ -90,7 +62,7 @@ pub(super) async fn protect( transaction, manifest: protected, parts, - bytes: manifest.byte_count, + bytes: manifest.byte_count(), }) } @@ -153,18 +125,11 @@ pub(super) async fn read( &manifest, ) .await?; - let decoded: Manifest = decoded - .expose_secret(|bytes| serde_json::from_slice(bytes)) - .map_err(|_| OperationError::RecoveryRequired)?; - if decoded.version != 1 - || decoded.workspace != selected.workspace_id() - || decoded.operation_id != anchor.operation_id() - || decoded.command_digest != anchor.command_digest() - || decoded.preparation_transaction != prepared.transaction_id() - || decoded.plan_digest.as_bytes() != &digest - || decoded.transaction_id != transaction - || decoded.part_count != part_count as usize - || decoded.byte_count != byte_count as usize + let decoded = decoded.expose_secret(|bytes| PlanManifest::decode(bytes, &prepared))?; + if decoded.plan_digest().as_bytes() != &digest + || decoded.transaction_id() != transaction + || decoded.part_count() != part_count as usize + || decoded.byte_count() != byte_count as usize { return Err(OperationError::RecoveryRequired); } @@ -228,13 +193,10 @@ pub(super) async fn read( bytes: byte_count as usize, }; // Validate the original T1 observation before returning even to internal callers. - let bound = - BoundSigningPlan::from_committed_store(prepared, plan, transaction, decoded.bound_at)?; + let bound_at = decoded.bound_at(); + let bound = decoded.bind(prepared, plan)?; let (prepared, plan) = bound.into_parts(); - Ok(( - prepared, - Some((plan, transaction, decoded.bound_at, protected)), - )) + Ok((prepared, Some((plan, transaction, bound_at, protected)))) } pub(super) async fn insert( diff --git a/crates/storage_sqlite/src/workspace/tests/plan_records.rs b/crates/storage_sqlite/src/workspace/tests/plan_records.rs @@ -404,5 +404,95 @@ async fn authenticated_plan_manifest_parts_and_transaction_comparisons_refuse_ea .await .is_err() ); + // A missing T0 must not become absence or a replacement operation while + // any original protected plan part remains. This is corrupted retained + // state, even when the SQL schema itself still passes quick_check. + let retained_command = prepared.request().command().protected_wire().to_vec(); + sqlx::query("DELETE FROM operations") + .execute(&mut database) + .await + .unwrap(); + let orphaned: Vec<Vec<u8>> = + sqlx::query_scalar("SELECT protected FROM signing_plan_parts ORDER BY part") + .fetch_all(&mut database) + .await + .unwrap(); + assert!(!orphaned.is_empty()); database.close().await.unwrap(); + let reopened = NativeWorkspace::open_existing(&path, selected.clone(), fixture.crypto(), clock) + .await + .unwrap(); + let binding = reopened + .authenticate(selected.clone(), &proof) + .await + .unwrap(); + // Absence is operation-scoped: unrelated retained orphan parts must not + // turn a genuinely unknown ID into an error or create a replacement. + assert!( + reopened + .signing_plan( + binding.clone(), + OperationId::from_bytes([52; 32]), + radroots_domain::CommandDigest::from_bytes([0; 32]), + copied(), + ) + .await + .unwrap() + .is_none() + ); + assert!(matches!( + reopened + .signing_plan( + binding.clone(), + operation_id, + prepared.identity().command_digest(), + copied(), + ) + .await, + Err(radroots_storage::command::OperationError::RecoveryRequired) + )); + let lookup = reopened + .operation(binding.clone(), operation_id, None, copied()) + .await; + let admission = reopened + .admit_command_and_hold( + AdmissionRequest::from_protected_wire(binding, &retained_command).unwrap(), + copied(), + ) + .await; + reopened.close().await.unwrap(); + assert!( + matches!( + lookup, + Err(radroots_storage::command::OperationError::RecoveryRequired) + ), + "orphan lookup must refuse, not report absence" + ); + assert!( + matches!( + admission, + Err(radroots_storage::command::OperationError::RecoveryRequired) + ), + "orphan state must not acquire a replacement preparation" + ); + let mut unchanged = SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(path.join("execution_v1.sqlite")) + .create_if_missing(false) + .read_only(true), + ) + .await + .unwrap(); + let still_retained: Vec<Vec<u8>> = + sqlx::query_scalar("SELECT protected FROM signing_plan_parts ORDER BY part") + .fetch_all(&mut unchanged) + .await + .unwrap(); + assert_eq!(orphaned, still_retained); + let operations: i64 = sqlx::query_scalar("SELECT count(*) FROM operations") + .fetch_one(&mut unchanged) + .await + .unwrap(); + assert_eq!(operations, 0); + unchanged.close().await.unwrap(); }