lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

workspace.rs (28054B)


      1 //! Synthetic isolated host-effect fixture, never a production custody API.
      2 mod delivery;
      3 mod installation;
      4 mod issuance;
      5 mod observations;
      6 mod plans;
      7 pub use delivery::ObtainedEnvelope;
      8 use futures::FutureExt;
      9 pub use issuance::ObtainedSeal;
     10 pub use observations::ObtainedObservation;
     11 use radroots_domain::{
     12     ActorRole, CommandContextData, Coverage, OperationId, PublicKey, UnixSeconds, WorkspaceId,
     13 };
     14 use radroots_secrets::{
     15     SecretId, SecretRef,
     16     browser::BrowserProvider,
     17     id::{BackendKind, KeyVersion},
     18     provider::AccessPolicy,
     19 };
     20 use radroots_storage::{
     21     command::{AdmissionOutcome, AdmissionRequest, PreparedOperation},
     22     event::SourceGeneration,
     23     workspace::{AttachmentInput, AttachmentProof, WorkspaceClock, WorkspaceError, WorkspaceStore},
     24 };
     25 use radroots_storage_indexeddb::{
     26     Namespace,
     27     workspace::{BrowserWorkspace, LocalOutboxConfig},
     28 };
     29 use sha2::{Digest, Sha256};
     30 use std::{cell::Cell, rc::Rc};
     31 use wasm_bindgen::prelude::*;
     32 
     33 fn fail(e: WorkspaceError) -> JsValue {
     34     JsValue::from_str(e.code())
     35 }
     36 fn reference() -> SecretRef {
     37     SecretRef::new(
     38         SecretId::parse("workspace_fixture_key").unwrap(),
     39         BackendKind::External,
     40         KeyVersion::new(1).unwrap(),
     41     )
     42 }
     43 fn key_namespace(n: u8) -> SecretId {
     44     SecretId::parse(format!("workspace_fixture_{n}")).unwrap()
     45 }
     46 fn participant() -> PublicKey {
     47     PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap()
     48 }
     49 fn copied(proof: &AttachmentProof) -> AttachmentProof {
     50     proof.with_secret(|secret| AttachmentProof::from_protected_input(secret).unwrap())
     51 }
     52 struct Clock {
     53     now: Cell<u64>,
     54     after: Cell<Option<u64>>,
     55 }
     56 impl Clock {
     57     fn new() -> Self {
     58         Self {
     59             now: Cell::new(1000),
     60             after: Cell::new(None),
     61         }
     62     }
     63 }
     64 impl WorkspaceClock for Clock {
     65     fn now(&self) -> Result<UnixSeconds, WorkspaceError> {
     66         let now = self.now.get();
     67         if let Some(next) = self.after.take() {
     68             self.now.set(next);
     69         }
     70         if now == 0 {
     71             return Err(WorkspaceError::Unavailable);
     72         }
     73         UnixSeconds::new(now).map_err(|_| WorkspaceError::Unavailable)
     74     }
     75 }
     76 #[wasm_bindgen]
     77 pub struct WorkspaceFixture {
     78     owner: BrowserWorkspace,
     79     provider: Rc<BrowserProvider>,
     80     input: AttachmentInput,
     81     proof: AttachmentProof,
     82     clock: Rc<Clock>,
     83 }
     84 impl WorkspaceFixture {
     85     fn journal(&self) -> &dyn radroots_storage::command::OperationJournal {
     86         &self.owner
     87     }
     88 }
     89 #[wasm_bindgen]
     90 impl WorkspaceFixture {
     91     pub async fn admit_read_unknown(
     92         &self,
     93         n: u8,
     94         hook: js_sys::Function,
     95     ) -> Result<Vec<u8>, JsValue> {
     96         let request = self.request(n, false).await?;
     97         let digest = request.command().digest();
     98         hook.call0(&JsValue::NULL)?;
     99         match self
    100             .journal()
    101             .admit_command_and_hold(request, copied(&self.proof))
    102             .await
    103             .map_err(|e| JsValue::from_str(e.code()))?
    104         {
    105             AdmissionOutcome::Committed(_) => Err(JsValue::from_str("unexpected_commit")),
    106             AdmissionOutcome::Unknown(anchor) => {
    107                 assert_eq!(anchor.workspace_id(), self.input.workspace_id());
    108                 assert_eq!(anchor.operation_id(), OperationId::from_bytes([n; 32]));
    109                 assert_eq!(anchor.command_digest(), digest);
    110                 assert_eq!(anchor.transaction_id(), None);
    111                 let mut bytes = anchor.operation_id().as_bytes().to_vec();
    112                 bytes.extend_from_slice(anchor.command_digest().as_bytes());
    113                 Ok(bytes)
    114             }
    115         }
    116     }
    117     pub async fn admit_uncertain(&self, n: u8) -> Result<Vec<u8>, JsValue> {
    118         let request = self.request(n, false).await?;
    119         let digest = request.command().digest();
    120         match self
    121             .journal()
    122             .admit_command_and_hold(request, copied(&self.proof))
    123             .await
    124             .map_err(|e| JsValue::from_str(e.code()))?
    125         {
    126             AdmissionOutcome::Committed(_) => Err(JsValue::from_str("unexpected_commit")),
    127             AdmissionOutcome::Unknown(anchor) => {
    128                 assert_eq!(anchor.workspace_id(), self.input.workspace_id());
    129                 assert_eq!(anchor.operation_id(), OperationId::from_bytes([n; 32]));
    130                 assert_eq!(anchor.command_digest(), digest);
    131                 let mut bytes = anchor.operation_id().as_bytes().to_vec();
    132                 bytes.extend_from_slice(anchor.command_digest().as_bytes());
    133                 bytes.extend_from_slice(anchor.transaction_id().unwrap().as_bytes());
    134                 Ok(bytes)
    135             }
    136         }
    137     }
    138     pub async fn admit(&self, n: u8, changed: bool) -> Result<Vec<u8>, JsValue> {
    139         let request = self.request(n, changed).await?;
    140         match self
    141             .journal()
    142             .admit_command_and_hold(request, copied(&self.proof))
    143             .await
    144             .map_err(|e| JsValue::from_str(e.code()))?
    145         {
    146             AdmissionOutcome::Committed(prepared) => Ok(summary(prepared)),
    147             AdmissionOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")),
    148         }
    149     }
    150     pub async fn admit_public(&self, n: u8) -> Result<Vec<u8>, JsValue> {
    151         let public = self.public_request(n).await?;
    152         match self
    153             .journal()
    154             .admit_command_and_hold(public, copied(&self.proof))
    155             .await
    156             .map_err(|e| JsValue::from_str(e.code()))?
    157         {
    158             AdmissionOutcome::Committed(prepared) => Ok(summary(prepared)),
    159             AdmissionOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")),
    160         }
    161     }
    162     pub async fn bind_public(&self, n: u8) -> Result<Vec<u8>, JsValue> {
    163         let public = self.public_request(n).await?;
    164         let plan = radroots_protocol::listing::PublicSigningPlan::capture(
    165             public.command().listing().unwrap(),
    166             UnixSeconds::new(1000).unwrap(),
    167             &["wss://public-plan.fixture.example/a".to_string()],
    168             radroots_protocol::intent::SigningReplay::NonReplayable,
    169         )
    170         .unwrap();
    171         match self
    172             .journal()
    173             .bind_signing_intents(public.binding().clone(), plan.into(), copied(&self.proof))
    174             .await
    175             .map_err(|e| JsValue::from_str(e.code()))?
    176         {
    177             radroots_storage::command::PlanBindingOutcome::Committed(bound) => {
    178                 Ok(plans::summary(bound))
    179             }
    180             radroots_storage::command::PlanBindingOutcome::Unknown(_) => {
    181                 Err(JsValue::from_str("commit_unknown"))
    182             }
    183         }
    184     }
    185     pub async fn public_plan_query(&self, n: u8) -> Result<Vec<u8>, JsValue> {
    186         let request = self.public_request(n).await?;
    187         self.journal()
    188             .signing_plan(
    189                 request.binding().clone(),
    190                 request.command().context().operation_id(),
    191                 request.command().digest(),
    192                 copied(&self.proof),
    193             )
    194             .await
    195             .map(|v| v.map(plans::summary).unwrap_or_default())
    196             .map_err(|e| JsValue::from_str(e.code()))
    197     }
    198     pub async fn install_public(&self, n: u8) -> Result<String, JsValue> {
    199         let request = self.public_request(n).await?;
    200         let bound = self
    201             .journal()
    202             .signing_plan(
    203                 request.binding().clone(),
    204                 request.command().context().operation_id(),
    205                 request.command().digest(),
    206                 copied(&self.proof),
    207             )
    208             .await
    209             .map_err(|e| JsValue::from_str(e.code()))?
    210             .ok_or_else(|| JsValue::from_str("missing_plan"))?;
    211         let input = radroots_storage::command::InstallationRequest::new(
    212             request.binding().clone(),
    213             request.command().context().operation_id(),
    214             request.command().digest(),
    215             *bound.plan().digest(),
    216         );
    217         match self.journal().install_transition_and_outbox(input,copied(&self.proof)).await.map_err(|e|JsValue::from_str(e.code()))?{
    218             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()),
    219             radroots_storage::command::InstallationOutcome::Unknown(_)=>Err(JsValue::from_str("commit_unknown")),
    220             _=>Err(JsValue::from_str("unexpected_private_installation")),
    221         }
    222     }
    223     pub async fn public_snapshot(&self, n: u8) -> Result<String, JsValue> {
    224         let request = self.public_request(n).await?;
    225         let snapshot = self
    226             .journal()
    227             .operation_snapshot(
    228                 request.binding().clone(),
    229                 request.command().context().operation_id(),
    230                 Some(request.command().digest()),
    231                 copied(&self.proof),
    232             )
    233             .await
    234             .map_err(|e| JsValue::from_str(e.code()))?
    235             .ok_or_else(|| JsValue::from_str("missing_operation"))?;
    236         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())
    237     }
    238     pub async fn public_coordinate_key(&self, n: u8) -> Result<Vec<u8>, JsValue> {
    239         let request = self.public_request(n).await?;
    240         let command = request.command();
    241         let listing = command
    242             .listing()
    243             .ok_or_else(|| JsValue::from_str("missing_listing"))?;
    244         Ok(Sha256::new()
    245             .chain_update(b"radroots.browser.local_outbox.listing_coordinate.v1\0")
    246             .chain_update(self.input.workspace_id().as_bytes())
    247             .chain_update(self.input.participant().as_bytes())
    248             .chain_update(listing.input().id().as_bytes())
    249             .finalize()
    250             .to_vec())
    251     }
    252     pub async fn query(&self, n: u8) -> Result<Vec<u8>, JsValue> {
    253         let binding = self
    254             .owner
    255             .authenticate(self.input.clone(), copied(&self.proof))
    256             .await
    257             .map_err(fail)?;
    258         let result = self
    259             .journal()
    260             .operation(
    261                 binding,
    262                 OperationId::from_bytes([n; 32]),
    263                 None,
    264                 copied(&self.proof),
    265             )
    266             .await
    267             .map_err(|e| JsValue::from_str(e.code()))?;
    268         Ok(result.map(summary).unwrap_or_default())
    269     }
    270     pub async fn admit_expiring(&self, n: u8) -> Result<(), JsValue> {
    271         let request = self.request(n, false).await?;
    272         self.clock.after.set(Some(1500));
    273         self.journal()
    274             .admit_command_and_hold(request, copied(&self.proof))
    275             .await
    276             .map(|_| ())
    277             .map_err(|e| JsValue::from_str(e.code()))
    278     }
    279     pub async fn abandon_admission(&self, n: u8) -> Result<(), JsValue> {
    280         let request = self.request(n, false).await?;
    281         if self
    282             .journal()
    283             .admit_command_and_hold(request, copied(&self.proof))
    284             .now_or_never()
    285             .is_some()
    286         {
    287             return Err(JsValue::from_str("unexpected_immediate_admission"));
    288         }
    289         Ok(())
    290     }
    291     pub async fn sibling(&self) -> Result<Self, JsValue> {
    292         let clock = Rc::new(Clock::new());
    293         let config = LocalOutboxConfig::new(
    294             participant(),
    295             participant(),
    296             "synthetic-browser",
    297             UnixSeconds::new(2000).unwrap(),
    298         )
    299         .map_err(fail)?;
    300         let (owner, input, proof) = BrowserWorkspace::initialize_local_outbox(
    301             config,
    302             self.provider.clone(),
    303             reference(),
    304             AccessPolicy::standard(),
    305             clock.clone(),
    306         )
    307         .await
    308         .map_err(fail)?;
    309         Ok(Self {
    310             owner,
    311             provider: self.provider.clone(),
    312             input,
    313             proof,
    314             clock,
    315         })
    316     }
    317     pub async fn create(n: u8) -> Result<Self, JsValue> {
    318         Self::initialize(n, false, false).await
    319     }
    320     pub async fn create_seller(n: u8) -> Result<Self, JsValue> {
    321         Self::initialize(n, false, true).await
    322     }
    323     pub async fn create_expiring(n: u8) -> Result<(), JsValue> {
    324         let owner = Self::initialize(n, true, false).await?;
    325         owner.close().await
    326     }
    327     pub async fn open(
    328         n: u8,
    329         fingerprint: Vec<u8>,
    330         selection: Vec<u8>,
    331         proof: Vec<u8>,
    332     ) -> Result<Self, JsValue> {
    333         Self::open_fixture(n, fingerprint, selection, proof, false).await
    334     }
    335     pub async fn open_capture(
    336         n: u8,
    337         fingerprint: Vec<u8>,
    338         selection: Vec<u8>,
    339         proof: Vec<u8>,
    340     ) -> Result<Self, JsValue> {
    341         Self::open_fixture(n, fingerprint, selection, proof, true).await
    342     }
    343     pub fn selection(&self) -> Vec<u8> {
    344         serde_json::to_vec(&self.input).unwrap()
    345     }
    346     pub fn proof(&self) -> Vec<u8> {
    347         self.proof.with_secret(|bytes| bytes.to_vec())
    348     }
    349     pub fn fingerprint(&self) -> Vec<u8> {
    350         self.provider.fingerprint().to_vec()
    351     }
    352     pub fn data_namespace(&self) -> String {
    353         let mut h = Sha256::new();
    354         h.update(b"radroots.browser.local_outbox.namespace.v2\0");
    355         h.update(self.input.workspace_id().as_bytes());
    356         Namespace::new(SourceGeneration::new(h.finalize().into()).unwrap()).name()
    357     }
    358     pub fn set_time(&self, now: u32) {
    359         self.clock.now.set(now as u64);
    360     }
    361     pub fn expire_after_next_read(&self) {
    362         self.clock.after.set(Some(2000));
    363     }
    364     pub async fn authenticate(&self) -> Result<u32, JsValue> {
    365         let bound = self
    366             .owner
    367             .authenticate(self.input.clone(), copied(&self.proof))
    368             .await
    369             .map_err(fail)?;
    370         assert_eq!(
    371             bound.actor().role(),
    372             match bound.scope() {
    373                 radroots_storage::workspace::WorkspaceScope::NewBuyerOutbox => ActorRole::Buyer,
    374                 radroots_storage::workspace::WorkspaceScope::NewSellerOutbox => ActorRole::Seller,
    375                 radroots_storage::workspace::WorkspaceScope::SellerStockOwner => {
    376                     panic!("ordinary browser outbox admitted a stock-owner scope")
    377                 }
    378             }
    379         );
    380         assert_eq!(bound.actor().organization(), None);
    381         assert_eq!(bound.input(), &self.input);
    382         assert_eq!(bound.actor().grant_id(), Some(self.input.grant_id()));
    383         assert_eq!(bound.input().checkpoint().coverage(), Coverage::Partial);
    384         Ok(bound.grant_revision().get() as u32)
    385     }
    386     pub async fn is_seller(&self) -> Result<bool, JsValue> {
    387         let bound = self
    388             .owner
    389             .authenticate(self.input.clone(), copied(&self.proof))
    390             .await
    391             .map_err(fail)?;
    392         Ok(
    393             bound.scope() == radroots_storage::workspace::WorkspaceScope::NewSellerOutbox
    394                 && bound.actor().role() == ActorRole::Seller,
    395         )
    396     }
    397     /// Synthetic fault bytes for ordinary-outbox scope admission tests.
    398     pub async fn stock_scope_bytes(&self, material: Vec<u8>) -> Result<Vec<u8>, JsValue> {
    399         use radroots_secrets::{
    400             EncryptedEnvelope,
    401             context::{EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId},
    402             envelope::{Nonce, SealMaterial, SealRequest},
    403             wrapping::SecretMaterial,
    404         };
    405         use radroots_storage::workspace::{WorkspaceScope, grant::WorkspaceGrant};
    406         if material.len() != 56 {
    407             return Err(JsValue::from_str("invalid_fixture_material"));
    408         }
    409         let binding = self
    410             .owner
    411             .authenticate(self.input.clone(), copied(&self.proof))
    412             .await
    413             .map_err(fail)?;
    414         if binding.scope() != WorkspaceScope::NewSellerOutbox {
    415             return Err(JsValue::from_str("seller_fixture_required"));
    416         }
    417         let (input, _, grant) = LocalOutboxConfig::seller(
    418             self.input.participant(),
    419             self.input.endpoint_identity(),
    420             binding.principal_id(),
    421             binding.expires_at(),
    422         )
    423         .map_err(fail)?
    424         .enroll(
    425             binding.observed_at(),
    426             self.input.workspace_id(),
    427             self.input.authority().executor_id(),
    428             self.input.grant_id(),
    429             copied(&self.proof),
    430         )
    431         .map_err(fail)?;
    432         assert_eq!(input, self.input);
    433         let mut wire: serde_json::Value =
    434             serde_json::from_slice(&grant.encode().map_err(fail)?).unwrap();
    435         wire["scope"] = serde_json::json!("seller_stock_owner");
    436         let mut verifier = Sha256::new();
    437         verifier.update(b"radroots.seller_stock.credential.v1\0");
    438         verifier.update(self.input.workspace_id().as_bytes());
    439         verifier.update(self.input.grant_id().as_bytes());
    440         self.proof.with_secret(|secret| verifier.update(secret));
    441         wire["verifier"] = serde_json::json!(<[u8; 32]>::from(verifier.finalize()));
    442         let encoded = serde_json::to_vec(&wire).unwrap();
    443         let claim = WorkspaceGrant::decode(&encoded).map_err(fail)?;
    444         assert_eq!(
    445             claim
    446                 .authenticate(&self.input, &self.proof, binding.observed_at())
    447                 .map_err(fail)?
    448                 .scope(),
    449             WorkspaceScope::SellerStockOwner
    450         );
    451         let context = EnvelopeContext::new(
    452             EnvelopePurpose::parse("radroots.browser.workspace.grant").unwrap(),
    453             EnvelopeSubject::parse(
    454                 "workspace_grant",
    455                 format!("{}{}", self.input.workspace_id(), self.input.grant_id()),
    456             )
    457             .unwrap(),
    458             PayloadSchemaId::parse("radroots.browser.workspace.grant.v2").unwrap(),
    459         );
    460         let plaintext = SecretMaterial::from_slice(&encoded).unwrap();
    461         let expected = context.clone();
    462         let envelope = EncryptedEnvelope::seal(
    463             self.provider.as_ref(),
    464             SealRequest::new(
    465                 reference(),
    466                 context,
    467                 &plaintext,
    468                 SealMaterial::new(
    469                     SecretMaterial::from_slice(&material[..32]).unwrap(),
    470                     Nonce::new(material[32..].try_into().unwrap()),
    471                 ),
    472             ),
    473         )
    474         .await
    475         .map_err(|_| JsValue::from_str("fixture_seal_failed"))?;
    476         let verified = envelope
    477             .open(self.provider.as_ref(), &expected)
    478             .await
    479             .map_err(|_| JsValue::from_str("fixture_open_failed"))?;
    480         let verified_claim = verified
    481             .expose_secret(WorkspaceGrant::decode)
    482             .map_err(fail)?;
    483         assert_eq!(
    484             verified_claim
    485                 .authenticate(&self.input, &self.proof, binding.observed_at())
    486                 .map_err(fail)?
    487                 .scope(),
    488             WorkspaceScope::SellerStockOwner
    489         );
    490         envelope
    491             .encode()
    492             .map_err(|_| JsValue::from_str("fixture_encode_failed"))
    493     }
    494     pub async fn wrong_proof(&self) -> Result<(), JsValue> {
    495         self.owner
    496             .authenticate(
    497                 self.input.clone(),
    498                 AttachmentProof::from_protected_input(&[0x31; 32]).unwrap(),
    499             )
    500             .await
    501             .map(|_| ())
    502             .map_err(fail)
    503     }
    504     pub async fn wrong_selection(&self) -> Result<(), JsValue> {
    505         let wrong = AttachmentInput::new(
    506             WorkspaceId::from_bytes([3; 32]),
    507             self.input.authority(),
    508             self.input.participant(),
    509             self.input.endpoint(),
    510             self.input.endpoint_identity(),
    511             self.input.grant_id(),
    512             self.input.checkpoint().clone(),
    513             self.input.route_digest(),
    514         )
    515         .unwrap();
    516         self.owner
    517             .authenticate(wrong, copied(&self.proof))
    518             .await
    519             .map(|_| ())
    520             .map_err(fail)
    521     }
    522     pub async fn contended_open(&self) -> Result<(), JsValue> {
    523         let owner = BrowserWorkspace::open_existing(
    524             self.input.clone(),
    525             copied(&self.proof),
    526             self.provider.clone(),
    527             reference(),
    528             AccessPolicy::standard(),
    529             self.clock.clone(),
    530         )
    531         .await
    532         .map_err(fail)?;
    533         owner.close().await.map_err(fail)
    534     }
    535     pub async fn revoke(&self) -> Result<(), JsValue> {
    536         self.owner
    537             .revoke(self.input.clone(), copied(&self.proof))
    538             .await
    539             .map_err(fail)
    540     }
    541     pub fn abandon_auths(&self, count: u32) -> Result<u32, JsValue> {
    542         for n in 0..count {
    543             if let Some(result) = self
    544                 .owner
    545                 .authenticate(self.input.clone(), copied(&self.proof))
    546                 .now_or_never()
    547             {
    548                 return if matches!(result, Err(WorkspaceError::Capacity)) {
    549                     Ok(n)
    550                 } else {
    551                     Err(JsValue::from_str("unexpected_immediate_auth"))
    552                 };
    553             }
    554         }
    555         Ok(count)
    556     }
    557     pub fn abandon_close(&self) -> Result<(), JsValue> {
    558         if self.owner.close().now_or_never().is_some() {
    559             return Err(JsValue::from_str("unexpected_immediate_workspace_close"));
    560         }
    561         Ok(())
    562     }
    563     pub async fn close(&self) -> Result<(), JsValue> {
    564         self.owner.close().await.map_err(fail)
    565     }
    566 }
    567 impl WorkspaceFixture {
    568     async fn open_fixture(
    569         n: u8,
    570         fingerprint: Vec<u8>,
    571         selection: Vec<u8>,
    572         proof: Vec<u8>,
    573         capture_only: bool,
    574     ) -> Result<Self, JsValue> {
    575         if selection.len() > 16 * 1024 {
    576             return Err(JsValue::from_str("oversized_selection"));
    577         }
    578         let input: AttachmentInput = serde_json::from_slice(&selection)
    579             .map_err(|_| JsValue::from_str("invalid_selection"))?;
    580         let proof = AttachmentProof::from_protected_input(&proof).map_err(fail)?;
    581         let fingerprint = fingerprint
    582             .as_slice()
    583             .try_into()
    584             .map_err(|_| JsValue::from_str("invalid_fingerprint"))?;
    585         let provider = Rc::new(
    586             BrowserProvider::open(key_namespace(n), reference(), fingerprint)
    587                 .await
    588                 .map_err(|e| JsValue::from_str(e.code()))?,
    589         );
    590         let clock = Rc::new(Clock::new());
    591         let owner = if capture_only {
    592             BrowserWorkspace::open_existing_for_capture(
    593                 input.clone(),
    594                 copied(&proof),
    595                 provider.clone(),
    596                 reference(),
    597                 AccessPolicy::standard(),
    598                 clock.clone(),
    599             )
    600             .await
    601         } else {
    602             BrowserWorkspace::open_existing(
    603                 input.clone(),
    604                 copied(&proof),
    605                 provider.clone(),
    606                 reference(),
    607                 AccessPolicy::standard(),
    608                 clock.clone(),
    609             )
    610             .await
    611         }
    612         .map_err(fail)?;
    613         Ok(Self {
    614             owner,
    615             provider,
    616             input,
    617             proof,
    618             clock,
    619         })
    620     }
    621     async fn public_request(&self, n: u8) -> Result<AdmissionRequest, JsValue> {
    622         let request = self.request(n, false).await?;
    623         let input = serde_json::json!({"id":"01".repeat(16),"title":"Carrots","summary":"Quote required",
    624             "description_markdown":"Public terms","published_at":"1000","profile":{
    625             "profile":"radroots.listing","version":1,"state":"active",
    626             "product":{"name":"Carrots","description":"","producer":null,"origin_summary":null},
    627             "default_option":"02".repeat(32),"options":[{"id":"02".repeat(32),"label":"One bunch",
    628             "unit":{"type":"package","label":"bunch","contents":{"type":"unspecified"}},
    629             "increment":"1","minimum":"1","price":{"type":"quote_required"},
    630             "supply":{"type":"unknown"},"lead_seconds":"0"}],
    631             "fulfillment":{"modes":["pickup"],"area":"Example region","lead_seconds":"0"},
    632             "authority":null,"media":[]}});
    633         let wire = serde_json::to_vec(&serde_json::json!({"type":"listing.publish",
    634             "context":request.command().context(),"input":input}))
    635         .unwrap();
    636         let public = AdmissionRequest::from_protected_wire(request.binding().clone(), &wire)
    637             .map_err(|e| JsValue::from_str(e.code()))?;
    638         Ok(public)
    639     }
    640     async fn request(&self, n: u8, changed: bool) -> Result<AdmissionRequest, JsValue> {
    641         let binding = self
    642             .owner
    643             .authenticate(self.input.clone(), copied(&self.proof))
    644             .await
    645             .map_err(fail)?;
    646         let context = CommandContextData::new(
    647             OperationId::from_bytes([n; 32]),
    648             binding.actor(),
    649             self.input.workspace_id(),
    650             self.input.authority(),
    651             self.input.route_digest(),
    652             None,
    653             None,
    654             UnixSeconds::new(1500).unwrap(),
    655             None,
    656         )
    657         .unwrap();
    658         // Escaped control bytes exercise multiple private-record parts without
    659         // exceeding the shared 4096-byte chat text limit.
    660         let text = if changed {
    661             "changed".to_string()
    662         } else {
    663             // T1 additionally constructs the bounded complete rumor, whose
    664             // JSON framing must fit alongside the escaped text. Preserve the
    665             // earlier T0-only maximum-input cases exactly.
    666             "\u{0001}".repeat(if n >= 180 { 3000 } else { 4096 })
    667         };
    668         let peer = if n >= 180 {
    669             PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5")
    670                 .unwrap()
    671         } else {
    672             participant()
    673         };
    674         let wire = serde_json::to_vec(
    675             &serde_json::json!({"type":"inbox.inquire","context":context,
    676             "input":{"thread_id":"66".repeat(32),"peer":peer,"source":null,"text":text}}),
    677         )
    678         .unwrap();
    679         AdmissionRequest::from_protected_wire(binding, &wire)
    680             .map_err(|e| JsValue::from_str(e.code()))
    681     }
    682     async fn initialize(n: u8, expire: bool, seller: bool) -> Result<Self, JsValue> {
    683         let provider = Rc::new(
    684             BrowserProvider::create(key_namespace(n), reference())
    685                 .await
    686                 .map_err(|e| JsValue::from_str(e.code()))?,
    687         );
    688         let clock = Rc::new(Clock::new());
    689         if expire {
    690             clock.after.set(Some(2000));
    691         }
    692         let constructor = if seller {
    693             LocalOutboxConfig::seller
    694         } else {
    695             LocalOutboxConfig::new
    696         };
    697         let config = constructor(
    698             participant(),
    699             participant(),
    700             "synthetic-browser",
    701             UnixSeconds::new(2000).unwrap(),
    702         )
    703         .map_err(fail)?;
    704         let (owner, input, proof) = BrowserWorkspace::initialize_local_outbox(
    705             config,
    706             provider.clone(),
    707             reference(),
    708             AccessPolicy::standard(),
    709             clock.clone(),
    710         )
    711         .await
    712         .map_err(fail)?;
    713         Ok(Self {
    714             owner,
    715             provider,
    716             input,
    717             proof,
    718             clock,
    719         })
    720     }
    721 }
    722 fn summary(prepared: PreparedOperation) -> Vec<u8> {
    723     let mut bytes = prepared.transaction_id().as_bytes().to_vec();
    724     bytes.extend_from_slice(prepared.request().command().digest().as_bytes());
    725     bytes.extend_from_slice(&prepared.issuance_window().prepared_at().get().to_be_bytes());
    726     bytes.extend_from_slice(
    727         &prepared
    728             .issuance_window()
    729             .first_issue_not_after()
    730             .get()
    731             .to_be_bytes(),
    732     );
    733     bytes
    734 }