lib.rs (22555B)
1 #![forbid(unsafe_code)] 2 mod binding_fixture; 3 use futures::FutureExt; 4 use nostr::JsonUtil; 5 use radroots_browser::{ 6 BrowserConfig, BrowserNonceSource, Client, InquireInput, SessionState, StartMode, 7 WorkspaceSession, 8 }; 9 use radroots_domain::{OperationId, PublicKey, ThreadId, UnixSeconds}; 10 use radroots_nostr::{key::parse_secret_key, signing::LocalSigner}; 11 use radroots_secrets::{ 12 SecretId, SecretRef, 13 browser::BrowserProvider, 14 id::{BackendKind, KeyVersion}, 15 provider::{AccessPolicy, HardwarePolicy, ResidencyPolicy, UserPresencePolicy}, 16 }; 17 use radroots_signing::{ 18 provider::{NonceSource, ProviderError, SignerCallbacks, SignerHandle}, 19 signer::BoxFuture, 20 }; 21 use radroots_storage::workspace::{ 22 AttachmentInput, AttachmentProof, WorkspaceClock, WorkspaceError, 23 }; 24 use radroots_storage_indexeddb::workspace::{BrowserWorkspace, LocalOutboxConfig}; 25 use radroots_transport::policy::{SatisfactionClass, SatisfactionPolicy, TargetPolicy}; 26 use radroots_transport_nostr::{ 27 Config, RelayAccess, RelayEndpoint, RelayProfile, RelayProfileKind, RelayUrlPolicy, 28 }; 29 use std::{cell::Cell, rc::Rc}; 30 use wasm_bindgen::prelude::*; 31 32 #[wasm_bindgen] 33 extern "C" { 34 #[wasm_bindgen(js_namespace = globalThis, js_name = browserSocketCount)] 35 fn socket_count() -> u32; 36 #[wasm_bindgen(catch, js_namespace = globalThis, js_name = assertStorageCallbacksClosed)] 37 fn storage_callbacks_closed() -> Result<(), JsValue>; 38 } 39 fn require(value: bool, message: &str) -> Result<(), JsValue> { 40 if value { Ok(()) } else { Err(message.into()) } 41 } 42 fn fail(error: impl std::fmt::Debug) -> JsValue { 43 JsValue::from_str(&format!("fixture: {error:?}")) 44 } 45 fn now() -> u64 { 46 (js_sys::Date::now() / 1000.0) as u64 47 } 48 fn proof_copy(proof: &AttachmentProof) -> AttachmentProof { 49 proof.with_secret(|secret| AttachmentProof::from_protected_input(secret).unwrap()) 50 } 51 fn reference_copy(reference: &SecretRef) -> SecretRef { 52 SecretRef::new( 53 reference.id().clone(), 54 reference.backend(), 55 reference.key_version(), 56 ) 57 } 58 fn key(last: u8) -> nostr::Keys { 59 let mut bytes = [0; 32]; 60 bytes[31] = last; 61 nostr::Keys::new(nostr::SecretKey::from_slice(&bytes).unwrap()) 62 } 63 fn participant(last: u8) -> PublicKey { 64 PublicKey::from_bytes(key(last).public_key().to_bytes()).unwrap() 65 } 66 fn access() -> AccessPolicy { 67 AccessPolicy::new( 68 ResidencyPolicy::Any, 69 UserPresencePolicy::NotRequired, 70 HardwarePolicy::Any, 71 ) 72 } 73 struct Clock; 74 impl WorkspaceClock for Clock { 75 fn now(&self) -> Result<UnixSeconds, WorkspaceError> { 76 UnixSeconds::new(now()).map_err(|_| WorkspaceError::Unavailable) 77 } 78 } 79 struct Callbacks { 80 quiesced: Cell<u32>, 81 closed: Cell<u32>, 82 } 83 impl SignerCallbacks for Callbacks { 84 fn quiesce(&self) -> BoxFuture<'_, Result<(), ProviderError>> { 85 Box::pin(async move { 86 self.quiesced.set(self.quiesced.get() + 1); 87 Ok(()) 88 }) 89 } 90 fn close(&self) -> BoxFuture<'_, Result<(), ProviderError>> { 91 Box::pin(async move { 92 self.closed.set(self.closed.get() + 1); 93 Ok(()) 94 }) 95 } 96 } 97 fn signer_clock() -> Result<u64, radroots_signing::Error> { 98 Ok(js_sys::Date::now() as u64) 99 } 100 fn local_signer() -> LocalSigner { 101 LocalSigner::with_clock( 102 parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001") 103 .unwrap(), 104 signer_clock, 105 ) 106 .unwrap() 107 .with_nonce_source(Rc::new(BrowserNonceSource)) 108 } 109 async fn signer(client: &Client) -> Result<Rc<Callbacks>, JsValue> { 110 let signer = local_signer(); 111 let callbacks = Rc::new(Callbacks { 112 quiesced: Cell::new(0), 113 closed: Cell::new(0), 114 }); 115 client 116 .attach_signer(SignerHandle::new(Rc::new(signer), callbacks.clone())) 117 .await 118 .map_err(fail)?; 119 Ok(callbacks) 120 } 121 struct Existing { 122 namespace: SecretId, 123 reference: SecretRef, 124 fingerprint: [u8; 32], 125 input: AttachmentInput, 126 proof: AttachmentProof, 127 } 128 impl Existing { 129 async fn create(label: &str) -> Result<Self, JsValue> { 130 Self::create_scope(label, false).await 131 } 132 async fn create_scope(label: &str, seller: bool) -> Result<Self, JsValue> { 133 let namespace = SecretId::parse(label).unwrap(); 134 let reference = SecretRef::new( 135 SecretId::parse("ordinary_browser_workspace").unwrap(), 136 BackendKind::External, 137 KeyVersion::new(1).unwrap(), 138 ); 139 let provider = Rc::new( 140 BrowserProvider::create(namespace.clone(), reference_copy(&reference)) 141 .await 142 .map_err(fail)?, 143 ); 144 let fingerprint = provider.fingerprint(); 145 let constructor = if seller { 146 LocalOutboxConfig::seller 147 } else { 148 LocalOutboxConfig::new 149 }; 150 let (workspace, input, proof) = BrowserWorkspace::initialize_local_outbox( 151 constructor( 152 participant(1), 153 participant(3), 154 "isolated-browser-fixture", 155 UnixSeconds::new(now() + 600).unwrap(), 156 ) 157 .unwrap(), 158 provider.clone(), 159 reference_copy(&reference), 160 access(), 161 Rc::new(Clock), 162 ) 163 .await 164 .map_err(fail)?; 165 workspace.close().await.map_err(fail)?; 166 provider.close().await.map_err(fail)?; 167 Ok(Self { 168 namespace, 169 reference, 170 fingerprint, 171 input, 172 proof, 173 }) 174 } 175 fn config(&self, base: &str) -> BrowserConfig { 176 let transport = Config::from_profile( 177 RelayProfile::explicit( 178 RelayProfileKind::Simulator, 179 [ 180 RelayEndpoint::new(base, RelayUrlPolicy::Local, RelayAccess::ReadWrite) 181 .unwrap(), 182 ], 183 ) 184 .unwrap(), 185 ) 186 .with_timeouts(2000, 2000, 2000) 187 .unwrap(); 188 BrowserConfig::existing( 189 self.namespace.clone(), 190 reference_copy(&self.reference), 191 self.fingerprint, 192 self.input.clone(), 193 proof_copy(&self.proof), 194 access(), 195 ) 196 .with_nostr( 197 transport, 198 SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()), 199 ) 200 .unwrap() 201 } 202 async fn open(&self, base: &str) -> Result<(Client, WorkspaceSession), JsValue> { 203 let client = Client::open(self.config(base)).await.map_err(fail)?; 204 require( 205 client.state() == SessionState::Ready, 206 "open must remain ready", 207 )?; 208 let wrong = AttachmentProof::from_protected_input(&[99; 32]).unwrap(); 209 require( 210 client.attach(self.input.clone(), wrong).await.is_err(), 211 "key ownership cannot replace attachment proof", 212 )?; 213 let scope = client 214 .attach(self.input.clone(), proof_copy(&self.proof)) 215 .await 216 .map_err(fail)?; 217 Ok((client, scope)) 218 } 219 } 220 fn id() -> OperationId { 221 OperationId::from_bytes(BrowserNonceSource.next_nonce().unwrap()) 222 } 223 fn inquire() -> InquireInput { 224 InquireInput::new( 225 ThreadId::from_bytes([33; 32]), 226 participant(2), 227 None, 228 "ordinary browser inquiry", 229 ) 230 .unwrap() 231 } 232 fn context( 233 scope: &WorkspaceSession, 234 operation: OperationId, 235 deadline: u64, 236 ) -> radroots_browser::CommandContext { 237 scope 238 .command_context(operation, None, None, UnixSeconds::new(deadline).unwrap()) 239 .unwrap() 240 } 241 242 #[wasm_bindgen] 243 pub fn advertisements(base: String) -> String { 244 let values: Vec<_> = (1..=2) 245 .map(|last| { 246 nostr::EventBuilder::new(nostr::Kind::Custom(10050), "") 247 .tags([nostr::Tag::parse(["relay", base.as_str()]).unwrap()]) 248 .custom_created_at(nostr::Timestamp::from_secs(now() - 1)) 249 .sign_with_keys(&key(last)) 250 .unwrap() 251 .as_json() 252 }) 253 .collect(); 254 serde_json::to_string(&values).unwrap() 255 } 256 #[wasm_bindgen] 257 pub async fn verify_client(base: String, label: String) -> Result<String, JsValue> { 258 let mut passed = Vec::new(); 259 let existing = Existing::create(&label).await?; 260 // Build the alternate selection without exposing a key or mutating storage. 261 let mut wrong_pin = existing.fingerprint; 262 wrong_pin[0] ^= 1; 263 let wrong = BrowserConfig::existing( 264 existing.namespace.clone(), 265 reference_copy(&existing.reference), 266 wrong_pin, 267 existing.input.clone(), 268 proof_copy(&existing.proof), 269 access(), 270 ); 271 require( 272 Client::open(wrong).await.is_err(), 273 "wrong provider identity must refuse", 274 )?; 275 let (client, scope) = existing.open(&base).await?; 276 let callbacks = signer(&client).await?; 277 client.start(StartMode::Online).await.map_err(fail)?; 278 require( 279 socket_count() == 0, 280 "open, attach and start cannot perform network work", 281 )?; 282 passed.push("real existing IndexedDB and explicit authority, inert startup"); 283 let operation = id(); 284 let deadline = now() + 120; 285 let receipt = client 286 .inbox() 287 .inquire(context(&scope, operation, deadline), inquire()) 288 .await 289 .map_err(fail)?; 290 require( 291 receipt.durable() && receipt.business_result().is_some(), 292 "real inquiry must install business result", 293 )?; 294 let original = receipt.operation_checkpoint(); 295 let message = receipt.business_result().unwrap().id().to_string(); 296 let replay = client 297 .inbox() 298 .inquire(context(&scope, operation, deadline), inquire()) 299 .await 300 .map_err(fail)?; 301 require( 302 replay.operation_checkpoint() == original, 303 "replay must retain original checkpoint", 304 )?; 305 passed.push("shared T0 T1 real signing S T2 and self/peer relay acceptance"); 306 passed.push("same original command does not replace issuance or publication"); 307 require( 308 client.close().await.map_err(fail)?.storage_closed(), 309 "actual close receipt", 310 )?; 311 storage_callbacks_closed()?; 312 require( 313 callbacks.closed.get() == 1 && callbacks.quiesced.get() == 1, 314 "original signer callbacks close once", 315 )?; 316 require( 317 client.close().await.map_err(fail)?.storage_closed(), 318 "repeated close", 319 )?; 320 require( 321 client.operations(&scope).get(operation).await.is_err(), 322 "closed resource admission remains closed", 323 )?; 324 let sockets = socket_count(); 325 let (local, scope) = existing.open(&base).await?; 326 local.start(StartMode::LocalOnly).await.map_err(fail)?; 327 let retained = local 328 .operations(&scope) 329 .get(operation) 330 .await 331 .map_err(fail)? 332 .ok_or_else(|| JsValue::from_str("missing original operation"))?; 333 require( 334 retained.operation_checkpoint() == original, 335 "actual reopen retains original checkpoint", 336 )?; 337 require( 338 socket_count() == sockets, 339 "reopen/read/local start cannot open a socket", 340 )?; 341 passed.push("actual protected close/reopen retains original completed operation"); 342 let lost = id(); 343 let inbox = local.inbox(); 344 let mut observer = Box::pin(inbox.inquire(context(&scope, lost, deadline), inquire())); 345 require( 346 observer.as_mut().now_or_never().is_none(), 347 "owned command starts pending", 348 )?; 349 drop(observer); 350 local.close().await.map_err(fail)?; 351 let (resumed, scope) = existing.open(&base).await?; 352 let callbacks = signer(&resumed).await?; 353 resumed.start(StartMode::Online).await.map_err(fail)?; 354 let pending = resumed 355 .operations(&scope) 356 .get(lost) 357 .await 358 .map_err(fail)? 359 .ok_or_else(|| JsValue::from_str("observer loss erased original T0"))?; 360 require( 361 pending.durable() && pending.business_result().is_none(), 362 "local observer loss retains T0 without invented signing", 363 )?; 364 passed.push("lost observer and close drain preserve actual durable T0"); 365 let completed = resumed 366 .operations(&scope) 367 .resume(lost, None) 368 .await 369 .map_err(fail)?; 370 require( 371 completed.durable() && completed.business_result().is_some(), 372 "explicit resume must finish original inquiry", 373 )?; 374 let resumed_message = completed 375 .business_result() 376 .and_then(|value| value.as_chat()) 377 .ok_or_else(|| JsValue::from_str("resumed inquiry must retain its actual chat result"))? 378 .id() 379 .to_string(); 380 resumed.close().await.map_err(fail)?; 381 storage_callbacks_closed()?; 382 require(callbacks.closed.get() == 1, "resumed signer scope disposed")?; 383 passed.push("explicit original-operation resume signs and delivers after reopen"); 384 passed.push("ordered repeated close and permanent admission"); 385 Ok(serde_json::json!({"passed":passed,"messages":[message,resumed_message]}).to_string()) 386 } 387 #[wasm_bindgen] 388 pub async fn verify_publications(raw_events: String, expected: String) -> Result<(), JsValue> { 389 let events: Vec<String> = serde_json::from_str(&raw_events).map_err(fail)?; 390 let expected: Vec<String> = serde_json::from_str(&expected).map_err(fail)?; 391 require( 392 events.len() == 4 && expected.len() == 2, 393 "original self/peer envelope counts", 394 )?; 395 let mut seen = Vec::new(); 396 for raw in events { 397 let event = nostr::Event::from_json(&raw).map_err(fail)?; 398 event.verify().map_err(fail)?; 399 let recipient = event 400 .tags 401 .iter() 402 .find(|tag| tag.as_slice()[0] == "p") 403 .ok_or_else(|| JsValue::from_str("missing envelope recipient"))? 404 .as_slice()[1] 405 .clone(); 406 let n = if recipient == key(1).public_key().to_hex() { 407 1 408 } else { 409 2 410 }; 411 require( 412 recipient == key(n).public_key().to_hex(), 413 "unapproved envelope recipient", 414 )?; 415 let message = nostr::nips::nip59::extract_rumor(&key(n), &event) 416 .await 417 .map_err(fail)?; 418 require( 419 message.sender == key(1).public_key() 420 && message.rumor.content == "ordinary browser inquiry", 421 "independent nested authentication and original text", 422 )?; 423 let id = message 424 .rumor 425 .id 426 .ok_or_else(|| JsValue::from_str("missing rumor ID"))? 427 .to_hex(); 428 require(expected.contains(&id), "exact installed business result")?; 429 seen.push((id, n)); 430 } 431 seen.sort(); 432 seen.dedup(); 433 require( 434 seen.len() == 4, 435 "each original rumor has independent self and peer delivery", 436 ) 437 } 438 439 fn listing() -> radroots_protocol::listing::PublishInput { 440 let value = serde_json::json!({ 441 "id":"01".repeat(16),"title":" Browser carrots 🥕 ","summary":"Quote required", 442 "description_markdown":"Exact public terms","published_at":now().to_string(), 443 "profile":{"profile":"radroots.listing","version":1,"state":"active", 444 "product":{"name":"Carrots","description":"Fresh carrots","producer":null,"origin_summary":null}, 445 "default_option":"02".repeat(32), 446 "options":[{"id":"02".repeat(32),"label":"Bunch","unit":{"type":"package","label":"bunch","contents":{"type":"unspecified"}}, 447 "increment":"1","minimum":"1","price":{"type":"quote_required"},"supply":{"type":"available","amount":"10"},"lead_seconds":"0"}], 448 "fulfillment":{"modes":["pickup"],"area":"Example","lead_seconds":"0"},"authority":null,"media":[]}}); 449 radroots_protocol::listing::PublishInput::parse(&serde_json::to_vec(&value).unwrap()).unwrap() 450 } 451 452 #[wasm_bindgen] 453 pub async fn verify_listing(base: String, label: String) -> Result<String, JsValue> { 454 use radroots_execution::{BusinessInstallation, Issuance, OperationKind, TargetObservation}; 455 let mut passed = Vec::new(); 456 let existing = Existing::create_scope(&label, true).await?; 457 let (client, scope) = existing.open(&base).await?; 458 let callbacks = signer(&client).await?; 459 client.start(StartMode::Online).await.map_err(fail)?; 460 let sockets = socket_count(); 461 let operation = id(); 462 let input = listing(); 463 let deadline = now() + 120; 464 let original = client 465 .listings() 466 .publish(context(&scope, operation, deadline), input.clone()) 467 .await 468 .map_err(fail)?; 469 require( 470 original.kind() == OperationKind::Listing 471 && original.durable() 472 && original.business_installation() == BusinessInstallation::Installed 473 && original.issuance() == Issuance::Obtained, 474 "actual installed public receipt", 475 )?; 476 let value = original 477 .business_result() 478 .ok_or_else(|| JsValue::from_str("missing public result"))?; 479 require( 480 value.text().title() == " Browser carrots 🥕 " 481 && original.message_id().is_none() 482 && original.artifacts().iter().all(|v| v.recipient().is_none()), 483 "typed public result without private placeholders", 484 )?; 485 require( 486 original.delivery_observations().len() == 1 487 && original.delivery_observations()[0].outcome() == TargetObservation::Rejected, 488 "actual original relay rejection", 489 )?; 490 let revision = value.revision().to_string(); 491 let digest = original.command_digest(); 492 let checkpoint = original.operation_checkpoint(); 493 let replay = client 494 .listings() 495 .publish(context(&scope, operation, deadline), input.clone()) 496 .await 497 .map_err(fail)?; 498 require( 499 replay.operation_checkpoint() == checkpoint, 500 "replay retains original receipt", 501 )?; 502 require( 503 socket_count() == sockets + 1, 504 "public listing uses only configured publication socket", 505 )?; 506 passed.push("public shared T0 T1 S T2 and actual rejected D, typed Listing and exact replay"); 507 client.close().await.map_err(fail)?; 508 require( 509 callbacks.closed.get() == 1, 510 "original public signer callbacks close once", 511 )?; 512 let (reopened, scope) = existing.open(&base).await?; 513 let callbacks = signer(&reopened).await?; 514 reopened.start(StartMode::Online).await.map_err(fail)?; 515 let sockets = socket_count(); 516 let queried = reopened 517 .operations(&scope) 518 .get_matching(operation, Some(digest)) 519 .await 520 .map_err(fail)? 521 .ok_or_else(|| JsValue::from_str("missing original public operation"))?; 522 require( 523 queried.operation_checkpoint() == checkpoint && socket_count() == sockets, 524 "public open/start/query cannot redispatch", 525 )?; 526 require( 527 queried 528 .business_result() 529 .and_then(|v| v.as_listing()) 530 .is_some(), 531 "public query family", 532 )?; 533 passed.push( 534 "actual protected close/reopen retains original public checkpoint without network work", 535 ); 536 let resumed = reopened 537 .operations(&scope) 538 .resume(operation, Some(digest)) 539 .await 540 .map_err(fail)?; 541 require( 542 resumed 543 .delivery_observations() 544 .iter() 545 .any(|v| v.outcome() == TargetObservation::Accepted) 546 && resumed.issuance_window() == original.issuance_window() 547 && resumed.installation_transaction_id() == original.installation_transaction_id(), 548 "explicit retry retains original issuance and installation", 549 )?; 550 let attempts = resumed.delivery_attempts(); 551 require( 552 attempts.len() == 2 553 && attempts[0].envelope_digest() == attempts[1].envelope_digest() 554 && attempts[0].intent().publication_policy_digest() 555 == attempts[1].intent().publication_policy_digest(), 556 "retry retains original exact event and policy", 557 )?; 558 let mut ordinals: Vec<_> = attempts 559 .iter() 560 .flat_map(|v| v.target_ordinals().iter().copied()) 561 .collect(); 562 ordinals.sort(); 563 require( 564 ordinals == [1, 2], 565 "stable-identity sorted attempts retain both actual ordinals", 566 )?; 567 passed.push( 568 "explicit public delivery retry retains original bytes, policy and per-target attempts", 569 ); 570 let buyer = Existing::create(&(label.clone() + "_buyer")).await?; 571 let (other, buyer_scope) = buyer.open(&base).await?; 572 let other_callbacks = signer(&other).await?; 573 other.start(StartMode::Online).await.map_err(fail)?; 574 require( 575 other 576 .listings() 577 .publish(context(&buyer_scope, id(), deadline), input.clone()) 578 .await 579 .is_err(), 580 "buyer cannot publish public seller listing", 581 )?; 582 require( 583 reopened 584 .listings() 585 .publish(context(&buyer_scope, id(), deadline), input) 586 .await 587 .is_err(), 588 "foreign authenticated attachment cannot authorize this client", 589 )?; 590 other.close().await.map_err(fail)?; 591 require( 592 other_callbacks.closed.get() == 1, 593 "buyer signer callbacks close once", 594 )?; 595 reopened.close().await.map_err(fail)?; 596 require( 597 callbacks.closed.get() == 1, 598 "reopened public signer callbacks close once", 599 )?; 600 storage_callbacks_closed()?; 601 passed.push("buyer/foreign scope refusals and ordered actual resource close"); 602 Ok(serde_json::json!({"passed":passed,"revision":revision}).to_string()) 603 } 604 605 #[wasm_bindgen] 606 pub fn verify_listing_publications(raw_events: String, expected: String) -> Result<(), JsValue> { 607 let events: Vec<String> = serde_json::from_str(&raw_events).map_err(fail)?; 608 require( 609 events.len() == 2 && events[0] == events[1], 610 "only original exact public bytes are retried", 611 )?; 612 for raw in events { 613 let event = nostr::Event::from_json(&raw).map_err(fail)?; 614 event.verify().map_err(fail)?; 615 require( 616 event.kind.as_u16() == 30402 617 && event.id.to_hex() == expected 618 && event.pubkey == key(1).public_key(), 619 "independently verified public author, revision and kind", 620 )?; 621 require( 622 event.tags.iter().all(|tag| tag.as_slice()[0] != "p"), 623 "public event has no private envelope recipient", 624 )?; 625 } 626 Ok(()) 627 }