lib

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

commit 0ba661c25ae701ebbf40f574a02074cf3c035420
parent 9cbae6a094ba50de951e0de28e5ed974829ff3e4
Author: triesap <tyson@radroots.org>
Date:   Wed, 21 Oct 2026 05:23:14 +0000

browser: expose generated origin-thread client calls

- Delegate listing, inquiry and retained-operation calls to the shared client.
- Preserve exact typed values, receipt axes, scope checks and bounded capture.
- Qualify a packed TypeScript fixture in browser pages and dedicated workers.
- Verify native mechanics, strict lint, source policies and generated freshness.

Diffstat:
MCargo.lock | 2++
Mcrates/radroots_browser/Cargo.toml | 2++
Mcrates/radroots_browser/README.md | 23++++++++++++++++++++---
Acrates/radroots_browser/src/bindings/client.rs | 137+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/radroots_browser/src/bindings/error.rs | 155+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/radroots_browser/src/bindings/inputs.rs | 185+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/radroots_browser/src/bindings/mod.rs | 20++++++++++++++++++++
Acrates/radroots_browser/src/bindings/receipt.rs | 377+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/radroots_browser/src/bindings/states.rs | 130+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/radroots_browser/src/bindings/values.rs | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/radroots_browser/src/lib.rs | 2++
Mcrates/radroots_browser/tests/browser/Cargo.lock | 2++
Acrates/radroots_browser/tests/browser/consumer.ts | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/radroots_browser/tests/browser/pack.mjs | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/radroots_browser/tests/browser/packed.mjs | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/radroots_browser/tests/browser/src/binding_fixture.rs | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/radroots_browser/tests/browser/src/lib.rs | 1+
17 files changed, 1603 insertions(+), 3 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -3122,10 +3122,12 @@ dependencies = [ "radroots_transport", "radroots_transport_nostr", "radroots_transport_nostr_browser", + "serde_json", "universal-time", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "zeroize", ] [[package]] diff --git a/crates/radroots_browser/Cargo.toml b/crates/radroots_browser/Cargo.toml @@ -34,6 +34,8 @@ radroots_nostr = { workspace = true, features = ["signing", "nip17"] } radroots_protocol = { workspace = true, features = ["chat", "listing"] } radroots_secrets = { workspace = true, features = ["browser"] } js-sys = { workspace = true } +serde_json = { workspace = true, features = ["std"] } +zeroize = { workspace = true, features = ["alloc"] } wasm-bindgen = { workspace = true } wasm-bindgen-futures = { workspace = true } web-sys = { workspace = true, features = ["Crypto"] } diff --git a/crates/radroots_browser/README.md b/crates/radroots_browser/README.md @@ -25,6 +25,23 @@ and `Date.now`; do not combine it with another provider selection. Importing the module and constructing configuration perform no I/O. Native targets compile only host-independent task mechanics, not a browser client or fallback store. -This private implementation is not yet a packed browser distribution. Generated -JavaScript calls, scoped worker signer bridges and clean artifact installation -require their own executable qualification. +The `bindings` module generates local JavaScript handles and TypeScript +declarations for listing, inquiry, operation observation/resume and explicit +lifecycle calls. Its Rust constructors accept actual configured client and +authenticated workspace handles. Foreign descriptors cannot create workspace +authority. Inputs use the shared bounded parsers; IDs and times remain exact +strings. Owned typed results retain independent admission, installation, +issuance, delivery, wait, recovery and per-target provenance. String +admission bounds UTF-16 before a Rust copy, rejects unpaired surrogates and +checks the exact UTF-8 budget. Listing bytes are bounded before copying into +WASM memory. Shared parsers remain the semantic authority. Presentation text +copies have the foreign caller's lifetime; Rust retains zeroizing private data. +Close the client explicitly before releasing its handles. Dropping or freeing +one foreign wrapper does not complete asynchronous resource closure or undo +accepted commands. + +The browser test package packs generated exports with a clearly synthetic +Rust-authenticated host fixture for neutral TypeScript page/worker calls. That +fixture is not a general host/custody factory or the complete SDK distribution. +Scoped worker signer bridges and complete distribution remain separately +qualified work. diff --git a/crates/radroots_browser/src/bindings/client.rs b/crates/radroots_browser/src/bindings/client.rs @@ -0,0 +1,137 @@ +use super::inputs::bounded_string; +use super::{CommandRequest, Error, InquiryInput, ListingInput, Receipt, SessionState, StartMode}; +use js_sys::JsString; +use radroots_domain::{CommandDigest, OperationId}; +use wasm_bindgen::prelude::*; + +/// One actual origin-thread client. Foreign calls add no task owner or runtime. +#[derive(Clone)] +#[wasm_bindgen(js_name = Client)] +pub struct BrowserClient { + inner: crate::Client, +} +impl BrowserClient { + /// Injects the explicitly configured actual browser client without starting it. + pub fn from_browser(inner: crate::Client) -> Self { + Self { inner } + } +} +/// Actual authenticated shared scope, never constructed from a JS descriptor. +#[derive(Clone)] +#[wasm_bindgen] +pub struct Workspace { + inner: crate::WorkspaceSession, +} +impl Workspace { + /// Injects an actual shared-client attachment; ownership is rechecked on use. + pub fn from_session(inner: crate::WorkspaceSession) -> Self { + Self { inner } + } +} +#[wasm_bindgen] +impl Workspace { + /// Releases the attachment credential root without revoking the grant. + pub fn close(&self) { + self.inner.close(); + } +} +#[wasm_bindgen(js_class = Client)] +impl BrowserClient { + pub fn state(&self) -> SessionState { + self.inner.state().into() + } + pub async fn start(&self, mode: StartMode) -> Result<SessionState, JsValue> { + self.inner + .start(mode.into()) + .await + .map(Into::into) + .map_err(|v| Error::from(v).into()) + } + /// Resolves only after actual owned tasks, callbacks and storage close. + pub async fn close(&self) -> Result<(), JsValue> { + self.inner + .close() + .await + .map(|_| ()) + .map_err(|v| Error::from(v).into()) + } + pub async fn publish_listing( + &self, + workspace: &Workspace, + request: &CommandRequest, + input: &ListingInput, + ) -> Result<Receipt, JsValue> { + let context = request.capture(&workspace.inner)?; + let value = self + .inner + .listings() + .publish(context, input.inner.clone()) + .await + .map_err(Error::from)?; + Receipt::listing(&value).map_err(Into::into) + } + pub async fn inquire( + &self, + workspace: &Workspace, + request: &CommandRequest, + input: &InquiryInput, + ) -> Result<Receipt, JsValue> { + let context = request.capture(&workspace.inner)?; + let value = self + .inner + .inbox() + .inquire(context, input.captured_copy()?) + .await + .map_err(Error::from)?; + Receipt::chat(&value).map_err(Into::into) + } + /// Scoped observation; absence never proves safe nonissuance. + pub async fn operation( + &self, + workspace: &Workspace, + operation_id: JsString, + expected_digest: Option<JsString>, + ) -> Result<Option<Receipt>, JsValue> { + let (id, expected) = selector(operation_id, expected_digest)?; + self.inner + .operations(&workspace.inner) + .get_matching(id, expected) + .await + .map_err(Error::from)? + .as_ref() + .map(Receipt::status) + .transpose() + .map_err(Into::into) + } + /// Explicitly continues original retained work, without reissuing a claim. + pub async fn resume( + &self, + workspace: &Workspace, + operation_id: JsString, + expected_digest: Option<JsString>, + ) -> Result<Receipt, JsValue> { + let (id, expected) = selector(operation_id, expected_digest)?; + let value = self + .inner + .operations(&workspace.inner) + .resume(id, expected) + .await + .map_err(Error::from)?; + Receipt::status(&value).map_err(Into::into) + } +} +fn selector( + operation: JsString, + expected: Option<JsString>, +) -> Result<(OperationId, Option<CommandDigest>), Error> { + let operation = bounded_string(operation, 64, "operation_id")? + .parse() + .map_err(|_| Error::input("operation_id"))?; + let expected = expected + .map(|v| { + bounded_string(v, 64, "command_digest") + .and_then(|v| v.parse().map_err(|_| Error::input("command_digest"))) + }) + .transpose()?; + Ok((operation, expected)) +} diff --git a/crates/radroots_browser/src/bindings/error.rs b/crates/radroots_browser/src/bindings/error.rs @@ -0,0 +1,155 @@ +use super::Admission; +use wasm_bindgen::prelude::*; + +/// Pure command-parser failures retained across the native boundary. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum InputFailure { + UnsupportedCommand, + UnsupportedProfile, + LimitExceeded, +} + +/// Input-free failures; native details never become dependency/debug prose. +#[derive(Clone, Debug)] +pub enum Error { + InvalidInput { + field: String, + }, + CommandInput { + field: String, + kind: InputFailure, + }, + Operation { + code: String, + retry: String, + operation_id: Option<String>, + admission: Admission, + }, + UnsupportedState { + axis: String, + operation_id: Option<String>, + }, +} +impl Error { + pub(crate) fn command( + field: &'static str, + error: radroots_protocol::command::CommandError, + ) -> Self { + let kind = match error { + radroots_protocol::command::CommandError::InvalidInput => return Self::input(field), + radroots_protocol::command::CommandError::UnsupportedCommand => { + InputFailure::UnsupportedCommand + } + radroots_protocol::command::CommandError::UnsupportedProfile => { + InputFailure::UnsupportedProfile + } + radroots_protocol::command::CommandError::LimitExceeded => InputFailure::LimitExceeded, + _ => { + return Self::UnsupportedState { + axis: "command_input".to_owned(), + operation_id: None, + }; + } + }; + Self::CommandInput { + field: field.to_owned(), + kind, + } + } + pub(crate) fn input(field: &'static str) -> Self { + Self::InvalidInput { + field: field.to_owned(), + } + } + pub(crate) fn with_operation(self, id: String) -> Self { + match self { + Self::UnsupportedState { axis, .. } => Self::UnsupportedState { + axis, + operation_id: Some(id), + }, + value => value, + } + } +} +impl From<radroots_execution::Error> for Error { + fn from(value: radroots_execution::Error) -> Self { + let operation_id = value.context().operation_id().map(|v| v.to_string()); + match Admission::try_from(value.context().admission()) { + Ok(admission) => Self::Operation { + code: value.code().as_str().to_owned(), + retry: value.retry().as_str().to_owned(), + operation_id, + admission, + }, + Err(Self::UnsupportedState { axis, .. }) => { + Self::UnsupportedState { axis, operation_id } + } + Err(other) => other, + } + } +} + +/// Input-free exception value. No private input, provider cause or path crosses. +#[derive(Clone)] +#[wasm_bindgen] +pub struct Failure { + #[wasm_bindgen(readonly, getter_with_clone)] + pub code: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub retry: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub operation_id: Option<String>, + #[wasm_bindgen(readonly)] + pub admission: Option<Admission>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub field: Option<String>, +} +impl From<Error> for Failure { + fn from(value: Error) -> Self { + match value { + Error::InvalidInput { field } => Self { + code: "InvalidInput".into(), + retry: None, + operation_id: None, + admission: None, + field: Some(field), + }, + Error::CommandInput { field, kind } => Self { + code: match kind { + InputFailure::UnsupportedCommand => "UnsupportedCommand", + InputFailure::UnsupportedProfile => "UnsupportedProfile", + InputFailure::LimitExceeded => "LimitExceeded", + } + .into(), + retry: None, + operation_id: None, + admission: None, + field: Some(field), + }, + Error::Operation { + code, + retry, + operation_id, + admission, + } => Self { + code, + retry: Some(retry), + operation_id, + admission: Some(admission), + field: None, + }, + Error::UnsupportedState { axis, operation_id } => Self { + code: "UnsupportedState".into(), + retry: None, + operation_id, + admission: None, + field: Some(axis), + }, + } + } +} +impl From<Error> for JsValue { + fn from(value: Error) -> Self { + Failure::from(value).into() + } +} diff --git a/crates/radroots_browser/src/bindings/inputs.rs b/crates/radroots_browser/src/bindings/inputs.rs @@ -0,0 +1,185 @@ +use super::Error; +use js_sys::JsString; +use radroots_domain::{CorrelationId, OperationId, PublicKey, SourceId, ThreadId, UnixSeconds}; +use wasm_bindgen::prelude::*; + +/// Pure untrusted first-issue descriptor, captured only against a real scope. +#[wasm_bindgen] +pub struct CommandRequest { + operation: OperationId, + deadline: UnixSeconds, + correlation: Option<CorrelationId>, +} +#[wasm_bindgen] +impl CommandRequest { + #[wasm_bindgen(constructor)] + pub fn new( + operation_id: JsString, + first_issue_not_after: JsString, + correlation_id: Option<JsString>, + ) -> Result<CommandRequest, JsValue> { + Ok(Self { + operation: bounded_string(operation_id, 64, "operation_id")? + .parse() + .map_err(|_| Error::input("operation_id"))?, + deadline: bounded_string(first_issue_not_after, 12, "first_issue_not_after")? + .parse() + .map_err(|_| Error::input("first_issue_not_after"))?, + correlation: correlation_id + .map(|v| { + bounded_string(v, 128, "correlation_id").and_then(|v| { + CorrelationId::new(v).map_err(|_| Error::input("correlation_id")) + }) + }) + .transpose()?, + }) + } +} +impl CommandRequest { + pub(super) fn capture( + &self, + scope: &crate::WorkspaceSession, + ) -> Result<crate::CommandContext, Error> { + scope + .command_context_with_correlation( + self.operation, + None, + None, + self.deadline, + self.correlation.clone(), + ) + .map_err(Error::from) + } +} +/// Shared bounded initial listing input. Parsing has no host effects. +#[wasm_bindgen] +pub struct ListingInput { + pub(super) inner: radroots_protocol::listing::PublishInput, +} +#[wasm_bindgen] +impl ListingInput { + pub fn parse(input: js_sys::Uint8Array) -> Result<ListingInput, JsValue> { + if !input.is_instance_of::<js_sys::Uint8Array>() { + return Err(Error::input("listing_input").into()); + } + if input.length() as usize > radroots_protocol::command::COMMAND_MAX_BYTES { + return Err(Error::command( + "listing_input", + radroots_protocol::command::CommandError::LimitExceeded, + ) + .into()); + } + let inner = radroots_protocol::listing::PublishInput::parse(&input.to_vec()) + .map_err(|v| Error::command("listing_input", v))?; + Ok(Self { inner }) + } +} +/// Canonical public reference descriptor, without event or terms authentication. +#[wasm_bindgen] +pub struct ListingReference { + inner: radroots_execution::inbox::ListingRevisionRef, +} +#[wasm_bindgen] +impl ListingReference { + #[wasm_bindgen(constructor)] + pub fn new( + author: JsString, + discriminator: JsString, + event_id: JsString, + ) -> Result<ListingReference, JsValue> { + let author = public_key( + &bounded_string(author, 64, "listing_author")?, + "listing_author", + )?; + let discriminator = bounded_string(discriminator, 32, "listing_discriminator")?; + let event: SourceId = bounded_string(event_id, 64, "listing_event_id")? + .parse() + .map_err(|_| Error::input("listing_event_id"))?; + let inner = + radroots_execution::inbox::ListingRevisionRef::new(author, &discriminator, event) + .map_err(|v| Error::command("listing_reference", v))?; + Ok(Self { inner }) + } +} +/// Private input retains the shared zeroizing owner, with no foreign text cache. +#[wasm_bindgen] +pub struct InquiryInput { + inner: radroots_execution::inbox::InquireInput, +} +#[wasm_bindgen] +impl InquiryInput { + #[wasm_bindgen(constructor)] + pub fn new( + thread_id: JsString, + peer: JsString, + source: Option<ListingReference>, + text: JsString, + ) -> Result<InquiryInput, JsValue> { + let text = zeroize::Zeroizing::new(bounded_string( + text, + radroots_domain::CHAT_MAX_BYTES, + "inquiry_input", + )?); + let thread: ThreadId = bounded_string(thread_id, 64, "thread_id")? + .parse() + .map_err(|_| Error::input("thread_id"))?; + let peer = public_key(&bounded_string(peer, 64, "peer")?, "peer")?; + let inner = radroots_execution::inbox::InquireInput::new( + thread, + peer, + source.map(|v| v.inner), + &text, + ) + .map_err(|v| Error::command("inquiry_input", v))?; + Ok(Self { inner }) + } +} +impl InquiryInput { + pub(super) fn captured_copy(&self) -> Result<radroots_execution::inbox::InquireInput, Error> { + radroots_execution::inbox::InquireInput::new( + self.inner.thread_id(), + self.inner.peer(), + self.inner.source().cloned(), + self.inner.text(), + ) + .map_err(|v| Error::command("inquiry_input", v)) + } +} +// Check UTF-16 size before allocating a Rust copy, reject malformed surrogate +// sequences instead of replacing them, then enforce exact UTF-8 size. Shared +// parsers still own every semantic invariant. Partial private copies zeroize. +pub(super) fn bounded_string( + value: JsString, + max: usize, + field: &'static str, +) -> Result<String, Error> { + if !value.is_string() { + return Err(Error::input(field)); + } + let units = value.length() as usize; + let limit = || { + Error::command( + field, + radroots_protocol::command::CommandError::LimitExceeded, + ) + }; + if units > max { + return Err(limit()); + } + let mut output = zeroize::Zeroizing::new(String::with_capacity(units)); + for value in char::decode_utf16(value.iter()) { + let value = value.map_err(|_| Error::input(field))?; + if output.len() + value.len_utf8() > max { + return Err(limit()); + } + output.push(value); + } + Ok(std::mem::take(&mut *output)) +} +fn public_key(value: &str, field: &'static str) -> Result<PublicKey, Error> { + let key = PublicKey::from_hex(value).map_err(|_| Error::input(field))?; + if key.to_hex() != value { + return Err(Error::input(field)); + } + Ok(key) +} diff --git a/crates/radroots_browser/src/bindings/mod.rs b/crates/radroots_browser/src/bindings/mod.rs @@ -0,0 +1,20 @@ +//! Generated origin-thread JavaScript calls over the shared browser owner. +//! Rust host startup supplies authenticated handles explicitly. No JSON factory +//! creates authority, keys or an independently executing foreign outbox. +mod client; +mod error; +mod inputs; +mod receipt; +mod states; +mod values; + +pub use client::{BrowserClient, Workspace}; +pub use error::{Error, Failure, InputFailure}; +pub use inputs::{CommandRequest, InquiryInput, ListingInput, ListingReference}; +pub use receipt::{Artifact, DeliveryAttempt, Observation, Receipt, Target, TargetPolicy}; +pub use states::{ + Admission, ArtifactRole, BusinessInstallation, Delivery, Issuance, OperationKind, + RecoveryRequirement, SatisfactionClass, SessionState, StartMode, TargetObservation, + WaitTermination, +}; +pub use values::{ChatValue, ListingValue, Value}; diff --git a/crates/radroots_browser/src/bindings/receipt.rs b/crates/radroots_browser/src/bindings/receipt.rs @@ -0,0 +1,377 @@ +use super::{ + Admission, ArtifactRole, BusinessInstallation, Delivery, Error, Failure, Issuance, + OperationKind, RecoveryRequirement, SatisfactionClass, TargetObservation, Value, + WaitTermination, +}; +use wasm_bindgen::prelude::*; + +/// Exact protected artifact references, without payload or invocation rights. +#[derive(Clone)] +#[wasm_bindgen] +pub struct Artifact { + #[wasm_bindgen(readonly)] + pub role: ArtifactRole, + #[wasm_bindgen(readonly, getter_with_clone)] + pub recipient: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub expected_event: Option<String>, + #[wasm_bindgen(readonly)] + pub issuance: Issuance, + #[wasm_bindgen(readonly, getter_with_clone)] + pub attempt_id: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub claim_transaction: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub intent_digest: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub capture_transaction: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub obtained_digest: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub publication_transaction: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub observed_at_unix_ms: Option<String>, +} +#[derive(Clone)] +#[wasm_bindgen] +pub struct Observation { + #[wasm_bindgen(readonly, getter_with_clone)] + pub event_id: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub recipient: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub target: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub request_id: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub target_fingerprint: String, + #[wasm_bindgen(readonly)] + pub target_ordinal: u8, + #[wasm_bindgen(readonly)] + pub outcome: TargetObservation, + #[wasm_bindgen(readonly, getter_with_clone)] + pub observed_at_unix_ms: Option<String>, +} +/// Closed target policy without inventing a default for future variants. +#[derive(Clone)] +#[wasm_bindgen] +pub struct TargetPolicy { + #[wasm_bindgen(readonly, getter_with_clone)] + pub kind: String, + #[wasm_bindgen(readonly)] + pub threshold: Option<u16>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub fingerprints: Vec<String>, +} +#[derive(Clone)] +#[wasm_bindgen] +pub struct Target { + #[wasm_bindgen(readonly, getter_with_clone)] + pub uri: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub kind: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub fingerprint: String, +} +#[derive(Clone)] +#[wasm_bindgen] +pub struct DeliveryAttempt { + #[wasm_bindgen(readonly, getter_with_clone)] + pub request_id: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub event_id: String, + #[wasm_bindgen(readonly)] + pub role: ArtifactRole, + #[wasm_bindgen(readonly, getter_with_clone)] + pub recipient: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub targets: Vec<Target>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub selected_fingerprints: Vec<String>, + #[wasm_bindgen(readonly)] + pub satisfaction_class: SatisfactionClass, + #[wasm_bindgen(readonly, getter_with_clone)] + pub policy: TargetPolicy, + #[wasm_bindgen(readonly, getter_with_clone)] + pub publication_policy_digest: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub intent_digest: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub original_bytes_digest: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub transaction_id: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub work_transaction_id: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub retained_at: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub deadline_unix_ms: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub target_ordinals: Vec<u8>, +} + +/// Source-projected current facts. This data is never an executable context or +/// a new authority to sign, install, dispatch or infer recipient delivery. +#[derive(Clone)] +#[wasm_bindgen] +pub struct Receipt { + #[wasm_bindgen(readonly)] + pub kind: OperationKind, + #[wasm_bindgen(readonly, getter_with_clone)] + pub operation_id: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub captured_context_json: Vec<u8>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub command_digest: String, + #[wasm_bindgen(readonly)] + pub admission: Admission, + #[wasm_bindgen(readonly, getter_with_clone)] + pub admission_transaction_id: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub plan_transaction_id: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub installation_transaction_id: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub installed_at: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub prepared_at: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub first_issue_not_after: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub authority_checkpoint_json: Vec<u8>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub operation_checkpoint: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub observed_at: String, + #[wasm_bindgen(readonly)] + pub business_installation: BusinessInstallation, + #[wasm_bindgen(readonly, getter_with_clone)] + pub business_result: Option<Value>, + #[wasm_bindgen(readonly)] + pub issuance: Issuance, + #[wasm_bindgen(readonly)] + pub delivery: Delivery, + #[wasm_bindgen(readonly)] + pub wait_termination: WaitTermination, + #[wasm_bindgen(readonly, getter_with_clone)] + pub message_id: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub record_ids: Vec<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub missing_sources: Vec<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub conflicting_records: Vec<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub conflicting_sources: Vec<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub artifacts: Vec<Artifact>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub delivery_attempts: Vec<DeliveryAttempt>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub delivery_observations: Vec<Observation>, + recovery: Vec<RecoveryRequirement>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub error: Option<Failure>, +} +#[wasm_bindgen] +impl Receipt { + /// Exact closed shared recovery states, never an untyped or defaulted axis. + #[wasm_bindgen(getter, unchecked_return_type = "RecoveryRequirement[]")] + pub fn recovery(&self) -> Vec<RecoveryRequirement> { + self.recovery.clone() + } +} +impl Receipt { + pub(crate) fn listing( + value: &radroots_execution::OperationReceipt<radroots_domain::listing::Listing>, + ) -> Result<Self, Error> { + project(value, value.business_result().map(Value::listing)) + } + pub(crate) fn chat( + value: &radroots_execution::OperationReceipt<radroots_domain::ChatMessage>, + ) -> Result<Self, Error> { + project(value, value.business_result().map(Value::chat)) + } + pub(crate) fn status(value: &radroots_execution::OperationStatus) -> Result<Self, Error> { + let result = value.business_result().map(|v| match v { + radroots_execution::OperationValue::Listing(v) => Value::listing(v), + radroots_execution::OperationValue::Chat(v) => Value::chat(v), + }); + project(value, result) + } +} +fn project<T>( + value: &radroots_execution::OperationReceipt<T>, + business_result: Option<Value>, +) -> Result<Receipt, Error> { + let operation = value.context().operation_id().to_string(); + project_inner(value, business_result).map_err(|v| v.with_operation(operation)) +} +fn project_inner<T>( + value: &radroots_execution::OperationReceipt<T>, + business_result: Option<Value>, +) -> Result<Receipt, Error> { + let context = || Error::UnsupportedState { + axis: "receipt_data".to_owned(), + operation_id: Some(value.context().operation_id().to_string()), + }; + let artifacts = value + .artifacts() + .iter() + .map(|v| { + Ok(Artifact { + role: v.role().try_into()?, + recipient: v.recipient().map(|v| v.to_hex()), + expected_event: v.expected_event().map(|v| v.to_string()), + issuance: v.issuance().try_into()?, + attempt_id: v.attempt_id().map(|v| v.to_string()), + claim_transaction: v.claim_transaction_id().map(|v| v.to_string()), + intent_digest: v.intent_digest().map(|v| hex(&v)), + capture_transaction: v.capture_transaction_id().map(|v| v.to_string()), + obtained_digest: v.obtained_digest().map(|v| hex(&v)), + publication_transaction: v.publication_transaction_id().map(|v| v.to_string()), + observed_at_unix_ms: v.observed_at_unix_ms().map(|v| v.to_string()), + }) + }) + .collect::<Result<Vec<_>, Error>>()?; + let observations = value + .delivery_observations() + .iter() + .map(|v| { + Ok(Observation { + event_id: v.event_id().to_string(), + recipient: v.recipient().map(|v| v.to_hex()), + target: v.target().to_owned(), + request_id: v.request_id().to_owned(), + target_fingerprint: v.target_fingerprint().to_owned(), + target_ordinal: v.target_ordinal(), + outcome: v.outcome().try_into()?, + observed_at_unix_ms: v.observed_at_unix_ms().map(|v| v.to_string()), + }) + }) + .collect::<Result<Vec<_>, Error>>()?; + let attempts = value + .delivery_attempts() + .iter() + .map(|v| { + let intent = v.intent(); + let selected = intent.policy().targets(); + let policy = if selected.is_any() { + TargetPolicy { + kind: "any".into(), + threshold: None, + fingerprints: vec![], + } + } else if selected.is_all() { + TargetPolicy { + kind: "all".into(), + threshold: None, + fingerprints: vec![], + } + } else if let Some(threshold) = selected.quorum_threshold() { + TargetPolicy { + kind: "quorum".into(), + threshold: Some(threshold), + fingerprints: vec![], + } + } else if let Some(required) = selected.required_targets() { + TargetPolicy { + kind: "required".into(), + threshold: None, + fingerprints: required.iter().map(|v| v.as_str().to_owned()).collect(), + } + } else { + return Err(context()); + }; + Ok(DeliveryAttempt { + request_id: intent.request_id().as_str().to_owned(), + event_id: intent.event_id().to_string(), + role: intent.role().try_into()?, + recipient: v.work().target().recipient().map(|v| v.to_hex()), + targets: intent + .targets() + .targets() + .iter() + .map(|v| Target { + uri: v.uri().as_str().to_owned(), + kind: v.kind().as_str().to_owned(), + fingerprint: v.fingerprint().as_str().to_owned(), + }) + .collect(), + selected_fingerprints: intent + .selection() + .iter() + .map(|v| v.as_str().to_owned()) + .collect(), + satisfaction_class: intent.policy().class().into(), + policy, + publication_policy_digest: hex(intent.publication_policy_digest()), + intent_digest: hex(intent.digest()), + original_bytes_digest: hex(v.envelope_digest()), + transaction_id: v.transaction_id().to_string(), + work_transaction_id: v.work().transaction_id().to_string(), + retained_at: v.retained_at().to_string(), + deadline_unix_ms: intent.deadline_unix_ms().to_string(), + target_ordinals: v.target_ordinals().to_vec(), + }) + }) + .collect::<Result<Vec<_>, Error>>()?; + Ok(Receipt { + kind: value.kind().try_into()?, + operation_id: value.context().operation_id().to_string(), + captured_context_json: serde_json::to_vec(value.context()).map_err(|_| context())?, + command_digest: value.command_digest().to_string(), + admission: value.admission().try_into()?, + admission_transaction_id: value.admission_transaction_id().to_string(), + plan_transaction_id: value.plan_transaction_id().map(|v| v.to_string()), + installation_transaction_id: value.installation_transaction_id().map(|v| v.to_string()), + installed_at: value.installed_at().map(|v| v.to_string()), + prepared_at: value.issuance_window().prepared_at().to_string(), + first_issue_not_after: value.issuance_window().first_issue_not_after().to_string(), + authority_checkpoint_json: serde_json::to_vec(value.authority_checkpoint()) + .map_err(|_| context())?, + operation_checkpoint: value.operation_checkpoint().to_string(), + observed_at: value.observed_at().to_string(), + business_installation: value.business_installation().try_into()?, + business_result, + issuance: value.issuance().try_into()?, + delivery: value.delivery().try_into()?, + wait_termination: value.wait_termination().try_into()?, + message_id: value.message_id().map(|v| v.to_string()), + record_ids: value.record_ids().iter().map(ToString::to_string).collect(), + missing_sources: value + .missing_sources() + .iter() + .map(ToString::to_string) + .collect(), + conflicting_records: value + .conflicting_records() + .iter() + .map(ToString::to_string) + .collect(), + conflicting_sources: value + .conflicting_sources() + .iter() + .map(ToString::to_string) + .collect(), + artifacts, + delivery_attempts: attempts, + delivery_observations: observations, + recovery: value + .recovery() + .iter() + .copied() + .map(TryInto::try_into) + .collect::<Result<Vec<_>, Error>>()?, + error: value.error().map(Error::from).map(Failure::from), + }) +} +fn hex(bytes: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut result = String::with_capacity(bytes.len() * 2); + for byte in bytes { + result.push(DIGITS[(byte >> 4) as usize] as char); + result.push(DIGITS[(byte & 15) as usize] as char); + } + result +} diff --git a/crates/radroots_browser/src/bindings/states.rs b/crates/radroots_browser/src/bindings/states.rs @@ -0,0 +1,130 @@ +use super::Error; +use wasm_bindgen::prelude::*; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[wasm_bindgen] +pub enum SatisfactionClass { + Accepted, + Delivered, +} +impl From<radroots_transport::policy::SatisfactionClass> for SatisfactionClass { + fn from(value: radroots_transport::policy::SatisfactionClass) -> Self { + match value { + radroots_transport::policy::SatisfactionClass::Accepted => Self::Accepted, + radroots_transport::policy::SatisfactionClass::Delivered => Self::Delivered, + } + } +} + +// These are generated-language representations, not another state machine. +// A future source state refuses projection instead of gaining a default. +macro_rules! bridge { + ($name:ident, $native:path, [$($variant:ident),+ $(,)?]) => { + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + #[wasm_bindgen] + pub enum $name { $($variant),+ } + impl TryFrom<$native> for $name { + type Error = Error; + fn try_from(value: $native) -> Result<Self, Error> { + use $native as Native; + match value { + $(Native::$variant => Ok(Self::$variant),)+ + _ => Err(Error::UnsupportedState { axis: stringify!($name).to_owned(), operation_id: None }), + } + } + } + }; +} +bridge!( + Admission, + radroots_execution::Admission, + [NotAdmitted, Confirmed, Unknown] +); +bridge!( + BusinessInstallation, + radroots_execution::BusinessInstallation, + [NotApplicable, NotInstalled, Installed, Uncertain] +); +bridge!( + Issuance, + radroots_execution::Issuance, + [None, Pending, Obtained, Unknown, ProvablyUnissued] +); +bridge!( + Delivery, + radroots_execution::Delivery, + [NotStarted, Pending, Observed, Unknown] +); +bridge!( + WaitTermination, + radroots_execution::WaitTermination, + [Returned, Cancelled, DeadlineExceeded, ClientClosed] +); +bridge!( + RecoveryRequirement, + radroots_execution::RecoveryRequirement, + [ + ContinueOriginalOperation, + ReconcileIssuance, + InstallObtainedEvidence, + ResumeDelivery, + ManualReconciliation + ] +); +bridge!( + TargetObservation, + radroots_execution::TargetObservation, + [ + Accepted, + Rejected, + TimedOut, + Disconnected, + Unknown, + NotAttempted + ] +); +bridge!( + ArtifactRole, + radroots_protocol::intent::ArtifactRole, + [PublicEvent, BusinessSeal, GiftWrap] +); +bridge!( + OperationKind, + radroots_execution::OperationKind, + [Chat, Listing] +); + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[wasm_bindgen] +pub enum StartMode { + LocalOnly, + Online, +} +impl From<StartMode> for crate::StartMode { + fn from(value: StartMode) -> Self { + match value { + StartMode::LocalOnly => Self::LocalOnly, + StartMode::Online => Self::Online, + } + } +} +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[wasm_bindgen] +pub enum SessionState { + Ready, + Starting, + Running, + Closing, + Closed, +} +impl From<crate::SessionState> for SessionState { + fn from(value: crate::SessionState) -> Self { + match value { + crate::SessionState::Ready => Self::Ready, + crate::SessionState::Starting => Self::Starting, + crate::SessionState::Running => Self::Running, + crate::SessionState::Closing => Self::Closing, + crate::SessionState::Closed => Self::Closed, + } + } +} diff --git a/crates/radroots_browser/src/bindings/values.rs b/crates/radroots_browser/src/bindings/values.rs @@ -0,0 +1,140 @@ +use super::Error; +use wasm_bindgen::prelude::*; + +/// Actual owned installed family value. Projections grant no execution authority. +#[derive(Clone)] +#[wasm_bindgen] +pub struct Value { + inner: radroots_execution::OperationValue, +} +impl Value { + pub(super) fn listing(inner: &radroots_domain::listing::Listing) -> Self { + Self { + inner: radroots_execution::OperationValue::Listing(Box::new(inner.clone())), + } + } + pub(super) fn chat(inner: &radroots_domain::ChatMessage) -> Self { + Self { + inner: radroots_execution::OperationValue::Chat(Box::new(inner.clone())), + } + } +} +#[wasm_bindgen] +impl Value { + pub fn listing_value(&self) -> Option<ListingValue> { + match &self.inner { + radroots_execution::OperationValue::Listing(inner) => Some(ListingValue { + inner: inner.as_ref().clone(), + }), + _ => None, + } + } + pub fn chat_value(&self) -> Option<ChatValue> { + match &self.inner { + radroots_execution::OperationValue::Chat(inner) => Some(ChatValue { + inner: inner.as_ref().clone(), + }), + _ => None, + } + } +} +#[wasm_bindgen] +pub struct ListingValue { + inner: radroots_domain::listing::Listing, +} +#[wasm_bindgen] +impl ListingValue { + pub fn id(&self) -> String { + self.inner.id().to_string() + } + pub fn author(&self) -> String { + self.inner.author().to_hex() + } + pub fn revision(&self) -> String { + self.inner.revision().to_string() + } + pub fn created_at(&self) -> String { + self.inner.created_at().to_string() + } + pub fn published_at(&self) -> String { + self.inner.published_at().to_string() + } + pub fn title(&self) -> String { + self.inner.text().title().to_owned() + } + pub fn summary(&self) -> String { + self.inner.text().summary().to_owned() + } + pub fn description_markdown(&self) -> String { + self.inner.text().description_markdown().to_owned() + } + pub fn terms_json(&self) -> Result<Vec<u8>, JsValue> { + serde_json::to_vec(self.inner.terms()).map_err(|_| { + Error::UnsupportedState { + axis: "listing_terms".into(), + operation_id: None, + } + .into() + }) + } +} +#[wasm_bindgen] +pub struct ChatValue { + inner: radroots_domain::ChatMessage, +} +#[wasm_bindgen] +impl ChatValue { + pub fn id(&self) -> String { + self.inner.id().to_string() + } + pub fn thread_id(&self) -> String { + self.inner.thread_id().to_string() + } + pub fn author(&self) -> String { + self.inner.author().to_hex() + } + pub fn peer(&self) -> String { + self.inner.peer().to_hex() + } + pub fn created_at(&self) -> String { + self.inner.created_at().to_string() + } + /// Closed relation kind. A future source relation refuses projection. + pub fn relation(&self) -> Result<String, JsValue> { + match self.inner.relation() { + radroots_domain::ChatRelation::Inquire { .. } => Ok("inquire".into()), + radroots_domain::ChatRelation::Reply { .. } => Ok("reply".into()), + _ => Err(Error::UnsupportedState { + axis: "chat_relation".into(), + operation_id: None, + } + .into()), + } + } + pub fn source(&self) -> Result<Option<String>, JsValue> { + match self.inner.relation() { + radroots_domain::ChatRelation::Inquire { source } => Ok(source.map(|v| v.to_string())), + radroots_domain::ChatRelation::Reply { .. } => Ok(None), + _ => Err(Error::UnsupportedState { + axis: "chat_relation".into(), + operation_id: None, + } + .into()), + } + } + pub fn parent(&self) -> Result<Option<String>, JsValue> { + match self.inner.relation() { + radroots_domain::ChatRelation::Reply { parent } => Ok(Some(parent.to_string())), + radroots_domain::ChatRelation::Inquire { .. } => Ok(None), + _ => Err(Error::UnsupportedState { + axis: "chat_relation".into(), + operation_id: None, + } + .into()), + } + } + /// Explicit presentation copy; JS controls its own resulting string lifetime. + pub fn text(&self) -> String { + self.inner.text().to_owned() + } +} diff --git a/crates/radroots_browser/src/lib.rs b/crates/radroots_browser/src/lib.rs @@ -6,6 +6,8 @@ mod tasks; #[cfg(target_arch = "wasm32")] +pub mod bindings; +#[cfg(target_arch = "wasm32")] mod client; #[cfg(all(target_arch = "wasm32", feature = "artifact_clock"))] mod clock; diff --git a/crates/radroots_browser/tests/browser/Cargo.lock b/crates/radroots_browser/tests/browser/Cargo.lock @@ -1266,10 +1266,12 @@ dependencies = [ "radroots_transport", "radroots_transport_nostr", "radroots_transport_nostr_browser", + "serde_json", "universal-time", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "zeroize", ] [[package]] diff --git a/crates/radroots_browser/tests/browser/consumer.ts b/crates/radroots_browser/tests/browser/consumer.ts @@ -0,0 +1,160 @@ +import init, { + BindingFixture, Client, Workspace, CommandRequest, ListingInput, InquiryInput, + Receipt, Failure, Admission, BusinessInstallation, Issuance, OperationKind, + SessionState, StartMode, TargetObservation, verify_listing_publications, + verify_binding_inquiry, advertisements, +} from '@radroots/browser-feasibility'; + +function assert(value: unknown, message: string): asserts value { + if (!value) throw Error(message); +} +const decode = (value: Uint8Array): unknown => JSON.parse(new TextDecoder().decode(value)); +const id = (byte: string): string => byte.repeat(32); +const peer = 'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5'; +const now = (): string => String(Math.floor(Date.now() / 1000)); +const deadline = (): string => String(Math.floor(Date.now() / 1000) + 120); +const text = '\uFEFF cafe\u0301 / café 🥕\u0000 '; + +async function refuses(call: () => unknown, code: string): Promise<void> { + try { await call(); } catch (error: unknown) { + assert(error instanceof Failure, 'typed generated failure'); + assert(error.code === code, `safe failure ${error.code} expected ${code}`); + assert(!JSON.stringify([error.code,error.field,error.retry]).includes(text), 'input-free failure'); + error.free(); return; + } + throw Error(`expected ${code}`); +} +function receipt(value: Receipt, operation: string, kind: OperationKind): void { + assert(value.operation_id === operation && value.kind === kind, 'exact typed operation/family'); + assert(value.admission === Admission.Confirmed, 'confirmed durable admission'); + assert(value.business_installation === BusinessInstallation.Installed, 'actual installation'); + assert(value.issuance === Issuance.Obtained, 'actual obtained originals'); + for (const digest of [value.command_digest,value.operation_checkpoint,value.admission_transaction_id, + value.plan_transaction_id,value.installation_transaction_id]) assert(digest && /^[0-9a-f]{64}$/.test(digest), 'exact digest/transaction'); + assert(typeof value.prepared_at === 'string' && typeof value.first_issue_not_after === 'string' + && typeof value.installed_at === 'string' && typeof value.observed_at === 'string', 'exact time strings'); + assert(decode(value.captured_context_json) && decode(value.authority_checkpoint_json), 'source-owned structured context/checkpoint'); + assert(value.missing_sources.length === 0 && value.conflicting_records.length === 0 + && value.conflicting_sources.length === 0 && value.error === undefined, 'all conflict/error axes'); + assert(value.record_ids.length === 0, 'known listing/chat have no fabricated structured-commerce record IDs'); + const artifacts=value.artifacts; + assert(artifacts.length > 0, 'actual original artifacts'); + for (const artifact of artifacts) { + assert(artifact.issuance === Issuance.Obtained && artifact.attempt_id && artifact.claim_transaction + && artifact.intent_digest && artifact.capture_transaction && artifact.obtained_digest + && artifact.publication_transaction, 'complete original artifact provenance'); + assert(artifact.observed_at_unix_ms === undefined || typeof artifact.observed_at_unix_ms === 'string', 'nullable exact artifact time'); + artifact.free(); + } + for (const attempt of value.delivery_attempts) { + const policy = attempt.policy; + assert(policy.kind === 'all' && policy.threshold === undefined && policy.fingerprints.length === 0, 'original closed policy'); + const targets=attempt.targets; + assert(attempt.selected_fingerprints.length === 1 && targets.length === 1 + && attempt.target_ordinals.length === 1, 'actual target selection'); + for (const target of targets) { + assert(target.uri.startsWith('ws://127.0.0.1:') && target.kind && target.fingerprint, 'actual configured target'); + target.free(); + } + for (const field of [attempt.request_id,attempt.event_id,attempt.publication_policy_digest,attempt.intent_digest, + attempt.original_bytes_digest,attempt.transaction_id,attempt.work_transaction_id,attempt.retained_at,attempt.deadline_unix_ms]) assert(typeof field === 'string' && field.length > 0, 'complete original delivery commitment'); + policy.free(); attempt.free(); + } + for (const observation of value.delivery_observations) { + assert(observation.event_id && observation.target && observation.request_id && observation.target_fingerprint + && observation.target_ordinal > 0, 'complete correlated observation'); + assert(observation.observed_at_unix_ms === undefined || typeof observation.observed_at_unix_ms === 'string', 'nullable exact observation time'); + observation.free(); + } + assert(typeof value.delivery === 'number' && typeof value.wait_termination === 'number' + && Array.isArray(value.recovery), 'independent delivery/wait/recovery axes'); +} +function listingInput(): ListingInput { + return ListingInput.parse(new TextEncoder().encode(JSON.stringify({ + id:'01'.repeat(16),title:' Packed carrots 🥕 ',summary:'Quote required',description_markdown:'Exact public terms',published_at:now(), + profile:{profile:'radroots.listing',version:1,state:'active',product:{name:'Carrots',description:'Fresh carrots',producer:null,origin_summary:null}, + default_option:id('02'),options:[{id:id('02'),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:[]}, + }))); +} +async function query(client: Client, scope: Workspace, operation: string, digest: string): Promise<Receipt> { + const result = await client.operation(scope,operation,digest); + assert(result, 'actual retained original operation'); return result; +} +export async function run(base: string, context: string): Promise<unknown> { + await init(); + const publicRoute = '/listing/'+context, privateRoute = '/'+context; + await fetch(base+'/advertisements'+privateRoute,{method:'POST',body:advertisements(base.replace('http:','ws:')+privateRoute)}); + const seller = await BindingFixture.create(base.replace('http:','ws:')+publicRoute,'packed_public_'+context,true); + const client = seller.client(), scope = seller.workspace(); + assert(client.state() === SessionState.Ready, 'inert configured host'); + await client.start(StartMode.Online); + await refuses(()=>new CommandRequest(id('11').toUpperCase(),'253402300800'), 'InvalidInput'); + await refuses(()=>new CommandRequest(id('ab').toUpperCase(),deadline()), 'InvalidInput'); + await refuses(()=>new CommandRequest(id('11'),'0001'), 'InvalidInput'); + await refuses(()=>new InquiryInput(id('12'),peer,undefined,'x'.repeat(17000)), 'LimitExceeded'); + await refuses(()=>new InquiryInput(id('12'),peer,undefined,'\ud800'), 'InvalidInput'); + await refuses(()=>ListingInput.parse(new Uint8Array(65537)), 'LimitExceeded'); + await refuses(()=>ListingInput.parse(new TextEncoder().encode('{"id":"bad"}')), 'InvalidInput'); + const input=listingInput(), request=new CommandRequest(id('13'),deadline(),'packed-public'); + const original=await client.publish_listing(scope,request,input); + receipt(original,id('13'),OperationKind.Listing); + assert(original.message_id === undefined, 'public has no private message'); + const result=original.business_result; assert(result, 'typed public value'); + assert(result.chat_value() === undefined, 'public has no private placeholder'); + const listing=result.listing_value(); assert(listing && listing.title() === ' Packed carrots 🥕 ' + && listing.id() === '01'.repeat(16) && listing.published_at() && decode(listing.terms_json()), 'actual listing content'); + const revision=listing.revision(); listing.free(); result.free(); + for (const artifact of original.artifacts) { assert(artifact.recipient === undefined, 'public recipient absent'); artifact.free(); } + const observations=original.delivery_observations; + assert(observations.length === 1 && observations[0].outcome === TargetObservation.Rejected, 'actual public rejection'); + observations.forEach(value=>value.free()); + const digest=original.command_digest, checkpoint=original.operation_checkpoint; + const replay=await client.publish_listing(scope,request,input); + assert(replay.operation_checkpoint === checkpoint, 'idempotent JS replay'); replay.free(); + await client.close(); await client.close(); assert(seller.callbacks_closed() === 1, 'original callbacks closed once'); + const reopened=await seller.reopen(), resumedClient=reopened.client(), resumedScope=reopened.workspace(); + await resumedClient.start(StartMode.Online); + const retained=await query(resumedClient,resumedScope,id('13'),digest); + assert(retained.operation_checkpoint === checkpoint, 'reopen exact original checkpoint'); retained.free(); + const resumed=await resumedClient.resume(resumedScope,id('13'),digest); + receipt(resumed,id('13'),OperationKind.Listing); + assert(resumed.installation_transaction_id === original.installation_transaction_id + && resumed.first_issue_not_after === original.first_issue_not_after, 'original issuance/installation after retry'); + const attempts=resumed.delivery_attempts; + assert(attempts.length === 2 && attempts[0].original_bytes_digest === attempts[1].original_bytes_digest + && attempts[0].publication_policy_digest === attempts[1].publication_policy_digest, 'exact public retry/policy'); + assert(attempts.flatMap(value=>Array.from(value.target_ordinals)).sort().join(',') === '1,2', 'per-target original ordinals'); + attempts.forEach(value=>value.free()); + const accepted=resumed.delivery_observations; + assert(accepted.some(value=>value.outcome === TargetObservation.Accepted), 'actual retry acceptance'); accepted.forEach(value=>value.free()); + const publicEvents=await fetch(base+'/events'+publicRoute).then(response=>response.text()); + verify_listing_publications(publicEvents,revision); + const buyer=await BindingFixture.create(base.replace('http:','ws:')+privateRoute,'packed_private_'+context,false); + const buyerClient=buyer.client(), buyerScope=buyer.workspace(); await buyerClient.start(StartMode.Online); + const denied=new CommandRequest(id('14'),deadline()); + await refuses(()=>buyerClient.publish_listing(buyerScope,denied,input),'unauthorized'); + await refuses(()=>resumedClient.publish_listing(buyerScope,denied,input),'unauthorized'); + const inquiry=new InquiryInput(id('15'),peer,undefined,text), privateRequest=new CommandRequest(id('16'),deadline()); + const message=await buyerClient.inquire(buyerScope,privateRequest,inquiry); + receipt(message,id('16'),OperationKind.Chat); + const business=message.business_result; assert(business && business.listing_value() === undefined, 'private typed family'); + const chat=business.chat_value(); assert(chat && chat.text() === text && chat.thread_id() === id('15') && chat.peer() === peer + && chat.relation() === 'inquire' && chat.source() === undefined && chat.parent() === undefined, 'exact private original text/relation'); + const messageId=chat.id(); chat.free(); business.free(); + await verify_binding_inquiry(await fetch(base+'/events'+privateRoute).then(response=>response.text()),messageId,text); + const privateDigest=message.command_digest, privateCheckpoint=message.operation_checkpoint; + await buyerClient.close(); assert(buyer.callbacks_closed() === 1, 'private callbacks close once'); + const privateReopened=await buyer.reopen(), readClient=privateReopened.client(), readScope=privateReopened.workspace(); + await readClient.start(StartMode.LocalOnly); + const read=await query(readClient,readScope,id('16'),privateDigest); + assert(read.operation_checkpoint === privateCheckpoint && read.message_id === messageId, 'private exact reopen without network'); + await readClient.close(); await resumedClient.close(); + assert(privateReopened.callbacks_closed() === 1 && reopened.callbacks_closed() === 1, 'all original callback scopes close'); + await refuses(()=>client.start(StartMode.Online),'capability_unavailable'); + scope.close(); resumedScope.close(); buyerScope.close(); readScope.close(); + for (const value of [original,resumed,message,read]) value.free(); + for (const value of [request,denied,privateRequest,input,inquiry,scope,resumedScope,buyerScope,readScope,client,resumedClient,buyerClient,readClient,seller,reopened,buyer,privateReopened]) value.free(); + return {passed:['packed generated public call and exact replay','reopen/query and original exact-byte retry','all typed receipt axes','private JS call and independent nested authentication','bounded inputs, scope and lifecycle refusals','actual ordered close'],revision,messageId}; +} diff --git a/crates/radroots_browser/tests/browser/pack.mjs b/crates/radroots_browser/tests/browser/pack.mjs @@ -0,0 +1,51 @@ +import assert from 'node:assert/strict'; +import {spawnSync} from 'node:child_process'; +import {createHash} from 'node:crypto'; +import {cp,mkdir,readFile,readdir,writeFile} from 'node:fs/promises'; +import {dirname,resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; + +const [generated,destination,tsc]=process.argv.slice(2); +assert(generated&&destination&&tsc); +const root=resolve(destination), source=resolve(generated), local=dirname(fileURLToPath(import.meta.url)); +await mkdir(root,{recursive:false}); +const pkg=resolve(root,'package'), consumer=resolve(root,'consumer'); +await mkdir(pkg); await mkdir(consumer); +const files=['fixture.js','fixture.d.ts','fixture_bg.wasm','fixture_bg.wasm.d.ts']; +const hashes={}; +for(const file of files){ + await cp(resolve(source,file),resolve(pkg,file)); + hashes[file]=createHash('sha256').update(await readFile(resolve(pkg,file))).digest('hex'); +} +await writeFile(resolve(pkg,'package.json'),JSON.stringify({name:'@radroots/browser-feasibility',version:'0.0.0',private:true, + description:'Synthetic authenticated host fixture for actual generated Radroots browser calls; not a general SDK distribution', + type:'module',exports:{'.':{types:'./fixture.d.ts',import:'./fixture.js'}},files},null,2)+'\n'); +function run(command,args,cwd){ + const result=spawnSync(command,args,{cwd,encoding:'utf8',maxBuffer:8*1024*1024}); + assert.equal(result.status,0,`${command} ${args.join(' ')}\n${result.stdout}\n${result.stderr}`); + return result.stdout; +} +const archive=JSON.parse(run('npm',['pack','--json','--ignore-scripts'],pkg)); +assert.equal(archive.length,1); +const tarball=resolve(pkg,archive[0].filename); +await writeFile(resolve(consumer,'package.json'),JSON.stringify({name:'neutral-radroots-browser-consumer',private:true,type:'module', + dependencies:{'@radroots/browser-feasibility':`file:${tarball}`}},null,2)+'\n'); +run('npm',['install','--offline','--ignore-scripts','--no-audit','--no-fund'],consumer); +const installed=resolve(consumer,'node_modules/@radroots/browser-feasibility'); +for(const [file,hash] of Object.entries(hashes)) assert.equal(createHash('sha256').update(await readFile(resolve(installed,file))).digest('hex'),hash); +assert.deepEqual((await readdir(installed)).sort(),[...files,'package.json'].sort()); +await cp(resolve(local,'consumer.ts'),resolve(consumer,'consumer.ts')); +await writeFile(resolve(consumer,'tsconfig.json'),JSON.stringify({compilerOptions:{target:'ES2022',module:'NodeNext',moduleResolution:'NodeNext', + strict:true,skipLibCheck:false,noEmitOnError:true,lib:['ES2022','ESNext.Disposable','DOM'],outDir:'dist'},include:['consumer.ts']},null,2)+'\n'); +const compiler=run(process.execPath,[resolve(tsc),'--version'],consumer).trim(); +run(process.execPath,[resolve(tsc),'-p','.'],consumer); +const ssr=run(process.execPath,['--input-type=module','-e',` +for(const name of ['window','document','indexedDB','WebSocket','Worker']) Object.defineProperty(globalThis,name,{configurable:true,get(){throw Error('unexpected SSR host access: '+name);}}); +const sdk=await import('@radroots/browser-feasibility'); +if(typeof sdk.Client!=='function'||typeof sdk.CommandRequest!=='function'||typeof sdk.default!=='function') throw Error('missing actual exports'); +console.log('inert SSR import passed');`],consumer).trim(); +const report={scope:'packed neutral fixture, Rust-authenticated host injection; not a generic host factory or production SDK distribution', + compiler,node:process.version,npm:run('npm',['--version'],consumer).trim(),archive:archive[0],hashes,ssr, + consumer:resolve(consumer,'dist/consumer.js'),installed}; +await writeFile(resolve(root,'pack.json'),JSON.stringify(report,null,2)+'\n'); +console.log(JSON.stringify(report)); diff --git a/crates/radroots_browser/tests/browser/packed.mjs b/crates/radroots_browser/tests/browser/packed.mjs @@ -0,0 +1,123 @@ +import assert from 'node:assert/strict'; +import {createRequire} from 'node:module'; +import {createServer} from 'node:http'; +import {readFile} from 'node:fs/promises'; +import {resolve} from 'node:path'; + +const [tools,packedDir,engine='chromium']=process.argv.slice(2); +const pack=JSON.parse(await readFile(resolve(packedDir,'pack.json'),'utf8')); +const packageDir=pack.installed; +assert(tools&&packageDir&&['chromium','firefox','webkit'].includes(engine)); +const require=createRequire(resolve(tools,'package.json')); +const playwright=require('playwright'); +const {wsServer:WebSocketServer}=require(resolve(tools,'node_modules/playwright-core/lib/utilsBundle.js')); +const wss=new WebSocketServer({noServer:true}),sockets=new Set(),sources=new Map(),observed=[],upgrades=[]; +process.on('uncaughtExceptionMonitor',()=>console.error(JSON.stringify({engine,upgrades,observed}))); +const observer=` +const ActualWebSocket=globalThis.WebSocket,actualOpen=IDBFactory.prototype.open; +const observedSockets=[],databases=[]; +globalThis.WebSocket=class extends ActualWebSocket {constructor(...args){super(...args);observedSockets.push(this);}}; +globalThis.browserSocketCount=()=>observedSockets.length; +IDBFactory.prototype.open=function(...args){ + const request=actualOpen.apply(this,args); + request.addEventListener('success',()=>databases.push(request.result),{once:true}); + return request; +}; +globalThis.assertStorageCallbacksClosed=()=>{ + for(const db of databases)if(db.onversionchange||db.onclose)throw Error('explicit close retained database callback'); +}; +async function verifyCleanup(){ + await new Promise(resolve=>setTimeout(resolve,80)); + for(const socket of observedSockets){ + if(socket.onopen||socket.onmessage||socket.onerror||socket.onclose)throw Error('retained original socket callback'); + if(socket.readyState!==ActualWebSocket.CLOSED)throw Error('original socket remains open'); + } + assertStorageCallbacksClosed(); + return {sockets:observedSockets.length,databases:databases.length}; +}`; +const execute=` +const {run}=await import('./consumer.js'); +let result;try{result=await run(base,context);}catch(error){ + if(error&&typeof error.code==='string')throw Error(JSON.stringify({code:error.code,field:error.field,retry:error.retry,operation_id:error.operation_id,admission:error.admission})); + throw error; +} +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}})());} +catch(error){self.postMessage({error:String(error)});}};`; +const server=createServer(async(req,res)=>{ + try{ + if(req.url==='/'){res.setHeader('content-type','text/html');res.end('<!doctype html><title>Ordinary Radroots browser client</title>');return;} + if(req.url==='/worker.js'){res.setHeader('content-type','text/javascript');res.end(worker);return;} + if(req.url==='/advertisements/main'||req.url==='/advertisements/worker'){ + assert.equal(req.method,'POST');let body='';for await(const chunk of req){body+=chunk;assert(Buffer.byteLength(body)<=64*1024);} + const raw=JSON.parse(body);assert.equal(raw.length,2);const values=raw.map(value=>JSON.parse(value)); + for(const value of values)assert.equal(value.kind,10050); + sources.set(req.url.replace('/advertisements',''),values);res.end('ok');return; + } + 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; + } + if(req.url==='/consumer.js'){ + const compiled=await readFile(pack.consumer,'utf8'); + assert.equal(compiled.split("'@radroots/browser-feasibility'").length,2); + res.setHeader('content-type','text/javascript');res.end(compiled.replace("'@radroots/browser-feasibility'","'./fixture.js'"));return; + } + const name=new Map([['/fixture.js','fixture.js'],['/fixture_bg.wasm','fixture_bg.wasm']]).get(req.url); + if(!name){res.statusCode=404;res.end();return;} + res.setHeader('content-type',name.endsWith('.wasm')?'application/wasm':'text/javascript');res.end(await readFile(resolve(packageDir,name))); + }catch(error){res.statusCode=500;res.end('fixture setup failed');console.error(error);} +}); +server.on('connection',socket=>{sockets.add(socket);socket.on('close',()=>sockets.delete(socket));}); +server.on('upgrade',(req,socket,head)=>{ + 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,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'); + }); + }); +}); +await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); +const base=`http://127.0.0.1:${server.address().port}`;let browser; +const watchdog=setTimeout(()=>{void browser?.close();},120000);watchdog.unref(); +try{ + const automation=engine==='firefox'?'webdriver_bidi':'playwright_default'; + const options=engine==='firefox'?{headless:true,channel:'moz-firefox-nightly',executablePath:playwright.firefox.executablePath()}:{headless:true}; + browser=await playwright[engine].launch(options);let page=await browser.newPage();const errors=[]; + page.on('pageerror',error=>errors.push(error.message));await page.goto(base);await page.addScriptTag({content:observer}); + const main=await page.evaluate(new Function('base',`return(async()=>{const context='main';${execute}})();`),base); + console.error(JSON.stringify({phase:'main_completed',engine,result:main})); + await page.close();page=await browser.newPage();page.on('pageerror',error=>errors.push(error.message));await page.goto(base); + const dedicated=await page.evaluate(base=>new Promise((resolve,reject)=>{ + const worker=new Worker('./worker.js',{type:'module'}); + worker.onerror=event=>{worker.terminate();reject(Error(event.message));}; + 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,6);assert.deepEqual(main.passed,dedicated.passed);assert.deepEqual(errors,[]); + for(const context of ['main','worker']){ + const publications=observed.filter(item=>item.route==='/'+context&&item.message[0]==='EVENT'); + assert.equal(publications.length,2);assert.equal(new Set(publications.map(item=>item.message[1].id)).size,2); + assert.equal(upgrades.filter(route=>route==='/'+context).length,1); + 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({pack,engine,automation,version:browser.version(),main,dedicated,pageErrors:errors,upgrades,observed})); +}finally{ + clearTimeout(watchdog);await browser?.close();for(const client of wss.clients)client.terminate();for(const socket of sockets)socket.destroy(); + await new Promise(resolve=>wss.close(resolve));await new Promise(resolve=>server.close(resolve)); +} diff --git a/crates/radroots_browser/tests/browser/src/binding_fixture.rs b/crates/radroots_browser/tests/browser/src/binding_fixture.rs @@ -0,0 +1,96 @@ +//! Synthetic host assembly only; all JS command entry points are production. +use super::*; +use radroots_browser::bindings::{BrowserClient, Workspace}; + +#[wasm_bindgen] +pub struct BindingFixture { + existing: Rc<Existing>, + base: String, + client: Client, + scope: WorkspaceSession, + callbacks: Rc<Callbacks>, +} +#[wasm_bindgen] +impl BindingFixture { + pub async fn create( + base: String, + label: String, + seller: bool, + ) -> Result<BindingFixture, JsValue> { + let existing = Rc::new(Existing::create_scope(&label, seller).await?); + Self::open(existing, base).await + } + pub fn client(&self) -> BrowserClient { + BrowserClient::from_browser(self.client.clone()) + } + pub fn workspace(&self) -> Workspace { + Workspace::from_session(self.scope.clone()) + } + pub fn callbacks_closed(&self) -> u32 { + self.callbacks.closed.get() + } + pub async fn reopen(&self) -> Result<BindingFixture, JsValue> { + require( + self.client.state() == SessionState::Closed, + "fixture reopen requires explicit actual close", + )?; + Self::open(self.existing.clone(), self.base.clone()).await + } +} +impl BindingFixture { + async fn open(existing: Rc<Existing>, base: String) -> Result<Self, JsValue> { + let (client, scope) = existing.open(&base).await?; + let callbacks = signer(&client).await?; + Ok(Self { + existing, + base, + client, + scope, + callbacks, + }) + } +} + +/// Independent nested authentication of the original private JS command text. +#[wasm_bindgen] +pub async fn verify_binding_inquiry( + raw_events: String, + expected: String, + text: String, +) -> Result<(), JsValue> { + let events: Vec<String> = serde_json::from_str(&raw_events).map_err(fail)?; + require(events.len() == 2, "one original self and peer envelope")?; + let mut recipients = Vec::new(); + for raw in events { + let event = nostr::Event::from_json(&raw).map_err(fail)?; + event.verify().map_err(fail)?; + let recipient = event + .tags + .iter() + .find(|tag| tag.as_slice()[0] == "p") + .ok_or_else(|| JsValue::from_str("missing private recipient"))? + .as_slice()[1] + .clone(); + let n = if recipient == key(1).public_key().to_hex() { + 1 + } else { + 2 + }; + require( + recipient == key(n).public_key().to_hex(), + "unexpected private recipient", + )?; + let message = nostr::nips::nip59::extract_rumor(&key(n), &event) + .await + .map_err(fail)?; + require( + message.sender == key(1).public_key() + && message.rumor.content == text + && message.rumor.id.map(|v| v.to_hex()).as_deref() == Some(&expected), + "private JS text and original rumor identity", + )?; + recipients.push(n); + } + recipients.sort(); + require(recipients == [1, 2], "independent self and peer originals") +} diff --git a/crates/radroots_browser/tests/browser/src/lib.rs b/crates/radroots_browser/tests/browser/src/lib.rs @@ -1,4 +1,5 @@ #![forbid(unsafe_code)] +mod binding_fixture; use futures::FutureExt; use nostr::JsonUtil; use radroots_browser::{