commit 9cbae6a094ba50de951e0de28e5ed974829ff3e4 parent ef602f3f8040cd224c09de10d0d2f2159161461e Author: triesap <tyson@radroots.org> Date: Wed, 21 Oct 2026 04:42:43 +0000 browser: execute retained public listings through IndexedDB - Delegate ordinary publication to the shared command and lifecycle owner - Retain atomic coordinates and typed public signing and delivery evidence - Preserve private records and avoid redundant buyer preparation work - Verify three-browser replay, late capture, corruption and resource closure Diffstat:
29 files changed, 1330 insertions(+), 231 deletions(-)
diff --git a/contracts/architecture/decisions/browser_workspace.v2.json b/contracts/architecture/decisions/browser_workspace.v2.json @@ -9,7 +9,7 @@ "native_policy_consumer": "radroots_storage_sqlite::workspace", "shared_grant_wire_private": true, "default_import_side_effects": false, - "scope": "fresh_unrelated_buyer_outbox", + "scope": "fresh_unrelated_buyer_or_seller_outbox", "stock_authority": false, "participant_key_is_workspace_proof": false, "storage": { @@ -148,7 +148,9 @@ "publication_work", "delivery_frame", "delivery_observation", - "delivery_request_index" + "delivery_request_index", + "listing_installation", + "public_publication_work" ], "reserved_not_yet_implemented_families": [] }, @@ -271,5 +273,37 @@ "failed_recovery_keeps_uncertainty_and_writer": true, "accepted_recovery_survives_lost_observer": true, "final_close_drains_recovery_before_writer_release": true + }, + "public_listing": { + "state": "implemented_under_current_component_qualification", + "stock_authority": false, + "shared_checked_models": [ + "CapturedListingCommand", + "PublicSigningPlan", + "SigningTarget::PublicEvent", + "ListingInstallation", + "PublicPublicationWork", + "OperationSnapshot" + ], + "initial_coordinate": "atomic_T0_protected_author_listing_index_outside_operation_prefix", + "coordinate_existing_decision_and_original_preparation_verified": true, + "coordinate_compared_with_every_later_write": true, + "coordinate_replacement_or_expiry_reclamation": false, + "private_contexts_and_record_bytes_unchanged": true, + "public_issuance_target_position": 2, + "public_issuance_context_domain": "radroots.browser.local_outbox.public_issuance.context.v1", + "public_installation_and_work_families": [ + 10, + 11 + ], + "installation_metadata_clear_bytes": 76, + "work_metadata_clear_bytes": 76, + "public_delivery_frame_version": 3, + "private_delivery_frame_version": 2, + "public_delivery_uses_original_signed_bytes_without_wrapping": true, + "public_recipient": null, + "actual_page_worker_and_three_browser_execution_required": true, + "protected_corruption_reopen_and_private_regressions_required": true, + "full_browser_distribution_or_RCLD_qualification_claim": false } } diff --git a/crates/radroots_browser/Cargo.toml b/crates/radroots_browser/Cargo.toml @@ -31,7 +31,7 @@ radroots_storage_indexeddb = { workspace = true, features = ["workspace"] } radroots_transport_nostr_browser = { workspace = true } radroots_transport_nostr = { workspace = true } radroots_nostr = { workspace = true, features = ["signing", "nip17"] } -radroots_protocol = { workspace = true, features = ["chat"] } +radroots_protocol = { workspace = true, features = ["chat", "listing"] } radroots_secrets = { workspace = true, features = ["browser"] } js-sys = { workspace = true } wasm-bindgen = { workspace = true } diff --git a/crates/radroots_browser/README.md b/crates/radroots_browser/README.md @@ -6,6 +6,12 @@ signing and workspace attachment remain explicit. Opening existing state never creates missing keys, grants or records. Startup performs no automatic query, publication or outbox replay. Preview memory does not qualify protected work. +`listings().publish` delegates initial public listings to the same retained +command owner as private inquiry. It requires an authenticated seller outbox +and uses configured public write targets. Public results remain typed Listings; +they acquire no private recipient, wrapping or stock authority. Scoped operation +reads and explicit retry retain original signing and publication evidence. + Accepted commands belong to a bounded local Rust task owner independently of their observation futures. Close permanently stops admission, drains original obtained evidence, disconnects the shared session, disposes original socket and diff --git a/crates/radroots_browser/src/client.rs b/crates/radroots_browser/src/client.rs @@ -257,6 +257,10 @@ impl Client { pub const fn inbox(&self) -> Inbox<'_> { Inbox { client: self } } + /// Borrows initial public listing execution through the same shared owner. + pub const fn listings(&self) -> Listings<'_> { + Listings { client: self } + } /// Selects an explicitly authenticated scope for retained operation reads. pub fn operations(&self, scope: &WorkspaceSession) -> Operations<'_> { Operations { @@ -294,6 +298,25 @@ impl Inbox<'_> { .await } } +/// Public listing access through the actual protected browser journal. +pub struct Listings<'a> { + client: &'a Client, +} +impl Listings<'_> { + /// Captures initial publication under an authenticated seller attachment. + /// Shared execution owns signing, installation, delivery and retained work; + /// losing this observer never grants rollback or automatic redispatch. + pub async fn publish( + &self, + context: CommandContext, + input: radroots_protocol::listing::PublishInput, + ) -> Result<OperationReceipt<radroots_domain::listing::Listing>> { + self.client + .session + .publish_listing(self.client.workspace.clone(), context, input) + .await + } +} /// Authenticated original-operation reads and explicit delivery resumption. pub struct Operations<'a> { client: &'a Client, diff --git a/crates/radroots_browser/src/commands.rs b/crates/radroots_browser/src/commands.rs @@ -98,6 +98,12 @@ impl CommandIo for BrowserCommands { fn now(&self) -> Result<UnixSeconds, OperationError> { unix_seconds() } + fn public_targets(&self) -> Result<TargetSet, OperationError> { + if !self.enabled() { + return Err(OperationError::Unauthorized); + } + Ok(self.write.clone()) + } fn seal_time(&self, now: UnixSeconds) -> Result<UnixSeconds, OperationError> { let time = randomized_past_time( NonZeroU64::new(now.get()).ok_or(OperationError::RecoveryRequired)?, diff --git a/crates/radroots_browser/src/lib.rs b/crates/radroots_browser/src/lib.rs @@ -13,7 +13,7 @@ mod clock; mod commands; #[cfg(target_arch = "wasm32")] -pub use client::{BrowserConfig, Client, CloseReceipt, Inbox, Operations}; +pub use client::{BrowserConfig, Client, CloseReceipt, Inbox, Listings, Operations}; #[cfg(target_arch = "wasm32")] pub use commands::BrowserNonceSource; pub use radroots_domain::{CommandDigest, OperationId}; diff --git a/crates/radroots_browser/tests/browser/Cargo.lock b/crates/radroots_browser/tests/browser/Cargo.lock @@ -1371,6 +1371,7 @@ dependencies = [ "radroots_domain", "radroots_execution", "radroots_nostr", + "radroots_protocol", "radroots_secrets", "radroots_signing", "radroots_storage", diff --git a/crates/radroots_browser/tests/browser/Cargo.toml b/crates/radroots_browser/tests/browser/Cargo.toml @@ -15,6 +15,7 @@ radroots_browser = { path = "../..", features = ["artifact_clock"] } radroots_domain = { path = "../../../domain", default-features = false, features = ["std"] } radroots_execution = { path = "../../../execution", default-features = false, features = ["workspace_session"] } radroots_nostr = { path = "../../../nostr", default-features = false, features = ["signing", "nip17"] } +radroots_protocol = { path = "../../../protocol", default-features = false, features = ["listing"] } radroots_secrets = { path = "../../../secrets", default-features = false, features = ["browser"] } radroots_signing = { path = "../../../signing", default-features = false, features = ["chat", "std"] } radroots_storage = { path = "../../../storage", default-features = false, features = ["protected_outbox"] } diff --git a/crates/radroots_browser/tests/browser/run.mjs b/crates/radroots_browser/tests/browser/run.mjs @@ -34,13 +34,18 @@ async function verifyCleanup(){ return {sockets:observedSockets.length,databases:databases.length}; }`; const execute=` -const {default:init,advertisements,verify_client,verify_publications}=await import('./fixture.js');await init(); +const {default:init,advertisements,verify_client,verify_publications,verify_listing,verify_listing_publications}=await import('./fixture.js');await init(); const route='/'+context,endpoint=base.replace('http:','ws:')+route; const response=await fetch(base+'/advertisements'+route,{method:'POST',body:advertisements(endpoint)}); if(!response.ok)throw Error('fixture advertisement setup'); const result=JSON.parse(await verify_client(endpoint,'ordinary_browser_'+context)); const events=await fetch(base+'/events'+route).then(response=>response.text()); await verify_publications(events,JSON.stringify(result.messages)); +const publicRoute='/listing/'+context; +const listing=JSON.parse(await verify_listing(base.replace('http:','ws:')+publicRoute,'ordinary_public_'+context)); +const publicEvents=await fetch(base+'/events'+publicRoute).then(response=>response.text()); +verify_listing_publications(publicEvents,listing.revision); +result.listing=listing; result.disposed=await verifyCleanup();return result;`; const worker=`${observer} self.onmessage=async event=>{try{const base=event.data,context='worker';self.postMessage(await(async()=>{${execute}})());} @@ -55,7 +60,7 @@ const server=createServer(async(req,res)=>{ for(const value of values)assert.equal(value.kind,10050); sources.set(req.url.replace('/advertisements',''),values);res.end('ok');return; } - if(req.url==='/events/main'||req.url==='/events/worker'){ + if(['/events/main','/events/worker','/events/listing/main','/events/listing/worker'].includes(req.url)){ const route=req.url.replace('/events','');res.setHeader('content-type','application/json'); res.end(JSON.stringify(observed.filter(item=>item.route===route&&item.message[0]==='EVENT').map(item=>item.rawEvent)));return; } @@ -66,18 +71,22 @@ const server=createServer(async(req,res)=>{ }); server.on('connection',socket=>{sockets.add(socket);socket.on('close',()=>sockets.delete(socket));}); server.on('upgrade',(req,socket,head)=>{ - assert(sources.has(req.url));upgrades.push(req.url); + const publicRoute=['/listing/main','/listing/worker'].includes(req.url); + assert(publicRoute||sources.has(req.url));upgrades.push(req.url); wss.handleUpgrade(req,socket,head,ws=>{ ws.on('error',()=>{}); ws.on('message',(data,binary)=>{ assert(!binary);const raw=data.toString(),message=JSON.parse(raw); observed.push({route:req.url,message,rawEvent:message[0]==='EVENT'?raw.slice('["EVENT",'.length,-1):undefined}); if(message[0]==='REQ'){ + assert(!publicRoute,'public listing must not query a private route'); assert.equal(message[2].kinds[0],10050);assert.equal(message[2].authors.length,1); for(const value of sources.get(req.url))if(value.pubkey===message[2].authors[0])ws.send(JSON.stringify(['EVENT',message[1],value])); ws.send(JSON.stringify(['EOSE',message[1]])); }else if(message[0]==='EVENT'){ - assert.equal(message[1].kind,1059);ws.send(JSON.stringify(['OK',message[1].id,true,''])); + assert.equal(message[1].kind,publicRoute?30402:1059); + const firstPublic=publicRoute&&observed.filter(item=>item.route===req.url&&item.message[0]==='EVENT').length===1; + ws.send(JSON.stringify(['OK',message[1].id,!firstPublic,firstPublic?'blocked: measured loopback rejection':''])); }else assert.equal(message[0],'CLOSE'); }); }); @@ -99,10 +108,14 @@ try{ worker.onmessage=event=>{worker.terminate();event.data.error?reject(Error(event.data.error)):resolve(event.data);};worker.postMessage(base); }),base); assert.equal(main.passed.length,7);assert.deepEqual(main.passed,dedicated.passed);assert.deepEqual(errors,[]); + assert.equal(main.listing.passed.length,4);assert.deepEqual(main.listing.passed,dedicated.listing.passed); for(const context of ['main','worker']){ const publications=observed.filter(item=>item.route==='/'+context&&item.message[0]==='EVENT'); assert.equal(publications.length,4);assert.equal(new Set(publications.map(item=>item.message[1].id)).size,4); assert.equal(upgrades.filter(route=>route==='/'+context).length,2); + const publicEvents=observed.filter(item=>item.route==='/listing/'+context&&item.message[0]==='EVENT'); + assert.equal(publicEvents.length,2);assert.equal(publicEvents[0].rawEvent,publicEvents[1].rawEvent); + assert.equal(upgrades.filter(route=>route==='/listing/'+context).length,2); } console.log(JSON.stringify({engine,automation,version:browser.version(),main,dedicated,pageErrors:errors,upgrades,observed})); }finally{ diff --git a/crates/radroots_browser/tests/browser/src/lib.rs b/crates/radroots_browser/tests/browser/src/lib.rs @@ -123,6 +123,9 @@ struct Existing { } impl Existing { async fn create(label: &str) -> Result<Self, JsValue> { + Self::create_scope(label, false).await + } + async fn create_scope(label: &str, seller: bool) -> Result<Self, JsValue> { let namespace = SecretId::parse(label).unwrap(); let reference = SecretRef::new( SecretId::parse("ordinary_browser_workspace").unwrap(), @@ -135,8 +138,13 @@ impl Existing { .map_err(fail)?, ); let fingerprint = provider.fingerprint(); + let constructor = if seller { + LocalOutboxConfig::seller + } else { + LocalOutboxConfig::new + }; let (workspace, input, proof) = BrowserWorkspace::initialize_local_outbox( - LocalOutboxConfig::new( + constructor( participant(1), participant(3), "isolated-browser-fixture", @@ -423,3 +431,193 @@ pub async fn verify_publications(raw_events: String, expected: String) -> Result "each original rumor has independent self and peer delivery", ) } + +fn listing() -> radroots_protocol::listing::PublishInput { + let value = serde_json::json!({ + "id":"01".repeat(16),"title":" Browser carrots 🥕 ","summary":"Quote required", + "description_markdown":"Exact public terms","published_at":now().to_string(), + "profile":{"profile":"radroots.listing","version":1,"state":"active", + "product":{"name":"Carrots","description":"Fresh carrots","producer":null,"origin_summary":null}, + "default_option":"02".repeat(32), + "options":[{"id":"02".repeat(32),"label":"Bunch","unit":{"type":"package","label":"bunch","contents":{"type":"unspecified"}}, + "increment":"1","minimum":"1","price":{"type":"quote_required"},"supply":{"type":"available","amount":"10"},"lead_seconds":"0"}], + "fulfillment":{"modes":["pickup"],"area":"Example","lead_seconds":"0"},"authority":null,"media":[]}}); + radroots_protocol::listing::PublishInput::parse(&serde_json::to_vec(&value).unwrap()).unwrap() +} + +#[wasm_bindgen] +pub async fn verify_listing(base: String, label: String) -> Result<String, JsValue> { + use radroots_execution::{BusinessInstallation, Issuance, OperationKind, TargetObservation}; + let mut passed = Vec::new(); + let existing = Existing::create_scope(&label, true).await?; + let (client, scope) = existing.open(&base).await?; + let callbacks = signer(&client).await?; + client.start(StartMode::Online).await.map_err(fail)?; + let sockets = socket_count(); + let operation = id(); + let input = listing(); + let deadline = now() + 120; + let original = client + .listings() + .publish(context(&scope, operation, deadline), input.clone()) + .await + .map_err(fail)?; + require( + original.kind() == OperationKind::Listing + && original.durable() + && original.business_installation() == BusinessInstallation::Installed + && original.issuance() == Issuance::Obtained, + "actual installed public receipt", + )?; + let value = original + .business_result() + .ok_or_else(|| JsValue::from_str("missing public result"))?; + require( + value.text().title() == " Browser carrots 🥕 " + && original.message_id().is_none() + && original.artifacts().iter().all(|v| v.recipient().is_none()), + "typed public result without private placeholders", + )?; + require( + original.delivery_observations().len() == 1 + && original.delivery_observations()[0].outcome() == TargetObservation::Rejected, + "actual original relay rejection", + )?; + let revision = value.revision().to_string(); + let digest = original.command_digest(); + let checkpoint = original.operation_checkpoint(); + let replay = client + .listings() + .publish(context(&scope, operation, deadline), input.clone()) + .await + .map_err(fail)?; + require( + replay.operation_checkpoint() == checkpoint, + "replay retains original receipt", + )?; + require( + socket_count() == sockets + 1, + "public listing uses only configured publication socket", + )?; + passed.push("public shared T0 T1 S T2 and actual rejected D, typed Listing and exact replay"); + client.close().await.map_err(fail)?; + require( + callbacks.closed.get() == 1, + "original public signer callbacks close once", + )?; + let (reopened, scope) = existing.open(&base).await?; + let callbacks = signer(&reopened).await?; + reopened.start(StartMode::Online).await.map_err(fail)?; + let sockets = socket_count(); + let queried = reopened + .operations(&scope) + .get_matching(operation, Some(digest)) + .await + .map_err(fail)? + .ok_or_else(|| JsValue::from_str("missing original public operation"))?; + require( + queried.operation_checkpoint() == checkpoint && socket_count() == sockets, + "public open/start/query cannot redispatch", + )?; + require( + queried + .business_result() + .and_then(|v| v.as_listing()) + .is_some(), + "public query family", + )?; + passed.push( + "actual protected close/reopen retains original public checkpoint without network work", + ); + let resumed = reopened + .operations(&scope) + .resume(operation, Some(digest)) + .await + .map_err(fail)?; + require( + resumed + .delivery_observations() + .iter() + .any(|v| v.outcome() == TargetObservation::Accepted) + && resumed.issuance_window() == original.issuance_window() + && resumed.installation_transaction_id() == original.installation_transaction_id(), + "explicit retry retains original issuance and installation", + )?; + let attempts = resumed.delivery_attempts(); + require( + attempts.len() == 2 + && attempts[0].envelope_digest() == attempts[1].envelope_digest() + && attempts[0].intent().publication_policy_digest() + == attempts[1].intent().publication_policy_digest(), + "retry retains original exact event and policy", + )?; + let mut ordinals: Vec<_> = attempts + .iter() + .flat_map(|v| v.target_ordinals().iter().copied()) + .collect(); + ordinals.sort(); + require( + ordinals == [1, 2], + "stable-identity sorted attempts retain both actual ordinals", + )?; + passed.push( + "explicit public delivery retry retains original bytes, policy and per-target attempts", + ); + let buyer = Existing::create(&(label.clone() + "_buyer")).await?; + let (other, buyer_scope) = buyer.open(&base).await?; + let other_callbacks = signer(&other).await?; + other.start(StartMode::Online).await.map_err(fail)?; + require( + other + .listings() + .publish(context(&buyer_scope, id(), deadline), input.clone()) + .await + .is_err(), + "buyer cannot publish public seller listing", + )?; + require( + reopened + .listings() + .publish(context(&buyer_scope, id(), deadline), input) + .await + .is_err(), + "foreign authenticated attachment cannot authorize this client", + )?; + other.close().await.map_err(fail)?; + require( + other_callbacks.closed.get() == 1, + "buyer signer callbacks close once", + )?; + reopened.close().await.map_err(fail)?; + require( + callbacks.closed.get() == 1, + "reopened public signer callbacks close once", + )?; + storage_callbacks_closed()?; + passed.push("buyer/foreign scope refusals and ordered actual resource close"); + Ok(serde_json::json!({"passed":passed,"revision":revision}).to_string()) +} + +#[wasm_bindgen] +pub fn verify_listing_publications(raw_events: String, expected: String) -> Result<(), JsValue> { + let events: Vec<String> = serde_json::from_str(&raw_events).map_err(fail)?; + require( + events.len() == 2 && events[0] == events[1], + "only original exact public bytes are retried", + )?; + for raw in events { + let event = nostr::Event::from_json(&raw).map_err(fail)?; + event.verify().map_err(fail)?; + require( + event.kind.as_u16() == 30402 + && event.id.to_hex() == expected + && event.pubkey == key(1).public_key(), + "independently verified public author, revision and kind", + )?; + require( + event.tags.iter().all(|tag| tag.as_slice()[0] != "p"), + "public event has no private envelope recipient", + )?; + } + Ok(()) +} diff --git a/crates/storage_indexeddb/README.md b/crates/storage_indexeddb/README.md @@ -12,14 +12,24 @@ alone never acknowledges a commit. Accepted work remains owned after its observer is dropped. Closing stops admission and waits for accepted work. The default private host stores opaque bytes. The opt-in `workspace` feature -adds `workspace::BrowserWorkspace`: an authenticated protected local buyer -outbox using the shared storage enrollment/grant rules and an explicitly +adds `workspace::BrowserWorkspace`: authenticated protected local buyer and seller +outboxes using the shared storage enrollment/grant rules and an explicitly selected nonvolatile provider. It creates only a fresh unrelated outbox; opening existing data requires its retained selection and protected proof. -It implements the shared `OperationJournal` for this protected local buyer -outbox. Participant custody, general storage SPI and stock authority remain +It implements the shared `OperationJournal` for these protected local outboxes. +Participant custody, general storage SPI and stock authority remain separate. +Initial public listings use the same shared command, plan, claim, obtained +evidence, installation and delivery models. T0 atomically reserves the initial +author/listing coordinate in an independently protected index. Reads verify its +exact original decision, and later writes compare it inside the real transaction. +A second initial publication cannot replace that decision. Private record bytes +and positions stay unchanged; public issuance uses its own protection domain and +target position, and public installation/work use distinct fixed 76-byte metadata. +Direct public delivery retains the original signed event, policy, target ordinals +and observations without a private recipient or temporary wrapping key. + The workspace also executes immutable buyer operation admission and lookup. It retains the original command, transaction identity and first-issue window; an exact replay returns that preparation before acquiring entropy or applying @@ -36,8 +46,9 @@ 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 +plan digest. One real 31-record private transaction compares the grant, all five +T0 slots and all twenty-five T1 slots. Public binding also compares the original +coordinate, using the unchanged 32-record maximum. 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. diff --git a/crates/storage_indexeddb/src/workspace/address.rs b/crates/storage_indexeddb/src/workspace/address.rs @@ -14,6 +14,8 @@ pub(super) const PUBLICATION: u8 = 6; pub(super) const DELIVERY: u8 = 7; pub(super) const OBSERVATION: u8 = 8; pub(super) const REQUEST_INDEX: u8 = 9; +pub(super) const LISTING_INSTALLATION: u8 = 10; +pub(super) const PUBLIC_WORK: u8 = 11; fn prefix_bytes(operation: OperationId) -> [u8; 16] { let digest = Sha256::new() @@ -53,13 +55,14 @@ pub(super) fn fields(key: RecordKey) -> Result<(u8, u8, u8), OperationError> { } || match kind { PREPARED => recipient != 0 || part > 4, PLAN => recipient != 0 || part > 24, - CLAIM => recipient > 1 || part != 0, - EVIDENCE => recipient > 1 || part > 4, + CLAIM => recipient > 2 || part != 0, + EVIDENCE => recipient > 2 || part > 4, INSTALLATION => recipient != 0 || part != 0, PUBLICATION => recipient > 1 || part != 0, - DELIVERY => recipient > 1 || part > 24, - OBSERVATION => recipient > 1 || part != 0, - REQUEST_INDEX => recipient > 1 || part != 0, + LISTING_INSTALLATION | PUBLIC_WORK => recipient != 0 || part != 0, + DELIVERY => recipient > 2 || part > 24, + OBSERVATION => recipient > 2 || part != 0, + REQUEST_INDEX => recipient > 2 || part != 0, // Later reserved families remain unsupported until their actual // implementations and proving cohort land. Never ignore them. _ => true, diff --git a/crates/storage_indexeddb/src/workspace/delivery/codec.rs b/crates/storage_indexeddb/src/workspace/delivery/codec.rs @@ -1,7 +1,9 @@ //! Closed private v2 frame, manifest and independent request-index metadata. use core::num::NonZeroU64; use radroots_domain::{EnvelopeEventId, TransactionId, UnixSeconds}; -use radroots_storage::command::{DeliveryAttempt, DeliveryIntent, OperationError, PublicationWork}; +use radroots_storage::command::{ + DeliveryAttempt, DeliveryIntent, OperationError, PublicationArtifact, +}; use radroots_transport::{TargetSet, policy::SatisfactionPolicy, target::TargetFingerprint}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -51,7 +53,11 @@ pub(super) fn encode( } } let header = Header { - version: 2, + version: if matches!(value.work(), PublicationArtifact::Public(_)) { + 3 + } else { + 2 + }, work, request: value.intent().request_id().as_str(), event: value.intent().event_id(), @@ -78,7 +84,7 @@ pub(super) fn encode( } pub(super) fn decode( raw: &[u8], - work: PublicationWork, + work: PublicationArtifact, commitment: [u8; 32], ) -> Result<DeliveryAttempt, OperationError> { if raw.len() < 5 || raw.len() > MAX_BYTES { @@ -92,10 +98,21 @@ pub(super) fn decode( return Err(OperationError::RecoveryRequired); } let header: Header<'_> = serde_json::from_slice(&raw[4..boundary]).map_err(bad)?; - if header.version != 2 || header.work != commitment { + if header.version + != if matches!(work, PublicationArtifact::Public(_)) { + 3 + } else { + 2 + } + || header.work != commitment + { return Err(OperationError::RecoveryRequired); } - let intent = DeliveryIntent::new( + let constructor = match work { + PublicationArtifact::Private(_) => DeliveryIntent::new, + PublicationArtifact::Public(_) => DeliveryIntent::public, + }; + let intent = constructor( header.request, header.event, &header.targets, diff --git a/crates/storage_indexeddb/src/workspace/delivery/graph.rs b/crates/storage_indexeddb/src/workspace/delivery/graph.rs @@ -3,11 +3,7 @@ use super::{ codec::{self, Manifest}, context, routes, }; -use crate::workspace::{ - State, address, crypto, - installation::{Records, work_commitment}, - retained, -}; +use crate::workspace::{State, address, crypto, installation::Records, retained}; use crate::{Mutation, ReadSnapshot, RecordKey}; use radroots_domain::OperationId; use radroots_storage::command::{ @@ -22,7 +18,7 @@ pub(in crate::workspace) struct Graph { pub selected: Option<DeliveryAttempt>, pub(super) selected_slot: Option<Slot>, pub observations: Vec<DeliveryObservation>, - pub slots: [u16; 2], + pub slots: [u16; 3], } impl Graph { pub(in crate::workspace) async fn read( @@ -67,7 +63,7 @@ impl Graph { selected: None, selected_slot: None, observations: Vec::with_capacity(observation_count), - slots: [0; 2], + slots: [0; 3], }; let mut representations = BTreeMap::new(); for ((recipient, ordinal), positions) in positions { @@ -76,22 +72,9 @@ impl Graph { } result.slots[recipient as usize] = ordinal; let bound = original.bound().ok_or(OperationError::RecoveryRequired)?; - let participant = bound - .chat_plan()? - .seals() - .get(recipient as usize) - .ok_or(OperationError::RecoveryRequired)? - .recipient(); - let work = installed - .work - .iter() - .find(|work| work.recipient() == participant) - .copied() - .ok_or(OperationError::RecoveryRequired)?; - let commitment = work_commitment( - installed.message.ok_or(OperationError::RecoveryRequired)?, - work, - ); + let participant = super::super::issuance::target(bound, recipient)?; + let work = installed.artifact(participant)?; + let commitment = installed.commitment(work)?; let slot = Slot { operation, recipient, diff --git a/crates/storage_indexeddb/src/workspace/delivery/mod.rs b/crates/storage_indexeddb/src/workspace/delivery/mod.rs @@ -7,14 +7,13 @@ mod observation_operations; mod operations; use super::State; -use radroots_domain::PublicKey; use radroots_domain::{CommandDigest, EnvelopeEventId, OperationId, UnixSeconds}; use radroots_secrets::context::{ EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId, }; use radroots_storage::command::{ ArtifactEvidence, BoundSigningPlan, DeliveryAttempt, DeliveryIntent, OperationError, - OperationSnapshot, SignedDmRelaySource, + OperationSnapshot, SignedDmRelaySource, SigningTarget, }; use sha2::{Digest, Sha256}; @@ -58,9 +57,25 @@ fn context( } fn routes( bound: &BoundSigningPlan, - recipient: PublicKey, + recipient: SigningTarget, intent: &DeliveryIntent, ) -> Result<(), OperationError> { + if recipient == SigningTarget::PublicEvent { + if bound.plan().listing().is_none() + || bound + .plan() + .artifact(recipient) + .map_err(|_| OperationError::RecoveryRequired)? + .event_id() + != *intent.event_id().as_bytes() + { + return Err(OperationError::InvalidEvidence); + } + return Ok(()); + } + let recipient = recipient + .recipient() + .ok_or(OperationError::InvalidEvidence)?; let mut selected = None; for route in bound .chat_plan()? @@ -89,7 +104,7 @@ pub(super) use graph::Graph; #[derive(Clone, Copy)] pub(super) struct Selection<'a> { - pub recipient: PublicKey, + pub recipient: SigningTarget, pub request: &'a radroots_transport::sink::DeliveryRequestId, pub event: Option<EnvelopeEventId>, pub retain_seal: bool, @@ -99,7 +114,7 @@ pub(super) struct Facts { pub selected: Option<DeliveryAttempt>, selected_slot: Option<Slot>, pub original: Option<ArtifactEvidence>, - pub slots: [u16; 2], + pub slots: [u16; 3], } impl State { pub(super) async fn delivery_facts( @@ -130,6 +145,10 @@ impl State { .map(|snapshot| { snapshot .with_installation(installed.message, installed.work)? + .with_public_installation( + installed.listing, + installed.public.into_iter().collect(), + )? .with_delivery(deliveries.summaries, deliveries.observations) }) .transpose()?; diff --git a/crates/storage_indexeddb/src/workspace/delivery/observation_operations.rs b/crates/storage_indexeddb/src/workspace/delivery/observation_operations.rs @@ -28,7 +28,7 @@ impl BrowserWorkspace { let result = owned(work, async move { let input = binding.input().clone(); let (grant, protected) = state.capture_retained(&input, &proof).await?; - let actual_work = supplied.work().private()?; + let actual_work = supplied.work(); let evidence = actual_work.evidence(); let operation = evidence.operation_id(); let view = state.read_view(operation).await?; @@ -41,7 +41,7 @@ impl BrowserWorkspace { &t0, binding.observed_at(), Some(Selection { - recipient: evidence.recipient()?, + recipient: evidence.target(), request: supplied.request_id(), event: None, retain_seal: false, @@ -54,7 +54,7 @@ impl BrowserWorkspace { &binding, )?; let attempt = facts.selected.ok_or(OperationError::InvalidEvidence)?; - if attempt.work().private()? != actual_work { + if attempt.work() != actual_work { return Err(OperationError::InvalidEvidence); } let checked = DeliveryObservation::from_store_report( @@ -66,14 +66,14 @@ impl BrowserWorkspace { return Err(OperationError::InvalidEvidence); } let existing = snapshot.delivery_observations().iter().find(|value| { - value.work().private().ok() == Some(actual_work) + value.work() == actual_work && value.request_id() == supplied.request_id() && value.target_receipt().target().fingerprint() == supplied.target_receipt().target().fingerprint() && value.kind() == supplied.kind() }); let retained = existing.cloned().unwrap_or(supplied); - let extra = if existing.is_some() { + let mut extra = if existing.is_some() { Vec::new() } else { vec![ @@ -88,6 +88,7 @@ impl BrowserWorkspace { .await?, ] }; + extra.extend(state.coordinate_guard(snapshot.prepared()).await?); let batch = journal::mutations(protected, operation, t0, None, extra)?; let active = state.active()?; match state @@ -138,9 +139,7 @@ impl BrowserWorkspace { let state = self.state.clone(); owned(work, async move { let access = state.operation_access(&binding, proof).await?; - let recipient = target - .recipient() - .ok_or(OperationError::UnsupportedOperation)?; + let recipient = target; let view = state.read_view(operation).await?; let t0 = state.operation_records(&view, operation).await?; let facts = state @@ -168,8 +167,7 @@ impl BrowserWorkspace { .delivery_observations() .iter() .filter(|value| { - value.work().recipient() == Some(recipient) - && value.request_id() == &request + value.work().target() == recipient && value.request_id() == &request }) .cloned() .collect() diff --git a/crates/storage_indexeddb/src/workspace/delivery/operations.rs b/crates/storage_indexeddb/src/workspace/delivery/operations.rs @@ -1,6 +1,6 @@ use super::{Selection, codec, graph, routes}; use crate::workspace::{ - BrowserWorkspace, WorkspaceError, crypto, installation::work_commitment, + BrowserWorkspace, WorkspaceError, crypto, installation::publication_commitment, journal::OperationChange, owned, }; use nostr::JsonUtil; @@ -9,7 +9,7 @@ use radroots_storage::{ command::{ ArtifactEvidence, BoundSigningPlan, CommitAttempt, DeliveryAttempt, DeliveryAttemptOutcome, DeliveryAttemptRequest, DeliveryAttemptSummary, EnvelopeCandidate, OperationError, - PublicationWork, + PublicationArtifact, PublicationWork, SigningTarget, }, workspace::{AttachmentProof, WorkspaceBinding}, }; @@ -81,7 +81,7 @@ impl BrowserWorkspace { let state = self.state.clone(); let result = owned(work, async move { let access = state.operation_access(request.binding(), proof).await?; - let actual = request.work().private()?; + let actual = request.work(); let evidence = actual.evidence(); let operation = evidence.operation_id(); let view = state.read_view(operation).await?; @@ -94,7 +94,7 @@ impl BrowserWorkspace { &t0, access.binding.observed_at(), Some(Selection { - recipient: evidence.recipient()?, + recipient: evidence.target(), request: request.intent().request_id(), event: Some(request.intent().event_id()), retain_seal: true, @@ -106,36 +106,36 @@ impl BrowserWorkspace { snapshot.prepared().request().binding(), request.binding(), )?; - if !snapshot.publications().contains(&actual) { + if !match actual { + PublicationArtifact::Private(work) => snapshot.publications().contains(&work), + PublicationArtifact::Public(work) => snapshot.public_publications().contains(&work), + } { return Err(OperationError::InvalidEvidence); } let bound = snapshot .bound_plan() .ok_or(OperationError::RecoveryRequired)?; - let recipient = bound - .chat_plan()? - .seals() - .iter() - .position(|seal| Some(seal.recipient()) == evidence.target().recipient()) - .ok_or(OperationError::InvalidEvidence)? as u8; + let recipient = super::super::issuance::position(bound, evidence.target())? + .ok_or(OperationError::InvalidEvidence)?; let retained = facts .selected .as_ref() .filter(|value| value.intent().request_id() == request.intent().request_id()); if let Some(retained) = retained - && (retained.work().private()? != actual + && (retained.work() != actual || retained.intent().digest() != request.intent().digest() || candidate.as_ref().is_some_and(|value| { - value.work() != actual || value.raw_json() != retained.raw_json() + PublicationArtifact::Private(value.work()) != actual + || value.raw_json() != retained.raw_json() })) { return Err(OperationError::IdempotencyConflict); } let fresh = retained.is_none(); let (report, extra) = if fresh { - routes(bound, evidence.recipient()?, request.intent())?; + routes(bound, evidence.target(), request.intent())?; if snapshot.delivery_attempts().iter().any(|value| { - value.work().private().ok() == Some(actual) + value.work() == actual && value.intent().publication_policy_digest() != request.intent().publication_policy_digest() }) { @@ -162,7 +162,7 @@ impl BrowserWorkspace { let count = snapshot .delivery_attempts() .iter() - .filter(|value| value.work().private().ok() == Some(actual)) + .filter(|value| value.work() == actual) .flat_map(|value| value.intent().selected_targets()) .filter(|old| old.uri() == target.uri()) .count(); @@ -171,13 +171,28 @@ impl BrowserWorkspace { } ordinals.push(count as u8 + 1); } - let raw = if let Some(candidate) = &candidate { + let raw = if matches!(actual, PublicationArtifact::Public(_)) { + if candidate.is_some() { + return Err(OperationError::InvalidEvidence); + } + let source = facts + .original + .as_ref() + .ok_or(OperationError::RecoveryRequired)?; + if source.target() != SigningTarget::PublicEvent + || source.digest() != actual.evidence().digest() + || source.event_id() != request.intent().event_id() + { + return Err(OperationError::InvalidEvidence); + } + Zeroizing::new(source.raw_json().to_owned()) + } else if let Some(candidate) = &candidate { if candidate.event_id() != request.intent().event_id() { return Err(OperationError::InvalidEvidence); } contains_original( candidate, - actual, + actual.private()?, bound, facts .original @@ -190,7 +205,7 @@ impl BrowserWorkspace { .selected .as_ref() .filter(|value| { - value.work().private().ok() == Some(actual) + value.work() == actual && value.intent().event_id() == request.intent().event_id() }) .ok_or(OperationError::InvalidEvidence)?; @@ -213,12 +228,7 @@ impl BrowserWorkspace { now, ordinals, )?; - let commitment = work_commitment( - snapshot - .installation() - .ok_or(OperationError::RecoveryRequired)?, - actual, - ); + let commitment = publication_commitment(&snapshot, actual)?; let mut summaries = snapshot.delivery_attempts().to_vec(); summaries.push(DeliveryAttemptSummary::from_attempt(&report)); snapshot.with_delivery(summaries, Vec::new())?; @@ -299,9 +309,7 @@ impl BrowserWorkspace { let state = self.state.clone(); owned(work, async move { let access = state.operation_access(&binding, proof).await?; - let recipient = target - .recipient() - .ok_or(OperationError::UnsupportedOperation)?; + let recipient = target; let view = state.read_view(operation).await?; let t0 = state.operation_records(&view, operation).await?; let facts = state diff --git a/crates/storage_indexeddb/src/workspace/installation.rs b/crates/storage_indexeddb/src/workspace/installation.rs @@ -57,6 +57,8 @@ fn context( pub(super) struct Records { pub message: Option<ChatInstallation>, pub work: Vec<PublicationWork>, + pub listing: Option<radroots_storage::command::ListingInstallation>, + pub public: Option<radroots_storage::command::PublicPublicationWork>, } impl Records { pub(super) async fn read( @@ -65,6 +67,17 @@ impl Records { graph: &Graph, operation: OperationId, ) -> Result<Self, OperationError> { + if graph.bound().is_some_and(|v| v.plan().listing().is_some()) { + let (listing, public) = state + .read_public_installation(view, graph, operation) + .await?; + return Ok(Self { + message: None, + work: Vec::new(), + listing, + public, + }); + } let message = if let Some(raw) = state .read_view_key(view, address::key(operation, address::INSTALLATION, 0, 0)) .await? @@ -110,12 +123,74 @@ impl Records { { return Err(OperationError::RecoveryRequired); } - Ok(Self { message, work }) + Ok(Self { + message, + work, + listing: None, + public: None, + }) } } pub(super) fn work_commitment(message: ChatInstallation, work: PublicationWork) -> [u8; 32] { Sha256::digest(codec::work(message, work)).into() } +impl Records { + pub(super) fn artifact( + &self, + target: radroots_storage::command::SigningTarget, + ) -> Result<radroots_storage::command::PublicationArtifact, OperationError> { + if target == radroots_storage::command::SigningTarget::PublicEvent { + return self + .public + .map(Into::into) + .ok_or(OperationError::RecoveryRequired); + } + self.work + .iter() + .find(|v| Some(v.recipient()) == target.recipient()) + .copied() + .map(Into::into) + .ok_or(OperationError::RecoveryRequired) + } + pub(super) fn commitment( + &self, + work: radroots_storage::command::PublicationArtifact, + ) -> Result<[u8; 32], OperationError> { + match work { + radroots_storage::command::PublicationArtifact::Private(value) => Ok(work_commitment( + self.message.ok_or(OperationError::RecoveryRequired)?, + value, + )), + radroots_storage::command::PublicationArtifact::Public(value) => { + Ok(super::listing_installation::commitment( + self.listing.ok_or(OperationError::RecoveryRequired)?, + value, + )) + } + } + } +} +pub(super) fn publication_commitment( + snapshot: &OperationSnapshot, + work: radroots_storage::command::PublicationArtifact, +) -> Result<[u8; 32], OperationError> { + match work { + radroots_storage::command::PublicationArtifact::Private(value) => Ok(work_commitment( + snapshot + .installation() + .ok_or(OperationError::RecoveryRequired)?, + value, + )), + radroots_storage::command::PublicationArtifact::Public(value) => { + Ok(super::listing_installation::commitment( + snapshot + .listing_installation() + .ok_or(OperationError::RecoveryRequired)?, + value, + )) + } + } +} impl State { /// A missing claim must not conceal installation/publication descendants. /// The complete witnessed prefix still fences all facts at actual commit. @@ -170,6 +245,11 @@ impl BrowserWorkspace { if bound.plan().digest() != request.plan_digest() { return Err(OperationError::IdempotencyConflict); } + if bound.plan().listing().is_some() { + return state + .install_listing(request, access, view, t0, snapshot) + .await; + } let original = snapshot.installation(); let missing = snapshot .artifacts() diff --git a/crates/storage_indexeddb/src/workspace/issuance.rs b/crates/storage_indexeddb/src/workspace/issuance.rs @@ -2,7 +2,7 @@ use super::journal::{OperationChange, Records, mutations, storage_error}; use super::{BrowserWorkspace, Mutation, State, WorkspaceError, address, crypto, owned}; use crate::ReadSnapshot; -use radroots_domain::{CommandDigest, OperationId, PublicKey, SigningAttemptId, TransactionId}; +use radroots_domain::{CommandDigest, OperationId, SigningAttemptId, TransactionId}; use radroots_secrets::context::{ EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId, }; @@ -10,7 +10,7 @@ use radroots_storage::{ command::{ ArtifactEvidence, BoundSigningPlan, CapturedArtifact, ClaimAttemptOutcome, ClaimAttemptRequest, CommitAttempt, EvidenceCaptureOutcome, EvidenceReceipt, - OperationError, SigningAttempt, + OperationError, SigningAttempt, SigningTarget, protected::{ self, issuance::{ClaimRecord, EvidenceManifest}, @@ -26,28 +26,54 @@ pub(super) enum Claim { Absent(BoundSigningPlan, u8), Present(Box<SigningAttempt>), } -fn position(bound: &BoundSigningPlan, recipient: PublicKey) -> Result<Option<u8>, OperationError> { - Ok(bound - .chat_plan()? +pub(super) fn position( + bound: &BoundSigningPlan, + target: SigningTarget, +) -> Result<Option<u8>, OperationError> { + if target == SigningTarget::PublicEvent { + return Ok(bound.plan().listing().map(|_| 2)); + } + let Some(chat) = bound.plan().chat() else { + return Ok(None); + }; + Ok(chat .seals() .iter() - .position(|seal| seal.recipient() == recipient) + .position(|seal| Some(seal.recipient()) == target.recipient()) .and_then(|i| u8::try_from(i).ok())) } +pub(super) fn target(bound: &BoundSigningPlan, index: u8) -> Result<SigningTarget, OperationError> { + if index == 2 && bound.plan().listing().is_some() { + return Ok(SigningTarget::PublicEvent); + } + let chat = bound.chat_plan()?; + chat.seals() + .get(index as usize) + .map(|seal| SigningTarget::BusinessSeal(seal.recipient())) + .ok_or(OperationError::RecoveryRequired) +} fn base(state: &State, bound: &BoundSigningPlan, index: u8) -> Result<Sha256, OperationError> { let identity = bound.prepared().identity(); - let recipient = bound - .chat_plan()? - .seals() - .get(index as usize) - .ok_or(OperationError::InvalidCommand)? - .recipient(); + let target = target(bound, index)?; + if target == SigningTarget::PublicEvent { + return Ok(Sha256::new() + .chain_update(b"radroots.browser.local_outbox.public_issuance.context.v1\0") + .chain_update(state.selected.workspace_id().as_bytes()) + .chain_update(identity.operation_id().as_bytes()) + .chain_update(bound.plan().digest()) + .chain_update([index])); + } Ok(Sha256::new() .chain_update(b"radroots.browser.local_outbox.issuance.context.v2\0") .chain_update(state.selected.workspace_id().as_bytes()) .chain_update(identity.operation_id().as_bytes()) .chain_update(bound.plan().digest()) - .chain_update(recipient.as_bytes()) + .chain_update( + target + .recipient() + .ok_or(OperationError::RecoveryRequired)? + .as_bytes(), + ) .chain_update([index])) } fn finish(hash: Sha256, schema: &str) -> Result<EnvelopeContext, OperationError> { @@ -107,7 +133,7 @@ impl State { &self, view: &ReadSnapshot, bound: BoundSigningPlan, - recipient: PublicKey, + recipient: SigningTarget, index: u8, ) -> Result<Claim, OperationError> { let operation = bound.prepared().identity().operation_id(); @@ -271,55 +297,53 @@ impl BrowserWorkspace { return Err(OperationError::IdempotencyConflict); } let index = - position(&bound, request.recipient()?)?.ok_or(OperationError::InvalidCommand)?; - let (attempt, fresh, extra) = match state - .claim(&view, bound, request.recipient()?, index) - .await? - { - Claim::Present(attempt) => (*attempt, false, Vec::new()), - Claim::Absent(bound, index) => { - state - .check_claim_absence( - &view, - operation, - request.command_digest(), - &t0, - access.binding.observed_at(), + position(&bound, request.target())?.ok_or(OperationError::InvalidCommand)?; + let (attempt, fresh, extra) = + match state.claim(&view, bound, request.target(), index).await? { + Claim::Present(attempt) => (*attempt, false, Vec::new()), + Claim::Absent(bound, index) => { + state + .check_claim_absence( + &view, + operation, + request.command_digest(), + &t0, + access.binding.observed_at(), + ) + .await?; + let now = access.binding.observed_at(); + if now < bound.bound_at() { + return Err(WorkspaceError::Unavailable.into()); + } + if now >= bound.prepared().issuance_window().first_issue_not_after() { + return Err(OperationError::DeadlineExceeded); + } + let attempt = SigningAttempt::from_committed_store( + bound, + request.target(), + SigningAttemptId::from_bytes(*crypto::random::<32>()?), + TransactionId::from_bytes(*crypto::random::<32>()?), + now, + )?; + let encoded = ClaimRecord::capture(&attempt)?.encode()?; + let protected = crypto::seal_bound( + state.provider.as_ref(), + &state.reference, + claim_context(&state, attempt.bound_plan(), index)?, + &encoded, ) .await?; - let now = access.binding.observed_at(); - if now < bound.bound_at() { - return Err(WorkspaceError::Unavailable.into()); - } - if now >= bound.prepared().issuance_window().first_issue_not_after() { - return Err(OperationError::DeadlineExceeded); + let extra = vec![ + Mutation::new( + address::key(operation, address::CLAIM, index, 0), + None, + Some(protected), + ) + .map_err(storage_error)?, + ]; + (attempt, true, extra) } - let attempt = SigningAttempt::from_committed_store( - bound, - request.recipient()?, - SigningAttemptId::from_bytes(*crypto::random::<32>()?), - TransactionId::from_bytes(*crypto::random::<32>()?), - now, - )?; - let encoded = ClaimRecord::capture(&attempt)?.encode()?; - let protected = crypto::seal_bound( - state.provider.as_ref(), - &state.reference, - claim_context(&state, attempt.bound_plan(), index)?, - &encoded, - ) - .await?; - let extra = vec![ - Mutation::new( - address::key(operation, address::CLAIM, index, 0), - None, - Some(protected), - ) - .map_err(storage_error)?, - ]; - (attempt, true, extra) - } - }; + }; let anchor = attempt.identity(); let change = OperationChange { before: t0, @@ -371,11 +395,8 @@ impl BrowserWorkspace { if bound.plan().digest() != request.plan_digest() { return Err(OperationError::IdempotencyConflict); } - if let Some(index) = position(&bound, request.recipient()?)? { - match state - .claim(&view, bound, request.recipient()?, index) - .await? - { + if let Some(index) = position(&bound, request.target())? { + match state.claim(&view, bound, request.target(), index).await? { Claim::Present(attempt) => Some(*attempt), Claim::Absent(_, _) => { state @@ -438,11 +459,8 @@ impl BrowserWorkspace { .await? .ok_or(OperationError::RecoveryRequired)?; let index = - position(&bound, supplied.recipient()?)?.ok_or(OperationError::InvalidEvidence)?; - let attempt = match state - .claim(&view, bound, supplied.recipient()?, index) - .await? - { + position(&bound, supplied.target())?.ok_or(OperationError::InvalidEvidence)?; + let attempt = match state.claim(&view, bound, supplied.target(), index).await? { Claim::Present(attempt) => attempt, Claim::Absent(_, _) => return Err(OperationError::RecoveryRequired), }; @@ -455,7 +473,10 @@ impl BrowserWorkspace { supplied.observed_at_unix_ms(), )?; drop(supplied); - let (receipt, extra) = match state.evidence(&view, &attempt, index).await? { + let coordinate = state + .coordinate_guard(attempt.bound_plan().prepared()) + .await?; + let (receipt, mut extra) = match state.evidence(&view, &attempt, index).await? { Some((original, receipt)) => { if original.raw_json() != checked.raw_json() || original.digest() != checked.digest() @@ -481,6 +502,7 @@ impl BrowserWorkspace { receipt.command_digest(), Some(receipt.transaction_id()), ); + extra.extend(coordinate); let batch = mutations(protected, operation, t0, None, extra)?; let active = state.active()?; match state @@ -534,11 +556,8 @@ impl BrowserWorkspace { if bound.plan().digest() != request.plan_digest() { return Err(OperationError::IdempotencyConflict); } - if let Some(index) = position(&bound, request.recipient()?)? { - match state - .claim(&view, bound, request.recipient()?, index) - .await? - { + if let Some(index) = position(&bound, request.target())? { + match state.claim(&view, bound, request.target(), index).await? { Claim::Present(attempt) => { let obtained = state.evidence(&view, &attempt, index).await?; if obtained.is_none() { diff --git a/crates/storage_indexeddb/src/workspace/journal.rs b/crates/storage_indexeddb/src/workspace/journal.rs @@ -182,7 +182,9 @@ impl State { if Sha256::digest(plaintext.as_slice()).as_slice() != digest { return Err(OperationError::RecoveryRequired); } - protected::decode(&plaintext, &self.selected, operation).map(Some) + let prepared = protected::decode(&plaintext, &self.selected, operation)?; + self.coordinate_guard(&prepared).await?; + Ok(Some(prepared)) } async fn protect_preparation( &self, @@ -264,8 +266,16 @@ impl State { after, window, delivery_deadline, - extra, + mut extra, } = change; + // The current authenticated buyer grant cannot admit public work, and + // preparation decoding refuses any such stored command. Preserve the + // original private path without another decryption of every T0 part. + if access.binding.scope() != radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox + && let Some(prepared) = self.preparation(operation, &before).await? + { + extra.extend(self.coordinate_guard(&prepared).await?); + } let batch = mutations(access.protected, operation, before, after, extra)?; let active = self.active()?; let clock = self.clock.clone(); @@ -348,16 +358,11 @@ impl BrowserWorkspace { let state = self.state.clone(); let result = owned(work, async move { let access = state.operation_access(request.binding(), proof).await?; - // The current browser writer has no public signing/installation - // continuation. Refuse before admitting unsupported public work. - if request.command().listing().is_some() { - return Err(OperationError::UnsupportedOperation); - } let context = request.command().context(); let operation = context.operation_id(); let view = state.read_view(operation).await?; let before = state.operation_records(&view, operation).await?; - let extra = if before.iter().all(Option::is_none) { + let mut extra = if before.iter().all(Option::is_none) { state.absent_plans(&view, operation).await? } else { Vec::new() @@ -392,6 +397,7 @@ impl BrowserWorkspace { Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?, window, )?; + extra.extend(state.coordinate_creation(&prepared).await?); (prepared, Some(records), true) }; let attempt = prepared.identity(); diff --git a/crates/storage_indexeddb/src/workspace/listing.rs b/crates/storage_indexeddb/src/workspace/listing.rs @@ -0,0 +1,174 @@ +//! Atomic initial-coordinate ownership, separate from stock authority. +use super::{Mutation, RecordKey, State, crypto, journal::storage_error}; +use radroots_domain::{ + CommandDigest, OperationId, PublicKey, TransactionId, WorkspaceId, listing::ListingId, +}; +use radroots_secrets::context::{ + EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId, +}; +use radroots_storage::command::{OperationError, PreparedOperation}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use zeroize::Zeroizing; + +#[derive(Serialize, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +struct Decision { + version: u8, + workspace: WorkspaceId, + operation: OperationId, + command: CommandDigest, + author: PublicKey, + listing: ListingId, + transaction: TransactionId, +} +impl Decision { + fn new(prepared: &PreparedOperation) -> Result<Self, OperationError> { + let request = prepared.request(); + let command = request + .command() + .listing() + .ok_or(OperationError::UnsupportedOperation)?; + let context = request.command().context(); + Ok(Self { + version: 1, + workspace: context.workspace_id(), + operation: context.operation_id(), + command: request.command().digest(), + author: context.actor().participant(), + listing: command.input().id(), + transaction: prepared.transaction_id(), + }) + } + fn digest(&self) -> [u8; 32] { + Sha256::new() + .chain_update(b"radroots.browser.local_outbox.listing_coordinate.v1\0") + .chain_update(self.workspace.as_bytes()) + .chain_update(self.author.as_bytes()) + .chain_update(self.listing.as_bytes()) + .finalize() + .into() + } + fn key(&self) -> RecordKey { + RecordKey::new(self.digest()) + } + fn context(&self) -> Result<EnvelopeContext, OperationError> { + let subject = self + .digest() + .iter() + .map(|b| format!("{b:02x}")) + .collect::<String>(); + Ok(EnvelopeContext::new( + EnvelopePurpose::parse("radroots.browser.workspace.listing_coordinate") + .map_err(|_| OperationError::InvalidCommand)?, + EnvelopeSubject::parse("listing_coordinate", subject) + .map_err(|_| OperationError::InvalidCommand)?, + PayloadSchemaId::parse("radroots.browser.workspace.listing_coordinate.v1") + .map_err(|_| OperationError::InvalidCommand)?, + )) + } +} +impl State { + pub(super) async fn coordinate_creation( + &self, + prepared: &PreparedOperation, + ) -> Result<Vec<Mutation>, OperationError> { + if prepared.request().command().listing().is_none() { + return Ok(Vec::new()); + } + let decision = Decision::new(prepared)?; + if let Some(protected) = self + .database() + .get(decision.key()) + .await + .map_err(storage_error)? + { + let raw = crypto::open_bound( + self.provider.as_ref(), + &self.reference, + decision.context()?, + &protected, + ) + .await?; + let original: Decision = raw.expose_secret(|bytes| { + if bytes.len() > 2048 { + return Err(OperationError::RecoveryRequired); + } + serde_json::from_slice(bytes).map_err(|_| OperationError::RecoveryRequired) + })?; + if original.version != 1 + || original.workspace != decision.workspace + || original.author != decision.author + || original.listing != decision.listing + { + return Err(OperationError::RecoveryRequired); + } + let view = self.read_view(original.operation).await?; + let records = self.operation_records(&view, original.operation).await?; + let prepared = self + .preparation(original.operation, &records) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if Decision::new(&prepared)? != original { + return Err(OperationError::RecoveryRequired); + } + return Err(OperationError::StaleState); + } + let raw = Zeroizing::new( + serde_json::to_vec(&decision).map_err(|_| OperationError::InvalidCommand)?, + ); + let protected = crypto::seal_bound( + self.provider.as_ref(), + &self.reference, + decision.context()?, + &raw, + ) + .await?; + Ok(vec![ + Mutation::new(decision.key(), None, Some(protected)).map_err(storage_error)?, + ]) + } + /// Verifies the exact T0 decision and returns an unchanged CAS entry. It is + /// included with every later write, even though the index is outside the + /// operation prefix. There is no overwrite, lease or automatic reclamation. + pub(super) async fn coordinate_guard( + &self, + prepared: &PreparedOperation, + ) -> Result<Vec<Mutation>, OperationError> { + if prepared.request().command().listing().is_none() { + return Ok(Vec::new()); + } + if prepared.request().binding().scope() + != radroots_storage::workspace::LocalOutboxScope::NewSellerOutbox + { + return Err(OperationError::RecoveryRequired); + } + let expected = Decision::new(prepared)?; + let protected = self + .database() + .get(expected.key()) + .await + .map_err(storage_error)? + .ok_or(OperationError::RecoveryRequired)?; + let raw = crypto::open_bound( + self.provider.as_ref(), + &self.reference, + expected.context()?, + &protected, + ) + .await?; + let decision: Decision = raw.expose_secret(|bytes| { + if bytes.len() > 2048 { + return Err(OperationError::RecoveryRequired); + } + serde_json::from_slice(bytes).map_err(|_| OperationError::RecoveryRequired) + })?; + if decision != expected { + return Err(OperationError::RecoveryRequired); + } + Ok(vec![ + Mutation::new(expected.key(), Some(protected.clone()), Some(protected)) + .map_err(storage_error)?, + ]) + } +} diff --git a/crates/storage_indexeddb/src/workspace/listing_installation.rs b/crates/storage_indexeddb/src/workspace/listing_installation.rs @@ -0,0 +1,289 @@ +//! Protected public installation metadata, validated against actual retained S. +use super::{ + Mutation, State, address, crypto, + journal::{Access, OperationChange, Records, storage_error}, + retained::Graph, +}; +use crate::ReadSnapshot; +use radroots_domain::{OperationId, TransactionId, UnixSeconds}; +use radroots_secrets::context::{ + EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId, +}; +use radroots_storage::command::{ + BoundSigningPlan, CommitAttempt, EvidenceReceipt, InstallationOutcome, InstallationRequest, + ListingInstallation, OperationError, OperationSnapshot, PublicPublicationWork, SigningTarget, +}; +use sha2::{Digest, Sha256}; + +fn context( + state: &State, + bound: &BoundSigningPlan, + work: bool, +) -> Result<EnvelopeContext, OperationError> { + let subject = Sha256::new() + .chain_update(b"radroots.browser.local_outbox.public_installation.context.v1\0") + .chain_update(state.selected.workspace_id().as_bytes()) + .chain_update(bound.prepared().identity().operation_id().as_bytes()) + .chain_update(bound.plan().digest()) + .chain_update([u8::from(work)]) + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect::<String>(); + Ok(EnvelopeContext::new( + EnvelopePurpose::parse("radroots.browser.workspace.public_installation") + .map_err(|_| OperationError::InvalidCommand)?, + EnvelopeSubject::parse("public_installation", subject) + .map_err(|_| OperationError::InvalidCommand)?, + PayloadSchemaId::parse(if work { + "radroots.browser.workspace.public_work.v1" + } else { + "radroots.browser.workspace.listing_installation.v1" + }) + .map_err(|_| OperationError::InvalidCommand)?, + )) +} +fn evidence(hash: Sha256, value: EvidenceReceipt) -> Sha256 { + hash.chain_update(value.workspace_id().as_bytes()) + .chain_update(value.operation_id().as_bytes()) + .chain_update(value.command_digest().as_bytes()) + .chain_update(value.attempt_id().as_bytes()) + .chain_update(value.event_id().as_bytes()) + .chain_update(value.digest()) + .chain_update(value.transaction_id().as_bytes()) + .chain_update([u8::from(value.observed_at_unix_ms().is_some())]) + .chain_update( + value + .observed_at_unix_ms() + .map_or(0, |v| v.get()) + .to_be_bytes(), + ) +} +fn frame( + magic: &[u8; 4], + transaction: TransactionId, + time: UnixSeconds, + digest: [u8; 32], +) -> Vec<u8> { + let mut output = Vec::with_capacity(76); + output.extend_from_slice(magic); + output.extend_from_slice(transaction.as_bytes()); + output.extend_from_slice(&time.get().to_be_bytes()); + output.extend_from_slice(&digest); + output +} +fn selectors(raw: &[u8], magic: &[u8; 4]) -> Result<(TransactionId, UnixSeconds), OperationError> { + if raw.len() != 76 || &raw[..4] != magic { + return Err(OperationError::RecoveryRequired); + } + let transaction = TransactionId::from_bytes( + raw[4..36] + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ); + let time = UnixSeconds::new(u64::from_be_bytes( + raw[36..44] + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + )) + .map_err(|_| OperationError::RecoveryRequired)?; + Ok((transaction, time)) +} +fn installation(value: ListingInstallation) -> Vec<u8> { + let hash = Sha256::new() + .chain_update(b"radroots.browser.listing_installation.record.v1\0") + .chain_update(value.plan_digest()) + .chain_update(value.author().as_bytes()) + .chain_update(value.listing_id().as_bytes()) + .chain_update(value.revision().as_bytes()) + .chain_update(value.preparation_transaction_id().as_bytes()) + .chain_update(value.plan_transaction_id().as_bytes()); + frame( + b"RLI1", + value.transaction_id(), + value.installed_at(), + evidence(hash, value.basis()).finalize().into(), + ) +} +fn publication(installed: ListingInstallation, value: PublicPublicationWork) -> Vec<u8> { + let hash = Sha256::new() + .chain_update(b"radroots.browser.public_work.record.v1\0") + .chain_update(installation(installed)) + .chain_update(value.installation_transaction_id().as_bytes()) + .chain_update(value.plan_digest()); + frame( + b"RPW1", + value.transaction_id(), + value.queued_at(), + evidence(hash, value.evidence()).finalize().into(), + ) +} +pub(super) fn commitment(installed: ListingInstallation, work: PublicPublicationWork) -> [u8; 32] { + Sha256::digest(publication(installed, work)).into() +} + +impl State { + pub(super) async fn read_public_installation( + &self, + view: &ReadSnapshot, + graph: &Graph, + operation: OperationId, + ) -> Result<(Option<ListingInstallation>, Option<PublicPublicationWork>), OperationError> { + let left = self + .read_view_key( + view, + address::key(operation, address::LISTING_INSTALLATION, 0, 0), + ) + .await?; + let right = self + .read_view_key(view, address::key(operation, address::PUBLIC_WORK, 0, 0)) + .await?; + let (Some(left), Some(right)) = (left, right) else { + if view.keys().any(|key| { + matches!( + address::fields(key), + Ok((address::LISTING_INSTALLATION | address::PUBLIC_WORK, _, _)) + ) + }) { + return Err(OperationError::RecoveryRequired); + } + return Ok((None, None)); + }; + let bound = graph.bound().ok_or(OperationError::RecoveryRequired)?; + let basis = graph.receipt_target(SigningTarget::PublicEvent)?; + let raw = crypto::open_bound( + self.provider.as_ref(), + &self.reference, + context(self, bound, false)?, + &left, + ) + .await?; + let installed = raw.expose_secret(|raw| { + let (transaction, time) = selectors(raw, b"RLI1")?; + let checked = + ListingInstallation::from_committed_store(bound, basis, transaction, time)?; + if raw != installation(checked) { + return Err(OperationError::RecoveryRequired); + } + Ok(checked) + })?; + let raw = crypto::open_bound( + self.provider.as_ref(), + &self.reference, + context(self, bound, true)?, + &right, + ) + .await?; + let work = raw.expose_secret(|raw| { + let (transaction, time) = selectors(raw, b"RPW1")?; + let checked = PublicPublicationWork::from_committed_store( + bound, + installed, + basis, + transaction, + time, + )?; + if raw != publication(installed, checked) { + return Err(OperationError::RecoveryRequired); + } + Ok(checked) + })?; + Ok((Some(installed), Some(work))) + } + pub(super) async fn install_listing( + &self, + request: InstallationRequest, + access: Access, + view: ReadSnapshot, + t0: Records, + snapshot: OperationSnapshot, + ) -> Result<InstallationOutcome, OperationError> { + let bound = snapshot + .bound_plan() + .ok_or(OperationError::RecoveryRequired)?; + let mut extra = Vec::new(); + let installed = if let Some(installed) = snapshot.listing_installation() { + if snapshot.public_publications().len() != 1 { + return Err(OperationError::RecoveryRequired); + } + installed + } else { + if !snapshot.public_publications().is_empty() { + return Err(OperationError::RecoveryRequired); + } + let basis = snapshot + .artifacts() + .iter() + .find(|v| v.target() == SigningTarget::PublicEvent) + .and_then(|v| v.obtained()) + .ok_or(OperationError::InvalidEvidence)?; + let transaction = TransactionId::from_bytes(*crypto::random::<32>()?); + let installed = ListingInstallation::from_committed_store( + bound, + basis, + transaction, + access.binding.observed_at(), + )?; + let work = PublicPublicationWork::from_committed_store( + bound, + installed, + basis, + transaction, + access.binding.observed_at(), + )?; + for (kind, is_work, bytes) in [ + ( + address::LISTING_INSTALLATION, + false, + installation(installed), + ), + (address::PUBLIC_WORK, true, publication(installed, work)), + ] { + let protected = crypto::seal_bound( + self.provider.as_ref(), + &self.reference, + context(self, bound, is_work)?, + &bytes, + ) + .await?; + extra.push( + Mutation::new( + address::key(request.operation_id(), kind, 0, 0), + None, + Some(protected), + ) + .map_err(storage_error)?, + ); + } + installed + }; + let anchor = CommitAttempt::new( + installed.workspace_id(), + installed.operation_id(), + installed.command_digest(), + Some(installed.transaction_id()), + ); + match self + .check_operation( + access, + request.operation_id(), + OperationChange { + before: t0, + after: None, + window: None, + delivery_deadline: None, + extra, + }, + view, + ) + .await + { + Ok(()) => Ok(InstallationOutcome::ListingCommitted(Box::new(installed))), + Err(OperationError::Workspace(super::WorkspaceError::CommitUnknown)) => { + self.mark_unknown(); + Ok(InstallationOutcome::Unknown(anchor)) + } + Err(error) => Err(error), + } + } +} diff --git a/crates/storage_indexeddb/src/workspace/mod.rs b/crates/storage_indexeddb/src/workspace/mod.rs @@ -8,6 +8,8 @@ mod installation; mod issuance; mod journal; mod lease; +mod listing; +mod listing_installation; mod plans; mod ports; mod recovery; diff --git a/crates/storage_indexeddb/src/workspace/plans.rs b/crates/storage_indexeddb/src/workspace/plans.rs @@ -213,9 +213,6 @@ 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?; diff --git a/crates/storage_indexeddb/src/workspace/retained.rs b/crates/storage_indexeddb/src/workspace/retained.rs @@ -4,7 +4,7 @@ use crate::ReadSnapshot; use radroots_domain::{CommandDigest, EnvelopeEventId, OperationId, PublicKey, UnixSeconds}; use radroots_storage::command::{ ArtifactEvidence, ArtifactSnapshot, BoundSigningPlan, ClaimSnapshot, EvidenceReceipt, - OperationError, OperationSnapshot, RetainedOperation, protected, + OperationError, OperationSnapshot, RetainedOperation, SigningTarget, protected, }; pub(super) async fn header( @@ -38,9 +38,39 @@ pub(super) async fn header( }; for key in view.keys() { let (kind, recipient, _) = address::fields(key)?; - if kind >= address::CLAIM { - let chat = plan.chat().ok_or(OperationError::UnsupportedOperation)?; - if recipient as usize >= chat.seals().len() { + if matches!(kind, address::PREPARED | address::PLAN) { + continue; + } + if matches!(kind, address::LISTING_INSTALLATION | address::PUBLIC_WORK) { + if plan.listing().is_none() { + return Err(OperationError::RecoveryRequired); + } + } else if matches!(kind, address::INSTALLATION | address::PUBLICATION) { + if plan.chat().is_none() { + return Err(OperationError::RecoveryRequired); + } + if kind == address::PUBLICATION + && recipient as usize + >= plan + .chat() + .ok_or(OperationError::RecoveryRequired)? + .seals() + .len() + { + return Err(OperationError::RecoveryRequired); + } + } else { + let valid = if plan.listing().is_some() { + recipient == 2 + } else { + (recipient as usize) + < plan + .chat() + .ok_or(OperationError::RecoveryRequired)? + .seals() + .len() + }; + if !valid { return Err(OperationError::RecoveryRequired); } } @@ -62,7 +92,7 @@ impl Graph { operation: OperationId, digest: Option<CommandDigest>, t0: &Records, - selected: Option<PublicKey>, + selected: Option<SigningTarget>, ) -> Result<Self, OperationError> { let retained = header(state, view, operation, digest, t0).await?; let mut recipients = Vec::with_capacity(2); @@ -70,16 +100,25 @@ impl Graph { let retained = match retained { Some(RetainedOperation::Planned(bound)) => { let mut bound = *bound; - let keys = bound - .chat_plan()? - .seals() - .iter() - .map(|seal| seal.recipient()) - .collect::<Vec<_>>(); - for (index, recipient) in keys.into_iter().enumerate() { - let expected = - EnvelopeEventId::from_bytes(bound.chat_plan()?.seals()[index].event_id()); - match state.claim(view, bound, recipient, index as u8).await? { + let keys = match bound.plan().chat() { + Some(chat) => chat + .seals() + .iter() + .map(|seal| SigningTarget::BusinessSeal(seal.recipient())) + .collect::<Vec<_>>(), + None => vec![SigningTarget::PublicEvent], + }; + for recipient in keys { + let expected = EnvelopeEventId::from_bytes( + bound + .plan() + .artifact(recipient) + .map_err(|_| OperationError::RecoveryRequired)? + .event_id(), + ); + let index = super::issuance::position(&bound, recipient)? + .ok_or(OperationError::RecoveryRequired)?; + match state.claim(view, bound, recipient, index).await? { Claim::Absent(returned, _) => { recipients.push(ArtifactSnapshot::from_store_report( recipient, @@ -93,7 +132,7 @@ impl Graph { 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?; + let obtained = state.evidence(view, &attempt, index).await?; let receipt = obtained.as_ref().map(|(_, receipt)| *receipt); if Some(recipient) == selected { output = obtained.map(|(value, _)| value); @@ -111,9 +150,14 @@ impl Graph { Some(RetainedOperation::Planned(Box::new(bound))) } Some(RetainedOperation::Prepared(prepared)) => { - let command = prepared.request().chat_command()?; - let mut keys = vec![command.context().actor().participant(), command.peer()]; - keys.sort_unstable(); + let mut keys = match prepared.request().command().chat() { + Some(command) => vec![ + SigningTarget::BusinessSeal(command.context().actor().participant()), + SigningTarget::BusinessSeal(command.peer()), + ], + None => vec![SigningTarget::PublicEvent], + }; + keys.sort_unstable_by_key(|target| target.key()); keys.dedup(); for recipient in keys { recipients.push(ArtifactSnapshot::from_store_report( @@ -139,9 +183,15 @@ impl Graph { .and_then(RetainedOperation::bound_plan) } pub(super) fn receipt(&self, recipient: PublicKey) -> Result<EvidenceReceipt, OperationError> { + self.receipt_target(SigningTarget::BusinessSeal(recipient)) + } + pub(super) fn receipt_target( + &self, + target: SigningTarget, + ) -> Result<EvidenceReceipt, OperationError> { self.recipients .iter() - .find(|value| value.target().recipient() == Some(recipient)) + .find(|value| value.target() == target) .and_then(|value| value.obtained()) .ok_or(OperationError::RecoveryRequired) } diff --git a/crates/storage_indexeddb/tests/browser/seller.mjs b/crates/storage_indexeddb/tests/browser/seller.mjs @@ -9,6 +9,8 @@ assert(moduleRoot && packageDir && previousPackageDir && ['chromium','firefox',' const playwright = createRequire(resolve(moduleRoot,'package.json'))('playwright'); const root = resolve(packageDir), previousRoot = resolve(previousPackageDir); async function workflow({WorkspaceFixture}, previous) { + let phase='legacy setup'; + try { const tests = []; const check = (condition) => { if (!condition) throw Error('seller scope assertion'); }; const refuses = async (action, code) => { @@ -27,6 +29,7 @@ async function workflow({WorkspaceFixture}, previous) { const originalClaim = Array.from(obtained.original_claim()); const originalCapture = Array.from(await old.capture(obtained)); await old.close(); + phase='published private reopen'; 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)); @@ -38,25 +41,87 @@ async function workflow({WorkspaceFixture}, previous) { await refuses(() => current.obtain(243, 0, false), 'retained_no_dispatch'); await current.close(); tests.push('original published buyer T0, T1, claim and obtained capture reopen without replacement or reissue'); + phase='seller public T0/T1'; 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 preparation = Array.from(await seller.admit(242, false)); + const publicPreparation=Array.from(await seller.admit_public(244)); + const publicPlan=Array.from(await seller.bind_public(244)); + check(JSON.stringify(Array.from(await seller.admit_public(244)))===JSON.stringify(publicPreparation)); + check(JSON.stringify(Array.from(await seller.bind_public(244)))===JSON.stringify(publicPlan)); + await refuses(()=>seller.admit_public(245),'stale_state'); + check((await seller.query(245)).length===0); + phase='public signing'; + const publicOutput=await seller.obtain(244,2,false); + check(publicOutput.malformed_output_refused()); + seller.set_time(2000); + phase='late public capture'; + const publicCapture=Array.from(await seller.capture(publicOutput)); + seller.set_time(1500); + phase='late public installation'; + const publicInstallation=await seller.install_public(244); + check(await seller.install_public(244)===publicInstallation); + check(JSON.parse(publicInstallation).observed===null); + check(JSON.parse(publicInstallation).installed_at==='1500'); + check(JSON.parse(publicInstallation).capture===publicCapture.slice(0,32).map(value=>value.toString(16).padStart(2,'0')).join('')); + tests.push('public T0/T1 replay, coordinate refusal, real verified S, late null-time capture and exactly-once T2 after signing expiry'); const fingerprint = seller.fingerprint(), selection = seller.selection(), proof = seller.proof(); - const preparation = Array.from(await seller.admit(244, false)); await seller.close(); - const reopened = await WorkspaceFixture.open(245, fingerprint, selection, proof); + phase='retained public reopen'; + let reopened = await WorkspaceFixture.open(245, fingerprint, selection, proof); + reopened.set_time(1500); check(await reopened.is_seller()); - check(JSON.stringify(Array.from(await reopened.query(244))) === JSON.stringify(preparation)); - tests.push('actual protected close/reopen retains seller scope and original preparation'); + check(JSON.stringify(Array.from(await reopened.query(242))) === JSON.stringify(preparation)); + check(JSON.stringify(Array.from(await reopened.query(244)))===JSON.stringify(publicPreparation)); + check(JSON.stringify(Array.from(await reopened.public_plan_query(244)))===JSON.stringify(publicPlan)); + check(await reopened.install_public(244)===publicInstallation); + check(JSON.stringify(Array.from(await reopened.captured(244,2)))===JSON.stringify(publicCapture)); + await refuses(()=>reopened.obtain(244,2,false),'retained_no_dispatch'); + tests.push('actual protected close/reopen retains seller scope and original private/public preparation and plan'); + const originalSnapshot=await reopened.public_snapshot(244); + const namespace=reopened.data_namespace(),coordinate=Array.from(await reopened.public_coordinate_key(244)); + const openRaw=()=>new Promise((resolve,reject)=>{const request=indexedDB.open(namespace,1);request.onsuccess=()=>resolve(request.result);request.onerror=reject;request.onupgradeneeded=()=>request.transaction.abort();}); + const readRows=async()=>{const db=await openRaw();try{return await new Promise((resolve,reject)=>{const tx=db.transaction('records','readonly'),store=tx.objectStore('records');let keys,values;store.getAllKeys().onsuccess=event=>keys=event.target.result;store.getAll().onsuccess=event=>values=event.target.result;tx.oncomplete=()=>resolve({keys,values});tx.onabort=reject;});}finally{db.close();}}; + const change=async callback=>{const db=await openRaw();try{await new Promise((resolve,reject)=>{const tx=db.transaction('records','readwrite');callback(tx.objectStore('records'));tx.oncomplete=resolve;tx.onabort=reject;});}finally{db.close();}}; + const bytes=value=>Array.from(new Uint8Array(value)); + const before=await readRows(),coordinateIndex=before.keys.findIndex(key=>JSON.stringify(bytes(key))===JSON.stringify(coordinate)); + check(coordinateIndex>=0); + const prefixInput=new Uint8Array([...new TextEncoder().encode('radroots.browser.local_outbox.operation.prefix.v2\0'),...new Uint8Array(32).fill(244)]); + const prefix=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',prefixInput)).slice(0,16)); + const at=kind=>before.keys.findIndex(key=>{const raw=bytes(key);return raw[16]===kind&&JSON.stringify(raw.slice(0,16))===JSON.stringify(prefix);}); + const claim=at(3),evidence=at(4),installed=at(10),work=at(11); + check([claim,evidence,installed,work].every(index=>index>=0)); + await reopened.close(); + const faults=[... [coordinateIndex,claim,evidence,installed,work].map(index=>({index})),{index:installed,replacement:work},{index:work,replacement:installed},{index:coordinateIndex,flip:true,fresh:true},{index:claim,move:true}]; + for(const fault of faults){ + phase='public corruption '+JSON.stringify(fault); + const key=before.keys[fault.index];let moved; + await change(store=>{ + if(fault.move){moved=new Uint8Array(key).slice();moved[17]=0;store.delete(key);store.put(before.values[fault.index],moved.buffer);} + else if(fault.flip){const value=new Uint8Array(before.values[fault.index]).slice();value[value.length-1]^=1;store.put(value.buffer,key);} + else if(fault.replacement!==undefined)store.put(before.values[fault.replacement],key); + else store.delete(key); + }); + const corrupted=await readRows(); + reopened=await WorkspaceFixture.open(245,fingerprint,selection,proof);reopened.set_time(fault.fresh?1000:1500); + await refuses(()=>fault.fresh?reopened.admit_public(245):reopened.public_snapshot(244),'recovery_required'); + await reopened.close(); + const unchanged=await readRows(); + check(JSON.stringify(unchanged.keys.map(bytes))===JSON.stringify(corrupted.keys.map(bytes))); + check(JSON.stringify(unchanged.values.map(bytes))===JSON.stringify(corrupted.values.map(bytes))); + phase+=' restore'; + await change(store=>{if(moved)store.delete(moved.buffer);store.put(before.values[fault.index],key);}); + reopened=await WorkspaceFixture.open(245,fingerprint,selection,proof);reopened.set_time(1500); + check(await reopened.public_snapshot(244)===originalSnapshot);await reopened.close(); + } + reopened=await WorkspaceFixture.open(245,fingerprint,selection,proof);reopened.set_time(1500); + tests.push('actual protected public predecessor deletion, cross-family replacement, corrupt coordinate and wrong-target records refuse without rewriting evidence'); + phase='expiry and revocation'; reopened.set_time(2000); await refuses(() => reopened.authenticate(), 'grant_expired'); - reopened.set_time(1000); + reopened.set_time(1500); await reopened.revoke(); await reopened.close(); await refuses(() => WorkspaceFixture.open(245, fingerprint, selection, proof), 'grant_revoked'); @@ -70,6 +135,7 @@ async function workflow({WorkspaceFixture}, previous) { await buyer.close(); tests.push('independent buyer enrollment retains buyer scope'); return tests; + } catch(error) { throw Error(phase+': '+String(error)); } } const source = `import init, * as fixture from '/fixture.js'; import previousInit, * as previous from '/before/fixture.js'; const run = ${workflow.toString()}; @@ -102,7 +168,7 @@ try { const tests = contextName === 'page' ? await page.evaluate(async code => { const fixture = await import('/fixture.js'); await fixture.default(); const previous = await import('/before/fixture.js'); await previous.default(); return await (0,eval)(`(${code})`)(fixture,previous); },workflow.toString()) : await page.evaluate(() => new Promise((done,fail) => { const worker = new Worker('/worker.mjs',{type:'module'}); const timer = setTimeout(() => { worker.terminate(); fail(Error('worker timeout')); },60_000); worker.onmessage = event => { clearTimeout(timer); worker.terminate(); event.data.error ? fail(Error(event.data.error)) : done(event.data.tests); }; worker.onerror = error => { clearTimeout(timer); worker.terminate(); fail(Error(error.message)); }; worker.postMessage({run:true}); })); - assert.equal(tests.length,5); + assert.equal(tests.length,6); results.push({context:contextName,tests}); console.error(JSON.stringify({engine,context:contextName,passed:tests.length})); } finally { await context.close(); } diff --git a/crates/storage_indexeddb/tests/browser/src/workspace.rs b/crates/storage_indexeddb/tests/browser/src/workspace.rs @@ -147,15 +147,19 @@ impl WorkspaceFixture { AdmissionOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")), } } - pub async fn admit_public(&self, n: u8) -> Result<(), JsValue> { + pub async fn admit_public(&self, n: u8) -> Result<Vec<u8>, JsValue> { let public = self.public_request(n).await?; - self.journal() + match 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")) + .map_err(|e| JsValue::from_str(e.code()))? + { + AdmissionOutcome::Committed(prepared) => Ok(summary(prepared)), + AdmissionOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")), + } } - pub async fn bind_public(&self, n: u8) -> Result<(), JsValue> { + pub async fn bind_public(&self, n: u8) -> Result<Vec<u8>, JsValue> { let public = self.public_request(n).await?; let plan = radroots_protocol::listing::PublicSigningPlan::capture( public.command().listing().unwrap(), @@ -164,11 +168,86 @@ impl WorkspaceFixture { radroots_protocol::plan::SigningReplay::NonReplayable, ) .unwrap(); - self.journal() + match 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")) + .map_err(|e| JsValue::from_str(e.code()))? + { + radroots_storage::command::PlanBindingOutcome::Committed(bound) => { + Ok(plans::summary(bound)) + } + radroots_storage::command::PlanBindingOutcome::Unknown(_) => { + Err(JsValue::from_str("commit_unknown")) + } + } + } + pub async fn public_plan_query(&self, n: u8) -> Result<Vec<u8>, JsValue> { + let request = self.public_request(n).await?; + self.journal() + .signing_plan( + request.binding().clone(), + request.command().context().operation_id(), + request.command().digest(), + copied(&self.proof), + ) + .await + .map(|v| v.map(plans::summary).unwrap_or_default()) + .map_err(|e| JsValue::from_str(e.code())) + } + pub async fn install_public(&self, n: u8) -> Result<String, JsValue> { + let request = self.public_request(n).await?; + let bound = self + .journal() + .signing_plan( + request.binding().clone(), + request.command().context().operation_id(), + request.command().digest(), + copied(&self.proof), + ) + .await + .map_err(|e| JsValue::from_str(e.code()))? + .ok_or_else(|| JsValue::from_str("missing_plan"))?; + let input = radroots_storage::command::InstallationRequest::new( + request.binding().clone(), + request.command().context().operation_id(), + request.command().digest(), + *bound.plan().digest(), + ); + match self.journal().install_transition_and_outbox(input,copied(&self.proof)).await.map_err(|e|JsValue::from_str(e.code()))?{ + radroots_storage::command::InstallationOutcome::ListingCommitted(value)=>Ok(serde_json::json!({"transaction":value.transaction_id().to_string(),"revision":value.revision().to_string(),"capture":value.basis().transaction_id().to_string(),"observed":value.basis().observed_at_unix_ms().map(|v|v.get()),"installed_at":value.installed_at().to_string()}).to_string()), + radroots_storage::command::InstallationOutcome::Unknown(_)=>Err(JsValue::from_str("commit_unknown")), + _=>Err(JsValue::from_str("unexpected_private_installation")), + } + } + pub async fn public_snapshot(&self, n: u8) -> Result<String, JsValue> { + let request = self.public_request(n).await?; + let snapshot = self + .journal() + .operation_snapshot( + request.binding().clone(), + request.command().context().operation_id(), + Some(request.command().digest()), + copied(&self.proof), + ) + .await + .map_err(|e| JsValue::from_str(e.code()))? + .ok_or_else(|| JsValue::from_str("missing_operation"))?; + Ok(serde_json::json!({"checkpoint":snapshot.checkpoint_digest().to_string(),"installation":snapshot.listing_installation().map(|v|v.transaction_id().to_string()),"publications":snapshot.public_publications().len()}).to_string()) + } + pub async fn public_coordinate_key(&self, n: u8) -> Result<Vec<u8>, JsValue> { + let request = self.public_request(n).await?; + let command = request.command(); + let listing = command + .listing() + .ok_or_else(|| JsValue::from_str("missing_listing"))?; + Ok(Sha256::new() + .chain_update(b"radroots.browser.local_outbox.listing_coordinate.v1\0") + .chain_update(self.input.workspace_id().as_bytes()) + .chain_update(self.input.participant().as_bytes()) + .chain_update(listing.input().id().as_bytes()) + .finalize() + .to_vec()) } pub async fn query(&self, n: u8) -> Result<Vec<u8>, JsValue> { let binding = self 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().unwrap().event_id()); + raw.extend_from_slice(&attempt.artifact().unwrap().event_id()); raw } fn receipt(value: EvidenceReceipt) -> Vec<u8> { @@ -35,7 +35,8 @@ fn signed_output( attempt: &SigningAttempt, observed: Option<NonZeroU64>, ) -> Result<ArtifactEvidence, JsValue> { - let fields = attempt.seal().unwrap().fields(); + let artifact = attempt.artifact().unwrap(); + let fields = artifact.fields(); let context = nostr::secp256k1::Secp256k1::new(); let mut scalar = [0; 32]; scalar[31] = 1; @@ -46,7 +47,13 @@ fn signed_output( pubkey: keys.public_key(), created_at: nostr::Timestamp::from_secs(fields.created_at), kind: nostr::Kind::Custom(u16::try_from(fields.kind).unwrap()), - tags: nostr::Tags::from_list(vec![]), + tags: nostr::Tags::from_list( + fields + .tags + .iter() + .map(|tag| nostr::Tag::parse(tag).unwrap()) + .collect(), + ), content: fields.content.to_owned(), } .sign_with_ctx(&context, &mut BrowserRng, &keys) @@ -93,7 +100,11 @@ impl ObtainedSeal { } impl WorkspaceFixture { async fn claim_request(&self, n: u8, index: u8) -> Result<ClaimAttemptRequest, JsValue> { - let request = self.request(n, false).await?; + let request = if index == 2 { + self.public_request(n).await? + } else { + self.request(n, false).await? + }; let bound = self .journal() .signing_plan( @@ -105,14 +116,19 @@ impl WorkspaceFixture { .await .map_err(|e| JsValue::from_str(e.code()))? .ok_or(JsValue::from_str("missing_plan"))?; - let recipient = bound - .chat_plan() - .unwrap() - .seals() - .get(index as usize) - .ok_or(JsValue::from_str("invalid_recipient"))? - .recipient(); - Ok(ClaimAttemptRequest::new( + let recipient = if index == 2 { + radroots_storage::command::SigningTarget::PublicEvent + } else { + bound + .chat_plan() + .unwrap() + .seals() + .get(index as usize) + .ok_or(JsValue::from_str("invalid_recipient"))? + .recipient() + .into() + }; + Ok(ClaimAttemptRequest::for_artifact( request.binding().clone(), request.command().context().operation_id(), request.command().digest(), diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/plans.rs b/crates/storage_indexeddb/tests/browser/src/workspace/plans.rs @@ -58,7 +58,7 @@ pub(super) fn delivery_relays(large: bool) -> Vec<String> { ] } } -fn summary(bound: BoundSigningPlan) -> Vec<u8> { +pub(super) 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());