diff --git a/AGENTS.md b/AGENTS.md index fe82992..1a3510b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,11 +8,20 @@ chapter 15 gives trystero's design decisions with their reasons, and its () first. This file holds only what is specific to trystero. -- **The original, and its wire.** trystero ports Trystero 0.26.0 - (, MIT). The wire is Trystero's and never - changes: what a Trystero JS peer or a page sees is kept byte for byte, the - topic prefixes `"Trystero@"` and `"Trystero:"`, the handshake's - `"__trystero_pw"`, every protocol constant and message layout under +- **The port.** trystero ports Trystero 0.27.0, upstream commit `8d3f57e`, + as the change `trystero-0-27` (proposals) and its design D1 to D23 decided. + Its oracle and interop lanes meet Trystero 0.27.0. Every value of 0.27.0's + wire is proven against `test/fixtures/expected/trystero-0.27.0.json`, + which only `test/oracle/record_0_27.mjs` writes, run against a checkout of + the pin (`node test/oracle/record_0_27.mjs `), or over the + published packages (`--dist`, the oracle lane's `generated-vectors`); its + copy in the proposals is `reference/vectors/`. +- **The original, and its wire.** trystero ports Trystero 0.27.0 + (, MIT). The wire is Trystero's: what a + Trystero JS peer or a page sees is kept byte for byte, 0.27.0's topics, + keys, sealing, ids, identities, handshake, relays and action wire, the + handshake's member `"__trystero_id"`, every protocol constant and message + layout under `include/webcpp/trystero/protocol/`, the default relays in their order, and the names the chat's page calls, `joinRoom` and `sendText`, and the interop page's `window.leave`. A rename never replaces the word `trystero`: @@ -22,8 +31,8 @@ holds only what is specific to trystero. and the examples' app ids `webcpp-trystero-quick-start` and `webcpp-trystero-chat`. `LICENSE-TRYSTERO.txt` is Trystero's notice, unchanged, and the README names what derives from Trystero. Comments cite - Trystero's code as `dist/:`, the files of - `@trystero-p2p/core` 0.26.0 as published. + 0.27.0's code by its source file, `relay-manager.ts:122-124`, the files of + its `packages/core/src` and `packages/nostr/src`. - **The core and the platform.** ``, the headers directly under `include/webcpp/trystero/`, `protocol/` and `detail/` are the core: the rooms over the backend interface of `backend.hpp`, which @@ -36,7 +45,7 @@ holds only what is specific to trystero. `webrtc/` is its WebRTC, over webcpp::webrtc, on both targets: one peer connection and one data channel, which hold `webcpp::webrtc::basic_peer_connection` and `basic_data_channel` over a - `std::pmr::polymorphic_allocator` on the app's resource and keep + `std::pmr::polymorphic_allocator` on the room's resource and keep trystero's policies over them. Its relays are one session of webcpp::beast on both targets (`platform/websocket.hpp`), natively over Boost.Beast's own stream and in a page over webcpp::beast's page `WebSocket`. Its timer @@ -45,33 +54,39 @@ holds only what is specific to trystero. targets, `std::chrono::system_clock` floored to whole seconds (`unix_now`) and `std::chrono::steady_clock` (`steady_now`), which Emscripten reads from the page's `Date.now()` and `performance.now()`. - Two parts are the target's own, chosen by `WEBCPP_TARGET_EMSCRIPTEN`, - config's (neither the library nor its tests test `__EMSCRIPTEN__`): the - sealer (`platform/sealer.hpp`), natively OpenSSL's AES-256-GCM and in a - page `crypto.subtle` through webcpp::asio's `browser::async_await`; and - the platform's one source of randomness, - `platform::detail::fill_random` (`platform/entropy.hpp`), whose result is - checked: natively OpenSSL's `RAND_bytes`, in a page - `crypto.getRandomValues`, at most 65536 bytes a call, from an `EM_ASM` - block that catches what it throws (Emscripten's `getentropy` let a - missing or throwing one through into WebAssembly). Without randomness - `random()` aborts the program and a seal fails with - `error::backend_failure`. `platform/page.hpp`, which builds only on + The backend has no sealer (design D4): a room seals and opens its signals + in the call, with webcpp::crypto's AES-256-GCM (`protocol/seal.hpp`), + natively OpenSSL's and on emscripten BearSSL's. One part is the target's + own, chosen by `WEBCPP_TARGET_EMSCRIPTEN`, config's (neither the library + nor its tests test `__EMSCRIPTEN__`): `derive_password_master`, the PBKDF2 + of a room's password (D5), natively `webcpp::hash::async_pbkdf2` on a + one-thread `webcpp::asio::thread_pool` the backend makes at the first call + and joins when destroyed, in a page `async_pbkdf2` over + `backends::webcrypto`. The platform's one source of randomness is + webcpp::crypto's `random_device`; without it `random()` aborts the + program. On emscripten it reads `crypto.getRandomValues` through + `getentropy`, which lets a missing or throwing one through into + WebAssembly: the guard trystero 0.1.0 had (`entropy.hpp`) is gone with + it, and belongs to webcpp::crypto (design Open Question 1). Secrets are + held in `webcpp::crypto::secret` or wiped with trystero's own + `detail::wipe` (`detail/wipe.hpp`) before release, the password's copies in + the app, the keys' cache and each derivation included: a library never calls + another's `detail` (ruling R19), until webcpp::crypto publishes a wipe. + `platform/page.hpp`, which builds only on emscripten (an `#error` elsewhere), holds what a page's program uses beside the backend, `platform::page_call` and `platform::js_string`; a program includes no source file of trystero's: `/webcpp/asio//asio` links the browser runtime. `test/Jamfile` compiles each header alone on the targets that build it, in three calls: the core; `platform/backend.hpp`, - `entropy.hpp`, `sealer.hpp`, `websocket.hpp` and `webrtc/` on both - targets, with `/webcpp/trystero//platform`; and `platform/page.hpp` on + `websocket.hpp` and `webrtc/` on both targets, with `/webcpp/trystero//platform`; and `platform/page.hpp` on emscripten. - **The backend interface stays.** The rooms hold the backend's peer connections and data channels through `backend::peer_connection` and `backend::data_channel`, abstract classes, as chapter 15 decided: the memory relays (`test/support/memory_backend.hpp`) implement them for the rooms of the tests, on both targets, where node has no WebRTC, and the - interop's native peer wraps the platform backend's (`delayed_channel`, - `observed_connection`). Their one implementation over a platform is + interop's native peer derives from the platform backend to count the + connections it makes. Their one implementation over a platform is `webrtc/`, which webcpp::webrtc's table "trystero's backend, part by part" maps part by part. The interface's clocks are std::chrono's, so that no unit is converted at the seam: `factory::steady_now` returns the @@ -139,24 +154,27 @@ holds only what is specific to trystero. fits (616 bytes for the room test), so they no longer catch one. There is one timer, the core's `detail::timer` over webcpp::asio's `steady_timer`, on both targets, which `timer` tests on both. -- **The dependencies.** libsecp256k1 (every room) is webcpp's own build, - `/third_party//secp256k1` (v0.8.0, from `third_party/libs/secp256k1`), which - `/webcpp/trystero//trystero` names; its tables come from - `webcpp-secp256k1-tables` (see `doc/building.adoc`). Nothing is installed +- **The dependencies.** A room signs its Nostr events with webcpp::crypto's + secp256k1 (`/webcpp/crypto//secp256k1-default`, which `/webcpp/trystero//trystero` + names), over webcpp's own build of libsecp256k1 (v0.8.0, from + `third_party/libs/secp256k1`), and its identities and handshakes with + webcpp::crypto's P-256 (`/webcpp/crypto//p256-default`, BearSSL on every + target); trystero includes no header of either itself. Its tables come from `webcpp-secp256k1-tables` (see + `doc/building.adoc`). Nothing is installed outside the checkout, once the pinned submodules are initialised. `/webcpp/trystero//trystero` (`build.jam`'s `tag::trystero[]`) is the rooms alone, the core: `parts`, its headers, Boost, webcpp::document (`/webcpp/document//document`, with Boost.JSON's and Boost.Charconv's - definitions), config, webcpp::asio and libsecp256k1, and under Asyncify - the list that leaves Boost.JSON's parser uninstrumented + definitions), config, webcpp::asio, webcpp::hash and webcpp::crypto (its + secp256k1 over libsecp256k1), and under Asyncify the list that leaves + Boost.JSON's parser uninstrumented (**webcpp::document**, below); on no target does it bring webcpp::webrtc, and the tests over the memory relays use it alone. `/webcpp/trystero//platform` (`tag::platform[]`) is the platform backend's target on both targets, the rooms and `platform-parts`, the backend over `parts`, alternatives by `emscripten`, which a native program and a page's program both name. A test of a part that parses no JSON - (`timer`, `platform_websocket_url`, `platform_page_call`, - `platform_page_sealer`, `platform_page_sealer_allocation` and their twins + (`timer`, `platform_websocket_url`, `platform_page_call` and their twins without exceptions) links `parts` or `platform-parts` in place of the rooms, `$(part)` or `$(platform-part)` in `test/Jamfile`, without that list: Binaryen warns of a pattern that names none of a program's @@ -174,7 +192,7 @@ holds only what is specific to trystero. `LIBDATACHANNEL_ROOT`, `OPENSSL_ROOT` or installed binary is consulted. Initialize their sources with `git submodule update --init --recursive third_party/libs/libdatachannel third_party/libs/openssl - third_party/libs/secp256k1`. Native builds + third_party/libs/secp256k1 third_party/libs/bearssl`. Native builds need CMake 3.21 or newer in addition to OpenSSL's Perl and Make/nmake. B2 forwards the configured compiler, C++ ABI, runtime and optimization flags, and isolates artifacts by their effective configuration. The @@ -245,7 +263,7 @@ holds only what is specific to trystero. - **The backend's WebRTC policies** (`webrtc/`), on the executor, on both targets: a text message, or a binary one larger than a room frame, is dropped after `async_receive` (webcpp::webrtc reads every message into a - vector of the app's resource, at most `max_message_size`, 256 KiB); the + vector of the room's resource, at most `max_message_size`, 256 KiB); the connection's state and its ICE state merge into one, as a page sees them; a local candidate leaves as the JSON of an `RTCIceCandidateInit` and a remote one is read from it; `buffered_amount_low` is reported when the @@ -258,30 +276,34 @@ holds only what is specific to trystero. is passed to webcpp::webrtc on both targets; a page leaves it empty, since webcpp::webrtc refuses to bind there. - **Channel handoff.** Valid frames received before a message handler is - installed wait in an app-resource FIFO, at most 64 frames for 10 s from the - first, on both targets now. Overflow or expiry closes the channel; close - clears the queue. The timer is the factory's (`make_timer` with the app's - resource), whose waits a restart or a cancel invalidates. Installing a - receiver posts a resource-allocated flush, never an inline call. Each frame - checks the current handler and open channel, and a message already read - ahead of the flush drains older frames when a receiver exists. A transport - closed during adoption, before binding, forgets its negotiation and - restarts announcements. `platform_peer_connection` tests real queued events - (the offerer made on an executor the test runs), FIFO, replacement, close, - limits and resource release (`webrtc::data_channel::pending_frames`); - `shared` tests closure during adoption, and interop controls native open - delivery while a JS peer sends both rooms' presence first. -- **A room frame advertises its room.** A frame of a local room's token that - a connection keeps records the token as the remote's advertisement, as its - presence does (64 tokens at most; a frame never ends the connection for a - 65th), and the room binds on it. Trystero sends a room's presence once per - connection, from the open of its channel, and Chrome can drop what a page - sends on an answering channel as it opens: measured in a 2-CPU Linux - container, 8 of 240 runs of the interop's delayed-open scenario, Chrome - logging "Send failed INVALID_STATE" for both presence frames and the native - peer's SCTP receiving neither. Waiting for presence alone left the room - unbound for good, with the page's frames of the room kept and expiring. - `connection` and `shared` drop the presence over the memory relays. + installed (the open event and a first message reach the executor in either + order) wait in a room-resource FIFO under `peer_link`'s unbound bounds, + 0.27.0's `maxQueuedDataFrames` and `maxRoomFrameBytes` (64 frames of at + most 17 KiB, `protocol::max_queued_data_frames` and + `protocol::max_room_frame_bytes`), on both targets. One more, or a longer + one, closes the channel; close clears the queue. No timer: the link's 10 s + start as it takes the frames, and the signaling closes a channel no link + takes. Installing a receiver posts a resource-allocated flush, never an + inline call. Each frame checks the current handler and open channel, and + a message already read + ahead of the flush drains older frames when a receiver exists. + `platform_peer_connection` tests real queued events (the offerer made on an + executor the test runs), FIFO, replacement, close, limits and resource + release (`webrtc::data_channel::pending_frames`); `peer_link` tests the + link's bounds over a memory pair. +- **Wide chunks.** `backend::peer_connection::max_message_size` is + `sctp.maxMessageSize`; the platform backend reads webcpp::webrtc's + `peer_connection::max_message_size()` (natively libdatachannel's + `rtcGetRemoteMaxMessageSize` once a remote description is applied, in a + page the browser's `sctp.maxMessageSize`, both within 256 KiB), the limit + its channels' sends check. A send the platform channel refuses closes the + channel, so that a transfer ends with the peer rather than wait on a chunk + never sent; the memory network's `send_limit` refuses likewise. + `peer_link::max_bulk_frame_bytes` is 64 KiB at 64 KiB or more, else 16 KiB, + and the action wire offers wide on 64 KiB; the memory network says 256 KiB + unless a test sets `memory_network::max_message_size`. + `room_test` checks the frames against the vectors' `bulk` and `bulk_wide` + cases. - **embind.** Every program on emscripten links `-lembind`, which `/webcpp/asio//asio` adds as a linker flag, and `/webcpp/trystero//trystero` brings: `on`, b2's own feature, is not free, and b2 ignores it @@ -291,11 +313,11 @@ holds only what is specific to trystero. failed as a value, which the C++ turns into the error its interface has: a `WebSocket` constructor or `send` in webcpp::beast's page stream, which turns a socket that cannot be made into an error, so that its relay - reports a close; a Web Crypto method in an `EM_ASM` block of an inline - function of `platform/sealer.hpp`, made inside an `async` function, so - that what it throws rejects its promise, whose settlement is read only when - it is an `ArrayBuffer`; `crypto.getRandomValues` in an `EM_ASM` block of - `platform/entropy.hpp`, which returns its failure. Every event and every + reports a close; a PBKDF2 the page rejects, which webcpp::hash's Web + Crypto backend turns into the derivation's `error::backend_failure`. + `crypto.getRandomValues`, which webcpp::crypto's + `random_device` reads through `getentropy`, is the exception (above). + Every event and every page call enters C++ through webcpp::asio's bridge, which restores WebAssembly's stack pointer, catches a C++ exception in C++, which frees it (one that reached JavaScript would keep its object for good), and only @@ -305,8 +327,7 @@ holds only what is specific to trystero. io_context. A message that is not a frame is dropped on the executor, after webcpp::webrtc read it: a text as the few bytes it holds, a binary one at most 256 KiB, past which the channel closes. The platform's tests - on emscripten (`platform_backend`, `platform_sealer`, - `platform_websocket_unreachable`, `platform_websocket_url` and every + on emscripten (`platform_backend`, `platform_websocket_unreachable`, `platform_websocket_url` and every `platform_page*`) run under node with exceptions and without them (`*_no_exceptions`), and the interop lane passes both ways. @@ -315,15 +336,14 @@ holds only what is specific to trystero. reads the relays can send any signal in any peer's name. - Nothing a peer sends changes a negotiation before it opens with the room key: an offer, an answer or a candidate that does not open is - counted, reported once per negotiation, and changes nothing else. A - flood of fresh ids makes each a negotiation, so the reports are paced: - the first of a quiet 10 s goes to `on_error` at once, with its peer, - and the others of those 10 s in one report, with no peer and their - number. - - A sealed offer or answer holds neither its offer id nor a peer id - (Trystero's wire), so one recorded from the relays still opens when - anyone resends it in its sender's name, and so does the room's own, sent - back to it. A room remembers, by the SHA-256 of their opened text, the + counted and changes nothing else. An offer or an answer is reported to + `on_error` as `decrypt_failed`, with its peer and stage, at most once a + minute per peer and stage, the last 512 remembered, as 0.27.0 reports + them; a candidate is not reported. + - A sealed offer or answer is bound by its AAD, `||` (0.27.0's), to its kind, its sender and its offer: one recorded from + the relays opens only as what it was. Resent so, it still opens, and so + does the room's own, sent back to it under its own id. A room remembers, by the SHA-256 of their opened text, the last 1024 offers and answers it made or acted on (`detail::signaling::remembered_descriptions`), and refuses one that comes to it as a peer's: it changes nothing and is logged. It makes or @@ -340,30 +360,28 @@ holds only what is specific to trystero. alter anything the peers exchange, join the room, or touch peers already joined; a joined peer that drops is a new peer again. The room refuses only what it made or already acted on. Only a wire that - seals the offer id and both peer ids closes this, which Trystero would - have to share (reported upstream). + also seals the receiver's id closes this; 0.27.0's signed handshake, + which follows each connection, admits only the peer whose key derives + the id it connected as. - A room holds at most `detail::signaling::max_unconnected_peers` (32) negotiations with peers it is not connected to. A negotiation whose offer and answer expire without a connection is dropped, an idle one gives its place to a new peer, and a new peer beyond the bound is - refused and logged once. Idle means no connection and no offer of the - peer being opened (`negotiation::opening_offer`): the one idle longest + refused and logged once. Idle means no connection: the one idle longest goes, and of those idle as long, as at one instant of a page's coarse clock, the one taken first (`negotiation::admitted`), never the first in - id order. An offer the sealer is opening keeps its place, so new ids - that arrive meanwhile cannot have the room drop it unopened (`room`'s - `an_offer_being_opened_keeps_its_place` and - `a_flood_of_offers_at_one_instant_is_bounded`, over the memory backend's - `hold_sealer_opens`). - - A negotiation opens one offer of its peer at a time, as Trystero answers - one at a time (`dist/signal-handler.mjs:264-323`): another offer in that - name is ignored until it is opened, and the same offer through another - relay meanwhile has the answer sent there too, as Trystero's replay - records its relay. So the room opens at most 32 offers at once, and - offers in one name, however many, hold one open and one copy of an offer - (`room`'s `offers_in_one_name_are_opened_one_at_a_time`). As with - Trystero, a forged offer opened first has the peer's own, arriving - meanwhile, wait until the peer sends it again, 2 s later. + id order (`room`'s `a_flood_of_offers_at_one_instant_is_bounded`). A + signal opens in the call that reads it, so no offer waits unopened for + its place. + - A negotiation answers one offer of its peer at a time, as Trystero + answers one at a time: another offer in that name is ignored while it + answers one, and the same offer through another relay meanwhile has the + answer sent there too, as Trystero's replay records its relay. So offers + in one name, however many, hold one answer (`room`'s + `offers_in_one_name_are_answered_one_at_a_time`). As with Trystero, an + earlier offer of the peer's, resent by a watcher and answered first, has + the peer's own, arriving meanwhile, wait until the peer sends it again, + 2 s later. - A room makes at most `max_connections_per_window` (64) connections in any 57 s, however soon they end. The platform backend makes at most `backend_config::max_peer_connections_per_minute` (256) in any minute, @@ -374,10 +392,12 @@ holds only what is specific to trystero. frees them, as Chromium counts them against its 500 (measured with headless Chrome: the 501st throws "Cannot create so many PeerConnections", and a closed one counts until a collection). - - A signal's fields are bounded in `protocol/signal.hpp`: the peer id - (64 bytes; Trystero's are 20), the offer id, a sealed offer or answer - (64 KiB) and a sealed candidate (16 KiB, above the 8192 bytes of - plaintext Trystero takes). + - A signal is refused where 0.27.0's `parseSignalEnvelope` refuses it + (`protocol::read_signal`): a peer id of other than 20 base62 + characters, an offer id outside `[\w.~:!-]{1,64}` (or none with an + offer, answer or candidate), a sealed offer or answer past 64 Ki UTF-16 + code units, a sealed candidate past 4,096; the oracle's + `signal_envelopes` cases prove each refusal on 0.27.0 itself. - A room asks a peer below it to offer at most once in 5.3 s per relay, Trystero's announce interval, so a flood of low ids does not have the relays rate-limit the room. @@ -419,66 +439,77 @@ holds only what is specific to trystero. back as a new peer, with the same id, and is kept out the same way: the room has no renegotiation that would keep its place. Trystero JS bounds none of this. -- **The app and shared admission.** An `app` scopes one self id, one - immutable password and one connection per remote peer, with no static - registry. `app_config::password`, after `self_id`, is copied into the - app's resource; every room reads it there. `room_options` has no password. - Different passwords require separate apps with distinct self ids; their - connections, presence and tokens are never reused. The initial encrypted - signaling authenticates a protected app's password before any room can - reuse that connection. `join` returns a result, refusing duplicates - (`already_joined`) and a 65th room (`too_many_rooms`), counting farewells - until withdrawal. A changed domain password requires a new app. - Configuration errors go to `app::on_error`; room errors name peer - problems. A passwordless app's connected peers can echo another room's - token and join it. The Trystero JS 0.26.0 wire is unchanged: a JS page - that mixes room passwords retains its one-way handshake exposure, - including admission to its higher-id rooms without their password and - offline-guess material. C++ app domains protect the C++ app's admission; - they do not repair a remote JS page. A peer that already knows the domain - password can still send a bad room proof, kicked and paced by rebinding. -- **Shared connection bounds.** A connection accepts 64 advertised tokens - and at most 64 kept frames for local unbound rooms, expiring 10 s after - the first, and drops unknown room tokens. A malformed envelope ends all - bindings. A kick ends only its binding; if the last binding was kicked, - close at once. After departures, idle expiry is `app_config::idle_timeout`, - 123,333 ms by default, 0 closes immediately. A remote must advertise the token - itself before any binding, by its presence or a kept room frame; forged relay - announcements bind nothing. - Rebinding after a kick or peer leave uses the larger of handshake timeout - and 10 s plus 1 s, doubling to 5 minutes until a completed handshake or - connection end. The lower id refuses bindings during its own-kick - backoff and keeps frames; the higher drops frames after its own kick - until it sends presence and accepts the lower's presence immediately. - Reuse is a first-meeting path; later relay signals cannot shorten that - backoff. The initiator accepts correct answers to its last eight - challenges since the last completed handshake. Only the lower id reports - an invalid shared room proof. One room's departure does not close another's - transport; waiting sends take turns by binding at each drain. +- **The app and its rooms.** An `app` scopes one endpoint key, made when it + is made, whose compact key derives its peer id (0.27.0 has no custom one, + and `app_config` no `self_id`), one user identity (`app_config::identity` + or an ephemeral one, 0.27.0's `'custom'` and `'none'`; no `'local'`, + design D15 and D17), one immutable password, its relays' configuration, + the rooms' keys and the key records and verified signatures of peers and + users (`detail::identity_cache`, 0.27.0's bounds, per app, design D18), + with no static registry. `app_config::password` is copied into the app's + resource; every room derives its keys from it there, through the app's + `detail::room_keys_cache` (design D6: at most 64 rooms' keys, the least + recently used out, a failed derivation forgotten and reported as + `backend_failure`). `room_options` has no password. Different passwords + require separate apps with distinct self ids. `join` returns a result, + refusing a `max_users` of 0 or above 2^53 - 1 (`invalid_max_users`) and a + room joined (`already_joined`). Configuration errors go to + `app::on_error`; room errors name peer problems. An endpoint or user key + that cannot be made leaves the app without one, and each room it joins + reports `identity_failed`, then ends. +- **One connection per room and peer.** Each room negotiates its own + connection to each remote peer, in its own resource, as 0.27.0's rooms do + (design D9): its `detail::peer_link` keeps 64 frames of at most 17 KiB for + 10 s before the room binds it, then frames of at most 64 KiB, and ends at + `failed` and `closed`, or after 5 s of `disconnected`; frames travel bare. + Nothing of 0.1.0's sharing stays (presence frames, room tokens, rebinding, + idle connections, `max_rooms`, the password handshake `__trystero_pw`). + The room runs 0.27.0's identity handshake on each link + (`detail::handshake_manager` and `detail::identity_handshake`): the lower + id in UTF-16 order initiates, steps 1 to 3 as `@_hsdata`, the transcript + binding app, room, ids, nonces, fingerprints and users, the fingerprints + read from the last descriptions the signaling handled (design D20); 10 s, + 16 unread messages; ready frames `@_hsready` before the join. A pending + peer is absent from `peers()` and `users()`, and only its `@_hsdata`, + `@_hsready` and `@_leave` are read. A failed handshake reports + `handshake_failed` with 0.27.0's reason, once a run, and tells the peer to + leave. `max_users` counts users, refuses a new user with + `{"ok":false,"err":"room full"}`, and does not dial a refused peer again + while full. - **The memory relays.** `test/support/memory_backend.hpp`, in `webcpp::trystero::test`, is a backend in memory: Nostr relays that forward ephemeral events to matching subscriptions, peer connections that pair - through their descriptions, data channels that deliver in order, and a - sealer that opens only what was sealed under the same key, each event - posted to the `io_context`. A test of a whole room runs over it, on both - targets, without the network. + through their descriptions (`mem:` and an `a=fingerprint:sha-256` + line of the connection's own, `memory_description`), data channels that + deliver in order, and a password's derivation, webcpp::hash's PBKDF2 at + 1,000 iterations (`pbkdf2_iterations`), in the call, its completion posted + or held by `derive_delay` until `release_derivations`, each event posted to + the `io_context`. A peer's user is the one its handshake verified: a test + that needs one user with two peers makes two apps that import one + `user_identity`. The app's fixed endpoint key is a detail seam + (`detail::app_access::make` with an endpoint scalar, which + `test::endpoint_scalar` makes of a label, its peer id + `test::peer_id_of`; `test::ordered_labels` and + `test::label_beside` name apps whose ids are in an order a test needs). A + test of a whole room runs over it, on both targets, without the network. Its optional fault hooks use `std::size_t` connection ids, `on_made` (with ICE servers) and `peer_of`, a deliver/drop/hold filter, ordered - `release`, deferred one-end `open`, `inject` and `fail`. A held frame - holds every later frame from its sending end behind it. Buffered channels - drain up to `drain_per_post` bytes per post, delivering only complete - frames and reporting exact unsent bytes through `buffered`. Set + `release`, deferred one-end `open`, `inject` and `fail`; `on_random` + sees every draw of random bytes. A held frame holds every later frame + from its sending end behind it. Buffered channels drain up to + `drain_per_post` bytes per post, delivering only complete frames and + reporting exact unsent bytes through `buffered`. Set `virtual_clock` before making timers: `advance`, `step` and `poll_ready` run due timers and ready work deterministically, in due-time and registration order. The virtual clock is a `std::chrono::steady_clock::time_point` from the clock's epoch, which `steady_now` returns, and `unix_now` reads it as 2025-10-05T21:33:20Z plus its whole seconds; tests compare its durations exactly. Optional hook storage uses the default resource only - when enabled; allocation tests enable none. `connection`, `memory_backend`, `shared`, - `shared_no_exceptions` and `shared_hardened` cover these paths, with - sanitizers and library hardening checking resource lifetimes. + when enabled; allocation tests enable none. `memory_backend`, `peer_link`, + `handshake_manager` and `room` cover these paths, with sanitizers and + library hardening checking resource lifetimes. - **The oracle and the interop tests, trystero's own lanes.** - `test/oracle/` pins Trystero 0.26.0 (`trystero`, `@trystero-p2p/core` and + `test/oracle/` pins Trystero 0.27.0 (`trystero`, `@trystero-p2p/core` and `@trystero-p2p/nostr`, with `ws` 8.22.0 and `@noble/secp256k1` 3.2.0 for the local relay, which imports both, and werift 0.24.4, the WebRTC the twins give Trystero JS in Node as `rtcPolyfill`, which Trystero's README @@ -487,71 +518,65 @@ holds only what is specific to trystero. declares two own lanes. `oracle`, which names no target: `oracle.mjs` runs Trystero's own functions over the inputs of `test/fixtures/cases/protocol.json` and writes `expected.json`, which must - equal `test/fixtures/expected/expected.json` byte for byte, the file the - `protocol`, `signaling` and `platform_sealer` tests read, and `webcpp.twins` + equal `test/fixtures/oracle/expected.json` byte for byte, the file the + `protocol` and `signaling` tests read, and `webcpp.twins` runs every twin of `example/` through `run_twin.mjs` (below); `update-expected` is the only writer of `expected.json` and of each - divergent twin's output. Trystero draws its self id from `Math.random` when - its core loads, so the oracle draws it from the fixture's pattern then: the - answerer's signals, which Trystero's own signal handler publishes for the - oracle's offers, carry it. `interop`, on native and emscripten (`native.trystero.interop` and + divergent twin's output. `generated-vectors` runs `record_0_27.mjs --dist` + over the published packages with the vectors fixture as its previous + output (`vectors.py`), which must write it again byte for byte; only + `update-generated` writes it here. `interop`, on native and emscripten (`native.trystero.interop` and `emscripten.trystero.interop` in the report): two driven tests, `interop_native` and `interop_browser`, whose driver `interop/run.mjs` - meets the C++ peer, the native one as a process or the browser's in - headless Chrome, with Trystero JS peers in Chrome, over the in-memory - Nostr relay `interop/relay.mjs` on 127.0.0.1, with the existing scenarios and the shared scenarios below: - C++ offering, Trystero JS offering with a password, a Trystero JS peer - that also sends malformed candidates (`js.html`'s - `malformed-candidate-to`), a first relay whose URL no WebSocket can be - made to, a Trystero JS peer that also sends text messages on its data - channel (`text-messages`), a C++ peer given a TURN server without - credentials, a watcher without the key that answers every offer with - garbage in the other peer's name (`forger.html`), the same watcher - resending, after the Trystero JS peer's connections drop - (`window.drop`), the sealed answer and then the sealed offer it recorded - of that peer (`mode=replay`), which the C++ peer must refuse, the same - watcher sending the C++ peer its own sealed offer back as the other - peer's answer, and as its offer by way of a decoy id (`mode=reflect`), - which the C++ peer must refuse too, a flood of announcements and of - unsealed offers from fresh peer ids (`window.flood`, - `window.floodOffers`) whose offers the watcher answers too, a relay text - longer than 1 MiB, once and then after every subscription - (`relay.broadcast`, `relay.options.afterSubscribe`), the C++ peer and a - Trystero JS page each in two rooms of one app (`room2`), sharing one - connection and one self id per app, a wrong password, - and a mesh of three; and, for the native peer, three - more: a room moved over the joined one, which must leave it as - destroying it does; a relay that ends the connection just as the peer - writes, with a text longer than 1 MiB or a reset - (`relay.options.strike`), which twelve peers in turn must survive and - reconnect after; and the driver's own check that a native peer killed - by a signal (`abort` on its standard input) is named at once. The - native peer and `platform_websocket` are built with the standard - library's own checks (libc++'s extensive hardening, libstdc++'s - assertions), so that a completion that touches a cleared container - fails at once. Both lanes are of the kind `original`, so the CI gives - them its Node. - - Shared scenarios on both targets cover: (1) two rooms on one - connection, with chat and 100 KB files both ways; (2) a third room - joining later by presence; (3) the page's rooms joined before the C++ - app's; (4) admission to a passwordless room by token and refusal by a - protected app with another password and self id, in both id orders; - (5) either side leaving one room while another keeps exchanging without a new connection; (6) departure from every room, - followed by idle expiry; (7) corrupted room proofs after authenticated - connection establishment, in both id orders, with - paced reports and the other room unaffected; (8) a 5,000-message flood - while another room pings; (9) a held handshake frame recovering in both - id orders with no false password report. Crossed adoption races allow - retries but fail by connection count above four constructions per side. - - Recovered-peer relay scenarios wait for fresh, currently joined peers on - both sides within the existing 30 s setup bound, then require a fresh - round-trip message before injecting a relay fault. A join reported by one - side alone does not prove the other's handshake completed. The controlled - `delayNextRecovery` fixture delays one outbound direction of the first - recovered channel for 12 s, beyond the C++ handshake deadline; a subsequent - connection must complete the setup. A departure after the relay fault - still fails. Console errors remain fatal, with RTCError fields recorded - alongside peer events so a failure is not reduced to `OperationError`. + meets the C++ peer (`interop/peer_room.hpp`), the native one as a process + (`native_peer.cpp`) or the browser's in headless Chrome (`peer.cpp` in + `cpp.html`), with Trystero 0.27.0 pages in Chrome (`js.html`, which does + what the C++ peer does, and `forger.html`), over the in-memory Nostr relay + `interop/relay.mjs` on 127.0.0.1. Its scenarios, each on both lanes: ids + and messages both ways (each side sees the other's peer and user ids, and + text, JSON, binary, a request and a ping go both ways, the C++ peer's id + below and then above the page's, so that each side offers in turn); JS + verifying the C++ signatures (each joins the other only once its handshake + verified them); 1 MiB each way in 64 KiB frames (js.html's + `window.largest`); one password meeting and another reported once as + `decrypt_failed` by the higher id of the two, the C++ peer's id put below + and then above the page's (its `key` parameter, the endpoint key's label, + through `detail::app_access`, the driver deriving the id with 0.27.0's + own code); identities exported by one side and imported by the other; + two C++ apps of one imported identity, which a page sees as two peers and + one user; `max_users` 2 refusing a third user both ways (`room_full`, + `room-full`); requests and pings; leaves both ways (peer and user leave); + a forged user signature (`forger.html`: a custom identity whose `sign` + passes 0.27.0's startup check, then signs with another key), which the + C++ peer reports as `handshake_failed`, once per handshake run, and never + joins; a mesh of two pages and a C++ peer; and the relays' connectivity, + each side going offline (the relay sees its subscriptions closed), + missing a new peer, and meeting it once online, then starting offline + (`offline` parameter). The relay keeps what it forwarded + (`relay.received`), counts a topic's subscribers (`relay.subscribed`) and + holds picked events until `relay.release()` (`relay.options.hold`). Then, + on the local relay, peers that mean harm, through the driver's own relay + client (`openPublisher`, 0.27.0's `createEvent`, `genKey` and `encrypt`): + malformed candidates sealed for the C++ peer's offer, which it drops and + logs; and a flood of unsealed offers and announcements from fresh ids, + bounded by the C++ peer's 32 negotiations and 64 connections (cpp.html's + `madePeerConnections`, the native peer's `made-connection` events), + `decrypt_failed` once per peer and stage. Then the C++ + peer's own robustness on the relays: a first relay whose URL no WebSocket + can be made to, a TURN server without credentials, a relay text longer + than 1 MiB, once and then after every subscription (`relay.broadcast`, + `relay.options.afterSubscribe`); and, for the native peer, a relay that + ends the connection just as the peer writes, with a text longer than 1 MiB + or a reset (`relay.options.strike`), which twelve peers in turn must + survive and reconnect after, and the driver's own check that a native peer + killed by a signal (`abort` on its standard input) is named at once. Every + wait of a scenario is for something that must happen, bounded far above + its time only to end a hang; what must not happen is checked once what + must has. The native peer and `platform_websocket` are built with the + standard library's own checks (libc++'s extensive hardening, libstdc++'s + assertions), so that a completion that touches a cleared container fails + at once. Both lanes are of the kind `original`, so the CI gives them its + Node. - Every peer gathers its ICE candidates on the machine alone: the C++ peers get `stun:127.0.0.1:9`, where nothing answers, in place of Trystero's public STUN servers, the native peer binds its connections to @@ -581,8 +606,8 @@ holds only what is specific to trystero. name with what each peer saw. A native peer that dies by a signal the driver did not send, as a crash does, is named as soon as it dies (`native#0: killed by SIGSEGV`), and every wait of its scenario ends. A - wire string changed in the C++ library (`"__trystero_pw"`) fails the - password scenario of both. + wire string changed in the C++ library (the handshake's + `"trystero:id-hs:v2"`) fails every scenario of both. ``` b2 -a libs/trystero/test/oracle//oracle @@ -595,25 +620,22 @@ holds only what is specific to trystero. these rules. - **The app's resource and the room's.** `app_config::memory` defaults to `std::pmr::get_default_resource()` and must not be null. It receives - app state, copied configuration including the immutable password, self id, - registry, logger and sink, - every log sentence from the app and its rooms, connections, advertised - tokens, kept frames, drain order and presence. Peer connections, data - channels and received frames use it even while a room negotiates them. + app state, copied configuration including the immutable password, the + endpoint key and self id, the ephemeral user identity, registry, the + rooms' keys, the key records and verified signatures, logger and sink, + and every log sentence from the app and its rooms. `room_options::memory`, the app's resource when null, receives room - state, bindings and drain waiters, negotiation records, rebinding - counts and backoffs, sealed texts, relay sockets, signing context, - actions, outgoing frames, queues, transfers, the documents of the JSON - texts it reads, and handlers. + state, negotiation records, peer connections, data channels and the + frames received on them, each peer's link and handshake, sealed texts, + relay sockets, signing context, actions, outgoing frames, queues, + transfers, the documents of the JSON texts it reads, and handlers. Every touch runs on the app's executor; one thread needs no thread-safe resource, multiple threads require a strand. - - **References and detachment.** Rooms hold the app strongly, the app - reaches rooms weakly, bindings hold connections weakly and connections - hold plain pointers to bindings. Detachment fails and frees all drain - waiters and removes all pointer registrations before returning. The - app keeps no room-resource allocation after that room ends. Adoption - replaces the room's negotiation handlers with the app's; ending a - negotiation clears the room's handlers. + - **References.** Rooms hold the app strongly, and the app reaches rooms + weakly, through its registry, which a room leaves in every way it ends. + A link's handlers name it weakly; ending a link fails and frees its + drain waiters before returning. The app keeps no room-resource + allocation after that room ends. - **The resources' lifetimes.** The app's resource must outlive its state: its handle, all its rooms, retained values and pending operations. A room's own resource must outlive its state, retained @@ -639,7 +661,7 @@ holds only what is specific to trystero. `std::pmr::map` and `std::pmr::set`, and three Boost containers over `std::pmr::polymorphic_allocator`: `boost::unordered_flat_set` (the event ids a strategy remembers), `boost::circular_buffer` (the construction - window, the recent challenges) and + window) and `boost::circular_buffer_space_optimized` (the replay cache), each built over its owner's resource. A struct that holds them takes the room's `std::pmr::polymorphic_allocator<>` in its @@ -663,7 +685,7 @@ holds only what is specific to trystero. `f` fits in three pointers and is nothrow-movable, and in storage of the allocator otherwise. It replaces every `std::function` of `backend.hpp` (the handlers of `timer`, `websocket`, `data_channel`, - `peer_connection` and `sealer`), of the room and of + `peer_connection` and `derive_password_master`), of the room and of `detail::logger::sink`, since `std::function` takes no allocator since C++17. Constructed from `f` alone it uses the default resource; the app moves `app_config::log` into its resource with the allocator-extended @@ -674,11 +696,12 @@ holds only what is specific to trystero. that pointer. - **The backend.** Each method of `backend::factory` that makes an object takes a `std::pmr::memory_resource*` as its last parameter. Peer - connections, data channels and received frames use the app's; relay - sockets, sealers and room timers use the room's. The backend allocates + connections, data channels, received frames, relay sockets and room + timers use the room's; a derivation allocates its + operation with its completion's allocator. The backend allocates objects, handlers and their frames or texts through that resource; the backend's WebRTC gives webcpp::webrtc's objects a - `std::pmr::polymorphic_allocator` on the app's resource, and binds it + `std::pmr::polymorphic_allocator` on the room's resource, and binds it over the handler of each operation it starts. The platform backend's own state, its copy of `bind_address`, its window of constructions (`detail::construction_window`) and its own `webcpp::webrtc::runtime`, is @@ -695,11 +718,8 @@ holds only what is specific to trystero. (measured: two per post, in every round of five posts, natively and on emscripten). So `detail::post` posts through the executor of an `io_context` when the room's executor is one, where Asio allocates the - operation as the handler's allocator says, and a page's sealer awaits - each Web Crypto promise through it so too - (`platform_page_sealer_allocation` proves it, against two C library - allocations a seal or an open before); on another executor, a strand for - one, the wrapper stays Asio's. A user's completion handler is allocated + operation as the handler's allocator says; on another executor, a strand + for one, the wrapper stays Asio's. A user's completion handler is allocated as its own associated allocator says: the room never binds its allocator over it, and the page shows `bind_allocator` with the room's resource. When the room erases a completion handler's type @@ -760,25 +780,31 @@ holds only what is specific to trystero. holds no image and whose root reads `undefined`. `std::string`, `bytes`, `webcpp::document::document` and `payload` stay as they are, with `std::allocator`: the user's choice, and a received - `bytes`, or the binary of a `payload`, is a copy of the frame, which - starts in the app's resource. The two document types mirror + `bytes`, or the binary of a `payload`, is a copy of the frame, which is + in the room's resource. The two document types mirror `std::string` and `std::pmr::string`, with no alias of trystero's: a handle of a received document refers to its document object, and moving the document invalidates it, document's own rule, which the action's Doc Comments state. - An owning pmr binary payload is moved when its message buffer and the - room use the same resource, and copied once otherwise; chunked transfers - assemble their buffer in the room's resource. A received + An owning pmr binary payload is moved out of its frame, which is in the + room's resource; chunked transfers assemble their buffer there too. A received std::pmr::string always copies the text once into the room's resource. `encode` takes the resource too, for what keeps the payload alive. - **The protocol** (`protocol/`) takes a `std::pmr::memory_resource*` as the last parameter of every function that returns what it allocates, with `std::pmr::get_default_resource()` as its default, and returns - `std::pmr` types; `protocol::nostr::verify` uses - `secp256k1_context_static` and allocates nothing. + `std::pmr` types; `protocol::nostr::verify` is + webcpp::crypto's `verify_schnorr`, over `secp256k1_context_static`, and + allocates nothing. - **Outside the resource**, stated on the page: libdatachannel's and OpenSSL's own allocations, with the copy libdatachannel's C API makes of - a message before webcpp::webrtc reads it; `emscripten::val`'s JavaScript + a message before webcpp::webrtc reads it; natively OpenSSL's cipher + context of each seal and open of a signal, webcpp::crypto's AES-256-GCM + (two allocations each, which `allocation` counts apart with + `expect_openssl_allocations`; BearSSL's on emscripten allocates none); + natively the PBKDF2 thread of `derive_password_master` and its state, and + in a page what webcpp::hash's Web Crypto backend allocates for it, once + per room id an app derives; `emscripten::val`'s JavaScript heap; Asio's own once-per-context allocations (its services and the scheduler's first operation); the wrapper Asio puts around a post through an executor that is not an `io_context`'s, which @@ -813,7 +839,7 @@ holds only what is specific to trystero. an array on every call (the test replaces it, below), and under Asyncify the unwind data of every suspension of the run (the test counts it apart, below); and in a page, the storage of the bridge's map of pending - Web Crypto promises, in the io_context's allocator, made for the first + promises, in the io_context's allocator, made for the first and grown when more are pending at once than it holds (the WebSocket and `page_call` registrations are intrusive; a socket's events are posted in the room's resource, a `page_call`'s in the resource it is given). The @@ -843,10 +869,11 @@ holds only what is specific to trystero. both are destroyed and the io_context is drained, while neither `operator new` nor the C library sees an allocation, and the rooms' resources have nothing out once the io_context has drained. Two apps - with two rooms each also prove one binary payload copy into a distinct - room resource, with size-specific counters, and no extra copy when - resources match; their global counts are zero, and all resources - return to zero. + with two rooms each, one room in the app's resource and one in its own, + also prove that each room's connections and frames are in its own + resource, the payload moved out of the frame in either, and the app's + resource seeing nothing of the room with its own; their global counts + are zero, and all resources return to zero. The counting resources also count a return of memory they never gave, a pmr object freed through the wrong resource, which must be none. Only the thread `main` runs on is counted: the C library reports diff --git a/README.md b/README.md index 87ce9e7..409c8a3 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,28 @@ # trystero trystero is a header-only port of [Trystero](https://github.com/dmotz/trystero) -0.26.0's serverless WebRTC rooms for C++20, one of the libraries of +0.27.0's serverless WebRTC rooms for C++20, one of the libraries of [webcpp](https://github.com/webcpporg/webcpp). Peers find each other over public Nostr relays and exchange messages directly, over WebRTC data channels. The wire is Trystero's: a room joined from C++ and the same room joined from Trystero's JavaScript are one room. +trystero speaks Trystero 0.27.0 (upstream commit `8d3f57e`): its topics, room +keys, sealing, ids, relays and action wire, each value proven against vectors +recorded from 0.27.0's own code; its identities, signed with ECDSA P-256, and +its handshake; and its room API, with listeners that return a subscription, +users, `max_users`, room errors, request actions and the relays' +connectivity. Its rooms meet Trystero 0.27.0's: the interop lane meets 0.27.0 +pages in headless Chrome with the browser's peer and the native one. Programs +of trystero 0.1.0, the port of Trystero 0.26.0, move as +[Moving from trystero 0.1.0](#moving-from-trystero-010) says. + A room runs on two targets, native and emscripten, through one platform backend: | Header | Target | What it holds | | --- | --- | --- | -| `` | native and emscripten | `platform::backend`: webcpp::webrtc for WebRTC, natively over libdatachannel and in a page over its `RTCPeerConnection`; webcpp::beast for the relays' WebSockets, natively Boost.Beast's and in a page its `WebSocket`, their URLs read with Boost.URL; webcpp::asio's timers; and per target the sealer and the randomness, natively OpenSSL's AES-GCM and `RAND_bytes`, in a page `crypto.subtle` and `getentropy` | +| `` | native and emscripten | `platform::backend`: webcpp::webrtc for WebRTC, natively over libdatachannel and in a page over its `RTCPeerConnection`; webcpp::beast for the relays' WebSockets, natively Boost.Beast's and in a page its `WebSocket`, their URLs read with Boost.URL; webcpp::asio's timers; webcpp::crypto's `random_device` for randomness; and the PBKDF2 of a room's password, webcpp::hash's, natively on a thread of its own and in a page through `crypto.subtle` | | `` | emscripten | `platform::page_call` and `platform::js_string`, what a page's program uses beside the backend | `` is the rooms themselves, which build on both targets @@ -23,68 +33,107 @@ connection and data channel on both targets, and trystero's Asio is natively: a program runs its `io_context` from `main` on both targets, in the browser under a work guard, where `run` suspends into the page's event loop and the page's calls into C++ only post to it. Every name is in the -namespace `webcpp::trystero`. Messages, binary data and pings are ported; -audio and video tracks are not yet. +namespace `webcpp::trystero`. Messages, binary data, requests and pings are +ported; audio and video tracks are not yet. A room seals and opens its +signals in the call, with webcpp::crypto's AES-256-GCM, and hashes with +webcpp::hash: the backend has no sealer of its own. trystero raises no exception of its own: an operation that can fail completes with an error code. Every part of it, the platform backend included, compiles and works without exceptions: webcpp::webrtc calls libdatachannel's C API, where none crosses. -An `app` represents this program in one application: one peer id and one -connection per remote peer, shared by its rooms, with one immutable password -for the app. Different passwords use separate apps with distinct self ids. -Construct it with the -executor, backend and moved `app_config`, then call `join` and test its -`boost::system::result`. The standalone room constructor and -`room_config` are removed: shared configuration, including the password, -moves to `app_config`; handshake timeout and receive limit move to -`room_options`. Rooms have no password override. A new password requires a -new app. Two peers -in one process use two apps; rooms that must not be linked use one app each. - -`app_config::memory` receives the app's state, shared connections, received -frames and every log sentence. `room_options::memory` receives a room's -state, bindings, actions, relays, handlers and JSON; null uses the app's -resource. A received owning binary payload moves when its message buffer -and room resources match, and is copied once otherwise; received pmr text -is always copied once. Completion handlers use their own associated allocator, +An `app` represents this program in one application: one P-256 endpoint key, +made with the app, whose public key derives its peer id; one user, the +`user_identity` its configuration gives or an ephemeral one it makes; and one +immutable password, from which each room derives its keys off the room's +thread. Each room negotiates its own connection to each remote peer, as a +room of 0.27.0 does, and admits a peer once 0.27.0's handshake verified its +endpoint and its user, both signed over the connection's DTLS fingerprints. +Different passwords use separate apps with distinct peer ids. Construct it +with the executor, backend and moved `app_config`, then call `join` and test +its `boost::system::result`. 0.27.0 removed the custom peer id and the +handshake timeout: `app_config` has no `self_id`, and `room_options` no +`handshake_timeout`; `room_options::max_users` bounds a room's users. A +room's `on_*` functions add listeners and return a `subscription`; +`on_error` reports a `room_error` with 0.27.0's code; a send to a target not +connected completes with `error::not_connected`. `create_user_identity`, +`export_user_identity` and `import_user_identity` make, keep and read again +a user, 0.27.0's text included: nothing is kept for the program, which +stores the exported text where it wants. Rooms have no password override. A +new password requires a new app. Two peers in one process use two apps; +rooms that must not be linked use one app each. + +`app_config::memory` receives the app's state, its identities and the key +records and signatures it verified, the rooms' keys and every log sentence. +`room_options::memory` receives a room's state, its connections and the +frames received on them, actions, relays, handlers and JSON; null uses the +app's resource. A received `pmr_bytes` payload moves out of its frame; +received pmr text is always copied once. Completion handlers use their own associated allocator, which `webcpp::asio::bind_allocator` sets. The app's resource must outlive its handle, all its rooms, retained values and pending operations; each room's resource must outlive its values and operations too. Declare both before the io_context and drain or destroy it first; in a browser keep them for the page's life. Pools suit long-lived apps and rooms. webcpp::webrtc's -connections and channels use the app's resource; libdatachannel, OpenSSL -and the browser retain their own internal allocations. - -A passwordless app's rooms are open to peers already connected through any -of its rooms: presence reveals their tokens. A protected app uses a separate -identity and connection; the initial sealed signaling authenticates its -password before its rooms can share that connection. The Trystero JS 0.26.0 -wire remains unchanged, including its one-way room handshake: a JS page -that mixes room passwords still exposes its own rooms. Configure each JS -app with one password too. A peer that knows a C++ app's password can still -send a wrong room proof, reported by the lower id only. +connections and channels use the room's resource; libdatachannel, OpenSSL, +natively the cipher context of each seal and open and the PBKDF2 thread, and +the browser retain their own internal allocations. + +An app's password, `app_config::password`, seals the signals of each of its +rooms, as a Trystero JS room's password seals its own: a peer of another +password reads none of them, and the room reports its sealed offer or answer +as `decrypt_failed`. Each room negotiates its own connections with +Trystero 0.27.0's signed handshake, as a Trystero JS room does. + +## Moving from trystero 0.1.0 + +trystero 0.1.0 ported Trystero 0.26.0; its rooms meet only Trystero 0.27.0's +now, as 0.27.0's meet no 0.26.0 room. A program moves as Trystero's own +programs move from 0.26.0 to 0.27.0: + +- `app_config::self_id` and `room_options::handshake_timeout` are gone: the + app derives its id from its endpoint key (`app::self_id()`, + `room::self()`), and a peer has 10 s for its handshake. +- `app_config::idle_timeout`, `app::max_rooms` and `error::too_many_rooms` + are gone with the connection an app's rooms shared: each room has its own. +- `error::wrong_password` and `error::handshake_timed_out` are gone with + 0.26.0's password handshake: another password is `decrypt_failed`, a failed + handshake `handshake_failed`. The values of `error` after them moved, so a + program compares codes with the enumerators. +- Each `on_*` adds a listener and returns a `subscription`; a join listener + takes a `peer_event`, an error listener a `room_error`; `peers()` maps each + peer's id to its `peer_info`, and `users()` lists the users. +- A send to a target that has not joined completes with + `error::not_connected`, where it was `error::no_such_peer`. +- A peer's user is the one its handshake verified: `app_config::identity` + gives the app's, and `export_user_identity` and `import_user_identity` keep + one across runs. `room_options::max_users` bounds a room's users. +- A backend of a program's own returns from `backend::websocket::send` + whether the socket queued the text. + +The page's "Moving from trystero 0.1.0" lists each change with its +counterpart. ## Building inside the superproject trystero is developed inside the webcpp superproject, as a Boost library is -developed inside Boost. It builds on webcpp::asio, webcpp::webrtc and, for -the relays, webcpp::beast, three libraries of the superproject; its -TLS and WebRTC dependencies are built from pinned sources, and so is -libsecp256k1: +developed inside Boost. It builds on webcpp::asio, webcpp::hash, +webcpp::crypto, webcpp::webrtc and, for the relays, webcpp::beast, five +libraries of the superproject; its TLS and WebRTC dependencies are built from +pinned sources, and so are webcpp::crypto's libsecp256k1 and BearSSL: | Library | Needed by | Found where | | --- | --- | --- | -| libsecp256k1 0.8.0, with its `schnorrsig` and `extrakeys` modules | every room: it signs the Nostr events peers meet through | `/third_party//secp256k1`, from `third_party/libs/secp256k1` | +| webcpp::hash | every room: the SHA-256 of its topics and keys, HMAC, HKDF, and the PBKDF2 of a password's master | `/webcpp/hash//hash` | +| webcpp::crypto | every room: the AES-256-GCM of its signals (natively OpenSSL's, on emscripten BearSSL's), its randomness, its secrets, the ECDSA P-256 of its identities and handshakes, BearSSL's on every target, and the BIP-340 signatures of its Nostr events, over libsecp256k1 0.8.0 with its `schnorrsig` and `extrakeys` modules | `/webcpp/crypto//crypto`, `//gcm-default`, `//p256-default` and `//secp256k1-default`; libsecp256k1 from `third_party/libs/secp256k1`, BearSSL from `third_party/libs/bearssl` | | webcpp::asio | every room | `/webcpp/asio//asio` | | webcpp::webrtc | the platform backend's WebRTC | `/webcpp/webrtc//webrtc` | | webcpp::beast | the platform backend's relays: their WebSockets, and natively their TLS | natively `/webcpp/beast//tls`, Boost.Beast over the source-built OpenSSL; in a page `/webcpp/beast//browser`, over the page's `WebSocket` | | Boost.URL | the platform backend's relays: their URLs | `/webcpp//boost_url`, built from Boost's sources once per variant | | libdatachannel 0.24.6 | the platform backend natively, through webcpp::webrtc | `/webcpp/third_party//libdatachannel`, from pinned source submodules | -| OpenSSL 3.5.9 | the platform backend natively: TLS, AES-GCM and randomness | `/webcpp/third_party//openssl`, also used by Asio and Beast | +| OpenSSL 3.5.9 | natively: the platform backend's WebRTC and TLS, and webcpp::crypto's AES-GCM | `/webcpp/third_party//openssl`, also used by Asio and Beast | -The tables of libsecp256k1 follow `webcpp-secp256k1-tables`: `auto` is window 15 and +The tables of libsecp256k1, which webcpp::crypto links, follow `webcpp-secp256k1-tables`: `auto` is window 15 and comb 11x6 natively (a larger program, faster signing and verification) and window 2 and comb 2x5 on emscripten (the same signing, verification a little slower than window 4, a smaller program). A program that wants otherwise asks for `small` @@ -101,8 +150,8 @@ backend through `/webcpp/trystero//platform`, on both targets, as the examples' Jamfiles do. The target adds `/webcpp/trystero//trystero`, the rooms alone: trystero's headers, Boost's, webcpp::asio, which links embind on emscripten, -libsecp256k1 and webcpp::document with Boost.JSON's and Boost.Charconv's -definitions, compiled once per variant. Beside +webcpp::hash, webcpp::crypto with libsecp256k1, and webcpp::document with +Boost.JSON's and Boost.Charconv's definitions, compiled once per variant. Beside them it adds webcpp::webrtc and Boost.URL on both targets; natively libdatachannel and OpenSSL, through webcpp::webrtc, webcpp::beast's `//tls` and webcpp::asio's `//tls`, whose embedded authorities a program may trust in @@ -125,13 +174,13 @@ The quick start and the programs of the differences run in the lane `relayed`, each over a Nostr relay of its own on 127.0.0.1, whose URL `example/run_over_relay.mjs` gives the program in `TRYSTERO_RELAY_URL`; each passes when it ends by itself having printed its `.expected`. Each has its -twin, the same program on Trystero JS, under `test/oracle/twins/`. The chat -needs a browser, so the build links its program and never runs it. +twin, the same program on Trystero JS 0.27.0, under `test/oracle/twins/`. +The chat needs a browser, so the build links its program and never runs it. The quick start, whole: two apps of one program, `alice` and `bob`, each a -peer with the id the program gives it, join the room `lobby` of the app +peer with an id of its own, join the room `lobby` of the app `webcpp-trystero-quick-start`; alice greets bob when he joins, bob answers -from a coroutine, each prints what it received, after its sender's id, and +from a coroutine, each prints what it received, after the other's name, and both leave, which ends the program. Without `TRYSTERO_RELAY_URL` it meets over Trystero's public relays and STUN servers, as a program that names none does. @@ -152,20 +201,17 @@ none does. #include #include #include -#include namespace asio = boost::asio; namespace trystero = webcpp::trystero; namespace { -/** What one peer's app is made with: its id, and the relay `relay` names, or the public ones. */ -trystero::app_config config_for(std::string_view self_id, const char* relay) { +/** What one peer's app is made with: the relay `relay` names, or the public ones. Each app makes + * its own endpoint key, whose public key derives its id. */ +trystero::app_config config_for(const char* relay) { trystero::app_config config; config.app_id = "webcpp-trystero-quick-start"; - // An id of the program's own, where an app would draw 20 random characters, so that what each - // peer prints of the other is the same on every run. - config.self_id = self_id; if (relay != nullptr) { // The peers stay on this machine: the relay given, and a STUN server where nothing answers // in place of Trystero's public ones, beside a backend bound to the loopback. @@ -174,20 +220,20 @@ trystero::app_config config_for(std::string_view self_id, const char* relay) { } // Without a relay, both lists stay empty: Trystero's defaults, as a user's program has them, // the public relays its app id selects and Trystero's public STUN servers. - // A connection closes as soon as no room uses it, so that the program ends once both leave. - config.idle_timeout = std::chrono::milliseconds{0}; return config; } -/** bob's part: waits for a message, prints it, answers its sender, and leaves the room. */ +/** bob's part: waits for a message, prints it after alice's name, answers its sender, and leaves + * the room. */ asio::awaitable answer(trystero::room& lobby, trystero::action& chat) { // as_tuple hands the error over as a value: a room left first ends the wait without throwing. auto [ec, text, info] = co_await chat.async_receive(asio::as_tuple(asio::use_awaitable)); if (ec) { co_return; } - std::cout << info.from << ": " << text << '\n'; + // The sender's id derives from a key made on each run: its name prints the same every time. + std::cout << "alice: " << text << '\n'; auto [failed] = co_await chat.async_send("hello back", {.targets = {info.from}, .metadata = {}}, asio::as_tuple(asio::use_awaitable)); if (failed) { @@ -210,9 +256,9 @@ int main() { } trystero::platform::backend backend(io.get_executor(), local); - // Two apps, two peers, each with its own id, in the same room. - trystero::app alice(io.get_executor(), backend, config_for("alice", relay)); - trystero::app bob(io.get_executor(), backend, config_for("bob", relay)); + // Two apps, two peers, each with an id of its own, in the same room. + trystero::app alice(io.get_executor(), backend, config_for(relay)); + trystero::app bob(io.get_executor(), backend, config_for(relay)); auto alice_lobby = alice.join("lobby"); auto bob_lobby = bob.join("lobby"); if (!alice_lobby || !bob_lobby) { @@ -223,16 +269,17 @@ int main() { auto bob_chat = bob_lobby->make_action("chat"); // alice greets each peer once its handshake completes, prints the answer, and leaves. - alice_lobby->on_peer_join([&](std::string_view peer) { - alice_chat.async_send("hello", {.targets = {trystero::peer_id(peer)}, .metadata = {}}, + alice_lobby->on_peer_join([&](const trystero::peer_event& joined) { + alice_chat.async_send("hello", + {.targets = {trystero::peer_id(joined.peer_id)}, .metadata = {}}, [](boost::system::error_code ec) { if (ec) { std::cerr << "not delivered: " << ec.message() << '\n'; } }); }); - alice_chat.on_message([&](const std::string& text, const trystero::message_info& info) { - std::cout << info.from << ": " << text << '\n'; + alice_chat.on_message([&](const std::string& text, const trystero::message_info& /*info*/) { + std::cout << "bob: " << text << '\n'; alice_lobby->async_leave([](boost::system::error_code) {}); }); asio::co_spawn(io, answer(*bob_lobby, bob_chat), asio::detached); @@ -307,7 +354,7 @@ The recursive checkout already includes pinned OpenSSL, libdatachannel, libjuice, usrsctp, plog and libsrtp sources. For an existing checkout: ```sh -git -C webcpp submodule update --init --recursive third_party/libs/openssl third_party/libs/libdatachannel third_party/libs/secp256k1 +git -C webcpp submodule update --init --recursive third_party/libs/openssl third_party/libs/libdatachannel third_party/libs/secp256k1 third_party/libs/bearssl ``` B2 builds them with the selected compiler, runtime and C++ ABI when the @@ -378,21 +425,21 @@ page's app, `webcpp-trystero-chat`, and room, `lobby`. Within a few seconds each tab shows the other's id, its first six characters, "joined", and counts it as a peer; what you send from one tab appears in the other, under the sender's id. Every tab that joins the same app and room joins the same -chat, and so does any Trystero JS page. +chat, and so does any Trystero JS 0.27.0 page. -A native peer and a page meet too: the lane `interop` of `test/oracle` -meets the native peer, and the browser's, with Trystero JS pages in headless -Chrome (The tests, below). +A native peer and a page meet too. The lane `interop` of `test/oracle` meets +the native peer, and the browser's, with Trystero JS pages in headless Chrome +(The tests, below). ### When something goes wrong - **b2 prints `node: bad option: --experimental-wasm-threads`** when it configures the emscripten toolset: b2's toolset probes node with a flag that recent Node removed. It is harmless. -- **The page loads but never joins**: it must be opened at `localhost` (or - `127.0.0.1`), not at a network address or from a file. The browser gives - the cryptography the room needs only to secure pages, and `localhost` counts - as one. +- **The page loads but never joins a room with a password**: it must be + opened at `localhost` (or `127.0.0.1`), not at a network address or from a + file. The browser gives the PBKDF2 a password room needs only to secure + pages, and `localhost` counts as one. - **No peer appears**: both sides must use exactly the same app and room. The peers meet over public relays, so a network that blocks WebSockets to them keeps them apart. @@ -409,8 +456,14 @@ when a program defines `WEBCPP_NO_EXCEPTIONS`. `test/support/memory_backend.hpp` is a backend in memory, whose relays, peer connections and data channels run whole rooms in one process. +`crypto_layer` checks the protocol of 0.27.0 against +`test/fixtures/expected/trystero-0.27.0.json`, the vectors +`test/oracle/record_0_27.mjs` records from 0.27.0's own code +(`node test/oracle/record_0_27.mjs `, against a checkout of +`8d3f57e`). + Two lanes of trystero's own, declared in `test/oracle/Jamfile`, check it -against Trystero itself, pinned at 0.26.0 by `test/oracle/package.json` and +against Trystero itself, pinned at 0.27.0 by `test/oracle/package.json` and `package-lock.json`, with Node: b2 libs/trystero/test/oracle//oracle @@ -419,7 +472,7 @@ against Trystero itself, pinned at 0.26.0 by `test/oracle/package.json` and `oracle` runs Trystero's own functions over the inputs of `test/fixtures/cases/protocol.json` and checks that they still write -`test/fixtures/expected/expected.json`, the values the protocol tests +`test/fixtures/oracle/expected.json`, the values the protocol tests reproduce; `b2 libs/trystero/test/oracle//update-expected` writes it again. `interop` meets each C++ peer, the native one and the browser's, with Trystero JS peers in headless Chrome, over a Nostr relay of its own on @@ -429,23 +482,28 @@ Playwright's `chrome-headless-shell`. ## What derives from Trystero -trystero ports Trystero 0.26.0, Copyright (c) 2021 Dan Motzenbecker, +trystero ports Trystero 0.27.0, Copyright (c) 2021 Dan Motzenbecker, distributed under the MIT License. These parts of this repository derive from Trystero: - the wire protocol, ported from Trystero's code into `include/webcpp/trystero`: the Nostr strategy's topics, events and signals, - the room's handshake and its password check, and the action wire; -- its constants: the topic prefixes, the id alphabet and lengths, the - announcement cadence, the event kinds and the backpressure threshold; + the room keys, their derivation and the sealing of signals, the + identities, their keys, ids and texts, the room's signed handshake and its + ready frames, and the action wire with its requests; +- its constants: the domain tags, the topic prefixes, the id alphabet and + lengths, the announcement cadence, the event kinds, the relay health and + the backpressure threshold; - its message layouts: the signals, the action frames and their envelope; +- its room API: listeners and their options, users, room errors and their + codes, and the relays' connectivity; - its default relays (`protocol/relays.hpp`), with their order and the shuffle that derives an app's relays from its id, and its default STUN servers. Trystero's MIT licence and its copyright notice are in [LICENSE-TRYSTERO.txt](LICENSE-TRYSTERO.txt), exactly as Trystero 0.26.0 -ships them. That adds no licence to trystero's own code, which is under the +and 0.27.0 ship them. That adds no licence to trystero's own code, which is under the Boost Software License alone. ## Documentation diff --git a/build.jam b/build.jam index 0f631b8..f788170 100644 --- a/build.jam +++ b/build.jam @@ -11,13 +11,18 @@ project /webcpp/trystero ; -# libsecp256k1 (every room) is webcpp's build of it, /third_party//secp256k1: -# v0.8.0 from the submodule third_party/libs/secp256k1, with the tables the -# feature webcpp-secp256k1-tables chooses (small on emscripten, large natively; +# Hashes are webcpp::hash's and the ciphers, MACs and keys of every room +# webcpp::crypto's: the endpoint and user keys and their ECDSA signatures are +# its P-256, /webcpp/crypto//p256-default, BearSSL on every target. Its +# secp256k1 backend, /webcpp/crypto//secp256k1-default, +# is webcpp's build of libsecp256k1 (v0.8.0 from the submodule +# third_party/libs/secp256k1), with the tables the feature +# webcpp-secp256k1-tables chooses (small on emscripten, large natively; # CODING-GUIDELINES.md chapter 5). WebRTC is webcpp::webrtc's, whose native # libdatachannel and its OpenSSL are pinned source dependencies, built # together for the consumer's B2 variant. import errors ; +import feature ; # The platform backend's own dependencies, checked only when a target that # uses it is built: natively its WebRTC, libdatachannel's through @@ -47,14 +52,34 @@ rule platform-dependencies ( properties * ) # # trystero is parts and that list. parts, the same headers and dependencies # without it, is for a program of a part that parses no JSON, as trystero's -# tests of the timer, a relay's URL, a page's calls and the sealer are -# (test/Jamfile): such a program has none of the parser's functions, and -# Binaryen warns of a pattern of the list that names none. +# tests of the timer, a relay's URL and a page's calls are (test/Jamfile): +# such a program has none of the parser's functions, and Binaryen warns of a +# pattern of the list that names none. path-constant WEBCPP_TRYSTERO_ROOT : . ; + +# The rooms' AES-GCM: webcpp::crypto's default for the target, +# /webcpp/crypto//gcm-default, except in the reference (doc/Jamfile), where it +# is BearSSL, Emscripten's default. The reference reads the headers for +# Emscripten's target with a native toolset, whose gcm-default is OpenSSL, +# which webcpp::crypto refuses on Emscripten. The feature is incidental, since +# it changes no object a dependency builds, and propagated, so that the rooms +# see it. +feature.feature webcpp-trystero-reference : on : optional incidental propagated ; +rule rooms-gcm ( properties * ) +{ + if on in $(properties) + { + return /third_party//bearssl ; + } + return /webcpp/crypto//gcm-default ; +} + # tag::trystero[] alias parts : : : : include /boost//headers /webcpp/document//document - /webcpp/config//config /webcpp/asio//asio /third_party//secp256k1 ; + /webcpp/config//config /webcpp/asio//asio /webcpp/hash//hash + /webcpp/crypto//crypto @rooms-gcm + /webcpp/crypto//secp256k1-default /webcpp/crypto//p256-default ; alias trystero : : : : parts emscripten,asyncify:"-sASYNCIFY_REMOVE=@\"$(WEBCPP_TRYSTERO_ROOT)/asyncify-remove.json\"" ; diff --git a/doc/Jamfile b/doc/Jamfile index 980c01c..ff99312 100644 --- a/doc/Jamfile +++ b/doc/Jamfile @@ -17,6 +17,8 @@ webcpp.doc trystero : trystero.adoc ; # webcpp::asio and webcpp::beast, their browser implementations there, so it # parses with no configuration of Boost.Asio's (measured: the page builds # without BOOST_ASIO_DISABLE_THREADS, which Boost.Beast over Boost.Asio -# needed). +# needed). The rooms' AES-GCM there is BearSSL, Emscripten's default, rather +# than the native default's OpenSSL, which webcpp::crypto refuses on +# Emscripten's target (on, build.jam). webcpp.reference trystero : /webcpp/trystero//platform multi - /webcpp//emscripten-reference ; + /webcpp//emscripten-reference on ; diff --git a/doc/acknowledgements.adoc b/doc/acknowledgements.adoc index bca9d6f..334746a 100644 --- a/doc/acknowledgements.adoc +++ b/doc/acknowledgements.adoc @@ -9,18 +9,21 @@ == Acknowledgements trystero ports the wire protocol of https://github.com/dmotz/trystero[Trystero] -0.26.0, Copyright (c) 2021 Dan Motzenbecker, so that its rooms are +0.27.0, Copyright (c) 2021 Dan Motzenbecker, so that its rooms are Trystero's rooms. It was written with Trystero's source open: its protocol constants, its message layouts, its default relays in their order, with the shuffle that derives an app's relays from its id, and its default STUN servers come from it. Trystero is distributed under the MIT License, whose text and copyright notice are in `LICENSE-TRYSTERO.txt`, at the root of the -library, exactly as Trystero 0.26.0 ships them. That adds no licence to +library, exactly as Trystero 0.26.0 and 0.27.0 ship them. That adds no licence to trystero's own code, which is under the Boost Software License alone. -The BIP-340 signatures of the Nostr events are +The ECDSA P-256 signatures of identities and handshakes are +https://bearssl.org/[BearSSL]'s, by Thomas Pornin, under the MIT License, +and the BIP-340 signatures of the Nostr events https://github.com/bitcoin-core/secp256k1[libsecp256k1]'s, by the Bitcoin -Core contributors, under the MIT License. The platform backend's WebRTC is, +Core contributors, under the MIT License, both through webcpp::crypto. The +platform backend's WebRTC is, natively, webcpp::webrtc's over https://github.com/paullouisageneau/libdatachannel[libdatachannel], by Paul-Louis Ageneau, under the Mozilla Public License 2.0. diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 3c13bc6..9564ca7 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -16,36 +16,39 @@ own state. === The app's resource, the room's and the backend's * `app_config::memory`, `std::pmr::get_default_resource()` by default, - receives the app's state, configuration copy including its password, self id, - registry, shared - connections, advertised tokens, kept frames, drain order and presence - frames. Peer connections, data channels and received frames use it even - while a room negotiates them. The logger, sink and every sentence of the - app and its rooms use this resource too. It must be non-null, checked by - `BOOST_ASSERT` at app construction. + receives the app's state, configuration copy including its password, the + P-256 endpoint key, held in that state, and the self id it derives, the + ephemeral user identity the app makes when its configuration gives none, + the registry of its rooms, the key records and verified signatures of + peers and users (design D18), and the keys its rooms derive from its + password, with the cache that keeps them and each derivation's copy of + the password, its salt and its master (<>). The + logger, sink and every sentence of the app and its rooms use this + resource too. It must be non-null, checked by `BOOST_ASSERT` at app + construction. * `room_options::memory`, the app's resource when null, receives the room's - state, bindings and their drain waiters, negotiation records, rebinding - counts and backoffs, sealed texts, relays, actions, queues, outgoing - frames, transfers, the documents of the JSON texts it reads, and handlers. - The signing context is made there with - `secp256k1_context_preallocated_create`. + state, negotiation records, its peer connections, data channels and the + frames received on them, each peer's link and handshake, sealed texts, + relays, actions, queues, outgoing frames, transfers, the documents of the + JSON texts it reads, and handlers: no connection outlives its room, as in + 0.27.0 (design D9). + The room's signing key, webcpp::crypto's secp256k1 key pair, made at the + room's first event, makes its signing context there, its one allocation + (`secp256k1_context_preallocated_create`). * `platform::backend_config::memory`, `std::pmr::get_default_resource()` by default, receives the platform backend's own state: its copy of `bind_address`, its window of constructions and its own webcpp::webrtc runtime. It must be non-null, and outlive the backend and every connection of its runtime. What the backend makes for an app or a room is in the resource given with that call instead (<>). -* Adoption replaces negotiation handlers with the app's; ending a - negotiation clears the room's handlers. Detachment fails and frees a - binding's drain waiters and removes its registrations before returning. - After a room ends, the app retains no allocation in that room's resource. -* A received frame starts in the app's resource. A `pmr_bytes` payload - moves from its message buffer when that buffer and the room use the same - resource; otherwise it is copied once into the room's resource. A chunked +* Ending a link fails and frees its drain waiters before returning. After + a room ends, the app retains no allocation in that room's resource. +* A received frame is in the room's resource. A `pmr_bytes` payload moves + from its message buffer, an inline one taken out of its frame; a chunked transfer assembles its buffer in the room's resource. Received `std::pmr::string` text is always copied once into the room's resource. A JSON text is parsed into a `webcpp::document::pmr::document` of the - room's resource, a remote candidate into one of the app's, and a JSON + room's resource, a remote candidate too, and a JSON payload received as a `webcpp::document::pmr::document` into one of the room's resource: the document's image, which holds every value, strings included, and the working state of the parse that made it. @@ -131,15 +134,15 @@ over `std::pmr::polymorphic_allocator`: `std::pmr::string` (and `peer_id`), `std::pmr::vector` (and `backend::bytes`, `protocol::bytes` and `pmr_bytes`), `std::pmr::deque`, `std::pmr::map` and `std::pmr::set`, and `boost::unordered_flat_set` (the event ids a strategy remembers), -`boost::circular_buffer` (the construction window, the recent challenges) -and `boost::circular_buffer_space_optimized` (the replay cache), built over +`boost::circular_buffer` (the construction window) and +`boost::circular_buffer_space_optimized` (the replay cache), built over their owner's resource; `app_config`, `room_options`, `send_options`, `message_info` and `backend::ice_server` hold them too. Two types stay the user's choice of `std::allocator`: `trystero::bytes`, a `std::vector`, and `trystero::payload`, a variant of `std::string`, `webcpp::document::document` and `bytes`. A received -`bytes`, or the binary of a `payload`, is a copy of the frame, which starts -in the app's resource; a received `webcpp::document::document` is in the +`bytes`, or the binary of a `payload`, is a copy of the frame, which is in +the room's resource; a received `webcpp::document::document` is in the standard allocator, its image and the working state of its parse, as document's `document` is. `webcpp::document::pmr::document` is document's own allocator-aware type, over `std::pmr::polymorphic_allocator`, @@ -175,7 +178,7 @@ allocates through a `std::pmr::polymorphic_allocator<>`. Constructed with fits in three pointers and is nothrow-movable, and in storage of the allocator otherwise. It replaces every `std::function` of the backend interface (the handlers of its timer, WebSocket, data channel, peer -connection and sealer), of the room and of the log's sink. Constructed from +connection and key derivation), of the room and of the log's sink. Constructed from `f` alone it uses the default resource; the app moves `app_config::log` into its resource with the allocator-extended move. A move assignment carries the source's allocator with its target. @@ -189,23 +192,22 @@ A move assignment carries the source's allocator with its target. `webcpp::asio::any_io_executor` is wrapped by Asio in a function object allocated with `std::allocator`, from Asio's per-thread recycling cache, which calls `std::aligned_alloc` on a miss (measured: two per post, -in every round of five posts, natively and on emscripten). So the room, and -the platform backend's sealer, post through the executor of an `io_context` -when the executor they were given is one, where Asio allocates the operation -as the handler's allocator says, and in a page the sealer awaits each Web -Crypto promise through it too, so that its settlement is posted the same way. -On another executor, a strand over the `io_context` for one, the wrapper +in every round of five posts, natively and on emscripten). So the room posts +through the executor of an `io_context` when the executor it was given is +one, where Asio allocates the operation as the handler's allocator says. On +another executor, a strand over the `io_context` for one, the wrapper stays Asio's (<>). The executor is the program's: the examples and the tests give the app and the backend the executor of their `io_context`. *The backends.* Each method of `backend::factory` that makes an object takes a `std::pmr::memory_resource*` as its last parameter. Peer connections, -data channels and received frames use the app's resource; relay sockets, -sealers and room timers use the room's. Objects and their handlers allocate +data channels, received frames, relay sockets and room timers use the +room's resource; a password's derivation, which makes no object, +allocates its operation with its completion's allocator, the app's. Objects and their handlers allocate through that supplied resource. The backend's WebRTC (<>) gives webcpp::webrtc's connections and -channels a `std::pmr::polymorphic_allocator` on the app's resource, which +channels a `std::pmr::polymorphic_allocator` on the room's resource, which their state, their queues, their texts and their operations use: each operation's handler is bound to it. The platform backend's relays are one session of webcpp::beast's on both targets, made in the room's resource with @@ -230,8 +232,7 @@ what reads or writes it: the parser's state, the path and the pending key and text of the value being read, the tree's record of each change, and the writer's stack, each freed before the call that made it returns. trystero reads each text with `webcpp::document::parse(text, options, allocator)` -into a document of the room's resource, of the app's for a remote -candidate: its image starts at 4 KiB and grows in place, twice as large +into a document of the room's resource: its image starts at 4 KiB and grows in place, twice as large each time, up to twice the caller's bound and 64 KiB for a protocol text, and for a JSON payload up to 96 times its length and 64 KiB, which every valid payload fits, or the room's `room_options::max_json_document_bytes`, @@ -248,8 +249,8 @@ document's own allocator. *The protocol* (`protocol/`) takes a `std::pmr::memory_resource*` as the last parameter of every function that returns what it allocates, with the default resource as its default, and returns `std::pmr` types. -`protocol::nostr::verify` uses `secp256k1_context_static` and allocates -nothing. +`protocol::nostr::verify` is webcpp::crypto's `verify_schnorr`, over +`secp256k1_context_static`, and allocates nothing. [#trystero-allocation-outside] === What stays outside the resource @@ -258,13 +259,22 @@ nothing. API makes of a message before webcpp::webrtc reads it into the frame, and, natively, webcpp::webrtc's copies of what libdatachannel's threads report, in the standard allocator; +* natively, OpenSSL's cipher context of each seal and each open of a signal, + webcpp::crypto's AES-256-GCM being OpenSSL's there: two allocations each, + the EVP context and its AES-GCM state, which the allocation test counts + apart; on emscripten the cipher is BearSSL's, which allocates nothing; +* natively, the thread on which the platform backend runs a password's + PBKDF2, a `webcpp::asio::thread_pool` of one thread, made at the first + derivation and joined when the backend is destroyed, with its state and + the wrapper Asio puts around the completion it dispatches through the + backend's `any_io_executor`; and in a page what webcpp::hash's Web Crypto + backend and the page allocate for the derivation: a cost paid once per room + id an app derives, which no test of trystero's counts; * what `emscripten::val` holds, in the JavaScript heap; * Asio's own once-per-context allocations: its services, in a page webcpp::asio's bridge among them, and the scheduler's first operation; * the wrapper Asio puts around a post through an executor that is not the - executor of an `io_context`, a strand for one, and, given such an - executor, around the settlement of each Web Crypto promise of a page's - sealer; + executor of an `io_context`, a strand for one; * webcpp::webrtc's posts from libdatachannel's threads, which carry Asio's default allocator, since the resource is touched only on the room's executor; and the wrapper Asio puts around webcpp::webrtc's completions, @@ -319,22 +329,34 @@ nothing. `std::string`; * the payload types `std::string`, `bytes`, `webcpp::document::document` and `payload`, with `std::allocator`, the user's choice; +* a user identity the program gives the app (`app_config::identity`): its key, + with its compact public key and its user id, is one allocation of the + resource the program made or imported it in (`create_user_identity`'s and + `import_user_identity`'s `memory`, the default resource unless given), shared + by every copy, those of several apps included; an import's own buffers are + in that resource too, each wiped before it is freed; * on Emscripten, the C library's `select()`, which Asio's reactor calls on every wait of an `io_context` with a timer or a socket, and which callocs an array on every call; * on Emscripten under Asyncify, the unwind data Asyncify allocates whenever the browser program's `run` suspends; * in the browser, the storage of the map in which webcpp::asio's bridge finds - each pending Web Crypto promise, in the allocator of the `io_context`, - made for the first and grown when more are pending at once than it holds, - and kept until the `io_context` is destroyed. The rest of a page's seal or - open, the wait for its promise and the post of its settlement, is in the - room's resource when the backend's executor is that of an `io_context`: the - test `platform_page_sealer_allocation`, after a first seal and open, sees - neither `operator new` nor the C library allocate from the start of a seal - or an open to its completion. The registrations of a WebSocket and of a - `page_call` are intrusive, the events of a socket are posted in the room's - resource, and the calls of a `page_call` in the resource it is given. + each pending promise, in the allocator of the `io_context`, made for the + first and grown when more are pending at once than it holds, and kept + until the `io_context` is destroyed. The registrations of a WebSocket and + of a `page_call` are intrusive, the events of a socket are posted in the + room's resource, and the calls of a `page_call` in the resource it is + given. + +webcpp::crypto's secp256k1 allocates nothing outside the room's resource: +its key pair's context is the room's, and the secret, the context's seed and +each signature's auxiliary bytes are drawn into the stack from +webcpp::crypto's `random_device`, which allocates nothing. The room +allocation test below covers a room's first event, which makes the key, and +its signatures on both targets. Its P-256 allocates nothing either: the app's +endpoint key pair is part of the app's state, a drawn scalar comes from +`random_device` into the stack, and a signature is made and checked in +place. The test's memory relays are shared by every room of a test: they allocate their relays through the resource they are constructed with. @@ -370,14 +392,19 @@ is kept, by its address, in a table of a fixed size until it is freed. measure a round trip, one says goodbye, both are destroyed and the `io_context` is drained. From the first construction to the drain, while the rooms and the relay read and write their JSON texts, neither - `operator new` nor the C library sees an allocation. Once the rooms are + `operator new` nor the C library sees an allocation but, natively, + OpenSSL's, which the test counts apart: what this OpenSSL's cipher + contexts take for one seal and one open, measured first, for each signal + the rooms seal and open. Once the rooms are destroyed their resources still have memory out, the operations they left pending, and none once the `io_context` has drained. * Two apps with two rooms each exchange binary payloads, one room using the - app's resource and one its own. Size-specific counters prove one payload - copy into the distinct room resource, and no extra copy when resources - match. From construction through the drain neither `operator new` nor the - C library sees an allocation, and every resource ends with nothing out. + app's resource and one its own. Each room's connections and the frames + received on them are in its own resource, so in either room the payload + is moved into the value, and the app's resource sees nothing of the room + with its own. From construction through the drain neither `operator new` + nor the C library sees an allocation but, natively, OpenSSL's, counted + apart, and every resource ends with nothing out. The counting resources also count a return of memory they never gave, a `std::pmr` object freed through the wrong resource, which must be none. diff --git a/doc/building.adoc b/doc/building.adoc index 3356968..c5ac2db 100644 --- a/doc/building.adoc +++ b/doc/building.adoc @@ -8,19 +8,31 @@ == Building trystero is header-only, and is developed inside the webcpp superproject, as -a Boost library is developed inside Boost. It builds on three libraries of -webcpp's: webcpp::asio; webcpp::webrtc, the platform backend's WebRTC; and -webcpp::beast, its relays' WebSockets, on both targets. -Its native TLS and WebRTC dependencies, and libsecp256k1, are built from -pinned sources: +a Boost library is developed inside Boost. It builds on five libraries of +webcpp's: webcpp::asio; webcpp::hash and webcpp::crypto, its cryptography; +webcpp::webrtc, the platform backend's WebRTC; and webcpp::beast, its relays' +WebSockets, on both targets. Its native TLS and WebRTC dependencies, and +webcpp::crypto's libsecp256k1, are built from pinned sources: [cols="2,2,3",options="header"] |=== | Library | Needed by | Found where -| libsecp256k1 0.8.0, with its `schnorrsig` and `extrakeys` modules -| every room: it signs the Nostr events peers meet through -| `/third_party//secp256k1`, built from `third_party/libs/secp256k1` +| webcpp::hash +| every room: the SHA-256 of its topics and keys, HMAC, HKDF, and the PBKDF2 + of a password's master +| `/webcpp/hash//hash`, the superproject's `libs/hash` + +| webcpp::crypto +| every room: the AES-256-GCM of its signals, natively OpenSSL's and on + emscripten BearSSL's, its randomness, its secrets, the ECDSA P-256 + signatures of its identities and handshakes, BearSSL's on every target, + and the BIP-340 signatures of the Nostr events peers meet through, over + libsecp256k1 0.8.0 with its `schnorrsig` and `extrakeys` modules +| `/webcpp/crypto//crypto`, `//gcm-default`, `//p256-default` and + `//secp256k1-default`, the superproject's `libs/crypto`; libsecp256k1 is + `/third_party//secp256k1`, built from `third_party/libs/secp256k1`, and + BearSSL `/third_party//bearssl`, from `third_party/libs/bearssl` | webcpp::asio | every room @@ -44,12 +56,12 @@ pinned sources: | `/webcpp/third_party//libdatachannel`, built from `third_party/libs/libdatachannel` | OpenSSL 3.5.9 -| the platform backend natively: its WebRTC, its relays' TLS, its sealer and - its randomness +| natively: the platform backend's WebRTC and its relays' TLS, and + webcpp::crypto's AES-256-GCM | `/webcpp/third_party//openssl`, shared by the Asio, Beast and Trystero build graphs |=== -The tables of libsecp256k1 are chosen by the feature +The tables of libsecp256k1, which webcpp::crypto links, are chosen by the feature `webcpp-secp256k1-tables`. With `auto`, the default, natively they are window 15 and comb 11x6: a larger program, and faster signing and verification. On emscripten they are window 2 and comb 2x5: the same signing, verification a little slower than @@ -63,8 +75,8 @@ A program uses trystero through `/webcpp/trystero//platform`, the rooms and the platform backend (<>), on either target: natively, built with `threading=multi`, and in a page. `/webcpp/trystero//trystero` is the rooms alone, which adds trystero's headers, Boost's, webcpp::asio, -libsecp256k1 and webcpp::document with Boost.JSON's and Boost.Charconv's -definitions, compiled once per variant, and no +webcpp::hash, webcpp::crypto with libsecp256k1, and webcpp::document with +Boost.JSON's and Boost.Charconv's definitions, compiled once per variant, and no WebRTC on any target: a program that runs its rooms over a backend of its own, as trystero's tests run whole rooms over the memory relays (<>), needs no more: @@ -75,10 +87,13 @@ include::{library-root}/build.jam[tag=trystero] ---- `/webcpp/trystero//trystero` is `parts`, which brings those dependencies, -and, under Asyncify, the list that leaves Boost.JSON's recursive descent +the AES-GCM of its signals being webcpp::crypto's default for the target, +`/webcpp/crypto//gcm-default` (`rooms-gcm`; the reference alone, which reads +the headers for Emscripten's target, gets BearSSL in its place), and, under +Asyncify, the list that leaves Boost.JSON's recursive descent out of Asyncify's instrumentation (<>). A program of a part that parses no JSON, as trystero's tests of the timer, a relay's -URL, a page's calls and the sealer are, links `parts`, or `platform-parts` +URL and a page's calls are, links `parts`, or `platform-parts` (below), in place of the rooms: it has none of the parser's functions, and Binaryen warns of a pattern of the list that names none. @@ -173,7 +188,7 @@ Initialize the native dependencies from the superproject root: [source,bash] ---- git submodule update --init --recursive third_party/libs/openssl third_party/libs/libdatachannel \ - third_party/libs/secp256k1 + third_party/libs/secp256k1 third_party/libs/bearssl ---- Install CMake 3.21 or newer, Perl and Make (native Windows Perl and nmake @@ -220,8 +235,8 @@ servers, as a program that names none does, and prints the same two lines The chat needs a browser, so the build links its program and never runs it (<>). The target `site` copies the page and its program into a directory of its own under the build directory, out of the -tree, and prints it. The page is served from `localhost`, where -`crypto.subtle` exists: +tree, and prints it. The page is served from `localhost`, a secure context, +where `crypto.subtle` exists for the PBKDF2 of a room with a password: [source,bash] ---- diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 5d44e3e..cf0b96e 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,38 +16,41 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] +* *Breaking change:* Changed the wire to Trystero 0.27.0's: peers join after +its signed ECDSA P-256 handshake, each room has its own connections, and +signals 0.27.0 refuses are ignored. +* Added 0.27.0's users and identities: `app_config::identity`, +`create_user_identity`, `export_user_identity`, `import_user_identity`, +`room::users()`, and `room_options::max_users`, whose refusal is +`room_full`. +* *Breaking change:* Removed `app_config::self_id`, `idle_timeout`, +`room_options::handshake_timeout`, `app::max_rooms` and the errors +`too_many_rooms`, `wrong_password` and `handshake_timed_out`; `error`'s later +values moved. +* *Breaking change:* Changed each `on_*` to return a `subscription`, errors +to a `room_error`, `peers()` to a map of `peer_info`, and absent targets to +`not_connected`. +* *Breaking change:* Changed trystero's cryptography to webcpp::hash and +webcpp::crypto, libsecp256k1 included, with no sealer in the backend and no +`-sSECP256K1_ROOT`, and `backend::websocket::send` to return whether it +queued. * *Breaking change:* Changed `native::` and `browser::` to one -`platform::backend` (link `/webcpp/trystero//platform`), and a backend's -`now_ms()` and `unix_seconds()` to `steady_now()` and `unix_now()`, of -`std::chrono`. -* *Breaking change:* Changed trystero's Asio to webcpp::asio; a page's `main` -runs its `io_context` under a work guard, and calls in through -`platform::page_call` of `platform/page.hpp`. -* *Breaking change:* Changed JSON payloads to `webcpp::document::document` -and `webcpp::document::pmr::document`, sent as `JSON.stringify` writes them, -for `boost::json::value` and `json_resource`; `payload` has no copy -assignment, and programs link Boost.Charconv too. +`platform::backend` (link `/webcpp/trystero//platform`) over webcpp::asio, +whose page's `main` runs its `io_context`, and the clocks to `steady_now()` +and `unix_now()`. +* *Breaking change:* Changed JSON payloads and `protocol::` to +webcpp::document's documents, written as `JSON.stringify` writes them, +bounded by `room_options::max_json_document_bytes`, and `app::join` to +`+[[nodiscard]]+`. * *Breaking change:* Changed relays to verify TLS in any verify mode, drop binary messages, and refuse URLs a page reads otherwise and TLS contexts a page cannot honour. -* *Breaking change:* Changed `protocol::` to take webcpp::document's values, -removing `json::parse` and `make_id`; `append_string` returns its error, and -`proposal::size` is a `std::uint64_t`. -* *Breaking change:* Changed libsecp256k1 to `/third_party//secp256k1`, with -`webcpp-secp256k1-tables` for its tables and no `-sSECP256K1_ROOT`, and -`app::join` to `+[[nodiscard]]+`. -* Fixed relays hiding a genuine Nostr event, slowing rooms with colliding ids -or making them read 8 MiB refusals, rooms dropping or piling up simultaneous +* Fixed relays hiding a genuine Nostr event or unreachable over IPv6, rooms +with colliding ids reading 8 MiB refusals, 32-bit receivers misreading 4 GiB offers, and MSVC 14.52 builds. -* Added `room_options::max_json_document_bytes` for a received JSON payload; -every JSON text is read in the room's resource within bounds, and a self id -not UTF-8 is replaced by a random one. -* Fixed unreachable IPv6 relays, signals unlike Trystero's, 32-bit receivers -misreading 4 GiB offers, pages ignoring failing `crypto.getRandomValues` or -dropping early frames, unbound rooms after lost presence, and crossed-connection -peer errors. -* Changed the quick start to one native program, and added programs showing -differences beside Trystero JS's output. +* Changed the pages to the port to Trystero 0.27.0, the quick start to one +native program, and added programs showing differences beside Trystero JS's +output. // end::unreleased[] [#trystero-changelog-0-1-0] diff --git a/doc/design.adoc b/doc/design.adoc index 929ac78..a5645ae 100644 --- a/doc/design.adoc +++ b/doc/design.adoc @@ -16,20 +16,26 @@ | Protocol | `protocol/*.hpp` -| pure functions over bytes and text: no I/O, no platform +| pure functions over bytes and text: no I/O, no platform; among them the + crypto layer, the topics, ids, room keys and sealing of 0.27.0, its + identities and the messages and transcript of its handshake, over + webcpp::hash and webcpp::crypto (<>) | Backend interface | `backend.hpp` -| the WebSocket, peer connection, data channel, timer and AES-GCM sealer a - platform provides +| the WebSocket, peer connection, data channel, timer, clocks, randomness and + the PBKDF2 of a room's password a platform provides | App -| `app.hpp`, `detail/app_impl.hpp`, `detail/connection.hpp` -| one identity, the room registry, shared connections and their routing +| `app.hpp`, `identity.hpp`, `detail/app_impl.hpp`, + `detail/identity_cache.hpp`, `detail/room_keys_cache.hpp` +| the endpoint key and the user identity, the room registry, the rooms' + keys, and the key records and verified signatures of peers and users | Room | `room.hpp`, `detail/*.hpp` -| the Nostr strategy, signaling, bindings, action wire and room API +| the Nostr strategy, the signaling, each peer's link and handshake, the + users, the action wire and the room API | Backend's WebRTC | `webrtc/*.hpp` @@ -39,9 +45,10 @@ | Platform backend | `platform/*.hpp` | webcpp::webrtc, webcpp::beast (natively Boost.Beast, in a page its - `WebSocket`), Boost.URL, webcpp::asio's timers, and per target the sealer - and the randomness: OpenSSL natively, Web Crypto and - `crypto.getRandomValues` in a page; and, in a page, `page_call` and `js_string` + `WebSocket`), Boost.URL, webcpp::asio's timers, webcpp::crypto's + `random_device` for randomness, and webcpp::hash's `async_pbkdf2` for a + room's password, natively on a thread of the backend's own and in a page + through Web Crypto; and, in a page, `page_call` and `js_string` |=== Everything above the backend interface is the core, which builds on both @@ -54,8 +61,133 @@ Asio is webcpp::asio: natively Boost.Asio itself, on emscripten the backend webcpp::asio ships, whose `io_context` webcpp::webrtc's browser objects deliver their events to. -[#trystero-design-sharing] -=== Connections shared by the rooms of an app +[#trystero-design-port] +=== The port to Trystero 0.27.0 + +The port follows the change `trystero-0-27` (proposals), whose design +numbers its decisions D1 to D23; the library is what they built. + +*The backend has no sealer (D4, D5).* Hashing, the derivation of a room's +keys from their master, sealing and opening, room authentication and ids are +synchronous functions of `protocol/` (`topics.hpp`, `ids.hpp`, +`room_keys.hpp`, `seal.hpp`), over webcpp's default backends: a signal of a +few kilobytes seals in microseconds with OpenSSL natively and BearSSL on +emscripten, so the room seals and opens in the call, as Trystero awaits +`encrypt` and `decrypt` in turn. What stays asynchronous is the one costly +step, the PBKDF2 of a room's password, 600,000 iterations of HMAC-SHA-256, +some 0.2 s natively and several seconds in WebAssembly, which never runs on +a room's thread: `factory::derive_password_master` completes on the room's +executor after the call returns. The platform backend runs it natively with +`webcpp::hash::async_pbkdf2` on a one-thread `webcpp::asio::thread_pool` it +makes at the first call and joins when it is destroyed, and in a page with +`async_pbkdf2` over `backends::webcrypto`, the page's `crypto.subtle`, on the +backend's executor. A work executor in `app_config` was set aside: every +native program would fill an option for a cost paid once a room. + +*A room's keys, their cache and their failure (D6).* A room without a +password keys AES with the SHA-256 of `["trystero:room-aes:v3",,]`, +as `JSON.stringify` writes it. With one, the app derives a PBKDF2 master +under the salt SHA-256 of `["trystero:pbkdf2-master:v3",,]`, then +HKDF-SHA-256 to the AES key (`trystero:room-aes:v3`) and to the HMAC key +(`trystero:room-hmac:v3`), wipes the master, and keeps the keys of at most 64 +rooms, the least recently used out, as 0.27.0's `derivedRoomKeysCache` +(`detail::room_keys_cache`); a derivation that fails is forgotten, so that a +later join derives again, and is reported as `error::backend_failure`, since +0.27.0 has no room error for it. The password stays the app's (0.1.0's +ruling), so the cache is keyed by room id. A room announces nothing before +its key exists: `join` returns at once, and the room starts once the +derivation completes. The keys are held in `webcpp::crypto::secret<32>`, +and every other buffer of a secret is wiped by trystero's +`detail::wipe` before it is released: the password's three copies, the +app's, the cache's and each derivation's, among them (test +`the_password_is_wiped_before_it_is_freed`; the caller's +`app_config::password` is the program's). webcpp::crypto has no public wipe +of a buffer of a size known only at run time, so `detail::wipe` stays +trystero's until it has one (<>). + +*Dependencies (D7).* `parts` links webcpp::hash and webcpp::crypto +(`/webcpp/crypto//crypto`, `gcm-default`, `p256-default` and +`secp256k1-default`): libsecp256k1 and BearSSL arrive through +webcpp::crypto, libsecp256k1 with the same feature +`webcpp-secp256k1-tables`, and trystero includes no header of either. +OpenSSL stays natively for TLS and for libdatachannel, and is the AES-GCM of +webcpp::crypto's native default, but trystero's own code calls none of it. +What webcpp::crypto and webcpp::hash allocate outside a room's resource is +listed in <>. + +*One connection per room and remote peer (D9).* 0.27.0 removed 0.26.0's +`shared-peer.ts`: each room makes its own offers and answers, keeps one +connected peer per remote id, writes its action frames bare on the channel, +and binds its handshake to that connection's DTLS fingerprints and to its +app and room. So does the port: the app keeps its identity, its relays' +configuration and its rooms' keys; each room its own connections, in the +room's resource (<>). trystero 0.1.0's sharing, +its presence frames, room tokens, rebinding, idle connections, its 64-room +bound and its password handshake are gone with it: a JS peer's connection +belongs to one room, and another room's frames on it would be read as this +room's. A connection is bounded as `peer.ts` bounds it: 64 frames of at +most 17 KiB kept for 10 s before the room takes them, then frames of at +most 64 KiB. + +*Identity belongs to the app (D15, D17).* 0.27.0 caches one endpoint +identity per app id and page, and resolves a user identity per app and page +unless a room's configuration gives one. The port keeps both in the `app`: +one endpoint key pair, whose compact key derives `self_id()`, and one user +identity, `app_config::identity` or an ephemeral one made with the app. A +`user_identity` is a copyable handle to an immutable key, so that several +apps, of one process or several, are one user's endpoints; +`create_user_identity`, `import_user_identity` and `export_user_identity` +are 0.27.0's, with its `trystero_uk_` text and its JSON key form. There is +no `'local'` persistence: 0.27.0 keeps that one in IndexedDB, and a {cpp} +program keeps an identity where it wants with the exported text. A program +that wants two users in one room makes two apps, where 0.27.0 also takes an +identity per room (<>). An identity that +cannot be made, on a system without a generator, leaves the app without +one, and each room it joins reports `identity_failed`, then ends, as +0.27.0's rooms fail their setup. + +*Signatures are synchronous and deterministic (D18).* ECDSA P-256 is +webcpp::crypto's, over BearSSL on every target, synchronous like the rest of +the crypto layer, behind one seam of trystero's, `protocol/ecdsa.hpp`. +Signing normalizes to low S, and verification refuses a high S before it +verifies, as 0.27.0 does. BearSSL's nonces are RFC 6979's, so the port's +signatures are deterministic where WebCrypto's are random; both verify +alike, so the wire cannot tell. The key records (4,096) and the verified +signatures (8,192 entries, 2 MiB, payloads of at most 4,096 bytes) are +0.27.0's caches and bounds, kept per app rather than per page +(`detail::identity_cache`). Signatures, compact keys and the user key's text +are read as strict base64url, where 0.27.0's `Uint8Array.fromBase64` is +loose: a JS peer always writes the canonical form, so only a forged text can +tell, and it is refused. + +*The handshake reads its fingerprints from the descriptions the signaling +handled (D20).* 0.27.0 reads the `a=fingerprint:` lines of its connection's +local and remote descriptions. The port's signaling hands its room the last +local description it set and the last remote one it applied, and the room +reads them with `protocol::dtls_fingerprints`; the backend is unchanged. The +memory backend writes a fingerprint line of its own into each description. + +*The user-proof is protocol code only (D21).* 0.27.0's `identity.ts` +defines a user's proof of an endpoint, which its core neither sends nor +checks: the handshake's dual signatures bind the user key to the endpoint. +The port keeps its payload, `protocol::user_proof_payload`, proven by the +vectors, for the plugins that may use it. + +*Wide chunks follow the connection's largest message (D22).* 0.27.0 sends +64 KiB chunks to a peer whose connection's `sctp.maxMessageSize` is at least +65,536. `backend::peer_connection::max_message_size()` reports it, the +platform backend from webcpp::webrtc's `max_message_size()`, the limit its +channels' sends check, and the action wire offers wide transfers on such a +connection. + +*The error list is 0.27.0's (D23).* `wrong_password`, +`handshake_timed_out` and `too_many_rooms` named what 0.27.0 no longer has, +the password handshake, its timeout as a code of its own, and the 64-room +bound: they are gone, and the values after them moved. +`invalid_user_identity` and `invalid_max_users` name what 0.27.0 throws. + +[#trystero-design-ownership] +=== Who owns what [cols="1,3,2,1",options="header"] |=== @@ -67,45 +199,42 @@ deliver their events to. | None | `detail::app_impl` -| Configuration and immutable password, self id, logger, room registry by token and id, connections and user count -| While any shared reference lives; its last user closes its connections +| Configuration and immutable password, endpoint key and self id, user identity, logger, room registry by id, the rooms' keys, key records and verified signatures, and the user count +| While any shared reference lives | App's -| `detail::connection` -| One peer's connection and channel, advertised tokens, kept frames, idle timer and plain pointers to bindings and their drain order -| From adoption until its end -| App's - -| `detail::binding` -| One room's use of a connection: a weak reference, drain waiters and delivery to its room -| Until detachment, owned by its room's peer state -| Room's - | `room` | A reference to `detail::room_impl` | While the user keeps its handle; destruction leaves | None | `detail::room_impl` -| Signaling, strategy, actions, peers, bindings, handlers, rebinding counts, backoffs and a shared reference to the app +| The strategy, the signaling, each peer's link and handshake, users, actions, handlers and a shared reference to the app | Until its state and pending operations end | Room's, the app's by default + +| `detail::signaling` +| Each negotiation: its peer connection and data channel until a link takes them +| Until the negotiation ends or the room closes +| Room's + +| `detail::peer_link` +| One remote peer's connection and channel, once negotiated, and the frames kept before the room binds it +| Until the peer goes or the room ends +| Room's |=== -* A room holds the app strongly; the app reaches rooms weakly. A binding - holds its connection weakly, and the connection holds plain pointers to - bindings. Detachment removes those pointers and every drain registration - before returning. Ending a room removes its registry entry, so the app - keeps no allocation of that room's resource after it ends, and no cycle - keeps the objects alive. -* Sharing is scoped by the `app` the user constructs, with no registry +* A room holds the app strongly; the app reaches rooms weakly, through its + registry, which a room leaves in every way it ends. Ending a room removes + its registry entry, so the app keeps no allocation of that room's + resource after it ends, and no cycle keeps the objects alive. +* Each app is scoped by the `app` the user constructs, with no registry outside it and no static state keyed by the backend. Two apps with the same application id in one process are two peers. Each app has one immutable password. Different passwords use separate apps with distinct - self ids, so their connections, tokens and presence are never reused. -* The action wire continues to write its room token and send through a - `channel_link`. The binding implements that link: each room keeps its - own actions, transfers, queues and bounds. + self ids. +* A link's handlers name it weakly, so that a link the room let go reaches + nothing; no other room ever uses a room's connection. [#trystero-design-backend] === Why abstract classes for the backend @@ -126,9 +255,11 @@ refactor (2026-11-14), since webcpp::asio, webcpp::beast and webcpp::webrtc give both targets one interface, where everything but WebRTC was written twice. The abstract classes stay, for the memory relays, which run whole rooms on both targets where node has no WebRTC, and for the interop's native -peer, which wraps the platform backend. Only the sealer and the source of -randomness are chosen per target, by `WEBCPP_TARGET_EMSCRIPTEN`, until -webcpp::crypto exists (<>). +peer, which wraps the platform backend. Only the PBKDF2 of a room's +password is chosen per target, by `WEBCPP_TARGET_EMSCRIPTEN`: natively on a +thread of the backend's own, in a page through Web Crypto +(<>); randomness is webcpp::crypto's +`random_device` on both (<>). [#trystero-design-webrtc] === Why webcpp::webrtc @@ -152,7 +283,7 @@ The platform backend makes its peer connections and data channels the same way on both targets, in `` and `data_channel.hpp`: `webrtc::peer_connection` and `webrtc::data_channel` hold webcpp::webrtc's `basic_peer_connection` and `basic_data_channel` over a -`std::pmr::polymorphic_allocator` on the app's resource, keep a wait of each +`std::pmr::polymorphic_allocator` on the room's resource, keep a wait of each kind pending on them, re-armed on the executor, and report what each completes with through the backend interface. What is trystero's, and stays in them, over webcpp::webrtc: @@ -163,27 +294,41 @@ in them, over webcpp::webrtc: checking), and new. * The candidates. A local candidate leaves as the JSON of an `RTCIceCandidateInit`, the form Trystero JS adds with `addIceCandidate`; a - remote one is read from that JSON, at most 16 KiB of it. Natively it + remote one is read from that JSON, at most 4,096 bytes of it. Natively it carries `sdpMid` and an `sdpMLineIndex` of 0, and no user name fragment, as libdatachannel gives none; a candidate whose text is not UTF-8, which JSON cannot carry, is not reported. * The frames. A channel reads every message as it comes, with - `async_receive`, into a vector of the app's resource, which the message + `async_receive`, into a vector of the room's resource, which the message handler then owns. A text message, as a peer can send, or a binary one larger than any room frame, is dropped there, on the executor: neither can be a frame. What reaches the executor is bounded by webcpp::webrtc: a message is at most `max_message_size`, 256 KiB, which natively libdatachannel cuts a longer one to, and past which in the browser, or past - 16 MiB of unread messages, the channel closes. A binary payload moves when - its message buffer and the room use the same resource, and is copied once - otherwise; chunked transfers assemble their buffer in the room's resource. -* The frames no room has read. Valid binary frames that arrive before the - message handler is installed wait in a FIFO in the app's resource. The - queue holds at most 64 frames for at most 10 seconds from its first frame, - Trystero's pending-data bounds. Overflow or expiry closes the channel; - closing or destroying it discards the pending frames. The backend's timer - invalidates an expiry already queued when the queue drains or closes. - Installing a receiver posts delivery on the executor with the app's + 16 MiB of unread messages, the channel closes. A binary payload moves + from its message buffer when the action's type is `pmr_bytes`; chunked + transfers assemble their buffer in the room's resource. + A frame the channel refuses to send, larger than the connection's + `max_message_size` (webcpp::webrtc's, the transport's limit) or past what + it buffers, closes the channel: a transfer then ends with the peer rather + than wait on a chunk that was never sent. +* The frames no room has read. The open event and a first message reach + the executor in either order, and the room's link installs its handler + from the open event: valid binary frames that arrive before it wait in a + FIFO in the room's resource, under the bounds the link puts on a peer's + frames before its room binds it, 0.27.0's: at most 64 frames of at most + 17 KiB each. One more, or a longer one, closes the channel; closing or + destroying it discards the pending frames. The queue has no time bound of + its own: the link's 10 seconds start as it takes the frames, and a channel + no link takes is one the signaling closes. The signaling holds each channel + on a side of a negotiation, the offer's or the answer's, and every way a + side ends (its expiry, its connection's failure, the peer's leaving, the + other side's channel opening first, the room's close) clears the + channel's handlers, closes its connection, which closes the channel, and + lets go of it; an entry it drops otherwise holds no connection. A channel + waits, with at most 64 x 17 KiB (about 1.1 MiB) of frames, for at most its + side's lifetime. Installing a receiver posts + delivery on the executor with the room's allocator. It never calls the receiver inline, and delivery checks the current handler and channel before each frame, so a handler may replace itself or close the channel. A message already read ahead of that delivery @@ -241,9 +386,13 @@ The asynchronous operations are the exception, for the reason [#trystero-design-dependencies] === Dependencies -trystero builds on webcpp::asio, and its platform backend on webcpp::webrtc -and webcpp::beast. `/webcpp/trystero//trystero` is the rooms alone: it brings -`/webcpp/asio//asio`, which links embind on emscripten, and on no target +trystero builds on webcpp::asio, webcpp::hash and webcpp::crypto, and its +platform backend on webcpp::webrtc and webcpp::beast. +`/webcpp/trystero//trystero` is the rooms alone: it brings +`/webcpp/asio//asio`, which links embind on emscripten, +`/webcpp/hash//hash`, and `/webcpp/crypto//crypto` with its defaults for +AES-256-GCM (`gcm-default`), P-256 (`p256-default`, over BearSSL) and +secp256k1 (`secp256k1-default`, over libsecp256k1), and on no target webcpp::webrtc. A program names `/webcpp/trystero//platform` on both targets, which adds the backend to the rooms: `/webcpp/webrtc//webrtc` and `/webcpp//boost_url` on both; natively webcpp::webrtc's libdatachannel, diff --git a/doc/differences.adoc b/doc/differences.adoc index 9c7aa8c..592bed0 100644 --- a/doc/differences.adoc +++ b/doc/differences.adoc @@ -8,56 +8,59 @@ [#trystero-differences] == Differences from Trystero -trystero ports the part of Trystero 0.26.0 that rooms of messages need: the -Nostr strategy, the signaling, the password handshake, the action wire and -the room's API. Where it keeps a feature, it keeps Trystero's wire and its -defaults; where it bounds what a peer or a relay can make a room hold, it -says so in <>, since Trystero JS bounds none of it. -These features of Trystero are not ported, each for its reason: +trystero ports the part of Trystero 0.27.0 that rooms of messages need: the +Nostr strategy, the signaling, the action wire with its request actions, and +the room's API with its listeners, users and errors. Where it keeps a +feature, it keeps Trystero's wire and its defaults; where it bounds what a +peer or a relay can make a room hold, it says so in +<>, since Trystero JS bounds none of it. These +features of Trystero are not ported, each for its reason: [cols="2,3",options="header"] |=== | Not ported | Why -| Audio and video: `addStream`, `removeStream`, `addTrack`, `removeTrack`, - `replaceTrack`, `onPeerStream` and `onPeerTrack`, with the actions - `@_stream`, `@_track` and `@_signal` and their renegotiation +| Audio and video: `addStream`, `removeStream`, `replaceTrack` and + `onPeerStream`, with the actions `@_stream` and `@_signal` and their + renegotiation | The largest part left, on the roadmap (<>): in the browser, the page's `MediaStream` objects; natively, libdatachannel's RTP tracks, whose capture, encoding and decoding would be the application's. A room ignores a frame of one of these actions. -| Request actions, `kind: 'request'`: `request`, `requestMany` and - `onRequest` -| Not ported yet: an application answers a message with another, to its - sender's id. - -| `onReceive`, which accepts or declines an incoming transfer; the progress - callbacks `onProgress` and `onReceiveProgress`; and cancelling a send with - an `AbortSignal` -| Not ported yet: a room accepts every transfer for an action with a - receiver within `max_receive_bytes`, as Trystero does when no `onReceive` - is set, and reports a transfer only when it completes. - -| `onPeerHandshake`, a handshake of the application's own -| Not ported yet: the password handshake, which runs on the same internal - action, `@_hsdata`, is. +| 0.27.0's default identity, `identity: 'local'`, with + `clearUserIdentity` +| It keeps the user key in IndexedDB; the port has no implicit persistence + (design D15): an app's user is the identity its configuration gives, else + a new one, and a program keeps an identity with `export_user_identity` and + `import_user_identity`. + +| `makeState`, `makeUserState`, `roles`, `scale` and the plugins of `use`, + with `ready` +| Each a change of its own, on the roadmap (<>): signed + records and shared state, roles and moderation, and `scale()`'s relayed + peers. A room ignores a ban it receives from an active peer, and reports + one a pending peer sends as `banned`. + +| `requestMany`; a send's and a request's `onProgress` and `signal`; a + listener's `signal` +| Not ported yet (<>); a listener's subscription replaces + its `signal` (<>). | Passive rooms, `passive: true` | Not ported yet: a room always announces itself. | The BitTorrent, MQTT, Firebase, Supabase, IPFS and WebSocket relay strategies -| Each is a strategy of its own to port; Nostr's public relays need no - account and no server of the application's own. +| Each is a strategy of its own to port (design D3); Nostr's public relays + need no account and no server of the application's own. -| `getRelaySockets`, `pauseRelayReconnection`, `resumeRelayReconnection`, - `manualReconnection` and `warnOnRelayFailure` -| Not ported yet: a room reconnects with its backoff, and reports what its - relays do through its log. +| `getRelaySockets` and `warnOnRelayFailure` +| A room reconnects with its backoff, and reports what its relays do through + its log and `relay_failed`. -| `trickleIce: false`, `turnConfig` and `rtcPolyfill` +| `trickleIce: false`, `rtcConfig`, `turnConfig` and `rtcPolyfill` | Candidates are always trickled, as Trystero's Nostr strategy does by default; `ice_servers` names every STUN and TURN server, in place of Trystero's defaults; and the backend is what a polyfill would be. @@ -73,210 +76,106 @@ has nothing of it to run beside its twin. |=== | Behaviour | Trystero JS | Here | Why -| Scope of sharing and of the self id | the page: one `selfId` for every app and room, one manager per strategy | an `app` object: its self id and its connections | no static state; several peers in one process; an id across apps is a program's choice (`app_config::self_id`) and never reaches the wire of another app +| Scope of the peer id | the page: one peer id for each app id, from an endpoint identity the page creates once and caches, and a user id from the user's key | an `app` object: its peer id, from an endpoint key it makes, and its user's id from the identity its configuration gives, else a new one | no static state; several peers in one process (design D17) + +| A room's own identity | `joinRoom` takes an `identity` of its own, which overrides the page's for that room | the identity is the app's, `app_config::identity`, for every room of it; a program that presents two users makes two apps | the app holds one user's keys, which its key records and caches serve; two users are two endpoints (design D17) + +| Passwords across rooms | configured per room | one immutable `app_config::password` for every room, separate apps and peer ids for different passwords | 0.1.0's ruling, kept by design D6: a room's keys are cached by room id alone, and one app is one password domain + +| An ECDSA P-256 signature | WebCrypto's, with a random nonce: signing one text twice gives two signatures | BearSSL's, with RFC 6979's nonce: signing one text twice gives one signature | both verify alike, low S, so no peer can tell; webcpp::crypto's P-256 is synchronous and needs no randomness to sign (design D18) -| Passwords across rooms | independently configured per room, including mixed passwords on one shared connection | one immutable `app_config::password` for every room, separate apps and self ids for different passwords | the initial sealed negotiation authenticates one password domain before any of its rooms reuse the connection; the JS wire remains unchanged +| A signature, a compact key or a user key's text that is not strict base64url: padded, with a non-canonical last character | read by `Uint8Array.fromBase64`, which accepts it; a handshake signature with a character outside the alphabet fails with the `SyntaxError` of its decoding as its reason | refused: a handshake step fails as "peer identity verification failed", an import as `invalid_user_identity` | a JS peer writes only the canonical text, so only a forged one differs; one reading of each text, as for sealed texts and room auth tokens (design D18) -| A peer kicked from a room, or that kicked us, over a live connection | bound again by its next signal or presence | bound again at a rebinding time, 11 s doubling to 5 min; the lower id refuses it meanwhile and keeps its frames | a peer sending invalid room proofs would otherwise loop reports and announcements without end; one refusing side cannot alternate with another +| A user key's text whose JSON holds invalid UTF-8 in a member 0.27.0 ignores | decoded with `TextDecoder`, which replaces each invalid sequence by U+FFFD, then parsed: the key imports | refused as `invalid_user_identity` | webcpp::document's strings are UTF-8, and the export never writes such a member -| Reuse over a live connection | binds on any signal of that peer id | binds only a peer that advertised the room's token itself, and by reuse only on their first meeting over that connection | a forged announcement must not bind an innocent peer +| Relay sockets and the Nostr key | one socket per relay URL for the page, shared by the rooms that name it; a signing key per room | a socket per room and relay; a signing key per room | invisible to peers; sockets shared through the app in a later change -| A room frame before the peer's presence for the room | kept until the room binds by presence or by reuse | also taken as the peer's advertisement of the room, which binds it | a forged announcement cannot reuse, so a presence that Chrome dropped as the page's channel opened would otherwise leave the room unbound for good; only the peer writes its connection's frames +| Relay and ICE configuration | each room's own | the app's, for every room | one configuration for what the rooms share -| Announcements after a peer leaves | restarted after every leave | restarted only when no live connection to that peer remains | over a live connection, rebinding goes through the connection +| Listener tokens | `onPeerJoin` and the others return a function that removes the listener, and take a `signal` | they return a `subscription`, whose `unsubscribe()` removes the listener and whose destruction leaves it; no `signal` | a token that removed its listener when destroyed would silently remove the listeners whose token a program did not keep (design D10) -| Presence after binding | sent when a room registers | also sent again when a room binds by reuse or at its rebinding time | it makes the other side, Trystero JS included, bind at once +| `getSelf` | a promise, since WebCrypto makes the keys | `self()`, at once | an app's identity exists once it is made (design D11) -| An answer to an earlier challenge | checked against the current challenge only | accepted when it is correct for any of the last 8 challenges sent since the last completed handshake | a late answer of an ended binding is honest and proves the password; failing it reports a false error +| `getPeers` | each peer's `PeerInfo` with its `connection` | `peer_info` without it | the connection is the backend's (design D11) -| Frames after the higher id's own kick | kept for the next binding | dropped until the higher id sends presence | they belong to the ended binding; flushed into the next one, they would answer or be answered in its place +| `getPeers`, `getUsers` and a user's `peerIds` | objects and arrays in the order of insertion: a user's peers in the order their entries were made | a `std::pmr::map` of each in id order, with a transparent comparator; a user's peers in the order they became active | a map {cpp} looks a peer up in by `std::string_view` without building a string; the order of activity is the order a program sees joins -| Joining a room already joined | the same room | `error::already_joined` | a `room` is a handle whose destruction leaves +| A plaintext that is not UTF-8 | opened with `TextDecoder`, which replaces each invalid sequence by U+FFFD | refused as `decrypt_failed` | an SDP is ASCII, and a replaced text would be another text than the peer sealed (design D12) -| Rooms per app | unbounded; a peer advertising a 65th is dropped by the other side | `join` refuses the 65th, counting rooms in their farewell | the 65th would cost every connection of the app +| Relay connectivity | `setRelayConnectivity`, for the whole page; `'auto'` follows the page's `online`, `offline` and `visibilitychange`, reconnecting when the page becomes visible and is not offline; a value outside the three throws | `app::set_relay_connectivity`, per app; `automatic` follows `online` and `offline` alone, and natively is online; a value outside the enum, which only a cast makes, is taken as online | a process may hold several independent apps (design D13), and the design names `online` and `offline` alone -| A connection whose last room was kicked | idle 123,333 ms | closed at once | a bound: a failed peer holds no connection +| A send to a target that has not joined | rejects with "Trystero: no active peer with id " | completes with `error::not_connected`, whose message is the fixed "no active peer with this id" | an error code's message is its category's text, which names no peer -| Relay sockets and the Nostr key | shared by the rooms of the page, topics batched per socket | per room | not part of this decision; invisible to peers; shared through the app in a later change +| `onReceive` and `onRequest` | may answer with a promise: at most 128 receive decisions pending, 8 of one peer, and 64 concurrent requests of one peer; a gate set after an offer arrived is asked at the offer's next drain | answer at once, during the frame's processing, so none of those bounds has a counterpart; a gate set after an offer arrived is not asked of it | a callable that answers at once is the {cpp} form of a decision the frame waits for; an asynchronous one is a later change -| Relay and ICE configuration | the first room's relays; each negotiating room's RTC configuration | the app's, for every room | one configuration for what the rooms share +| A refused request | rejects with the reason the peer gave | completes with `error::request_rejected` alone, the reason in the room's log | an error code carries no text of a peer's -| `idle_timeout` | test-only (`_test_only_sharedPeerIdleMs`) | a configuration member, Trystero's default | tests and programs that close sooner +| An `@_response` that answers no request | its offer rejected, "unexpected response" | the same: an offer is rejected "unexpected response", an inline message is dropped, nothing is reported and the peer stays | none -| Frames waiting for a bound room's handler | 64, 10 s, then the connection drops | no such state | a binding's delivery is set when it is made +| A name made both a message action and a request action | throws "action type cannot be redefined" | the second handle's operations complete with `error::action_redefined` | trystero raises no exception of its own -| Renegotiation and media over a shared connection | routed through a control room, streams owned per room; a connection with any media is destroyed when its last room goes | not ported | media is on the roadmap (<>) +| A JSON payload or metadata holding a lone surrogate | delivered: `JSON.parse` takes it | not delivered; the reason of a refused request, which 0.27.0 cuts at 512 UTF-16 code units and may leave ending in one, is read with U+FFFD in its place | webcpp::document's strings are UTF-8 -| Passive rooms | presence only for active rooms | not ported | not ported yet: a room always announces itself +| The hint of `peer_connect_failed` without TURN, and `turnConfigured` | "configure TURN via turnConfig or rtcConfig.iceServers"; a TURN server of the raw configuration counts | "configure TURN via app_config::ice_servers"; only a TURN server the app kept counts | the port's option is `ice_servers`, and a server it dropped as unusable is none -| Duplicate connections | the first registered wins at each side and the other is closed at once; crossed, both lose and meet again | the first registered wins at each side; the other is held, unused, until the peer shows which it keeps: closed once the peer sends on the first, or after 2 s (higher id) or 10 s (lower id) when the peer does neither; it replaces the first when the peer closes the first, or, for the higher id, when the peer sends on it | libdatachannel ends an association with a stream reset and a SHUTDOWN, its ABORT a moment later, where a browser's ABORT follows its reset at once: closing at once the connection a Trystero JS peer kept, as it starts sending on it, made Chrome fail those sends and Trystero JS report a peer error. Following the peer's choice closes no connection the peer uses, keeps a crossed pair's rooms on the connection the peer kept, and still agrees with Trystero's rule +| `relay-failed` | reported once per room, when every relay's first connection failed before one opened, or when no relay's first announcement succeeded and the others failed to open; its message is the cause's, falling back to "all signaling relays failed" | the same two conditions, once per room, a skipped announcement (relay not open or cooling down) counting as no failure as in 0.27.0; the message is the failure's text, the constant when a relay did not open | none + +| The message of `identity-failed` | the underlying error's message when it has one, WebCrypto's for instance, else "endpoint identity resolution failed" or "identity resolution failed" | always the fallback text of the two | a key webcpp::crypto cannot make fails with an error code, whose message is its category's text, not the cause a page's WebCrypto would name + +| An announcement the socket cannot queue | `client.send` is a silent no-op on a socket that is not open, so a dropped write is no failure; only signing or JSON failures fail an announcement | `backend::websocket::send` returns whether it queued the text, and a refused text fails the announcement (a queue overflow on a socket the room sees open) | a connection that cannot take the text is a relay that cannot carry the announcement, and the port has no other way to see it | A Nostr event a relay repeats, or that several relays carry | acted on each time | acted on once among the 4096 newest event ids, when its id is checked to be its own, the SHA-256 of its NIP-01 serialization; an event with any other id is acted on each time and its id never kept | every relay of the room carries each event; an id taken unchecked would let a relay hide a genuine event behind a forged one it sends first under the same id, or fill the room's resource with the ids kept -| A relay's text, a signal or a handshake message past its bound | parsed with `JSON.parse` whatever its length, under the relay's own limit | dropped before it is read: 68,608 bytes for a relay's text, 66,560 for a signal, 1,024 for a handshake message (<>) | the bounds are those of the fields Trystero sends, so no text a Trystero peer writes is refused; a longer one would cost the room its length to read +| A relay's text or a signal past its bound | a relay's text parsed with `JSON.parse` whatever its length, under the relay's own limit; a signal parsed up to 128 Ki characters (`maxSignalMessageChars`) | dropped before it is read: 68,608 bytes for a relay's text, 66,560 for a signal (<>) | the bounds are those of the fields Trystero sends, a sealed offer of 64 Ki characters and the longest ids, so no signal a Trystero peer writes is refused; a longer one holds members Trystero never writes, or sealed text that is not ASCII and never opens | A protocol text of thousands of values | parsed | refused once its image passes twice its bound and 64 KiB | no Trystero message holds more than a few dozen values, and a document's value takes some 200 bytes of image -| A protocol text nested deeper than 16 | parsed | dropped as a malformed one is | no Trystero message nests deeper than 4, a relay's event and its tags, and each level of a parse is a level of recursion, which a hostile relay would otherwise take to 256 - -| A self id that is not UTF-8 | impossible: a JavaScript string | set aside for a random one, with a configuration report | JSON carries UTF-8 alone, and a signal writes the id as a JSON string +| A protocol text nested deeper than 16, a relay's event, a signal or a step of the handshake | parsed | dropped as a malformed one is; a step of the handshake fails as "peer identity verification failed" | no Trystero message nests deeper than 4, a relay's event and its tags, and each level of a parse is a level of recursion, which a hostile peer or relay would otherwise take to 256 | A JSON payload's number that a double cannot hold: an integer past 2^53^, a decimal of more digits, one past a double's range | sent as the nearest double, and one past a double's range as `null`: a JavaScript number is a double | sent exact, as webcpp::document holds it; a Trystero JS peer reads the nearest double, or `Infinity` | webcpp::document keeps every number exact, and writes each one a double holds as JavaScript does -| A JSON payload nested deeper than 256, or holding a lone surrogate | delivered: `JSON.parse` takes both | not delivered | webcpp::document's defaults: a bounded depth, and strings that are UTF-8 +| A JSON payload nested deeper than 256 | delivered: `JSON.parse` takes it | not delivered | webcpp::document's default, a bounded depth | A JSON payload whose document passes the room's `room_options::max_json_document_bytes`, 64 MiB by default: some 350,000 values of one character | delivered: `JSON.parse` has no bound but the page's memory | not delivered (<>) | each value of a document is a node of 192 bytes of image, 96 times its text at most, so a program bounds what a peer's JSON may take of its room's resource; every payload within the bound is delivered -| The characters of a random id (the self id, offer ids, nonces, subscription ids) | each of the 62 alike, from `Math.random` | one random byte each, at its remainder in 62: each of the first eight characters from 5 of the 256 bytes, each other from 4, about 5.95 bits a character | the bytes come from the backend's secure randomness, not `Math.random`; the bias costs about 0.005 bits a character, below log2(62) - +| The width of a transfer's chunks over a connection whose peer announces no message size limit (`a=max-message-size:0`) | narrow, 16 KiB frames: `sctp.maxMessageSize` is then `Infinity`, which is not finite | wide, 64 KiB frames: webcpp::webrtc's `max_message_size()` reports such a connection's limit as `options::max_message_size` in a browser and libdatachannel's local limit natively | webcpp::webrtc has no value for "no limit"; a receiver takes either width, as every 0.27.0 peer takes frames up to 64 KiB |=== Each difference a program can show has one, `example/diff_.cpp`, -with its twin, the same program on Trystero 0.26.0, in `test/oracle/twins/` +with its twin, the same program on Trystero JS, in `test/oracle/twins/` (<>); <> gives the reason of each other row. [#trystero-differences-shown] === The differences, shown -Each difference below is shown by a {cpp} program and, but for the last, -its twin, the same program written for Trystero JS: the part of the {cpp} -program that differs, the twin whole, then what the twin printed on Trystero -0.26.0, then what the {cpp} program printed. Both ran, and the outputs are -theirs: a program and its twin each join over a Nostr relay of their own on -127.0.0.1, whose URL is in their environment, `TRYSTERO_RELAY_URL`, and two -peers of one program meet there, as two apps in {cpp} and as two pages in -Trystero JS (<>). The lane `relayed` runs the -programs again, and the oracle lane the twins, and each fails when its -program no longer prints what is shown here. The twins of the programs of +Each difference below is shown by a {cpp} program and its twin, the same +program written for Trystero JS: the part of the {cpp} program that differs, +the twin whole, then what the twin printed, then what the {cpp} program +printed. Both ran, and the outputs are theirs: a program and its twin each +join over a Nostr relay of their own on 127.0.0.1, whose URL is in their +environment, `TRYSTERO_RELAY_URL`, and two peers of one program meet there, +as two apps in {cpp} and as two pages in Trystero JS +(<>). The lane `relayed` runs the programs, and +fails when one no longer prints what is shown here. The twins of the programs of `example/` agree with {n-twins-agreeing} of them, the quick start among them (<>), and diverge from {n-twins-divergent}, each a -difference below; {n-examples-without-twin} programs have no twin, the last -difference below and the chat page, each with its reason in -`test/oracle/twins/without-twin.txt`. - -[#trystero-differences-already-joined] -==== Joining a room already joined - -Trystero JS:: `joinRoom` with the id of a room the page holds returns that -room. -trystero:: `app::join` refuses with `error::already_joined` while a room of -that id is joined. -Why:: A `room` is a handle whose destruction leaves the room: two handles of -one room would leave it twice. - -[source] ----- -include::{examples}/diff_already_joined.cpp[tag=example,indent=0] ----- - -.The twin, on Trystero JS -[source,javascript] ----- -include::{twins}/diff_already_joined.mjs[lines=7..] ----- - -.Trystero JS prints -[listing] ----- -include::{twins}/diff_already_joined.expected[] ----- - -.trystero prints -[listing] ----- -include::{examples}/diff_already_joined.expected[] ----- - -[#trystero-differences-rooms] -==== Rooms per app - -Trystero JS:: `joinRoom` joins every room a page asks for: the 65th, 66th and -67th rooms of one `appId` are each a room. It advertises every room of the -app over every connection of the app, and a peer that is advertised a 65th -room token over one connection drops that connection, "too many advertised -rooms" (`dist/shared-peer.mjs:457`). -trystero:: `app::join` refuses a 65th room with `error::too_many_rooms`. A -room still in its farewell, the 99 ms of `async_leave`, counts, so another -room can be joined once that leave has completed. -Why:: A 65th room would be advertised over every connection of the app, and -each Trystero JS peer at the other end would drop the connection. - -[source] ----- -include::{examples}/diff_rooms_per_app.cpp[tag=example,indent=0] ----- - -.The twin, on Trystero JS -[source,javascript] ----- -include::{twins}/diff_rooms_per_app.mjs[lines=7..] ----- - -.Trystero JS prints -[listing] ----- -include::{twins}/diff_rooms_per_app.expected[] ----- - -.trystero prints -[listing] ----- -include::{examples}/diff_rooms_per_app.expected[] ----- - -[#trystero-differences-self-id] -==== The self id - -Trystero JS:: A page has one `selfId`, drawn once when Trystero's module -loads, and every room of every app announces it, so a peer that meets the -page in two apps sees the same id in both. Its one manager of shared -connections keys them by app id, so the two apps share the id and not their -connections. -trystero:: Each app draws its own self id and holds its own connections, so a -peer that meets the program in rooms of two apps sees two ids, and two rooms -of one app show one. A program that wants one id across apps names it, -`app_config::self_id`. -Why:: No static state, so that one process holds several peers; an id shared -across apps is the program's choice, and never reaches another app's wire -unless the program chooses it. - -[source] ----- -include::{examples}/diff_self_id.cpp[tag=example,indent=0] ----- - -.The twin, on Trystero JS -[source,javascript] ----- -include::{twins}/diff_self_id.mjs[lines=7..] ----- - -.Trystero JS prints -[listing] ----- -include::{twins}/diff_self_id.expected[] ----- - -.trystero prints -[listing] ----- -include::{examples}/diff_self_id.expected[] ----- +difference below; {n-examples-without-twin} program has no twin, the chat +page, with its reason in `test/oracle/twins/without-twin.txt`. [#trystero-differences-passwords] ==== Passwords across rooms Trystero JS:: Each `joinRoom` takes its own password, so one page joins a lobby with one password and a kitchen with another, and a peer that joins -both meets the page as one peer, over one connection that carries both -rooms' password handshakes. +both meets the page as one peer, its one peer id, over a connection of each +room. trystero:: A password is an app's, `app_config::password`, the same for every room of the app and never changed: rooms of different passwords are rooms of separate apps, each with its own self id and connections, so the other peer meets two peers. -Why:: The sealed negotiation that makes a connection authenticates one -password before any room of the app reuses it; the wire stays Trystero's. +Why:: One app is one password domain (0.1.0's ruling, kept by design D6, so +that a room's keys are cached by room id alone). [source] ---- @@ -289,7 +188,7 @@ include::{examples}/diff_passwords.cpp[tag=example,indent=0] include::{twins}/diff_passwords.mjs[lines=7..] ---- -.Trystero JS prints +.Trystero JS 0.27.0 printed [listing] ---- include::{twins}/diff_passwords.expected[] @@ -301,55 +200,16 @@ include::{twins}/diff_passwords.expected[] include::{examples}/diff_passwords.expected[] ---- -[#trystero-differences-relay-config] -==== Relay and ICE configuration - -Trystero JS:: The first room a page joins, while it holds no other, opens the -relays, and every room joined while one remains uses them, whatever relays -it was given. A connection is made with the RTC configuration of the room -that negotiates it, and a room that binds over it later shares it. So a -kitchen joined with a second configuration after the lobby uses the lobby's -relays and the lobby's ICE servers. -trystero:: Relays and ICE servers are the app's, for every room of the app: a -room with another configuration is a room of another app, which uses its -own. A room hands out neither its relays' sockets nor its connections, so -the program gives each app a backend that records what the app asks of the -platform's. -Why:: One configuration for what the rooms of an app share. - -[source] ----- -include::{examples}/diff_relay_config.cpp[tag=example,indent=0] ----- - -.The twin, on Trystero JS -[source,javascript] ----- -include::{twins}/diff_relay_config.mjs[lines=7..] ----- - -.Trystero JS prints -[listing] ----- -include::{twins}/diff_relay_config.expected[] ----- - -.trystero prints -[listing] ----- -include::{examples}/diff_relay_config.expected[] ----- - [#trystero-differences-relay-sockets] ==== Relay sockets -Trystero JS:: A page opens one WebSocket per relay, which every room of the -page shares, its topics batched on it; `getRelaySockets` returns them. +Trystero JS:: A page opens one WebSocket per relay URL, which every room of +the page whose configuration names it shares (its relay manager's pool), its +topics batched on it; `getRelaySockets` returns them. trystero:: Each room opens its own. The program counts the WebSockets its app asks of the backend, since a room hands out none. -Why:: Not part of the decision that shares connections between rooms; peers -see no difference. The rooms of an app may share their relays' sockets in a -later change. +Why:: Peers see no difference. The rooms of an app may share their relays' +sockets in a later change. [source] ---- @@ -362,7 +222,7 @@ include::{examples}/diff_relay_sockets.cpp[tag=example,indent=0] include::{twins}/diff_relay_sockets.mjs[lines=7..] ---- -.Trystero JS prints +.Trystero JS 0.27.0 printed [listing] ---- include::{twins}/diff_relay_sockets.expected[] @@ -374,50 +234,18 @@ include::{twins}/diff_relay_sockets.expected[] include::{examples}/diff_relay_sockets.expected[] ---- -[#trystero-differences-peer-join] -==== `on_peer_join` does not replay the joined peers - -Trystero JS:: A newly set `onPeerJoin` is called at once with each peer -already joined. -trystero:: A room reports a join from its executor, after the call to `join` -has returned, to the handler set then, so a handler set right after `join` -sees every join; `peers()` lists the joined peers for a handler set later. -Why:: A join is an event, reported once; the peers joined are the room's -state, which `peers()` reads. - -[source] ----- -include::{examples}/diff_peer_join.cpp[tag=example,indent=0] ----- - -.The twin, on Trystero JS -[source,javascript] ----- -include::{twins}/diff_peer_join.mjs[lines=7..] ----- - -.Trystero JS prints -[listing] ----- -include::{twins}/diff_peer_join.expected[] ----- - -.trystero prints -[listing] ----- -include::{examples}/diff_peer_join.expected[] ----- - [#trystero-differences-peers] -==== `peers()` lists ids - -Trystero JS:: `getPeers` returns an object that maps each joined peer's id to -its `RTCPeerConnection`, of the class given as `rtcPolyfill` when one is -given. -trystero:: `peers()` returns the joined peers' ids. +==== `peers()` has no connection + +Trystero JS:: `getPeers` returns an object that maps each active peer's id to +its `PeerInfo`: its user's id, whether it is direct, its hops, its roles and +its `connection`, an `RTCPeerConnection` of the class given as +`rtcPolyfill` when one is given. +trystero:: `peers()` maps each active peer's id to its `peer_info`, the same +members without the connection. Why:: A connection is the backend's, webcpp::webrtc's over a page's object in -the browser and over libdatachannel's natively, shared by the app's rooms, -and the room does not hand it out. +the browser and over libdatachannel's natively, and the room does not hand +it out (design D11). [source] ---- @@ -430,7 +258,7 @@ include::{examples}/diff_peers.cpp[tag=example,indent=0] include::{twins}/diff_peers.mjs[lines=7..] ---- -.Trystero JS prints +.Trystero JS 0.27.0 printed [listing] ---- include::{twins}/diff_peers.expected[] @@ -443,15 +271,16 @@ include::{examples}/diff_peers.expected[] ---- [#trystero-differences-send] -==== A send to a peer that has not joined fails +==== A send to a peer that has not joined fails with a fixed message -Trystero JS:: The send warns on the console, "no peer with id ... found", -and resolves. -trystero:: `async_send` completes with `error::no_such_peer`. With several -targets, the send still goes to the others, and completes with the first -failure. -Why:: An operation that fails says so with its error code, which a program -can act on, and a console's warning is not. +Trystero JS:: The send rejects with an error whose message names the +target, "Trystero: no active peer with id" and its id. +trystero:: `async_send` fails too: it completes with `error::not_connected`, +whose message is the category's fixed "no active peer with this id". With +several targets, the send still goes to the others, and completes with the +first failure. +Why:: An error code's message is a text of its category, which names no +peer: the program knows the targets it gave. [source] ---- @@ -464,7 +293,7 @@ include::{examples}/diff_send_to_absent_peer.cpp[tag=example,indent=0] include::{twins}/diff_send_to_absent_peer.mjs[lines=7..] ---- -.Trystero JS prints +.Trystero JS 0.27.0 printed [listing] ---- include::{twins}/diff_send_to_absent_peer.expected[] @@ -502,7 +331,7 @@ include::{examples}/diff_json_numbers.cpp[tag=example,indent=0] include::{twins}/diff_json_numbers.mjs[lines=7..] ---- -.Trystero JS prints +.Trystero JS 0.27.0 printed [listing] ---- include::{twins}/diff_json_numbers.expected[] @@ -557,7 +386,7 @@ include::{examples}/diff_json_refused.cpp[tag=example,indent=0] include::{twins}/diff_json_refused.mjs[lines=7..] ---- -.Trystero JS prints +.Trystero JS 0.27.0 printed [listing] ---- include::{twins}/diff_json_refused.expected[] @@ -569,31 +398,6 @@ include::{twins}/diff_json_refused.expected[] include::{examples}/diff_json_refused.expected[] ---- -[#trystero-differences-self-id-not-utf8] -==== A self id that is not UTF-8 - -Trystero JS:: Has none: it draws its `selfId` when its module loads and takes -none from a program. -trystero:: An app given a self id that is not UTF-8 sets it aside for 20 -random characters, and reports `error::invalid_configuration` to -`app::on_error`. -Why:: JSON carries UTF-8 alone, and a signal writes the id as a JSON string. - -This program has no twin, since no program of Trystero's can give it an id -(`test/oracle/twins/without-twin.txt`), and it joins no room, so it needs no -relay: it runs with the ordinary examples. - -[source] ----- -include::{examples}/diff_self_id_not_utf8.cpp[tag=example,indent=0] ----- - -.trystero prints -[listing] ----- -include::{examples}/diff_self_id_not_utf8.expected[] ----- - [#trystero-differences-unshown] === The differences no program shows @@ -604,45 +408,39 @@ its reason. |=== | Behaviour | Why no program shows it -| A peer kicked from a room, or that kicked us, over a live connection; frames after the higher id's own kick; a connection whose last room was kicked -| A kick follows a room proof that fails over a live connection, and two {cpp} apps never send one: an app has one password for every room, and apps of different passwords share no connection. A Trystero JS page that mixes passwords does, so the interop lane's wrong room proofs show trystero's side, against a page and not a twin (<>), and the `shared` test holds the rest over the memory relays. +| Scope of the peer id; a room's own identity +| Both sides derive their peer and user ids from keys made on each run, so a program and its twin print ids that no two runs share: what differs is which object holds an identity, which the `app_impl` and `room` tests hold over the memory relays, and the interop's `imported_identities` and `one_user_two_cpp_peers` scenarios against Trystero 0.27.0 pages. -| Reuse over a live connection -| Only a forged announcement shows it: a third party that publishes, in a peer's name, a room token that peer never advertised, which neither API publishes. The `shared` test forges one over the memory relays. +| An ECDSA P-256 signature +| Only the relay and the peer see a signature, and each verifies the other's alike; the `crypto_layer` test signs the vectors' texts and checks them against 0.27.0's own verification, and the interop's `js_verifies_cpp_signatures` has 0.27.0 verify the {cpp} peer's. -| A room frame before the peer's presence for the room -| Both APIs advertise a room before its first frame on a connection, so only a presence lost on the way shows it: Chrome drops it, rarely, when a page sends as its answering channel opens, and the interop lane's delayed-open scenario met it; the `connection` and `shared` tests drop it over the memory relays. +| A signature, a compact key or a user key's text that is not strict base64url; a user key's text holding invalid UTF-8 +| A JS peer and `exportUserIdentity` write only the canonical text, in UTF-8, so only a forged one shows it. The `crypto_layer` and `room` tests refuse such texts, a forged handshake step among them. -| Announcements after a peer leaves -| What differs is what a room publishes to its relays after a peer leaves it while their connection stays, which neither API reports: the peers see the same joins and leaves. +| Listener tokens, `getSelf`, the order of `getPeers` and `getUsers`, `onReceive` and `onRequest`, a refused request, a redefined action +| What differs is the form of the API, a token, a value at once, a map, a callable that answers at once, an error code, which a program and its twin write each in its own language; the `subscription`, `room` and `user_table` tests hold the {cpp} side over the memory relays. -| Presence after binding -| A frame on the connection, which neither API reports; what it changes is how soon the other side binds, a time that no two runs print alike. +| A plaintext that is not UTF-8; an `@_response` that answers no request; a JSON metadata holding a lone surrogate +| Only a peer that means harm, or one that writes a text no Trystero peer writes, sends one. The `crypto_layer` test refuses such a plaintext, and the `room` test reads a refusal's reason that ends in a lone surrogate. -| An answer to an earlier challenge -| It needs a handshake answer that arrives after a newer challenge, a race between two bindings that no program sets up on a real network; the `shared` test holds it over the memory relays, whose frames it holds and releases. - -| Relay sockets and the Nostr key: the key -| Which key signs a room's events only the relay sees; neither a room nor a peer reports it. The sockets are shown (<>). +| Relay connectivity; `relay-failed`; an announcement the socket cannot queue +| What differs is a page's event, `visibilitychange`, which no native program and twin receive, and an announcement every relay refuses, which no local relay of the lanes refuses; the `room` and `platform_page_connectivity` tests hold the {cpp} side. -| `idle_timeout` -| Not a behaviour: both keep an idle connection 123,333 ms, and Trystero JS takes the same setting under its test-only name, so a program and its twin would agree. +| The hint of `peer_connect_failed` +| A connection that fails after its descriptions were exchanged, which the loopback of the lanes never fails; the `room` test fails one over the memory relays. -| Frames waiting for a bound room's handler -| A state Trystero JS passes through between a binding and its room's data handler, which its rooms set as they bind; no program reaches it through the API. +| The message of `identity-failed` +| Only a system without a generator fails to make a key, which no machine of the lanes is; the `room` test reports both fallback texts. -| Renegotiation and media over a shared connection; passive rooms -| Not ported: trystero has nothing of them to run. +| The width of a transfer's chunks over a connection with no message size limit +| A browser and libdatachannel each announce a limit, so no connection of the lanes has none; either width reaches the receiver whole, so neither API shows which one was sent. -| Duplicate connections -| Only two connections whose channels open within a millisecond of each other, from two rooms meeting the peer at once, make a pair that is crossed, which no program sets up on demand: the interop lane's two-room scenarios meet one now and then, and the `app_impl` and `shared` tests hold each outcome over the memory relays. +| Relay sockets and the Nostr key: the key +| Which key signs a room's events only the relay sees; neither a room nor a peer reports it. The sockets are shown (<>). | A Nostr event a relay repeats, or that several relays carry | What an event changes when it comes twice is the signaling's work, offers and answers made again, which neither API reports: a program sees one join either way, and over honest relays an event's id is always its own. The `protocol` and `room` tests hold the dedup, forged ids included. -| A relay's text, a signal or a handshake message past its bound; a protocol text of thousands of values, or nested deeper than 16 -| No Trystero peer writes such a text, so only a relay or a peer that means harm sends one, and what changes is whether the room reads it, which neither API reports. The `protocol` and `signaling` tests hold the bounds. - -| The characters of a random id -| A bias of about 0.005 bits a character, which only a count over many ids shows, and a count of random characters prints something else on every run. +| A relay's text or a signal past its bound; a protocol text of thousands of values, or nested deeper than 16 +| No Trystero peer writes such a text, so only a relay or a peer that means harm sends one, and what changes is whether the room reads it, which neither API reports. The `protocol` and `signaling` tests hold the bounds, and the oracle's `signal_envelopes` show 0.27.0 refusing what it refuses. |=== diff --git a/doc/guarantees.adoc b/doc/guarantees.adoc index a777216..5f70536 100644 --- a/doc/guarantees.adoc +++ b/doc/guarantees.adoc @@ -14,34 +14,47 @@ after it, so a comment of the code or of a test cites it by that anchor: `b2 libs/trystero/doc`, which builds this page, fails on a citation that names no anchor of it. The tests are those of <>. -. [[trystero-invariant-1]]*The wire is Trystero 0.26.0's.* A {cpp} peer, +. [[trystero-invariant-1]]*The wire is Trystero's.* A {cpp} peer, in the browser or native, and Trystero JS peers in one room join, exchange text, JSON and binary messages, files both ways with metadata, and pings, -leave, and form a mesh, with either side offering. _Held by_ the `interop` -lane, `interop_browser` on emscripten and `interop_native` natively, against -Trystero 0.26.0 itself in headless Chrome. +leave, and form a mesh, with either side offering; each verifies the +other's signatures before it joins it, sees its peer and user ids, and +refuses another password, a third user past `max_users` and a forged user +signature. _Held by_ the `interop` lane, `interop_browser` on emscripten and +`interop_native` natively, against Trystero 0.27.0 itself in headless +Chrome. . [[trystero-invariant-2]]*Every protocol value equals Trystero JS's.* -Topics, room tokens, the relay shuffle, sealed text, Nostr event ids, inline -and chunked action frames, control frames, envelopes and presence are what -Trystero's own functions compute from the same inputs, byte for byte. _Held -by_ `protocol`, against the values the `oracle` lane has Trystero 0.26.0 -write, and by the `oracle` lane, which fails when Trystero would write -other values than those committed; and by `platform_sealer`, natively and on -emscripten, which opens what Trystero JS sealed with Web Crypto. +Topics, ids, room keys, room auth tokens, the relay shuffle, sealed text, +topic kinds, Nostr event ids, inline and chunked action frames and control +frames, compact keys and the ids they derive, user key texts, the +handshake's steps, transcript and ready frames, and ping frames are what +Trystero 0.27.0's own functions compute from the same inputs, byte for byte, +and 0.27.0 verifies the signatures it recorded. _Held by_ `crypto_layer` and +`crypto_layer_release`, +natively and on emscripten, against the vectors +`test/oracle/record_0_27.mjs` recorded from 0.27.0's own code, sealed texts +opened as 0.27.0 sealed them among them; by `protocol` and `signaling`, +against the values Trystero 0.27.0 writes for the `oracle` lane, which fails +when Trystero would write other values than those committed; and by the +`oracle` lane's `generated-vectors`, which records the vectors again from +the published packages. . [[trystero-invariant-3]]*A peer with another password never joins a protected {cpp} app's rooms.* Its initial signals do not open under the -app's password, so it obtains no shared connection into that domain. Every -room of that app uses the same immutable password. This promise concerns -the {cpp} app's admission; an upstream JS page that mixes passwords retains -its one-way handshake exposure (<>). _Held -by_ `room` (`the_same_password_joins_and_another_does_not`), `platform_room` -(`another_password_never_joins`), and password-domain tests of `shared` and -`interop`. +room's keys, derived from the app's password, so it never connects, and +the room reports `decrypt_failed`, at most once a minute per peer and stage. +Every room of that app uses the same immutable password. _Held by_ `room` +(`two_passwords_never_meet` and +`decrypt_failed_is_reported_once_a_minute`), `platform_room` +(`another_password_never_joins`), and the interop's `passwords` scenario, +with either side offering. . [[trystero-invariant-4]]*A payload larger than a frame travels in chunks, both ways.* It is offered, accepted and sent in chunks of at most 16,370 -bytes, and arrives whole, from either peer. _Held by_ `room` -(`large_payloads_travel_in_chunks_both_ways`, 100 KB each way), and the -file transfers of the `interop` lane. +bytes, or 65,522 on a connection that takes messages of 64 KiB, as 0.27.0 +sends them, and arrives whole, from either peer. _Held by_ `room` +(`large_payloads_travel_in_chunks_both_ways`, 100 KB each way, +`a_wide_link_sends_wide_chunks` and +`a_wide_transfer_arrives_in_wide_chunks_in_any_order`), and the interop's +`wide_transfers_both_ways` scenario, 1 MiB each way. . [[trystero-invariant-5]]*Every allocation of an app and its rooms goes through their resources,* but what <> lists: from its construction until its `io_context` has drained, neither the global @@ -51,8 +64,9 @@ the `std::pmr` types and `webcpp::document::pmr::document`; over the platform backend's relays, natively a message adds nothing, and in a page each event of a relay's `WebSocket` adds embind's string of the event's type, two for a message. -_Held by_ `allocation`, natively and on emscripten; for a page's sealer, -`platform_page_sealer_allocation`; and for the relays, +Natively OpenSSL's cipher context of each seal and open is outside, as +listed, and counted. _Held by_ `allocation`, natively and on emscripten; and +for the relays, `platform_websocket_allocation` natively and `platform_page_relay_allocation` in a page, which counts exactly what is listed. @@ -66,12 +80,12 @@ container that has no network but the loopback (`docker run` with the network `none`). . [[trystero-invariant-7]]*A room refuses a replayed or reflected offer or answer.* A sealed offer or answer it made, or acted on, that comes back to it -as a peer's changes nothing (<>). _Held by_ `room` -(`a_replayed_answer_is_refused`, `a_replayed_offer_is_refused`, -`a_reflected_offer_is_refused_as_an_answer`, +as a peer's changes nothing (<>); one replayed or +reflected as another kind, or for another offer, does not open, its AAD +being another's. _Held by_ `room` (`a_replayed_answer_does_not_open`, +`a_replayed_offer_is_refused`, `a_reflected_offer_is_refused_as_an_answer`, `a_reflected_offer_is_refused_as_an_offer` and -`a_reflected_answer_is_refused_as_an_answer`), and the replay and -reflection scenarios of the `interop` lane. +`a_reflected_answer_does_not_open_as_an_answer`). . [[trystero-invariant-8]]*A relay that stops reading is dropped.* Once the text held unsent for it would pass 4 MiB, the connection is dropped, and reports one close, after which the room reconnects with its backoff, as it @@ -85,15 +99,32 @@ session's queue does, which checks one close and no message after it; the reconnection by `room` (`a_relay_that_closes_at_once_is_tried_less_and_less_often`). -. [[trystero-invariant-9]]*One connection per remote peer per app is shared -by its rooms.* Each room keeps its own membership and actions on that -connection. _Held by_ `shared`, cases 1 to 3, and the interop's first shared -scenario. +. [[trystero-invariant-9]]*Each room of an app has its own connection to +each remote peer,* as each room of 0.27.0 has: its frames travel bare on +it, no other room uses it, and a room keeps one connection per peer. +_Held by_ `room` (`rooms_of_one_app_have_their_own_connections`, +`a_room_keeps_one_connection_per_peer` and `frames_travel_bare`), and the +interop lane, whose Trystero 0.27.0 pages read the {cpp} peer's frames. . [[trystero-invariant-10]]*A room's departure leaves the app's other rooms -joined.* They continue sending over the same connection. _Held by_ -`shared`, case 8, and shared interop scenario 5, with either side leaving. -. [[trystero-invariant-11]]*Different passwords share no {cpp} app -connection or presence.* Protected rooms use a separate app with a -distinct self id; a peer of a passwordless app gains no binding to that -protected app by echoing tokens. _Held by_ the password-domain cases of -`shared` and shared interop scenario 4. +joined.* They keep their connections to the peer and go on sending, and the +room that left negotiates nothing more. _Held by_ `room` +(`leaving_one_room_keeps_the_other_rooms_connection` and +`a_leaving_room_negotiates_nothing`). +. [[trystero-invariant-11]]*A peer joins only once its signed handshake +verified it.* Its endpoint key derives its id, its user key derives its +user id, both signatures of the transcript verify, and the fingerprints it +claims are those of the connection; a forged step, other fingerprints, or a +handshake that does not complete in 10 s fail it, and the peer never joins. +_Held by_ `room` (`peers_verify_each_other_and_join_with_their_user_ids`, +`a_forged_step_fails_the_handshake`, +`another_fingerprint_fails_the_handshake` and +`a_handshake_that_never_completes_fails_after_10_s`), `handshake_manager`, +and the interop's `a_forged_user_signature` and +`js_verifies_cpp_signatures` scenarios. +. [[trystero-invariant-12]]*A room holds at most `max_users` users.* A peer +of a new user is refused once its handshake passed, and its room reports +`room_full`; a peer of a user present is admitted. _Held by_ `room` +(`a_full_room_refuses_a_new_user`, +`another_peer_of_a_present_user_is_admitted` and +`concurrent_admissions_respect_the_limit`), and the interop's +`max_users_both_ways` scenario. diff --git a/doc/overview.adoc b/doc/overview.adoc index 9ae4e24..913817e 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -14,27 +14,34 @@ https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr] relays, exchange the WebRTC offer and answer through them, and from then on talk over the connection the browser or the network stack established. -It ports the protocol of https://github.com/dmotz/trystero[Trystero] 0.26.0, -and keeps its wire byte for byte. A room joined from {cpp} and the same room -joined from Trystero's JavaScript are one room: the peers see each other, and -an action sent from one side arrives on the other. +It ports the protocol of https://github.com/dmotz/trystero[Trystero] 0.27.0, +and keeps its wire byte for byte: a room joined from {cpp} and the same room +joined from Trystero's JavaScript are one room. The peers verify each +other's identities with Trystero's signed handshake, see each other, and an +action sent from one side arrives on the other. The library provides: -* `room`, which joins a room of an application over Nostr relays, reports - the peers that join and leave, measures round trips, and leaves with - Trystero's farewell; +* `room`, which joins a room of an application over Nostr relays, admits + each peer once its signed handshake verified its endpoint and its user, + holds at most `max_users` users, reports the peers and users that join + and leave, and the problems it handled, to listeners that each return a + subscription, measures round trips, and leaves with Trystero's farewell; * `action`, a named channel of messages: text, JSON (webcpp::document's), binary, or any of the three, with optional JSON - metadata, of any size, sent inline or in chunks with backpressure; -* one immutable password per app, part of every room's sealed signaling - key and challenge handshake; separate passwords use separate apps and ids; + metadata, of any size, sent inline or in chunks with backpressure, to + peers or users, with a receive gate and progress; and + `request_action`, whose requests a peer answers; +* one immutable password per app, from which every room derives its keys + off the room's thread; separate passwords use separate apps and ids; * every asynchronous operation as an Asio initiating function, so it completes with a callback, `webcpp::asio::use_awaitable`, `webcpp::asio::deferred` or any other completion token of webcpp::asio, which natively is Boost.Asio itself; * an `app` per program in one application and password domain, with one - identity and one connection per remote peer shared by its rooms; + endpoint identity, its peer id, and one user identity, ephemeral or a + `user_identity` the program creates, exports and imports as 0.27.0 does; + each of its rooms negotiates its own connection to each remote peer; * a resource for the app and an optional resource for each room, which receive their allocations (<>); * a backend interface that separates the room from the platform, and the @@ -58,9 +65,9 @@ out. The backend is a header of its own, beside a page's: libdatachannel and in a page over its `RTCPeerConnection` and `RTCDataChannel`; webcpp::beast for the relays' WebSockets, natively Boost.Beast's and in a page its `WebSocket`, their URLs read with - Boost.URL; webcpp::asio's timers; and per target the sealer and the - randomness, natively OpenSSL's AES-GCM and `RAND_bytes`, in a page - `crypto.subtle` and `crypto.getRandomValues` (<>) + Boost.URL; webcpp::asio's timers; webcpp::crypto's `random_device`; and + the PBKDF2 of a room's password, webcpp::hash's, natively on a thread of + its own and in a page through `crypto.subtle` (<>) | `` | emscripten @@ -80,17 +87,18 @@ on both. Every name is in the namespace `webcpp::trystero`. Container (its `pmr` base class), Endian, Hash2, System and Unordered for the rooms; URL for the platform backend's relays, and Beast for them natively. -* webcpp::document for every JSON text, webcpp::asio, and webcpp::webrtc - and webcpp::beast for the platform backend's WebRTC and relays - (<>). -* https://github.com/bitcoin-core/secp256k1[libsecp256k1] 0.8.0, with its - `schnorrsig` and `extrakeys` modules, for the BIP-340 signatures of Nostr - events: every room needs it. webcpp builds it from its pinned - source, `/third_party//secp256k1`. -* In the browser: Emscripten 6.0.11, the version webcpp pins, a page - served from a secure context (https, or http on `localhost`), where - `crypto.subtle` exists, and a program whose `main` runs its `io_context` - (<>). +* webcpp::document for every JSON text, webcpp::asio, webcpp::hash for the + digests, HMAC, HKDF and PBKDF2 of the room keys, webcpp::crypto for + AES-256-GCM, randomness, the ECDSA P-256 signatures of identities and + handshakes, over BearSSL, and the BIP-340 signatures of Nostr events, over + https://github.com/bitcoin-core/secp256k1[libsecp256k1] 0.8.0, both of + which webcpp builds from their pinned sources, and webcpp::webrtc and + webcpp::beast + for the platform backend's WebRTC and relays (<>). +* In the browser: Emscripten 6.0.11, the version webcpp pins, and a program + whose `main` runs its `io_context` (<>); a room + with a password also needs a page served from a secure context (https, + or http on `localhost`), where `crypto.subtle` exists for its PBKDF2. * Natively: https://github.com/paullouisageneau/libdatachannel[libdatachannel] 0.24.6, through webcpp::webrtc, and OpenSSL 3. diff --git a/doc/platform.adoc b/doc/platform.adoc index 111fceb..96a3873 100644 --- a/doc/platform.adoc +++ b/doc/platform.adoc @@ -15,11 +15,11 @@ https://github.com/paullouisageneau/libdatachannel[libdatachannel]'s and in a page the page's own `RTCPeerConnection` and `RTCDataChannel` (<>); its relays' WebSockets are webcpp::beast's, natively Boost.Beast's own and in a page its `WebSocket`; -its timers are webcpp::asio's `steady_timer`. Two parts are the target's own, -chosen by `WEBCPP_TARGET_EMSCRIPTEN`: the sealer, natively OpenSSL's AES-GCM -and in a page `crypto.subtle`, and the source of randomness, natively -OpenSSL's generator and in a page `crypto.getRandomValues`, called from -JavaScript that catches what it throws. Its clocks are the standard +its timers are webcpp::asio's `steady_timer`; its randomness is +webcpp::crypto's `random_device`. One part is the target's own, chosen by +`WEBCPP_TARGET_EMSCRIPTEN`: the PBKDF2 of a room's password, natively on a +thread of the backend's own and in a page through `crypto.subtle` +(<>). Its clocks are the standard library's on both: `std::chrono::system_clock` for Nostr's `created_at`, and `std::chrono::steady_clock` for its timing, which Emscripten reads from the page's `Date.now()` and `performance.now()`. @@ -55,9 +55,8 @@ its relays and its own state with, beside the app's `ice_servers`: in every app it serves together, 256: beyond, it makes none, and a room reports each negotiation it cannot start. A room makes at most 64 in any 57 s however its peers behave (<>), so the - default lets four rooms do so at once. A connection still counts against - its negotiating room's 57 s window after adoption by the app; presence and - reuse make none. + default lets four rooms do so at once. Each room makes its own + connections, one to each peer it meets, as 0.27.0's rooms do. | `runtime` | What the backend's own webcpp::webrtc runtime is made with, @@ -255,26 +254,34 @@ Each drop reports one close, and the room reconnects with its backoff (<>). [#trystero-platform-randomness] -=== Randomness and sealing - -The backend's randomness, the room's keys and nonces, and the IV of each -seal come from the platform's one secure source, its result checked: -OpenSSL's `RAND_bytes` natively, and in a page `crypto.getRandomValues`, at -most 65536 bytes a call, which the backend calls from JavaScript that catches -what it throws: a page whose `getRandomValues` is missing or throws has no -randomness, and no JavaScript exception enters WebAssembly, where Emscripten's -`getentropy` let it through. When it has none, `random()` aborts the program, -since nothing is safe without it, and a seal fails with -`error::backend_failure`. - -The sealer is asynchronous on both targets, as Web Crypto is: natively it -works synchronously and posts its completion, and in a page it awaits each -Web Crypto promise with webcpp::asio's `browser::async_await`, under a key it -imports on its first operation, while the operations that arrive meanwhile -wait with a copy of their text. A completion never runs inside the call that -started it. A settlement that is not an `ArrayBuffer`, which only a page whose -`crypto.subtle` was replaced gives, fails the seal or the open with -`error::backend_failure`. +=== Randomness and a password's derivation + +The backend's randomness, the ids and nonces a room draws, and the IV of each +seal, come from webcpp::crypto's `random_device`, the platform's one secure +source: `getentropy` natively, and in a page, through it, +`crypto.getRandomValues`. When it has none, `random()` aborts the program, +since nothing is safe without it. In a page whose `getRandomValues` is +missing or throws, Emscripten's `getentropy` lets the exception into +WebAssembly, where trystero 0.1.0's own source caught it in JavaScript: the +program ends either way, and the guard belongs to webcpp::crypto's +`random_device` (design Open Question 1). The test `platform_page_entropy`, +which expects each room of such a page to report `identity_failed` and no +exception in WebAssembly, runs only by name until that guard lands. The room's signing key draws its +secret and each signature's auxiliary bytes from `random_device` too. + +The backend has no sealer: a room seals and opens its signals in the call, +with webcpp::crypto's AES-256-GCM, natively OpenSSL's and in a page +BearSSL's (<>). What stays asynchronous is the +PBKDF2 of a room's password, `factory::derive_password_master`, 600,000 +iterations, which never runs on a room's thread: natively +`webcpp::hash::async_pbkdf2` runs it on a `webcpp::asio::thread_pool` of one +thread, which the backend makes at the first derivation and joins when it is +destroyed, the completion of the derivation it waited for then posted to the +backend's executor: a program destroys the backend before its `io_context`; +in a page `async_pbkdf2` over `backends::webcrypto` awaits +`crypto.subtle` on the backend's executor. Either completes on the +backend's executor, after the call that started it; a derivation that fails +completes with `error::backend_failure`, its output zeroed. [#trystero-platform-exceptions] === Exceptions @@ -313,10 +320,6 @@ the `io_context` on several threads gives the app a strand, shared by all its rooms. A native program that uses the backend is built with `threading=multi` (<>). -If a transport closes during adoption, before the room obtains a binding, -the room forgets that negotiation and restarts announcements. Its later close -event cannot leave signaling marked connected with no binding. - [#trystero-platform-libdatachannel] ==== What the backend asks of libdatachannel @@ -340,8 +343,8 @@ hands out held until its owner lets it go. The backend adds: In a page the backend is given the executor of the program's `io_context`, which the program runs from `main`. One backend serves every app and room of -the page. Apps with different passwords use distinct self ids and share no -connection or presence. ``, which builds +the page. Apps with different passwords use distinct self ids, and each +room its own connections. ``, which builds only on emscripten, holds what a page's program uses beside it: `platform::page_call` and `platform::js_string`. @@ -422,14 +425,13 @@ is made to carry either. ==== No JavaScript exception enters WebAssembly The backend makes every call into JavaScript that can throw, a `WebSocket` -constructor or `send`, a Web Crypto method, `crypto.getRandomValues`, in -JavaScript that catches what it throws: webcpp::beast's page stream turns a -socket that cannot be made into an error, and its relay reports its close; a -Web Crypto call is made inside an `async` function, so that what it throws -becomes the rejection of its promise, which the {cpp} turns into the error -its interface has, and its settlement is read only when it is an -`ArrayBuffer`; and `crypto.getRandomValues`, missing or throwing, is a -platform without randomness (<>). +constructor or `send`, or a Web Crypto method, in JavaScript that catches +what it throws: webcpp::beast's page stream turns a socket that cannot be +made into an error, and its relay reports its close; webcpp::hash's Web +Crypto backend turns a PBKDF2 the page rejects into the derivation's error. +`crypto.getRandomValues`, called by webcpp::crypto's +`random_device` through `getentropy`, is the exception: missing or +throwing, it ends the program (<>). webcpp::webrtc's JavaScript catches the page's WebRTC exceptions the same way. The bridge's functions catch what still escapes a delivery, put WebAssembly's stack pointer back and report it, and with exceptions a {cpp} @@ -457,17 +459,17 @@ stops it. `backend_config::max_peer_connections_per_minute` (256) in any minute, as natively. Beyond, the rooms report each negotiation they cannot start. -Peer connections, data channels and received frames use the app's resource; -relay sockets, their events, timers and sealed signaling texts use the -room's. Presence or reuse binds another room without making another peer -connection. +Peer connections, data channels, received frames, relay sockets, their +events, timers and sealed signaling texts use the room's resource. [#trystero-platform-needs] ==== What a page needs -* A secure context: https, or http on `localhost` or `127.0.0.1`. Elsewhere - `crypto.subtle`, which seals the signaling, does not exist, and every - sealing operation fails with `error::backend_failure`. +* For a room with a password, a secure context: https, or http on + `localhost` or `127.0.0.1`. Elsewhere `crypto.subtle`, which derives the + password's master, does not exist, and the derivation fails with + `error::backend_failure`, which the room reports; a room without a + password needs no secure context. * No threads: Emscripten's threads need a cross-origin isolated page, so trystero uses none. Its Asio is webcpp::asio's, built without threads when the program has no pthread ABI, and `main` runs it on the page's one @@ -514,8 +516,8 @@ for the page's life, and makes the action `chat` twice: once as include::{examples}/chat/chat.cpp[tag=state] ---- -The program joins the app and the room its user typed, and sets its -handlers; it reads the page's form only once it knows it holds two strings, +The program joins the app and the room its user typed, and adds its +listeners; it reads the page's form only once it knows it holds two strings, since its handler lets no JavaScript error out (<>), and a received message goes from its frame straight into a JavaScript string: diff --git a/doc/protocol.adoc b/doc/protocol.adoc index 086d258..5e0455f 100644 --- a/doc/protocol.adoc +++ b/doc/protocol.adoc @@ -7,13 +7,130 @@ [#trystero-protocol] == The protocol -A room keeps Trystero 0.26.0's wire byte for byte. The protocol's pure -functions are in ``; their tests compare them, -byte for byte, with values Trystero JS computed itself -(<>). What a Trystero JS peer or a page sees never changes: -the topic prefixes `Trystero@` and `Trystero:`, the handshake's -`+__trystero_pw+`, every constant and message layout, and the default relays -in their order. +A room speaks Trystero 0.27.0's topics, room keys, sealing, ids, identities, +handshake, relays, Nostr events and action wire, byte for byte. The +protocol's pure functions are in ``; the +`crypto_layer` test compares them, byte for byte, with the vectors 0.27.0's +own code computed, `test/fixtures/expected/trystero-0.27.0.json`, which +`test/oracle/record_0_27.mjs` records by importing 0.27.0's +`packages/core/src` and `packages/nostr/src` unchanged and pinning +randomness only around the calls whose output it decides, and keeping the +WebCrypto signatures of its previous output that 0.27.0 still verifies; the +`protocol` and `signaling` tests hold, against the values Trystero 0.27.0 +writes for the oracle lane, a Nostr event's id, the JSON texts and the +signals 0.27.0 refuses (<>). + +[#trystero-protocol-crypto] +=== Topics, ids, room keys and sealing + +Every value below is 0.27.0's, as its `crypto.ts`, `primitives.ts` and +`utils.ts` compute it; the vectors hold each for the app `example.com/app` +and the room `lobby`, the names written raw in UTF-8 as `JSON.stringify` +writes them, `café` and an emoji among the vectors. + +[cols="1,3",options="header"] +|=== +| Value | What it is + +| Path and topic +| `topic_path` writes its parts as `JSON.stringify` writes an array of + strings; `hash_topic` is the base64url SHA-256 of a text's UTF-8 bytes. + The root topic is `hash_topic(["Trystero",,])`, and a peer's + topic `hash_topic([,])`, over the root topic's path + and the peer's id, where it receives its offers, answers and candidates + +| Domain tags +| `trystero::v`, `domain_tag`, which separates each use of a + key or a hash from every other + +| `hash32` and `str_to_num` +| FNV-1a 32 over the UTF-8 bytes, then MurmurHash3's `fmix32`; `str_to_num` + is `hash32` modulo its limit, `Number.MAX_SAFE_INTEGER` by default + +| Ids +| `gen_id(n)` draws `ceil(n * 1.15) + 4` bytes a round and keeps + `0-9A-Za-z[b % 62]` of each byte below 248, skipping the others, until `n` + characters: peer ids of 20, user ids of 22, offer ids of 12, nonces of 8, + subscription ids of 64. `uuid_v4` is RFC 9562's version 4 over 16 random + bytes. A peer's id and a user's are derived from a key + (<>) + +| Base64url +| RFC 4648's URL alphabet without padding; `from_base64url` accepts a text + only when it is nonempty, holds only `[A-Za-z0-9_-]`, has no padding and + writes the same text again from its bytes, as `fromBase64Url` and its + re-encoding check accept it + +| Room key without a password +| AES-256 keyed with the SHA-256 of `["trystero:room-aes:v3",,]` + +| Room keys with a password +| a PBKDF2-HMAC-SHA-256 master of the password's UTF-8, 600,000 iterations, + 32 bytes, under the salt SHA-256 of + `["trystero:pbkdf2-master:v3",,]`, derived off the room's + thread (<>); then HKDF-SHA-256 with 32 zero bytes + of salt to the AES key, info `trystero:room-aes:v3`, and the HMAC key, + info `trystero:room-hmac:v3` + +| Room auth token +| the base64url HMAC-SHA-256 of + `["trystero:ov-auth:v3",,,,]`; verification + refuses a token that is not strict base64url of 32 bytes, or a `seq` past + 2^53^ - 1, and compares the MACs in constant time + (`webcpp::crypto::equal`). The port computes and verifies it, and sends + none: 0.27.0 uses it for `scale()`, which is not ported + +| Sealed text +| AES-256-GCM with a 12-byte IV drawn from the backend's randomness and the + AAD, written as the base64url of `iv \|\| ciphertext \|\| tag`; `open` refuses + a text that is not strict base64url, one shorter than 28 bytes, a tag that + does not match, and a plaintext that is not UTF-8 (<>) + +| A signal's AAD +| `\|\|`: `offer`, `answer` or `candidate`, the + sender, and the offer the signal belongs to +|=== + +[#trystero-protocol-identities] +=== Identities + +Every key of 0.27.0's identities is ECDSA P-256 (`identity.ts`), and so is +every signature, over the SHA-256 of what it signs: 64 bytes, r then s, the +form WebCrypto writes, always written with a low S and refused with a high +one (`protocol/ecdsa.hpp`), sent as base64url. + +[cols="1,3",options="header"] +|=== +| Value | What it is + +| Compact key +| A public key as `base64url(x) + "." + base64url(y)`, 87 characters; + `parse_compact_public_key` refuses another length, a misplaced `.`, a + half that is not strict base64url of 32 bytes, and a point not on the + curve + +| Peer id +| `derive_peer_id`: the low 20 base62 digits of the SHA-256 of + `trystero:pid:v1:`, over the app's endpoint key, which the + app makes when it is made; it is the app's `selfId` in every room + +| User id +| `derive_user_id`: the low 22 base62 digits of the SHA-256 of + `trystero:uid:v1:`, over the user's key + +| A user key's text +| `trystero_uk_` and the base64url of the JSON `{"d":..,"x":..,"y":..}`, + the private scalar and the point, each the base64url of 32 bytes, which + `export_user_identity` writes; `import_user_identity` also reads the JSON + of a private P-256 JWK, and accepts a key only when it signs the bytes of + `trystero:identity-self-test:v1` with a signature its point verifies, as + `importUserIdentity` does. The text holds the secret key + +| A user's proof of an endpoint +| `protocol::user_proof_payload`, 0.27.0's `userEndpointProofPayload`, + which its core neither sends nor checks; kept for the plugins that may + (design D21) +|=== [#trystero-protocol-discovery] === Discovery over Nostr @@ -22,37 +139,50 @@ in their order. |=== | Part | What it is -| Root topic -| Trystero's `sha1` of `Trystero@@`: each SHA-1 byte in base 36, - unpadded, concatenated - -| Peer topic -| the same of `Trystero@@@`, where a peer receives its - offers, answers and candidates +| Topics +| the root topic and the peer's own (<>) | Event -| kind 20000 plus the sum of the topic's UTF-16 code units modulo 10000, - ephemeral; the topic in an `x` tag; signed with BIP-340 +| kind 20000 plus FNV-1a 32 over the topic's UTF-16 code units, without + `fmix32`, modulo 10000, ephemeral; the topic in an `x` tag; signed with + BIP-340 by a key of the room's own, made at its first event + (webcpp::crypto's `curves::secp256k1`) | Subscription -| one per relay, to the root topic and the peer's own topic +| on each relay, the peer's own topic then the root topic, at most 250 + topics a REQ, with the deduplicated kinds of its topics and `since` a + minute ago, `max(0, now - 60)` | Announcement -| `+{"peerId":...,"nonce":...}+` on the root topic: at once, then after 233, - 533, 1333 and 5333 ms, then every 60 s +| `+{"peerId":...,"nonce":...}+` on the root topic, with a fresh nonce of 8 + characters each time: at once, then after 233, 533, 1333 and 5333 ms, then + every 60 s; an announcement a relay cannot take now is skipped, and the + cadence goes on | Relays -| the configured ones, or 5 of Trystero's 29 defaults, shuffled with - `sin(seed{plus}{plus}) * 10000` seeded by the app id +| the configured ones, or `relay_redundancy` (5) of 0.27.0's 30 defaults, + in the order of its seeded shuffle: a 32-bit generator, + `state += 0x6d2b79f5` and its two mixing steps, seeded with + `str_to_num()`, in a Fisher-Yates from the end |=== -A relay that answers `rate-limited:` is skipped for 60 s, doubling to 15 -minutes while the replies persist; one that answers `blocked:`, -`restricted:`, `auth-required:` or `pow:` is retired. A lost relay is -reconnected after a random share of 3.3 s, doubling to 60 s, and the delay -comes back to 3.3 s only once a connection stayed open for 60 s, so that a -relay that closes the room at once after each open is tried less and less -often. +A relay that answers `rate-limited:` cools down for 60 s, doubling to 15 +minutes while the replies persist, then is on probation, which an accepted +event ends; one that answers `blocked:`, `restricted:`, `auth-required:` or +`pow:` is retired and closed, and the room goes on over its other relays. A +CLOSED of a subscription not the room's own is ignored; a closed +subscription is asked again after 5333 ms, doubling to 60 s, or after the +cooldown. When the last pending EOSE comes 1 s or more after its REQ, the +announcements are replayed. A lost relay is reconnected after a random share +of 3.3 s, doubling to 60 s, and the delay comes back to 3.3 s only once a +connection stayed open for 60 s, so that a relay that closes the room at +once after each open is tried less and less often; a reopened relay is +subscribed again and its announcement replayed once, without a new warm-up. +When the first connection of every relay closed before any opened, the room +reports `relay_failed` once. `app::set_relay_connectivity` closes every +relay of the app's rooms and holds them closed (`offline`), reconnects at +once each relay not connected (`online`), or follows the page's `online` +and `offline` events (`automatic`, online natively). A relay may repeat an event, and every relay of the room carries it, so a room acts on an event once: it remembers the ids of the newest 4096 events it @@ -75,14 +205,75 @@ other's announcement. The higher one answers an announcement by announcing itself on the other's peer topic, so the lower one offers: at most once a second per peer, and once in 5.3 s per relay for the whole room, Trystero's announce interval, so that a flood of low ids does not have the relays -rate-limit the room. Offers, answers and candidates are sealed with AES-GCM -under the SHA-256 of `::`, using the immutable -`app_config::password`, empty for a passwordless app, with a 16-byte IV, as the text `$`: the IV's bytes -in decimal joined by commas, and the ciphertext with its tag in base64. +rate-limit the room. Offers, answers and candidates are sealed under the +room's AES key, derived from the immutable `app_config::password`, or +without one when it is empty, with the AAD of their type, their sender and +their offer id, and opened in the call (<>). Candidates follow their offer or answer, trickled. A negotiation ends when -the data channel opens: the app adopts the connection, and signals from a -bound peer are ignored. A live connection is reused for another room only -after the peer advertised that room's token itself on the connection. +the data channel opens: the room's link to that peer takes the connection +and its channel, which no other room uses, and the handshake starts on it. +A signal 0.27.0's `parseSignalEnvelope` refuses is ignored +(<>). + +[#trystero-protocol-handshake] +=== The handshake + +Every frame of a room travels bare on its connection to the peer: an action +frame of the wire below, with no envelope, as 0.27.0's `sendFrame` writes +it. Before it delivers any other, a room runs 0.27.0's identity handshake +with the peer (`handshake.ts`), whose messages are payloads of the internal +action `@_hsdata`, JSON texts of at most 64 KiB: + +The initiator is the side whose id is lower in UTF-16 order, as 0.27.0 +compares its strings: + +[cols="1,2,8",options="header"] +|=== +| Step | Sender | What it is + +| 1 +| The initiator +| `{"__trystero_id":1,"n":..,"dtls":[..],` `"uid":..,"pk":..,"uk":..}`: its + nonce, a version 4 UUID drawn for the run; the DTLS fingerprints of its + description; its user id; its compact endpoint and user keys + +| 2 +| The responder +| The same members of its own, then `"ps":..,"us":..`: its endpoint's and + its user's signatures of the transcript + +| 3 +| The initiator +| `{"__trystero_id":3,"ps":..,"us":..}`, once step 2 verified: its own two + signatures of the transcript +|=== + +The transcript is the JSON array +`["trystero:id-hs:v2",,,,,,,[],[],,]`, +as `JSON.stringify` writes it, so that the signatures bind the app, the +room, both peers, both runs and both users to this connection. A +description's fingerprints are the values of its `a=fingerprint:` lines, +trimmed, lowercased, deduplicated and sorted (`dtls_fingerprints`), read +from the last local description the signaling set and the last remote one +it applied. Each side checks that a step's `pk` derives the peer's id, that +its `uk` derives its `uid`, that the fingerprints it claims are those of +the description this side applied, and that both signatures verify, through +the app's key records and verified signatures (design D18). A step of +another shape, a nonce shorter than 16 UTF-16 code units, or a signature +that is not strict base64url fails as "peer identity verification failed". + +Once its steps passed, each side sends `@_hsready`: an empty text, or, from +a room with `max_users` that cannot take the peer's user, +`{"ok":false,"err":"room full"}`; a Trystero JS peer with roles may send +`{"ok":false,"err":"peer banned"}`, with a reason. The peer joins once both +sides sent an empty one: the ready frame goes before the join is reported, +so that a send in `on_peer_join` follows it on the wire. A handshake fails +after 10 s ("handshake timed out after 10000ms"), at a 17th message the +handshake has not read ("too many pending handshake messages"), or for a +step's reason, and its room reports `handshake_failed` with that reason, +without 0.27.0's `Trystero:` prefix, then tells the peer to leave. While a +peer is pending, only its `@_hsdata`, `@_hsready` and `@_leave` are read; +its other frames are not delivered. [#trystero-protocol-json] === JSON texts @@ -101,8 +292,8 @@ before reading it, as it drops a malformed one: | a relay's text | 68,608 bytes | an event that carries the longest signal, with 2 KiB for its other fields | a signal | 66,560 bytes | a sealed offer or answer of 64 KiB with the longest ids, and 1 KiB to spare -| a handshake message | 1,024 bytes | ten times Trystero's longest, 99 bytes -| a remote candidate | 16 KiB | the bound of a sealed candidate, which its opened JSON never passes +| a handshake message | 65,536 bytes | 0.27.0's own bound of an `@_hsdata` payload, `maxPayloadBytes` +| a remote candidate | 4,096 bytes | the bound of a sealed candidate, which its opened JSON never passes |=== The image grows in place, twice as large each time, to at most twice the @@ -143,82 +334,40 @@ first, in both suspension variants. A text the protocol writes is a fixed shape of a few strings and numbers, appended field by field, its strings quoted by `webcpp::document::quote`, the bytes `JSON.stringify` writes. A string that is not UTF-8 cannot be quoted, and -the writer returns that error: the only such string a program gives that is -ever written, its self id, is set aside for a random one when the app is -made, with a configuration report to `app::on_error`, and a local candidate -whose text is not UTF-8, which no browser's is, is not sent. +the writer returns that error: a program gives no string that is ever +written, the peer id being derived, and a local candidate whose text is not +UTF-8, which no browser's is, is not sent. [#trystero-protocol-channel] === The data channel -Every message is a room frame: `1`, the length of the room token (16 bits, -big-endian), the token, the hexadecimal SHA-256 of `Trystero::`, -then an action frame. A presence frame, `2`, present or not, the token's -length and the token, announces or withdraws the room. - -Presence advertises every room of the app on each connection. It records -which rooms the remote peer joined and binds matching local rooms; a -withdrawal detaches only that room. The connection routes by token: - -[cols="2,3",options="header"] -|=== -| Frame | What happens - -| An envelope that does not decode -| The connection ends for every room. - -| `presence(1, T)`, new token -| Record it; a 65th distinct token ends the connection. Bind the matching - local room when its binding conditions permit. - -| `presence(1, T)`, known token -| Bind the matching unbound local room when permitted. - -| `presence(0, T)` -| Forget the token and its kept frames, and end its binding as a departure. - -| Room frame, token bound -| Deliver it to that room's action wire. - -| Room frame after the higher id's own kick, before it sends presence -| Drop it: it belongs to the ended binding. - -| Room frame for another room of the app, not bound to this connection -| Keep it, at most 64 frames per connection, all expiring 10 s after the - first, and record its token as the peer's advertisement, below 64 tokens. - Bind when no backoff runs. - -| Room frame for any other token -| Drop it silently; keep the connection. -|=== - -A room frame is the peer's own advertisement of its room, as its presence -is: only the peer writes to its connection. Trystero sends a room's presence -once per connection, from the open of the channel, and Chrome can drop what a -page sends on an answering channel as it opens (its log says "Send failed -INVALID_STATE"): a room waiting for that presence alone would never bind the -peer, whose frames of the room keep coming. - -On binding, kept frames arrive before later frames; a kept `@_leave` -discards itself and everything kept before it for that token. There is no -buffer for a bound room awaiting its handler: delivery is installed in the -same call that makes its binding. - -Waiting sends take turns by binding on each channel drain, preserving each -binding's waiter order and the 10 s stall bound. Chunked transfers send one -chunk per drain, giving waiting sends from other rooms a turn. Inline sends -at a buffered amount of at most 64 KiB go straight to the channel: they have -no trystero rate bound, so a flood of pings can delay every room's traffic -to that peer, and that peer only. - -Action frames are Trystero's action wire, version 2: an inline frame carries -the payload whole; a larger payload is an offer, accepted or refused by the -receiver, then chunks of at most 16,370 bytes, in order. Integers and +Every message on a room's channel is an action frame, bare, as 0.27.0's +`peer-transport.ts` writes it: no envelope names the room, since the +connection is the room's alone. Before the room binds the peer, once the +channel opens, its link keeps at most 64 frames of at most 17 KiB, for at +most 10 s, as 0.27.0's `peer.ts` keeps them; one more, a longer one, or the +deadline passed ends the link. Once bound, a frame of more than 64 KiB ends +it. A connection whose state becomes `failed` or `closed` ends its link at +once, and one that is `disconnected` after 5 s unless it comes back. A frame +or a chunk is handed to the channel only while it buffers at most 64 KiB, +waiting at most 10 s for it to drain; inline sends have no rate bound of +trystero's. + +Action frames are 0.27.0's action wire, version 3 (`action-wire.ts`), as the +frames the recorder captured from it show: an inline frame carries the +payload whole; a larger payload is an offer, accepted or refused by the +receiver, then chunks of at most 16,370 bytes, in order, or, when the offer +carries the wide flag, 64, of at most 65,522 bytes, 64 KiB with their +header. As 0.27.0, a room offers a transfer wide when its peer's connection +takes SCTP messages of 64 KiB at least, the backend's +`peer_connection::max_message_size` (`sctp.maxMessageSize`), read as the +offer is sent, and narrow otherwise or when the connection says no size; +it receives either. Integers and float64 values are big-endian, as JavaScript's `DataView` writes them. An offer's size is a float64 that must be a whole number from 1 to 2^53^ - 1, JavaScript's `Number.MAX_SAFE_INTEGER` (`protocol::max_offer_size`), as -Trystero checks it: any other makes the frame malformed, and the room kicks -its sender, as Trystero does. The size is read in 64 bits on every target, +Trystero checks it: any other makes the frame malformed, and the room +reports `peer_error` and tells its sender to leave, as Trystero does. The size is read in 64 bits on every target, so a 32-bit one too compares the whole size with `max_receive_bytes`, and refuses a transfer beyond it as Trystero does. @@ -226,14 +375,23 @@ refuses a transfer beyond it as Trystero does. |=== | Frame | Bytes -| inline (kind 0) | 2, the kind and the format shifted by four, the name (32 bytes, NUL padded), the metadata's length (uint16), the metadata, the payload -| offer (kind 1) | the inline header, the transfer's id (uint32), the payload's size (float64), the metadata -| chunk (kind 2) | 2, 2, the transfer's id (uint32), the offset (float64), the bytes -| accepted (kind 3) | 2, 3, the transfer's id (uint32) -| rejected (kind 4) | 2, 4, the transfer's id (uint32), the reason (UTF-8, at most 200 bytes) -| cancelled (kind 5) | 2, 5, the transfer's id (uint32) +| inline (kind 0) | 3, the kind and the format shifted by four, the name (32 bytes, NUL padded), the metadata's length (uint16), the metadata, the payload +| offer (kind 1) | the inline header, with the wide flag, 64, in its second byte when its chunks are wide; the transfer's id (uint32), the payload's size (float64), the metadata +| chunk (kind 2) | 3, 2, the transfer's id (uint32), the offset (float64), the bytes +| accepted (kind 3) | 3, 3, the transfer's id (uint32) +| rejected (kind 4) | 3, 4, the transfer's id (uint32), the reason (UTF-8, at most 200 bytes) +| cancelled (kind 5) | 3, 5, the transfer's id (uint32) |=== +A receiver keeps at most 1024 offers pending across its peers and 64 of one +peer, reserves at most `max_receive_bytes` across them, and drops a peer +whose channel buffers more than 1 MiB when a control frame is to be sent to +it, as 0.27.0 does. A frame of an action the room has not made is dropped, +and its offer rejected at once as an "unregistered action", as 0.27.0 keeps +none: a page that makes an action after it joined misses what came before. +A frame of an action made, before the action listens, waits for it, 32 per +action and peer, the oldest dropped first, for 10 s. + The payload's format is text (0), JSON (1) or binary (2). Internal actions run the room: @@ -241,10 +399,11 @@ run the room: |=== | Action | What it carries -| `@_hsdata` | the password handshake: the lower id sends a challenge, and the other answers with the hexadecimal SHA-256 of `:::` -| `@_hsready` | the sender's side of the handshake passed; a peer joins when both sides sent it -| `@_ping`, `@_pong` | round trips +| `@_hsdata` | a step of the identity handshake, a JSON text of at most 64 KiB (<>) +| `@_hsready` | the sender's side of the handshake passed, an empty text, or its refusal of the receiver, `{"ok":false,"err":"room full"}` or `{"ok":false,"err":"peer banned"}` with a reason; a peer joins when both sides sent an empty one +| `@_ping` | a ping, a request of the internal action `@_ping` with an empty text, answered through `@_response` with an empty text | `@_leave` | the sender leaves the room +| `@_response` | the answer to a request: a request is a message of its action whose metadata is `{"r":,"m":}`, and its answer a message of `@_response` whose metadata is `{"r":}`, or `{"r":,"e":}` for a refusal, its reason cut at 512 UTF-16 code units, as 0.27.0's |=== The media actions, `@_stream`, `@_track` and `@_signal`, are not ported @@ -259,37 +418,41 @@ signal in any peer's name. Trystero JS bounds none of this; trystero bounds what each costs a room. * Nothing a peer sends changes a negotiation before it opens with the room - key: an offer, an answer or a candidate that does not open is counted, - reported once per negotiation, and changes nothing else. A flood of fresh - ids makes each a negotiation, so the reports are paced: the first of a - quiet 10 s goes to `on_error` at once, with its peer, and the others of - those 10 s in one report, with no peer and their number. + key: an offer, an answer or a candidate that does not open is counted and + changes nothing else. An offer or an answer is reported to `on_error` as + `decrypt_failed`, with its peer and stage, at most once a minute per peer + and stage, the last 512 remembered, as 0.27.0 reports them; a candidate + is not reported. * A room holds at most `detail::signaling::max_unconnected_peers` (32) negotiations with peers it is not connected to. A negotiation whose offer and answer expire without a connection is dropped, an idle one gives its place to a new peer, and a new peer beyond the bound is refused and logged - once. A negotiation is idle when it holds no connection and no offer of its - peer is being opened: the one idle longest gives its place, and of those - idle as long, as every negotiation is at one instant of a page's coarse - clock, the one the room took first. So an offer whose sealed text the - backend is still opening (Web Crypto's asynchronous step in a page) keeps - its place however many new ids arrive meanwhile, and is acted on once it - opens. -* A negotiation opens one offer of its peer at a time, as Trystero answers - one at a time: until it is opened, another offer in that name is ignored, - and the same offer through another relay has the answer sent there too. - So the room opens at most 32 offers at once, and offers sent in one name, - however many, hold one open and one copy of an offer. As with Trystero, a - forged offer opened first has the peer's own, arriving meanwhile, wait - until the peer sends it again, 2 s later. + once. A negotiation is idle when it holds no connection: the one idle + longest gives its place, and of those idle as long, as every negotiation + is at one instant of a page's coarse clock, the one the room took first. + A signal opens in the call that reads it (<>), so + no offer waits, unopened, for its place. +* A negotiation answers one offer of its peer at a time, as Trystero answers + one at a time: while it answers one, another offer in that name is + ignored, and the same offer through another relay has the answer sent + there too. So offers sent in one name, however many, hold one answer. As + with Trystero, an earlier offer of the peer's, resent by a watcher and + answered first, has the peer's own, arriving meanwhile, wait until the + peer sends it again, 2 s later. * A room makes at most `max_connections_per_window` (64) connections in any 57 s, however soon they end; the platform backend makes at most 256 a minute on both targets (<>), and a page holds at most 256 (<>). -* A signal's fields are bounded in `protocol/signal.hpp`: the peer id (64 - bytes; Trystero's are 20), the offer id (64 bytes), a sealed offer or - answer (64 KiB) and a sealed candidate (16 KiB, above the 8192 bytes of - plaintext Trystero takes). +* A signal is read as 0.27.0's `parseSignalEnvelope` reads it + (`protocol::read_signal`), and refused where it refuses it: a peer id of + other than 20 base62 characters, an offer id of other than 1 to 64 + characters of `[\w.~:!-]` (or none with an offer, answer or candidate), a + sealed offer or answer of more than 64 Ki UTF-16 code units, a sealed + candidate of more than 4,096. The vectors of `signal_envelopes` in + `test/fixtures/oracle/expected.json` show 0.27.0 refusing each. 0.27.0 + parses a text of up to 128 Ki characters; a room drops one of more than + 66,560 bytes unread, which only members Trystero never writes, or sealed + text that is not ASCII and never opens, can make. * A relay is a third party too: its texts are bounded at 1 MiB, what the room holds unsent for it at 4 MiB, and, natively, its silence at 30 s (<>). @@ -298,79 +461,54 @@ what each costs a room. |=== | Bound | Scope | Value and consequence -| Joined rooms -| App -| 64, counting farewells until withdrawal; `join` returns `error::too_many_rooms` beyond it. - -| Advertised room tokens -| Connection -| 64 distinct tokens; a 65th ends the connection. - -| Kept frames for unbound local rooms -| Connection -| 64, at most 64 x 16,515 bytes; expire together 10 s after the first. - Other tokens retain nothing. - -| Room frame and token +| Frames before the room binds a peer | Connection -| 16,515 bytes, token 1 to 128 bytes; an invalid envelope ends the connection. +| 64, each at most 17 KiB, for 10 s after the first, as 0.27.0's `peer.ts`; + one more, a longer one, or the time passed ends the connection. -| No bindings +| A frame once bound | Connection -| `idle_timeout` after a departure, 123,333 ms by default, 0 closes immediately; - closed at once if its last binding was kicked. +| 64 KiB, as 0.27.0; a longer one ends the connection. | Handshake | Room and peer -| `handshake_timeout`, 10 s; failure kicks that binding only. +| 10 s, as 0.27.0, which has no option for it, and 16 messages it has not + read; failure ends that peer only. -| Earlier challenges -| Room and peer -| Last 8 since the last completed handshake; a correct answer to any passes. +| Users +| Room +| `room_options::max_users`, none by default; a peer of a new user is + refused past it, a peer of a user present is admitted. + +| Key records and verified signatures +| App +| 4,096 records, and 8,192 signatures of payloads of at most 4,096 bytes, + 2 MiB in all, as 0.27.0's caches; the least recently used out. -| Pending action frames +| Action frames before a listener +| Action and peer +| 32 for 10 s, of an action made; of an action not made, none. + +| Transfers and queued messages | Room and peer -| 64 for 120 s; one incoming transfer per peer, `max_receive_bytes` across - peers, and 1024 queued messages per action. +| 1024 pending offers, 64 a peer, `max_receive_bytes` across peers, and + 1024 queued messages per action once it is awaited. |=== -After a kick or the peer's `@_leave`, a live connection is rebound one step -after that binding ended. The initial step is the larger of -`handshake_timeout` and 10 s, plus 1 s (11 s by default), doubling at each -further end to 5 minutes. Only a completed handshake or the connection's -end resets it. After its own kicks the lower id refuses bindings until its -backoff ends, ignores signals and keeps frames; the higher id drops frames -until it next sends presence and accepts the lower id's presence at once. -The room sends presence again on reuse or scheduled rebinding, making the -other side bind without a relay response. Announcements restart only when -no live connection remains. A forged announcement never binds a peer that -has not advertised that token itself. - -A connection counts against its negotiating room's 64-per-57-s window even -after the app adopts it; presence and reuse make no connections. Fresh ids -that connect and depart keep at most `64 x ceil(idle_timeout / 57 s)` idle -connections per room, 192 by default, within the backend's own bound. -Leaving a room with many peers retains no more connections than the app -already held. Kept frames and tokens cost at most about 1 MiB and 8 KiB -per connection; each of at most 64 bound rooms retains its own peer bounds. -A flood spends its room's queues, transfers and reservations; routing never -holds one room's frame for another room. - -With the lower id an invalid room response proof causes at most six kicks and reports in -the first ten minutes, then one per 5 minutes. The higher id can be rebound -by a lower-id peer at that peer's pace, but reports at most one handshake -timeout per `handshake_timeout`, and does not verify a response proof. -Malformed challenges are rejected by their receiver and can also report -`wrong_password`; their report rate follows the malicious peer's repeated -bindings, rather than the timeout bound. +Each room negotiates its own connection to each peer, as 0.27.0's rooms +do: an app whose rooms meet one peer in three rooms holds three connections +to it, each counted in its room's window of 64 connections in 57 s, and +each closed as its room leaves or the peer goes. [#trystero-protocol-replay] === Replayed offers and answers -A sealed offer or answer holds neither its offer id nor a peer id -(Trystero's wire), so one recorded from the relays still opens when anyone -resends it in its sender's name, and so does the room's own, sent back to it. -A room remembers, by the SHA-256 of their opened text, the last 1024 offers +A sealed offer or answer is bound by its AAD to its type, its sender and its +offer id (<>), so one recorded from the relays +opens only as what it was: never as another's, nor an answer sent back as an +offer. Resent so, in its sender's name and for its offer, it still opens, +and so does the room's own, sent back to it under its own id. A room +remembers, by the SHA-256 of their opened text, the last 1024 offers and answers it made or acted on (`detail::signaling::remembered_descriptions`), and refuses one that comes to it as a peer's: it changes nothing and is logged. It makes or acts on at most @@ -382,25 +520,27 @@ as a peer's offer or answer. [#trystero-protocol-limitations] === What remains -Sharing preserves Trystero JS 0.26.0's wire. Each {cpp} app is one password -domain: it copies one password at construction, and all its rooms use it. -The initial sealed signaling authenticates that password before the data -channel is adopted. Later room binding reuses this authenticated connection. +Each {cpp} app is one password domain: it copies one password at +construction, and all its rooms use it. A room's signals are sealed under +keys derived from that password, so a peer of another password opens none +of them and never connects, as in 0.27.0, which has no password challenge. There are no per-room overrides, and different passwords require separate -apps with distinct self ids. This protects admission to the {cpp} app's -rooms without changing the room handshake on the wire. - -*A watcher not connected to the app, without the key, can keep two peers apart.* A sealed offer or -answer the room neither made nor acted on still opens and is acted on. Such -texts are not scarce: every peer seals a fresh offer for any id announced -above its own, and announcements need no key. So anyone who reads and -publishes on the relays, without the key, can keep any two peers of a room -apart from their first meeting for as long as it keeps at it, each attempt -costing the other peer a connection of its window. A watcher not connected to the app cannot read or alter -anything the peers exchange, join the room, or touch peers already joined; a -joined peer that drops is a new peer again. The room refuses only what it -made or already acted on. Only a wire that seals the offer id and both peer -ids closes this, which Trystero would have to share (reported upstream). +apps with distinct self ids. + +*A watcher not connected to the app, without the key, can keep two peers +apart.* A sealed offer or answer the room neither made nor acted on still +opens and is acted on: the AAD names its sender and its offer, not its +receiver. Such texts are not scarce: every peer seals a fresh offer for any +id announced above its own, and announcements need no key. So anyone who +reads and publishes on the relays, without the key, can keep any two peers +of a room apart from their first meeting for as long as it keeps at it, each +attempt costing the other peer a connection of its window. It cannot read +or alter anything the peers exchange, join the room, or touch peers already +joined: the signed handshake that follows each connection admits only the +peer whose key derives the id it connected as, over the fingerprints of +that connection. A joined peer that drops is a new peer again. The room +refuses only what it made or already acted on. Only a wire that also seals +the receiver's id closes this, which Trystero would have to share. *A flooder can delay new peers.* Joined peers, memory and connections stay safe under a flood, but a flooder who keeps sending new ids takes each place, @@ -411,49 +551,9 @@ with the same id, and is kept out the same way: the room has no renegotiation that would keep its place. Closing it needs announcements that prove the room key, a wire change Trystero would have to share. -*A passwordless app's rooms are open to its connected peers.* Presence -gives a peer connected through any room the token of every room of that -app. Relay events reveal their topics in the clear, and announcements -reveal the app's peer id. The token alone binds the existing connection, -and the empty app password goes straight to `@_hsready`, so that peer can -join another room without knowing its id. A watcher not connected to the -app still needs the room id to derive its topics and signaling key. -Protected rooms belong to another app with a password and a distinct self -id. Its presence, tokens and connections never reach the passwordless app. - -*The upstream one-way handshake remains.* The responder to a room -challenge answers and passes its side; only the lower id verifies the -password proof. A Trystero JS page that itself mixes different passwords -on one app's shared connection can therefore admit a peer to its own -higher-id room without that room's password, and can expose a challenge -response for offline guessing. The {cpp} app-domain boundary does not -repair such a JS page. Configure all rooms of one JS app with one password, -and use separate page contexts for different password domains. The wire -has not gained bilateral room proofs. - -*A domain member can send an invalid room proof.* A peer already -connected to a protected {cpp} app knows its domain password from the -initial sealed negotiation. It can nevertheless answer a later room's -challenge incorrectly or send malformed handshake data. The room kicks -that binding and applies the documented backoff; only the lower id checks -and reports a wrong response. These checks isolate faulty peers within an -authenticated domain, rather than admitting another password domain. - *One identity links the app's rooms.* Each room announces the same -`peerId` in clear, and connected peers see it across shared rooms. Relay -observers and peers can link those rooms to one program. Separate apps -provide separate identities and connections for rooms that must remain -unlinked. A forged announcement in a connected peer's name binds nothing: -only the peer itself, on its encrypted connection, can advertise the token. -It causes no report or rebinding count against that innocent peer. - -*Two transient cases remain with a Trystero JS lower id.* If it binds by -reuse during the higher {cpp} id's dropping window, its challenge is -dropped and its handshake can time out once. With the default 10 s timeout -the next rebinding joins by at most 43 s after the first kick plus one-way -delay, with no false password error on either side. If a JS page's timer -that expires a stale answer runs later than the 1 s margin before presence -arrives, JS can flush the old answer into a new handshake and report a -false password error. One-minute timer lag can repeat this at the 11, 22 -and 44 s steps, at most three times, before the 88 s step exceeds that lag. -The {cpp} side reports nothing false in either case. +`peerId` in clear, and its handshake presents the same endpoint and user +keys, so relay observers and peers can link the rooms of one app to one +program, as 0.27.0 links the rooms of one page. Separate apps provide +separate identities for rooms that must remain unlinked; apps given one +`user_identity` are one user's endpoints, by design. diff --git a/doc/quick-start.adoc b/doc/quick-start.adoc index a7a8c57..c1641df 100644 --- a/doc/quick-start.adoc +++ b/doc/quick-start.adoc @@ -8,8 +8,8 @@ == Quick start The quick start is one native program with two peers in it, `alice` and -`bob`: each is an app of its own, with an id the program gives it, and both -join the room `lobby` of the app `webcpp-trystero-quick-start`. alice greets +`bob`: each is an app of its own, with an id of its own, and both join the +room `lobby` of the app `webcpp-trystero-quick-start`. alice greets bob when he joins, bob answers, each prints what it received, and both leave, which ends the program. In the browser the same rooms run in a page, as the chat example shows (<>). @@ -18,10 +18,11 @@ as the chat example shows (<>). [#trystero-quick-start-native] === Two peers in one program -An app is one peer: its id among the peers, its relays and its STUN servers. -The program gives each app its id, `app_config::self_id`, where an app would -draw 20 random characters, so that what it prints is the same on every run. -It meets over the relay whose URL is in the environment, +An app is one peer: its id among the peers, 20 base62 characters derived +from the P-256 endpoint key it makes when it is made, as 0.27.0 derives it +and has no custom id, its user, ephemeral here, its relays and its STUN +servers. Each peer prints what it receives after the other's name, so that +what the program prints is the same on every run. It meets over the relay whose URL is in the environment, `TRYSTERO_RELAY_URL`, which the lane `relayed` starts on 127.0.0.1, and then keeps its peers on the machine; without it, the program uses Trystero's public relays and STUN servers, as every program that names none @@ -38,17 +39,17 @@ include::{examples}/quick_start.cpp[tag=config] room, and makes in each room the action `chat`, whose messages are `std::string`. alice greets each peer that joins, once its handshake completes, with a message to that peer alone, and prints what she receives, -after its sender's id, then leaves. bob's part is a coroutine. `run` -returns once no work is left: each room closes its relays as it leaves, and -each connection closes as soon as no room uses it: +after bob's name, then leaves. bob's part is a coroutine. `run` +returns once no work is left: each room closes its relays and its +connections as it leaves: [source] ---- include::{examples}/quick_start.cpp[tag=main] ---- -bob awaits the first message with `async_receive`, prints it after its -sender's id, answers its sender with `async_send`, and leaves with +bob awaits the first message with `async_receive`, prints it after alice's +name, answers its sender with `async_send`, and leaves with `async_leave`. `asio::as_tuple` hands each error over as a value, so a room left first ends the wait instead of throwing: @@ -64,9 +65,8 @@ The program prints bob's line, then alice's: include::{examples}/quick_start.expected[] ---- -Its twin on Trystero JS prints the same two lines. Trystero draws one -`selfId` per page, so bob is a second page there, and each peer prints the -other's name where the {cpp} program prints the id it gave the app: +Its twin on Trystero JS prints the same two lines. Trystero keeps one +endpoint identity per app id and page, so bob is a second page there: [source,javascript] ---- @@ -90,5 +90,5 @@ include::{examples}/chat/chat.cpp[tag=state] <> shows how it joins, sends, and runs its `io_context` from `main`, and <> serves it. Two tabs of the chat that join the same app and room meet; so do a native -peer and a page, which the lane `interop` proves with Trystero JS pages in -headless Chrome (<>). +peer and a page. The lane `interop` proves it with Trystero 0.27.0's pages +in headless Chrome (<>). diff --git a/doc/roadmap.adoc b/doc/roadmap.adoc index f16a2e5..57210e7 100644 --- a/doc/roadmap.adoc +++ b/doc/roadmap.adoc @@ -11,14 +11,24 @@ What trystero does not port yet, and what it does not build itself yet (<> gives each feature left out with its reason): -. *Media.* Audio and video tracks and streams, and Trystero's `@_stream`, -`@_track` and `@_signal` actions with renegotiation. In the browser they are +. *Media.* Audio and video tracks and streams, and Trystero's `@_stream` and +`@_signal` actions with renegotiation. In the browser they are the page's `MediaStreamTrack` objects. Natively they would be libdatachannel's RTP tracks, whose encoding, decoding and capture are the application's. What that needs was measured: libdatachannel keeps only weak references to tracks, answers with every codec offered unless the answer is pruned, and echoes the offerer's `msid` into the answer. Media will be an interface of webcpp::webrtc's, which the backends' WebRTC is. -. *Trystero's other features.* Request actions (`kind: 'request'`), -decisions on incoming transfers and their progress, the application's own -handshake, passive rooms, and the other strategies, among them MQTT and BitTorrent trackers. +. *Trystero 0.27.0's plugins.* Each a change of its own, on an +interoperable library: signed records and shared state, `makeState` and +`makeUserState`; roles and moderation, `roles` with its bans and role +certificates; and `scale`, with its relayed peers and their pairwise keys. +. *Trystero's other features.* `requestMany`, the progress and the +cancelling of sends and requests, the receive and request decisions +answered later, with 0.27.0's bounds on those pending (128 receive +decisions, 8 of one peer, 64 concurrent requests of one peer), passive +rooms, and the other strategies, among them MQTT and BitTorrent trackers. +. *What webcpp::crypto does not provide yet.* A public wipe of a buffer of a +size known only at run time: trystero wipes the password's copies and the +buffers of an import with its own `detail::wipe` until webcpp::crypto has +one. diff --git a/doc/testing.adoc b/doc/testing.adoc index c231633..4a606a9 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -15,9 +15,10 @@ another machine. The backend interface is the seam: a program's tests run its rooms over a backend of their own, in memory, as trystero's own tests run whole rooms over `test/support/memory_backend.hpp`, a backend whose Nostr relays forward ephemeral events to matching subscriptions, whose peer -connections pair through their descriptions, whose data channels deliver in -order, and whose sealer opens only what was sealed under the same key, each -event posted to the `io_context`. It is in the namespace +connections pair through their descriptions, each with a DTLS fingerprint +line of its own for the handshake, whose data channels deliver in order, and whose derivation of a password's master runs webcpp::hash's +PBKDF2 in the call, 1,000 iterations in place of 600,000 since its rooms +meet only each other, each event posted to the `io_context`. It is in the namespace `webcpp::trystero::test`, outside the library's public headers, and a program may copy it. @@ -27,9 +28,9 @@ paired end. A `filter` delivers, drops or holds frames; a held frame holds all later frames from its sending end behind it, preserving channel order until `release`. Deferred `open` calls open each end separately; `inject` and `fail` supply malformed frames and transport failure. With -`hold_sealer_opens`, every sealer's opens wait, as Web Crypto's take their -time in a page, until `release_sealer_opens` completes them in order; -`held_sealer_opens` counts them. +`derive_delay`, every derivation's completion waits, as a page's Web Crypto +takes its time, until `release_derivations` completes them in order; +`held_derivations` counts them. With `channel_capacity` enabled, the channel queues bytes and drains up to `drain_per_post` per post. It delivers a frame only after its last byte @@ -73,8 +74,8 @@ list (<>). | the public headers | Each compiled alone, on each target that builds it: the core, and the - platform backend's `backend.hpp`, `entropy.hpp`, `sealer.hpp` and - `websocket.hpp` with the backend's WebRTC, on both, natively against + platform backend's `backend.hpp` and `websocket.hpp` with the backend's + WebRTC, on both, natively against webcpp::webrtc's libdatachannel and OpenSSL and in a page over its own objects; and `platform/page.hpp`, on emscripten alone. @@ -85,52 +86,89 @@ list (<>). `WEBCPP_NO_EXCEPTIONS`), and keeps it when a developer defines it for trystero alone in a build that has them. +| `crypto_layer`, `crypto_layer_release` +| The protocol of Trystero 0.27.0 against the vectors its own code computed, + `test/fixtures/expected/trystero-0.27.0.json`, which + `test/oracle/record_0_27.mjs` records: topic paths, topics and their + kinds, `hash32` and `str_to_num`, domain tags, the relay shuffle, `gen_id` + and the ids derived from a compact key, strict base64url, room keys with + and without a password, room auth tokens, sealed texts and their AAD, the + texts `open` refuses, the action wire's recorded frames, P-256 keys, + compact keys and signatures, low S, user identities exported and + imported, the user's proof, the handshake's steps, transcript and frames, + and the ping's frames; and trystero's wipe. The 600,000 iterations of a password's PBKDF2 run in + `crypto_layer_release` alone, a release build. + | `protocol` -| The protocol against values Trystero JS 0.26.0 computed itself: topics, - room tokens, the relay shuffle, sealed text, Nostr event ids, inline and - chunked action frames, control frames, envelopes and presence, a JSON - payload's numbers and key order, and the bounds of a signal's fields. +| Against values Trystero JS 0.27.0 computed itself, which the oracle lane + writes into `test/fixtures/oracle/expected.json`: Nostr event ids, a JSON + payload's numbers and key order, and the rules no recorded value shows: an + action's name, the wide chunks' bound, an offer's size, big-endian fields, + and the bounds of a signal's fields. | `signaling` -| The signaling and the Nostr strategy alone: as an answerer, the signals - Trystero JS 0.26.0's own signal handler published for the same offers, - byte for byte, a signal or a relay's text read at its bound and - dropped one byte past it, and a relay's text read 16 deep and dropped one - level deeper. +| The signaling and the Nostr strategy alone: an answerer's signals, each + signal 0.27.0's `parseSignalEnvelope` refuses refused, against the + oracle's `signal_envelopes`, a signal or a relay's text read at its bound + and dropped one byte past it, and a relay's text read 16 deep and dropped + one level deeper. + +| `subscription`, `user_table` +| The listeners of an event, 0.27.0's emitter: in the order added, removed + while one runs, `once`, `replay`, one added while an event is reported + waiting for the next, and a subscription dropped leaving its listener; and + the users of a room, which their first peer joins and their last leaves. | `room`, `room_asyncify_release` | Whole rooms in one process, over the memory relays: every payload format, - 100 KB transfers both ways, ping, passwords right and wrong, leaving and + 100 KB transfers both ways, wide transfers sent and received, frames of an + action not made dropped, 0.27.0's bounds on frames, the identity + handshake, its ready frames, its 10 s and its failures, forged steps and + other fingerprints among them, ids derived from keys and imported + identities, `max_users` and its admissions, request actions, receive gates + and progress, listeners, users, `self()`, sends to users and to absent + targets, 0.27.0's room errors, each with its emitter, and their pacing, + relay connectivity, a password's keys derived after the join returns, once + per room and again after a failure, ping, passwords right and wrong, the + connections of each room its own, leaving and returning, a room moved over a joined one, ICE servers checked as WebRTC checks them, floods of announcements and of forged, replayed and reflected - signals, offers being opened that keep their places when new ids arrive - at the same instant, one offer of a peer opened at a time, a relay that + signals, offers that keep their places when new ids arrive at the same + instant, one offer of a peer answered at a time, a relay that closes at once or rate-limits, a three-peer mesh, coroutines and view handlers, JSON payloads read in the room's resource up to its bound, and a rejected document receive. | `app_impl`, `app_impl_asyncify_release` -| Configuration copying and validation, a self id that is not UTF-8 set - aside, resource ownership, weak room - registration, shared adoption, stale replacement, reentrant adoption, - last-user closure and quiet destruction with pending work. - -| `connection` -| Shared transport routing, advertised token and kept-frame limits, binding - detachment, departures and kicks, idle expiry and drain ordering. +| Configuration copying and validation, no custom self id, resource + ownership, weak room registration, the relays' connectivity reaching every + room, the page's watch ending with its last user, quiet destruction with + pending work, and the password wiped before it is freed. + +| `peer_link`, `peer_link_hardened` +| One room's connection to one peer alone, over a memory pair: the frames + kept before the room binds it, in order, and 0.27.0's bounds on them, the + bound on a frame once bound, which follows the connection's largest + message, the drain waiters, and a disconnection's grace; once more + natively with the standard libraries' checks. + +| `handshake_manager`, `handshake_manager_hardened` +| A room's handshakes alone, 0.27.0's handshake manager: who initiates, the + ready frame before the join, the join once both sides are ready, a + deferred responder, the 16 buffered messages, the 10 s on the virtual + clock, and a clear that fails a waiting step; once more natively with the + standard libraries' checks. + +| `identity_cache` +| An app's key records and verified signatures against 0.27.0's vectors: + their bounds, least recently used out, a cached answer given without + verifying again, a high S refused before verification, and ids checked + against their keys. | `memory_backend` | Virtual timer ordering, cancellation, held-frame order, deferred opens, injection and failures, and byte-accurate buffering and drain. -| `shared`, `shared_no_exceptions`, `shared_hardened` -| Multiple apps and rooms with one connection per remote peer, adoption - races, presence and reuse, room isolation, departures, idle connections, - password-domain isolation, invalid room proofs, transient handshake recovery, - fairness, bounds, a handshake message read at its bound and failing one - byte past it, and resource ownership. The suite also runs without exceptions and with - standard-library hardening; sanitizers check lifetimes and detachment. - | `allocation`, `allocation_asyncify_release` | Every allocation of two apps and their rooms goes through their resources (<>). @@ -141,7 +179,7 @@ list (<>). cancelled, restarted or destroyed never fires, even when its expiry was already queued. -| `platform_backend`, `platform_sealer`, `platform_websocket_unreachable`, +| `platform_backend`, `platform_websocket_unreachable`, `platform_websocket_url`, and each `_no_exceptions` | The platform backend on both targets, natively and on emscripten under node, which has the page's WebSocket and Web Crypto but no WebRTC. The @@ -150,14 +188,9 @@ list (<>). it in the default resource, and gives it all back when it is destroyed (<>); its clocks are the standard library's, its randomness fills what it is given, differently each time, beyond a - piece of its source too (65536 bytes in a page), its executor is the one - it was given and its TLS context is made. The sealer opens what Trystero JS - sealed with Web Crypto, seals a text that opens again in Trystero's form, - takes a text sealed under another key, or no sealed text, for a wrong - password, completes after the call that started it, never inside it, and - completes each of two seals and two opens given in one call, which in a - page wait while it imports its key; in a page without `crypto.subtle` it - fails with `error::backend_failure`. A relay it cannot reach, of a URL the + piece of its source too, its executor is the one it was given and its TLS + context is made, its destruction waits for a derivation under way, and + without a page it watches no connectivity. A relay it cannot reach, of a URL the session refuses, `http://` and `https://` among them, reports exactly one close, after the call that made it, and so does one of a port on 127.0.0.1 or `::1` where nothing listens, which is attempted: natively its TCP @@ -207,8 +240,8 @@ list (<>). `platform_page_websocket_ingress`, `platform_page_websocket_tls`, `platform_page_data_channel`, `platform_page_peer_connection`, `platform_page`, `platform_page_call`, `platform_page_handlers`, - `platform_page_sealer`, `platform_page_sealer_allocation`, - `platform_page_relay_allocation`, and each `_no_exceptions` + `platform_page_relay_allocation`, `platform_page_connectivity`, and each + `_no_exceptions` | The platform backend in a page, on emscripten under node, each test's `main` running its `io_context` as a page's program does: the relays' WebSocket, its bound on what a relay holds unsent, both the session's own @@ -230,20 +263,16 @@ list (<>). and breaks nothing; a call through a function the page kept after its `page_call`, or its `io_context`, was destroyed reaches nothing, and the handler reads the page's value as it is when it runs, and a number within - its range; the relay socket's and the sealer's handlers run outside the - page's events; a page whose `crypto.getRandomValues` throws or is missing - has no randomness and fails a seal, and one whose `crypto.subtle` settles - with something other than an `ArrayBuffer` fails a seal and an open, with - `error::backend_failure`, no JavaScript exception entering WebAssembly; and - a seal and an open allocate nothing outside the room's resource, neither - with `operator new` nor with the C library's functions. + its range; the relay socket's handlers run outside the page's events; and + the page's `online` and `offline` events reach an app's relays, which + `automatic` follows. |=== The platform backend's tests run on each target that builds them, and once more without exceptions (<>), as a program that uses the backend may be built, but for `platform_websocket`, which -runs once, with the standard libraries' checks. The tests of a relay's URL, -a page's calls and the sealer in a page, parts that parse no JSON, link +runs once, with the standard libraries' checks. The tests of a relay's URL +and a page's calls, parts that parse no JSON, link `platform-parts` (`$(platform-part)`) in place of the backend and the rooms: [listing] @@ -281,8 +310,8 @@ Emscripten 6.0.11): include::{library-root}/test/Jamfile[tag=asyncify-release] ---- -From the root of a webcpp checkout, with libsecp256k1 found -(<>), each of these builds and runs the tests, +From the root of a webcpp checkout, with the dependencies prepared +(<>), each of these builds and runs the tests, natively, under AddressSanitizer and UndefinedBehaviorSanitizer, and on emscripten: @@ -304,8 +333,18 @@ built from scratch, with `b2 -a`. === The oracle and the interop lanes Two lanes of trystero's own, declared in `test/oracle/Jamfile`, check it -against Trystero itself, pinned at 0.26.0 by `test/oracle/package.json` and -`package-lock.json`, with Node, run as `node --conditions=development`: +against Trystero itself, pinned at 0.27.0 by `test/oracle/package.json` and +`package-lock.json`, with Node, run as `node --conditions=development`. The +vectors come from `test/oracle/record_0_27.mjs`, which +`node test/oracle/record_0_27.mjs ` runs against a checkout of +0.27.0 at `8d3f57e` and which writes +`test/fixtures/expected/trystero-0.27.0.json`, the file the `crypto_layer` +and `identity_cache` tests read. WebCrypto's ECDSA is random, so the +recorder takes its previous output and keeps each signature recorded there +that 0.27.0 still verifies, signing only what is missing: a run over the +fixture writes it again byte for byte. The fixture's `recorded_with` names +the Node that recorded it, `node v26.13.0`, the one member that is not +0.27.0's: [listing] ---- @@ -314,10 +353,17 @@ include::{library-root}/test/oracle/Jamfile[tag=oracle] `oracle`, which names no target, runs Trystero's own functions over the inputs of `test/fixtures/cases/protocol.json` and checks that they still -write `test/fixtures/expected/expected.json` byte for byte, the values the -`protocol` and `platform_sealer` tests reproduce, and runs the twins of the +write `test/fixtures/oracle/expected.json` byte for byte, the values the +`protocol` and `signaling` tests reproduce, and runs the twins of the examples (<>); `update-expected` is the only writer of the expected values and of each divergent twin's output. +`generated-vectors` runs the recorder over the published packages, +`@trystero-p2p/core` and `@trystero-p2p/nostr` 0.27.0, with the fixture as +its previous output (`test/oracle/vectors.py`, `record_0_27.mjs --dist`), +which must write the fixture again byte for byte, keeping its +`recorded_with` so that any Node, the CI's pinned one included, compares +what the packages compute: what a JS peer installs is the pinned source. +`update-generated` is the fixture's only writer there. [listing] ---- @@ -325,55 +371,65 @@ include::{library-root}/test/oracle/Jamfile[tag=interop] ---- `interop`, natively and on emscripten, meets each {cpp} peer, the native one -as a process and the browser's in headless Chrome, with Trystero JS peers in -Chrome, over an in-memory Nostr relay on 127.0.0.1 that verifies every -event's id and signature as a public relay does. Its scenarios: the {cpp} -peer offering; Trystero JS offering, with a password; a Trystero JS peer that -also sends malformed candidates, or text messages on its data channel; a -first relay to which no WebSocket can be made; a {cpp} peer given a TURN -server without credentials; a watcher without the key that answers every -offer with garbage in the other peer's name, that resends a sealed answer -and offer it recorded, and that sends the {cpp} peer its own sealed offer -back, which the {cpp} peer must refuse; a flood of announcements and of -unsealed offers from fresh peer ids; a relay text longer than 1 MiB; a {cpp} -peer and a Trystero JS page each in two rooms of one app, sharing one -connection and one peer id per app; a wrong password; -and a mesh of three. The native peer meets three more: a room -moved over the joined one, which must leave it as destroying it does; a -relay that ends the connection just as the peer writes, which twelve peers in -turn must survive; and the driver's own check that a peer killed by a signal -is named at once. - -The shared-connection scenarios run in both lanes: - -. Two rooms exchange chat and 100 KB files both ways on one adopted, - connected transport. -. A third room joins later through presence on that transport. -. Rooms the JS page joined first bind when the {cpp} app joins them later. -. A peer can enter another room of a passwordless app by token, while a - protected app with another password and self id shares no connection or - presence with it, in either id order. -. Either side leaves one room while the other keeps exchanging, making - no connection. -. Leaving every room closes the transport after the configured idle time. -. An authenticated peer sending wrong room proofs in both id orders gives - paced lower-id reports while - the other room keeps exchanging over the same connection. -. A 5,000-message flood in one room leaves pings in another completing - within 2 s. -. A held handshake frame recovers in both id orders after one timeout, - without a false password report; the other room keeps exchanging. - -The {cpp} peers accept `room2Delay` and `room3Delay` in milliseconds; the JS -page also accepts `room2Delay`. These delayed joins establish the first room -before a shared-binding scenario begins; -the proof-pacing scenario first authenticates the shared password domain, -then corrupts room proofs after the initial announcement burst. - -The adoption scenarios allow a crossed pair of connections to resolve, but -fail with connection counts if either side constructs more than four. Transient -recovery accounts for JS reuse during the higher id's dropping window -(<>). +as a process and the browser's in headless Chrome, with Trystero 0.27.0 +pages in Chrome, over an in-memory Nostr relay on 127.0.0.1 that verifies +every event's id and signature as a public relay does. The {cpp} peers +(`test/oracle/interop/peer_room.hpp`) and the page (`js.html`) take the same +parameters and report the same events. Its scenarios, each in both lanes: + +. Each side sees the other's peer and user ids, and text, JSON and binary + messages, a request and a ping go both ways, with the {cpp} peer's id put + below the page's and then above it, so that each side offers in turn (the + lower id offers, as in 0.27.0), which the relay shows. +. The page joins the {cpp} peer only once it verified its endpoint and user + signatures, and the {cpp} peer the page likewise. +. 1 MiB each way, in 0.27.0's wide frames of 64 KiB both ways, which the + page sees on its data channel. +. One password meets; another is reported as `decrypt_failed` by the higher + id of the two, which cannot open the lower id's offer, once however often + it is offered, the {cpp} peer's id put below the page's and then above it, + and no peer joins. +. Each side imports an identity the other exported, and presents its user. +. Two {cpp} apps of one imported identity are two peers and one user to a + page. +. A room with `max_users` 2 refuses a third user, the page's and the {cpp} + peer's, `room-full` and `room_full`. +. Requests and pings complete both ways. +. A leave is the other side's peer and user leave, both ways. +. A page whose identity's `sign` passes 0.27.0's startup check and then + signs with another key is reported as `handshake_failed`, once per + handshake run, and never joined. +. Two pages and a {cpp} peer form a mesh. +. A peer whose relays go offline has its subscriptions closed at the relay, + misses a new peer whose announcement the relay forwarded, and subscribes + again and meets it once online; a peer that starts offline subscribes to + nothing and sends nothing until it goes online, and then meets the others; + each side in turn. + +Then, on the local relay, peers that mean harm: a peer of the room that sends +the {cpp} peer candidates that are not candidates, sealed under the room's key +for its offer (the relay holds the page's answer until they are in), which the +{cpp} peer drops, saying so, before it completes the exchange; and a flood of +offers sealed by no key and of announcements, each from fresh ids, sent with +0.27.0's own code, which the {cpp} peer handles each, reports at most once per +peer and stage, answers with at most its bounds of negotiations (32) and +connections (64), counted as the platform counts them, and survives with the +page it joined. + +Then the {cpp} peer's own robustness on the relays: a first relay to which +no WebSocket can be made; a TURN server without credentials; a relay text +longer than 1 MiB, once and after every subscription; and, natively, a relay +that ends the connection just as the peer writes, which twelve peers in turn +must survive, and the driver's own check that a peer killed by a signal is +named at once. Each wait of a scenario is for something that must happen, +bounded only to end a hang; what must not happen is checked once what must +has, and again at the scenario's end. + +The handshake of a Trystero 0.27.0 page has its own fixed bound, 10 s: on a +machine so loaded that a handshake takes longer, the page reports +`handshake-timeout`, and `js_verifies_cpp_signatures`, which fails on any +error, fails. That is a known risk, not a reason to tolerate the error: the +fix is at its cause, the work the handshake waits on. Every peer gathers its ICE candidates on the machine alone: the {cpp} peers get `stun:127.0.0.1:9` in place of Trystero's public STUN servers, the @@ -410,20 +466,20 @@ include::{library-root}/example/Jamfile[tag=differences] ---- Each of these programs has its twin in `test/oracle/twins/`, the same -program on Trystero 0.26.0, which the oracle lane runs through +program on Trystero 0.27.0, which the oracle lane runs through `test/oracle/run_twin.mjs`: a relay of its own, its URL in `TRYSTERO_RELAY_URL`, and the twin, whose output must be the program's `.expected`, or, for a difference, its own `.expected`, which must differ. The twins agree with {n-twins-agreeing} of the programs and diverge from -{n-twins-divergent}; {n-examples-without-twin} have none, each with its -reason in `test/oracle/twins/without-twin.txt`: the chat, a page that prints -nothing, and a difference whose original has no counterpart. +{n-twins-divergent}; {n-examples-without-twin} has none, with its reason in +`test/oracle/twins/without-twin.txt`: the chat, a page that prints nothing. -Trystero JS has one self id per page, so a twin whose room meets a peer, as +Trystero JS has one endpoint identity per app id and page, so a twin whose +room meets a peer, as a {cpp} program's second app does, runs that peer as a second page, a worker thread with Trystero's modules of its own (`test/oracle/page.mjs`). Node has no WebRTC: Trystero JS takes werift's `RTCPeerConnection` as `rtcPolyfill`, -the WebRTC for Node that Trystero 0.26.0's own README names, pinned at 0.24.4 +the WebRTC for Node that Trystero's own README names, pinned at 0.24.4 in `test/oracle/package.json` for the twins alone. The {cpp} programs whose apps meet bind their connections to 127.0.0.1 with `stun:127.0.0.1:9`, and the twins have no ICE server, so every peer stays on the machine. diff --git a/doc/trystero.adoc b/doc/trystero.adoc index 60358b2..8d3527f 100644 --- a/doc/trystero.adoc +++ b/doc/trystero.adoc @@ -13,11 +13,21 @@ :attribute-missing: warn trystero is a header-only port of https://github.com/dmotz/trystero[Trystero] -0.26.0's serverless WebRTC rooms for {cpp}20, one of the libraries of +0.27.0's serverless WebRTC rooms for {cpp}20, one of the libraries of https://github.com/webcpporg/webcpp[webcpp]. Peers find each other over public Nostr relays and exchange messages directly, over WebRTC data -channels. The wire is Trystero's: a room joined from {cpp} and the same room -joined from Trystero's JavaScript are one room. +channels. The wire is Trystero's: a room joined from {cpp} and the same +room joined from Trystero's JavaScript are one room. + +trystero speaks Trystero 0.27.0 (upstream commit `8d3f57e`): its topics, +room keys, sealing, ids, relays and action wire, each value proven against +vectors recorded from 0.27.0's own code (<>); its +identities and its handshake, signed with ECDSA P-256; and its room API: +listeners that return a subscription, users, `max_users`, room errors and +the relays' connectivity. Its rooms meet Trystero 0.27.0's, which the +interop lane proves in headless Chrome (<>). +Programs of trystero's earlier versions, the port of Trystero 0.26.0, move +as <> says. This page teaches trystero section by section: what a room is, how a program joins one in the browser and natively, how its actions carry messages, where @@ -55,7 +65,7 @@ include::testing.adoc[] Every name trystero declares, in the namespace `webcpp::trystero` and those nested in it, from the Doc Comments of its headers: each class, function, type and enumerator with its declaration, what it does, what it asks of its -caller and how it fails, and the part of Trystero 0.26.0 it ports. The other +caller and how it fails, and the part of Trystero 0.27.0 it ports. The other sections teach the library; this one is where a name is looked up. include::{reference}[leveloffset=+1] diff --git a/doc/usage.adoc b/doc/usage.adoc index bbfdfaf..6ac0f05 100644 --- a/doc/usage.adoc +++ b/doc/usage.adoc @@ -8,30 +8,39 @@ == Rooms and actions A room is what Trystero's `joinRoom` returns, and an action what its -`makeAction` returns: this section is the {cpp} form of both. +`makeAction` returns: this section is the {cpp} form of both, as 0.27.0 +has them. [#trystero-usage-joining] === Joining -An `app` is this program in one application and password domain: one peer id, -one immutable password, and one connection -to each remote peer, which every room of the app it shares with that peer -uses, as a Trystero JS page shares them. Constructing it takes the executor -every handler and completion runs on, the backend, which must outlive it, -and its configuration, `app_config`, moved. A room is joined with `join`, -which returns a `boost::system::result` to test, or an error: -`error::already_joined` while a room of that id is joined in the app, and -`error::too_many_rooms` when 64 rooms count, since a peer drops a connection -that advertises more. Joining an id in its 99 ms farewell finishes that -farewell first and joins afresh. +An `app` is this program in one application and password domain: one +endpoint identity, a P-256 key it makes when it is made, whose public key +derives its peer id; one user identity, the one its configuration gives or +an ephemeral one it makes; one immutable password; its relays and its ICE +servers. Each room of the app negotiates its own connection to each remote +peer, as each room of 0.27.0 does: the app shares its identity, its relays' +configuration and its rooms' keys with its rooms, and no connection. +Constructing it takes the executor every listener and completion runs on, +the backend, which must outlive it, and its configuration, `app_config`, +moved. A room is joined with `join`, which returns a +`boost::system::result` to test, or an error: +`error::invalid_max_users` for a `room_options::max_users` of 0 or above +2^53^ - 1, as 0.27.0's `joinRoom` throws, and `error::already_joined` while +a room of that id is joined in the app, as 0.27.0 refuses a second join. +Joining an id in its 99 ms farewell finishes that farewell first and joins +afresh. A room of an app with a password announces itself once the app has +derived its keys, off the room's thread; `join` returns before +(<>). `join` and the app's other methods run where its executor runs. An app and all its rooms use that executor; a multithreaded `io_context` needs a strand. Destroying or moving over the app handle releases it; its rooms keep the app's state alive and continue. Two `app` objects, even with the same app -id, are two peers. Rooms with different passwords use separate apps with -distinct self ids. A room has no password override; changing the domain -password requires a new app. No registry or identity is kept in static storage. +id, are two peers, of one user when they are given one `user_identity`. +Rooms with different passwords use separate apps with distinct peer ids. A +room has no password override; changing the domain password requires a new +app. No registry or identity is kept in static storage. [cols="1,3",options="header"] |=== @@ -40,23 +49,20 @@ password requires a new app. No registry or identity is kept in static storage. | `app_id` | The application's id, Trystero's `appId`: rooms of different apps never meet. -| `self_id` -| One id for every room of the app; empty, 20 random characters drawn once. - An id longer than 64 bytes is replaced and reported. This id links the - app's rooms: rooms that must not be linked to one program use an `app` - each (<>). - | `password` | The immutable password shared by every room of this app, copied into the - app's resource. It contributes to each room's sealed signaling key and - challenge handshake. Empty, the app is passwordless. Different passwords - require separate apps and distinct self ids; they share no connections, - presence or tokens (<>). + app's resource. Each room derives its keys from it + (<>), which seal its signals: a peer of another + password opens none of them, and never connects, as in 0.27.0, which has + no password challenge. Empty, the app is passwordless, its signals still + sealed with the app and room ids. Different passwords require separate + apps and distinct peer ids. | `relay_urls` -| The Nostr relays. Empty, `relay_redundancy` of Trystero's 29 defaults, - shuffled with the app id so every peer picks the same ones. Their - configuration is the app's; sockets and the Nostr signing key remain per room. +| The Nostr relays. Empty, `relay_redundancy` of 0.27.0's 30 defaults, in + the order its seeded shuffle gives them for the app id, so every peer + picks the same ones. Their configuration is the app's; sockets and the + Nostr signing key remain per room. | `relay_redundancy` | The number of default relays to use, 5. @@ -66,10 +72,10 @@ password requires a new app. No registry or identity is kept in static storage. URL, or a TURN server without a user name and credential, is dropped and reported to `app::on_error` with `error::invalid_configuration`. -| `idle_timeout` -| How long a connection with no rooms stays after a departure, 123,333 ms; - 0 closes it immediately. A negative value becomes 0 and is reported. A - connection whose last binding was kicked closes at once. +| `identity` +| The user the app's rooms present, a `user_identity` the program made or + imported (0.27.0's `'custom'`); absent, the app makes an ephemeral one + (0.27.0's `'none'`), lost with the app (<>). | `log` | One sink for the app and its rooms, called with a category (`app`, `nostr`, @@ -81,108 +87,198 @@ password requires a new app. No registry or identity is kept in static storage. must be non-null (<>). |=== -`app_config` is move-only because its log sink is a `handler`: pass it -moved, or build it in place. Each room adds `room_options`: +It has no `self_id`: 0.27.0 has no custom peer id, and an app derives its +id, 20 base62 characters, from its endpoint key, which `app::self_id()` and +`room::self()` give. `app_config` is move-only because its log sink is a +`handler`: pass it moved, or build it in place. Each room adds +`room_options`: [cols="1,3",options="header"] |=== | `room_options` member | What it is -| `handshake_timeout` -| How long a binding has to finish the handshake, 10 s. - | `max_receive_bytes` | The most bytes the room reserves for incoming transfers across peers, 256 MiB. | `max_json_document_bytes` | The largest image a received JSON payload's document may take of the room's resource, webcpp::document's default, 64 MiB; a payload past it is not delivered (<>). +| `max_users` +| The most users the room holds, its own included, Trystero's `maxUsers`; empty, no bound. A peer of a user already in the room is admitted when it is full; a peer of a new user is refused once its handshake passed, and its room reports `room_full` (<>). + | `memory` | The room's own resource; null uses the app's resource. |=== +It has no `handshake_timeout`: 0.27.0 removed `handshakeTimeoutMs`, and a +peer has 10 s to finish the handshake. + [#trystero-usage-migration] -==== Moving from `room_config` +==== Moving from trystero 0.1.0 -`room(executor, backend, room_config, room_id)` and `room_config` are gone: -a room is joined through an `app`. +trystero 0.1.0 ported Trystero 0.26.0. Its programs move as Trystero's own +programs move from 0.26.0 to 0.27.0, and its rooms meet only Trystero +0.27.0's now, as 0.27.0's meet no 0.26.0 room: [cols="2,3",options="header"] |=== -| Previous use | New use - -| Standalone room construction -| Construct `app` with the executor, backend and `app_config`, then call - `join` with the room id and `room_options`; test the returned result. - -| `room_config::{app_id, self_id, password, relay_urls, relay_redundancy, ice_servers}` -| `app_config` - -| `room_config::log` -| `app_config::log`: one sink for the app and its rooms, with sentences in the app's resource - -| `room_config::{handshake_timeout, max_receive_bytes}` -| `room_options` - -| `room_config::memory` -| `app_config::memory`, with `room_options::memory` for a room's own resource - -| Configuration reports from `room::on_error`, with an empty peer id -| `app::on_error`; `room::on_error` reports problems with peers - -| Two rooms with separate peer ids to meet Trystero JS in both -| Two calls to `join` on one `app` +| In 0.1.0 | Now + +| `app_config::self_id` +| Gone: the app derives its id from the endpoint key it makes; + `app::self_id()` and `room::self()` give it. + +| `room_options::handshake_timeout` +| Gone: a peer has 10 s. + +| `app_config::idle_timeout`, `app::max_rooms` and `error::too_many_rooms` +| Gone with the connection an app's rooms shared: each room has its own + connections, closed as it leaves, and an app joins any number of rooms. + +| `error::wrong_password` and `error::handshake_timed_out` +| Gone with 0.26.0's password handshake: a peer of another password is + reported as `decrypt_failed`, and a handshake that fails, its 10 s + included, as `handshake_failed` with 0.27.0's reason. The values of + `error` that followed them moved: a program compares codes with the + enumerators, never with numbers it kept. + +| `on_peer_join(f)`, `on_peer_leave(f)`, `on_error(f)` and an action's + `on_message(f)`, each setting the one handler and replacing the one before +| Each adds a listener beside those added before and returns its + `subscription`, whose `unsubscribe()` removes it; `listen_options` has + `once` and, for joins, `replay` (<>). + +| A join listener called with a peer's id +| Called with a `peer_event`: the peer's id and its user's. + +| `on_error(f)` called with a peer, a code and a text +| Called with a `room_error`: 0.27.0's code, its message, the app's and the + room's ids, and the context of its code (<>). + +| `peers()`, the joined peers' ids +| A map of each active peer's id to its `peer_info`, its user's id among + it; `users()` lists the users, and `self()` this peer. + +| A send to a target that has not joined, `error::no_such_peer` +| `error::not_connected`; a target may be a user's id, which stands for its + active peers. + +| Frames of an action that arrived before it was made, kept 64 per peer for + 120 s +| Dropped, and their transfers rejected, as 0.27.0 keeps none: a room makes + the actions it receives right after it is joined. + +| No user: a peer was its id +| A peer's user is the one its handshake verified; an app presents + `app_config::identity`, or an ephemeral user, and a program keeps one + across runs with `export_user_identity` and `import_user_identity`. + +| A room of any number of peers +| `room_options::max_users` bounds its users, and `join` refuses a bound of + 0 with `error::invalid_max_users`. + +| `backend::websocket::send` returns nothing +| It returns whether the socket queued the text, for a backend of a + program's own (<>). +|=== -| Two peers in one process -| Two `app` objects +`room(executor, backend, room_config, room_id)` and `room_config`, of +trystero's earlier versions, are gone too: a room is joined through an +`app`, the members of `room_config` are those of `app_config` and +`room_options`, and two peers in one process are two `app` objects. -| Rooms with different passwords, or rooms that must not be linked to one program -| Separate apps with distinct self ids; set each password in its `app_config` +[#trystero-usage-peers] +=== Peers and users + +A peer is one endpoint in the room, a user who it is: in 0.27.0 several +peers, the tabs of one person, may be one user. An app's peer id derives +from the P-256 endpoint key it makes when it is made, and its user id from +its user identity, `app_config::identity` or an ephemeral one the app makes +(`app::self_id`, `app::user_id`). A `user_identity` is made with +`create_user_identity`, kept as the text `export_user_identity` writes and +read again with `import_user_identity`, 0.27.0's `trystero_uk_` text or the +JSON of a private P-256 key; several apps given one are one user's +endpoints. A remote peer joins once 0.27.0's identity handshake has +verified its endpoint key and its user key, both bound to the DTLS +fingerprints of the connection, and its user id is the one it proved. + +`on_peer_join` adds a listener of each peer whose handshake completed, with +its `peer_event`, and `on_peer_leave` one of each joined peer that leaves; +`on_user_join` adds a listener of each user whose first peer joined, after +that peer's `on_peer_join`, and `on_user_leave` one of each user whose last +peer left, after that peer's `on_peer_leave`. `peers()` maps each active +peer's id to its `peer_info`: its user's id, whether it is reached +directly, always until relayed peers are ported, its distance, 1, and its +roles, none until roles are ported. `users()` maps each user's id to its +active peers, in the order they became active, and its roles; this peer's +own user is left out. `self()` is this peer at once, synchronously, since +an app's identity exists from its construction on: its peer and user ids, +the identity's persistence, `ephemeral` for one the app made, `imported` for +`app_config::identity`'s, the room's id, the id it was +joined as, and its roles. The maps are a `std::pmr::map` over the room's +resource with a transparent comparator, so a program looks a peer up by a +`std::string_view`. -| Changing a room's password by leaving and joining again -| Construct a new app with the new domain password and a distinct self id -|=== +`on_error` adds a listener of each problem the room handled itself, as +Trystero's `onError`: each is a `room_error` (<>). +Every view a listener receives is valid for the call. -[#trystero-usage-peers] -=== Peers - -`on_peer_join` and `on_peer_leave` set what is called with each peer whose -handshake completed, and with each joined peer that leaves; `peers()` lists -the joined peers. `on_error` sets what is called with each problem with one -peer that the room handled itself, as Trystero's `onPeerError`: a peer with -signals under another password, a malformed room proof, a handshake that -timed out, a connection the backend -refused. It is called with an empty peer id for a count of signals -that did not open with the room key (<>). Each -handler replaces the one set before, and every view it receives is valid for -the call. - -`async_ping` measures the round trip to a joined peer, from sending -`@_ping` to receiving its `@_pong`. +`async_ping` measures the round trip to an active peer, from sending the +request `@_ping` to receiving its answer, or completes with +`error::no_such_peer`. It has no timeout, as Trystero's, and completes with +`error::room_left` or `error::peer_disconnected` when the room or the peer goes. `async_leave` says goodbye to every peer, Trystero's `@_leave`, gives the -farewell 99 ms, as Trystero waits, then detaches its bindings and closes its relay +farewell 99 ms, as Trystero waits, then closes its connections and its relay sockets, and every pending operation completes with `error::room_left`. Destroying a room leaves at once, without the 99 ms, and so does assigning another room over a joined one: every peer is told, and every pending operation completes with `error::room_left`, even while an `action` of it lives. -A kick or a peer's `@_leave` ends only that room's binding: the app's other -rooms keep using the connection. When it stays live, rebinding waits one -step after the end, initially the larger of `handshake_timeout` and 10 s, -plus 1 s, doubling after each further end to at most 5 minutes. A completed -handshake or the connection's end resets the count. After its own kick the -lower id refuses bindings until that time and keeps frames; the higher id -drops frames until it sends presence, but accepts the lower id's presence. -A binding also requires the peer to have advertised the token itself, by -its presence or by a frame of the room on its connection. -A peer on a protected app's shared connection already authenticated with -that app's password through the initial sealed negotiation. A peer that -knows it can still send a wrong room proof: only the lower id reports that -proof as `wrong_password`; the higher id answers and sees a departure. -Malformed challenge data is rejected by its receiver too. This room -handshake retains Trystero JS 0.26.0's one-way wire behavior. +A room admits a peer as 0.27.0's handshake manager does. Once the data +channel opens, the side whose id is lower in UTF-16 order initiates: it +sends its nonce, the DTLS fingerprints of its description, its user id and +its endpoint and user keys; the other answers with its own and its two +signatures of the transcript, which binds the app, the room, both ids, both +nonces, both sides' fingerprints and both users; the initiator verifies +them, signs the transcript too, and the responder verifies those +(<>). Each side then sends its ready frame, +and the peer joins once both did. Until then the peer is pending: absent +from `peers()` and `users()`, and its frames other than the handshake's and +`@_leave` are not delivered. A handshake that does not complete in 10 s, a +step that does not verify, fingerprints that are not the connection's, or +more than 16 messages the handshake has not read, end the peer: its room +reports `handshake_failed` with 0.27.0's reason, once a handshake, and the +peer is told to leave. + +In a room with `room_options::max_users`, a peer whose handshake passed is +admitted when its user is in the room already, or the users, those of +admissions under way included, are fewer than the bound; else it is refused +with a ready frame saying "room full", and its room reports `room_full` +with the refusing peer's id. The room counts users, not peers: another tab +of a user present is welcome in a full room. It does not dial a peer it +refused again while it stays full. + +[#trystero-usage-listeners] +=== Listeners and subscriptions + +Every `on_*` of a room, of an action and of an app adds a listener and +returns a `subscription`, as each of Trystero's returns the function that +removes it: `unsubscribe()` removes the listener, and destroying the token +leaves it, as dropping Trystero's function does. Listeners of one event run +in the order added, each event reported from the room's executor; one added +while an event is reported waits for the next, and one removed before its +turn does not run. `listen_options::once` removes a listener before its +first run, and `replay`, which only the joins of peers and users take, calls +it first, within the call that adds it, with each peer or user already +joined. Trystero's `signal`, an `AbortSignal`, has no {cpp} counterpart: +`unsubscribe` replaces it. A subscription requires the resource of what +keeps its listener to outlive it. + +An action's `on_receive` and a request action's `on_request` take one +listener at a time, and return a `boost::system::result`: +`error::already_subscribed` while one is in place, as Trystero throws. [#trystero-usage-actions] === Actions @@ -198,12 +294,12 @@ messages travel and how they are received: | `std::string` | text | a copy of the bytes | `std::pmr::string` | text | a copy of the bytes, in the room's resource -| `std::string_view` | text | a view of the frame it arrived in, valid during the handler +| `std::string_view` | text | a view of the frame it arrived in, valid during the listener | `webcpp::document::document` | JSON | parsed into a document of its own, with the standard allocator | `webcpp::document::pmr::document` | JSON | parsed into a document of the room's resource, which holds its image and the parse's working state | `trystero::bytes` | binary | a copy of the bytes -| `trystero::pmr_bytes` | binary | the transfer's buffer, moved when resources match, otherwise copied once into the room's resource -| `std::span` | binary | a view of the frame, valid during the handler +| `trystero::pmr_bytes` | binary | the payload's buffer in the room's resource, moved +| `std::span` | binary | a view of the frame, valid during the listener | `trystero::payload` | any | a `std::variant` of `std::string`, `webcpp::document::document` and `bytes`, by format |=== @@ -264,30 +360,80 @@ Several actions of different types may share a name: one receives as views, another sends by moving strings, as the chat does (<>). -Messages arrive at the handler `on_message` sets, with a `message_info`: the -sender's id and the metadata it passed. Without a handler they queue, up to -1024 per action, the oldest dropped first, for `async_receive`, which needs -an owning type: a view would outlive the message; a message of another -format, or a JSON text that does not parse, completes it with -`error::transfer_rejected` and an empty value, which allocates nothing: an -empty container, in the room's resource for a `std::pmr` type, and for a JSON -one webcpp::document's `nothing()`, a document with no image whose root reads -`undefined`. Frames of an action that -arrived before it was made are kept, 64 per peer for 120 s, and delivered -to it once it is. - -`async_send` sends to `send_options::targets`, or to every joined peer, with -optional JSON metadata. A payload that fits one 16 KiB frame with its header -and metadata travels inline; a larger one is offered, accepted by the -receiver within 120 s, and sent in chunks of at most 16,370 bytes. A frame -or a chunk is handed to the data channel only while the channel buffers at -most 64 KiB, waiting at most 10 s for it to drain. `async_send` completes -once each target's local data channel has taken the inline frame, or the -last chunk of the transfer the receiver accepted, with the first failure if -any, as Trystero's `send` resolves: nothing confirms that the receiver has -the message. A receiver takes one transfer per peer at a time, accepts it only for -an action with a receiver, and reserves at most `max_receive_bytes` across -peers. +Messages arrive at the listeners `on_message` adds, each with a +`message_info`: the sender's id and the metadata it passed. Each listener +decodes the message, so with several each takes its own copy. Until the +action listens, its messages wait, as 0.27.0's wait for a listener, 32 per +sender for 10 s, the oldest dropped first. An action listens once it has a +listener, and from its first `async_receive` on, which needs an owning type, +since a view would outlive the message: once awaited, the messages no +receive waits for queue for the next, up to 1024 per action, the oldest +dropped first. A message of another format, or a JSON text that does not +parse, completes it with `error::transfer_rejected` and an empty value, +which allocates nothing: an empty container, in the room's resource for a +`std::pmr` type, and for a JSON one webcpp::document's `nothing()`, a +document with no image whose root reads `undefined`. Frames of an action +the room has not made are dropped, and its transfers rejected, as 0.27.0 +does: a room makes the actions it receives right after it is joined. + +`on_receive` sets the action's receive gate, Trystero's `onReceive`, asked +about each message as it arrives, with its sender, its size and its +metadata, before the action receives it: a refused inline message is +dropped, and a refused transfer rejected with "payload rejected by +receiver", which completes its sender's send with +`error::transfer_rejected`. It runs during the frame's processing and +answers at once; Trystero's may also answer with a promise. Without a gate, +a room accepts every transfer within `max_receive_bytes`, as Trystero does. +`on_receive_progress` adds a listener of the share of each transfer received +after each chunk but the last, then 1 once the message is whole. + +`async_send` sends to `send_options::targets`, each an active peer's id or +a user's, which stands for each of its active peers (a peer reached twice +is sent to once), or to every active peer, with optional JSON metadata; to +a room without peers it succeeds, and to a target that is neither an active +peer nor a user of one it completes with `error::not_connected`. A payload +that fits one 16 KiB frame with its header and metadata travels inline; a +larger one is offered, accepted by the receiver within 120 s, and sent in +chunks of at most 16,370 bytes (<>). A frame or a +chunk is handed to the data channel only while the channel buffers at most +64 KiB, waiting at most 10 s for it to drain. `async_send` completes once +each target's local data channel has taken the inline frame, or the last +chunk of the transfer the receiver accepted, with the first failure if any, +as Trystero's `send` resolves: nothing confirms that the receiver has the +message. A receiver reserves at most `max_receive_bytes` across peers. + +[#trystero-usage-requests] +==== Request actions + +`make_request_action` makes a request action, Trystero's `makeAction` +with `kind: 'request'`: `async_request` asks one peer, or the active peer of +a user with the lowest id, as 0.27.0 picks one, with +`request_options::metadata` and an optional `timeout`, and completes with +`(error_code, R)`, the answer. The peer asked answers with the listener +`on_request` sets, which returns an `R`, or a `boost::system::result` +whose error refuses the request: the requester's request then completes +with `error::request_rejected`, without the reason, which the room logs; +`error::request_timed_out` after the timeout, `error::not_connected` for a +target not connected, `error::peer_disconnected` when the peer leaves first. +An answer that answers no request is dropped, as 0.27.0 drops it: its offer +is rejected "unexpected response", and nothing is reported; the peer stays. +The listener answers at once; Trystero's may answer with a promise. A name +is a message action or a request action, not both: a handle of the other +kind completes its operations with `error::action_redefined`, where +Trystero throws. `requestMany`, and the `onProgress` and `signal` of sends +and requests, are not ported (<>). + +[#trystero-usage-connectivity] +=== Relay connectivity + +`app::set_relay_connectivity` sets how the relays of every room of the app +connect, Trystero's `setRelayConnectivity`, for this app alone, since a +process may hold several: `offline` closes every relay socket of the app's +rooms and holds them closed, those of a room joined meanwhile too; `online` +reconnects at once every relay not connected, which then subscribes and +announces again; `automatic`, the default, follows the page's `online` and +`offline` events, and natively, where there are none, is online. A +connection already made goes on while the relays are offline. [#trystero-usage-tokens] === Completion tokens and ownership @@ -310,25 +456,47 @@ when it is a JSON document; `send_options` owns its strings; and === Errors Operations complete with a `boost::system::error_code` in the category -`webcpp.trystero`, of the enumeration `error`: +`webcpp.trystero`, of the enumeration `error`, whose messages are 0.27.0's +where it has one. `room::on_error` reports a problem the room handled itself +as a `room_error`: its code, its message, the app's and the room's ids, and, +for the codes that have them, the peer's id, the stage of a +`decrypt_failed` (offer or answer), whether a TURN server was configured +for a `peer_connect_failed`, the reason of a `banned` and the plugin of a +`plugin_failed`. `room_error_code_name` gives 0.27.0's name of a room +error's code, `decrypt-failed` and the others. `app::on_error` reports what +the app set aside of its configuration, as `error::invalid_configuration` +with no room nor peer. [cols="1,3",options="header"] |=== | Value | Meaning | `room_left` | the room was left while the operation was pending -| `no_such_peer` | the target is not a joined peer +| `no_such_peer` | the peer pinged is not an active peer | `peer_disconnected` | the peer went away before the operation finished | `invalid_action_name` | an action's name is not 1 to 32 UTF-8 bytes without NUL | `metadata_too_large` | the metadata does not fit one frame | `transfer_rejected` | the receiver refused the transfer, or a message had another format than the awaited type | `transfer_timed_out` | the receiver neither accepted nor refused within 120 s | `channel_stalled` | the data channel stopped draining for 10 s -| `wrong_password` | a peer's signals or handshake used another password, or a handshake message had the wrong shape -| `handshake_timed_out` | a connected peer did not finish the handshake in time -| `handshake_failed` | reserved: nothing reports it today -| `backend_failure` | the browser or the native stack refused an operation +| `handshake_failed` | 0.27.0's `handshake-failed`, reported by the room whose handshake with a connected peer failed, once a handshake, with 0.27.0's reason: a step that does not verify, fingerprints that are not the connection's, more than 16 unread messages, or 10 s passed ("handshake timed out after 10000ms"); the peer is told to leave +| `backend_failure` | the browser or the native stack refused an operation, or a room's keys could not be derived | `invalid_configuration` | the app dropped an unusable configuration value and continues without it | `already_joined` | a room of that id is already joined in the app -| `too_many_rooms` | the app already holds 64 rooms, including farewells +| `room_full` | 0.27.0's `room-full`, reported by the room a peer's full room refused, with that peer's id, once its handshake verified the peer; the peer goes, and is not announced to again +| `plugin_failed` | 0.27.0's `plugin-failed`, which nothing reports: plugins are not ported +| `banned` | 0.27.0's `banned`, reported by the room a pending peer refused with its ready frame, with that peer's id and its reason, when it gave one, in the message; a peer has no roles to ban with, so only a Trystero JS peer sends one +| `peer_error` | a peer's frame was malformed or against the protocol; its message says which, as 0.27.0's, and the peer is told to leave and goes +| `identity_failed` | the app's endpoint key or its ephemeral user identity could not be made (a system without a generator): each room it joins reports it once the join has returned, then ends without reaching a relay +| `relay_failed` | the first connection of every relay closed before any opened, or no relay took its first announcement and the others failed to open; reported once, with the failure's text when there is one +| `decrypt_failed` | an offer or an answer did not open with the room key: another password, a corrupted or forged signal, or a plaintext that is not UTF-8; reported at most once a minute per peer and stage +| `peer_connect_failed` | the connection with a peer did not open after the exchange of descriptions; its message hints at TURN when none is configured +| `already_subscribed` | a listener that takes one at a time is already set +| `not_connected` | a target of a send or a request is neither an active peer nor a user of one +| `action_aborted` | 0.27.0's "operation aborted"; nothing aborts an action before its `signal` is ported +| `request_rejected` | the peer asked refused the request +| `request_timed_out` | the request was not answered within its timeout +| `action_redefined` | the action's name was made the other kind of action first +| `invalid_user_identity` | `import_user_identity` was given a text that is no user key, a point that is not on the curve, or a scalar that is not its point's +| `invalid_max_users` | `app::join` was given a `room_options::max_users` of 0 or above 2^53^ - 1 |=== diff --git a/example/Jamfile b/example/Jamfile index 74cf7cc..e05be25 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -31,16 +31,11 @@ webcpp.drive quick_start : quick_start.cpp # The programs of the appendix "Differences" (doc: #trystero-differences). # tag::differences[] local differences = - diff_already_joined diff_json_numbers diff_json_refused diff_passwords - diff_peer_join diff_peers - diff_relay_config diff_relay_sockets - diff_rooms_per_app - diff_self_id diff_send_to_absent_peer ; for local difference in $(differences) @@ -49,7 +44,4 @@ for local difference in $(differences) : /webcpp/trystero//platform multi : run_over_relay.mjs : : native ; } webcpp.lane relayed : quick_start $(differences) : native ; -# One needs no relay, its app joining no room, and has no twin. -webcpp.example diff_self_id_not_utf8.cpp - : /webcpp/trystero//platform multi : native ; # end::differences[] diff --git a/example/chat/chat.cpp b/example/chat/chat.cpp index b2416fd..0b0d752 100644 --- a/example/chat/chat.cpp +++ b/example/chat/chat.cpp @@ -85,8 +85,8 @@ void join_room(chat& c, const val& form) { c.room->make_action("chat")); c.outgoing = std::make_unique>(c.room->make_action("chat")); - c.room->on_peer_join([](std::string_view peer) { ui("peerJoined", peer); }); - c.room->on_peer_leave([](std::string_view peer) { ui("peerLeft", peer); }); + c.room->on_peer_join([](const trystero::peer_event& e) { ui("peerJoined", e.peer_id); }); + c.room->on_peer_leave([](const trystero::peer_event& e) { ui("peerLeft", e.peer_id); }); // A view of the received frame: the text goes from the frame straight into a JavaScript string. c.messages->on_message([](std::string_view text, const trystero::message_info& info) { ui("message", std::string_view(info.from), text, false); diff --git a/example/diff_already_joined.cpp b/example/diff_already_joined.cpp deleted file mode 100644 index dfeb52b..0000000 --- a/example/diff_already_joined.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -// A difference from Trystero (doc: #trystero-differences-behaviour): joining a room the app has -// joined already. Trystero's joinRoom returns the room it joined before; app::join refuses with -// error::already_joined, since a room is a handle whose destruction leaves. Its twin is -// test/oracle/twins/diff_already_joined.mjs. Both join over the relay whose URL is in the -// environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. - -#include -#include -#include - -#include - -#include -#include -#include - -namespace trystero = webcpp::trystero; - -int main() { - const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); - if (relay == nullptr) { - std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; - return 1; - } - boost::asio::io_context io; - trystero::platform::backend backend(io.get_executor()); - // tag::example[] - trystero::app app(io.get_executor(), backend, - {.app_id = "webcpp-trystero-differences", .relay_urls = {relay}}); - auto first = app.join("lobby"); - const auto second = app.join("lobby"); - std::cout << "the first join: " << (first ? std::string("a room") : first.error().message()) - << '\n' - << "the second join: " - << (second ? std::string("another room") : second.error().message()) << '\n'; - // end::example[] - if (first) { - first->async_leave([](boost::system::error_code) {}); - } - io.run(); // lint-run: the room's farewell, over the relay -} diff --git a/example/diff_already_joined.expected b/example/diff_already_joined.expected deleted file mode 100644 index fb46897..0000000 --- a/example/diff_already_joined.expected +++ /dev/null @@ -1,2 +0,0 @@ -the first join: a room -the second join: the app has already joined a room of that id diff --git a/example/diff_json_numbers.cpp b/example/diff_json_numbers.cpp index 06762ac..d57b8e0 100644 --- a/example/diff_json_numbers.cpp +++ b/example/diff_json_numbers.cpp @@ -51,8 +51,6 @@ int main() { c.app_id = "webcpp-trystero-differences"; c.relay_urls = {relay}; c.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}}; - // The connection closes once no room uses it, so that the program ends when both leave. - c.idle_timeout = std::chrono::milliseconds{0}; return c; }; trystero::app other_app(io.get_executor(), backend, config()); @@ -84,7 +82,7 @@ int main() { text += ']'; // This room sends the payload its JSON text makes, once it meets the other peer. auto payload = room.make_action("payload"); - room.on_peer_join([&](std::string_view) { + room.on_peer_join([&](const trystero::peer_event&) { wd::result value = wd::parse(text); if (!value) { std::cerr << "not parsed: " << value.error().message() << '\n'; diff --git a/example/diff_json_refused.cpp b/example/diff_json_refused.cpp index 9634d2f..9968310 100644 --- a/example/diff_json_refused.cpp +++ b/example/diff_json_refused.cpp @@ -24,7 +24,6 @@ #include #include #include -#include #include #include @@ -33,7 +32,6 @@ #include #include -#include #include #include #include @@ -41,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -73,18 +72,14 @@ class json_marking_channel final : public trystero::backend::data_channel { [[nodiscard]] bool is_open() const override { return channel_->is_open(); } void send(std::span frame) override { - const auto envelope = protocol::decode_envelope(frame); - if (envelope && envelope->type == protocol::envelope::kind::room) { - const auto decoded = protocol::decode_action(envelope->payload); - const auto* const p = - decoded.frame ? std::get_if(&*decoded.frame) : nullptr; - if (p != nullptr && p->kind == protocol::frame_kind::inline_payload && - p->format == protocol::payload_format::text && p->name == action_name) { - const auto action = protocol::encode_inline(p->name, protocol::payload_format::json, - p->metadata, p->payload, memory_); - channel_->send(protocol::room_frame(envelope->token, action, memory_)); - return; - } + const auto decoded = protocol::decode_action(frame); + const auto* const p = + decoded.frame ? std::get_if(&*decoded.frame) : nullptr; + if (p != nullptr && p->kind == protocol::frame_kind::inline_payload && + p->format == protocol::payload_format::text && p->name == action_name) { + channel_->send(protocol::encode_inline(p->name, protocol::payload_format::json, + p->metadata, p->payload, memory_)); + return; } channel_->send(frame); } @@ -152,6 +147,10 @@ class json_marking_connection final : public trystero::backend::peer_connection return connection_->has_remote_description(); } + [[nodiscard]] std::optional max_message_size() const override { + return connection_->max_message_size(); + } + void close() override { connection_->close(); } private: @@ -190,9 +189,11 @@ class json_marking_backend final : public trystero::backend::factory { return backend_.make_timer(memory); } - std::shared_ptr make_sealer( - std::array key, std::pmr::memory_resource* memory) override { - return backend_.make_sealer(key, memory); + void derive_password_master(std::span password, + std::span salt, + std::span out, + trystero::handler done) override { + backend_.derive_password_master(password, salt, out, std::move(done)); } void random(std::span out) override { backend_.random(out); } @@ -222,8 +223,6 @@ int main() { c.app_id = "webcpp-trystero-differences"; c.relay_urls = {relay}; c.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}}; - // The connection closes once no room uses it, so that the program ends when both leave. - c.idle_timeout = std::chrono::milliseconds{0}; return c; }; // The other peer, as a Trystero JS page would be: its app's backend marks the text payloads of @@ -278,7 +277,7 @@ int main() { // The other peer sends each payload's text once it meets this room. An inline frame leaves at // once, so they leave in the order of the sends, as a Trystero JS page awaits each. auto sending = other->make_action(action_name); - other->on_peer_join([&](std::string_view) { + other->on_peer_join([&](const trystero::peer_event&) { for (const auto& [label, value] : payloads) { sending.async_send("[\"" + std::string(label) + "\"," + value + "]", [](boost::system::error_code) {}); diff --git a/example/diff_passwords.cpp b/example/diff_passwords.cpp index 7c2fa3d..5b6f421 100644 --- a/example/diff_passwords.cpp +++ b/example/diff_passwords.cpp @@ -6,10 +6,11 @@ // A difference from Trystero (doc: #trystero-differences-behaviour): passwords across rooms. // Trystero JS takes a password with each room, so that one page holds rooms of different -// passwords, over one connection to a peer it meets in several. A password here is an app's, the -// same for every room of the app and never changed, since the sealed negotiation that makes a -// connection authenticates that password before any room of the app reuses the connection: rooms -// of different passwords are rooms of separate apps, each with its own self id. This program joins +// passwords, each room with its own connection to a peer it meets in several, which the sealed +// negotiation of that room authenticates: 0.27.0 has no password challenge on the connection. A +// password here is an app's, the same for every room of the app and never changed, the app's room +// keys derived from it: rooms of different passwords are rooms of separate apps, each with its own +// self id. This program joins // a lobby with one password and a kitchen with another, as another peer of the same program does, // and compares the peers its two rooms meet. Its twin is test/oracle/twins/diff_passwords.mjs. // Both meet over the relay whose URL is in the environment, TRYSTERO_RELAY_URL, which their lanes @@ -48,8 +49,6 @@ int main() { c.password = password; c.relay_urls = {relay}; c.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}}; - // The connection closes once no room uses it, so that the program ends when all leave. - c.idle_timeout = std::chrono::milliseconds{0}; return c; }; // The other peer, as another page would be, with the same passwords for the same rooms. @@ -81,11 +80,11 @@ int main() { std::array met; std::size_t meetings = 0; for (std::size_t i = 0; i < rooms.size(); ++i) { - rooms[i]->on_peer_join([&, i](std::string_view peer) { + rooms[i]->on_peer_join([&, i](const trystero::peer_event& joined) { if (!met[i].empty()) { return; } - met[i] = peer; + met[i] = joined.peer_id; if (++meetings < met.size()) { return; } diff --git a/example/diff_peer_join.cpp b/example/diff_peer_join.cpp deleted file mode 100644 index 57d5183..0000000 --- a/example/diff_peer_join.cpp +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -// A difference from Trystero (doc: #trystero-differences-behaviour): a join handler set once a -// peer has joined. Trystero calls a newly set onPeerJoin with each peer already joined; a room -// reports a join from its executor once, to the handler set then, and peers() lists the peers -// joined. Two apps of one program meet in a room, as two pages would. Its twin is -// test/oracle/twins/diff_peer_join.mjs. Both meet over the relay whose URL is in the environment, -// TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. - -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include - -namespace asio = boost::asio; -namespace trystero = webcpp::trystero; - -int main() { - const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); - if (relay == nullptr) { - std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; - return 1; - } - asio::io_context io; - // The peers meet on this machine alone: every connection bound to the loopback, and a STUN - // server where nothing answers in place of Trystero's public ones. - trystero::platform::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); - const auto config = [relay] { - trystero::app_config c; - c.app_id = "webcpp-trystero-differences"; - c.relay_urls = {relay}; - c.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}}; - // The connection closes once no room uses it, so that the program ends when both leave. - c.idle_timeout = std::chrono::milliseconds{0}; - return c; - }; - trystero::app other_app(io.get_executor(), backend, config()); - auto other = other_app.join("lobby"); - trystero::app app(io.get_executor(), backend, config()); - auto joined = app.join("lobby"); - if (!other || !joined) { - std::cerr << "not joined\n"; - return 1; - } - trystero::room room = std::move(*joined); - const auto leave = [&] { - room.async_leave([](boost::system::error_code) {}); - other->async_leave([](boost::system::error_code) {}); - }; - // tag::example[] - int late_calls = 0; - room.on_peer_join([&](std::string_view) { - std::cout << "the handler set before the join: called\n"; - // Once the join is reported, another handler replaces this one. - asio::post(io, [&] { - room.on_peer_join([&late_calls](std::string_view) { ++late_calls; }); - asio::post(io, [&] { - std::cout << "the handler set after the join: " - << (late_calls == 0 ? "not called" : "called") << '\n' - << "peers: " << room.peers().size() << '\n'; - leave(); - }); - }); - }); - // end::example[] - io.run(); // lint-run: the program's network I/O; libdatachannel's threads post to it -} diff --git a/example/diff_peer_join.expected b/example/diff_peer_join.expected deleted file mode 100644 index e3c5a91..0000000 --- a/example/diff_peer_join.expected +++ /dev/null @@ -1,3 +0,0 @@ -the handler set before the join: called -the handler set after the join: not called -peers: 1 diff --git a/example/diff_peers.cpp b/example/diff_peers.cpp index 71d9a77..a73e299 100644 --- a/example/diff_peers.cpp +++ b/example/diff_peers.cpp @@ -5,8 +5,9 @@ // https://www.boost.org/LICENSE_1_0.txt) // A difference from Trystero (doc: #trystero-differences): what a room lists of its peers. -// Trystero's getPeers maps each joined peer's id to its RTCPeerConnection; room::peers lists the -// ids, since a connection is the backend's and the room does not hand it out. Two apps of one +// Trystero's getPeers maps each joined peer's id to its user id, its RTCPeerConnection and the rest +// of its PeerInfo; room::peers maps it to its user id and the rest without the connection, since a +// connection is the backend's and the room does not hand it out. Two apps of one // program meet in a room, as two pages would. Its twin is test/oracle/twins/diff_peers.mjs. Both // meet over the relay whose URL is in the environment, TRYSTERO_RELAY_URL, which their lanes start // on 127.0.0.1. @@ -41,8 +42,6 @@ int main() { c.app_id = "webcpp-trystero-differences"; c.relay_urls = {relay}; c.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}}; - // The connection closes once no room uses it, so that the program ends when both leave. - c.idle_timeout = std::chrono::milliseconds{0}; return c; }; trystero::app other_app(io.get_executor(), backend, config()); @@ -59,11 +58,14 @@ int main() { other->async_leave([](boost::system::error_code) {}); }; // tag::example[] - room.on_peer_join([&](std::string_view peer_id) { + room.on_peer_join([&](const trystero::peer_event& joined) { const auto peers = room.peers(); + const auto entry = peers.find(joined.peer_id); std::cout << "peers: " << peers.size() << '\n' << "the joined peer's entry: " - << (peers.size() == 1 && peers.front() == peer_id ? "its id" : "not its id") + << (entry != peers.end() && entry->second.user_id == joined.user_id + ? "its user id, without a connection" + : "not its own") << '\n'; leave(); }); diff --git a/example/diff_peers.expected b/example/diff_peers.expected index 804338c..e80061f 100644 --- a/example/diff_peers.expected +++ b/example/diff_peers.expected @@ -1,2 +1,2 @@ peers: 1 -the joined peer's entry: its id +the joined peer's entry: its user id, without a connection diff --git a/example/diff_relay_config.cpp b/example/diff_relay_config.cpp deleted file mode 100644 index ecae417..0000000 --- a/example/diff_relay_config.cpp +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -// A difference from Trystero (doc: #trystero-differences-behaviour): where a room's relays and ICE -// servers come from. Trystero JS opens the relays of the first room a page joins, and every room -// joined while one remains uses them, whatever relays it was given; and it makes a connection with -// the RTC configuration of the room that negotiates it, which the page's other rooms then share. A -// room here uses its app's relays and ICE servers, so a room joined with another configuration is -// a room of another app. Two peers of one program meet in a lobby with a first configuration, and -// in a kitchen with a second. Trystero JS hands out the page's relay sockets and a room's -// connection; a room here hands out neither, so each app of this program is given a backend that -// records what the app asks of the platform one. Its twin is -// test/oracle/twins/diff_relay_config.mjs. Both meet over the relay whose URL is in the -// environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. - -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace asio = boost::asio; -namespace trystero = webcpp::trystero; - -namespace { - -// The relays and the ICE servers an app is configured with. -struct configuration { - std::string relay; // the one relay's URL - std::string stun; // the one STUN server's URL -}; - -// A backend that forwards to another, and records the relays and ICE servers asked of it. -class observing_backend final : public trystero::backend::factory { -public: - explicit observing_backend(trystero::backend::factory& backend) : backend_(backend) {} - - // The URLs of the relays it was asked to connect to. - [[nodiscard]] const std::set& relays() const { return relays_; } - - // The URLs of the ICE servers of the peer connections it was asked to make. - [[nodiscard]] const std::set& ice_servers() const { return ice_servers_; } - - std::shared_ptr connect( - std::string_view url, trystero::backend::websocket::handlers h, - std::pmr::memory_resource* memory) override { - relays_.emplace(url); - return backend_.connect(url, std::move(h), memory); - } - - std::shared_ptr make_peer_connection( - std::span servers, - std::pmr::memory_resource* memory) override { - for (const auto& server : servers) { - ice_servers_.insert(server.urls.begin(), server.urls.end()); - } - return backend_.make_peer_connection(servers, memory); - } - - std::shared_ptr make_timer( - std::pmr::memory_resource* memory) override { - return backend_.make_timer(memory); - } - - std::shared_ptr make_sealer( - std::array key, std::pmr::memory_resource* memory) override { - return backend_.make_sealer(key, memory); - } - - void random(std::span out) override { backend_.random(out); } - - std::chrono::sys_seconds unix_now() override { return backend_.unix_now(); } - - std::chrono::steady_clock::time_point steady_now() override { return backend_.steady_now(); } - -private: - trystero::backend::factory& backend_; - std::set relays_; - std::set ice_servers_; -}; - -} // namespace - -int main() { - const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); - if (relay == nullptr) { - std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; - return 1; - } - asio::io_context io; - // The peers meet on this machine alone: every connection bound to the loopback, and STUN - // servers where nothing answers in place of Trystero's public ones. - trystero::platform::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); - // Two configurations. The second relay is the same local relay under a path, which it accepts - // as it accepts any. - const configuration first{.relay = relay, .stun = "stun:127.0.0.1:9"}; - const configuration second{ - .relay = std::string(relay) + "/second", - .stun = "stun:127.0.0.1:19", - }; - const auto config = [](const configuration& c) { - trystero::app_config out; - out.app_id = "webcpp-trystero-differences"; - out.relay_urls = {std::pmr::string(c.relay)}; - out.ice_servers = {{.urls = {std::pmr::string(c.stun)}, .username = {}, .credential = {}}}; - // The connection closes once no room uses it, so that the program ends when all leave. - out.idle_timeout = std::chrono::milliseconds{0}; - return out; - }; - // The other peer, as another page would be: the lobby with the first configuration, the - // kitchen with the second. - trystero::app other_first(io.get_executor(), backend, config(first)); - trystero::app other_second(io.get_executor(), backend, config(second)); - auto other_lobby = other_first.join("lobby"); - auto other_kitchen = other_second.join("kitchen"); - // Each app of this program is given a backend that records what the app asks of the platform - // one. - observing_backend first_backend(backend); - observing_backend second_backend(backend); - // The configuration whose URL, and only it, a backend was asked for, of the two URLs given. - const auto which = [](const std::set& urls, const std::string& first_url, - const std::string& second_url) { - if (urls == std::set{first_url}) { - return "the first configuration's"; - } - return urls == std::set{second_url} ? "the second configuration's" : "another"; - }; - const auto relays_of = [&](const observing_backend& b) { - return which(b.relays(), first.relay, second.relay); - }; - const auto ice_servers_of = [&](const observing_backend& b) { - return which(b.ice_servers(), first.stun, second.stun); - }; - // tag::example[] - // A configuration is an app's: the kitchen, joined with the second, is a room of a second app. - trystero::app lobby_app(io.get_executor(), first_backend, config(first)); - trystero::app kitchen_app(io.get_executor(), second_backend, config(second)); - auto lobby = lobby_app.join("lobby"); - auto kitchen = kitchen_app.join("kitchen"); - // What each app's backend was asked for, once both rooms have met the other peer. - const auto report = [&] { - std::cout << "the lobby's relays: " << relays_of(first_backend) << '\n' - << "the kitchen's relays: " << relays_of(second_backend) << '\n' - << "the lobby's connection: " << ice_servers_of(first_backend) << " ICE servers\n" - << "the kitchen's connection: " << ice_servers_of(second_backend) - << " ICE servers\n"; - }; - // end::example[] - if (!other_lobby || !other_kitchen || !lobby || !kitchen) { - std::cerr << "not joined\n"; - return 1; - } - // Once each of this program's rooms has met the other peer, it reports, and every room leaves. - bool reported = false; - const auto met = [&](std::string_view) { - if (reported || lobby->peers().empty() || kitchen->peers().empty()) { - return; - } - reported = true; - report(); - for (trystero::room* room : {&*lobby, &*kitchen, &*other_lobby, &*other_kitchen}) { - room->async_leave([](boost::system::error_code) {}); - } - }; - lobby->on_peer_join(met); - kitchen->on_peer_join(met); - io.run(); // lint-run: the program's network I/O; libdatachannel's threads post to it -} diff --git a/example/diff_relay_config.expected b/example/diff_relay_config.expected deleted file mode 100644 index f70889b..0000000 --- a/example/diff_relay_config.expected +++ /dev/null @@ -1,4 +0,0 @@ -the lobby's relays: the first configuration's -the kitchen's relays: the second configuration's -the lobby's connection: the first configuration's ICE servers -the kitchen's connection: the second configuration's ICE servers diff --git a/example/diff_relay_sockets.cpp b/example/diff_relay_sockets.cpp index eac1f0c..8eb82e6 100644 --- a/example/diff_relay_sockets.cpp +++ b/example/diff_relay_sockets.cpp @@ -14,13 +14,14 @@ #include #include +#include #include #include #include #include +#include -#include #include #include #include @@ -63,9 +64,11 @@ class counting_backend final : public trystero::backend::factory { return backend_.make_timer(memory); } - std::shared_ptr make_sealer( - std::array key, std::pmr::memory_resource* memory) override { - return backend_.make_sealer(key, memory); + void derive_password_master(std::span password, + std::span salt, + std::span out, + trystero::handler done) override { + backend_.derive_password_master(password, salt, out, std::move(done)); } void random(std::span out) override { backend_.random(out); } diff --git a/example/diff_rooms_per_app.cpp b/example/diff_rooms_per_app.cpp deleted file mode 100644 index 7100524..0000000 --- a/example/diff_rooms_per_app.cpp +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -// A difference from Trystero (doc: #trystero-differences-behaviour): how many rooms an app holds. -// Trystero joins every room a page asks for, and a peer that advertises a 65th over one -// connection is dropped by the other side; app::join refuses the 65th with -// error::too_many_rooms, counting a room in its farewell, since the 65th would cost every -// connection of the app. Its twin is test/oracle/twins/diff_rooms_per_app.mjs. Both join over the -// relay whose URL is in the environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. - -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace trystero = webcpp::trystero; - -int main() { - const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); - if (relay == nullptr) { - std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; - return 1; - } - boost::asio::io_context io; - trystero::platform::backend backend(io.get_executor()); - trystero::app app(io.get_executor(), backend, - {.app_id = "webcpp-trystero-differences", .relay_urls = {relay}}); - std::vector rooms; - // What a join gives, a room kept until the end or the error that refused it. - const auto join = [&](const std::string& room_id) { - auto joined = app.join(room_id); - if (!joined) { - return joined.error().message(); - } - rooms.push_back(std::move(*joined)); - return std::string("a room"); - }; - const auto leave_all = [&] { - for (auto& room : rooms) { - room.async_leave([](boost::system::error_code) {}); - } - }; - // tag::example[] - for (std::size_t n = 1; n <= 64; ++n) { - join("room-" + std::to_string(n)); - } - std::cout << "joins 1 to 64: " << rooms.size() << " rooms\n"; - std::cout << "join 65: " << join("room-65") << '\n'; - rooms.front().async_leave([&](boost::system::error_code) { - std::cout << "join 67, once room 1 has left: " << join("room-67") << '\n'; - leave_all(); - }); - std::cout << "join 66, while room 1 is leaving: " << join("room-66") << '\n'; - // end::example[] - io.run(); // lint-run: the rooms' announcements and farewells, over the relay -} diff --git a/example/diff_rooms_per_app.expected b/example/diff_rooms_per_app.expected deleted file mode 100644 index 6072db6..0000000 --- a/example/diff_rooms_per_app.expected +++ /dev/null @@ -1,4 +0,0 @@ -joins 1 to 64: 64 rooms -join 65: the app holds as many rooms as a peer accepts, 64 -join 66, while room 1 is leaving: the app holds as many rooms as a peer accepts, 64 -join 67, once room 1 has left: a room diff --git a/example/diff_self_id.cpp b/example/diff_self_id.cpp deleted file mode 100644 index e7895d1..0000000 --- a/example/diff_self_id.cpp +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -// A difference from Trystero (doc: #trystero-differences-behaviour): the scope of the self id. -// Trystero JS draws one selfId for the page, which it announces in every room of every app; an -// app here draws its own, and keeps its connections, so that one program holds several peers, and -// one id across apps is the program's choice, app_config::self_id. This program joins two rooms of -// one app and a room of a second app, and another peer, two apps of the same program, compares the -// ids it meets there. Its twin is test/oracle/twins/diff_self_id.mjs. Both meet over the relay -// whose URL is in the environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. - -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace asio = boost::asio; -namespace trystero = webcpp::trystero; - -int main() { - const char* const relay = std::getenv("TRYSTERO_RELAY_URL"); - if (relay == nullptr) { - std::cerr << "TRYSTERO_RELAY_URL names no relay\n"; - return 1; - } - asio::io_context io; - // The peers meet on this machine alone: every connection bound to the loopback, and a STUN - // server where nothing answers in place of Trystero's public ones. - trystero::platform::backend backend(io.get_executor(), {.bind_address = "127.0.0.1"}); - const auto config = [relay](std::string_view app_id) { - trystero::app_config c; - c.app_id = app_id; - c.relay_urls = {relay}; - c.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}}; - // The connection closes once no room uses it, so that the program ends when all leave. - c.idle_timeout = std::chrono::milliseconds{0}; - return c; - }; - constexpr std::string_view first_app = "webcpp-trystero-differences"; - constexpr std::string_view second_app = "webcpp-trystero-differences-second"; - // The other peer, as another page would be: an app of each id, in the rooms this program joins. - trystero::app other_first(io.get_executor(), backend, config(first_app)); - trystero::app other_second(io.get_executor(), backend, config(second_app)); - auto other_lobby = other_first.join("lobby"); - auto other_kitchen = other_first.join("kitchen"); - auto other_second_lobby = other_second.join("lobby"); - // tag::example[] - // Each app draws a self id of its own, unless app_config::self_id names one for both. - trystero::app first(io.get_executor(), backend, config(first_app)); - trystero::app second(io.get_executor(), backend, config(second_app)); - auto lobby = first.join("lobby"); - auto kitchen = first.join("kitchen"); - auto second_lobby = second.join("lobby"); - // What the other peer meets in those three rooms. - const auto report = [](std::string_view in_lobby, std::string_view in_kitchen, - std::string_view in_second_lobby) { - std::cout << "two rooms of one app: " << (in_lobby == in_kitchen ? "one id" : "two ids") - << '\n' - << "rooms of two apps: " << (in_lobby == in_second_lobby ? "one id" : "two ids") - << '\n'; - }; - // end::example[] - if (!other_lobby || !other_kitchen || !other_second_lobby || !lobby || !kitchen || - !second_lobby) { - std::cerr << "not joined\n"; - return 1; - } - // The id each of the other peer's rooms meets first; once all three have met one, the program - // reports, and every room leaves. - const std::array observers{&*other_lobby, &*other_kitchen, &*other_second_lobby}; - std::array met; - std::size_t meetings = 0; - for (std::size_t i = 0; i < observers.size(); ++i) { - observers[i]->on_peer_join([&, i](std::string_view peer) { - if (!met[i].empty()) { - return; - } - met[i] = peer; - if (++meetings < met.size()) { - return; - } - report(met[0], met[1], met[2]); - for (trystero::room* room : {&*lobby, &*kitchen, &*second_lobby}) { - room->async_leave([](boost::system::error_code) {}); - } - for (trystero::room* room : observers) { - room->async_leave([](boost::system::error_code) {}); - } - }); - } - io.run(); // lint-run: the program's network I/O; libdatachannel's threads post to it -} diff --git a/example/diff_self_id.expected b/example/diff_self_id.expected deleted file mode 100644 index d15734e..0000000 --- a/example/diff_self_id.expected +++ /dev/null @@ -1,2 +0,0 @@ -two rooms of one app: one id -rooms of two apps: two ids diff --git a/example/diff_self_id_not_utf8.cpp b/example/diff_self_id_not_utf8.cpp deleted file mode 100644 index 4cd322d..0000000 --- a/example/diff_self_id_not_utf8.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -// A difference from Trystero (doc: #trystero-differences-behaviour): a self id that is not UTF-8. -// An app given one sets it aside for 20 random characters and reports error::invalid_configuration, -// since a signal writes the id as a JSON string, which carries UTF-8 alone. Trystero JS draws its -// selfId when its module loads and takes none from a program, so it has no such id, and this -// program no twin (test/oracle/twins/without-twin.txt). The app joins no room, so it needs no -// relay. - -#include -#include - -#include - -#include -#include -#include -#include - -namespace trystero = webcpp::trystero; - -int main() { - boost::asio::io_context io; - trystero::platform::backend backend(io.get_executor()); - // tag::example[] - const std::string given = "caf\xE9"; // ISO 8859-1's "café": its last byte is no UTF-8 - trystero::app_config config; - config.app_id = "webcpp-trystero-differences"; - config.self_id = given; - trystero::app app(io.get_executor(), backend, std::move(config)); - app.on_error([](std::string_view, boost::system::error_code ec, std::string_view what) { - std::cout << "reported: " << ec.message() << ": " << what << '\n'; - }); - std::cout << "the self id given: " << given.size() << " bytes, not UTF-8\n" - << "the app's self id: " - << (app.self_id() == given - ? std::string("the one given") - : std::to_string(app.self_id().size()) + " random characters") - << '\n'; - // end::example[] - io.run(); // lint-run: delivers the report the app's constructor posted -} diff --git a/example/diff_self_id_not_utf8.expected b/example/diff_self_id_not_utf8.expected deleted file mode 100644 index f1ac4d0..0000000 --- a/example/diff_self_id_not_utf8.expected +++ /dev/null @@ -1,3 +0,0 @@ -the self id given: 4 bytes, not UTF-8 -the app's self id: 20 random characters -reported: the configuration is unusable: self_id is not UTF-8, which no peer reads, so the app uses a random one diff --git a/example/diff_send_to_absent_peer.cpp b/example/diff_send_to_absent_peer.cpp index 11f67b8..15135c0 100644 --- a/example/diff_send_to_absent_peer.cpp +++ b/example/diff_send_to_absent_peer.cpp @@ -5,8 +5,8 @@ // https://www.boost.org/LICENSE_1_0.txt) // A difference from Trystero (doc: #trystero-differences): a send to a peer that has not joined. -// Trystero's send warns on the console and resolves; async_send completes with -// error::no_such_peer, since an operation that fails says so with its error code. Its twin is +// Trystero 0.27.0's send rejects with an Error whose message names the peer; async_send completes +// with error::not_connected, since an operation that fails says so with its error code. Its twin is // test/oracle/twins/diff_send_to_absent_peer.mjs. Both join over the relay whose URL is in the // environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1. diff --git a/example/quick_start.cpp b/example/quick_start.cpp index 6b6d2d1..a3a54c0 100644 --- a/example/quick_start.cpp +++ b/example/quick_start.cpp @@ -7,10 +7,10 @@ // The quick start of the documentation (doc: #trystero-quick-start), which includes the tagged // regions below: two apps of one program, the peers alice and bob, join the room "lobby" of the // app webcpp-trystero-quick-start; alice greets bob when he joins, bob answers from a coroutine, -// each prints what it received, and both leave, which ends the program. Its twin is -// test/oracle/twins/quick_start.mjs. Both meet over the relay whose URL is in the environment, -// TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1; without it, the program meets over -// Trystero's public relays, as a user's program does. +// each prints what it received after the other's name, and both leave, which ends the program. Its +// twin is test/oracle/twins/quick_start.mjs. Both meet over the relay whose URL is in the +// environment, TRYSTERO_RELAY_URL, which their lanes start on 127.0.0.1; without it, the program +// meets over Trystero's public relays, as a user's program does. // tag::program[] // tag::includes[] @@ -28,7 +28,6 @@ #include #include #include -#include namespace asio = boost::asio; namespace trystero = webcpp::trystero; @@ -37,13 +36,11 @@ namespace trystero = webcpp::trystero; namespace { // tag::config[] -/** What one peer's app is made with: its id, and the relay `relay` names, or the public ones. */ -trystero::app_config config_for(std::string_view self_id, const char* relay) { +/** What one peer's app is made with: the relay `relay` names, or the public ones. Each app makes + * its own endpoint key, whose public key derives its id. */ +trystero::app_config config_for(const char* relay) { trystero::app_config config; config.app_id = "webcpp-trystero-quick-start"; - // An id of the program's own, where an app would draw 20 random characters, so that what each - // peer prints of the other is the same on every run. - config.self_id = self_id; if (relay != nullptr) { // The peers stay on this machine: the relay given, and a STUN server where nothing answers // in place of Trystero's public ones, beside a backend bound to the loopback. @@ -52,22 +49,22 @@ trystero::app_config config_for(std::string_view self_id, const char* relay) { } // Without a relay, both lists stay empty: Trystero's defaults, as a user's program has them, // the public relays its app id selects and Trystero's public STUN servers. - // A connection closes as soon as no room uses it, so that the program ends once both leave. - config.idle_timeout = std::chrono::milliseconds{0}; return config; } // end::config[] // tag::answer[] -/** bob's part: waits for a message, prints it, answers its sender, and leaves the room. */ +/** bob's part: waits for a message, prints it after alice's name, answers its sender, and leaves + * the room. */ asio::awaitable answer(trystero::room& lobby, trystero::action& chat) { // as_tuple hands the error over as a value: a room left first ends the wait without throwing. auto [ec, text, info] = co_await chat.async_receive(asio::as_tuple(asio::use_awaitable)); if (ec) { co_return; } - std::cout << info.from << ": " << text << '\n'; + // The sender's id derives from a key made on each run: its name prints the same every time. + std::cout << "alice: " << text << '\n'; auto [failed] = co_await chat.async_send("hello back", {.targets = {info.from}, .metadata = {}}, asio::as_tuple(asio::use_awaitable)); if (failed) { @@ -92,9 +89,9 @@ int main() { } trystero::platform::backend backend(io.get_executor(), local); - // Two apps, two peers, each with its own id, in the same room. - trystero::app alice(io.get_executor(), backend, config_for("alice", relay)); - trystero::app bob(io.get_executor(), backend, config_for("bob", relay)); + // Two apps, two peers, each with an id of its own, in the same room. + trystero::app alice(io.get_executor(), backend, config_for(relay)); + trystero::app bob(io.get_executor(), backend, config_for(relay)); auto alice_lobby = alice.join("lobby"); auto bob_lobby = bob.join("lobby"); if (!alice_lobby || !bob_lobby) { @@ -105,16 +102,17 @@ int main() { auto bob_chat = bob_lobby->make_action("chat"); // alice greets each peer once its handshake completes, prints the answer, and leaves. - alice_lobby->on_peer_join([&](std::string_view peer) { - alice_chat.async_send("hello", {.targets = {trystero::peer_id(peer)}, .metadata = {}}, + alice_lobby->on_peer_join([&](const trystero::peer_event& joined) { + alice_chat.async_send("hello", + {.targets = {trystero::peer_id(joined.peer_id)}, .metadata = {}}, [](boost::system::error_code ec) { if (ec) { std::cerr << "not delivered: " << ec.message() << '\n'; } }); }); - alice_chat.on_message([&](const std::string& text, const trystero::message_info& info) { - std::cout << info.from << ": " << text << '\n'; + alice_chat.on_message([&](const std::string& text, const trystero::message_info& /*info*/) { + std::cout << "bob: " << text << '\n'; alice_lobby->async_leave([](boost::system::error_code) {}); }); asio::co_spawn(io, answer(*bob_lobby, bob_chat), asio::detached); diff --git a/include/webcpp/trystero.hpp b/include/webcpp/trystero.hpp index 862258b..77c456f 100644 --- a/include/webcpp/trystero.hpp +++ b/include/webcpp/trystero.hpp @@ -21,7 +21,10 @@ #include #include #include +#include #include #include +#include +#include #endif diff --git a/include/webcpp/trystero/app.hpp b/include/webcpp/trystero/app.hpp index e4c9747..ad440ae 100644 --- a/include/webcpp/trystero/app.hpp +++ b/include/webcpp/trystero/app.hpp @@ -14,6 +14,8 @@ #include #include #include +#include +#include #include // lint-world: names the executor only @@ -21,7 +23,7 @@ #include #include -#include +#include #include #include #include @@ -32,9 +34,55 @@ namespace webcpp::trystero { +class app; + +namespace detail { + +/** Reaches the state an `app` handle shares with its rooms, for what the handle does not offer. */ +struct app_access { + /** The state of `a`, which must hold one. */ + [[nodiscard]] static app_impl& impl(const app& a); + + /** + * An app as `app`'s constructor makes it, but whose endpoint key is made of `endpoint_scalar` + * in place of one drawn: the library's own tests fix their peers' keys, so that their ids are + * known. A scalar that is no valid key, zero for instance, makes the endpoint fail, as a + * system without a generator does. + * + * @param ex The executor every app and room event runs on. + * @param factory The backend that makes the platform objects. + * @param config The app's configuration. + * @param endpoint_scalar The endpoint key's scalar. + * @return The app. + */ + [[nodiscard]] static app make(webcpp::asio::any_io_executor ex, backend::factory& factory, + app_config config, + std::span endpoint_scalar); + + /** + * An app as the other `make` makes it, whose ephemeral user key is also made of `user_scalar` + * in place of one drawn, when `config` gives no identity. A scalar that is no valid key, zero + * for instance, makes the user identity fail, as a system without a generator does. + * + * @param ex The executor every app and room event runs on. + * @param factory The backend that makes the platform objects. + * @param config The app's configuration. + * @param endpoint_scalar The endpoint key's scalar. + * @param user_scalar The ephemeral user key's scalar. + * @return The app. + */ + [[nodiscard]] static app make(webcpp::asio::any_io_executor ex, backend::factory& factory, + app_config config, + std::span endpoint_scalar, + std::span user_scalar); +}; + +} // namespace detail + /** - * This program in one app: one peer id, and one connection per remote peer, shared by the rooms it - * joins, as a Trystero JS page shares them. + * This program in one app: one endpoint key and the peer id it derives, one user, the relays and + * the configuration its rooms share, as a Trystero JS page's rooms share them; each room has its + * own connection to each peer, as 0.27.0's rooms do. * * Every room uses the app's immutable password; * different passwords require separate apps with distinct peer ids. @@ -50,15 +98,14 @@ class app { /** The executor every handler and completion of the app and its rooms runs on. */ using executor_type = webcpp::asio::any_io_executor; - /** The most rooms an app holds at once: a Trystero JS peer drops a connection that advertises - * more, its limit of 64 room tokens per connection. */ - static constexpr std::size_t max_rooms = 64; - /** - * Makes an app: draws its id unless the configuration names one, and keeps the configuration. + * Makes an app: draws its P-256 endpoint key, whose public key derives its id, makes an + * ephemeral user identity unless the configuration gives one, and keeps the configuration. * - * What no peer could use (an id longer than any peer accepts, a negative idle time, an ICE - * server WebRTC refuses) is set aside, and reported to `on_error`. + * What no peer could use (an ICE server WebRTC refuses) is set aside, and reported to + * `on_error`. A key that cannot be made (a system without a generator) leaves the app without + * an identity: its `self_id` is empty when the endpoint key is the one missing, and each room + * it joins reports `error::identity_failed`, then ends, as 0.27.0's rooms fail their setup. * * @param ex The executor of the app and of its rooms. * @param factory The backend, which must outlive the app and its rooms. @@ -66,9 +113,7 @@ class app { * @pre `config.memory` is not null. */ app(executor_type ex, backend::factory& factory, app_config config) - : impl_(make(std::move(ex), factory, std::move(config))) { - impl_->add_user(); - } + : app(make(std::move(ex), factory, std::move(config))) {} /** * Takes the state of the app moved from, which may then only be destroyed or assigned. @@ -77,8 +122,6 @@ class app { */ app(app&& other) noexcept = default; - // Releasing the last user ends every connection, which logs in the app's resource: a resource - // that fails then ends the program, as in the destructor. /** * Releases the state it held, then takes the state of the app moved from, which may then only * be destroyed or assigned; the rooms of the state released go on. @@ -86,7 +129,7 @@ class app { * @param other The app moved from. * @return This app. */ - app& operator=(app&& other) noexcept { // NOLINT(bugprone-exception-escape) + app& operator=(app&& other) noexcept { if (this != &other) { if (impl_) { impl_->release_user(); @@ -96,16 +139,14 @@ class app { return *this; } - /** Not copyable: an app is one peer id and its connections. */ + /** Not copyable: an app is one endpoint key. */ app(const app&) = delete; - /** Not copy-assignable: an app is one peer id and its connections. */ + /** Not copy-assignable: an app is one endpoint key. */ app& operator=(const app&) = delete; - // Releasing the last user ends every connection, which logs in the app's resource: a resource - // that fails then ends the program, as in any destructor. /** Releases the state; its rooms go on, and their connections with them. */ - ~app() { // NOLINT(bugprone-exception-escape) + ~app() { if (impl_) { impl_->release_user(); } @@ -132,15 +173,28 @@ class app { } /** - * This peer's id in every room of the app, Trystero's `selfId`. + * This peer's id in every room of the app, Trystero's `selfId`: 20 base62 characters derived + * from the endpoint key the app made, as 0.27.0 derives it; 0.27.0 has no custom one. * - * @return The id, valid as long as the app. + * @return The id, valid as long as the app; empty when the endpoint key could not be made. */ [[nodiscard]] std::string_view self_id() const { BOOST_ASSERT(impl_); return impl_->self_id(); } + /** + * The id of the user every room of the app presents, 0.27.0's `selfUserId`: the user identity + * of `app_config::identity`, or of the ephemeral one the app made. + * + * @return The id, 22 base62 characters, valid as long as the app; empty when the ephemeral + * user identity could not be made. + */ + [[nodiscard]] std::string_view user_id() const { + BOOST_ASSERT(impl_); + return impl_->user_id(); + } + /** * The Nostr relays every room of the app uses, derived from the app id unless the * configuration named them. @@ -153,25 +207,56 @@ class app { } /** - * Sets what is called with each part of the configuration the app set aside, with an empty - * peer id and `error::invalid_configuration`. + * Sets how the relays of every room of the app connect, Trystero's `setRelayConnectivity`, + * for this app alone (a process may hold several). * - * The reports are delivered once the caller has - * returned, each once, to the handler set when they are delivered: one replaced before then - * gets none. + * `offline` closes every relay socket of the app's rooms and holds them closed, those of a room + * joined meanwhile too; `online` reconnects at once every relay not connected, as each call + * does, which then subscribes and announces again; `automatic`, the default, follows the + * page's `online` and `offline` events, and natively, where there are none, is online: set + * after `offline`, it reconnects the relays. Unlike 0.27.0, `automatic` does not reconnect the + * relays when the page becomes visible again: the port does not follow `visibilitychange`. * - * @tparam F A callable with the peer's id, the @ref error and a description, the views valid - * for the call. - * @param f The handler, kept in the app's resource; it replaces the one set before. + * Tip: what the relays carry is how peers find each other; a connection already made goes on + * while the relays are offline. + * + * @param mode The connectivity to set. + * @return The connectivity now in place, `mode`. + */ + trystero::relay_connectivity set_relay_connectivity(trystero::relay_connectivity mode) { + BOOST_ASSERT(impl_); + return impl_->set_connectivity(mode); + } + + /** + * How the relays of every room of the app connect, Trystero's `setRelayConnectivity()` + * without an argument. + * + * @return The connectivity last set, `relay_connectivity::automatic` until one is. + */ + [[nodiscard]] trystero::relay_connectivity relay_connectivity() const { + BOOST_ASSERT(impl_); + return impl_->connectivity(); + } + + /** + * Adds a listener of each part of the configuration the app set aside, reported as a + * @ref room_error of `error::invalid_configuration` with the app's id and no room nor peer. + * + * The reports are delivered once the caller has returned, each once, to the listeners in + * place when they are delivered: one added after then gets none. + * + * @tparam F A callable with a `const room_error&`, whose views are valid for the call. + * @param f The listener, kept in the app's resource beside those added before. + * @param options `once` removes it before its first run; `replay` is ignored. + * @return Its subscription, which requires the app's resource to outlive it; destroying it + * leaves the listener. */ template - requires std::is_invocable_v - void on_error(F&& f) { + requires std::is_invocable_v + subscription on_error(F&& f, listen_options options = {}) { BOOST_ASSERT(impl_); - impl_->on_error( - impl_->bind( - std::forward(f))); + return impl_->on_error(impl_->bind(std::forward(f)), options); } /** @@ -179,41 +264,77 @@ class app { * the relays and announces this peer on the room's topic. * * @param room_id The room's id, Trystero's `roomId`, read during the call. - * @param options The handshake timeout, receive bound and resource of the room. - * @return The room, or `error::already_joined` while a room of that id is joined in the app, - * or `error::too_many_rooms` when `max_rooms` rooms count. + * @param options The receive bounds, the bound on users and the resource of the room. + * @return The room; `error::invalid_max_users` when `options.max_users` is 0 or above + * `room_options::max_users_limit`, as 0.27.0's `joinRoom` throws, before it looks for the + * room; or `error::already_joined` while a room of that id is joined in the app, as 0.27.0 + * refuses a second join. */ [[nodiscard]] boost::system::result join(std::string_view room_id, room_options options = {}) { BOOST_ASSERT(impl_); + if (options.max_users && + (*options.max_users == 0 || + static_cast(*options.max_users) > room_options::max_users_limit)) { + return error::invalid_max_users; + } if (const auto existing = impl_->find_room(room_id)) { if (!existing->leaving()) { return error::already_joined; } - // Trystero's rejoin (dist/strategy.mjs:38): the old room's presence(0) goes before - // the new room's presence(1). + // A rejoin during the farewell ends the old room first, as 0.27.0's joinRoom + // finalizes a leaving slot's cleanup (strategy.ts:180-182). existing->finish_farewell(); } - if (impl_->counted_rooms() >= max_rooms) { - return error::too_many_rooms; - } return room(detail::room_impl::make(impl_, options, room_id)); } private: + /** Takes the state `make` made, as its first user. */ + explicit app(std::shared_ptr impl) : impl_(std::move(impl)) { + impl_->add_user(); + } + // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on - static std::shared_ptr make(executor_type ex, backend::factory& factory, - app_config config) { + static std::shared_ptr make( + executor_type ex, backend::factory& factory, app_config config, + std::span endpoint_scalar = {}, + std::span user_scalar = {}) { // NOLINTEND(performance-unnecessary-value-param) std::pmr::memory_resource* const memory = config.memory; BOOST_ASSERT_MSG(memory != nullptr, "app_config::memory names no resource"); return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), - std::move(ex), factory, std::move(config)); + std::move(ex), factory, std::move(config), + endpoint_scalar, user_scalar); } + friend struct detail::app_access; + std::shared_ptr impl_; }; +inline detail::app_impl& detail::app_access::impl(const app& a) { + BOOST_ASSERT(a.impl_); + return *a.impl_; +} + +// NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on +inline app detail::app_access::make(webcpp::asio::any_io_executor ex, backend::factory& factory, + app_config config, + std::span endpoint_scalar) { + // NOLINTEND(performance-unnecessary-value-param) + return app(app::make(std::move(ex), factory, std::move(config), endpoint_scalar)); +} + +// NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on +inline app detail::app_access::make(webcpp::asio::any_io_executor ex, backend::factory& factory, + app_config config, + std::span endpoint_scalar, + std::span user_scalar) { + // NOLINTEND(performance-unnecessary-value-param) + return app(app::make(std::move(ex), factory, std::move(config), endpoint_scalar, user_scalar)); +} + } // namespace webcpp::trystero #endif diff --git a/include/webcpp/trystero/backend.hpp b/include/webcpp/trystero/backend.hpp index 719e7d8..b91fdb6 100644 --- a/include/webcpp/trystero/backend.hpp +++ b/include/webcpp/trystero/backend.hpp @@ -13,11 +13,12 @@ #include -#include #include +#include #include #include #include +#include #include #include #include @@ -34,22 +35,23 @@ * them there first. * * Every handler runs after the call that caused it has returned, never inside it: a completion - * (`done`) of a `peer_connection` or a `sealer`, and a `websocket`'s `close` when no socket can be - * made, are posted even when their result is known at once. The room calls these operations from - * inside handlers whose state a completion run there would change under them. + * (`done`) of a `peer_connection` or of `factory::derive_password_master`, and a `websocket`'s + * `close` when no socket can be made, are posted even when their result is known at once. The + * room calls these operations from inside handlers whose state a completion run there would + * change under them. * * Text crosses this interface as `std::string_view`, valid for the duration of the call or of the * handler: a backend reads what it is given before returning, and a handler copies what it keeps. * The one exception is a data channel message, handed over by value: the receiver keeps the frame, * and taking ownership of it is what spares a copy. * - * Tip: every method that makes an object takes a memory resource last, the app's for a peer - * connection and the room's for the rest, and the backend allocates the object, its handlers and - * what it hands to the room (a frame, a text) through it, on the room's executor only. + * Tip: every method that makes an object takes a memory resource last, the room's for every object + * it makes, and the backend allocates the object, its handlers and what it hands to the room (a + * frame, a text) through it, on the room's executor only. */ namespace webcpp::trystero::backend { -/** A data channel frame in a memory resource: a received one in the app's, as its connection. */ +/** A data channel frame in a memory resource: a received one in the room's, as its connection. */ using bytes = std::pmr::vector; /** The error code every completion of a backend reports, empty on success. */ @@ -118,11 +120,17 @@ class websocket { virtual ~websocket() = default; /** - * Sends a text message; one sent before the connection opens or after it closes is dropped. + * Sends a text message; one sent before the connection opens, while it closes or after it + * closed is dropped, and so is one the connection cannot queue. * * @param text The message, read during the call. + * @return Whether the message was taken to be written; false when it was dropped. This is the + * port's own notion: 0.27.0's `client.send` is a silent no-op on a socket that is not open, so + * there a dropped write is no failure, and only a signing or JSON failure fails an + * announcement. A room counts an announcement whose text the connection could not take, which + * on a socket the room sees open is a queue overflow, as a failed one. */ - virtual void send(std::string_view text) = 0; + virtual bool send(std::string_view text) = 0; /** Closes the connection, which the handler `close` reports. */ virtual void close() = 0; @@ -139,7 +147,7 @@ class data_channel { struct handlers { /** The channel opened. */ handler open; - /** A binary message arrived, handed over in the app's resource. */ + /** A binary message arrived, handed over in the connection's resource, the room's. */ handler message; /** The channel closed; called once. */ handler close; @@ -171,7 +179,10 @@ class data_channel { [[nodiscard]] virtual bool is_open() const = 0; /** - * Sends a binary message; one sent while the channel is not open is dropped. + * Sends a binary message; one sent while the channel is not open is dropped, and one the + * platform refuses while it is open (larger than the connection's `max_message_size`, or past + * what the channel buffers) closes the channel, which the handler `close` reports, so that a + * frame is never lost while the channel goes on. * * @param frame The message, read during the call. */ @@ -277,41 +288,17 @@ class peer_connection { */ [[nodiscard]] virtual bool has_remote_description() const = 0; - /** Closes the connection and its channels. */ - virtual void close() = 0; -}; - -/** - * AES-GCM under one room key, in Trystero's sealed text form (protocol/signal.hpp), what Trystero's - * `encrypt` and `decrypt` do with `crypto.subtle`. - * - * @see "The protocol", in the guide. - */ -class sealer { -public: - /** Destroys the sealer. */ - virtual ~sealer() = default; - /** - * Seals a text under a fresh random IV. + * The largest message the connection's SCTP transport takes, its `sctp.maxMessageSize`, which + * decides whether a transfer's chunks go wide (`detail::channel_link::max_bulk_frame_bytes`). * - * @param plaintext The text, read during the call. - * @param done Called with the sealed text, a view valid for the call, or with - * `error::backend_failure` and an empty view. + * @return The size in bytes once the peer's limit is known (natively once a remote description + * is applied, in a page once the connection has an SCTP transport); nothing before. */ - virtual void seal(std::string_view plaintext, - handler done) = 0; + [[nodiscard]] virtual std::optional max_message_size() const = 0; - /** - * Opens a sealed text. - * - * @param sealed The sealed text, read during the call. - * @param done Called with the plaintext, a view valid for the call, or with an error and an - * empty view: `trystero::error::wrong_password` when the text was sealed under another key or - * is not a sealed text. - */ - virtual void open(std::string_view sealed, - handler done) = 0; + /** Closes the connection and its channels. */ + virtual void close() = 0; }; /** @@ -319,8 +306,8 @@ class sealer { * browser, one per application natively, one per test. * * Each object it makes is allocated, with its handlers and what it hands to the room, in the memory - * resource it is given, the app's for a peer connection and the room's for the rest: that resource - * must outlive the object and every operation the object leaves pending. + * resource it is given, the room's for every object it makes: that resource must outlive the object + * and every operation the object leaves pending. * * @see "Allocation", in the guide. */ @@ -345,8 +332,8 @@ class factory { * Makes a peer connection that gathers its candidates through `servers`. * * @param servers The STUN and TURN servers, read during the call. - * @param memory The app's resource, which the connection, its channels, its handlers and its - * texts are allocated in, as the app owns the connection once a room adopted it. + * @param memory The room's resource, which the connection, its channels, its handlers and its + * texts are allocated in, as the room owns the connection: it ends with the room or the peer. * @return The connection, or null when the platform refuses to make one: the room then * reports the negotiation with that peer as failed, through `room::on_error`. */ @@ -362,15 +349,20 @@ class factory { virtual std::shared_ptr make_timer(std::pmr::memory_resource* memory) = 0; /** - * Makes a sealer under a room's key. + * Derives a room's PBKDF2 master from its password: PBKDF2-HMAC-SHA-256 of `password` with + * `salt` and `protocol::pbkdf2_iterations` iterations, 32 bytes, what 0.27.0's + * `deriveBits` gives, off the room's thread, since 600,000 iterations would stall it. * - * @param key The raw AES-256 key, as `protocol::seal_key` derives it. - * @param memory The room's resource, which the sealer, its texts and its completions are - * allocated in. - * @return The sealer. + * @param password The password, in UTF-8; the caller's until `done` runs. + * @param salt The salt, `protocol::pbkdf2_salt`; the caller's until `done` runs. + * @param out Where the master is written; the caller's until `done` runs, zeroed on error. + * @param done Called on the room's executor once the master is written, or with + * `error::backend_failure`; what the derivation allocates goes through its allocator. */ - virtual std::shared_ptr make_sealer(std::array key, - std::pmr::memory_resource* memory) = 0; + virtual void derive_password_master(std::span password, + std::span salt, + std::span out, + handler done) = 0; /** * Fills `out` with bytes from a cryptographically secure source: they become secret keys and @@ -396,6 +388,26 @@ class factory { * @return The current time. */ virtual std::chrono::steady_clock::time_point steady_now() = 0; // lint-world: a type only + + /** + * Watches the page's connectivity, its `online` and `offline` events, which an app's relays + * follow while they are `relay_connectivity::automatic`, as 0.27.0's relay manager listens to + * them. + * + * This default watches nothing, as natively, where no such event exists: the app's relays then + * stay online. + * + * @param changed Called on the app's executor after each event, never inside it: `true` after + * an `online` event, `false` after an `offline` one; never once the watch is destroyed. + * @param memory The app's resource, which the watch and `changed` are allocated in. + * @return The watch, whose destruction ends it; null when the platform has no such events. + */ + virtual std::shared_ptr watch_connectivity(handler changed, + std::pmr::memory_resource* memory) { + (void)changed; + (void)memory; + return nullptr; + } }; } // namespace webcpp::trystero::backend diff --git a/include/webcpp/trystero/detail/action_wire.hpp b/include/webcpp/trystero/detail/action_wire.hpp index 1de04b7..4639d41 100644 --- a/include/webcpp/trystero/detail/action_wire.hpp +++ b/include/webcpp/trystero/detail/action_wire.hpp @@ -14,9 +14,12 @@ #include #include #include -#include +#include #include +#include +#include +#include #include #include #include @@ -60,6 +63,11 @@ struct incoming { // NOLINT(bugprone-exception-escape) range payload_at = {}; /** Where the metadata, JSON text or empty, is in the buffer. */ range metadata_at = {}; + /** + * Whether several listeners read the message: each then copies what it takes, leaving the + * message whole for the next. + */ + bool shared = false; /** The action's name, a view into the buffer. */ [[nodiscard]] std::string_view name() const { return text(name_at); } @@ -89,6 +97,16 @@ struct incoming { // NOLINT(bugprone-exception-escape) } }; +/** What a room's receive gate, Trystero's `onReceive`, says of a message it is asked about. */ +enum class admission { + /** The action has no gate: the message is received unasked. */ + open, + /** The gate took the message. */ + admitted, + /** The gate refused the message: an inline one is dropped, an offer rejected. */ + refused, +}; + /** A payload to send: the bytes, and what keeps them alive while a transfer is in flight. */ struct payload_ref { /** The payload's bytes. */ @@ -97,16 +115,20 @@ struct payload_ref { std::shared_ptr owner; }; -/** What the wire sends through: a room's use of a peer's connection, a `detail::binding`. */ +/** What the wire sends through: a room's connection to a peer, a `detail::peer_link`. */ class channel_link { public: - /** Sends a room frame; false when the channel is no longer open. */ - virtual bool send(std::span room_frame) = 0; + /** Sends an action frame as it is; false when the channel is no longer open. */ + virtual bool send(std::span frame) = 0; /** The bytes the channel buffers, not yet sent; 0 once it ended. */ [[nodiscard]] virtual std::size_t buffered_amount() const = 0; /** Calls `done(true)` once the channel's buffer is below Trystero's threshold, `done(false)` if * it closes first. */ virtual void wait_drained(handler done) = 0; + /** The largest frame a transfer's chunk may fill, 0.27.0's `maxBulkFrameBytes` getter + * (`peer-transport.ts`): `protocol::max_bulk_frame_bytes` when the connection's SCTP takes + * messages of that size, else `protocol::max_action_frame_bytes`. */ + [[nodiscard]] virtual std::size_t max_bulk_frame_bytes() const = 0; protected: channel_link() = default; @@ -117,19 +139,47 @@ class channel_link { /** * Sends and receives a room's actions over Trystero's action wire (protocol/action_wire.hpp), after - * its action wire manager and action receiver. Every frame it sends is a room frame: it writes the - * room envelope's header and the action frame into one buffer, once per send, shared by every - * target. + * its action wire manager and action receiver. Every frame it sends is an action frame, written + * bare on the room's channel as 0.27.0's `sendFrame` writes it: once per send, into one buffer + * shared by every target. * * | Rule | Value | * | inline | when header, metadata and payload fit 16 KiB | * | larger payloads | offer, wait for "accepted" (120 s), then chunks in order, each | * | | sent only while the channel buffers at most 64 KiB (10 s at most | - * | | per wait) | + * | | per wait); wide when the link takes 64 KiB frames (see below) | * | receiving | one transfer per peer at a time, accepted only for an action with | - * | | a receiver, at most `max_receive_bytes` reserved across peers | - * | frames before a receiver | kept (64 per peer, 120 s) until the action gets one | + * | | a listener, at most `max_receive_bytes` reserved across peers; | + * | | 1024 pending transfers, 64 per peer; chunks wide or not, as the | + * | | offer says, in any order, each once | + * | an action not made | an inline frame is dropped, an offer rejected at once as an | + * | | "unregistered action" | + * | a payload past its bound | `max_receive_bytes`, or the action's own `max_payload` when lower: | + * | | an inline frame is dropped, an offer rejected, as "payload exceeds | + * | | receiver size limit" | + * | frames before a listener | of an action made: kept, 32 per action and peer (a newer one drops | + * | | the oldest), for 10 s, until the action gets one | + * | the receive gate | asked of an inline frame and of an offer as it arrives, and of a | + * | | kept frame it was not asked of before it is delivered; a refusal | + * | | drops the frame, or rejects the offer "payload rejected by | + * | | receiver" | + * | progress | after each chunk but the last, the share received | + * | control frames | sent only while the channel buffers at most 1 MiB, else the peer | + * | | is dropped | * | protocol violations | the peer is dropped | + * + * As 0.27.0's `sendBulk`, a transfer is offered wide, its offer flagged and each chunk but the last + * filling a 64 KiB frame, when its link's `channel_link::max_bulk_frame_bytes` is + * `protocol::max_bulk_frame_bytes` as the offer is sent, and narrow, in 16 KiB frames, otherwise; + * transfers are received wide or narrow, as their offer says. + * + * Frames of an action the room has not made are not kept, as Trystero keeps none: a page that makes + * an action after it joined misses what came before. An action listens while it has a message + * listener or a request listener, and from its first `async_receive` on; its frames wait + * meanwhile. + * + * The receive gate runs during the frame's processing, as Trystero's does, and may end the peer or + * the room: the wire looks the peer up again after it. */ class action_wire : public std::enable_shared_from_this { public: @@ -138,7 +188,7 @@ class action_wire : public std::enable_shared_from_this { /** The peer's channel, gone once the peer is. */ std::weak_ptr target; - /** Sends a room frame; false when the channel is gone or no longer open. */ + /** Sends an action frame; false when the channel is gone or no longer open. */ [[nodiscard]] bool send(std::span frame) const { const auto t = target.lock(); return t && t->send(frame); @@ -150,6 +200,13 @@ class action_wire : public std::enable_shared_from_this { return t ? t->buffered_amount() : std::size_t{0}; } + /** The largest frame a chunk may fill; `protocol::max_action_frame_bytes` when the + * channel is gone. */ + [[nodiscard]] std::size_t max_bulk_frame_bytes() const { + const auto t = target.lock(); + return t ? t->max_bulk_frame_bytes() : protocol::max_action_frame_bytes; + } + /** Calls `done(true)` once the channel drained, `done(false)` if it is gone or closes. */ void wait_drained(handler done) const { if (const auto t = target.lock()) { @@ -168,20 +225,46 @@ class action_wire : public std::enable_shared_from_this { handler(bool include_pending)> peers; /** Whether a peer's message of an action may be received now: the handshake gate. */ handler may_receive; - /** Whether an action has a receiver in the room: it was made, or it is internal. */ - handler has_receiver; + /** Whether the room has an action: it was made, or it is internal; Trystero's registered + * actions. */ + handler has_action; + /** Whether an action the room has listens to its messages now, Trystero's receiver. */ + handler has_listener; /** Hands a received message to the room. */ handler deliver; - /** Drops a peer that broke the protocol, with the reason. */ + /** Drops a peer that broke the protocol, with the reason, 0.27.0's `onPeerError`. */ handler fail_peer; + /** Whether a message of an action the room has is one it expects from the peer now, with + * its metadata, 0.27.0's `receiveScope`: an answer must answer a request of the room's. + * An inline message it does not expect is dropped, an offer rejected with "unexpected + * response"; empty, every message is expected. */ + handler + expects = nullptr; + /** Asks the receive gate of an action the room has about a message, with its payload's + * size and its metadata; empty, every message is received unasked. */ + handler + admit = nullptr; + /** The wire refused a message of an action the room has, with the reason, Trystero's + * `onReject`: the gate's refusal, a size or a count over its bound, a transfer timed out. + */ + handler + rejected = nullptr; + /** A transfer's share received, below 1, after each of its chunks but the last. */ + handler + progress = nullptr; + /** The longest payload of an action, 0.27.0's `maxPayloadBytes`, below the room's + * `max_receive_bytes`; empty, every action has the room's. */ + handler max_payload = nullptr; }; /** Every allocation goes through `memory`. */ - action_wire(backend::factory& factory, std::string_view room_token, - std::size_t max_receive_bytes, callbacks cb, std::pmr::memory_resource* memory) + action_wire(backend::factory& factory, std::size_t max_receive_bytes, callbacks cb, + std::pmr::memory_resource* memory) : factory_(factory), memory_(memory), - token_(room_token, memory), max_receive_bytes_(max_receive_bytes), cb_(std::move(cb)), outgoing_(memory), @@ -215,16 +298,15 @@ class action_wire : public std::enable_shared_from_this { const auto state = std::allocate_shared(allocator(), chosen.size(), std::move(done)); if (protocol::fits_inline(metadata.size(), payload.data.size())) { - auto frame = protocol::begin_room_frame( - token_, protocol::inline_header_size + metadata.size() + payload.data.size(), - memory_); + auto frame = + begin_frame(protocol::inline_header_size + metadata.size() + payload.data.size()); protocol::append_inline(frame, name, format, metadata, payload.data); const std::shared_ptr shared = std::allocate_shared(allocator(), std::move(frame)); for (const auto peer : chosen) { auto l = cb_.find_link(peer, include_pending); if (!l) { - state->complete(make_error_code(error::no_such_peer)); + state->complete(make_error_code(error::not_connected)); continue; } send_when_drained( @@ -243,20 +325,18 @@ class action_wire : public std::enable_shared_from_this { for (const auto peer : chosen) { auto l = cb_.find_link(peer, include_pending); if (!l) { - state->complete(make_error_code(error::no_such_peer)); + state->complete(make_error_code(error::not_connected)); continue; } send_bulk(peer, *l, name, format, metadata, payload, state); } } - /** One action frame from a peer: `action` is a view into `frame`, which the message keeps if it - * is delivered. */ - void handle(std::string_view peer, backend::bytes&& frame, - std::span action) { - const auto decoded = protocol::decode_action(action); + /** One action frame from a peer, which the message keeps if it is delivered. */ + void handle(std::string_view peer, backend::bytes&& frame) { + const auto decoded = protocol::decode_action(frame); if (!decoded.frame) { - cb_.fail_peer(peer, "invalid action frame"); + cb_.fail_peer(peer, violation(decoded.error)); return; } if (const auto* p = std::get_if(&*decoded.frame)) { @@ -275,8 +355,8 @@ class action_wire : public std::enable_shared_from_this { } } - /** An action got a receiver: deliver what waited for it and accept its transfers. */ - void receiver_added() { drain(); } + /** An action got a listener: deliver what waited for it and accept its transfers. */ + void listener_added() { drain(); } /** Fails a peer's transfers with `reason` and forgets what it sent, once it is gone. */ void clear_peer(std::string_view peer, boost::system::error_code reason) { @@ -293,6 +373,7 @@ class action_wire : public std::enable_shared_from_this { reserved_bytes_ -= b.size; } } + pending_transfers_ -= it->second.bulk.size(); incoming_.erase(it); } drain(); @@ -302,9 +383,14 @@ class action_wire : public std::enable_shared_from_this { using pmr_allocator = std::pmr::polymorphic_allocator<>; using done_handler = handler; + /** Trystero's `transferTimeoutMs`. */ static constexpr auto transfer_timeout = std::chrono::milliseconds(120'000); + /** Trystero's `backpressureWaitTimeoutMs`. */ static constexpr auto drain_timeout = std::chrono::milliseconds(10'000); - static constexpr std::size_t max_pending_per_peer = 64; + /** Trystero's `pendingDataTimeoutMs`: how long a message waits for its action's receiver. */ + static constexpr auto pending_data_timeout = std::chrono::milliseconds(10'000); + /** Trystero's `sizeLimitMsg`: why a payload past its action's bound is refused. */ + static constexpr std::string_view size_limit_reason = "payload exceeds receiver size limit"; /** Completes a send once every target finished, with the first error. */ struct fan_out { @@ -339,13 +425,20 @@ class action_wire : public std::enable_shared_from_this { }; struct bulk_in { - explicit bulk_in(pmr_allocator a) : name(a), metadata(a), data(a) {} + explicit bulk_in(pmr_allocator a) : name(a), metadata(a), data(a), seen(a) {} std::pmr::string name; protocol::payload_format format = protocol::payload_format::binary; std::pmr::string metadata; std::size_t size = 0; + /** The payload bytes of each chunk but the last, as the offer's wide flag says. */ + std::size_t chunk = protocol::chunk_size; + /** The payload, then its metadata and name, once the first chunk arrived. */ backend::bytes data; + /** A bit per chunk, set once it arrived. */ + std::pmr::vector seen; + /** The payload bytes arrived. */ + std::size_t received = 0; bool receiving = false; std::shared_ptr timer; }; @@ -356,20 +449,61 @@ class action_wire : public std::enable_shared_from_this { struct waiting_inline { // NOLINT(bugprone-exception-escape) incoming message; time_point arrived{}; + /** Whether the receive gate took it as it arrived. */ + bool admitted = false; }; struct peer_in { explicit peer_in(pmr_allocator a) : bulk(a), waiting(a) {} std::pmr::map bulk; + /** The inline messages that wait for their action's receiver, oldest first. */ std::pmr::deque waiting; std::optional active; - - [[nodiscard]] std::size_t count() const { return bulk.size() + waiting.size(); } }; pmr_allocator allocator() const { return {memory_}; } + /** Why a frame that cannot be decoded drops its peer, in 0.27.0's words (`handleData`). */ + static std::string_view violation(protocol::wire_error error) { + switch (error) { + case protocol::wire_error::incompatible_version: + return "incompatible action protocol version"; + case protocol::wire_error::invalid_control: return "invalid action control"; + case protocol::wire_error::invalid_header: return "invalid action header"; + case protocol::wire_error::invalid_proposal: return "invalid action proposal"; + case protocol::wire_error::invalid_frame: break; + } + return "invalid action frame"; + } + + /** Whether the room expects a message of an action it has from `peer`, 0.27.0's + * `receiveScope`. */ + bool expected(std::string_view peer, std::string_view name, std::string_view metadata) { + return !cb_.expects || cb_.expects(peer, name, metadata); + } + + /** Asks the receive gate about a message; open without one. */ + admission gate(std::string_view peer, std::string_view name, std::size_t size, + std::string_view metadata) { + return cb_.admit ? cb_.admit(peer, name, size, metadata) : admission::open; + } + + /** The longest payload of an action, 0.27.0's `payloadLimit`: the room's bound, or the + * action's own when it is lower. */ + std::size_t payload_limit(std::string_view name) { + return cb_.max_payload ? std::min(max_receive_bytes_, cb_.max_payload(name)) + : max_receive_bytes_; + } + + /** Tells the room a message of an action it has was refused. */ + void refused(std::string_view peer, std::string_view name, std::string_view metadata, + std::string_view reason) { + if (cb_.rejected) { + cb_.rejected(peer, name, metadata, reason); + } + } + /** `f` as a handler of the room's resource. */ template handler bind(F&& f) const { @@ -406,10 +540,18 @@ class action_wire : public std::enable_shared_from_this { })); } + /** An empty frame in the wire's resource, with room reserved for `size` bytes, which the + * caller then writes once. */ + [[nodiscard]] backend::bytes begin_frame(std::size_t size) const { + backend::bytes out(memory_); + out.reserve(size); + return out; + } + std::shared_ptr control_frame(void (*append)(backend::bytes&, std::uint32_t), std::uint32_t id) { - auto frame = protocol::begin_room_frame(token_, protocol::control_header_size, memory_); + auto frame = begin_frame(protocol::control_header_size); append(frame, id); return std::allocate_shared(allocator(), std::move(frame)); } @@ -418,9 +560,12 @@ class action_wire : public std::enable_shared_from_this { protocol::payload_format format, std::string_view metadata, const payload_ref& payload, const std::shared_ptr& state) { const std::uint32_t id = next_id_++; - auto offer = protocol::begin_room_frame( - token_, protocol::offer_header_size + metadata.size(), memory_); - protocol::append_offer(offer, name, format, metadata, id, payload.data.size()); + // 0.27.0 reads the transport's size once per transfer, as it offers it. + const bool wide = l.max_bulk_frame_bytes() >= protocol::max_bulk_frame_bytes; + const std::size_t chunk = wide ? protocol::wide_chunk_size : protocol::chunk_size; + auto offer = begin_frame(protocol::offer_header_size + metadata.size()); + protocol::append_offer(offer, name, format, metadata, id, payload.data.size(), + wide ? protocol::chunk_width::wide : protocol::chunk_width::narrow); std::pmr::string peer(peer_view, memory_); // the transfer's handlers outlive this call auto& transfers = outgoing_[peer]; const auto transfer = std::allocate_shared(allocator()); @@ -436,21 +581,7 @@ class action_wire : public std::enable_shared_from_this { return; } if (const auto self = weak.lock()) { - if (const auto it = self->outgoing_.find(peer); it != self->outgoing_.end()) { - it->second.erase(id); - if (it->second.empty()) { - self->outgoing_.erase(it); - } - } - // The receiver may hold a reservation for this transfer: tell it, as Trystero - // does. A channel that refuses the frame is closing, which frees it anyway. - if (ec && ec != make_error_code(error::transfer_rejected) && - ec != make_error_code(error::peer_disconnected)) { - if (auto l = self->cb_.find_link(peer, true)) { - static_cast( - l->send(*self->control_frame(protocol::append_cancelled, id))); - } - } + self->end_outgoing(peer, id, ec); } state->complete(ec); }); @@ -460,15 +591,15 @@ class action_wire : public std::enable_shared_from_this { transfer->timer->start(transfer_timeout, bind([finish] { (*finish)(make_error_code(error::transfer_timed_out)); })); - transfer->accepted = - bind([weak, l, id, payload, finish, transfer_weak = std::weak_ptr(transfer)] { + transfer->accepted = bind( + [weak, l, id, chunk, payload, finish, transfer_weak = std::weak_ptr(transfer)] { const auto self = weak.lock(); const auto t = transfer_weak.lock(); if (!self || !t) { return; } t->timer->cancel(); - self->send_chunks(l, id, payload, 0, finish); + self->send_chunks(l, id, chunk, payload, 0, finish); }); send_when_drained( l, std::allocate_shared(allocator(), std::move(offer)), @@ -479,37 +610,61 @@ class action_wire : public std::enable_shared_from_this { })); } - void send_chunks(const link& l, std::uint32_t id, const payload_ref& payload, + /** Forgets the outgoing transfer `id` to `peer`, settled with `ec`; one that failed but for a + * refusal or a departure is cancelled to the peer. */ + void end_outgoing(const std::pmr::string& peer, std::uint32_t id, + boost::system::error_code ec) { + if (const auto it = outgoing_.find(peer); it != outgoing_.end()) { + it->second.erase(id); + if (it->second.empty()) { + outgoing_.erase(it); + } + } + // The receiver may hold a reservation for this transfer: tell it, as Trystero does. A + // channel that refuses the frame is closing, which frees it anyway. + if (ec && ec != make_error_code(error::transfer_rejected) && + ec != make_error_code(error::peer_disconnected)) { + if (auto l = cb_.find_link(peer, true); + l && l->buffered_amount() <= protocol::max_control_buffered_bytes) { + static_cast(l->send(*control_frame(protocol::append_cancelled, id))); + } + } + } + + /** Sends the chunks of transfer `id` from `offset` on, each of `chunk` payload bytes but the + * last, one per drain. */ + void send_chunks(const link& l, std::uint32_t id, std::size_t chunk, const payload_ref& payload, std::size_t offset, const std::shared_ptr& finish) { if (offset >= payload.data.size()) { (*finish)({}); return; } - const auto length = std::min(protocol::chunk_size, payload.data.size() - offset); - auto frame = - protocol::begin_room_frame(token_, protocol::chunk_header_size + length, memory_); + const auto length = std::min(chunk, payload.data.size() - offset); + auto frame = begin_frame(protocol::chunk_header_size + length); protocol::append_chunk(frame, id, offset, payload.data.subspan(offset, length)); const auto weak = weak_from_this(); send_when_drained( l, std::allocate_shared(allocator(), std::move(frame)), - bind( - [weak, l, id, payload, offset, length, finish](boost::system::error_code ec) { - if (ec) { - (*finish)(ec); - return; - } - const auto self = weak.lock(); - if (!self) { - (*finish)(make_error_code(error::room_left)); - return; - } - self->send_chunks(l, id, payload, offset + length, finish); - })); + bind([weak, l, id, chunk, payload, offset, length, + finish](boost::system::error_code ec) { + if (ec) { + (*finish)(ec); + return; + } + const auto self = weak.lock(); + if (!self) { + (*finish)(make_error_code(error::room_left)); + return; + } + self->send_chunks(l, id, chunk, payload, offset + length, finish); + })); } + /** Sends a control frame, as Trystero's `sendControlFrame`: a channel that buffers more than + * 1 MiB, or refuses it, drops the peer. */ void control(std::string_view peer, const backend::bytes& frame) { if (auto l = cb_.find_link(peer, true)) { - if (!l->send(frame)) { + if (l->buffered_amount() > protocol::max_control_buffered_bytes || !l->send(frame)) { cb_.fail_peer(peer, "unable to send action control"); } } @@ -557,15 +712,49 @@ class action_wire : public std::enable_shared_from_this { .payload_at = {.offset = offset_of(p.payload.data()), .size = p.payload.size()}, .metadata_at = {.offset = offset_of(p.metadata.data()), .size = p.metadata.size()}, }; - if (cb_.has_receiver(p.name)) { + if (!cb_.has_action(p.name)) { + return; // as Trystero drops a frame of an unregistered action + } + if (!expected(peer, p.name, p.metadata)) { + return; // as 0.27.0's resolveAdmission drops an inline message out of scope + } + if (p.payload.size() > payload_limit(p.name)) { + refused(peer, p.name, p.metadata, size_limit_reason); + return; + } + const auto verdict = gate(peer, p.name, p.payload.size(), p.metadata); + if (verdict == admission::refused) { + refused(peer, p.name, p.metadata, "payload rejected by receiver"); + return; + } + if (verdict == admission::admitted && !cb_.may_receive(peer, p.name)) { + return; // the gate ended the peer, or the room + } + if (cb_.has_listener(p.name)) { cb_.deliver(std::move(message)); return; } auto& in = incoming_for(peer); - if (in.count() >= max_pending_per_peer) { - return; + const auto now = steady_now(factory_); + while (!in.waiting.empty() && now - in.waiting.front().arrived > pending_data_timeout) { + in.waiting.pop_front(); + } + // As Trystero's pre-listener ring: a newer message of a full action drops its oldest. + std::size_t same_action = 0; + auto oldest = in.waiting.end(); + for (auto w = in.waiting.begin(); w != in.waiting.end(); ++w) { + if (w->message.name() == p.name && same_action++ == 0) { + oldest = w; + } + } + if (same_action >= protocol::max_pre_listener_messages) { + in.waiting.erase(oldest); } - in.waiting.push_back({.message = std::move(message), .arrived = steady_now(factory_)}); + in.waiting.push_back({ + .message = std::move(message), + .arrived = now, + .admitted = verdict == admission::admitted, + }); } peer_in& incoming_for(std::string_view peer) { @@ -577,30 +766,57 @@ class action_wire : public std::enable_shared_from_this { } void on_offer(std::string_view peer, const protocol::proposal& p) { - auto& in = incoming_for(peer); - if (in.bulk.contains(p.id)) { + if (const auto it = incoming_.find(peer); + it != incoming_.end() && it->second.bulk.contains(p.id)) { cb_.fail_peer(peer, "duplicate action offer"); return; } - const auto reject = [&](std::string_view reason) { - auto frame = protocol::begin_room_frame( - token_, protocol::control_header_size + reason.size(), memory_); + // Each rejection returns at once: a control frame that cannot go drops the peer. The room + // hears of the rejections of an action it has. + const auto reject = [&](std::string_view reason, bool registered = true) { + auto frame = begin_frame(protocol::control_header_size + reason.size()); protocol::append_rejected(frame, p.id, reason); + if (registered) { + refused(peer, p.name, p.metadata, reason); + } control(peer, frame); }; - if (p.size > max_receive_bytes_) { - reject("payload exceeds receiver size limit"); + if (!cb_.has_action(p.name)) { + reject("unregistered action", false); + return; + } + if (!expected(peer, p.name, p.metadata)) { + reject("unexpected response", false); + return; + } + if (p.size > payload_limit(p.name)) { + reject(size_limit_reason); return; } - if (in.count() >= max_pending_per_peer) { + if (const auto it = incoming_.find(peer); + pending_transfers_ >= protocol::max_pending_transfers || + (it != incoming_.end() && + it->second.bulk.size() >= protocol::max_pending_transfers_per_peer)) { reject("too many pending transfers"); return; } + // The gate, as Trystero asks it once the offer is pending; its code may end the peer. + const auto verdict = gate(peer, p.name, static_cast(p.size), p.metadata); + if (verdict == admission::refused) { + reject("payload rejected by receiver"); + return; + } + if (verdict == admission::admitted && !cb_.may_receive(peer, p.name)) { + return; + } + auto& in = incoming_for(peer); auto& b = in.bulk.try_emplace(p.id, allocator()).first->second; + ++pending_transfers_; b.name = p.name; b.format = p.format; b.metadata = p.metadata; - b.size = static_cast(p.size); // within max_receive_bytes_, checked above + b.size = static_cast(p.size); // within payload_limit, checked above + b.chunk = p.wide ? protocol::wide_chunk_size : protocol::chunk_size; b.timer = factory_.make_timer(memory_); arm(peer, p.id, b); drain(); @@ -623,10 +839,13 @@ class action_wire : public std::enable_shared_from_this { if (b == it->second.bulk.end()) { return; } + // What the room hears of the rejection outlives the transfer's state. + const std::pmr::string name(b->second.name, self->memory_); + const std::pmr::string metadata(b->second.metadata, self->memory_); self->release_bulk(it->second, b); - auto frame = protocol::begin_room_frame( - self->token_, protocol::control_header_size + 32, self->memory_); + auto frame = self->begin_frame(protocol::control_header_size + 32); protocol::append_rejected(frame, id, "action transfer timed out"); + self->refused(peer, name, metadata, "action transfer timed out"); self->control(peer, frame); self->drain(); })); @@ -642,26 +861,48 @@ class action_wire : public std::enable_shared_from_this { return; // cancelled or expired transfers cannot resurrect } auto& t = b->second; - if (!t.receiving || c.offset != static_cast(t.data.size()) || c.data.empty() || - c.data.size() != std::min(protocol::chunk_size, t.size - t.data.size())) { - cb_.fail_peer(peer, "invalid action chunk offset or length"); + // As Trystero checks a chunk: a whole offset within the payload, at a chunk's start, and + // the length of that chunk. The offset is a float64: compared as one, before it is cast. + if (!t.receiving || !(c.offset >= 0) || !(c.offset < static_cast(t.size)) || + std::floor(c.offset) != c.offset) { + cb_.fail_peer(peer, "invalid action chunk"); + return; + } + const auto offset = static_cast(c.offset); + const auto index = offset / t.chunk; + if (offset % t.chunk != 0 || c.data.empty() || + c.data.size() != std::min(t.chunk, t.size - offset)) { + cb_.fail_peer(peer, "invalid action chunk"); return; } // Room for the payload, then its metadata and name, so the delivered message is this one // buffer. - if (t.data.empty()) { - t.data.reserve(t.size + t.metadata.size() + t.name.size()); + if (t.seen.empty()) { + t.data.resize(t.size + t.metadata.size() + t.name.size()); + t.seen.resize((((t.size + t.chunk - 1) / t.chunk) + 7) / 8); + } + const auto bit = static_cast(1U << (index % 8)); + if ((t.seen[index / 8] & bit) != 0) { + cb_.fail_peer(peer, "invalid action chunk"); + return; } - t.data.insert(t.data.end(), c.data.begin(), c.data.end()); + t.seen[index / 8] |= bit; + std::ranges::copy(c.data, t.data.begin() + static_cast(offset)); + t.received += c.data.size(); arm(peer, c.id, t); - if (t.data.size() < t.size) { + if (t.received < t.size) { + if (cb_.progress) { + cb_.progress(peer, t.name, t.metadata, + static_cast(t.received) / static_cast(t.size)); + } return; } const incoming::range payload_at{.offset = 0, .size = t.size}; const incoming::range metadata_at{.offset = t.size, .size = t.metadata.size()}; const incoming::range name_at{.offset = t.size + t.metadata.size(), .size = t.name.size()}; - t.data.insert(t.data.end(), t.metadata.begin(), t.metadata.end()); - t.data.insert(t.data.end(), t.name.begin(), t.name.end()); + std::ranges::copy(t.metadata, + t.data.begin() + static_cast(metadata_at.offset)); + std::ranges::copy(t.name, t.data.begin() + static_cast(name_at.offset)); incoming message{ .peer = std::pmr::string(peer, memory_), .format = t.format, @@ -683,50 +924,97 @@ class action_wire : public std::enable_shared_from_this { in.active.reset(); } in.bulk.erase(b); + --pending_transfers_; } - /** Delivers inline frames whose action now has a receiver, and accepts the next transfer of - * each idle peer. */ + /** Delivers inline frames whose action now has a listener, and accepts the next transfer of + * each idle peer. It changes the peers' state first, and delivers and sends after: a delivery + * or a control frame that cannot go may drop a peer, whose removal clears it from `incoming_` + * and drains again. */ void drain() { const auto now = steady_now(factory_); - std::pmr::vector ready(memory_); + std::pmr::vector ready(memory_); + std::pmr::vector> accepted(memory_); for (auto& [peer, in] : incoming_) { - std::pmr::deque still_waiting(memory_); - for (auto& w : in.waiting) { - if (cb_.has_receiver(w.message.name())) { - ready.push_back(std::move(w.message)); - } else if (now - w.arrived < transfer_timeout) { - still_waiting.push_back(std::move(w)); - } + take_ready_inline(in, now, ready); + if (!in.active) { + accept_next_transfer(peer, in, accepted); } - in.waiting = std::move(still_waiting); - if (in.active) { + } + for (auto& w : ready) { + deliver_ready(w); + } + for (const auto& [peer, id] : accepted) { + // A delivery or an earlier acceptance may have dropped this peer. + if (const auto it = incoming_.find(peer); + it != incoming_.end() && it->second.active == id) { + control(peer, *control_frame(protocol::append_accepted, id)); + } + } + } + + /** Moves a peer's inline frames whose action now has a listener to `ready`, and drops those + * that waited past `pending_data_timeout`, as Trystero's sweep drops them, even if their + * action is here. */ + void take_ready_inline(peer_in& in, time_point now, std::pmr::vector& ready) { + std::pmr::deque still_waiting(memory_); + for (auto& w : in.waiting) { + if (now - w.arrived > pending_data_timeout) { continue; } - for (auto& [id, b] : in.bulk) { - if (b.receiving || !cb_.has_receiver(b.name) || - reserved_bytes_ + b.size > max_receive_bytes_) { - continue; - } - b.receiving = true; - reserved_bytes_ += b.size; - in.active = id; - control(peer, *control_frame(protocol::append_accepted, id)); - break; + if (cb_.has_listener(w.message.name())) { + ready.push_back(std::move(w)); + } else { + still_waiting.push_back(std::move(w)); + } + } + in.waiting = std::move(still_waiting); + } + + /** Marks the first of an idle peer's transfers that has a listener and fits the receive + * budget as receiving, and records it in `accepted`, the peer's id copied into the room's + * resource. */ + void accept_next_transfer( + const std::pmr::string& peer, peer_in& in, + std::pmr::vector>& accepted) { + for (auto& [id, b] : in.bulk) { + if (b.receiving || !cb_.has_listener(b.name) || + reserved_bytes_ + b.size > max_receive_bytes_) { + continue; + } + b.receiving = true; + reserved_bytes_ += b.size; + in.active = id; + accepted.emplace_back(peer, id); + return; + } + } + + /** Delivers an inline frame whose action now has a listener. A frame kept before its action + * had a gate is asked now, as Trystero asks it when it flushes; the gate's code, or a + * delivery, may have ended its peer. */ + void deliver_ready(waiting_inline& w) { + if (!w.admitted) { + const auto& m = w.message; + const auto verdict = gate(m.peer, m.name(), m.payload().size(), m.metadata()); + if (verdict == admission::refused) { + refused(m.peer, m.name(), m.metadata(), "payload rejected by receiver"); + return; } } - for (auto& m : ready) { - cb_.deliver(std::move(m)); + if (cb_.may_receive(w.message.peer, w.message.name())) { + cb_.deliver(std::move(w.message)); } } backend::factory& factory_; std::pmr::memory_resource* memory_; - std::pmr::string token_; std::size_t max_receive_bytes_; callbacks cb_; std::uint32_t next_id_ = 0; std::size_t reserved_bytes_ = 0; + /** The offers kept across peers, against `protocol::max_pending_transfers`. */ + std::size_t pending_transfers_ = 0; std::pmr::map>, std::less<>> outgoing_; diff --git a/include/webcpp/trystero/detail/app_impl.hpp b/include/webcpp/trystero/detail/app_impl.hpp index fb7f106..14c0072 100644 --- a/include/webcpp/trystero/detail/app_impl.hpp +++ b/include/webcpp/trystero/detail/app_impl.hpp @@ -10,33 +10,36 @@ #include #include -#include #include +#include #include #include -#include +#include +#include #include #include +#include #include +#include #include #include #include #include +#include +#include #include // lint-world: names the executor only #include #include -#include -#include #include #include -#include #include #include #include #include +#include #include #include #include @@ -46,8 +49,8 @@ namespace webcpp::trystero::detail { /** - * What a room of the app is to the app: the calls a connection's events become. A room implements - * it; the app reaches it through the registry, which the room leaves before it ends. + * What a room of the app is to the app: what a join and the page's connectivity ask of it. A room + * implements it; the app reaches it through the registry, which the room leaves before it ends. */ class room_endpoint { public: @@ -55,17 +58,9 @@ class room_endpoint { [[nodiscard]] virtual bool leaving() const = 0; /** Finishes its farewell and completes every pending leave. */ virtual void finish_farewell() = 0; - /** The remote advertised this room's token (`present`) or withdrew it. */ - virtual void presence_changed(std::string_view peer, bool present) = 0; - /** Whether the connection keeps this room's frames from `peer` while the room is not bound to - * it: false while the room drops them (its dropping window). */ - [[nodiscard]] virtual bool keeps_frames_from(std::string_view peer) const = 0; - /** A frame of this room's token from `peer` was kept. */ - virtual void frame_kept(std::string_view peer) = 0; - /** The app's connection `ended` to `peer` ended: not always the one the room is bound to, so a - * room acts only on what it holds on `ended`. */ - virtual void connection_ended(const std::shared_ptr& ended, std::string_view peer, - std::string_view reason) = 0; + /** The app's relays went offline (`offline`), so the room closes its relay sockets and holds + * them closed, or online, so it reconnects every one not connected. */ + virtual void relays_offline(bool offline) = 0; protected: room_endpoint() = default; @@ -75,52 +70,65 @@ class room_endpoint { }; /** - * The state an `app` and its rooms share: the configuration, the self id, the rooms by token, and - * one connection per remote peer. Every allocation goes through `app_config::memory`. + * The state an `app` and its rooms share: the configuration, the endpoint key and the self id it + * derives, the user identity, the rooms by id, the rooms' keys, the key records and verified + * signatures of peers and users, and the relays' connectivity. + * Nothing else is shared, as in 0.27.0, whose rooms share the identity and the relays alone: each + * room has its own connection to each peer. Every allocation goes through `app_config::memory`, + * except the key of a user identity the program gives, which is in the program's resource. * - * Tip: its users are the `app` handle and every room not yet ended; when the last goes, it ends - * every connection at that call. Its destructor ends nothing: it may run while the io_context is - * destroyed, from the last operation pending there. + * Tip: its users are the `app` handle and every room not yet ended; when the last goes, it stops + * watching the page's connectivity at that call. Its destructor ends nothing: it may run while the + * io_context is destroyed, from the last operation pending there. */ class app_impl : public std::enable_shared_from_this { public: /** The executor shared by the app and its rooms. */ using executor_type = webcpp::asio::any_io_executor; - /** Copies the configuration into its resource, draws the self id unless it names one, and sets - * aside what no peer could use, each kept as a report. */ - app_impl(executor_type ex, backend::factory& factory, app_config config) + /** + * Copies the configuration into its resource, makes the endpoint key and the user identity, + * sets aside what no peer could use, each kept as a report, and watches the page's + * connectivity, which the relays follow while they are `relay_connectivity::automatic`. + * + * The endpoint key is drawn from the system's generator, 0.27.0's `createEndpointIdentity`, + * and derives the self id; the user identity is the configuration's, or an ephemeral one made + * here. When either cannot be made, @ref identity_failure says which, and the self id is + * empty if the endpoint key is the one missing. + * + * Tip: `endpoint_scalar` and `user_scalar`, when not empty, are the endpoint key's and the + * ephemeral user key's scalars in place of ones drawn: the library's own tests fix their + * peers' keys, so that their ids are known; a scalar that is no valid key, zero for instance, + * makes its key fail. `user_scalar` is unused when the configuration gives an identity. + * + * @param ex The executor every app and room event runs on. + * @param factory The backend that makes the app's and the rooms' platform objects. + * @param config The app's configuration, moved from. + * @param endpoint_scalar The endpoint key's scalar, 32 bytes; empty draws one. + * @param user_scalar The ephemeral user key's scalar, 32 bytes; empty draws one. + */ + app_impl(executor_type ex, backend::factory& factory, app_config config, + std::span endpoint_scalar = {}, + std::span user_scalar = {}) : memory_(config.memory), ex_(std::move(ex)), factory_(factory), log_(std::move(config.log), memory_), app_id_(config.app_id, memory_), - self_id_(config.self_id, memory_), + endpoint_(make_endpoint_identity(endpoint_scalar, memory_)), + identity_(std::move(config.identity)), + persistence_(identity_ ? identity_persistence::imported + : identity_persistence::ephemeral), password_(config.password, memory_), + room_keys_(std::allocate_shared(allocator(), ex_, factory_, app_id_, + password_, memory_)), + identities_(memory_), relay_urls_(config.relay_urls, memory_), ice_servers_(copy_ice_servers(config.ice_servers, memory_)), - idle_timeout_(config.idle_timeout), setup_reports_(memory_), - rooms_(memory_), - connections_(memory_), - seconds_(memory_) { - if (self_id_.size() > protocol::max_peer_id_bytes) { - self_id_.clear(); - set_aside("self_id is longer than any peer accepts, so the app uses a random one"); - } - // A signal writes the id as a JSON string, which holds UTF-8 alone, as any JavaScript - // string is once encoded. - if (!protocol::json::quotable(self_id_)) { - self_id_.clear(); - set_aside("self_id is not UTF-8, which no peer reads, so the app uses a random one"); - } - if (self_id_.empty()) { - self_id_ = detail::random_id(factory_, protocol::peer_id_size, memory_); - } - if (idle_timeout_ < std::chrono::milliseconds::zero()) { - idle_timeout_ = std::chrono::milliseconds::zero(); - set_aside("idle_timeout is negative, so the app closes an unused connection at once"); - } + errors_(allocator()), + rooms_(memory_) { + resolve_identity(user_scalar); if (ice_servers_.empty()) { ice_servers_ = default_ice_servers(memory_); } @@ -149,6 +157,7 @@ class app_impl : public std::enable_shared_from_this { relay_urls_.emplace_back(url); } } + watch_page(); } /** The app state has one identity and cannot be copied. */ @@ -156,6 +165,10 @@ class app_impl : public std::enable_shared_from_this { /** The app state cannot be replaced by copying. */ app_impl& operator=(const app_impl&) = delete; + /** Wipes the app's copy of the password; it touches only its own member, so it may run while + * the io_context is destroyed. */ + ~app_impl() { webcpp::trystero::detail::wipe(password_.data(), password_.size()); } + /** The executor every app and room event runs on. */ [[nodiscard]] const executor_type& get_executor() const { return ex_; } @@ -171,51 +184,150 @@ class app_impl : public std::enable_shared_from_this { /** The application id shared by every room. */ [[nodiscard]] std::string_view app_id() const { return app_id_; } - /** The local peer id shared by every room. */ - [[nodiscard]] std::string_view self_id() const { return self_id_; } + /** + * The local peer id shared by every room, derived from the endpoint key. + * + * @return The id; empty when the endpoint key could not be made. + */ + [[nodiscard]] std::string_view self_id() const { + return endpoint_ ? std::string_view(endpoint_->peer_id) : std::string_view(); + } + + /** + * The endpoint key's compact public key. + * + * @return The key; empty when it could not be made. + */ + [[nodiscard]] std::string_view endpoint_key() const { + return endpoint_ ? std::string_view(endpoint_->compact) : std::string_view(); + } + + /** + * The endpoint key, which signs this side of each handshake of the app's rooms. + * + * @return The key; only while @ref identity_failure is empty. + */ + [[nodiscard]] const endpoint_identity& endpoint() const { + BOOST_ASSERT(endpoint_.has_value()); + return *endpoint_; + } - /** The immutable password shared by this app's rooms and authenticated connections. */ + /** + * The user identity every room of the app presents, which signs each handshake too. + * + * @return The identity; only while @ref identity_failure is empty. + */ + [[nodiscard]] const user_identity& user() const { + BOOST_ASSERT(identity_.has_value()); + return *identity_; + } + + /** + * The id of the user every room of the app presents. + * + * @return The id; empty when the ephemeral user identity could not be made. + */ + [[nodiscard]] std::string_view user_id() const { + return identity_ ? identity_->user_id() : std::string_view(); + } + + /** + * Where the user identity comes from. + * + * @return `imported` for the configuration's, `ephemeral` for one made with the app. + */ + [[nodiscard]] identity_persistence persistence() const { return persistence_; } + + /** + * Why the app has no identity, the message 0.27.0's rooms report with `identity-failed`. + * + * Tip: 0.27.0 reports the error's own message when it has one, WebCrypto's for instance, and + * these texts only as its fallbacks; the port reports the fallbacks always. + * + * @return "endpoint identity resolution failed" when the endpoint key could not be made, + * "identity resolution failed" when the ephemeral user identity could not be; empty when both + * exist. + */ + [[nodiscard]] std::string_view identity_failure() const { + if (!endpoint_) { + return "endpoint identity resolution failed"; + } + if (!identity_) { + return "identity resolution failed"; + } + return {}; + } + + /** The immutable password shared by this app's rooms. */ [[nodiscard]] std::string_view password() const { return password_; } + /** The keys of the app's rooms, derived once per room id when the app has a password. */ + [[nodiscard]] room_keys_cache& room_keys() const { return *room_keys_; } + + /** The key records and verified signatures of the app's peers and users, which its rooms + * share. */ + [[nodiscard]] identity_cache& identities() { return identities_; } + /** The relays configured once for the app. */ [[nodiscard]] std::span relay_urls() const { return relay_urls_; } - /** How long the higher id holds a second connection to a peer that neither sends on it nor - * closes it (`hold_second`). */ - static constexpr std::chrono::milliseconds second_wait_higher{2'000}; - /** How long the lower id holds a second connection to a peer that neither sends on the first - * nor closes one of them (`hold_second`). */ - static constexpr std::chrono::milliseconds second_wait_lower{10'000}; + /** How the relays of the app's rooms connect: `relay_connectivity::automatic` until the + * program sets another. */ + [[nodiscard]] relay_connectivity connectivity() const { return connectivity_; } + + /** Whether the relays of the app's rooms are held closed now: offline, or automatic since the + * page's `offline` event. A room joined meanwhile opens none. */ + [[nodiscard]] bool relays_offline() const { return relays_offline_; } + + /** + * Sets how the relays of the app's rooms connect, as 0.27.0's `setRelayConnectivity` sets it + * for its page: `offline` holds every relay closed; `online` reconnects at once every relay not + * connected, its reconnection delay back at its least, as each call does; `automatic` follows + * the page's events from now on, and reconnects the relays a program held offline. + * + * Tip: a value outside the enumeration, which only a cast can make, is stored and taken as + * `online`, where 0.27.0 throws "invalid relay connectivity mode". + * + * @return The connectivity now in place, `mode`. + */ + relay_connectivity set_connectivity(relay_connectivity mode) { + if (mode == relay_connectivity::automatic) { + const bool held = connectivity_ != relay_connectivity::automatic && relays_offline_; + connectivity_ = mode; + watch_page(); + if (held) { + set_relays_offline(false); + } + return connectivity_; + } + page_watch_.reset(); + connectivity_ = mode; + set_relays_offline(mode == relay_connectivity::offline); + return connectivity_; + } /** The validated ICE servers used for every negotiation. */ [[nodiscard]] std::span ice_servers() const { return ice_servers_; } - /** The lifetime of a connection left with no bindings after a departure. */ - [[nodiscard]] std::chrono::milliseconds idle_timeout() const { return idle_timeout_; } - /** What the constructor set aside, a sentence each, in its order. */ [[nodiscard]] std::span setup_reports() const { return setup_reports_; } - /** Sets what is called with each part of the configuration set aside, with an empty peer id - * and `error::invalid_configuration`, and posts the delivery of the reports the constructor - * made, which no handler could see then. + /** Adds a listener of each part of the configuration set aside, reported with + * `error::invalid_configuration` and no room, and posts the delivery of the reports the + * constructor made, which no listener could see then. * - * Tip: the delivery calls the handler current when it runs, so one replaced before it gets - * none, and it hands each report over once, so one set after it gets none either. */ - void on_error(handler f) { - if (!f) { - on_error_ = nullptr; - return; - } - on_error_ = std::allocate_shared(allocator(), std::move(f)); - if (delivered_reports_ == setup_reports_.size()) { - return; + * Tip: the delivery reaches the listeners in place when it runs, and it hands each report over + * once, so one added after it gets none. */ + subscription on_error(handler f, listen_options options) { + auto out = errors_.add(std::move(f), options); + if (delivered_reports_ != setup_reports_.size()) { + post(ex_, memory_, [weak = weak_from_this()] { + if (const auto self = weak.lock()) { + self->deliver_setup_reports(); + } + }); } - post(ex_, memory_, [weak = weak_from_this()] { - if (const auto self = weak.lock()) { - self->deliver_setup_reports(); - } - }); + return out; } /** `f` as a handler of the app's resource. */ @@ -224,36 +336,18 @@ class app_impl : public std::enable_shared_from_this { return handler(std::allocator_arg, allocator(), std::forward(f)); } - /** The connections not ended whose channel is open. */ - [[nodiscard]] std::pmr::vector> live_connections() const { - std::pmr::vector> out(memory_); - for (const auto& [peer, c] : connections_) { - if (c->live()) { - out.push_back(c); - } - } - return out; - } - /** Counts a user: the `app` handle, or a room not yet ended. */ void add_user() { ++users_; } - /** Releases a user; the last one's release ends every connection. */ + /** Releases a user; the last one's release ends the watch of the page's connectivity, so a + * page event after it reaches neither the rooms nor the program's log. */ void release_user() { if (users_ == 0) { return; } --users_; - if (users_ != 0) { - return; - } - auto connections = std::exchange(connections_, decltype(connections_)(memory_)); - for (auto& [peer, c] : connections) { - c->end("the app has no room left"); - } - auto seconds = std::exchange(seconds_, decltype(seconds_)(memory_)); - for (auto& [peer, second] : seconds) { - close_second(*second); + if (users_ == 0) { + page_watch_.reset(); } } @@ -262,371 +356,95 @@ class app_impl : public std::enable_shared_from_this { /** Registers a room by a weak reference: its control block is in the room's resource, so the * room unregisters before its state goes, in every way it ends, its destructor included. */ - void register_room(std::string_view room_id, std::string_view token, - const std::shared_ptr& room) { - rooms_.insert_or_assign(std::pmr::string(token, memory_), - entry{ - .room_id = std::pmr::string(room_id, memory_), - .room = room, - .raw = room.get(), - }); + void register_room(std::string_view room_id, const std::shared_ptr& room) { + rooms_.insert_or_assign(std::pmr::string(room_id, memory_), entry{ + .room = room, + .raw = room.get(), + }); } - /** Forgets the room of `token`, if it is still `room`'s entry. */ - void unregister_room(std::string_view token, const room_endpoint* room) { - if (const auto it = rooms_.find(token); it != rooms_.end() && it->second.raw == room) { + /** Forgets the room of `room_id`, if it is still `room`'s entry. */ + void unregister_room(std::string_view room_id, const room_endpoint* room) { + if (const auto it = rooms_.find(room_id); it != rooms_.end() && it->second.raw == room) { rooms_.erase(it); } } /** The room of `room_id`, while it lives. */ [[nodiscard]] std::shared_ptr find_room(std::string_view room_id) const { - for (const auto& [token, e] : rooms_) { - if (e.room_id == room_id) { - return e.room.lock(); - } - } - return nullptr; - } - - /** The live connection to `peer`, or null. */ - [[nodiscard]] std::shared_ptr find(std::string_view peer) const { - const auto it = connections_.find(peer); - return it != connections_.end() && it->second->live() ? it->second : nullptr; - } - - /** The connection a room's negotiation opened becomes the app's, or, when the app already has - * a live one to that peer, the existing one is returned, as in Trystero's - * dist/shared-peer.mjs:105-108, and the new one is held as the peer's second connection - * (`hold_second`). - * - * Tip: a stale connection to the peer, one whose channel is closing, ends first, as Trystero - * clears it (dist/shared-peer.mjs:142-149): the rooms hear its end before the new - * connection is adopted, and a room may adopt one to the peer from inside that call, which is - * then the one shared, or ends in its turn if it is stale by then. One whose end is already - * under way, further up the stack, is let go: it ends no second time. */ - std::shared_ptr adopt(std::string_view peer_view, - std::shared_ptr pc, - std::shared_ptr channel) { - // `peer_view` may be a view into the stale connection, which its end frees. - const std::pmr::string peer(peer_view, memory_); - for (auto it = connections_.find(peer); it != connections_.end() && !it->second->live(); - it = connections_.find(peer)) { - const auto stale = it->second; - stale->end("replaced by a new connection to the peer"); - if (const auto again = connections_.find(peer); - again != connections_.end() && again->second == stale) { - connections_.erase(again); - } - } - return share_or_adopt(peer, std::move(pc), std::move(channel)); + const auto it = rooms_.find(room_id); + return it == rooms_.end() ? nullptr : it->second.room.lock(); } private: - /** A second connection to a peer, held unused until the peer shows which of the two it keeps: - * the frames its channel received meanwhile, in their order, and its deadline. */ - struct second_connection { - std::pmr::string peer; - std::shared_ptr pc; - std::shared_ptr channel; - std::pmr::deque frames; - std::shared_ptr deadline; - }; - - // Its implicit move assignment, which insert_or_assign uses, may allocate: a std::pmr member - // copies when the two resources differ, which bugprone-exception-escape reports. Every entry - // is in the app's resource, so it never does. - struct entry { // NOLINT(bugprone-exception-escape) - std::pmr::string room_id; + struct entry { std::weak_ptr room; const room_endpoint* raw; // identity only, for unregister_room; never dereferenced }; - /** Closes the new connection and returns the live one to `peer`, if any; else adopts it. */ - // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on - std::shared_ptr share_or_adopt(std::string_view peer, - std::shared_ptr pc, - std::shared_ptr channel) { - // NOLINTEND(performance-unnecessary-value-param) - if (auto existing = find(peer)) { - hold_or_close(peer, *existing, std::move(pc), std::move(channel)); - return existing; - } - const auto weak = weak_from_this(); - // The connection whose `ended` this is, set once it exists: its end erases its own entry - // only, never one a room adopted since (Trystero's owns(), dist/shared-peer.mjs:210-212). - const auto owner = std::allocate_shared>(allocator()); - auto c = std::allocate_shared( - allocator(), factory_, peer, std::move(pc), std::move(channel), - connection_callbacks{ - .presence = bind( - [weak](std::string_view p, std::string_view token, bool present) { - if (const auto self = weak.lock()) { - if (const auto room = self->room_of(token)) { - room->presence_changed(p, present); - } - } - }), - .keeps = bind( - [weak](std::string_view p, std::string_view token) { - const auto self = weak.lock(); - const auto room = self ? self->room_of(token) : nullptr; - return room != nullptr && room->keeps_frames_from(p); - }), - .kept = bind( - [weak](std::string_view p, std::string_view token) { - if (const auto self = weak.lock()) { - if (const auto room = self->room_of(token)) { - room->frame_kept(p); - } - } - }), - .ended = bind( - [weak, owner](std::string_view p, std::string_view reason) { - if (const auto self = weak.lock()) { - self->on_connection_end(owner->lock(), p, reason); - } - }), - .used = bind([weak](std::string_view p) { - if (const auto self = weak.lock()) { - if (const auto it = self->seconds_.find(p); it != self->seconds_.end()) { - self->forget_second(*it->second, "the peer keeps the first"); - } - } - }), - }, - log_, memory_); - *owner = c; - connections_.insert_or_assign(std::pmr::string(peer, memory_), c); - std::pmr::vector tokens(memory_); - for (const auto& [token, e] : rooms_) { - tokens.emplace_back(token); - } - c->start(tokens); - return c; - } - - /** A connection to `peer` opened while `first` is live: held as the second - * (`hold_second`) while the peer has sent nothing on the first and none is held, else - * closed. */ - // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on - void hold_or_close(std::string_view peer, const connection& first, - std::shared_ptr pc, - std::shared_ptr channel) { - // NOLINTEND(performance-unnecessary-value-param) - if (!first.used() && !seconds_.contains(peer)) { - hold_second(peer, std::move(pc), std::move(channel)); - return; + /** Hands every report not yet delivered to the listeners in place, one at a time: a listener + * may remove itself, or another, from inside its call. */ + void deliver_setup_reports() { + while (delivered_reports_ < setup_reports_.size() && !errors_.empty()) { + const std::string_view what = setup_reports_[delivered_reports_++]; + room_error e; + e.code = make_error_code(error::invalid_configuration); + e.message = what; + e.app_id = app_id_; + errors_.emit(e); } - channel->set_handlers({}); - pc->set_handlers({}); - channel->close(); - pc->close(); - log_("webrtc", "another connection with ", peer, - " closed: ", first.used() ? "the peer keeps the first" : "a second is held already"); } - /** Holds a second connection to `peer`, opened while the first was live and before the peer - * sent anything on the first, until the peer shows which of the two it keeps, rather than - * closing it at once as Trystero does. + /** + * Watches the page's connectivity through the backend, while the relays are automatic, unless + * it is watched already. * - * Each side keeps the connection whose channel opened first on its side (Trystero's - * dist/shared-peer.mjs:105-108), so the two sides of a crossed pair keep different ones, and - * a side sends only on the one it keeps. A frame on the first shows the peer keeps it: the - * second is closed, as the peer closes its own. Trystero JS closes its other connection at - * once, so that in a crossed pair the first ends, and the second, the one the peer keeps, - * replaces it (`on_connection_end`) with the frames it received meanwhile. A peer that holds - * its second, as this app does, closes neither, so the higher id gives way: a frame on its - * second makes the second replace its first (`switch_to_second`), whose end closes the lower - * id's second. A second the peer neither sends on nor closes is closed after - * `second_wait_higher` by the higher id, and after `second_wait_lower` by the lower id. - * - * Closing the second at once, as Trystero does, closes in a crossed pair the connection the - * peer keeps, just as the peer starts sending on it. libdatachannel ends an association with - * a stream reset and a SHUTDOWN, and its ABORT comes a moment later, where a browser's ABORT - * follows its reset at once: Chrome fails a send made in between and closes the channel with - * that failure, which Trystero JS reports as a peer error. */ - void hold_second(std::string_view peer, std::shared_ptr pc, - std::shared_ptr channel) { - auto second = std::allocate_shared( - allocator(), second_connection{ - .peer = std::pmr::string(peer, memory_), - .pc = std::move(pc), - .channel = std::move(channel), - .frames = std::pmr::deque(memory_), - .deadline = factory_.make_timer(memory_), - }); - const auto weak = weak_from_this(); - const std::weak_ptr held = second; - second->channel->set_handlers({ - .open = {}, - .message = bind([weak, held](backend::bytes frame) { - const auto self = weak.lock(); - const auto s = held.lock(); - if (!self || !s) { - return; - } - if (s->frames.size() >= connection::max_kept_frames) { - self->forget_second(*s, "it received more frames than are kept"); - return; - } - s->frames.push_back(std::move(frame)); - // Posted: the switch replaces the handlers this call runs in. - if (std::string_view(self->self_id_) > s->peer && s->frames.size() == 1) { - post(self->ex_, self->memory_, [weak, held] { - const auto app = weak.lock(); - if (const auto second = held.lock(); app && second) { - app->switch_to_second(*second); - } - }); - } - }), - .close = bind([weak, held] { - const auto self = weak.lock(); - const auto s = held.lock(); - if (self && s) { - self->forget_second(*s, "its channel closed"); - } - }), - .buffered_amount_low = {}, - }); - second->pc->set_handlers({ - .ice_candidate = {}, - .data_channel = {}, - .state = bind( - [weak, held](backend::connection_state state) { - const auto self = weak.lock(); - const auto s = held.lock(); - if (self && s && - (state == backend::connection_state::failed || - state == backend::connection_state::closed)) { - self->forget_second(*s, "its connection ended"); - } - }), - }); - second->deadline->start( - std::string_view(self_id_) > peer ? second_wait_higher : second_wait_lower, - bind([weak, held] { - const auto self = weak.lock(); - const auto s = held.lock(); - if (self && s) { - self->forget_second(*s, "the peer kept neither"); - } - })); - seconds_.insert_or_assign(std::pmr::string(peer, memory_), second); - log_("webrtc", "a second connection with ", peer, - " held until the peer shows which one it keeps"); - } - - /** The peer sends on the second connection the higher id holds, which it keeps: the second - * replaces the first, which ends, and takes the frames it received. As in - * `on_connection_end`, the second takes the first's place before the rooms hear of the end, - * and its frames come after. */ - void switch_to_second(second_connection& s) { - const auto it = seconds_.find(s.peer); - if (it == seconds_.end() || it->second.get() != &s) { + * Tip: the handler names the app by its address: the watch is the app's, and the backend calls + * no handler of a watch once it is destroyed. + */ + void watch_page() { + if (page_watch_) { return; } - const auto second = it->second; - seconds_.erase(it); - const std::pmr::string peer(second->peer, memory_); - second->deadline.reset(); - auto frames = std::exchange(second->frames, std::pmr::deque(memory_)); - std::shared_ptr first; - if (const auto at = connections_.find(peer); at != connections_.end()) { - first = at->second; - connections_.erase(at); - } - log_("webrtc", "the second connection with ", peer, - " replaces the first: the peer keeps it"); - const auto replacement = share_or_adopt(peer, second->pc, second->channel); - if (first) { - first->end("the peer keeps the second connection"); - } - replacement->replay(std::move(frames)); - } - - /** Closes a held second connection and forgets it, if it is still the one held. */ - void forget_second(second_connection& s, std::string_view why) { - const auto it = seconds_.find(s.peer); - if (it == seconds_.end() || it->second.get() != &s) { - return; - } - const auto keep = it->second; // `s` lives until this call returns - seconds_.erase(it); - log_("webrtc", "the second connection with ", keep->peer, " closed: ", why); - close_second(*keep); - } - - /** Closes a second connection without reporting its close. */ - static void close_second(second_connection& s) { - s.deadline.reset(); - s.channel->set_handlers({}); - s.pc->set_handlers({}); - s.channel->close(); - s.pc->close(); + page_watch_ = + factory_.watch_connectivity(bind([this](bool online) { + if (connectivity_ == relay_connectivity::automatic) { + set_relays_offline(!online); + } + }), + memory_); } - [[nodiscard]] std::shared_ptr room_of(std::string_view token) const { - const auto it = rooms_.find(token); - return it == rooms_.end() ? nullptr : it->second.room.lock(); - } - - /** Forgets `ended`, unless another connection to the peer took its place, and tells every - * room: those of a connection the last user's release took out of the registry too. */ - void on_connection_end(const std::shared_ptr& ended, std::string_view peer_view, - std::string_view reason_view) { - // The slot is filled before the connection starts, and its end holds it alive. - BOOST_ASSERT(ended); - const std::pmr::string peer(peer_view, memory_); - const std::pmr::string reason(reason_view, memory_); - if (const auto it = connections_.find(peer); - it != connections_.end() && it->second == ended) { - connections_.erase(it); - } - // The second connection held to the peer replaces the first when the peer or the network - // ended the first, which is how Trystero JS keeps the second of a crossed pair; it is - // closed when this side ended the first. It takes the first's place before the rooms hear - // of the end, so that none looks for the peer again, and its frames come after, once the - // rooms let the peer go, so that they bind it again over the second. - std::shared_ptr replacement; - std::pmr::deque frames(memory_); - if (const auto it = seconds_.find(peer); it != seconds_.end()) { - const auto second = it->second; - seconds_.erase(it); - if (ended->ended_by_transport() && second->channel->is_open() && !find(peer)) { - second->deadline.reset(); - frames = std::move(second->frames); - log_("webrtc", "the second connection with ", peer, " replaces the first"); - replacement = share_or_adopt(peer, second->pc, second->channel); - } else { - log_("webrtc", "the second connection with ", peer, " closed: the first ended"); - close_second(*second); - } - } - // A room may leave the registry from inside the call: the rooms are locked first, each - // kept alive across its call. + /** Holds the relays of every room closed (`offline`), or reconnects them. */ + void set_relays_offline(bool offline) { + relays_offline_ = offline; + log_("app", offline ? "the relays go offline" : "the relays go online"); + // A room may leave from inside the call, through the log sink: the registry is read first. std::pmr::vector> rooms(memory_); - for (const auto& [token, e] : rooms_) { - if (auto r = e.room.lock()) { - rooms.push_back(std::move(r)); + for (const auto& [id, e] : rooms_) { + if (auto room = e.room.lock()) { + rooms.push_back(std::move(room)); } } for (const auto& room : rooms) { - room->connection_ended(ended, peer, reason); - } - if (replacement) { - replacement->replay(std::move(frames)); + room->relays_offline(offline); } } - /** Hands every report not yet delivered to the current handler, one at a time: a handler may - * replace itself, or clear itself, from inside its call. */ - void deliver_setup_reports() { - while (delivered_reports_ < setup_reports_.size() && on_error_) { - const auto f = on_error_; - const std::string_view what = setup_reports_[delivered_reports_++]; - (*f)("", make_error_code(error::invalid_configuration), what); + /** + * Makes the ephemeral user identity when the configuration gave none, and logs what could not + * be made. + * + * @param user_scalar The ephemeral user key's scalar; empty draws one. + */ + void resolve_identity(std::span user_scalar) { + if (!identity_) { + if (auto made = user_identity_access::make(user_scalar, memory_)) { + identity_ = std::move(*made); + } + } + if (const auto failure = identity_failure(); !failure.empty()) { + log_("app", failure); } } @@ -642,19 +460,24 @@ class app_impl : public std::enable_shared_from_this { backend::factory& factory_; logger log_; std::pmr::string app_id_; - std::pmr::string self_id_; + std::optional endpoint_; + std::optional identity_; + identity_persistence persistence_; std::pmr::string password_; + std::shared_ptr room_keys_; + identity_cache identities_; std::pmr::vector relay_urls_; std::pmr::vector ice_servers_; - std::chrono::milliseconds idle_timeout_; std::pmr::vector setup_reports_; - std::shared_ptr> - on_error_; + listeners errors_; std::size_t delivered_reports_ = 0; // the setup reports handed to a handler, in their order std::pmr::map> rooms_; - std::pmr::map, std::less<>> connections_; - std::pmr::map, std::less<>> seconds_; std::size_t users_ = 0; + relay_connectivity connectivity_ = relay_connectivity::automatic; + bool relays_offline_ = false; + // The page's connectivity, watched while the relays are automatic and the app has a user: + // last, so that it ends first. + std::shared_ptr page_watch_; }; } // namespace webcpp::trystero::detail diff --git a/include/webcpp/trystero/detail/connection.hpp b/include/webcpp/trystero/detail/connection.hpp deleted file mode 100644 index 5258e7b..0000000 --- a/include/webcpp/trystero/detail/connection.hpp +++ /dev/null @@ -1,661 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -#ifndef WEBCPP_TRYSTERO_DETAIL_CONNECTION_HPP -#define WEBCPP_TRYSTERO_DETAIL_CONNECTION_HPP - -#include - -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace webcpp::trystero::detail { - -/** What a connection asks of its app. Every handler is in the app's resource, and every one is - * set. */ -struct connection_callbacks { - /** The remote advertised (`present`) or withdrew a room's token. */ - handler presence; - /** Whether to keep a frame of `token`, which no room bound to this connection has: the app - * says no for a token of no room of it, and for a room whose dropping window runs. */ - handler keeps; - /** A frame of `token` was kept. */ - handler kept; - /** The connection ended, with the reason; called once. */ - handler ended; - /** The remote sent its first frame, which shows that it keeps this connection; called once, - * and may be empty. */ - handler used; -}; - -// clang-tidy reports a class's destructor at its first declaration: binding is final, and nothing -// destroys it through channel_link, whose destructor is protected. -class binding; // NOLINT(cppcoreguidelines-virtual-class-destructor) - -/** - * One remote peer's connection, shared by every room of the app bound to it: it decodes each - * frame's envelope, routes a room frame to the binding of its token, keeps a few frames for a room - * of the app not bound yet, and records the rooms the remote advertises. - * - * | Frame | Done | - * | does not decode | the connection ends, for every room | - * | presence(1, T), T new | recorded; a 65th distinct token ends the connection | - * | presence(0, T) | forgotten; frames kept for T dropped | - * | room frame, T bound | to the binding of T | - * | room frame, T kept by the app | T recorded, below 64; kept: 64 per connection, all | - * | | dropped 10 s after the first | - * | room frame, any other T | dropped | - * - * A room frame the app keeps advertises its token as presence does: only the remote writes to its - * connection, and its presence for a room comes once per connection, which a page can lose, since - * Chrome drops what a page sends on an answering channel as it opens (its log says "Send failed - * INVALID_STATE"). Without it the room would never bind the remote, whose frames of the room keep - * coming. - * - * Tip: it holds plain pointers to its bindings, which remove themselves before they go, so that it - * keeps nothing of a room's resource after the room has ended. - */ -class connection : public std::enable_shared_from_this { -public: - /** The most distinct tokens a remote may advertise at once. */ - static constexpr std::size_t max_remote_rooms = 64; - /** The most frames kept for rooms not bound yet. */ - static constexpr std::size_t max_kept_frames = 64; - /** How long after the first kept frame every kept frame is dropped. */ - static constexpr std::chrono::milliseconds kept_frames_ttl{10'000}; - - /** A connection to `peer` over its negotiated connection and open channel, in `memory`, the - * app's resource. - * - * @pre Every handler of `cb` is set. */ - connection(backend::factory& factory, std::string_view peer, - std::shared_ptr pc, - std::shared_ptr channel, connection_callbacks cb, logger log, - std::pmr::memory_resource* memory) - : factory_(factory), - memory_(memory), - peer_(peer, memory), - pc_(std::move(pc)), - channel_(std::move(channel)), - cb_(std::move(cb)), - log_(std::move(log)), - remote_tokens_(memory), - bound_(memory), - kept_(memory), - drain_order_(memory), - attached_(memory) { - BOOST_ASSERT(cb_.presence && cb_.keeps && cb_.kept && cb_.ended); - } - - /** A shared transport has one identity and cannot be copied. */ - connection(const connection&) = delete; - /** A shared transport cannot be replaced by copying. */ - connection& operator=(const connection&) = delete; - - /** Takes over the channel's and the connection's events, which replaces the handlers a room's - * negotiation set, and advertises `tokens`. */ - void start(std::span tokens) { - const auto weak = weak_from_this(); - const std::pmr::polymorphic_allocator<> allocator(memory_); - channel_->set_handlers({ - .open = {}, - .message = - { - std::allocator_arg, - allocator, - [weak](backend::bytes frame) { - if (const auto self = weak.lock()) { - self->on_message(std::move(frame)); - } - }, - }, - .close = - { - std::allocator_arg, - allocator, - [weak] { - if (const auto self = weak.lock()) { - self->end_by_transport("data channel closed"); - } - }, - }, - .buffered_amount_low = - { - std::allocator_arg, - allocator, - [weak] { - if (const auto self = weak.lock()) { - self->on_drained(true); - } - }, - }, - }); - pc_->set_handlers({ - .ice_candidate = {}, - .data_channel = {}, - .state = - { - std::allocator_arg, - allocator, - [weak](backend::connection_state state) { - if (const auto self = weak.lock()) { - self->on_state(state); - } - }, - }, - }); - for (const auto token : tokens) { - send_presence(token, true); - } - // The sink may destroy a room and invalidate its token in the app's registry. Finish - // reading the snapshot before calling it, so a withdrawal also follows its advertisement. - log_("webrtc", "connection with ", peer_, " adopted"); - } - - /** The remote peer's id. */ - [[nodiscard]] std::string_view peer() const { return peer_; } - - /** Not stale, as Trystero says it: not ended, and its channel neither closing nor closed. A - * connection is adopted once its channel is open, so "still opening" does not arise here. */ - [[nodiscard]] bool live() const { return !ended_ && channel_->is_open(); } - - /** How many frames are kept for rooms not bound yet. */ - [[nodiscard]] std::size_t kept_count() const { return kept_.size(); } - - /** Whether the remote advertises the room of `token`: by its presence, or by a room frame of - * the token that the app kept. */ - [[nodiscard]] bool advertised(std::string_view token) const { - return remote_tokens_.contains(token); - } - - /** Tells the remote this peer joined (`present`) or left the room of `token`. */ - void send_presence(std::string_view token, bool present) { - if (!ended_ && channel_->is_open()) { - channel_->send(protocol::presence_frame(token, present, memory_)); - } - } - - /** Sends a frame as it is; false when the connection ended or its channel is no longer open. - */ - bool send(std::span frame) { - if (ended_ || !channel_->is_open()) { - return false; - } - channel_->send(frame); - return true; - } - - /** The bytes the channel buffers; 0 once the connection ended. */ - [[nodiscard]] std::size_t buffered_amount() const { - return ended_ ? 0 : channel_->buffered_amount(); - } - - /** Registers a room's binding by its token, and keeps the connection from idling; returns the - * binding's id, which no other binding of this connection has. - * - * @pre No binding of the same token is bound: the app binds a room to a connection once. */ - std::uint64_t attach(binding& b); - - /** Removes a binding; with none left, ends the connection after a kick or a zero idle time, - * else after `idle_timeout`. */ - void detach(binding& b, bool after_kick, std::chrono::milliseconds idle_timeout); - - /** Starts the idle period after a departure when no binding remains, without extending an - * idle period already running. Also covers a room that left during connection adoption. */ - void idle_if_unused(std::chrono::milliseconds idle_timeout); - - /** Gives the binding a place in the drain order, once. */ - void wait_drained(const binding& b); - - /** The frames kept for `token`, in their order; they are no longer kept. */ - std::pmr::deque take_kept(std::string_view token) { - std::pmr::deque out(memory_); - for (auto it = kept_.begin(); it != kept_.end();) { - if (it->first == token) { - out.push_back(std::move(it->second)); - it = kept_.erase(it); - } else { - ++it; - } - } - forget_kept_if_empty(); - return out; - } - - /** Ends the connection for every room, once: its handlers cleared, its bindings let go, the - * connection and its channel closed, `ended` called last. */ - void end(std::string_view reason); - - /** Whether the remote sent a frame on it, which shows that it keeps it. */ - [[nodiscard]] bool used() const { return used_; } - - /** Whether it ended because its channel or its connection closed or failed, which the remote - * or the network did, rather than because this side ended it. */ - [[nodiscard]] bool ended_by_transport() const { return ended_by_transport_; } - - /** Handles, in their order, the frames its channel received before `start`, as if they came - * now: those a second connection received while the app held it for the remote's choice. */ - void replay(std::pmr::deque frames) { - const auto self = shared_from_this(); - for (auto& frame : frames) { - if (ended_) { - return; - } - on_message(std::move(frame)); - } - } - -private: - friend class binding; - void remove(binding& b); - void on_message(backend::bytes&& frame); - void on_state(backend::connection_state state); - void on_drained(bool open); - void keep(std::string_view token, backend::bytes&& frame); - void forget_kept_if_empty(); - - void end_by_transport(std::string_view reason) { - if (!ended_) { - ended_by_transport_ = true; - } - end(reason); - } - - backend::factory& factory_; - std::pmr::memory_resource* memory_; - std::pmr::string peer_; - std::shared_ptr pc_; - std::shared_ptr channel_; - connection_callbacks cb_; - logger log_; - std::pmr::set> remote_tokens_; - std::pmr::map> bound_; - std::pmr::deque> kept_; - std::shared_ptr kept_timer_; - std::shared_ptr idle_timer_; - std::shared_ptr disconnect_timer_; - // Bindings are named by id, never by address: a binding made during a drain may take the block - // of one destroyed in it, and must not inherit its turn. - std::pmr::deque drain_order_; - std::pmr::map attached_; // by id: in the order of attachment - std::uint64_t next_binding_id_ = 0; - bool ended_ = false; - bool ended_by_transport_ = false; - bool used_ = false; -}; - -/** - * A room's use of one connection: the action wire's link to a peer, whose frames carry the room's - * token. It lives in the room's resource and owns its drain waiters; the connection holds only a - * pointer to it, which it removes when it detaches. - */ -class binding final : public channel_link, public std::enable_shared_from_this { -public: - /** Binds the room of `token` to `c`, which hands it every room frame of the token. */ - binding(const std::shared_ptr& c, std::string_view token, - handler)> deliver, - std::pmr::memory_resource* room_memory) - : connection_(c), - token_(token, room_memory), - deliver_(std::move(deliver)), - waiters_(room_memory) { - id_ = c->attach(*this); - } - - /** A binding registers one identity and cannot be copied. */ - binding(const binding&) = delete; - /** A binding cannot be replaced by copying. */ - binding& operator=(const binding&) = delete; - - /** Leaves the connection quietly: its waiters freed uncalled, its place in the connection - * forgotten, and nothing ended, idled, closed or called back, since it may run while the - * io_context is destroyed. */ - ~binding() { - if (std::exchange(detached_, true)) { - return; - } - waiters_.clear(); - deliver_ = {}; - if (const auto c = connection_.lock()) { - c->remove(*this); - } - } - - /** The room's token. */ - [[nodiscard]] std::string_view token() const { return token_; } - - /** The binding's id on its connection, which no other binding of the connection has. */ - [[nodiscard]] std::uint64_t id() const { return id_; } - - /** Whether this binding is on `c`, by identity, alive or not: by the owner, so that a - * connection made at the address of one destroyed is not taken for it. */ - [[nodiscard]] bool is_on(const std::shared_ptr& c) const { - return !connection_.owner_before(c) && !c.owner_before(connection_); - } - - /** The connection, until the binding detaches or the connection is gone. */ - [[nodiscard]] std::shared_ptr shared_connection() const { - return detached_ ? nullptr : connection_.lock(); - } - - /** Sends through the live shared channel, or fails after detachment. */ - bool send(std::span room_frame) override { - const auto c = shared_connection(); - return c && c->send(room_frame); - } - - /** The shared channel's unsent bytes, or zero after detachment. */ - [[nodiscard]] std::size_t buffered_amount() const override { - const auto c = shared_connection(); - return c ? c->buffered_amount() : 0; - } - - /** Waits in this binding's order for channel drain, or fails after detachment. */ - void wait_drained(handler done) override { - const auto c = shared_connection(); - if (!c || !c->live()) { - done(false); - return; - } - if (c->buffered_amount() <= backend::data_channel::low_threshold) { - done(true); - return; - } - waiters_.push_back(std::move(done)); - c->wait_drained(*this); - } - - /** A room frame of this binding's token, from the connection. */ - void deliver(backend::bytes&& frame, std::span action) { - if (detached_) { - return; - } - // The room may detach or destroy this binding from inside the call (a kick): it and its - // delivery stay alive until the call returns. A lock, not shared_from_this, - // which would abort without exceptions when no shared_ptr owns the binding. - const auto self = weak_from_this().lock(); - deliver_(std::move(frame), action); - } - - /** This binding's turn at a drain: each of its waiters, in its order. */ - void drained(bool open) { - // Keep the binding alive if a waiter releases its last owner. Leave the rest of this - // turn in the queue so a nested end or detach fails them before returning. New waits - // belong to the next turn, even when a callback appends them to this queue. - const auto self = weak_from_this().lock(); - const auto count = waiters_.size(); - for (std::size_t i = 0; i < count && !waiters_.empty(); ++i) { - auto waiter = std::move(waiters_.front()); - waiters_.pop_front(); - waiter(open); - } - } - - /** Leaves the connection: every waiter is told `false` and freed, no frame is delivered any - * more, and the connection idles or ends when no binding is left. - * - * Tip: the delivery is not reset here, since it may be the very call that detaches; it goes - * with the binding, which its room owns. */ - void detach(bool after_kick, std::chrono::milliseconds idle_timeout) { - if (std::exchange(detached_, true)) { - return; - } - // A waiter told `false` may release the room's last reference to this binding. - const auto self = weak_from_this().lock(); - drained(false); - if (const auto c = connection_.lock()) { - c->detach(*this, after_kick, idle_timeout); - } - } - -private: - std::weak_ptr connection_; - std::pmr::string token_; - handler)> deliver_; - std::pmr::deque> waiters_; - bool detached_ = false; - std::uint64_t id_ = 0; -}; - -inline std::uint64_t connection::attach(binding& b) { - BOOST_ASSERT(!bound_.contains(b.token())); - bound_.insert_or_assign(std::pmr::string(b.token(), memory_), &b); - const auto id = ++next_binding_id_; - attached_.emplace(id, &b); - idle_timer_.reset(); - return id; -} - -inline void connection::wait_drained(const binding& b) { - if (std::ranges::find(drain_order_, b.id()) == drain_order_.end()) { - drain_order_.push_back(b.id()); - } -} - -/** Forgets a binding, and nothing else: its maps, its place in the drain order. */ -inline void connection::remove(binding& b) { - if (const auto it = bound_.find(b.token()); it != bound_.end() && it->second == &b) { - bound_.erase(it); - } - attached_.erase(b.id()); - std::erase(drain_order_, b.id()); -} - -inline void connection::detach(binding& b, bool after_kick, - std::chrono::milliseconds idle_timeout) { - remove(b); - if (ended_ || !bound_.empty()) { - return; - } - if (after_kick) { - end("its last room kicked the peer"); - return; - } - idle_if_unused(idle_timeout); -} - -inline void connection::idle_if_unused(std::chrono::milliseconds idle_timeout) { - if (ended_ || !bound_.empty() || idle_timer_) { - return; - } - if (idle_timeout <= std::chrono::milliseconds::zero()) { - end("no room left"); - return; - } - idle_timer_ = factory_.make_timer(memory_); - idle_timer_->start( - idle_timeout, - {std::allocator_arg, std::pmr::polymorphic_allocator<>(memory_), [weak = weak_from_this()] { - if (const auto self = weak.lock()) { - self->end("idle"); - } - }}); -} - -inline void connection::end(std::string_view reason_view) { - if (ended_) { - return; - } - ended_ = true; - // The reason may be a view into what the calls below free. - const std::pmr::string reason(reason_view, memory_); - log_("webrtc", "connection with ", peer_, " ended: ", reason); - const auto self = shared_from_this(); - idle_timer_.reset(); - kept_timer_.reset(); - disconnect_timer_.reset(); - channel_->set_handlers({}); - pc_->set_handlers({}); - channel_->close(); - pc_->close(); - // The bindings are let go before anyone is told: a room may destroy its binding, or itself, - // from inside `ended` (Trystero's clear, dist/shared-peer.mjs:170-180). Every attached - // binding is told, those of the drain order first, then the others in the order they attached: - // an end from inside a drain's turn leaves waiters of that drain in no drain order. A failure - // may detach or destroy another binding, so each is looked up before its turn; one attached - // meanwhile finds the connection not live, and fails at once. - bound_.clear(); - auto order = std::exchange(drain_order_, std::pmr::deque(memory_)); - for (const auto& [id, b] : attached_) { - if (std::ranges::find(order, id) == order.end()) { - order.push_back(id); - } - } - for (const auto id : order) { - if (const auto it = attached_.find(id); it != attached_.end()) { - it->second->drained(false); - } - } - attached_.clear(); - kept_ = decltype(kept_)(memory_); - auto ended = std::move(cb_.ended); - ended(peer_, reason); -} - -/** Routes a decoded envelope to presence handling, its binding or the bounded keep queue. */ -inline void connection::on_message(backend::bytes&& frame) { - if (!std::exchange(used_, true) && cb_.used) { - // The app may end this connection from inside the call. - const auto self = shared_from_this(); - cb_.used(peer_); - if (ended_) { - return; - } - } - const auto envelope = protocol::decode_envelope(frame); - if (!envelope) { - end("invalid or incompatible room frame"); - return; - } - // The app may end this connection from inside any call below: it stays alive until it returns. - const auto self = shared_from_this(); - const std::string_view token = envelope->token; // into `frame`, which outlives every use - if (envelope->type == protocol::envelope::kind::presence) { - if (envelope->present) { - if (!remote_tokens_.contains(token) && remote_tokens_.size() >= max_remote_rooms) { - end("too many advertised rooms"); - return; - } - remote_tokens_.emplace(token); - } else { - if (const auto it = remote_tokens_.find(token); it != remote_tokens_.end()) { - remote_tokens_.erase(it); - } - std::erase_if(kept_, [token](const auto& k) { return k.first == token; }); - forget_kept_if_empty(); - } - cb_.presence(peer_, token, envelope->present); - return; - } - if (const auto it = bound_.find(token); it != bound_.end()) { - const auto action = envelope->payload; - it->second->deliver(std::move(frame), action); - return; - } - if (cb_.keeps(peer_, token) && !ended_) { - // The remote's own advertisement, before its room is told: within the bound on tokens, - // which a frame never ends the connection for. - if (!remote_tokens_.contains(token) && remote_tokens_.size() < max_remote_rooms) { - remote_tokens_.emplace(token); - } - keep(token, std::move(frame)); - } -} - -/** Keeps an unbound local room's frame within the connection's count and time bounds. */ -inline void connection::keep(std::string_view token, backend::bytes&& frame) { - if (kept_.size() >= max_kept_frames) { - return; - } - kept_.emplace_back(std::pmr::string(token, memory_), std::move(frame)); - if (!kept_timer_) { - // All kept frames go 10 s after the first, as in Trystero's dist/shared-peer.mjs:425-428. - kept_timer_ = factory_.make_timer(memory_); - kept_timer_->start(kept_frames_ttl, - {std::allocator_arg, std::pmr::polymorphic_allocator<>(memory_), - [weak = weak_from_this()] { - if (const auto self = weak.lock()) { - self->kept_ = decltype(self->kept_)(self->memory_); - self->kept_timer_.reset(); - } - }}); - } - // `token` may be a view into the frame just kept, which the app may take from inside the call. - const std::pmr::string kept_token(kept_.back().first, memory_); - cb_.kept(peer_, kept_token); -} - -/** With nothing kept, the window stops, so that the next kept frame has 10 s of its own, as - * Trystero's syncDataTimers does (dist/shared-peer.mjs:417-422). */ -inline void connection::forget_kept_if_empty() { - if (!kept_.empty()) { - return; - } - kept_timer_.reset(); - // A cleared deque keeps blocks (libc++ keeps up to two): a new one frees them. - kept_ = decltype(kept_)(memory_); -} - -/** Ends a failed transport and gives a transient disconnection five seconds to recover. */ -inline void connection::on_state(backend::connection_state state) { - using backend::connection_state; - if (state == connection_state::failed || state == connection_state::closed) { - end_by_transport(state == connection_state::failed ? "connection failed" - : "connection closed"); - } else if (state == connection_state::disconnected) { - // Trystero waits five seconds before treating a disconnection as the end. - if (!disconnect_timer_) { - disconnect_timer_ = factory_.make_timer(memory_); - } - disconnect_timer_->start(std::chrono::milliseconds(5000), - {std::allocator_arg, std::pmr::polymorphic_allocator<>(memory_), - [weak = weak_from_this()] { - if (const auto self = weak.lock()) { - self->end_by_transport("connection lost"); - } - }}); - } else if (disconnect_timer_) { - disconnect_timer_->cancel(); - } -} - -/** Gives every waiting binding its turn, looking up each identity again after callbacks. */ -inline void connection::on_drained(bool open) { - // Every binding waiting at this drain gets its turn, in the order it began to wait. A turn may - // detach another binding of the snapshot, even destroy it: each is looked up by its id before - // its turn, so that one made meanwhile, at the same address, is not taken for it. - const auto self = shared_from_this(); - const auto order = std::exchange(drain_order_, std::pmr::deque(memory_)); - for (const auto id : order) { - if (const auto it = attached_.find(id); it != attached_.end()) { - it->second->drained(open); - } - } -} - -} // namespace webcpp::trystero::detail - -#endif diff --git a/include/webcpp/trystero/detail/handshake_manager.hpp b/include/webcpp/trystero/detail/handshake_manager.hpp new file mode 100644 index 0000000..c45d16e --- /dev/null +++ b/include/webcpp/trystero/detail/handshake_manager.hpp @@ -0,0 +1,440 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_TRYSTERO_DETAIL_HANDSHAKE_MANAGER_HPP +#define WEBCPP_TRYSTERO_DETAIL_HANDSHAKE_MANAGER_HPP + +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::detail { + +/** + * What a @ref handshake_manager asks of its room, 0.27.0's `HandshakeManagerDeps` without the state + * plugin's `beforeSendHandshakeReady` (Phase 3). Every one is set. + * + * Each is called on the room's executor, and may call the manager back: the manager looks its peer + * up again after each call. + */ +struct handshake_callbacks { + /** Runs the handshake's steps with a peer, 0.27.0's `onPeerHandshake`: the room's identity + * handshake, through @ref handshake_manager::next_message; `done` takes "" when they passed, + * else the reason they failed. */ + handler done)> + run_steps; + /** Sends the ready frame, `\@_hsready`, whose payload is `ready_json`: "" for 0.27.0's empty + * text, else a JSON text. */ + handler send_ready; + /** The steps passed on this side, 0.27.0's `onLocalHandshakePassed`: false when the room + * refused the peer, a full room a new user (a ban needs roles, Phase 3). */ + handler local_passed; + /** Admits the peer, 0.27.0's `acquireAdmissionSlot`: false when the room no longer wants it. */ + handler admit; + /** Both sides are ready: the peer joins, 0.27.0's `onActivate`. */ + handler activate; + /** The handshake failed, with the reason, 0.27.0's `onHandshakeError` and `onFailure`; the room + * lets the peer go, which clears it. */ + handler failed; +}; + +/** + * The handshake of each peer of a room, 0.27.0's `createHandshakeManager` (`handshake.ts`): its + * phases, its 10 s, its 16 buffered messages and its ready frames. + * + * | Phase | Left by | + * | `added` | `start`, which runs the steps and starts the timer | + * | `running_steps` | the steps' end: to `awaiting_remote_ready` for a deferred | + * | | responder whose peer is not ready, else through | + * | | `preparing_ready`, which sends the ready frame, to | + * | | `awaiting_peer_ready`, or to `active` when the peer is ready | + * | `awaiting_remote_ready` | the peer's ready frame, then as above | + * | `awaiting_peer_ready` | the peer's ready frame: `active` | + * | `active` | `clear` alone | + * + * The initiator is the side whose id is lower in UTF-16 code unit order, as 0.27.0's + * `effectiveSelfId < id` compares its strings. The ready frame is sent before `activate` is called, + * so that a send inside the room's `on_peer_join` follows it on the wire. A failure is reported + * through `callbacks::failed` while the handshake is pending, once per timer or message that causes + * it: the timer's 10 s ("handshake timed out after 10000ms"), a 17th message buffered before the + * steps read it ("too many pending handshake messages"), or the steps' own reason. The room then + * clears the peer. + * + * Every allocation goes through the room's resource. It is owned by a `std::shared_ptr`, made with + * `std::allocate_shared`: its timers and the steps' `done` name it weakly. + * + * Tip: each `add` gives the peer a new generation, which every timer and `done` carries, so that + * one of a cleared or replaced handshake reaches nothing, as 0.27.0 compares the peer's handle. + */ +class handshake_manager final : public std::enable_shared_from_this { +public: + /** How long a handshake has once started, 0.27.0's `defaultHandshakeTimeoutMs`. */ + static constexpr std::chrono::milliseconds timeout{10'000}; + /** The most messages buffered before the steps read them, 0.27.0's + * `maxBufferedHandshakeMessages`. */ + static constexpr std::size_t max_buffered_messages = 16; + /** The reason the steps get with a message they wait for when the peer is cleared, 0.27.0's + * `handshakeDisconnectErr`, whose code is `error::peer_disconnected`. */ + static constexpr std::string_view disconnected_reason = + protocol::handshake_reason::disconnected; + /** The reason of a handshake whose timer expired, 0.27.0's message without its prefix. */ + static constexpr std::string_view timed_out_reason = protocol::handshake_reason::timed_out; + /** The reason of a 17th buffered message, 0.27.0's message without its prefix. */ + static constexpr std::string_view too_many_messages_reason = + protocol::handshake_reason::too_many_messages; + + /** Where a peer's handshake is, 0.27.0's `HandshakePeerEntry` phases. */ + enum class phase { + /** Added; its messages and its ready frame are kept until `start`. */ + added, + /** The steps run. */ + running_steps, + /** A deferred responder's steps passed; it waits for the peer's ready frame. */ + awaiting_remote_ready, + /** The ready frame is being prepared: reserved for Phase 3's state plugin, whose + * preparation is asynchronous. Until then the preparation ends in the call that starts it, + * and no peer is ever in this phase, so the cases that read it (`receive_ready`'s + * among them) are untested until Phase 3 enters it. */ + preparing_ready, + /** The ready frame was sent; it waits for the peer's. */ + awaiting_peer_ready, + /** Both sides are ready: the peer is in the room. */ + active, + }; + + /** + * A manager of the handshakes of the room of `self_id`. + * + * @param self_id This peer's id, copied: the lower id initiates. + * @param defer_responder_ready Whether the responder waits for the initiator's ready frame + * before it admits and sends its own, 0.27.0's `deferResponderReady`: a room with + * `max_users`. + * @param cb What the manager asks of its room. + * @param factory The backend, for the timers; it outlives the manager. + * @param memory The room's resource, which outlives the manager. + */ + // NOLINTNEXTLINE(performance-unnecessary-value-param): a sink, moved on + handshake_manager(std::string_view self_id, bool defer_responder_ready, handshake_callbacks cb, + backend::factory& factory, std::pmr::memory_resource* memory) + : factory_(factory), + memory_(memory), + self_id_(self_id, memory), + defer_responder_ready_(defer_responder_ready), + cb_(std::move(cb)), + peers_(memory) {} + + /** A manager has one identity and cannot be copied. */ + handshake_manager(const handshake_manager&) = delete; + /** A manager cannot be replaced by copying. */ + handshake_manager& operator=(const handshake_manager&) = delete; + + /** Calls nothing: pending steps and timers reach nothing once it is gone. */ + ~handshake_manager() = default; + + /** + * Adds a peer in the phase `added`, 0.27.0's `addPeer`; a handshake the peer had is cleared + * first, as `clear` clears it. + * + * @param peer The peer's id, copied. + */ + void add(std::string_view peer) { + clear(peer); + auto& e = peers_.try_emplace(std::pmr::string(peer, memory_), allocator()).first->second; + e.generation = ++generations_; + } + + /** + * Starts an added peer's handshake, 0.27.0's `start`: the timer, then the steps, which may pass + * during the call. A peer not in the phase `added` is left as it is. + * + * @param peer_view The peer's id. + */ + void start(std::string_view peer_view) { + auto* e = find(peer_view); + if (e == nullptr || e->at != phase::added) { + return; + } + const std::pmr::string peer(peer_view, memory_); + const auto generation = e->generation; + const auto weak = weak_from_this(); + e->timer = factory_.make_timer(memory_); + e->timer->start(timeout, + bind([weak, peer = std::pmr::string(peer, memory_), generation] { + if (const auto self = weak.lock()) { + self->fail(peer, generation, timed_out_reason); + } + })); + e->at = phase::running_steps; + e->initiator = protocol::utf16_less(self_id_, peer); + cb_.run_steps(peer, e->initiator, + bind([weak, peer = std::pmr::string(peer, memory_), + generation](std::string_view reason) { + if (const auto self = weak.lock()) { + self->steps_done(peer, generation, reason); + } + })); + } + + /** + * Forgets a peer's handshake, 0.27.0's `clearPeer`: its timer stops, its buffered messages go, + * and a step waiting for a message completes with `error::peer_disconnected` + * (@ref disconnected_reason). Nothing is reported. + * + * @param peer The peer's id. + */ + void clear(std::string_view peer) { + const auto it = peers_.find(peer); + if (it == peers_.end()) { + return; + } + // A node handle's mapped value is mutable through a const handle. + const auto node = peers_.extract(it); + auto& e = node.mapped(); + if (e.timer) { + e.timer->cancel(); + } + auto waiters = std::move(e.waiters); + for (auto& next : waiters) { + next(make_error_code(error::peer_disconnected), {}); + } + } + + /** + * A message of the peer's steps, the payload of an `\@_hsdata` frame, 0.27.0's `receiveData`: + * to the step waiting for one, else buffered, a 17th buffered one failing the handshake. + * Dropped once the steps passed. + * + * @param peer The peer's id. + * @param json The payload, copied when buffered. + */ + void receive_data(std::string_view peer, std::string_view json) { + auto* e = find(peer); + if (e == nullptr || (e->at != phase::added && e->at != phase::running_steps)) { + return; + } + if (!e->waiters.empty()) { + auto next = std::move(e->waiters.front()); + e->waiters.pop_front(); + next(boost::system::error_code{}, json); + return; + } + if (e->messages.size() >= max_buffered_messages) { + fail(peer, e->generation, too_many_messages_reason); + return; + } + e->messages.emplace_back(json); + } + + /** + * Hands the steps the peer's next message, 0.27.0's `receive`: a buffered one during the call, + * else the next to arrive. `next` completes with `error::peer_disconnected` when the peer's + * steps are not running, or once it is cleared. + * + * @param peer The peer's id. + * @param next Called once, with the message, valid for the duration of the call. + */ + void next_message(std::string_view peer, + handler next) { + auto* e = find(peer); + if (e == nullptr || e->at != phase::running_steps) { + next(make_error_code(error::peer_disconnected), {}); + return; + } + if (!e->messages.empty()) { + const std::pmr::string json = std::move(e->messages.front()); + e->messages.pop_front(); + next(boost::system::error_code{}, json); + return; + } + e->waiters.push_back(std::move(next)); + } + + /** + * The peer's ready frame, 0.27.0's `receiveReady`: kept until this side's steps passed, or the + * peer joins now. + * + * @param peer The peer's id. + */ + void receive_ready(std::string_view peer) { + auto* e = find(peer); + if (e == nullptr) { + return; + } + switch (e->at) { + case phase::added: + case phase::running_steps: + case phase::preparing_ready: e->remote_ready = true; return; + case phase::awaiting_remote_ready: + begin_preparing_ready(std::pmr::string(peer, memory_), e->generation, true); + return; + case phase::awaiting_peer_ready: { + const std::pmr::string id(peer, memory_); + e->timer->cancel(); + e->at = phase::active; + cb_.activate(id); + return; + } + case phase::active: return; + } + } + + /** + * Whether a message of the peer may be received now, 0.27.0's `canReceiveFromPeer`: the peer's + * handshake is known, and it is active or the action is received while pending. + * + * @param peer The peer's id. + * @param receive_while_pending Whether the action is received during the handshake. + * @return Whether it may. + */ + [[nodiscard]] bool can_receive(std::string_view peer, bool receive_while_pending) const { + const auto it = peers_.find(peer); + return it != peers_.end() && (it->second.at == phase::active || receive_while_pending); + } + + /** + * Where a peer's handshake is. + * + * @param peer The peer's id. + * @return Its phase; empty for a peer not added, or cleared. + */ + [[nodiscard]] std::optional phase_of(std::string_view peer) const { + const auto it = peers_.find(peer); + return it == peers_.end() ? std::nullopt : std::optional(it->second.at); + } + +private: + struct entry { + explicit entry(std::pmr::polymorphic_allocator<> a) : messages(a), waiters(a) {} + + phase at = phase::added; + std::uint64_t generation = 0; + bool remote_ready = false; + bool initiator = false; + std::shared_ptr timer; + std::pmr::deque messages; + std::pmr::deque> waiters; + }; + + std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } + + template + handler bind(F&& f) const { + return handler(std::allocator_arg, allocator(), std::forward(f)); + } + + entry* find(std::string_view peer) { + const auto it = peers_.find(peer); + return it == peers_.end() ? nullptr : &it->second; + } + + /** The peer's entry, if it is still the handshake of `generation`. */ + entry* find(std::string_view peer, std::uint64_t generation) { + auto* e = find(peer); + return e != nullptr && e->generation == generation ? e : nullptr; + } + + /** 0.27.0's `failPeerHandshake`: the timer stops and the room hears of it; the entry stays + * until the room clears it. */ + void fail(std::string_view peer_view, std::uint64_t generation, std::string_view reason_view) { + const auto* e = find(peer_view, generation); + if (e == nullptr) { + return; + } + if (e->timer) { + e->timer->cancel(); + } + // Copies: the room's call may free the views' storage. + const std::pmr::string peer(peer_view, memory_); + const std::pmr::string reason(reason_view, memory_); + cb_.failed(peer, reason); + } + + /** The steps ended: a reason fails the handshake; else, the steps having run in the phase + * `running_steps`, the room hears they passed, and the ready frame follows. */ + void steps_done(std::string_view peer, std::uint64_t generation, std::string_view reason) { + if (!reason.empty()) { + fail(peer, generation, reason); + return; + } + auto* e = find(peer, generation); + if (e == nullptr || e->at != phase::running_steps) { + return; + } + e->messages.clear(); + auto waiters = std::move(e->waiters); + e->waiters.clear(); + for (auto& next : waiters) { + next(make_error_code(error::peer_disconnected), {}); + } + if (!cb_.local_passed(peer)) { + return; + } + e = find(peer, generation); + if (e == nullptr || e->at != phase::running_steps) { + return; + } + if (defer_responder_ready_ && !e->initiator && !e->remote_ready) { + e->at = phase::awaiting_remote_ready; + return; + } + begin_preparing_ready(peer, generation, e->remote_ready); + } + + /** 0.27.0's `beginPreparingReady` and its `finishReady`, which nothing prepares before Phase + * 3's state plugin: the ready frame is "", sent before the peer joins. */ + void begin_preparing_ready(std::string_view peer, std::uint64_t generation, bool remote_ready) { + if (!cb_.admit(peer)) { + return; + } + auto* e = find(peer, generation); + if (e == nullptr || e->at == phase::active) { + return; + } + const bool ready = remote_ready || e->at == phase::awaiting_remote_ready || e->remote_ready; + if (ready) { + e->timer->cancel(); + e->at = phase::active; + } else { + e->at = phase::awaiting_peer_ready; + } + cb_.send_ready(peer, ""); + // The send can have ended the peer; 0.27.0 reports a failed send later, from its promise. + if (ready && find(peer, generation) != nullptr) { + cb_.activate(peer); + } + } + + backend::factory& factory_; + std::pmr::memory_resource* memory_; + std::pmr::string self_id_; + bool defer_responder_ready_; + handshake_callbacks cb_; + std::pmr::map> peers_; + std::uint64_t generations_ = 0; +}; + +} // namespace webcpp::trystero::detail + +#endif diff --git a/include/webcpp/trystero/detail/identity_cache.hpp b/include/webcpp/trystero/detail/identity_cache.hpp new file mode 100644 index 0000000..5336eb8 --- /dev/null +++ b/include/webcpp/trystero/detail/identity_cache.hpp @@ -0,0 +1,310 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_TRYSTERO_DETAIL_IDENTITY_CACHE_HPP +#define WEBCPP_TRYSTERO_DETAIL_IDENTITY_CACHE_HPP + +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::detail { + +/** + * A peer's or a user's public key as 0.27.0's `getVerifiedPubKeyRecord` resolves it: the key, + * read from its compact text and on the curve, with the peer id and the user id it derives. + */ +struct key_record { + /** The key, ready to verify signatures. */ + webcpp::crypto::curves::p256::public_key key; + /** Its compact text, `base64url(x) + "." + base64url(y)`. */ + std::pmr::string compact; + /** The peer id the key derives, `protocol::derive_peer_id`. */ + std::pmr::string peer_id; + /** The user id the key derives, `protocol::derive_user_id`. */ + std::pmr::string user_id; +}; + +/** + * The verification an @ref identity_cache makes in production: `protocol::verify_p256`. + * + * A cache is a template of a verifier so that a test can count and substitute the verifications + * (a seam of the tests, not of the public API): the bounds and the rule that a cached answer is + * given without verifying are then proven without thousands of real signatures. + */ +struct protocol_verifier { + /** Whether a signature is the key's, of the payload, `protocol::verify_p256`. */ + [[nodiscard]] bool operator()(std::span signature, + std::span payload, + const webcpp::crypto::curves::p256::public_key& key) const { + return protocol::verify_p256(signature, payload, key); + } +}; + +/** + * The key records and the verified signatures of an app, 0.27.0's `resolvedPubKeyCache` and + * `verifiedSigPayloads` (design D18): at most @ref max_records records and at most + * @ref max_signatures signatures whose payloads total at most @ref max_signature_bytes, the least + * recently used leaving first, every one in the app's resource. + * + * Tip: 0.27.0 keeps both caches for the whole page and resolves them asynchronously; the port + * keeps them per app and resolves them at once (design D18), so rooms of one app share them and two + * apps never do. + */ +template +class basic_identity_cache { +public: + /** How many key records the cache keeps, 0.27.0's `createBoundedCache` default. */ + static constexpr std::size_t max_records = 4096; + /** How many verified signatures the cache keeps, 0.27.0's `maxSigCacheEntries`. */ + static constexpr std::size_t max_signatures = 8192; + /** How many payload bytes the verified signatures keep in all, 0.27.0's + * `maxSigCacheTotalBytes`. */ + static constexpr std::size_t max_signature_bytes = std::size_t{2} * 1024 * 1024; + /** The longest payload whose signature is kept, 0.27.0's `maxCachedSigPayloadBytes`. */ + static constexpr std::size_t max_cached_payload_bytes = 4096; + + /** + * An empty cache. + * + * @param memory The resource of the records and the signatures: the app's. + * @param verifier What verifies a signature that is not cached, called with a signature of low + * S only. + */ + explicit basic_identity_cache(std::pmr::memory_resource* memory, Verifier verifier = {}) + : verifier_(std::move(verifier)), + memory_(memory), + records_(memory), + record_order_(memory), + signatures_(memory), + signature_order_(memory) {} + + /** The maps hold views of their lists' nodes: no copy. */ + basic_identity_cache(const basic_identity_cache&) = delete; + /** Not assignable either. */ + basic_identity_cache& operator=(const basic_identity_cache&) = delete; + + /** Frees every record and signature. */ + ~basic_identity_cache() = default; + + /** + * The record of a compact key, 0.27.0's `getVerifiedPubKeyRecord`: the cached one, made the + * most recently used, or a new one when the text is compact + * (`protocol::parse_compact_public_key`) and its point is on the curve, which evicts the least + * recently used record once + * @ref max_records are kept. A refused text is not remembered. + * + * @param compact The key's compact text. + * @return The record, valid until a later call of this cache adds a record; nullptr when the + * text or its point is refused. + */ + [[nodiscard]] const key_record* record(std::string_view compact) { + if (const auto it = records_.find(compact); it != records_.end()) { + record_order_.splice(record_order_.begin(), record_order_, it->second); + return &*it->second; + } + const auto point = protocol::parse_compact_public_key(compact, memory_); + if (!point) { + return nullptr; + } + auto key = protocol::p256_public_key(*point); + if (!key) { + return nullptr; + } + if (record_order_.size() >= max_records) { + records_.erase(record_order_.back().compact); + record_order_.pop_back(); + } + record_order_.push_front(key_record{ + .key = *key, + .compact = std::pmr::string(compact, memory_), + .peer_id = protocol::derive_peer_id(compact, memory_), + .user_id = protocol::derive_user_id(compact, memory_), + }); + records_.emplace(record_order_.front().compact, record_order_.begin()); + return &record_order_.front(); + } + + /** + * Whether a signature is the key's, of the payload, 0.27.0's `verifyWithP256`: 64 bytes, low S + * (refused before any verification, by the cache itself), by the key of a record + * (@ref record). + * + * A payload of at most @ref max_cached_payload_bytes is first looked up: when the key and the + * signature were verified before, the answer is whether the payload is the one they signed, + * without verifying, and they become the most recently used. Otherwise it is verified, and a + * signature that verifies is kept with a copy of its payload, the least recently used leaving + * while @ref max_signatures are kept or the payloads would exceed @ref max_signature_bytes. A + * longer payload is verified each time and never kept. + * + * @param compact The signer's compact key. + * @param signature The signature, r then s. + * @param payload The bytes signed. + * @return Whether the signature is the key's, of `payload`. + */ + [[nodiscard]] bool verify(std::string_view compact, std::span signature, + std::span payload) { + if (signature.size() != std::tuple_size_v) { + return false; + } + const key_record* const rec = record(compact); + if (rec == nullptr) { + return false; + } + // Only the signature cache is touched from here to the end, so `rec` stays valid; a call of + // record() in between could evict it. + if (payload.size() > max_cached_payload_bytes) { + return protocol::is_low_s(signature) && verifier_(signature, payload, rec->key); + } + const signature_key key = key_of(rec->compact, signature); + const std::string_view key_text(key.data(), key.size()); + if (const auto it = signatures_.find(key_text); it != signatures_.end()) { + signature_order_.splice(signature_order_.begin(), signature_order_, it->second); + return std::ranges::equal(it->second->payload, payload); + } + if (!protocol::is_low_s(signature) || !verifier_(signature, payload, rec->key)) { + return false; + } + while (signature_order_.size() >= max_signatures || + (!signature_order_.empty() && + signature_bytes_ + payload.size() > max_signature_bytes)) { + signature_bytes_ -= signature_order_.back().payload.size(); + signatures_.erase(std::string_view(signature_order_.back().key.data(), + signature_order_.back().key.size())); + signature_order_.pop_back(); + } + signature_order_.push_front(signature_entry{ + .key = key, + .payload = std::pmr::vector(payload.begin(), payload.end(), memory_), + }); + signatures_.emplace(std::string_view(signature_order_.front().key.data(), + signature_order_.front().key.size()), + signature_order_.begin()); + signature_bytes_ += payload.size(); + return true; + } + + /** + * Whether a peer id is the one a key derives, 0.27.0's `verifyPeerIdKey`: an empty id is + * refused before any lookup. + * + * @param peer_id The id claimed. + * @param compact The key's compact text. + * @return Whether the key's record exists and derives `peer_id`. + */ + [[nodiscard]] bool verify_peer_id(std::string_view peer_id, std::string_view compact) { + if (peer_id.empty()) { + return false; + } + const key_record* const rec = record(compact); + return rec != nullptr && rec->peer_id == peer_id; + } + + /** + * Whether a user id is the one a key derives, 0.27.0's `verifyUserIdKey`: an id that is not + * `protocol::user_id_size` base62 characters (its `userIdRegex`) is refused before any lookup. + * + * @param user_id The id claimed. + * @param compact The key's compact text. + * @return Whether the key's record exists and derives `user_id`. + */ + [[nodiscard]] bool verify_user_id(std::string_view user_id, std::string_view compact) { + if (user_id.size() != protocol::user_id_size || + user_id.find_first_not_of(protocol::base62_alphabet) != std::string_view::npos) { + return false; + } + const key_record* const rec = record(compact); + return rec != nullptr && rec->user_id == user_id; + } + + /** How many key records the cache keeps now. */ + [[nodiscard]] std::size_t records() const noexcept { return record_order_.size(); } + + /** Whether the cache keeps the record of `compact`, which this leaves where it is in the + * order of use. */ + [[nodiscard]] bool holds_record(std::string_view compact) const { + return records_.contains(compact); + } + + /** How many verified signatures the cache keeps now. */ + [[nodiscard]] std::size_t signatures() const noexcept { return signature_order_.size(); } + + /** How many payload bytes the verified signatures keep now. */ + [[nodiscard]] std::size_t signature_bytes() const noexcept { return signature_bytes_; } + + /** Whether the cache keeps `signature` as verified by `compact`, which this leaves where it is + * in the order of use. */ + [[nodiscard]] bool holds_signature(std::string_view compact, + std::span signature) const { + if (compact.size() != compact_size || + signature.size() != std::tuple_size_v) { + return false; + } + const signature_key key = key_of(compact, signature); + return signatures_.contains(std::string_view(key.data(), key.size())); + } + +private: + /** The length of a compact key's text. */ + static constexpr std::size_t compact_size = 87; + /** A signature's key in the cache: the signer's compact text, then the signature's bytes. */ + using signature_key = + std::array>; + + /** A verified signature: its key and a copy of the payload it signs. */ + struct signature_entry { + signature_key key{}; + std::pmr::vector payload; + }; + + /** The key of a compact text of @ref compact_size characters and a signature of 64 bytes. */ + static signature_key key_of(std::string_view compact, std::span signature) { + signature_key key{}; + std::ranges::copy(compact, key.begin()); + std::ranges::transform(signature, key.begin() + compact_size, + [](std::uint8_t byte) { return static_cast(byte); }); + return key; + } + + Verifier verifier_; + std::pmr::memory_resource* memory_; + // By compact text, each key a view of its record's text in the order list, which owns it. + std::pmr::map::iterator, std::less<>> + records_; + // The records, the most recently used first. + std::pmr::list record_order_; + // By key, each a view of its entry's key in the order list, which owns it. + std::pmr::map::iterator, std::less<>> + signatures_; + // The verified signatures, the most recently used first. + std::pmr::list signature_order_; + std::size_t signature_bytes_ = 0; +}; + +/** The cache of an app: its verifications are `protocol::verify_p256`. */ +using identity_cache = basic_identity_cache<>; + +} // namespace webcpp::trystero::detail + +#endif diff --git a/include/webcpp/trystero/detail/identity_handshake.hpp b/include/webcpp/trystero/detail/identity_handshake.hpp new file mode 100644 index 0000000..bee5253 --- /dev/null +++ b/include/webcpp/trystero/detail/identity_handshake.hpp @@ -0,0 +1,375 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_TRYSTERO_DETAIL_IDENTITY_HANDSHAKE_HPP +#define WEBCPP_TRYSTERO_DETAIL_IDENTITY_HANDSHAKE_HPP + +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::detail { + +/** + * This side of a handshake: its endpoint key and the user it presents. + * + * It refers to what the app holds, which outlives every handshake of its rooms. + */ +struct local_identity { + /** The endpoint's key pair, which signs the transcript. */ + const webcpp::crypto::curves::p256::keypair& endpoint; + /** The endpoint's peer id. */ + std::string_view peer_id; + /** The endpoint's compact public key, sent as `pk`. */ + std::string_view endpoint_key; + /** The user presented, whose id and key are sent as `uid` and `uk` and who signs the + * transcript. */ + const user_identity& user; +}; + +/** + * One side's run of 0.27.0's identity handshake with one remote peer, `createIdentityHandshake`'s + * `run`, as a synchronous step machine: the room calls @ref start once, then @ref receive with each + * `\@_hsdata` payload of the peer, and sends what each returns. + * + * The initiator sends step 1 (its nonce, fingerprints, user id, endpoint and user keys), the + * responder answers step 2 (its own, and its two signatures of the transcript), and the initiator, + * once they verify, signs the transcript too and sends step 3. Each step's `pk` must derive the + * remote peer's id and its `uk` the `uid` claimed, through the app's @ref identity_cache, whose + * cache also verifies the signatures. + * + * Tip: 0.27.0's `onVerified`, which its roles plugin uses to check bans, runs between the + * initiator's verification and its step 3; this port has no roles plugin (Phase 3), so the + * initiator reports the remote's identity and its step 3 at once. + */ +class identity_handshake { +public: + /** The remote side's identity, verified: 0.27.0's `VerifiedPeerIdentity`. */ + struct verified { + /** Its user id. */ + std::pmr::string user_id; + /** Its endpoint's compact public key. */ + std::pmr::string endpoint_key; + /** Its user's compact public key. */ + std::pmr::string user_key; + }; + + /** What a call of the machine gives the room. */ + struct outcome { + /** An `\@_hsdata` payload to send, or empty. */ + std::pmr::string send; + /** The remote's identity once verified; then the run is over. */ + std::optional done; + /** A `protocol::handshake_reason` when the run failed, then over; empty otherwise. */ + std::string_view failure; + }; + + /** + * A run that has not started. + * + * @param self This side's endpoint and user, which outlive the run. + * @param cache The app's identity cache, which outlives the run. + * @param app_id The app's id. + * @param room_id The room's id. + * @param remote_peer The remote peer's id. + * @param initiator Whether this side starts, 0.27.0's `selfId < remotePeerId`. + * @param local_dtls The fingerprints of this side's description. + * @param remote_dtls The fingerprints of the remote description this side applied. + * @param nonce_random 16 random bytes, this side's nonce once a version 4 UUID. + * @param memory The resource of the run's texts and of what it returns. + */ + identity_handshake(local_identity self, identity_cache& cache, std::string_view app_id, + std::string_view room_id, std::string_view remote_peer, bool initiator, + std::span local_dtls, + std::span remote_dtls, + std::array nonce_random, std::pmr::memory_resource* memory) + : self_(self), + cache_(&cache), + memory_(memory), + app_id_(app_id, memory), + room_id_(room_id, memory), + remote_peer_(remote_peer, memory), + local_dtls_(local_dtls.begin(), local_dtls.end(), memory), + remote_dtls_(remote_dtls.begin(), remote_dtls.end(), memory), + nonce_(memory), + transcript_(memory), + remote_{ + .user_id = std::pmr::string(memory), + .endpoint_key = std::pmr::string(memory), + .user_key = std::pmr::string(memory), + }, + initiator_(initiator) { + const auto uuid = protocol::uuid_v4(nonce_random); + nonce_.assign(uuid.data(), uuid.size()); + } + + /** + * Starts the run: it fails with `dtls_missing` when either description has no fingerprint; + * else the initiator sends step 1, and the responder waits for it. + * + * @return Step 1 to send (initiator), nothing (responder), or the failure. + */ + outcome start() { + if (stage_ != stage::idle) { + return nothing(); + } + if (local_dtls_.empty() || remote_dtls_.empty()) { + return fail(protocol::handshake_reason::dtls_missing); + } + if (!initiator_) { + stage_ = stage::awaiting_step_1; + return nothing(); + } + stage_ = stage::awaiting_step_2; + auto out = nothing(); + out.send = write_claims(1, nullptr); + return out; + } + + /** + * Takes the remote's next `\@_hsdata` payload: step 1 (responder), step 2 (initiator) or step 3 + * (responder). Before @ref start and once the run is over, it takes nothing. + * + * @param json The payload. + * @return What to send, the remote's identity once verified, or the failure. + */ + outcome receive(std::string_view json) { + switch (stage_) { + case stage::awaiting_step_1: return receive_step_1(json); + case stage::awaiting_step_2: return receive_step_2(json); + case stage::awaiting_step_3: return receive_step_3(json); + case stage::idle: + case stage::finished: break; + } + return nothing(); + } + +private: + enum class stage : std::uint8_t { + idle, + awaiting_step_1, + awaiting_step_2, + awaiting_step_3, + finished, + }; + + /** The two signatures of the transcript, base64url. */ + struct signatures { + std::pmr::string endpoint; + std::pmr::string user; + }; + + /** An outcome with nothing in it, in the run's resource. */ + [[nodiscard]] outcome nothing() const { + return outcome{.send = std::pmr::string(memory_), .done = std::nullopt, .failure = {}}; + } + + /** Ends the run with `reason`. */ + outcome fail(std::string_view reason) { + stage_ = stage::finished; + auto out = nothing(); + out.failure = reason; + return out; + } + + /** Ends the run with the remote's identity, and `send` to send. */ + outcome succeed(std::pmr::string send) { + stage_ = stage::finished; + auto out = nothing(); + out.send = std::move(send); + out.done.emplace(std::move(remote_)); + return out; + } + + /** This side's step 1 or 2, 0.27.0's `sendClaims`, with `signed_by` at step 2. */ + [[nodiscard]] std::pmr::string write_claims(int step, const signatures* signed_by) const { + protocol::handshake_claims claims{ + .step = step, + .nonce = std::pmr::string(nonce_, memory_), + .user_id = std::pmr::string(self_.user.user_id(), memory_), + .endpoint_key = std::pmr::string(self_.endpoint_key, memory_), + .user_key = std::pmr::string(self_.user.public_key(), memory_), + .endpoint_signature = std::pmr::string(memory_), + .user_signature = std::pmr::string(memory_), + .dtls = std::pmr::vector(local_dtls_, memory_), + }; + if (signed_by != nullptr) { + claims.endpoint_signature = signed_by->endpoint; + claims.user_signature = signed_by->user; + } + return protocol::write_handshake_step(claims, memory_); + } + + /** + * Reads step 1 or 2 and checks its keys, 0.27.0's `parseAndVerifyPeerIdentityClaims`: the + * remote's ids and keys are kept; on failure, the reason. + */ + std::optional read_claims(std::string_view json, int step, + std::string_view& failure) { + auto read = protocol::read_handshake_step(json, step, remote_dtls_, local_dtls_, memory_); + if (!read.claims) { + failure = read.failure; + return std::nullopt; + } + if (!cache_->verify_peer_id(remote_peer_, read.claims->endpoint_key) || + !cache_->verify_user_id(read.claims->user_id, read.claims->user_key)) { + failure = protocol::handshake_reason::identity; + return std::nullopt; + } + remote_.user_id = read.claims->user_id; + remote_.endpoint_key = read.claims->endpoint_key; + remote_.user_key = read.claims->user_key; + return std::move(read.claims); + } + + /** The remote fingerprints the transcript holds, 0.27.0's `resolveRemoteDtls`: the + * description's when known, else those claimed. */ + [[nodiscard]] std::span remote_dtls_for( + const protocol::handshake_claims& claims) const noexcept { + if (!remote_dtls_.empty()) { + return remote_dtls_; + } + return claims.dtls; + } + + /** The transcript's bytes. */ + [[nodiscard]] std::span transcript_bytes() const noexcept { + return {reinterpret_cast(transcript_.data()), transcript_.size()}; + } + + /** Signs the transcript by the endpoint and by the user, 0.27.0's `signTranscript`. */ + [[nodiscard]] std::optional sign() const { + const auto endpoint = protocol::sign_p256(self_.endpoint, transcript_bytes()); + const auto user = self_.user.sign(transcript_bytes()); + if (!endpoint || !user) { + return std::nullopt; + } + return signatures{ + .endpoint = protocol::to_base64url(*endpoint, memory_), + .user = protocol::to_base64url(*user, memory_), + }; + } + + /** Whether the remote's two signatures verify over the transcript, 0.27.0's + * `verifyTranscriptDualSignatures`, by the keys of its step 1 or 2. */ + [[nodiscard]] bool verify(std::string_view endpoint_signature, + std::string_view user_signature) const { + // 0.27.0 reads a signature with its loose fromBase64Url; this reading is strict (design + // D18), so a text it would not write is refused as a signature that does not verify. + const auto endpoint = protocol::from_base64url(endpoint_signature, memory_); + const auto user = protocol::from_base64url(user_signature, memory_); + return endpoint && user && + cache_->verify(remote_.endpoint_key, *endpoint, transcript_bytes()) && + cache_->verify(remote_.user_key, *user, transcript_bytes()); + } + + /** The responder takes step 1, signs the transcript and answers step 2. */ + outcome receive_step_1(std::string_view json) { + std::string_view failure; + const auto claims = read_claims(json, 1, failure); + if (!claims) { + return fail(failure); + } + transcript_ = protocol::handshake_transcript( + app_id_, room_id_, remote_peer_, self_.peer_id, claims->nonce, nonce_, + remote_dtls_for(*claims), local_dtls_, claims->user_id, self_.user.user_id(), memory_); + const auto signed_by = sign(); + if (!signed_by) { + // Our own key could not sign, not a fault of the peer's; 0.27.0 fails the run with + // WebCrypto's error. A key webcpp::crypto made always signs, so the reason that blames + // the peer here only stands for a case that cannot happen. + return fail(protocol::handshake_reason::identity); + } + stage_ = stage::awaiting_step_3; + auto out = nothing(); + out.send = write_claims(2, &*signed_by); + return out; + } + + /** The initiator takes step 2, verifies its signatures, and ends with step 3. */ + outcome receive_step_2(std::string_view json) { + std::string_view failure; + const auto claims = read_claims(json, 2, failure); + if (!claims) { + return fail(failure); + } + transcript_ = protocol::handshake_transcript( + app_id_, room_id_, self_.peer_id, remote_peer_, nonce_, claims->nonce, local_dtls_, + remote_dtls_for(*claims), self_.user.user_id(), claims->user_id, memory_); + if (!verify(claims->endpoint_signature, claims->user_signature)) { + return fail(protocol::handshake_reason::identity); + } + const auto signed_by = sign(); + if (!signed_by) { + // Our own key could not sign, not a fault of the peer's; 0.27.0 fails the run with + // WebCrypto's error. A key webcpp::crypto made always signs, so the reason that blames + // the peer here only stands for a case that cannot happen. + return fail(protocol::handshake_reason::identity); + } + const protocol::handshake_claims step_3{ + .step = 3, + .nonce = std::pmr::string(memory_), + .user_id = std::pmr::string(memory_), + .endpoint_key = std::pmr::string(memory_), + .user_key = std::pmr::string(memory_), + // In the run's resource: a std::pmr::string's copy takes the default one. + .endpoint_signature = std::pmr::string(signed_by->endpoint, memory_), + .user_signature = std::pmr::string(signed_by->user, memory_), + .dtls = std::pmr::vector(memory_), + }; + return succeed(protocol::write_handshake_step(step_3, memory_)); + } + + /** The responder takes step 3 and verifies its signatures. */ + outcome receive_step_3(std::string_view json) { + const auto read = protocol::read_handshake_step(json, 3, {}, {}, memory_); + if (!read.claims) { + return fail(read.failure); + } + if (!verify(read.claims->endpoint_signature, read.claims->user_signature)) { + return fail(protocol::handshake_reason::identity); + } + return succeed(std::pmr::string(memory_)); + } + + local_identity self_; + identity_cache* cache_; + std::pmr::memory_resource* memory_; + std::pmr::string app_id_; + std::pmr::string room_id_; + std::pmr::string remote_peer_; + std::pmr::vector local_dtls_; + std::pmr::vector remote_dtls_; + // This side's nonce, a version 4 UUID. + std::pmr::string nonce_; + // The transcript both sides sign, once the remote's nonce is known. + std::pmr::string transcript_; + // The remote's ids and keys, once its step 1 or 2 is read. + verified remote_; + bool initiator_; + stage stage_ = stage::idle; +}; + +} // namespace webcpp::trystero::detail + +#endif diff --git a/include/webcpp/trystero/detail/nostr_strategy.hpp b/include/webcpp/trystero/detail/nostr_strategy.hpp index 0fa4443..62ea5c8 100644 --- a/include/webcpp/trystero/detail/nostr_strategy.hpp +++ b/include/webcpp/trystero/detail/nostr_strategy.hpp @@ -20,6 +20,7 @@ #include +#include #include #include #include @@ -34,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -129,17 +131,32 @@ class recent_event_ids { }; /** - * Trystero's Nostr strategy: one subscription per relay to the room's root and self topics, - * announcements on the root topic at Trystero's cadence, and signals published on the relay that - * carried the message they answer. + * Trystero's Nostr strategy, as 0.27.0's `\@trystero-p2p/nostr` runs it: subscriptions on each + * relay to the room's topics, announcements on the root topic at Trystero's cadence, and signals + * published on the relay that carried the message they answer, every event signed with the room's + * own key. * * | Rule | Value | - * | announce cadence | at once, then after 233, 533, 1333 and 5333 ms, then every 60 s | - * | rate-limited relay | skipped for 60 s, doubling to 15 min, while "rate-limited:" replies | - * | | persist | - * | terminal rejection | "blocked:", "restricted:", "auth-required:" or "pow:" retires the relay | + * | signer | one per room, made on its first event, dropped when the room stops | + * | announce cadence | at once, then after 233, 533, 1333 and 5333 ms, then every 60 s; each | + * | | announcement with a fresh nonce; one the relay cannot take now is | + * | | skipped, and the cadence goes on | + * | subscription | at most 250 topics per REQ, since a minute ago | + * | relay health | healthy; cooldown 60 s, doubling to 15 min, on "rate-limited:"; then | + * | | probation, which an accepted event ends; retired on "blocked:", | + * | | "restricted:", "auth-required:" or "pow:" | + * | slow subscription | an EOSE 1 s or more after the REQ replays the announcements | + * | closed subscription| asked again after 5333 ms, doubling to 60 s, or after the cooldown | * | reconnect | after a random share of 3.3 s, doubling to 60 s; back to 3.3 s once a | * | | connection stayed open for 60 s | + * | reopened relay | its subscriptions asked again and the announcement replayed once, or | + * | | both after its cooldown; the cadence is not started over | + * | every relay failed | reported once, as 0.27.0 reports `relay-failed`: when each relay's | + * | | first connection closed before it opened and none opened yet; or when | + * | | no relay's first announcement was written and each relay either failed | + * | | so or had its first announcement fail, unsigned or unwritten | + * | offline | every socket closed, no reconnection; the cadence goes on, skipping | + * | online | each relay not connected connects at once, its delay bound back to 3.3 s | * * Tip: the bound of the reconnection delay comes back down only after a connection that lasted, * so that a relay that closes us at once after each open, as one that sends a text longer than we @@ -156,19 +173,27 @@ class nostr_strategy : public std::enable_shared_from_this { using message_handler = handler; - /** Every allocation goes through `memory`, the parsed relay messages' documents included. */ + /** The text of an announcement, given the nonce the strategy drew for it, as Trystero adds a + * `nonce` to the announcement's payload each time it publishes it. */ + using announcement_handler = handler; + + /** Every allocation goes through `memory`, the parsed relay messages' documents included; + * `all_failed`, when set, is called once every relay failed (see the table), at most once, with + * the text of the failure that settled it, empty when it has none (a relay that did not + * open). */ nostr_strategy(backend::factory& factory, std::span urls, std::pmr::vector topics, std::string_view announce_topic, - handler announcement, message_handler on_message, logger log, - std::pmr::memory_resource* memory) + announcement_handler announcement, message_handler on_message, logger log, + std::pmr::memory_resource* memory, + handler all_failed = {}) : factory_(factory), memory_(memory), topics_(std::move(topics), memory), announce_topic_(announce_topic, memory), announcement_(std::move(announcement)), on_message_(std::move(on_message)), + all_failed_(std::move(all_failed)), log_(std::move(log)), - signer_(make_signer(factory, memory)), relays_(memory), seen_(remembered_events, draw_key(factory), memory) { relays_.reserve(urls.size()); @@ -177,57 +202,127 @@ class nostr_strategy : public std::enable_shared_from_this { } } - /** Connects to every relay; each subscribes and announces once it opens. */ + /** Connects to every relay, unless they are held closed; each subscribes and announces once + * it opens. */ void start() { + started_ = true; for (std::size_t i = 0; i < relays_.size(); ++i) { connect(i); } } - /** Publishes a signal to a peer's topic on one relay, unless that relay is closed or backing - * off; Trystero drops it too. */ - void publish(std::size_t index, std::string_view topic, std::string_view content) { - if (index >= relays_.size()) { + /** + * Closes every relay's socket and holds it closed, reconnecting none until @ref reconnect, + * 0.27.0's `holdRelaySockets`: a socket closed so is no failure, and its close is not + * reported. The announce cadence goes on, each announcement skipped as on a closed relay. + */ + void hold() { + if (stopped_ || std::exchange(held_, true)) { return; } - const auto& r = relays_[index]; - if (!r.open || backoff_remaining(r) > time_point::duration::zero()) { + log_("nostr", "holding the relays closed"); + for (auto& r : relays_) { + ++r.attempt; // what the closed socket still reports reaches nothing + r.reconnect_timer.reset(); + if (r.subscription_timer) { + r.subscription_timer->cancel(); + } + r.subscription_retry_pending = false; + r.pending.clear(); + r.subscribed = sync::unsynced; + r.open = false; + if (r.socket) { + r.socket->close(); + r.socket.reset(); + } + } + } + + /** + * Connects at once every relay that has no socket, whether held closed or waiting to + * reconnect, each delay bound back at its least, 0.27.0's `reconnectRelaySockets`; a relay + * that opened before subscribes and announces again once it reopens. + */ + void reconnect() { + if (stopped_) { return; } - r.socket->send(event_for(topic, content)); + held_ = false; + if (!started_) { + return; // the room's keys are not there yet: start() connects + } + for (std::size_t i = 0; i < relays_.size(); ++i) { + auto& r = relays_[i]; + r.retry = first_retry; + if (!r.socket) { + r.reconnect_timer.reset(); + connect(i); + } + } } - /** Starts the announce cadence over, as Trystero does when a peer leaves. */ + /** Publishes a signal to a peer's topic on one relay, unless that relay is closed, cooling + * down or retired; Trystero drops it too. */ + void publish(std::size_t index, std::string_view topic, std::string_view content) { + if (index >= relays_.size() || blocked(relays_[index])) { + return; + } + send_event(relays_[index], topic, content); + } + + /** Starts the announce cadence over on each relay where it started, as Trystero's + * `requeueAnnounce` does when a peer leaves. */ void restart_announcements() { for (std::size_t i = 0; i < relays_.size(); ++i) { - relays_[i].announce_attempt = 0; - if (relays_[i].open) { + if (relays_[i].announced) { + relays_[i].announce_attempt = 0; announce(i); } } } + /** Announces nothing from now on, the relays left as they are, as 0.27.0's room cancels its + * announce timers once it starts to leave (strategy.ts's onBeforeLeave): a peer that hears no + * announcement of a leaving room offers it nothing. */ + void stop_announcing() { + announcing_ = false; + for (auto& r : relays_) { + r.announce_timer.reset(); + } + } + /** How many relays the strategy uses. */ std::size_t relay_count() const { return relays_.size(); } /** The ids of the events it acted on, which it remembers to drop their repeats. */ [[nodiscard]] const recent_event_ids& seen() const { return seen_; } - /** Stops announcing and reconnecting, closes each subscription and each connection. */ + /** The room's signer, which the strategy makes at its first event and drops when it stops; + * null before the one and after the other. */ + [[nodiscard]] const protocol::nostr::signer* current_signer() const { + return signer_ ? &*signer_ : nullptr; + } + + /** Stops announcing and reconnecting, closes each subscription and each connection, and drops + * the room's signer. */ void stop() { stopped_ = true; for (auto& r : relays_) { r.announce_timer.reset(); r.reconnect_timer.reset(); + r.subscription_timer.reset(); if (r.socket) { if (r.open) { - r.socket->send(protocol::nostr::close_message(r.subscription, memory_)); + for (const auto& id : r.subscriptions) { + r.socket->send(protocol::nostr::close_message(id, memory_)); + } } r.socket->close(); r.socket.reset(); } r.open = false; } + signer_.reset(); } private: @@ -238,55 +333,103 @@ class nostr_strategy : public std::enable_shared_from_this { std::chrono::milliseconds(1333), std::chrono::milliseconds(5333), }; - /** The delay between announcements after the warm-up, and a rate-limited relay's first pause: + /** The delay between announcements after the warm-up, and a relay's first cooldown: * Trystero's `steadyAnnounceIntervalMs`. */ static constexpr auto steady_announce = std::chrono::milliseconds(60'000); - /** The longest pause of a rate-limited relay, Trystero's `maxRelayBackoffMs`. */ + /** The longest cooldown of a relay, Trystero's `maxRelayBackoffMs`. */ static constexpr auto max_backoff = std::chrono::milliseconds(15 * 60'000); /** The first bound of the reconnection delay, Trystero's `defaultRetryMs`. */ static constexpr auto first_retry = std::chrono::milliseconds(3333); /** The largest bound of the reconnection delay, Trystero's `maxRetryMs`. */ static constexpr auto max_retry = std::chrono::milliseconds(60'000); /** How long a connection stays open before the reconnection bound comes back down. */ - static constexpr auto healthy = std::chrono::milliseconds(60'000); - /** The least delay before a closed subscription is made again, Trystero's - * `subscriptionRetryMs`. */ + static constexpr auto healthy_connection = std::chrono::milliseconds(60'000); + /** The least delay before a closed subscription is asked for again, Trystero's + * `subscriptionRetryMs`; it doubles up to @ref steady_announce. */ static constexpr auto subscription_retry = std::chrono::milliseconds(5333); - static constexpr std::size_t subscription_id_size = 64; + /** How late an EOSE may come before the strategy announces again, as Trystero does once its + * subscriptions are slow to install. */ + static constexpr auto slow_eose = std::chrono::milliseconds(1000); + + /** A relay's health, Trystero's `RelayHealthState`. */ + enum class health { + /** Nothing refused. */ + healthy, + /** Rate-limited: nothing is published until `cooldown_until`. */ + cooldown, + /** A cooldown ended: an accepted event makes the relay healthy, another rate limit cools + * it down for twice as long. */ + probation, + /** Refused for good: never used again. */ + retired, + }; + + /** How a relay's first announcement went, 0.27.0's `InitialAnnounceOutcome`. */ + enum class first_announcement { + /** Not made yet. */ + pending, + /** Written, or skipped because the relay could not take it then, which 0.27.0's + * `publishTopic` returns from without failing. */ + succeeded, + /** It could not be signed or written. */ + failed, + }; + + /** Where a relay's subscriptions are, Trystero's `BatchSyncState`. */ + enum class sync { + /** Not asked for, or closed by the relay. */ + unsynced, + /** Asked for: the relay has not ended the stored events of each yet. */ + awaiting_eose, + /** The relay sent an EOSE for each. */ + synced, + }; struct relay_state { relay_state(std::string_view address, std::pmr::memory_resource* memory) - : url(address, memory), subscription(memory) {} + : url(address, memory), subscriptions(memory), pending(memory) {} std::pmr::string url; + // The socket, from its connection until it closes; null meanwhile. std::shared_ptr socket; - std::pmr::string subscription; + // Which connection the socket's handlers report: one a hold closed reports nothing. + std::uint64_t attempt = 0; + // The ids of the subscriptions, one per max_topics_per_subscription topics, kept across + // reconnections, as Trystero's batcher keeps its subIds. + std::pmr::vector subscriptions; bool open = false; - bool retired = false; bool opened_before = false; - // How many announcements went out since the cadence started, which picks the next delay. + // Whether its first connection closed before it opened, 0.27.0's `boot-failed`. + bool boot_failed = false; + // How many announcements the cadence made since it started, sent or skipped, which picks + // the next delay. std::size_t announce_attempt = 0; - // The pause of a rate-limited relay, zero when it is not, and when it ends. - std::chrono::milliseconds backoff{}; - time_point backoff_until{}; + // Whether the announce cadence started on this relay: a reopening or an EOSE that came late + // then replays the announcement. + bool announced = false; + // How the cadence's first announcement went, and how many of its announcements in a row + // failed since one was written. + first_announcement initial = first_announcement::pending; + std::size_t announce_errors = 0; + health state = health::healthy; + // The cooldown's length, which a probation remembers as its last. + std::chrono::milliseconds cooldown{}; + time_point cooldown_until{}; + sync subscribed = sync::unsynced; + // The subscriptions still awaiting their EOSE, and when they were asked for. + std::pmr::vector pending; + time_point requested{}; + // The delay before a closed subscription is asked for again, and whether that is pending. + std::chrono::milliseconds subscription_delay = subscription_retry; + bool subscription_retry_pending = false; // The bound of the next reconnection delay. std::chrono::milliseconds retry = first_retry; time_point opened{}; std::shared_ptr announce_timer; std::shared_ptr reconnect_timer; + std::shared_ptr subscription_timer; }; - static protocol::nostr::signer make_signer(backend::factory& factory, - std::pmr::memory_resource* memory) { - std::array secret{}; - for (;;) { - factory.random(secret); - if (auto s = protocol::nostr::signer::from_secret(secret, memory)) { - return std::move(*s); - } - } - } - static std::array draw_key( backend::factory& factory) { std::array key{}; @@ -296,24 +439,70 @@ class nostr_strategy : public std::enable_shared_from_this { std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } - std::pmr::string event_for(std::string_view topic, std::string_view content) { - std::array aux{}; - factory_.random(aux); - return protocol::nostr::event_message(signer_, unix_now(factory_), topic, content, aux, - memory_); + /** The room's signer, made at its first event, as Trystero's `getRoomSigner`; null, logged, + * when it cannot be made. */ + const protocol::nostr::signer* room_signer() { + if (!signer_) { + auto made = protocol::nostr::signer::generate(memory_); + if (!made) { + log_("nostr", "cannot make the room's signing key: ", made.error()); + return nullptr; + } + signer_.emplace(std::move(*made)); + } + return &*signer_; } - /** How long `r` still pauses, being rate-limited; zero when it does not. */ - time_point::duration backoff_remaining(const relay_state& r) const { - return std::max(time_point::duration::zero(), r.backoff_until - steady_now(factory_)); + /** Signs an event of `content` on `topic` and sends it on `r`; one that cannot be signed is + * logged and dropped. The text of the failure, empty when the event was signed and its socket + * took it: as 0.27.0's `toErrorMessage(cause, ...)`, a signing failure carries its own text, + * and a socket that cannot queue the text, which 0.27.0 does not know, the port's. */ + std::pmr::string send_event(relay_state& r, std::string_view topic, std::string_view content) { + const auto* key = room_signer(); + if (key == nullptr) { + return {"cannot make the room's signing key", memory_}; + } + const auto message = + protocol::nostr::event_message(*key, unix_now(factory_), topic, content, memory_); + if (!message) { + log_("nostr", "cannot sign an event: ", message.error()); + return std::pmr::string(message.error().message(), memory_); + } + if (!r.socket->send(*message)) { + return {"the relay's connection cannot take the event", memory_}; + } + return std::pmr::string(memory_); + } + + /** `r`'s health now: a cooldown that ended is a probation, as `getRelayHealth` reads it. */ + health health_of(relay_state& r) const { + if (r.state == health::cooldown && steady_now(factory_) >= r.cooldown_until) { + r.state = health::probation; + } + return r.state; + } + + /** How long `r` still cools down; zero when it does not. */ + time_point::duration cooldown_remaining(relay_state& r) const { + if (health_of(r) != health::cooldown) { + return time_point::duration::zero(); + } + return std::max(time_point::duration::zero(), r.cooldown_until - steady_now(factory_)); + } + + /** Whether nothing is published on `r` now, Trystero's `getPublishBlockedResult`. */ + bool blocked(relay_state& r) const { + return !r.open || health_of(r) == health::retired || + cooldown_remaining(r) > time_point::duration::zero(); } void connect(std::size_t index) { - if (stopped_ || relays_[index].retired) { + if (stopped_ || held_ || relays_[index].state == health::retired) { return; } const auto weak = weak_from_this(); const auto a = allocator(); + const auto attempt = ++relays_[index].attempt; relays_[index].socket = factory_.connect(relays_[index].url, { @@ -321,8 +510,9 @@ class nostr_strategy : public std::enable_shared_from_this { { std::allocator_arg, a, - [weak, index] { - if (const auto self = weak.lock()) { + [weak, index, attempt] { + if (const auto self = weak.lock(); + self && self->current(index, attempt)) { self->on_open(index); } }, @@ -331,8 +521,9 @@ class nostr_strategy : public std::enable_shared_from_this { { std::allocator_arg, a, - [weak, index](std::string_view text) { - if (const auto self = weak.lock()) { + [weak, index, attempt](std::string_view text) { + if (const auto self = weak.lock(); + self && self->current(index, attempt)) { self->on_relay_message(index, text); } }, @@ -341,8 +532,9 @@ class nostr_strategy : public std::enable_shared_from_this { { std::allocator_arg, a, - [weak, index] { - if (const auto self = weak.lock()) { + [weak, index, attempt] { + if (const auto self = weak.lock(); + self && self->current(index, attempt)) { self->on_close(index); } }, @@ -351,35 +543,147 @@ class nostr_strategy : public std::enable_shared_from_this { memory_); } + /** Whether `attempt` is the connection of relay `index` now. */ + [[nodiscard]] bool current(std::size_t index, std::uint64_t attempt) const { + return relays_[index].attempt == attempt; + } + void on_open(std::size_t index) { auto& r = relays_[index]; r.open = true; + any_opened_ = true; r.opened = steady_now(factory_); - if (r.subscription.empty()) { - r.subscription = random_id(factory_, subscription_id_size, memory_); - } - r.socket->send(protocol::nostr::subscribe_message(r.subscription, topics_, - unix_now(factory_), memory_)); - log_("nostr", r.opened_before ? "reconnected to " : "connected to ", r.url, - ", subscribed to the room's topics"); - r.opened_before = true; + log_("nostr", r.opened_before ? "reconnected to " : "connected to ", r.url); + if (std::exchange(r.opened_before, true)) { + // Trystero's resubscribeOnReconnect: the cadence that started at the first opening + // goes on, and the relay gets the subscriptions and the announcement once, after its + // cooldown when it still cools down. + resubscribe(index); + return; + } + subscribe(index); r.announce_attempt = 0; announce(index); } + /** + * Asks `r` for the room's topics, Trystero's `flushBatch`: one REQ per + * `max_topics_per_subscription` topics, under the ids the relay's subscriptions had, since a + * minute ago; each then awaits its EOSE. + */ + void subscribe(std::size_t index) { + auto& r = relays_[index]; + if (r.subscription_timer) { + r.subscription_timer->cancel(); + } + r.subscription_retry_pending = false; + constexpr std::size_t chunk = protocol::nostr::max_topics_per_subscription; + const std::size_t requests = (topics_.size() + chunk - 1) / chunk; + // The topics are the strategy's for its whole life, so the subscriptions never outnumber + // the REQs: Trystero's CLOSE of the surplus ids, for a batcher whose topics leave, has no + // case here. + BOOST_ASSERT(r.subscriptions.size() <= requests); + const auto since = protocol::nostr::subscribe_since(unix_now(factory_)); + r.pending.clear(); + for (std::size_t i = 0; i < requests; ++i) { + if (i == r.subscriptions.size()) { + r.subscriptions.push_back( + random_id(factory_, protocol::subscription_id_size, memory_)); + } + const std::span topics( + topics_.data() + (i * chunk), std::min(chunk, topics_.size() - (i * chunk))); + r.socket->send( + protocol::nostr::subscribe_message(r.subscriptions[i], topics, since, memory_)); + r.pending.push_back(r.subscriptions[i]); + } + r.subscribed = sync::awaiting_eose; + r.requested = steady_now(factory_); + } + + /** Asks `r` for its subscriptions again, unless it still cools down, and replays the room's + * announcement there: Trystero's `resubscribeOnReconnect`. */ + void resubscribe(std::size_t index) { + auto& r = relays_[index]; + if (stopped_ || !r.open || r.state == health::retired) { + return; + } + if (cooldown_remaining(r) > time_point::duration::zero()) { + retry_subscription(index, true); + return; + } + subscribe(index); + replay_announcement(index); + } + + /** + * Asks for `r`'s subscriptions again later, Trystero's `retrySubscription`: after the cooldown + * of a rate-limited relay, otherwise after a delay of 5333 ms that doubles up to 60 s; never + * sooner than 5333 ms. A retry already pending stays, unless the relay rate-limits us. + */ + void retry_subscription(std::size_t index, bool rate_limited) { + auto& r = relays_[index]; + if (!r.open || (r.subscription_retry_pending && !rate_limited)) { + return; + } + const auto delay = + rate_limited + ? std::chrono::duration_cast(cooldown_remaining(r)) + : r.subscription_delay; + r.subscription_delay = std::min(r.subscription_delay * 2, steady_announce); + if (r.subscribed == sync::synced) { + r.subscribed = sync::unsynced; + } + if (!r.subscription_timer) { + r.subscription_timer = factory_.make_timer(memory_); + } + r.subscription_retry_pending = true; + const auto weak = weak_from_this(); + r.subscription_timer->start(std::max(delay, subscription_retry), + {std::allocator_arg, allocator(), [weak, index] { + if (const auto self = weak.lock()) { + self->relays_[index].subscription_retry_pending = + false; + self->resubscribe(index); + } + }}); + } + + /** Publishes the room's announcement on `r` again, with a fresh nonce, outside its cadence, + * as Trystero's `replayAnnouncements` does; only once the room announced there. */ + void replay_announcement(std::size_t index) { + auto& r = relays_[index]; + if (!announcing_ || !r.announced || blocked(r)) { + return; + } + send_event(r, announce_topic_, announcement()); + } + + /** The announcement's text, with a nonce of `protocol::nonce_size` characters drawn now. */ + std::pmr::string announcement() { + const auto nonce = random_id(factory_, protocol::nonce_size, memory_); + return announcement_(nonce); + } + void on_close(std::size_t index) { auto& r = relays_[index]; const bool was_open = r.open; r.open = false; - r.announce_timer.reset(); - if (stopped_ || r.retired) { + r.socket.reset(); + if (stopped_ || r.state == health::retired) { return; } - if (was_open && steady_now(factory_) - r.opened >= healthy) { + if (was_open && steady_now(factory_) - r.opened >= healthy_connection) { r.retry = first_retry; } log_("nostr", was_open ? "lost " : "could not reach ", r.url, ", next attempt within ", r.retry.count(), " ms"); + if (!r.opened_before && !std::exchange(r.boot_failed, true)) { + report_if_all_boot_failed(); + // The report reaches the user's log sink, which may leave the room and so stop this. + if (stopped_) { + return; + } + } std::array random{}; factory_.random(random); // A share of the bound in [0, 1), in steps of 1/65536, and the delay in whole @@ -397,22 +701,92 @@ class nostr_strategy : public std::enable_shared_from_this { }}); } + /** Reports every relay failed, when no relay opened yet and the first connection of every + * relay closed before it opened, as 0.27.0's `maybeReportAllBootFailed` reports + * `relay-failed`. */ + void report_if_all_boot_failed() { + if (any_opened_ || relays_.empty() || + !std::ranges::all_of(relays_, [](const relay_state& r) { return r.boot_failed; })) { + return; + } + report_all_failed({}); + } + + /** Reports every relay failed, when no relay's first announcement succeeded and each relay + * either failed to boot or had its first announcement settled, as 0.27.0's `queueAnnounce` + * reports `relay-failed` once an initial announcement fails. */ + void report_if_no_first_announcement(std::string_view cause) { + const auto succeeded = [](const relay_state& r) { + return r.initial == first_announcement::succeeded; + }; + const auto settled = [](const relay_state& r) { + return r.boot_failed || r.initial != first_announcement::pending; + }; + if (relays_.empty() || std::ranges::any_of(relays_, succeeded) || + !std::ranges::all_of(relays_, settled)) { + return; + } + report_all_failed(cause); + } + + /** Calls `all_failed` once in the strategy's life, whichever path reports it first, as 0.27.0's + * `reportAllRelaysFailed` reports once per room, with `cause`'s text. */ + void report_all_failed(std::string_view cause) { + if (std::exchange(all_failed_reported_, true)) { + return; + } + log_("nostr", "every relay failed"); + if (all_failed_) { + all_failed_(cause); + } + } + + /** Records how an announcement of the cadence went on `r`, as 0.27.0's `queueAnnounce` does: + * a failure is logged once per run of failures, and a failed first announcement may mean that + * every relay failed, for the reason `failure` gives; empty when it went. */ + void announced_on(std::size_t index, std::string_view failure) { + auto& r = relays_[index]; + const bool first = r.initial == first_announcement::pending; + if (failure.empty()) { + r.announce_errors = 0; + if (first) { + r.initial = first_announcement::succeeded; + } + return; + } + if (r.announce_errors++ == 0) { + log_("nostr", "announce failed on ", r.url); + } + if (first) { + r.initial = first_announcement::failed; + report_if_no_first_announcement(failure); + } + } + void announce(std::size_t index) { auto& r = relays_[index]; - if (stopped_ || r.retired) { + if (stopped_ || !announcing_ || r.state == health::retired) { return; } + r.announced = true; + // As Trystero's queueAnnounce: an announcement the relay cannot take now waits for the + // cooldown, at least 60 s, and the warm-up's delays bound the wait either way. auto next = steady_announce; - if (const auto remaining = backoff_remaining(r); + if (const auto remaining = cooldown_remaining(r); !r.open || remaining > time_point::duration::zero()) { next = std::max(steady_announce, std::chrono::duration_cast(remaining)); + announced_on(index, {}); // skipped, which 0.27.0 counts as no failure } else { - r.socket->send(event_for(announce_topic_, announcement_())); - if (const auto attempt = r.announce_attempt++; attempt < warmup.size()) { - next = warmup[attempt]; + announced_on(index, send_event(r, announce_topic_, announcement())); + // The report reaches the user's log sink, which may leave the room and so stop this. + if (stopped_ || !announcing_) { + return; } } + if (const auto attempt = r.announce_attempt++; attempt < warmup.size()) { + next = std::min(next, warmup[attempt]); + } if (!r.announce_timer) { r.announce_timer = factory_.make_timer(memory_); } @@ -424,13 +798,21 @@ class nostr_strategy : public std::enable_shared_from_this { }}); } + /** Cools `r` down, Trystero's `backoffRelay`: 60 s from health, twice the last cooldown from a + * cooldown or a probation, at most 15 min. */ void back_off(relay_state& r) { - r.backoff = r.backoff == std::chrono::milliseconds::zero() - ? steady_announce - : std::min(std::max(steady_announce, r.backoff * 2), max_backoff); - r.backoff_until = steady_now(factory_) + r.backoff; + switch (health_of(r)) { + case health::retired: return; + case health::healthy: r.cooldown = steady_announce; break; + case health::cooldown: + case health::probation: + r.cooldown = std::min(std::max(steady_announce, r.cooldown * 2), max_backoff); + break; + } + r.state = health::cooldown; + r.cooldown_until = steady_now(factory_) + r.cooldown; log_("nostr", r.url, " rate-limits us, pausing it for ", - std::chrono::duration_cast(r.backoff).count(), " s"); + std::chrono::duration_cast(r.cooldown).count(), " s"); } static bool terminal(std::string_view reason) { @@ -444,17 +826,26 @@ class nostr_strategy : public std::enable_shared_from_this { prefixes, [reason](std::string_view prefix) { return reason.starts_with(prefix); }); } - void retire(std::size_t index, std::string_view reason) { + /** Retires a relay for good, Trystero's `retireRelay`; false when it was retired already. */ + bool retire(std::size_t index, std::string_view reason) { auto& r = relays_[index]; - if (r.retired) { - return; + if (r.state == health::retired) { + return false; } - r.retired = true; + r.state = health::retired; log_("nostr", "retiring ", r.url, ": ", reason); r.announce_timer.reset(); + r.subscription_timer.reset(); + r.subscription_retry_pending = false; if (r.socket) { r.socket->close(); } + return true; + } + + /** Whether `id` is one of `r`'s subscriptions. */ + static bool owns(const relay_state& r, std::string_view id) { + return std::ranges::find(r.subscriptions, id) != r.subscriptions.end(); } void on_relay_message(std::size_t index, std::string_view text) { @@ -469,81 +860,114 @@ class nostr_strategy : public std::enable_shared_from_this { if (!message) { return; } - auto& r = relays_[index]; if (const auto* e = std::get_if(&*message)) { - if (e->subscription != r.subscription || e->topic.empty() || - std::ranges::find(topics_, e->topic) == topics_.end()) { - return; - } - // A repeat is dropped only under an id checked to be its event's own: a relay could - // otherwise send a forged event under a genuine event's id ahead of the relay that - // carries the genuine one, and have the room drop it. - if (protocol::nostr::has_own_id(*e, memory_) && !seen_.remember(e->id)) { - return; - } - on_message_(index, e->topic, e->content); - } else if (const auto* o = std::get_if(&*message)) { - if (o->accepted) { - if (backoff_remaining(r) == time_point::duration::zero()) { - r.backoff = std::chrono::milliseconds::zero(); - } - } else if (o->reason.starts_with("rate-limited:")) { - back_off(r); - } else if (terminal(o->reason)) { - retire(index, o->reason); - } else if (!o->reason.starts_with("duplicate:")) { - log_("nostr", r.url, " refused an event: ", o->reason); - } - } else if (const auto* c = std::get_if(&*message)) { - if (terminal(c->reason)) { - retire(index, c->reason); - return; - } - if (c->reason.starts_with("rate-limited:")) { - back_off(r); - } - log_("nostr", r.url, " closed our subscription: ", c->reason); - resubscribe_later(index); - } else if (const auto* n = std::get_if(&*message)) { + on_event(index, *e); + } else { + on_feedback(index, *message); + } + } + + void on_event(std::size_t index, const protocol::nostr::event& e) { + if (!owns(relays_[index], e.subscription) || e.topic.empty() || + std::ranges::find(topics_, e.topic) == topics_.end()) { + return; + } + // A repeat is dropped only under an id checked to be its event's own: a relay could + // otherwise send a forged event under a genuine event's id ahead of the relay that carries + // the genuine one, and have the room drop it. + if (protocol::nostr::has_own_id(e, memory_) && !seen_.remember(e.id)) { + return; + } + on_message_(index, e.topic, e.content); + } + + /** A relay's OK, EOSE, CLOSED or NOTICE, as 0.27.0's relay handler reads it. */ + void on_feedback(std::size_t index, const protocol::nostr::relay_message& message) { + auto& r = relays_[index]; + const auto* o = std::get_if(&message); + const auto* c = std::get_if(&message); + // A CLOSED of a subscription not ours says nothing of this room's. + if (c != nullptr && !owns(r, c->subscription)) { + return; + } + const bool rejected = o != nullptr && !o->accepted; + std::string_view reason; + if (c != nullptr) { + reason = c->reason; + } else if (o != nullptr) { + reason = o->reason; + } + const bool refused = rejected || c != nullptr; + const bool rate_limited = refused && reason.starts_with("rate-limited:"); + const bool is_terminal = terminal(reason); + if (o != nullptr && o->accepted && health_of(r) == health::probation) { + r.state = health::healthy; + } + if (refused && is_terminal) { + retire(index, reason); + return; + } + if (rate_limited) { + back_off(r); + } else if (const auto* end = std::get_if(&message)) { + on_eose(index, end->subscription); + } + if (c != nullptr) { + retry_subscription(index, rate_limited); + log_("nostr", r.url, " closed our subscription: ", reason); + } else if (rejected && !reason.starts_with("duplicate:")) { + log_("nostr", r.url, " refused an event: ", reason); + } else if (const auto* n = std::get_if(&message)) { log_("nostr", r.url, " notice: ", n->text); } } - void resubscribe_later(std::size_t index) { + /** The end of a subscription's stored events: once the last pending one ends, the relay is + * synced, and one that took 1 s or more gets the room's announcement again. */ + void on_eose(std::size_t index, std::string_view subscription) { auto& r = relays_[index]; - if (!r.reconnect_timer) { - r.reconnect_timer = factory_.make_timer(memory_); + if (r.subscribed != sync::awaiting_eose) { + return; + } + const auto it = std::ranges::find(r.pending, subscription); + if (it == r.pending.end()) { + return; + } + r.pending.erase(it); + if (!r.pending.empty()) { + return; + } + if (r.subscription_timer) { + r.subscription_timer->cancel(); + } + r.subscription_retry_pending = false; + r.subscription_delay = subscription_retry; + r.subscribed = sync::synced; + if (steady_now(factory_) - r.requested >= slow_eose) { + replay_announcement(index); } - const auto delay = - std::max(subscription_retry, - std::chrono::duration_cast(backoff_remaining(r))); - const auto weak = weak_from_this(); - r.reconnect_timer->start(delay, - {std::allocator_arg, allocator(), [weak, index] { - const auto self = weak.lock(); - if (!self || self->stopped_) { - return; - } - const auto& relay = self->relays_[index]; - if (relay.open) { - relay.socket->send(protocol::nostr::subscribe_message( - relay.subscription, self->topics_, - unix_now(self->factory_), self->memory_)); - } - }}); } backend::factory& factory_; std::pmr::memory_resource* memory_; std::pmr::vector topics_; std::pmr::string announce_topic_; - handler announcement_; + announcement_handler announcement_; message_handler on_message_; + handler all_failed_; logger log_; - protocol::nostr::signer signer_; + std::optional signer_; std::pmr::vector relays_; recent_event_ids seen_; bool stopped_ = false; + // Whether the room still announces itself: not once it started to leave. + bool announcing_ = true; + // Whether start() ran, and whether the relays are held closed. + bool started_ = false; + bool held_ = false; + // Whether a relay ever opened, and whether the failure of every relay was reported. + bool any_opened_ = false; + bool all_failed_reported_ = false; }; } // namespace webcpp::trystero::detail diff --git a/include/webcpp/trystero/detail/peer_link.hpp b/include/webcpp/trystero/detail/peer_link.hpp new file mode 100644 index 0000000..8a9f569 --- /dev/null +++ b/include/webcpp/trystero/detail/peer_link.hpp @@ -0,0 +1,392 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_TRYSTERO_DETAIL_PEER_LINK_HPP +#define WEBCPP_TRYSTERO_DETAIL_PEER_LINK_HPP + +#include + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::detail { + +/** + * One room's connection to one remote peer, 0.27.0's peer (`peer.ts`): the negotiated connection + * and its open data channel, whose frames are the room's action frames, written bare + * (`peer-transport.ts`'s `sendFrame`). It lives in the room's resource, and ends with the room or + * with the peer: no other room ever uses it. + * + * | Frame | Done | + * | before `bind`, at most 17 KiB | kept, in order, at most 64, the first starting a 10 s | + * | | deadline | + * | before `bind`, longer, a 65th | the link ends, as 0.27.0's `failData` | + * | or the deadline passed | | + * | after `bind`, at most 64 KiB | to `callbacks::frame` | + * | after `bind`, longer | the link ends, as 0.27.0's `failData` | + * + * The connection's state ends it as 0.27.0's does: `failed` and `closed` at once, `disconnected` + * after a grace of 5 s that a return to `connected` cancels; so does its channel's close. + * + * Tip: its handlers name it weakly, so that a link the room let go reaches nothing; its destructor + * ends nothing and calls nothing, since it may run while the io_context is destroyed. + */ +class peer_link final : public channel_link, public std::enable_shared_from_this { + /** Keeps the constructor for `make`, while `std::allocate_shared` can still call it. */ + struct private_tag { + explicit private_tag() = default; + }; + +public: + /** What a link hands its room once bound. Both are set. */ + struct callbacks { + /** An action frame, in arrival order. */ + handler frame; + /** The link ended, with the reason; called once. */ + handler ended; + }; + + /** The most frames kept before `bind`, 0.27.0's `maxQueuedDataFrames`. */ + static constexpr std::size_t max_pending_frames = protocol::max_queued_data_frames; + /** How long after the first kept frame the link waits for `bind`, 0.27.0's + * `pendingDataTimeoutMs`. */ + static constexpr std::chrono::milliseconds pending_frames_timeout = + protocol::pending_data_timeout; + /** The longest frame kept before `bind`, 0.27.0's `maxRoomFrameBytes`: an action frame and + * its overlay's header. */ + static constexpr std::size_t max_unbound_frame_bytes = protocol::max_room_frame_bytes; + /** The longest frame after `bind`, 0.27.0's `maxBulkFrameBytes`. */ + static constexpr std::size_t max_bound_frame_bytes = protocol::max_bulk_frame_bytes; + /** How long a `disconnected` connection has to come back, 0.27.0's grace. */ + static constexpr std::chrono::milliseconds disconnected_grace{5'000}; + + /** + * A link to `peer` over its negotiated connection and open channel, made in `memory`, the + * room's: it takes over their events at once, keeping every frame until `bind`. + * + * @param peer The remote peer's id, copied. + * @param pc The negotiated connection. + * @param dc Its open data channel. + * @param factory The backend, for the link's timers; it outlives the link. + * @param memory The room's resource, which outlives the link. + * @return The link. + */ + // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on + static std::shared_ptr make(std::string_view peer, + std::shared_ptr pc, + std::shared_ptr dc, + backend::factory& factory, + std::pmr::memory_resource* memory) { + // NOLINTEND(performance-unnecessary-value-param) + auto link = std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), + private_tag{}, peer, std::move(pc), + std::move(dc), factory, memory); + link->start(); + return link; + } + + /** For `make` alone, through its tag. */ + // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on + peer_link(private_tag /*tag*/, std::string_view peer, + std::shared_ptr pc, + std::shared_ptr dc, backend::factory& factory, + std::pmr::memory_resource* memory) + // NOLINTEND(performance-unnecessary-value-param) + : factory_(factory), + memory_(memory), + peer_(peer, memory), + pc_(std::move(pc)), + dc_(std::move(dc)), + pending_(memory), + waiters_(memory), + reason_(memory) {} + + /** A link has one identity and cannot be copied. */ + peer_link(const peer_link&) = delete; + /** A link cannot be replaced by copying. */ + peer_link& operator=(const peer_link&) = delete; + + /** Ends nothing: what it holds goes quietly, its handlers reaching nothing any more. */ + ~peer_link() = default; + + /** The remote peer's id. */ + [[nodiscard]] std::string_view peer() const { return peer_; } + + /** Not ended, and its channel open: 0.27.0's peer not stale. */ + [[nodiscard]] bool live() const { return !ended_ && dc_->is_open(); } + + /** Whether `bind` ran. */ + [[nodiscard]] bool bound() const { return bound_; } + + /** How many frames wait for `bind`. */ + [[nodiscard]] std::size_t pending_count() const { return pending_.size(); } + + /** + * Hands the frames to `cb` from now on, those kept before it first, in their order; a link + * that ended before calls `cb.ended` at once, with its reason. Once. + * + * @param cb The room's callbacks, both set. + */ + void bind(callbacks cb) { + BOOST_ASSERT(cb.frame && cb.ended); + BOOST_ASSERT(!bound_); + bound_ = true; + cb_ = std::move(cb); + if (ended_) { + const std::pmr::string reason(reason_, memory_); + auto ended = std::exchange(cb_.ended, {}); + cb_.frame = {}; + ended(reason); + return; + } + pending_timer_.reset(); + auto frames = std::exchange(pending_, std::pmr::deque(memory_)); + // The room may end the link, or let it go, from inside a frame's call, as 0.27.0 stops + // replaying once its peer is no longer bound. + const auto self = weak_from_this().lock(); + for (auto& frame : frames) { + if (ended_) { + return; + } + cb_.frame(std::move(frame)); + } + } + + /** + * Ends the link, once: the channel and the connection closed, their handlers cleared, the kept + * frames dropped, every drain waiter told `false`, then `callbacks::ended` called, when bound. + * + * @param reason Why, read during the call. + */ + void end(std::string_view reason) { + if (ended_) { + return; + } + ended_ = true; + reason_ = reason; // `reason` may be a view into what the calls below free + const auto self = weak_from_this().lock(); + pending_timer_.reset(); + disconnect_timer_.reset(); + dc_->set_handlers({}); + pc_->set_handlers({}); + dc_->close(); + pc_->close(); + pending_ = std::pmr::deque(memory_); + drained(false); + if (!bound_) { + return; + } + auto ended = std::exchange(cb_.ended, {}); + cb_.frame = {}; + ended(reason_); + } + + /** Sends an action frame as it is; false when the link ended or its channel is not open. */ + bool send(std::span frame) override { + if (!live()) { + return false; + } + dc_->send(frame); + return true; + } + + /** The bytes the channel buffers; 0 once the link ended. */ + [[nodiscard]] std::size_t buffered_amount() const override { + return ended_ ? 0 : dc_->buffered_amount(); + } + + /** `protocol::max_bulk_frame_bytes` when the connection's `max_message_size` is at least that, + * else `protocol::max_action_frame_bytes`, as 0.27.0's getter reads `sctp.maxMessageSize` at + * each transfer. */ + [[nodiscard]] std::size_t max_bulk_frame_bytes() const override { + const auto size = pc_->max_message_size(); + return size && *size >= protocol::max_bulk_frame_bytes ? protocol::max_bulk_frame_bytes + : protocol::max_action_frame_bytes; + } + + /** Calls `done(true)` once the channel buffers at most `data_channel::low_threshold`, at once + * when it does already, or `done(false)` when the link ends first or has ended. */ + void wait_drained(handler done) override { + if (!live()) { + done(false); + return; + } + if (dc_->buffered_amount() <= backend::data_channel::low_threshold) { + done(true); + return; + } + waiters_.push_back(std::move(done)); + } + +private: + /** Takes over the channel's and the connection's events, which replaces the handlers the + * negotiation set. */ + void start() { + const auto weak = weak_from_this(); + const std::pmr::polymorphic_allocator<> allocator(memory_); + dc_->set_handlers({ + .open = {}, + .message = + { + std::allocator_arg, + allocator, + [weak](backend::bytes frame) { + if (const auto self = weak.lock()) { + self->on_frame(std::move(frame)); + } + }, + }, + .close = + { + std::allocator_arg, + allocator, + [weak] { + if (const auto self = weak.lock()) { + self->end("data channel closed"); + } + }, + }, + .buffered_amount_low = + { + std::allocator_arg, + allocator, + [weak] { + if (const auto self = weak.lock()) { + self->drained(true); + } + }, + }, + }); + pc_->set_handlers({ + .ice_candidate = {}, + .data_channel = {}, + .state = + { + std::allocator_arg, + allocator, + [weak](backend::connection_state state) { + if (const auto self = weak.lock()) { + self->on_state(state); + } + }, + }, + }); + } + + /** A frame from the channel, kept or handed over within 0.27.0's bounds (`peer.ts`'s + * `onmessage`). */ + void on_frame(backend::bytes&& frame) { + if (ended_) { + return; + } + if (bound_) { + if (frame.size() > max_bound_frame_bytes) { + fail_data(); + return; + } + cb_.frame(std::move(frame)); + return; + } + if (frame.size() > max_unbound_frame_bytes || pending_.size() >= max_pending_frames) { + fail_data(); + return; + } + pending_.push_back(std::move(frame)); + if (!pending_timer_) { + pending_timer_ = factory_.make_timer(memory_); + pending_timer_->start(pending_frames_timeout, + {std::allocator_arg, std::pmr::polymorphic_allocator<>(memory_), + [weak = weak_from_this()] { + if (const auto self = weak.lock()) { + self->fail_data(); + } + }}); + } + } + + /** 0.27.0's `failData`, which warns "excessive pre-handler data; disconnecting peer". */ + void fail_data() { end("excessive pre-handler data"); } + + /** Ends a failed or closed connection at once, and a disconnected one after its grace, which a + * later disconnection does not extend, as 0.27.0 starts it only from an open connection. */ + void on_state(backend::connection_state state) { + using backend::connection_state; + if (state == connection_state::failed || state == connection_state::closed) { + end(state == connection_state::failed ? "connection failed" : "connection closed"); + } else if (state == connection_state::disconnected) { + if (in_grace_) { + return; + } + if (!disconnect_timer_) { + disconnect_timer_ = factory_.make_timer(memory_); + } + in_grace_ = true; + disconnect_timer_->start( + disconnected_grace, {std::allocator_arg, std::pmr::polymorphic_allocator<>(memory_), + [weak = weak_from_this()] { + if (const auto self = weak.lock()) { + self->in_grace_ = false; + self->end("connection lost"); + } + }}); + } else if (in_grace_) { + in_grace_ = false; + disconnect_timer_->cancel(); + } + } + + /** Gives every waiter of this drain its turn, in the order it began to wait: one that waits + * again from its call waits for the next drain. */ + void drained(bool open) { + // A waiter may let the room release its last reference to the link. + const auto self = weak_from_this().lock(); + const auto count = waiters_.size(); + for (std::size_t i = 0; i < count && !waiters_.empty(); ++i) { + auto waiter = std::move(waiters_.front()); + waiters_.pop_front(); + waiter(open); + } + if (waiters_.empty()) { + // A cleared deque keeps blocks (libc++ keeps up to two): a new one frees them. + waiters_ = std::pmr::deque>(memory_); + } + } + + backend::factory& factory_; + std::pmr::memory_resource* memory_; + std::pmr::string peer_; + std::shared_ptr pc_; + std::shared_ptr dc_; + callbacks cb_; + std::pmr::deque pending_; + std::pmr::deque> waiters_; + std::shared_ptr pending_timer_; + std::shared_ptr disconnect_timer_; + std::pmr::string reason_; + bool bound_ = false; + bool ended_ = false; + /** Whether a disconnection's grace runs on `disconnect_timer_`. */ + bool in_grace_ = false; +}; + +} // namespace webcpp::trystero::detail + +#endif diff --git a/include/webcpp/trystero/detail/random_id.hpp b/include/webcpp/trystero/detail/random_id.hpp index cb982fb..374406a 100644 --- a/include/webcpp/trystero/detail/random_id.hpp +++ b/include/webcpp/trystero/detail/random_id.hpp @@ -10,11 +10,10 @@ #include #include -#include +#include #include -#include #include #include #include @@ -26,15 +25,13 @@ namespace webcpp::trystero::detail { /** The longest id @ref random_id draws: a Nostr subscription's, 64 characters. */ inline constexpr std::size_t max_random_id_size = 64; -/** An id of `n` characters drawn from the backend's randomness, as `protocol::random_id` maps +/** An id of `n` characters drawn from the backend's randomness as @ref protocol::gen_id draws * them, allocated in `memory`; `n` is at most @ref max_random_id_size. */ inline std::pmr::string random_id(backend::factory& factory, std::size_t n, std::pmr::memory_resource* memory) { BOOST_ASSERT(n <= max_random_id_size); - std::array random{}; - const auto drawn = std::span(random).first(n); - factory.random(drawn); - return protocol::random_id(drawn, memory); + return protocol::gen_id( + n, [&factory](std::span bytes) { factory.random(bytes); }, memory); } } // namespace webcpp::trystero::detail diff --git a/include/webcpp/trystero/detail/rebinding.hpp b/include/webcpp/trystero/detail/rebinding.hpp deleted file mode 100644 index 48d265f..0000000 --- a/include/webcpp/trystero/detail/rebinding.hpp +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -#ifndef WEBCPP_TRYSTERO_DETAIL_REBINDING_HPP -#define WEBCPP_TRYSTERO_DETAIL_REBINDING_HPP -#include - -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace webcpp::trystero::detail { -class connection; - -/** The bounded delay after the given number of unsuccessful bindings. */ -constexpr std::chrono::milliseconds rebinding_step(std::chrono::milliseconds handshake_timeout, - std::uint32_t ends) { - BOOST_ASSERT(ends >= 1); - // Trystero's pendingDataTimeoutMs (dist/data-limits.mjs:4). - constexpr std::chrono::milliseconds keep_time{10'000}; - constexpr std::chrono::milliseconds margin{1'000}; - constexpr std::chrono::milliseconds cap{300'000}; - if (handshake_timeout >= cap - margin) { - return cap; - } - auto step = std::max(handshake_timeout, keep_time) + margin; - for (std::uint32_t i = 1; i < ends && step < cap; ++i) { - step = step >= cap / 2 ? cap : step * 2; - } - return std::min(step, cap); -} - -/** The last eight nonces issued since a completed handshake. */ -class recent_challenges { -public: - /** The most challenges remembered between completed handshakes. */ - static constexpr std::size_t capacity = 8; - - /** Keeps the bounded challenge history in the room resource. */ - explicit recent_challenges(std::pmr::polymorphic_allocator<> a) : values_(capacity, a) {} - - /** Deleted: a boost::circular_buffer moves by swapping its allocator, which std::pmr's - * cannot. */ - recent_challenges(recent_challenges&&) = delete; - /** Deleted, as the move constructor is. */ - recent_challenges& operator=(recent_challenges&&) = delete; - - /** Remembers a challenge, in the oldest's place beyond capacity. */ - void push(std::pmr::string challenge) { values_.push_back(std::move(challenge)); } - - /** Whether any remembered challenge satisfies the response matcher. */ - template - [[nodiscard]] bool any_of(Matches&& matches) const { - return std::ranges::any_of(values_, std::forward(matches)); - } - - /** Forgets challenges after a completed handshake. */ - void clear() { values_.clear(); } - -private: - boost::circular_buffer> - values_; -}; - -/** One room's history of a peer on a particular shared connection. */ -struct rebind_state { - /** Creates one peer's history in the room resource. */ - explicit rebind_state(std::pmr::polymorphic_allocator<> a) : challenges(a) {} - - /** The consecutive binding ends since a completed handshake. */ - std::uint32_t ends = 0; - /** Whether this room has met the peer on this connection. */ - bool met = false; - /** Whether the lower id's own-kick backoff refuses binding. */ - bool refusing = false; - /** Whether the higher id drops frames until it sends presence. */ - bool dropping = false; - /** The connection this history belongs to, without keeping it alive. */ - std::weak_ptr on; - /** The next scheduled rebinding, cancelled when history ends. */ - std::shared_ptr timer; - /** The initiator's recent challenges whose correct answers still pass. */ - recent_challenges challenges; -}; -} // namespace webcpp::trystero::detail -#endif diff --git a/include/webcpp/trystero/detail/room_keys_cache.hpp b/include/webcpp/trystero/detail/room_keys_cache.hpp new file mode 100644 index 0000000..08019c5 --- /dev/null +++ b/include/webcpp/trystero/detail/room_keys_cache.hpp @@ -0,0 +1,225 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_TRYSTERO_DETAIL_ROOM_KEYS_CACHE_HPP +#define WEBCPP_TRYSTERO_DETAIL_ROOM_KEYS_CACHE_HPP + +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include // lint-world: names the executor only + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::detail { + +/** + * The keys of an app's rooms, as 0.27.0's `genKey` and `derivedRoomKeysCache` give them: a room + * without a password keys AES with the SHA-256 of its domain-tagged path, computed at each call; + * with one, the room's PBKDF2 master is derived once per room id, off the room's thread through + * `backend::factory::derive_password_master`, then HKDF gives the AES and HMAC keys, and the + * master is wiped. The derived keys of at most @ref capacity rooms are kept, the least recently + * asked for leaving first, and a failed derivation is forgotten, so that the next call derives + * again. + * + * The password is the app's, one for all its rooms (0.1.0's ruling), so the keys are kept by room + * id alone. Everything is in the app's resource. + * + * Tip: a derivation outlives the cache when the app ends during it: it owns its copy of the + * password, its salt and its master, which the backend reads and writes until its completion, and + * its completion reaches the cache through a weak reference. + */ +class room_keys_cache : public std::enable_shared_from_this { +public: + /** How many rooms' derived keys the cache keeps, 0.27.0's 64. */ + static constexpr std::size_t capacity = 64; + + /** What a call of @ref get completes with: the error, and the keys, valid for the call. */ + using done_handler = handler; + + /** A cache of the rooms of `app_id`, whose password is `password`, both copied. */ + room_keys_cache(webcpp::asio::any_io_executor ex, backend::factory& factory, + std::string_view app_id, std::string_view password, + std::pmr::memory_resource* memory) + : ex_(std::move(ex)), + factory_(factory), + memory_(memory), + app_id_(app_id, memory), + password_(password, memory), + entries_(memory), + recency_(memory) {} + + /** The cache holds a secret, which no copy must duplicate. */ + room_keys_cache(const room_keys_cache&) = delete; + /** Not assignable either. */ + room_keys_cache& operator=(const room_keys_cache&) = delete; + + /** Wipes the password; a derivation under way completes without the cache. */ + ~room_keys_cache() { webcpp::trystero::detail::wipe(password_.data(), password_.size()); } + + /** + * The keys of `room_id`, through `done`, posted to the executor: after the call returns, even + * when they are known at once. + * + * @param room_id The room's id, read during the call. + * @param done Called with the keys; or, when the derivation failed, with + * `error::backend_failure` and keys of zeros, the cache then forgetting it. + */ + void get(std::string_view room_id, done_handler done) { + if (password_.empty()) { + protocol::room_keys keys{ + .aes = protocol::room_aes_key_without_password(app_id_, room_id, memory_), + .hmac = {}, + }; + post(ex_, memory_, + [keys = std::move(keys), done = std::move(done)]() mutable { done({}, keys); }); + return; + } + if (const auto it = entries_.find(room_id); it != entries_.end()) { + recency_.splice(recency_.begin(), recency_, it->second.place); + const auto d = it->second.keys; + if (d->keys) { + post(ex_, memory_, [d, done = std::move(done)]() mutable { done({}, *d->keys); }); + } else { + d->waiters.push_back(std::move(done)); + } + return; + } + derive(room_id, std::move(done)); + } + + /** How many rooms' keys the cache holds now, or derives. */ + [[nodiscard]] std::size_t size() const { return entries_.size(); } + +private: + /** One room's derivation and, once it succeeded, its keys. */ + struct derivation { + derivation(std::pmr::memory_resource* memory, std::string_view room_id, + std::string_view password) + : room_id(room_id, memory), password(password, memory), waiters(memory) {} + + derivation(const derivation&) = delete; + derivation& operator=(const derivation&) = delete; + + /** Wipes the password's copy; the master and the keys wipe themselves. */ + ~derivation() { webcpp::trystero::detail::wipe(password.data(), password.size()); } + + std::pmr::string room_id; + std::pmr::string password; + std::array salt{}; + webcpp::crypto::secret<32> master; + std::optional keys; + std::pmr::vector waiters; + }; + + struct entry { + std::shared_ptr keys; + std::pmr::list::iterator place; + }; + + std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } + + /** Starts the derivation of `room_id`'s keys, which the cache holds no entry of. */ + void derive(std::string_view room_id, done_handler done) { + if (entries_.size() >= capacity) { + entries_.erase(recency_.back()); + recency_.pop_back(); + } + const auto d = std::allocate_shared(allocator(), memory_, room_id, password_); + d->salt = protocol::pbkdf2_salt(app_id_, room_id, memory_); + d->waiters.push_back(std::move(done)); + recency_.emplace_front(room_id); + entries_.try_emplace(recency_.front(), entry{.keys = d, .place = recency_.begin()}); + const std::span password( + reinterpret_cast(d->password.data()), d->password.size()); + const std::span master = d->master.writable(); + factory_.derive_password_master( + password, d->salt, master, + handler( + std::allocator_arg, allocator(), + [weak = weak_from_this(), d](boost::system::error_code ec) { + derived(weak, d, ec); + })); + } + + /** Ends the derivation `d`: its keys from its master by HKDF, its master wiped, and every + * waiter called; a failure leaves the cache. */ + static void derived(const std::weak_ptr& weak, + const std::shared_ptr& d, boost::system::error_code ec) { + if (!ec) { + auto keys = protocol::derive_room_keys(d->master.bytes(), + d->waiters.get_allocator().resource()); + if (keys) { + d->keys.emplace(std::move(*keys)); + } else { + ec = make_error_code(error::backend_failure); + } + } + const auto master = d->master.writable(); + webcpp::trystero::detail::wipe(master.data(), master.size()); + const auto self = weak.lock(); + if (ec) { + ec = make_error_code(error::backend_failure); + if (self) { + self->forget(d); + } + } + // A waiter may ask again, or end the app: the waiters are taken out first, and `d` keeps + // the keys each is handed. + auto waiters = + std::exchange(d->waiters, std::pmr::vector(d->waiters.get_allocator())); + const protocol::room_keys none; + for (auto& waiter : waiters) { + waiter(ec, d->keys ? *d->keys : none); + } + } + + /** Forgets `d`, if the cache still holds it. */ + void forget(const std::shared_ptr& d) { + const auto it = entries_.find(d->room_id); + if (it != entries_.end() && it->second.keys == d) { + recency_.erase(it->second.place); + entries_.erase(it); + } + } + + webcpp::asio::any_io_executor ex_; + backend::factory& factory_; + std::pmr::memory_resource* memory_; + std::pmr::string app_id_; + std::pmr::string password_; + // By room id, each key a view of its node in the recency list, which owns the text. + std::pmr::map> entries_; + // The room ids, the most recently asked for first. + std::pmr::list recency_; +}; + +} // namespace webcpp::trystero::detail + +#endif diff --git a/include/webcpp/trystero/detail/signaling.hpp b/include/webcpp/trystero/detail/signaling.hpp index 1f6bd21..e9c71ed 100644 --- a/include/webcpp/trystero/detail/signaling.hpp +++ b/include/webcpp/trystero/detail/signaling.hpp @@ -19,17 +19,25 @@ #include #include #include +#include #include #include +#include + +#include #include +#include +#include + #include #include #include #include #include #include +#include #include #include #include @@ -44,6 +52,58 @@ namespace webcpp::trystero::detail { +/** + * When each key was last reported, for at most `capacity` keys, the least recently reported or + * looked up forgotten first, as 0.27.0's `createBoundedCache` keeps its last decrypt errors: a key + * is reported again only once `interval` has passed since its last report. + */ +class report_pacer { +public: + /** Remembers nothing yet, in `memory`. */ + report_pacer(std::size_t capacity, std::chrono::milliseconds interval, + std::pmr::memory_resource* memory) + : capacity_(capacity), interval_(interval), order_(memory), at_(memory) {} + + /** + * Whether `key` is reported at `now`: it was never reported, or it was forgotten, or its last + * report is `interval` old or older; when it is, `now` becomes its last report. Either way it + * becomes the most recent key, as 0.27.0's cache refreshes a key it reads. + */ + bool due(std::string_view key, time_point now) { + if (const auto it = at_.find(key); it != at_.end()) { + order_.splice(order_.end(), order_, it->second.place); + if (now - it->second.reported < interval_) { + return false; + } + it->second.reported = now; + return true; + } + if (capacity_ == 0) { + return true; + } + if (at_.size() >= capacity_) { + at_.erase(std::string_view(order_.front())); + order_.pop_front(); + } + // A list never moves what it holds, so the view stays valid until its key is forgotten. + const std::string_view stored = order_.emplace_back(key); + at_.emplace(stored, entry{.reported = now, .place = std::prev(order_.end())}); + return true; + } + +private: + struct entry { + time_point reported; + std::pmr::list::iterator place; + }; + + std::size_t capacity_; + std::chrono::milliseconds interval_; + // The keys, the least recent first. + std::pmr::list order_; + std::pmr::map> at_; +}; + /** * The negotiation with each peer seen on the signaling topics, after Trystero's signal handler. * @@ -51,41 +111,44 @@ namespace webcpp::trystero::detail { * | announcement | the lower peer id offers on the relay that carried it; the higher one asks the | * | | other to offer by announcing itself on the other's topic, at most once a | * | | second per peer and once in 5.3 s per relay for the whole room | - * | offer | answers it, unless it already answers or opens one, or offers itself and its | - * | | id is lower; the same offer through another relay, while it is opened, has the | - * | | answer sent there too | + * | offer | answers it, unless it already answers one, or offers itself and its id is | + * | | lower; the same offer through another relay has the answer sent there too | * | answer | applies it to the matching offer | * | candidate | adds it to the connection its offer id names, or keeps it until that | * | | connection has a remote description | * - * An offer, an answer and every candidate travel sealed (protocol/signal.hpp). A negotiation ends - * when the data channel opens: the connection is handed to the room and signals from that peer are - * ignored until it leaves. + * A peer the room does not want (`callbacks::should_connect`: one a full room refused) gets none of + * this: its announcements, offers and answers are ignored, an answer ending the offer it answers. + * + * An offer, an answer and every candidate travel sealed under the room's AES key, with the AAD of + * their type, their sender and their offer id (protocol/seal.hpp), sealed and opened at once, in + * the call, as 0.27.0's `encrypt` and `decrypt` do them in WebCrypto. A negotiation ends when the + * data channel opens: the connection is handed to the room and signals from that peer are ignored + * until it leaves. * * Announcements are not sealed, so anyone who knows the app and room ids can announce any number * of peer ids, and anyone who reads the relays can send any signal in any peer's name. Nothing a * peer sends changes a negotiation before it opens with the room key: a signal that does not open - * is counted, reported once per negotiation, and changes nothing else; and since a flood of fresh - * ids makes each a negotiation, the reports are paced too: the first of a quiet interval at once, - * the rest together when it ends (`failed_open_report_interval`). A sealed offer or answer holds - * neither its offer id nor a peer id (Trystero's wire), so one recorded from the relays still opens - * when it is resent in its sender's name: the room remembers the offers and answers it made or - * acted on (`remembered_descriptions`) and refuses one that comes to it as a peer's, which it logs: - * a resent one, or its own sent back. One it neither made nor acted on still opens and is acted - * on, and every peer seals a fresh offer for any id announced above its own: so anyone who reads - * and publishes on the relays, without the key, can keep two peers apart from their first meeting - * for as long as it keeps at it, though it can neither read nor join anything, nor touch joined - * peers. Only a wire that seals the offer id and both peer ids closes this. The negotiations under - * way are bounded (`max_unconnected_peers`): a negotiation is dropped when its offer and its answer - * expire without a connection, an idle one (no connection, no offer being opened) gives its place - * to a new peer, and beyond the bound a new peer is refused, logged once. The connections made are - * bounded too (`max_connections_per_window`), however soon they end, since a browser counts a - * closed one until its garbage collector runs. Joined peers, memory and connections stay safe - * under a flood; new peers do not: a flooder who keeps sending fresh ids takes each place, and each - * connection of the window, as it frees, and keeps new peers out for as long as the flood lasts. A - * joined peer whose connection drops is a new peer when it comes back, with the same id, and is - * kept out the same way: there is no renegotiation of a joined peer's connection. Trystero bounds - * none of this. + * is counted and changes nothing else, and an offer or an answer that does not open is reported + * as `decrypt_failed` at most once a minute per peer and stage, as 0.27.0 reports it + * (`decrypt_report_interval`). The AAD binds a sealed signal to its type, its sender and its + * offer id, so that one recorded from the relays opens only as what + * it was: the same signal of the same sender for the same offer, never another's, nor an answer + * sent back as an offer. Resent so, it still opens: the room remembers the offers and answers it + * made or acted on (`remembered_descriptions`) and refuses one that comes to it again, which it + * logs. The AAD does not name the receiver, and every peer seals a fresh offer for any id + * announced above its own: so anyone who reads and publishes on the relays, without the key, can + * still announce ids and answer nothing, though it can neither read nor join anything, nor touch + * joined peers. The negotiations under way are bounded (`max_unconnected_peers`): a negotiation is + * dropped when its offer and its answer expire without a connection, an idle one (no connection) + * gives its place to a new peer, and beyond the bound a new peer is refused, logged once. The + * connections made are bounded too (`max_connections_per_window`), however soon they end, since a + * browser counts a closed one until its garbage collector runs. Joined peers, memory and + * connections stay safe under a flood; new peers do not: a flooder who keeps sending fresh ids + * takes each place, and each connection of the window, as it frees, and keeps new peers out for as + * long as the flood lasts. A joined peer whose connection drops is a new peer when it comes back, + * with the same id, and is kept out the same way: there is no renegotiation of a joined peer's + * connection. Trystero bounds none of this. * * Tip: a peer id is copied once, into the map's key, and every asynchronous handler captures its * own copy, in the room's resource, because it may outlive the entry. The entry points a handler @@ -97,7 +160,7 @@ class signaling : public std::enable_shared_from_this { /** * The most negotiations a room holds at once with peers it is not connected to, each with at * most two pending connections: a peer beyond it waits for its next announcement, or its offer - * sent again. It bounds the offers opened at once too, one per negotiation. + * sent again. */ static constexpr std::size_t max_unconnected_peers = 32; @@ -121,46 +184,67 @@ class signaling : public std::enable_shared_from_this { /** What the signaling asks of its room. */ struct callbacks { - /** Whether the room claims a signal over an existing app connection. */ - handler claim; /** Publishes a signal on a topic, through the relay given. */ handler publish; - /** A negotiation ended with an open data channel: the connection is the room's. */ + /** A negotiation ended with an open data channel: the connection is the room's, with the + * descriptions the negotiation set, the last one `set_local_description` gave and the last + * one applied with `set_remote_description`, whose DTLS fingerprints the room's handshake + * binds (design D20). The views are valid for the call. */ handler, - std::shared_ptr)> + std::shared_ptr, std::string_view local_sdp, + std::string_view remote_sdp)> connected; /** - * A negotiation with a peer failed, with the error and what happened, or an empty text - * for the error's own message; several, with an empty peer, when `what` counts them. + * A negotiation with a peer failed: an offer or an answer did not open + * (`error::decrypt_failed`), a connection did not open after the exchange of descriptions + * (`error::peer_connect_failed`), or the backend made no connection + * (`error::backend_failure`). The report's views are valid for the call; its room's id is + * set, and its app's. */ - handler - failed; + handler failed; + /** + * Whether the room wants a connection to a peer, 0.27.0's `shouldConnectPeer`, which its + * room answers with `canConnectPeer`: false for a peer whose user a full room refused + * while it stays full. Asked before an announcement, an offer or an answer of that peer is + * acted on; empty, every peer is wanted. The view is valid for the call. + */ + handler should_connect; }; - /** Every allocation goes through `memory`, the parsed signals' documents included, but the - * peer connections, which are made in `connection_memory`, the app's: the - * one a negotiation opens becomes the app's connection. */ - signaling(backend::factory& factory, std::shared_ptr sealer, - std::string_view app_id, std::string_view room_id, std::string_view self_id, - std::span ice_servers, callbacks cb, logger log, - std::pmr::memory_resource* memory, std::pmr::memory_resource* connection_memory) + /** Every allocation goes through `memory`, the room's, the parsed signals' documents and the + * peer connections included: the one a negotiation opens becomes the room's, and ends with the + * room or the peer. */ + signaling(backend::factory& factory, std::string_view app_id, std::string_view room_id, + std::string_view self_id, std::span ice_servers, + callbacks cb, logger log, std::pmr::memory_resource* memory) : factory_(factory), memory_(memory), - connection_memory_(connection_memory), - sealer_(std::move(sealer)), app_id_(app_id, memory), room_id_(room_id, memory), self_id_(self_id, memory), ice_servers_(copy_ice_servers(ice_servers, memory)), + turn_configured_(has_turn_server(ice_servers)), cb_(std::move(cb)), log_(std::move(log)), peers_(memory) {} + /** + * Gives the signaling the room's AES key, which it seals and opens every signal under: the room + * gives it before its strategy starts, so before the first message. + * + * @param key The room's AES key, copied. + */ + void set_key(const webcpp::crypto::secret<32>& key) { + std::ranges::copy(key.bytes(), key_.writable().begin()); + keyed_ = true; + } + /** A message on the root or the self topic; `content` is read during the call. */ void handle(std::size_t relay, std::string_view content) { if (closed_) { return; } + BOOST_ASSERT(keyed_); // A signal past its bound is dropped as a malformed one is, before it is read. const auto document = webcpp::document::parse( content, protocol::json::protocol_limits(protocol::max_parsed_signal_bytes), @@ -170,7 +254,20 @@ class signaling : public std::enable_shared_from_this { if (!message || message->peer_id == self_id_) { return; } - if (cb_.claim && cb_.claim(message->peer_id)) { + // A peer the room does not want is not negotiated with, as 0.27.0's signal handler asks + // shouldConnectPeer before it acts on an announcement, an offer or an answer: an answer + // ends the offer it answers. A candidate needs no asking, its connection having been. + // 0.27.0 first handles a connected or stale peer's announcement, then asks; the order + // matters once a connected peer can be unwanted (Phase 3, scale), and not for a refused + // peer, which never connected. + const bool candidate_only = + !message->is_announcement() && message->offer.empty() && message->answer.empty(); + if (!candidate_only && cb_.should_connect && !cb_.should_connect(message->peer_id)) { + if (const auto known = peers_.find(message->peer_id); + known != peers_.end() && !message->answer.empty() && !known->second.connected) { + reset_offer(known->second); + drop_if_done(message->peer_id); + } return; } auto it = peers_.find(message->peer_id); @@ -246,25 +343,31 @@ class signaling : public std::enable_shared_from_this { static constexpr auto counter_announce_interval = std::chrono::milliseconds(5'333); /** How many refused peer ids are remembered, so that each is logged once. */ static constexpr std::size_t remembered_refusals = 64; - /** The least time between two reports of signals that did not open. */ - static constexpr auto failed_open_report_interval = std::chrono::milliseconds(10'000); + /** The least time between two reports of an offer, or of an answer, of one peer that did not + * open: 0.27.0's `decryptErrDedupeTtlMs`. */ + static constexpr auto decrypt_report_interval = std::chrono::milliseconds(60'000); + /** How many peers and stages the last report of a signal that did not open is remembered for, + * the least recently reported or seen forgotten first: 0.27.0's bound of `recentDecryptErrors`. + */ + static constexpr std::size_t remembered_decrypt_failures = 512; /** One side of a negotiation: a connection, the remote candidates waiting for its remote - * description. */ + * description, and the descriptions it set. */ struct side { - explicit side(pmr_allocator a) : pending_remote(a) {} + explicit side(pmr_allocator a) : pending_remote(a), local_sdp(a), remote_sdp(a) {} std::shared_ptr pc; std::shared_ptr channel; std::pmr::vector pending_remote; + // The last description `set_local_description` gave the connection. + std::pmr::string local_sdp; + // The last description the connection applied with `set_remote_description`. + std::pmr::string remote_sdp; }; struct negotiation { negotiation(pmr_allocator a, std::uint64_t admitted) : admitted(admitted), - opening_offer_id(a), - opening_offer(a), - opening_relays(a), offer(a), offer_id(a), sealed_offer(a), @@ -282,21 +385,16 @@ class signaling : public std::enable_shared_from_this { counter_announced(a) {} // Its place in the order the room took its negotiations in: of two idle as long, the one - // taken first gives its place first, and an opened offer finds by it the very negotiation - // it came to, not a later one with the same peer. + // taken first gives its place first. std::uint64_t admitted; bool connected = false; // When the peer last sent a message, for the eviction of an idle negotiation. time_point last_message{}; - // The peer's offer the sealer is opening, one at a time, as Trystero answers one at a - // time: its id, its sealed text, empty when none is being opened, and the relays it came - // through, where the answer goes. Until it is opened, the negotiation is not idle, and - // keeps its place. - std::pmr::string opening_offer_id; - std::pmr::string opening_offer; - std::pmr::set opening_relays; - // Whether a signal of this negotiation that did not open was reported. - bool failed_open_reported = false; + // Whether a signal of this negotiation that did not open was logged. + bool failed_open_logged = false; + // Whether the failure of a connection of this negotiation to open after the exchange of + // descriptions was reported, 0.27.0's `didReportFailure`: once per offer or answer. + bool connect_failure_reported = false; // Whether an offer or an answer of this negotiation that the room had used before was // logged. bool replay_logged = false; @@ -348,24 +446,36 @@ class signaling : public std::enable_shared_from_this { return it == peers_.end() ? nullptr : &it->second; } - /** The negotiation with `peer` that the room took in `admitted`-th, if it still holds it. */ - negotiation* find(std::string_view peer, std::uint64_t admitted) { - auto* n = find(peer); - return n != nullptr && n->admitted == admitted ? n : nullptr; - } - /** Starts a negotiation with `peer`, which has none. */ negotiations::iterator admit(std::string_view peer) { return peers_.try_emplace(std::pmr::string(peer, memory_), allocator(), admissions_++) .first; } + /** Whether a negotiation waits on nothing: it is not connected and holds no connection. */ + static bool idle(const negotiation& n) { return !n.connected && !n.offer.pc && !n.answer.pc; } + /** - * Whether a negotiation waits on nothing: it is not connected, holds no connection, and no - * offer of its peer is being opened. + * `plaintext` sealed as a signal of this side's, under the room key, with a fresh IV from the + * backend's randomness, as 0.27.0's `toCipher` seals it. */ - static bool idle(const negotiation& n) { - return !n.connected && !n.offer.pc && !n.answer.pc && n.opening_offer.empty(); + [[nodiscard]] boost::system::result seal_signal(std::string_view type, + std::string_view offer_id, + std::string_view plaintext) { + BOOST_ASSERT(keyed_); + std::array iv{}; + factory_.random(iv); + const auto aad = protocol::signal_aad(type, self_id_, offer_id, memory_); + return protocol::seal(key_, iv, plaintext, std::string_view(aad), memory_); + } + + /** `sealed` opened as a signal of `peer`'s, under the room key, as 0.27.0's `toPlain` opens + * it. */ + [[nodiscard]] boost::system::result open_signal( + std::string_view type, std::string_view peer, std::string_view offer_id, + std::string_view sealed) const { + const auto aad = protocol::signal_aad(type, peer, offer_id, memory_); + return protocol::open(key_, sealed, std::string_view(aad), memory_); } /** @@ -373,11 +483,6 @@ class signaling : public std::enable_shared_from_this { * `max_unconnected_peers` unconnected negotiations, or one of them is idle and is dropped, the * one idle longest, and of those idle as long the one taken first. Otherwise the peer is * refused, and logged once. - * - * Tip: the sealer opens an offer in a step that takes its time (Web Crypto's, in a page), and - * new ids keep arriving meanwhile, at one instant of a page's coarse clock, where no - * negotiation is idle longer than another: an offer being opened holds its negotiation's - * place, so that none of them has the room drop it unopened. */ bool make_room_for(std::string_view peer) { std::size_t unconnected = 0; @@ -433,14 +538,14 @@ class signaling : public std::enable_shared_from_this { } return nullptr; } - auto pc = factory_.make_peer_connection(ice_servers_, connection_memory_); + auto pc = factory_.make_peer_connection(ice_servers_, memory_); if (!pc) { refused(peer); } return pc; } - /** Drops a negotiation that is idle: no connection, and no offer being opened. */ + /** Drops a negotiation that is idle: no connection. */ void drop_if_done(std::string_view peer) { if (const auto it = peers_.find(peer); it != peers_.end() && idle(it->second)) { peers_.erase(it); @@ -487,6 +592,7 @@ class signaling : public std::enable_shared_from_this { void start_offer(std::string_view peer, negotiation& n) { n.offer_id = random_id(factory_, protocol::offer_id_size, memory_); + n.connect_failure_reported = false; n.offer.pc = make_connection(peer); if (!n.offer.pc) { reset_offer(n); @@ -551,24 +657,15 @@ class signaling : public std::enable_shared_from_this { return; } used_.insert(sdp); // sent back to the room in a peer's name, it is refused - const auto weak = weak_from_this(); - sealer_->seal(sdp, bind( - [weak, peer = copy(peer), pc](boost::system::error_code ec, - std::string_view sealed) { - if (const auto self = weak.lock()) { - self->on_offer_sealed(peer, pc, ec, sealed); - } - })); - } - - /** Sends the sealed offer on every relay that asked for it, then the candidates it held. */ - void on_offer_sealed(std::string_view peer, const std::shared_ptr& pc, - boost::system::error_code ec, std::string_view sealed) { - auto* m = find(peer); - if (m == nullptr || m->offer.pc != pc || ec) { + m->offer.local_sdp = sdp; + auto sealed = seal_signal("offer", m->offer_id, sdp); + if (!sealed) { + log_("signal", "could not seal the offer for ", peer, ": ", sealed.error()); + reset_offer(*m); return; } - m->sealed_offer = sealed; + // Sent on every relay that asked for it, then the candidates it held. + m->sealed_offer = std::move(*sealed); for (const auto relay : m->offer_relays) { send_offer(relay, peer, *m); } @@ -614,64 +711,16 @@ class signaling : public std::enable_shared_from_this { if (n.offer.pc && self_id_ < peer) { return; // we lead; our offer stands } - // One offer of a peer is opened at a time, as Trystero answers one at a time, ignoring - // another until the first fails (dist/signal-handler.mjs:264-323): so offers sent in one - // name hold one open and one copy. The same offer through another relay has the answer - // sent there too, as Trystero's replay records its relay. - if (!n.opening_offer.empty()) { - if (offer == n.opening_offer && offer_id == n.opening_offer_id) { - n.opening_relays.insert(relay); - } - return; - } - // Nothing changes until the offer opens with the room key: a forged one, which anyone who + // Nothing changes unless the offer opens with the room key: a forged one, which anyone who // reads the relays can send in any peer's name, makes no connection and resets no offer. - // Until it opens, the negotiation keeps its place. - n.opening_offer_id = offer_id; - n.opening_offer = offer; - n.opening_relays.insert(relay); - const auto weak = weak_from_this(); - sealer_->open(n.opening_offer, bind( - [weak, peer = copy(peer), admitted = n.admitted]( - boost::system::error_code ec, std::string_view sdp) { - if (const auto self = weak.lock()) { - self->on_offer_opened(peer, admitted, ec, sdp); - } - })); - } - - /** - * Answers the offer the sealer opened for the negotiation taken in `admitted`-th: makes the - * answering connection and applies the offer as its remote description, and the next offer of - * the peer may be opened. An offer that did not open changes nothing, nor one whose - * negotiation the room no longer holds: the peer left, or the room closed. - */ - void on_offer_opened(std::string_view peer, std::uint64_t admitted, - boost::system::error_code ec, std::string_view sdp) { - auto* found = find(peer, admitted); - if (found == nullptr) { - return; - } - auto& n = *found; - // Taken out of the negotiation, which then opens none: the same resource on both sides, - // so each swap only exchanges what the two hold. - std::pmr::string offer_id(memory_); - std::pmr::string offer(memory_); - std::pmr::set relays(memory_); - offer_id.swap(n.opening_offer_id); - offer.swap(n.opening_offer); - relays.swap(n.opening_relays); - if (n.connected) { - return; - } - if (ec) { - failed_open(peer, n, "offer"); + // One that opens is answered at once, so that the same offer again, through this relay or + // another, has the answer replayed (replay_answer), as Trystero's replay records its relay. + const auto sdp = open_signal("offer", peer, offer_id, offer); + if (!sdp) { + failed_open(peer, n, signal_stage::offer); return; } - if (n.answer.pc || n.answered || (n.offer.pc && self_id_ < peer)) { - return; // another offer, or our own, came first - } - if (used_.contains(sdp)) { + if (used_.contains(*sdp)) { replayed(peer, n, "offer"); return; } @@ -679,7 +728,9 @@ class signaling : public std::enable_shared_from_this { if (!made) { return; } - start_answer(peer, n, made, std::move(offer_id), std::move(offer), relays, sdp); + std::pmr::set relays(memory_); + relays.insert(relay); + start_answer(peer, n, made, copy(offer_id), copy(offer), relays, *sdp); } /** @@ -696,6 +747,7 @@ class signaling : public std::enable_shared_from_this { reset_offer(n); } log_("signal", "offer ", offer_id, " from ", peer); + n.connect_failure_reported = false; n.answer.pc = pc; n.answered_offer_id = std::move(offer_id); n.answered_offer = std::move(offer); @@ -738,16 +790,20 @@ class signaling : public std::enable_shared_from_this { return; } self->log_("signal", "answering ", peer, " timed out"); + if (m->answer_sent) { + self->report_connect_failed(peer, *m); + } reset_answer(*m); self->drop_if_done(peer); })); - pc->set_remote_description("offer", sdp, - bind( - [weak, peer = copy(peer), pc](boost::system::error_code ec) { - if (const auto self = weak.lock()) { - self->on_offer_applied(peer, pc, ec); - } - })); + pc->set_remote_description( + "offer", sdp, + bind( + [weak, peer = copy(peer), pc, offered = copy(sdp)](boost::system::error_code ec) { + if (const auto self = weak.lock()) { + self->on_offer_applied(peer, pc, ec, offered); + } + })); } /** The same offer again: Trystero replays its answer on that relay, at most once a second. */ @@ -767,10 +823,10 @@ class signaling : public std::enable_shared_from_this { } } - /** Creates the answer once the offer is the connection's remote description. */ + /** Creates the answer once the offer, `sdp`, is the connection's remote description. */ void on_offer_applied(std::string_view peer, const std::shared_ptr& pc, - boost::system::error_code ec) { + boost::system::error_code ec, std::string_view sdp) { auto* m = find(peer); if (m == nullptr || m->answer.pc != pc) { return; @@ -780,6 +836,7 @@ class signaling : public std::enable_shared_from_this { reset_answer(*m); return; } + m->answer.remote_sdp = sdp; flush_remote_candidates(peer, m->answer); const auto weak = weak_from_this(); pc->set_local_description( @@ -796,38 +853,26 @@ class signaling : public std::enable_shared_from_this { void on_answer_created(std::string_view peer, const std::shared_ptr& pc, boost::system::error_code ec, std::string_view sdp) { - const auto* m = find(peer); + auto* m = find(peer); if (m == nullptr || m->answer.pc != pc || ec) { return; } used_.insert(sdp); // sent back to the room in a peer's name, it is refused - const auto weak = weak_from_this(); - sealer_->seal(sdp, bind( - [weak, peer = copy(peer), pc](boost::system::error_code ec, - std::string_view sealed) { - if (const auto self = weak.lock()) { - self->on_answer_sealed(peer, pc, ec, sealed); - } - })); - } - - /** Sends the sealed answer on every relay the offer came through, then the candidates it - * held. */ - void on_answer_sealed(std::string_view peer, - const std::shared_ptr& pc, - boost::system::error_code ec, std::string_view sealed) { - auto* m = find(peer); - if (m == nullptr || m->answer.pc != pc || ec) { + m->answer.local_sdp = sdp; + const auto sealed = seal_signal("answer", m->answered_offer_id, sdp); + if (!sealed) { + log_("signal", "could not seal the answer for ", peer, ": ", sealed.error()); + reset_answer(*m); return; } + // Sent on every relay the offer came through, then the candidates it held. log_("signal", "sending answer to ", peer); send_answer_message(peer, *m, protocol::write_signal( { .peer_id = self_id_, .offer_id = m->answered_offer_id, - .answer = sealed, - .answering = true, + .answer = *sealed, }, {}, memory_)); m->answer_sent = true; @@ -845,129 +890,146 @@ class signaling : public std::enable_shared_from_this { } void on_answer(std::string_view peer, std::string_view offer_id, std::string_view answer, - const negotiation& n) { + negotiation& n) { if (!n.offer.pc || n.answered || (!offer_id.empty() && offer_id != n.offer_id)) { return; } - // Nothing changes until the answer opens with the room key: a forged one, sent in this + // Nothing changes unless the answer opens with the room key: a forged one, sent in this // peer's name, must not reset the offer the peer's own answer is on its way to. - const auto pc = n.offer.pc; - const auto weak = weak_from_this(); - sealer_->open(answer, bind( - [weak, peer = copy(peer), pc](boost::system::error_code ec, - std::string_view sdp) { - if (const auto self = weak.lock()) { - self->on_answer_opened(peer, pc, ec, sdp); - } - })); - } - - /** Applies an answer the sealer opened to our offer. An answer that did not open changes - * nothing. */ - void on_answer_opened(std::string_view peer, - const std::shared_ptr& pc, - boost::system::error_code ec, std::string_view sdp) { - auto* m = find(peer); - if (m == nullptr || m->offer.pc != pc || m->answered || m->connected) { - return; - } - if (ec) { - failed_open(peer, *m, "answer"); + const auto sdp = open_signal("answer", peer, offer_id, answer); + if (!sdp) { + failed_open(peer, n, signal_stage::answer); return; } - if (used_.contains(sdp)) { - replayed(peer, *m, "answer"); + if (used_.contains(*sdp)) { + replayed(peer, n, "answer"); return; } - used_.insert(sdp); - m->answered = true; + used_.insert(*sdp); + const auto pc = n.offer.pc; + n.answered = true; const auto weak = weak_from_this(); - m->offer_expiry->start(answered_offer_ttl, bind([weak, peer = copy(peer), pc] { - const auto self = weak.lock(); - auto* n = self ? self->find(peer) : nullptr; - if (n == nullptr || n->connected || n->offer.pc != pc) { - return; - } - self->log_("signal", peer, - " answered but the connection never opened"); - reset_offer(*n); - self->drop_if_done(peer); - })); + n.offer_expiry->start(answered_offer_ttl, bind([weak, peer = copy(peer), pc] { + const auto self = weak.lock(); + auto* m = self ? self->find(peer) : nullptr; + if (m == nullptr || m->connected || m->offer.pc != pc) { + return; + } + self->log_("signal", peer, + " answered but the connection never opened"); + self->report_connect_failed(peer, *m); + reset_offer(*m); + self->drop_if_done(peer); + })); log_("signal", "answer from ", peer); - pc->set_remote_description("answer", sdp, - bind( - [weak, peer = copy(peer), pc](boost::system::error_code ec) { - const auto self = weak.lock(); - auto* n = self ? self->find(peer) : nullptr; - if (n == nullptr || n->offer.pc != pc) { - return; - } - if (ec) { - self->log_("webrtc", "the answer from ", peer, - " was refused: ", ec); - reset_offer(*n); - return; - } - self->flush_remote_candidates(peer, n->offer); - })); + pc->set_remote_description( + "answer", *sdp, + bind( + [weak, peer = copy(peer), pc, answered = copy(*sdp)](boost::system::error_code ec) { + const auto self = weak.lock(); + auto* n = self ? self->find(peer) : nullptr; + if (n == nullptr || n->offer.pc != pc) { + return; + } + if (ec) { + self->log_("webrtc", "the answer from ", peer, " was refused: ", ec); + reset_offer(*n); + return; + } + n->offer.remote_sdp = answered; + self->flush_remote_candidates(peer, n->offer); + })); } /** * Counts a sealed signal from `peer` that did not open with the room key, and changes nothing * else: the peer used another password, or someone forged it in the peer's name. The first of - * a negotiation is logged and reported as `wrong_password`; the rest only counted. Reports are - * paced: the first of a quiet interval goes at once, with its peer, and the others of the - * interval in one report when it ends, with no peer and their number. + * a negotiation is logged; an offer or an answer is reported as `decrypt_failed`, at most once + * per `decrypt_report_interval` for each peer and stage, as 0.27.0's `reportDecryptErr` + * reports it; a candidate is not reported, as 0.27.0 drops it unreported. * - * Tip: anyone who reads the relays can send garbage from any number of fresh ids, each a - * negotiation of its own; the application then gets one report per interval, not one per id. + * Tip: anyone who reads the relays can send garbage from any number of fresh ids, and each id + * is reported, as 0.27.0 reports each; the reports remembered are bounded, as 0.27.0's are. */ - void failed_open(std::string_view peer, negotiation& n, std::string_view what) { + void failed_open(std::string_view peer, negotiation& n, std::optional stage) { ++failed_opens_; - if (std::exchange(n.failed_open_reported, true)) { - return; + if (!std::exchange(n.failed_open_logged, true)) { + log_("signal", "could not open the ", stage ? stage_name(*stage) : "candidate", + " from ", peer, ": another password, or forged in its name; ignored"); } - log_("signal", "could not open the ", what, " from ", peer, - ": another password, or forged in its name; ignored"); - const auto now = steady_now(factory_); - if (unreported_failed_opens_ == 0 && - (!failed_open_reported_ || - now - *failed_open_reported_ >= failed_open_report_interval)) { - failed_open_reported_ = now; - cb_.failed(peer, make_error_code(error::wrong_password), {}); + if (stage) { + report_decrypt_failed(peer, *stage); + } + } + + /** The name 0.27.0 gives a signal of `stage`: "offer" or "answer". */ + static std::string_view stage_name(signal_stage stage) { + return stage == signal_stage::offer ? "offer" : "answer"; + } + + /** Reports that `peer`'s signal of `stage` did not open, unless it was reported less than + * `decrypt_report_interval` ago. */ + void report_decrypt_failed(std::string_view peer, signal_stage stage) { + const std::string_view name = stage_name(stage); + std::pmr::string key(name, memory_); + key += ':'; + key += peer; + if (!decrypt_reports_.due(key, steady_now(factory_))) { return; } - if (unreported_failed_opens_++ != 0) { - return; // the report of the interval is already due - } - failed_open_report_ = factory_.make_timer(memory_); - // The interval runs from the last report, which there always is by now. - const auto due = failed_open_reported_.value_or(now) + failed_open_report_interval; - const auto delay = - std::max(std::chrono::milliseconds::zero(), - std::chrono::duration_cast(due - now)); - failed_open_report_->start(delay, bind([weak = weak_from_this()] { - if (const auto self = weak.lock()) { - self->report_failed_opens(); - } - })); + std::pmr::string message("failed to decrypt ", memory_); + message += name; + message += " (incorrect password or corrupted signal)"; + room_error e = report_of(error::decrypt_failed, message, peer); + e.stage = stage; + cb_.failed(e); } - /** Reports, in one, the negotiations whose signals did not open since the last report. */ - void report_failed_opens() { - const auto count = std::exchange(unreported_failed_opens_, 0); - if (closed_ || count == 0) { + /** + * Reports that a connection with `peer` did not open after the exchange of descriptions, once + * per offer or answer, as 0.27.0's `reportSdpFailure` does: an offer answered, or an answer + * sent, whose connection expired, failed or closed before it opened. + */ + void report_connect_failed(std::string_view peer, negotiation& n) { + if (closed_ || n.connected || std::exchange(n.connect_failure_reported, true)) { return; } - failed_open_reported_ = steady_now(factory_); - std::pmr::string what(memory_); - protocol::json::append_integer(what, static_cast(count)); - what += " more peers sent signals that did not open with the room key, in the last "; - protocol::json::append_integer( - what, - std::chrono::duration_cast(failed_open_report_interval).count()); - what += " s: another password, or forged in their names"; - cb_.failed({}, make_error_code(error::wrong_password), what); + std::pmr::string message("could not connect to peer ", memory_); + message += peer; + message += " after exchanging SDP; "; + message += turn_configured_ ? "verify TURN server URLs and credentials" + : "configure TURN via app_config::ice_servers"; + room_error e = report_of(error::peer_connect_failed, message, peer); + e.turn_configured = turn_configured_; + cb_.failed(e); + } + + /** A report of `code` about `peer`, with its message, the app's and the room's ids, and no + * other context. */ + room_error report_of(error code, std::string_view message, std::string_view peer) const { + room_error e; + e.code = make_error_code(code); + e.message = message; + e.app_id = app_id_; + e.room_id = room_id_; + e.peer_id = peer; + return e; + } + + /** Whether any of `servers` has a `turn:` or `turns:` URL, in any case, as 0.27.0's + * `hasTurnServer` reads them. */ + static bool has_turn_server(std::span servers) { + const auto starts_with = [](std::string_view url, std::string_view scheme) { + return url.size() >= scheme.size() && + std::ranges::equal(url.substr(0, scheme.size()), scheme, [](char a, char b) { + return (a >= 'A' && a <= 'Z' ? static_cast(a - 'A' + 'a') : a) == b; + }); + }; + return std::ranges::any_of(servers, [&](const backend::ice_server& server) { + return std::ranges::any_of(server.urls, [&](const std::pmr::string& url) { + return starts_with(url, "turn:") || starts_with(url, "turns:"); + }); + }); } /** @@ -987,46 +1049,37 @@ class signaling : public std::enable_shared_from_this { ": the room made or used it before, so someone sent it again, maybe in its name"); } - void on_candidate(std::string_view peer, std::string_view offer_id_view, + void on_candidate(std::string_view peer, std::string_view offer_id, std::string_view candidate) { - const auto weak = weak_from_this(); - sealer_->open( - candidate, - bind( - [weak, peer = copy(peer), offer_id = copy(offer_id_view)]( - boost::system::error_code ec, std::string_view plain) { - const auto self = weak.lock(); - auto* m = self ? self->find(peer) : nullptr; - if (m == nullptr || m->connected) { - return; - } - if (ec) { - self->failed_open(peer, *m, "candidate"); - return; - } - // A candidate names the offer it belongs to; one that names none - // goes to the connection this side answers, else to its offer. - const bool answers = - m->answer.pc && (offer_id.empty() || offer_id == m->answered_offer_id); - const bool offers = - m->offer.pc && (offer_id.empty() ? !answers : offer_id == m->offer_id); - side* target = nullptr; - if (offers) { - target = &m->offer; - } else if (answers) { - target = &m->answer; - } - if (target == nullptr) { - return; - } - if (!target->pc->has_remote_description()) { - if (target->pending_remote.size() < max_pending_candidates) { - target->pending_remote.emplace_back(plain); - } - return; - } - target->pc->add_ice_candidate(plain, self->candidate_added(peer)); - })); + auto* m = find(peer); + if (m == nullptr || m->connected) { + return; + } + const auto plain = open_signal("candidate", peer, offer_id, candidate); + if (!plain) { + failed_open(peer, *m, std::nullopt); + return; + } + // A candidate names the offer it belongs to; one that names none goes to the connection + // this side answers, else to its offer. + const bool answers = m->answer.pc && (offer_id.empty() || offer_id == m->answered_offer_id); + const bool offers = m->offer.pc && (offer_id.empty() ? !answers : offer_id == m->offer_id); + side* target = nullptr; + if (offers) { + target = &m->offer; + } else if (answers) { + target = &m->answer; + } + if (target == nullptr) { + return; + } + if (!target->pc->has_remote_description()) { + if (target->pending_remote.size() < max_pending_candidates) { + target->pending_remote.emplace_back(*plain); + } + return; + } + target->pc->add_ice_candidate(*plain, candidate_added(peer)); } void flush_remote_candidates(std::string_view peer, side& s) { @@ -1074,40 +1127,35 @@ class signaling : public std::enable_shared_from_this { void publish_candidate(std::string_view peer, const std::shared_ptr& pc, std::string_view candidate) { - const auto weak = weak_from_this(); - sealer_->seal(candidate, bind( - [weak, peer = copy(peer), pc](boost::system::error_code ec, - std::string_view sealed) { - const auto self = weak.lock(); - auto* m = self ? self->find(peer) : nullptr; - if (m == nullptr || ec || m->connected) { - return; - } - if (pc == m->offer.pc) { - const auto message = protocol::write_signal( - { - .peer_id = self->self_id_, - .offer_id = m->offer_id, - .candidate = sealed, - }, - {}, self->memory_); - const auto topic = self->peer_topic(peer); - for (const auto relay : m->offer_relays) { - self->cb_.publish(relay, topic, message); - } - } else if (pc == m->answer.pc) { - self->send_answer_message( - peer, *m, - protocol::write_signal( - { - .peer_id = self->self_id_, - .offer_id = m->answered_offer_id, - .candidate = sealed, - .answering = true, - }, - {}, self->memory_)); - } - })); + auto* m = find(peer); + if (m == nullptr || m->connected) { + return; + } + if (pc == m->offer.pc) { + const auto sealed = seal_signal("candidate", m->offer_id, candidate); + if (!sealed) { + return; + } + const auto message = protocol::write_signal( + {.peer_id = self_id_, .offer_id = m->offer_id, .candidate = *sealed}, {}, memory_); + const auto topic = peer_topic(peer); + for (const auto relay : m->offer_relays) { + cb_.publish(relay, topic, message); + } + } else if (pc == m->answer.pc) { + const auto sealed = seal_signal("candidate", m->answered_offer_id, candidate); + if (!sealed) { + return; + } + send_answer_message(peer, *m, + protocol::write_signal( + { + .peer_id = self_id_, + .offer_id = m->answered_offer_id, + .candidate = *sealed, + }, + {}, memory_)); + } } void watch_channel(std::string_view peer, const std::shared_ptr& pc, @@ -1134,6 +1182,10 @@ class signaling : public std::enable_shared_from_this { void on_channel_open(std::string_view peer_view, const std::shared_ptr& pc) { + // A channel whose side ended never gets here: close_side cleared its handlers, closed its + // connection, and with it the channel, and let go of it; an entry dropped without a reset + // holds no connection. The returns below only guard a backend that still delivers an open + // event the reset raced with, for a channel that is closed by then. const auto peer = copy(peer_view); auto* n = find(peer); if (n == nullptr || n->connected) { @@ -1151,10 +1203,12 @@ class signaling : public std::enable_shared_from_this { n->connected = true; auto connected_pc = std::move(winner->pc); auto channel = std::move(winner->channel); + const auto local_sdp = std::move(winner->local_sdp); + const auto remote_sdp = std::move(winner->remote_sdp); reset_offer(*n); reset_answer(*n); log_("webrtc", "data channel open with ", peer); - cb_.connected(peer, std::move(connected_pc), std::move(channel)); + cb_.connected(peer, std::move(connected_pc), std::move(channel), local_sdp, remote_sdp); } void on_state(std::string_view peer_view, const std::shared_ptr& pc, @@ -1170,9 +1224,15 @@ class signaling : public std::enable_shared_from_this { } if (pc == n->offer.pc) { log_("webrtc", "the connection we offered to ", peer, " failed"); + if (n->answered) { + report_connect_failed(peer, *n); + } reset_offer(*n); } else if (pc == n->answer.pc) { log_("webrtc", "the connection we answered for ", peer, " failed"); + if (n->answer_sent) { + report_connect_failed(peer, *n); + } reset_answer(*n); } } @@ -1188,6 +1248,8 @@ class signaling : public std::enable_shared_from_this { s.pc.reset(); s.channel.reset(); s.pending_remote.clear(); + s.local_sdp.clear(); + s.remote_sdp.clear(); } /** @@ -1196,9 +1258,14 @@ class signaling : public std::enable_shared_from_this { */ void refused(std::string_view peer) { log_("webrtc", "the backend made no connection for ", peer); - cb_.failed(peer, make_error_code(error::backend_failure), {}); + std::array buffer{}; // the message without a std::string + cb_.failed(report_of( + error::backend_failure, + make_error_code(error::backend_failure).message(buffer.data(), buffer.size()), peer)); } + /** Ends the offer side; a failure to connect may be reported again afterwards, as 0.27.0's + * `resetOfferState` clears `didReportFailure`. */ static void reset_offer(negotiation& n) { close_side(n.offer); n.offer_id.clear(); @@ -1209,6 +1276,7 @@ class signaling : public std::enable_shared_from_this { n.offer_expiry.reset(); n.offer_retry.clear(); n.offer_retries.clear(); + n.connect_failure_reported = false; } static void reset_answer(negotiation& n) { @@ -1225,12 +1293,15 @@ class signaling : public std::enable_shared_from_this { backend::factory& factory_; std::pmr::memory_resource* memory_; - std::pmr::memory_resource* connection_memory_; - std::shared_ptr sealer_; + // The room's AES key, once the room gave it (set_key). + webcpp::crypto::secret<32> key_; + bool keyed_ = false; std::pmr::string app_id_; std::pmr::string room_id_; std::pmr::string self_id_; std::pmr::vector ice_servers_; + // Whether a TURN server is among them, which a report of a connection that did not open says. + bool turn_configured_; callbacks cb_; logger log_; negotiations peers_; @@ -1240,11 +1311,8 @@ class signaling : public std::enable_shared_from_this { std::pmr::map counter_announced_{memory_}; // per relay replay_cache used_{remembered_descriptions, memory_}; std::size_t failed_opens_ = 0; - // Negotiations whose failed open waits for the next report, when it was last made (never - // yet, when empty), and the timer of the next. - std::size_t unreported_failed_opens_ = 0; - std::optional failed_open_reported_; - std::shared_ptr failed_open_report_; + // The last report of each peer's offers and answers that did not open. + report_pacer decrypt_reports_{remembered_decrypt_failures, decrypt_report_interval, memory_}; std::size_t replayed_ = 0; bool closed_ = false; }; diff --git a/include/webcpp/trystero/detail/user_table.hpp b/include/webcpp/trystero/detail/user_table.hpp new file mode 100644 index 0000000..6ab296f --- /dev/null +++ b/include/webcpp/trystero/detail/user_table.hpp @@ -0,0 +1,130 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_TRYSTERO_DETAIL_USER_TABLE_HPP +#define WEBCPP_TRYSTERO_DETAIL_USER_TABLE_HPP + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::detail { + +/** + * The users of a room and their active peers, in the room's resource: a user joins with its first + * peer and leaves with its last, as 0.27.0's room counts a user's peers (`room.ts`, + * `emitActivatedEvents` and `removePeerEntry`). + * + * A peer belongs to one user for as long as it is in the table: a peer known already is never + * added again, under its user or under another. + */ +class user_table { +public: + /** The peers of each user, in the order they were added. */ + using user_map = + std::pmr::map, std::less<>>; + + /** No user yet; what the table holds is allocated in `memory`. */ + explicit user_table(std::pmr::memory_resource* memory) + : user_by_peer_(memory), peers_by_user_(memory) {} + + /** + * Adds an active peer of a user. + * + * @return Whether the user is new, `peer_id` its first peer; false as well when `peer_id` is + * known already, which changes nothing. + */ + bool add(std::string_view peer_id, std::string_view user_id) { + if (user_by_peer_.contains(peer_id)) { + return false; + } + auto* const memory = user_by_peer_.get_allocator().resource(); + user_by_peer_.try_emplace(std::pmr::string(peer_id, memory), + std::pmr::string(user_id, memory)); + auto user = peers_by_user_.find(user_id); + const bool first = user == peers_by_user_.end(); + if (first) { + user = peers_by_user_ + .try_emplace(std::pmr::string(user_id, memory), + std::pmr::vector(memory)) + .first; + } + user->second.emplace_back(peer_id); + return first; + } + + /** + * Removes a peer. + * + * @return Its user, when `peer_id` was its last peer; nothing when the user keeps another peer + * or `peer_id` is not in the table. + */ + std::optional remove(std::string_view peer_id) { + const auto peer = user_by_peer_.find(peer_id); + if (peer == user_by_peer_.end()) { + return std::nullopt; + } + // `add` lists each peer under its user, so the two maps agree. + const auto user = peers_by_user_.find(peer->second); + BOOST_ASSERT(user != peers_by_user_.end()); + user_by_peer_.erase(peer); + auto& peers = user->second; + const auto listed = std::ranges::find(peers, peer_id); + BOOST_ASSERT(listed != peers.end()); + peers.erase(listed); + if (!peers.empty()) { + return std::nullopt; + } + return std::move(peers_by_user_.extract(user).key()); + } + + /** The peers of a user, in the order they were added; none for a user not in the table. The + * span is valid until the table changes. */ + [[nodiscard]] std::span peers_of(std::string_view user_id) const { + const auto user = peers_by_user_.find(user_id); + if (user == peers_by_user_.end()) { + return {}; + } + return user->second; + } + + /** The user of a peer, or nothing for a peer not in the table. The view is valid until the + * peer is removed. */ + [[nodiscard]] std::optional user_of(std::string_view peer_id) const { + const auto peer = user_by_peer_.find(peer_id); + if (peer == user_by_peer_.end()) { + return std::nullopt; + } + return peer->second; + } + + /** Every user, by id, with its peers in the order they were added. */ + [[nodiscard]] const user_map& users() const { return peers_by_user_; } + + /** Removes every peer and every user, reporting none. */ + void clear() noexcept { + user_by_peer_.clear(); + peers_by_user_.clear(); + } + +private: + std::pmr::map> user_by_peer_; + user_map peers_by_user_; +}; + +} // namespace webcpp::trystero::detail + +#endif diff --git a/include/webcpp/trystero/detail/wipe.hpp b/include/webcpp/trystero/detail/wipe.hpp new file mode 100644 index 0000000..c5b7f49 --- /dev/null +++ b/include/webcpp/trystero/detail/wipe.hpp @@ -0,0 +1,86 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_TRYSTERO_DETAIL_WIPE_HPP +#define WEBCPP_TRYSTERO_DETAIL_WIPE_HPP + +#include + +#include +#include +#include +#include + +namespace webcpp::trystero::detail { + +/** + * Zeroes `byte_count` bytes at `wiped_data` with stores the optimiser cannot drop. + * + * This stands in until webcpp::crypto publishes a wipe of its own; the library does not reach + * into another library's detail namespace. + * + * Tip: a `memset` before an object dies is a dead store a compiler may remove; stores through + * a volatile pointer, then a signal fence, are kept. + * + * @param wiped_data The first byte, or null when `byte_count` is 0. + * @param byte_count How many bytes. + */ +inline void wipe(void* wiped_data, std::size_t byte_count) noexcept { + auto* const wiped_bytes = static_cast(wiped_data); + for (std::size_t byte_index = 0; byte_index < byte_count; ++byte_index) { + wiped_bytes[byte_index] = 0; + } + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +/** + * Zeroes an object's bytes, as @ref wipe does. + * + * @tparam T A trivially copyable type, a C library's key schedule or context. + * @param wiped_object The object. + */ +template +void wipe_object(T& wiped_object) noexcept { + static_assert(std::is_trivially_copyable_v, "only a plain state is wiped"); + wipe(&wiped_object, sizeof wiped_object); +} + +/** + * A memory resource that wipes each block before it gives it back to its upstream: what a parse of + * a secret allocates, its text, its document and its decoded bytes, is wiped when it is freed, at + * the latest when the parse's objects end. + * + * Tip: declared before the objects that allocate in it, it ends after them. + */ +class wiping_resource final : public std::pmr::memory_resource { +public: + /** + * A resource over `upstream`. + * + * @param upstream The resource every block comes from, which outlives this one. + */ + explicit wiping_resource(std::pmr::memory_resource* upstream) noexcept : upstream_(upstream) {} + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + return upstream_->allocate(bytes, alignment); + } + + void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override { + wipe(p, bytes); + upstream_->deallocate(p, bytes, alignment); + } + + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; + } + + std::pmr::memory_resource* upstream_; +}; + +} // namespace webcpp::trystero::detail + +#endif // WEBCPP_TRYSTERO_DETAIL_WIPE_HPP diff --git a/include/webcpp/trystero/error.hpp b/include/webcpp/trystero/error.hpp index dc0f461..8f21136 100644 --- a/include/webcpp/trystero/error.hpp +++ b/include/webcpp/trystero/error.hpp @@ -20,9 +20,10 @@ namespace webcpp::trystero { /** * What an operation of the library completes with when it does not succeed. * - * Each value is one of the errors Trystero rejects a promise with or reports to `onPeerError`, - * as a code of @ref error_category rather than a message: an operation completes with it, and - * `room::on_error` reports it with the peer it concerns. + * Each value is one of the errors Trystero rejects a promise with or reports to a room's + * `onError`, as a code of @ref error_category rather than a message: an operation completes with + * it, and `room::on_error` reports it in a @ref room_error, with the context Trystero gives it and + * `room_error_code_name` gives Trystero's name of a room error's code. * * @see "Rooms and actions", in the guide. */ @@ -44,17 +45,12 @@ enum class error { /** The data channel stopped draining while a transfer waited for it. */ channel_stalled, /** - * A peer's signal or handshake used another password, or the peer sent a handshake message the - * protocol does not expect, Trystero's "incorrect password for overlapping room". - */ - wrong_password, - /** A connected peer did not finish the handshake in time, Trystero's "handshake timed out". */ - handshake_timed_out, - /** - * Reserved: nothing reports it today. + * A connected peer's handshake failed, 0.27.0's `handshake-failed` room error, which + * `room_error_code_name` names: the report's message is 0.27.0's reason, as "handshake timed + * out after 10000ms", and the peer is told to leave. * - * A handshake message of the wrong shape reports `wrong_password`, as Trystero's handshake - * does. + * A signal under another password is `decrypt_failed`: 0.27.0 keeps another password out by + * the sealing of its signals alone. */ handshake_failed, /** The browser or the native stack refused an operation. */ @@ -66,8 +62,57 @@ enum class error { invalid_configuration, /** The app already holds a room of that id; a room is joined once per app. */ already_joined, - /** The app already holds as many rooms as a peer accepts, 64 of them. */ - too_many_rooms, + /** + * The room holds as many users as its `room_options::max_users` accepts, 0.27.0's "room full": + * reported by the room a full peer refused, with the refusing peer's id. + */ + room_full, + /** The peer is banned from the room, 0.27.0's "peer banned". */ + banned, + /** Every signaling relay failed, 0.27.0's `relay-failed` room error. */ + relay_failed, + /** A peer's or the endpoint's identity could not be resolved, 0.27.0's `identity-failed`. */ + identity_failed, + /** A plugin of the room failed to set up, 0.27.0's `plugin-failed`. */ + plugin_failed, + /** + * A signal could not be opened: another room password, a corrupted text, or a plaintext that + * is not UTF-8, 0.27.0's `decrypt-failed`. + * + * A room reports it for an offer or an answer, at most + * once a minute per peer and stage, with the stage in the report and its message, as + * "failed to decrypt offer (incorrect password or corrupted signal)". + */ + decrypt_failed, + /** The peer could not be connected after the SDP exchange, 0.27.0's `peer-connect-failed`. */ + peer_connect_failed, + /** A peer reported an error, 0.27.0's `peer-error`. */ + peer_error, + /** A listener that takes one at a time is already set, 0.27.0's "already registered". */ + already_subscribed, + /** The target of a send is not connected, 0.27.0's "no active peer with id". */ + not_connected, + /** An action was aborted by its caller, 0.27.0's "operation aborted". */ + action_aborted, + /** The receiver of a request answered with a failure, 0.27.0's `rejected` action error. */ + request_rejected, + /** A request was not answered in time, 0.27.0's "request timed out". */ + request_timed_out, + /** + * The action's name was made the other kind of action first, a message action or a request + * action, 0.27.0's "action type cannot be redefined", which it throws. + */ + action_redefined, + /** + * A text is not a user identity `import_user_identity` reads, 0.27.0's "invalid user identity + * key material; expected exported userKey or P-256 JWK", which `importUserIdentity` throws. + */ + invalid_user_identity, + /** + * A room's `room_options::max_users` is 0 or above 2^53 - 1, 0.27.0's "maxUsers must be a + * positive safe integer", which `joinRoom` throws: `app::join` refuses it. + */ + invalid_max_users, }; /** @@ -117,13 +162,29 @@ class error_category_impl final : public boost::system::error_category { case error::transfer_rejected: return "the receiver rejected the transfer"; case error::transfer_timed_out: return "the action transfer timed out"; case error::channel_stalled: return "the data channel stopped draining"; - case error::wrong_password: return "the peer uses another room password"; - case error::handshake_timed_out: return "the handshake timed out"; - case error::handshake_failed: return "the handshake failed"; + case error::handshake_failed: return "handshake failed"; case error::backend_failure: return "the WebRTC backend refused an operation"; case error::invalid_configuration: return "the configuration is unusable"; case error::already_joined: return "the app has already joined a room of that id"; - case error::too_many_rooms: return "the app holds as many rooms as a peer accepts, 64"; + case error::room_full: return "room full"; + case error::banned: return "peer banned"; + case error::relay_failed: return "all signaling relays failed"; + case error::identity_failed: return "identity resolution failed"; + case error::plugin_failed: return "plugin setup failed"; + case error::decrypt_failed: + return "failed to decrypt offer or answer (incorrect password or corrupted signal)"; + case error::peer_connect_failed: + return "could not connect to peer after exchanging SDP"; + case error::peer_error: return "peer error"; + case error::already_subscribed: return "handler already registered; unsubscribe first"; + case error::not_connected: return "no active peer with this id"; + case error::action_aborted: return "operation aborted"; + case error::request_rejected: return "request rejected"; + case error::request_timed_out: return "request timed out"; + case error::action_redefined: return "action type cannot be redefined"; + case error::invalid_user_identity: + return "invalid user identity key material; expected exported userKey or P-256 JWK"; + case error::invalid_max_users: return "maxUsers must be a positive safe integer"; } return "unknown webcpp.trystero error"; } diff --git a/include/webcpp/trystero/identity.hpp b/include/webcpp/trystero/identity.hpp new file mode 100644 index 0000000..a00b6af --- /dev/null +++ b/include/webcpp/trystero/identity.hpp @@ -0,0 +1,340 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + A user's identity, Trystero 0.27.0's `UserIdentity`: a P-256 key whose public key derives the + user's id, which one or several apps present as their user; made, imported and exported as + 0.27.0's `createUserIdentity`, `importUserIdentity` and `exportUserIdentity` make, import and + export it. +*/ +#ifndef WEBCPP_TRYSTERO_IDENTITY_HPP +#define WEBCPP_TRYSTERO_IDENTITY_HPP + +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero { + +/** + * Where this peer's user identity comes from, Trystero's `IdentityPersistence` (design D17). + */ +enum class identity_persistence { + /** Made with the app and lost with it, 0.27.0's `'none'`. */ + ephemeral, + /** Given to the app by the program, which made or imported it, 0.27.0's `'custom'`. */ + imported, +}; + +class user_identity; + +namespace detail { + +/** A P-256 key pair and its public point, as trystero's identities hold them. */ +struct p256_key { + /** The key pair. */ + webcpp::crypto::curves::p256::keypair key; + /** Its public point, SEC 1's uncompressed form. */ + std::array point; +}; + +/** + * The P-256 key pair of a scalar, or one drawn from the system's generator, with its point. + * + * Tip: this, `import_user_identity`, @ref protocol::sign_p256, @ref protocol::verify_p256 and + * @ref protocol::p256_public_key are trystero's only calls of webcpp::crypto's P-256 keys, so that + * a change of its interface is made in these two headers alone. + * + * @param scalar The secret scalar, 32 bytes big-endian; empty draws one. + * @return The key and its point; webcpp::crypto's error when the scalar is no valid key or the + * system has no generator. + */ +[[nodiscard]] inline boost::system::result make_p256_key( + std::span scalar) { + using webcpp::crypto::curves::p256::keypair; + auto key = scalar.empty() ? keypair::generate() : keypair::make(scalar); + if (!key) { + return key.error(); + } + const auto public_key = key->public_key(); + if (!public_key) { + return public_key.error(); + } + return p256_key{.key = std::move(*key), .point = public_key->uncompressed()}; +} + +/** An app's endpoint key, 0.27.0's endpoint identity: its key pair, its compact public key and + * the peer id it derives. */ +struct endpoint_identity { + /** The key pair. */ + webcpp::crypto::curves::p256::keypair key; + /** Its compact public key. */ + std::pmr::string compact; + /** The peer id, derived from the compact key. */ + std::pmr::string peer_id; +}; + +/** + * Makes an endpoint key, 0.27.0's `createEndpointIdentity`: of a scalar, or drawn from the + * system's generator. + * + * @param scalar The secret scalar, 32 bytes big-endian; empty draws one. + * @param memory The resource the compact key and the peer id are allocated in. + * @return The endpoint key; nothing when the scalar is no valid key or the system has no + * generator. + */ +[[nodiscard]] inline std::optional make_endpoint_identity( + std::span scalar, std::pmr::memory_resource* memory) { + auto made = make_p256_key(scalar); + if (!made) { + return std::nullopt; + } + auto compact = protocol::compact_public_key(made->point, memory); + auto peer_id = protocol::derive_peer_id(compact, memory); + return endpoint_identity{ + .key = std::move(made->key), + .compact = std::move(compact), + .peer_id = std::move(peer_id), + }; +} + +/** What a @ref user_identity holds: its key pair, its point and the texts derived from it. */ +struct user_key { + /** The key pair. */ + webcpp::crypto::curves::p256::keypair key; + /** Its public point, SEC 1's uncompressed form. */ + std::array point; + /** Its compact public key. */ + std::pmr::string compact; + /** The user's id, derived from the compact key. */ + std::pmr::string user_id; +}; + +/** Reaches what a @ref user_identity holds, for the functions that make and export one. */ +struct user_identity_access { + /** The key `identity` holds. */ + [[nodiscard]] static const user_key& key(const user_identity& identity) noexcept; + + /** + * The identity of a key pair and its point: the key, with its compact key and its user's id, + * allocated in `memory` through a `std::pmr::polymorphic_allocator`. + * + * @param key The key pair. + * @param point Its public point. + * @param memory The resource the key is allocated in. + * @return The identity. + */ + [[nodiscard]] static user_identity make(webcpp::crypto::curves::p256::keypair key, + const std::array& point, + std::pmr::memory_resource* memory); + + /** + * The identity of a scalar, or of one drawn from the system's generator, as + * `create_user_identity` makes it: the library's own tests fix their users' keys with it. + * + * @param scalar The secret scalar, 32 bytes big-endian; empty draws one. + * @param memory The resource the key is allocated in, which outlives every copy. + * @return The identity; webcpp::crypto's error when the scalar is no valid key or the system + * has no generator. + */ + [[nodiscard]] static boost::system::result make( + std::span scalar, std::pmr::memory_resource* memory); +}; + +} // namespace detail + +/** + * A user's identity, 0.27.0's `UserIdentity`: a P-256 key pair, the user's id its public key + * derives, and the signatures it makes. + * + * It is a handle: copies share one immutable key, allocated in the resource it was made with, which + * must outlive every copy. Several apps given copies are one user's endpoints, as several pages of + * one imported identity are in 0.27.0. + * + * @see "Peers and users", in the guide. + */ +class user_identity { +public: + /** + * A copy of `other`, which shares its key. + * + * Tip: an identity has no move of its own, so that none is ever empty: a move copies. + * + * @param other The identity copied. + */ + user_identity(const user_identity& other) = default; + + /** + * Makes this a copy of `other`, sharing its key. + * + * @param other The identity copied. + * @return This identity. + */ + user_identity& operator=(const user_identity& other) = default; + + /** Releases this copy's share of the key; the last copy frees it. */ + ~user_identity() = default; + + /** + * The user's id, 0.27.0's `userId`: 22 base62 characters derived from the public key. + * + * @return The id, valid while a copy of this identity lives. + */ + [[nodiscard]] std::string_view user_id() const noexcept { return key_->user_id; } + + /** + * The user's public key in its compact form, `base64url(x) + "." + base64url(y)`. + * + * @return The key, 87 characters, valid while a copy of this identity lives. + */ + [[nodiscard]] std::string_view public_key() const noexcept { return key_->compact; } + + /** + * Signs a payload as the user, 0.27.0's `sign`: ECDSA P-256 of its SHA-256, low S. + * + * @param payload The bytes signed. + * @return The signature, r then s; webcpp::crypto's error when the key cannot sign, which it + * never is once made. + */ + [[nodiscard]] boost::system::result sign( + std::span payload) const { + return protocol::sign_p256(key_->key, payload); + } + +private: + explicit user_identity(std::shared_ptr key) : key_(std::move(key)) {} + + friend struct detail::user_identity_access; + + std::shared_ptr key_; +}; + +inline const detail::user_key& detail::user_identity_access::key( + const user_identity& identity) noexcept { + return *identity.key_; +} + +inline user_identity detail::user_identity_access::make(webcpp::crypto::curves::p256::keypair key, + const std::array& point, + std::pmr::memory_resource* memory) { + auto compact = protocol::compact_public_key(point, memory); + auto user_id = protocol::derive_user_id(compact, memory); + return user_identity(std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), + user_key{ + .key = std::move(key), + .point = point, + .compact = std::move(compact), + .user_id = std::move(user_id), + })); +} + +inline boost::system::result detail::user_identity_access::make( + std::span scalar, std::pmr::memory_resource* memory) { + auto made = make_p256_key(scalar); + if (!made) { + return made.error(); + } + return make(std::move(made->key), made->point, memory); +} + +/** + * Makes a new user identity, 0.27.0's `createUserIdentity`: a P-256 key pair drawn from the + * system's generator. + * + * @param memory The resource the key is allocated in, which outlives every copy of the identity. + * @return The identity; webcpp::crypto's `entropy_unavailable` when the system has no generator. + */ +[[nodiscard]] inline boost::system::result create_user_identity( + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + return detail::user_identity_access::make(std::span(), memory); +} + +/** + * Imports a user identity from its text, 0.27.0's `importUserIdentity`: the text + * @ref export_user_identity writes, or the JSON of a private P-256 key (a JWK), read as + * `protocol::parse_user_key` reads them; the key must then sign the bytes of + * `trystero:identity-self-test:v1` with a signature its point verifies. + * + * The scalar is wiped from every buffer of trystero's that held it; the program's text is its + * own. + * + * @param text The text. + * @param memory The resource the key and the import's buffers are allocated in, which outlives + * every copy of the identity. + * @return The identity; `error::invalid_user_identity` for a text that is not a user key, a point + * that is not on the curve and a scalar that is not the point's. + */ +[[nodiscard]] inline boost::system::result import_user_identity( + std::string_view text, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + namespace p256 = webcpp::crypto::curves::p256; + const auto material = protocol::parse_user_key(text, memory); + if (!material) { + return error::invalid_user_identity; + } + auto key = p256::keypair::make(material->d.bytes()); + const auto point = protocol::p256_public_key(material->point); + if (!key || !point) { + return error::invalid_user_identity; + } + // 0.27.0's self-test: the key signs its payload, and the given point verifies the signature. + const auto payload = protocol::domain_tag("identity-self-test", 1, memory); + const std::span bytes(reinterpret_cast(payload.data()), + payload.size()); + const auto signature = protocol::sign_p256(*key, bytes); + if (!signature || !protocol::verify_p256(*signature, bytes, *point)) { + return error::invalid_user_identity; + } + return detail::user_identity_access::make(std::move(*key), material->point, memory); +} + +/** + * The text of a user identity, 0.27.0's `exportUserIdentity`: @ref protocol::user_key_prefix and + * the base64url of the JSON `{"d":..,"x":..,"y":..}`, which @ref import_user_identity reads. + * + * The text holds the secret key: a program keeps it as it keeps a password, and wipes it when + * done. + * + * @param identity The identity. + * @param memory The resource the text is allocated in. + * @return The text, 214 characters. + */ +[[nodiscard]] inline std::pmr::string export_user_identity( + const user_identity& identity, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + const auto& key = detail::user_identity_access::key(identity); + auto scalar = key.key.secret_scalar(); + // A key pair made by webcpp::crypto and never moved from has its scalar. + BOOST_ASSERT(scalar.has_value()); + protocol::user_key_material material; + if (scalar) { + material.d = std::move(*scalar); + } + material.point = key.point; + return protocol::write_user_key(material, memory); +} + +} // namespace webcpp::trystero + +#endif diff --git a/include/webcpp/trystero/options.hpp b/include/webcpp/trystero/options.hpp index c607aa2..aa0487e 100644 --- a/include/webcpp/trystero/options.hpp +++ b/include/webcpp/trystero/options.hpp @@ -11,13 +11,14 @@ #include #include +#include #include -#include #include #include #include +#include #include #include #include @@ -27,7 +28,10 @@ namespace webcpp::trystero { /** * What an app is made with: the part of Trystero's `joinRoom` configuration that every room of - * the app shares, its peer id among it, and the one connection per remote peer its rooms share. + * the app shares. + * + * It names no peer id: 0.27.0 has no custom `peerId`, and the app derives its own from the P-256 + * endpoint key it makes (`app::self_id`). * * The app copies every part of it into `memory`. It is move-only, as its `log` is: pass it moved, * or build it in place with designated initializers. @@ -35,21 +39,13 @@ namespace webcpp::trystero { struct app_config { /** The application's id, Trystero's `appId`: rooms of different apps never meet. */ std::pmr::string app_id = {}; - /** - * This program's id in every room of the app, Trystero's `selfId`; empty means 20 random - * characters, drawn once for the app. - * - * Other peers ignore an id longer than `protocol::max_peer_id_bytes` (64): the app replaces - * one with 20 random characters, and reports it with `error::invalid_configuration`. - */ - std::pmr::string self_id = {}; /** * The password shared by every room of this app, Trystero's `password`. * * The app copies it into its resource and keeps it unchanged. Different passwords require - * separate apps with distinct peer ids, so a connection authenticated in one domain cannot - * be reused in another. Empty means a passwordless domain. Signals are still sealed with the - * app and room ids, and the room handshake then has no password challenge. + * separate apps with distinct peer ids. Empty means a passwordless domain, whose signals are + * still sealed with the app and room ids. A peer of another password never connects: the + * sealing of the signals alone keeps it out, as in 0.27.0, which has no password challenge. */ std::pmr::string password = {}; /** @@ -72,12 +68,16 @@ struct app_config { */ std::pmr::vector ice_servers = {}; /** - * How long a connection with no room bound to it after a departure stays open, Trystero's - * `sharedPeerIdleMs`; 0 closes it at once. + * The user this app's rooms present, Trystero's `identity` given a user identity: one made + * with @ref create_user_identity or imported with @ref import_user_identity, whose resource + * must outlive the app, which keeps a copy; rooms report it as + * `identity_persistence::imported`, 0.27.0's `'custom'`. * - * A negative value is replaced with 0, and reported with `error::invalid_configuration`. + * Absent, the app makes an ephemeral user identity of its own, 0.27.0's `'none'`, in `memory`, + * lost with the app: there is no store the port keeps a user in, as 0.27.0's `'local'` keeps + * it in IndexedDB (design D15). Several apps given one identity are one user's endpoints. */ - std::chrono::milliseconds idle_timeout{123'333}; + std::optional identity = {}; /** * Where the app's and its rooms' diagnostics go: called with a category ("app", "nostr", * "signal", "webrtc", "room" or "action") and a sentence; empty means none, and then no text @@ -87,9 +87,8 @@ struct app_config { */ detail::logger::sink log = {}; /** - * The resource every allocation of the app goes through: its state, its connections, the peer - * connections and data channels its rooms' negotiations make, the frames received on them, the - * sentences of its log; not null. + * The resource every allocation of the app goes through: its state, its rooms' keys and the + * sentences of its log, and each room's whose `room_options::memory` is null; not null. * * What libdatachannel, OpenSSL and the browser's JavaScript allocate stays theirs. The app uses * the resource from its executor only, so it need not be thread-safe when that executor runs @@ -108,13 +107,14 @@ struct app_config { /** * What a room of an app is joined with: the part of Trystero's `joinRoom` configuration that is * the room's own. + * + * It has no handshake timeout: 0.27.0 removed `handshakeTimeoutMs`, and a peer has 10 s, its + * default, to finish the handshake. */ struct room_options { - /** - * How long a connected peer has to finish the handshake before it is dropped, Trystero's - * `handshakeTimeoutMs`. - */ - std::chrono::milliseconds handshake_timeout{10'000}; + /** The largest `max_users` a room takes, JavaScript's `Number.MAX_SAFE_INTEGER`, 2^53 - 1. */ + static constexpr std::uint64_t max_users_limit = (std::uint64_t{1} << 53U) - 1; + /** * The most bytes the room reserves at once for the transfers it receives, across peers, * Trystero's `maxReceiveBytes`. @@ -132,19 +132,52 @@ struct room_options { */ std::uint64_t max_json_document_bytes = webcpp::document::parse_options().max_document_bytes; /** - * The resource every allocation of the room goes through: its state, bindings, negotiations, - * relays, actions, sent frames, transfers and JSON. + * The most users the room holds, its own user included, Trystero's `maxUsers`; empty means no + * bound. + * + * `app::join` refuses 0 and a value above @ref max_users_limit with + * `error::invalid_max_users`, as 0.27.0's `joinRoom` throws on a value that is not a positive + * safe integer. + * + * The room counts users, not peers, by the user ids their handshakes verified: another peer of + * a user already in the room is admitted when it is full. A peer of a new user is refused once + * its handshake has passed, with a ready frame saying "room full", which its room reports as + * `error::room_full`; the room then does not connect to that peer again while it stays full. + */ + std::optional max_users = {}; + /** + * The resource every allocation of the room goes through: its state, negotiations, peer + * connections and data channels, the frames sent and received on them, relays, actions, + * transfers and JSON. * * Null means the app's resource. * * It must outlive the room, every value it hands out and every operation it leaves pending: on * Asio, until its io_context has run out of the room's work or has been destroyed; in the - * browser, until its pending promises have settled. Received frames and shared connections use - * the app's resource. + * browser, until its pending promises have settled. */ std::pmr::memory_resource* memory = nullptr; }; +/** + * How the relays of an app's rooms connect, Trystero's `RelayConnectivity`, which + * `app::set_relay_connectivity` sets for one app. + */ +enum class relay_connectivity { + /** Connected: a relay closed is reconnected, Trystero's `'online'`. */ + online, + /** Held closed: every relay socket is closed, and none is opened or reconnected until the app + * is online again, Trystero's `'offline'`. */ + offline, + /** Following the page, Trystero's `'auto'`, the default: offline from the page's `offline` + * event until its `online` event; natively, where no such event exists, online. + * + * Tip: unlike 0.27.0, which also reconnects the relays when the page becomes visible again + * (its `visibilitychange` listener), the port follows only the `online` and `offline` events. + */ + automatic, +}; + /** * Trystero's default STUN servers, its `defaultIceServers`: Google's and Cloudflare's. * diff --git a/include/webcpp/trystero/platform/backend.hpp b/include/webcpp/trystero/platform/backend.hpp index d2f38a8..a0002f6 100644 --- a/include/webcpp/trystero/platform/backend.hpp +++ b/include/webcpp/trystero/platform/backend.hpp @@ -12,18 +12,32 @@ #include #include #include +#include #include -#include -#include #include +#include #include #include #include #include +#include // lint-world: the backend's randomness +#include +#include +#include + #include // lint-world: names the executor only +#include // lint-world: binds an allocator only +#include // lint-world: binds an executor only #include // lint-world: the relays' TLS +#ifndef WEBCPP_TARGET_EMSCRIPTEN +#include // lint-world: the thread a PBKDF2 runs on +#else +#include + +#include +#endif #include @@ -34,6 +48,7 @@ #include #include #include +#include #include #include #include @@ -42,13 +57,80 @@ /** * The platform: one implementation of the backend interface for both targets, over webcpp::webrtc - * for WebRTC, webcpp::beast for the relays' WebSockets and webcpp::asio for timers; natively - * libdatachannel's WebRTC, Boost.Beast's WebSockets and OpenSSL's TLS, AES-GCM and randomness, in a - * page its own `RTCPeerConnection`, `WebSocket` and `crypto.subtle`. Everything it reports runs on - * the executor it is given, whose io_context the program runs. + * for WebRTC, webcpp::beast for the relays' WebSockets, webcpp::asio for timers, webcpp::crypto + * for randomness and webcpp::hash for a password's PBKDF2; natively libdatachannel's WebRTC, + * Boost.Beast's WebSockets and OpenSSL's TLS, in a page its own `RTCPeerConnection`, `WebSocket` + * and `crypto.subtle`. Everything it reports runs on the executor it is given, whose io_context + * the program runs. */ namespace webcpp::trystero::platform { +#ifdef WEBCPP_TARGET_EMSCRIPTEN +namespace detail { + +/** + * The page's `online` and `offline` events, a listener of each on the page's global object, each + * of which posts `changed` with `true` or `false` to the executor; the listeners are removed when + * it is destroyed, and a call posted then reaches nothing. + */ +class connectivity_watch { +public: + /** What each listener runs, on the executor. */ + struct event { + /** The watcher's handler, which both listeners share. */ + std::shared_ptr> changed; + /** Whether the event is `online`. */ + bool online = false; + + /** Calls the handler; the event itself is not read. */ + void operator()(const emscripten::val& /*event*/) const { (*changed)(online); } + }; + + /** Whether the page's global object takes listeners: a page's window or worker does, node's + * global object does not. */ + static bool page_has_events() { + return emscripten::val::global("addEventListener") + .typeOf() + .strictlyEquals(emscripten::val("function")); + } + + /** Adds both listeners, whose calls go through the bridge of `ex`'s io_context. */ + connectivity_watch(const webcpp::asio::any_io_executor& ex, handler changed, + std::pmr::memory_resource* memory) + : changed_(std::allocate_shared>( + std::pmr::polymorphic_allocator<>(memory), std::move(changed))), + online_(ex, event{.changed = changed_, .online = true}, memory), + offline_(ex, event{.changed = changed_, .online = false}, memory), + online_function_(online_.function()), + offline_function_(offline_.function()) { + const auto page = emscripten::val::global(); + page.call("addEventListener", emscripten::val("online"), online_function_); + page.call("addEventListener", emscripten::val("offline"), offline_function_); + } + + /** Not copyable: the page holds its listeners. */ + connectivity_watch(const connectivity_watch&) = delete; + /** Not copy-assignable. */ + connectivity_watch& operator=(const connectivity_watch&) = delete; + + /** Removes both listeners from the page. */ + ~connectivity_watch() { + const auto page = emscripten::val::global(); + page.call("removeEventListener", emscripten::val("online"), online_function_); + page.call("removeEventListener", emscripten::val("offline"), offline_function_); + } + +private: + std::shared_ptr> changed_; + page_call online_; + page_call offline_; + emscripten::val online_function_; + emscripten::val offline_function_; +}; + +} // namespace detail +#endif + /** * What a backend makes its peer connections, its relays' WebSockets and its own state with, beside * the app's `app_config::ice_servers`. @@ -107,9 +189,10 @@ struct backend_config { * page. * * It makes peer connections, data channels and received frames in `app_config::memory`, and - * WebSockets, sealers and room timers in the room's effective `room_options::memory`; its own state - * is in `backend_config::memory`. Objects and their handlers use the resource supplied to their - * factory method. What libdatachannel and OpenSSL allocate stays theirs, and what + * WebSockets and room timers in the room's effective `room_options::memory`; its own state is in + * `backend_config::memory`. Objects and their handlers use the resource supplied to their factory + * method, and a derivation its completion's allocator. What libdatachannel and OpenSSL allocate + * stays theirs, as does the thread of `derive_password_master` natively, and what * `emscripten::val` holds is in the JavaScript heap. * * Its peer connections are webcpp::webrtc's, counted by a `webcpp::webrtc::runtime`: its own, or @@ -123,7 +206,8 @@ struct backend_config { * Tip: in a page, every object it makes runs on its executor, whose io_context the program runs * from `main`, under a work guard, for as long as the page lives: the page's events, the timers and * the promises it awaits post to that io_context, and run only while it runs. A page needs a - * secure context (https, or http on localhost), where `crypto.subtle` exists, for its sealer. + * secure context (https, or http on localhost), where `crypto.subtle` exists, for the PBKDF2 of a + * room with a password. * * @see "The platform backend", in the guide. */ @@ -198,6 +282,29 @@ class backend : public trystero::backend::factory { std::shared_ptr<::webcpp::webrtc::runtime>(), &runtime), config) {} + /** + * Waits for the derivation its thread runs, natively, if any, then destroys the backend. + * + * The completion of that derivation is posted to the backend's executor, so its io_context + * must still exist: a program destroys the backend before its io_context. + */ + ~backend() override { +#ifndef WEBCPP_TARGET_EMSCRIPTEN + if (pool_) { + pool_->join(); + } +#endif + } + + /** Not copyable: its rooms, connections and relays hold it by reference. */ + backend(const backend&) = delete; + /** Not copy-assignable. */ + backend& operator=(const backend&) = delete; + /** Not movable: its rooms, connections and relays hold it by reference. */ + backend(backend&&) = delete; + /** Not move-assignable. */ + backend& operator=(backend&&) = delete; + /** * The executor everything the backend reports runs on. * @@ -257,7 +364,7 @@ class backend : public trystero::backend::factory { * `RTCPeerConnection` refuses the connection for a server it cannot use. * * @param servers The STUN and TURN servers, read during the call. - * @param memory The app's resource, which the connection, its channels, its handlers and its + * @param memory The room's resource, which the connection, its channels, its handlers and its * texts are allocated in. * @return The connection, or null when the backend made * `backend_config::max_peer_connections_per_minute` in the last minute, when its runtime holds @@ -269,12 +376,12 @@ class backend : public trystero::backend::factory { if (!constructions_.take(steady_now())) { return nullptr; } - auto made = webrtc::peer_connection::make(runtime_, ex_, servers, config_.bind_address, - *this, memory); + auto made = + webrtc::peer_connection::make(runtime_, ex_, servers, config_.bind_address, memory); #ifndef WEBCPP_TARGET_EMSCRIPTEN if (!made && made.error() == ::webcpp::webrtc::error::syntax_error) { made = webrtc::peer_connection::make(runtime_, ex_, parsed(servers, memory), - config_.bind_address, *this, memory); + config_.bind_address, memory); } #endif return made ? *made : nullptr; @@ -293,28 +400,58 @@ class backend : public trystero::backend::factory { } /** - * Makes a sealer: natively over OpenSSL's AES-256-GCM, in a page over `crypto.subtle`. + * Derives a room's PBKDF2 master off the room's thread: natively with + * `webcpp::hash::async_pbkdf2` on a thread of the backend's own, made at the first call and + * joined when the backend is destroyed; in a page through the page's WebCrypto + * (`backends::webcrypto`), awaited on the backend's executor. * - * @param key The raw AES-256 key. - * @param memory The room's resource, which the sealer, its texts and its completions are - * allocated in. - * @return The sealer. + * @param password The password, in UTF-8; the caller's until `done` runs. + * @param salt The salt; the caller's until `done` runs. + * @param out Where the master is written; the caller's until `done` runs, zeroed on error. + * @param done Called on the backend's executor, after the call returns, once the master is + * written, or with `error::backend_failure`; the derivation's operation is allocated with its + * allocator. */ - std::shared_ptr make_sealer( - std::array key, std::pmr::memory_resource* memory) override { - return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), ex_, key, - memory); + void derive_password_master(std::span password, + std::span salt, + std::span out, + handler done) override { + // The pool's thread dispatches the completion through `ex_`, an `any_io_executor`, which + // drops the allocator property: so nothing is allocated in `done`'s resource there, off + // the room's thread. A concrete executor type would change that. + const auto allocator = done.get_allocator(); + auto completion = webcpp::asio::bind_executor( + ex_, webcpp::asio::bind_allocator(allocator, [out, done = std::move(done)]( + boost::system::error_code ec) mutable { + if (ec) { + webcpp::trystero::detail::wipe(out.data(), out.size()); + done(make_error_code(error::backend_failure)); + return; + } + done({}); + })); +#ifdef WEBCPP_TARGET_EMSCRIPTEN + webcpp::hash::async_pbkdf2( + ex_, out, password, salt, protocol::pbkdf2_iterations, std::move(completion)); +#else + if (!pool_) { + pool_.emplace(1); + } + webcpp::hash::async_pbkdf2( + pool_->get_executor(), out, password, salt, protocol::pbkdf2_iterations, + std::move(completion)); +#endif } /** - * Fills `out` from the platform's secure source of randomness, natively OpenSSL's generator, - * in a page its `crypto.getRandomValues`; the program aborts when it has none. + * Fills `out` from the system's generator, through webcpp::crypto, in a page its + * `crypto.getRandomValues`; the program aborts when it has none. * * @param out The bytes to fill. */ void random(std::span out) override { - if (!detail::fill_random(out)) { - std::abort(); // no secure randomness: nothing is safe + if (!webcpp::crypto::random_device().fill(out)) { // lint-world: Trystero's randomness + std::abort(); // no secure randomness: nothing is safe } } @@ -337,6 +474,29 @@ class backend : public trystero::backend::factory { return std::chrono::steady_clock::now(); // lint-world: Trystero's timing } +#ifdef WEBCPP_TARGET_EMSCRIPTEN + /** + * Watches the page's `online` and `offline` events, through listeners on its global object + * whose calls post to the backend's executor; natively, where there are none, it watches + * nothing, as the interface's default does. + * + * @param changed Called on the backend's executor after each event: `true` after `online`, + * `false` after `offline`. + * @param memory The app's resource, which the watch, its listeners' state and the calls they + * post are allocated in. + * @return The watch, whose destruction removes the listeners; null where the page's global + * object takes no listener, as node's. + */ + std::shared_ptr watch_connectivity(handler changed, + std::pmr::memory_resource* memory) override { + if (!detail::connectivity_watch::page_has_events()) { + return nullptr; + } + return std::allocate_shared( + std::pmr::polymorphic_allocator<>(memory), ex_, std::move(changed), memory); + } +#endif + private: // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on backend(webcpp::asio::any_io_executor ex, boost::system::result tls, @@ -406,6 +566,10 @@ class backend : public trystero::backend::factory { std::shared_ptr<::webcpp::webrtc::runtime> runtime_; trystero::detail::construction_window constructions_; boost::system::result tls_; +#ifndef WEBCPP_TARGET_EMSCRIPTEN + // The one thread of the derivations, made at the first. + std::optional pool_; +#endif }; } // namespace webcpp::trystero::platform diff --git a/include/webcpp/trystero/platform/entropy.hpp b/include/webcpp/trystero/platform/entropy.hpp deleted file mode 100644 index 7962403..0000000 --- a/include/webcpp/trystero/platform/entropy.hpp +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -#ifndef WEBCPP_TRYSTERO_PLATFORM_ENTROPY_HPP -#define WEBCPP_TRYSTERO_PLATFORM_ENTROPY_HPP - -#include - -#ifdef WEBCPP_TARGET_EMSCRIPTEN -#include -#else -#include -#endif - -#include -#include -#include -#include - -namespace webcpp::trystero::platform::detail { - -#ifdef WEBCPP_TARGET_EMSCRIPTEN - -// clang-format off -/** - * Fills the `size` bytes at `data` from the page's `crypto.getRandomValues`: 0 when it filled - * them, -1 when the page has no such function or it threw, caught here, so that no JavaScript - * exception enters WebAssembly, as one does through the C library's entropy call, Emscripten's, - * which lets the page's exception through. - */ -// NOLINTNEXTLINE(misc-const-correctness): JavaScript writes to the pointed WebAssembly storage -inline int js_fill_random(void* data, std::size_t size) { - return EM_ASM_INT(({ - const data = $0 >>> 0; - const size = $1 >>> 0; - - try { - const view = HEAPU8.subarray(data, data + size); - /* Web Crypto fills no view of a SharedArrayBuffer, which a threaded build's memory is. */ - if (view.buffer instanceof ArrayBuffer) { - crypto.getRandomValues(view); - } else { - view.set(crypto.getRandomValues(new Uint8Array(size))); - } - return 0; - } catch (_) { - return -1; - } - }), data, size); -} -// clang-format on - -#endif - -/** - * Fills `out` from the platform's one secure source of randomness, its result checked: natively - * OpenSSL's generator; on emscripten the page's `crypto.getRandomValues`, whose absence or - * exception is a failure, not an exception in WebAssembly. - * - * @param out The bytes to fill. - * @return Whether every byte was filled; on false, the bytes must not be used. - */ -inline bool fill_random(std::span out) noexcept { -#ifdef WEBCPP_TARGET_EMSCRIPTEN - // Web Crypto fills at most 65536 bytes a call, and throws for more. - constexpr std::size_t most = std::size_t{1} << 16U; -#else - // OpenSSL's generator takes its count as an int. - constexpr std::size_t most = std::size_t{1} << 30U; -#endif - for (std::size_t at = 0; at < out.size(); at += most) { - const auto piece = std::min(most, out.size() - at); -#ifdef WEBCPP_TARGET_EMSCRIPTEN - if (js_fill_random(out.data() + at, piece) != 0) { // lint-world: Trystero's randomness - return false; - } -#else - const auto count = static_cast(piece); // at most 2^30, in an int's range - if (RAND_bytes(out.data() + at, count) != 1) { // lint-world: Trystero's randomness - return false; - } -#endif - } - return true; -} - -} // namespace webcpp::trystero::platform::detail - -#endif diff --git a/include/webcpp/trystero/platform/sealer.hpp b/include/webcpp/trystero/platform/sealer.hpp deleted file mode 100644 index 7bd9852..0000000 --- a/include/webcpp/trystero/platform/sealer.hpp +++ /dev/null @@ -1,488 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -#ifndef WEBCPP_TRYSTERO_PLATFORM_SEALER_HPP -#define WEBCPP_TRYSTERO_PLATFORM_SEALER_HPP - -#include - -#include -#include -#include -#include -#include -#include - -#include // lint-world: posts handlers only - -#ifdef WEBCPP_TARGET_EMSCRIPTEN -#include // lint-world: binds an allocator only -#include // lint-world: awaits the page's promises -#include // lint-world: names its executor only - -#include -#include -#include - -#include -#else -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace webcpp::trystero::platform { - -namespace detail { - -#ifdef WEBCPP_TARGET_EMSCRIPTEN - -// The page's Web Crypto, called from C++. Each function is an EM_ASM block in an inline function, -// which Emscripten allows in several translation units, as webcpp::webrtc's and webcpp::beast's -// browser imports are. A Web Crypto call is made inside an async function, so that what it throws -// becomes the rejection of the promise it returns, and no JavaScript exception reaches a -// WebAssembly frame. The functions use Emval and HEAPU8, which webcpp::asio's browser runtime has -// Emscripten link, in every program on /webcpp/asio//asio. - -// clang-format off -/** Copies the first `size` bytes of `bytes`, a `Uint8Array`, to `data`. */ -// NOLINTNEXTLINE(misc-const-correctness): JavaScript writes to the pointed WebAssembly storage -inline void js_copy(emscripten::EM_VAL bytes, void* data, std::size_t size) { - EM_ASM(({ - const bytes = Emval.toValue($0); - const data = $1 >>> 0; - const size = $2 >>> 0; - - HEAPU8.set(bytes.subarray(0, size), data); - }), bytes, data, size); -} - -/** - * A promise of the AES-GCM key of the `size` raw bytes at `key`, from `crypto.subtle.importKey`, - * rejected where there is no `crypto.subtle`. - */ -inline emscripten::EM_VAL js_import_key(const std::uint8_t* key, std::size_t size) { - return reinterpret_cast(EM_ASM_PTR(({ - const key = $0 >>> 0; - const size = $1 >>> 0; - - const raw = HEAPU8.slice(key, key + size); - return Emval.toHandle((async () => crypto.subtle.importKey('raw', raw, 'AES-GCM', false, - ['encrypt', 'decrypt']))()); - }), key, size)); -} - -/** - * A promise of `crypto.subtle.encrypt`, or `decrypt`, of the `size` bytes at `data` under `key` - * and the IV at `iv`, rejected for what the call throws as for what it rejects. - */ -inline emscripten::EM_VAL js_crypt(bool decrypt, emscripten::EM_VAL key, const std::uint8_t* iv, - std::size_t iv_size, const void* data, std::size_t size) { - return reinterpret_cast(EM_ASM_PTR(({ - const decrypt = $0; - const key = Emval.toValue($1); - const iv = HEAPU8.slice($2 >>> 0, ($2 >>> 0) + ($3 >>> 0)); - const data = HEAPU8.slice($4 >>> 0, ($4 >>> 0) + ($5 >>> 0)); - - const algorithm = {name: 'AES-GCM', iv}; - return Emval.toHandle((async () => decrypt ? crypto.subtle.decrypt(algorithm, key, data) - : crypto.subtle.encrypt(algorithm, key, data))()); - }), decrypt, key, iv, iv_size, data, size)); -} -// clang-format on - -/** Takes ownership of a handle an import returned. */ -inline emscripten::val take(emscripten::EM_VAL handle) { - return emscripten::val::take_ownership(handle); -} - -/** - * A copy of the bytes of a Web Crypto settlement, in `memory`; nothing when it is no `ArrayBuffer`, - * which a page whose `crypto.subtle` was replaced can settle with, and whose reading as one could - * throw (`new Uint8Array(-1)`) or read what it is not. - */ -inline std::optional from_js(const emscripten::val& buffer, - std::pmr::memory_resource* memory) { - if (!buffer.instanceof(emscripten::val::global("ArrayBuffer"))) { - return std::nullopt; - } - const emscripten::val view = emscripten::val::global("Uint8Array").new_(buffer); - backend::bytes out(view["length"].as(), memory); - js_copy(view.as_handle(), out.data(), out.size()); - return out; -} - -#else - -/** Frees an OpenSSL cipher context. */ -struct cipher_context_deleter { - /** Frees `c`. */ - void operator()(EVP_CIPHER_CTX* c) const { EVP_CIPHER_CTX_free(c); } -}; - -/** An OpenSSL cipher context, freed with its owner. */ -using cipher_context = std::unique_ptr; - -/** The size of AES-GCM's authentication tag, which WebCrypto appends to the ciphertext. */ -inline constexpr std::size_t gcm_tag_size = 16; - -/** AES-256-GCM with a 16-byte IV, the ciphertext followed by its 16-byte tag: what WebCrypto's - * encrypt returns. */ -inline std::optional aes_gcm(bool encrypt, const std::array& key, - std::span iv, - std::span input, - std::pmr::memory_resource* memory) { - if (!encrypt && input.size() < gcm_tag_size) { - return std::nullopt; - } - const cipher_context context(EVP_CIPHER_CTX_new()); - if (!context) { - return std::nullopt; - } - const auto body = encrypt ? input : input.first(input.size() - gcm_tag_size); - backend::bytes out(body.size() + (encrypt ? gcm_tag_size : 0), memory); - int length = 0; - int final_length = 0; - // OpenSSL's functions return 0 when they fail. - bool ok = EVP_CipherInit_ex(context.get(), EVP_aes_256_gcm(), nullptr, nullptr, nullptr, - encrypt ? 1 : 0) != 0 && - EVP_CIPHER_CTX_ctrl(context.get(), EVP_CTRL_GCM_SET_IVLEN, - static_cast(iv.size()), nullptr) != 0 && - EVP_CipherInit_ex(context.get(), nullptr, nullptr, key.data(), iv.data(), -1) != 0 && - EVP_CipherUpdate(context.get(), out.data(), &length, body.data(), - static_cast(body.size())) != 0; - if (ok && !encrypt) { - // OpenSSL takes the expected tag through a pointer to mutable bytes, and only reads it. - auto* tag = const_cast(input.data() + body.size()); - ok = EVP_CIPHER_CTX_ctrl(context.get(), EVP_CTRL_GCM_SET_TAG, - static_cast(gcm_tag_size), tag) != 0; - } - ok = ok && EVP_CipherFinal_ex(context.get(), out.data() + length, &final_length) != 0; - if (ok && encrypt) { - ok = EVP_CIPHER_CTX_ctrl(context.get(), EVP_CTRL_GCM_GET_TAG, - static_cast(gcm_tag_size), out.data() + body.size()) != 0; - } - if (!ok) { - return std::nullopt; - } - return out; -} - -#endif - -} // namespace detail - -#ifdef WEBCPP_TARGET_EMSCRIPTEN - -/** - * AES-GCM under one room key, in Trystero's sealed text form: on emscripten through the page's - * `crypto.subtle`, under a key imported once, as Trystero's `encrypt` and `decrypt` do. - * - * Each Web Crypto promise is awaited with webcpp::asio's `browser::async_await`, which posts its - * settlement to the executor, through the io_context's own executor when the executor is one, so - * that the wait and the settlement's post are both in the room's resource. The text is copied into - * JavaScript during the call; an operation that arrives while the key is still being imported waits - * with a copy of its text, in the room's resource. Without `crypto.subtle`, outside a secure - * context, every operation fails. A seal's IV comes from the platform's one source of randomness, - * the page's `crypto.getRandomValues` there. - * - * @see "The platform backend", in the guide. - */ -class sealer : public backend::sealer, public std::enable_shared_from_this { -public: - /** What a seal or an open completes with: an error, or the text, a view valid for the call. */ - using done_handler = handler; - - /** - * Constructs a sealer under a room's key, which it imports on its first operation. - * - * @param ex The executor its completions run on, an io_context's of webcpp::asio, which must - * outlive the sealer's pending promises. - * @param key The raw AES-256 key, `protocol::seal_key`'s. - * @param memory The room's resource, which its texts, its waiting operations and its - * completions are allocated in. - */ - sealer(webcpp::asio::any_io_executor ex, std::array key, - std::pmr::memory_resource* memory) - : ex_(std::move(ex)), raw_key_(key), memory_(memory), waiting_(memory) {} - - /** - * Seals a text under a fresh random IV, with `crypto.subtle.encrypt`. - * - * @param plaintext The text, read during the call. - * @param done Called with the sealed text, or with `error::backend_failure` when the key - * cannot be imported, the page has no entropy for the IV, or the encryption fails. - */ - void seal(std::string_view plaintext, done_handler done) override { - if (state_ == key_state::ready) { - encrypt(plaintext, std::move(done)); - return; - } - wait_for_key({std::allocator_arg, allocator(), - [plaintext = std::pmr::string(plaintext, memory_), done = std::move(done)]( - sealer& self, bool ok) mutable { - if (!ok) { - done(make_error_code(error::backend_failure), {}); - return; - } - self.encrypt(plaintext, std::move(done)); - }}); - } - - /** - * Opens a sealed text, with `crypto.subtle.decrypt`. - * - * @param sealed The sealed text, read during the call. - * @param done Called with the plaintext, or with `error::wrong_password` when the text was - * sealed under another key or is not a sealed text, and `error::backend_failure` when the key - * cannot be imported. - */ - void open(std::string_view sealed, done_handler done) override { - if (state_ == key_state::ready) { - decrypt(sealed, std::move(done)); - return; - } - wait_for_key({std::allocator_arg, allocator(), - [sealed = std::pmr::string(sealed, memory_), done = std::move(done)]( - sealer& self, bool ok) mutable { - if (!ok) { - done(make_error_code(error::backend_failure), {}); - return; - } - self.decrypt(sealed, std::move(done)); - }}); - } - -private: - using waiting_operation = handler; - - [[nodiscard]] std::pmr::polymorphic_allocator<> allocator() const { return {memory_}; } - - /** Calls `done` with `failure` after the call, on the executor. */ - void fail(done_handler done, trystero::error failure) { - trystero::detail::post(ex_, memory_, [done = std::move(done), failure]() mutable { - done(make_error_code(failure), {}); - }); - } - - /** - * Awaits `promise`, its settlement posted to `handler` through the io_context's own executor - * when `ex_` is one. - * - * Tip: as `trystero::detail::post` does. Asio posts what it posts through an `any_io_executor` - * in a function object and an operation of `std::allocator`, which it takes from the C library - * when its cache has none (measured: two for each seal and each open); through the io_context's - * own executor the operation is allocated as the handler's allocator says, in the room's - * resource. - */ - template - void await(emscripten::val promise, Handler&& handler) { - if (const auto* io = ex_.target()) { - webcpp::asio::browser::async_await(*io, std::move(promise), - std::forward(handler)); - return; - } - webcpp::asio::browser::async_await(ex_, std::move(promise), std::forward(handler)); - } - - void encrypt(std::string_view plaintext, done_handler done) { - std::array iv{}; - if (!detail::fill_random(iv)) { - fail(std::move(done), error::backend_failure); - return; - } - await(detail::take(detail::js_crypt(false, key_.as_handle(), iv.data(), iv.size(), - plaintext.data(), plaintext.size())), - webcpp::asio::bind_allocator( - allocator(), - [iv, done = std::move(done), memory = memory_]( - boost::system::error_code ec, const emscripten::val& cipher) mutable { - const auto bytes = ec ? std::nullopt : detail::from_js(cipher, memory); - if (!bytes) { - done(make_error_code(error::backend_failure), {}); - return; - } - const auto sealed = protocol::format_sealed(iv, *bytes, memory); - done({}, sealed); - })); - } - - void decrypt(std::string_view sealed, done_handler done) { - const auto parts = protocol::parse_sealed(sealed, memory_); - if (!parts || parts->iv.empty()) { - fail(std::move(done), error::wrong_password); - return; - } - await(detail::take(detail::js_crypt(true, key_.as_handle(), parts->iv.data(), - parts->iv.size(), parts->ciphertext.data(), - parts->ciphertext.size())), - webcpp::asio::bind_allocator(allocator(), [done = std::move(done), memory = memory_]( - boost::system::error_code ec, - const emscripten::val& plain) mutable { - if (ec) { - done(make_error_code(error::wrong_password), {}); - return; - } - const auto b = detail::from_js(plain, memory); - if (!b) { - done(make_error_code(error::backend_failure), {}); - return; - } - done({}, std::string_view(reinterpret_cast(b->data()), b->size())); - })); - } - - /** - * Runs `op` once the key is imported, or has failed to be: after the call in every case, so - * that no completion runs inside the operation that started it. - */ - void wait_for_key(waiting_operation op) { - const std::weak_ptr weak = weak_from_this(); - if (state_ == key_state::failed) { - trystero::detail::post(ex_, memory_, [weak, op = std::move(op)]() mutable { - if (const auto self = weak.lock()) { - op(*self, false); - } - }); - return; - } - waiting_.push_back(std::move(op)); - if (state_ == key_state::importing) { - return; - } - state_ = key_state::importing; - await(detail::take(detail::js_import_key(raw_key_.data(), raw_key_.size())), - webcpp::asio::bind_allocator( - allocator(), [weak](boost::system::error_code ec, const emscripten::val& key) { - if (const auto self = weak.lock()) { - self->key_imported(!ec, key); - } - })); - } - - void key_imported(bool ok, const emscripten::val& key) { - state_ = ok ? key_state::ready : key_state::failed; - key_ = key; - std::pmr::deque ready(allocator()); - ready.swap(waiting_); - for (auto& op : ready) { - op(*this, ok); - } - } - - enum class key_state : std::uint8_t { none, importing, ready, failed }; - - webcpp::asio::any_io_executor ex_; - std::array raw_key_; - std::pmr::memory_resource* memory_; - key_state state_ = key_state::none; - emscripten::val key_ = emscripten::val::undefined(); - std::pmr::deque waiting_; -}; - -#else - -/** - * AES-GCM under one room key, in Trystero's sealed text form: natively through OpenSSL, what - * Trystero's `encrypt` and `decrypt` do with `crypto.subtle`. - * - * It works synchronously and posts each completion to the executor, as the backend interface asks: - * a handler never runs inside the call that started it. Its texts and completions are in the - * room's resource; OpenSSL's cipher context is OpenSSL's. A seal's IV comes from the platform's one - * source of randomness, OpenSSL's generator there. It needs no exceptions. - * - * @see "The platform backend", in the guide. - */ -class sealer : public backend::sealer { -public: - /** What a seal or an open completes with: an error, or the text, a view valid for the call. */ - using done_handler = handler; - - /** - * Constructs a sealer under a room's key. - * - * @param ex The executor its completions are posted to. - * @param key The raw AES-256 key, `protocol::seal_key`'s. - * @param memory The room's resource, which its texts and its completions are allocated in; it - * must outlive the completions it posts. - */ - sealer(webcpp::asio::any_io_executor ex, std::array key, - std::pmr::memory_resource* memory) - : ex_(std::move(ex)), key_(key), memory_(memory) {} - - /** - * Seals a text under a fresh random IV. - * - * @param plaintext The text, read during the call. - * @param done Called on the executor with the sealed text, or with `error::backend_failure` - * when there is no randomness for the IV or OpenSSL fails. - */ - void seal(std::string_view plaintext, done_handler done) override { - std::array iv{}; - if (!detail::fill_random(iv)) { - complete(std::move(done), error::backend_failure); - return; - } - const auto cipher = detail::aes_gcm( - true, key_, iv, - std::span(reinterpret_cast(plaintext.data()), plaintext.size()), - memory_); - if (!cipher) { - complete(std::move(done), error::backend_failure); - return; - } - complete(std::move(done), {}, protocol::format_sealed(iv, *cipher, memory_)); - } - - /** - * Opens a sealed text. - * - * @param sealed The sealed text, read during the call. - * @param done Called on the executor with the plaintext, or with `error::wrong_password` when - * the text was sealed under another key or is not a sealed text. - */ - void open(std::string_view sealed, done_handler done) override { - const auto parts = protocol::parse_sealed(sealed, memory_); - const auto plain = parts && !parts->iv.empty() - ? detail::aes_gcm(false, key_, parts->iv, parts->ciphertext, memory_) - : std::nullopt; - if (!plain) { - complete(std::move(done), error::wrong_password); - return; - } - complete(std::move(done), {}, std::pmr::string(plain->begin(), plain->end(), memory_)); - } - -private: - void complete(done_handler done, backend::error_code ec, std::pmr::string text) { - trystero::detail::post( - ex_, memory_, - [done = std::move(done), ec, text = std::move(text)]() mutable { done(ec, text); }); - } - - void complete(done_handler done, error e) { - complete(std::move(done), make_error_code(e), std::pmr::string(memory_)); - } - - webcpp::asio::any_io_executor ex_; - std::array key_; - std::pmr::memory_resource* memory_; -}; - -#endif - -} // namespace webcpp::trystero::platform - -#endif diff --git a/include/webcpp/trystero/platform/websocket.hpp b/include/webcpp/trystero/platform/websocket.hpp index 755eebe..7338069 100644 --- a/include/webcpp/trystero/platform/websocket.hpp +++ b/include/webcpp/trystero/platform/websocket.hpp @@ -390,24 +390,25 @@ class websocket_session : public std::enable_shared_from_this limits_.max_queued_bytes) { // The relay stopped reading: no close frame could reach it, so the socket is closed, // the read fails, and end() reports the close. closing_ = true; webcpp::beast::get_lowest_layer(ws_).close(); - return; + return false; } queued_bytes_ += text.size(); queue_.emplace_back(text); // a write outlives the call, so the text is copied once, here - if (std::exchange(writing_, true)) { - return; + if (!std::exchange(writing_, true)) { + write_next(); } - write_next(); + return true; } /** Closes with a WebSocket close frame, or drops a connection still being made. */ @@ -742,8 +743,8 @@ class websocket_handle : public backend::websocket { /** Abandons the session. */ ~websocket_handle() override { session_->abandon(); } - /** Sends a text through the session. */ - void send(std::string_view text) override { session_->send(text); } + /** Sends a text through the session; whether it was queued. */ + bool send(std::string_view text) override { return session_->send(text); } /** Closes the session. */ void close() override { session_->close(); } diff --git a/include/webcpp/trystero/protocol/action_wire.hpp b/include/webcpp/trystero/protocol/action_wire.hpp index 0085905..842b1d1 100644 --- a/include/webcpp/trystero/protocol/action_wire.hpp +++ b/include/webcpp/trystero/protocol/action_wire.hpp @@ -9,14 +9,16 @@ #include -#include +#include #include #include #include #include +#include #include +#include #include #include #include @@ -29,7 +31,7 @@ namespace webcpp::trystero::protocol { /** - * The format of an action's payload, the high four bits of a frame's second byte: how Trystero's + * The format of an action's payload, bits 4 and 5 of a frame's second byte: how Trystero's * `decodePayload` reads it. * * @see "The protocol", in the guide. @@ -45,20 +47,23 @@ enum class payload_format : std::uint8_t { /** * The kind of an action frame, the low four bits of its second byte, in Trystero's action wire, - * version 2. + * version 3 (0.27.0's `action-wire.ts`). * * A payload that fits one frame travels inline; a larger one is offered, accepted by the receiver, * then sent in chunks. Integers and float64 values are big-endian, as `DataView` writes them. * * | Frame | Bytes | - * | inline (kind 0) | 2, kind or format << 4, name (32 bytes, NUL padded), metadata length | + * | inline (kind 0) | 3, kind or format << 4, name (32 bytes, NUL padded), metadata length | * | | (uint16), metadata, payload | - * | offer (kind 1) | the inline header, transfer id (uint32), payload size (float64), | - * | | metadata | - * | chunk (kind 2) | 2, 2, transfer id (uint32), offset (float64), bytes | - * | accepted (kind 3) | 2, 3, transfer id (uint32) | - * | rejected (kind 4) | 2, 4, transfer id (uint32), reason (UTF-8, at most 200 bytes) | - * | cancelled (kind 5) | 2, 5, transfer id (uint32) | + * | offer (kind 1) | the inline header, with @ref wide_bulk_flag in the second byte when its | + * | | chunks are wide; transfer id (uint32), payload size (float64), metadata | + * | chunk (kind 2) | 3, 2, transfer id (uint32), offset (float64), bytes | + * | accepted (kind 3) | 3, 3, transfer id (uint32) | + * | rejected (kind 4) | 3, 4, transfer id (uint32), reason (UTF-8, at most 200 bytes) | + * | cancelled (kind 5) | 3, 5, transfer id (uint32) | + * + * Every frame but a chunk is at most @ref max_action_frame_bytes; a chunk of a wide transfer is at + * most @ref max_bulk_frame_bytes, one of any other at most @ref max_action_frame_bytes. * * @see "The protocol", in the guide. */ @@ -77,8 +82,41 @@ enum class frame_kind : std::uint8_t { cancelled = 5, }; -/** The version of the action wire, every frame's first byte, Trystero's `version`. */ -inline constexpr std::uint8_t action_wire_version = 2; +/** The version of the action wire, every frame's first byte, Trystero's `actionWireVersion`. */ +inline constexpr std::uint8_t action_wire_version = 3; +/** + * The flag of an offer whose chunks are wide, up to @ref max_bulk_frame_bytes each, in its second + * byte above the format, Trystero's `wideBulkFlag`. + * + * Trystero sets it when the connection's SCTP + * takes messages of @ref max_bulk_frame_bytes; no other frame may carry it. + */ +inline constexpr std::uint8_t wide_bulk_flag = 64; +/** The chunks a transfer's offer announces: @ref chunk_size or, under @ref wide_bulk_flag, + * @ref wide_chunk_size bytes each but the last. */ +enum class chunk_width : std::uint8_t { + /** Chunks of @ref chunk_size, as every transport takes. */ + narrow, + /** Chunks of @ref wide_chunk_size, for a connection whose SCTP takes 64 KiB messages. */ + wide, +}; +/** The largest action frame, Trystero's `maxActionFrameBytes`: 16 KiB. */ +inline constexpr std::size_t max_action_frame_bytes = std::size_t{16} * 1024; +/** The largest chunk frame of a wide transfer, Trystero's `maxBulkFrameBytes`: 64 KiB. */ +inline constexpr std::size_t max_bulk_frame_bytes = std::size_t{64} * 1024; +/** The longest header an overlay puts around an action frame, Trystero's + * `maxOverlayHeaderBytes`. */ +inline constexpr std::size_t max_overlay_header_bytes = 1024; +/** The longest message a peer's channel takes before its room binds it, an action frame and its + * overlay's header, Trystero's `maxRoomFrameBytes`: 17 KiB. */ +inline constexpr std::size_t max_room_frame_bytes = + max_action_frame_bytes + max_overlay_header_bytes; +/** The most messages a peer's channel keeps before its room binds it, Trystero's + * `maxQueuedDataFrames`. */ +inline constexpr std::size_t max_queued_data_frames = 64; +/** How long after its first kept message a peer's channel waits for its room, Trystero's + * `pendingDataTimeoutMs`. */ +inline constexpr std::chrono::milliseconds pending_data_timeout{10'000}; /** The size of an inline frame's header, Trystero's `inlineHeaderSize`. */ inline constexpr std::size_t inline_header_size = 36; /** The size of an offer's header, Trystero's `offerHeaderSize`. */ @@ -87,14 +125,34 @@ inline constexpr std::size_t offer_header_size = 48; inline constexpr std::size_t control_header_size = 6; /** The size of a chunk's header, Trystero's `chunkHeaderSize`. */ inline constexpr std::size_t chunk_header_size = 14; -/** The most payload bytes one chunk carries, Trystero's `chunkSize`. */ +/** The payload bytes each chunk but the last carries, Trystero's `minChunkSize`. */ inline constexpr std::size_t chunk_size = max_action_frame_bytes - chunk_header_size; +/** The payload bytes each chunk but the last of a wide transfer carries, `maxChunkSize`. */ +inline constexpr std::size_t wide_chunk_size = max_bulk_frame_bytes - chunk_header_size; /** The longest action name, in UTF-8 bytes. */ inline constexpr std::size_t max_action_name_bytes = 32; /** The longest reason a rejected frame carries, in UTF-8 bytes. */ inline constexpr std::size_t max_reject_reason_bytes = 200; /** The largest size an offer may announce, JavaScript's `Number.MAX_SAFE_INTEGER`, 2^53 - 1. */ inline constexpr std::uint64_t max_offer_size = 9007199254740991; +/** The most transfers a receiver keeps pending across its peers, `maxPendingTransfers`. */ +inline constexpr std::size_t max_pending_transfers = 1024; +/** The most transfers a receiver keeps pending of one peer, Trystero's `maxPendingPerPeer`. */ +inline constexpr std::size_t max_pending_transfers_per_peer = 64; +/** The most receive decisions a receiver awaits across its peers, Trystero's `maxDecisions`. */ +inline constexpr std::size_t max_receive_decisions = 128; +/** The most receive decisions a receiver awaits of one peer, `maxDecisionsPerPeer`. */ +inline constexpr std::size_t max_receive_decisions_per_peer = 8; +/** The most messages of one action and peer kept until the action can take them, + * `maxPreListenerMessages`; a newer one drops the oldest. */ +inline constexpr std::size_t max_pre_listener_messages = 32; +/** + * The most bytes a channel may buffer for a control frame to be sent on it, + * `maxControlBufferedBytes`: 1 MiB. + * + * Above it the peer is dropped. + */ +inline constexpr std::size_t max_control_buffered_bytes = std::size_t{1024} * 1024; namespace detail { @@ -163,12 +221,14 @@ namespace detail { /** Appends the header an inline frame and an offer share: version, kind and format, name. */ inline void append_header(bytes& out, frame_kind kind, std::string_view name, payload_format format, - std::string_view metadata, std::size_t header_size) { + std::string_view metadata, std::size_t header_size, + chunk_width width = chunk_width::narrow) { const auto at = out.size(); out.resize(at + header_size, 0); out[at] = action_wire_version; out[at + 1] = static_cast(static_cast(kind) | - (static_cast(format) << 4U)); + (static_cast(format) << 4U) | + (width == chunk_width::wide ? wide_bulk_flag : 0U)); std::memcpy(out.data() + at + 2, name.data(), name.size()); set_u16(out, at + 34, static_cast(metadata.size())); } @@ -212,13 +272,15 @@ inline void append_inline(bytes& out, std::string_view name, payload_format form * @param metadata JSON text, or empty. * @param id The transfer's id. * @param size The payload's size in bytes. + * @param width The chunks' width: @ref wide_chunk_size each but the last when wide. * @pre `valid_action_name(name)`, and the metadata fits one frame after the offer's header. */ inline void append_offer(bytes& out, std::string_view name, payload_format format, - std::string_view metadata, std::uint32_t id, std::size_t size) { + std::string_view metadata, std::uint32_t id, std::size_t size, + chunk_width width = chunk_width::narrow) { out.reserve(out.size() + offer_header_size + metadata.size()); const auto at = out.size(); - detail::append_header(out, frame_kind::offer, name, format, metadata, offer_header_size); + detail::append_header(out, frame_kind::offer, name, format, metadata, offer_header_size, width); detail::set_u32(out, at + 36, id); detail::set_f64(out, at + 40, static_cast(size)); out.insert(out.end(), metadata.begin(), metadata.end()); @@ -230,7 +292,8 @@ inline void append_offer(bytes& out, std::string_view name, payload_format forma * @param out The buffer to append to. * @param id The transfer's id. * @param offset Where `data` starts in the payload. - * @param data At most @ref chunk_size bytes of the payload. + * @param data At most @ref chunk_size bytes of the payload, or @ref wide_chunk_size in a wide + * transfer. */ inline void append_chunk(bytes& out, std::uint32_t id, std::size_t offset, std::span data) { @@ -303,14 +366,16 @@ inline bytes encode_inline(std::string_view name, payload_format format, std::st * @param metadata JSON text, or empty. * @param id The transfer's id. * @param size The payload's size in bytes. + * @param width The chunks' width. * @param memory The resource the frame is allocated in. * @return The frame, as @ref append_offer writes it. */ inline bytes encode_offer(std::string_view name, payload_format format, std::string_view metadata, std::uint32_t id, std::size_t size, + chunk_width width = chunk_width::narrow, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { bytes out(memory); - append_offer(out, name, format, metadata, id, size); + append_offer(out, name, format, metadata, id, size, width); return out; } @@ -319,7 +384,8 @@ inline bytes encode_offer(std::string_view name, payload_format format, std::str * * @param id The transfer's id. * @param offset Where `data` starts in the payload. - * @param data At most @ref chunk_size bytes of the payload. + * @param data At most @ref chunk_size bytes of the payload, or @ref wide_chunk_size in a wide + * transfer. * @param memory The resource the frame is allocated in. * @return The frame, as @ref append_chunk writes it. */ @@ -389,6 +455,8 @@ struct proposal { std::string_view metadata; /** The transfer's id; offers only. */ std::uint32_t id = 0; + /** Whether the transfer's chunks are wide, the offer's @ref wide_bulk_flag; offers only. */ + bool wide = false; /** * The payload's size; for an inline frame, the bytes that follow the metadata. * @@ -425,7 +493,7 @@ using decoded_action = std::variant; /** Why a frame cannot be decoded; Trystero drops the peer for any of these. */ enum class wire_error { - /** Too short, too long, or a kind or a format that does not exist. */ + /** Too short, too long, a kind or a format that does not exist, or a flag where none may be. */ invalid_frame, /** A version other than @ref action_wire_version. */ incompatible_version, @@ -484,7 +552,7 @@ inline decode_result decode_control(std::span bytes_in, fram /** Decodes a proposal, a payload inline or the offer of a transfer, of the kind given. */ inline decode_result decode_proposal(std::span bytes_in, frame_kind kind, - payload_format format) { + payload_format format, bool wide) { decode_result result; const bool is_inline = kind == frame_kind::inline_payload; const std::size_t header_size = is_inline ? inline_header_size : offer_header_size; @@ -516,6 +584,7 @@ inline decode_result decode_proposal(std::span bytes_in, fra } p.id = get_u32(bytes_in, 36); p.size = static_cast(size); + p.wide = wide; } p.metadata = std::string_view(reinterpret_cast(bytes_in.data() + header_size), metadata_size); @@ -533,25 +602,30 @@ inline decode_result decode_proposal(std::span bytes_in, fra */ inline decode_result decode_action(std::span bytes_in) { decode_result result; - if (bytes_in.size() < 2 || bytes_in.size() > max_action_frame_bytes) { + if (bytes_in.size() < 2 || bytes_in.size() > max_bulk_frame_bytes) { return result; } if (bytes_in[0] != action_wire_version) { result.error = wire_error::incompatible_version; return result; } - const auto kind = static_cast(bytes_in[1] & 15U); - const auto format = static_cast(bytes_in[1] >> 4U); + const std::uint32_t kind_byte = bytes_in[1]; + const auto kind = static_cast(kind_byte & 15U); + const auto format = static_cast((kind_byte >> 4U) & 3U); + const auto flags = static_cast(kind_byte >> 6U); + constexpr auto offer = static_cast(frame_kind::offer); if (kind > static_cast(frame_kind::cancelled) || format > static_cast(payload_format::binary) || - (kind > static_cast(frame_kind::offer) && format != 0)) { + flags > (kind == offer ? 1U : 0U) || (kind > offer && format != 0) || + (kind != static_cast(frame_kind::chunk) && + bytes_in.size() > max_action_frame_bytes)) { return result; } if (kind >= static_cast(frame_kind::chunk)) { return detail::decode_control(bytes_in, static_cast(kind)); } return detail::decode_proposal(bytes_in, static_cast(kind), - static_cast(format)); + static_cast(format), flags == 1); } } // namespace webcpp::trystero::protocol diff --git a/include/webcpp/trystero/protocol/ecdsa.hpp b/include/webcpp/trystero/protocol/ecdsa.hpp new file mode 100644 index 0000000..a24333a --- /dev/null +++ b/include/webcpp/trystero/protocol/ecdsa.hpp @@ -0,0 +1,145 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + ECDSA P-256 with SHA-256 as Trystero 0.27.0 signs and checks it: a signature is 64 bytes, r then + s (IEEE P1363, WebCrypto's form), always written with a low S and refused with a high one. + + Tip: @ref sign_p256, @ref verify_p256 and @ref p256_public_key are trystero's only calls of + webcpp::crypto's P-256 signing, verification and public keys; every other part of the library + signs, verifies and reads a peer's key through them, so that a change of webcpp::crypto's + interface is made here alone. +*/ +#ifndef WEBCPP_TRYSTERO_PROTOCOL_ECDSA_HPP +#define WEBCPP_TRYSTERO_PROTOCOL_ECDSA_HPP + +#include + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::protocol { + +/** A P-256 signature: r then s, 32 bytes each, big-endian (IEEE P1363, WebCrypto's form). */ +using p256_signature = std::array; + +/** The order n of P-256's group, big-endian: a secret scalar is in [1, n - 1]. */ +inline constexpr std::array p256_order{ + 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51, +}; + +/** + * Whether 32 bytes are a P-256 secret scalar, 0.27.0's `isValidP256PrivateScalar`: not zero, and + * below the group order. + * + * The comparison reads every byte whatever their values: the bytes are a secret. + * + * @param scalar The scalar, big-endian. + * @return Whether it is in [1, n - 1]. + */ +[[nodiscard]] inline bool is_p256_scalar(std::span scalar) noexcept { + // A subtraction scalar - n from the last byte up: its final borrow says scalar < n. + unsigned borrow = 0; + unsigned any = 0; + for (std::size_t i = scalar.size(); i != 0; --i) { + const unsigned difference = unsigned{scalar[i - 1]} - unsigned{p256_order[i - 1]} - borrow; + borrow = (difference >> 8U) & 1U; + any |= scalar[i - 1]; + } + return (borrow == 1U) && (any != 0U); +} + +/** + * The public key of a point, as 0.27.0's `crypto.subtle.importKey('raw', ...)` imports it for + * verification: refused when the point is not on the curve. + * + * @param point The point, SEC 1's uncompressed `04 || x || y`. + * @return The key; nothing when the point is no P-256 public key. + */ +[[nodiscard]] inline std::optional p256_public_key( + std::span point) { + auto key = webcpp::crypto::curves::p256::public_key::make(point); + if (!key) { + return std::nullopt; + } + return *key; +} + +/** + * Whether a signature is in the form 0.27.0 accepts, its `isLowSP256Signature`: 64 bytes, r in + * [1, n - 1], and s in [1, (n - 1) / 2]. + * + * It does not verify the signature: @ref verify_p256 does. + * + * @param signature The signature. + * @return Whether it has 0.27.0's form. + */ +[[nodiscard]] inline bool is_low_s(std::span signature) noexcept { + if (signature.size() != std::tuple_size_v) { + return false; + } + return webcpp::crypto::curves::p256::check_low_s(signature.first<64>()).has_value(); +} + +/** + * Signs a payload as 0.27.0's `ecdsaSign` signs it: ECDSA of the SHA-256 of the payload, its S + * made low. + * + * Tip: webcpp::crypto's nonce is RFC 6979's, so the same key and payload give the same signature, + * where WebCrypto's are random; 0.27.0 verifies both alike. + * + * @param key The signer's key pair. + * @param payload The bytes signed. + * @return The signature, low S; webcpp::crypto's error when the key pair cannot sign, which a key + * pair made by webcpp::crypto and not moved from never is. + */ +[[nodiscard]] inline boost::system::result sign_p256( + const webcpp::crypto::curves::p256::keypair& key, std::span payload) { + const auto digest = + sha256(std::string_view(reinterpret_cast(payload.data()), payload.size())); + const auto signature = key.sign_ecdsa(digest); + if (!signature) { + return signature.error(); + } + return webcpp::crypto::curves::p256::normalize_ecdsa(*signature); +} + +/** + * Verifies a signature as 0.27.0's `verifyWithP256` does, without its cache: a signature of 64 + * bytes, in low-S form (@ref is_low_s), of the SHA-256 of the payload, by `key`. + * + * @param signature The signature. + * @param payload The bytes signed. + * @param key The signer's public key. + * @return Whether the signature is the key's, of the payload, with a low S. + */ +[[nodiscard]] inline bool verify_p256(std::span signature, + std::span payload, + const webcpp::crypto::curves::p256::public_key& key) { + if (!is_low_s(signature)) { + return false; + } + const auto digest = + sha256(std::string_view(reinterpret_cast(payload.data()), payload.size())); + return webcpp::crypto::curves::p256::verify_ecdsa(signature.first<64>(), digest, key) + .has_value(); +} + +} // namespace webcpp::trystero::protocol + +#endif diff --git a/include/webcpp/trystero/protocol/envelope.hpp b/include/webcpp/trystero/protocol/envelope.hpp deleted file mode 100644 index 37c4211..0000000 --- a/include/webcpp/trystero/protocol/envelope.hpp +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -#ifndef WEBCPP_TRYSTERO_PROTOCOL_ENVELOPE_HPP -#define WEBCPP_TRYSTERO_PROTOCOL_ENVELOPE_HPP - -#include - -#include - -#include - -#include -#include -#include -#include -#include -#include - -namespace webcpp::trystero::protocol { - -/** The largest action frame, Trystero's `maxActionFrameBytes`: 16 KiB. */ -inline constexpr std::size_t max_action_frame_bytes = std::size_t{16} * 1024; -/** The longest room token a room frame may carry, in bytes. */ -inline constexpr std::size_t max_room_token_bytes = 128; -/** The largest room frame, Trystero's `maxRoomFrameBytes`: an action frame in its envelope. */ -inline constexpr std::size_t max_room_frame_bytes = - max_action_frame_bytes + 3 + max_room_token_bytes; - -/** - * Starts a room frame in an empty buffer: the header for `token`, with room reserved for - * `payload_size` more bytes. - * - * The action frame is then appended in place, so the frame is allocated and written once. - * - * @param token The room's token, @ref room_token's. - * @param payload_size The size of the action frame that will follow. - * @param memory The resource the frame is allocated in. - * @return The frame's header. - */ -inline bytes begin_room_frame( - std::string_view token, std::size_t payload_size, - std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - bytes out(memory); - out.reserve(3 + token.size() + payload_size); - out.resize(3); - out[0] = 1; - boost::endian::store_big_u16(out.data() + 1, static_cast(token.size())); - out.insert(out.end(), token.begin(), token.end()); - return out; -} - -/** - * A room frame, Trystero's `wrapRoomFrame`: an action frame in the envelope of its room. - * - * @param token The room's token, @ref room_token's. - * @param payload The action frame. - * @param memory The resource the frame is allocated in. - * @return The frame. - */ -inline bytes room_frame(std::string_view token, std::span payload, - std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - auto out = begin_room_frame(token, payload.size(), memory); - out.insert(out.end(), payload.begin(), payload.end()); - return out; -} - -/** - * A presence frame, Trystero's `wrapRoomPresenceFrame`: whether this peer is in a room. - * - * @param token The room's token, @ref room_token's. - * @param present Whether the peer joins (true) or leaves (false) the room. - * @param memory The resource the frame is allocated in. - * @return The frame. - */ -inline bytes presence_frame(std::string_view token, bool present, - std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - bytes out(memory); - out.reserve(4 + token.size()); - out.resize(4); - out[0] = 2; - out[1] = present ? 1 : 0; - boost::endian::store_big_u16(out.data() + 2, static_cast(token.size())); - out.insert(out.end(), token.begin(), token.end()); - return out; -} - -/** - * A decoded room envelope, as views into the frame: every data channel message names the room it - * belongs to, so one connection can serve several rooms of the same app. - * - * | Frame | Bytes | - * | room | 1, token length (uint16 BE), token, action frame | - * | presence | 2, present (0 or 1), token length (uint16 BE), token | - * - * @see "The protocol", in the guide. - */ -struct envelope { - /** The kind of a frame, its first byte. */ - enum class kind { - /** A room frame, 1: an action frame for the room. */ - room, - /** A presence frame, 2: the peer joins or leaves the room. */ - presence, - }; - /** The frame's kind. */ - kind type = kind::room; - /** The token of the room the frame is for. */ - std::string_view token; - /** Whether the peer is in the room, for `kind::presence`. */ - bool present = false; - /** The action frame, for `kind::room`. */ - std::span payload; -}; - -/** - * Decodes the envelope of a frame, with the checks of Trystero's `unwrapFrame`. - * - * @param frame A data channel message. - * @return The envelope, or nothing when the frame is malformed; Trystero drops the peer then. - */ -inline std::optional decode_envelope(std::span frame) { - if (frame.size() < 3 || frame.size() > max_room_frame_bytes) { - return std::nullopt; - } - // The token's length follows the kind of a room frame (1), and a presence frame's (2) byte. - const std::size_t offset = frame[0] == 1 || frame[0] == 2 ? frame[0] : 0; - if (offset == 0 || frame.size() < offset + 2) { - return std::nullopt; - } - const std::size_t token_size = boost::endian::load_big_u16(frame.data() + offset); - const std::size_t header_size = offset + 2 + token_size; - if (token_size == 0 || token_size > max_room_token_bytes || frame.size() < header_size) { - return std::nullopt; - } - envelope out; - out.token = - std::string_view(reinterpret_cast(frame.data() + offset + 2), token_size); - if (frame[0] == 1) { - out.type = envelope::kind::room; - out.payload = frame.subspan(header_size); - } else { - out.type = envelope::kind::presence; - out.present = frame[1] == 1; - } - return out; -} - -} // namespace webcpp::trystero::protocol - -#endif diff --git a/include/webcpp/trystero/protocol/handshake.hpp b/include/webcpp/trystero/protocol/handshake.hpp new file mode 100644 index 0000000..f4e44ba --- /dev/null +++ b/include/webcpp/trystero/protocol/handshake.hpp @@ -0,0 +1,356 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The messages of Trystero 0.27.0's identity handshake (`handshake.ts`): the DTLS fingerprints of a + description, the three steps sent as `\@_hsdata` payloads, the reading of a step without its key + checks, and the transcript both sides sign. +*/ +#ifndef WEBCPP_TRYSTERO_PROTOCOL_HANDSHAKE_HPP +#define WEBCPP_TRYSTERO_PROTOCOL_HANDSHAKE_HPP + +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::protocol { + +/** The shortest nonce a step may carry, in UTF-16 code units: 0.27.0's `n.length < 16` refusal. */ +inline constexpr std::size_t min_nonce_units = 16; + +namespace detail { + +/** + * Where the line after the one at `at` starts, as a multiline regular expression's `^` sees it: + * after a line feed, a carriage return, U+2028 or U+2029. + * + * @return The position, or `npos` when the line at `at` is the last. + */ +inline std::size_t next_line(std::string_view text, std::size_t at) noexcept { + for (std::size_t i = at; i < text.size(); ++i) { + if (text[i] == '\n' || text[i] == '\r') { + return i + 1; + } + auto rest = text; + rest.remove_prefix(i); + if (rest.starts_with("\xe2\x80\xa8") || rest.starts_with("\xe2\x80\xa9")) { + return i + 3; + } + } + return std::string_view::npos; +} + +/** Whether two lists join with commas into the same text, 0.27.0's `a.join(',') !== b.join(',')` + * negated. */ +inline bool joined_equal(std::span a, + std::span b) noexcept { + // Walks both joins character by character, without building them. + std::size_t ai = 0; + std::size_t bi = 0; + std::size_t ac = 0; + std::size_t bc = 0; + const auto next = [](std::span list, std::size_t& item, + std::size_t& at) -> int { + while (item < list.size()) { + if (at < list[item].size()) { + return static_cast(list[item][at++]); + } + ++item; + at = 0; + if (item < list.size()) { + return ','; + } + } + return -1; + }; + for (;;) { + const int x = next(a, ai, ac); + const int y = next(b, bi, bc); + if (x != y) { + return false; + } + if (x < 0) { + return true; + } + } +} + +} // namespace detail + +/** + * The DTLS fingerprints of a description, 0.27.0's `extractDtlsFingerprints`: the value of each + * line `a=fingerprint:` (a multiline `^a=fingerprint:([^\\r\\n]+)$`, so a line also starts + * after U+2028 or U+2029, and the value runs to the line's `\\r` or `\\n`), without the white space + * JavaScript's `trim` removes, lowercased; the empty ones dropped, the others deduplicated and + * sorted in UTF-16 order. + * + * Tip: the letters are lowercased in ASCII, where JavaScript's `toLowerCase` lowercases every + * letter: a fingerprint is hexadecimal and a hash name ASCII. + * + * @param sdp The description. + * @param memory The resource the list is allocated in. + * @return The fingerprints; empty when there is none. + */ +[[nodiscard]] inline std::pmr::vector dtls_fingerprints( + std::string_view sdp, std::pmr::memory_resource* memory) { + static constexpr std::string_view prefix = "a=fingerprint:"; + std::pmr::vector out(memory); + std::size_t at = 0; + while (at != std::string_view::npos) { + if (sdp.substr(at).starts_with(prefix)) { + const std::size_t start = at + prefix.size(); + const std::size_t end = std::min(sdp.find_first_of("\r\n", start), sdp.size()); + if (end > start) { + std::pmr::string value(detail::js_trim(sdp.substr(start, end - start)), memory); + std::ranges::transform(value, value.begin(), [](char c) { + return c >= 'A' && c <= 'Z' ? static_cast(c - 'A' + 'a') : c; + }); + if (!value.empty()) { + out.push_back(std::move(value)); + } + // The match ends at the line's end: a U+2028 inside the value starts no line. + at = end; + } + } + at = detail::next_line(sdp, at); + } + std::ranges::sort(out, utf16_less); + const auto duplicates = std::ranges::unique(out); + out.erase(duplicates.begin(), duplicates.end()); + return out; +} + +/** The members of a step of the handshake, 0.27.0's claims. */ +struct handshake_claims { + /** The step, `__trystero_id`: 1, 2 or 3. */ + int step = 0; + /** The sender's nonce, `n`. */ + std::pmr::string nonce; + /** The sender's user id, `uid`. */ + std::pmr::string user_id; + /** The sender's endpoint key, compact, `pk`. */ + std::pmr::string endpoint_key; + /** The sender's user key, compact, `uk`. */ + std::pmr::string user_key; + /** The endpoint's signature of the transcript, base64url, `ps`: steps 2 and 3. */ + std::pmr::string endpoint_signature; + /** The user's signature of the transcript, base64url, `us`: steps 2 and 3. */ + std::pmr::string user_signature; + /** The sender's DTLS fingerprints, `dtls`. */ + std::pmr::vector dtls; +}; + +/** + * The JSON of a step, as 0.27.0's `sendClaims` and its step 3 write it: steps 1 and 2 are + * `{"__trystero_id":,"n":..,"dtls":[..],"uid":..,"pk":..,"uk":..}`, step 2 followed by + * `"ps":..,"us":..`; step 3 is `{"__trystero_id":3,"ps":..,"us":..}`. + * + * @param claims The step's members. + * @param memory The resource the text is allocated in. + * @return The text, an `\@_hsdata` payload. + */ +[[nodiscard]] inline std::pmr::string write_handshake_step(const handshake_claims& claims, + std::pmr::memory_resource* memory) { + std::pmr::string out(memory); + out += '{'; + json::append_key(out, handshake_step_key); + json::append_integer(out, claims.step); + if (claims.step != 3) { + json::append_key(out, "n"); + json::append_string_total(out, claims.nonce); + json::append_key(out, "dtls"); + out += '['; + for (std::size_t i = 0; i < claims.dtls.size(); ++i) { + if (i != 0) { + out += ','; + } + json::append_string_total(out, claims.dtls[i]); + } + out += ']'; + json::append_key(out, "uid"); + json::append_string_total(out, claims.user_id); + json::append_key(out, "pk"); + json::append_string_total(out, claims.endpoint_key); + json::append_key(out, "uk"); + json::append_string_total(out, claims.user_key); + } + if (claims.step != 1) { + json::append_key(out, "ps"); + json::append_string_total(out, claims.endpoint_signature); + json::append_key(out, "us"); + json::append_string_total(out, claims.user_signature); + } + out += '}'; + return out; +} + +/** What @ref read_handshake_step reads of a step, its members or the reason it is refused. */ +struct handshake_read { + /** The members; nothing when the step is refused. */ + std::optional claims; + /** A @ref handshake_reason when the step is refused; empty otherwise. */ + std::string_view failure; +}; + +/** + * Reads a step as 0.27.0's `parseAndVerifyPeerIdentityClaims` reads it, without its key checks + * (the identity cache's), and step 3 as its responder reads it. + * + * Steps 1 and 2: an object whose `__trystero_id` is the number `expected_step`, `n` a string of + * @ref min_nonce_units UTF-16 code units or more, `dtls` an array (its members that are no strings + * dropped), `uid` a nonempty string, `pk` and `uk` strings, and at step 2 `ps` and `us` strings; + * else @ref handshake_reason::identity. Then the DTLS rule: when `expected_remote_dtls` is not + * empty, the claimed list joined with commas must be it joined with commas, and when `local_dtls` + * is not empty, the claimed list must not be; else @ref handshake_reason::dtls_mismatch. + * + * Step 3: an object whose `__trystero_id` is the number 3, `ps` and `us` strings; else + * @ref handshake_reason::identity. The lists are not read. + * + * Tip: the text is read with the protocol's limits (@ref json::protocol_limits), nested 16 deep at + * most: a step 0.27.0 writes nests 2 deep. + * + * @param json The `\@_hsdata` payload. + * @param expected_step The step expected: 1, 2 or 3. + * @param expected_remote_dtls The fingerprints of the remote description this side applied. + * @param local_dtls The fingerprints of this side's description. + * @param memory The resource the parse and the members are allocated in. + * @return The members, or the reason the step is refused. + */ +[[nodiscard]] inline handshake_read read_handshake_step( + std::string_view json, int expected_step, + std::span expected_remote_dtls, + std::span local_dtls, std::pmr::memory_resource* memory) { + const auto refused = [] { + return handshake_read{.claims = std::nullopt, .failure = handshake_reason::identity}; + }; + const auto parsed = webcpp::document::parse(json, json::protocol_limits(json.size()), + std::pmr::polymorphic_allocator(memory)); + if (!parsed) { + return refused(); + } + const json::const_value root = parsed->root(); + const auto step = root[handshake_step_key]; + if (!root.is_object() || !step.is_number() || step.value_or(std::int64_t{0}) != expected_step) { + return refused(); + } + const auto ps = root["ps"]; + const auto us = root["us"]; + const bool signed_step = expected_step != 1; + if (signed_step && (!ps.is_string() || !us.is_string())) { + return refused(); + } + handshake_claims claims{ + .step = expected_step, + .nonce = std::pmr::string(memory), + .user_id = std::pmr::string(memory), + .endpoint_key = std::pmr::string(memory), + .user_key = std::pmr::string(memory), + .endpoint_signature = std::pmr::string(signed_step ? json::text_of(ps) : "", memory), + .user_signature = std::pmr::string(signed_step ? json::text_of(us) : "", memory), + .dtls = std::pmr::vector(memory), + }; + if (expected_step == 3) { + return {.claims = std::move(claims), .failure = {}}; + } + const auto n = root["n"]; + const auto dtls = root["dtls"]; + const auto uid = root["uid"]; + const auto pk = root["pk"]; + const auto uk = root["uk"]; + const auto units = n.length(); + if (!n.is_string() || !units || *units < min_nonce_units || !dtls.is_array() || + !uid.is_string() || json::text_of(uid).empty() || !pk.is_string() || !uk.is_string()) { + return refused(); + } + claims.nonce = json::text_of(n); + claims.user_id = json::text_of(uid); + claims.endpoint_key = json::text_of(pk); + claims.user_key = json::text_of(uk); + for (const auto item : dtls) { + if (item.is_string()) { + claims.dtls.emplace_back(json::text_of(item)); + } + } + if ((!expected_remote_dtls.empty() && + !detail::joined_equal(expected_remote_dtls, claims.dtls)) || + (!local_dtls.empty() && claims.dtls.empty())) { + return {.claims = std::nullopt, .failure = handshake_reason::dtls_mismatch}; + } + return {.claims = std::move(claims), .failure = {}}; +} + +/** + * The transcript both sides sign, 0.27.0's `encodeTranscript`: the JSON array + * `["trystero:id-hs:v2",app,room,initiator peer,responder peer,initiator nonce,responder nonce, + * [initiator dtls],[responder dtls],initiator user,responder user]`, written as `JSON.stringify` + * writes it. + * + * @param app_id The app's id. + * @param room_id The room's id. + * @param initiator_peer The initiator's peer id. + * @param responder_peer The responder's peer id. + * @param initiator_nonce The initiator's nonce. + * @param responder_nonce The responder's nonce. + * @param initiator_dtls The initiator's fingerprints. + * @param responder_dtls The responder's fingerprints. + * @param initiator_user The initiator's user id. + * @param responder_user The responder's user id. + * @param memory The resource the text is allocated in. + * @return The transcript, whose UTF-8 bytes are signed. + */ +[[nodiscard]] inline std::pmr::string handshake_transcript( + std::string_view app_id, std::string_view room_id, std::string_view initiator_peer, + std::string_view responder_peer, std::string_view initiator_nonce, + std::string_view responder_nonce, std::span initiator_dtls, + std::span responder_dtls, std::string_view initiator_user, + std::string_view responder_user, std::pmr::memory_resource* memory) { + std::pmr::string out(memory); + const auto list = [&out](std::span items) { + out += ",["; + for (std::size_t i = 0; i < items.size(); ++i) { + if (i != 0) { + out += ','; + } + json::append_string_total(out, items[i]); + } + out += ']'; + }; + out += '['; + json::append_string_total(out, domain_tag("id-hs", 2, memory)); + for (const auto part : + {app_id, room_id, initiator_peer, responder_peer, initiator_nonce, responder_nonce}) { + out += ','; + json::append_string_total(out, part); + } + list(initiator_dtls); + list(responder_dtls); + for (const auto part : {initiator_user, responder_user}) { + out += ','; + json::append_string_total(out, part); + } + out += ']'; + return out; +} + +} // namespace webcpp::trystero::protocol + +#endif diff --git a/include/webcpp/trystero/protocol/handshake_reason.hpp b/include/webcpp/trystero/protocol/handshake_reason.hpp new file mode 100644 index 0000000..5c2b76b --- /dev/null +++ b/include/webcpp/trystero/protocol/handshake_reason.hpp @@ -0,0 +1,43 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The names of Trystero 0.27.0's identity handshake that the handshake manager and the steps share: + the member that names a step and the reasons a handshake fails. Light on purpose, it pulls in no + parser and no cryptography. +*/ +#ifndef WEBCPP_TRYSTERO_PROTOCOL_HANDSHAKE_REASON_HPP +#define WEBCPP_TRYSTERO_PROTOCOL_HANDSHAKE_REASON_HPP + +#include + +#include + +namespace webcpp::trystero::protocol { + +/** The member that names a step of the handshake, 0.27.0's `hsStepKey`: `__${libId}_id`. */ +inline constexpr std::string_view handshake_step_key = "__trystero_id"; + +/** The reasons a handshake fails, 0.27.0's messages without their `Trystero: ` prefix. */ +namespace handshake_reason { +/** A step of the wrong shape, a key that does not derive the id claimed, or a signature that does + * not verify, 0.27.0's `peerIdentityErr`. */ +inline constexpr std::string_view identity = "peer identity verification failed"; +/** The fingerprints claimed are not those of the description this side applied. */ +inline constexpr std::string_view dtls_mismatch = "DTLS fingerprint mismatch"; +/** A description of the connection has no fingerprint. */ +inline constexpr std::string_view dtls_missing = "DTLS fingerprint missing"; +/** The peer sent more than 16 messages the handshake had not read. */ +inline constexpr std::string_view too_many_messages = "too many pending handshake messages"; +/** The handshake did not complete in 10 seconds. */ +inline constexpr std::string_view timed_out = "handshake timed out after 10000ms"; +/** The peer left while its handshake ran, 0.27.0's `handshakeDisconnectErr`. */ +inline constexpr std::string_view disconnected = "peer disconnected during handshake"; +} // namespace handshake_reason + +} // namespace webcpp::trystero::protocol + +#endif diff --git a/include/webcpp/trystero/protocol/identity.hpp b/include/webcpp/trystero/protocol/identity.hpp new file mode 100644 index 0000000..2ca36c9 --- /dev/null +++ b/include/webcpp/trystero/protocol/identity.hpp @@ -0,0 +1,294 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The texts of Trystero 0.27.0's user identity: the user key a program keeps, `trystero_uk_` and the + base64url of its JSON, or the JSON itself; and the payload of a user's proof that an endpoint is + its own, which 0.27.0 defines but its core never sends. +*/ +#ifndef WEBCPP_TRYSTERO_PROTOCOL_IDENTITY_HPP +#define WEBCPP_TRYSTERO_PROTOCOL_IDENTITY_HPP + +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::protocol { + +/** The prefix of an exported user key, 0.27.0's `userKeyPrefix`: `libId` and `_uk_`. */ +inline constexpr std::string_view user_key_prefix = "trystero_uk_"; + +/** A user's P-256 key as its text gives it: the secret scalar and the public point. */ +struct user_key_material { + /** The secret scalar d, big-endian, in [1, n - 1]. */ + webcpp::crypto::secret<32> d; + /** The public point, SEC 1's uncompressed `04 || x || y`; not checked to be on the curve, nor + * to be d's. */ + std::array point{}; +}; + +namespace detail { + +/** + * The length of the white space of JavaScript's `String.prototype.trim` that starts `text`, in + * UTF-8: tab, line feed, vertical tab, form feed, carriage return, space, U+00A0, U+1680, U+2000 + * to U+200A, U+2028, U+2029, U+202F, U+205F, U+3000 and U+FEFF. + * + * @param text The text. + * @param at_end Whether the white space ends `text` rather than starts it. + * @return The length of one such character, 0 when there is none. + */ +inline std::size_t js_space(std::string_view text, bool at_end) noexcept { + const auto piece = [&](std::size_t n) noexcept { + if (text.size() < n) { + return std::string_view(); + } + auto p = text; + if (at_end) { + p.remove_prefix(text.size() - n); + } else { + p.remove_suffix(text.size() - n); + } + return p; + }; + if (const auto one = piece(1); !one.empty()) { + switch (one[0]) { + case '\t': + case '\n': + case '\v': + case '\f': + case '\r': + case ' ': return 1; + default: break; + } + } + if (piece(2) == "\xc2\xa0") { + return 2; + } + const auto three = piece(3); + if (three.size() != 3) { + return 0; + } + const auto b1 = static_cast(three[1]); + const auto b2 = static_cast(three[2]); + const bool space = three == "\xe1\x9a\x80" || three == "\xe3\x80\x80" || + three == "\xef\xbb\xbf" || three == "\xe2\x81\x9f" || + (three[0] == '\xe2' && b1 == 0x80 && + ((b2 >= 0x80 && b2 <= 0x8a) || b2 == 0xa8 || b2 == 0xa9 || b2 == 0xaf)); + return space ? 3 : 0; +} + +/** + * `text` without the white space of JavaScript's `String.prototype.trim` around it. + * + * @param text The text, UTF-8. + * @return The view of what remains. + */ +inline std::string_view js_trim(std::string_view text) noexcept { + while (const auto n = js_space(text, false)) { + text.remove_prefix(n); + } + while (const auto n = js_space(text, true)) { + text.remove_suffix(n); + } + return text; +} + +/** + * Whether a JSON member that may be absent is absent or false to JavaScript's `&&`: undefined, + * null, false, 0 or the empty string. + * + * @param v The member, undefined when absent. + * @return Whether JavaScript reads it as false. + */ +inline bool js_falsy(const json::const_value& v) { + if (v.is_undefined() || v.is_null()) { + return true; + } + if (v.is_boolean()) { + return !v.value_or(true); + } + if (v.is_number()) { + // Only a zero reads as the integer 0; a number that is no integer reads as the fallback. + return v.value_or(std::int64_t{1}) == 0; + } + if (v.is_string()) { + return json::text_of(v).empty(); + } + return false; +} + +} // namespace detail + +/** + * Reads a user key as 0.27.0's `tryParsePrivateJwk` reads a text. + * + * The text is read without the white space `String.prototype.trim` removes; when it starts with + * @ref user_key_prefix, the rest is strict base64url of the JSON, read as `TextDecoder` reads it + * (a leading byte order mark dropped); when it starts with `{`, it is the JSON. The JSON is an + * object whose `d`, `x` and `y` are nonempty strings, `d` the strict base64url of 32 bytes that + * are a valid scalar (@ref is_p256_scalar), `x` and `y` of 32 bytes each; its `kty`, unless + * absent or falsy, is `"EC"`, and its `crv` `"P-256"`. + * + * Every buffer that held `d`, its text, the decoded JSON, the parse's document and the scalar's + * bytes, is wiped before the call returns. + * + * Tip: 0.27.0's `fromBase64Url` is loose where this reading is strict (design D18): a padded + * user key, which 0.27.0 never writes, is refused here. + * + * @param text The key's text, as a program kept it. + * @param memory The resource the intermediate buffers are allocated in. + * @return The key's scalar and point, or nothing when the text is not a user key. + */ +[[nodiscard]] inline std::optional parse_user_key( + std::string_view text, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + // First, so that it ends last: every buffer below is wiped when it is freed. + webcpp::trystero::detail::wiping_resource wiping(memory); + const auto trimmed = detail::js_trim(text); + std::optional decoded; + std::string_view json_text; + if (trimmed.starts_with(user_key_prefix)) { + decoded = from_base64url(trimmed.substr(user_key_prefix.size()), &wiping); + if (!decoded) { + return std::nullopt; + } + json_text = + std::string_view(reinterpret_cast(decoded->data()), decoded->size()); + if (json_text.starts_with("\xef\xbb\xbf")) { + json_text.remove_prefix(3); // TextDecoder drops a byte order mark + } + } else if (trimmed.starts_with('{')) { + json_text = trimmed; + } else { + return std::nullopt; + } + const auto parsed = + webcpp::document::parse(json_text, webcpp::document::parse_options(), + std::pmr::polymorphic_allocator(&wiping)); + if (!parsed) { + return std::nullopt; + } + const json::const_value root = parsed->root(); + const auto d = root["d"]; + const auto x = root["x"]; + const auto y = root["y"]; + if (!root.is_object() || !d.is_string() || !x.is_string() || !y.is_string()) { + return std::nullopt; + } + const auto kty = root["kty"]; + const auto crv = root["crv"]; + if ((!detail::js_falsy(kty) && !(kty.is_string() && json::text_of(kty) == "EC")) || + (!detail::js_falsy(crv) && !(crv.is_string() && json::text_of(crv) == "P-256"))) { + return std::nullopt; + } + // Empty texts are refused here too: strict base64url has no empty text. + const auto scalar = from_base64url(json::text_of(d), &wiping); + const auto x_bytes = from_base64url(json::text_of(x), &wiping); + const auto y_bytes = from_base64url(json::text_of(y), &wiping); + if (!scalar || scalar->size() != 32 || !x_bytes || x_bytes->size() != 32 || !y_bytes || + y_bytes->size() != 32) { + return std::nullopt; + } + if (!is_p256_scalar(std::span(scalar->data(), 32))) { + return std::nullopt; + } + user_key_material out; + std::ranges::copy(*scalar, out.d.writable().begin()); + out.point[0] = 0x04; + std::ranges::copy(*x_bytes, out.point.begin() + 1); + std::ranges::copy(*y_bytes, out.point.begin() + 33); + return out; +} + +/** + * The text of a user key, as 0.27.0's `buildExtractableUserIdentity` writes it: @ref + * user_key_prefix and the base64url of the JSON `{"d":..,"x":..,"y":..}`, each member the + * base64url of its 32 bytes. + * + * The JSON, which holds the scalar, is wiped before the call returns; the text returned holds it + * too, and is the caller's to keep or wipe. + * + * @param key The key. + * @param memory The resource the text is allocated in. + * @return The text, 214 characters. + */ +[[nodiscard]] inline std::pmr::string write_user_key(const user_key_material& key, + std::pmr::memory_resource* memory) { + // {"d":"<43>","x":"<43>","y":"<43>"}: 151 bytes, whose base64url is 202 characters. Each + // buffer is reserved whole, so that no copy of the scalar is left in a block freed by growth. + constexpr std::size_t json_size = 151; + constexpr std::size_t text_size = 214; + webcpp::trystero::detail::wiping_resource wiping(memory); + std::pmr::string json_text(&wiping); + json_text.reserve(json_size); + json_text += R"({"d":")"; + append_base64url(json_text, key.d.bytes()); + json_text += R"(","x":")"; + append_base64url(json_text, std::span(key.point).subspan(1, 32)); + json_text += R"(","y":")"; + append_base64url(json_text, std::span(key.point).subspan(33, 32)); + json_text += R"("})"; + std::pmr::string out(memory); + out.reserve(text_size); + out += user_key_prefix; + append_base64url( + out, std::span(reinterpret_cast(json_text.data()), json_text.size())); + return out; +} + +/** + * The payload a user signs to prove an endpoint its own, 0.27.0's `userEndpointProofPayload`: the + * JSON `["trystero:user-proof:v3",app,room,peer,compact,seq]`, its strings written as + * `JSON.stringify` writes them. + * + * Tip: 0.27.0's core neither sends nor checks a user-proof (design D21): the handshake's two + * signatures bind the user to the endpoint. The payload is kept, with @ref sign_p256 and + * @ref verify_p256, as 0.27.0 defines it. + * + * @param app_id The app's id. + * @param room_id The room's id. + * @param peer_id The endpoint's peer id. + * @param peer_compact The endpoint's compact public key. + * @param seq The proof's sequence number, at most `Number.MAX_SAFE_INTEGER`. + * @param memory The resource the payload is allocated in. + * @return The payload, UTF-8. + */ +[[nodiscard]] inline std::pmr::string user_proof_payload( + std::string_view app_id, std::string_view room_id, std::string_view peer_id, + std::string_view peer_compact, std::uint64_t seq, std::pmr::memory_resource* memory) { + std::pmr::string out(memory); + out += '['; + json::append_string_total(out, domain_tag("user-proof", 3, memory)); + for (const auto part : {app_id, room_id, peer_id, peer_compact}) { + out += ','; + json::append_string_total(out, part); + } + out += ','; + json::append_integer(out, static_cast(seq)); + out += ']'; + return out; +} + +} // namespace webcpp::trystero::protocol + +#endif diff --git a/include/webcpp/trystero/protocol/ids.hpp b/include/webcpp/trystero/protocol/ids.hpp new file mode 100644 index 0000000..391c7c7 --- /dev/null +++ b/include/webcpp/trystero/protocol/ids.hpp @@ -0,0 +1,224 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_TRYSTERO_PROTOCOL_IDS_HPP +#define WEBCPP_TRYSTERO_PROTOCOL_IDS_HPP + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::protocol { + +/** The 62 characters of Trystero 0.27.0's ids, its `base62Alphabet`, in its order. */ +inline constexpr std::string_view base62_alphabet = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + +/** The length of a Trystero peer id, its `selfId` and the id @ref derive_peer_id makes. */ +inline constexpr std::size_t peer_id_size = 20; +/** The length of the id of a user, which @ref derive_user_id makes from a compact public key. */ +inline constexpr std::size_t user_id_size = 22; +/** The length of the id of a Trystero offer, which its answer and candidates name. */ +inline constexpr std::size_t offer_id_size = 12; +/** The length of the nonce that makes repeated announcements distinct Nostr events. */ +inline constexpr std::size_t nonce_size = 8; +/** The length of the id of a Nostr subscription. */ +inline constexpr std::size_t subscription_id_size = 64; +/** The length of a UUID's text, `8-4-4-4-12` hexadecimal digits and four hyphens. */ +inline constexpr std::size_t uuid_text_size = 36; + +/** + * How many random bytes one round of @ref gen_id draws for an id of `n` characters, Trystero's + * `Math.ceil(n * 1.15) + 4`, computed in integers. + * + * @param n The id's length. + * @return `ceil(n * 1.15) + 4`. + */ +constexpr std::size_t gen_id_draw_size(std::size_t n) { + return (((n * 115) + 99) / 100) + 4; +} + +/** + * Trystero 0.27.0's `genId`: an unbiased base62 id of `n` characters. + * + * Each round fills @ref gen_id_draw_size bytes through `draw`; a byte below 248 (the largest + * multiple of 62 that fits a byte) appends the character at its remainder in 62, a larger byte is + * skipped, so each of the 62 characters is equally likely. Rounds repeat until the id is complete. + * + * @tparam Draw A callable with `void(std::span)` that fills its argument with + * random bytes. + * @param n The id's length. + * @param draw The source of random bytes. + * @param memory The resource the id is allocated in. + * @return The id, `n` characters of @ref base62_alphabet. + */ +template +std::pmr::string gen_id(std::size_t n, Draw&& draw, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + constexpr std::uint8_t unbiased_limit = 248; + std::pmr::string out(memory); + if (n == 0) { + return out; + } + out.reserve(n); + std::pmr::vector random(gen_id_draw_size(n), memory); + while (out.size() < n) { + draw(std::span(random)); + for (std::size_t i = 0; i < random.size() && out.size() < n; ++i) { + if (random[i] < unbiased_limit) { + out += base62_alphabet[random[i] % base62_alphabet.size()]; + } + } + } + return out; +} + +/** + * The low `length` base-62 digits of a big-endian number, most significant first: Trystero's + * `encodeBase62`, which takes the number modulo 62^`length`. + * + * @param big_endian The number's bytes, most significant first. + * @param length How many digits. + * @param memory The resource the text is allocated in. + * @return `length` characters of @ref base62_alphabet. + */ +inline std::pmr::string encode_base62( + std::span big_endian, std::size_t length, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + std::pmr::vector number(big_endian.begin(), big_endian.end(), memory); + std::pmr::string out(length, '0', memory); + for (std::size_t digit = length; digit != 0; --digit) { + std::uint32_t remainder = 0; + for (auto& byte : number) { + const std::uint32_t current = (remainder << 8U) | byte; + byte = static_cast(current / 62U); + remainder = current % 62U; + } + out[digit - 1] = base62_alphabet[remainder]; + } + return out; +} + +/** + * A version 4 UUID (RFC 9562) of 16 random bytes, as `crypto.randomUUID()` writes it. + * + * @param random The random bytes; the version and variant bits are set in the copy used. + * @return The text, lowercase `8-4-4-4-12`, 36 characters. + */ +inline std::array uuid_v4(std::array random) { + random[6] = static_cast((random[6] & 0x0fU) | 0x40U); + random[8] = static_cast((random[8] & 0x3fU) | 0x80U); + constexpr std::string_view digits = "0123456789abcdef"; + std::array out{}; + std::size_t at = 0; + for (std::size_t i = 0; i < random.size(); ++i) { + if (i == 4 || i == 6 || i == 8 || i == 10) { + out[at++] = '-'; + } + out[at++] = digits[random[i] >> 4U]; + out[at++] = digits[random[i] & 0x0fU]; + } + return out; +} + +/** + * The compact form of a public key: `base64url(x) + "." + base64url(y)`, 87 characters. + * + * @param uncompressed The key's SEC1 uncompressed point, `04 || x || y`. + * @param memory The resource the text is allocated in. + * @return The compact text. + */ +inline std::pmr::string compact_public_key( + std::span uncompressed, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + std::pmr::string out = to_base64url(uncompressed.subspan(1, 32), memory); + out += '.'; + append_base64url(out, uncompressed.subspan(33, 32)); + return out; +} + +/** + * The point of a compact public key: 87 characters, a `.` at 43, and strict base64url of 32 bytes + * on each side. + * + * The point is not checked to be on the curve. + * + * @param compact The compact text. + * @param memory The resource the decoding's buffers are allocated in. + * @return The SEC1 uncompressed point, `04 || x || y`, or nothing when the text is not compact. + */ +inline std::optional> parse_compact_public_key( + std::string_view compact, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + constexpr std::size_t half = 43; + if (compact.size() != (2 * half) + 1 || compact[half] != '.') { + return std::nullopt; + } + std::array out{}; + out[0] = 0x04; + for (std::size_t side = 0; side < 2; ++side) { + const auto read = from_base64url(compact.substr(side * (half + 1), half), memory); + if (!read || read->size() != 32) { + return std::nullopt; + } + std::ranges::copy(*read, out.begin() + 1 + static_cast(side * 32)); + } + return out; +} + +/** Internal helper of the two derivations below: the id of `length` base62 characters from the + * SHA-256 of the tag of `name`, `:` and `compact`. + */ +inline std::pmr::string identity_id_of(std::string_view name, std::string_view compact, + std::size_t length, std::pmr::memory_resource* memory) { + const auto tag = domain_tag(name, 1, memory); + return encode_base62(sha256_of({tag, ":", compact}), length, memory); +} + +/** + * A peer's id, derived from its compact public key: the low 20 base-62 digits of the SHA-256 of + * `"trystero:pid:v1:" + compact`. + * + * @param compact The key's compact text, see @ref compact_public_key. + * @param memory The resource the id is allocated in. + * @return The id, @ref peer_id_size characters. + */ +inline std::pmr::string derive_peer_id( + std::string_view compact, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + return identity_id_of("pid", compact, peer_id_size, memory); +} + +/** + * A user's id, derived from its compact public key: the low 22 base-62 digits of the SHA-256 of + * `"trystero:uid:v1:" + compact`. + * + * @param compact The key's compact text, see @ref compact_public_key. + * @param memory The resource the id is allocated in. + * @return The id, @ref user_id_size characters. + */ +inline std::pmr::string derive_user_id( + std::string_view compact, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + return identity_id_of("uid", compact, user_id_size, memory); +} + +} // namespace webcpp::trystero::protocol + +#endif diff --git a/include/webcpp/trystero/protocol/json.hpp b/include/webcpp/trystero/protocol/json.hpp index d837342..43dde9c 100644 --- a/include/webcpp/trystero/protocol/json.hpp +++ b/include/webcpp/trystero/protocol/json.hpp @@ -146,6 +146,46 @@ inline bool quotable(std::string_view text) { return webcpp::document::quote(text, out); } +/** + * Appends `text` as the string `JSON.stringify` writes, whatever its bytes: quoted, `"` and `\\` + * escaped, `\\b`, `\\f`, `\\n`, `\\r` and `\\t` by their letters, the other controls below 0x20 + * as lowercase `\\u00XX`, and every other byte as it is (DEL and U+2028 too, as `JSON.stringify` + * writes them). + * + * It is the library's one writer of a string that is not refused. + * + * Tip: unlike @ref append_string it never refuses a text, so that a topic built of an app id or a + * room id, which nothing checks to be UTF-8, never silently loses a part; a byte that is not UTF-8 + * is copied as it is. On UTF-8 it writes what @ref append_string writes. + * + * @param out The text to append to. + * @param text The text. + */ +inline void append_string_total(std::pmr::string& out, std::string_view text) { + static constexpr std::string_view digits = "0123456789abcdef"; + out += '"'; + for (const char c : text) { + switch (c) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\f': out += "\\f"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if (static_cast(c) < 0x20) { + out += "\\u00"; + out += digits[static_cast(c) >> 4U]; + out += digits[static_cast(c) & 15U]; + } else { + out += c; + } + } + } + out += '"'; +} + namespace detail { /** @@ -154,8 +194,7 @@ namespace detail { * is made. */ inline void append_utf8(std::pmr::string& out, std::string_view text) { - // Quoting fails only on a text that is not UTF-8, which the precondition rules out. - static_cast(append_string(out, text)); + append_string_total(out, text); } } // namespace detail diff --git a/include/webcpp/trystero/protocol/nostr.hpp b/include/webcpp/trystero/protocol/nostr.hpp index 9c91349..3c43bbd 100644 --- a/include/webcpp/trystero/protocol/nostr.hpp +++ b/include/webcpp/trystero/protocol/nostr.hpp @@ -12,13 +12,16 @@ #include #include #include +#include #include -#include -#include -#include -#include +#include +#include +#include // lint-world: a signature's aux randomness +#include + #include +#include #include #include @@ -26,15 +29,14 @@ #include #include #include -#include #include #include -#include #include #include #include #include #include +#include namespace webcpp::trystero::protocol::nostr { @@ -54,15 +56,37 @@ static_assert(max_parsed_relay_text_bytes < max_relay_message_bytes); /** The tag a Trystero event carries its topic in, its `tag`: "x". */ inline constexpr std::string_view topic_tag = "x"; +/** The most topics one subscription lists, Trystero's `maxTopicsPerSubscription`: a room with + * more subscribes in several requests. */ +inline constexpr std::size_t max_topics_per_subscription = 250; + +/** How far back a subscription asks for events, Trystero's `subscribeClockSkewSeconds`: a peer + * whose clock is behind ours by up to a minute is still heard. */ +inline constexpr std::chrono::seconds subscribe_clock_skew{60}; + /** * The event kind a topic maps to, Trystero's `topicToKind`: 20000 to 29999, ephemeral, so relays * forward the events and keep none. * - * @param topic The topic's name. - * @return 20000 plus `str_to_num(topic, 10000)`, below 30000. + * @param topic The topic's name, in UTF-8. + * @return FNV-1a of 32 bits over the topic's UTF-16 code units, modulo 10000, plus 20000. Unlike + * @ref hash32 it hashes code units, not bytes, and has no final mix. */ inline std::uint32_t topic_kind(std::string_view topic) { - return static_cast(str_to_num(topic, 10000)) + 20000; + std::uint32_t h = 0x811c9dc5U; + for_each_utf16_code_unit(topic, [&h](std::uint32_t unit) { h = (h ^ unit) * 0x01000193U; }); + return (h % 10000U) + 20000U; +} + +/** + * The earliest `created_at` a subscription asks for, Trystero's `subscribeSince`. + * + * @param now The time, in whole seconds since the Unix epoch. + * @return `now` less @ref subscribe_clock_skew, and never before the epoch. + */ +inline std::chrono::sys_seconds subscribe_since(std::chrono::sys_seconds now) { + const auto since = now - subscribe_clock_skew; + return std::max(since, std::chrono::sys_seconds{}); } namespace detail { @@ -155,37 +179,49 @@ inline std::array event_id( } /** - * A BIP-340 key pair over libsecp256k1, the one key a peer signs every event with, as Trystero's - * Nostr strategy does with its `pubkey`. + * A BIP-340 key pair over webcpp::crypto's secp256k1, the key a room signs its events with, as + * Trystero's Nostr strategy does with a room's `NostrSigner`. * - * Tip: its signing context is made in the resource it is given - * (`secp256k1_context_preallocated_create`), where `secp256k1_context_create` would take it from - * `malloc`. + * Tip: its signing context is made in the resource it is given, the key pair's one allocation. */ class signer { public: /** - * Makes a key from 32 random bytes. + * Makes a key from a random secret, as Trystero's `createSigner` does: webcpp::crypto's + * `secp256k1::keypair::generate`, which draws the secret from the system's generator, again + * when one is not a valid secret key (at most four draws), and wipes each. + * + * @param memory The resource the signing context and the public key's text are allocated in; + * it must outlive the signer. + * @return The signer; `webcpp::crypto::error::entropy_unavailable` when the system's generator + * fails or every draw is refused; any other error of `keypair::generate`. + */ + [[nodiscard]] static boost::system::result generate( + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + auto key = webcpp::crypto::curves::secp256k1::keypair::generate(memory); + if (!key) { + return key.error(); + } + return from_keypair(std::move(*key), memory); + } + + /** + * Makes a key from a given secret. * * @param secret The secret key. * @param memory The resource the signing context and the public key's text are allocated in; * it must outlive the signer. - * @return The signer, or nothing when the bytes are not a valid secret key, which is - * negligibly rare. + * @return The signer; `webcpp::crypto::error::invalid_secret_key` when the bytes are not a + * valid secret key; any other error of `keypair::make`. */ - static std::optional from_secret( + [[nodiscard]] static boost::system::result from_secret( std::span secret, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - signer s(memory); - if (secp256k1_keypair_create(s.context_.get(), &s.keypair_, secret.data()) == 0) { - return std::nullopt; + auto key = webcpp::crypto::curves::secp256k1::keypair::make(secret, memory); + if (!key) { + return key.error(); } - secp256k1_xonly_pubkey xonly; - secp256k1_keypair_xonly_pub(s.context_.get(), &xonly, nullptr, &s.keypair_); - std::array pub{}; - secp256k1_xonly_pubkey_serialize(s.context_.get(), pub.data(), &xonly); - s.pubkey_ = to_hex(pub, memory); - return s; + return from_keypair(std::move(*key), memory); } /** @@ -193,56 +229,48 @@ class signer { * * @return 64 lowercase hexadecimal digits, valid as long as the signer. */ - [[nodiscard]] std::string_view pubkey() const { return pubkey_; } + [[nodiscard]] std::string_view pubkey_hex() const { return pubkey_; } /** - * Signs a message with BIP-340 Schnorr. + * Signs an event id with BIP-340 Schnorr, with 32 bytes of auxiliary randomness from the + * system's generator, through webcpp::crypto, as Trystero's `schnorr.signAsync` draws its own. * - * @param message The 32 bytes to sign, an event id. - * @param aux 32 random bytes of auxiliary randomness. - * @return The 64-byte signature, an event's `sig`. + * @param event_id The 32 bytes to sign. + * @return The 64-byte signature, an event's `sig`; `webcpp::crypto::error::entropy_unavailable` + * when the generator fails; an error of `keypair::sign_schnorr`. */ - [[nodiscard]] std::array sign(std::span message, - std::span aux) const { - std::array sig{}; - secp256k1_schnorrsig_sign32(context_.get(), sig.data(), message.data(), &keypair_, - aux.data()); - return sig; + [[nodiscard]] boost::system::result> sign( + std::span event_id) const { + webcpp::crypto::secret<32> aux; + if (!webcpp::crypto::random_device().fill(aux.writable())) { // lint-world: aux randomness + return webcpp::crypto::error::entropy_unavailable; + } + return key_.sign_schnorr(event_id, aux.bytes()); } private: - /** Destroys a context made in a resource, and gives its memory back there. */ - struct context_deleter { - std::pmr::memory_resource* memory = nullptr; - - void operator()(secp256k1_context* c) const { - secp256k1_context_preallocated_destroy(c); - memory->deallocate(c, context_size(), alignof(std::max_align_t)); + /** The signer of a key pair: its x-only public key's text, in `memory`. */ + [[nodiscard]] static boost::system::result from_keypair( + webcpp::crypto::curves::secp256k1::keypair key, std::pmr::memory_resource* memory) { + const auto xonly = key.xonly_public_key(); + if (!xonly) { + return xonly.error(); } - }; - - // A context that signs and verifies needs no flag. libsecp256k1 spells it with a shift of a - // signed constant, (1 << 0), inside its own macro, which is the dependency's to write. - // NOLINTNEXTLINE(bugprone-signed-bitwise) - static constexpr unsigned context_flags = SECP256K1_CONTEXT_NONE; - - static std::size_t context_size() { return secp256k1_context_preallocated_size(context_flags); } + return signer(std::move(key), to_hex(*xonly, memory)); + } - explicit signer(std::pmr::memory_resource* memory) - : context_(secp256k1_context_preallocated_create( - memory->allocate(context_size(), alignof(std::max_align_t)), context_flags), - context_deleter{memory}), - pubkey_(memory) {} + signer(webcpp::crypto::curves::secp256k1::keypair key, std::pmr::string pubkey) + : key_(std::move(key)), pubkey_(std::move(pubkey)) {} - std::unique_ptr context_; - secp256k1_keypair keypair_{}; + webcpp::crypto::curves::secp256k1::keypair key_; std::pmr::string pubkey_; }; /** * Whether a BIP-340 signature over an event id verifies under an x-only public key. * - * It uses libsecp256k1's static context, which allocates nothing. + * It is webcpp::crypto's `verify_schnorr`, on libsecp256k1's static context, which allocates + * nothing. * * @param sig The signature. * @param id The event id. @@ -251,12 +279,7 @@ class signer { */ inline bool verify(std::span sig, std::span id, std::span pubkey) { - secp256k1_xonly_pubkey key; - if (secp256k1_xonly_pubkey_parse(secp256k1_context_static, &key, pubkey.data()) == 0) { - return false; - } - return secp256k1_schnorrsig_verify(secp256k1_context_static, sig.data(), id.data(), id.size(), - &key) == 1; + return webcpp::crypto::curves::secp256k1::verify_schnorr(sig, id, pubkey).has_value(); } /** @@ -270,21 +293,24 @@ inline bool verify(std::span sig, std::span event_message( const signer& key, std::chrono::sys_seconds created_at, std::string_view topic, - std::string_view content, std::span aux, + std::string_view content, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { const auto kind = topic_kind(topic); const auto quoted_topic = detail::quoted(topic, memory); const auto quoted_content = detail::quoted(content, memory); - const auto id = detail::event_id(key.pubkey(), created_at, kind, quoted_topic, quoted_content); - const auto sig = key.sign(id, aux); + const auto id = + detail::event_id(key.pubkey_hex(), created_at, kind, quoted_topic, quoted_content); + const auto sig = key.sign(id); + if (!sig) { + return sig.error(); + } std::pmr::string out(memory); out.reserve(256 + quoted_topic.size() + quoted_content.size()); out += R"(["EVENT",{"kind":)"; @@ -296,11 +322,11 @@ inline std::pmr::string event_message( out += R"(,"content":)"; out += quoted_content; out += R"(,"pubkey":")"; - out += key.pubkey(); + out += key.pubkey_hex(); out += R"(","id":")"; append_hex(out, id); out += R"(","sig":")"; - append_hex(out, sig); + append_hex(out, *sig); out += R"("}])"; return out; } @@ -310,9 +336,10 @@ inline std::pmr::string event_message( * "since": t, "#x": [...]}]`. * * @param subscription The subscription's id. - * @param topics The topics, whose kinds the filter lists once each, in increasing order. + * @param topics The topics, at most @ref max_topics_per_subscription, whose kinds the filter lists + * once each, in the order of their first topic, as Trystero's `new Set` keeps them. * @param since The earliest `created_at` of the events wanted, in whole seconds since the Unix - * epoch. + * epoch, @ref subscribe_since of now in a room. * @param memory The resource the message is allocated in. * @return The message's JSON text. * @pre `subscription` and the topics are UTF-8, as a room's, which are ASCII, are. @@ -321,9 +348,12 @@ inline std::pmr::string subscribe_message( std::string_view subscription, std::span topics, std::chrono::sys_seconds since, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - std::pmr::set kinds(memory); + std::pmr::vector kinds(memory); + kinds.reserve(topics.size()); for (const auto& t : topics) { - kinds.insert(topic_kind(t)); + if (const auto k = topic_kind(t); std::ranges::find(kinds, k) == kinds.end()) { + kinds.push_back(k); + } } std::pmr::string out(memory); out.reserve(96 + subscription.size() + (topics.size() * 48)); diff --git a/include/webcpp/trystero/protocol/relays.hpp b/include/webcpp/trystero/protocol/relays.hpp index 246a880..4ce3254 100644 --- a/include/webcpp/trystero/protocol/relays.hpp +++ b/include/webcpp/trystero/protocol/relays.hpp @@ -13,10 +13,13 @@ #include #include +#include +#include #include #include #include #include +#include #include namespace webcpp::trystero::protocol { @@ -42,72 +45,73 @@ inline constexpr std::size_t max_relay_message_bytes = std::size_t{1} << 20U; inline constexpr std::size_t max_queued_relay_bytes = std::size_t{4} << 20U; /** - * Trystero 0.26's default Nostr relays, its `defaultRelayUrls`, in its order: the order is part of - * the relay derivation. + * Trystero 0.27.0's default Nostr relays, its `defaultRelayUrls`, in its order: the order is part + * of the relay derivation. */ -inline constexpr std::array default_nostr_relays{ - "wss://0x-nostr-relay.fly.dev", - "wss://bendernostur.duckdns.org:8443", - "wss://cdn.satellite.earth", - "wss://nos.lol", +inline constexpr std::array default_nostr_relays{ + "wss://bucket.coracle.social", + "wss://fanfares.nostr1.com", + "wss://no.str.cr", + "wss://nostr-01.yakihonne.com", + "wss://nostr-pub.wellorder.net", + "wss://nostr.azzamo.net", "wss://nostr.chaima.info", - "wss://nostr.christiansass.de", - "wss://nostr.rblb.it", - "wss://nostr.red5d.dev", - "wss://nostr.robosats.org", - "wss://nostr.stakey.net", - "wss://nostrcity-club.fly.dev", - "wss://relay-dev.gulugulu.moe", - "wss://relay.aarpia.com", - "wss://relay.agentry.com", - "wss://relay.bitmacro.cloud", - "wss://relay.bullishbounty.com", - "wss://relay.degmods.com", - "wss://relay.flashapp.me", - "wss://relay.grigic.org", - "wss://relay.hackshed.dev", - "wss://relay.kaleidoswap.com", - "wss://relay.layer.systems", - "wss://relay.nostr.blockhenge.com", - "wss://relay.nostr.dev.br", - "wss://relay.nostrmap.net", - "wss://relay.novospes.com", - "wss://relay.piazza.today", - "wss://relay.routstr.com", - "wss://testr.nymble.world", + "wss://nostr.data.haus", + "wss://nostr.hifish.org", + "wss://nostr.liberty.fans", + "wss://nostr.overmind.lol", + "wss://nostr.sathoarder.com", + "wss://nostrelay.circum.space", + "wss://relay.angor.io", + "wss://relay.ditto.pub", + "wss://relay.dwadziesciajeden.pl", + "wss://relay.fundstr.me", + "wss://relay.guggero.org", + "wss://relay.masize.com", + "wss://relay.minibolt.info", + "wss://relay.mostro.network", + "wss://relay.nostr.com", + "wss://relay.nostr.net", + "wss://relay.nostrhub.fr", + "wss://relay.notoshi.win", + "wss://relay.primal.net", + "wss://relay.snort.social", + "wss://relay.wavlake.com", + "wss://soloco.nl", + "wss://yabu.me", }; /** - * Trystero's `shuffle`: Fisher-Yates driven by `sin(seed++) * 10000`, so every peer of an app picks - * the same order. + * Trystero 0.27.0's `shuffle`: a Fisher-Yates shuffle driven by a 32-bit generator (mulberry32) + * seeded with `seed`, so every peer of an app picks the same order. * - * Tip: the seed and the draws are doubles, JavaScript's Numbers, as in Trystero; `std::sin` and - * V8's `Math.sin` agree on these inputs; the oracle's fixtures check it. + * Tip: the generator is integer-only, so every target and every standard library shuffle alike. * - * @tparam Sequence A sequence with `size()` and random access, as `std::pmr::vector`. - * @param items The items, shuffled in the copy returned. - * @param seed The seed, @ref str_to_num of the app id for the relays. - * @return The items, shuffled. + * @tparam T The element type. + * @param xs The elements, shuffled in place. + * @param seed The seed; 0 stands for 1, as in Trystero. */ -template -Sequence shuffle(Sequence items, double seed) { - const auto rand = [&seed] { - const double x = std::sin(seed++) * 10000; - return x - std::floor(x); +template +void seeded_shuffle(std::span xs, std::uint32_t seed) { + std::uint32_t state = seed != 0 ? seed : 1U; + const auto rand = [&state] { + state += 0x6d2b79f5U; + std::uint32_t t = (state ^ (state >> 15U)) * (1U | state); + t = (t + ((t ^ (t >> 7U)) * (61U | t))) ^ t; + return static_cast(t ^ (t >> 14U)) / 4294967296.0; }; - for (std::size_t i = items.size(); i != 0;) { + for (std::size_t i = xs.size(); i != 0;) { const auto j = static_cast(std::floor(rand() * static_cast(i))); --i; - std::swap(items[i], items[j]); + std::swap(xs[i], xs[j]); } - return items; } /** - * The relays an app uses when it names none, Trystero's `getRelays`: the defaults shuffled by the - * app id, the first `redundancy` kept. + * The relays an app uses when it names none, Trystero's `getRelays`: the defaults shuffled by + * @ref str_to_num of the app id, the first `redundancy` kept. * - * @param app_id The application's id, whose @ref str_to_num seeds the shuffle. + * @param app_id The application's id. * @param defaults The relays to choose from, @ref default_nostr_relays for a room. * @param redundancy How many to keep. * @param memory The resource the list is allocated in. @@ -116,9 +120,8 @@ Sequence shuffle(Sequence items, double seed) { inline std::pmr::vector derive_relays( std::string_view app_id, std::span defaults, std::size_t redundancy, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - auto shuffled = - shuffle(std::pmr::vector(defaults.begin(), defaults.end(), memory), - str_to_num(app_id)); + std::pmr::vector shuffled(defaults.begin(), defaults.end(), memory); + seeded_shuffle(std::span(shuffled), static_cast(str_to_num(app_id))); if (shuffled.size() > redundancy) { shuffled.resize(redundancy); } diff --git a/include/webcpp/trystero/protocol/room_keys.hpp b/include/webcpp/trystero/protocol/room_keys.hpp new file mode 100644 index 0000000..d281a58 --- /dev/null +++ b/include/webcpp/trystero/protocol/room_keys.hpp @@ -0,0 +1,236 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_TRYSTERO_PROTOCOL_ROOM_KEYS_HPP +#define WEBCPP_TRYSTERO_PROTOCOL_ROOM_KEYS_HPP + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::protocol { + +/** The iterations of the PBKDF2 that turns a room's password into its master key, 0.27.0's. */ +inline constexpr std::uint64_t pbkdf2_iterations = 600'000; + +/** The largest sequence number of a room authentication token, `Number.MAX_SAFE_INTEGER`. */ +inline constexpr std::uint64_t max_room_auth_seq = (std::uint64_t{1} << 53U) - 1; + +/** + * The keys of a room that has a password: the AES-256-GCM key its signals are sealed under and the + * HMAC-SHA-256 key its authentication tokens are signed with. + */ +struct room_keys { + /** The key the room's signals are sealed under. */ + webcpp::crypto::secret<32> aes; + /** The key the room's authentication tokens are signed with. */ + webcpp::crypto::secret<32> hmac; +}; + +namespace detail { + +/** The bytes of a text, as a span. */ +inline std::span bytes_of_text(std::string_view text) noexcept { + return {reinterpret_cast(text.data()), text.size()}; +} + +} // namespace detail + +/** + * The AES key of a room without a password: the SHA-256 of + * `JSON.stringify(["trystero:room-aes:v3", appId, roomId])`. + * + * @param app_id The app id, in UTF-8. + * @param room_id The room id, in UTF-8. + * @param memory The resource the hashed text is allocated in. + * @return The key. + */ +inline webcpp::crypto::secret<32> room_aes_key_without_password( + std::string_view app_id, std::string_view room_id, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + webcpp::crypto::secret<32> key; + auto digest = sha256(topic_path({domain_tag("room-aes", 3, memory), app_id, room_id}, memory)); + std::ranges::copy(digest, key.writable().begin()); + // webcpp::crypto has no public wipe of an array yet: trystero's own (detail/wipe.hpp). + webcpp::trystero::detail::wipe_object(digest); + return key; +} + +/** + * The salt of the PBKDF2 that turns a room's password into its master key: the SHA-256 of + * `JSON.stringify(["trystero:pbkdf2-master:v3", appId, roomId])`. + * + * @param app_id The app id, in UTF-8. + * @param room_id The room id, in UTF-8. + * @param memory The resource the hashed text is allocated in. + * @return The salt. + */ +inline std::array pbkdf2_salt( + std::string_view app_id, std::string_view room_id, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + return sha256(topic_path({domain_tag("pbkdf2-master", 3, memory), app_id, room_id}, memory)); +} + +/** + * The AES and HMAC keys of a room that has a password, from its PBKDF2 master: two HKDF-SHA-256 + * derivations of 32 bytes over a salt of 32 zero bytes, with the infos `trystero:room-aes:v3` and + * `trystero:room-hmac:v3`, which is what WebCrypto's `deriveKey` of a 256-bit key yields. + * + * @param master The 32 bytes of PBKDF2 over the password, @ref pbkdf2_salt and + * @ref pbkdf2_iterations. + * @param memory The resource the infos are allocated in. + * @return The keys, or the error of the derivation. + */ +[[nodiscard]] inline boost::system::result derive_room_keys( + std::span master, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + constexpr std::array no_salt{}; + room_keys keys; + const auto aes_info = domain_tag("room-aes", 3, memory); + auto derived = webcpp::hash::hkdf( + keys.aes.writable(), no_salt, master, detail::bytes_of_text(aes_info)); + if (!derived) { + return derived.error(); + } + const auto hmac_info = domain_tag("room-hmac", 3, memory); + derived = webcpp::hash::hkdf(keys.hmac.writable(), no_salt, master, + detail::bytes_of_text(hmac_info)); + if (!derived) { + return derived.error(); + } + return keys; +} + +/** + * The text a room authentication token is the MAC of: + * `JSON.stringify(["trystero:ov-auth:v3", appId, roomId, peerId, seq])`. + * + * @param app_id The app id, in UTF-8. + * @param room_id The room id, in UTF-8. + * @param peer_id The id of the peer the token is for. + * @param seq The token's sequence number. + * @param memory The resource the text is allocated in. + * @pre `seq` is at most @ref max_room_auth_seq, since a number a peer sends is checked by + * @ref verify_room_auth, which refuses a larger one, before it reaches here. + * @return The text. + */ +inline std::pmr::string room_auth_payload( + std::string_view app_id, std::string_view room_id, std::string_view peer_id, std::uint64_t seq, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + BOOST_ASSERT(seq <= max_room_auth_seq); + std::pmr::string out(memory); + out += '['; + json::append_string_total(out, domain_tag("ov-auth", 3, memory)); + for (const auto part : {app_id, room_id, peer_id}) { + out += ','; + json::append_string_total(out, part); + } + out += ','; + json::append_integer(out, static_cast(seq)); + out += ']'; + return out; +} + +namespace detail { + +/** The HMAC-SHA-256 of a room authentication payload. */ +inline std::array room_auth_mac(const webcpp::crypto::secret<32>& hmac_key, + std::string_view app_id, std::string_view room_id, + std::string_view peer_id, std::uint64_t seq, + std::pmr::memory_resource* memory) { + const auto payload = room_auth_payload(app_id, room_id, peer_id, seq, memory); + const auto key = hmac_key.bytes(); + webcpp::hash::hmac_sha2_256 mac(key.data(), key.size()); + mac.update(payload.data(), payload.size()); + const auto result = mac.result(); + std::array out{}; + std::ranges::copy(result, out.begin()); + return out; +} + +} // namespace detail + +/** + * A room authentication token: the base64url of the HMAC-SHA-256 of @ref room_auth_payload. + * + * @param hmac_key The room's HMAC key. + * @param app_id The app id, in UTF-8. + * @param room_id The room id, in UTF-8. + * @param peer_id The id of the peer the token is for. + * @param seq The token's sequence number, at most @ref max_room_auth_seq. + * @param memory The resource the token and its working text are allocated in. + * @pre `seq` is at most @ref max_room_auth_seq. + * @return The token, 43 characters. + */ +inline std::pmr::string sign_room_auth( + const webcpp::crypto::secret<32>& hmac_key, std::string_view app_id, std::string_view room_id, + std::string_view peer_id, std::uint64_t seq, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + return to_base64url(detail::room_auth_mac(hmac_key, app_id, room_id, peer_id, seq, memory), + memory); +} + +/** + * Whether a token is the one @ref sign_room_auth makes: it must read as strict base64url of 32 + * bytes, and equal the recomputed MAC in constant time. + * + * @param hmac_key The room's HMAC key. + * @param app_id The app id, in UTF-8. + * @param room_id The room id, in UTF-8. + * @param peer_id The id of the peer the token claims to be for. + * @param seq The sequence number the token claims. + * @param token The token received. + * @param memory The resource the working text is allocated in. + * @return Whether the token is genuine; false, as 0.27.0 answers, when `seq` is beyond + * @ref max_room_auth_seq. + */ +inline bool verify_room_auth(const webcpp::crypto::secret<32>& hmac_key, std::string_view app_id, + std::string_view room_id, std::string_view peer_id, std::uint64_t seq, + std::string_view token, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + if (seq > max_room_auth_seq) { + return false; + } + // 32 bytes are 43 characters unpadded; any other length is refused before it is decoded, so + // that the decoding below fits its arena. + constexpr std::size_t token_size = 43; + if (token.size() != token_size) { + return false; + } + std::array storage{}; + std::pmr::monotonic_buffer_resource arena(storage.data(), storage.size(), + std::pmr::null_memory_resource()); + const auto given = from_base64url(token, &arena); + if (!given || given->size() != 32) { + return false; + } + const auto expected = detail::room_auth_mac(hmac_key, app_id, room_id, peer_id, seq, memory); + return webcpp::crypto::equal(std::span(*given), expected); +} + +} // namespace webcpp::trystero::protocol + +#endif diff --git a/include/webcpp/trystero/protocol/seal.hpp b/include/webcpp/trystero/protocol/seal.hpp new file mode 100644 index 0000000..6976d7f --- /dev/null +++ b/include/webcpp/trystero/protocol/seal.hpp @@ -0,0 +1,167 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_TRYSTERO_PROTOCOL_SEAL_HPP +#define WEBCPP_TRYSTERO_PROTOCOL_SEAL_HPP + +#include + +#include +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero::protocol { + +/** The size of the IV of a sealed signal, AES-GCM's 12 bytes, 0.27.0's `gcmIvBytes`. */ +inline constexpr std::size_t gcm_iv_size = 12; + +/** The size of the tag of a sealed signal, 16 bytes, 0.27.0's `gcmTagBytes`. */ +inline constexpr std::size_t gcm_tag_size = 16; + +/** + * The size of the text a plaintext seals to: the unpadded base64url of the IV, the ciphertext and + * the tag. + * + * @param plaintext The plaintext's size, in bytes. + * @return The size of the sealed text, in bytes. + */ +constexpr std::size_t sealed_size(std::size_t plaintext) { + const std::size_t packed = gcm_iv_size + plaintext + gcm_tag_size; + return ((4 * packed) + 2) / 3; +} + +namespace detail { + +/** The bytes of a text, as a span. */ +inline std::span seal_bytes_of(std::string_view text) noexcept { + return {reinterpret_cast(text.data()), text.size()}; +} + +} // namespace detail + +/** + * Seals a signal's plaintext as 0.27.0's `encrypt` does: AES-256-GCM, and the base64url of the IV, + * the ciphertext and the tag. + * + * An absent AAD and an empty one are the same to GCM; the parameter keeps Trystero's distinction + * readable at the call. + * + * @param key The room's AES key. + * @param iv The 12 bytes of the IV, never repeated under `key`. + * @param plaintext The text to seal. + * @param aad The additional authenticated data, @ref signal_aad for a signal; absent for none. + * @param memory The resource the sealed text and the working buffer are allocated in. + * @return The sealed text, @ref sealed_size characters, or the error of the cipher. + */ +[[nodiscard]] inline boost::system::result seal( + const webcpp::crypto::secret<32>& key, std::span iv, + std::string_view plaintext, std::optional aad, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + auto cipher = webcpp::crypto::ciphers::aes256_gcm::make(key.bytes()); + if (!cipher) { + return cipher.error(); + } + // The working buffer holds the IV, then the plaintext, sealed in place, then the tag. + bytes packed(memory); + packed.reserve(gcm_iv_size + plaintext.size() + gcm_tag_size); + packed.insert(packed.end(), iv.begin(), iv.end()); + const auto body = detail::seal_bytes_of(plaintext); + packed.insert(packed.end(), body.begin(), body.end()); + const auto tag = + cipher->seal(iv, aad ? detail::seal_bytes_of(*aad) : std::span{}, + std::span(packed).subspan(gcm_iv_size, plaintext.size())); + if (!tag) { + webcpp::trystero::detail::wipe(packed.data(), packed.size()); + return tag.error(); + } + packed.insert(packed.end(), tag->begin(), tag->end()); + auto out = to_base64url(packed, memory); + webcpp::trystero::detail::wipe(packed.data(), packed.size()); + return out; +} + +/** + * Opens a sealed signal as 0.27.0's `decrypt` does, strictly. + * + * @param key The room's AES key. + * @param sealed The sealed text. + * @param aad The additional authenticated data the seal used; absent for none. + * @param memory The resource the plaintext and the working buffer are allocated in. + * @return The plaintext; `error::decrypt_failed` for a text that is not strict base64url (what + * @ref from_base64url refuses), one of fewer than 28 bytes, a tag that does not match the key and + * the AAD, or a plaintext that is not UTF-8 (design D12); or the error of the cipher, when it + * cannot be made. + */ +[[nodiscard]] inline boost::system::result open( + const webcpp::crypto::secret<32>& key, std::string_view sealed, + std::optional aad, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + auto packed = from_base64url(sealed, memory); + if (!packed || packed->size() < gcm_iv_size + gcm_tag_size) { + return error::decrypt_failed; + } + auto cipher = webcpp::crypto::ciphers::aes256_gcm::make(key.bytes()); + if (!cipher) { + return cipher.error(); + } + const std::span all(*packed); + const auto body = all.subspan(gcm_iv_size, all.size() - gcm_iv_size - gcm_tag_size); + const auto opened = cipher->open( + all.first(gcm_iv_size), aad ? detail::seal_bytes_of(*aad) : std::span{}, + body, all.last(gcm_tag_size)); + if (!opened) { + webcpp::trystero::detail::wipe(packed->data(), packed->size()); + return error::decrypt_failed; + } + std::pmr::string out(reinterpret_cast(body.data()), body.size(), memory); + webcpp::trystero::detail::wipe(packed->data(), packed->size()); + if (!json::quotable(out)) { + webcpp::trystero::detail::wipe(out.data(), out.size()); + return error::decrypt_failed; + } + return out; +} + +/** + * The AAD of a signal's sealed field: `type + "|" + peerId + "|" + offerId`. + * + * @param type "offer", "answer" or "candidate". + * @param peer_id The id of the peer that sent the signal. + * @param offer_id The id of the offer the signal belongs to. + * @param memory The resource the text is allocated in. + * @return The AAD. + */ +inline std::pmr::string signal_aad( + std::string_view type, std::string_view peer_id, std::string_view offer_id, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + std::pmr::string out(memory); + out.reserve(type.size() + peer_id.size() + offer_id.size() + 2); + out += type; + out += '|'; + out += peer_id; + out += '|'; + out += offer_id; + return out; +} + +} // namespace webcpp::trystero::protocol + +#endif diff --git a/include/webcpp/trystero/protocol/signal.hpp b/include/webcpp/trystero/protocol/signal.hpp index 8accea9..df9b29f 100644 --- a/include/webcpp/trystero/protocol/signal.hpp +++ b/include/webcpp/trystero/protocol/signal.hpp @@ -9,12 +9,14 @@ #include +#include #include +#include #include #include -#include -#include +#include +#include #include #include #include @@ -23,153 +25,78 @@ namespace webcpp::trystero::protocol { /** - * The longest peer id a room accepts in a signal, in bytes; a signal with a longer one is - * ignored. + * The longest offer id a signal may carry, in characters: 0.27.0's `maxSignalOfferIdChars`. * - * Every id Trystero makes is 20 characters (`selfId`, @ref peer_id_size); the bound leaves room for - * an application's own ids and keeps a flood of long ids from costing more than a short one. + * Trystero's own are @ref offer_id_size; @ref is_signal_offer_id is the whole rule. */ -inline constexpr std::size_t max_peer_id_bytes = 64; - -/** The size of the IV Trystero's `encrypt` draws for AES-GCM: 16 bytes, not the usual 12. */ -inline constexpr std::size_t seal_iv_size = 16; +inline constexpr std::size_t max_offer_id_chars = 64; /** - * The longest text a plaintext seals to, as @ref format_sealed writes it. - * - * The IV's bytes in decimal and commas, "$", and the ciphertext with its 16-byte tag in base64. + * The longest sealed offer or answer a signal may carry, in UTF-16 code units as JavaScript counts + * a string's length: 0.27.0's `maxSignalSdpChars`. * - * @param plaintext The plaintext's size, in bytes. - * @return The size of the longest sealed text, in bytes, whatever the IV. + * A sealed text is ASCII, one byte a unit. */ -constexpr std::size_t sealed_size(std::size_t plaintext) { - return (seal_iv_size * 4) - 1 + 1 + (((plaintext + 16 + 2) / 3) * 4); -} - -/** The longest offer id a signal may carry, in bytes; Trystero's are @ref offer_id_size. */ -inline constexpr std::size_t max_offer_id_bytes = 64; +inline constexpr std::size_t max_sealed_description_chars = std::size_t{64} * 1024; /** - * The longest sealed offer or answer a signal may carry, in bytes. + * The longest sealed candidate a signal may carry, in UTF-16 code units as JavaScript counts a + * string's length: 0.27.0's `maxSignalCandidateChars`. * - * A data channel's SDP is a few KiB, with every candidate gathered in it a few more. Trystero - * bounds none; this one bounds what a negotiation copies and keeps, and refuses no SDP a browser - * writes for a data channel. - */ -inline constexpr std::size_t max_sealed_description_bytes = std::size_t{64} * 1024; - -/** - * The longest sealed candidate a signal may carry, in bytes. + * A sealed text is ASCII, one byte a unit. * - * Trystero drops a candidate whose plaintext is longer than 8192 bytes - * (`maxRemoteCandidateSdpLength`), and every candidate up to that size, sealed, fits. + * It holds a candidate's JSON of up to 3044 bytes, sealed by @ref seal; 0.27.0 sends a longer one + * as it is, and its receivers, as a room, ignore the signal. */ -inline constexpr std::size_t max_sealed_candidate_bytes = std::size_t{16} * 1024; -static_assert(sealed_size(8192) <= max_sealed_candidate_bytes); +inline constexpr std::size_t max_sealed_candidate_chars = 4096; +static_assert(sealed_size(3044) == max_sealed_candidate_chars); +static_assert(sealed_size(3045) > max_sealed_candidate_chars); /** * The longest signal a room reads, in bytes: a longer one is dropped before it is read. * * The longest signal measured is an answer, 762 bytes, among Trystero JS in Chrome and both * backends, which trickle their candidates. The bound is the longest signal the bounds of its - * fields admit, a sealed offer or answer of @ref max_sealed_description_bytes with the longest ids, - * and 1 KiB to spare, so that it refuses no signal they accept. + * fields admit, a sealed offer or answer of @ref max_sealed_description_chars with the longest ids, + * and 1 KiB to spare, so that it refuses no signal Trystero writes. + * + * Tip: 0.27.0 parses a text of up to 128 Ki characters (`maxSignalMessageChars`). A room drops a + * longer text than this bound unread, where 0.27.0 parses it; only members Trystero never writes, + * or a sealed text that is not ASCII and so never opens, make one. The smaller bound bounds what a + * relay has a room parse. */ -inline constexpr std::size_t max_parsed_signal_bytes = max_sealed_description_bytes + 1024; -// The 64 bytes hold the 53 of the keys and the punctuation of an answer from a passive room. -static_assert(max_sealed_description_bytes + max_peer_id_bytes + max_offer_id_bytes + 64 <= +inline constexpr std::size_t max_parsed_signal_bytes = max_sealed_description_chars + 1024; +// The 64 bytes hold the keys and the punctuation of an offer or an answer, 38 at most. +static_assert(max_sealed_description_chars + peer_id_size + max_offer_id_chars + 64 <= max_parsed_signal_bytes, "the longest signal the bounds of its fields admit is read"); /** - * The longest message of the password handshake a room reads, in bytes: a longer one fails the - * handshake, as a message of the wrong shape does. + * Whether a text is a peer id a signal may carry, 0.27.0's `isValidSignalPeerId`: @ref peer_id_size + * characters of @ref base62_alphabet (`^[0-9A-Za-z]{20}$`). * - * Trystero's are at most 99 bytes, `{"__trystero_pw":"response","h":"<64 hexadecimal digits>"}`; - * the bound is ten times that. + * @param id The text. + * @return Whether it is one. */ -inline constexpr std::size_t max_handshake_bytes = 1024; - -/** - * The raw AES-GCM key of a room, what Trystero's `genKey` imports: the SHA-256 of - * "::". - * - * @param password The password used for this room, shared by its app; empty means none. - * @param app_id The application's id. - * @param room_id The room's id. - * @return The AES-256 key. - */ -inline std::array seal_key(std::string_view password, std::string_view app_id, - std::string_view room_id) { - return sha256_of({password, ":", app_id, ":", room_id}); +[[nodiscard]] constexpr bool is_signal_peer_id(std::string_view id) noexcept { + return id.size() == peer_id_size && std::ranges::all_of(id, [](char c) { + return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); + }); } -/** A sealed signal's parts, as @ref parse_sealed reads them. */ -struct sealed_parts { - /** The IV, 16 bytes in what Trystero writes. */ - bytes iv; - /** The ciphertext, followed by its 16-byte tag. */ - bytes ciphertext; -}; - /** - * The text form of a sealed signal, what Trystero's `encrypt` returns: the IV's bytes in decimal - * joined by commas, "$", the ciphertext in base64. + * Whether a text is an offer id a signal may carry, 0.27.0's `isValidSignalOfferId`: 1 to + * @ref max_offer_id_chars characters, each a letter or a digit of ASCII or one of `_.~:!-` + * (`^[0-9A-Za-z_.~:!-]{1,64}$`). * - * @param iv The IV. - * @param ciphertext The ciphertext with its tag, as `crypto.subtle.encrypt` returns it. - * @param memory The resource the text is allocated in. - * @return The text. + * @param id The text. + * @return Whether it is one. */ -inline std::pmr::string format_sealed( - std::span iv, std::span ciphertext, - std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - std::pmr::string out(memory); - out.reserve((iv.size() * 4) + 1 + ((ciphertext.size() + 2) / 3 * 4)); - for (std::size_t i = 0; i < iv.size(); ++i) { - if (i != 0) { - out += ','; - } - json::append_integer(out, iv[i]); - } - out += '$'; - append_base64(out, ciphertext); - return out; -} - -/** - * The parts of a sealed signal's text, as Trystero's `decrypt` splits it. - * - * @param text The text. - * @param memory The resource the parts are allocated in. - * @return The parts, or nothing when the text has no "$", an IV byte that is not a decimal number - * up to 255, or a ciphertext that is not base64. - */ -inline std::optional parse_sealed( - std::string_view text, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - const auto dollar = text.find('$'); - if (dollar == std::string_view::npos) { - return std::nullopt; - } - sealed_parts out{.iv = bytes(memory), .ciphertext = bytes(memory)}; - for (std::string_view ivs = text.substr(0, dollar); !ivs.empty();) { - const auto comma = ivs.find(','); - const auto item = ivs.substr(0, comma); - // A byte: from_chars refuses a number above 255 as out of range. - std::uint8_t value = 0; - const auto [end, ec] = std::from_chars(item.data(), item.data() + item.size(), value); - if (ec != std::errc{} || end != item.data() + item.size()) { - return std::nullopt; - } - out.iv.push_back(value); - ivs = comma == std::string_view::npos ? std::string_view{} : ivs.substr(comma + 1); - } - auto ciphertext = base64_decode(text.substr(dollar + 1), memory); - if (!ciphertext) { - return std::nullopt; - } - out.ciphertext = std::move(*ciphertext); - return out; +[[nodiscard]] constexpr bool is_signal_offer_id(std::string_view id) noexcept { + return !id.empty() && id.size() <= max_offer_id_chars && std::ranges::all_of(id, [](char c) { + return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || + std::string_view("_.~:!-").find(c) != std::string_view::npos; + }); } /** @@ -182,9 +109,12 @@ inline std::optional parse_sealed( * @see "The protocol", in the guide. */ struct signal_message { - /** The sender's id, `peerId`: 1 to @ref max_peer_id_bytes bytes. */ + /** The sender's id, `peerId`, one for which @ref is_signal_peer_id holds. */ std::string_view peer_id = {}; - /** The offer the message belongs to, `offerId`; empty in an announcement. */ + /** + * The offer the message belongs to, `offerId`, one for which @ref is_signal_offer_id holds; + * empty in an announcement that carries none. + */ std::string_view offer_id = {}; /** The sealed SDP of an offer, `offer`. */ std::string_view offer = {}; @@ -192,19 +122,6 @@ struct signal_message { std::string_view answer = {}; /** A sealed ICE candidate, `candidate`. */ std::string_view candidate = {}; - /** - * Whether the sender's room is passive, `passive`: a Trystero room joined with `passive` - * announces only once it has seen a peer that is not passive. - */ - bool passive = false; - /** - * Whether the sender answers the offer, which places `offerId` in the text. - * - * Trystero's answerer writes `offerId` after its answer or candidate, its offerer before its - * offer or candidate. Written only; a reader leaves it false, the order being no part of the - * meaning. - */ - bool answering = false; /** * Whether the message is an announcement. @@ -217,17 +134,19 @@ struct signal_message { }; /** - * The message a parsed signaling payload holds, as views into its document. + * The message a parsed signaling payload holds, as views into its document, read as 0.27.0's + * `parseSignalEnvelope` reads it: what it refuses, a room ignores. * * A key written twice is read as JavaScript reads it, the last value, which the parse keeps. * * @param document The root of the parsed payload, whose document the caller keeps alive and * unchanged while it reads the views. - * @return The message, or nothing when Trystero would ignore it (not an object, one with a member - * `peer`, no peer id, or an offer, answer or candidate that is not a non-empty string), or when a - * field is longer than its bound: the peer id than @ref max_peer_id_bytes, the offer id than - * @ref max_offer_id_bytes, an offer or answer than @ref max_sealed_description_bytes, a candidate - * than @ref max_sealed_candidate_bytes. + * @return The message, or nothing when 0.27.0 refuses it or acts on no peer: not an object; one + * with a member `peer`; no `peerId`, or one for which @ref is_signal_peer_id does not hold; an + * `offerId` for which @ref is_signal_offer_id does not hold (a value that is no string included), + * or none with an offer, answer or candidate; an offer, answer or candidate that is not a non-empty + * string, an offer or answer longer than @ref max_sealed_description_chars, a candidate longer than + * @ref max_sealed_candidate_chars. */ inline std::optional read_signal(const json::const_value& document) { // Trystero ignores a text that names a member `peer`, which its own rooms keep for a peer @@ -236,37 +155,51 @@ inline std::optional read_signal(const json::const_value& docume return std::nullopt; } signal_message out; - const auto text = [&document](std::string_view key, std::string_view& into, - bool must_be_nonempty) { + bool content = false; + // An offer, answer or candidate, when present, is a non-empty string within its bound, counted + // in UTF-16 code units as JavaScript's length counts it. + const auto sealed = [&document, &content](std::string_view key, std::string_view& into, + std::size_t bound) { const json::const_value v = document[key]; if (v.is_undefined()) { return true; } - if (!v.is_string() || (must_be_nonempty && json::text_of(v).empty())) { - return !must_be_nonempty; + content = true; + const auto units = v.length(); + if (!v.is_string() || !units || *units == 0 || *units > bound) { + return false; } into = json::text_of(v); return true; }; - if (!text("offer", out.offer, true) || !text("answer", out.answer, true) || - !text("candidate", out.candidate, true)) { + if (!sealed("offer", out.offer, max_sealed_description_chars) || + !sealed("answer", out.answer, max_sealed_description_chars) || + !sealed("candidate", out.candidate, max_sealed_candidate_chars)) { return std::nullopt; } - text("peerId", out.peer_id, false); - text("offerId", out.offer_id, false); - out.passive = document["passive"].value_or(false); - if (out.peer_id.empty() || out.peer_id.size() > max_peer_id_bytes || - out.offer_id.size() > max_offer_id_bytes || - out.offer.size() > max_sealed_description_bytes || - out.answer.size() > max_sealed_description_bytes || - out.candidate.size() > max_sealed_candidate_bytes) { + // A peer id that is not one refuses the signal, and so does none, on which 0.27.0 acts no + // further. An offer id, when present, or when the signal carries an offer, answer or + // candidate, is one: JSON holds no `undefined`, so a member `offerId` of any other value + // refuses. + const json::const_value peer_id = document["peerId"]; + const json::const_value offer_id = document["offerId"]; + if (!peer_id.is_string() || !is_signal_peer_id(json::text_of(peer_id))) { return std::nullopt; } + out.peer_id = json::text_of(peer_id); + if (content || !offer_id.is_undefined()) { + if (!offer_id.is_string() || !is_signal_offer_id(json::text_of(offer_id))) { + return std::nullopt; + } + out.offer_id = json::text_of(offer_id); + } return out; } /** - * The JSON text of a message, with its members in Trystero's order and the empty ones left out. + * The JSON text of a message, as 0.27.0's signal handler writes it: `peerId`, then `offerId`, then + * the one of `offer`, `answer` and `candidate` it carries, the empty ones left out, and `nonce` + * last, as the Nostr strategy adds it to an announcement. * * @param m The message. * @param nonce A random text, which makes repeated announcements distinct events; empty for none. @@ -291,42 +224,15 @@ inline std::pmr::string write_signal( json::detail::append_utf8(out, value); }; field("peerId", m.peer_id); - if (!m.answering) { - field("offerId", m.offer_id); - } + field("offerId", m.offer_id); field("offer", m.offer); field("answer", m.answer); field("candidate", m.candidate); - if (m.answering) { - field("offerId", m.offer_id); - } - if (m.passive) { - json::append_key(out, "passive"); - out += "true"; - } field("nonce", nonce); out += '}'; return out; } -/** - * The password handshake's proof, Trystero's `hashChallenge`: the hexadecimal SHA-256 of - * ":::". - * - * @param challenge The challenge the other peer sent. - * @param password The password used for this room, shared by its app. - * @param app_id The application's id. - * @param room_id The room's id. - * @param memory The resource the proof is allocated in. - * @return The proof, 64 hexadecimal digits. - */ -inline std::pmr::string handshake_proof( - std::string_view challenge, std::string_view password, std::string_view app_id, - std::string_view room_id, - std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - return to_hex(sha256_of({challenge, ":", password, ":", app_id, ":", room_id}), memory); -} - } // namespace webcpp::trystero::protocol #endif diff --git a/include/webcpp/trystero/protocol/text.hpp b/include/webcpp/trystero/protocol/text.hpp index 21c5ba6..3a75068 100644 --- a/include/webcpp/trystero/protocol/text.hpp +++ b/include/webcpp/trystero/protocol/text.hpp @@ -9,7 +9,9 @@ #include +#include #include +#include #include #include #include @@ -195,18 +197,144 @@ inline std::optional base64_decode( } /** - * The sum of the UTF-16 code units of a UTF-8 text, what JavaScript's `charCodeAt` sees. + * Appends unpadded base64url, Trystero's `toBase64Url`. * - * Tip: Trystero derives Nostr kinds and the relay shuffle seed from it, so non-ASCII ids must count - * as in JS. The sum is a double, JavaScript's Number, as Trystero's is; the oracle's fixtures pin - * it. + * @param out The text to append to. + * @param in The bytes. + */ +inline void append_base64url(std::pmr::string& out, std::span in) { + static constexpr std::string_view table = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + std::size_t i = 0; + for (; i + 2 < in.size(); i += 3) { + const std::uint32_t v = (std::uint32_t{in[i]} << 16U) | (std::uint32_t{in[i + 1]} << 8U) | + std::uint32_t{in[i + 2]}; + out += table[(v >> 18U) & 63U]; + out += table[(v >> 12U) & 63U]; + out += table[(v >> 6U) & 63U]; + out += table[v & 63U]; + } + if (const auto rest = in.size() - i; rest == 1) { + const std::uint32_t v = std::uint32_t{in[i]} << 16U; + out += table[(v >> 18U) & 63U]; + out += table[(v >> 12U) & 63U]; + } else if (rest == 2) { + const std::uint32_t v = (std::uint32_t{in[i]} << 16U) | (std::uint32_t{in[i + 1]} << 8U); + out += table[(v >> 18U) & 63U]; + out += table[(v >> 12U) & 63U]; + out += table[(v >> 6U) & 63U]; + } +} + +/** + * Unpadded base64url, Trystero's `toBase64Url`. + * + * @param in The bytes. + * @param memory The resource the text is allocated in. + * @return The text, `A-Za-z0-9_-` only, without padding. + */ +inline std::pmr::string to_base64url( + std::span in, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + std::pmr::string out(memory); + append_base64url(out, in); + return out; +} + +/** + * The bytes of a base64url text, read strictly as Trystero's `fromBase64Url` reads it. + * + * The text must be nonempty, of `A-Za-z0-9_-` only, without padding, of a length that is not 1 + * modulo 4, and canonical: the unused low bits of its last character are zero, so that encoding + * the bytes gives the text back. + * + * @param text The text. + * @param memory The resource the bytes are allocated in. + * @return The bytes, or nothing when the text is not strict base64url. + */ +inline std::optional from_base64url( + std::string_view text, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + // A digit's value, or `not_base64` for a character that is none. + constexpr std::uint32_t not_base64 = 64; + const auto value = [](char c) -> std::uint32_t { + if (c >= 'A' && c <= 'Z') { + return static_cast(c - 'A'); + } + if (c >= 'a' && c <= 'z') { + return static_cast(c - 'a' + 26); + } + if (c >= '0' && c <= '9') { + return static_cast(c - '0' + 52); + } + if (c == '-') { + return 62; + } + if (c == '_') { + return 63; + } + return not_base64; + }; + if (text.empty() || text.size() % 4 == 1) { + return std::nullopt; + } + bytes out(memory); + out.reserve(text.size() * 3 / 4); + std::uint32_t buffer = 0; + std::uint32_t bits = 0; + for (const char c : text) { + const std::uint32_t v = value(c); + if (v == not_base64) { + return std::nullopt; + } + buffer = ((buffer << 6U) | v) & 0xffffU; + bits += 6U; + if (bits >= 8U) { + bits -= 8U; + out.push_back(static_cast((buffer >> bits) & 0xffU)); + } + } + // The bits left over are the unused low bits of the last character, which must be zero. + if ((buffer & ((1U << bits) - 1U)) != 0) { + return std::nullopt; + } + return out; +} + +/** + * Whether `a` is before `b` in UTF-16 code unit order, JavaScript's string order (its `<`), both + * UTF-8. + * + * The orders differ only where a character from U+E000 to U+FFFF (lead byte 0xee or 0xef) meets + * one beyond U+FFFF (lead byte 0xf0 to 0xf4), whose surrogates are below 0xe000: those two lead + * bytes are ranked above the others. Two valid texts first differ at a lead byte or at a + * continuation byte of the same lead, which ranks as it is. + * + * @param a A text, in UTF-8. + * @param b Another, in UTF-8. + * @return Whether `a < b` in JavaScript. + */ +inline bool utf16_less(std::string_view a, std::string_view b) noexcept { + const auto rank = [](char c) { + const auto byte = static_cast(c); + return byte == 0xeeU || byte == 0xefU ? byte + 0x10U : unsigned{byte}; + }; + return std::ranges::lexicographical_compare(a, b, + [&](char x, char y) { return rank(x) < rank(y); }); +} + +/** + * Visits the UTF-16 code units of a UTF-8 text, what JavaScript's `charCodeAt` sees, in order. + * + * Tip: Trystero 0.27.0's `topicToKind` hashes a topic's code units, so a non-ASCII topic must + * count as in JavaScript: a character above U+FFFF is its two surrogates. A byte that does not + * start a sequence the text completes is visited as the unit of its own value. * + * @tparam Visit A callable with a `std::uint32_t`. * @param utf8 The text, in UTF-8. - * @return The sum of the code units of its UTF-16 form, a character above U+FFFF counting as its - * two surrogates. + * @param visit Called with each code unit, a `std::uint32_t` below 0x10000. */ -inline double utf16_code_unit_sum(std::string_view utf8) { - double sum = 0; +template +void for_each_utf16_code_unit(std::string_view utf8, Visit&& visit) { for (std::size_t i = 0; i < utf8.size();) { // The bytes as unsigned values: a char may be signed. const auto byte = [utf8](std::size_t at) -> std::uint32_t { @@ -228,14 +356,13 @@ inline double utf16_code_unit_sum(std::string_view utf8) { } if (point >= 0x10000) { point -= 0x10000; - sum += 0xd800 + (point >> 10U); - sum += 0xdc00 + (point & 0x3ffU); + visit(0xd800U + (point >> 10U)); + visit(0xdc00U + (point & 0x3ffU)); } else { - sum += point; + visit(point); } i += length; } - return sum; } } // namespace webcpp::trystero::protocol diff --git a/include/webcpp/trystero/protocol/topics.hpp b/include/webcpp/trystero/protocol/topics.hpp index c2ad80d..a125026 100644 --- a/include/webcpp/trystero/protocol/topics.hpp +++ b/include/webcpp/trystero/protocol/topics.hpp @@ -9,14 +9,14 @@ #include +#include #include -#include -#include +#include + +#include -#include #include -#include #include #include #include @@ -26,57 +26,41 @@ namespace webcpp::trystero::protocol { -/** The 62 characters Trystero draws peer ids, offer ids and nonces from, its `charSet`. */ -inline constexpr std::string_view id_alphabet = - "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"; - -/** The length of a Trystero peer id, its `selfId`. */ -inline constexpr std::size_t peer_id_size = 20; -/** The length of the id of a Trystero offer, which its answer and candidates name. */ -inline constexpr std::size_t offer_id_size = 12; -/** The length of the nonce that makes repeated announcements distinct Nostr events. */ -inline constexpr std::size_t nonce_size = 8; - -/** - * An id of one character of `id_alphabet` for each random byte, Trystero's `genId`. - * - * Each byte picks the character at its remainder in 62, as Trystero picks one character of its - * `charSet` for each draw, so an id of `n` characters takes `n` random bytes. - * - * Tip: 256 is not a multiple of 62, so each of the first eight characters comes from 5 of the 256 - * bytes and each other from 4, where Trystero draws each of the 62 alike: a character carries - * about 5.95 bits of its byte's 8, a little less than log2(62). - * - * @param random The random bytes, one for each character. - * @param memory The resource the id is allocated in. - * @return The id, as long as `random`. - */ -inline std::pmr::string random_id( - std::span random, - std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - std::pmr::string out(random.size(), '0', memory); - std::ranges::transform(random, out.begin(), - [](std::uint8_t b) { return id_alphabet[b % id_alphabet.size()]; }); - return out; -} - /** * The SHA-256 of the concatenation of `parts`, fed to the hash one part at a time. * * Tip: every digest the protocol takes is of a few ids joined by separators; hashing the parts in * place builds none. * + * Tip: SHA-256 over webcpp::hash's backends cannot fail: the hasher starts, takes pieces of any + * size and finishes into 32 bytes. That is this function's precondition; were it broken, a debug + * build asserts and a release build returns zeros. + * * @param parts The texts, in order. * @return The digest. */ inline std::array sha256_of(std::initializer_list parts) { - boost::hash2::sha2_256 h; + std::array out{}; + // SHA-256 over webcpp::hash's default backend has no failure to report; if one came, `out` + // stays zeroed and the assertion says so in a debug build. + auto hashing = webcpp::hash::hasher::make(); + BOOST_ASSERT(hashing.has_value()); + if (!hashing) { + return out; + } for (const auto part : parts) { - h.update(part.data(), part.size()); + const auto fed = hashing->update( + std::span(reinterpret_cast(part.data()), part.size())); + BOOST_ASSERT(fed.has_value()); + if (!fed) { + return out; + } + } + const auto done = hashing->finish(out); + BOOST_ASSERT(done.has_value()); + if (!done) { + out.fill(0); } - const auto digest = h.result(); - std::array out{}; - std::ranges::copy(digest, out.begin()); return out; } @@ -90,54 +74,87 @@ inline std::array sha256(std::string_view text) { return sha256_of({text}); } +/** Trystero's library name, `libName`, the first part of every topic's path. */ +inline constexpr std::string_view lib_name = "Trystero"; +/** Trystero's library id, `libId`, the first part of every domain tag. */ +inline constexpr std::string_view lib_id = "trystero"; + /** - * Trystero's `sha1` of the concatenation of `parts`, the name of a topic. + * Trystero's `domainTag`: the text that separates one use of a key or a hash from another. * - * It is the SHA-1 digest with every byte written in base 36 without padding, concatenated. - * - * Tip: the text is not fixed width; it is a topic name and is only ever compared, never decoded. + * @param name The use's name. + * @param version The use's version. + * @param memory The resource the tag is allocated in. + * @return "trystero::v". + */ +inline std::pmr::string domain_tag( + std::string_view name, unsigned version, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + std::pmr::string out(memory); + out += lib_id; + out += ':'; + out += name; + out += ":v"; + // Written in `memory`: no std::string, which MSVC's debug library gives a proxy from the + // global heap even for a text this short. + json::append_integer(out, version); + return out; +} + +/** + * Trystero's `topicPath`: the JSON array of the parts, `["a","b"]`, which no choice of parts can + * make equal to another's. * - * @param parts The texts, in order. - * @param memory The resource the name is allocated in. - * @return The name. + * @param parts The texts, in UTF-8. + * @param memory The resource the path is allocated in. + * @return The path. */ -inline std::pmr::string sha1_topic_of( +inline std::pmr::string topic_path( std::initializer_list parts, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - boost::hash2::sha1_160 h; - for (const auto part : parts) { - h.update(part.data(), part.size()); - } std::pmr::string out(memory); - out.reserve(40); - for (std::uint8_t b : h.result()) { - std::array digits{}; - std::size_t n = 0; - do { - digits[n++] = "0123456789abcdefghijklmnopqrstuvwxyz"[b % 36]; - b /= 36; - } while (b != 0); - while (n != 0) { - out += digits[--n]; + out += '['; + bool first = true; + for (const auto part : parts) { + if (!first) { + out += ','; } + first = false; + json::append_string_total(out, part); } + out += ']'; return out; } /** - * Trystero's `sha1` of a text, the name of a topic. + * Trystero's `hashTopic`: the base64url of the SHA-256 of a text's UTF-8 bytes. * - * @param text The text. - * @param memory The resource the name is allocated in. - * @return The name, as @ref sha1_topic_of writes it. + * @param text The text, in UTF-8. + * @param memory The resource the topic is allocated in. + * @return The topic's name, 43 characters. */ -inline std::pmr::string sha1_topic( +inline std::pmr::string hash_topic( std::string_view text, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - return sha1_topic_of({text}, memory); + return to_base64url(sha256(text), memory); } /** - * The topic every member of a room announces on, Trystero's `sha1` of "Trystero\@\@". + * The text whose hash is the topic every member of a room announces on: the path of the library's + * name, the app's id and the room's id. + * + * @param app_id The application's id. + * @param room_id The room's id. + * @param memory The resource the text is allocated in. + * @return The path. + */ +inline std::pmr::string root_topic_text( + std::string_view app_id, std::string_view room_id, + std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { + return topic_path({lib_name, app_id, room_id}, memory); +} + +/** + * The topic every member of a room announces on, the hash of @ref root_topic_text. * * @param app_id The application's id. * @param room_id The room's id. @@ -147,12 +164,12 @@ inline std::pmr::string sha1_topic( inline std::pmr::string root_topic( std::string_view app_id, std::string_view room_id, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - return sha1_topic_of({"Trystero@", app_id, "@", room_id}, memory); + return hash_topic(root_topic_text(app_id, room_id, memory), memory); } /** - * The topic a peer receives its offers, answers and candidates on, Trystero's `sha1` of the root - * topic's text, "\@" and the peer's id. + * The topic a peer receives its offers, answers and candidates on: the hash of the path of the + * root topic's text and the peer's id. * * @param app_id The application's id. * @param room_id The room's id. @@ -163,36 +180,40 @@ inline std::pmr::string root_topic( inline std::pmr::string peer_topic( std::string_view app_id, std::string_view room_id, std::string_view peer_id, std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - return sha1_topic_of({"Trystero@", app_id, "@", room_id, "@", peer_id}, memory); + return hash_topic(topic_path({root_topic_text(app_id, room_id, memory), peer_id}, memory), + memory); } /** - * The token that names a room inside a data channel's envelope: the hexadecimal SHA-256 of - * "Trystero::". + * Trystero's `hash32`: FNV-1a over the UTF-8 bytes, then MurmurHash3's final mix. * - * @param app_id The application's id. - * @param room_id The room's id. - * @param memory The resource the token is allocated in. - * @return The token, 64 hexadecimal digits. + * @param utf8 The text, in UTF-8. + * @return The 32-bit hash. */ -inline std::pmr::string room_token( - std::string_view app_id, std::string_view room_id, - std::pmr::memory_resource* memory = std::pmr::get_default_resource()) { - return to_hex(sha256_of({"Trystero:", app_id, ":", room_id}), memory); +inline std::uint32_t hash32(std::string_view utf8) { + std::uint32_t h = 0x811c9dc5U; + for (const char c : utf8) { + h = (h ^ static_cast(c)) * 0x01000193U; + } + h ^= h >> 16U; + h *= 0x85ebca6bU; + h ^= h >> 13U; + h *= 0xc2b2ae35U; + h ^= h >> 16U; + return h; } /** - * Trystero's `strToNum`: the sum of the text's UTF-16 code units, modulo `limit`. - * - * Tip: it computes in doubles, JavaScript's Numbers, as `strToNum` does, so that every peer derives - * the same kinds and relays; the oracle's fixtures pin it. + * Trystero's `strToNum`: @ref hash32 of the text, modulo `limit`. * - * @param text The text, in UTF-8. + * @param utf8 The text, in UTF-8. + * @pre `limit != 0`. * @param limit The modulus; the default is JavaScript's `Number.MAX_SAFE_INTEGER`. * @return The number, in [0, `limit`). */ -inline double str_to_num(std::string_view text, double limit = 9007199254740991.0) { - return std::fmod(utf16_code_unit_sum(text), limit); +inline std::uint64_t str_to_num(std::string_view utf8, std::uint64_t limit = 9007199254740991ULL) { + BOOST_ASSERT(limit != 0); + return hash32(utf8) % limit; } } // namespace webcpp::trystero::protocol diff --git a/include/webcpp/trystero/room.hpp b/include/webcpp/trystero/room.hpp index c83c85f..15621e1 100644 --- a/include/webcpp/trystero/room.hpp +++ b/include/webcpp/trystero/room.hpp @@ -12,22 +12,29 @@ #include #include #include -#include +#include #include +#include #include #include +#include #include -#include -#include #include +#include #include #include +#include #include -#include +#include +#include #include #include +#include #include +#include #include +#include +#include #include // lint-world: posts handlers only #include // lint-world: posts handlers only @@ -44,13 +51,21 @@ #include +#include #include #include +#include +#include #include +#include +#include +#include +#include #include #include #include #include +#include #include #include #include @@ -65,7 +80,7 @@ class app; /** * A peer's id in a room, Trystero's `selfId` and the ids `getPeers` lists: 20 characters of - * `protocol::id_alphabet` unless the configuration names one. + * `protocol::base62_alphabet` unless the configuration names one. * * A room hands its ids out in its own resource. */ @@ -83,9 +98,9 @@ using bytes = std::vector; * Binary data in a memory resource, an action's binary payload in the room's resource. * * A message received as `pmr_bytes` uses the room's effective `room_options::memory`, which - * must outlive the value. A received buffer in the same resource is moved into the value; - * a buffer in the app's distinct resource is copied once into the room's. An inline payload - * is taken out of its frame before being moved or copied. + * must outlive the value. A room receives its frames, and assembles its transfers, in that + * resource, so the payload is moved into the value: an inline payload is taken out of its frame + * first. * * @see "Allocation", in the guide. */ @@ -114,6 +129,129 @@ struct message_info { std::pmr::string metadata; }; +/** + * A peer that joined or left a room, what `room::on_peer_join` and `room::on_peer_leave` report, + * Trystero's `PeerJoinContext` and `PeerLeaveContext` without their roles. + * + * The views are valid for the duration of the listener's call. + */ +struct peer_event { + /** The peer's id. */ + std::string_view peer_id; + /** The id of the peer's user, the one its identity handshake verified. */ + std::string_view user_id; +}; + +/** + * A user that joined or left a room, what `room::on_user_join` and `room::on_user_leave` report, + * Trystero's `UserJoinContext` and `UserLeaveContext` without their roles. + * + * The views are valid for the duration of the listener's call. + */ +struct user_event { + /** The user's id. */ + std::string_view user_id; + /** The peer whose join or departure made the user join or leave: its first or its last. */ + std::string_view peer_id; +}; + +/** + * A user of a room, an entry of `room::users`, Trystero's `UserInfo`. + */ +struct user_info { + /** The user's active peers, in the order they became active. */ + std::pmr::vector peer_ids; + /** The user's roles; none until roles are ported. */ + std::pmr::vector roles; +}; + +/** + * An active peer of a room, an entry of `room::peers`, Trystero's `PeerInfo` without its + * `connection`: the peer connection is the backend's, which a room does not hand out. + */ +struct peer_info { + /** The id of the peer's user. */ + std::pmr::string user_id; + /** Whether the room reaches the peer over a connection of its own; always, until relayed + * peers are ported. */ + bool direct = true; + /** How many connections away the peer is: 1 for a direct one. */ + std::uint32_t hops = 1; + /** The peer's roles; none until roles are ported. */ + std::pmr::vector roles; +}; + +/** + * This peer in a room, what `room::self` reports, Trystero's `SelfInfo`. + * + * The views are valid as long as the room. + */ +struct self_info { + /** This peer's id, the app's. */ + std::string_view peer_id; + /** This peer's user's id, the app's user identity's (`app::user_id`). */ + std::string_view user_id; + /** Where the user identity comes from: the app's configuration, or made with the app. */ + identity_persistence persistence = identity_persistence::ephemeral; + /** The id of the room as it runs now. */ + std::string_view room_id; + /** The id the room was joined as; the same as `room_id` until rooms that scale are ported. */ + std::string_view base_room_id; + /** Whether this peer administers the room; never, until roles are ported. */ + bool is_admin = false; + /** This peer's roles; none until roles are ported. */ + std::span roles; +}; + +/** + * What an action's receive gate is asked about, Trystero's `ActionReceiveContext` without its + * roles, its signal and its kind: a message, before it is received. + * + * The views are valid for the duration of the gate's call. + */ +struct receive_info { + /** The sender's id. */ + std::string_view peer_id; + /** The id of the sender's user. */ + std::string_view user_id; + /** The size of the message's payload, in bytes. */ + std::size_t byte_length = 0; + /** The metadata the sender passed, as JSON text, or empty when it passed none. */ + std::string_view metadata; +}; + +/** + * Whose message an action's progress concerns, Trystero's `ActionProgressContext`. + * + * The views are valid for the duration of the listener's call. + */ +struct progress_info { + /** The sender's id. */ + std::string_view peer_id; + /** The id of the sender's user. */ + std::string_view user_id; + /** The metadata the sender passed, as JSON text, or empty when it passed none. */ + std::string_view metadata; +}; + +/** + * Where a request goes, what it carries beside its payload and how long it waits, Trystero's + * `RequestOptions` without `onProgress` and `signal`. + * + * Tip: it owns its strings because a completion token such as `asio::deferred` starts the + * operation later, after the caller's views may be gone. + */ +struct request_options { + /** The peer asked, which must be active, or a user, whose active peer of the lowest id is + * asked, as 0.27.0 picks one. */ + peer_id target = {}; + /** The metadata, as JSON text, or empty for none. */ + std::pmr::string metadata = {}; + /** How long the request waits for its answer, Trystero's `timeoutMs`; none waits as long as + * the peer stays. */ + std::optional timeout = std::nullopt; +}; + /** * Where an action's message goes and what it carries beside its payload, the target and the * metadata of Trystero's `send`. @@ -122,7 +260,8 @@ struct message_info { * operation later, after the caller's views may be gone. */ struct send_options { - /** The peers to send to; empty means every active peer. */ + /** Where to send: each an active peer's id, or a user's, which stands for each of its active + * peers (a peer reached twice is sent to once); empty means every active peer. */ std::pmr::vector targets = {}; /** The metadata, as JSON text, or empty for none. */ std::pmr::string metadata = {}; @@ -386,14 +525,14 @@ struct payload_traits { } /** - * The message's payload as this type: the message's buffer, moved when the payload starts it, - * in the room's resource; nothing for another format. + * The message's payload as this type: the message's buffer, moved when the payload starts it + * and no other listener reads the message, in the room's resource; nothing for another format. */ static std::optional decode(incoming& m, const decoding& to) { if (m.format != protocol::payload_format::binary) { return std::nullopt; } - if (m.buffer.get_allocator().resource() != to.memory) { + if (m.shared || m.buffer.get_allocator().resource() != to.memory) { const auto payload = m.payload(); return pmr_bytes(payload.begin(), payload.end(), to.memory); } @@ -488,6 +627,220 @@ T empty_payload(std::pmr::memory_resource* memory) noexcept { } } +/** + * What a request's metadata holds, `{"r":,"m":}` as 0.27.0's request actions write + * it: the request's id, and the sender's own metadata, as JSON text, or empty when it passed none. + */ +struct request_envelope { + /** The request's id, which its answer names. */ + std::pmr::string id; + /** The sender's metadata, as JSON text, or empty. */ + std::pmr::string metadata; +}; + +/** + * What an answer's metadata holds, `{"r":}` or `{"r":,"e":}`: the id of the + * request it answers, and the reason of a refusal. + */ +struct response_envelope { + /** The id of the request answered. */ + std::pmr::string id; + /** Whether the answer refuses the request. */ + bool refused = false; + /** The reason of a refusal, or empty. */ + std::pmr::string reason; +}; + +/** The object a request's or an answer's metadata holds, within a JSON payload's limits; a text + * that is no object, or does not parse, holds nothing. */ +inline std::optional envelope_of(std::string_view metadata, + const decoding& to) { + if (metadata.empty()) { + return std::nullopt; + } + auto v = webcpp::document::parse(metadata, json_payload_limits(metadata, to), + std::pmr::polymorphic_allocator(to.memory)); + if (!v.has_value() || !v->root().is_object() || !v->root()["r"].is_string()) { + return std::nullopt; + } + return std::move(v).unsafe_value(); +} + +/** A request's metadata read, as 0.27.0's `getRequestMetadata` reads it; nothing when it names no + * request. */ +inline std::optional read_request(std::string_view metadata, const decoding& to) { + const auto v = envelope_of(metadata, to); + if (!v) { + return std::nullopt; + } + request_envelope out{ + .id = std::pmr::string(protocol::json::text_of(v->root()["r"]), to.memory), + .metadata = std::pmr::string(to.memory), + }; + protocol::json::append_value(out.metadata, v->root()["m"]); // `undefined` writes nothing + return out; +} + +/** The value of a hexadecimal digit, either case, or nothing for another character. */ +inline std::optional hex_digit_value(char c) { + if (c >= '0' && c <= '9') { + return static_cast(c - '0'); + } + if (c >= 'a' && c <= 'f') { + return static_cast(c - 'a' + 10); + } + if (c >= 'A' && c <= 'F') { + return static_cast(c - 'A' + 10); + } + return std::nullopt; +} + +/** The UTF-16 code unit of the `\\uXXXX` escape at `at` of a JSON text, or nothing when none + * starts there. */ +inline std::optional unicode_escape_at(std::string_view json, std::size_t at) { + if (at + 6 > json.size() || json[at] != '\\' || json[at + 1] != 'u') { + return std::nullopt; + } + std::uint32_t unit = 0; + for (std::size_t i = at + 2; i < at + 6; ++i) { + const auto digit = hex_digit_value(json[i]); + if (!digit) { + return std::nullopt; + } + unit = (unit << 4U) | *digit; + } + return unit; +} + +/** + * A JSON text with each lone surrogate escape, `\\ud83d` without its low half, written as the + * replacement character's, `\\ufffd`, which webcpp::document's parser can read: it refuses a lone + * surrogate, which JavaScript's `JSON.parse` reads. + * + * Tip: outside a string JSON holds no backslash, so every backslash met starts an escape. + */ +inline std::pmr::string without_lone_surrogates(std::string_view json, + std::pmr::memory_resource* memory) { + const auto high = [](std::uint32_t u) { return u >= 0xD800U && u <= 0xDBFFU; }; + const auto low = [](std::uint32_t u) { return u >= 0xDC00U && u <= 0xDFFFU; }; + std::pmr::string out(memory); + out.reserve(json.size()); + for (std::size_t i = 0; i < json.size();) { + if (json[i] != '\\') { + out += json[i++]; + continue; + } + const auto unit = unicode_escape_at(json, i); + if (!unit) { + out.append(json.substr(i, std::min(2, json.size() - i))); // \n, \", ... + i += 2; + continue; + } + if (const auto next = unicode_escape_at(json, i + 6); high(*unit) && next && low(*next)) { + out.append(json.substr(i, 12)); // a pair + i += 12; + } else if (high(*unit) || low(*unit)) { + out += "\\ufffd"; + i += 6; + } else { + out.append(json.substr(i, 6)); + i += 6; + } + } + return out; +} + +/** An answer's metadata read, as 0.27.0's `getResponseMetadata` reads it: only a text `e` + * refuses; nothing when it names no request. A reason that ends in a lone surrogate, as 0.27.0's + * cut at 512 UTF-16 code units may leave it, is read with the replacement character in its place. + */ +inline std::optional read_response(std::string_view metadata, + const decoding& to) { + auto v = envelope_of(metadata, to); + if (!v && metadata.find("\\u") != std::string_view::npos) { + v = envelope_of(without_lone_surrogates(metadata, to.memory), to); + } + if (!v) { + return std::nullopt; + } + const auto e = v->root()["e"]; + return response_envelope{ + .id = std::pmr::string(protocol::json::text_of(v->root()["r"]), to.memory), + .refused = e.is_string(), + .reason = std::pmr::string(e.is_string() ? protocol::json::text_of(e) : std::string_view{}, + to.memory), + }; +} + +/** The payload of the ready frame by which a full room refuses a peer, 0.27.0's + * `{ok: false, err: roomFullMsg}`. */ +inline constexpr std::string_view room_full_ready = R"({"ok":false,"err":"room full"})"; + +/** The longest reason of a ban a room reports, in UTF-16 code units, 0.27.0's `<= 512`. */ +inline constexpr std::size_t max_ban_reason_units = 512; + +/** A refusal a peer's ready frame carries, 0.27.0's `{ok: false, err}`. */ +struct ready_refusal { + /** Why the peer refuses this side. */ + enum class kind { + /** Its room is full, 0.27.0's `roomFullMsg`. */ + room_full, + /** It bans this side, 0.27.0's `peerBannedMsg`. */ + banned, + }; + + /** Why. */ + kind why = kind::room_full; + /** A ban's reason, when the peer gave a text of at most @ref max_ban_reason_units UTF-16 code + * units. */ + std::optional reason; +}; + +/** + * The refusal a ready frame's payload carries, as 0.27.0's room reads `data.ok === false` and + * `data.err`: a JSON object whose `ok` is false and whose `err` is "room full" or "peer banned"; + * nothing for any other payload, which is a plain ready frame. A ban's `reason` is kept when it is + * a text of at most 512 UTF-16 code units, one that ends in a lone surrogate read with the + * replacement character in its place, as a response's reason is. + */ +inline std::optional read_refusal(protocol::payload_format format, + std::string_view payload, const decoding& to) { + if (format != protocol::payload_format::json) { + return std::nullopt; + } + const std::pmr::polymorphic_allocator memory(to.memory); + auto v = webcpp::document::parse(payload, json_payload_limits(payload, to), memory); + if (!v.has_value() && payload.find("\\u") != std::string_view::npos) { + const auto readable = without_lone_surrogates(payload, to.memory); + v = webcpp::document::parse(readable, json_payload_limits(readable, to), memory); + } + if (!v.has_value() || !v->root().is_object()) { + return std::nullopt; + } + const auto ok = v->root()["ok"]; + const auto err = v->root()["err"]; + if (!ok.is_boolean() || ok.value_or(true) || !err.is_string()) { + return std::nullopt; + } + const auto why = protocol::json::text_of(err); + if (why == "room full") { + return ready_refusal{.why = ready_refusal::kind::room_full, .reason = std::nullopt}; + } + if (why != "peer banned") { + return std::nullopt; + } + ready_refusal out{.why = ready_refusal::kind::banned, .reason = std::nullopt}; + if (const auto reason = v->root()["reason"]; reason.is_string()) { + const auto text = protocol::json::text_of(reason); + std::size_t units = 0; + protocol::for_each_utf16_code_unit(text, [&units](std::uint32_t) { ++units; }); + if (units <= max_ban_reason_units) { + out.reason.emplace(text, to.memory); + } + } + return out; +} + /** * A user's completion handler, type-erased, and whether its associated executor is the room's, * which only its concrete type tells cheaply: a type-erased executor is compared through objects @@ -516,24 +869,50 @@ struct completion { } }; +/** A ping waiting for its answer: when it was sent, and what it completes. */ +struct pending_ping { + /** When the request was sent. */ + detail::time_point started{}; + /** The user's completion, with the round trip. */ + completion handler; +}; + +/** What a request completes: a request action's handler, with the answer, or a ping, with the + * round trip. */ +using request_completion = + std::variant, pending_ping>; + /** - * Everything a joined room is: the strategy, the negotiations, the peers bound to the app's - * connections and their handshakes, the action wire and the actions the application made. `room` - * and `action` are handles to it. Every allocation goes through its resource; what it shares with - * the app's other rooms (the configuration, the self id, the connections) is the app's. + * Everything a joined room is: the strategy, the negotiations, its connection to each peer and + * their handshakes, the action wire and the actions the application made. `room` and `action` are + * handles to it. Every allocation goes through its resource, its connections' included, since no + * connection outlives its room, as in 0.27.0, whose rooms make their own offers and answers + * (`strategy.ts`, `signal-handler.ts`); what it shares with the app's other rooms (the + * configuration, the self id, the relays, the rooms' keys) is the app's. * * | Internal action | Meaning | - * | \@_hsdata | a handshake message: the password challenge and its response | - * | \@_hsready | the sender's side of the handshake passed | - * | \@_ping, \@_pong | round-trip measurement | + * | \@_hsdata | a step of the identity handshake, a JSON text of at most 64 KiB | + * | \@_hsready | the sender's side of the handshake passed, at most 128 KiB: an | + * | | empty text; or a full room refuses the receiver, | + * | | `{"ok":false,"err":"room full"}`; or the sender bans it, | + * | | `{"ok":false,"err":"peer banned"[,"reason":]}`, which | + * | | only a Trystero peer with `roles()` sends | + * | \@_ping | a request of an empty text, answered with an empty text: a round | + * | | trip | * | \@_leave | the sender leaves the room | + * | \@_response | the answer to a request, `{"r":}` or `{"r":,"e":}` | + * | | in its metadata, as 0.27.0's request actions answer; an offer of | + * | | one that answers no request of the receiver's is rejected with | + * | | "unexpected response" | */ class room_impl final : public std::enable_shared_from_this, public room_endpoint { public: /** The executor every handler and completion of the room runs on. */ using executor_type = webcpp::asio::any_io_executor; - /** What an action's `on_message` becomes: a handler of each received message. */ + /** What an action's `on_message` becomes: a listener of each received message. */ using message_handler = handler; + /** What a request action's `on_request` becomes: the listener that answers each request. */ + using request_handler = handler; /** A room of `app`, with its own options copied into `memory`. */ room_impl(std::shared_ptr app, room_options options, std::string_view room_id, @@ -544,18 +923,27 @@ class room_impl final : public std::enable_shared_from_this, public r factory_(app_->factory()), log_(app_->log()), options_{ - .handshake_timeout = options.handshake_timeout, .max_receive_bytes = options.max_receive_bytes, .max_json_document_bytes = options.max_json_document_bytes, + .max_users = options.max_users, .memory = memory_, }, room_id_(room_id, memory_), - token_(protocol::room_token(app_->app_id(), room_id_, memory_)), root_topic_(protocol::root_topic(app_->app_id(), room_id_, memory_)), self_topic_(protocol::peer_topic(app_->app_id(), room_id_, app_->self_id(), memory_)), peers_(memory_), - rebinds_(memory_), + users_(memory_), + reserved_(memory_), + refused_order_(memory_), + refused_(memory_), + flushing_(memory_), actions_(memory_), + requests_(memory_), + peer_join_(allocator()), + peer_leave_(allocator()), + user_join_(allocator()), + user_leave_(allocator()), + errors_(allocator()), leave_completions_(memory_) {} /** Room state represents one membership and cannot be copied. */ @@ -578,19 +966,99 @@ class room_impl final : public std::enable_shared_from_this, public r /** * Leaves the app's registry and lets go quietly: it may run while the io_context is destroyed, - * so it ends no connection, idles none, calls nothing back and releases no user of the app. - * Its peers' bindings leave their connections as they go. + * so it ends no connection, calls nothing back and releases no user of the app. Its peers' + * connections go with it. */ - ~room_impl() { app_->unregister_room(token_, this); } + ~room_impl() { app_->unregister_room(room_id_, this); } - /** Joins: makes the sealer, the action wire, the signaling and the strategy, registers the - * room with its app, and starts the strategy. */ + /** Joins: makes the action wire, the signaling and the strategy, registers the room with its + * app, and asks for the room's keys, the strategy starting once they exist. */ void start() { const auto weak = weak_from_this(); - sealer_ = factory_.make_sealer( - protocol::seal_key(app_->password(), app_->app_id(), room_id_), memory_); + make_handshakes(weak); + make_wire(weak); + make_signaling(weak); + make_strategy(weak); + // A room joined while the app's relays are offline opens none until they are online. + if (app_->relays_offline()) { + strategy_->hold(); + } + register_with_app(); + } + + /** + * Makes the handshake manager, whose callbacks reach the room while it lives: 0.27.0's + * `createHandshakeManager` as `room.ts` sets it up, its steps the identity handshake, the + * responder's ready frame deferred in a room with `max_users`, whose admissions check the + * room's users. + */ + void make_handshakes(const std::weak_ptr& weak) { + handshakes_ = std::allocate_shared( + allocator(), app_->self_id(), options_.max_users.has_value(), + handshake_callbacks{ + .run_steps = bind)>( + [weak](std::string_view peer, bool initiator, + handler done) { + if (const auto self = weak.lock()) { + self->run_identity(peer, initiator, std::move(done)); + } + }), + .send_ready = bind( + [weak](std::string_view peer, std::string_view ready_json) { + if (const auto self = weak.lock()) { + // 0.27.0's empty ready payload is a text; its other payloads, JSON. + self->send_internal("@_hsready", peer, + ready_json.empty() ? protocol::payload_format::text + : protocol::payload_format::json, + ready_json); + } + }), + .local_passed = bind([weak](std::string_view peer) { + // As 0.27.0's onLocalHandshakePassed: a full room refuses a new user. + const auto self = weak.lock(); + if (!self) { + return false; + } + if (self->full_for(peer, false)) { + self->refuse_full(peer); + return false; + } + return true; + }), + .admit = bind([weak](std::string_view peer) { + // As 0.27.0's acquireAdmissionSlot: the peer is still the room's, the room is + // not leaving, and it has a place for the peer's user. + const auto self = weak.lock(); + return self && !self->left_ && self->peers_.contains(peer) && + self->try_admit(peer); + }), + .activate = bind([weak](std::string_view peer) { + if (const auto self = weak.lock()) { + self->activate(peer); + } + }), + .failed = bind( + [weak](std::string_view peer_view, std::string_view reason_view) { + const auto self = weak.lock(); + if (!self) { + return; + } + // 0.27.0's onHandshakeError, then its onFailure: the peer is told to leave + // and goes. Copies: the kick frees the views' storage. + const std::pmr::string peer(peer_view, self->memory_); + const std::pmr::string reason(reason_view, self->memory_); + self->reserved_.erase(peer); + self->report(peer, make_error_code(error::handshake_failed), reason); + self->kick(peer, reason); + }), + }, + factory_, memory_); + } + + /** Makes the action wire, whose callbacks reach the room while it lives. */ + void make_wire(const std::weak_ptr& weak) { wire_ = std::allocate_shared( - allocator(), factory_, token_, options_.max_receive_bytes, + allocator(), factory_, options_.max_receive_bytes, action_wire::callbacks{ .find_link = bind(std::string_view, bool)>( [weak](std::string_view peer, @@ -609,9 +1077,13 @@ class room_impl final : public std::enable_shared_from_this, public r const auto self = weak.lock(); return self && self->may_receive(peer, name); }), - .has_receiver = bind([weak](std::string_view name) { + .has_action = bind([weak](std::string_view name) { const auto self = weak.lock(); - return self && (name.starts_with("@_") || self->actions_.contains(name)); + return self && self->has_action(name); + }), + .has_listener = bind([weak](std::string_view name) { + const auto self = weak.lock(); + return self && self->listens(name); }), .deliver = bind([weak](incoming&& m) { if (const auto self = weak.lock()) { @@ -621,88 +1093,184 @@ class room_impl final : public std::enable_shared_from_this, public r .fail_peer = bind( [weak](std::string_view peer, std::string_view reason) { if (const auto self = weak.lock()) { - self->kick(peer, reason); + self->fail_peer(peer, reason); + } + }), + .expects = bind( + [weak](std::string_view peer, std::string_view name, + std::string_view metadata) { + const auto self = weak.lock(); + return self && self->expects(peer, name, metadata); + }), + .admit = bind( + [weak](std::string_view peer, std::string_view name, std::size_t size, + std::string_view metadata) { + const auto self = weak.lock(); + return self ? self->admit(peer, name, size, metadata) : admission::open; + }), + .rejected = bind( + [weak](std::string_view peer, std::string_view name, std::string_view metadata, + std::string_view reason) { + if (const auto self = weak.lock()) { + self->on_rejected(peer, name, metadata, reason); } }), + .progress = + bind( + [weak](std::string_view peer, std::string_view name, + std::string_view metadata, double share) { + if (const auto self = weak.lock()) { + self->post_progress(peer, name, metadata, share); + } + }), + .max_payload = bind(&room_impl::max_payload), }, memory_); + } + + /** Makes the signaling, whose callbacks reach the room while it lives. */ + void make_signaling(const std::weak_ptr& weak) { signaling_ = std::allocate_shared( - allocator(), factory_, sealer_, app_->app_id(), room_id_, app_->self_id(), - app_->ice_servers(), + allocator(), factory_, app_->app_id(), room_id_, app_->self_id(), app_->ice_servers(), signaling::callbacks{ - .claim = bind([weak](std::string_view peer) { - const auto self = weak.lock(); - return self && self->claim(peer); - }), .publish = bind( [weak](std::size_t relay, std::string_view topic, std::string_view content) { - if (const auto self = weak.lock()) { + // A leaving room publishes nothing more: no candidate, no retried offer, + // as 0.27.0's signal handler checks isLeaving before each. + if (const auto self = weak.lock(); self && !self->left_) { self->strategy_->publish(relay, topic, content); } }), .connected = bind, - std::shared_ptr)>( + std::shared_ptr, std::string_view, + std::string_view)>( [weak](std::string_view peer, std::shared_ptr pc, - std::shared_ptr channel) { + std::shared_ptr channel, + std::string_view local_sdp, std::string_view remote_sdp) { if (const auto self = weak.lock()) { - self->on_connected(peer, std::move(pc), std::move(channel)); - } - }), - .failed = bind( - [weak](std::string_view peer, boost::system::error_code ec, - std::string_view what) { - if (const auto self = weak.lock()) { - std::array buffer{}; // the message without a std::string - self->report( - peer, ec, - what.empty() ? ec.message(buffer.data(), buffer.size()) : what); + self->on_connected(peer, std::move(pc), std::move(channel), local_sdp, + remote_sdp); } }), + .failed = bind([weak](const room_error& e) { + if (const auto self = weak.lock()) { + self->report(e); + } + }), + .should_connect = bind([weak](std::string_view peer) { + const auto self = weak.lock(); + return self && self->can_connect(peer); + }), }, - log_, memory_, app_->memory()); + log_, memory_); + } + + /** Makes the strategy on the app's relays and the room's topics, whose callbacks reach the + * room while it lives. */ + void make_strategy(const std::weak_ptr& weak) { + // The self topic before the root topic, as Trystero's rooms subscribe them, so that the + // REQ lists them, and their kinds, in 0.27.0's order. std::pmr::vector topics(memory_); - topics.push_back(root_topic_); topics.push_back(self_topic_); + topics.push_back(root_topic_); strategy_ = std::allocate_shared( allocator(), factory_, app_->relay_urls(), std::move(topics), root_topic_, - bind([weak, memory = memory_] { - const auto self = weak.lock(); - return self ? protocol::write_signal( - {.peer_id = self->app_->self_id()}, - detail::random_id(self->factory_, protocol::nonce_size, memory), - memory) - : std::pmr::string(memory); - }), + bind( + [weak, memory = memory_](std::string_view nonce) { + const auto self = weak.lock(); + return self ? protocol::write_signal({.peer_id = self->app_->self_id()}, nonce, + memory) + : std::pmr::string(memory); + }), bind( [weak](std::size_t relay, std::string_view, std::string_view content) { - if (const auto self = weak.lock()) { + // A room in its farewell negotiates nothing more, as 0.27.0's signal handler + // drops every signal once its room is leaving (signal-handler.ts's isLeaving). + if (const auto self = weak.lock(); self && !self->left_) { self->signaling_->handle(relay, content); } }), - log_, memory_); - register_and_advertise(); + log_, memory_, bind([weak](std::string_view cause) { + if (const auto self = weak.lock()) { + const auto code = make_error_code(error::relay_failed); + std::array buffer{}; // the message without a std::string + // As 0.27.0's toErrorMessage(cause, 'all signaling relays failed'). + self->report( + {}, code, + cause.empty() ? code.message(buffer.data(), buffer.size()) : cause); + } + })); } - /** Registers the membership, starts discovery, and advertises it on live connections. */ - void register_and_advertise() { + /** Registers the membership with the app and asks for the keys that start discovery; or, when + * the app has no identity, fails the setup. */ + void register_with_app() { // By a weak reference: the room leaves the registry before it ends, its destructor // included. - app_->register_room(room_id_, token_, - std::static_pointer_cast(shared_from_this())); + app_->register_room(room_id_, std::static_pointer_cast(shared_from_this())); app_->add_user(); // The registry reserves this room before the sink can reenter app::join. log_("room", "joining room ", room_id_, " of app ", app_->app_id(), " as ", app_->self_id(), " over ", app_->relay_urls().size(), " relays"); - strategy_->start(); - // As Trystero joins a room: bound over every live connection whose remote advertised it, - // then announced on every live connection, so that each remote binds in turn. - const auto connections = app_->live_connections(); - for (const auto& c : connections) { - try_bind(c->peer(), bind_event::joined); + if (const auto failure = app_->identity_failure(); !failure.empty()) { + fail_setup(failure); + return; + } + request_keys(); + } + + /** + * Fails the room's setup, as 0.27.0's `failSetup` fails it when its identities cannot be + * resolved: once the join has returned, reports `error::identity_failed` with `message`, then + * leaves. The strategy never starts: nothing reaches a relay. + * + * @param message The report's message, the app's @ref app_impl::identity_failure. + */ + void fail_setup(std::string_view message) { + report({}, make_error_code(error::identity_failed), message); + // Posted after the report, so that it runs after it: a room left first reports nothing. + post([weak = weak_from_this()] { + if (const auto self = weak.lock()) { + self->begin_leave(); + } + }); + } + + /** + * Asks the app for the room's keys, which complete after the join returns: a room with a + * password derives them off its thread. The strategy starts once they exist, so that nothing + * is announced before the room can seal, as 0.27.0's room waits for `genKey`. + */ + void request_keys() { + app_->room_keys().get(room_id_, + bind( + [weak = weak_from_this()](boost::system::error_code ec, + const protocol::room_keys& keys) { + if (const auto self = weak.lock()) { + self->on_keys(ec, keys); + } + })); + } + + /** + * Starts the strategy under the room's keys; a room left meanwhile starts nothing. A failed + * derivation is reported as `error::backend_failure`, 0.27.0 having no room error for it + * (design D6), and the room announces nothing: a rejoin derives again. + */ + void on_keys(boost::system::error_code ec, const protocol::room_keys& keys) { + if (left_) { + return; } - for (const auto& c : connections) { - c->send_presence(token_, true); + if (ec) { + report({}, make_error_code(error::backend_failure), + "the room's keys could not be derived from its password, so it announces " + "nothing; join it again to retry"); + return; } + signaling_->set_key(keys.aes); + strategy_->start(); } /** The room's executor. */ @@ -725,104 +1293,412 @@ class room_impl final : public std::enable_shared_from_this, public r /** The relays the room uses, the app's. */ std::span relay_urls() const { return app_->relay_urls(); } - /** The ids of the peers whose handshake completed, in the room's resource. */ - std::pmr::vector active_peers() const { - std::pmr::vector out(memory_); + /** This peer's user's id, the app's user identity's. */ + std::string_view self_user_id() const { return app_->user_id(); } + + /** The id of a peer's user, the one its handshake verified, as 0.27.0 sets a peer's `userId` + * once verified; the peer's own id for a peer not verified. */ + std::string_view user_of(std::string_view peer) const { + const auto it = peers_.find(peer); + return it != peers_.end() && it->second.identity + ? std::string_view(it->second.identity->user_id) + : peer; + } + + /** The room's users but this peer's own, each with its active peers, in the room's resource: + * 0.27.0's `getUsers` leaves its own user out. */ + std::pmr::map> users() const { + std::pmr::map> out(memory_); + for (const auto& [user, peer_ids] : users_.users()) { + if (user == self_user_id()) { + continue; + } + out.try_emplace(std::pmr::string(user, memory_), + user_info{ + .peer_ids = std::pmr::vector(peer_ids, memory_), + .roles = std::pmr::vector(memory_), + }); + } + return out; + } + + /** The peers whose handshake completed, each with its user, in the room's resource. */ + std::pmr::map> peers() const { + std::pmr::map> out(memory_); for (const auto& [id, p] : peers_) { if (p.active) { - out.push_back(id); + out.try_emplace(std::pmr::string(id, memory_), + peer_info{ + .user_id = std::pmr::string(user_of(id), memory_), + .direct = true, + .hops = 1, + .roles = std::pmr::vector(memory_), + }); } } return out; } - /** Sets the handler of each peer that becomes active. */ - void on_peer_join(handler f) { on_join_ = keep_handler(std::move(f)); } + /** This peer in the room. */ + self_info self() const { + return { + .peer_id = app_->self_id(), + .user_id = self_user_id(), + .persistence = app_->persistence(), + .room_id = room_id_, + .base_room_id = room_id_, + .is_admin = false, + .roles = {}, + }; + } - /** Sets the handler of each active peer that leaves. */ - void on_peer_leave(handler f) { - on_leave_ = keep_handler(std::move(f)); + /** Adds a listener of each peer that becomes active; `replay` calls it first with each active + * peer. */ + subscription on_peer_join(handler f, listen_options options) { + // Copies: the listener's code may end the room, and free the peers' entries. + const auto ids = peers(); + std::pmr::vector current(memory_); + current.reserve(ids.size()); + for (const auto& [id, info] : ids) { + current.push_back({.peer_id = id, .user_id = info.user_id}); + } + return peer_join_.add(std::move(f), options, current); } - /** Sets the handler of each problem with a peer that the room handled itself. */ - void on_error(handler f) { - on_error_ = keep_handler(std::move(f)); + /** Adds a listener of each active peer that leaves. */ + subscription on_peer_leave(handler f, listen_options options) { + return peer_leave_.add(std::move(f), options); } - /** Binds advertised peers when allowed, or detaches a withdrawn token. */ - void presence_changed(std::string_view peer, bool present) override { - if (present) { - const auto it = rebinds_.find(peer); - if (it != rebinds_.end() && it->second.dropping) { - it->second.dropping = false; - try_bind(peer, bind_event::reuse); - return; - } - try_bind(peer, bind_event::presence); - } else if (peers_.contains(peer)) { - remove_peer(peer, "peer left the room", end_kind::withdrawn); + /** Adds a listener of each user whose first peer becomes active; `replay` calls it first with + * each user joined, and its first peer. This peer's own user is no other user. */ + subscription on_user_join(handler f, listen_options options) { + // Copies: the listener's code may end the room, and free the users' entries. + const auto joined = users(); + std::pmr::vector current(memory_); + current.reserve(joined.size()); + for (const auto& [user, info] : joined) { + current.push_back({.user_id = user, .peer_id = info.peer_ids.front()}); } + return user_join_.add(std::move(f), options, current); } - /** Whether this peer's unbound frames survive the higher id's dropping window. */ - [[nodiscard]] bool keeps_frames_from(std::string_view peer) const override { - const auto it = rebinds_.find(peer); - return it == rebinds_.end() || !it->second.dropping; + /** Adds a listener of each user whose last active peer leaves. */ + subscription on_user_leave(handler f, listen_options options) { + return user_leave_.add(std::move(f), options); } - /** Tries to bind a peer after its frame for this room was kept, which advertised the room. */ - void frame_kept(std::string_view peer) override { try_bind(peer, bind_event::frame); } + /** Adds a listener of each problem the room handled itself. */ + subscription on_error(handler f, listen_options options) { + return errors_.add(std::move(f), options); + } - /** Forgets history and removes only the binding belonging to the ended connection. */ - void connection_ended(const std::shared_ptr& ended, std::string_view peer, - std::string_view reason) override { - if (const auto it = rebinds_.find(peer); - it != rebinds_.end() && it->second.on.lock() == ended) { - rebinds_.erase(it); + /** + * A negotiation of this room opened a channel to `peer`: the connection becomes the room's link + * to the peer, made in the room's resource. A room keeps one link per peer, as 0.27.0's + * `connectPeer` keeps a connected peer that is not stale: a second connection that opens while + * the peer's link is live is closed, and one whose link is ending replaces it. + * + * The DTLS fingerprints of the negotiation's descriptions are kept with the peer: its identity + * handshake binds them, as 0.27.0 reads its connection's `localDescription` and + * `remoteDescription` (design D20). + * + * Tip: the signaling calls it; the library's own tests call it with a pair of their own, as no + * signal reaches a room for a peer it is connected to. + * + * @param peer_view The peer's id. + * @param pc The connection. + * @param channel Its open data channel. + * @param local_sdp The last description the connection's `set_local_description` gave. + * @param remote_sdp The last description it applied with `set_remote_description`. + */ + // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on + void on_connected(std::string_view peer_view, std::shared_ptr pc, + std::shared_ptr channel, std::string_view local_sdp, + std::string_view remote_sdp) { + // NOLINTEND(performance-unnecessary-value-param) + const std::pmr::string peer(peer_view, memory_); + const auto link = + peer_link::make(peer, std::move(pc), std::move(channel), factory_, memory_); + if (left_) { + link->end("the room is left"); + return; } - // The peer may be bound to another connection by now: a late end of an older one is not - // its end. - if (const auto it = peers_.find(peer); - it != peers_.end() && it->second.link->is_on(ended)) { - remove_peer(peer, reason, end_kind::connection_end); + // A peer a full room refused is not taken back while it stays full, as 0.27.0's onPeer + // destroys a peer canConnectPeer refuses; that close prunes the peer's signaling state, so + // its next negotiation is weighed again. The link owns the connection, which the + // signaling's entry no longer holds: forgetting the entry closes nothing of it. + if (!can_connect(peer)) { + link->end("room full"); + signaling_->forget(peer); + return; } + if (const auto it = peers_.find(peer); it != peers_.end()) { + if (it->second.link->live()) { + log_("webrtc", "another connection with ", peer, + " closed: the room keeps its live one"); + link->end("the room keeps its live connection to the peer"); + return; + } + remove_peer(peer, "replaced by a new connection to the peer"); + // The removal's log may leave the room. + if (left_) { + link->end("the room is left"); + return; + } + } + bind_peer(peer, link, local_sdp, remote_sdp); } - /** Registers an action; frames that waited for it are delivered to it from now on. */ - void add_action(std::string_view name) { - if (!actions_.contains(name)) { - actions_.try_emplace(std::pmr::string(name, memory_), allocator()); + /** Holds the room's relays closed, or reconnects them; a room that left has none. */ + void relays_offline(bool offline) override { + if (left_) { + return; } - if (wire_) { - wire_->receiver_added(); + if (offline) { + strategy_->hold(); + } else { + strategy_->reconnect(); + } + } + + /** Registers an action, a request action when `request` says so: from now on its frames are + * kept for its listeners, where frames of an action not made are dropped, as Trystero drops + * them. The first make of a name sets its kind; whether this one asks for the same. */ + [[nodiscard]] bool add_action(std::string_view name, bool request) { + if (const auto* const slot = made(name)) { + return slot->request == request; } + slot_for(name).request = request; + return true; } - /** Sets an action's handler, and posts it every message that queued while it had none. */ - void set_action_handler(std::string_view name, message_handler handler) { + /** Adds a listener of an action's messages, posts it every message that queued for + * `async_receive` meanwhile, and delivers what the wire kept for the action. */ + subscription add_message_listener(std::string_view name, message_handler f, + listen_options options) { auto& slot = slot_for(name); - slot.handler = keep_handler(std::move(handler)); + auto out = slot.messages.add(std::move(f), options); while (!slot.queue.empty()) { - post_call(slot.handler, std::move(slot.queue.front())); + post_message(slot, std::move(slot.queue.front())); slot.queue.pop_front(); } + if (wire_) { + wire_->listener_added(); + } + return out; } - /** Completes with an action's next message: a queued one at once, else the next to arrive. */ - void receive(std::string_view name, - completion handler) { - if (left_) { - complete(std::move(handler), make_error_code(error::room_left), incoming{}); - return; - } + /** Sets the listener that answers a request action's requests, unless one is in place. */ + [[nodiscard]] boost::system::result add_request_listener(std::string_view name, + request_handler f, + listen_options options) { auto& slot = slot_for(name); - if (!slot.queue.empty()) { + if (!slot.requests.empty()) { + return error::already_subscribed; + } + auto out = slot.requests.add(std::move(f), options); + if (wire_) { + wire_->listener_added(); + } + return out; + } + + /** Sets an action's receive gate, unless one is in place. */ + [[nodiscard]] boost::system::result add_receive_gate( + std::string_view name, handler f, listen_options options) { + auto& slot = slot_for(name); + if (!slot.gate.empty()) { + return error::already_subscribed; + } + auto out = slot.gate.add(std::move(f), options); + if (wire_) { + wire_->listener_added(); + } + return out; + } + + /** Adds a listener of the progress of an action's messages. */ + subscription add_progress_listener(std::string_view name, + handler f, + listen_options options) { + return slot_for(name).progress.add(std::move(f), options); + } + + /** Completes with an action's next message: a queued one at once, else the next to arrive; + * the action listens from then on. */ + void receive(std::string_view name, + completion handler) { + if (left_) { + complete(std::move(handler), make_error_code(error::room_left), incoming{}); + return; + } + auto& slot = slot_for(name); + if (!slot.queue.empty()) { auto m = std::move(slot.queue.front()); slot.queue.pop_front(); complete(std::move(handler), boost::system::error_code{}, std::move(m)); return; } slot.receivers.push_back(std::move(handler)); + if (!std::exchange(slot.awaited, true) && wire_) { + wire_->listener_added(); + } + } + + /** + * Sends a request action's payload to one active peer, and completes with its answer: the + * message the answer is, `error::request_rejected` when it refuses, or the first failure. + */ + void request(std::string_view name, encoded_payload payload, const request_options& options, + completion handler) { + if (left_) { + complete(std::move(handler), make_error_code(error::room_left), incoming{}); + return; + } + const auto peer = request_target(options.target); + if (peer.empty()) { + complete(std::move(handler), make_error_code(error::not_connected), incoming{}); + return; + } + send_request(peer, name, std::move(payload), options.metadata, options.timeout, + std::move(handler)); + } + + /** The active peer a request to `target` goes to, a view of its id in the room: the peer of + * that id, else the user's peer of the lowest id, as 0.27.0's `resolveRequestTarget` picks + * it; empty when none is active. */ + std::string_view request_target(std::string_view target) const { + auto peer = peers_.find(target); + if (peer == peers_.end() || !peer->second.active) { + if (const auto of_user = users_.peers_of(target); !of_user.empty()) { + peer = peers_.find(*std::ranges::min_element(of_user)); + } + } + return peer != peers_.end() && peer->second.active ? std::string_view(peer->first) + : std::string_view(); + } + + /** + * Sends a request of action `name` to the active peer `peer`, as 0.27.0's request actions + * send it: its id a random UUID, `{"r":[,"m":]}` its metadata; `handler` + * completes once, with the answer or the first failure. + */ + void send_request(std::string_view peer, std::string_view name, encoded_payload payload, + std::string_view user_metadata, + std::optional timeout, + request_completion handler) { + // 0.27.0's crypto.randomUUID(), from the backend's randomness. + std::array random{}; + factory_.random(random); + const auto uuid = protocol::uuid_v4(random); + std::pmr::string id(uuid.data(), uuid.size(), memory_); + std::pmr::string metadata(R"({"r":)", memory_); + protocol::json::detail::append_utf8(metadata, id); + if (!user_metadata.empty()) { + metadata += R"(,"m":)"; + metadata += user_metadata; + } + metadata += '}'; + const auto weak = weak_from_this(); + auto& waiter = requests_ + .try_emplace(std::pmr::string(id, memory_), + request_waiter{ + .peer = std::pmr::string(peer, memory_), + .handler = std::move(handler), + .timer = nullptr, + }) + .first->second; + if (timeout) { + waiter.timer = factory_.make_timer(memory_); + waiter.timer->start(*timeout, bind([weak, id = std::pmr::string(id, memory_)] { + if (const auto self = weak.lock()) { + self->finish_request(id, make_error_code(error::request_timed_out), {}); + } + })); + } + const std::string_view target = waiter.peer; + wire_->send(name, payload.format, metadata, std::move(payload.ref), std::span(&target, 1), + false, + bind( + [weak, id = std::move(id)](boost::system::error_code ec) { + const auto self = weak.lock(); + if (ec && self) { + self->finish_request(id, ec, {}); + } + })); + } + + /** Answers a request of `peer` with a payload. */ + void respond(std::string_view peer, std::string_view id, encoded_payload payload) { + std::pmr::string metadata(R"({"r":)", memory_); + protocol::json::detail::append_utf8(metadata, id); + metadata += '}'; + send_response(peer, metadata, std::move(payload)); + } + + /** Refuses a request of `peer` with a reason and a JSON `null` payload. The reason is cut at + * 512 UTF-16 code units, as 0.27.0's `.slice(0, 512)` cuts it: a character beyond the basic + * plane counts two, and one cut in two leaves its high surrogate, which `JSON.stringify` writes + * as `\\udXXX`. */ + void respond_error(std::string_view peer, std::string_view id, std::string_view reason) { + constexpr std::size_t max_reason_units = 512; + std::size_t units = 0; + std::size_t cut = 0; + std::uint32_t high_surrogate = 0; // of a character cut in two, or 0 + while (cut < reason.size()) { + const auto lead = static_cast(reason[cut]); + std::size_t length = 1; // an ASCII byte, or one that leads no sequence + if (lead >= 0xF0U) { + length = 4; + } else if (lead >= 0xE0U) { + length = 3; + } else if (lead >= 0xC0U) { + length = 2; + } + length = std::min(length, reason.size() - cut); + const std::size_t width = length == 4 ? 2 : 1; + if (units + width > max_reason_units) { + if (width == 2 && units + 1 == max_reason_units) { + const auto byte = [&](std::size_t i) { + return static_cast( + static_cast(reason[cut + i]) & 0x3FU); + }; + const std::uint32_t code_point = + ((lead & 0x07U) << 18U) | (byte(1) << 12U) | (byte(2) << 6U) | byte(3); + high_surrogate = 0xD800U + ((code_point - 0x10000U) >> 10U); + } + break; + } + units += width; + cut += length; + } + std::pmr::string metadata(R"({"r":)", memory_); + protocol::json::detail::append_utf8(metadata, id); + metadata += R"(,"e":)"; + protocol::json::detail::append_utf8(metadata, reason.substr(0, cut)); + if (high_surrogate != 0) { + static constexpr std::string_view digits = "0123456789abcdef"; + metadata.pop_back(); // the closing quote + metadata += "\\u"; + for (const unsigned shift : {12U, 8U, 4U, 0U}) { + metadata += digits[(high_surrogate >> shift) & 15U]; + } + metadata += '"'; + } + metadata += '}'; + static constexpr std::string_view null = "null"; + send_response( + peer, metadata, + { + .format = protocol::payload_format::json, + .ref = + { + .data = std::span(reinterpret_cast(null.data()), + null.size()), + .owner = nullptr, + }, + }); } /** @@ -836,10 +1712,11 @@ class room_impl final : public std::enable_shared_from_this, public r return; } const auto weak = weak_from_this(); - const std::pmr::vector targets(options.targets.begin(), - options.targets.end(), memory_); + const bool include_pending = is_internal_to_pending(name); + const auto peers = resolve_targets(options.targets, include_pending); + const std::pmr::vector targets(peers.begin(), peers.end(), memory_); wire_->send(name, payload.format, options.metadata, std::move(payload.ref), targets, - is_internal_to_pending(name), + include_pending, bind( [weak, handler = std::move(handler)](boost::system::error_code ec) mutable { if (const auto self = weak.lock()) { @@ -848,19 +1725,52 @@ class room_impl final : public std::enable_shared_from_this, public r })); } - /** Sends `\@_ping` to an active peer, and completes with the time until its `\@_pong`. */ - void ping(std::string_view peer, + /** + * The peers a send's targets name, as 0.27.0's resolveSendTarget reads them: an active peer, + * or a pending one when the action goes to those, is itself; a user stands for each of its + * active peers, even for an action that goes to pending ones, where 0.27.0 adds its pending + * peers too (only the room's own actions go to pending peers, and they name peers); another + * target stays, which the wire fails as not connected. Each peer once, copied: a send may end + * a peer while it goes through them. + */ + std::pmr::vector resolve_targets(std::span targets, + bool include_pending) const { + std::pmr::vector out(memory_); + const auto add = [&out](std::string_view id) { + if (std::ranges::find(out, id) == out.end()) { + out.emplace_back(id); + } + }; + for (const auto& target : targets) { + const auto peer = peers_.find(target); + if (peer != peers_.end() && (peer->second.active || include_pending)) { + add(target); + continue; + } + const auto of_user = users_.peers_of(target); + if (of_user.empty()) { + add(target); + } + for (const auto& id : of_user) { + add(id); + } + } + return out; + } + + /** Requests `\@_ping` of an active peer, or of a user's, with an empty text, as 0.27.0's + * `ping` requests it, and completes with the time until its answer. */ + void ping(std::string_view target, completion handler) { - const auto it = peers_.find(peer); - if (left_ || it == peers_.end() || !it->second.active) { + const auto peer = left_ ? std::string_view() : request_target(target); + if (peer.empty()) { complete(std::move(handler), make_error_code(left_ ? error::room_left : error::no_such_peer), std::chrono::milliseconds{}); return; } - it->second.pings.push_back( - {.started = steady_now(factory_), .handler = std::move(handler)}); - send_internal("@_ping", it->first); + send_request(peer, "@_ping", encoded_payload(), std::string_view(), std::nullopt, + pending_ping{.started = steady_now(factory_), .handler = std::move(handler)}); } /** Says `\@_leave` to every peer, then ends the room after Trystero's 99 ms. A leave asked @@ -871,6 +1781,12 @@ class room_impl final : public std::enable_shared_from_this, public r return; } leave_completions_.push_back(std::move(handler)); + begin_leave(); + } + + /** Starts the farewell, unless it has started: `\@_leave` to every peer, then the room ends + * after Trystero's 99 ms, completing every leave pending then. */ + void begin_leave() { if (std::exchange(left_, true)) { return; } @@ -878,6 +1794,9 @@ class room_impl final : public std::enable_shared_from_this, public r if (ended_) { return; // a rejoin or destruction in the sink already finished this farewell } + // Nothing is announced during the farewell, as 0.27.0's leave cancels its announcements + // first: a peer that let this room go would otherwise offer it a new connection. + strategy_->stop_announcing(); for (const auto& [id, p] : peers_) { send_internal("@_leave", id); } @@ -905,8 +1824,8 @@ class room_impl final : public std::enable_shared_from_this, public r /** Whether this room is still in its farewell interval. */ [[nodiscard]] bool leaving() const override { return left_ && !ended_; } - /** Ends the room now: its presence(0) sent, the room unregistered and the app's user released - * (close_everything), then every pending leave completed, once. */ + /** Ends the room now: its connections ended, the room unregistered and the app's user + * released (close_everything), then every pending leave completed, once. */ void finish_farewell() override { if (std::exchange(ended_, true)) { return; @@ -983,45 +1902,87 @@ class room_impl final : public std::enable_shared_from_this, public r } } - /** How a binding ended: the peer's \@_leave, its presence(0), a kick of this room, the - * connection's end, or this room's own leave. */ - enum class end_kind { peer_left, withdrawn, kick, connection_end, room_end }; + /** A peer's run of the identity handshake: 0.27.0's `run` for the peer's connection, whose + * steps the handshake manager hands it, and the manager's `done`, called once. */ + struct identity_run { + // NOLINTNEXTLINE(performance-unnecessary-value-param): a sink, moved on + identity_run(handler finished, local_identity self, + identity_cache& cache, std::string_view app_id, std::string_view room_id, + std::string_view remote_peer, bool initiator, + std::span local_dtls, + std::span remote_dtls, + std::array nonce_random, std::pmr::memory_resource* memory) + : machine(self, cache, app_id, room_id, remote_peer, initiator, local_dtls, remote_dtls, + nonce_random, memory), + done(std::move(finished)) {} - struct pending_ping { - detail::time_point started{}; - completion handler; + identity_handshake machine; + handler done; }; struct peer_state { - explicit peer_state(std::pmr::polymorphic_allocator<> a) : challenge(a), pings(a) {} - - std::shared_ptr link; - bool active = false; - bool local_passed = false; - bool remote_ready = false; - bool challenge_sent = false; - std::pmr::string challenge; // the initiator's, while it waits for the response - std::shared_ptr handshake_timer; - std::pmr::deque pings; + explicit peer_state(std::pmr::polymorphic_allocator<> a) : local_dtls(a), remote_dtls(a) {} + + std::shared_ptr link; + /** The DTLS fingerprints of the link's local and remote descriptions. */ + std::pmr::vector local_dtls; + std::pmr::vector remote_dtls; + /** Its identity handshake, while it runs; its outcome, once verified. */ + std::shared_ptr run; + std::optional identity; + bool active = false; // its handshake completed: the manager's `phase::active` + /** A refusal that arrived before the peer was verified, 0.27.0's deferredReady. */ + std::optional refusal_before_verified; }; - struct action_slot { - explicit action_slot(std::pmr::polymorphic_allocator<> a) : queue(a), receivers(a) {} + /** A link the room let go, until its last frames had their time to leave. */ + struct flushing_link { + std::shared_ptr link; + std::pmr::string reason; + std::shared_ptr grace; + std::shared_ptr cap; + }; - std::shared_ptr handler; + /** The most peers whose users a full room remembers, 0.27.0's `rejectedFullPeerUsers`. */ + static constexpr std::size_t max_refused_peers = 256; + /** How long a let-go link waits at least before it ends, 0.27.0's destroyAfterFlush grace. */ + static constexpr std::chrono::milliseconds flush_grace{40}; + /** How long a let-go link waits at most before it ends, 0.27.0's destroyAfterFlush cap. */ + static constexpr std::chrono::milliseconds flush_cap{150}; + + struct action_slot { + explicit action_slot(std::pmr::polymorphic_allocator<> a) + : messages(a), requests(a), gate(a), progress(a), queue(a), receivers(a) {} + + /** Whether its messages are requests, which its request listener answers. */ + bool request = false; + /** Whether `async_receive` was called: the action listens from then on, its messages + * queuing for the next receive. */ + bool awaited = false; + listeners messages; + /** One at a time. */ + listeners requests; + /** One at a time. */ + listeners gate; + listeners progress; + /** The messages that arrived while no listener and no receive waited, for the next. */ std::pmr::deque queue; std::pmr::deque> receivers; }; + /** A request sent, waiting for its answer. */ + struct request_waiter { + std::pmr::string peer; + request_completion handler; + std::shared_ptr timer; + }; + static constexpr std::size_t max_queued_messages = 1024; - /** A handler that several posts call, shared in the room's resource. */ - template - std::shared_ptr> keep_handler(handler f) const { - if (!f) { - return nullptr; - } - return std::allocate_shared>(allocator(), std::move(f)); + /** The slot of an action the room made, or null. */ + action_slot* made(std::string_view name) { + const auto it = actions_.find(name); + return it == actions_.end() ? nullptr : &it->second; } template @@ -1041,9 +2002,143 @@ class room_impl final : public std::enable_shared_from_this, public r return name == "@_leave" || name == "@_hsdata" || name == "@_hsready"; } + /** The longest handshake message, 0.27.0's `maxPayloadBytes` of `\@_hsdata`. */ + static constexpr std::size_t max_handshake_data_bytes = std::size_t{64} * 1024; + /** The longest ready frame's payload, 0.27.0's `maxPayloadBytes` of `\@_hsready`. */ + static constexpr std::size_t max_handshake_ready_bytes = std::size_t{128} * 1024; + + /** The longest payload of an action, 0.27.0's `maxPayloadBytes`: the handshake's own; every + * other action has the room's `max_receive_bytes`. */ + static std::size_t max_payload(std::string_view name) { + if (name == "@_hsdata") { + return max_handshake_data_bytes; + } + if (name == "@_hsready") { + return max_handshake_ready_bytes; + } + return std::numeric_limits::max(); + } + + /** Whether the room has the action: it was made, or it is internal. */ + bool has_action(std::string_view name) const { + return name.starts_with("@_") || actions_.contains(name); + } + + /** Whether an action the room has listens, 0.27.0's receiver: an internal one always; a + * request action while its request listener is in place; another while it has a message + * listener, and from its first `async_receive` on. Its frames wait in the wire meanwhile. */ + bool listens(std::string_view name) const { + if (name.starts_with("@_")) { + return true; + } + const auto it = actions_.find(name); + if (it == actions_.end()) { + return false; + } + const auto& slot = it->second; + return slot.request ? !slot.requests.empty() : !slot.messages.empty() || slot.awaited; + } + + /** The metadata a listener of an action reads: a request's own, inside its envelope; nothing + * when a request's names none. */ + std::optional user_metadata(const action_slot& slot, + std::string_view metadata) const { + if (!slot.request) { + return std::pmr::string(metadata, memory_); + } + auto envelope = read_request(metadata, decoding()); + if (!envelope) { + return std::nullopt; + } + return std::move(envelope->metadata); + } + + /** Asks an action's receive gate about a message, as the wire receives it. The gate runs + * during the call, and may end the peer or the room. */ + admission admit(std::string_view peer, std::string_view name, std::size_t size, + std::string_view metadata) { + auto* const slot = made(name); + if (slot == nullptr || slot->gate.empty()) { + return admission::open; + } + const auto own = user_metadata(*slot, metadata); + if (!own) { + return admission::refused; // a request without its envelope, which nothing answers + } + // A copy: the gate may end the room, and free the users' entries. + const std::pmr::string user(user_of(peer), memory_); + const receive_info info{ + .peer_id = peer, + .user_id = user, + .byte_length = size, + .metadata = *own, + }; + return slot->gate.call_first(info) ? admission::admitted : admission::refused; + } + + /** The wire refused a message of an action: a request is answered with the reason, as 0.27.0's + * request actions answer it, so that the requester need not wait. */ + void on_rejected(std::string_view peer, std::string_view name, std::string_view metadata, + std::string_view reason) { + const auto* const slot = made(name); + if (slot == nullptr || !slot->request || left_) { + return; + } + if (const auto envelope = read_request(metadata, decoding())) { + respond_error(peer, envelope->id, reason); + } + } + + /** Posts the progress of a message of an action to its progress listeners. */ + void post_progress(std::string_view peer, std::string_view name, std::string_view metadata, + double share) { + auto* const slot = made(name); + if (slot == nullptr || slot->progress.empty()) { + return; + } + auto own = user_metadata(*slot, metadata); + if (!own) { + return; + } + post([weak = weak_from_this(), slot, share, peer = std::pmr::string(peer, memory_), + user = std::pmr::string(user_of(peer), memory_), metadata = std::move(*own)] { + // Held for the whole emission: a listener may release the room's last handles. + if (const auto self = weak.lock()) { + slot->progress.emit(share, + {.peer_id = peer, .user_id = user, .metadata = metadata}); + } + }); + } + + /** + * Posts a message to an action's listeners, or, when none is left once the post runs, to its + * next receive. A slot lives as long as its room. + * + * Tip: `hand_over` posts here again when listeners came back meanwhile, a loop through the + * executor and not a recursion, since each post runs once the call that made it has returned. + * It is called through a pointer, so that the analysis of calls (misc-no-recursion) sees no + * cycle through Asio's post. + */ + void post_message(action_slot& slot, incoming&& m) { + post([weak = weak_from_this(), slot = &slot, m = std::move(m), + hand_over_to = &room_impl::hand_over]() mutable { + const auto self = weak.lock(); + if (!self) { + return; + } + if (slot->messages.empty()) { + ((*self).*hand_over_to)(*slot, std::move(m)); + return; + } + m.shared = slot->messages.size() > 1; + slot->messages.emit(m); + }); + } + + /** 0.27.0's `canReceiveFromPeer`: a peer's messages are received once its handshake + * completed, the handshake's own and `\@_leave` while it is pending. */ bool may_receive(std::string_view peer, std::string_view name) const { - const auto it = peers_.find(peer); - return it != peers_.end() && (it->second.active || is_internal_to_pending(name)); + return handshakes_->can_receive(peer, is_internal_to_pending(name)); } std::pmr::vector peer_views(bool include_pending) const { @@ -1081,325 +2176,318 @@ class room_impl final : public std::enable_shared_from_this, public r bind([](boost::system::error_code) {})); } - void post_call(const std::shared_ptr& handler, incoming m) { - post([handler, m = std::move(m)]() mutable { (*handler)(m); }); - } - - void report(std::string_view peer, boost::system::error_code ec, std::string_view what) { - // The sink may end the room and release the storage behind either view. - std::pmr::string peer_copy(peer, memory_); - std::pmr::string what_copy(what, memory_); - log_("room", "peer ", peer_copy, ": ", what_copy); - if (on_error_) { - post([f = on_error_, peer = std::move(peer_copy), ec, what = std::move(what_copy)] { - (*f)(peer, ec, what); - }); - } - } - - /** What makes a room bind a peer over a live connection: its own join, the peer's presence, a - * frame of the room the connection kept, the reuse of the connection by a signal, or the room's - * rebinding time. */ - enum class bind_event { joined, presence, frame, reuse, rebinding }; - - /** A live app connection consumes signals; only the first meeting may bind by reuse. */ - bool claim(std::string_view peer) { - if (!app_->find(peer)) { - return false; - } - if (!met(peer)) { - try_bind(peer, bind_event::reuse); - } - return true; + /** Reports a problem with `peer`, or with none, to the room's error listeners. */ + void report(std::string_view peer, boost::system::error_code ec, std::string_view message) { + room_error e; + e.code = ec; + e.message = message; + e.peer_id = peer; + report(e); } - /** Binds `peer` over the app's live connection to it when every condition holds: the peer has - * itself advertised this room's token on that connection, this room is not leaving, no backoff - * of this room runs for the peer, and the peer is not bound already. Whether it bound. - * - * Tip: the advertisement is the peer's own, its presence or a room frame of the token, on a - * connection only it can write to, so that an announcement or a signal anyone publishes in its - * name binds nothing. */ - bool try_bind(std::string_view peer, bind_event event) { - if (left_ || peers_.contains(peer)) { - return false; - } - const auto c = app_->find(peer); - if (!c || !c->advertised(token_) || refusing(peer)) { - return false; - } - if (event == bind_event::reuse || event == bind_event::rebinding) { - c->send_presence(token_, true); - } - bind_peer(peer, c); - return true; - } - - /** Whether this room has already met `peer` over the current shared connection. */ - [[nodiscard]] bool met(std::string_view peer) const { - const auto it = rebinds_.find(peer); - return it != rebinds_.end() && it->second.met; - } - - /** Whether the lower id is refusing a binding during its backoff. */ - [[nodiscard]] bool refusing(std::string_view peer) const { - const auto it = rebinds_.find(peer); - return it != rebinds_.end() && it->second.refusing; - } - - /** Whether a kept frame is a `\@_leave`, which ends a binding of the other side. */ - static bool is_leave(std::span frame) { - const auto e = protocol::decode_envelope(frame); - const auto d = e ? protocol::decode_action(e->payload) : protocol::decode_result{}; - const auto* p = d.frame ? std::get_if(&*d.frame) : nullptr; - return p != nullptr && p->name == "@_leave"; - } + /** + * Logs a problem the room handled itself and posts its report to the error listeners, with + * the app's and the room's ids: what is in place when the post runs, unless the room was left + * by then, as 0.27.0 reports nothing once its room is leaving. + */ + void report(const room_error& e) { + // Copies: the post runs after the views' storage may be gone. + struct owned { + boost::system::error_code code; + std::pmr::string message; + std::pmr::string peer_id; + std::optional stage; + bool turn_configured; + std::pmr::string reason; + std::pmr::string plugin; + }; - /** Delivers the frames `c` kept for this room, in order, but a kept \@_leave and everything - * kept before it, which belong to a binding of the other side that has ended. Stops once the - * peer's entry is gone or holds another binding. */ - void deliver_kept(const std::pmr::string& peer, connection& c, const detail::binding* mine) { - auto frames = c.take_kept(token_); - std::size_t first = 0; - for (std::size_t i = 0; i < frames.size(); ++i) { - if (is_leave(frames[i])) { - first = i + 1; - } + owned copy{ + .code = e.code, + .message = std::pmr::string(e.message, memory_), + .peer_id = std::pmr::string(e.peer_id, memory_), + .stage = e.stage, + .turn_configured = e.turn_configured, + .reason = std::pmr::string(e.reason, memory_), + .plugin = std::pmr::string(e.plugin, memory_), + }; + if (copy.peer_id.empty()) { + log_("room", copy.message); + } else { + log_("room", "peer ", copy.peer_id, ": ", copy.message); } - for (std::size_t i = first; i < frames.size(); ++i) { - if (const auto it = peers_.find(peer); - it == peers_.end() || it->second.link.get() != mine) { + post([weak = weak_from_this(), copy = std::move(copy)] { + const auto self = weak.lock(); + if (!self || self->left_) { return; } - const auto envelope = protocol::decode_envelope(frames[i]); - BOOST_ASSERT(envelope); - const auto action = envelope->payload; - wire_->handle(peer, std::move(frames[i]), action); - } - } - - /** A negotiation of this room opened a channel to `peer`: the app adopts the connection, or - * keeps the one it has to the peer, and the room binds the peer to it. - * - * Tip: the adoption may end a stale connection to the peer, whose end reaches this room - * synchronously and may remove the peer; nothing of the room is held across it, and the id is - * this call's own copy. */ - // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on - void on_connected(std::string_view peer_view, std::shared_ptr pc, - std::shared_ptr channel) { - // NOLINTEND(performance-unnecessary-value-param) - if (left_) { - channel->set_handlers({}); - pc->set_handlers({}); - channel->close(); - pc->close(); - return; - } - const std::pmr::string peer(peer_view, memory_); - const auto c = app_->adopt(peer, std::move(pc), std::move(channel)); - // Adoption logs synchronously: the sink may leave or destroy this room, or end the - // connection. A farewell still counts as leaving and must not gain a new binding. - if (left_) { - if (ended_) { - c->idle_if_unused(app_->idle_timeout()); - } else { - departing_connection_ = c; - } - } else if (c->live()) { - bind_peer(peer, c); - } else { - // A native transport can close while adoption calls the log sink. No binding - // exists yet, so its queued end cannot remove_peer and forget this negotiation. - signaling_->forget(peer); - strategy_->restart_announcements(); - } + self->errors_.emit({ + .code = copy.code, + .message = copy.message, + .app_id = self->app_->app_id(), + .room_id = self->room_id_, + .peer_id = copy.peer_id, + .stage = copy.stage, + .turn_configured = copy.turn_configured, + .reason = copy.reason, + .plugin = copy.plugin, + }); + }); } - /** Binds this room to `c` for `peer`, in the order the specification sets: the negotiation - * marked connected, the peer's state and handshake timer, the frames the connection kept for - * this room, then the handshake's first message, as Trystero adds a peer before it flushes. + /** Binds this room to `link` for `peer`, in the order the specification sets: the negotiation + * marked connected, the peer's state and its handshake added, the frames the link kept, then + * the handshake started, as 0.27.0's room adds a peer to its handshake manager, sets the + * peer's handlers, which flush what it kept, then starts the handshake. * * Tip: the peer's id is copied first, since every step may run code that removes the peer's * entry (a kick); the entry is never held by reference across such a step, and each step - * looks it up again. Each lambda keeps its own copy in the room's resource, named: a plain copy - * of a std::pmr::string takes the default resource. */ - void bind_peer(std::string_view peer_view, const std::shared_ptr& c) { - // A peer is bound once until its removal, as the connection's attach requires: the - // signaling hands over no channel while its entry is connected, which `on_channel_open` - // and `bound` set and only `forget` clears, after `remove_peer` has taken the peer out. + * looks it up again by the link it holds. Each lambda keeps its own copy in the room's + * resource, named: a plain copy of a std::pmr::string takes the default resource. */ + void bind_peer(std::string_view peer_view, const std::shared_ptr& link, + std::string_view local_sdp, std::string_view remote_sdp) { + // A peer is bound once until its removal: the signaling hands over no channel while its + // entry is connected, which `on_channel_open` and `bound` set and only `forget` clears, + // after `remove_peer` has taken the peer out. BOOST_ASSERT(!peers_.contains(peer_view)); const std::pmr::string peer(peer_view, memory_); const auto weak = weak_from_this(); signaling_->bound(peer); - auto& history = - rebinds_.try_emplace(std::pmr::string(peer, memory_), allocator()).first->second; - history.met = true; - history.on = c; - // This binding, held until the call returns: a kept frame may remove the peer's entry and - // free it, and another made meanwhile must not be taken for it at the same address. - std::shared_ptr mine; - { - auto& state = peers_.try_emplace(peer, allocator()).first->second; - state.link = std::allocate_shared( - allocator(), c, token_, - bind)>( - [weak, peer = std::pmr::string(peer, memory_)]( - backend::bytes&& frame, std::span action) { - if (const auto self = weak.lock()) { - self->wire_->handle(peer, std::move(frame), action); - } - }), - memory_); - state.handshake_timer = factory_.make_timer(memory_); - state.handshake_timer->start( - options_.handshake_timeout, - bind([weak, peer = std::pmr::string(peer, memory_)] { - const auto self = weak.lock(); - if (!self) { - return; + auto& state = peers_.try_emplace(peer, allocator()).first->second; + state.link = link; + state.local_dtls = protocol::dtls_fingerprints(local_sdp, memory_); + state.remote_dtls = protocol::dtls_fingerprints(remote_sdp, memory_); + handshakes_->add(peer); + // The link's identity, never dereferenced: a link made later at its address is never the + // one whose end this names, since the link calls its `ended` alive. + const peer_link* const mine = link.get(); + link->bind({ + .frame = bind( + [weak, peer = std::pmr::string(peer, memory_), mine](backend::bytes frame) { + // A link the room let go, which flushes its last frames before it ends, + // delivers nothing, as 0.27.0's destroyAfterFlush clears its peer's handlers. + // The handshake manager already refuses frames of a peer it forgot; this + // keeps that so for a link whose peer id is bound again by another link, + // which no path reaches yet (the gate refuses a refused user's connections) + // and so no test does. + if (const auto self = weak.lock(); self && self->is_link_of(peer, mine)) { + self->wire_->handle(peer, std::move(frame)); } - self->report(peer, make_error_code(error::handshake_timed_out), - "handshake timed out"); - self->kick(peer, "handshake timed out"); - })); - mine = state.link; - } - deliver_kept(peer, *c, mine.get()); + }), + .ended = bind( + [weak, peer = std::pmr::string(peer, memory_), mine](std::string_view reason) { + if (const auto self = weak.lock()) { + self->on_link_ended(peer, mine, reason); + } + }), + }); if (const auto it = peers_.find(peer); - it != peers_.end() && it->second.link.get() == mine.get()) { - start_handshake(it->first, it->second); + it != peers_.end() && it->second.link.get() == mine) { + handshakes_->start(peer); } } - void start_handshake(std::string_view peer, peer_state& state) { - if (app_->password().empty()) { - pass_local(peer); + /** A peer's link ended on its own (its channel, its connection, or a frame past 0.27.0's + * bounds): the peer goes, if the link is still its. */ + void on_link_ended(std::string_view peer, const peer_link* link, std::string_view reason_view) { + if (const auto it = peers_.find(peer); + it == peers_.end() || it->second.link.get() != link) { return; } - if (app_->self_id() < peer) { - state.challenge = detail::random_id(factory_, 36, memory_); // Trystero's genId(36) - if (const auto history = rebinds_.find(peer); history != rebinds_.end()) { - history->second.challenges.push(std::pmr::string(state.challenge, memory_)); - } - std::pmr::string text(R"({"__trystero_pw":"challenge","c":)", memory_); - protocol::json::detail::append_utf8(text, state.challenge); // drawn from id_alphabet - text += '}'; - send_internal("@_hsdata", peer, protocol::payload_format::json, text); - state.challenge_sent = true; - } + const std::pmr::string reason(reason_view, memory_); + remove_peer(peer, reason); } - void on_handshake_data(std::string_view peer, std::string_view data) { - const auto it = peers_.find(peer); - if (it == peers_.end() || it->second.active || it->second.local_passed) { - return; - } - // A message past its bound fails the handshake as one of the wrong shape does. - const auto value = webcpp::document::parse( - data, protocol::json::protocol_limits(protocol::max_handshake_bytes), - std::pmr::polymorphic_allocator(memory_)); - const protocol::json::const_value o = value.has_value() && value->root().is_object() - ? value->root() - : protocol::json::const_value(); - const auto field = [&o](std::string_view key) { return protocol::json::text_of(o[key]); }; - if (app_->self_id() < peer) { - const auto h = field("h"); - const auto r = rebinds_.find(peer); - const bool proves = - field("__trystero_pw") == "response" && r != rebinds_.end() && - r->second.challenges.any_of([&](std::string_view c) { - return h == protocol::handshake_proof(c, app_->password(), app_->app_id(), - room_id_, memory_); - }); - if (proves) { - pass_local(peer); - return; - } - if (!it->second.challenge_sent) { - return; // a late answer of an ended binding, before this one's challenge - } - fail_handshake(peer); + /** + * Runs the identity handshake with a peer, as 0.27.0's handshake manager runs the room's + * `identityHandshake.run`: this side's nonce drawn from the backend's randomness for this run, + * the fingerprints of the peer's descriptions, and the peer's `\@_hsdata` messages through + * `next_message`. `done` takes "" once the peer's identity is verified and kept, else the + * reason the handshake failed. + */ + void run_identity(std::string_view peer_view, bool initiator, + handler done) { + const auto it = peers_.find(peer_view); + if (it == peers_.end()) { + done(handshake_manager::disconnected_reason); return; } - if (field("__trystero_pw") != "challenge" || !o["c"].is_string()) { - fail_handshake(peer); + // An app without its identity has no keys to prove: its rooms fail setup before any + // handshake, and a run that starts anyway fails closed. + if (!app_->identity_failure().empty()) { + done(protocol::handshake_reason::identity); return; } - std::pmr::string text(R"({"__trystero_pw":"response","h":)", memory_); - protocol::json::detail::append_utf8( - text, protocol::handshake_proof(field("c"), app_->password(), app_->app_id(), room_id_, - memory_)); - text += '}'; - send_internal("@_hsdata", peer, protocol::payload_format::json, text); - pass_local(peer); + // 0.27.0's crypto.randomUUID(), fresh for every run. + std::array nonce{}; + factory_.random(nonce); + const auto& endpoint = app_->endpoint(); + const std::pmr::string peer(it->first, memory_); + const auto run = std::allocate_shared( + allocator(), std::move(done), + local_identity{ + .endpoint = endpoint.key, + .peer_id = endpoint.peer_id, + .endpoint_key = endpoint.compact, + .user = app_->user(), + }, + app_->identities(), app_->app_id(), room_id_, peer, initiator, it->second.local_dtls, + it->second.remote_dtls, nonce, memory_); + it->second.run = run; + auto first = run->machine.start(); + step_identity(peer, run, std::move(first)); } - void fail_handshake(std::string_view peer_view) { - const std::pmr::string peer(peer_view, memory_); - report(peer, make_error_code(error::wrong_password), - "incorrect password for overlapping room"); - kick(peer, "handshake failed"); + /** The peer's state, if `run` is still its identity handshake. */ + peer_state* running(std::string_view peer, const std::shared_ptr& run) { + const auto it = peers_.find(peer); + return it != peers_.end() && it->second.run == run ? &it->second : nullptr; } - void pass_local(std::string_view peer) { - const auto it = peers_.find(peer); - if (it == peers_.end()) { + /** Ends a run once: the handshake manager hears `reason`, "" when the identity verified. */ + static void finish_identity(identity_run& run, std::string_view reason) { + if (!run.done) { return; } - it->second.local_passed = true; - send_internal("@_hsready", it->first); - maybe_activate(it->first); + auto done = std::move(run.done); + done(reason); } - void maybe_activate(std::string_view peer) { + /** + * Acts on what a call of a peer's identity handshake gave: its identity, verified, kept in the + * peer's state first, as 0.27.0's `onVerified` keeps it before the initiator's step 3; then the + * message to send; then the run's end, or a wait for the peer's next message. + */ + void step_identity(std::string_view peer, const std::shared_ptr& run, + identity_handshake::outcome out) { + // Only an identity kept in the peer's state ends the run verified; a run whose peer went + // ends as disconnected, never as verified. + bool kept = false; + std::optional refused; + if (out.done) { + if (auto* const state = running(peer, run)) { + // Constructed in place, as a move assignment of a std::pmr::string may allocate. + state->identity.emplace(std::move(*out.done)); + kept = true; + if (auto& before = state->refusal_before_verified) { + refused.emplace(std::move(*before)); + before.reset(); + } + } + } + if (!out.send.empty()) { + send_internal("@_hsdata", peer, protocol::payload_format::json, out.send); + } + // A refusal that arrived before the peer was verified is delivered now, 0.27.0's + // deferredReady, from the microtask that runs while the steps await their last send: the + // steps then end on a peer that is gone. + if (refused) { + refused_by(peer, *refused); + } + if (!out.failure.empty()) { + finish_identity(*run, out.failure); + return; + } + if (out.done) { + finish_identity(*run, + kept ? std::string_view() : handshake_manager::disconnected_reason); + return; + } + // The send may have let the peer go. + if (running(peer, run) == nullptr) { + finish_identity(*run, handshake_manager::disconnected_reason); + return; + } + handshakes_->next_message( + peer, bind( + [weak = weak_from_this(), peer = std::pmr::string(peer, memory_), run]( + boost::system::error_code ec, std::string_view json) { + const auto self = weak.lock(); + if (!self) { + return; + } + if (ec || self->running(peer, run) == nullptr) { + finish_identity(*run, handshake_manager::disconnected_reason); + return; + } + self->step_identity(peer, run, run->machine.receive(json)); + })); + } + + /** Both sides of a peer's handshake are ready, 0.27.0's `onActivate`: the peer joins, and its + * user with its first peer. */ + void activate(std::string_view peer) { const auto it = peers_.find(peer); - if (it == peers_.end() || it->second.active || !it->second.local_passed || - !it->second.remote_ready) { + if (it == peers_.end() || it->second.active) { return; } - it->second.active = true; - if (const auto history = rebinds_.find(peer); history != rebinds_.end()) { - history->second.ends = 0; - history->second.challenges.clear(); - history->second.timer.reset(); + // A peer joins only under the identity its handshake verified: users come from verified + // ids alone. + BOOST_ASSERT(it->second.identity); + if (!it->second.identity) { + return; + } + // As 0.27.0's onActivate, the room's users are counted again: a place taken meanwhile + // refuses the peer. Defensive until Phase 3 (scale): every place a peer's user could take + // is reserved from admission to here, so no public path reaches this refusal, and no test + // does. Keep it: virtual peers will. + if (full_for(peer, false)) { + refuse_full(peer); + return; } - it->second.handshake_timer.reset(); + reserved_.erase(it->first); + it->second.active = true; + it->second.run.reset(); + // Its user, the one its handshake verified, joins with its first peer, as 0.27.0 counts a + // user's peers; this peer's own user is no other user. + std::pmr::string user(user_of(peer), memory_); + const bool first_of_user = users_.add(peer, user) && user != self_user_id(); std::pmr::string peer_copy(it->first, memory_); const auto link = it->second.link; log_("room", "peer joined: ", peer_copy); // The sink may leave the room or remove this binding before notification is posted. const auto current = peers_.find(peer_copy); - if (!left_ && current != peers_.end() && current->second.link == link && on_join_) { - post([f = on_join_, peer = std::move(peer_copy)] { (*f)(peer); }); + if (!left_ && current != peers_.end() && current->second.link == link) { + // A user joins after its first peer, as 0.27.0 reports it. + // A room left before the post runs reports no join, as 0.27.0 reports none once its + // room is leaving. + post([weak = weak_from_this(), peer = std::move(peer_copy), user = std::move(user), + first_of_user] { + const auto self = weak.lock(); + if (!self || self->left_) { + return; + } + self->peer_join_.emit({.peer_id = peer, .user_id = user}); + if (first_of_user) { + self->user_join_.emit({.user_id = user, .peer_id = peer}); + } + }); } } void on_incoming(incoming&& m) { const auto name = m.name(); const auto it_peer = peers_.find(m.peer); + // A leaving room handles no handshake message, as 0.27.0's room checks isLeavingOrLeft. if (name == "@_hsready") { - if (it_peer != peers_.end() && !it_peer->second.active) { - it_peer->second.remote_ready = true; - maybe_activate(it_peer->first); + if (it_peer != peers_.end() && !left_) { + on_ready(it_peer->first, it_peer->second, + read_refusal(m.format, as_text(m.payload()), decoding())); } } else if (name == "@_hsdata") { - if (it_peer != peers_.end()) { - on_handshake_data(it_peer->first, as_text(m.payload())); + if (it_peer != peers_.end() && !left_) { + handshakes_->receive_data(it_peer->first, as_text(m.payload())); } } else if (name == "@_ping") { - if (it_peer != peers_.end()) { - send_internal("@_pong", it_peer->first); - } - } else if (name == "@_pong") { - if (it_peer != peers_.end() && !it_peer->second.pings.empty()) { - auto ping = std::move(it_peer->second.pings.front()); - it_peer->second.pings.pop_front(); - const auto elapsed = std::chrono::duration_cast( - steady_now(factory_) - ping.started); - complete(std::move(ping.handler), boost::system::error_code{}, elapsed); + // 0.27.0's internal request action, whose listener answers each request with "". One + // whose metadata names no request is dropped, as deliver_request drops a user's. + if (const auto envelope = read_request(m.metadata(), decoding())) { + respond(m.peer, envelope->id, {}); } } else if (name == "@_leave") { - remove_peer(m.peer, "peer left the room", end_kind::peer_left); + remove_peer(m.peer, "peer left the room"); + } else if (name == "@_response") { + on_response(std::move(m)); } else if (name.starts_with("@_")) { // Media and renegotiation actions: not implemented yet (doc: #trystero-roadmap). } else if (const auto it = actions_.find(name); it != actions_.end()) { @@ -1407,84 +2495,435 @@ class room_impl final : public std::enable_shared_from_this, public r } } - /** Delivers an application message, rechecking consumers after a queue-limit log sink. */ + /** Delivers an application message: its progress is complete, and it goes to the request + * listener, the message listeners, or the next receive, in that order. */ void deliver_action(std::string_view name, action_slot& slot, incoming&& message) { - if (!slot.handler && slot.receivers.empty() && slot.queue.size() >= max_queued_messages) { - log_("action", "dropping the oldest unread message of ", name); + post_progress(message.peer, name, message.metadata(), 1.0); + if (slot.request) { + deliver_request(slot, std::move(message)); + } else if (!slot.messages.empty()) { + post_message(slot, std::move(message)); + } else { + hand_over(slot, std::move(message)); + } + } + + /** Hands a message to the next receive, or queues it for one, rechecking consumers after a + * queue-limit log sink. */ + void hand_over(action_slot& slot, incoming&& message) { + // A message posted before a leave that finds no listener once it runs goes with the room, + // as the rest of what waited at the leave went: a receive or listener added since gets + // nothing. + if (left_) { + return; + } + if (slot.messages.empty() && slot.receivers.empty() && + slot.queue.size() >= max_queued_messages) { + log_("action", "dropping the oldest unread message of ", message.name()); if (left_) { return; } - // Installing a handler or receiving from the sink can drain the queue synchronously. + // Adding a listener or receiving from the sink can drain the queue synchronously. if (slot.queue.size() >= max_queued_messages) { slot.queue.pop_front(); } } - if (slot.handler) { - post_call(slot.handler, std::move(message)); - } else if (!slot.receivers.empty()) { + if (!slot.receivers.empty()) { auto receiver = std::move(slot.receivers.front()); slot.receivers.pop_front(); complete(std::move(receiver), boost::system::error_code{}, std::move(message)); + } else if (!slot.messages.empty()) { + post_message(slot, std::move(message)); } else { slot.queue.push_back(std::move(message)); } } + /** Posts a request to the listener that answers it; one whose metadata names no request is + * dropped, as 0.27.0 drops it, and one that finds no listener once the post runs is refused. */ + void deliver_request(action_slot& slot, incoming&& message) { + auto envelope = read_request(message.metadata(), decoding()); + if (!envelope) { + return; + } + post([weak = weak_from_this(), slot = &slot, envelope = std::move(*envelope), + m = std::move(message)]() mutable { + const auto self = weak.lock(); + if (!self) { + return; + } + if (slot->requests.empty()) { + self->respond_error(m.peer, envelope.id, "no active request handler"); + return; + } + slot->requests.call_first(m, envelope); + }); + } + + /** An answer to a request: it completes the request of its id, if the peer it was sent to + * answered it. */ + void on_response(incoming&& m) { + const auto envelope = read_response(m.metadata(), decoding()); + if (!envelope) { + return; + } + const auto it = requests_.find(envelope->id); + if (it == requests_.end() || it->second.peer != m.peer) { + return; + } + if (envelope->refused) { + // The request completes with the code alone; the reason the peer gave is logged. + log_("action", "request ", envelope->id, " refused by ", m.peer, ": ", + envelope->reason); + } + finish_request(envelope->id, + envelope->refused ? make_error_code(error::request_rejected) + : boost::system::error_code{}, + std::move(m)); + } + + /** Completes a request once, with its answer or its failure. */ + void finish_request(std::string_view id, boost::system::error_code ec, incoming&& m) { + const auto it = requests_.find(id); + if (it == requests_.end()) { + return; + } + // A node handle's mapped value is mutable through a const handle. + const auto node = requests_.extract(it); + if (node.mapped().timer) { + node.mapped().timer->cancel(); + } + if (auto* const ping = std::get_if(&node.mapped().handler)) { + const auto elapsed = ec ? std::chrono::milliseconds{} + : std::chrono::duration_cast( + steady_now(factory_) - ping->started); + complete(std::move(ping->handler), ec, elapsed); + return; + } + complete(std::move(std::get<0>(node.mapped().handler)), ec, std::move(m)); + } + + /** Whether the room expects a message of `name` from `peer`, 0.27.0's `receiveScope`: an + * answer only when it answers a request of the room's sent to that peer, every other + * message always. */ + bool expects(std::string_view peer, std::string_view name, std::string_view metadata) const { + if (name != "@_response") { + return true; + } + const auto envelope = read_response(metadata, decoding()); + if (!envelope) { + return false; + } + const auto it = requests_.find(envelope->id); + return it != requests_.end() && it->second.peer == peer; + } + + /** Fails every request sent to `peer`, or every request when it is empty. */ + void fail_requests(std::string_view peer, boost::system::error_code ec) { + std::pmr::vector ids(memory_); + for (const auto& [id, w] : requests_) { + if (peer.empty() || w.peer == peer) { + ids.emplace_back(id); // in the vector's resource, the room's + } + } + for (const auto& id : ids) { + finish_request(id, ec, {}); + } + } + + /** Sends an answer, inline or as a transfer, to one peer, the room not left. */ + void send_response(std::string_view peer, std::string_view metadata, encoded_payload payload) { + if (left_ || !wire_) { + return; + } + wire_->send("@_response", payload.format, metadata, std::move(payload.ref), + std::span(&peer, 1), false, + bind([](boost::system::error_code) {})); + } + + /** + * Drops a peer the action wire caught breaking the protocol, 0.27.0's `onPeerError`: a peer + * of the room, pending or active, is reported as `error::peer_error` with the reason as its + * message, then told to leave and dropped; one the room does not have is ignored, as + * 0.27.0's `hasAnyPeer` checks. + */ + void fail_peer(std::string_view peer_view, std::string_view reason_view) { + const auto it = peers_.find(peer_view); + if (it == peers_.end()) { + return; + } + // Copies: the kick frees the views' storage. + const std::pmr::string peer(it->first, memory_); + const std::pmr::string reason(reason_view, memory_); + report(peer, make_error_code(error::peer_error), reason); + kick(peer, reason); + } + void kick(std::string_view peer, std::string_view reason) { const auto it = peers_.find(peer); if (it == peers_.end()) { return; } send_internal("@_leave", it->first); - remove_peer(it->first, reason, end_kind::kick); + remove_peer(it->first, reason); } - /** Detaches a peer's binding as its end says: the connection idles after a departure, this - * room's own leave among them, and ends after a kick of its last room; at the connection's - * end, the connection has let the binding go already. */ - void let_go(peer_state& state, end_kind kind) { - if (kind == end_kind::connection_end) { + /** + * A peer's ready frame, 0.27.0's `handshakeReadyAction.onMessage`: kept until the peer is + * verified, as its `deferredReady`, then a refusal ends a pending peer, and another ready + * frame goes to the handshake manager. + */ + void on_ready(std::string_view peer, peer_state& state, std::optional refusal) { + if (!state.identity) { + // The last frame received wins, as 0.27.0 keeps one deferredReady; a plain one is the + // manager's remote readiness, which it keeps itself. + // Constructed in place, as a move assignment of a std::pmr::string may allocate. + state.refusal_before_verified.reset(); + if (refusal) { + state.refusal_before_verified.emplace(std::move(*refusal)); + } else { + handshakes_->receive_ready(peer); + } return; } - state.link->detach(kind == end_kind::kick, app_->idle_timeout()); - } - - /** After a binding with `peer` ended over a live connection, by a kick of either side: the - * next binding at one step (detail::rebinding_step); meanwhile the lower id refuses after its - * own kick, and the higher id drops the peer's frames after its own kick, until it sends - * presence. */ - void schedule_rebinding(std::string_view peer, bool own_kick) { - auto& r = rebinds_.try_emplace(std::pmr::string(peer, memory_), allocator()).first->second; - ++r.ends; - const bool lower = app_->self_id() < peer; - r.refusing = own_kick && lower; - r.dropping = own_kick && !lower; - r.timer = factory_.make_timer(memory_); - r.timer->start( - rebinding_step(options_.handshake_timeout, r.ends), - bind([weak = weak_from_this(), peer = std::pmr::string(peer, memory_)] { - if (const auto self = weak.lock()) { - self->on_rebinding_time(peer); + if (refusal) { + refused_by(peer, *refusal); + return; + } + handshakes_->receive_ready(peer); + } + + /** + * A pending peer refused this one, 0.27.0's `processHandshakeReady` on `ok: false`; an active + * peer's refusal, or one of a peer whose handshake ended, is ignored. + * + * | Refusal | Report | Then | + * | `room full` | `error::room_full`, "room full", the peer's id | the peer goes, | + * | | | unannounced | + * | `peer banned` | `error::banned`, "peer banned" or "peer banned: | the peer is told to | + * | | ", the reason, the peer's id | leave and goes, | + * | | | unannounced | + */ + void refused_by(std::string_view peer_view, const ready_refusal& refusal) { + const auto it = peers_.find(peer_view); + if (it == peers_.end() || it->second.active || !handshakes_->phase_of(peer_view)) { + return; + } + const std::pmr::string peer(it->first, memory_); + handshakes_->clear(peer); + if (refusal.why == ready_refusal::kind::room_full) { + report(peer, make_error_code(error::room_full), "room full"); + remove_peer(peer, "room full", true); + return; + } + // 0.27.0's mkBannedErr: the reason in the message when it is not empty, and as the reason + // whenever the peer gave one. + std::pmr::string message("peer banned", memory_); + if (refusal.reason && !refusal.reason->empty()) { + message += ": "; + message += *refusal.reason; + } + room_error e; + e.code = make_error_code(error::banned); + e.message = message; + e.peer_id = peer; + if (refusal.reason) { + e.reason = *refusal.reason; + } + report(e); + // 0.27.0's kickPeer with peerBannedErr: the farewell, then exitPeer, which lets the + // connection flush and does not announce the room again. + send_internal("@_leave", peer); + remove_peer(peer, "peer banned", true); + } + + /** Whether `link` is still the one of `peer`. */ + bool is_link_of(std::string_view peer, const peer_link* link) const { + const auto it = peers_.find(peer); + return it != peers_.end() && it->second.link.get() == link; + } + + /** The user a peer is known as, 0.27.0's `userId` of its entry: the one its handshake + * verified, else the one this room refused while full (made the most recently used); empty + * when neither. */ + std::optional known_user(std::string_view peer) { + if (const auto it = peers_.find(peer); it != peers_.end()) { + if (const auto& identity = it->second.identity) { + return std::string_view(identity->user_id); + } + } + const auto it = refused_.find(peer); + if (it == refused_.end()) { + return std::nullopt; + } + refused_order_.splice(refused_order_.begin(), refused_order_, it->second); + return std::string_view(it->second->second); + } + + /** Remembers the user a full room refused a peer as, 0.27.0's `rejectedFullPeerUsers`: the + * most recently used first, the least recently used forgotten past + * @ref max_refused_peers. */ + void remember_refused(std::string_view peer, std::string_view user) { + if (const auto it = refused_.find(peer); it != refused_.end()) { + refused_order_.splice(refused_order_.begin(), refused_order_, it->second); + it->second->second = user; + return; + } + if (refused_order_.size() >= max_refused_peers) { + refused_.erase(refused_order_.back().first); + refused_order_.pop_back(); + } + refused_order_.emplace_front(std::pmr::string(peer, memory_), + std::pmr::string(user, memory_)); + refused_.emplace(refused_order_.front().first, refused_order_.begin()); + } + + /** + * Whether the room is full for a peer that is not active, 0.27.0's `isFullForPeer`: its users, + * this peer's own, the active peers' and, with `include_reserved`, those of the admissions + * under way but the peer's own, reach `max_users`, and the peer's user (or its id, when it has + * none known) is not among them. Never for a room without `max_users`, nor an active peer. + */ + bool full_for(std::string_view peer, bool include_reserved) { + if (!options_.max_users) { + return false; + } + if (const auto it = peers_.find(peer); it != peers_.end() && it->second.active) { + return false; + } + std::pmr::set users(memory_); + users.insert(self_user_id()); + for (const auto& [user, peer_ids] : users_.users()) { + users.insert(user); + } + if (include_reserved) { + for (const auto& [reserving, user] : reserved_) { + if (reserving != peer) { + users.insert(user); } - })); + } + } + const auto candidate = known_user(peer).value_or(peer); + return !users.contains(candidate) && users.size() >= *options_.max_users; + } + + /** Whether the room connects to a peer, 0.27.0's `canConnectPeer` without bans (Phase 3): not + * when its user is known and the room is full for it. */ + bool can_connect(std::string_view peer) { + return !(known_user(peer).has_value() && full_for(peer, true)); } - void on_rebinding_time(std::string_view peer) { - const auto it = rebinds_.find(peer); - if (it == rebinds_.end()) { + /** Admits a peer whose steps passed, 0.27.0's `tryAdmitPeer`: in a room with `max_users`, a + * peer not active takes a place for its user (`reserved_`) until it joins or goes, or is + * refused when the room is full for it. */ + bool try_admit(std::string_view peer) { + if (!options_.max_users) { + return true; + } + const auto it = peers_.find(peer); + if (it == peers_.end() || it->second.active) { + return true; + } + if (full_for(peer, true)) { + refuse_full(peer); + return false; + } + reserved_.insert_or_assign(std::pmr::string(it->first, memory_), + std::pmr::string(user_of(peer), memory_)); + return true; + } + + /** + * Refuses a peer because the room is full, 0.27.0's `rejectPeer` with `room full`: its user + * remembered, its handshake cleared, the ready frame of the refusal sent, then the peer goes, + * unannounced, its connection ended once the frame had its time to leave. + */ + void refuse_full(std::string_view peer_view) { + const auto it = peers_.find(peer_view); + if (it == peers_.end()) { return; } - it->second.refusing = false; - if (peers_.contains(peer)) { - return; // something bound it before its time + const std::pmr::string peer(it->first, memory_); + if (it->second.identity) { + remember_refused(peer, it->second.identity->user_id); + } + log_("room", "room full: refusing ", peer); + handshakes_->clear(peer); + reserved_.erase(peer); + send_internal("@_hsready", peer, protocol::payload_format::json, room_full_ready); + remove_peer(peer, "room full", true); + } + + /** + * Ends a link the room let go once its last frames had their time to leave, 0.27.0's + * `destroyAfterFlush`: 40 ms at least, then once the channel has drained, 150 ms at most. A + * link already closed ends at once. + */ + void flush_then_end(const std::shared_ptr& link, std::string_view reason) { + if (!link->live()) { + link->end(reason); + return; } - if (const auto c = app_->find(peer); c && c->advertised(token_)) { - it->second.dropping = false; - try_bind(peer, bind_event::rebinding); + const peer_link* const key = link.get(); + const auto& f = flushing_ + .try_emplace(key, + flushing_link{ + .link = link, + .reason = std::pmr::string(reason, memory_), + .grace = factory_.make_timer(memory_), + .cap = factory_.make_timer(memory_), + }) + .first->second; + const auto weak = weak_from_this(); + f.grace->start(flush_grace, bind([weak, key] { + const auto self = weak.lock(); + if (!self) { + return; + } + if (const auto at = self->flushing_.find(key); + at != self->flushing_.end()) { + at->second.link->wait_drained(self->bind_flushed(weak, key)); + } + })); + f.cap->start(flush_cap, bind([weak, key] { + if (const auto self = weak.lock()) { + self->end_flushed(key); + } + })); + } + + /** The handler that ends a flushing link once its channel drained. */ + handler bind_flushed(const std::weak_ptr& weak, + const peer_link* key) const { + return bind([weak, key](bool) { + if (const auto self = weak.lock()) { + self->end_flushed(key); + } + }); + } + + /** Ends a flushing link, once. */ + void end_flushed(const peer_link* key) { + const auto it = flushing_.find(key); + if (it == flushing_.end()) { + return; } + // A node handle's mapped value is mutable through a const handle. + const auto node = flushing_.extract(it); + node.mapped().grace->cancel(); + node.mapped().cap->cancel(); + node.mapped().link->end(node.mapped().reason); } - void remove_peer(std::string_view peer_view, std::string_view reason, end_kind kind) { + /** + * Lets a peer go: its user leaves with its last peer, its handshake, its transfers and its + * requests, its pings among them, end, and its negotiation is forgotten. + * + * @param refused Whether a full room refused it, or this side was refused by one or banned: + * its connection then ends once the refusal had its time to leave, and the room does not + * announce itself again for it, as 0.27.0's exitPeer with `roomFullErr` or `peerBannedErr`. + */ + void remove_peer(std::string_view peer_view, std::string_view reason, bool refused = false) { const auto it = peers_.find(peer_view); if (it == peers_.end()) { return; @@ -1493,78 +2932,119 @@ class room_impl final : public std::enable_shared_from_this, public r const auto node = peers_.extract(it); std::pmr::string peer = std::move(node.key()); auto& state = node.mapped(); + // Its user leaves with its last peer, as 0.27.0 counts a user's peers. + std::pmr::string user( + state.identity ? std::string_view(state.identity->user_id) : std::string_view(peer), + memory_); + const bool last_of_user = + state.active && users_.remove(peer).has_value() && user != self_user_id(); log_("room", "peer ", peer, " gone: ", reason); - let_go(state, kind); - for (auto& ping : state.pings) { - complete(std::move(ping.handler), make_error_code(error::peer_disconnected), - std::chrono::milliseconds{}); + handshakes_->clear(peer); + reserved_.erase(peer); + // The connection ends with the peer, as 0.27.0 destroys a peer it lets go; at its own end, + // it has ended already. + if (refused && !left_) { + flush_then_end(state.link, reason); + } else { + state.link->end(reason); } wire_->clear_peer(peer, make_error_code(error::peer_disconnected)); + fail_requests(peer, make_error_code(error::peer_disconnected)); if (left_) { return; } - if ((kind == end_kind::kick || kind == end_kind::peer_left) && app_->find(peer)) { - schedule_rebinding(peer, kind == end_kind::kick); - } + // The peer's next announcement or offer negotiates a new connection, as 0.27.0's + // reannounceAfterDisconnect has the room met again. signaling_->forget(peer); - // Announcements find peers without a connection; over a live one every rebinding goes - // through it. - if (!app_->find(peer)) { + if (!refused) { strategy_->restart_announcements(); } - if (state.active && on_leave_) { - post([f = on_leave_, peer = std::move(peer)] { (*f)(peer); }); + if (state.active) { + // As a join, a leave is not reported once the room is left. + post([weak = weak_from_this(), peer = std::move(peer), user = std::move(user), + last_of_user] { + const auto self = weak.lock(); + if (!self || self->left_) { + return; + } + self->peer_leave_.emit({.peer_id = peer, .user_id = user}); + if (last_of_user) { + self->user_leave_.emit({.user_id = user, .peer_id = peer}); + } + }); } } - /** Says the room is left on every live connection of the app, lets every peer go as a - * departure, and leaves the app: its registry, and once, its users. - * - * Tip: the presence goes first, since a departure of a connection's last room ends it at once - * when the app's idle time is 0. */ + /** Lets every peer go, its connection ended, and leaves the app: its registry, and once, its + * users. */ void close_everything() { leave_timer_.reset(); - rebinds_.clear(); - const auto connections = app_->live_connections(); - for (const auto& c : connections) { - c->send_presence(token_, false); - } auto peers = std::move(peers_); peers_.clear(); + users_.clear(); // without leaves, as 0.27.0 reports none once its room is leaving + reserved_.clear(); + // Swapped out, both in the room's resource: a move assignment of the map would assign its + // entries' std::pmr::string, which may allocate. + decltype(flushing_) flushing_links(memory_); + flushing_links.swap(flushing_); + for (auto& [key, flushing] : flushing_links) { + flushing.grace->cancel(); + flushing.cap->cancel(); + flushing.link->end("the room is left"); + } for (auto& [id, state] : peers) { - let_go(state, end_kind::room_end); - for (auto& ping : state.pings) { - complete(std::move(ping.handler), make_error_code(error::room_left), - std::chrono::milliseconds{}); - } + handshakes_->clear(id); + state.link->end("the room is left"); if (wire_) { wire_->clear_peer(id, make_error_code(error::room_left)); } } - // A log callback may have left this room during adoption, before it had a binding - // to detach. Its connection still gets an idle deadline after the farewell withdrawal. - if (const auto c = departing_connection_.lock()) { - c->idle_if_unused(app_->idle_timeout()); - } - departing_connection_.reset(); + // Every listener goes, as 0.27.0 clears its emitters and its actions' listeners once its + // room is left. From a post: an emission under way finishes, as 0.27.0's leave clears only + // once it completes, and what was posted to the listeners before is delivered, as 0.27.0 + // delivers it at once; a join or a leave posted before checks `left_` itself. + post([weak = weak_from_this()] { + if (const auto self = weak.lock()) { + self->clear_listeners(); + } + }); for (auto& [name, slot] : actions_) { for (auto& receiver : slot.receivers) { complete(std::move(receiver), make_error_code(error::room_left), incoming{}); } slot.receivers.clear(); + // What waited for a receive or a listener goes too, as 0.27.0 drops each peer's + // pending data when its room is left: a listener added later gets none of it. + slot.queue.clear(); } + fail_requests({}, make_error_code(error::room_left)); if (signaling_) { signaling_->close(); } if (strategy_) { strategy_->stop(); } - app_->unregister_room(token_, this); + app_->unregister_room(room_id_, this); if (!std::exchange(released_, true)) { app_->release_user(); } } + /** Removes every listener of the room and of its actions: their subscriptions are inactive. */ + void clear_listeners() noexcept { + peer_join_.clear(); + peer_leave_.clear(); + user_join_.clear(); + user_leave_.clear(); + errors_.clear(); + for (auto& [name, slot] : actions_) { + slot.messages.clear(); + slot.requests.clear(); + slot.gate.clear(); + slot.progress.clear(); + } + } + std::pmr::memory_resource* memory_; std::shared_ptr app_; executor_type ex_; @@ -1572,22 +3052,33 @@ class room_impl final : public std::enable_shared_from_this, public r logger log_; room_options options_; std::pmr::string room_id_; - std::pmr::string token_; std::pmr::string root_topic_; std::pmr::string self_topic_; - std::shared_ptr sealer_; + std::shared_ptr handshakes_; std::shared_ptr wire_; std::shared_ptr signaling_; std::shared_ptr strategy_; std::pmr::map> peers_; - std::pmr::map> rebinds_; + user_table users_; // the active peers', by user + // The users of the admissions under way, by peer, 0.27.0's reservedAdmissionUsers. + std::pmr::map> reserved_; + // The users of the peers refused while full, the most recently used first, and by peer, each + // key a view of its entry's peer in the list, which owns it. + std::pmr::list> refused_order_; + std::pmr::map>::iterator, + std::less<>> + refused_; + // The links let go, flushing, by identity. + std::pmr::map flushing_; std::pmr::map> actions_; - std::shared_ptr> on_join_; - std::shared_ptr> on_leave_; - std::shared_ptr> - on_error_; + std::pmr::map> requests_; + listeners peer_join_; + listeners peer_leave_; + listeners user_join_; + listeners user_leave_; + listeners errors_; std::shared_ptr leave_timer_; - std::weak_ptr departing_connection_; std::pmr::vector> leave_completions_; bool ended_ = false; bool left_ = false; @@ -1599,24 +3090,28 @@ class room_impl final : public std::enable_shared_from_this, public r template class action; +template +class request_action; + /** * A room joined over Trystero's Nostr strategy, what Trystero's `joinRoom` returns. * * `app::join` makes it, joined; `async_leave` leaves with Trystero's farewell, and destroying it - * leaves at once. Its peers meet over the relays, connect over WebRTC through the connections its - * app shares between its rooms, and exchange the messages of the actions it makes, wire compatible - * with Trystero's JavaScript. + * leaves at once. Its peers meet over the relays, connect over WebRTC, each room with a connection + * of its own to each peer, as 0.27.0's rooms do, and exchange the messages of the actions it makes, + * written bare on the connection. A peer joins once 0.27.0's identity handshake has bound its + * endpoint and user keys to both DTLS fingerprints, and its user is the one it proved. * - * Every room uses its app's immutable password. Initial sealed signaling authenticates that - * domain before a connection is adopted. The unchanged JS room handshake verifies only at the - * lower id; different passwords require separate apps with distinct self ids. + * Every room uses its app's immutable password, under which the signals that make its connections + * are sealed: as in 0.27.0, the sealing alone keeps peers of another password out, which never + * connect; different passwords require separate apps. * * Tip: every handler the room calls, and every completion, runs on its app's executor. The views a * handler receives are valid for the duration of the call. Every allocation of the room goes - * through its effective `room_options::memory`, the app's resource when null; shared connections - * and received frames use `app_config::memory`. A completion handler is allocated as its own - * associated allocator says. Destroying the room leaves operations pending on its executor, so - * both resources must outlive those operations and every retained value allocated in them. + * through its effective `room_options::memory`, the app's resource when null, its connections and + * the frames received on them included. A completion handler is allocated as its own associated + * allocator says. Destroying the room leaves operations pending on its executor, so both resources + * must outlive those operations and every retained value allocated in them. * * @see "Rooms and actions", in the guide. */ @@ -1642,9 +3137,8 @@ class room { * Leaves the membership this room held at once, as the destructor does, then takes the * membership of the room moved from, which may then only be destroyed or assigned. * - * Every peer of the membership left is told, the room lets go of the app's connections, which - * the app's other rooms may go on using, and every operation pending on it completes with - * `error::room_left`, even while an `action` of it lives. + * Every peer of the membership left is told, the room's connections end, and every operation + * pending on it completes with `error::room_left`, even while an `action` of it lives. * * @param other The room moved from. * @return This room. @@ -1662,9 +3156,8 @@ class room { // Leaving sends each peer Trystero's farewell, whose frames are allocated in the room's // resource: a resource that fails then ends the program, as in any destructor. /** - * Leaves at once, without the farewell's grace period: every peer is told, the room lets go of - * the app's connections, which the app's other rooms may go on using, and every pending - * operation completes with `error::room_left`. + * Leaves at once, without the farewell's grace period: every peer is told, the room's + * connections end, and every pending operation completes with `error::room_left`. */ ~room() { // NOLINT(bugprone-exception-escape) if (impl_) { @@ -1697,65 +3190,161 @@ class room { } /** - * The peers whose handshake completed, Trystero's `getPeers`. + * This peer in the room, Trystero's `getSelf`, at once: the app's identity exists from its + * construction on. * - * @return Their ids, in the room's resource. + * @return This peer's and its user's ids, the room's ids and roles, whose views are valid as + * long as the room. */ - [[nodiscard]] std::pmr::vector peers() const { return impl_->active_peers(); } + [[nodiscard]] self_info self() const { return impl_->self(); } /** - * Sets what is called with each peer that joins, once its handshake completes, Trystero's + * The users with a peer in the room, Trystero's `getUsers`: this peer's own user is left out. + * + * @return Each user by id, with its active peers in the order they became active, in the + * room's resource. + */ + [[nodiscard]] std::pmr::map> users() const { + return impl_->users(); + } + + /** + * The peers whose handshake completed, Trystero's `getPeers` without their connections. + * + * @return Each peer by id, with its user, in the room's resource. + */ + [[nodiscard]] std::pmr::map> peers() const { + return impl_->peers(); + } + + /** + * Adds a listener of each peer that joins, once its handshake completes, Trystero's * `onPeerJoin`. * - * @tparam F A callable with a `std::string_view`, the peer's id, valid for the call. - * @param f The handler, kept in the room's resource; it replaces the one set before. + * Listeners run in the order added, each join reported from the room's executor; one added + * while a join is reported waits for the next, and one removed before its turn does not run. + * + * @tparam F A callable with a `const peer_event&`, whose views are valid for the call. + * @param f The listener, kept in the room's resource beside those added before. + * @param options `once` removes it before its first run; `replay` calls it first, within this + * call, with each peer already joined. + * @return Its subscription, which requires the room's resource to outlive it; destroying it + * leaves the listener. */ template - requires std::is_invocable_v - void on_peer_join(F&& f) { - impl_->on_peer_join(impl_->bind(std::forward(f))); + requires std::is_invocable_v + subscription on_peer_join(F&& f, listen_options options = {}) { + const auto impl = impl_; // the replay may destroy or reassign this handle + return impl->on_peer_join(impl->bind(std::forward(f)), options); } /** - * Sets what is called with each joined peer that leaves, Trystero's `onPeerLeave`. + * Adds a listener of each joined peer that leaves, Trystero's `onPeerLeave`. * - * @tparam F A callable with a `std::string_view`, the peer's id, valid for the call. - * @param f The handler, kept in the room's resource; it replaces the one set before. + * @tparam F A callable with a `const peer_event&`, whose views are valid for the call. + * @param f The listener, kept in the room's resource beside those added before. + * @param options `once` removes it before its first run; `replay` is ignored. + * @return Its subscription, which requires the room's resource to outlive it; destroying it + * leaves the listener. */ template - requires std::is_invocable_v - void on_peer_leave(F&& f) { - impl_->on_peer_leave(impl_->bind(std::forward(f))); + requires std::is_invocable_v + subscription on_peer_leave(F&& f, listen_options options = {}) { + return impl_->on_peer_leave(impl_->bind(std::forward(f)), + options); } /** - * Sets what is called with each problem with one peer that the room handled itself, as a - * wrong password or a timed-out handshake, Trystero's `onPeerError`. + * Adds a listener of each user that joins, when its first peer joins, after that peer's + * `on_peer_join`, Trystero's `onUserJoin`; a peer of this peer's own user makes no user join. + * + * A peer's user is the one its identity handshake verified: the peers of apps that present + * one `user_identity` are one user. * - * Signals that do not open with the room key (`error::wrong_password`) are reported once per - * negotiation, and paced: the first of a quiet 10 s at once, with its peer, and the others of - * those 10 s in one report, with an empty peer id and a description that starts with their - * number, since anyone who reads the relays can send them from any number of fresh ids. A part - * of the configuration the app set aside is reported to `app::on_error`, not here. + * @tparam F A callable with a `const user_event&`, whose views are valid for the call. + * @param f The listener, kept in the room's resource beside those added before. + * @param options `once` removes it before its first run; `replay` calls it first, within this + * call, with each user already joined. + * @return Its subscription, which requires the room's resource to outlive it; destroying it + * leaves the listener. + */ + template + requires std::is_invocable_v + subscription on_user_join(F&& f, listen_options options = {}) { + const auto impl = impl_; // the replay may destroy or reassign this handle + return impl->on_user_join(impl->bind(std::forward(f)), options); + } + + /** + * Adds a listener of each user that leaves, when its last peer leaves, after that peer's + * `on_peer_leave`, Trystero's `onUserLeave`; this peer's own user never leaves. * - * @tparam F A callable with the peer's id, the @ref error and a description, the views valid - * for the call. - * @param f The handler, kept in the room's resource; it replaces the one set before. + * @tparam F A callable with a `const user_event&`, whose views are valid for the call. + * @param f The listener, kept in the room's resource beside those added before. + * @param options `once` removes it before its first run; `replay` is ignored. + * @return Its subscription, which requires the room's resource to outlive it; destroying it + * leaves the listener. */ template - requires std::is_invocable_v - void on_error(F&& f) { - impl_->on_error( - impl_->bind( - std::forward(f))); + requires std::is_invocable_v + subscription on_user_leave(F&& f, listen_options options = {}) { + return impl_->on_user_leave(impl_->bind(std::forward(f)), + options); + } + + /** + * Adds a listener of each problem the room handled itself, Trystero's `onError`: each report + * is a @ref room_error, with its code, its message, the app's and the room's ids, and the + * context Trystero gives that code. + * + * Nothing is reported once the room is being left. + * + * | Code | When | + * | `decrypt_failed` | a peer's offer or answer did not open with the room key: | + * | | another password, or a corrupted or forged signal; at most | + * | | once a minute per peer and stage, as Trystero reports it | + * | `peer_connect_failed` | the connection with a peer did not open after the exchange | + * | | of descriptions; once per offer or answer | + * | `relay_failed` | the first connection of every relay failed before any | + * | | opened, or no relay took its first announcement and the | + * | | others failed to open; once, with the text of the failure | + * | | that settled it, as 0.27.0 gives it | + * | `peer_error` | a peer's frame was malformed or against the protocol, or | + * | | it sent a `\@_response` none waits for; the message says | + * | | which, as 0.27.0's, and the peer is told to leave and goes | + * | `banned` | a peer refused this room's user with its ready message; | + * | | its reason is the message when it gave one, and the room | + * | | leaves the peer, which it may meet again | + * | `handshake_failed` | a connected peer's handshake failed, with 0.27.0's reason | + * | | as its message, as "handshake timed out after 10000ms"; | + * | | the peer is told to leave, and goes | + * | `backend_failure` | the backend made no connection for a peer, or the room's | + * | | keys could not be derived | + * + * A part of the configuration the app set aside is reported to `app::on_error`, not here. + * + * @tparam F A callable with a `const room_error&`, whose views are valid for the call. + * @param f The listener, kept in the room's resource beside those added before. + * @param options `once` removes it before its first run; `replay` is ignored. + * @return Its subscription, which requires the room's resource to outlive it; destroying it + * leaves the listener. + */ + template + requires std::is_invocable_v + subscription on_error(F&& f, listen_options options = {}) { + return impl_->on_error(impl_->bind(std::forward(f)), options); } /** * Makes an action of this room, Trystero's `makeAction`: a named channel of messages. * - * Frames of the action that arrived before it was made, which the room keeps for a while (64 - * per peer, for 120 s), are delivered to it. + * Frames of the action that arrived before it was made are dropped, and its transfers offered + * meanwhile rejected, as Trystero's are: a room makes the actions it receives right after it + * is joined. A name is made again as often as wanted, each handle the same action; a name made + * first by `make_request_action` cannot be made a message action, where Trystero throws "action + * type cannot be redefined": the handle's sends and receives complete with + * `error::action_redefined`, its `on_receive` returns it, and its other listeners are not + * added. * * @tparam T The type of its messages: `std::string`, `std::pmr::string`, `std::string_view`, * `webcpp::document::document`, `webcpp::document::pmr::document`, @ref bytes, @ref pmr_bytes, @@ -1767,15 +3356,40 @@ class room { template action make_action(std::string_view name); + /** + * Makes a request action of this room, Trystero's `makeAction` with `kind: 'request'`: a named + * channel of requests, each answered by the peer asked. + * + * A request travels as a message of the action whose metadata is `{"r":,"m":}`, + * and its answer as the internal action `\@_response`, as 0.27.0's do. A name is a request + * action or a message action, not both: a name made first by `make_action` cannot be made a + * request action, where Trystero throws "action type cannot be redefined": the handle's + * requests complete with `error::action_redefined`, its `on_request` and `on_receive` return + * it, and its progress listeners are not added. + * + * @tparam T The type of its requests, one of those `make_action` lists. + * @tparam R The type of its answers, one of them that owns its storage. + * @param name The action's name, 1 to 32 UTF-8 bytes without NUL; with another, every request + * fails with `error::invalid_action_name`. + * @return The action. + */ + template + request_action make_request_action(std::string_view name); + /** * Measures the round trip to a peer, Trystero's `ping`. * - * Completes with `(error_code, std::chrono::milliseconds)`: the time from sending `\@_ping` - * to receiving its `\@_pong`, or `error::no_such_peer` when the peer is not active, - * `error::peer_disconnected` when it leaves first, and `error::room_left`. + * A ping is 0.27.0's internal request action `\@_ping`: a request of an empty text, which the + * peer answers with an empty text through `\@_response`. + * + * Completes with `(error_code, std::chrono::milliseconds)`: the time from sending the request + * to receiving its answer, or `error::no_such_peer` when the peer is not active, + * `error::request_rejected` when it refuses the request, `error::peer_disconnected` when it + * leaves first, and `error::room_left`. * * @tparam CompletionToken An Asio completion token for `void(error_code, milliseconds)`. - * @param peer The peer's id, copied at the call, so a deferred operation does not depend on + * @param peer The peer's id, or a user's, whose active peer of the lowest id is asked, as + * 0.27.0's request picks it; copied at the call, so a deferred operation does not depend on * the caller's string. * @param token The completion token. * @return What the token's initiation returns. @@ -1795,10 +3409,9 @@ class room { /** * Says goodbye to every peer and closes everything, Trystero's `leave`. * - * Each peer is sent `\@_leave`, and 99 ms later, as Trystero waits, the room lets go of the - * app's connections, which the app's other rooms may go on using, and every pending operation - * completes with `error::room_left`. Completes with `(error_code)`, empty, also when the room - * was already left. + * Each peer is sent `\@_leave`, and 99 ms later, as Trystero waits, the room's connections + * end, and every pending operation completes with `error::room_left`. Completes with + * `(error_code)`, empty, also when the room was already left. * * @tparam CompletionToken An Asio completion token for `void(error_code)`. * @param token The completion token. @@ -1824,13 +3437,14 @@ class room { }; /** - * A named channel of messages of type `T` within a room, wire compatible with what Trystero's - * `makeAction` returns. + * A named channel of messages of type `T` within a room, what Trystero's `makeAction` returns. * - * Messages arrive at the handler `on_message` set, or, without one, queue for `async_receive`, up - * to 1024 per action, the oldest dropped first. A message of another format than `T`'s is not - * delivered to the handler. A room makes it with `room::make_action`, and it keeps the room's - * state alive. + * Messages arrive at the listeners `on_message` adds, or, without one, at `async_receive`. Until + * the action has a listener or was first awaited, its messages wait as Trystero's wait for a + * listener, 32 per sender for 10 s, the oldest dropped first; once awaited, those no receive + * waits for queue for the next, up to 1024, the oldest dropped first. A message + * of another format than `T`'s is not delivered to a listener. A room makes it with + * `room::make_action`, and it keeps the room's state alive. * * @tparam T The type of its messages, one of those `room::make_action` lists. * @see "Rooms and actions", in the guide. @@ -1846,47 +3460,117 @@ class action { [[nodiscard]] std::string_view name() const { return name_; } /** - * Sets what is called with every message, Trystero's `onMessage`. + * Adds a listener of every message, Trystero's `onMessage`. * - * Messages that queued while the action had no handler are delivered to it first. + * Listeners run in the order added, each message reported from the room's executor; one added + * while a message is reported waits for the next, and one removed before its turn does not + * run. Messages that queued for `async_receive`, and those that waited for a listener, are + * delivered first. Each listener decodes the message: with several, each takes its own copy. * * @tparam F A callable with a `T` and a `const message_info&`; with a view type, the view is - * valid for the duration of the call. A JSON document is the handler's to keep: a handle of its - * values refers to the document object, as every handle of webcpp::document does, so moving the - * document invalidates it. - * @param f The handler, kept in the room's resource; it replaces the one set before. + * valid for the duration of the call. A JSON document is the listener's to keep: a handle of + * its values refers to the document object, as every handle of webcpp::document does, so moving + * the document invalidates it. + * @param f The listener, kept in the room's resource beside those added before. + * @param options `once` removes it before its first run; `replay` is ignored. + * @return Its subscription, which requires the room's resource to outlive it; destroying it + * leaves the listener. It is inactive, and nothing is added, when the name was made a request + * action first. */ template requires std::is_invocable_v - void on_message(F&& f) { - impl_->set_action_handler( + subscription on_message(F&& f, listen_options options = {}) { + if (redefined_) { + return {}; + } + // Held for the call: delivering what waited may run a receive gate, which may release the + // room's last handles, this one among them. + const auto impl = impl_; + return impl->add_message_listener( name_, - impl_->bind( - [f = std::forward(f), to = impl_->decoding()](detail::incoming& m) mutable { + impl->template bind( + [f = std::forward(f), to = impl->decoding()](detail::incoming& m) mutable { // The metadata is read before decoding: a binary payload takes the buffer the // metadata lives in. const message_info info{ - .from = std::move(m.peer), + .from = m.shared ? std::pmr::string(m.peer, to.memory) : std::move(m.peer), .metadata = std::pmr::string(m.metadata(), to.memory), }; if (auto value = detail::payload_traits::decode(m, to)) { f(std::move(*value), info); } - })); + }), + options); + } + + /** + * Sets the action's receive gate, Trystero's `onReceive`: asked about each message as it + * arrives, before the action receives it, with its size and metadata. + * + * It runs during the frame's processing, as Trystero's runs, rather than from a post: its + * answer decides at once. A refused inline message is dropped; a refused transfer is rejected + * with "payload rejected by receiver", and its sender's send completes with + * `error::transfer_rejected`. A message that waited for a listener before the gate was set is + * asked before it is delivered. + * + * @tparam F A callable with a `const receive_info&`, whose views are valid for the call, + * returning whether to receive the message. + * @param f The gate, kept in the room's resource. + * @param options `once` removes it before its first run; `replay` is ignored. + * @return Its subscription, which requires the room's resource to outlive it; + * `error::already_subscribed` while a gate is in place, or `error::action_redefined` when the + * name was made the other kind of action first. + */ + template + requires std::is_invocable_r_v + [[nodiscard]] boost::system::result on_receive(F&& f, + listen_options options = {}) { + if (redefined_) { + return error::action_redefined; + } + const auto impl = impl_; // delivering what waited may release this handle + return impl->add_receive_gate( + name_, impl->template bind(std::forward(f)), options); + } + + /** + * Adds a listener of the progress of each message received, Trystero's `onReceiveProgress`: + * the share of a transfer received after each chunk but the last, then 1 once the message is + * whole, reported from the room's executor. + * + * @tparam F A callable with a `double` from 0 to 1 and a `const progress_info&`, whose views + * are valid for the call. + * @param f The listener, kept in the room's resource beside those added before. + * @param options `once` removes it before its first run; `replay` is ignored. + * @return Its subscription, which requires the room's resource to outlive it; destroying it + * leaves the listener. It is inactive, and nothing is added, when the name was made the other + * kind of action first. + */ + template + requires std::is_invocable_v + subscription on_receive_progress(F&& f, listen_options options = {}) { + if (redefined_) { + return {}; + } + return impl_->add_progress_listener( + name_, impl_->bind(std::forward(f)), options); } // T is the action's type, taken by value and moved into its encoding, which keeps a value // that owns its storage; a JSON document is written there at once, from a reference. /** - * Sends a message to `options.targets`, or every active peer, Trystero's `send`. + * Sends a message to `options.targets`, each a peer or a user, or to every active peer, + * Trystero's `send`; to a room without peers, it succeeds. * * A payload that fits one frame is sent inline; a larger one is offered, accepted by each * receiver, and sent in chunks. Completes with `(error_code)` once each target's local data * channel has taken the inline frame, or the last chunk of a transfer the receiver accepted, * as Trystero's `send` resolves: nothing confirms that the receiver has the message. It * completes with the first failure: `error::invalid_action_name`, `error::metadata_too_large`, - * `error::no_such_peer`, `error::transfer_rejected`, `error::transfer_timed_out`, - * `error::channel_stalled`, `error::peer_disconnected` or `error::room_left`. + * `error::not_connected` for a target that is neither an active peer nor a user of one, + * `error::transfer_rejected`, `error::transfer_timed_out`, + * `error::channel_stalled`, `error::peer_disconnected` or `error::room_left`; at once with + * `error::action_redefined` when the name was made a request action first. * * @tparam CompletionToken An Asio completion token for `void(error_code)`. * @param value The message, taken at the call: moved when `T` owns its storage, copied once @@ -1900,8 +3584,12 @@ class action { auto async_send(T value, send_options options, // NOLINT(performance-unnecessary-value-param) CompletionToken&& token) { return webcpp::asio::async_initiate( - [impl = impl_, name = std::pmr::string(name_, impl_->memory())]( + [impl = impl_, name = std::pmr::string(name_, impl_->memory()), redefined = redefined_]( auto handler, detail::encoded_payload payload, const send_options& options) { + if (redefined) { + impl->complete(std::move(handler), make_error_code(error::action_redefined)); + return; + } impl->send( name, std::move(payload), options, impl->template erase(std::move(handler))); @@ -1924,12 +3612,16 @@ class action { } /** - * Receives the next message, when no handler is set: the oldest queued, or the next to arrive. + * Receives the next message, when no listener is in place: the oldest queued, or the next to + * arrive. + * + * From the first call on, the action listens: its messages queue for the next. * * Completes with `(error_code, T, message_info)`; a message of another payload format than * `T`'s, or a JSON text that does not parse, completes with `error::transfer_rejected` and an * empty value, which allocates nothing (a JSON document that holds nothing, whose root reads - * `undefined`), and leaving the room with `error::room_left`. + * `undefined`), leaving the room with `error::room_left`, and at once with + * `error::action_redefined` when the name was made a request action first. * `T` must own its storage: a view would outlive the message. A JSON document is the * handler's: a handle of its values refers to the document object, so moving the document * invalidates it. @@ -1944,7 +3636,17 @@ class action { "a received view would outlive the message: await an owning type"); return webcpp::asio::async_initiate( - [impl = impl_, name = std::pmr::string(name_, impl_->memory())](auto handler) { + [impl = impl_, name = std::pmr::string(name_, impl_->memory()), + redefined = redefined_](auto handler) { + if (redefined) { + impl->complete(std::move(handler), make_error_code(error::action_redefined), + detail::empty_payload(impl->memory()), + message_info{ + .from = std::pmr::string(impl->memory()), + .metadata = std::pmr::string(impl->memory()), + }); + return; + } // The decoding step is allocated as the user's handler is, which it carries. const auto allocator = webcpp::asio::get_associated_allocator(handler); impl->receive( @@ -1976,12 +3678,225 @@ class action { friend class room; action(std::shared_ptr impl, std::string_view name) - : impl_(std::move(impl)), name_(name, impl_->memory()) { - impl_->add_action(name_); + : impl_(std::move(impl)), + name_(name, impl_->memory()), + redefined_(!impl_->add_action(name_, false)) {} + + std::shared_ptr impl_; + std::pmr::string name_; + /** Whether the name was made a request action first: every operation fails. */ + bool redefined_; +}; + +/** + * A named channel of requests of type `T`, each answered with an `R` by the peer asked, within a + * room, what Trystero's `makeAction` returns for `kind: 'request'`. + * + * The peer asked answers with the listener `on_request` sets. While it has none, requests wait as + * Trystero's messages wait for a listener, 32 per sender for 10 s. A room makes it with + * `room::make_request_action`, and it keeps the room's state alive. + * + * @tparam T The type of its requests, one of those `room::make_action` lists. + * @tparam R The type of its answers, one of those that own their storage. + * @see "Rooms and actions", in the guide. + */ +template +class request_action { +public: + static_assert(detail::payload_traits::owning, + "an answer completes a request later: answer with an owning type"); + + /** + * The action's name. + * + * @return The name, valid as long as the action. + */ + [[nodiscard]] std::string_view name() const { return name_; } + + /** + * Sets the listener that answers each request, Trystero's `onRequest`. + * + * It is called from the room's executor with the request and who sent it, and its result is + * the answer: an `R`, or a `boost::system::result` whose error refuses the request with the + * error's message, which the requester's request completes with as `error::request_rejected`. + * A request of another format than `T`'s is refused. + * + * @tparam F A callable with a `T` and a `const message_info&`, whose metadata is the sender's + * own, returning an `R` or a `boost::system::result`; with a view type, the view is valid + * for the duration of the call. + * @param f The listener, kept in the room's resource. + * @param options `once` removes it before its first run; `replay` is ignored. + * @return Its subscription, which requires the room's resource to outlive it; + * `error::already_subscribed` while a listener is in place, or `error::action_redefined` when + * the name was made a message action first. + */ + template + requires std::is_invocable_v + [[nodiscard]] boost::system::result on_request(F&& f, + listen_options options = {}) { + using answer = std::invoke_result_t; + static_assert( + std::is_convertible_v || std::is_same_v>, + "a request listener returns an R or a boost::system::result"); + if (redefined_) { + return error::action_redefined; + } + // Held for the call: delivering what waited may run a receive gate, which may release the + // room's last handles, this one among them. + const auto impl = impl_; + // The listener is the room's own: it reaches its room through a plain pointer, since a + // shared one would keep the room alive through itself. + detail::room_impl* const room = impl.get(); + return impl->add_request_listener( + name_, + impl->template bind( + [f = std::forward(f), room, to = impl->decoding()]( + detail::incoming& m, const detail::request_envelope& envelope) mutable { + const message_info info{ + .from = std::pmr::string(m.peer, to.memory), + .metadata = std::pmr::string(envelope.metadata, to.memory), + }; + auto value = detail::payload_traits::decode(m, to); + if (!value) { + room->respond_error(info.from, envelope.id, + make_error_code(error::transfer_rejected).message()); + return; + } + if constexpr (std::is_same_v>) { + auto r = f(std::move(*value), info); + if (!r) { + room->respond_error(info.from, envelope.id, r.error().message()); + return; + } + room->respond(info.from, envelope.id, + detail::payload_traits::encode(std::move(*r), to.memory)); + } else { + room->respond(info.from, envelope.id, + detail::payload_traits::encode(f(std::move(*value), info), + to.memory)); + } + }), + options); } + /** + * Sets the action's receive gate, Trystero's `onReceive`: asked about each request as it + * arrives, as `action::on_receive` asks. + * + * A refused request is answered with "payload rejected by receiver". + * + * @tparam F A callable with a `const receive_info&`, whose metadata is the sender's own, + * returning whether to receive the request. + * @param f The gate, kept in the room's resource. + * @param options `once` removes it before its first run; `replay` is ignored. + * @return Its subscription, which requires the room's resource to outlive it; + * `error::already_subscribed` while a gate is in place, or `error::action_redefined` when the + * name was made the other kind of action first. + */ + template + requires std::is_invocable_r_v + [[nodiscard]] boost::system::result on_receive(F&& f, + listen_options options = {}) { + if (redefined_) { + return error::action_redefined; + } + const auto impl = impl_; // delivering what waited may release this handle + return impl->add_receive_gate( + name_, impl->template bind(std::forward(f)), options); + } + + /** + * Adds a listener of the progress of each request received, Trystero's `onReceiveProgress`, + * as `action::on_receive_progress` reports it. + * + * @tparam F A callable with a `double` from 0 to 1 and a `const progress_info&`. + * @param f The listener, kept in the room's resource beside those added before. + * @param options `once` removes it before its first run; `replay` is ignored. + * @return Its subscription, which requires the room's resource to outlive it; destroying it + * leaves the listener. It is inactive, and nothing is added, when the name was made the other + * kind of action first. + */ + template + requires std::is_invocable_v + subscription on_receive_progress(F&& f, listen_options options = {}) { + if (redefined_) { + return {}; + } + return impl_->add_progress_listener( + name_, impl_->bind(std::forward(f)), options); + } + + // T is the action's type, taken by value and moved into its encoding, as `action::async_send` + // takes it. + /** + * Asks one peer, or one peer of a user, Trystero's `request`. + * + * Completes with `(error_code, R)`: the answer, as Trystero's promise resolves with it; or + * `error::not_connected` when the target is neither an active peer nor a user of one, + * `error::request_rejected` when the peer refused the request (its listener's error, no + * listener, or a refused transfer), `error::request_timed_out` after `options.timeout`, + * `error::transfer_rejected` for an answer of another format than `R`'s, + * `error::peer_disconnected` when the peer leaves first, `error::room_left`, the failure of + * the request's send, or at once `error::action_redefined` when the name was made a message + * action first. An unsuccessful completion carries an empty answer. + * + * Unlike Trystero's rejection, which carries the reason the peer gave, a refusal completes with + * the code alone: the room logs the reason, under "action". + * + * @tparam CompletionToken An Asio completion token for `void(error_code, R)`. + * @param value The request, taken at the call as `action::async_send` takes a message. + * @param options The peer asked, the metadata, and the timeout. + * @param token The completion token. + * @return What the token's initiation returns. + */ + template + auto async_request(T value, + request_options options, // NOLINT(performance-unnecessary-value-param) + CompletionToken&& token) { + return webcpp::asio::async_initiate( + [impl = impl_, name = std::pmr::string(name_, impl_->memory()), redefined = redefined_]( + auto handler, detail::encoded_payload payload, const request_options& options) { + if (redefined) { + impl->complete(std::move(handler), make_error_code(error::action_redefined), + detail::empty_payload(impl->memory())); + return; + } + // The decoding step is allocated as the user's handler is, which it carries. + const auto allocator = webcpp::asio::get_associated_allocator(handler); + impl->request( + name, std::move(payload), options, + impl->template erase( + webcpp::asio::bind_allocator( + allocator, + [impl, handler = std::move(handler)](boost::system::error_code ec, + detail::incoming m) mutable { + const detail::decoding to = impl->decoding(); + auto answer = + ec ? std::nullopt : detail::payload_traits::decode(m, to); + if (!ec && !answer) { + ec = make_error_code(error::transfer_rejected); + } + impl->complete(std::move(handler), ec, + answer ? std::move(*answer) + : detail::empty_payload(to.memory)); + }))); + }, + token, detail::payload_traits::encode(std::move(value), impl_->memory()), + std::move(options)); + } + +private: + friend class room; + + request_action(std::shared_ptr impl, std::string_view name) + : impl_(std::move(impl)), + name_(name, impl_->memory()), + redefined_(!impl_->add_action(name_, true)) {} + std::shared_ptr impl_; std::pmr::string name_; + /** Whether the name was made a message action first: every operation fails. */ + bool redefined_; }; template @@ -1989,6 +3904,11 @@ action room::make_action(std::string_view name) { return action(impl_, name); } +template +request_action room::make_request_action(std::string_view name) { + return request_action(impl_, name); +} + } // namespace webcpp::trystero #endif diff --git a/include/webcpp/trystero/room_error.hpp b/include/webcpp/trystero/room_error.hpp new file mode 100644 index 0000000..0afe37f --- /dev/null +++ b/include/webcpp/trystero/room_error.hpp @@ -0,0 +1,105 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_TRYSTERO_ROOM_ERROR_HPP +#define WEBCPP_TRYSTERO_ROOM_ERROR_HPP + +#include + +#include + +#include + +#include +#include + +namespace webcpp::trystero { + +/** + * The kind of signal that did not open, the `stage` of Trystero's `decrypt-failed` room error. + */ +enum class signal_stage { + /** An offer. */ + offer, + /** An answer. */ + answer, +}; + +/** + * A problem a room or an app handled itself, what `room::on_error` and `app::on_error` report, + * Trystero's `RoomError` without its `cause`. + * + * Every report carries a code, its message, and the app's and the room's ids; the other members + * are set only for the codes Trystero sets them for, and are empty otherwise. + * + * | Code | Members set | + * | `decrypt_failed` | `peer_id`, `stage` | + * | `peer_connect_failed` | `peer_id`, `turn_configured` | + * | `room_full` | `peer_id` | + * | `banned` | `peer_id` and `reason`, when the peer gave them | + * | `plugin_failed` | `plugin`, when the plugin is known | + * | `handshake_failed` | `peer_id` | + * | `peer_error` | `peer_id` | + * + * The views are valid for the duration of the listener's call. + */ +struct room_error { + /** What happened, an @ref error; @ref room_error_code_name gives Trystero's name of it. */ + boost::system::error_code code; + /** A description, Trystero's `message`: for `decrypt_failed` it names the stage, as "failed + * to decrypt offer (incorrect password or corrupted signal)". */ + std::string_view message; + /** The app's id. */ + std::string_view app_id; + /** The room's id; empty for a report of the app's configuration. */ + std::string_view room_id; + /** The id of the peer it concerns; empty when it concerns none. */ + std::string_view peer_id; + /** For `decrypt_failed`, the kind of the signal that did not open. */ + std::optional stage; + /** + * For `peer_connect_failed`, whether a TURN server was configured: an ICE server with a + * `turn:` or `turns:` URL among those the app kept. + * + * An ICE server the app dropped as unusable (`app::on_error` reported it), as a `turn:` URL + * without credentials, does not count, where 0.27.0 reads its raw configuration and counts it. + */ + bool turn_configured = false; + /** For `banned`, the reason the peer gave, when it gave one. */ + std::string_view reason; + /** For `plugin_failed`, the plugin that failed, when it is known. */ + std::string_view plugin; +}; + +/** + * Trystero's name of a room error's code, its `RoomErrorCode`. + * + * @param code A code of @ref error_category. + * @return "room-full", "banned", "relay-failed", "identity-failed", "plugin-failed", + * "decrypt-failed", "peer-connect-failed", "handshake-failed" or "peer-error" for the @ref error + * of that name, or an empty view for any other code: the others are no room error of Trystero's. + */ +inline std::string_view room_error_code_name(boost::system::error_code code) noexcept { + if (code.category() != error_category()) { + return {}; + } + switch (static_cast(code.value())) { + case error::room_full: return "room-full"; + case error::banned: return "banned"; + case error::relay_failed: return "relay-failed"; + case error::identity_failed: return "identity-failed"; + case error::plugin_failed: return "plugin-failed"; + case error::decrypt_failed: return "decrypt-failed"; + case error::peer_connect_failed: return "peer-connect-failed"; + case error::handshake_failed: return "handshake-failed"; + case error::peer_error: return "peer-error"; + default: return {}; + } +} + +} // namespace webcpp::trystero + +#endif diff --git a/include/webcpp/trystero/subscription.hpp b/include/webcpp/trystero/subscription.hpp new file mode 100644 index 0000000..0e80aa8 --- /dev/null +++ b/include/webcpp/trystero/subscription.hpp @@ -0,0 +1,340 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_TRYSTERO_SUBSCRIPTION_HPP +#define WEBCPP_TRYSTERO_SUBSCRIPTION_HPP + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::trystero { + +/** + * How a listener is added, Trystero's `ListenerOptions` and `ReplayListenerOptions` without their + * `signal`: `subscription::unsubscribe` takes the place of an `AbortSignal`. + * + * The @ref subscription an `on_` function returns refers to its listener through storage of the + * room's resource, which must outlive the subscription. + */ +struct listen_options { + /** Whether the listener runs once: it is removed before its first run. */ + bool once = false; + /** + * Whether the listener is first called, within the call that adds it, with what is current: the + * peers or the users already joined. + * + * Only the room's join events replay; the other events + * ignore it, as Trystero's do. + */ + bool replay = false; +}; + +namespace detail { + +/** What a subscription refers to: whether its listener is still in place. */ +struct listener_state { + /** False once the listener was removed, by its subscription or by its `once`. */ + bool active = true; +}; + +/** The listeners of one event, Trystero's event emitter, defined below. */ +template +class listeners; + +} // namespace detail + +/** + * A listener in place, what an `on_` function returns, Trystero's unsubscribe function. + * + * `unsubscribe` removes the listener. Destroying the subscription leaves the listener in place, as + * dropping the function Trystero returns does: a program that never removes a listener need not + * keep it. A listener goes with its room: when the room is left, as Trystero clears its listeners + * then, or once its last handle and those of its actions are gone. A subscription may outlive its + * room: it is then inactive, and `unsubscribe` does nothing. + * + * Requires: the room's resource outlives the subscription. The subscription refers to its + * listener weakly, through storage allocated in that resource, which the last subscription of a + * listener gone releases into it. + */ +class subscription { +public: + /** A subscription of no listener: `active` is false and `unsubscribe` does nothing. */ + subscription() noexcept = default; + + /** Not copyable: one subscription removes its listener. */ + subscription(const subscription&) = delete; + + /** Not copy-assignable: one subscription removes its listener. */ + subscription& operator=(const subscription&) = delete; + + /** Takes the listener of the subscription moved from, which then refers to none. */ + subscription(subscription&&) noexcept = default; + + /** + * Takes the listener of the subscription moved from, which then refers to none; the listener + * this one referred to stays in place, as on destruction. + * + * @return This subscription. + */ + subscription& operator=(subscription&&) noexcept = default; + + /** Leaves the listener in place. */ + ~subscription() = default; + + /** + * Removes the listener: it does not run again, not even for an event that is being reported + * and has not reached it yet. + * + * Does nothing once the listener is gone. + */ + void unsubscribe() noexcept { + if (const auto state = state_.lock()) { + state->active = false; + } + state_.reset(); + } + + /** + * Whether the listener is still in place: not removed, not run once with `once`, and its room + * or action still there. + * + * @return Whether it is. + */ + [[nodiscard]] bool active() const noexcept { + const auto state = state_.lock(); + return state && state->active; + } + +private: + template + friend class detail::listeners; + + explicit subscription(std::weak_ptr state) noexcept + : state_(std::move(state)) {} + + std::weak_ptr state_; +}; + +namespace detail { + +/** + * The listeners of one event, Trystero's event emitter: each added with its options, each removed + * through the @ref subscription that `add` returns, all in the resource of the listeners' owner. + * + * | Rule | What it does | + * | order | listeners run in the order they were added | + * | added while emitting | does not run for that emission | + * | removed while emitting | does not run, if its turn had not come | + * | `once` | removed before it runs | + * | `replay` | called with each item at once, within `add`, before it is in | + * | | place, so that an emission meanwhile does not reach it | + * + * @tparam R The listeners' result: `void` for an event, a value for a listener taken one at a + * time (`call_first`). + * @tparam Args What each listener is called with. + */ +template +class listeners { +public: + /** What the listeners are kept with. */ + using allocator_type = std::pmr::polymorphic_allocator<>; + + /** No listener, in `alloc`'s resource. */ + explicit listeners(allocator_type alloc) : entries_(alloc) {} + + /** + * Adds a listener, after those in place. + * + * @param f The listener, which must not be empty. + * @param options Its options; `replay` is ignored, nothing being current. + * @return Its subscription. + */ + subscription add(handler f, listen_options options) { + return keep(make(std::move(f), options)); + } + + /** + * Adds a listener, after those in place; with `options.replay`, first calls it with each item + * of `replay` in turn, until it is removed (`once` removes it before the first). + * + * @tparam Items A range whose elements the listener takes as its one argument. + * @param f The listener, which must not be empty. + * @param options Its options. + * @param replay What is current, read only with `options.replay`. + * @return Its subscription, inactive when the listener was removed during the replay. + */ + template + requires(sizeof...(Args) == 1) + subscription add(handler f, listen_options options, const Items& replay) { + auto e = make(std::move(f), options); + if (options.replay) { + // A clear during the replay removes this listener too, as Trystero's epoch does. + const std::size_t clears = clears_; + for (const auto& item : replay) { + if (clears != clears_) { + e->active = false; + } + if (!e->active) { + break; + } + if (e->once) { + e->active = false; + } + e->f(item); + } + if (clears != clears_) { + e->active = false; + } + } + return keep(std::move(e)); + } + + /** + * Calls every listener in place when the call starts, in order: one added meanwhile waits for + * the next emission, one removed meanwhile does not run, and a `once` one is removed first. + * + * @param args What each listener is called with. + */ + void emit(Args... args) // NOLINT(performance-unnecessary-value-param): views and references + requires std::is_void_v + { + // Ends the emission however it ends, a listener's exception included, so that the + // listeners removed meanwhile are forgotten. + struct emission { + listeners& self; + + explicit emission(listeners& s) : self(s) { ++self.depth_; } + + emission(const emission&) = delete; + emission& operator=(const emission&) = delete; + + ~emission() { + if (--self.depth_ == 0) { + self.compact(); + } + } + }; + + const emission guard(*this); + const std::size_t n = entries_.size(); + for (std::size_t i = 0; i < n; ++i) { + // A copy: a listener may add others, which moves the entries. + const std::shared_ptr e = entries_[i]; + if (!e->active) { + continue; + } + if (e->once) { + e->active = false; + } + e->f(args...); + } + } + + /** + * Calls the first listener in place, as Trystero calls a handler taken one at a time; a `once` + * one is removed first. + * + * @param args What the listener is called with. + * @return What it returns. + */ + R call_first(Args... args) { // NOLINT(performance-unnecessary-value-param): views, references + const auto it = std::ranges::find_if(entries_, [](const auto& e) { return e->active; }); + BOOST_ASSERT(it != entries_.end()); + // A copy, which the check takes for a needless one: the listener may remove itself, or + // others, which releases the entries' own. + // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) + const std::shared_ptr e = *it; + if (e->once) { + e->active = false; + } + return e->f(args...); + } + + /** + * Removes every listener, as Trystero's emitter `clear` does when its room is left: none runs + * again, not even within an emission under way, and their subscriptions are inactive; one + * being added with `replay` is removed once its replay ends. + */ + void clear() noexcept { + ++clears_; + for (const auto& e : entries_) { + e->active = false; + } + if (depth_ == 0) { + entries_.clear(); + } + } + + /** + * Whether no listener is in place. + * + * @return Whether none is. + */ + [[nodiscard]] bool empty() const noexcept { return size() == 0; } + + /** + * How many listeners are in place. + * + * @return Their number. + */ + [[nodiscard]] std::size_t size() const noexcept { + return static_cast( + std::ranges::count_if(entries_, [](const auto& e) { return e->active; })); + } + +private: + struct entry : listener_state { + entry(handler fn, bool o) : f(std::move(fn)), once(o) {} + + handler f; + bool once; + }; + + std::shared_ptr make(handler f, listen_options options) { + BOOST_ASSERT(f); + return std::allocate_shared(entries_.get_allocator(), std::move(f), options.once); + } + + /** Puts a listener in place, unless a replay removed it, and returns its subscription. */ + subscription keep(std::shared_ptr e) { + subscription out{std::weak_ptr(e)}; + if (e->active) { + if (depth_ == 0) { + compact(); + } + entries_.push_back(std::move(e)); + } + return out; + } + + /** Forgets the listeners removed, once no emission walks them. */ + void compact() { + std::erase_if(entries_, [](const auto& e) { return !e->active; }); + } + + std::pmr::vector> entries_; + /** The emissions under way, nested when a listener reports another of the same event. */ + std::size_t depth_ = 0; + /** How many times the listeners were cleared, which a replay under way checks. */ + std::size_t clears_ = 0; +}; + +} // namespace detail + +} // namespace webcpp::trystero + +#endif diff --git a/include/webcpp/trystero/webrtc/data_channel.hpp b/include/webcpp/trystero/webrtc/data_channel.hpp index 465246c..e151ff9 100644 --- a/include/webcpp/trystero/webrtc/data_channel.hpp +++ b/include/webcpp/trystero/webrtc/data_channel.hpp @@ -11,7 +11,7 @@ #include #include -#include +#include #include #include @@ -27,7 +27,6 @@ #include -#include #include #include #include @@ -47,7 +46,7 @@ namespace webcpp::trystero::webrtc { /** The executor of the backend's WebRTC objects: the app's. */ using executor_type = webcpp::asio::any_io_executor; -/** The allocator of their state, their queues and their texts: the app's resource. */ +/** The allocator of their state, their queues and their texts: the room's resource. */ using allocator_type = std::pmr::polymorphic_allocator; /** @@ -55,15 +54,22 @@ using allocator_type = std::pmr::polymorphic_allocator; * frames. * * It reads every message as it comes, with `async_receive`, on the executor. A text message, as a - * peer can send, or a binary one larger than any room frame (`protocol::max_room_frame_bytes`), is - * then dropped: neither can be a frame. Frames received while no message handler is installed wait - * in the app's resource, in order, up to `max_pending_frames` for `pending_frames_ttl` from the - * first, Trystero's pending-data bounds; exceeding either closes the channel. Installing a receiver - * posts their delivery, so that `set_handlers` never calls it inline. In the browser, a message - * larger than webcpp::webrtc's `options::max_message_size`, or past its receive budget, closes the - * channel too. + * peer can send, or a binary one larger than any frame (`protocol::max_bulk_frame_bytes`, a wide + * chunk's bound), closes the channel: neither can be a frame, and 0.27.0's `failData` (`peer.ts`) + * ends the peer for either. * - * Tip: a received frame is read once, by webcpp::webrtc, into a vector of the app's resource, + * Frames received while no message handler is installed wait in the room's resource, in order: + * the open event and a first message reach the executor in either order, and the room's link + * (`detail::peer_link`) installs its handler from the open event, so that only that gap is + * covered. The frames wait under the bounds the link puts on a peer's frames before its room binds + * it, 0.27.0's (`peer.ts`): at most `max_pending_frames`, each at most `max_pending_frame_bytes`; + * one more, or a longer one, closes the channel, as the link would end on it. They have no time + * bound of their own: the link's 10 s starts as it takes them, and a channel no link takes is one + * the signaling closes, which discards them. Installing a receiver posts their delivery, so that + * `set_handlers` never calls it inline. In the browser, a message larger than webcpp::webrtc's + * `options::max_message_size`, or past its receive budget, closes the channel too. + * + * Tip: a received frame is read once, by webcpp::webrtc, into a vector of the room's resource, * which the message handler then owns; what the platform holds before is the platform's. * * @see "The backend's WebRTC", in the guide. @@ -78,11 +84,15 @@ class data_channel : public backend::data_channel, /** webcpp::webrtc's data channel it holds. */ using channel_type = ::webcpp::webrtc::basic_data_channel; - /** The most frames kept while no message handler is installed: more close the channel. */ - static constexpr std::size_t max_pending_frames = 64; + /** The most frames kept while no message handler is installed, 0.27.0's + * `maxQueuedDataFrames`, as the room's link keeps before its room binds it: one more closes + * the channel. */ + static constexpr std::size_t max_pending_frames = protocol::max_queued_data_frames; - /** How long after the first kept frame the channel closes, if no handler took them. */ - static constexpr std::chrono::milliseconds pending_frames_ttl{10'000}; + /** The longest frame kept while no message handler is installed, 0.27.0's + * `maxRoomFrameBytes`, as the room's link keeps before its room binds it: a longer one closes + * the channel. */ + static constexpr std::size_t max_pending_frame_bytes = protocol::max_room_frame_bytes; /** * Takes over a channel of webcpp::webrtc: its threshold, and its events. @@ -90,19 +100,18 @@ class data_channel : public backend::data_channel, * @param runtime The runtime of the channel's connection, which the channel keeps alive. * @param channel The channel, made or accepted by a connection of the same executor and * allocator. - * @param factory The backend, which makes the timer of the pending frames, in `memory`. - * @param memory The app's resource, the channel's: the wrapper, its handlers and its frames + * @param memory The room's resource, the channel's: the wrapper, its handlers and its frames * are allocated in it. * @return The channel. */ // NOLINTBEGIN(performance-unnecessary-value-param): sinks, moved on static std::shared_ptr make(std::shared_ptr<::webcpp::webrtc::runtime> runtime, - channel_type channel, backend::factory& factory, + channel_type channel, std::pmr::memory_resource* memory) { // NOLINTEND(performance-unnecessary-value-param) - auto self = std::allocate_shared( - std::pmr::polymorphic_allocator<>(memory), private_tag{}, std::move(runtime), - std::move(channel), factory.make_timer(memory), memory); + auto self = std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), + private_tag{}, std::move(runtime), + std::move(channel), memory); self->start(); return self; } @@ -112,16 +121,13 @@ class data_channel : public backend::data_channel, * * @param runtime The runtime of the channel's connection. * @param channel The channel. - * @param timer The timer of the pending frames. * @param memory The resource its handlers and its frames are allocated in. */ data_channel(private_tag /*tag*/, std::shared_ptr<::webcpp::webrtc::runtime> runtime, - channel_type channel, std::shared_ptr timer, - std::pmr::memory_resource* memory) + channel_type channel, std::pmr::memory_resource* memory) : runtime_(std::move(runtime)), memory_(memory), pending_(memory), - pending_timer_(std::move(timer)), frame_(memory), channel_(std::move(channel)) {} @@ -168,8 +174,13 @@ class data_channel : public backend::data_channel, } /** - * Sends a binary message when the channel is open; one the channel refuses, as one that would - * pass webcpp::webrtc's bound on what it buffers, is dropped. + * Sends a binary message when the channel is open. + * + * One the channel refuses, larger than the connection's `max_message_size()` or past + * webcpp::webrtc's bound on what it buffers, closes the channel, which the handler `close` + * reports: a frame is never dropped while the channel goes on, so that a transfer cannot wait + * on a chunk that was never sent, as a browser's `send` throws and its channel goes on no + * further. * * @param frame The message, read during the call. */ @@ -177,9 +188,8 @@ class data_channel : public backend::data_channel, if (!is_open()) { return; } - // A channel closed in between refuses the frame, and its close event reports it; a frame - // refused leaves nothing to drain. if (channel_.send(webcpp::asio::buffer(frame.data(), frame.size()))) { + close(); return; } watch_drain(); @@ -268,14 +278,18 @@ class data_channel : public backend::data_channel, close(); return; } + // Trystero frames are binary, and none is larger than a wide chunk: a message that is + // neither closes the channel, as 0.27.0's failData (peer.ts) closes it, before the frame + // goes anywhere. + if (text || frame_.size() > protocol::max_bulk_frame_bytes) { + frame_.clear(); + close(); + return; + } auto frame = std::exchange(frame_, backend::bytes(memory_)); if (!closed_) { receive(); } - // Trystero frames are binary, and none is larger than the largest room frame. - if (text || frame.size() > protocol::max_room_frame_bytes) { - return; - } on_message(std::move(frame)); } @@ -299,31 +313,19 @@ class data_channel : public backend::data_channel, return; } } - const auto h = h_; - if ((!h || !h->message || !pending_.empty()) && pending_.size() >= max_pending_frames) { - close(); - return; - } - if (h && h->message && pending_.empty()) { + if (const auto h = h_; h && h->message && pending_.empty()) { h->message(std::move(frame)); return; } - if (pending_.empty()) { - pending_timer_->start(pending_frames_ttl, - {std::allocator_arg, allocator(), [weak = weak_from_this()] { - if (const auto self = weak.lock(); - self && !self->pending_.empty()) { - self->close(); - } - }}); + // No receiver yet, or frames ahead of this one: the bounds of the link's unbound frames. + if (frame.size() > max_pending_frame_bytes || pending_.size() >= max_pending_frames) { + close(); + return; } pending_.push_back(std::move(frame)); } - void clear_pending() { - pending_.clear(); - pending_timer_->cancel(); - } + void clear_pending() { pending_.clear(); } void flush_pending() { while (!pending_.empty()) { @@ -381,7 +383,6 @@ class data_channel : public backend::data_channel, std::pmr::memory_resource* memory_; std::shared_ptr h_; std::pmr::deque pending_; - std::shared_ptr pending_timer_; backend::bytes frame_; std::optional buffer_; bool flush_posted_ = false; diff --git a/include/webcpp/trystero/webrtc/peer_connection.hpp b/include/webcpp/trystero/webrtc/peer_connection.hpp index b6f2c3d..7fca05a 100644 --- a/include/webcpp/trystero/webrtc/peer_connection.hpp +++ b/include/webcpp/trystero/webrtc/peer_connection.hpp @@ -100,8 +100,8 @@ inline webcpp::document::result candidate_json( * disconnected, connected (or ICE completed), connecting (or ICE checking), and new. * * Tip: the connection, its channels, its handlers, its operations and the texts it hands to the - * app are in the app's resource; what the platform holds (libdatachannel's objects, or the page's) - * is the platform's. + * room are in the room's resource; what the platform holds (libdatachannel's objects, or the + * page's) is the platform's. * * @see "The backend's WebRTC", in the guide. */ @@ -146,9 +146,7 @@ class peer_connection : public backend::peer_connection, * @param ex The executor every handler of the connection runs on. * @param servers The STUN and TURN servers it gathers through, read during the call. * @param bind_address The local address it binds to, natively; empty for every interface. - * @param factory The backend, which makes its channels' timers, and which outlives every - * operation of the connection. - * @param memory The app's resource: the connection, its channels, its handlers and its texts + * @param memory The room's resource: the connection, its channels, its handlers and its texts * are allocated in it. * @return The connection, or webcpp::webrtc's error: `too_many_peer_connections` past the * runtime's cap, `syntax_error` for an ICE server URL the platform cannot parse, @@ -158,7 +156,7 @@ class peer_connection : public backend::peer_connection, [[nodiscard]] static boost::system::result> make( std::shared_ptr<::webcpp::webrtc::runtime> runtime, const executor_type& ex, std::span servers, std::string_view bind_address, - backend::factory& factory, std::pmr::memory_resource* memory) { + std::pmr::memory_resource* memory) { // NOLINTEND(performance-unnecessary-value-param) auto made = make_connection(*runtime, ex, servers, bind_address, memory); if (!made) { @@ -166,7 +164,7 @@ class peer_connection : public backend::peer_connection, } auto self = std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), private_tag{}, std::move(runtime), - std::move(*made), factory, memory); + std::move(*made), memory); self->start(); return self; } @@ -220,13 +218,11 @@ class peer_connection : public backend::peer_connection, * * @param runtime The runtime that counts the connection. * @param pc webcpp::webrtc's connection. - * @param factory The backend, which makes its channels' timers. * @param memory The resource its handlers and its texts are allocated in. */ peer_connection(private_tag /*tag*/, std::shared_ptr<::webcpp::webrtc::runtime> runtime, - connection_type pc, backend::factory& factory, - std::pmr::memory_resource* memory) - : runtime_(std::move(runtime)), factory_(factory), memory_(memory), pc_(std::move(pc)) {} + connection_type pc, std::pmr::memory_resource* memory) + : runtime_(std::move(runtime)), memory_(memory), pc_(std::move(pc)) {} /** Not copyable: its operations reach it by its address. */ peer_connection(const peer_connection&) = delete; @@ -261,7 +257,7 @@ class peer_connection : public backend::peer_connection, if (!made) { return nullptr; } - return data_channel::make(runtime_, std::move(*made), factory_, memory_); + return data_channel::make(runtime_, std::move(*made), memory_); } /** @@ -310,16 +306,16 @@ class peer_connection : public backend::peer_connection, * Adds a remote ICE candidate; the empty candidate that ends the remote gathering adds none. * * @param candidate_json The JSON of an `RTCIceCandidateInit`, read during the call, at most - * `protocol::max_sealed_candidate_bytes`, the bound of a sealed candidate, which its opened - * JSON never passes. + * `protocol::max_sealed_candidate_chars` bytes, the bound of a sealed candidate, an ASCII text + * whose opened JSON is shorter. * @param done Called on the executor once it is added, or with `error::backend_failure` when * the JSON has no candidate or the platform refuses it. */ void add_ice_candidate(std::string_view candidate_json, handler done) override { - // The document lives in the app's resource for the call: the platform copies the views. + // The document lives in the room's resource for the call: the platform copies the views. const auto document = webcpp::document::parse( - candidate_json, protocol::json::protocol_limits(protocol::max_sealed_candidate_bytes), + candidate_json, protocol::json::protocol_limits(protocol::max_sealed_candidate_chars), std::pmr::polymorphic_allocator(memory_)); const protocol::json::const_value object = document.has_value() ? document->root() : protocol::json::const_value(); @@ -357,6 +353,21 @@ class peer_connection : public backend::peer_connection, return pc_.has_remote_description(); } + /** + * The largest message a channel of the connection sends, as webcpp::webrtc's + * `max_message_size()` reads it from the transport: natively libdatachannel's + * `rtcGetRemoteMaxMessageSize`, in a page the browser's `sctp.maxMessageSize`, each bounded by + * webcpp::webrtc's `options::max_message_size`. + * + * It is the limit the channels' sends check. + * + * @return The size; nothing before the peer's limit is known (natively before a remote + * description is applied, in a page while the connection has no SCTP transport). + */ + [[nodiscard]] std::optional max_message_size() const override { + return pc_.max_message_size(); + } + /** Closes the connection and its channels, as the W3C's `close()`: no state is reported. */ void close() override { pc_.close(); } @@ -469,7 +480,7 @@ class peer_connection : public backend::peer_connection, } void on_channel(data_channel::channel_type channel) { - auto wrapped = data_channel::make(runtime_, std::move(channel), factory_, memory_); + auto wrapped = data_channel::make(runtime_, std::move(channel), memory_); if (const auto h = h_; h && h->data_channel) { h->data_channel(std::move(wrapped)); } @@ -505,7 +516,6 @@ class peer_connection : public backend::peer_connection, // The runtime outlives the connection, which goes first. std::shared_ptr<::webcpp::webrtc::runtime> runtime_; - backend::factory& factory_; std::pmr::memory_resource* memory_; std::shared_ptr h_; state state_ = state::new_; diff --git a/meta/libraries.json b/meta/libraries.json index be4fd56..4b5c6bb 100644 --- a/meta/libraries.json +++ b/meta/libraries.json @@ -9,7 +9,7 @@ "port-of": { "name": "Trystero", "language": "JavaScript", - "version": "0.26.0", + "version": "0.27.0", "url": "https://github.com/dmotz/trystero", "licence": "MIT" } diff --git a/test/CONVERSION.md b/test/CONVERSION.md index a1f115e..c51c657 100644 --- a/test/CONVERSION.md +++ b/test/CONVERSION.md @@ -19,10 +19,11 @@ new one checks it, so that the conversion can be reviewed assertion by assertion | `test/unit/native_peer_connection_test.cpp` | `test/native_peer_connection_test.cpp` | `native_peer_connection` | native | | `test/unit/native_room_test.cpp` | `test/native_room_test.cpp` | `native_room` | native | -The fixture `test/unit/fixtures/expected.json`, which the original's oracle writes from Trystero -JS 0.26, is now `test/fixtures/expected/expected.json`, byte for byte. `protocol` and -`native_sealer` receive its path as their one argument (``), as the old -`run` rule passed it. +The fixture `test/unit/fixtures/expected.json`, which the original's oracle wrote from Trystero +JS 0.26, became `test/fixtures/expected/expected.json`, byte for byte, and is now +`test/fixtures/oracle/expected.json`, which the oracle writes from Trystero JS 0.27.0. +`protocol` and `native_sealer` receive its path as their one argument (``), +as the old `run` rule passed it. `native_peer_connection` and `native_room` declare `on`: they need `native::peer_connection` and `native::backend`, which exist only with exceptions, since diff --git a/test/Jamfile b/test/Jamfile index 88e0536..240fe93 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -27,8 +27,8 @@ rule native-threads ( properties * ) } } local platform = /webcpp/trystero//platform @native-threads ; -# A test of a part that parses no JSON, the timer, a relay's URL, a page's -# calls or the sealer, links parts or platform-parts in place of the rooms: +# A test of a part that parses no JSON, the timer, a relay's URL or a page's +# calls, links parts or platform-parts in place of the rooms: # they leave out the rooms' Asyncify list, whose pattern names Boost.JSON's # parser, of which such a program has no function, and Binaryen warns of a # pattern that names none (build.jam). @@ -44,8 +44,7 @@ local platform-part = -/webcpp/trystero//trystero webcpp.headers-alone trystero : ../include : trystero.hpp trystero/*.hpp trystero/protocol/*.hpp trystero/detail/*.hpp ; webcpp.headers-alone trystero : ../include - : trystero/platform/backend.hpp trystero/platform/entropy.hpp - trystero/platform/sealer.hpp trystero/platform/websocket.hpp trystero/webrtc/*.hpp + : trystero/platform/backend.hpp trystero/platform/websocket.hpp trystero/webrtc/*.hpp : $(platform) ; webcpp.headers-alone trystero : ../include : trystero/platform/page.hpp : $(platform) : emscripten ; @@ -61,32 +60,59 @@ webcpp.compile config_developer_defined : config_test.cpp webcpp.compile config_all_off : config_test.cpp : WEBCPP_NO_EXCEPTIONS WEBCPP_TEST_TRYSTERO_ALL_OFF ; -# The protocol against what Trystero JS computed, which the original's oracle -# wrote into fixtures/expected/expected.json, and whole rooms over the memory -# backend of support/memory_backend.hpp: on both targets. +# The protocol against what Trystero JS 0.27.0 computed, which the original's +# oracle wrote into fixtures/oracle/expected.json, and whole rooms over the +# memory backend of support/memory_backend.hpp: on both targets. # tag::both-targets[] -webcpp.run protocol : protocol_test.cpp : fixtures/expected/expected.json ; +webcpp.run protocol : protocol_test.cpp : fixtures/oracle/expected.json ; +# The crypto layer of the port to Trystero 0.27.0 against the vectors +# recorded from its own code (oracle/record_0_27.mjs). +webcpp.run crypto_layer : crypto_layer_test.cpp + : fixtures/expected/trystero-0.27.0.json ; +# The PBKDF2 case of crypto_layer (600,000 iterations) is compiled only +# where WEBCPP_TRYSTERO_TEST_SLOW_KDF is defined, which this target alone +# defines, in a release build: the debug run of crypto_layer skips it by +# construction, so this target runs it in every lane. +webcpp.run crypto_layer_release : crypto_layer_test.cpp + : fixtures/expected/trystero-0.27.0.json release + WEBCPP_TRYSTERO_TEST_SLOW_KDF ; # The signaling and the Nostr strategy alone: an answerer's signals against # Trystero's, and the bounds of the texts they read. webcpp.run signaling : signaling_test.cpp - : fixtures/expected/expected.json ; -webcpp.run room : room_test.cpp ; -# Rooms of one app that share one connection per remote peer; once as the -# build asks, once without exceptions, on both targets; and, natively, once -# with the standard libraries' checks, so that a kept frame that kicks during -# a binding, or a waiter failed during a connection's end, fails at once when -# it touches what it removed. -webcpp.run shared : shared_test.cpp ; -webcpp.run shared_no_exceptions : shared_test.cpp : off ; -webcpp.run shared_hardened : shared_test.cpp + : fixtures/oracle/expected.json ; +# Whole rooms, whose transfers are checked frame by frame against those 0.27.0 +# sent (action_frames). +webcpp.run room : room_test.cpp : fixtures/expected/trystero-0.27.0.json ; +# The listeners of an event alone, as Trystero 0.27.0's emitter runs them. +webcpp.run subscription : subscription_test.cpp ; +# A room's users and their peers alone, as 0.27.0's room counts them. +webcpp.run user_table : user_table_test.cpp ; +# The memory backend's hooks, which the tests of rooms drive. +webcpp.run memory_backend : memory_backend_test.cpp ; +# One room's connection to one peer alone, over a memory pair: 0.27.0's +# bounds on the frames kept before its room binds it, and on a frame after. +webcpp.run peer_link : peer_link_test.cpp ; +# Natively once more with the standard libraries' checks, so that a frame that +# ends its link during the replay, or a waiter failed during the end, fails at +# once when it touches what it removed. +webcpp.run peer_link_hardened : peer_link_test.cpp + : _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE _GLIBCXX_ASSERTIONS + : native ; +# A room's handshakes alone, 0.27.0's handshake manager: its phases, its 10 s +# on the virtual clock, its 16 buffered messages and its ready frames. +webcpp.run handshake_manager : handshake_manager_test.cpp ; +# Natively once more with the standard libraries' checks, so that a callback +# that clears its peer while the manager calls it fails at once when the +# manager touches what it removed. +webcpp.run handshake_manager_hardened : handshake_manager_test.cpp : _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE _GLIBCXX_ASSERTIONS : native ; -# The memory backend's hooks, which the tests of shared connections drive. -webcpp.run memory_backend : memory_backend_test.cpp ; -# The shared connection alone, over a memory pair. -webcpp.run connection : connection_test.cpp ; # The state an app and its rooms share, alone, over the memory backend. webcpp.run app_impl : app_impl_test.cpp ; +# An app's key records and verified signatures alone, against 0.27.0's +# vectors: its bounds, its least recently used order, and a high S refused. +webcpp.run identity_cache : identity_cache_test.cpp + : fixtures/expected/trystero-0.27.0.json ; # The timer over webcpp::asio's steady_timer, which the platform backend # makes: a wait cancelled, restarted or destroyed never fires. webcpp.run timer : timer_test.cpp : $(part) ; @@ -94,8 +120,7 @@ webcpp.run timer : timer_test.cpp : $(part) ; # The platform backend's own tests, on each target that builds them. On both: # the backend itself (its own state in backend_config::memory, its clocks, -# its randomness, its TLS context); its sealer, natively OpenSSL's AES-GCM, in -# a page Web Crypto under node, against what Trystero JS sealed; relays it +# its randomness, its PBKDF2 off the room's thread, its TLS context); relays it # cannot reach; and how a relay's URL is read. Natively, against # libdatachannel and in-process servers: the relays' WebSocket, built with the # standard libraries' own checks, libc++'s extensive hardening and @@ -108,8 +133,6 @@ webcpp.run timer : timer_test.cpp : $(part) ; # libdatachannel throws, so the backend needs none. # tag::platform[] webcpp.run platform_backend : platform_backend_test.cpp : $(platform) ; -webcpp.run platform_sealer : platform_sealer_test.cpp - : $(platform) fixtures/expected/expected.json ; webcpp.run platform_websocket_unreachable : platform_websocket_unreachable_test.cpp : $(platform) ; webcpp.run platform_websocket_url : platform_websocket_url_test.cpp : $(platform-part) ; @@ -124,8 +147,6 @@ webcpp.run platform_peer_connection : platform_peer_connection_test.cpp webcpp.run platform_room : platform_room_test.cpp : $(platform) : native ; webcpp.run platform_backend_no_exceptions : platform_backend_test.cpp : $(platform) off ; -webcpp.run platform_sealer_no_exceptions : platform_sealer_test.cpp - : $(platform) fixtures/expected/expected.json off ; webcpp.run platform_websocket_unreachable_no_exceptions : platform_websocket_unreachable_test.cpp : $(platform) off ; webcpp.run platform_websocket_url_no_exceptions : platform_websocket_url_test.cpp @@ -166,7 +187,9 @@ webcpp.run allocation : allocation_test.cpp : emscripten:-sA # into main); in debug, now the deepest build, 2,344, 2,068 and 2,020. # tag::asyncify-release[] webcpp.run room_asyncify_release : room_test.cpp - : asyncify release : emscripten ; + : fixtures/expected/trystero-0.27.0.json asyncify + release + : emscripten ; webcpp.run app_impl_asyncify_release : app_impl_test.cpp : asyncify release : emscripten ; webcpp.run allocation_asyncify_release : allocation_test.cpp @@ -199,25 +222,35 @@ webcpp.run platform_page_peer_connection : platform_page_peer_connection_test.cp # A page's program: main runs the io_context under a work guard, and the # page's calls into C++ only post to it. webcpp.run platform_page : platform_page_test.cpp : $(platform) : emscripten ; -# A page's sealer allocates nothing outside the room's resource from the -# start of a seal or an open to its completion: the global operator new and -# the C library's allocation functions, replaced, count none. -webcpp.run platform_page_sealer_allocation : platform_page_sealer_allocation_test.cpp - : $(platform-part) : emscripten ; # A relay's connection and each of its messages allocate outside the room's # resource exactly what the guide lists, no more and no fewer. webcpp.run platform_page_relay_allocation : platform_page_relay_allocation_test.cpp : $(platform) : emscripten ; -# A page whose crypto misbehaves: its randomness and its sealer fail with -# their errors, and no JavaScript exception enters WebAssembly. -webcpp.run platform_page_sealer : platform_page_sealer_test.cpp : $(platform-part) : emscripten ; # A page_call's handler sees the page's value as it is when it runs; a # function the page kept reaches nothing once its page_call, or its # io_context, is destroyed; and a page_call outlives its io_context harmlessly. webcpp.run platform_page_call : platform_page_call_test.cpp : $(platform-part) : emscripten ; -# A relay socket's handlers and a sealer's completions run outside the page's -# events. +# A relay socket's handlers and a derivation's completion run outside the +# page's events. webcpp.run platform_page_handlers : platform_page_handlers_test.cpp : $(platform) : emscripten ; +# The page's online and offline events, which an app's automatic relays +# follow, reach the backend's watch after each event, and nothing once the +# watch is destroyed. +webcpp.run platform_page_connectivity : platform_page_connectivity_test.cpp + : $(platform) : emscripten ; +# A page without the browser's generator: each room of an app that cannot make +# its keys reports identity_failed, and no JavaScript exception enters +# WebAssembly. Linked for node 19 or newer, Emscripten draws from +# crypto.getRandomValues under node too, as in a page, where for older nodes it +# would draw from node:crypto, which the test cannot take away. +webcpp.run platform_page_entropy : platform_page_entropy_test.cpp + : $(platform) -sMIN_NODE_VERSION=190000 : emscripten ; +# It runs only by name until webcpp::crypto guards its read: random_device's +# read_entropy (crypto/detail/entropy.hpp) calls getentropy, whose Emscripten +# implementation lets the exception of a missing or throwing +# crypto.getRandomValues through, which terminates in the noexcept read +# (measured with Emscripten 6.0.11). The guard is the crypto stream's. +explicit platform_page_entropy ; # end::page[] # The same, built without exceptions, as a page's program may be: no @@ -238,17 +271,14 @@ webcpp.run platform_page_peer_connection_no_exceptions : platform_page_peer_conn : $(platform) off : emscripten ; webcpp.run platform_page_no_exceptions : platform_page_test.cpp : $(platform) off : emscripten ; -webcpp.run platform_page_sealer_allocation_no_exceptions - : platform_page_sealer_allocation_test.cpp - : $(platform-part) off : emscripten ; -webcpp.run platform_page_sealer_no_exceptions : platform_page_sealer_test.cpp - : $(platform-part) off : emscripten ; webcpp.run platform_page_relay_allocation_no_exceptions : platform_page_relay_allocation_test.cpp : $(platform) off : emscripten ; webcpp.run platform_page_call_no_exceptions : platform_page_call_test.cpp : $(platform-part) off : emscripten ; webcpp.run platform_page_handlers_no_exceptions : platform_page_handlers_test.cpp : $(platform) off : emscripten ; +webcpp.run platform_page_connectivity_no_exceptions : platform_page_connectivity_test.cpp + : $(platform) off : emscripten ; # end::no-exceptions[] # The combined Asio/Beast/Trystero provider has its own recurring native lane. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index b3b4645..a8f99c5 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -8,13 +8,17 @@ // they make goes through the resources of their configurations: the counting // resources see them, and the global operator new, replaced here, sees none, // nor do the C library's allocation functions where the platform lets a -// program count them (doc: #trystero-allocation). +// program count them (doc: #trystero-allocation), but natively OpenSSL's: +// webcpp::crypto's AES-256-GCM is OpenSSL's there, whose cipher context each +// seal and open of a signal allocates, outside the rooms' resources, counted +// apart. #include #include "cases.hpp" #include "require.hpp" #include "support/memory_backend.hpp" +#include "support/rooms.hpp" #include #include @@ -22,6 +26,7 @@ #include #include #include +#include #include #include @@ -50,6 +55,9 @@ #else #include #endif +#ifndef WEBCPP_TARGET_EMSCRIPTEN +#include +#endif #ifdef WEBCPP_TARGET_EMSCRIPTEN #include #include @@ -93,6 +101,15 @@ bool live_overflow = false; // counts nothing: that allocation is operator new's, counted once. // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) bool inside_operator_new = false; +#ifndef WEBCPP_TARGET_EMSCRIPTEN +// Set while OpenSSL takes its memory from the C library (openssl_malloc), which then counts +// nothing: natively each seal and open of a signal allocates OpenSSL's cipher context, outside the +// rooms' resources, which openssl_allocations counts apart. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +bool inside_openssl = false; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::size_t openssl_allocations = 0; +#endif #ifdef WEBCPP_TARGET_EMSCRIPTEN // Set, from JavaScript, while Asyncify allocates the unwind data of a call that suspends, on // emscripten under Asyncify: webcpp::asio's run family suspends there, and that allocation is the @@ -175,6 +192,11 @@ void __libc_free(void* pointer); namespace { void* counted(void* pointer) { +#ifndef WEBCPP_TARGET_EMSCRIPTEN + if (inside_openssl) { + return pointer; + } +#endif if (on_counted_thread() && counting && !inside_operator_new) { #ifdef WEBCPP_TARGET_EMSCRIPTEN ++(inside_runtime != 0 ? runtime_allocations : c_allocations); @@ -310,7 +332,7 @@ constexpr std::uint32_t malloc_log_allocate = 2; void count_c_allocation(std::uint32_t type, std::uintptr_t /*zone*/, std::uintptr_t /*size*/, std::uintptr_t /*other*/, std::uintptr_t /*result*/, std::uint32_t /*frames*/) { - if (on_counted_thread() && counting && !inside_operator_new && + if (on_counted_thread() && counting && !inside_operator_new && !inside_openssl && (type & malloc_log_allocate) != 0) { ++c_allocations; } @@ -496,10 +518,15 @@ class counting_resource final : public std::pmr::memory_resource { /** How long each run of the io_context the test drives lasts. */ constexpr std::chrono::milliseconds slice = 10ms; -/** Runs io in slices of 10 ms until done holds, for 5 s at most. */ +/** The wall-clock ceiling of a wait for something that must happen: a hang guard, far above any + * loaded run, never what a case measures. */ +constexpr std::chrono::milliseconds hang_guard = 120s; + +/** Runs io in slices of 10 ms until done holds, for `hang_guard` of the wall clock at most. */ template bool run_until(webcpp::asio::io_context& io, Predicate done) { - for (auto ran = 0ms; ran < 5s && !done(); ran += slice) { + const auto end = std::chrono::steady_clock::now() + hang_guard; + while (!done() && std::chrono::steady_clock::now() < end) { io.restart(); io.run_for(slice); // lint-run: the memory relays post to it } @@ -601,6 +628,22 @@ void free_planted() { planted = nullptr; } +/** The endpoint scalars of two apps, `low` of the lower peer id: the tests' apps a and z, whose + * order tells which offers. */ +struct endpoints { + std::array low; + std::array high; +}; + +/** Two endpoint scalars in the order of their peer ids, made before a counting window opens. */ +endpoints ordered_endpoints() { + const auto labels = trystero::test::ordered_labels(2); + return { + .low = trystero::test::endpoint_scalar(labels[0]), + .high = trystero::test::endpoint_scalar(labels[1]), + }; +} + /** * Two rooms exchange two payloads that make builds; the second is counted, and the global counts * seen in its window returned. With `planting`, the receiving handler plants allocations outside @@ -617,20 +660,21 @@ seen exchange_through_the_rooms_resources(Make make, bool planting = false) { // derives Trystero's public relays, which it refuses. constexpr std::string_view relay = "wss://relay.test"; network.relay(relay); - trystero::app a_app(io.get_executor(), network, - { - .app_id = "allocation", - .self_id = "AAAAAAAAAAAAAAAAAAAA", - .relay_urls = {std::pmr::string(relay)}, - .memory = &a_memory, - }); - trystero::app z_app(io.get_executor(), network, - { - .app_id = "allocation", - .self_id = "zzzzzzzzzzzzzzzzzzzz", - .relay_urls = {std::pmr::string(relay)}, - .memory = &z_memory, - }); + const auto ends = ordered_endpoints(); + auto a_app = trystero::detail::app_access::make(io.get_executor(), network, + { + .app_id = "allocation", + .relay_urls = {std::pmr::string(relay)}, + .memory = &a_memory, + }, + ends.low); + auto z_app = trystero::detail::app_access::make(io.get_executor(), network, + { + .app_id = "allocation", + .relay_urls = {std::pmr::string(relay)}, + .memory = &z_memory, + }, + ends.high); auto a = join(a_app, "room"); auto z = join(z_app, "room"); std::size_t received = 0; @@ -734,14 +778,15 @@ void reading_a_text_allocates_through_its_resource() { secret.fill(7); const auto key = tp::nostr::signer::from_secret(secret, &memory); webcpp::test::require(BOOST_TEST(key.has_value())); - const std::array aux{}; const std::pmr::string sealed(1100, 'A', &memory); const auto signal = tp::write_signal( {.peer_id = "AAAAAAAAAAAAAAAAAAAA", .offer_id = "BBBBBBBBBBBBBBBBBBBB", .offer = sealed}, {}, &memory); - const auto message = tp::nostr::event_message( - *key, std::chrono::sys_seconds(std::chrono::seconds(1'759'700'000)), "topic", signal, aux, + const auto signed_message = tp::nostr::event_message( + *key, std::chrono::sys_seconds(std::chrono::seconds(1'759'700'000)), "topic", signal, &memory); + webcpp::test::require(BOOST_TEST(signed_message.has_value())); + const auto& message = *signed_message; // A relay's text of that event: `["EVENT","",]`. const std::string_view written = message; std::pmr::string relayed(R"(["EVENT","CCCCCCCCCCCCCCCCCCCC",)", &memory); @@ -750,9 +795,6 @@ void reading_a_text_allocates_through_its_resource() { const std::pmr::string ok( R"(["OK","0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",true,""])", &memory); - const std::pmr::string handshake( - R"({"__trystero_pw":"response","h":"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"})", - &memory); const std::pmr::string candidate( R"({"candidate":"candidate:1 1 UDP 2122317823 192.168.1.10 54321 typ host","sdpMid":"0","sdpMLineIndex":0,"usernameFragment":"abcd"})", &memory); @@ -764,12 +806,11 @@ void reading_a_text_allocates_through_its_resource() { }; constexpr std::size_t relay_bound = tp::nostr::max_parsed_relay_text_bytes; - const std::array texts{ + const std::array texts{ text{.what = "relay event", .json = relayed, .bound = relay_bound}, text{.what = "relay OK", .json = ok, .bound = relay_bound}, text{.what = "signal", .json = signal, .bound = tp::max_parsed_signal_bytes}, - text{.what = "handshake", .json = handshake, .bound = tp::max_handshake_bytes}, - text{.what = "candidate", .json = candidate, .bound = tp::max_sealed_candidate_bytes}, + text{.what = "candidate", .json = candidate, .bound = tp::max_sealed_candidate_chars}, }; for (const text& t : texts) { const std::size_t outstanding = memory.outstanding; @@ -797,11 +838,12 @@ void reading_a_text_allocates_through_its_resource() { BOOST_TEST_EQ(memory.foreign, 0U); } -/** Runs io for about `duration`, whatever happens, in slices of 10 ms. */ -void run_for(webcpp::asio::io_context& io, std::chrono::milliseconds duration) { - for (auto ran = 0ms; ran + slice <= duration; ran += slice) { +/** Runs the ready work of io until there is none: every frame of the memory relays is a posted + * handler, so what is left when this returns is only what waits on a timer. */ +void drain(webcpp::asio::io_context& io) { + io.restart(); + while (io.poll() > 0) { io.restart(); - io.run_for(slice); // lint-run: the memory relays post to it } } @@ -820,16 +862,15 @@ void warm(webcpp::asio::io_context& io) { timer->cancel(); } webcpp::asio::post(io, [] {}); - run_for(io, 20ms); + drain(io); } // tag::config[] /** An app's configuration, every part of it in `memory`, made before the window. */ -trystero::app_config app_config_in(counting_resource& memory, std::string_view self_id, - std::string_view relay, std::size_t& lines) { +trystero::app_config app_config_in(counting_resource& memory, std::string_view relay, + std::size_t& lines) { return trystero::app_config{ .app_id = std::pmr::string("allocation", &memory), - .self_id = std::pmr::string(self_id, &memory), .password = std::pmr::string("a password", &memory), .relay_urls = std::pmr::vector({std::pmr::string(relay, &memory)}, &memory), @@ -851,6 +892,60 @@ trystero::room_options options_in(counting_resource& memory) { // end::config[] +#ifndef WEBCPP_TARGET_EMSCRIPTEN +// What OpenSSL allocates for one seal and one open of a signal, measured in this process by +// start_counting_openssl. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::size_t openssl_allocations_per_seal_and_open = 0; + +/** Seals a signal and opens it, in `memory`, as a room does; true when both succeed. */ +bool seal_and_open(std::pmr::memory_resource* memory) { + const webcpp::crypto::secret<32> key; + const std::array iv{}; + const std::string_view aad = "offer|AAAAAAAAAAAAAAAAAAAA|ZZZZZZZZZZZZZZZZZZZZ"; + const auto sealed = tp::seal(key, iv, "v=0", aad, memory); + return sealed && tp::open(key, *sealed, aad, memory); +} +#endif + +/** + * Starts OpenSSL's count over, for the case that follows, and natively measures what OpenSSL + * allocates for one seal and one open (after one of each, which warms it), so that the case's + * count is checked against this OpenSSL's own, whatever its cipher contexts allocate. + */ +void start_counting_openssl() { +#ifndef WEBCPP_TARGET_EMSCRIPTEN + std::array buffer{}; + std::pmr::monotonic_buffer_resource memory(buffer.data(), buffer.size(), + std::pmr::null_memory_resource()); + BOOST_TEST(seal_and_open(&memory)); + const auto globals = global_allocations; + const auto cs = c_allocations; + const bool was_counting = counting; + openssl_allocations = 0; + counting = true; + BOOST_TEST(seal_and_open(&memory)); + counting = was_counting; + BOOST_TEST_EQ(global_allocations, globals); + BOOST_TEST_EQ(c_allocations, cs); + openssl_allocations_per_seal_and_open = openssl_allocations; + openssl_allocations = 0; +#endif +} + +/** + * Natively, that OpenSSL allocated since start_counting_openssl, counted apart: webcpp::crypto's + * AES-256-GCM is OpenSSL's there, whose cipher contexts the rooms' seals and opens make, outside + * their resources: what start_counting_openssl measured for a seal and an open, times `pairs`, how + * many signals the case seals, each opened once, and nothing else. On emscripten the cipher is + * BearSSL's, which allocates nothing, and the C library's count holds that. + */ +void expect_openssl_allocations([[maybe_unused]] std::size_t pairs) { +#ifndef WEBCPP_TARGET_EMSCRIPTEN + BOOST_TEST_EQ(openssl_allocations, pairs * openssl_allocations_per_seal_and_open); +#endif +} + /** * Two apps, each with a log and a relay of its own, are made one after the other * and join a room with a password, whose two sides exchange a payload that travels @@ -868,6 +963,7 @@ void a_room_allocates_through_its_resource_from_join_to_destruction() { constexpr std::string_view relay = "wss://relay.test"; network.relay(relay); warm(io); + const auto ends = ordered_endpoints(); std::size_t a_lines = 0; std::size_t z_lines = 0; std::size_t files = 0; @@ -881,6 +977,7 @@ void a_room_allocates_through_its_resource_from_join_to_destruction() { return std::pmr::polymorphic_allocator<>(&memory); }; // end::allocator[] + start_counting_openssl(); counting = true; { // z is subscribed and announcing before a arrives, so that z, whose id is @@ -889,15 +986,15 @@ void a_room_allocates_through_its_resource_from_join_to_destruction() { // moved-from object behind: MSVC's debug standard library keeps, in a moved-from // std::pmr::string or vector, 16 bytes of its resource for the container's debug // proxy, which the test would count as the app's until the end of the function. - trystero::app z_app(io.get_executor(), network, - app_config_in(z_memory, "zzzzzzzzzzzzzzzzzzzz", relay, z_lines)); + auto z_app = trystero::detail::app_access::make( + io.get_executor(), network, app_config_in(z_memory, relay, z_lines), ends.high); auto z = join(z_app, "room", options_in(z_memory)); - run_for(io, 100ms); + drain(io); { - trystero::app a_app(io.get_executor(), network, - app_config_in(a_memory, "AAAAAAAAAAAAAAAAAAAA", relay, a_lines)); + auto a_app = trystero::detail::app_access::make( + io.get_executor(), network, app_config_in(a_memory, relay, a_lines), ends.low); auto a = join(a_app, "room", options_in(a_memory)); - a.on_peer_leave([&left](std::string_view /*peer*/) { ++left; }); + a.on_peer_leave([&left](const trystero::peer_event&) { ++left; }); z.make_action("file").on_message( [&files](const trystero::pmr_bytes& data, const trystero::message_info& /*info*/) { files += data.size() == 100'000 ? 1 : 0; @@ -934,7 +1031,7 @@ void a_room_allocates_through_its_resource_from_join_to_destruction() { // } // io.run(); // lint-run: the program's I/O; or destroy io: pending operations free const std::size_t left_behind = a_memory.outstanding + z_memory.outstanding; - run_for(io, 300ms); + drain(io); counting = false; BOOST_TEST_GT(left_behind, 0U); BOOST_TEST_EQ(a_memory.outstanding, 0U); @@ -950,6 +1047,8 @@ void a_room_allocates_through_its_resource_from_join_to_destruction() { BOOST_TEST_EQ(live_count, 0U); BOOST_TEST(!live_overflow); BOOST_TEST_EQ(c_allocations, 0U); + // Two rooms: each seals its offer or answer and a candidate, and opens the other's two. + expect_openssl_allocations(4U); BOOST_TEST_GT(network_memory.allocations, 0U); global_allocations = 0; c_allocations = 0; @@ -958,9 +1057,9 @@ void a_room_allocates_through_its_resource_from_join_to_destruction() { /** * Two apps, each with two rooms, one room in the app's resource and one in a resource of its own, * exchange binary payloads: from construction until the io_context drains, neither operator new nor - * the C library sees an allocation. A payload received by the room with its own resource is copied - * into that resource once, the received frame staying the app's; by the room in the app's resource, - * the payload taken out of the frame is moved into the value (doc: #trystero-allocation). + * the C library sees an allocation. Each room's connections are in its own resource, the frames + * received on them too: in either room the payload taken out of the frame is moved into the value, + * and the app's resource sees nothing of the room with its own (doc: #trystero-allocation). */ void rooms_of_one_app_allocate_through_their_resources() { counting_resource network_memory; @@ -973,13 +1072,14 @@ void rooms_of_one_app_allocate_through_their_resources() { // Construct configurations in their resources before the counting window. They, and the // payloads, are destroyed before the resources are checked: a moved-from object may still // hold memory of its resource (MSVC's debug containers keep an iterator proxy). - auto a_config = app_config_in(a_memory, "AAAAAAAAAAAAAAAAAAAA", "wss://relay.test", lines); - auto z_config = app_config_in(z_memory, "zzzzzzzzzzzzzzzzzzzz", "wss://relay.test", lines); + auto a_config = app_config_in(a_memory, "wss://relay.test", lines); + auto z_config = app_config_in(z_memory, "wss://relay.test", lines); const auto a_own = options_in(a_room_memory); const auto z_own = options_in(z_room_memory); // An inline payload of a size no other allocation has: its frame is at most 256 bytes // longer. constexpr std::size_t payload_size = 12'345; + const auto ends = ordered_endpoints(); const trystero::pmr_bytes to_shared(payload_size, std::uint8_t{1}, &a_memory); const trystero::pmr_bytes to_own(payload_size, std::uint8_t{2}, &a_room_memory); { @@ -987,10 +1087,13 @@ void rooms_of_one_app_allocate_through_their_resources() { trystero::test::memory_network network{io, 1, &network_memory}; network.relay("wss://relay.test"); warm(io); + start_counting_openssl(); counting = true; { - trystero::app a(io.get_executor(), network, std::move(a_config)); - trystero::app z(io.get_executor(), network, std::move(z_config)); + auto a = trystero::detail::app_access::make(io.get_executor(), network, + std::move(a_config), ends.low); + auto z = trystero::detail::app_access::make(io.get_executor(), network, + std::move(z_config), ends.high); auto a1 = join(a, "shared", options_in(a_memory)); auto a2 = join(a, "own", a_own); auto z1 = join(z, "shared", options_in(z_memory)); @@ -1019,9 +1122,10 @@ void rooms_of_one_app_allocate_through_their_resources() { webcpp::asio::bind_allocator(std::pmr::polymorphic_allocator<>(&a_room_memory), [](boost::system::error_code) {})); BOOST_TEST(run_until(io, [&] { return got == 1; })); - BOOST_TEST_EQ(z_room_memory.sized, 1U); // copied once, out of the frame - BOOST_TEST_EQ(z_memory.sized, 1U); // the received frame, and nothing more - z_memory.sized = 0; + // The frame, and the payload taken out and moved on, both in the room's resource, + // as its connection is since each room has its own; nothing in the app's. + BOOST_TEST_EQ(z_room_memory.sized, 2U); + BOOST_TEST_EQ(z_memory.sized, 0U); a1.make_action("b").async_send( trystero::pmr_bytes(to_shared, &a_memory), webcpp::asio::bind_allocator(std::pmr::polymorphic_allocator<>(&a_memory), @@ -1029,7 +1133,7 @@ void rooms_of_one_app_allocate_through_their_resources() { BOOST_TEST(run_until(io, [&] { return got == 2; })); BOOST_TEST_EQ(z_memory.sized, 2U); // the frame, the payload taken out and moved on } - run_for(io, 300ms); // the io_context runs out of the rooms' work + drain(io); // the io_context runs out of the rooms' work } counting = false; } @@ -1038,6 +1142,8 @@ void rooms_of_one_app_allocate_through_their_resources() { BOOST_TEST_EQ(live_count, 0U); BOOST_TEST(!live_overflow); BOOST_TEST_EQ(c_allocations, 0U); + // Four rooms, two pairs of the above. + expect_openssl_allocations(8U); for (const auto* m : {&a_memory, &a_room_memory, &z_memory, &z_room_memory}) { BOOST_TEST_EQ(m->outstanding, 0U); BOOST_TEST_EQ(m->foreign, 0U); @@ -1113,9 +1219,44 @@ void mark_the_runtime_allocations() { } // namespace +#ifndef WEBCPP_TARGET_EMSCRIPTEN +namespace { + +/** OpenSSL's allocation functions: the C library's, counted apart (inside_openssl). */ +void* openssl_malloc(std::size_t size, const char* /*file*/, int /*line*/) { + inside_openssl = true; + void* const pointer = std::malloc(size); // NOLINT(cppcoreguidelines-no-malloc) + inside_openssl = false; + if (on_counted_thread() && counting) { + ++openssl_allocations; + } + return pointer; +} + +void* openssl_realloc(void* pointer, std::size_t size, const char* /*file*/, int /*line*/) { + inside_openssl = true; + void* const moved = std::realloc(pointer, size); // NOLINT(cppcoreguidelines-no-malloc) + inside_openssl = false; + if (on_counted_thread() && counting) { + ++openssl_allocations; + } + return moved; +} + +void openssl_free(void* pointer, const char* /*file*/, int /*line*/) { + std::free(pointer); // NOLINT(cppcoreguidelines-no-malloc) +} + +} // namespace +#endif + int main() { count_this_thread(); mark_the_runtime_allocations(); +#ifndef WEBCPP_TARGET_EMSCRIPTEN + // Before OpenSSL's first allocation, which a later call could not replace. + BOOST_TEST_EQ(CRYPTO_set_mem_functions(&openssl_malloc, &openssl_realloc, &openssl_free), 1); +#endif #if defined(WEBCPP_TEST_TRYSTERO_COUNTS_C_ALLOCATIONS) && defined(__APPLE__) && \ !defined(WEBCPP_TARGET_EMSCRIPTEN) malloc_logger = &count_c_allocation; diff --git a/test/app_impl_test.cpp b/test/app_impl_test.cpp index 257cb03..2187701 100644 --- a/test/app_impl_test.cpp +++ b/test/app_impl_test.cpp @@ -5,13 +5,14 @@ // https://www.boost.org/LICENSE_1_0.txt) // The state an app and its rooms share, alone, over a memory network: the configuration it -// completes and what it sets aside, the registry of rooms, the adoption of connections, the -// routing of a connection's events to the rooms, and the end of every connection with its last -// user. +// completes and what it sets aside, the registry of rooms, the relays' connectivity it hands every +// room, and the page's watch, which ends with its last user. It shares no connection: each room +// has its own. #include +#include #include -#include +#include #include #include @@ -22,7 +23,6 @@ #include #include -#include #include #include #include @@ -36,7 +36,6 @@ #include #include "cases.hpp" -#include "require.hpp" namespace asio = webcpp::asio; namespace trystero = webcpp::trystero; @@ -50,8 +49,21 @@ concept has_password_option = requires(Options options) { options.password; }; static_assert(has_password_option); static_assert(!has_password_option); +// The options 0.27.0 removed: a custom peer id (`peerId`, once `selfId`) and `handshakeTimeoutMs`. +template +concept has_self_id_option = requires(Options options) { options.self_id; }; +template +concept has_handshake_timeout_option = requires(Options options) { options.handshake_timeout; }; +static_assert(!has_self_id_option); +static_assert(!has_handshake_timeout_option); +static_assert(!has_handshake_timeout_option); + +/** The wall-clock ceiling of a wait for something that must happen: a hang guard, far above any + * loaded run, never what a case measures. */ +constexpr std::chrono::milliseconds hang_guard = 120s; + bool run_until(asio::io_context& io, const std::function& done, - std::chrono::milliseconds limit = 5s) { + std::chrono::milliseconds limit = hang_guard) { const auto end = std::chrono::steady_clock::now() + limit; while (!done() && std::chrono::steady_clock::now() < end) { io.run_for(10ms); // lint-run: the memory network posts to it @@ -70,97 +82,20 @@ void settle(asio::io_context& io) { } } -/** A room as the app sees it, which records every call: "+P", "-P", "kept P", "ended P: why", and - * the connection each end names. */ +/** A room as the app sees it, which records every call: "relays offline", "relays online". */ class fake_room final : public detail::room_endpoint { public: [[nodiscard]] bool leaving() const override { return false; } void finish_farewell() override {} - void presence_changed(std::string_view peer, bool present) override { - events.push_back((present ? "+" : "-") + std::string(peer)); - } - - [[nodiscard]] bool keeps_frames_from(std::string_view /*peer*/) const override { return keeps; } - - void frame_kept(std::string_view peer) override { - events.push_back("kept " + std::string(peer)); - } - - void connection_ended(const std::shared_ptr& ended, std::string_view peer, - std::string_view reason) override { - ended_connections.push_back(ended); - events.push_back("ended " + std::string(peer) + ": " + std::string(reason)); - if (on_end) { - on_end(); - } + void relays_offline(bool offline) override { + events.emplace_back(offline ? "relays offline" : "relays online"); } std::vector events; - /** The connection each end named, in the order of `events`' ends; weak, so that the record - * keeps none alive. */ - std::vector> ended_connections; - bool keeps = true; - /** Called after a connection's end is recorded: a room that leaves the registry there. */ - std::function on_end; -}; - -/** One negotiated pair: the app's end, whose connection and channel it adopts, and the remote's, - * which records every frame it receives. */ -struct pair_ends { - std::shared_ptr local_pc; - std::shared_ptr local; - std::shared_ptr remote_pc; - std::shared_ptr remote; - std::size_t local_id = 0; // the memory network's id of `local_pc` - std::shared_ptr>> received = - std::make_shared>>(); }; -pair_ends negotiate(asio::io_context& io, trystero::test::memory_network& net) { - auto* m = std::pmr::get_default_resource(); - pair_ends p; - p.local_pc = net.make_peer_connection({}, m); - p.remote_pc = net.make_peer_connection({}, m); - p.local_id = std::static_pointer_cast(p.local_pc)->id(); - p.local = p.local_pc->create_data_channel("data"); - p.remote_pc->set_handlers({ - .ice_candidate = {}, - .data_channel = - [&p](std::shared_ptr c) { p.remote = std::move(c); }, - .state = {}, - }); - std::pmr::string offer(m); - std::pmr::string answer(m); - p.local_pc->set_local_description([&offer](trystero::backend::error_code, std::string_view, - std::string_view sdp) { offer = sdp; }); - webcpp::test::require(BOOST_TEST(run_until(io, [&] { return !offer.empty(); }))); - p.remote_pc->set_remote_description("offer", offer, [](trystero::backend::error_code) {}); - p.remote_pc->set_local_description([&answer](trystero::backend::error_code, std::string_view, - std::string_view sdp) { answer = sdp; }); - webcpp::test::require(BOOST_TEST(run_until(io, [&] { return !answer.empty(); }))); - p.local_pc->set_remote_description("answer", answer, [](trystero::backend::error_code) {}); - webcpp::test::require(BOOST_TEST( - run_until(io, [&] { return p.local->is_open() && p.remote && p.remote->is_open(); }))); - p.remote_pc->set_handlers({}); // its handler names `p`, which the return may move - p.remote->set_handlers({ - .open = {}, - .message = - [received = p.received](trystero::backend::bytes frame) { - received->emplace_back(frame.begin(), frame.end()); - }, - .close = {}, - .buffered_amount_low = {}, - }); - return p; -} - -std::vector presence(std::string_view token, bool present) { - const auto frame = trystero::protocol::presence_frame(token, present); - return {frame.begin(), frame.end()}; -} - /** What the app's sink received: "category: text". */ using lines = std::vector; @@ -196,8 +131,9 @@ std::vector urls_of(std::span return out; } -// An empty self id is drawn from the factory, the ICE servers default to Trystero's, and the -// relays are derived from the app id; nothing is set aside. +// The self id derives from the endpoint key the app drew, the user id from the ephemeral user +// identity it made, the ICE servers default to Trystero's, and the relays are derived from the app +// id; nothing is set aside. void the_configuration_is_copied_and_completed() { asio::io_context io; trystero::test::memory_network net(io); @@ -206,66 +142,58 @@ void the_configuration_is_copied_and_completed() { BOOST_TEST_EQ(app->app_id(), "app"); BOOST_TEST(app->password().empty()); BOOST_TEST_EQ(app->self_id().size(), trystero::protocol::peer_id_size); - BOOST_TEST_EQ(app->self_id().find_first_not_of(trystero::protocol::id_alphabet), + BOOST_TEST_EQ(app->self_id().find_first_not_of(trystero::protocol::base62_alphabet), std::string_view::npos); + BOOST_TEST_EQ(app->self_id(), trystero::protocol::derive_peer_id(app->endpoint_key())); + BOOST_TEST(trystero::protocol::parse_compact_public_key(app->endpoint_key()).has_value()); + BOOST_TEST_EQ(app->user_id().size(), trystero::protocol::user_id_size); + BOOST_TEST(app->persistence() == trystero::identity_persistence::ephemeral); + BOOST_TEST(app->identity_failure().empty()); BOOST_TEST(urls_of(app->ice_servers()) == urls_of(trystero::default_ice_servers())); const auto derived = trystero::protocol::derive_relays("app", trystero::protocol::default_nostr_relays, 5); BOOST_TEST_EQ(app->relay_urls().size(), 5U); BOOST_TEST(std::ranges::equal(app->relay_urls(), derived)); - BOOST_TEST(app->idle_timeout() == 123'333ms); BOOST_TEST(app->setup_reports().empty()); BOOST_TEST(log.empty()); BOOST_TEST(app->memory() == std::pmr::get_default_resource()); BOOST_TEST(app->get_executor() == io.get_executor()); BOOST_TEST(&app->factory() == &net); BOOST_TEST_EQ(app->counted_rooms(), 0U); - BOOST_TEST(app->live_connections().empty()); } -// What the configuration names is kept: a self id of 64 bytes, the relays, a redundancy that -// their list makes moot, the ICE servers with their scheme lowercased. +// What the configuration names is kept: the relays, a redundancy that their list makes moot, the +// ICE servers with their scheme lowercased. void what_the_configuration_names_is_kept() { asio::io_context io; trystero::test::memory_network net(io); lines log; - const std::string id(trystero::protocol::max_peer_id_bytes, 'x'); const auto app = make_app(io, net, log, [&](trystero::app_config& c) { - c.self_id = id; c.password = "the immutable password of every room in this app"; c.relay_urls.emplace_back("wss://relay.example"); c.relay_redundancy = 1; c.ice_servers.push_back(server("STUN:stun.example:3478")); - c.idle_timeout = 0ms; }); - BOOST_TEST_EQ(app->self_id(), id); BOOST_TEST_EQ(app->password(), "the immutable password of every room in this app"); BOOST_TEST_EQ(app->relay_urls().size(), 1U); BOOST_TEST_EQ(app->relay_urls()[0], "wss://relay.example"); BOOST_TEST(urls_of(app->ice_servers()) == (std::vector{"stun:stun.example:3478"})); - BOOST_TEST(app->idle_timeout() == 0ms); BOOST_TEST(app->setup_reports().empty()); } -// An over-long self id, a negative idle time and every ICE server no peer connection could be -// made with are set aside, each reported once and logged, in that order. +// Every ICE server no peer connection could be made with is set aside, each reported once and +// logged, in their order. void what_no_peer_could_use_is_set_aside() { asio::io_context io; trystero::test::memory_network net(io); lines log; const auto app = make_app(io, net, log, [](trystero::app_config& c) { - c.self_id = std::pmr::string(trystero::protocol::max_peer_id_bytes + 1, 'x'); - c.idle_timeout = -1ms; c.ice_servers.push_back(server("http://example")); c.ice_servers.push_back(server("stun:stun.example")); c.ice_servers.push_back({}); }); - BOOST_TEST_EQ(app->self_id().size(), trystero::protocol::peer_id_size); - BOOST_TEST(app->idle_timeout() == 0ms); BOOST_TEST(urls_of(app->ice_servers()) == (std::vector{"stun:stun.example"})); const std::vector expected{ - "self_id is longer than any peer accepts, so the app uses a random one", - "idle_timeout is negative, so the app closes an unused connection at once", "the ICE server http://example is not stun:, stuns:, turn: or turns:, so the app goes on " "without it", "the ICE server (no URL) names no URL, so the app goes on without it", @@ -279,72 +207,176 @@ void what_no_peer_could_use_is_set_aside() { BOOST_TEST(log == logged); } -// A self id that is not UTF-8, which a signal could not write as a JSON string, is set aside for a -// random one, reported and logged; one in UTF-8 past ASCII is kept as it is. -void a_self_id_that_is_not_utf8_is_set_aside() { +// No configuration names the self id, as 0.27.0 has no custom one: each app draws its own +// endpoint key from the system's generator, as 0.27.0 draws it with WebCrypto, not from the +// factory's randomness, and derives its 20 base62 characters from it, so that two apps of one +// network differ; and no room option names a handshake timeout (the static assertions above). +void no_custom_self_id() { asio::io_context io; trystero::test::memory_network net(io); - for (const std::string_view id : - {std::string_view("peer\xff"), std::string_view("\xc3\xa9t\xc3\xa9")}) { - lines log; - const auto app = make_app(io, net, log, [&](trystero::app_config& c) { c.self_id = id; }); - const auto reports = app->setup_reports(); - if (id == "peer\xff") { - BOOST_TEST_EQ(app->self_id().size(), trystero::protocol::peer_id_size); - BOOST_TEST_EQ(app->self_id().find_first_not_of(trystero::protocol::id_alphabet), - std::string_view::npos); - const std::vector expected{ - "self_id is not UTF-8, which no peer reads, so the app uses a random one", - }; - BOOST_TEST(std::vector(reports.begin(), reports.end()) == expected); - BOOST_TEST(log == lines{"app: " + expected[0]}); - } else { - BOOST_TEST_EQ(app->self_id(), id); - BOOST_TEST(reports.empty()); - BOOST_TEST(log.empty()); - } + lines log; + const auto before = net.random_bytes; + const auto a = make_app(io, net, log); + BOOST_TEST_EQ(net.random_bytes, before); + const auto b = make_app(io, net, log); + for (const auto& app : {a, b}) { + BOOST_TEST_EQ(app->self_id().size(), trystero::protocol::peer_id_size); + BOOST_TEST_EQ(app->self_id().find_first_not_of(trystero::protocol::base62_alphabet), + std::string_view::npos); } + BOOST_TEST_NE(a->self_id(), b->self_id()); + BOOST_TEST(a->setup_reports().empty()); + BOOST_TEST(log.empty()); +} + +// The connectivity reaches every room of the app, as 0.27.0's `setRelayConnectivity` reaches every +// socket: `offline` holds the relays at each call, `online` reconnects them at each call, and +// `automatic` reconnects only relays a program held offline. Natively there is no page to watch: +// the app is automatic and online from the start, and asks the backend for a watch again each time +// it becomes automatic. +void the_connectivity_reaches_every_room() { + asio::io_context io; + trystero::test::memory_network net(io); + lines log; + const auto app = make_app(io, net, log); + BOOST_TEST(app->connectivity() == trystero::relay_connectivity::automatic); + BOOST_TEST(!app->relays_offline()); + const auto r1 = std::make_shared(); + const auto r2 = std::make_shared(); + app->register_room("r1", r1); + app->register_room("r2", r2); + BOOST_TEST(app->set_connectivity(trystero::relay_connectivity::offline) == + trystero::relay_connectivity::offline); + BOOST_TEST(app->relays_offline()); + BOOST_TEST(app->set_connectivity(trystero::relay_connectivity::offline) == + trystero::relay_connectivity::offline); + BOOST_TEST(app->set_connectivity(trystero::relay_connectivity::automatic) == + trystero::relay_connectivity::automatic); + BOOST_TEST(!app->relays_offline()); + BOOST_TEST(app->set_connectivity(trystero::relay_connectivity::automatic) == + trystero::relay_connectivity::automatic); + BOOST_TEST(app->set_connectivity(trystero::relay_connectivity::online) == + trystero::relay_connectivity::online); + BOOST_TEST(app->set_connectivity(trystero::relay_connectivity::online) == + trystero::relay_connectivity::online); + BOOST_TEST(app->connectivity() == trystero::relay_connectivity::online); + const std::vector expected{ + "relays offline", "relays offline", "relays online", "relays online", "relays online", + }; + BOOST_TEST(r1->events == expected); + BOOST_TEST(r2->events == expected); + BOOST_TEST(log == (lines{ + "app: the relays go offline", + "app: the relays go offline", + "app: the relays go online", + "app: the relays go online", + "app: the relays go online", + })); } -// Every allocation of the app's construction, of its registry, of an adoption, of a stale -// connection's replacement and end, of the list of live connections and of the last user's release -// goes through its resource: the default resource refuses every request meanwhile. +// Where the page has events, an automatic app follows them, each after the event, and an app a +// program set online or offline does not, until it is automatic again. +void an_automatic_app_follows_the_pages_events() { + asio::io_context io; + trystero::test::memory_network net(io); + net.page_events = true; + lines log; + const auto app = make_app(io, net, log); + const auto room = std::make_shared(); + app->register_room("r1", room); + net.page_connectivity(false); + BOOST_TEST(room->events.empty()); // the event is posted + settle(io); + BOOST_TEST(app->relays_offline()); + BOOST_TEST(app->connectivity() == trystero::relay_connectivity::automatic); + net.page_connectivity(true); + settle(io); + BOOST_TEST(!app->relays_offline()); + app->set_connectivity(trystero::relay_connectivity::online); + net.page_connectivity(false); + settle(io); + BOOST_TEST(!app->relays_offline()); + app->set_connectivity(trystero::relay_connectivity::automatic); + net.page_connectivity(false); + settle(io); + BOOST_TEST(app->relays_offline()); + BOOST_TEST(room->events == (std::vector{ + "relays offline", + "relays online", + "relays online", + "relays offline", + })); +} + +// The last user's release ends the watch of the page: an app a pending operation still holds +// hears no page event after it, so nothing reaches the rooms or the program's log. +void the_last_user_ends_the_page_watch() { + asio::io_context io; + trystero::test::memory_network net(io); + net.page_events = true; + lines log; + const auto app = make_app(io, net, log); + const auto room = std::make_shared(); + app->register_room("r1", room); + app->add_user(); + net.page_connectivity(false); + settle(io); + BOOST_TEST(app->relays_offline()); + app->release_user(); + log.clear(); + net.page_connectivity(true); + settle(io); + BOOST_TEST(app->relays_offline()); + BOOST_TEST(log.empty()); + BOOST_TEST(room->events == (std::vector{"relays offline"})); +} + +// Every allocation of the app's construction, of its registry, of a log sentence, of the +// connectivity's fan-out to the rooms, of its key records and verified signatures and of the last +// user's release goes through its resource: the default resource refuses every request meanwhile. void every_allocation_goes_through_the_apps_resource() { - std::pmr::unsynchronized_pool_resource pool; // outlives the io_context and the connections + std::pmr::unsynchronized_pool_resource pool; // outlives the io_context asio::io_context io; trystero::test::memory_network net(io); - const auto ends = negotiate(io, net); - const auto next = negotiate(io, net); trystero::app_config config{.memory = &pool}; config.app_id = "app"; const std::string expected_password(60, 'p'); config.password = expected_password; - config.self_id = std::pmr::string(40, 'x'); // beyond the short string config.ice_servers.push_back(server("stun:stun.example:3478")); std::size_t sentences = 0; config.log = [&sentences](std::string_view, std::string_view) { ++sentences; }; const auto room = std::make_shared(); + const auto signer = trystero::create_user_identity(); + if (!BOOST_TEST(signer.has_value())) { + return; + } + constexpr std::string_view payload = "payload"; + const std::span payload_bytes( + reinterpret_cast(payload.data()), payload.size()); + const auto signature = signer->sign(payload_bytes); + if (!BOOST_TEST(signature.has_value())) { + return; + } std::shared_ptr app; - std::size_t live = 0; - const std::string_view peer = "a peer id longer than the short string"; auto* const previous = std::pmr::set_default_resource(std::pmr::null_memory_resource()); { + // The endpoint key and the ephemeral user identity drawn, their texts derived. app = std::allocate_shared(std::pmr::polymorphic_allocator<>(&pool), io.get_executor(), net, std::move(config)); + BOOST_TEST_EQ(app->self_id().size(), trystero::protocol::peer_id_size); + BOOST_TEST_EQ(app->user_id().size(), trystero::protocol::user_id_size); BOOST_TEST_EQ(app->password(), expected_password); - app->register_room("r1", "a room token longer than the short string", room); + BOOST_TEST(app->identities().verify_peer_id(app->self_id(), app->endpoint_key())); + BOOST_TEST(app->identities().verify(signer->public_key(), *signature, payload_bytes)); + BOOST_TEST_EQ(app->identities().signatures(), 1U); + app->register_room("a room id longer than the short string", room); app->add_user(); - app->adopt(peer, ends.local_pc, ends.local); - ends.local->close(); - app->adopt(peer, next.local_pc, next.local); - live = app->live_connections().size(); + app->set_connectivity(trystero::relay_connectivity::offline); app->release_user(); } std::pmr::set_default_resource(previous); - BOOST_TEST_EQ(live, 1U); - BOOST_TEST_EQ(sentences, 4U); // adopted, ended, adopted, ended - BOOST_TEST_EQ(room->events.size(), 2U); - BOOST_TEST(app->live_connections().empty()); + BOOST_TEST_EQ(sentences, 1U); // the relays go offline + BOOST_TEST(room->events == (std::vector{"relays offline"})); } // Rooms are found by id through a weak reference, and a room leaves the registry only by its own @@ -356,472 +388,95 @@ void the_registry_holds_rooms_by_a_weak_reference() { const auto app = make_app(io, net, log); auto r1 = std::make_shared(); const auto other = std::make_shared(); - app->register_room("r1", "T1", r1); + app->register_room("r1", r1); BOOST_TEST_EQ(app->counted_rooms(), 1U); BOOST_TEST(app->find_room("r1") == r1); BOOST_TEST(app->find_room("r2") == nullptr); - app->unregister_room("T1", other.get()); + app->unregister_room("r1", other.get()); BOOST_TEST(app->find_room("r1") == r1); - app->unregister_room("T1", r1.get()); + app->unregister_room("r1", r1.get()); BOOST_TEST_EQ(app->counted_rooms(), 0U); BOOST_TEST(app->find_room("r1") == nullptr); - app->register_room("r1", "T1", r1); - app->register_room("r1", "T1", other); // the same token: the later room's entry + app->register_room("r1", r1); + app->register_room("r1", other); // the same id: the later room's entry BOOST_TEST_EQ(app->counted_rooms(), 1U); BOOST_TEST(app->find_room("r1") == other); - app->register_room("r2", "T2", r1); + app->register_room("r2", r1); r1.reset(); BOOST_TEST(app->find_room("r2") == nullptr); // the registry did not keep it } -// An adopted connection advertises every registered room's token, is found by its peer and is -// live; a second connection to the same peer is held, and the first returned; once the peer sends -// on the first, the second is closed. -void adopt_starts_one_connection_per_peer() { - asio::io_context io; - trystero::test::memory_network net(io); - lines log; - const auto app = make_app(io, net, log); - const auto r1 = std::make_shared(); - const auto r2 = std::make_shared(); - app->register_room("r1", "T1", r1); - app->register_room("r2", "T2", r2); - const auto first = negotiate(io, net); - const auto c = app->adopt("B", first.local_pc, first.local); - webcpp::test::require(BOOST_TEST(c != nullptr)); - BOOST_TEST_EQ(c->peer(), "B"); - BOOST_TEST(app->find("B") == c); - BOOST_TEST(app->find("C") == nullptr); - BOOST_TEST_EQ(app->live_connections().size(), 1U); - BOOST_TEST(run_until(io, [&] { return first.received->size() == 2; })); - BOOST_TEST(*first.received == (std::vector>{presence("T1", true), - presence("T2", true)})); - const auto second = negotiate(io, net); - BOOST_TEST(app->adopt("B", second.local_pc, second.local) == c); - settle(io); - BOOST_TEST(second.local->is_open()); - BOOST_TEST(c->live()); - BOOST_TEST_EQ(app->live_connections().size(), 1U); - first.remote->send(trystero::protocol::presence_frame("T1", true)); - BOOST_TEST(run_until(io, [&] { return !second.local->is_open(); })); - BOOST_TEST(c->live()); - BOOST_TEST(app->find("B") == c); - BOOST_TEST( - log == - (lines{ - "webrtc: connection with B adopted", - "webrtc: a second connection with B held until the peer shows which one it keeps", - "webrtc: the second connection with B closed: the peer keeps the first", - })); - BOOST_TEST(r1->events == (std::vector{"+B"})); - BOOST_TEST(r2->events.empty()); -} - -// A connection opened once the peer sent on the first is closed at once: the peer keeps the -// first, and closes its own other one. -void another_connection_after_the_peers_first_frame_is_closed() { - asio::io_context io; - trystero::test::memory_network net(io); - lines log; - const auto app = make_app(io, net, log); - app->register_room("r1", "T1", std::make_shared()); - const auto first = negotiate(io, net); - const auto c = app->adopt("B", first.local_pc, first.local); - first.remote->send(trystero::protocol::presence_frame("T1", true)); - webcpp::test::require(BOOST_TEST(run_until(io, [&] { return c->used(); }))); - const auto second = negotiate(io, net); - BOOST_TEST(app->adopt("B", second.local_pc, second.local) == c); - BOOST_TEST(!second.local->is_open()); - BOOST_TEST(log == (lines{ - "webrtc: connection with B adopted", - "webrtc: another connection with B closed: the peer keeps the first", - })); -} - -/** An app of self id `self`, whose timers run on the virtual clock of `net`. */ -std::shared_ptr make_app_as(asio::io_context& io, - trystero::test::memory_network& net, lines& log, - std::string_view self) { - net.virtual_clock = true; - return make_app(io, net, log, [self](trystero::app_config& c) { c.self_id = self; }); -} - -// The lower id holds the second until the peer closes the first, as Trystero JS closes the other -// connection of a crossed pair: the second then takes the first's place, after the rooms heard -// the first's end, and hands them the frames it received meanwhile. -void the_second_replaces_a_first_the_peer_closes() { - asio::io_context io; - trystero::test::memory_network net(io); - lines log; - const auto app = make_app_as(io, net, log, "A"); - const auto room = std::make_shared(); - app->register_room("r1", "T1", room); - const auto first = negotiate(io, net); - const auto c = app->adopt("B", first.local_pc, first.local); - const auto second = negotiate(io, net); - app->adopt("B", second.local_pc, second.local); - second.remote->send(trystero::protocol::presence_frame("T1", true)); - settle(io); - BOOST_TEST(app->find("B") == c); // the lower id waits for the peer - BOOST_TEST(room->events.empty()); - first.remote->close(); - webcpp::test::require(BOOST_TEST(run_until(io, [&] { return app->find("B") != c; }))); - const auto replacement = app->find("B"); - webcpp::test::require(BOOST_TEST(replacement != nullptr)); - BOOST_TEST(replacement->live()); - BOOST_TEST(replacement->advertised("T1")); - BOOST_TEST(room->events == (std::vector{"ended B: data channel closed", "+B"})); - BOOST_TEST(run_until(io, [&] { return second.received->size() == 1; })); - BOOST_TEST(second.received->at(0) == presence("T1", true)); // the replacement advertises - BOOST_TEST_EQ(app->live_connections().size(), 1U); -} +/** A resource over new and delete that counts the blocks still holding `secret` when freed. */ +class secret_scanning_resource final : public std::pmr::memory_resource { +public: + explicit secret_scanning_resource(std::string_view secret) : secret_(secret) {} -// The higher id gives way: the peer's first frame on the second makes the second replace the -// first, which ends and so closes the peer's second. -void the_higher_id_takes_the_second_the_peer_sends_on() { - asio::io_context io; - trystero::test::memory_network net(io); - lines log; - const auto app = make_app_as(io, net, log, "Z"); - const auto room = std::make_shared(); - app->register_room("r1", "T1", room); - const auto first = negotiate(io, net); - const auto c = app->adopt("B", first.local_pc, first.local); - const auto second = negotiate(io, net); - app->adopt("B", second.local_pc, second.local); - second.remote->send(trystero::protocol::presence_frame("T1", true)); - webcpp::test::require(BOOST_TEST(run_until(io, [&] { return app->find("B") != c; }))); - BOOST_TEST(!c->live()); - BOOST_TEST(run_until(io, [&] { return !first.remote->is_open(); })); - BOOST_TEST(app->find("B")->advertised("T1")); - BOOST_TEST(room->events == - (std::vector{"ended B: the peer keeps the second connection", "+B"})); - BOOST_TEST_EQ(app->live_connections().size(), 1U); -} + /** How many freed blocks held the secret's bytes. */ + std::size_t holding = 0; -// A second the peer neither sends on nor closes, while it sends nothing on the first either, is -// closed after 2 s by the higher id and after 10 s by the lower id; the first stays. -void a_second_the_peer_leaves_alone_is_closed_in_time() { - for (const auto& [self, wait] : - {std::pair{std::string_view("Z"), 2'000ms}, std::pair{std::string_view("A"), 10'000ms}}) { - asio::io_context io; - trystero::test::memory_network net(io); - lines log; - const auto app = make_app_as(io, net, log, self); - app->register_room("r1", "T1", std::make_shared()); - const auto first = negotiate(io, net); - const auto c = app->adopt("B", first.local_pc, first.local); - const auto second = negotiate(io, net); - app->adopt("B", second.local_pc, second.local); - BOOST_TEST(net.advance(wait - 1ms)); - settle(io); - BOOST_TEST(second.local->is_open()); - BOOST_TEST(net.advance(1ms)); - settle(io); - BOOST_TEST(!second.local->is_open()); - BOOST_TEST(c->live()); - BOOST_TEST_EQ(log.back(), - "webrtc: the second connection with B closed: the peer kept neither"); +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + return std::pmr::new_delete_resource()->allocate(bytes, alignment); } -} - -// The remote's presence reaches the room of its token, a frame of a room not bound is kept when -// the room keeps frames, and the connection's end reaches every room, even when one leaves the -// registry from inside the call; the ended connection is let go. -void the_connections_events_reach_the_rooms() { - asio::io_context io; - trystero::test::memory_network net(io); - lines log; - const auto app = make_app(io, net, log); - const auto r1 = std::make_shared(); - const auto r2 = std::make_shared(); - r1->keeps = false; - app->register_room("r1", "T1", r1); - app->register_room("r2", "T2", r2); - r1->on_end = [&] { app->unregister_room("T1", r1.get()); }; - const auto ends = negotiate(io, net); - auto c = app->adopt("B", ends.local_pc, ends.local); - const std::weak_ptr weak = c; - ends.remote->send(trystero::protocol::presence_frame("T1", true)); - ends.remote->send(trystero::protocol::presence_frame("T9", true)); // no room of the app - ends.remote->send(trystero::protocol::presence_frame("T1", false)); - const std::array action{2, 0}; - ends.remote->send(trystero::protocol::room_frame("T1", action)); // r1 drops frames - ends.remote->send(trystero::protocol::room_frame("T2", action)); - ends.remote->send(trystero::protocol::room_frame("T9", action)); // no room: dropped - BOOST_TEST(run_until(io, [&] { return r2->events.size() == 1; })); - settle(io); - BOOST_TEST(r1->events == (std::vector{"+B", "-B"})); - BOOST_TEST(r2->events == (std::vector{"kept B"})); - BOOST_TEST_EQ(c->kept_count(), 1U); - BOOST_TEST_EQ(c->take_kept("T2").size(), 1U); - c.reset(); - net.fail(ends.local_id); - BOOST_TEST(run_until(io, [&] { return r1->events.size() == 3; })); - settle(io); - BOOST_TEST_EQ(r1->events.back(), "ended B: connection failed"); - BOOST_TEST_EQ(r2->events.back(), "ended B: connection failed"); - BOOST_TEST_EQ(app->counted_rooms(), 1U); // r1 left during its call - BOOST_TEST(app->find("B") == nullptr); - BOOST_TEST(app->live_connections().empty()); - BOOST_TEST(weak.expired()); -} - -// The last user's release ends every connection, at that call; an earlier release ends none. -void the_last_user_ends_every_connection() { - asio::io_context io; - trystero::test::memory_network net(io); - lines log; - const auto app = make_app(io, net, log); - const auto room = std::make_shared(); - app->register_room("r1", "T1", room); - const auto b = negotiate(io, net); - const auto c = negotiate(io, net); - app->add_user(); - app->add_user(); - const auto to_b = app->adopt("B", b.local_pc, b.local); - const auto to_c = app->adopt("C", c.local_pc, c.local); - app->release_user(); - BOOST_TEST(to_b->live() && to_c->live()); - BOOST_TEST(room->events.empty()); - app->release_user(); - BOOST_TEST(!to_b->live() && !to_c->live()); - BOOST_TEST(room->events == (std::vector{ - "ended B: the app has no room left", - "ended C: the app has no room left", - })); - BOOST_TEST(app->live_connections().empty()); - app->release_user(); // no user left: nothing to release - BOOST_TEST_EQ(room->events.size(), 2U); - const auto d = negotiate(io, net); - const auto to_d = app->adopt("D", d.local_pc, d.local); - app->add_user(); - app->release_user(); - BOOST_TEST(!to_d->live()); - BOOST_TEST_EQ(room->events.back(), "ended D: the app has no room left"); -} -// A connection whose channel is closing is not reused; the connection that replaces it ends it -// first, as Trystero clears a stale peer (dist/shared-peer.mjs:142-149), so the rooms hear its end -// before the new one is adopted, and its later close event ends nothing. -void a_stale_connection_ends_before_its_replacement() { - asio::io_context io; - trystero::test::memory_network net(io); - lines log; - const auto app = make_app(io, net, log); - const auto room = std::make_shared(); - app->register_room("r1", "T1", room); - const auto first = negotiate(io, net); - const auto second = negotiate(io, net); - const auto stale = app->adopt("B", first.local_pc, first.local); - first.local->close(); // closing: its close event is posted - BOOST_TEST(app->find("B") == nullptr); - BOOST_TEST(app->live_connections().empty()); - const auto fresh = app->adopt("B", second.local_pc, second.local); - BOOST_TEST(fresh != stale); - BOOST_TEST(room->events == - (std::vector{"ended B: replaced by a new connection to the peer"})); - settle(io); - BOOST_TEST(app->find("B") == fresh); - BOOST_TEST(fresh->live()); - BOOST_TEST_EQ(room->events.size(), 1U); -} - -// A room that adopts a connection to the peer from inside the stale connection's end: the -// replacement the outer adoption brought is held as the second, and the room's is the one kept, -// so the peer has one connection, whose end by this side closes the second too and leaves none -// (Trystero's owns(), dist/shared-peer.mjs:210-212). -void an_adoption_from_inside_a_stale_end_is_the_one_kept() { - asio::io_context io; - trystero::test::memory_network net(io); - lines log; - const auto app = make_app(io, net, log); - const auto room = std::make_shared(); - app->register_room("r1", "T1", room); - const auto first = negotiate(io, net); - const auto second = negotiate(io, net); - const auto third = negotiate(io, net); - app->adopt("B", first.local_pc, first.local); - std::shared_ptr nested; - room->on_end = [&] { - if (!nested) { - nested = app->adopt("B", third.local_pc, third.local); + void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override { + const std::string_view block(static_cast(p), bytes); + if (block.find(secret_) != std::string_view::npos) { + ++holding; } - }; - first.local->close(); - const auto outer = app->adopt("B", second.local_pc, second.local); - webcpp::test::require(BOOST_TEST(nested != nullptr)); - BOOST_TEST(outer == nested); - BOOST_TEST(second.local->is_open()); - BOOST_TEST(nested->live()); - BOOST_TEST_EQ(app->live_connections().size(), 1U); - settle(io); - BOOST_TEST(app->find("B") == nested); - room->on_end = {}; - nested->end("test"); - BOOST_TEST(app->find("B") == nullptr); - BOOST_TEST(app->live_connections().empty()); - BOOST_TEST(!second.local->is_open()); - BOOST_TEST_EQ(room->events.back(), "ended B: test"); -} - -// A room adopts a connection to the peer from inside the stale connection's end, and its channel -// starts closing before the outer adoption goes on: that one is stale too, and ends before the -// outer one is adopted, so no room hears an end once the outer one is the peer's. -void a_nested_adoption_gone_stale_ends_before_the_outer_one() { - asio::io_context io; - trystero::test::memory_network net(io); - lines log; - const auto app = make_app(io, net, log); - const auto room = std::make_shared(); - app->register_room("r1", "T1", room); - const auto first = negotiate(io, net); - const auto second = negotiate(io, net); - const auto third = negotiate(io, net); - app->adopt("B", first.local_pc, first.local); - std::shared_ptr nested; - room->on_end = [&] { - if (!nested) { - nested = app->adopt("B", third.local_pc, third.local); - third.local->close(); // closing: its close event is posted - } - }; - first.local->close(); - const auto outer = app->adopt("B", second.local_pc, second.local); - webcpp::test::require(BOOST_TEST(nested != nullptr)); - BOOST_TEST(outer != nested); - const std::vector ends{ - "ended B: replaced by a new connection to the peer", - "ended B: replaced by a new connection to the peer", - }; - BOOST_TEST(room->events == ends); - settle(io); - BOOST_TEST(room->events == ends); - BOOST_TEST(app->find("B") == outer); - BOOST_TEST(outer->live()); - BOOST_TEST_EQ(app->live_connections().size(), 1U); -} + std::pmr::new_delete_resource()->deallocate(p, bytes, alignment); + } -// An adoption from inside a connection's own end, before the rooms hear it (a drain waiter the end -// fails): the ending connection is let go, the new one is the peer's, and the rooms hear the end -// once. -void an_adoption_from_inside_an_end_under_way() { - asio::io_context io; - trystero::test::memory_network net(io); - lines log; - const auto app = make_app(io, net, log); - const auto room = std::make_shared(); - app->register_room("r1", "T1", room); - const auto first = negotiate(io, net); - const auto second = negotiate(io, net); - const auto c = app->adopt("B", first.local_pc, first.local); - auto* m = std::pmr::get_default_resource(); - const std::pmr::polymorphic_allocator<> alloc(m); - const auto b = std::allocate_shared( - alloc, c, "T1", - trystero::handler)>( - std::allocator_arg, alloc, - [](trystero::backend::bytes&&, std::span) {}), - m); - net.channel_capacity = 1; - const std::vector payload(16'000, 0); - for (std::size_t i = 0; i < 5; ++i) { - webcpp::test::require( - BOOST_TEST(b->send(trystero::protocol::room_frame("T9", payload, m)))); + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; } - std::shared_ptr nested; - b->wait_drained({std::allocator_arg, alloc, - [&](bool) { nested = app->adopt("B", second.local_pc, second.local); }}); - c->end("test"); - webcpp::test::require(BOOST_TEST(nested != nullptr)); - BOOST_TEST(nested != c); - BOOST_TEST(nested->live()); - BOOST_TEST(app->find("B") == nested); - BOOST_TEST(room->events == (std::vector{"ended B: test"})); - // The end the rooms hear names the connection that ended, not the peer's new one. - webcpp::test::require(BOOST_TEST_EQ(room->ended_connections.size(), 1U)); - BOOST_TEST(room->ended_connections.front().lock() == c); - settle(io); - BOOST_TEST(app->find("B") == nested); - BOOST_TEST_EQ(room->events.size(), 1U); -} -// A connection's end takes its own entry only: the last user's release ends the connections it -// took out of the registry, and a room that adopts one to the same peer from inside the calls keeps -// it registered, though the rooms still hear the released connection's end. -void an_end_takes_only_its_own_entry() { - asio::io_context io; - trystero::test::memory_network net(io); - lines log; - const auto app = make_app(io, net, log); - const auto room = std::make_shared(); - app->register_room("r1", "T1", room); - const auto b = negotiate(io, net); - const auto c = negotiate(io, net); - const auto again = negotiate(io, net); - app->add_user(); - app->adopt("B", b.local_pc, b.local); - app->adopt("C", c.local_pc, c.local); - std::shared_ptr nested; - room->on_end = [&] { - if (!nested) { - nested = app->adopt("C", again.local_pc, again.local); - } - }; - app->release_user(); - webcpp::test::require(BOOST_TEST(nested != nullptr)); - BOOST_TEST(room->events == (std::vector{ - "ended B: the app has no room left", - "ended C: the app has no room left", - })); - BOOST_TEST(nested->live()); - BOOST_TEST(app->find("C") == nested); -} + std::string_view secret_; +}; -// The peer named by a view into the stale connection, which its end frees: the replacement is -// adopted under a copy taken before the end. -void a_view_into_the_stale_connection_names_its_replacement() { - asio::io_context io; - trystero::test::memory_network net(io); - lines log; - const auto app = make_app(io, net, log); - const auto first = negotiate(io, net); - const auto second = negotiate(io, net); - const std::string id(40, 'p'); // beyond the short string: the view is into the heap - const std::weak_ptr stale = app->adopt(id, first.local_pc, first.local); - first.local->close(); - const auto view = stale.lock()->peer(); - const auto fresh = app->adopt(view, second.local_pc, second.local); - BOOST_TEST(stale.expired()); - BOOST_TEST_EQ(fresh->peer(), id); - BOOST_TEST(app->find(id) == fresh); +// No block the app frees holds its password: the app's own copy, the cache's and a derivation's +// are wiped before they are released, as the app itself is. +void the_password_is_wiped_before_it_is_freed() { + const std::string password = "a password no freed block of the app may still hold"; + secret_scanning_resource memory(password); + { + asio::io_context io; + trystero::test::memory_network net(io); + trystero::app_config config{.memory = &memory}; + config.app_id = "app"; + config.password = password; + auto app = std::allocate_shared( + std::pmr::polymorphic_allocator<>(&memory), io.get_executor(), net, std::move(config)); + bool derived = false; + app->room_keys().get( + "room", [&derived](boost::system::error_code ec, const trystero::protocol::room_keys&) { + BOOST_TEST(!ec); + derived = true; + }); + BOOST_TEST(run_until(io, [&derived] { return derived; })); + BOOST_TEST_EQ(app->password(), password); + app.reset(); + settle(io); + } + BOOST_TEST_EQ(memory.holding, 0U); } -// The app's destruction ends nothing and calls nothing back, and a connection that outlives it -// routes nothing. +// The app's destruction ends nothing and calls nothing back: a page event after it reaches no room +// and no log, as the watch went with it. void the_apps_destruction_is_quiet() { asio::io_context io; trystero::test::memory_network net(io); + net.page_events = true; lines log; auto app = make_app(io, net, log); const auto room = std::make_shared(); - app->register_room("r1", "T1", room); - const auto ends = negotiate(io, net); - const auto c = app->adopt("B", ends.local_pc, ends.local); - const auto logged = log.size(); + app->register_room("r1", room); app.reset(); settle(io); - BOOST_TEST(c->live()); - ends.remote->send(trystero::protocol::presence_frame("T1", true)); - const std::array action{2, 0}; - ends.remote->send(trystero::protocol::room_frame("T1", action)); + net.page_connectivity(false); settle(io); - BOOST_TEST(c->advertised("T1")); - BOOST_TEST_EQ(c->kept_count(), 0U); // no app: no room keeps it - c->end("test"); BOOST_TEST(room->events.empty()); - BOOST_TEST_EQ(log.size(), logged + 1); // the connection's own line, through the shared sink - BOOST_TEST_EQ(log.back(), "webrtc: connection with B ended: test"); + BOOST_TEST(log.empty()); } } // namespace @@ -832,23 +487,14 @@ int main() { run_case(the_configuration_is_copied_and_completed); run_case(what_the_configuration_names_is_kept); run_case(what_no_peer_could_use_is_set_aside); - run_case(a_self_id_that_is_not_utf8_is_set_aside); + run_case(no_custom_self_id); + run_case(the_connectivity_reaches_every_room); + run_case(an_automatic_app_follows_the_pages_events); + run_case(the_last_user_ends_the_page_watch); run_case(every_allocation_goes_through_the_apps_resource); run_case(the_registry_holds_rooms_by_a_weak_reference); - run_case(adopt_starts_one_connection_per_peer); - run_case(another_connection_after_the_peers_first_frame_is_closed); - run_case(the_second_replaces_a_first_the_peer_closes); - run_case(the_higher_id_takes_the_second_the_peer_sends_on); - run_case(a_second_the_peer_leaves_alone_is_closed_in_time); - run_case(the_connections_events_reach_the_rooms); - run_case(the_last_user_ends_every_connection); - run_case(a_stale_connection_ends_before_its_replacement); - run_case(an_adoption_from_inside_a_stale_end_is_the_one_kept); - run_case(a_nested_adoption_gone_stale_ends_before_the_outer_one); - run_case(an_adoption_from_inside_an_end_under_way); - run_case(an_end_takes_only_its_own_entry); - run_case(a_view_into_the_stale_connection_names_its_replacement); run_case(the_apps_destruction_is_quiet); + run_case(the_password_is_wiped_before_it_is_freed); // Under Asyncify, a main that suspended loses what it returns: the status goes first. return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/connection_test.cpp b/test/connection_test.cpp deleted file mode 100644 index 4409ad7..0000000 --- a/test/connection_test.cpp +++ /dev/null @@ -1,946 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -// The shared connection alone, over a memory pair: routing by token, kept frames, presence, the -// bound on advertised rooms, malformed frames, the drain waiters, the end, the idle time and a -// disconnection, and calls back into the connection or a binding from inside its own calls. - -#include -#include - -#include "support/memory_backend.hpp" - -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "require.hpp" - -namespace asio = webcpp::asio; -namespace trystero = webcpp::trystero; -namespace detail = webcpp::trystero::detail; -using namespace std::chrono_literals; - -namespace { - -bool run_until(asio::io_context& io, const std::function& done, - std::chrono::milliseconds limit = 5s) { - const auto end = std::chrono::steady_clock::now() + limit; - while (!done() && std::chrono::steady_clock::now() < end) { - io.run_for(10ms); // lint-run: the memory network posts to it - if (io.stopped()) { - io.restart(); - } - } - return done(); -} - -/** Runs the ready work of `io` until there is none: the memory network's drains are posted, not - * timed. */ -void settle(asio::io_context& io) { - io.restart(); - while (io.poll() > 0) { - io.restart(); - } -} - -/** What one side's connection reported, and what its app does from inside the calls. */ -struct side { - std::shared_ptr c; - std::vector presence; // "+T" or "-T" - std::vector kept; - std::string ended; - /** `keeps` ends the connection, then says yes. */ - bool end_in_keeps = false; - /** `kept` takes the kept frames of its token, then reads the token. */ - bool take_in_kept = false; - std::size_t taken = 0; - std::size_t used = 0; // the calls of `used` -}; - -detail::connection_callbacks callbacks(side& s) { - auto* m = std::pmr::get_default_resource(); - const std::pmr::polymorphic_allocator<> a(m); - return { - .presence = - { - std::allocator_arg, - a, - [&s](std::string_view, std::string_view t, bool present) { - s.presence.push_back((present ? "+" : "-") + std::string(t)); - }, - }, - .keeps = - { - std::allocator_arg, - a, - [&s](std::string_view, std::string_view t) { - if (s.end_in_keeps) { - s.c->end("ended in keeps"); - } - return t != "nobody"; - }, - }, - .kept = - { - std::allocator_arg, - a, - [&s](std::string_view, std::string_view t) { - if (s.take_in_kept) { - s.taken += s.c->take_kept(t).size(); - } - s.kept.emplace_back(t); // after the take: the token must outlive it - }, - }, - .ended = - { - std::allocator_arg, - a, - [&s](std::string_view, std::string_view why) { s.ended = why; }, - }, - .used = - { - std::allocator_arg, - a, - [&s](std::string_view) { ++s.used; }, - }, - }; -} - -/** Two connections over a memory pair, each started with the tokens given. */ -struct link_pair { - asio::io_context io; - trystero::test::memory_network net{io}; - std::shared_ptr offerer; // a's, id 0 - std::shared_ptr answerer; // b's, id 1 - side a; - side b; - - link_pair(std::span a_tokens, - std::span b_tokens); -}; - -link_pair::link_pair(std::span a_tokens, - std::span b_tokens) { - net.virtual_clock = true; // the keep timer waits for advance() - auto* m = std::pmr::get_default_resource(); - const std::pmr::polymorphic_allocator<> alloc(m); - offerer = net.make_peer_connection({}, m); - answerer = net.make_peer_connection({}, m); - auto offer_end = offerer->create_data_channel("data"); - std::shared_ptr answer_end; - answerer->set_handlers({ - .ice_candidate = {}, - .data_channel = - [&answer_end](std::shared_ptr c) { - answer_end = std::move(c); - }, - .state = {}, - }); - std::pmr::string offer(m); - std::pmr::string answer(m); - offerer->set_local_description([&offer](trystero::backend::error_code, std::string_view, - std::string_view sdp) { offer = sdp; }); - webcpp::test::require(BOOST_TEST(run_until(io, [&] { return !offer.empty(); }))); - answerer->set_remote_description("offer", offer, [](trystero::backend::error_code) {}); - answerer->set_local_description([&answer](trystero::backend::error_code, std::string_view, - std::string_view sdp) { answer = sdp; }); - webcpp::test::require(BOOST_TEST(run_until(io, [&] { return !answer.empty(); }))); - offerer->set_remote_description("answer", answer, [](trystero::backend::error_code) {}); - webcpp::test::require(BOOST_TEST(run_until( - io, [&] { return offer_end->is_open() && answer_end && answer_end->is_open(); }))); - a.c = std::allocate_shared(alloc, net, "B", offerer, offer_end, - callbacks(a), detail::logger{}, m); - b.c = std::allocate_shared(alloc, net, "A", answerer, answer_end, - callbacks(b), detail::logger{}, m); - a.c->start(a_tokens); - b.c->start(b_tokens); -} - -/** A binding of `token` on `c`, which records the action of every frame delivered to it. */ -std::shared_ptr make_binding(const std::shared_ptr& c, - std::string_view token, - std::vector>& got) { - auto* m = std::pmr::get_default_resource(); - const std::pmr::polymorphic_allocator<> alloc(m); - return std::allocate_shared( - alloc, c, token, - trystero::handler)>( - std::allocator_arg, alloc, - [&got](trystero::backend::bytes&&, std::span action) { - got.emplace_back(action.begin(), action.end()); - }), - m); -} - -/** A binding of `token` on `c`, made in `pool`, which reuses a freed block at once. */ -std::shared_ptr make_pooled(std::pmr::memory_resource& pool, - const std::shared_ptr& c, - std::string_view token) { - const std::pmr::polymorphic_allocator<> alloc(&pool); - return std::allocate_shared( - alloc, c, token, - trystero::handler)>( - std::allocator_arg, alloc, - [](trystero::backend::bytes&&, std::span) {}), - &pool); -} - -/** Sends through `b` room frames the other side drops, of `payloads` bytes of action each. */ -void send_dropped(detail::binding& b, std::span payloads) { - auto* m = std::pmr::get_default_resource(); - for (const auto size : payloads) { - const std::vector payload(size, 0); - BOOST_TEST(b.send(trystero::protocol::room_frame("nobody", payload, m))); - } -} - -/** Fills a buffering channel past Trystero's threshold through `b`: 5 frames of 16,009 bytes. */ -void fill(detail::binding& b) { - const std::array payloads{16'000, 16'000, 16'000, 16'000, 16'000}; - send_dropped(b, payloads); -} - -/** A waiter that records `name`, or `!name` when told the channel closed. */ -trystero::handler record(std::vector& turns, std::string name) { - return {std::allocator_arg, std::pmr::polymorphic_allocator<>(std::pmr::get_default_resource()), - [&turns, name = std::move(name)](bool open) { - turns.emplace_back(open ? name : "!" + name); - }}; -} - -void start_advertises_every_token() { - const std::array a_tokens{"T1", "T2"}; - const std::array b_tokens{"T1"}; - link_pair p(a_tokens, b_tokens); - BOOST_TEST( - run_until(p.io, [&] { return p.b.presence.size() == 2 && p.a.presence.size() == 1; })); - BOOST_TEST(p.b.presence == (std::vector{"+T1", "+T2"})); - BOOST_TEST(p.a.presence == (std::vector{"+T1"})); - BOOST_TEST(p.b.c->advertised("T1") && p.b.c->advertised("T2") && !p.b.c->advertised("T3")); - BOOST_TEST(p.a.c->advertised("T1") && !p.a.c->advertised("T2")); -} - -void a_withdrawn_token_is_forgotten() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.c->advertised("T1"); }))); - p.a.c->send_presence("T1", false); - BOOST_TEST(run_until(p.io, [&] { return !p.b.c->advertised("T1"); })); - BOOST_TEST(p.b.presence == (std::vector{"+T1", "-T1"})); -} - -void a_bound_token_reaches_its_binding_and_another_is_kept() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - std::vector> got; - const auto bound = make_binding(p.b.c, "T1", got); - auto* m = std::pmr::get_default_resource(); - const std::array action{2, 0}; - p.a.c->send(trystero::protocol::room_frame("T1", action, m)); - p.a.c->send(trystero::protocol::room_frame("T2", action, m)); - p.a.c->send(trystero::protocol::room_frame("nobody", action, m)); - BOOST_TEST(run_until(p.io, [&] { return got.size() == 1 && p.b.kept.size() == 1; })); - BOOST_TEST(got.at(0) == (std::vector{2, 0})); - BOOST_TEST_EQ(p.b.kept.at(0), "T2"); - BOOST_TEST_EQ(p.b.c->kept_count(), 1U); - BOOST_TEST_EQ(p.b.c->take_kept("T2").size(), 1U); - BOOST_TEST_EQ(p.b.c->kept_count(), 0U); - BOOST_TEST(p.b.c->take_kept("nobody").empty()); -} - -void a_withdrawn_token_drops_its_kept_frames() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - auto* m = std::pmr::get_default_resource(); - const std::array action{2, 0}; - p.a.c->send(trystero::protocol::room_frame("T2", action, m)); - p.a.c->send(trystero::protocol::room_frame("T3", action, m)); - webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.kept.size() == 2; }))); - p.a.c->send_presence("T2", false); - BOOST_TEST(run_until(p.io, [&] { return p.b.presence.size() == 2; })); - BOOST_TEST_EQ(p.b.c->kept_count(), 1U); - BOOST_TEST(p.b.c->take_kept("T2").empty()); - BOOST_TEST_EQ(p.b.c->take_kept("T3").size(), 1U); -} - -// A room frame the app keeps advertises its token, as the remote's presence does, and reports no -// presence: only the remote writes to its connection, and its presence for a room comes once per -// connection, which a page can lose (Chrome drops what a page sends on an answering channel as it -// opens). A frame the app does not keep advertises nothing. -void a_kept_frame_advertises_its_token() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - auto* m = std::pmr::get_default_resource(); - const std::array action{2, 0}; - p.a.c->send(trystero::protocol::room_frame("nobody", action, m)); - p.a.c->send(trystero::protocol::room_frame("T2", action, m)); - webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.kept.size() == 1; }))); - BOOST_TEST(p.b.c->advertised("T2")); - BOOST_TEST(!p.b.c->advertised("nobody")); - BOOST_TEST(p.b.presence == (std::vector{"+T1"})); -} - -// A kept frame never advertises a 65th token, nor ends the connection as a 65th presence does: -// it is kept, and its token is not advertised. -void a_kept_frame_never_advertises_a_65th_token() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - auto* m = std::pmr::get_default_resource(); - for (std::size_t i = 0; i < 63; ++i) { - p.a.c->send(trystero::protocol::presence_frame("X" + std::to_string(i), true, m)); - } - const std::array action{2, 0}; - p.a.c->send(trystero::protocol::room_frame("T2", action, m)); - webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.kept.size() == 1; }))); - BOOST_TEST_EQ(p.b.presence.size(), 64U); - BOOST_TEST(!p.b.c->advertised("T2")); - BOOST_TEST(p.b.ended.empty()); - BOOST_TEST(p.b.c->live()); -} - -void a_65th_advertised_token_ends_the_connection() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - auto* m = std::pmr::get_default_resource(); - // T1 and 63 more: 64 tokens, the most a remote may advertise. - for (std::size_t i = 0; i < 63; ++i) { - p.a.c->send(trystero::protocol::presence_frame("X" + std::to_string(i), true, m)); - } - webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.presence.size() == 64; }))); - BOOST_TEST(p.b.ended.empty()); - p.a.c->send(trystero::protocol::presence_frame("X0", true, m)); // known: not a new token - p.a.c->send(trystero::protocol::presence_frame("X63", true, m)); - BOOST_TEST(run_until(p.io, [&] { return !p.b.ended.empty(); })); - BOOST_TEST_EQ(p.b.ended, "too many advertised rooms"); - BOOST_TEST_EQ(p.b.presence.size(), 65U); - BOOST_TEST(!p.b.c->live()); - BOOST_TEST(run_until(p.io, [&] { return p.a.ended == "data channel closed"; })); -} - -void a_malformed_frame_ends_the_connection() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - const std::array bad{3, 0, 1, 'x'}; - p.a.c->send(bad); - BOOST_TEST(run_until(p.io, [&] { return !p.b.ended.empty(); })); - BOOST_TEST_EQ(p.b.ended, "invalid or incompatible room frame"); -} - -void kept_frames_are_bounded_and_dropped_after_10_s() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - auto* m = std::pmr::get_default_resource(); - const std::string token(trystero::protocol::max_room_token_bytes, 'T'); - const std::vector action(trystero::protocol::max_action_frame_bytes, 0); - const auto frame = trystero::protocol::room_frame(token, action, m); - BOOST_TEST_EQ(frame.size(), 16'515U); - for (std::size_t i = 0; i < 65; ++i) { - p.a.c->send(trystero::protocol::room_frame(token, action, m)); - } - BOOST_TEST(run_until(p.io, [&] { return p.b.kept.size() == 64; })); - BOOST_TEST(p.net.advance(9'999ms)); - BOOST_TEST_EQ(p.b.kept.size(), 64U); // the 65th, beyond the bound, was not kept - BOOST_TEST_EQ(p.b.c->kept_count(), 64U); - BOOST_TEST(p.net.advance(1ms)); // 10 s after the first was kept - BOOST_TEST_EQ(p.b.c->kept_count(), 0U); - BOOST_TEST(p.b.c->take_kept(token).empty()); -} - -// A connection whose channel is closing or closed is not live, so the app does not reuse it. -void a_closing_channel_is_not_live() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - BOOST_TEST(p.a.c->live()); - p.net.fail(p.net.peer_of(0)); - BOOST_TEST(run_until(p.io, [&] { return !p.a.c->live(); })); - BOOST_TEST(run_until(p.io, [&] { return !p.a.ended.empty() && !p.b.ended.empty(); })); - BOOST_TEST_EQ(p.b.ended, "connection failed"); -} - -// The bindings waiting at one drain each get their turn, in the order they began to wait, and a -// binding destroyed by an earlier turn gets none. -void drain_turns_follow_the_order_of_waiting() { - const std::array tokens{"T1", "T2", "T3"}; - link_pair p(tokens, tokens); - webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.presence.size() == 3; }))); - std::vector> got; - const auto t1 = make_binding(p.a.c, "T1", got); - const auto t2 = make_binding(p.a.c, "T2", got); - auto t3 = make_binding(p.a.c, "T3", got); - p.net.channel_capacity = 1; - auto* m = std::pmr::get_default_resource(); - // Frames the other side drops, past the threshold: 5 x 16,000 bytes. - const std::vector payload(16'000, 0); - for (std::size_t i = 0; i < 5; ++i) { - BOOST_TEST(t1->send(trystero::protocol::room_frame("nobody", payload, m))); - } - webcpp::test::require( - BOOST_TEST_GT(t1->buffered_amount(), trystero::backend::data_channel::low_threshold)); - std::vector turns; - const std::pmr::polymorphic_allocator<> alloc(m); - t2->wait_drained({std::allocator_arg, alloc, - [&turns](bool open) { turns.emplace_back(open ? "T2" : "!T2"); }}); - t1->wait_drained({std::allocator_arg, alloc, [&turns, &t3](bool open) { - turns.emplace_back(open ? "T1" : "!T1"); - t3.reset(); - }}); - t3->wait_drained({std::allocator_arg, alloc, - [&turns](bool open) { turns.emplace_back(open ? "T3" : "!T3"); }}); - t2->wait_drained({std::allocator_arg, alloc, - [&turns](bool open) { turns.emplace_back(open ? "T2'" : "!T2'"); }}); - BOOST_TEST(run_until(p.io, [&] { return turns.size() >= 3; })); - settle(p.io); - BOOST_TEST(turns == (std::vector{"T2", "T2'", "T1"})); - BOOST_TEST(!t3); - BOOST_TEST(p.a.ended.empty() && p.b.ended.empty()); -} - -// A connection's end fails every waiting binding's drain, once. -void the_end_fails_every_drain_waiter() { - const std::array tokens{"T1", "T2"}; - link_pair p(tokens, tokens); - std::vector> got; - const auto t1 = make_binding(p.a.c, "T1", got); - const auto t2 = make_binding(p.a.c, "T2", got); - p.net.channel_capacity = 1; - auto* m = std::pmr::get_default_resource(); - const std::vector payload(16'000, 0); - for (std::size_t i = 0; i < 5; ++i) { - t1->send(trystero::protocol::room_frame("nobody", payload, m)); - } - std::vector turns; - const std::pmr::polymorphic_allocator<> alloc(m); - t1->wait_drained({std::allocator_arg, alloc, - [&turns](bool open) { turns.emplace_back(open ? "T1" : "!T1"); }}); - t2->wait_drained({std::allocator_arg, alloc, - [&turns](bool open) { turns.emplace_back(open ? "T2" : "!T2"); }}); - p.a.c->end("test"); - BOOST_TEST(turns == (std::vector{"!T1", "!T2"})); - BOOST_TEST_EQ(p.a.ended, "test"); - BOOST_TEST(!t1->send(trystero::protocol::room_frame("T1", payload, m))); - t1->wait_drained({std::allocator_arg, alloc, - [&turns](bool open) { turns.emplace_back(open ? "T1" : "!T1"); }}); - BOOST_TEST_EQ(turns.size(), 3U); - BOOST_TEST_EQ(turns.back(), "!T1"); -} - -// The end fails the waiters in the order they began to wait, not in the order their bindings -// attached. -void the_end_fails_the_waiters_in_the_order_of_waiting() { - const std::array tokens{"T1", "T2"}; - link_pair p(tokens, tokens); - std::vector> got; - const auto t1 = make_binding(p.a.c, "T1", got); - const auto t2 = make_binding(p.a.c, "T2", got); - p.net.channel_capacity = 1; - fill(*t1); - std::vector turns; - t2->wait_drained(record(turns, "T2")); - t1->wait_drained(record(turns, "T1")); - BOOST_TEST(turns.empty()); - p.a.c->end("test"); - BOOST_TEST(turns == (std::vector{"!T2", "!T1"})); -} - -// The last binding to detach ends the connection after a kick, or with no idle time; otherwise -// after the idle time, which a new binding cancels. -void the_last_binding_ends_or_idles_the_connection() { - const std::array tokens{"T1"}; - std::vector> got; - { - const link_pair p(tokens, tokens); - const auto t1 = make_binding(p.a.c, "T1", got); - const auto t2 = make_binding(p.a.c, "T2", got); - t1->detach(true, 1000ms); - BOOST_TEST(p.a.ended.empty()); // T2 is still bound - t2->detach(true, 1000ms); - BOOST_TEST_EQ(p.a.ended, "its last room kicked the peer"); - } - { - const link_pair p(tokens, tokens); - const auto t1 = make_binding(p.a.c, "T1", got); - t1->detach(false, 0ms); - BOOST_TEST_EQ(p.a.ended, "no room left"); - } - { - link_pair p(tokens, tokens); - const auto t1 = make_binding(p.a.c, "T1", got); - t1->detach(false, 1000ms); - BOOST_TEST(p.net.advance(999ms)); - const auto t2 = make_binding(p.a.c, "T2", got); // cancels the idle timer - BOOST_TEST(p.net.advance(10'000ms)); - BOOST_TEST(p.a.ended.empty()); - t2->detach(false, 1000ms); - BOOST_TEST(p.net.advance(999ms)); - BOOST_TEST(p.a.ended.empty()); - BOOST_TEST(p.net.advance(1ms)); - BOOST_TEST_EQ(p.a.ended, "idle"); - } -} - -// A turn destroys a binding that waits after it and makes another in the same resource, which a -// pool gives the freed block: the new binding began to wait during this drain, so its turn is the -// next drain, once the channel has drained, never the old one's. -void a_binding_made_during_a_drain_waits_for_the_next() { - const std::array tokens{"T1", "T2", "T3"}; - link_pair p(tokens, tokens); - std::pmr::unsynchronized_pool_resource pool; - const auto t1 = make_pooled(pool, p.a.c, "T1"); - auto t2 = make_pooled(pool, p.a.c, "T2"); - std::shared_ptr t3; - p.net.channel_capacity = 1; - fill(*t1); - std::vector turns; - std::size_t t3_buffered_at_its_turn = 0; - const void* const t2_address = t2.get(); - bool same_address = false; - const std::pmr::polymorphic_allocator<> alloc(std::pmr::get_default_resource()); - t1->wait_drained({std::allocator_arg, alloc, [&](bool) { - turns.emplace_back("T1"); - fill(*t1); // above the threshold again - t2.reset(); - t3 = make_pooled(pool, p.a.c, "T3"); - same_address = t3.get() == t2_address; - t3->wait_drained({std::allocator_arg, alloc, [&](bool) { - turns.emplace_back("T3"); - t3_buffered_at_its_turn = t3->buffered_amount(); - }}); - }}); - t2->wait_drained(record(turns, "T2")); - BOOST_TEST(run_until(p.io, [&] { return turns.size() >= 2; })); - BOOST_TEST(same_address); - BOOST_TEST(turns == (std::vector{"T1", "T3"})); - BOOST_TEST_LE(t3_buffered_at_its_turn, trystero::backend::data_channel::low_threshold); -} - -// A turn that ends the connection: every binding still waiting after it is told `false`. -void an_end_inside_a_drain_fails_the_waiters_after_it() { - const std::array tokens{"T1", "T2"}; - link_pair p(tokens, tokens); - std::vector> got; - const auto t1 = make_binding(p.a.c, "T1", got); - const auto t2 = make_binding(p.a.c, "T2", got); - p.net.channel_capacity = 1; - fill(*t1); - std::vector turns; - const std::pmr::polymorphic_allocator<> alloc(std::pmr::get_default_resource()); - t1->wait_drained({std::allocator_arg, alloc, [&](bool open) { - turns.emplace_back(open ? "T1" : "!T1"); - p.a.c->end("ended in a turn"); - }}); - t2->wait_drained(record(turns, "T2")); - BOOST_TEST(run_until(p.io, [&] { return !p.a.ended.empty(); })); - settle(p.io); - BOOST_TEST_EQ(p.a.ended, "ended in a turn"); - BOOST_TEST(turns == (std::vector{"T1", "!T2"})); -} - -// A waiter may end the connection or detach its own binding. Waiters already selected for -// that same drain must fail before the ending call returns, not receive a stale success later. -void an_end_inside_one_binding_fails_its_remaining_waiters() { - for (const bool detach : {false, true}) { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - std::vector> got; - const auto t1 = make_binding(p.a.c, "T1", got); - p.net.channel_capacity = 1; - fill(*t1); - std::vector turns; - const std::pmr::polymorphic_allocator<> alloc(std::pmr::get_default_resource()); - t1->wait_drained({std::allocator_arg, alloc, [&](bool open) { - BOOST_TEST(open); - turns.emplace_back("first"); - if (detach) { - t1->detach(false, 1000ms); - } else { - p.a.c->end("ended in its own drain"); - } - BOOST_TEST(turns == (std::vector{"first", "!second"})); - }}); - t1->wait_drained(record(turns, "second")); - BOOST_TEST(run_until(p.io, [&] { return turns.size() == 2; })); - BOOST_TEST(turns == (std::vector{"first", "!second"})); - } -} - -/** A binding of T1 on `p`'s b side whose delivery kicks the peer (`destroy` false) or drops the - * binding (`destroy` true), then reads its own capture, as a room's delivery passes its `peer` - * on after a kick: a use-after-free here would fail under the sanitizers. */ -void a_delivery_that_lets_its_binding_go(bool destroy) { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - auto* m = std::pmr::get_default_resource(); - const std::pmr::polymorphic_allocator<> alloc(m); - std::shared_ptr bound; - std::string seen; - bound = std::allocate_shared( - alloc, p.b.c, "T1", - trystero::handler)>( - std::allocator_arg, alloc, - [&bound, &seen, destroy, - peer = std::pmr::string("a peer id longer than any short string", m)]( - trystero::backend::bytes&&, std::span) { - if (destroy) { - bound.reset(); // the room's peer state goes, and its binding with it - } else { - bound->detach(true, 0ms); // the room kicks the peer - } - seen = peer; - }), - m); - const std::array action{2, 0}; - p.a.c->send(trystero::protocol::room_frame("T1", action, m)); - BOOST_TEST(run_until(p.io, [&] { return !seen.empty(); })); - BOOST_TEST_EQ(seen, "a peer id longer than any short string"); - BOOST_TEST_EQ(bound == nullptr, destroy); - BOOST_TEST_EQ(p.b.ended, destroy ? "" : "its last room kicked the peer"); -} - -void a_delivery_that_kicks_its_binding() { - a_delivery_that_lets_its_binding_go(false); -} - -void a_delivery_that_drops_its_binding() { - a_delivery_that_lets_its_binding_go(true); -} - -// A waiter told `false` by `detach` releases the room's last reference to the binding, as a -// transfer's failure may. -void a_waiter_that_releases_its_binding_during_detach() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - std::vector> got; - auto t1 = make_binding(p.a.c, "T1", got); - p.net.channel_capacity = 1; - fill(*t1); - bool told = false; - t1->wait_drained({std::allocator_arg, - std::pmr::polymorphic_allocator<>(std::pmr::get_default_resource()), - [&](bool open) { - told = !open; - t1.reset(); - }}); - auto* const raw = t1.get(); - raw->detach(false, 1000ms); - BOOST_TEST(told); - BOOST_TEST(!t1); - BOOST_TEST(p.a.ended.empty()); // idling: the idle time is 1 s -} - -// Detaching tells each of the binding's waiters `false` before it returns, and no other binding's. -void detach_fails_the_waiters_of_its_binding_alone() { - const std::array tokens{"T1", "T2"}; - link_pair p(tokens, tokens); - std::vector> got; - const auto t1 = make_binding(p.a.c, "T1", got); - const auto t2 = make_binding(p.a.c, "T2", got); - p.net.channel_capacity = 1; - fill(*t1); - std::vector turns; - t1->wait_drained(record(turns, "a")); - t2->wait_drained(record(turns, "T2")); - t1->wait_drained(record(turns, "b")); - t1->detach(false, 1000ms); - BOOST_TEST(turns == (std::vector{"!a", "!b"})); - BOOST_TEST(run_until(p.io, [&] { return turns.size() == 3; })); - BOOST_TEST_EQ(turns.back(), "T2"); -} - -// A detached binding is cut off: it sends nothing and its waits fail at once, while its connection -// goes on for the others. -void a_detached_binding_neither_sends_nor_waits() { - const std::array tokens{"T1", "T2"}; - const link_pair p(tokens, tokens); - std::vector> got; - const auto t1 = make_binding(p.a.c, "T1", got); - const auto t2 = make_binding(p.a.c, "T2", got); - t1->detach(false, 1000ms); - auto* m = std::pmr::get_default_resource(); - const std::array action{2, 0}; - BOOST_TEST(!t1->send(trystero::protocol::room_frame("T1", action, m))); - BOOST_TEST(!t1->shared_connection()); - std::vector turns; - t1->wait_drained(record(turns, "T1")); - BOOST_TEST(turns == (std::vector{"!T1"})); - BOOST_TEST(t2->send(trystero::protocol::room_frame("T2", action, m))); - BOOST_TEST(p.a.c->live()); -} - -// A binding names its connection by identity, whether it detached and whether the connection -// ended: never another connection, nor none. -void a_binding_is_on_its_connection_alone() { - const std::array tokens{"T1"}; - const link_pair p(tokens, tokens); - std::vector> got; - const auto t1 = make_binding(p.a.c, "T1", got); - BOOST_TEST(t1->is_on(p.a.c)); - BOOST_TEST(!t1->is_on(p.b.c)); - BOOST_TEST(!t1->is_on(nullptr)); - t1->detach(false, 1000ms); - BOOST_TEST(t1->is_on(p.a.c)); - p.a.c->end("test"); - BOOST_TEST(t1->is_on(p.a.c)); - BOOST_TEST(!t1->is_on(p.b.c)); -} - -// A wait with the channel at or below Trystero's threshold completes at once; one byte above -// waits for the drain. -void a_wait_at_the_threshold_completes_at_once() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - std::vector> got; - const auto t1 = make_binding(p.a.c, "T1", got); - p.net.channel_capacity = 1; - std::vector turns; - t1->wait_drained(record(turns, "empty")); - BOOST_TEST(turns == (std::vector{"empty"})); - // 4 x 16,009 + 1,499: 65,535 bytes, the threshold itself. - const std::array payloads{16'000, 16'000, 16'000, 16'000, 1'490}; - send_dropped(*t1, payloads); - webcpp::test::require( - BOOST_TEST_EQ(t1->buffered_amount(), trystero::backend::data_channel::low_threshold)); - t1->wait_drained(record(turns, "at")); - BOOST_TEST(turns == (std::vector{"empty", "at"})); - const std::array one_more{0}; // a frame of 9 bytes - send_dropped(*t1, one_more); - t1->wait_drained(record(turns, "above")); - BOOST_TEST_EQ(turns.size(), 2U); - BOOST_TEST(run_until(p.io, [&] { return turns.size() == 3; })); - BOOST_TEST_EQ(turns.back(), "above"); -} - -// A binding has one place in a drain however many times it waits: a waiter that waits again from -// its turn completes at the next drain, not in this one. -void a_binding_has_one_turn_per_drain() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - std::vector> got; - const auto t1 = make_binding(p.a.c, "T1", got); - p.net.channel_capacity = 1; - fill(*t1); - std::vector turns; - std::size_t buffered_at_rewait = 0; - const std::pmr::polymorphic_allocator<> alloc(std::pmr::get_default_resource()); - t1->wait_drained({std::allocator_arg, alloc, [&](bool) { - turns.emplace_back("a"); - fill(*t1); - t1->wait_drained({std::allocator_arg, alloc, [&](bool) { - turns.emplace_back("again"); - buffered_at_rewait = t1->buffered_amount(); - }}); - }}); - t1->wait_drained(record(turns, "b")); - BOOST_TEST(run_until(p.io, [&] { return turns.size() == 3; })); - BOOST_TEST(turns == (std::vector{"a", "b", "again"})); - BOOST_TEST_LE(buffered_at_rewait, trystero::backend::data_channel::low_threshold); -} - -// Taking the last kept frame stops the window: a frame kept later has 10 s of its own. -void taking_every_kept_frame_restarts_the_window() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - auto* m = std::pmr::get_default_resource(); - const std::array action{2, 0}; - p.a.c->send(trystero::protocol::room_frame("T2", action, m)); - webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.kept.size() == 1; }))); - BOOST_TEST(p.net.advance(5'000ms)); - BOOST_TEST_EQ(p.b.c->take_kept("T2").size(), 1U); - BOOST_TEST(p.net.advance(1'000ms)); - p.a.c->send(trystero::protocol::room_frame("T2", action, m)); - webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.kept.size() == 2; }))); - BOOST_TEST(p.net.advance(9'999ms)); // 15.999 s - BOOST_TEST_EQ(p.b.c->kept_count(), 1U); - BOOST_TEST(p.net.advance(1ms)); // 16 s, 10 s after the second was kept - BOOST_TEST_EQ(p.b.c->kept_count(), 0U); -} - -// A withdrawal that leaves nothing kept stops the window too, as Trystero's syncDataTimers does -// (dist/shared-peer.mjs:417-422, 468-472). -void a_withdrawal_that_empties_the_kept_frames_restarts_the_window() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - auto* m = std::pmr::get_default_resource(); - const std::array action{2, 0}; - p.a.c->send(trystero::protocol::room_frame("T2", action, m)); - webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.kept.size() == 1; }))); - BOOST_TEST(p.net.advance(5'000ms)); - p.a.c->send_presence("T2", false); - webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.presence.size() == 2; }))); - BOOST_TEST_EQ(p.b.c->kept_count(), 0U); - BOOST_TEST(p.net.advance(1'000ms)); - p.a.c->send(trystero::protocol::room_frame("T3", action, m)); - webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.kept.size() == 2; }))); - BOOST_TEST(p.net.advance(9'999ms)); // 15.999 s - BOOST_TEST_EQ(p.b.c->kept_count(), 1U); - BOOST_TEST(p.net.advance(1ms)); - BOOST_TEST_EQ(p.b.c->kept_count(), 0U); -} - -// `keeps` that ends the connection: nothing is kept, and no timer is made. -void keeps_that_ends_the_connection_keeps_nothing() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - p.b.end_in_keeps = true; - auto* m = std::pmr::get_default_resource(); - const std::array action{2, 0}; - p.a.c->send(trystero::protocol::room_frame("T2", action, m)); - BOOST_TEST(run_until(p.io, [&] { return !p.b.ended.empty(); })); - BOOST_TEST_EQ(p.b.ended, "ended in keeps"); - BOOST_TEST(p.b.kept.empty()); - BOOST_TEST_EQ(p.b.c->kept_count(), 0U); - BOOST_TEST_EQ(p.net.scheduled(), 0U); -} - -// `kept` may take the frame it is told of: the token it was given outlives the take (under the -// sanitizers). -void kept_may_take_its_frame() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - p.b.take_in_kept = true; - auto* m = std::pmr::get_default_resource(); - const std::array action{2, 0}; - const std::string token = "a room token longer than any short string"; - p.a.c->send(trystero::protocol::room_frame(token, action, m)); - BOOST_TEST(run_until(p.io, [&] { return p.b.kept.size() == 1; })); - BOOST_TEST_EQ(p.b.kept.at(0), token); - BOOST_TEST_EQ(p.b.taken, 1U); - BOOST_TEST_EQ(p.b.c->kept_count(), 0U); -} - -// The end closes the peer connection as well as the channel, and frees what was kept. -void the_end_closes_the_connection_and_frees_the_kept_frames() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - auto* m = std::pmr::get_default_resource(); - const std::array action{2, 0}; - p.a.c->send(trystero::protocol::room_frame("T2", action, m)); - webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.kept.size() == 1; }))); - p.b.c->end("test"); - BOOST_TEST_EQ(p.b.c->kept_count(), 0U); - BOOST_TEST(!p.b.c->live()); - // A closed peer connection refuses a description. - std::optional refused; - p.answerer->set_local_description([&refused](trystero::backend::error_code ec, std::string_view, - std::string_view) { refused = ec; }); - BOOST_TEST(run_until(p.io, [&] { return refused.has_value(); })); - BOOST_TEST(refused && *refused == make_error_code(trystero::error::backend_failure)); -} - -// The remote's first frame says it uses the connection, once; an end by this side is not the -// transport's, and a channel the remote closes is. -void the_first_frame_says_the_remote_uses_it() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.presence.size() == 1; }))); - BOOST_TEST(p.b.c->used()); - BOOST_TEST_EQ(p.b.used, 1U); - p.a.c->send_presence("T2", true); - BOOST_TEST(run_until(p.io, [&] { return p.b.presence.size() == 2; })); - BOOST_TEST_EQ(p.b.used, 1U); - p.a.c->end("test"); - BOOST_TEST(!p.a.c->ended_by_transport()); - BOOST_TEST(run_until(p.io, [&] { return !p.b.ended.empty(); })); - BOOST_TEST_EQ(p.b.ended, "data channel closed"); - BOOST_TEST(p.b.c->ended_by_transport()); -} - -// Frames replayed are handled in their order as if they came now, and stop at an end. -void replayed_frames_are_handled_in_order() { - const std::array tokens{"T1"}; - link_pair p(tokens, tokens); - webcpp::test::require(BOOST_TEST(run_until(p.io, [&] { return p.b.presence.size() == 1; }))); - auto* m = std::pmr::get_default_resource(); - std::pmr::deque frames(m); - for (const auto* token : {"T2", "T3"}) { - const auto f = trystero::protocol::presence_frame(token, true, m); - frames.emplace_back(f.begin(), f.end()); - } - frames.emplace_back(3, std::uint8_t{9}); // malformed: ends the connection - const auto t4 = trystero::protocol::presence_frame("T4", true, m); - frames.emplace_back(t4.begin(), t4.end()); - p.b.c->replay(std::move(frames)); - BOOST_TEST(p.b.presence == (std::vector{"+T1", "+T2", "+T3"})); - BOOST_TEST_EQ(p.b.ended, "invalid or incompatible room frame"); -} - -// A disconnection ends the connection after 5 s, as Trystero's; a reconnection before then -// cancels it. -void a_disconnection_ends_after_5_s_unless_it_reconnects() { - const std::array tokens{"T1"}; - { - link_pair p(tokens, tokens); - p.net.disconnect(0); - BOOST_TEST(p.net.advance(4'999ms)); - BOOST_TEST(p.a.ended.empty()); - BOOST_TEST(p.net.advance(1ms)); - BOOST_TEST_EQ(p.a.ended, "connection lost"); - } - { - link_pair p(tokens, tokens); - p.net.disconnect(0); - BOOST_TEST(p.net.advance(4'000ms)); - p.net.reconnect(0); - BOOST_TEST(p.net.advance(10'000ms)); - BOOST_TEST(p.a.ended.empty()); - BOOST_TEST(p.a.c->live()); - } -} - -} // namespace - -int main() { - start_advertises_every_token(); - the_first_frame_says_the_remote_uses_it(); - replayed_frames_are_handled_in_order(); - a_withdrawn_token_is_forgotten(); - a_bound_token_reaches_its_binding_and_another_is_kept(); - a_withdrawn_token_drops_its_kept_frames(); - a_kept_frame_advertises_its_token(); - a_kept_frame_never_advertises_a_65th_token(); - a_65th_advertised_token_ends_the_connection(); - a_malformed_frame_ends_the_connection(); - kept_frames_are_bounded_and_dropped_after_10_s(); - a_closing_channel_is_not_live(); - drain_turns_follow_the_order_of_waiting(); - the_end_fails_every_drain_waiter(); - the_end_fails_the_waiters_in_the_order_of_waiting(); - the_last_binding_ends_or_idles_the_connection(); - a_binding_made_during_a_drain_waits_for_the_next(); - an_end_inside_a_drain_fails_the_waiters_after_it(); - an_end_inside_one_binding_fails_its_remaining_waiters(); - a_delivery_that_kicks_its_binding(); - a_delivery_that_drops_its_binding(); - a_waiter_that_releases_its_binding_during_detach(); - detach_fails_the_waiters_of_its_binding_alone(); - a_detached_binding_neither_sends_nor_waits(); - a_binding_is_on_its_connection_alone(); - a_wait_at_the_threshold_completes_at_once(); - a_binding_has_one_turn_per_drain(); - taking_every_kept_frame_restarts_the_window(); - a_withdrawal_that_empties_the_kept_frames_restarts_the_window(); - keeps_that_ends_the_connection_keeps_nothing(); - kept_may_take_its_frame(); - the_end_closes_the_connection_and_frees_the_kept_frames(); - a_disconnection_ends_after_5_s_unless_it_reconnects(); - // Under Asyncify, a main that suspended loses what it returns: the status goes first. - return webcpp::test::exit_status(boost::report_errors()); -} diff --git a/test/crypto_layer_test.cpp b/test/crypto_layer_test.cpp new file mode 100644 index 0000000..02a19af --- /dev/null +++ b/test/crypto_layer_test.cpp @@ -0,0 +1,1923 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Tests the crypto layer of the port to Trystero 0.27.0 against the vectors recorded from +// 0.27.0's own code (fixtures/expected/trystero-0.27.0.json, written by oracle/record_0_27.mjs). +// The fixture's path is the test's one argument, as webcpp.run passes its input file. The +// fixture is read with webcpp::document; section(name) gives a case the named section of it. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cases.hpp" + +namespace wd = webcpp::document; +namespace tp = webcpp::trystero::protocol; +namespace trystero = webcpp::trystero; + +namespace { + +/** A value of the fixture: a read-only handle of an owned document. */ +using fixture_value = wd::basic_const_value<>; + +/** The fixture, which main loads before it runs a case. */ +std::optional& fixture_document() { + static std::optional document; + return document; +} + +/** The fixture, read as JSON.parse reads it. */ +wd::result load(const char* path) { + const std::ifstream file(path); + std::stringstream text; + text << file.rdbuf(); + return wd::parse(text.str()); +} + +/** The named top-level section of the fixture: an array of vectors, or the value itself. */ +fixture_value section(std::string_view name) { + return fixture_document()->root()[name]; +} + +void fixture_is_trystero_0_27_0() { + BOOST_TEST_EQ(section("trystero").value_or(std::string_view()), std::string_view("0.27.0")); +} + +/** The text of a fixture value. */ +std::string_view str(const fixture_value& v) { + return v.value_or(std::string_view()); +} + +/** The bytes of a fixture's hexadecimal text. */ +tp::bytes bytes_of(const fixture_value& v) { + const auto decoded = tp::from_hex(str(v)); + BOOST_TEST(decoded.has_value()); + return decoded.value_or(tp::bytes()); +} + +/** An integer of a fixture. */ +std::uint64_t integer(const fixture_value& v) { + return static_cast(v.value_or(std::int64_t{-1})); +} + +void base64url_matches() { + for (const auto entry : section("base64url")) { + const auto data = bytes_of(entry["bytes"]); + BOOST_TEST_EQ(tp::to_base64url(data), str(entry["text"])); + if (data.empty()) { + // Trystero's encoder writes "" for no bytes; the strict reader refuses "". + BOOST_TEST(!tp::from_base64url(str(entry["text"])).has_value()); + continue; + } + const auto read = tp::from_base64url(str(entry["text"])); + BOOST_TEST(read.has_value()); + BOOST_TEST(read.value_or(tp::bytes()) == data); + } +} + +void base64url_is_strict() { + for (const std::string_view text : + {"", "A", "AB==", "AB+/", "AR", "A B", "AB=", "AB\n", "AAAAA", "A-_", "AB_+"}) { + BOOST_TEST(!tp::from_base64url(text).has_value()); + } + // Canonical texts of every length are read, and read back as they were written. + for (const std::string_view text : {"AA", "AAA", "AAAA", "__4", "-_-_", "AQID"}) { + const auto read = tp::from_base64url(text); + BOOST_TEST(read.has_value()); + if (read) { + BOOST_TEST_EQ(tp::to_base64url(*read), text); + } + } +} + +void topic_path_matches() { + for (const auto entry : section("topic_path")) { + std::vector parts; + for (const auto part : entry["parts"]) { + parts.push_back(str(part)); + } + // The fixture holds paths of two parts and of three. + if (parts.size() == 3) { + BOOST_TEST_EQ(tp::topic_path({parts[0], parts[1], parts[2]}), str(entry["path"])); + } else if (BOOST_TEST_EQ(parts.size(), 2U)) { + BOOST_TEST_EQ(tp::topic_path({parts[0], parts[1]}), str(entry["path"])); + } + } + // The escapes JSON.stringify writes, beyond the fixture's. + BOOST_TEST_EQ(tp::topic_path({"\b\f\n\r\t\x01\x1f", "a/b"}), + std::string_view(R"(["\b\f\n\r\t\u0001\u001f","a/b"])")); +} + +// The one writer of a string that is not refused: JSON.stringify's output on UTF-8, with DEL and +// U+2028 raw; and, on a byte that is not UTF-8, the byte as it is. +void the_total_string_writer_is_json_stringifys() { + for (const std::string_view text : { + "", + "plain", + "a\"b\\c", + "\b\f\n\r\t", + "\x01\x1f", + "del\x7f", + "ls\xe2\x80\xa8ps", + "caf\xc3\xa9 \xf0\x9f\x98\x80", + "\x7f\xe2\x80\xa9", + }) { + std::pmr::string total; + tp::json::append_string_total(total, text); + std::pmr::string checked; + BOOST_TEST(tp::json::append_string(checked, text).has_value()); + BOOST_TEST_EQ(total, checked); + } + // DEL and U+2028 are written raw, as JSON.stringify writes them. + std::pmr::string raw; + tp::json::append_string_total(raw, "\x7f\xe2\x80\xa8"); + BOOST_TEST_EQ(raw, std::string_view("\"\x7f\xe2\x80\xa8\"")); + // A byte that is not UTF-8 is kept, where append_string refuses the text. + std::pmr::string bad; + tp::json::append_string_total(bad, "a\xffz"); + BOOST_TEST_EQ(bad, std::string_view("\"a\xffz\"")); + std::pmr::string refused; + BOOST_TEST(!tp::json::append_string(refused, "a\xffz").has_value()); +} + +void hash_topic_matches() { + for (const auto entry : section("hash_topic")) { + const auto topic = tp::hash_topic(str(entry["text"])); + BOOST_TEST_EQ(topic, str(entry["topic"])); + BOOST_TEST_EQ(topic.size(), 43U); + } +} + +void room_topics_match() { + for (const auto entry : section("room_topics")) { + const auto app = str(entry["app"]); + const auto room = str(entry["room"]); + BOOST_TEST_EQ(tp::root_topic_text(app, room), str(entry["root_text"])); + BOOST_TEST_EQ(tp::root_topic(app, room), str(entry["root_topic"])); + BOOST_TEST_EQ(tp::peer_topic(app, room, str(entry["peer_id"])), str(entry["peer_topic"])); + } +} + +void hash32_matches() { + for (const auto entry : section("hash32")) { + BOOST_TEST_EQ(tp::hash32(str(entry["text"])), integer(entry["value"])); + } +} + +void str_to_num_matches() { + for (const auto entry : section("str_to_num")) { + BOOST_TEST_EQ(tp::str_to_num(str(entry["text"]), 10000), integer(entry["value"])); + BOOST_TEST_EQ(tp::str_to_num(str(entry["text"])), tp::hash32(str(entry["text"]))); + } +} + +// A topic's kind is 0.27.0's topicToKind: FNV-1a over its UTF-16 code units, an astral character +// as its two surrogates, modulo 10000 and above 20000; a room's root topic has the kind recorded +// with it. +void topic_kind_matches() { + for (const auto entry : section("topic_to_kind")) { + BOOST_TEST_EQ(tp::nostr::topic_kind(str(entry["topic"])), integer(entry["kind"])); + } + for (const auto entry : section("room_topics")) { + BOOST_TEST_EQ(tp::nostr::topic_kind(str(entry["root_topic"])), integer(entry["root_kind"])); + } +} + +void domain_tags_match() { + for (const auto entry : section("domain_tags")) { + BOOST_TEST_EQ( + tp::domain_tag(str(entry["name"]), static_cast(integer(entry["version"]))), + str(entry["tag"])); + } +} + +// The shuffle's order for each seed, the seed being str_to_num of the app id, and the relays an +// app derives: the first five of the order, as indices into the 30 defaults. +void shuffle_matches() { + BOOST_TEST_EQ(tp::default_nostr_relays.size(), 30U); + BOOST_TEST_EQ(tp::default_nostr_relays.front(), "wss://bucket.coracle.social"); + BOOST_TEST_EQ(tp::default_nostr_relays.back(), "wss://yabu.me"); + for (const auto entry : section("shuffle")) { + const auto seed = static_cast(integer(entry["seed"])); + BOOST_TEST_EQ(tp::str_to_num(str(entry["app"])), seed); + std::vector expected; + for (const auto i : entry["order"]) { + expected.push_back(static_cast(integer(i))); + } + std::array order{}; + for (std::size_t i = 0; i < order.size(); ++i) { + order[i] = i; + } + tp::seeded_shuffle(std::span(order), seed); + BOOST_TEST_ALL_EQ(order.begin(), order.end(), expected.begin(), expected.end()); + + const auto derived = tp::derive_relays(str(entry["app"]), tp::default_nostr_relays, 5); + BOOST_TEST_EQ(derived.size(), 5U); + for (std::size_t i = 0; i < derived.size() && i < expected.size(); ++i) { + BOOST_TEST_EQ(derived[i], tp::default_nostr_relays[expected[i]]); + } + } + // A redundancy above the list's size keeps the whole shuffled list, as a slice does. + BOOST_TEST_EQ(tp::derive_relays("app", tp::default_nostr_relays, 40).size(), 30U); + BOOST_TEST_EQ(tp::derive_relays("app", tp::default_nostr_relays, 0).size(), 0U); + // A zero seed is one, as Trystero's `|| 1`. + std::array zero{0, 1, 2, 3, 4, 5, 6, 7}; + std::array one = zero; + tp::seeded_shuffle(std::span(zero), 0); + tp::seeded_shuffle(std::span(one), 1); + BOOST_TEST(zero == one); +} + +// genId over the fixture's random cycle, each round drawing gen_id_draw_size bytes from where the +// last one stopped, as the recorder's withRandom does. +void gen_id_matches() { + for (const auto entry : section("gen_id")) { + const auto cycle = bytes_of(entry["random_cycle"]); + std::size_t at = 0; + const auto n = static_cast(integer(entry["n"])); + const auto id = tp::gen_id(n, [&](std::span out) { + BOOST_TEST_EQ(out.size(), tp::gen_id_draw_size(n)); + for (auto& byte : out) { + byte = cycle[at++ % cycle.size()]; + } + }); + BOOST_TEST_EQ(id, str(entry["id"])); + } + BOOST_TEST_EQ(tp::gen_id_draw_size(8), 14U); + BOOST_TEST_EQ(tp::gen_id_draw_size(20), 27U); + BOOST_TEST(tp::gen_id(0, [](std::span) { BOOST_TEST(false); }).empty()); + // Bytes of 248 and above are skipped: only the last one of three rounds is kept. + int round = 0; + const auto skipped = tp::gen_id(1, [&](std::span out) { + std::ranges::fill(out, round++ < 2 ? std::uint8_t{248} : std::uint8_t{61}); + }); + BOOST_TEST_EQ(skipped, "z"); + BOOST_TEST_EQ(round, 3); +} + +void identity_ids_match() { + for (const auto entry : section("identity_ids")) { + const auto compact = str(entry["compact_pub"]); + const auto point = tp::parse_compact_public_key(compact); + BOOST_TEST(point.has_value()); + if (point) { + BOOST_TEST_EQ((*point)[0], 0x04); + BOOST_TEST_EQ(tp::compact_public_key(*point), compact); + } + BOOST_TEST_EQ(tp::derive_peer_id(compact), str(entry["peer_id"])); + BOOST_TEST_EQ(tp::derive_user_id(compact), str(entry["user_id"])); + BOOST_TEST_EQ(tp::derive_peer_id(compact).size(), tp::peer_id_size); + BOOST_TEST_EQ(tp::derive_user_id(compact).size(), tp::user_id_size); + } + // encode_base62 keeps the low digits: 62^2 + 5 is "105" in base 62 and "05" in two digits. + const std::array number{0x0f, 0x09}; // 3844 + 5 = 3849 + BOOST_TEST_EQ(tp::encode_base62(number, 3), "105"); + BOOST_TEST_EQ(tp::encode_base62(number, 2), "05"); + BOOST_TEST_EQ(tp::encode_base62(number, 4), "0105"); + BOOST_TEST_EQ(tp::encode_base62(std::span{}, 3), "000"); +} + +void uuid_v4_has_its_form() { + const auto text = [](const std::array& uuid) { + return std::string_view(uuid.data(), uuid.size()); + }; + std::array random{}; + random.fill(0xff); + BOOST_TEST_EQ(text(tp::uuid_v4(random)), "ffffffff-ffff-4fff-bfff-ffffffffffff"); + random.fill(0); + BOOST_TEST_EQ(text(tp::uuid_v4(random)), "00000000-0000-4000-8000-000000000000"); + for (std::size_t i = 0; i < random.size(); ++i) { + random[i] = static_cast(i); + } + BOOST_TEST_EQ(text(tp::uuid_v4(random)), "00010203-0405-4607-8809-0a0b0c0d0e0f"); +} + +void compact_key_is_strict() { + const auto& entries = section("identity_ids"); + const std::string compact(str(entries[0]["compact_pub"])); + BOOST_TEST(tp::parse_compact_public_key(compact).has_value()); + BOOST_TEST(!tp::parse_compact_public_key(compact.substr(0, 86))); + BOOST_TEST(!tp::parse_compact_public_key(compact + "A")); + BOOST_TEST(!tp::parse_compact_public_key("")); + auto moved = compact; // the dot one place off, the length unchanged + moved[43] = 'A'; + moved[42] = '.'; + BOOST_TEST(!tp::parse_compact_public_key(moved)); + auto no_dot = compact; + no_dot[43] = 'A'; + BOOST_TEST(!tp::parse_compact_public_key(no_dot)); + auto padded = compact; // a half of 44 characters, padded, with the whole 87 long + padded[42] = '='; + BOOST_TEST(!tp::parse_compact_public_key(padded)); + auto outside = compact; + outside[5] = '+'; + BOOST_TEST(!tp::parse_compact_public_key(outside)); + auto non_canonical = compact; // the last character's unused bits set + non_canonical.back() = 'W'; + BOOST_TEST(!tp::parse_compact_public_key(non_canonical)); +} + +/** The vector of `room_keys_password` for an app, a room and a password. */ +fixture_value password_vector(std::string_view app, std::string_view room, + std::string_view password) { + for (const auto entry : section("room_keys_password")) { + if (str(entry["app"]) == app && str(entry["room"]) == room && + str(entry["password"]) == password) { + return entry; + } + } + BOOST_TEST(false); + return section("room_keys_password"); +} + +void room_key_without_password_matches() { + for (const auto entry : section("room_key_no_password")) { + const auto key = tp::room_aes_key_without_password(str(entry["app"]), str(entry["room"])); + BOOST_TEST(std::ranges::equal(key.bytes(), bytes_of(entry["key"]))); + } +} + +void room_keys_from_master_match() { + for (const auto entry : section("room_keys_password")) { + const auto salt = bytes_of(entry["salt"]); + const auto made = tp::pbkdf2_salt(str(entry["app"]), str(entry["room"])); + BOOST_TEST(std::ranges::equal(made, salt)); + const auto master = bytes_of(entry["master"]); + BOOST_TEST_EQ(master.size(), 32U); + const auto keys = tp::derive_room_keys(std::span(master)); + BOOST_TEST(keys.has_value()); + if (keys) { + BOOST_TEST(std::ranges::equal(keys->aes.bytes(), bytes_of(entry["aes_key"]))); + BOOST_TEST(std::ranges::equal(keys->hmac.bytes(), bytes_of(entry["hmac_key"]))); + } + } +} + +// 600,000 iterations of HMAC-SHA-256 take about 0.2 s in a release build and tens of times that +// in a debug one, so it runs in the release variant's run only, which defines +// WEBCPP_TRYSTERO_TEST_SLOW_KDF (see main and the Jamfile's crypto_layer_release); one vector +// proves the iteration count and the salt's use. +[[maybe_unused]] void pbkdf2_master_matches() { + BOOST_TEST_EQ(tp::pbkdf2_iterations, 600'000U); + const auto entry = password_vector("example.com/app", "lobby", "hunter2"); + const auto salt = bytes_of(entry["salt"]); + const auto password = str(entry["password"]); + std::array master{}; + const auto derived = webcpp::hash::pbkdf2( + master, std::span(reinterpret_cast(password.data()), password.size()), + salt, tp::pbkdf2_iterations); + BOOST_TEST(derived.has_value()); + BOOST_TEST(std::ranges::equal(master, bytes_of(entry["master"]))); +} + +void room_auth_matches() { + for (const auto entry : section("room_auth")) { + const auto app = str(entry["app"]); + const auto room = str(entry["room"]); + const auto peer = str(entry["peer_id"]); + const auto seq = integer(entry["seq"]); + const auto keys = password_vector(app, room, str(entry["password"])); + const auto hmac_bytes = bytes_of(keys["hmac_key"]); + webcpp::crypto::secret<32> hmac; + std::ranges::copy(hmac_bytes, hmac.writable().begin()); + BOOST_TEST_EQ(tp::room_auth_payload(app, room, peer, seq), str(entry["payload"])); + const auto token = tp::sign_room_auth(hmac, app, room, peer, seq); + BOOST_TEST_EQ(token, str(entry["token"])); + BOOST_TEST_EQ(token.size(), 43U); + BOOST_TEST_EQ(tp::verify_room_auth(hmac, app, room, peer, seq, token), + entry["verifies"].value_or(false)); + BOOST_TEST_EQ(tp::verify_room_auth(hmac, app, room, peer, seq + 1, token), + entry["wrong_seq_verifies"].value_or(true)); + BOOST_TEST(!tp::verify_room_auth(hmac, app, room, std::string(peer) + "x", seq, token)); + } + // The largest safe integer is written as a decimal integer. + BOOST_TEST_EQ(tp::room_auth_payload("a", "r", "p", tp::max_room_auth_seq), + std::string_view(R"(["trystero:ov-auth:v3","a","r","p",9007199254740991])")); +} + +void room_auth_token_is_strict() { + const auto entry = section("room_auth")[std::size_t{0}]; + const auto app = str(entry["app"]); + const auto room = str(entry["room"]); + const auto peer = str(entry["peer_id"]); + const auto seq = integer(entry["seq"]); + const auto hmac_bytes = + bytes_of(password_vector(app, room, str(entry["password"]))["hmac_key"]); + webcpp::crypto::secret<32> hmac; + std::ranges::copy(hmac_bytes, hmac.writable().begin()); + const std::string token(str(entry["token"])); + BOOST_TEST(tp::verify_room_auth(hmac, app, room, peer, seq, token)); + BOOST_TEST(!tp::verify_room_auth(hmac, app, room, peer, seq, token + "=")); + BOOST_TEST(!tp::verify_room_auth(hmac, app, room, peer, seq, token.substr(0, 42))); + BOOST_TEST(!tp::verify_room_auth(hmac, app, room, peer, seq, token + "A")); + BOOST_TEST(!tp::verify_room_auth(hmac, app, room, peer, seq, "")); + // The 43rd character carries 4 bits and 2 unused ones: another character with the same top 4 + // bits decodes to the same bytes, and is refused as non-canonical. + constexpr std::string_view alphabet = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + const auto last = alphabet.find(token.back()); + BOOST_TEST(last != std::string_view::npos); + auto twin = token; + twin.back() = alphabet[last ^ 1U]; + BOOST_TEST(twin != token); + BOOST_TEST(!tp::verify_room_auth(hmac, app, room, peer, seq, twin)); + BOOST_TEST(!tp::from_base64url(twin).has_value()); + // A sequence number beyond 2^53 - 1 is refused, as 0.27.0 refuses it, not asserted. + BOOST_TEST(!tp::verify_room_auth(hmac, app, room, peer, tp::max_room_auth_seq + 1, token)); + BOOST_TEST(!tp::verify_room_auth(hmac, app, room, peer, UINT64_MAX, token)); + auto outside = token; + outside[3] = '+'; + BOOST_TEST(!tp::verify_room_auth(hmac, app, room, peer, seq, outside)); +} + +/** The AES key of an entry of "seal" or "open_refused": without a password, or the vector's. */ +webcpp::crypto::secret<32> key_of(const fixture_value& entry) { + const auto app = str(entry["app"]); + const auto room = str(entry["room"]); + const auto password = str(entry["password"]); + if (password.empty()) { + return tp::room_aes_key_without_password(app, room); + } + webcpp::crypto::secret<32> key; + std::ranges::copy(bytes_of(password_vector(app, room, password)["aes_key"]), + key.writable().begin()); + return key; +} + +/** An entry's AAD: absent when the fixture holds null. */ +std::optional aad_of(const fixture_value& entry) { + const auto aad = entry["aad"]; + if (aad.is_null()) { + return std::nullopt; + } + return str(aad); +} + +void seal_matches() { + for (const auto entry : section("seal")) { + const auto key = key_of(entry); + const auto iv = bytes_of(entry["iv"]); + const auto plaintext = str(entry["plaintext"]); + const auto aad = aad_of(entry); + const auto sealed = + tp::seal(key, std::span(iv), plaintext, aad); + BOOST_TEST(sealed.has_value()); + if (sealed) { + BOOST_TEST_EQ(*sealed, str(entry["sealed"])); + BOOST_TEST_EQ(sealed->size(), tp::sealed_size(plaintext.size())); + } + const auto opened = tp::open(key, str(entry["sealed"]), aad); + BOOST_TEST(opened.has_value()); + if (opened) { + BOOST_TEST_EQ(*opened, plaintext); + } + } +} + +void password_probe_opens() { + for (const auto entry : section("room_keys_password")) { + webcpp::crypto::secret<32> key; + std::ranges::copy(bytes_of(entry["aes_key"]), key.writable().begin()); + const auto opened = tp::open(key, str(entry["probe_sealed"]), "offer|p|o"); + BOOST_TEST(opened.has_value()); + if (opened) { + BOOST_TEST_EQ(*opened, std::string_view("probe")); + } + // Another AAD, and no AAD, do not open it. + BOOST_TEST(!tp::open(key, str(entry["probe_sealed"]), "offer|p|x").has_value()); + BOOST_TEST(!tp::open(key, str(entry["probe_sealed"]), std::nullopt).has_value()); + } +} + +void open_refuses_what_trystero_refuses() { + for (const auto entry : section("open_refused")) { + BOOST_TEST(entry["refused"].value_or(false)); + const auto opened = tp::open(key_of(entry), str(entry["sealed"]), std::nullopt); + BOOST_TEST(!opened.has_value()); + if (!opened) { + BOOST_TEST(opened.error() == webcpp::trystero::error::decrypt_failed); + } + } + // A text with padding, a character outside the alphabet and another last character of the + // same bytes, of a sealed text that opens: the seal of a non-ASCII plaintext, without a + // password or an AAD, under the IV 0..11. + std::optional chosen; + for (const auto candidate : section("seal")) { + if (!chosen && str(candidate["app"]) == "example.com/app" && + str(candidate["password"]).empty() && + str(candidate["iv"]) == "000102030405060708090a0b" && + str(candidate["plaintext"]) == "caf\xc3\xa9 \xf0\x9f\x98\x80" && + candidate["aad"].is_null()) { + chosen = candidate; + } + } + if (!BOOST_TEST(chosen.has_value())) { + return; + } + const auto entry = *chosen; + const auto key = key_of(entry); + const std::string good(str(entry["sealed"])); + BOOST_TEST(tp::open(key, good, std::nullopt).has_value()); + BOOST_TEST(!tp::open(key, good + "=", std::nullopt).has_value()); + BOOST_TEST(!tp::open(key, good + "A", std::nullopt).has_value()); + auto outside = good; + outside[5] = '+'; + BOOST_TEST(!tp::open(key, outside, std::nullopt).has_value()); + // Fewer than 28 bytes: 27 bytes are 36 characters. + BOOST_TEST(!tp::open(key, std::string(36, 'A'), std::nullopt).has_value()); + // A tag that does not match. + auto flipped = good; + flipped[flipped.size() / 2] = flipped[flipped.size() / 2] == 'A' ? 'B' : 'A'; + BOOST_TEST(!tp::open(key, flipped, std::nullopt).has_value()); +} + +void open_refuses_another_aad() { + for (const auto entry : section("seal")) { + const auto key = key_of(entry); + const auto aad = aad_of(entry); + const std::string_view other = aad ? std::string_view("answer|x|y") : "offer|x|y"; + BOOST_TEST(!tp::open(key, str(entry["sealed"]), other).has_value()); + if (aad) { + BOOST_TEST(!tp::open(key, str(entry["sealed"]), std::nullopt).has_value()); + } else { + // An absent AAD and an empty one are the same to GCM. + BOOST_TEST(tp::open(key, str(entry["sealed"]), std::string_view()).has_value()); + } + } +} + +// A plaintext that is not UTF-8 seals, and is refused on opening (design D12). +void open_refuses_a_plaintext_that_is_not_utf8() { + const auto key = tp::room_aes_key_without_password("a", "r"); + const std::array iv{}; + const auto sealed = tp::seal(key, iv, std::string_view("ab\xff\xfe", 4), std::nullopt); + BOOST_TEST(sealed.has_value()); + if (sealed) { + const auto opened = tp::open(key, *sealed, std::nullopt); + BOOST_TEST(!opened.has_value()); + if (!opened) { + BOOST_TEST(opened.error() == webcpp::trystero::error::decrypt_failed); + } + } +} + +// The library's own wipe zeroes a buffer and a plain object. +void wipe_zeroes_what_it_is_given() { + std::array buffer{}; + buffer.fill(0xA5); + webcpp::trystero::detail::wipe(buffer.data(), buffer.size()); + BOOST_TEST(std::ranges::all_of(buffer, [](unsigned char byte) { return byte == 0; })); + + struct plain { + std::uint64_t word; + std::array tail; + }; + + plain object{.word = ~std::uint64_t{0}, .tail = {}}; + object.tail.fill(0xFF); + webcpp::trystero::detail::wipe_object(object); + BOOST_TEST_EQ(object.word, 0U); + BOOST_TEST(std::ranges::all_of(object.tail, [](std::uint8_t byte) { return byte == 0; })); + + webcpp::trystero::detail::wipe(nullptr, 0); +} + +void signal_aad_matches() { + for (const auto entry : section("signal_aad")) { + BOOST_TEST_EQ( + tp::signal_aad(str(entry["type"]), str(entry["peer_id"]), str(entry["offer_id"])), + str(entry["aad"])); + } +} + +/** The payload of an action frames case: its text, its bytes, or (i * 31) mod 256 of its size. */ +tp::bytes payload_of(const fixture_value& entry) { + if (const auto text = entry["payload_text"].value_or(std::string_view()); !text.empty()) { + return {text.begin(), text.end()}; + } + if (entry["payload_hex"].is_string()) { + return bytes_of(entry["payload_hex"]); + } + tp::bytes out(integer(entry["payload_size"])); + for (std::size_t i = 0; i < out.size(); ++i) { + out[i] = static_cast(i * 31); + } + return out; +} + +/** The text of a fixture value, or empty for null. */ +std::string_view text_or_empty(const fixture_value& v) { + return v.value_or(std::string_view()); +} + +/** Whether `encoded` is the recorded frame: its hex, or, for a chunk, its header, size and + * SHA-256. */ +bool is_recorded(const tp::bytes& encoded, const fixture_value& frame) { + if (frame["hex"].is_string()) { + const auto expected = bytes_of(frame["hex"]); + return BOOST_TEST_ALL_EQ(encoded.begin(), encoded.end(), expected.begin(), expected.end()); + } + const auto head = bytes_of(frame["head"]); + const auto digest = + tp::sha256(std::string_view(reinterpret_cast(encoded.data()), encoded.size())); + return BOOST_TEST_EQ(encoded.size(), integer(frame["size"])) && + BOOST_TEST(std::ranges::equal(std::span(encoded).first(head.size()), head)) && + BOOST_TEST_EQ(tp::to_hex(digest), str(frame["sha256"])); +} + +/** An action frames case, as the frames of it read it. */ +struct frames_case { + fixture_value entry; + std::string_view name; + tp::bytes payload; + tp::payload_format format{}; + std::string_view metadata; + bool wide = false; + std::size_t chunk = 0; + /** The chunks met so far. */ + std::size_t chunks = 0; +}; + +/** One recorded frame of a case: who sent it, its kind, and, for a refusal, its reason. */ +struct recorded_frame { + fixture_value frame; + bool from_sender = false; + tp::frame_kind kind{}; + /** A control frame's reason, as recorded: what follows its header. */ + std::string reason; + + [[nodiscard]] std::uint32_t transfer_id() const { + return static_cast(integer(frame["transfer_id"])); + } +}; + +recorded_frame read_frame(const fixture_value& frame) { + recorded_frame out{ + .frame = frame, + .from_sender = str(frame["from"]) == "A", + .kind = static_cast(frame["hex"].is_string() + ? bytes_of(frame["hex"])[1] & 15U + : bytes_of(frame["head"])[1] & 15U), + .reason = {}, + }; + if (out.kind == tp::frame_kind::rejected) { + const auto recorded = bytes_of(frame["hex"]); + out.reason.assign(recorded.begin() + tp::control_header_size, recorded.end()); + } + return out; +} + +/** The inline frame the port writes for a recorded one: the sender's of the case's action, or + * the receiver's answer. */ +tp::bytes encode_inline_of(const frames_case& c, const recorded_frame& f) { + if (f.from_sender) { + return tp::encode_inline(str(c.entry["action"]), c.format, c.metadata, c.payload); + } + const auto answer = c.entry["answer"]; + const auto text = str(answer["payload_text"]); + return tp::encode_inline(str(answer["action"]), + static_cast(integer(answer["format"])), + str(answer["metadata"]), tp::bytes(text.begin(), text.end())); +} + +/** The frame the port writes from the inputs of a recorded one; a chunk counts in `c`. */ +tp::bytes encode_like(frames_case& c, const recorded_frame& f) { + switch (f.kind) { + case tp::frame_kind::inline_payload: return encode_inline_of(c, f); + case tp::frame_kind::offer: + return tp::encode_offer(str(c.entry["action"]), c.format, c.metadata, f.transfer_id(), + c.payload.size(), + c.wide ? tp::chunk_width::wide : tp::chunk_width::narrow); + case tp::frame_kind::chunk: { + const auto offset = c.chunks++ * c.chunk; + const auto length = std::min(c.chunk, c.payload.size() - offset); + return tp::encode_chunk(f.transfer_id(), offset, + std::span(c.payload).subspan(offset, length)); + } + case tp::frame_kind::accepted: return tp::encode_accepted(f.transfer_id()); + case tp::frame_kind::cancelled: return tp::encode_cancelled(f.transfer_id()); + case tp::frame_kind::rejected: return tp::encode_rejected(f.transfer_id(), f.reason); + } + return {}; +} + +/** Checks an inline frame or an offer read back against the case it was written from. */ +void check_proposal(const frames_case& c, const recorded_frame& f, const tp::proposal& p) { + BOOST_TEST(p.kind == f.kind); + if (f.from_sender) { + BOOST_TEST_EQ(p.name, str(c.entry["action"])); + BOOST_TEST(p.format == c.format); + BOOST_TEST_EQ(p.metadata, c.metadata); + BOOST_TEST_EQ(p.size, c.payload.size()); + } + if (f.kind == tp::frame_kind::offer) { + BOOST_TEST_EQ(p.wide, c.wide); + BOOST_TEST_EQ(p.id, f.transfer_id()); + return; + } + if (f.from_sender) { + BOOST_TEST(std::ranges::equal(p.payload, c.payload)); + return; + } + const auto answer = c.entry["answer"]; + const auto text = str(answer["payload_text"]); + BOOST_TEST_EQ(p.name, str(answer["action"])); + BOOST_TEST(p.format == static_cast(integer(answer["format"]))); + BOOST_TEST_EQ(p.metadata, str(answer["metadata"])); + BOOST_TEST(std::ranges::equal( + p.payload, std::span(reinterpret_cast(text.data()), text.size()))); +} + +/** Checks a frame read back against the recorded one it was written like. */ +void check_decoded(const frames_case& c, const recorded_frame& f, const tp::decoded_action& frame) { + if (const auto* p = std::get_if(&frame)) { + check_proposal(c, f, *p); + } else if (const auto* piece = std::get_if(&frame)) { + BOOST_TEST_EQ(piece->offset, static_cast((c.chunks - 1) * c.chunk)); + BOOST_TEST_EQ(piece->id, f.transfer_id()); + } else { + const auto& m = std::get(frame); + BOOST_TEST(m.kind == f.kind); + BOOST_TEST_EQ(m.id, f.transfer_id()); + BOOST_TEST_EQ(m.reason, f.reason); + } +} + +// Each frame Trystero 0.27.0's action-wire.ts sent between two of its managers: the port writes it +// from the same inputs, and reads it back to the same message. A case's first frame is the sender's +// inline frame or offer of the case's action, format, metadata and payload; a request's answer is +// the receiver's inline frame of "@_response". +void action_frames_match() { + for (const auto entry : section("action_frames")) { + const bool wide = entry["wide"].value_or(false); + frames_case c{ + .entry = entry, + .name = str(entry["case"]), + .payload = payload_of(entry), + .format = static_cast(integer(entry["format"])), + .metadata = text_or_empty(entry["metadata"]), + .wide = wide, + .chunk = wide ? tp::wide_chunk_size : tp::chunk_size, + .chunks = 0, + }; + for (const auto frame : entry["frames"]) { + const auto f = read_frame(frame); + const auto encoded = encode_like(c, f); + if (!is_recorded(encoded, frame)) { + BOOST_ERROR(std::string("case ").append(c.name).c_str()); + continue; + } + const auto decoded = tp::decode_action(encoded); + if (BOOST_TEST(decoded.frame.has_value())) { + check_decoded(c, f, *decoded.frame); + } + } + if (c.chunks != 0 && c.name != "cancelled") { + BOOST_TEST_EQ(c.chunks, (c.payload.size() + c.chunk - 1) / c.chunk); + } + } + BOOST_TEST_EQ(section("action_frames").size(), 10U); +} + +// The handshake's frames 0.27.0 writes (handshake_frames), each the inline frame of its action, as +// the port's encoder writes it for a room: the ready frame, `@_hsready` with the empty text of +// 0.27.0's `payload || ''`; a step of the identity handshake, `@_hsdata` with its JSON; the +// refusal of a full room, `@_hsready` with its JSON; and a ban, `@_hsready` with its JSON, which +// the port never sends, having no roles, and which room_test's `a_ban_from_a_peer_reports_banned` +// injects byte for byte. +void handshake_frames_match() { + std::size_t matched = 0; + for (const auto entry : section("handshake_frames")) { + const auto name = str(entry["case"]); + const bool ready = name == "ready"; + BOOST_TEST_EQ(str(entry["action"]), name == "step 1" ? "@_hsdata" : "@_hsready"); + const auto payload = str(entry["payload_json"]); + if (ready) { + BOOST_TEST_EQ(payload, R"("")"); + } else if (name == "room full") { + BOOST_TEST_EQ(payload, R"({"ok":false,"err":"room full"})"); + } else if (name == "banned") { + BOOST_TEST_EQ(payload, R"({"ok":false,"err":"peer banned","reason":"spam"})"); + } else { + BOOST_TEST_EQ(name, "step 1"); + BOOST_TEST(payload.starts_with(R"({"__trystero_id":1,)")); + } + BOOST_TEST(entry["delivered"].value_or(false) == true); + std::vector frames; + for (const auto frame : entry["frames"]) { + frames.push_back(frame); + } + if (!BOOST_TEST_EQ(frames.size(), 1U)) { + continue; + } + BOOST_TEST_EQ(str(frames[0]["from"]), "A"); + // The room sends a step and a refusal as a JSON payload, the ready frame's empty text as + // a text. + const auto encoded = + ready + ? tp::encode_inline("@_hsready", tp::payload_format::text, "", {}) + : tp::encode_inline(str(entry["action"]), tp::payload_format::json, "", + std::span(reinterpret_cast(payload.data()), + payload.size())); + BOOST_TEST_EQ(encoded.size(), integer(frames[0]["size"])); + BOOST_TEST(is_recorded(encoded, frames[0])); + ++matched; + } + BOOST_TEST_EQ(matched, 4U); +} + +// 0.27.0's ping (ping_frames): a request of the internal action `@_ping`, an empty text whose +// metadata `{"r":}` names the request, answered by the other peer with an empty text through +// `@_response` under the same metadata; the port writes both frames byte for byte. room_test's +// `ping_is_a_request_action` checks a room's own frames against them. +void ping_frames_match() { + const auto entry = section("ping_frames"); + BOOST_TEST_EQ(str(entry["action"]), "@_ping"); + BOOST_TEST_EQ(str(entry["response"]), ""); + std::string metadata(R"({"r":")"); + metadata += str(entry["request_id"]); + metadata += "\"}"; + std::vector frames; + for (const auto frame : entry["frames"]) { + frames.push_back(frame); + } + if (!BOOST_TEST_EQ(frames.size(), 2U)) { + return; + } + BOOST_TEST_EQ(str(frames[0]["from"]), "A"); + BOOST_TEST(is_recorded(tp::encode_inline("@_ping", tp::payload_format::text, metadata, {}), + frames[0])); + BOOST_TEST_EQ(str(frames[1]["from"]), "B"); + BOOST_TEST(is_recorded(tp::encode_inline("@_response", tp::payload_format::text, metadata, {}), + frames[1])); +} + +// The P-256 identity of 0.27.0 (Phase 2): keys, compact keys, the user key's text, the user-proof +// and low S, against the sections 0.27.0's recorder wrote. + +namespace p256 = webcpp::crypto::curves::p256; + +/** The key pair of a fixture's base64url scalar. */ +std::optional keypair_of(const fixture_value& d) { + const auto scalar = tp::from_base64url(str(d)); + if (!BOOST_TEST(scalar.has_value()) || !BOOST_TEST_EQ(scalar->size(), 32U)) { + return std::nullopt; + } + auto key = p256::keypair::make(*scalar); + if (!BOOST_TEST(key.has_value())) { + return std::nullopt; + } + return std::move(*key); +} + +/** The entry of `p256_keys` labelled `label`. */ +fixture_value p256_key_entry(std::string_view label) { + for (const auto entry : section("p256_keys")) { + if (str(entry["label"]) == label) { + return entry; + } + } + BOOST_ERROR("p256_keys has no such label"); + return section("p256_keys")[0]; +} + +/** The public key of a compact text, which must be one. */ +std::optional public_key_of(std::string_view compact) { + const auto point = tp::parse_compact_public_key(compact); + if (!BOOST_TEST(point.has_value())) { + return std::nullopt; + } + const auto key = p256::public_key::make(*point); + if (!BOOST_TEST(key.has_value())) { + return std::nullopt; + } + return *key; +} + +/** The bytes of a text, as a span. */ +std::span bytes_view(std::string_view text) { + return {reinterpret_cast(text.data()), text.size()}; +} + +void p256_keys_derive_their_ids() { + std::size_t keys = 0; + for (const auto entry : section("p256_keys")) { + const auto key = keypair_of(entry["d"]); + if (!key) { + continue; + } + const auto point = key->public_key(); + if (!BOOST_TEST(point.has_value())) { + continue; + } + const auto uncompressed = point->uncompressed(); + BOOST_TEST(std::ranges::equal(uncompressed, bytes_of(entry["uncompressed"]))); + const auto compact = tp::compact_public_key(uncompressed); + BOOST_TEST_EQ(compact, str(entry["compact"])); + BOOST_TEST_EQ(tp::derive_peer_id(compact), str(entry["peer_id"])); + BOOST_TEST_EQ(tp::derive_user_id(compact), str(entry["user_id"])); + ++keys; + } + BOOST_TEST_EQ(keys, 5U); +} + +void compact_keys_are_read_as_0_27_0_reads_them() { + std::size_t cases = 0; + for (const auto entry : section("compact_keys")) { + const auto point = tp::parse_compact_public_key(str(entry["text"])); + BOOST_TEST_EQ(point.has_value(), entry["text_valid"].value_or(false)); + const bool record = point && p256::public_key::make(*point).has_value(); + BOOST_TEST_EQ(record, entry["record"].value_or(false)); + ++cases; + } + BOOST_TEST_EQ(cases, 6U); +} + +void user_identity_text_matches() { + const auto entry = section("user_identity"); + const auto imported = trystero::import_user_identity(str(entry["text"])); + if (!BOOST_TEST(imported.has_value())) { + return; + } + BOOST_TEST_EQ(trystero::export_user_identity(*imported), str(entry["text"])); + BOOST_TEST_EQ(imported->user_id(), str(entry["user_id"])); + BOOST_TEST_EQ(imported->public_key(), str(p256_key_entry(str(entry["label"]))["compact"])); + // The JSON form is the same key, and exports as the text. + const auto from_json = trystero::import_user_identity(str(entry["json"])); + if (BOOST_TEST(from_json.has_value())) { + BOOST_TEST_EQ(from_json->user_id(), str(entry["user_id"])); + BOOST_TEST_EQ(trystero::export_user_identity(*from_json), str(entry["text"])); + } + // The material is the JWK's. + const auto material = tp::parse_user_key(str(entry["text"])); + if (BOOST_TEST(material.has_value())) { + BOOST_TEST_EQ(tp::to_base64url(material->d.bytes()), str(entry["jwk"]["d"])); + BOOST_TEST_EQ( + std::string(tp::compact_public_key(material->point)), + std::string(str(entry["jwk"]["x"])) + "." + std::string(str(entry["jwk"]["y"]))); + } +} + +void user_identity_imports_match() { + std::size_t cases = 0; + for (const auto entry : section("user_identity_imports")) { + const auto imported = trystero::import_user_identity(str(entry["text"])); + const bool accepted = entry["accepted"].value_or(false); + if (!BOOST_TEST_EQ(imported.has_value(), accepted)) { + BOOST_LIGHTWEIGHT_TEST_OSTREAM << " case: " << str(entry["case"]) << "\n"; + continue; + } + if (accepted) { + BOOST_TEST_EQ(imported->user_id(), str(entry["user_id"])); + } else { + BOOST_TEST(imported.error() == trystero::error::invalid_user_identity); + } + ++cases; + } + BOOST_TEST_EQ(cases, 12U); +} + +/** A resource over `new` and `delete` that, as each block is freed, counts the blocks that still + * hold a fixture key's scalar, as its 32 bytes or as its base64url text. */ +class secret_watch final : public std::pmr::memory_resource { +public: + secret_watch() { + for (const auto entry : section("p256_keys")) { + const std::string text(str(entry["d"])); + const auto scalar = tp::from_base64url(text); + if (BOOST_TEST(scalar.has_value()) && BOOST_TEST_EQ(scalar->size(), 32U)) { + needles_.emplace_back(reinterpret_cast(scalar->data()), + scalar->size()); + } + needles_.push_back(text); + } + } + + /** The blocks freed with a scalar in them so far. */ + [[nodiscard]] std::size_t hits() const { return hits_; } + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + return std::pmr::new_delete_resource()->allocate(bytes, alignment); + } + + void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override { + const std::string_view block(static_cast(p), bytes); + if (std::ranges::any_of(needles_, [&](const std::string& needle) { + return block.find(needle) != std::string_view::npos; + })) { + ++hits_; + } + std::pmr::new_delete_resource()->deallocate(p, bytes, alignment); + } + + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; + } + + std::vector needles_; + std::size_t hits_ = 0; +}; + +/** Makes a resource the default one while it lives. */ +class default_resource_scope { +public: + explicit default_resource_scope(std::pmr::memory_resource* r) + : previous_(std::pmr::set_default_resource(r)) {} + + default_resource_scope(const default_resource_scope&) = delete; + default_resource_scope& operator=(const default_resource_scope&) = delete; + + ~default_resource_scope() { std::pmr::set_default_resource(previous_); } + +private: + std::pmr::memory_resource* previous_; +}; + +// No buffer of trystero's that held a user key's scalar is freed with it: importing, parsing and +// exporting a key, accepted or refused after its d is decoded, through a resource that is also the +// default one, frees no block that holds a scalar of the fixture's keys. +void user_key_buffers_are_wiped() { + // Static, so that it outlives any block allocated in it while it is the default resource. + static secret_watch watch; + // The watch sees a copy of a scalar's text freed as it is. + { + const std::pmr::string copy(str(section("user_identity")["jwk"]["d"]), &watch); + BOOST_TEST(!copy.empty()); + } + BOOST_TEST_EQ(watch.hits(), 1U); + std::vector texts; + for (const auto entry : section("user_identity_imports")) { + texts.emplace_back(str(entry["text"])); + } + texts.emplace_back(str(section("user_identity")["json"])); + std::size_t accepted = 0; + { + const default_resource_scope scope(&watch); + for (const auto& text : texts) { + { + const auto imported = trystero::import_user_identity(text, &watch); + if (imported) { + ++accepted; + // The text is the caller's, which wipes it, as the function's doc asks. + auto exported = trystero::export_user_identity(*imported, &watch); + trystero::detail::wipe(exported.data(), exported.size()); + } + } + const auto material = tp::parse_user_key(text, &watch); + } + // A created identity, exported, then ended. + const auto created = trystero::create_user_identity(&watch); + if (BOOST_TEST(created.has_value())) { + auto exported = trystero::export_user_identity(*created, &watch); + trystero::detail::wipe(exported.data(), exported.size()); + } + } + BOOST_TEST_EQ(accepted, 4U); + BOOST_TEST_EQ(watch.hits(), 1U); +} + +// What 0.27.0's tryParsePrivateJwk reads beyond the fixture: String.prototype.trim's white space, +// the kty and crv it ignores when falsy, the byte order mark TextDecoder drops. +void user_key_text_is_read_as_0_27_0_reads_it() { + const auto entry = section("user_identity"); + const std::string text(str(entry["text"])); + const std::string json(str(entry["json"])); + const std::string user_id(str(entry["user_id"])); + const auto accepts = [&](std::string_view candidate) { + const auto imported = trystero::import_user_identity(candidate); + return imported.has_value() && imported->user_id() == user_id; + }; + // U+00A0, U+FEFF, U+2028, U+3000, tab and vertical tab around the text. + BOOST_TEST(accepts("\xc2\xa0\xef\xbb\xbf" + text + "\xe2\x80\xa8\xe3\x80\x80\t\v")); + BOOST_TEST(accepts("\xe2\x80\x8a" + json + "\xe2\x81\x9f")); + // U+200B is no white space of trim's. + BOOST_TEST(!accepts("\xe2\x80\x8b" + text)); + const std::string members = json.substr(1); // "d":...} + BOOST_TEST(accepts(R"({"kty":"","crv":null,)" + members)); + BOOST_TEST(accepts(R"({"kty":0,"crv":false,)" + members)); + BOOST_TEST(!accepts(R"({"kty":1,)" + members)); + BOOST_TEST(!accepts(R"({"kty":"OKP",)" + members)); + BOOST_TEST(!accepts(R"({"crv":["P-256"],)" + members)); + // A member written twice keeps its last value, as JSON.parse keeps it. + BOOST_TEST(accepts(R"({"d":"AAAA",)" + members)); + BOOST_TEST(!accepts(R"({"d":1,"x":2,"y":3})")); + BOOST_TEST(!accepts("[" + json + "]")); + // The prefixed text of the JSON with a byte order mark, which TextDecoder drops. + const std::string bom_json = "\xef\xbb\xbf" + json; + std::string bom_text(tp::user_key_prefix); + bom_text += tp::to_base64url(bytes_view(bom_json)); + BOOST_TEST(accepts(bom_text)); + BOOST_TEST(!accepts(tp::user_key_prefix)); + BOOST_TEST(!accepts(" ")); +} + +void user_proof_matches() { + const auto entry = section("user_proof"); + const auto payload = tp::user_proof_payload( + str(entry["app"]), str(entry["room"]), str(entry["peer_id"]), str(entry["peer_compact"]), + integer(entry["seq"]), std::pmr::get_default_resource()); + BOOST_TEST_EQ(payload, str(entry["payload"])); + BOOST_TEST_EQ(tp::to_hex(tp::sha256(payload)), str(entry["digest"])); + const auto user_key = public_key_of(str(entry["user_compact"])); + const auto proof = tp::from_base64url(str(entry["proof"])); + if (!user_key || !BOOST_TEST(proof.has_value())) { + return; + } + BOOST_TEST_EQ(tp::verify_p256(*proof, bytes_view(payload), *user_key), + entry["verifies"].value_or(false)); + const auto other_seq = tp::user_proof_payload( + str(entry["app"]), str(entry["room"]), str(entry["peer_id"]), str(entry["peer_compact"]), + integer(entry["seq"]) + 1, std::pmr::get_default_resource()); + BOOST_TEST_EQ(tp::verify_p256(*proof, bytes_view(other_seq), *user_key), + entry["other_seq_verifies"].value_or(true)); + // The port's own proof, by user-a's key, is low S and verifies. + const auto user_a = p256_key_entry("user-a"); + BOOST_TEST_EQ(str(user_a["user_id"]), str(entry["user_id"])); + const auto key = keypair_of(user_a["d"]); + if (!key) { + return; + } + const auto signed_payload = tp::sign_p256(*key, bytes_view(payload)); + if (BOOST_TEST(signed_payload.has_value())) { + BOOST_TEST(tp::is_low_s(*signed_payload)); + BOOST_TEST(tp::verify_p256(*signed_payload, bytes_view(payload), *user_key)); + BOOST_TEST(!tp::verify_p256(*signed_payload, bytes_view(other_seq), *user_key)); + } +} + +void low_s_matches() { + const auto entry = section("user_proof"); + const auto payload = tp::user_proof_payload( + str(entry["app"]), str(entry["room"]), str(entry["peer_id"]), str(entry["peer_compact"]), + integer(entry["seq"]), std::pmr::get_default_resource()); + const auto user_key = public_key_of(str(entry["user_compact"])); + if (!user_key) { + return; + } + std::size_t cases = 0; + std::size_t in_range = 0; + for (const auto c : section("low_s")) { + const auto signature = bytes_of(c["signature"]); + BOOST_TEST_EQ(tp::is_low_s(signature), c["is_low_s"].value_or(true)); + BOOST_TEST_EQ(tp::verify_p256(signature, bytes_view(payload), *user_key), + c["verifies"].value_or(true)); + if (signature.size() == 64) { + const auto normalized = + p256::normalize_ecdsa(std::span(signature.data(), 64)); + if (normalized) { + BOOST_TEST(std::ranges::equal(*normalized, bytes_of(c["normalized"]))); + ++in_range; + } else { + // r or s is 0 or not below n: 0.27.0 leaves the signature as it is. + BOOST_TEST(bytes_of(c["normalized"]) == signature); + } + } + ++cases; + } + BOOST_TEST_EQ(cases, 8U); + BOOST_TEST_EQ(in_range, 5U); + // A signature of another length is never low S, as isLowSP256Signature says. + BOOST_TEST(!tp::is_low_s(std::span{})); +} + +void cpp_signatures_are_deterministic_and_low_s() { + const auto key = keypair_of(p256_key_entry("endpoint-a")["d"]); + if (!key) { + return; + } + const auto point = key->public_key(); + if (!BOOST_TEST(point.has_value())) { + return; + } + for (const std::string_view payload : {"", "payload", "trystero:identity-self-test:v1"}) { + const auto first = tp::sign_p256(*key, bytes_view(payload)); + const auto second = tp::sign_p256(*key, bytes_view(payload)); + if (!BOOST_TEST(first.has_value()) || !BOOST_TEST(second.has_value())) { + continue; + } + BOOST_TEST(*first == *second); // RFC 6979 + BOOST_TEST(tp::is_low_s(*first)); + BOOST_TEST(tp::verify_p256(*first, bytes_view(payload), *point)); + } +} + +void identities_sign_as_their_keys() { + // A user identity signs as its key does. + const auto identity = trystero::import_user_identity(str(section("user_identity")["text"])); + if (BOOST_TEST(identity.has_value())) { + const auto made = identity->sign(bytes_view("payload")); + const auto again = identity->sign(bytes_view("payload")); + BOOST_TEST(made.has_value() && again.has_value() && *made == *again); + if (made) { + BOOST_TEST(tp::verify_p256(*made, bytes_view("payload"), + *public_key_of(identity->public_key()))); + } + } + // A created identity is fresh each time, and exports as a text that imports to it. + const auto a = trystero::create_user_identity(); + const auto b = trystero::create_user_identity(); + if (BOOST_TEST(a.has_value()) && BOOST_TEST(b.has_value())) { + BOOST_TEST_NE(a->user_id(), b->user_id()); + BOOST_TEST_EQ(a->user_id().size(), tp::user_id_size); + const auto text = trystero::export_user_identity(*a); + BOOST_TEST_EQ(text.size(), 214U); + const auto again = trystero::import_user_identity(text); + BOOST_TEST(again.has_value() && again->user_id() == a->user_id()); + // A move copies: an identity has no move of its own, so the one moved from keeps its key. + // What the analysis says of the move below (it does nothing, the identity moved from could + // be const and is used after it) is what this case asserts. + // NOLINTBEGIN(bugprone-use-after-move,performance-move-const-arg,misc-const-correctness) + auto moved = *a; + const auto target = std::move(moved); + BOOST_TEST_EQ(moved.user_id(), target.user_id()); + BOOST_TEST(moved.sign(bytes_view("payload")).has_value()); + // NOLINTEND(bugprone-use-after-move,performance-move-const-arg,misc-const-correctness) + } +} + +void scalars_are_checked_against_the_order() { + std::array scalar{}; + BOOST_TEST(!tp::is_p256_scalar(scalar)); // zero + scalar.back() = 1; + BOOST_TEST(tp::is_p256_scalar(scalar)); + scalar = tp::p256_order; + BOOST_TEST(!tp::is_p256_scalar(scalar)); // n + scalar.back() -= 1; + BOOST_TEST(tp::is_p256_scalar(scalar)); // n - 1 + scalar.fill(0xff); + BOOST_TEST(!tp::is_p256_scalar(scalar)); +} + +// The identity handshake: its messages, transcript and each side's run, against 0.27.0's record. + +/** The fingerprints of a description, in the default resource. */ +std::pmr::vector dtls_of(std::string_view sdp) { + return tp::dtls_fingerprints(sdp, std::pmr::get_default_resource()); +} + +/** The texts of a fixture's array of strings. */ +std::pmr::vector strings_of(const fixture_value& array) { + std::pmr::vector out; + for (const auto item : array) { + out.emplace_back(str(item)); + } + return out; +} + +/** A recorded step's members, as the test reads them from its JSON (not through the reader). */ +tp::handshake_claims claims_of(std::string_view json) { + tp::handshake_claims claims; + const auto parsed = wd::parse(json); + if (!BOOST_TEST(parsed.has_value())) { + return claims; + } + const fixture_value root = parsed->root(); + claims.step = static_cast(root[tp::handshake_step_key].value_or(std::int64_t{0})); + claims.nonce = str(root["n"]); + claims.dtls = strings_of(root["dtls"]); + claims.user_id = str(root["uid"]); + claims.endpoint_key = str(root["pk"]); + claims.user_key = str(root["uk"]); + claims.endpoint_signature = str(root["ps"]); + claims.user_signature = str(root["us"]); + return claims; +} + +/** The recorded message of a case with `step`, or an empty text. */ +std::string_view message_of(const fixture_value& c, int step) { + for (const auto m : c["messages"]) { + if (m["step"].value_or(std::int64_t{0}) == step) { + return str(m["json"]); + } + } + return {}; +} + +/** The 16 random bytes `uuid_v4` turns into a recorded nonce. */ +std::array nonce_random_of(std::string_view uuid) { + std::string hex; + std::ranges::copy_if(uuid, std::back_inserter(hex), [](char ch) { return ch != '-'; }); + const auto decoded = tp::from_hex(hex); + std::array out{}; + if (BOOST_TEST(decoded.has_value() && decoded->size() == 16)) { + std::ranges::copy(*decoded, out.begin()); + } + return out; +} + +/** The scalar of a fixture key's `d`. */ +tp::bytes scalar_of(std::string_view label) { + const auto scalar = tp::from_base64url(str(p256_key_entry(label)["d"])); + BOOST_TEST(scalar.has_value()); + return scalar.value_or(tp::bytes()); +} + +/** One side of a recorded handshake as the C++ side runs it: its keys, cache and machine. */ +struct handshake_side { + trystero::detail::endpoint_identity endpoint; + trystero::user_identity user; + std::pmr::vector local_dtls; + std::pmr::vector remote_dtls; + trystero::detail::identity_cache cache{std::pmr::get_default_resource()}; + std::optional machine{}; +}; + +/** The endpoint identity of a fixture key. */ +trystero::detail::endpoint_identity endpoint_of(std::string_view label) { + auto made = trystero::detail::make_endpoint_identity(scalar_of(label), + std::pmr::get_default_resource()); + BOOST_TEST(made.has_value()); + return std::move(made.value()); +} + +/** The user identity of a fixture key. */ +trystero::user_identity user_of(std::string_view label) { + auto made = trystero::detail::user_identity_access::make(scalar_of(label), + std::pmr::get_default_resource()); + BOOST_TEST(made.has_value()); + return made.value(); +} + +/** Makes the C++ side of `role` ("initiator" or "responder") of a recorded case; `room` and `nonce` + * replace the recorded room and own nonce when not empty. */ +std::unique_ptr side_of(const fixture_value& c, std::string_view role, + std::string_view room = {}, std::string_view nonce = {}) { + const bool initiator = role == "initiator"; + const auto self = c[role]; + const auto remote = c[initiator ? "responder" : "initiator"]; + // The endpoint, the user, the local and the remote fingerprints; the cache and the machine + // take their defaults. + auto side = std::make_unique( + endpoint_of(str(self["endpoint"])), user_of(str(self["user"])), + dtls_of(str(self["sdp_local"])), dtls_of(str(self["sdp_remote"]))); + BOOST_TEST_EQ(side->endpoint.peer_id, str(self["peer_id"])); + BOOST_TEST_EQ(side->user.user_id(), str(self["user_id"])); + side->machine.emplace( + trystero::detail::local_identity{ + .endpoint = side->endpoint.key, + .peer_id = side->endpoint.peer_id, + .endpoint_key = side->endpoint.compact, + .user = side->user, + }, + side->cache, str(c["app"]), room.empty() ? str(c["room"]) : room, str(remote["peer_id"]), + initiator, side->local_dtls, side->remote_dtls, + nonce_random_of(nonce.empty() ? str(c["nonces"][initiator ? 0 : 1]) : nonce), + std::pmr::get_default_resource()); + return side; +} + +/** The recorded case named `name`. */ +fixture_value handshake_case(std::string_view name) { + for (const auto c : section("handshake")) { + if (str(c["case"]) == name) { + return c; + } + } + BOOST_ERROR("handshake has no such case"); + return section("handshake")[0]; +} + +/** Whether `signature` (base64url) is `compact`'s, of `payload`, through an identity cache. */ +bool verifies(std::string_view compact, std::string_view signature, std::string_view payload) { + trystero::detail::identity_cache cache(std::pmr::get_default_resource()); + const auto bytes = tp::from_base64url(signature); + return bytes && cache.verify(compact, *bytes, bytes_view(payload)); +} + +void dtls_fingerprints_match() { + std::size_t sent = 0; + for (const auto c : section("handshake")) { + for (const auto m : c["messages"]) { + const auto step = m["step"].value_or(std::int64_t{0}); + if (step == 3) { + continue; + } + const auto* const role = str(m["from"]) == "A" ? "initiator" : "responder"; + BOOST_TEST(dtls_of(str(c[role]["sdp_local"])) == claims_of(str(m["json"])).dtls); + ++sent; + } + } + BOOST_TEST_EQ(sent, 11U); + // The rule itself: lines that start "a=fingerprint:" (a line starts after \n, \r, U+2028 or + // U+2029), the value to the line's \r or \n, trimmed, lowercased, deduplicated, in UTF-16 + // order. + using list = std::pmr::vector; + BOOST_TEST(dtls_of("").empty()); + BOOST_TEST(dtls_of("a=fingerprint:").empty()); + BOOST_TEST(dtls_of("a=fingerprint: \r\n").empty()); + BOOST_TEST(dtls_of(" a=fingerprint:x\r\nb a=fingerprint:y").empty()); + BOOST_TEST(dtls_of("a=fingerprint:B\na=fingerprint: b \r\ra=fingerprint:A") == + (list{"a", "b"})); + BOOST_TEST(dtls_of("v=0\xe2\x80\xa8" + "a=fingerprint:x\xe2\x80\xa9" + "a=fingerprint:y\r\n") == (list{"x\xe2\x80\xa9" + "a=fingerprint:y"})); + BOOST_TEST(dtls_of("x\xe2\x80\xa8" + "a=fingerprint:z") == (list{"z"})); + // U+FF01 is after U+1F600 in UTF-16 (0xff01 > 0xd83d), before it in UTF-8. + BOOST_TEST(dtls_of("a=fingerprint:\xef\xbc\x81\na=fingerprint:\xf0\x9f\x98\x80") == + (list{"\xf0\x9f\x98\x80", "\xef\xbc\x81"})); + // JavaScript's trim removes U+00A0 and U+3000 too. + BOOST_TEST(dtls_of("a=fingerprint:\xc2\xa0Sha-256 AB\xe3\x80\x80") == (list{"sha-256 ab"})); +} + +void handshake_steps_match() { + const auto c = handshake_case("verified"); + std::size_t steps = 0; + for (const auto m : c["messages"]) { + const auto json = str(m["json"]); + BOOST_TEST_EQ(tp::write_handshake_step(claims_of(json), std::pmr::get_default_resource()), + json); + ++steps; + } + BOOST_TEST_EQ(steps, 3U); + // The frames' payloads are these steps. + BOOST_TEST_EQ(str(section("handshake_frames")[0]["payload_json"]), message_of(c, 1)); + // Each step reads back as it was written, under the descriptions the recipient applied. + const auto a_dtls = dtls_of(str(c["initiator"]["sdp_local"])); + const auto b_dtls = dtls_of(str(c["responder"]["sdp_local"])); + for (int step = 1; step <= 3; ++step) { + const auto json = message_of(c, step); + const bool from_b = step == 2; + const auto read = + tp::read_handshake_step(json, step, from_b ? b_dtls : a_dtls, from_b ? a_dtls : b_dtls, + std::pmr::get_default_resource()); + if (BOOST_TEST(read.claims.has_value())) { + BOOST_TEST(read.failure.empty()); + BOOST_TEST_EQ(tp::write_handshake_step(*read.claims, std::pmr::get_default_resource()), + json); + } + } +} + +/** `json` with the value of its top-level member `member` replaced by `value`, a JSON text. */ +std::pmr::string with_member(std::pmr::string json, std::string_view member, + std::string_view value) { + const std::string key = "\"" + std::string(member) + "\":"; + const auto at = json.find(key); + BOOST_TEST(at != std::string::npos); + auto end = at + key.size(); + int depth = 0; + bool quoted = false; + for (; end < json.size(); ++end) { + const char ch = json[end]; + if (quoted) { + quoted = ch != '"'; + continue; + } + if (ch == '"') { + quoted = true; + } else if (ch == '[') { + ++depth; + } else if (ch == ']') { + --depth; + } else if ((ch == ',' || ch == '}') && depth == 0) { + break; + } + } + json.replace(at + key.size(), end - at - key.size(), value); + return json; +} + +void handshake_steps_are_read_as_0_27_0_reads_them() { + const auto c = handshake_case("verified"); + const auto a_dtls = dtls_of(str(c["initiator"]["sdp_local"])); + const auto b_dtls = dtls_of(str(c["responder"]["sdp_local"])); + auto* memory = std::pmr::get_default_resource(); + const auto read = [&](std::string_view json, int step) { + return tp::read_handshake_step(json, step, step == 2 ? b_dtls : a_dtls, + step == 2 ? a_dtls : b_dtls, memory); + }; + // A step 1 with one member replaced. + const auto step1 = [&](std::string_view member, std::string_view value) { + const auto claims = claims_of(message_of(c, 1)); + return with_member(tp::write_handshake_step(claims, memory), member, value); + }; + const auto identity = tp::handshake_reason::identity; + const auto mismatch = tp::handshake_reason::dtls_mismatch; + BOOST_TEST(read(message_of(c, 1), 1).claims.has_value()); + for (const std::string_view json : {"", "null", "1", "\"x\"", "[]", "{", "{}"}) { + BOOST_TEST_EQ(read(json, 1).failure, identity); + } + BOOST_TEST_EQ(read(message_of(c, 1), 2).failure, identity); // another step + BOOST_TEST_EQ(read(step1("__trystero_id", "\"1\""), 1).failure, identity); + BOOST_TEST_EQ(read(step1("__trystero_id", "1.5"), 1).failure, identity); // not truncated to 1 + BOOST_TEST(read(step1("__trystero_id", "1.0"), 1).claims.has_value()); + BOOST_TEST(read(step1("__trystero_id", "1e0"), 1).claims.has_value()); + BOOST_TEST_EQ(read(step1("n", "123456789012345"), 1).failure, identity); + BOOST_TEST_EQ(read(step1("n", "\"012345678901234\""), 1).failure, identity); + BOOST_TEST(read(step1("n", "\"0123456789012345\""), 1).claims.has_value()); + BOOST_TEST_EQ(read(step1("uid", "\"\""), 1).failure, identity); + BOOST_TEST_EQ(read(step1("uid", "7"), 1).failure, identity); + BOOST_TEST(read(step1("pk", "\"\""), 1).claims.has_value()); // the key checks are the cache's + BOOST_TEST_EQ(read(step1("uk", "null"), 1).failure, identity); + BOOST_TEST_EQ(read(step1("dtls", "\"x\""), 1).failure, identity); + // The DTLS rule: what the description gives, or a list when this side has one. + std::string dtls_with_extras = "[1,null,{\"a\":[]},"; + for (std::size_t i = 0; i < a_dtls.size(); ++i) { + dtls_with_extras += (i == 0 ? "\"" : ",true,\"") + std::string(a_dtls[i]) + "\""; + } + dtls_with_extras += ",false]"; + const auto extras = read(step1("dtls", dtls_with_extras), 1); + if (BOOST_TEST(extras.claims.has_value())) { + BOOST_TEST(extras.claims->dtls == a_dtls); // the non-strings dropped + } + BOOST_TEST_EQ(read(step1("dtls", "[]"), 1).failure, mismatch); + BOOST_TEST_EQ(read(step1("dtls", "[\"sha-256 00\"]"), 1).failure, mismatch); + // Lists are compared as 0.27.0 compares them, joined with commas. + const std::string joined = + "[\"" + std::string(a_dtls[0]) + "," + std::string(a_dtls[1]) + "\"]"; + BOOST_TEST(read(step1("dtls", joined), 1).claims.has_value()); + // Without a description, the claimed list is taken; without a local list, an empty one too. + BOOST_TEST(tp::read_handshake_step(step1("dtls", "[\"sha-256 00\"]"), 1, {}, b_dtls, memory) + .claims.has_value()); + BOOST_TEST_EQ(tp::read_handshake_step(step1("dtls", "[]"), 1, {}, b_dtls, memory).failure, + mismatch); + BOOST_TEST(tp::read_handshake_step(step1("dtls", "[]"), 1, {}, {}, memory).claims.has_value()); + // Step 2 needs both signatures as strings; step 3 is its signatures alone. + auto step2 = claims_of(message_of(c, 2)); + BOOST_TEST(read(message_of(c, 2), 2).claims.has_value()); + step2.step = 1; // written without its signatures + auto unsigned_step2 = tp::write_handshake_step(step2, memory); + unsigned_step2.replace(unsigned_step2.find(":1,"), 3, ":2,"); + BOOST_TEST_EQ(read(unsigned_step2, 2).failure, identity); + const std::string_view without_us = R"({"__trystero_id":3,"ps":"a"})"; + const std::string_view numbered_2 = R"({"__trystero_id":2,"ps":"a","us":"b"})"; + BOOST_TEST_EQ(read(without_us, 3).failure, identity); + BOOST_TEST_EQ(read(numbered_2, 3).failure, identity); + const auto step3 = read(R"({"__trystero_id":3,"ps":"a","us":""})", 3); + if (BOOST_TEST(step3.claims.has_value())) { + BOOST_TEST_EQ(step3.claims->endpoint_signature, std::string_view("a")); + BOOST_TEST(step3.claims->user_signature.empty()); + } +} + +void handshake_transcript_matches() { + for (const auto c : section("handshake")) { + if (!c["transcript"].is_string()) { + continue; + } + const auto transcript = tp::handshake_transcript( + str(c["app"]), str(c["room"]), str(c["initiator"]["peer_id"]), + str(c["responder"]["peer_id"]), str(c["nonces"][0]), str(c["nonces"][1]), + dtls_of(str(c["initiator"]["sdp_local"])), dtls_of(str(c["responder"]["sdp_local"])), + str(c["initiator"]["user_id"]), str(c["responder"]["user_id"]), + std::pmr::get_default_resource()); + BOOST_TEST_EQ(transcript, str(c["transcript"])); + BOOST_TEST_EQ(tp::to_hex(tp::sha256(transcript)), str(c["transcript_digest"])); + } +} + +void js_handshake_signatures_verify() { + const auto c = handshake_case("verified"); + const auto transcript = str(c["transcript"]); + const auto step2 = claims_of(message_of(c, 2)); + const auto step3 = claims_of(message_of(c, 3)); + const auto compact = [](std::string_view label) { + return str(p256_key_entry(label)["compact"]); + }; + BOOST_TEST(c["transcript_verified"]["step2_endpoint"].value_or(false)); + BOOST_TEST(verifies(compact("endpoint-b"), step2.endpoint_signature, transcript)); + BOOST_TEST(c["transcript_verified"]["step2_user"].value_or(false)); + BOOST_TEST(verifies(compact("user-b"), step2.user_signature, transcript)); + BOOST_TEST(verifies(compact("endpoint-a"), step3.endpoint_signature, transcript)); + BOOST_TEST(verifies(compact("user-a"), step3.user_signature, transcript)); + // Of another key, or of another transcript, they do not. + BOOST_TEST(!verifies(compact("endpoint-a"), step2.endpoint_signature, transcript)); + BOOST_TEST(!verifies(compact("user-b"), step3.user_signature, transcript)); + BOOST_TEST( + !verifies(compact("endpoint-b"), step2.endpoint_signature, std::string(transcript) + " ")); +} + +void cpp_responder_meets_the_js_initiator() { + const auto c = handshake_case("verified"); + const auto b = side_of(c, "responder"); + const auto started = b->machine->start(); + BOOST_TEST(started.send.empty()); + BOOST_TEST(!started.done.has_value()); + BOOST_TEST(started.failure.empty()); + const auto stepped = b->machine->receive(message_of(c, 1)); + BOOST_TEST(stepped.failure.empty()); + BOOST_TEST(!stepped.done.has_value()); + // Step 2 is the recorded one but for its signatures, RFC 6979's where WebCrypto's are random. + const auto sent = claims_of(stepped.send); + auto expected = claims_of(message_of(c, 2)); + expected.endpoint_signature = sent.endpoint_signature; + expected.user_signature = sent.user_signature; + BOOST_TEST_EQ(stepped.send, + tp::write_handshake_step(expected, std::pmr::get_default_resource())); + BOOST_TEST(verifies(b->endpoint.compact, sent.endpoint_signature, str(c["transcript"]))); + BOOST_TEST(verifies(b->user.public_key(), sent.user_signature, str(c["transcript"]))); + const auto finished = b->machine->receive(message_of(c, 3)); + BOOST_TEST(finished.failure.empty()); + BOOST_TEST(finished.send.empty()); + if (BOOST_TEST(finished.done.has_value())) { + BOOST_TEST_EQ(finished.done->user_id, str(c["verified"]["B"]["user_id"])); + BOOST_TEST_EQ(finished.done->endpoint_key, str(p256_key_entry("endpoint-a")["compact"])); + BOOST_TEST_EQ(finished.done->user_key, str(p256_key_entry("user-a")["compact"])); + } + // A finished run takes nothing more. + const auto after = b->machine->receive(message_of(c, 3)); + BOOST_TEST(after.send.empty() && !after.done && after.failure.empty()); +} + +void cpp_initiator_meets_the_js_responder() { + const auto c = handshake_case("verified"); + const auto a = side_of(c, "initiator"); + // Before its start, a run takes nothing. + const auto early = a->machine->receive(message_of(c, 2)); + BOOST_TEST(early.send.empty() && !early.done && early.failure.empty()); + const auto started = a->machine->start(); + BOOST_TEST_EQ(started.send, message_of(c, 1)); + BOOST_TEST(!started.done.has_value()); + BOOST_TEST(started.failure.empty()); + const auto finished = a->machine->receive(message_of(c, 2)); + BOOST_TEST(finished.failure.empty()); + if (BOOST_TEST(finished.done.has_value())) { + BOOST_TEST_EQ(finished.done->user_id, str(c["verified"]["A"]["user_id"])); + BOOST_TEST_EQ(finished.done->endpoint_key, str(p256_key_entry("endpoint-b")["compact"])); + BOOST_TEST_EQ(finished.done->user_key, str(p256_key_entry("user-b")["compact"])); + } + const auto step3 = claims_of(finished.send); + BOOST_TEST_EQ(step3.step, 3); + BOOST_TEST_EQ(finished.send, tp::write_handshake_step(step3, std::pmr::get_default_resource())); + BOOST_TEST(verifies(a->endpoint.compact, step3.endpoint_signature, str(c["transcript"]))); + BOOST_TEST(verifies(a->user.public_key(), step3.user_signature, str(c["transcript"]))); +} + +void signatures_of_another_transcript_are_refused() { + const auto c = handshake_case("verified"); + // A responder of another room reads the recorded steps 1 and 3: its transcript differs, so + // the initiator's signatures do not verify. + const auto other_room = side_of(c, "responder", "another-room"); + other_room->machine->start(); + BOOST_TEST(other_room->machine->receive(message_of(c, 1)).failure.empty()); + const auto refused = other_room->machine->receive(message_of(c, 3)); + BOOST_TEST_EQ(refused.failure, tp::handshake_reason::identity); + BOOST_TEST(!refused.done.has_value()); + // An initiator of another nonce reads the recorded step 2, a replay of another run's. + const auto other_nonce = side_of(c, "initiator", {}, "00000000-0000-4000-8000-000000000000"); + other_nonce->machine->start(); + const auto replayed = other_nonce->machine->receive(message_of(c, 2)); + BOOST_TEST_EQ(replayed.failure, tp::handshake_reason::identity); + BOOST_TEST(!replayed.done.has_value()); +} + +/** The outcomes of a recorded case's run on the C++ side of `role`, its start and each message of + * the other side's, up to its first failure. */ +std::vector run_side(const fixture_value& c, + std::string_view role) { + const auto side = side_of(c, role); + const std::string_view own = role == "initiator" ? "A" : "B"; + std::vector outcomes; + outcomes.push_back(side->machine->start()); + for (const auto m : c["messages"]) { + if (!outcomes.back().failure.empty()) { + break; + } + if (str(m["from"]) != own) { + outcomes.push_back(side->machine->receive(str(m["json"]))); + } + } + return outcomes; +} + +/** What a side of a recorded case ended in. */ +enum class side_end : std::uint8_t { + verified, + waits, + failed, +}; + +/** Checks the C++ side of `role` of a recorded case against 0.27.0's: verified as it, waiting + * as it, or failed with its reason; returns which. */ +side_end check_side(const fixture_value& c, std::string_view role) { + const auto error = c[std::string(role) + "_error"]; + const std::string_view own = role == "initiator" ? "A" : "B"; + const auto outcomes = run_side(c, role); + const auto failed = + std::ranges::find_if(outcomes, [](const auto& o) { return !o.failure.empty(); }); + const auto done = + std::ranges::find_if(outcomes, [](const auto& o) { return o.done.has_value(); }); + if (error.is_null()) { + // The side 0.27.0 verified verifies too. + BOOST_TEST(failed == outcomes.end()); + if (BOOST_TEST(done != outcomes.end())) { + BOOST_TEST_EQ(done->done->user_id, str(c["verified"][own]["user_id"])); + } + return side_end::verified; + } + BOOST_TEST(done == outcomes.end()); + if (str(error) == "waits") { + BOOST_TEST(failed == outcomes.end()); + return side_end::waits; + } + std::string_view expected = str(error); + BOOST_TEST(expected.starts_with("Trystero: ")); + expected.remove_prefix(std::string_view("Trystero: ").size()); + if (BOOST_TEST(failed != outcomes.end())) { + BOOST_TEST_EQ(failed->failure, expected); + } + return side_end::failed; +} + +void handshake_failures_match() { + std::size_t failing = 0; + std::size_t waiting = 0; + std::size_t verified = 0; + for (const auto c : section("handshake")) { + if (str(c["case"]) == "verified") { + continue; + } + for (const std::string_view role : {"initiator", "responder"}) { + switch (check_side(c, role)) { + case side_end::verified: ++verified; break; + case side_end::waits: ++waiting; break; + case side_end::failed: ++failing; break; + } + } + } + BOOST_TEST_EQ(failing, 7U); + BOOST_TEST_EQ(waiting, 6U); + BOOST_TEST_EQ(verified, 1U); +} + +void uuid_nonces_have_16_units_or_more() { + const auto c = handshake_case("verified"); + const auto a_dtls = dtls_of(str(c["initiator"]["sdp_local"])); + const auto b_dtls = dtls_of(str(c["responder"]["sdp_local"])); + auto* memory = std::pmr::get_default_resource(); + auto claims = claims_of(message_of(c, 1)); + const auto accepted = [&](std::string_view nonce) { + claims.nonce = nonce; + return tp::read_handshake_step(tp::write_handshake_step(claims, memory), 1, a_dtls, b_dtls, + memory) + .claims.has_value(); + }; + for (const std::uint8_t fill : std::to_array({0x00, 0x5a, 0xff})) { + std::array random{}; + random.fill(fill); + const auto uuid = tp::uuid_v4(random); + BOOST_TEST_GE(uuid.size(), tp::min_nonce_units); + BOOST_TEST(accepted(std::string_view(uuid.data(), uuid.size()))); + } + // Counted in UTF-16 code units, as `n.length`: 15 accented letters are 30 bytes but 15 units; + // 8 emoji are 16 units. + std::string accented; + std::string emoji; + for (int i = 0; i < 15; ++i) { + accented += "\xc3\xa9"; + } + for (int i = 0; i < 8; ++i) { + emoji += "\xf0\x9f\x98\x80"; + } + BOOST_TEST(!accepted(accented)); + BOOST_TEST(accepted(accented + "x")); + BOOST_TEST(accepted(emoji)); + BOOST_TEST(!accepted(std::string(15, 'x'))); + BOOST_TEST(accepted(std::string(16, 'x'))); +} + +/** A failed start: the run reports `dtls_missing` when a description has no fingerprint. */ +void a_run_without_fingerprints_fails_at_its_start() { + const auto c = handshake_case("verified"); + for (const std::string_view role : {"initiator", "responder"}) { + for (const bool local : {true, false}) { + auto side = side_of(c, role); + (local ? side->local_dtls : side->remote_dtls).clear(); + side->machine.emplace( + trystero::detail::local_identity{ + .endpoint = side->endpoint.key, + .peer_id = side->endpoint.peer_id, + .endpoint_key = side->endpoint.compact, + .user = side->user, + }, + side->cache, str(c["app"]), str(c["room"]), + str(c[role == "initiator" ? "responder" : "initiator"]["peer_id"]), + role == "initiator", side->local_dtls, side->remote_dtls, + std::array{}, std::pmr::get_default_resource()); + const auto started = side->machine->start(); + BOOST_TEST_EQ(started.failure, tp::handshake_reason::dtls_missing); + BOOST_TEST(started.send.empty()); + // A failed run takes nothing more. + const auto after = side->machine->receive(message_of(c, role == "initiator" ? 2 : 1)); + BOOST_TEST(after.send.empty() && !after.done && after.failure.empty()); + } + } +} + +} // namespace + +int main(int argc, char* argv[]) { + if (!BOOST_TEST_EQ(argc, 2)) { + BOOST_LIGHTWEIGHT_TEST_OSTREAM + << "usage: crypto_layer_test \n"; + return boost::report_errors(); + } + auto loaded = load(argv[1]); + if (!BOOST_TEST(loaded.has_value())) { + return boost::report_errors(); + } + fixture_document().emplace(std::move(*loaded)); + webcpp::test::run_case(fixture_is_trystero_0_27_0); + webcpp::test::run_case(base64url_matches); + webcpp::test::run_case(base64url_is_strict); + webcpp::test::run_case(topic_path_matches); + webcpp::test::run_case(the_total_string_writer_is_json_stringifys); + webcpp::test::run_case(hash_topic_matches); + webcpp::test::run_case(room_topics_match); + webcpp::test::run_case(hash32_matches); + webcpp::test::run_case(str_to_num_matches); + webcpp::test::run_case(topic_kind_matches); + webcpp::test::run_case(domain_tags_match); + webcpp::test::run_case(shuffle_matches); + webcpp::test::run_case(gen_id_matches); + webcpp::test::run_case(identity_ids_match); + webcpp::test::run_case(uuid_v4_has_its_form); + webcpp::test::run_case(compact_key_is_strict); + webcpp::test::run_case(room_key_without_password_matches); + webcpp::test::run_case(room_keys_from_master_match); +#ifdef WEBCPP_TRYSTERO_TEST_SLOW_KDF + webcpp::test::run_case(pbkdf2_master_matches); +#endif + webcpp::test::run_case(room_auth_matches); + webcpp::test::run_case(room_auth_token_is_strict); + webcpp::test::run_case(seal_matches); + webcpp::test::run_case(password_probe_opens); + webcpp::test::run_case(open_refuses_what_trystero_refuses); + webcpp::test::run_case(open_refuses_another_aad); + webcpp::test::run_case(open_refuses_a_plaintext_that_is_not_utf8); + webcpp::test::run_case(wipe_zeroes_what_it_is_given); + webcpp::test::run_case(signal_aad_matches); + webcpp::test::run_case(action_frames_match); + webcpp::test::run_case(handshake_frames_match); + webcpp::test::run_case(ping_frames_match); + webcpp::test::run_case(p256_keys_derive_their_ids); + webcpp::test::run_case(compact_keys_are_read_as_0_27_0_reads_them); + webcpp::test::run_case(user_identity_text_matches); + webcpp::test::run_case(user_identity_imports_match); + webcpp::test::run_case(user_key_buffers_are_wiped); + webcpp::test::run_case(user_key_text_is_read_as_0_27_0_reads_it); + webcpp::test::run_case(user_proof_matches); + webcpp::test::run_case(low_s_matches); + webcpp::test::run_case(cpp_signatures_are_deterministic_and_low_s); + webcpp::test::run_case(identities_sign_as_their_keys); + webcpp::test::run_case(scalars_are_checked_against_the_order); + webcpp::test::run_case(dtls_fingerprints_match); + webcpp::test::run_case(handshake_steps_match); + webcpp::test::run_case(handshake_steps_are_read_as_0_27_0_reads_them); + webcpp::test::run_case(handshake_transcript_matches); + webcpp::test::run_case(js_handshake_signatures_verify); + webcpp::test::run_case(cpp_responder_meets_the_js_initiator); + webcpp::test::run_case(cpp_initiator_meets_the_js_responder); + webcpp::test::run_case(signatures_of_another_transcript_are_refused); + webcpp::test::run_case(handshake_failures_match); + webcpp::test::run_case(uuid_nonces_have_16_units_or_more); + webcpp::test::run_case(a_run_without_fingerprints_fails_at_its_start); + return boost::report_errors(); +} diff --git a/test/fixtures/cases/protocol.json b/test/fixtures/cases/protocol.json index 4c3ccf9..99b965c 100644 --- a/test/fixtures/cases/protocol.json +++ b/test/fixtures/cases/protocol.json @@ -1,23 +1,7 @@ { - "topics": [ - ["trystero-cpp-probe", "lobby", "00000000000000000000"], - ["my-app", "room-1", "zzzzzzzzzzzzzzzzzzzz"], - ["café ☕ app", "sala ünïcode 🎉", "AbCdEfGhIjKlMnOpQrSt"], - ["a", "b", "c"] - ], - "str_to_num": ["", "a", "trystero-cpp-probe", "café ☕", "🎉🎉", "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v"], - "relays": ["trystero-cpp-probe", "my-app", "café ☕ app", "x", "a-much-longer-application-identifier-for-testing"], - "relay_redundancy": 5, - "shuffle": {"seeds": [0, 1, 1234567, 9007199254740991], "length": 29}, - "handshake": [["ch4ll3ng3", "secret", "my-app", "room-1"], ["x", "", "a", "b"]], - "sealed": { - "password": "secret", + "nostr_events": { "app_id": "my-app", "room_id": "room-1", - "plaintext": "v=0\r\no=- 4611731400430051336 2 IN IP4 127.0.0.1\r\n", - "random": {"multiplier": 17, "offset": 3} - }, - "nostr_events": { "pubkey": "4f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa", "created_at": 1759700000, "contents": [ @@ -26,97 +10,277 @@ "" ] }, - "actions": { - "text": ["chat", "hello from Trystero JS"], - "json": ["drink", {"drink": "negroni", "withIce": true, "n": [1, 2.5, null]}], - "binary": ["pic", [0, 1, 2, 253, 254, 255]], - "text_with_metadata": ["chat", "hi", {"from": "js", "n": 7}], - "empty_text": ["@_hsready", ""], - "thirty_two_byte_name": ["abcdefghijklmnopqrstuvwxyz012345", "x"], - "chunked": {"type": "file", "length": 40000, "multiplier": 7, "metadata": {"name": "big.bin"}} - }, - "controls": {"max_receive_bytes": 30000}, - "envelope": {"app_id": "my-app", "room_id": "room-1", "frame": [2, 0, 99, 104, 97, 116], "timeout": 60000}, "event_messages": { - "random": {"multiplier": 29, "offset": 11}, + "random": { + "multiplier": 29, + "offset": 11 + }, "created_at": 1759700000, "events": [ - ["585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f"], - ["585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", "quote \" backslash \\ both \\\" solidus / space tilde ~"], - ["585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", "line separator 
 paragraph separator 
 delete \u007f"], - ["585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", "astral 🎉 𝄞, two bytes é \u0080 ߿, three ☕ ࠀ ￿"], - ["topic \u0000 \u001f \" \\ 
 
 \u007f 🎉", "{\"peerId\":\"abc\",\"nonce\":\"12345678\"}"], - ["", ""] + [ + "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", + "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f" + ], + [ + "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", + "quote \" backslash \\ both \\\" solidus / space tilde ~" + ], + [ + "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", + "line separator 
 paragraph separator 
 delete " + ], + [ + "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", + "astral 🎉 𝄞, two bytes é € ߿, three ☕ ࠀ ￿" + ], + [ + "topic \u0000 \u001f \" \\ 
 
  🎉", + "{\"peerId\":\"abc\",\"nonce\":\"12345678\"}" + ], + [ + "", + "" + ] ] }, "signal_texts": [ - {"peerId": "\u0000\u0001\u001f", "nonce": "\" \\ 
 
 \u007f 🎉"}, - {"peerId": "\b\f\n\r\t\u000b", "passive": true, "nonce": "n0nce"}, - {"peerId": "p", "offerId": "
\u007f", "offer": "🎉\u0000𝄞 é"}, - {"peerId": "p", "offerId": "o", "candidate": "\u001f \u007f \u0080 \"\\", "passive": true}, - {"peerId": "q\"\\\n", "answer": "
\u0000"}, - {"peerId": "a", "answer": "sealed \u007f", "offerId": "o"}, - {"peerId": "a", "candidate": "\u2028\u2029", "offerId": "o", "passive": true} + { + "peerId": "\u0000\u0001\u001f", + "nonce": "\" \\ 
 
  🎉" + }, + { + "peerId": "\b\f\n\r\t\u000b", + "nonce": "n0nce" + }, + { + "peerId": "peerAAAAAAAAAAAAAAAA", + "offerId": "o", + "offer": "🎉\u0000𝄞 é" + }, + { + "peerId": "peerAAAAAAAAAAAAAAAA", + "offerId": "o", + "candidate": "\u001f  € \"\\" + }, + { + "peerId": "q\"\\\n", + "offerId": "o", + "answer": "
\u0000" + }, + { + "peerId": "peerBBBBBBBBBBBBBBBB", + "offerId": "o", + "answer": "sealed " + }, + { + "peerId": "peerBBBBBBBBBBBBBBBB", + "offerId": "o", + "candidate": "

" + } ], "duplicate_keys": { + "app_id": "my-app", + "room_id": "room-1", + "self_id": "oracleSelf0000000000", "signals": [ - "{\"peerId\":\"first\",\"peerId\":\"last\",\"nonce\":\"n\"}", - "{\"peerId\":\"plain\",\"peer\\u0049d\":\"escaped\"}", - "{\"peerId\":\"p\",\"offerId\":\"first\",\"offer\":\"first\",\"offerId\":\"last\",\"offer\":\"last\"}", - "{\"peerId\":\"p\",\"offer\":\"\",\"offer\":\"sealed\"}", - "{\"peerId\":\"p\",\"offer\":\"sealed\",\"offer\":\"\"}", - "{\"peerId\":\"p\",\"candidate\":1,\"candidate\":\"sealed\"}", - "{\"peerId\":\"p\",\"answer\":\"sealed\",\"answer\":null}", - "{\"peerId\":\"p\",\"passive\":true,\"passive\":false}", - "{\"peerId\":\"p\",\"passive\":false,\"passive\":true}", - "{\"peerId\":\"p\",\"peerId\":\"\"}", - "{\"peerId\":\"\",\"answer\":\"sealed\",\"peerId\":\"p\"}", - "{\"peerId\":\"p\",\"peer\":\"x\",\"offer\":\"sealed\"}", - "{\"peerId\":\"p\",\"peer\":null,\"nonce\":\"n\"}" + "{\"peerId\":\"peerBBBBBBBBBBBBBBBB\",\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"nonce\":\"n\"}", + "{\"peerId\":\"peerBBBBBBBBBBBBBBBB\",\"peer\\u0049d\":\"peerAAAAAAAAAAAAAAAA\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"first\",\"offer\":\"first\",\"offerId\":\"last\",\"offer\":\"last\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"offer\":\"\",\"offer\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"offer\":\"sealed\",\"offer\":\"\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"candidate\":1,\"candidate\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"answer\":\"sealed\",\"answer\":null}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"not an id\",\"offerId\":\"o\",\"answer\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"nonce\":\"a\",\"nonce\":\"b\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"peerId\":\"\"}", + "{\"peerId\":\"\",\"offerId\":\"o\",\"answer\":\"sealed\",\"peerId\":\"peerAAAAAAAAAAAAAAAA\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"peer\":\"x\",\"offerId\":\"o\",\"offer\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"peer\":null,\"nonce\":\"n\"}" ], "events": { "app_id": "my-app", "room_id": "room-1", + "closing_prefix": "oracleClosing", + "offer_id": "o", "texts": [ [ - ["tags", [["x", "{root}"]]], - ["content", "{\"peerId\":\"content-first\",\"answer\":\"x\"}"], - ["content", "{\"peerId\":\"content-last\",\"answer\":\"x\"}"] + [ + "tags", + [ + [ + "x", + "{root}" + ] + ] + ], + [ + "content", + "{\"peerId\":\"contentFirst00000000\",\"offerId\":\"o\",\"answer\":\"x\"}" + ], + [ + "content", + "{\"peerId\":\"contentLast000000000\",\"offerId\":\"o\",\"answer\":\"x\"}" + ] ], [ - ["tags", [["x", "{root}"]]], - ["content", "{\"peerId\":\"escaped-first\",\"answer\":\"x\"}"], - ["con\\u0074ent", "{\"peerId\":\"escaped-last\",\"answer\":\"x\"}"] + [ + "tags", + [ + [ + "x", + "{root}" + ] + ] + ], + [ + "content", + "{\"peerId\":\"escapedFirst00000000\",\"offerId\":\"o\",\"answer\":\"x\"}" + ], + [ + "con\\u0074ent", + "{\"peerId\":\"escapedLast000000000\",\"offerId\":\"o\",\"answer\":\"x\"}" + ] ], [ - ["tags", [["x", "another-topic"]]], - ["content", "{\"peerId\":\"root-tags-last\",\"answer\":\"x\"}"], - ["tags", [["x", "{root}"]]] + [ + "tags", + [ + [ + "x", + "another-topic" + ] + ] + ], + [ + "content", + "{\"peerId\":\"rootTagsLast00000000\",\"offerId\":\"o\",\"answer\":\"x\"}" + ], + [ + "tags", + [ + [ + "x", + "{root}" + ] + ] + ] ], [ - ["tags", [["x", "{root}"]]], - ["content", "{\"peerId\":\"root-tags-first\",\"answer\":\"x\"}"], - ["tags", [["x", "another-topic"]]] + [ + "tags", + [ + [ + "x", + "{root}" + ] + ] + ], + [ + "content", + "{\"peerId\":\"rootTagsFirst0000000\",\"offerId\":\"o\",\"answer\":\"x\"}" + ], + [ + "tags", + [ + [ + "x", + "another-topic" + ] + ] + ] ], [ - ["tags", [["x", "{root}"]]], - ["content", 7], - ["content", "{\"peerId\":\"text-content-last\",\"answer\":\"x\"}"] + [ + "tags", + [ + [ + "x", + "{root}" + ] + ] + ], + [ + "content", + 7 + ], + [ + "content", + "{\"peerId\":\"textContentLast00000\",\"offerId\":\"o\",\"answer\":\"x\"}" + ] ], [ - ["tags", [["x", "{root}"]]], - ["content", "{\"peerId\":\"text-content-first\",\"answer\":\"x\"}"], - ["content", 7] + [ + "tags", + [ + [ + "x", + "{root}" + ] + ] + ], + [ + "content", + "{\"peerId\":\"textContentFirst0000\",\"offerId\":\"o\",\"answer\":\"x\"}" + ], + [ + "content", + 7 + ] ] ] } }, + "signal_envelopes": { + "app_id": "my-app", + "room_id": "room-1", + "self_id": "oracleSelf0000000000", + "signals": [ + "{\"peerId\":\"peerAAAAAAAAAAAAAAA\",\"nonce\":\"n\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAAA\",\"nonce\":\"n\"}", + "{\"peerId\":\"pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp\",\"nonce\":\"n\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAA-\",\"nonce\":\"n\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAé\",\"nonce\":\"n\"}", + "{\"peerId\":5,\"nonce\":\"n\"}", + "{\"peerId\":null,\"nonce\":\"n\"}", + "{\"offerId\":\"o\",\"answer\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"not an id\",\"answer\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\",\"answer\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"\",\"answer\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":5,\"answer\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":null,\"answer\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"oé\",\"answer\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offer\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"answer\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"candidate\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"\",\"nonce\":\"n\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":5,\"nonce\":\"n\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"candidate\":\"ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"candidate\":\"😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀c\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\",\"answer\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"a_.~:!-Z9\",\"answer\":\"sealed\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"candidate\":\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"candidate\":\"😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀\"}", + "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"nonce\":\"n\"}" + ], + "events": [ + "{\"peerId\":\"envShort00000000000\",\"offerId\":\"o\",\"answer\":\"x\"}", + "{\"peerId\":\"envNotAscii00000000é\",\"offerId\":\"o\",\"answer\":\"x\"}", + "{\"peerId\":\"envSpace000000000000\",\"offerId\":\"not an id\",\"answer\":\"x\"}", + "{\"peerId\":\"envLong0000000000000\",\"offerId\":\"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\",\"answer\":\"x\"}", + "{\"peerId\":\"envNumber00000000000\",\"offerId\":5,\"answer\":\"x\"}", + "{\"peerId\":\"envMissing0000000000\",\"answer\":\"x\"}", + "{\"peerId\":\"envLongest0000000000\",\"offerId\":\"oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\",\"answer\":\"x\"}", + "{\"peerId\":\"envChars000000000000\",\"offerId\":\"a_.~:!-Z9\",\"answer\":\"x\"}" + ] + }, "answerer": { "app_id": "my-app", "room_id": "room-1", - "password": "secret", - "self_id_random": {"multiplier": 23, "offset": 5}, - "random": {"multiplier": 31, "offset": 7}, + "self_id": "5JuBmYeQ3ItAlXdP1Hs8", + "random": { + "multiplier": 31, + "offset": 7 + }, "offer_sdp": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=offer\r\n", "answer_sdp": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\ns=answer\r\n", "candidate": { @@ -126,8 +290,14 @@ "usernameFragment": "uf" }, "offers": [ - {"peerId": "zzzzzzzzzzzzzzzzzzz1", "offerId": "o\"\\ 
 é"}, - {"peerId": "zzzzzzzzzzzzzzzzzzz2"} + { + "peerId": "zzzzzzzzzzzzzzzzzzz1", + "offerId": "o.~:!-_Az09" + }, + { + "peerId": "zzzzzzzzzzzzzzzzzzz2", + "offerId": "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" + } ] }, "payload_texts": [ diff --git a/test/fixtures/expected/expected.json b/test/fixtures/expected/expected.json deleted file mode 100644 index 9525ab0..0000000 --- a/test/fixtures/expected/expected.json +++ /dev/null @@ -1,666 +0,0 @@ -{ - "topics": [ - { - "app_id": "trystero-cpp-probe", - "room_id": "lobby", - "peer_id": "00000000000000000000", - "root_topic": "2t3c266f57311q4o1j4w3j6o611y1m1u4d6st6b", - "self_topic": "2i443c4a4z2u3a2k3o3qg4b454i1r2x4d283624", - "room_token": "51973cfa31a2d9d4d518716a1c7c9607b9ea8a950ac81960c5b50c6e8a3deeac" - }, - { - "app_id": "my-app", - "room_id": "room-1", - "peer_id": "zzzzzzzzzzzzzzzzzzzz", - "root_topic": "731p275e6u4l455l3849481dl46536q3g1r6h5y", - "self_topic": "4i5p4v3i2d3s5p6t196qp3o3yf4h1v33z605s", - "room_token": "2e4f09c7740641f4d3233ddd1ee0cd54aba1e7fdc69e8b3e2ddfcded88bacd3d" - }, - { - "app_id": "café ☕ app", - "room_id": "sala ünïcode 🎉", - "peer_id": "AbCdEfGhIjKlMnOpQrSt", - "root_topic": "17143jw612606z6w1zw1l5g6z6k5f5e601qy", - "self_topic": "371n1i5ei5x1a4gg161v3r7565p2r6a1v4g1k", - "room_token": "fc05f72d7a821209b4f5cbb492b5857a069978603eb8bf3c98f71c53161c90da" - }, - { - "app_id": "a", - "room_id": "b", - "peer_id": "c", - "root_topic": "692z14e6i1l6g2k1t442a2u5t5b6k1e3z2n4f1a", - "self_topic": "213n4w56d3v5x45645o45kh4xh6b5n11675p", - "room_token": "133a13e5333baccf0a9f808d87277878556e4dacc242aeb67295a5e78d6477e8" - } - ], - "str_to_num": [ - { - "text": "", - "unbounded": 0, - "mod_10000": 0 - }, - { - "text": "a", - "unbounded": 97, - "mod_10000": 97 - }, - { - "text": "trystero-cpp-probe", - "unbounded": 1857, - "mod_10000": 1857 - }, - { - "text": "café ☕", - "unbounded": 10312, - "mod_10000": 312 - }, - { - "text": "🎉🎉", - "unbounded": 225162, - "mod_10000": 5162 - }, - { - "text": "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", - "unbounded": 2890, - "mod_10000": 2890 - } - ], - "default_relays": [ - "wss://0x-nostr-relay.fly.dev", - "wss://bendernostur.duckdns.org:8443", - "wss://cdn.satellite.earth", - "wss://nos.lol", - "wss://nostr.chaima.info", - "wss://nostr.christiansass.de", - "wss://nostr.rblb.it", - "wss://nostr.red5d.dev", - "wss://nostr.robosats.org", - "wss://nostr.stakey.net", - "wss://nostrcity-club.fly.dev", - "wss://relay-dev.gulugulu.moe", - "wss://relay.aarpia.com", - "wss://relay.agentry.com", - "wss://relay.bitmacro.cloud", - "wss://relay.bullishbounty.com", - "wss://relay.degmods.com", - "wss://relay.flashapp.me", - "wss://relay.grigic.org", - "wss://relay.hackshed.dev", - "wss://relay.kaleidoswap.com", - "wss://relay.layer.systems", - "wss://relay.nostr.blockhenge.com", - "wss://relay.nostr.dev.br", - "wss://relay.nostrmap.net", - "wss://relay.novospes.com", - "wss://relay.piazza.today", - "wss://relay.routstr.com", - "wss://testr.nymble.world" - ], - "relays": [ - { - "app_id": "trystero-cpp-probe", - "relays": [ - "wss://testr.nymble.world", - "wss://nostr.stakey.net", - "wss://relay.grigic.org", - "wss://relay.nostr.dev.br", - "wss://bendernostur.duckdns.org:8443" - ] - }, - { - "app_id": "my-app", - "relays": [ - "wss://nostr.red5d.dev", - "wss://relay.nostrmap.net", - "wss://relay.piazza.today", - "wss://relay.bitmacro.cloud", - "wss://relay.nostr.dev.br" - ] - }, - { - "app_id": "café ☕ app", - "relays": [ - "wss://nostr.chaima.info", - "wss://nostr.rblb.it", - "wss://relay.novospes.com", - "wss://relay.nostrmap.net", - "wss://relay.bullishbounty.com" - ] - }, - { - "app_id": "x", - "relays": [ - "wss://relay.routstr.com", - "wss://relay.layer.systems", - "wss://cdn.satellite.earth", - "wss://bendernostur.duckdns.org:8443", - "wss://relay.nostr.blockhenge.com" - ] - }, - { - "app_id": "a-much-longer-application-identifier-for-testing", - "relays": [ - "wss://relay.bullishbounty.com", - "wss://relay.degmods.com", - "wss://relay.layer.systems", - "wss://nostr.christiansass.de", - "wss://relay.kaleidoswap.com" - ] - } - ], - "shuffle": [ - { - "seed": 0, - "order": [ - 11, - 2, - 6, - 25, - 15, - 9, - 21, - 8, - 16, - 7, - 23, - 28, - 13, - 20, - 17, - 10, - 4, - 1, - 14, - 3, - 12, - 22, - 27, - 18, - 24, - 5, - 26, - 19, - 0 - ] - }, - { - "seed": 1, - "order": [ - 6, - 21, - 7, - 9, - 2, - 16, - 10, - 23, - 26, - 17, - 8, - 22, - 0, - 14, - 13, - 24, - 11, - 4, - 1, - 15, - 3, - 12, - 19, - 28, - 18, - 25, - 5, - 27, - 20 - ] - }, - { - "seed": 1234567, - "order": [ - 16, - 14, - 22, - 3, - 17, - 1, - 18, - 27, - 11, - 6, - 25, - 19, - 10, - 9, - 28, - 8, - 2, - 4, - 0, - 26, - 23, - 13, - 24, - 12, - 7, - 21, - 20, - 5, - 15 - ] - }, - { - "seed": 9007199254740991, - "order": [ - 0, - 1, - 22, - 2, - 3, - 4, - 21, - 5, - 6, - 7, - 24, - 8, - 9, - 10, - 27, - 11, - 12, - 13, - 25, - 28, - 15, - 16, - 23, - 17, - 18, - 26, - 19, - 20, - 14 - ] - } - ], - "handshake": [ - { - "challenge": "ch4ll3ng3", - "password": "secret", - "app_id": "my-app", - "room_id": "room-1", - "hash": "3eb149e6ff08bcbab230d022e4ff330dbfa7df9fcac6c378695fee988587e579" - }, - { - "challenge": "x", - "password": "", - "app_id": "a", - "room_id": "b", - "hash": "fccc86c33cc191182c6e4a032153814c58a4864256ca5bf60a024e013c40f8c8" - } - ], - "sealed": { - "plaintext": "v=0\r\no=- 4611731400430051336 2 IN IP4 127.0.0.1\r\n", - "text": "3,20,37,54,71,88,105,122,139,156,173,190,207,224,241,2$ZtkZKcLsGfFd/0pp36cUJzLpIzV1VmUSSVJx8q0QBlJDrnUySIas/ifQDiq8+UqNj6dm1CMiqIxicYa1+fdkfVE=", - "key_material": "a11095bfc9cdd863704127af9c923044169c2784ed35e2ca808601f62878e886" - }, - "nostr_events": [ - { - "pubkey": "4f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa", - "created_at": 1759700000, - "kind": 22943, - "topic": "2t3c266f57311q4o1j4w3j6o611y1m1u4d6st6b", - "content": "{\"peerId\":\"abc\",\"nonce\":\"12345678\"}", - "id": "37f4a4dff48b6313b6821bc0a11811b40cdca11e2de6630578de1299250f483b" - }, - { - "pubkey": "4f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa", - "created_at": 1759700000, - "kind": 22943, - "topic": "2t3c266f57311q4o1j4w3j6o611y1m1u4d6st6b", - "content": "quote \" backslash \\ newline \n tab \t unicode é ☕ 🎉 control \u0001", - "id": "26aaafd65aeca7fe5aef126e26163272369df74c1c809d6cda32731470425f36" - }, - { - "pubkey": "4f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa", - "created_at": 1759700000, - "kind": 22943, - "topic": "2t3c266f57311q4o1j4w3j6o611y1m1u4d6st6b", - "content": "", - "id": "3e13e2102ab2a0bae6d1cdd37c2a8f28f60791d40fc45d644bdedac9a27fb08e" - } - ], - "actions": { - "text": [ - "02006368617400000000000000000000000000000000000000000000000000000000000068656c6c6f2066726f6d20547279737465726f204a53" - ], - "json": [ - "02106472696e6b00000000000000000000000000000000000000000000000000000000007b226472696e6b223a226e6567726f6e69222c2277697468496365223a747275652c226e223a5b312c322e352c6e756c6c5d7d" - ], - "binary": [ - "022070696300000000000000000000000000000000000000000000000000000000000000000102fdfeff" - ], - "text_with_metadata": [ - "0200636861740000000000000000000000000000000000000000000000000000000000137b2266726f6d223a226a73222c226e223a377d6869" - ], - "empty_text": [ - "0200405f6873726561647900000000000000000000000000000000000000000000000000" - ], - "thirty_two_byte_name": [ - "02006162636465666768696a6b6c6d6e6f707172737475767778797a303132333435000078" - ], - "chunked": { - "payload": "00070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9", - "frames": [ - "022166696c650000000000000000000000000000000000000000000000000000000000120000000040e38800000000007b226e616d65223a226269672e62696e227d", - "020200000000000000000000000000070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b82899097", - "02020000000040cff900000000009ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e35", - "02020000000040dff900000000003c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9" - ] - } - }, - "controls": { - "rejected_too_large": "0204000000007061796c6f616420657863656564732072656365697665722073697a65206c696d6974" - }, - "envelope": { - "room_token": "2e4f09c7740641f4d3233ddd1ee0cd54aba1e7fdc69e8b3e2ddfcded88bacd3d", - "frames": [ - "0201004032653466303963373734303634316634643332333364646431656530636435346162613165376664633639653862336532646466636465643838626163643364", - "01004032653466303963373734303634316634643332333364646431656530636435346162613165376664633639653862336532646466636465643838626163643364020063686174", - "0200004032653466303963373734303634316634643332333364646431656530636435346162613165376664633639653862336532646466636465643838626163643364" - ] - }, - "event_messages": { - "secret_key": "ea25be8deb88b3e137d8e64800a8f1f323fdf2a5ec32e8d5f28fc5bafad693df", - "aux": "0b2845627f9cb9d6f3102d4a6784a1bedbf815324f6c89a6c3e0fd1a3754718e", - "created_at": 1759700000, - "events": [ - { - "topic": "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", - "content": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f", - "id": "1a1d25f95e3d191c5013f25147ae177218b97ace92b83429191abe55eb0c396b", - "message": "[\"EVENT\",{\"kind\":22890,\"tags\":[[\"x\",\"585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v\"]],\"created_at\":1759700000,\"content\":\"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"1a1d25f95e3d191c5013f25147ae177218b97ace92b83429191abe55eb0c396b\",\"sig\":\"f20743fac20bca48ec3d3e5545188fcf392cf719607a52e5ab4a42978d42036c68bafec56f1727484c1c2232c55ec170db5dab795edf776ed56cb2ec1ba09d9e\"}]" - }, - { - "topic": "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", - "content": "quote \" backslash \\ both \\\" solidus / space tilde ~", - "id": "5389620285f316864588a74ab8b06f8d7bf0cf6b3536ad8b0fb5e3bfb8b41bc6", - "message": "[\"EVENT\",{\"kind\":22890,\"tags\":[[\"x\",\"585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v\"]],\"created_at\":1759700000,\"content\":\"quote \\\" backslash \\\\ both \\\\\\\" solidus / space tilde ~\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"5389620285f316864588a74ab8b06f8d7bf0cf6b3536ad8b0fb5e3bfb8b41bc6\",\"sig\":\"b57c6506bbc141d819181a6af8c52820cd058ae1c3df78c8772f39d4ec7b56d86fa41521375fe3c8a9ced10dd7996c70a3483a8506a899884d4a8474d7792329\"}]" - }, - { - "topic": "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", - "content": "line separator 
 paragraph separator 
 delete ", - "id": "8cb08d994e6070975ebaa7b1448a76df8f11af1ea39d17ec7e0021fd4936ee17", - "message": "[\"EVENT\",{\"kind\":22890,\"tags\":[[\"x\",\"585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v\"]],\"created_at\":1759700000,\"content\":\"line separator 
 paragraph separator 
 delete \",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"8cb08d994e6070975ebaa7b1448a76df8f11af1ea39d17ec7e0021fd4936ee17\",\"sig\":\"76a457faff38f4daaa016a67185d71fa9cac213de3b474c442680d59e9e2b30bfb907cbbf92f7134e435836cd8f94f14b90efa0f1301316e54724b192ec4e9c5\"}]" - }, - { - "topic": "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", - "content": "astral 🎉 𝄞, two bytes é € ߿, three ☕ ࠀ ￿", - "id": "2d68203eac4a759e21079a3f4b4871d31e912ce44f2ad8ba8746d313ea9d7053", - "message": "[\"EVENT\",{\"kind\":22890,\"tags\":[[\"x\",\"585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v\"]],\"created_at\":1759700000,\"content\":\"astral 🎉 𝄞, two bytes é € ߿, three ☕ ࠀ ￿\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"2d68203eac4a759e21079a3f4b4871d31e912ce44f2ad8ba8746d313ea9d7053\",\"sig\":\"24ffe69b6129f4e4144f48c441df99fc578a021e73141d7b9452bd98234e0b56a0224399e80e344ab7642cf22c3467c0f1c20463667c7a32e803dc780ae0443c\"}]" - }, - { - "topic": "topic \u0000 \u001f \" \\ 
 
  🎉", - "content": "{\"peerId\":\"abc\",\"nonce\":\"12345678\"}", - "id": "23e556c7184e81b671731fa9f7c7a0d52ffcdf4c7a9c9ebbde4dd6fde2a5d115", - "message": "[\"EVENT\",{\"kind\":20129,\"tags\":[[\"x\",\"topic \\u0000 \\u001f \\\" \\\\ 
 
  🎉\"]],\"created_at\":1759700000,\"content\":\"{\\\"peerId\\\":\\\"abc\\\",\\\"nonce\\\":\\\"12345678\\\"}\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"23e556c7184e81b671731fa9f7c7a0d52ffcdf4c7a9c9ebbde4dd6fde2a5d115\",\"sig\":\"3c9df43a7063d0e2f5cc1d6feec3cd2dad55f1e3c56073cf884ca1aa57c23b312b27d7a970bea57e746d507d3407b381f7c000655c27e8c111803c952030f924\"}]" - }, - { - "topic": "", - "content": "", - "id": "cff4dd0852bd9746a0b233a890ae9e67db1559f3bd0744d74f5fc2ee0ff50e02", - "message": "[\"EVENT\",{\"kind\":20000,\"tags\":[[\"x\",\"\"]],\"created_at\":1759700000,\"content\":\"\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"cff4dd0852bd9746a0b233a890ae9e67db1559f3bd0744d74f5fc2ee0ff50e02\",\"sig\":\"f99498986e5f1779cd7c8762f3719517193528e511f292db4b7a6feefb0ed6601c2f972c262f6f1a58288982688002861828c4e350b693aa4290186fd16daef3\"}]" - } - ] - }, - "signal_texts": [ - { - "signal": { - "peerId": "\u0000\u0001\u001f", - "nonce": "\" \\ 
 
  🎉" - }, - "text": "{\"peerId\":\"\\u0000\\u0001\\u001f\",\"nonce\":\"\\\" \\\\ 
 
  🎉\"}" - }, - { - "signal": { - "peerId": "\b\f\n\r\t\u000b", - "passive": true, - "nonce": "n0nce" - }, - "text": "{\"peerId\":\"\\b\\f\\n\\r\\t\\u000b\",\"passive\":true,\"nonce\":\"n0nce\"}" - }, - { - "signal": { - "peerId": "p", - "offerId": "
", - "offer": "🎉\u0000𝄞 é" - }, - "text": "{\"peerId\":\"p\",\"offerId\":\"
\",\"offer\":\"🎉\\u0000𝄞 é\"}" - }, - { - "signal": { - "peerId": "p", - "offerId": "o", - "candidate": "\u001f  € \"\\", - "passive": true - }, - "text": "{\"peerId\":\"p\",\"offerId\":\"o\",\"candidate\":\"\\u001f  € \\\"\\\\\",\"passive\":true}" - }, - { - "signal": { - "peerId": "q\"\\\n", - "answer": "
\u0000" - }, - "text": "{\"peerId\":\"q\\\"\\\\\\n\",\"answer\":\"
\\u0000\"}" - }, - { - "signal": { - "peerId": "a", - "answer": "sealed ", - "offerId": "o" - }, - "text": "{\"peerId\":\"a\",\"answer\":\"sealed \",\"offerId\":\"o\"}" - }, - { - "signal": { - "peerId": "a", - "candidate": "

", - "offerId": "o", - "passive": true - }, - "text": "{\"peerId\":\"a\",\"candidate\":\"

\",\"offerId\":\"o\",\"passive\":true}" - } - ], - "duplicate_keys": { - "signals": [ - { - "text": "{\"peerId\":\"first\",\"peerId\":\"last\",\"nonce\":\"n\"}", - "read": { - "peer_id": "last", - "passive": false - } - }, - { - "text": "{\"peerId\":\"plain\",\"peer\\u0049d\":\"escaped\"}", - "read": { - "peer_id": "escaped", - "passive": false - } - }, - { - "text": "{\"peerId\":\"p\",\"offerId\":\"first\",\"offer\":\"first\",\"offerId\":\"last\",\"offer\":\"last\"}", - "read": { - "peer_id": "p", - "offer": "last", - "offer_id": "last", - "passive": false - } - }, - { - "text": "{\"peerId\":\"p\",\"offer\":\"\",\"offer\":\"sealed\"}", - "read": { - "peer_id": "p", - "offer": "sealed", - "passive": false - } - }, - { - "text": "{\"peerId\":\"p\",\"offer\":\"sealed\",\"offer\":\"\"}", - "read": null - }, - { - "text": "{\"peerId\":\"p\",\"candidate\":1,\"candidate\":\"sealed\"}", - "read": { - "peer_id": "p", - "candidate": "sealed", - "passive": false - } - }, - { - "text": "{\"peerId\":\"p\",\"answer\":\"sealed\",\"answer\":null}", - "read": null - }, - { - "text": "{\"peerId\":\"p\",\"passive\":true,\"passive\":false}", - "read": { - "peer_id": "p", - "passive": false - } - }, - { - "text": "{\"peerId\":\"p\",\"passive\":false,\"passive\":true}", - "read": { - "peer_id": "p", - "passive": true - } - }, - { - "text": "{\"peerId\":\"p\",\"peerId\":\"\"}", - "read": null - }, - { - "text": "{\"peerId\":\"\",\"answer\":\"sealed\",\"peerId\":\"p\"}", - "read": { - "peer_id": "p", - "answer": "sealed", - "passive": false - } - }, - { - "text": "{\"peerId\":\"p\",\"peer\":\"x\",\"offer\":\"sealed\"}", - "read": null - }, - { - "text": "{\"peerId\":\"p\",\"peer\":null,\"nonce\":\"n\"}", - "read": null - } - ], - "root_topic": "731p275e6u4l455l3849481dl46536q3g1r6h5y", - "events": [ - { - "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"731p275e6u4l455l3849481dl46536q3g1r6h5y\"]],\"content\":\"{\\\"peerId\\\":\\\"content-first\\\",\\\"answer\\\":\\\"x\\\"}\",\"content\":\"{\\\"peerId\\\":\\\"content-last\\\",\\\"answer\\\":\\\"x\\\"}\"}]", - "acted": "content-last" - }, - { - "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"731p275e6u4l455l3849481dl46536q3g1r6h5y\"]],\"content\":\"{\\\"peerId\\\":\\\"escaped-first\\\",\\\"answer\\\":\\\"x\\\"}\",\"con\\u0074ent\":\"{\\\"peerId\\\":\\\"escaped-last\\\",\\\"answer\\\":\\\"x\\\"}\"}]", - "acted": "escaped-last" - }, - { - "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"another-topic\"]],\"content\":\"{\\\"peerId\\\":\\\"root-tags-last\\\",\\\"answer\\\":\\\"x\\\"}\",\"tags\":[[\"x\",\"731p275e6u4l455l3849481dl46536q3g1r6h5y\"]]}]", - "acted": "root-tags-last" - }, - { - "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"731p275e6u4l455l3849481dl46536q3g1r6h5y\"]],\"content\":\"{\\\"peerId\\\":\\\"root-tags-first\\\",\\\"answer\\\":\\\"x\\\"}\",\"tags\":[[\"x\",\"another-topic\"]]}]", - "acted": null - }, - { - "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"731p275e6u4l455l3849481dl46536q3g1r6h5y\"]],\"content\":7,\"content\":\"{\\\"peerId\\\":\\\"text-content-last\\\",\\\"answer\\\":\\\"x\\\"}\"}]", - "acted": "text-content-last" - }, - { - "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"731p275e6u4l455l3849481dl46536q3g1r6h5y\"]],\"content\":\"{\\\"peerId\\\":\\\"text-content-first\\\",\\\"answer\\\":\\\"x\\\"}\",\"content\":7}]", - "acted": null - } - ] - }, - "answerer": { - "self_id": "5JuBmYeQ3ItAlXdP1Hs8", - "app_id": "my-app", - "room_id": "room-1", - "answer_sdp": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\ns=answer\r\n", - "candidate": "{\"candidate\":\"candidate:1 1 udp 2122260223 192.0.2.1 54400 typ host\",\"sdpMid\":\"0\",\"sdpMLineIndex\":0,\"usernameFragment\":\"uf\"}", - "sealed": [ - { - "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=offer\r\n", - "text": "7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$XccAwuMxbp5cYdiY235agss4Yz6zXoOPHcepm9bcphyewQqvfpvvs2gwPQJETj4gYc719bGYIKY=" - }, - { - "plaintext": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\ns=answer\r\n", - "text": "7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$XccAwuMxbp5cY9ie235agss4Yz6zXoOPHcepm9bcphyezwK6bIyQtMvVseJhAyE4HRH0kfRvD/5a" - }, - { - "plaintext": "{\"candidate\":\"candidate:1 1 udp 2122260223 192.0.2.1 54400 typ host\",\"sdpMid\":\"0\",\"sdpMLineIndex\":0,\"usernameFragment\":\"uf\"}", - "text": "7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$UNhTroc6OtcdJJ2IwRV3w+wMPnrjGNGbHMmolZK13E+Rn177Kd/Si/PNl4WOZYZxegGCVXXhJjfEgqGQo8VwP4iA3AS52+5RcDzVW8PyGn+zNeJwpRALn6lQTPLPLn8oYaes+TjSqjTGct1fs70+l7hPk8xZdRG0HBGROwxx2cUwNhUmqm1ywDYfDwM=" - } - ], - "cases": [ - { - "offer": "{\"peerId\":\"zzzzzzzzzzzzzzzzzzz1\",\"offerId\":\"o\\\"\\\\ 
 é\",\"offer\":\"7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$XccAwuMxbp5cYdiY235agss4Yz6zXoOPHcepm9bcphyewQqvfpvvs2gwPQJETj4gYc719bGYIKY=\"}", - "published": [ - { - "topic": "u1l2v1r6s2h4j64g721v372v194qs5g3w3b2y", - "text": "{\"peerId\":\"5JuBmYeQ3ItAlXdP1Hs8\",\"answer\":\"7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$XccAwuMxbp5cY9ie235agss4Yz6zXoOPHcepm9bcphyezwK6bIyQtMvVseJhAyE4HRH0kfRvD/5a\",\"offerId\":\"o\\\"\\\\ 
 é\"}" - }, - { - "topic": "u1l2v1r6s2h4j64g721v372v194qs5g3w3b2y", - "text": "{\"peerId\":\"5JuBmYeQ3ItAlXdP1Hs8\",\"candidate\":\"7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$UNhTroc6OtcdJJ2IwRV3w+wMPnrjGNGbHMmolZK13E+Rn177Kd/Si/PNl4WOZYZxegGCVXXhJjfEgqGQo8VwP4iA3AS52+5RcDzVW8PyGn+zNeJwpRALn6lQTPLPLn8oYaes+TjSqjTGct1fs70+l7hPk8xZdRG0HBGROwxx2cUwNhUmqm1ywDYfDwM=\",\"offerId\":\"o\\\"\\\\ 
 é\"}" - } - ] - }, - { - "offer": "{\"peerId\":\"zzzzzzzzzzzzzzzzzzz2\",\"offer\":\"7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$XccAwuMxbp5cYdiY235agss4Yz6zXoOPHcepm9bcphyewQqvfpvvs2gwPQJETj4gYc719bGYIKY=\"}", - "published": [ - { - "topic": "18705o161g2q2q714y46684f4710141d4x2y3n22", - "text": "{\"peerId\":\"5JuBmYeQ3ItAlXdP1Hs8\",\"answer\":\"7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$XccAwuMxbp5cY9ie235agss4Yz6zXoOPHcepm9bcphyezwK6bIyQtMvVseJhAyE4HRH0kfRvD/5a\"}" - }, - { - "topic": "18705o161g2q2q714y46684f4710141d4x2y3n22", - "text": "{\"peerId\":\"5JuBmYeQ3ItAlXdP1Hs8\",\"candidate\":\"7,38,69,100,131,162,193,224,255,30,61,92,123,154,185,216$UNhTroc6OtcdJJ2IwRV3w+wMPnrjGNGbHMmolZK13E+Rn177Kd/Si/PNl4WOZYZxegGCVXXhJjfEgqGQo8VwP4iA3AS52+5RcDzVW8PyGn+zNeJwpRALn6lQTPLPLn8oYaes+TjSqjTGct1fs70+l7hPk8xZdRG0HBGROwxx2cUwNhUmqm1ywDYfDwM=\"}" - } - ] - } - ] - }, - "payload_texts": [ - { - "text": "{\"b\":1,\"a\":2,\"10\":3,\"2\":4,\"-1\":5,\"01\":6,\"1.5\":7,\"4294967294\":8,\"4294967295\":9,\"0\":10}", - "written": "{\"0\":10,\"2\":4,\"10\":3,\"4294967294\":8,\"b\":1,\"a\":2,\"-1\":5,\"01\":6,\"1.5\":7,\"4294967295\":9}" - }, - { - "text": "{\"z\":{\"y\":[1,{\"3\":true,\"x\":null,\"1\":false}],\"0\":\"\"},\"a\":[]}", - "written": "{\"z\":{\"0\":\"\",\"y\":[1,{\"1\":false,\"3\":true,\"x\":null}]},\"a\":[]}" - }, - { - "text": "[0,-0,1,-1,100,1E3,1e+2,12e-1,0.1,1.5,123.45,0.30000000000000004,1e20,1e21,123e19,0.000001,1e-6,1e-7,2.5e-8]", - "written": "[0,0,1,-1,100,1000,100,1.2,0.1,1.5,123.45,0.30000000000000004,100000000000000000000,1e+21,1.23e+21,0.000001,0.000001,1e-7,2.5e-8]" - }, - { - "text": "[1.5e300,-1.5e-300,5e-324,1.7976931348623157e308,9007199254740991,-9007199254740991,4294967296]", - "written": "[1.5e+300,-1.5e-300,5e-324,1.7976931348623157e+308,9007199254740991,-9007199254740991,4294967296]" - }, - { - "text": "[\"\\u2028\\u0000\\u007f é 🎉\\\"\\\\/\",true,false,null,{}]", - "written": "[\"
\\u0000 é 🎉\\\"\\\\/\",true,false,null,{}]" - } - ], - "payload_beyond_doubles": [ - { - "text": "[9007199254740993,-9223372036854775808,0.1000000000000000055511151231257827,1e400]", - "written": "[9007199254740992,-9223372036854776000,0.1,null]" - } - ] -} diff --git a/test/fixtures/expected/trystero-0.27.0.json b/test/fixtures/expected/trystero-0.27.0.json new file mode 100644 index 0000000..4aff1be --- /dev/null +++ b/test/fixtures/expected/trystero-0.27.0.json @@ -0,0 +1,2080 @@ +{ + "trystero": "0.27.0", + "recorded_with": "node v26.13.0", + "domain_tags": [ + { + "name": "room-aes", + "version": 3, + "tag": "trystero:room-aes:v3" + }, + { + "name": "room-hmac", + "version": 3, + "tag": "trystero:room-hmac:v3" + }, + { + "name": "pbkdf2-master", + "version": 3, + "tag": "trystero:pbkdf2-master:v3" + }, + { + "name": "ov-auth", + "version": 3, + "tag": "trystero:ov-auth:v3" + }, + { + "name": "e2e-salt", + "version": 2, + "tag": "trystero:e2e-salt:v2" + }, + { + "name": "e2e-info", + "version": 2, + "tag": "trystero:e2e-info:v2" + }, + { + "name": "pid", + "version": 1, + "tag": "trystero:pid:v1" + }, + { + "name": "uid", + "version": 1, + "tag": "trystero:uid:v1" + }, + { + "name": "user-proof", + "version": 3, + "tag": "trystero:user-proof:v3" + }, + { + "name": "id-hs", + "version": 2, + "tag": "trystero:id-hs:v2" + }, + { + "name": "identity-self-test", + "version": 1, + "tag": "trystero:identity-self-test:v1" + } + ], + "hash_topic": [ + { + "text": "", + "topic": "47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU" + }, + { + "text": "lobby", + "topic": "S13Adue5wSKzyJEhqXEPxztJDUjh_zZhVXkZF15QVjM" + }, + { + "text": "Trystero", + "topic": "KLfz8SY4qeunN-XyEUfFRFEjynHbPWsxK2cGRSaalcE" + }, + { + "text": "[\"Trystero\",\"app\",\"room\"]", + "topic": "EPOSMWej0eSk-IKnPAPZOgCqRnomHYt9zEpqgHdxook" + }, + { + "text": "café 😀", + "topic": "BDdk33c6x87qYXXhSYiT5u4z55iFKIQXzB11y6YJSCc" + }, + { + "text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "topic": "qiDCPjIBg0BQZ54diJQbmm_tBVfJpwXLLDFeLmP9SG0" + } + ], + "topic_path": [ + { + "parts": [ + "Trystero", + "example.com/app", + "lobby" + ], + "path": "[\"Trystero\",\"example.com/app\",\"lobby\"]" + }, + { + "parts": [ + "Trystero", + "a\"b\\c", + "café" + ], + "path": "[\"Trystero\",\"a\\\"b\\\\c\",\"café\"]" + }, + { + "parts": [ + "[\"Trystero\",\"app\",\"room\"]", + "peer0123456789abcdef" + ], + "path": "[\"[\\\"Trystero\\\",\\\"app\\\",\\\"room\\\"]\",\"peer0123456789abcdef\"]" + } + ], + "room_topics": [ + { + "app": "example.com/app", + "room": "lobby", + "peer_id": "T5sdTwb84yyey80e4qjv", + "root_text": "[\"Trystero\",\"example.com/app\",\"lobby\"]", + "root_topic": "Ez_9ACs-onxWTTRRn7pFD2rqRce5y0HrAay9k2X7Ip0", + "peer_text": "[\"[\\\"Trystero\\\",\\\"example.com/app\\\",\\\"lobby\\\"]\",\"T5sdTwb84yyey80e4qjv\"]", + "peer_topic": "j0YMUkrR_ecDTTcdbXvJV9GW8StO2JaSN1Do2CyT75w", + "root_kind": 26501 + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "peer_id": "AbCdEfGhIjKlMnOpQrSt", + "root_text": "[\"Trystero\",\"webcpp-trystero-quick-start\",\"café\"]", + "root_topic": "SpLDMeLr8p_xce0guAVzHESuo1H9xb1FiYJ5i31PwIU", + "peer_text": "[\"[\\\"Trystero\\\",\\\"webcpp-trystero-quick-start\\\",\\\"café\\\"]\",\"AbCdEfGhIjKlMnOpQrSt\"]", + "peer_topic": "dT5cAPs12Eo2XtHySSAvPbypWnlE8AI4MHdOPWU4H1I", + "root_kind": 26084 + } + ], + "base64url": [ + { + "bytes": "", + "text": "" + }, + { + "bytes": "00", + "text": "AA" + }, + { + "bytes": "fffe", + "text": "__4" + }, + { + "bytes": "010203", + "text": "AQID" + }, + { + "bytes": "fbffbf", + "text": "-_-_" + }, + { + "bytes": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20", + "text": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8g" + } + ], + "hash32": [ + { + "text": "", + "value": 2872998923 + }, + { + "text": "lobby", + "value": 1937637236 + }, + { + "text": "Trystero", + "value": 2975451718 + }, + { + "text": "[\"Trystero\",\"app\",\"room\"]", + "value": 777894491 + }, + { + "text": "café 😀", + "value": 622887659 + }, + { + "text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "value": 3644158961 + } + ], + "str_to_num": [ + { + "text": "", + "limit": 10000, + "value": 8923 + }, + { + "text": "lobby", + "limit": 10000, + "value": 7236 + }, + { + "text": "Trystero", + "limit": 10000, + "value": 1718 + }, + { + "text": "[\"Trystero\",\"app\",\"room\"]", + "limit": 10000, + "value": 4491 + }, + { + "text": "café 😀", + "limit": 10000, + "value": 7659 + }, + { + "text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "limit": 10000, + "value": 8961 + } + ], + "shuffle": [ + { + "app": "example.com/app", + "seed": 3213600185, + "order": [ + 24, + 4, + 9, + 29, + 12, + 3, + 11, + 17, + 2, + 13, + 10, + 0, + 27, + 1, + 15, + 6, + 22, + 23, + 21, + 14, + 16, + 8, + 5, + 19, + 7, + 28, + 26, + 20, + 25, + 18 + ] + }, + { + "app": "webcpp-trystero-quick-start", + "seed": 507786972, + "order": [ + 6, + 24, + 18, + 12, + 11, + 10, + 9, + 7, + 4, + 28, + 22, + 14, + 8, + 0, + 5, + 19, + 20, + 29, + 2, + 16, + 13, + 26, + 27, + 23, + 1, + 21, + 3, + 25, + 15, + 17 + ] + }, + { + "app": "", + "seed": 2872998923, + "order": [ + 27, + 15, + 20, + 22, + 14, + 28, + 3, + 18, + 24, + 23, + 29, + 10, + 25, + 9, + 5, + 11, + 7, + 19, + 8, + 16, + 2, + 1, + 13, + 21, + 6, + 4, + 17, + 0, + 26, + 12 + ] + }, + { + "app": "café", + "seed": 3746663762, + "order": [ + 2, + 23, + 0, + 9, + 14, + 11, + 15, + 28, + 10, + 29, + 21, + 3, + 27, + 8, + 6, + 16, + 18, + 25, + 1, + 22, + 26, + 20, + 24, + 5, + 4, + 12, + 19, + 13, + 17, + 7 + ] + } + ], + "topic_to_kind": [ + { + "topic": "", + "kind": 26261 + }, + { + "topic": "lobby", + "kind": 24083 + }, + { + "topic": "Trystero", + "kind": 24407 + }, + { + "topic": "[\"Trystero\",\"app\",\"room\"]", + "kind": 26553 + }, + { + "topic": "café 😀", + "kind": 26241 + }, + { + "topic": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "kind": 20693 + } + ], + "gen_id": [ + { + "n": 8, + "random_cycle": "00013d3e7bf7f8f9ff0ac8642122232425262728", + "id": "01z0zzAE" + }, + { + "n": 12, + "random_cycle": "00013d3e7bf7f8f9ff0ac8642122232425262728", + "id": "01z0zzAEcXYZ" + }, + { + "n": 20, + "random_cycle": "00013d3e7bf7f8f9ff0ac8642122232425262728", + "id": "01z0zzAEcXYZabcde01z" + }, + { + "n": 22, + "random_cycle": "00013d3e7bf7f8f9ff0ac8642122232425262728", + "id": "01z0zzAEcXYZabcde01z0z" + }, + { + "n": 64, + "random_cycle": "00013d3e7bf7f8f9ff0ac8642122232425262728", + "id": "01z0zzAEcXYZabcde01z0zzAEcXYZabcde01z0zzAEcXYZabcde01z0zzAEcXYZa" + } + ], + "identity_ids": [ + { + "compact_pub": "WKn-ZIGevcwGIyyrzFoZNBdQq79v3jZ8Nl3S1Jvxm7I.HdKAMKoHOpFkK-nMlm9JN6qzGlcrJ8nd5I4L8ss1V40", + "pid_digest": "99af88cf2e624ba696ab443d9c64d155c43311ee20a6add847336f00969b6a4f", + "uid_digest": "284b4d8b3e4b1613b005cbc7f734432d87f185d6b86bea9a1077a6ed36d52415", + "peer_id": "T5sdTwb84yyey80e4qjv", + "user_id": "2Ag9nxCt2tqpTCQ2x1bNyf" + } + ], + "room_key_no_password": [ + { + "app": "example.com/app", + "room": "lobby", + "preimage": "[\"trystero:room-aes:v3\",\"example.com/app\",\"lobby\"]", + "key": "b03810047a4001c5c48b2a81106f3649447465c05eca736b56c02f94facf207a" + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "preimage": "[\"trystero:room-aes:v3\",\"webcpp-trystero-quick-start\",\"café\"]", + "key": "4d371f0aab945ec4316b6f040d2008484ecc853f21c4af9aa760a5f099340241" + } + ], + "room_keys_password": [ + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "salt": "6c5d7a340e7fb5f0e2be6c42e4a8608da6e462638e82ba39f15ff69ead1313f7", + "master": "0a9daa6bbfe5e7a974b8ab2030704abcd09c0451a3e189a4bf5cda230e8fa8a7", + "aes_key": "4ae994c98ce84eb65c425d575f6041fd4b2d746e9aeadf55e8f5dec459b63f05", + "hmac_key": "fec04ff31caf38cf34185134d1073aaf4ed427f030574f42620f527f9aea3b53", + "probe_sealed": "AAECAwQFBgcICQoLGRjC2fdNlRMsEdzU_EXZAqj5nGES" + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "päss wörd", + "salt": "6c5d7a340e7fb5f0e2be6c42e4a8608da6e462638e82ba39f15ff69ead1313f7", + "master": "7b7cc66397463c41cd90ae25a3cbc14f3cc36fc5720c0d18634881d0d0456fc3", + "aes_key": "7cb04dde0775f7d1510aa484f6e852251cf574b83f35e641c3282dc03e16e48e", + "hmac_key": "f1d2a20f580624e4de679bb145476e2ff23cb29c15915ef9bec82ae1f123ff20", + "probe_sealed": "AAECAwQFBgcICQoLxIfa5stgfSD9cMjAlr4aNDVnEyQk" + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "salt": "7f62b7322788b421ec9f0a971fe8ca8f63b64328ddc496060cdbd1882b63d19f", + "master": "54f135ffd28ed3bc7089e3eea636f68c73e59e22fa6c1c885ba65154754fe15d", + "aes_key": "4175388a1c6ac3c97f3c78339c61323d90d8d90663964549d955d432b295d98a", + "hmac_key": "434268e92183bc6011f9003e660c4683b7d727a5ad690ae3009a563ce9c0d834", + "probe_sealed": "AAECAwQFBgcICQoLuzWCXwmcKKap6O2D9GLhZLhD4hR_" + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "päss wörd", + "salt": "7f62b7322788b421ec9f0a971fe8ca8f63b64328ddc496060cdbd1882b63d19f", + "master": "a01a75529a965885396180a2b765bcd577deb86c876e4f1f719c5673de65ea44", + "aes_key": "ca1d05568590c9dc5ba781844b836a6409af2a0776424d8b15421611ad39bb53", + "hmac_key": "37c9eb6d6473988d727964d8cfafb80e8acff634df7762b9b28ad768c1c70cb3", + "probe_sealed": "AAECAwQFBgcICQoLDylLYiH6u5rKzfH259JrM6gIa9WU" + } + ], + "room_auth": [ + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "peer_id": "@topology", + "seq": 0, + "payload": "[\"trystero:ov-auth:v3\",\"example.com/app\",\"lobby\",\"@topology\",0]", + "token": "2NJHPBHFvtay1mqxqeYGpGBT0NhRgaIvzZ9E-qfyuJI", + "verifies": true, + "wrong_seq_verifies": false + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "peer_id": "AbCdEfGhIjKlMnOpQrSt", + "seq": 7, + "payload": "[\"trystero:ov-auth:v3\",\"example.com/app\",\"lobby\",\"AbCdEfGhIjKlMnOpQrSt\",7]", + "token": "ZVSE0m_rYBRZpncsk78FJryImX5vT6j7fumci7tZIek", + "verifies": true, + "wrong_seq_verifies": false + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "peer_id": "@topology", + "seq": 0, + "payload": "[\"trystero:ov-auth:v3\",\"webcpp-trystero-quick-start\",\"café\",\"@topology\",0]", + "token": "T5-424RfPUNhHrePJh6wn_hz7qkujtgFMf8vpn42eb0", + "verifies": true, + "wrong_seq_verifies": false + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "peer_id": "AbCdEfGhIjKlMnOpQrSt", + "seq": 7, + "payload": "[\"trystero:ov-auth:v3\",\"webcpp-trystero-quick-start\",\"café\",\"AbCdEfGhIjKlMnOpQrSt\",7]", + "token": "BYwedXMyzF97paMCoMfwkE2UUat1CafFc4Jvc-Hea3s", + "verifies": true, + "wrong_seq_verifies": false + } + ], + "seal": [ + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "iv": "000102030405060708090a0b", + "plaintext": "", + "aad": null, + "sealed": "AAECAwQFBgcICQoLGc_6jhLrcbNj8hjzhPUqZg", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "iv": "000102030405060708090a0b", + "plaintext": "", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "AAECAwQFBgcICQoLPHygQYpNoS7kXhQ0XeG6eg", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "iv": "000102030405060708090a0b", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": null, + "sealed": "AAECAwQFBgcICQoLUeV4DjL1H_cMk-fvBvO1Re-y3nO7Ne-JJIVUU3PfsMhbgaUH0KbUBLB8Pxk60EQ", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "iv": "000102030405060708090a0b", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "AAECAwQFBgcICQoLUeV4DjL1H_cMk-fvBvO1Re-y3nO7Ne-JJIVUU3PfsCMnrjZs721Qbi0h3xljAcY", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "iv": "000102030405060708090a0b", + "plaintext": "café 😀", + "aad": null, + "sealed": "AAECAwQFBgcICQoLRLkuwJG60kW0ImujKoffDrU_pLvxs5ugxig", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "iv": "000102030405060708090a0b", + "plaintext": "café 😀", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "AAECAwQFBgcICQoLRLkuwJG60kW0Ioexh2NTJekXSRKgHeQyk4I", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "iv": "ffffffffffffffffffffffff", + "plaintext": "", + "aad": null, + "sealed": "________________x9ehIHdByjLZoxc2AHDg_Q", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "iv": "ffffffffffffffffffffffff", + "plaintext": "", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "________________4mT77-_nGq9eDxvx2WRw4Q", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "iv": "ffffffffffffffffffffffff", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": null, + "sealed": "________________2zK42CrSR5fpZl3tcbvbFls_oetjUwCxMJLNojXULbykNyYg2kK4jAUNGUPoG3k", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "iv": "ffffffffffffffffffffffff", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "________________2zK42CrSR5fpZl3tcbvbFls_oetjUwCxMJLNojXULVfYGLVL5Yk85phQ-UOxyvs", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "iv": "ffffffffffffffffffffffff", + "plaintext": "café 😀", + "aad": null, + "sealed": "________________zm7uFomdiiVR1wCLHrBKy25hdYx9kwsBb48", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "iv": "ffffffffffffffffffffffff", + "plaintext": "café 😀", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "________________zm7uFomdiiVR1-yZs1TG4DJJmCUsPXSTOiU", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "iv": "000102030405060708090a0b", + "plaintext": "", + "aad": null, + "sealed": "AAECAwQFBgcICQoLU7rlzvmNe5NDby7HWNMYjw", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "iv": "000102030405060708090a0b", + "plaintext": "", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "AAECAwQFBgcICQoLp5uLDAohzG2vycYFeAI54g", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "iv": "000102030405060708090a0b", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": null, + "sealed": "AAECAwQFBgcICQoLH1edtphfX1Sibsj2gu6gxXecH_vhL_4MGdXQ8Ond0lAnscgR97CMUrU9QG7Y6cM", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "iv": "000102030405060708090a0b", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "AAECAwQFBgcICQoLH1edtphfX1Sibsj2gu6gxXecH_vhL_4MGdXQ8Ond0s6d3v9lvAOof7aT5pPEdko", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "iv": "000102030405060708090a0b", + "plaintext": "café 😀", + "aad": null, + "sealed": "AAECAwQFBgcICQoLCgvLeDsQkuYa3_btujkE61AA_JWS0ZPMt9s", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "iv": "000102030405060708090a0b", + "plaintext": "café 😀", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "AAECAwQFBgcICQoLCgvLeDsQkuYa3-1BkjfzBucxRacy2JGUNjo", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "iv": "ffffffffffffffffffffffff", + "plaintext": "", + "aad": null, + "sealed": "________________ZLRVu8Pz-WGqEDp9yQjAWQ", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "iv": "ffffffffffffffffffffffff", + "plaintext": "", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "________________kJU7eTBfTp9GttK_6dnhNA", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "iv": "ffffffffffffffffffffffff", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": null, + "sealed": "________________lXPjrb_hjUvTU0PvtNpTDbmWUvFRogTyC8A7ZR_p9koJP0Zpi7xsN6u-g9JggVg", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "iv": "ffffffffffffffffffffffff", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "________________lXPjrb_hjUvTU0PvtNpTDbmWUvFRogTyC8A7ZR_p9tSzUHEdwA9IGqgQJS98HtE", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "iv": "ffffffffffffffffffffffff", + "plaintext": "café 😀", + "aad": null, + "sealed": "________________gC-1YxyuQPlr4nyf6xfmF4hlvzA_KkBP0nE", + "opened_equal": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "hunter2", + "iv": "ffffffffffffffffffffffff", + "plaintext": "café 😀", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "________________gC-1YxyuQPlr4mczwxkR-j9UBgKfI0IXU5A", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "", + "iv": "000102030405060708090a0b", + "plaintext": "", + "aad": null, + "sealed": "AAECAwQFBgcICQoLj0jjmghtRCOnPJZpqsMD2Q", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "", + "iv": "000102030405060708090a0b", + "plaintext": "", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "AAECAwQFBgcICQoLpZ7jQZsODIcTq-DFSG2ZcA", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "", + "iv": "000102030405060708090a0b", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": null, + "sealed": "AAECAwQFBgcICQoLJANGWduDCr8olDIuVhrLZrq4Qv7semA5FQaEtq00-iRfHxw8x3y68O_kjSAHpu0", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "", + "iv": "000102030405060708090a0b", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "AAECAwQFBgcICQoLJANGWduDCr8olDIuVhrLZrq4Qv7semA5FQaEtq00-kGyltqViFxLmwhetU3FQDQ", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "", + "iv": "000102030405060708090a0b", + "plaintext": "café 😀", + "aad": null, + "sealed": "AAECAwQFBgcICQoLMV8Ql3jMxw2QJV8SOBjnrAY6XECmtHiJe2g", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "", + "iv": "000102030405060708090a0b", + "plaintext": "café 😀", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "AAECAwQFBgcICQoLMV8Ql3jMxw2QJZOasbdFmJ-6dhb34-bjkvQ", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "", + "iv": "ffffffffffffffffffffffff", + "plaintext": "", + "aad": null, + "sealed": "________________wAiHUcFAhvnNn_0MqWT3xQ", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "", + "iv": "ffffffffffffffffffffffff", + "plaintext": "", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "________________6t6HilIjzl15CIugS8ptbA", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "", + "iv": "ffffffffffffffffffffffff", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": null, + "sealed": "________________SX-C8cB81taRVv3VfCBW578hzFY9ZGK1Ol9iu0TILXBipXwRUoDRzfcfeCpEs6k", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "", + "iv": "ffffffffffffffffffffffff", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "________________SX-C8cB81taRVv3VfCBW578hzFY9ZGK1Ol9iu0TILRWPLLq4HaAgphClQEeGVXA", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "", + "iv": "ffffffffffffffffffffffff", + "plaintext": "café 😀", + "aad": null, + "sealed": "________________XCPUP2MzG2Qp58dCQBqtu9e70g1sJqG39bk", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "", + "iv": "ffffffffffffffffffffffff", + "plaintext": "café 😀", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "________________XCPUP2MzG2Qp5wvKybUPj047-Fs9cT_dHCU", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "iv": "000102030405060708090a0b", + "plaintext": "", + "aad": null, + "sealed": "AAECAwQFBgcICQoLK5_ohRzzZRSOfSQ_C-agZw", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "iv": "000102030405060708090a0b", + "plaintext": "", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "AAECAwQFBgcICQoLNXW7Kdeex04S-E4Le8VLAQ", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "iv": "000102030405060708090a0b", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": null, + "sealed": "AAECAwQFBgcICQoLvXrdMGYS3zvIh2u26fdDBhsrBFed56pW6SKXV9GHcL_uixOIh3fuJft3j9QAbRc", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "iv": "000102030405060708090a0b", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "AAECAwQFBgcICQoLvXrdMGYS3zvIh2u26fdDBhsrBFed56pW6SKXV9GHcPTqw0ToHbW3fiJoN7YDn4c", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "iv": "000102030405060708090a0b", + "plaintext": "café 😀", + "aad": null, + "sealed": "AAECAwQFBgcICQoLqCaL_sVdEolwNsS94x6gm-4mo8h2XJ4M0VI", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "iv": "000102030405060708090a0b", + "plaintext": "café 😀", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "AAECAwQFBgcICQoLqCaL_sVdEolwNnOkYmH_uFkYtYo1mIDId2Q", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "iv": "ffffffffffffffffffffffff", + "plaintext": "", + "aad": null, + "sealed": "________________zY4lFp8CCCx-uNu8ttQbBQ", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "iv": "ffffffffffffffffffffffff", + "plaintext": "", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "________________02R2ulRvqnbiPbGIxvfwYw", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "iv": "ffffffffffffffffffffffff", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": null, + "sealed": "________________h-y5jK4U0I1a2muOyB4XWE9fkh5G3_rtXeOu79ZMHeXfgaGNwCWmLqpylLfUC1A", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "iv": "ffffffffffffffffffffffff", + "plaintext": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "________________h-y5jK4U0I1a2muOyB4XWE9fkh5G3_rtXeOu79ZMHa7byfbtWuf_dXNtLNXX-cA", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "iv": "ffffffffffffffffffffffff", + "plaintext": "café 😀", + "aad": null, + "sealed": "________________krDvQg1bHT_ia-IrSqhCVHZWu8e2Lz-tlTw", + "opened_equal": true + }, + { + "app": "webcpp-trystero-quick-start", + "room": "café", + "password": "hunter2", + "iv": "ffffffffffffffffffffffff", + "plaintext": "café 😀", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab", + "sealed": "________________krDvQg1bHT_ia1Uyy9cdd8ForYX16yFpMwo", + "opened_equal": true + } + ], + "open_refused": [ + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "sealed": "", + "refused": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "sealed": "not base64!", + "refused": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "sealed": "AAECAwQFBgcICQoLRLku", + "refused": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "sealed": "AAECAwQFBgcICQoLRLkuwJG60kW0ImujKoffDrU_pLvxs5ugxig=", + "refused": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "sealed": "AAECAwQFBgcICQoLRLkuwJG60kW0ImujKoffDrU_pLvxs5ugxiA", + "refused": true + }, + { + "app": "example.com/app", + "room": "lobby", + "password": "", + "sealed": "BAECAwQFBgcICQoLRLkuwJG60kW0ImujKoffDrU_pLvxs5ugxig", + "refused": true + } + ], + "signal_aad": [ + { + "type": "offer", + "peer_id": "AbCdEfGhIjKlMnOpQrSt", + "offer_id": "0123456789ab", + "aad": "offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab" + }, + { + "type": "answer", + "peer_id": "x", + "offer_id": "y", + "aad": "answer|x|y" + } + ], + "action_frames": [ + { + "case": "text", + "action": "chat", + "format": 0, + "metadata": null, + "payload_text": "hello, café", + "wide": false, + "frames": [ + { + "from": "A", + "size": 48, + "hex": "03006368617400000000000000000000000000000000000000000000000000000000000068656c6c6f2c20636166c3a9" + } + ], + "delivered": true, + "send_error": null + }, + { + "case": "json", + "action": "json", + "format": 1, + "metadata": null, + "payload_text": "{\"n\":1,\"list\":[true,null,\"x\"]}", + "wide": false, + "frames": [ + { + "from": "A", + "size": 66, + "hex": "03106a736f6e0000000000000000000000000000000000000000000000000000000000007b226e223a312c226c697374223a5b747275652c6e756c6c2c2278225d7d" + } + ], + "delivered": true, + "send_error": null + }, + { + "case": "binary", + "action": "bin", + "format": 2, + "metadata": null, + "payload_hex": "00010203040506070809", + "wide": false, + "frames": [ + { + "from": "A", + "size": 46, + "hex": "032062696e0000000000000000000000000000000000000000000000000000000000000000010203040506070809" + } + ], + "delivered": true, + "send_error": null + }, + { + "case": "metadata", + "action": "chat", + "format": 0, + "metadata": "{\"a\":1}", + "payload_text": "hi", + "wide": false, + "frames": [ + { + "from": "A", + "size": 45, + "hex": "0300636861740000000000000000000000000000000000000000000000000000000000077b2261223a317d6869" + } + ], + "delivered": true, + "send_error": null + }, + { + "case": "bulk", + "action": "file", + "format": 2, + "metadata": "{\"name\":\"big.bin\"}", + "payload_size": 204800, + "wide": false, + "frames": [ + { + "from": "A", + "size": 66, + "transfer_id": 0, + "is_offer": true, + "hex": "032166696c650000000000000000000000000000000000000000000000000000000000120000000041090000000000007b226e616d65223a226269672e62696e227d" + }, + { + "from": "B", + "size": 6, + "transfer_id": 0, + "hex": "030300000000" + }, + { + "from": "A", + "size": 16384, + "transfer_id": 0, + "head": "0302000000000000000000000000", + "sha256": "6c243b9f165ea104ddf836b0f2afa49a144fd823ca4fe2c6bc9fb3a0d33532d7" + }, + { + "from": "A", + "size": 16384, + "transfer_id": 0, + "head": "03020000000040cff90000000000", + "sha256": "1e35919dfaa348b7d73dfd0ebac70968b275742d11ca5a83806d2756b1136e7e" + }, + { + "from": "A", + "size": 16384, + "transfer_id": 0, + "head": "03020000000040dff90000000000", + "sha256": "06a46e6b3baeb5e2cdc9befbcbb358e09c4b0a9bb41187e84072c1a56efae2d1" + }, + { + "from": "A", + "size": 16384, + "transfer_id": 0, + "head": "03020000000040e7fac000000000", + "sha256": "fe71da8c0b320218c2668f3148eb914054bd0036012a578287e5c98aff518777" + }, + { + "from": "A", + "size": 16384, + "transfer_id": 0, + "head": "03020000000040eff90000000000", + "sha256": "6fe28af7e9e2aed6c27ba118bd71169a8fe13e2d82233c21ed78240e60f86e5f" + }, + { + "from": "A", + "size": 16384, + "transfer_id": 0, + "head": "03020000000040f3fba000000000", + "sha256": "33ce5c4ab83c93a9217f6f12226a8a41adac9f0d56d4fde4f30b65207bd2028c" + }, + { + "from": "A", + "size": 16384, + "transfer_id": 0, + "head": "03020000000040f7fac000000000", + "sha256": "3816c7ebae0828e2edb81a0852db1edbd008a12f387d84143c01a5f733184a84" + }, + { + "from": "A", + "size": 16384, + "transfer_id": 0, + "head": "03020000000040fbf9e000000000", + "sha256": "d38dbacfb1e191f3a694236a79c2a55ffbe0638c9f13f2c34d128daa7f8b8a73" + }, + { + "from": "A", + "size": 16384, + "transfer_id": 0, + "head": "03020000000040fff90000000000", + "sha256": "cd290e22efacc8ef21d1dc5915bdf7fbecf590a29641177bc4f73334c66006e2" + }, + { + "from": "A", + "size": 16384, + "transfer_id": 0, + "head": "0302000000004101fc1000000000", + "sha256": "71cf9ff89b10340e20111791467df9056241658498da1e56e15e6d219d836b12" + }, + { + "from": "A", + "size": 16384, + "transfer_id": 0, + "head": "0302000000004103fba000000000", + "sha256": "0de88995f2916480ac8e98b6c73cf304b53eb4283c6aa878fa82d4ac7dad7bbc" + }, + { + "from": "A", + "size": 16384, + "transfer_id": 0, + "head": "0302000000004105fb3000000000", + "sha256": "3ceb883b35f71d9526a71ba9e0b8a0f69622783e14d8a59fc51c83ec1d506aec" + }, + { + "from": "A", + "size": 8374, + "transfer_id": 0, + "head": "0302000000004107fac000000000", + "sha256": "1d0504952ba84c434f8d3dd7c8726f4a1c5b8717f2ed4ecb871e4e8e4b4f8616" + } + ], + "delivered": true, + "send_error": null + }, + { + "case": "bulk_wide", + "action": "file", + "format": 2, + "metadata": "{\"name\":\"big.bin\"}", + "payload_size": 204800, + "wide": true, + "frames": [ + { + "from": "A", + "size": 66, + "transfer_id": 0, + "is_offer": true, + "hex": "036166696c650000000000000000000000000000000000000000000000000000000000120000000041090000000000007b226e616d65223a226269672e62696e227d" + }, + { + "from": "B", + "size": 6, + "transfer_id": 0, + "hex": "030300000000" + }, + { + "from": "A", + "size": 65536, + "transfer_id": 0, + "head": "0302000000000000000000000000", + "sha256": "08c4d25d142279a04f2230a4d58c4960fe80a7aafbdf1fa35165a93ca79c9436" + }, + { + "from": "A", + "size": 65536, + "transfer_id": 0, + "head": "03020000000040effe4000000000", + "sha256": "4be38fbee0a587e6eb6057c7db3e052dc2209e0e3d2a7790fdc536aa89cf604d" + }, + { + "from": "A", + "size": 65536, + "transfer_id": 0, + "head": "03020000000040fffe4000000000", + "sha256": "de7250e6ca73c65fd70b192f7b0e1702b62cbbd87222c2b349f3b2ae17578958" + }, + { + "from": "A", + "size": 8248, + "transfer_id": 0, + "head": "0302000000004107feb000000000", + "sha256": "16206adfc7c0ccb7139c8564814bd983e6a2d4c25771412f40553162ab2f30dd" + } + ], + "delivered": true, + "send_error": null + }, + { + "case": "declined", + "action": "file", + "format": 2, + "metadata": null, + "payload_size": 20000, + "wide": false, + "frames": [ + { + "from": "A", + "size": 48, + "transfer_id": 0, + "is_offer": true, + "hex": "032166696c650000000000000000000000000000000000000000000000000000000000000000000040d3880000000000" + }, + { + "from": "B", + "size": 34, + "transfer_id": 0, + "hex": "0304000000007061796c6f61642072656a6563746564206279207265636569766572" + } + ], + "delivered": false, + "send_error": "Trystero: payload rejected by receiver" + }, + { + "case": "cancelled", + "action": "file", + "format": 2, + "metadata": null, + "payload_size": 204800, + "wide": false, + "frames": [ + { + "from": "A", + "size": 48, + "transfer_id": 0, + "is_offer": true, + "hex": "032166696c65000000000000000000000000000000000000000000000000000000000000000000004109000000000000" + }, + { + "from": "B", + "size": 6, + "transfer_id": 0, + "hex": "030300000000" + }, + { + "from": "A", + "size": 16384, + "transfer_id": 0, + "head": "0302000000000000000000000000", + "sha256": "6c243b9f165ea104ddf836b0f2afa49a144fd823ca4fe2c6bc9fb3a0d33532d7" + }, + { + "from": "A", + "size": 6, + "transfer_id": 0, + "hex": "030500000000" + } + ], + "delivered": false, + "send_error": "Trystero: operation aborted" + }, + { + "case": "request", + "action": "ask", + "format": 0, + "metadata": "{\"r\":\"0b1c2d3e-4f50-4617-8899-aabbccddeeff\",\"m\":{\"x\":1}}", + "payload_text": "ping", + "wide": false, + "frames": [ + { + "from": "A", + "size": 96, + "hex": "030061736b000000000000000000000000000000000000000000000000000000000000387b2272223a2230623163326433652d346635302d343631372d383839392d616162626363646465656666222c226d223a7b2278223a317d7d70696e67" + }, + { + "from": "B", + "size": 89, + "hex": "0300405f726573706f6e736500000000000000000000000000000000000000000000002c7b2272223a2230623163326433652d346635302d343631372d383839392d616162626363646465656666227d706f6e673a70696e67" + } + ], + "response": "pong:ping", + "send_error": null, + "answer": { + "action": "@_response", + "format": 0, + "metadata": "{\"r\":\"0b1c2d3e-4f50-4617-8899-aabbccddeeff\"}", + "payload_text": "pong:ping" + } + }, + { + "case": "request_failed", + "action": "ask", + "format": 0, + "metadata": "{\"r\":\"0b1c2d3e-4f50-4617-8899-aabbccddeeff\",\"m\":{\"x\":1}}", + "payload_text": "ping", + "wide": false, + "frames": [ + { + "from": "A", + "size": 96, + "hex": "030061736b000000000000000000000000000000000000000000000000000000000000387b2272223a2230623163326433652d346635302d343631372d383839392d616162626363646465656666222c226d223a7b2278223a317d7d70696e67" + }, + { + "from": "B", + "size": 100, + "hex": "0310405f726573706f6e736500000000000000000000000000000000000000000000003c7b2272223a2230623163326433652d346635302d343631372d383839392d616162626363646465656666222c2265223a226e6f20616e73776572227d6e756c6c" + } + ], + "response": null, + "send_error": "Trystero: no answer", + "answer": { + "action": "@_response", + "format": 1, + "metadata": "{\"r\":\"0b1c2d3e-4f50-4617-8899-aabbccddeeff\",\"e\":\"no answer\"}", + "payload_text": "null" + } + } + ], + "signatures": { + "a high-S endpoint signature:a:endpoint": "qUfkdmwIYOsSSUqR54nbxlm4TVfh8eng8edl1sypdIo7BrdKk3GQZfy9Cot4URLwdG6IPX9Oi0hPYP3dyS1scA", + "a high-S endpoint signature:a:user": "M7glmr-vE4YbYZ2sK7GHKof2daOTPBbGv_tJB-7JUcpeFigIoebjU5ttShwNyzY2JgZhPwhH_knIPnkA4GgvnQ", + "a high-S endpoint signature:b:endpoint": "r3L3zOoMemI-F7b06SrooCiQxh9RJnfdPC3Nh7fXUul43HjYcm0rwYwGZCP8jpMlCeyfzj2874xkPTRabCyR6A", + "a high-S endpoint signature:b:user": "_I0E-_dTqVt3HjkAE4nm4Wq_Bhls3fjpg-slG-G74AZB3VDaCPFv9fzDpRjt5KKrErVyQo8mfzzgyuTZKy6suw", + "a user signature of another key:b:endpoint": "CXNVYawWseUv7GMyVOaoYnTVVOUJ9H7iwpFDPLRw9Conm6EYqntGA9GiGqYLH2-DJnD_yDI-U2-kgW6hl4ZoNg", + "a user signature of another key:b:user": "5mWZZscqEKToj1Y2ykbCy2VCP4GFxCKfrtOXRq6hkD8paEPiUwT8RE4IcZmQUfXVdx3R5_w8qDDVlieHzzt4VQ", + "an endpoint key of another peer id:b:endpoint": "tzg9WR33ggX2DqIPk2uS-bAvw5j9upFklbElHURcMMBV-5E6gVnTCLLIzt6Z9-WtxeHW5nsOl3g7BpWAJRA7ZA", + "an endpoint key of another peer id:b:user": "PAd0ECqTGhpEPxDDCL9ysveQj-5MlpQV_DBn02VQ0wEfLZ97DwPwk0elfp5hZgZXqykfrDTz9xam_j7tpyENuw", + "user_proof": "yKjEX7A1gfPylw5b0nVJqwA0Oz8gxERTU47YIPgtaIQxt0Ry8fY0CZYjpSwrd3dR3Q_4HrgdVCWNG5sPUDO7TQ", + "verified:a:endpoint": "saWD2e3IzdwI1XLYaJNydv0RHMBBbNIszXFYyx3alJUO2fog_yBKkpd19aC-TzVr7uIPSlhVW-KabBAeflypJw", + "verified:a:user": "kCivJlKg135n4UPn5zVLVFMPFzcKvcgrt0sdfamwNhwdhpuw_09dBGvqPz-L9BXwhRG0aVyi73WF4ihyN6QYkQ", + "verified:b:endpoint": "xoj5UqGMR8duyQzQBdES01oYfZTskbPsMJ2NRidRBNg9tKFneusIazxZZQk9fwL1vQk1E2-nl4coiRIfGFQ8CQ", + "verified:b:user": "IqTv3MG9H2buDNJN7YeTdja-LjAVwF_2BZL8adRyS3orYNMxn6xTh8cPm1BipNUx7HmATAKjEwhS9rVvHITV0A" + }, + "p256_keys": [ + { + "label": "endpoint-a", + "d": "uYTVzeHv6cts2IzXz7UkD2Q9bBcmHKZpPFZ1eNcoUdk", + "uncompressed": "049208dd7b3b924dc1707732cf2068f38a43e43754486db546641189291fec37076e18016d13fd4a05f94a4d70b1ccbf6b92c7024b7a3d3e2f6af5f5bd21e4fd77", + "compact": "kgjdezuSTcFwdzLPIGjzikPkN1RIbbVGZBGJKR_sNwc.bhgBbRP9SgX5Sk1wscy_a5LHAkt6PT4vavX1vSHk_Xc", + "peer_id": "m7oEQitmWEQ4WW5aqhKp", + "user_id": "ynY5geuP51wDNIjKq1xkDh" + }, + { + "label": "user-a", + "d": "tZPnmQ9fFvgPg4d4vNFgEq98uEmgMtL3J4aEB9wYXus", + "uncompressed": "048ef6630e180f22011d6300ce42c09bd3c10492006728f34b2726a90a5364e3e9417b714bdd2e6abb84bb90989ebfab80385264d0f21e3fc34238d62467263e9b", + "compact": "jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k.QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPps", + "peer_id": "1uTF5q1EXmKMmm1jRF82", + "user_id": "8Qc8kjJP0X70oY14zVW6rM" + }, + { + "label": "endpoint-b", + "d": "VZc6ctCgUCX-BEpJSZK32uUTs81zGlZj1PdqgxO-50Q", + "uncompressed": "04d97653a7ae3e3c5c106c035b8ecb9bcc8e53cbb40b0370984b7d5f04857a00f0ecdf620983aa9cd814834443dd17b4ffbe18514e67f7d907fb916f5d2579bc18", + "compact": "2XZTp64-PFwQbANbjsubzI5Ty7QLA3CYS31fBIV6APA.7N9iCYOqnNgUg0RD3Re0_74YUU5n99kH-5FvXSV5vBg", + "peer_id": "izta8zhsZH7HVcLteLNl", + "user_id": "dOStHaQPEAKBivzjmTuiML" + }, + { + "label": "user-b", + "d": "pbbWpBUNjtwncadIiWH_ELxOVWyS8jYKa8xdUk0PWjs", + "uncompressed": "0459ac6fd68e871bf153021478db213068d63b8bf62fa07e4e10ff9194834756448d8fce88850eb4f01e7599152dd2d7ca5bf0dced2f5d13e2fce9e9119b29cc2c", + "compact": "Waxv1o6HG_FTAhR42yEwaNY7i_YvoH5OEP-RlINHVkQ.jY_OiIUOtPAedZkVLdLXylvw3O0vXRPi_OnpEZspzCw", + "peer_id": "qhFA33xYMserGVDmcM8S", + "user_id": "8oysJYYlxgfcFBn7jJOcpc" + }, + { + "label": "user-export", + "d": "5khreCrQOZlmNMIhJJlJAVHk4x1uILg85U8e1TSTKrw", + "uncompressed": "046959c6d6054b15792dbed030b0b52820f640ed1962bb4bf3182f414c4def8f209094952e94ded7652938a98e0af0407d2043ae1ae2415c109e141c83444db82d", + "compact": "aVnG1gVLFXktvtAwsLUoIPZA7Rliu0vzGC9BTE3vjyA.kJSVLpTe12UpOKmOCvBAfSBDrhriQVwQnhQcg0RNuC0", + "peer_id": "WYwjb2NLbczwLb6k5chL", + "user_id": "Gawjnehj72iKv8sp1tHMwI" + } + ], + "compact_keys": [ + { + "text": "jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k.QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPps", + "text_valid": true, + "record": true + }, + { + "text": "jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k.QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPp", + "text_valid": false, + "record": false + }, + { + "text": "jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k.QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPpsA", + "text_valid": false, + "record": false + }, + { + "text": "jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k_QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPps", + "text_valid": false, + "record": false + }, + { + "text": "jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-=.QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPps", + "text_valid": false, + "record": false + }, + { + "text": "jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k.AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", + "text_valid": true, + "record": false + } + ], + "user_identity": { + "label": "user-export", + "jwk": { + "d": "5khreCrQOZlmNMIhJJlJAVHk4x1uILg85U8e1TSTKrw", + "x": "aVnG1gVLFXktvtAwsLUoIPZA7Rliu0vzGC9BTE3vjyA", + "y": "kJSVLpTe12UpOKmOCvBAfSBDrhriQVwQnhQcg0RNuC0" + }, + "user_id": "Gawjnehj72iKv8sp1tHMwI", + "text": "trystero_uk_eyJkIjoiNWtocmVDclFPWmxtTk1JaEpKbEpBVkhrNHgxdUlMZzg1VThlMVRTVEtydyIsIngiOiJhVm5HMWdWTEZYa3R2dEF3c0xVb0lQWkE3UmxpdTB2ekdDOUJURTN2anlBIiwieSI6ImtKU1ZMcFRlMTJVcE9LbU9DdkJBZlNCRHJocmlRVndRbmhRY2cwUk51QzAifQ", + "json": "{\"d\":\"5khreCrQOZlmNMIhJJlJAVHk4x1uILg85U8e1TSTKrw\",\"x\":\"aVnG1gVLFXktvtAwsLUoIPZA7Rliu0vzGC9BTE3vjyA\",\"y\":\"kJSVLpTe12UpOKmOCvBAfSBDrhriQVwQnhQcg0RNuC0\"}" + }, + "user_identity_imports": [ + { + "case": "the exported text", + "text": "trystero_uk_eyJkIjoiNWtocmVDclFPWmxtTk1JaEpKbEpBVkhrNHgxdUlMZzg1VThlMVRTVEtydyIsIngiOiJhVm5HMWdWTEZYa3R2dEF3c0xVb0lQWkE3UmxpdTB2ekdDOUJURTN2anlBIiwieSI6ImtKU1ZMcFRlMTJVcE9LbU9DdkJBZlNCRHJocmlRVndRbmhRY2cwUk51QzAifQ", + "accepted": true, + "user_id": "Gawjnehj72iKv8sp1tHMwI" + }, + { + "case": "the text with spaces around it", + "text": " trystero_uk_eyJkIjoiNWtocmVDclFPWmxtTk1JaEpKbEpBVkhrNHgxdUlMZzg1VThlMVRTVEtydyIsIngiOiJhVm5HMWdWTEZYa3R2dEF3c0xVb0lQWkE3UmxpdTB2ekdDOUJURTN2anlBIiwieSI6ImtKU1ZMcFRlMTJVcE9LbU9DdkJBZlNCRHJocmlRVndRbmhRY2cwUk51QzAifQ\n", + "accepted": true, + "user_id": "Gawjnehj72iKv8sp1tHMwI" + }, + { + "case": "the JSON text", + "text": "{\"kty\":\"EC\",\"crv\":\"P-256\",\"d\":\"5khreCrQOZlmNMIhJJlJAVHk4x1uILg85U8e1TSTKrw\",\"x\":\"aVnG1gVLFXktvtAwsLUoIPZA7Rliu0vzGC9BTE3vjyA\",\"y\":\"kJSVLpTe12UpOKmOCvBAfSBDrhriQVwQnhQcg0RNuC0\"}", + "accepted": true, + "user_id": "Gawjnehj72iKv8sp1tHMwI" + }, + { + "case": "another prefix", + "text": "trystero_pk_eyJkIjoiNWtocmVDclFPWmxtTk1JaEpKbEpBVkhrNHgxdUlMZzg1VThlMVRTVEtydyIsIngiOiJhVm5HMWdWTEZYa3R2dEF3c0xVb0lQWkE3UmxpdTB2ekdDOUJURTN2anlBIiwieSI6ImtKU1ZMcFRlMTJVcE9LbU9DdkJBZlNCRHJocmlRVndRbmhRY2cwUk51QzAifQ", + "accepted": false, + "user_id": null + }, + { + "case": "the payload padded", + "text": "trystero_uk_eyJkIjoiNWtocmVDclFPWmxtTk1JaEpKbEpBVkhrNHgxdUlMZzg1VThlMVRTVEtydyIsIngiOiJhVm5HMWdWTEZYa3R2dEF3c0xVb0lQWkE3UmxpdTB2ekdDOUJURTN2anlBIiwieSI6ImtKU1ZMcFRlMTJVcE9LbU9DdkJBZlNCRHJocmlRVndRbmhRY2cwUk51QzAifQ=", + "accepted": false, + "user_id": null + }, + { + "case": "d of another key", + "text": "trystero_uk_eyJkIjoidFpQbm1ROWZGdmdQZzRkNHZORmdFcTk4dUVtZ010TDNKNGFFQjl3WVh1cyIsIngiOiJhVm5HMWdWTEZYa3R2dEF3c0xVb0lQWkE3UmxpdTB2ekdDOUJURTN2anlBIiwieSI6ImtKU1ZMcFRlMTJVcE9LbU9DdkJBZlNCRHJocmlRVndRbmhRY2cwUk51QzAifQ", + "accepted": false, + "user_id": null + }, + { + "case": "d zero", + "text": "trystero_uk_eyJkIjoiQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQSIsIngiOiJhVm5HMWdWTEZYa3R2dEF3c0xVb0lQWkE3UmxpdTB2ekdDOUJURTN2anlBIiwieSI6ImtKU1ZMcFRlMTJVcE9LbU9DdkJBZlNCRHJocmlRVndRbmhRY2cwUk51QzAifQ", + "accepted": false, + "user_id": null + }, + { + "case": "d the group order", + "text": "trystero_uk_eyJkIjoiX19fX193QUFBQURfX19fX19fX19fN3ptLXEybkY1NkU4N25Ld3Z4akpWRSIsIngiOiJhVm5HMWdWTEZYa3R2dEF3c0xVb0lQWkE3UmxpdTB2ekdDOUJURTN2anlBIiwieSI6ImtKU1ZMcFRlMTJVcE9LbU9DdkJBZlNCRHJocmlRVndRbmhRY2cwUk51QzAifQ", + "accepted": false, + "user_id": null + }, + { + "case": "d of 31 bytes", + "text": "trystero_uk_eyJkIjoiU0d0NEt0QTVtV1kwd2lFa21Va0JVZVRqSFc0Z3VEemxUeDdWTkpNcXZBIiwieCI6ImFWbkcxZ1ZMRlhrdHZ0QXdzTFVvSVBaQTdSbGl1MHZ6R0M5QlRFM3ZqeUEiLCJ5Ijoia0pTVkxwVGUxMlVwT0ttT0N2QkFmU0JEcmhyaVFWd1FuaFFjZzBSTnVDMCJ9", + "accepted": false, + "user_id": null + }, + { + "case": "crv P-384", + "text": "trystero_uk_eyJjcnYiOiJQLTM4NCIsImQiOiI1a2hyZUNyUU9abG1OTUloSkpsSkFWSGs0eDF1SUxnODVVOGUxVFNUS3J3IiwieCI6ImFWbkcxZ1ZMRlhrdHZ0QXdzTFVvSVBaQTdSbGl1MHZ6R0M5QlRFM3ZqeUEiLCJ5Ijoia0pTVkxwVGUxMlVwT0ttT0N2QkFmU0JEcmhyaVFWd1FuaFFjZzBSTnVDMCJ9", + "accepted": false, + "user_id": null + }, + { + "case": "no y", + "text": "trystero_uk_eyJkIjoiNWtocmVDclFPWmxtTk1JaEpKbEpBVkhrNHgxdUlMZzg1VThlMVRTVEtydyIsIngiOiJhVm5HMWdWTEZYa3R2dEF3c0xVb0lQWkE3UmxpdTB2ekdDOUJURTN2anlBIn0", + "accepted": false, + "user_id": null + }, + { + "case": "empty", + "text": "", + "accepted": false, + "user_id": null + } + ], + "user_proof": { + "app": "example.com/app", + "room": "lobby", + "peer_id": "m7oEQitmWEQ4WW5aqhKp", + "peer_compact": "kgjdezuSTcFwdzLPIGjzikPkN1RIbbVGZBGJKR_sNwc.bhgBbRP9SgX5Sk1wscy_a5LHAkt6PT4vavX1vSHk_Xc", + "seq": 7, + "user_id": "8Qc8kjJP0X70oY14zVW6rM", + "user_compact": "jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k.QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPps", + "payload": "[\"trystero:user-proof:v3\",\"example.com/app\",\"lobby\",\"m7oEQitmWEQ4WW5aqhKp\",\"kgjdezuSTcFwdzLPIGjzikPkN1RIbbVGZBGJKR_sNwc.bhgBbRP9SgX5Sk1wscy_a5LHAkt6PT4vavX1vSHk_Xc\",7]", + "digest": "6891b6751ffa4d90b10e41cc7daf42e6c1a129e31ae2a2870448a40a331b521a", + "proof": "yKjEX7A1gfPylw5b0nVJqwA0Oz8gxERTU47YIPgtaIQxt0Ry8fY0CZYjpSwrd3dR3Q_4HrgdVCWNG5sPUDO7TQ", + "verifies": true, + "other_seq_verifies": false + }, + "low_s": [ + { + "case": "signed", + "signature": "c8a8c45fb03581f3f2970e5bd27549ab00343b3f20c44453538ed820f82d688431b74472f1f634099623a52c2b777751dd0ff81eb81d54258d1b9b0f5033bb4d", + "is_low_s": true, + "normalized": "c8a8c45fb03581f3f2970e5bd27549ab00343b3f20c44453538ed820f82d688431b74472f1f634099623a52c2b777751dd0ff81eb81d54258d1b9b0f5033bb4d", + "verifies": true + }, + { + "case": "its high form", + "signature": "c8a8c45fb03581f3f2970e5bd27549ab00343b3f20c44453538ed820f82d6884ce48bb8c0e09cbf769dc5ad3d48888addfd7028eeefa4a5f669e2fb3ac2f6a04", + "is_low_s": false, + "normalized": "c8a8c45fb03581f3f2970e5bd27549ab00343b3f20c44453538ed820f82d688431b74472f1f634099623a52c2b777751dd0ff81eb81d54258d1b9b0f5033bb4d", + "verifies": false + }, + { + "case": "s = (n - 1) / 2", + "signature": "c8a8c45fb03581f3f2970e5bd27549ab00343b3f20c44453538ed820f82d68847fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192a8", + "is_low_s": true, + "normalized": "c8a8c45fb03581f3f2970e5bd27549ab00343b3f20c44453538ed820f82d68847fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192a8", + "verifies": false + }, + { + "case": "s = (n + 1) / 2", + "signature": "c8a8c45fb03581f3f2970e5bd27549ab00343b3f20c44453538ed820f82d68847fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192a9", + "is_low_s": false, + "normalized": "c8a8c45fb03581f3f2970e5bd27549ab00343b3f20c44453538ed820f82d68847fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192a8", + "verifies": false + }, + { + "case": "s = n - 1", + "signature": "c8a8c45fb03581f3f2970e5bd27549ab00343b3f20c44453538ed820f82d6884ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632550", + "is_low_s": false, + "normalized": "c8a8c45fb03581f3f2970e5bd27549ab00343b3f20c44453538ed820f82d68840000000000000000000000000000000000000000000000000000000000000001", + "verifies": false + }, + { + "case": "s = 0", + "signature": "c8a8c45fb03581f3f2970e5bd27549ab00343b3f20c44453538ed820f82d68840000000000000000000000000000000000000000000000000000000000000000", + "is_low_s": false, + "normalized": "c8a8c45fb03581f3f2970e5bd27549ab00343b3f20c44453538ed820f82d68840000000000000000000000000000000000000000000000000000000000000000", + "verifies": false + }, + { + "case": "r = 0", + "signature": "000000000000000000000000000000000000000000000000000000000000000031b74472f1f634099623a52c2b777751dd0ff81eb81d54258d1b9b0f5033bb4d", + "is_low_s": false, + "normalized": "000000000000000000000000000000000000000000000000000000000000000031b74472f1f634099623a52c2b777751dd0ff81eb81d54258d1b9b0f5033bb4d", + "verifies": false + }, + { + "case": "r = n", + "signature": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc63255131b74472f1f634099623a52c2b777751dd0ff81eb81d54258d1b9b0f5033bb4d", + "is_low_s": false, + "normalized": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc63255131b74472f1f634099623a52c2b777751dd0ff81eb81d54258d1b9b0f5033bb4d", + "verifies": false + } + ], + "handshake": [ + { + "case": "verified", + "app": "example.com/app", + "room": "lobby", + "initiator": { + "peer_id": "m7oEQitmWEQ4WW5aqhKp", + "user_id": "8Qc8kjJP0X70oY14zVW6rM", + "endpoint": "endpoint-a", + "user": "user-a", + "sdp_local": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n", + "sdp_remote": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n" + }, + "responder": { + "peer_id": "izta8zhsZH7HVcLteLNl", + "user_id": "8oysJYYlxgfcFBn7jJOcpc", + "endpoint": "endpoint-b", + "user": "user-b", + "sdp_local": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n", + "sdp_remote": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n" + }, + "nonces": [ + "5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506", + "c0ffee00-1234-4abc-8def-0123456789ab" + ], + "messages": [ + { + "from": "A", + "step": 1, + "json": "{\"__trystero_id\":1,\"n\":\"5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506\",\"dtls\":[\"sha-1 11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44\",\"sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\"],\"uid\":\"8Qc8kjJP0X70oY14zVW6rM\",\"pk\":\"kgjdezuSTcFwdzLPIGjzikPkN1RIbbVGZBGJKR_sNwc.bhgBbRP9SgX5Sk1wscy_a5LHAkt6PT4vavX1vSHk_Xc\",\"uk\":\"jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k.QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPps\"}" + }, + { + "from": "B", + "step": 2, + "json": "{\"__trystero_id\":2,\"n\":\"c0ffee00-1234-4abc-8def-0123456789ab\",\"dtls\":[\"sha-256 0a:1b:2c:3d:4e:5f:60:71:82:93:a4:b5:c6:d7:e8:f9:0a:1b:2c:3d:4e:5f:60:71:82:93:a4:b5:c6:d7:e8:f9\"],\"uid\":\"8oysJYYlxgfcFBn7jJOcpc\",\"pk\":\"2XZTp64-PFwQbANbjsubzI5Ty7QLA3CYS31fBIV6APA.7N9iCYOqnNgUg0RD3Re0_74YUU5n99kH-5FvXSV5vBg\",\"uk\":\"Waxv1o6HG_FTAhR42yEwaNY7i_YvoH5OEP-RlINHVkQ.jY_OiIUOtPAedZkVLdLXylvw3O0vXRPi_OnpEZspzCw\",\"ps\":\"xoj5UqGMR8duyQzQBdES01oYfZTskbPsMJ2NRidRBNg9tKFneusIazxZZQk9fwL1vQk1E2-nl4coiRIfGFQ8CQ\",\"us\":\"IqTv3MG9H2buDNJN7YeTdja-LjAVwF_2BZL8adRyS3orYNMxn6xTh8cPm1BipNUx7HmATAKjEwhS9rVvHITV0A\"}" + }, + { + "from": "A", + "step": 3, + "json": "{\"__trystero_id\":3,\"ps\":\"saWD2e3IzdwI1XLYaJNydv0RHMBBbNIszXFYyx3alJUO2fog_yBKkpd19aC-TzVr7uIPSlhVW-KabBAeflypJw\",\"us\":\"kCivJlKg135n4UPn5zVLVFMPFzcKvcgrt0sdfamwNhwdhpuw_09dBGvqPz-L9BXwhRG0aVyi73WF4ihyN6QYkQ\"}" + } + ], + "initiator_error": null, + "responder_error": null, + "verified": { + "A": { + "peer_id": "izta8zhsZH7HVcLteLNl", + "user_id": "8oysJYYlxgfcFBn7jJOcpc" + }, + "B": { + "peer_id": "m7oEQitmWEQ4WW5aqhKp", + "user_id": "8Qc8kjJP0X70oY14zVW6rM" + } + }, + "transcript": "[\"trystero:id-hs:v2\",\"example.com/app\",\"lobby\",\"m7oEQitmWEQ4WW5aqhKp\",\"izta8zhsZH7HVcLteLNl\",\"5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506\",\"c0ffee00-1234-4abc-8def-0123456789ab\",[\"sha-1 11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44\",\"sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\"],[\"sha-256 0a:1b:2c:3d:4e:5f:60:71:82:93:a4:b5:c6:d7:e8:f9:0a:1b:2c:3d:4e:5f:60:71:82:93:a4:b5:c6:d7:e8:f9\"],\"8Qc8kjJP0X70oY14zVW6rM\",\"8oysJYYlxgfcFBn7jJOcpc\"]", + "transcript_digest": "db7fc1e8a4ad703cefe61f11f03886b3b616172c20a5c2a216a2462a4c24edd5", + "transcript_verified": { + "step2_endpoint": true, + "step2_user": true + } + }, + { + "case": "another remote fingerprint", + "app": "example.com/app", + "room": "lobby", + "initiator": { + "peer_id": "m7oEQitmWEQ4WW5aqhKp", + "user_id": "8Qc8kjJP0X70oY14zVW6rM", + "endpoint": "endpoint-a", + "user": "user-a", + "sdp_local": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n", + "sdp_remote": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n" + }, + "responder": { + "peer_id": "izta8zhsZH7HVcLteLNl", + "user_id": "8oysJYYlxgfcFBn7jJOcpc", + "endpoint": "endpoint-b", + "user": "user-b", + "sdp_local": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n", + "sdp_remote": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2B:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n" + }, + "nonces": [ + "5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506", + "c0ffee00-1234-4abc-8def-0123456789ab" + ], + "messages": [ + { + "from": "A", + "step": 1, + "json": "{\"__trystero_id\":1,\"n\":\"5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506\",\"dtls\":[\"sha-1 11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44\",\"sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\"],\"uid\":\"8Qc8kjJP0X70oY14zVW6rM\",\"pk\":\"kgjdezuSTcFwdzLPIGjzikPkN1RIbbVGZBGJKR_sNwc.bhgBbRP9SgX5Sk1wscy_a5LHAkt6PT4vavX1vSHk_Xc\",\"uk\":\"jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k.QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPps\"}" + } + ], + "initiator_error": "waits", + "responder_error": "Trystero: DTLS fingerprint mismatch", + "verified": {} + }, + { + "case": "a user id of another key", + "app": "example.com/app", + "room": "lobby", + "initiator": { + "peer_id": "m7oEQitmWEQ4WW5aqhKp", + "user_id": "8Qc8kjJP0X70oY14zVW6rM", + "endpoint": "endpoint-a", + "user": "user-a", + "sdp_local": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n", + "sdp_remote": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n" + }, + "responder": { + "peer_id": "izta8zhsZH7HVcLteLNl", + "user_id": "8oysJYYlxgfcFBn7jJOcpc", + "endpoint": "endpoint-b", + "user": "user-b", + "sdp_local": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n", + "sdp_remote": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n" + }, + "nonces": [ + "5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506", + "c0ffee00-1234-4abc-8def-0123456789ab" + ], + "messages": [ + { + "from": "A", + "step": 1, + "json": "{\"__trystero_id\":1,\"n\":\"5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506\",\"dtls\":[\"sha-1 11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44\",\"sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\"],\"uid\":\"8oysJYYlxgfcFBn7jJOcpc\",\"pk\":\"kgjdezuSTcFwdzLPIGjzikPkN1RIbbVGZBGJKR_sNwc.bhgBbRP9SgX5Sk1wscy_a5LHAkt6PT4vavX1vSHk_Xc\",\"uk\":\"jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k.QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPps\"}" + } + ], + "initiator_error": "waits", + "responder_error": "Trystero: peer identity verification failed", + "verified": {} + }, + { + "case": "an endpoint key of another peer id", + "app": "example.com/app", + "room": "lobby", + "initiator": { + "peer_id": "m7oEQitmWEQ4WW5aqhKp", + "user_id": "8Qc8kjJP0X70oY14zVW6rM", + "endpoint": "endpoint-a", + "user": "user-a", + "sdp_local": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n", + "sdp_remote": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n" + }, + "responder": { + "peer_id": "izta8zhsZH7HVcLteLNl", + "user_id": "8oysJYYlxgfcFBn7jJOcpc", + "endpoint": "endpoint-b", + "user": "user-b", + "sdp_local": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n", + "sdp_remote": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n" + }, + "nonces": [ + "5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506", + "c0ffee00-1234-4abc-8def-0123456789ab" + ], + "messages": [ + { + "from": "A", + "step": 1, + "json": "{\"__trystero_id\":1,\"n\":\"5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506\",\"dtls\":[\"sha-1 11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44\",\"sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\"],\"uid\":\"8Qc8kjJP0X70oY14zVW6rM\",\"pk\":\"kgjdezuSTcFwdzLPIGjzikPkN1RIbbVGZBGJKR_sNwc.bhgBbRP9SgX5Sk1wscy_a5LHAkt6PT4vavX1vSHk_Xc\",\"uk\":\"jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k.QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPps\"}" + }, + { + "from": "B", + "step": 2, + "json": "{\"__trystero_id\":2,\"n\":\"c0ffee00-1234-4abc-8def-0123456789ab\",\"dtls\":[\"sha-256 0a:1b:2c:3d:4e:5f:60:71:82:93:a4:b5:c6:d7:e8:f9:0a:1b:2c:3d:4e:5f:60:71:82:93:a4:b5:c6:d7:e8:f9\"],\"uid\":\"8oysJYYlxgfcFBn7jJOcpc\",\"pk\":\"kgjdezuSTcFwdzLPIGjzikPkN1RIbbVGZBGJKR_sNwc.bhgBbRP9SgX5Sk1wscy_a5LHAkt6PT4vavX1vSHk_Xc\",\"uk\":\"Waxv1o6HG_FTAhR42yEwaNY7i_YvoH5OEP-RlINHVkQ.jY_OiIUOtPAedZkVLdLXylvw3O0vXRPi_OnpEZspzCw\",\"ps\":\"tzg9WR33ggX2DqIPk2uS-bAvw5j9upFklbElHURcMMBV-5E6gVnTCLLIzt6Z9-WtxeHW5nsOl3g7BpWAJRA7ZA\",\"us\":\"PAd0ECqTGhpEPxDDCL9ysveQj-5MlpQV_DBn02VQ0wEfLZ97DwPwk0elfp5hZgZXqykfrDTz9xam_j7tpyENuw\"}" + } + ], + "initiator_error": "Trystero: peer identity verification failed", + "responder_error": "waits", + "verified": {} + }, + { + "case": "a short nonce", + "app": "example.com/app", + "room": "lobby", + "initiator": { + "peer_id": "m7oEQitmWEQ4WW5aqhKp", + "user_id": "8Qc8kjJP0X70oY14zVW6rM", + "endpoint": "endpoint-a", + "user": "user-a", + "sdp_local": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n", + "sdp_remote": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n" + }, + "responder": { + "peer_id": "izta8zhsZH7HVcLteLNl", + "user_id": "8oysJYYlxgfcFBn7jJOcpc", + "endpoint": "endpoint-b", + "user": "user-b", + "sdp_local": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n", + "sdp_remote": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n" + }, + "nonces": [ + "5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506", + "c0ffee00-1234-4abc-8def-0123456789ab" + ], + "messages": [ + { + "from": "A", + "step": 1, + "json": "{\"__trystero_id\":1,\"n\":\"0123456789abcde\",\"dtls\":[\"sha-1 11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44\",\"sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\"],\"uid\":\"8Qc8kjJP0X70oY14zVW6rM\",\"pk\":\"kgjdezuSTcFwdzLPIGjzikPkN1RIbbVGZBGJKR_sNwc.bhgBbRP9SgX5Sk1wscy_a5LHAkt6PT4vavX1vSHk_Xc\",\"uk\":\"jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k.QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPps\"}" + } + ], + "initiator_error": "waits", + "responder_error": "Trystero: peer identity verification failed", + "verified": {} + }, + { + "case": "a user signature of another key", + "app": "example.com/app", + "room": "lobby", + "initiator": { + "peer_id": "m7oEQitmWEQ4WW5aqhKp", + "user_id": "8Qc8kjJP0X70oY14zVW6rM", + "endpoint": "endpoint-a", + "user": "user-a", + "sdp_local": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n", + "sdp_remote": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n" + }, + "responder": { + "peer_id": "izta8zhsZH7HVcLteLNl", + "user_id": "8oysJYYlxgfcFBn7jJOcpc", + "endpoint": "endpoint-b", + "user": "user-b", + "sdp_local": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n", + "sdp_remote": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n" + }, + "nonces": [ + "5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506", + "c0ffee00-1234-4abc-8def-0123456789ab" + ], + "messages": [ + { + "from": "A", + "step": 1, + "json": "{\"__trystero_id\":1,\"n\":\"5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506\",\"dtls\":[\"sha-1 11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44\",\"sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\"],\"uid\":\"8Qc8kjJP0X70oY14zVW6rM\",\"pk\":\"kgjdezuSTcFwdzLPIGjzikPkN1RIbbVGZBGJKR_sNwc.bhgBbRP9SgX5Sk1wscy_a5LHAkt6PT4vavX1vSHk_Xc\",\"uk\":\"jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k.QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPps\"}" + }, + { + "from": "B", + "step": 2, + "json": "{\"__trystero_id\":2,\"n\":\"c0ffee00-1234-4abc-8def-0123456789ab\",\"dtls\":[\"sha-256 0a:1b:2c:3d:4e:5f:60:71:82:93:a4:b5:c6:d7:e8:f9:0a:1b:2c:3d:4e:5f:60:71:82:93:a4:b5:c6:d7:e8:f9\"],\"uid\":\"8oysJYYlxgfcFBn7jJOcpc\",\"pk\":\"2XZTp64-PFwQbANbjsubzI5Ty7QLA3CYS31fBIV6APA.7N9iCYOqnNgUg0RD3Re0_74YUU5n99kH-5FvXSV5vBg\",\"uk\":\"Waxv1o6HG_FTAhR42yEwaNY7i_YvoH5OEP-RlINHVkQ.jY_OiIUOtPAedZkVLdLXylvw3O0vXRPi_OnpEZspzCw\",\"ps\":\"CXNVYawWseUv7GMyVOaoYnTVVOUJ9H7iwpFDPLRw9Conm6EYqntGA9GiGqYLH2-DJnD_yDI-U2-kgW6hl4ZoNg\",\"us\":\"CXNVYawWseUv7GMyVOaoYnTVVOUJ9H7iwpFDPLRw9Conm6EYqntGA9GiGqYLH2-DJnD_yDI-U2-kgW6hl4ZoNg\"}" + } + ], + "initiator_error": "Trystero: peer identity verification failed", + "responder_error": "waits", + "verified": {} + }, + { + "case": "a high-S endpoint signature", + "app": "example.com/app", + "room": "lobby", + "initiator": { + "peer_id": "m7oEQitmWEQ4WW5aqhKp", + "user_id": "8Qc8kjJP0X70oY14zVW6rM", + "endpoint": "endpoint-a", + "user": "user-a", + "sdp_local": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n", + "sdp_remote": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n" + }, + "responder": { + "peer_id": "izta8zhsZH7HVcLteLNl", + "user_id": "8oysJYYlxgfcFBn7jJOcpc", + "endpoint": "endpoint-b", + "user": "user-b", + "sdp_local": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n", + "sdp_remote": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n" + }, + "nonces": [ + "5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506", + "c0ffee00-1234-4abc-8def-0123456789ab" + ], + "messages": [ + { + "from": "A", + "step": 1, + "json": "{\"__trystero_id\":1,\"n\":\"5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506\",\"dtls\":[\"sha-1 11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44\",\"sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\"],\"uid\":\"8Qc8kjJP0X70oY14zVW6rM\",\"pk\":\"kgjdezuSTcFwdzLPIGjzikPkN1RIbbVGZBGJKR_sNwc.bhgBbRP9SgX5Sk1wscy_a5LHAkt6PT4vavX1vSHk_Xc\",\"uk\":\"jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k.QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPps\"}" + }, + { + "from": "B", + "step": 2, + "json": "{\"__trystero_id\":2,\"n\":\"c0ffee00-1234-4abc-8def-0123456789ab\",\"dtls\":[\"sha-256 0a:1b:2c:3d:4e:5f:60:71:82:93:a4:b5:c6:d7:e8:f9:0a:1b:2c:3d:4e:5f:60:71:82:93:a4:b5:c6:d7:e8:f9\"],\"uid\":\"8oysJYYlxgfcFBn7jJOcpc\",\"pk\":\"2XZTp64-PFwQbANbjsubzI5Ty7QLA3CYS31fBIV6APA.7N9iCYOqnNgUg0RD3Re0_74YUU5n99kH-5FvXSV5vBg\",\"uk\":\"Waxv1o6HG_FTAhR42yEwaNY7i_YvoH5OEP-RlINHVkQ.jY_OiIUOtPAedZkVLdLXylvw3O0vXRPi_OnpEZspzCw\",\"ps\":\"r3L3zOoMemI-F7b06SrooCiQxh9RJnfdPC3Nh7fXUul43HjYcm0rwYwGZCP8jpMlCeyfzj2874xkPTRabCyR6A\",\"us\":\"_I0E-_dTqVt3HjkAE4nm4Wq_Bhls3fjpg-slG-G74AZB3VDaCPFv9fzDpRjt5KKrErVyQo8mfzzgyuTZKy6suw\"}" + }, + { + "from": "A", + "step": 3, + "json": "{\"__trystero_id\":3,\"ps\":\"qUfkdmwIYOsSSUqR54nbxlm4TVfh8eng8edl1sypdIrE-Ui0bI5vmwNC9XSHru0PSHhycCfJEzykWMzlMzW44Q\",\"us\":\"M7glmr-vE4YbYZ2sK7GHKof2daOTPBbGv_tJB-7JUcpeFigIoebjU5ttShwNyzY2JgZhPwhH_knIPnkA4GgvnQ\"}" + } + ], + "initiator_error": null, + "responder_error": "Trystero: peer identity verification failed", + "verified": { + "A": { + "peer_id": "izta8zhsZH7HVcLteLNl", + "user_id": "8oysJYYlxgfcFBn7jJOcpc" + } + } + }, + { + "case": "no fingerprint in the remote description", + "app": "example.com/app", + "room": "lobby", + "initiator": { + "peer_id": "m7oEQitmWEQ4WW5aqhKp", + "user_id": "8Qc8kjJP0X70oY14zVW6rM", + "endpoint": "endpoint-a", + "user": "user-a", + "sdp_local": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n", + "sdp_remote": "v=0\r\n" + }, + "responder": { + "peer_id": "izta8zhsZH7HVcLteLNl", + "user_id": "8oysJYYlxgfcFBn7jJOcpc", + "endpoint": "endpoint-b", + "user": "user-b", + "sdp_local": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9 \r\n", + "sdp_remote": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0\r\na=fingerprint:sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44\r\na=fingerprint:sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\r\n" + }, + "nonces": [ + "5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506", + "c0ffee00-1234-4abc-8def-0123456789ab" + ], + "messages": [], + "initiator_error": "Trystero: DTLS fingerprint missing", + "responder_error": "waits", + "verified": {} + } + ], + "handshake_frames": [ + { + "case": "step 1", + "action": "@_hsdata", + "payload_json": "{\"__trystero_id\":1,\"n\":\"5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506\",\"dtls\":[\"sha-1 11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44\",\"sha-256 4f:2a:9c:11:00:7b:ee:31:58:aa:0d:6c:93:12:47:bf:c8:21:5e:70:66:d4:3a:91:0b:cf:28:7e:55:19:a3:f0\"],\"uid\":\"8Qc8kjJP0X70oY14zVW6rM\",\"pk\":\"kgjdezuSTcFwdzLPIGjzikPkN1RIbbVGZBGJKR_sNwc.bhgBbRP9SgX5Sk1wscy_a5LHAkt6PT4vavX1vSHk_Xc\",\"uk\":\"jvZjDhgPIgEdYwDOQsCb08EEkgBnKPNLJyapClNk4-k.QXtxS90uaruEu5CYnr-rgDhSZNDyHj_DQjjWJGcmPps\"}", + "frames": [ + { + "from": "A", + "size": 502, + "hex": "0310405f68736461746100000000000000000000000000000000000000000000000000007b225f5f747279737465726f5f6964223a312c226e223a2235613166306332652d386233642d346536662d396137302d623163326433653466353036222c2264746c73223a5b227368612d312031313a32323a33333a34343a35353a36363a37373a38383a39393a61613a62623a63633a64643a65653a66663a30303a31313a32323a33333a3434222c227368612d3235362034663a32613a39633a31313a30303a37623a65653a33313a35383a61613a30643a36633a39333a31323a34373a62663a63383a32313a35653a37303a36363a64343a33613a39313a30623a63663a32383a37653a35353a31393a61333a6630225d2c22756964223a22385163386b6a4a50305837306f5931347a565736724d222c22706b223a226b676a64657a755354634677647a4c5049476a7a696b506b4e315249626256475a42474a4b525f734e77632e626867426252503953675835536b31777363795f61354c48416b743650543476617658317653486b5f5863222c22756b223a226a765a6a44686750496745645977444f51734362303845456b67426e4b504e4c4a796170436c4e6b342d6b2e515874785339307561727545753543596e722d72674468535a4e4479486a5f44516a6a574a47636d507073227d" + } + ], + "delivered": true + }, + { + "case": "ready", + "action": "@_hsready", + "payload_json": "\"\"", + "frames": [ + { + "from": "A", + "size": 36, + "hex": "0300405f6873726561647900000000000000000000000000000000000000000000000000" + } + ], + "delivered": true + }, + { + "case": "room full", + "action": "@_hsready", + "payload_json": "{\"ok\":false,\"err\":\"room full\"}", + "frames": [ + { + "from": "A", + "size": 66, + "hex": "0310405f68737265616479000000000000000000000000000000000000000000000000007b226f6b223a66616c73652c22657272223a22726f6f6d2066756c6c227d" + } + ], + "delivered": true + }, + { + "case": "banned", + "action": "@_hsready", + "payload_json": "{\"ok\":false,\"err\":\"peer banned\",\"reason\":\"spam\"}", + "frames": [ + { + "from": "A", + "size": 84, + "hex": "0310405f68737265616479000000000000000000000000000000000000000000000000007b226f6b223a66616c73652c22657272223a22706565722062616e6e6564222c22726561736f6e223a227370616d227d" + } + ], + "delivered": true + } + ], + "ping_frames": { + "action": "@_ping", + "request_id": "0b1c2d3e-4f50-4617-8899-aabbccddeeff", + "response": "", + "frames": [ + { + "from": "A", + "size": 80, + "hex": "0300405f70696e670000000000000000000000000000000000000000000000000000002c7b2272223a2230623163326433652d346635302d343631372d383839392d616162626363646465656666227d" + }, + { + "from": "B", + "size": 80, + "hex": "0300405f726573706f6e736500000000000000000000000000000000000000000000002c7b2272223a2230623163326433652d346635302d343631372d383839392d616162626363646465656666227d" + } + ] + }, + "identity_limits": { + "pub_key_records": 4096, + "signature_cache_entries": 8192, + "signature_cache_bytes": 2097152, + "signature_cache_payload_bytes": 4096, + "handshake_timeout_ms": 10000, + "buffered_handshake_messages": 16, + "handshake_nonce_min_chars": 16, + "hsdata_max_payload_bytes": 65536, + "hsready_max_payload_bytes": 131072 + } +} diff --git a/test/fixtures/oracle/expected.json b/test/fixtures/oracle/expected.json new file mode 100644 index 0000000..8e4caeb --- /dev/null +++ b/test/fixtures/oracle/expected.json @@ -0,0 +1,494 @@ +{ + "event_messages": { + "secret_key": "ea25be8deb88b3e137d8e64800a8f1f323fdf2a5ec32e8d5f28fc5bafad693df", + "aux": "0b2845627f9cb9d6f3102d4a6784a1bedbf815324f6c89a6c3e0fd1a3754718e", + "created_at": 1759700000, + "events": [ + { + "topic": "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", + "content": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f", + "id": "5f62f6ad95b21def223138ceb6f082483211912df6adc7a7d5e09b1872a022da", + "message": "[\"EVENT\",{\"kind\":27537,\"tags\":[[\"x\",\"585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v\"]],\"created_at\":1759700000,\"content\":\"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"5f62f6ad95b21def223138ceb6f082483211912df6adc7a7d5e09b1872a022da\",\"sig\":\"7b8c58e0daf260c6acc79b6455a126cf7a55ef9ceac3c5011f7436f967334dcac34634c949e482477ecbd6258286667d4c991b724f82e56d7585a56d81109e5d\"}]" + }, + { + "topic": "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", + "content": "quote \" backslash \\ both \\\" solidus / space tilde ~", + "id": "484bfd2be609436d45f740791b9936e2cffaab24dba1689f956823e557557ccb", + "message": "[\"EVENT\",{\"kind\":27537,\"tags\":[[\"x\",\"585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v\"]],\"created_at\":1759700000,\"content\":\"quote \\\" backslash \\\\ both \\\\\\\" solidus / space tilde ~\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"484bfd2be609436d45f740791b9936e2cffaab24dba1689f956823e557557ccb\",\"sig\":\"071d4188d1fcee2fb4af1a0d5550b570d3dc996508f85c69055f3717cbc12717ff295a430f7d9586594f87ec875de8c6fa88fe10b676826a926e03a4dd6e37b1\"}]" + }, + { + "topic": "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", + "content": "line separator 
 paragraph separator 
 delete ", + "id": "c6ed4168c19d27b74b2248371feda643c6d926e62c88a42a5de5b946030d9f9c", + "message": "[\"EVENT\",{\"kind\":27537,\"tags\":[[\"x\",\"585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v\"]],\"created_at\":1759700000,\"content\":\"line separator 
 paragraph separator 
 delete \",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"c6ed4168c19d27b74b2248371feda643c6d926e62c88a42a5de5b946030d9f9c\",\"sig\":\"98d78f5b966dd48d9cf7dbeaf1c19b087d78541d62f4946fc9c5ae3411ebfe9593535e1deda46e922e2051a9062b48aeef371c47ea87d9fe1c70bb5c4cab9065\"}]" + }, + { + "topic": "585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v", + "content": "astral 🎉 𝄞, two bytes é € ߿, three ☕ ࠀ ￿", + "id": "bc2070739c362d6be6e2ab89a66d84412f459d7aa0f786a3b32785fe11560e78", + "message": "[\"EVENT\",{\"kind\":27537,\"tags\":[[\"x\",\"585q4w3ia403j31626l2p3k1p3kh6u2v2g5n4v\"]],\"created_at\":1759700000,\"content\":\"astral 🎉 𝄞, two bytes é € ߿, three ☕ ࠀ ￿\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"bc2070739c362d6be6e2ab89a66d84412f459d7aa0f786a3b32785fe11560e78\",\"sig\":\"494960b77cc8b52c024736acadddf33582ea36070155d93ed439be68f7e5db103a06ab47660a5c882587f05473e2280be160c12a4f47e7ffb82d5548464a8c1e\"}]" + }, + { + "topic": "topic \u0000 \u001f \" \\ 
 
  🎉", + "content": "{\"peerId\":\"abc\",\"nonce\":\"12345678\"}", + "id": "85af94110ce9b15832bfd9068dd48f72cd34c143e0284e9ad41db661e93e16a5", + "message": "[\"EVENT\",{\"kind\":27604,\"tags\":[[\"x\",\"topic \\u0000 \\u001f \\\" \\\\ 
 
  🎉\"]],\"created_at\":1759700000,\"content\":\"{\\\"peerId\\\":\\\"abc\\\",\\\"nonce\\\":\\\"12345678\\\"}\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"85af94110ce9b15832bfd9068dd48f72cd34c143e0284e9ad41db661e93e16a5\",\"sig\":\"75a933375f57d3a4e1677b6463cd404bbfb649f1ee4b9337d9c3e53c20cfa75065dae4e29ffd48beeb5d996efd95af9c1b89002c70d6c046844bd5a2d3a43ec4\"}]" + }, + { + "topic": "", + "content": "", + "id": "b3b52a52fdc022396fc44405ebf08bf1ada81fbc14be2fe7e5ea6f903f9664d7", + "message": "[\"EVENT\",{\"kind\":26261,\"tags\":[[\"x\",\"\"]],\"created_at\":1759700000,\"content\":\"\",\"pubkey\":\"162ce256bae9f15d702b9d933909fa9f31e93b38cf4bc8f62591026fd00259a5\",\"id\":\"b3b52a52fdc022396fc44405ebf08bf1ada81fbc14be2fe7e5ea6f903f9664d7\",\"sig\":\"dd00b9cd61eb66bb2da975ee7faf02972e9afdd6d5443c52a92e877aece0051f035d53b8d70bd563362967afc5b44f3c3912a4989351376812ba7a34c12833b8\"}]" + } + ] + }, + "nostr_events": [ + { + "pubkey": "4f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa", + "created_at": 1759700000, + "kind": 28500, + "topic": "OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns", + "content": "{\"peerId\":\"abc\",\"nonce\":\"12345678\"}", + "id": "5bfd86a6da55234ea94d913caa855eb474b07f09d9710a2bab1d471d4b806f0e" + }, + { + "pubkey": "4f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa", + "created_at": 1759700000, + "kind": 28500, + "topic": "OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns", + "content": "quote \" backslash \\ newline \n tab \t unicode é ☕ 🎉 control \u0001", + "id": "2ecae57c4da4bd5f2fe0c5265f1ec8e2347653cc67591b4def58f673940f6059" + }, + { + "pubkey": "4f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa", + "created_at": 1759700000, + "kind": 28500, + "topic": "OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns", + "content": "", + "id": "56801788c27a326e68199a55b1b79331f948671f5a62c7ca02d8e8059d22865e" + } + ], + "signal_texts": [ + { + "signal": { + "peerId": "\u0000\u0001\u001f", + "nonce": "\" \\ 
 
  🎉" + }, + "text": "{\"peerId\":\"\\u0000\\u0001\\u001f\",\"nonce\":\"\\\" \\\\ 
 
  🎉\"}", + "read": null + }, + { + "signal": { + "peerId": "\b\f\n\r\t\u000b", + "nonce": "n0nce" + }, + "text": "{\"peerId\":\"\\b\\f\\n\\r\\t\\u000b\",\"nonce\":\"n0nce\"}", + "read": null + }, + { + "signal": { + "peerId": "peerAAAAAAAAAAAAAAAA", + "offerId": "o", + "offer": "🎉\u0000𝄞 é" + }, + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"offer\":\"🎉\\u0000𝄞 é\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA", + "offer": "🎉\u0000𝄞 é", + "offer_id": "o" + } + }, + { + "signal": { + "peerId": "peerAAAAAAAAAAAAAAAA", + "offerId": "o", + "candidate": "\u001f  € \"\\" + }, + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"candidate\":\"\\u001f  € \\\"\\\\\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA", + "candidate": "\u001f  € \"\\", + "offer_id": "o" + } + }, + { + "signal": { + "peerId": "q\"\\\n", + "offerId": "o", + "answer": "
\u0000" + }, + "text": "{\"peerId\":\"q\\\"\\\\\\n\",\"offerId\":\"o\",\"answer\":\"
\\u0000\"}", + "read": null + }, + { + "signal": { + "peerId": "peerBBBBBBBBBBBBBBBB", + "offerId": "o", + "answer": "sealed " + }, + "text": "{\"peerId\":\"peerBBBBBBBBBBBBBBBB\",\"offerId\":\"o\",\"answer\":\"sealed \"}", + "read": { + "peer_id": "peerBBBBBBBBBBBBBBBB", + "answer": "sealed ", + "offer_id": "o" + } + }, + { + "signal": { + "peerId": "peerBBBBBBBBBBBBBBBB", + "offerId": "o", + "candidate": "

" + }, + "text": "{\"peerId\":\"peerBBBBBBBBBBBBBBBB\",\"offerId\":\"o\",\"candidate\":\"

\"}", + "read": { + "peer_id": "peerBBBBBBBBBBBBBBBB", + "candidate": "

", + "offer_id": "o" + } + } + ], + "duplicate_keys": { + "self_id": "oracleSelf0000000000", + "signals": [ + { + "text": "{\"peerId\":\"peerBBBBBBBBBBBBBBBB\",\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"nonce\":\"n\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA" + } + }, + { + "text": "{\"peerId\":\"peerBBBBBBBBBBBBBBBB\",\"peer\\u0049d\":\"peerAAAAAAAAAAAAAAAA\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA" + } + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"first\",\"offer\":\"first\",\"offerId\":\"last\",\"offer\":\"last\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA", + "offer": "last", + "offer_id": "last" + } + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"offer\":\"\",\"offer\":\"sealed\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA", + "offer": "sealed", + "offer_id": "o" + } + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"offer\":\"sealed\",\"offer\":\"\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"candidate\":1,\"candidate\":\"sealed\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA", + "candidate": "sealed", + "offer_id": "o" + } + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"answer\":\"sealed\",\"answer\":null}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"not an id\",\"offerId\":\"o\",\"answer\":\"sealed\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA", + "answer": "sealed", + "offer_id": "o" + } + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"nonce\":\"a\",\"nonce\":\"b\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA" + } + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"peerId\":\"\"}", + "read": null + }, + { + "text": "{\"peerId\":\"\",\"offerId\":\"o\",\"answer\":\"sealed\",\"peerId\":\"peerAAAAAAAAAAAAAAAA\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA", + "answer": "sealed", + "offer_id": "o" + } + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"peer\":\"x\",\"offerId\":\"o\",\"offer\":\"sealed\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"peer\":null,\"nonce\":\"n\"}", + "read": null + } + ], + "root_topic": "OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns", + "events": [ + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns\"]],\"content\":\"{\\\"peerId\\\":\\\"contentFirst00000000\\\",\\\"offerId\\\":\\\"o\\\",\\\"answer\\\":\\\"x\\\"}\",\"content\":\"{\\\"peerId\\\":\\\"contentLast000000000\\\",\\\"offerId\\\":\\\"o\\\",\\\"answer\\\":\\\"x\\\"}\"}]", + "acted": "contentLast000000000" + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns\"]],\"content\":\"{\\\"peerId\\\":\\\"escapedFirst00000000\\\",\\\"offerId\\\":\\\"o\\\",\\\"answer\\\":\\\"x\\\"}\",\"con\\u0074ent\":\"{\\\"peerId\\\":\\\"escapedLast000000000\\\",\\\"offerId\\\":\\\"o\\\",\\\"answer\\\":\\\"x\\\"}\"}]", + "acted": "escapedLast000000000" + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"another-topic\"]],\"content\":\"{\\\"peerId\\\":\\\"rootTagsLast00000000\\\",\\\"offerId\\\":\\\"o\\\",\\\"answer\\\":\\\"x\\\"}\",\"tags\":[[\"x\",\"OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns\"]]}]", + "acted": "rootTagsLast00000000" + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns\"]],\"content\":\"{\\\"peerId\\\":\\\"rootTagsFirst0000000\\\",\\\"offerId\\\":\\\"o\\\",\\\"answer\\\":\\\"x\\\"}\",\"tags\":[[\"x\",\"another-topic\"]]}]", + "acted": null + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns\"]],\"content\":7,\"content\":\"{\\\"peerId\\\":\\\"textContentLast00000\\\",\\\"offerId\\\":\\\"o\\\",\\\"answer\\\":\\\"x\\\"}\"}]", + "acted": "textContentLast00000" + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns\"]],\"content\":\"{\\\"peerId\\\":\\\"textContentFirst0000\\\",\\\"offerId\\\":\\\"o\\\",\\\"answer\\\":\\\"x\\\"}\",\"content\":7}]", + "acted": null + } + ] + }, + "signal_envelopes": { + "self_id": "oracleSelf0000000000", + "signals": [ + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAA\",\"nonce\":\"n\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAAA\",\"nonce\":\"n\"}", + "read": null + }, + { + "text": "{\"peerId\":\"pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp\",\"nonce\":\"n\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAA-\",\"nonce\":\"n\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAé\",\"nonce\":\"n\"}", + "read": null + }, + { + "text": "{\"peerId\":5,\"nonce\":\"n\"}", + "read": null + }, + { + "text": "{\"peerId\":null,\"nonce\":\"n\"}", + "read": null + }, + { + "text": "{\"offerId\":\"o\",\"answer\":\"sealed\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"not an id\",\"answer\":\"sealed\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\",\"answer\":\"sealed\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"\",\"answer\":\"sealed\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":5,\"answer\":\"sealed\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":null,\"answer\":\"sealed\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"oé\",\"answer\":\"sealed\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offer\":\"sealed\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"answer\":\"sealed\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"candidate\":\"sealed\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"\",\"nonce\":\"n\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":5,\"nonce\":\"n\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"candidate\":\"ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"candidate\":\"😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀c\"}", + "read": null + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\",\"answer\":\"sealed\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA", + "answer": "sealed", + "offer_id": "oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" + } + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"a_.~:!-Z9\",\"answer\":\"sealed\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA", + "answer": "sealed", + "offer_id": "a_.~:!-Z9" + } + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"candidate\":\"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA", + "candidate": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "offer_id": "o" + } + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"candidate\":\"😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA", + "candidate": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀", + "offer_id": "o" + } + }, + { + "text": "{\"peerId\":\"peerAAAAAAAAAAAAAAAA\",\"offerId\":\"o\",\"nonce\":\"n\"}", + "read": { + "peer_id": "peerAAAAAAAAAAAAAAAA" + } + } + ], + "root_topic": "OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns", + "events": [ + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns\"]],\"content\":\"{\\\"peerId\\\":\\\"envShort00000000000\\\",\\\"offerId\\\":\\\"o\\\",\\\"answer\\\":\\\"x\\\"}\"}]", + "acted": null + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns\"]],\"content\":\"{\\\"peerId\\\":\\\"envNotAscii00000000é\\\",\\\"offerId\\\":\\\"o\\\",\\\"answer\\\":\\\"x\\\"}\"}]", + "acted": null + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns\"]],\"content\":\"{\\\"peerId\\\":\\\"envSpace000000000000\\\",\\\"offerId\\\":\\\"not an id\\\",\\\"answer\\\":\\\"x\\\"}\"}]", + "acted": null + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns\"]],\"content\":\"{\\\"peerId\\\":\\\"envLong0000000000000\\\",\\\"offerId\\\":\\\"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\\\",\\\"answer\\\":\\\"x\\\"}\"}]", + "acted": null + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns\"]],\"content\":\"{\\\"peerId\\\":\\\"envNumber00000000000\\\",\\\"offerId\\\":5,\\\"answer\\\":\\\"x\\\"}\"}]", + "acted": null + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns\"]],\"content\":\"{\\\"peerId\\\":\\\"envMissing0000000000\\\",\\\"answer\\\":\\\"x\\\"}\"}]", + "acted": null + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns\"]],\"content\":\"{\\\"peerId\\\":\\\"envLongest0000000000\\\",\\\"offerId\\\":\\\"oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\\\",\\\"answer\\\":\\\"x\\\"}\"}]", + "acted": "envLongest0000000000" + }, + { + "text": "[\"EVENT\",\"sub\",{\"tags\":[[\"x\",\"OteOXmT4_REZm4Lt7jSQVD5OVHgqpYvse6W5hmnx4Ns\"]],\"content\":\"{\\\"peerId\\\":\\\"envChars000000000000\\\",\\\"offerId\\\":\\\"a_.~:!-Z9\\\",\\\"answer\\\":\\\"x\\\"}\"}]", + "acted": "envChars000000000000" + } + ] + }, + "answerer": { + "self_id": "5JuBmYeQ3ItAlXdP1Hs8", + "app_id": "my-app", + "room_id": "room-1", + "offer_sdp": "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=offer\r\n", + "answer_sdp": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\ns=answer\r\n", + "candidate": "{\"candidate\":\"candidate:1 1 udp 2122260223 192.0.2.1 54400 typ host\",\"sdpMid\":\"0\",\"sdpMLineIndex\":0,\"usernameFragment\":\"uf\"}", + "cases": [ + { + "offer": "{\"peerId\":\"zzzzzzzzzzzzzzzzzzz1\",\"offerId\":\"o.~:!-_Az09\",\"offer\":\"ByZFZIOiweD_Hj1czCbhDWMyzQVIlzZ1SGFX75b2Wbs2bi0oo-qi82pwMzv2Ym4M-BnaI5WOKlxbYm70OA7XAfzZF68\"}", + "published": [ + { + "topic": "aBpCgjuITmJIKuHsnl_kv5m-JTBugyy-R1sVilnwR8E", + "text": "{\"peerId\":\"5JuBmYeQ3ItAlXdP1Hs8\",\"offerId\":\"o.~:!-_Az09\",\"answer\":\"ByZFZIOiweD_Hj1czCbhDWMyzQVIlTZzSGFX75b2Wbs2bi0oo-qi82pwMzv2bGYZ6g6lJPSx4zAGOLqObTea72E90G6Z\"}", + "sealed": "ByZFZIOiweD_Hj1czCbhDWMyzQVIlTZzSGFX75b2Wbs2bi0oo-qi82pwMzv2bGYZ6g6lJPSx4zAGOLqObTea72E90G6Z", + "plaintext": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\ns=answer\r\n" + }, + { + "topic": "aBpCgjuITmJIKuHsnl_kv5m-JTBugyy-R1sVilnwR8E", + "text": "{\"peerId\":\"5JuBmYeQ3ItAlXdP1Hs8\",\"offerId\":\"o.~:!-_Az09\",\"candidate\":\"ByZFZIOiweD_Hj1cwTmyYQc5mUwJ0nNlUgp6rrHCBP9mKH88ouSj_S4ZSWj5PDpYr13nG8xwOqbe-NGeZiVXYJ9IF0sfRJNff3KUi_MMAKSmw3e0dmw4MEIbX8s9Vd2Bpm_Dq1lmACeT_OUnT228nqwfNY3TiGPtrw7Qx1O8u69GHwSyc21W2_-z_9Tu53IeLrgvLFxr3rA\"}", + "sealed": "ByZFZIOiweD_Hj1cwTmyYQc5mUwJ0nNlUgp6rrHCBP9mKH88ouSj_S4ZSWj5PDpYr13nG8xwOqbe-NGeZiVXYJ9IF0sfRJNff3KUi_MMAKSmw3e0dmw4MEIbX8s9Vd2Bpm_Dq1lmACeT_OUnT228nqwfNY3TiGPtrw7Qx1O8u69GHwSyc21W2_-z_9Tu53IeLrgvLFxr3rA", + "plaintext": "{\"candidate\":\"candidate:1 1 udp 2122260223 192.0.2.1 54400 typ host\",\"sdpMid\":\"0\",\"sdpMLineIndex\":0,\"usernameFragment\":\"uf\"}" + } + ] + }, + { + "offer": "{\"peerId\":\"zzzzzzzzzzzzzzzzzzz2\",\"offerId\":\"OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO\",\"offer\":\"ByZFZIOiweD_Hj1czCbhDWMyzQVIlzZ1SGFX75b2Wbs2bi0oo-qi82pwMzv2Ym4M-BnaI37Nf_D_fShG2dNdn5_aKiI\"}", + "published": [ + { + "topic": "Ur_XL0y25p_rypqf7d6czhZAyZtP1TXJ3Do1iHR4HEA", + "text": "{\"peerId\":\"5JuBmYeQ3ItAlXdP1Hs8\",\"offerId\":\"OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO\",\"answer\":\"ByZFZIOiweD_Hj1czCbhDWMyzQVIlTZzSGFX75b2Wbs2bi0oo-qi82pwMzv2bGYZ6g6lJPShY3mz7FjvZNNGnoV_YEhE\"}", + "sealed": "ByZFZIOiweD_Hj1czCbhDWMyzQVIlTZzSGFX75b2Wbs2bi0oo-qi82pwMzv2bGYZ6g6lJPShY3mz7FjvZNNGnoV_YEhE", + "plaintext": "v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\ns=answer\r\n" + }, + { + "topic": "Ur_XL0y25p_rypqf7d6czhZAyZtP1TXJ3Do1iHR4HEA", + "text": "{\"peerId\":\"5JuBmYeQ3ItAlXdP1Hs8\",\"offerId\":\"OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO\",\"candidate\":\"ByZFZIOiweD_Hj1cwTmyYQc5mUwJ0nNlUgp6rrHCBP9mKH88ouSj_S4ZSWj5PDpYr13nG8xwOqbe-NGeZiVXYJ9IF0sfRJNff3KUi_MMAKSmw3e0dmw4MEIbX8s9Vd2Bpm_Dq1lmACeT_OUnT228nqwfNY3TiGPtrw7Qx1O8u69GHwSyc21W2xVcEDUPR4ZhvTim36IJU4Y\"}", + "sealed": "ByZFZIOiweD_Hj1cwTmyYQc5mUwJ0nNlUgp6rrHCBP9mKH88ouSj_S4ZSWj5PDpYr13nG8xwOqbe-NGeZiVXYJ9IF0sfRJNff3KUi_MMAKSmw3e0dmw4MEIbX8s9Vd2Bpm_Dq1lmACeT_OUnT228nqwfNY3TiGPtrw7Qx1O8u69GHwSyc21W2xVcEDUPR4ZhvTim36IJU4Y", + "plaintext": "{\"candidate\":\"candidate:1 1 udp 2122260223 192.0.2.1 54400 typ host\",\"sdpMid\":\"0\",\"sdpMLineIndex\":0,\"usernameFragment\":\"uf\"}" + } + ] + } + ] + }, + "payload_texts": [ + { + "text": "{\"b\":1,\"a\":2,\"10\":3,\"2\":4,\"-1\":5,\"01\":6,\"1.5\":7,\"4294967294\":8,\"4294967295\":9,\"0\":10}", + "written": "{\"0\":10,\"2\":4,\"10\":3,\"4294967294\":8,\"b\":1,\"a\":2,\"-1\":5,\"01\":6,\"1.5\":7,\"4294967295\":9}" + }, + { + "text": "{\"z\":{\"y\":[1,{\"3\":true,\"x\":null,\"1\":false}],\"0\":\"\"},\"a\":[]}", + "written": "{\"z\":{\"0\":\"\",\"y\":[1,{\"1\":false,\"3\":true,\"x\":null}]},\"a\":[]}" + }, + { + "text": "[0,-0,1,-1,100,1E3,1e+2,12e-1,0.1,1.5,123.45,0.30000000000000004,1e20,1e21,123e19,0.000001,1e-6,1e-7,2.5e-8]", + "written": "[0,0,1,-1,100,1000,100,1.2,0.1,1.5,123.45,0.30000000000000004,100000000000000000000,1e+21,1.23e+21,0.000001,0.000001,1e-7,2.5e-8]" + }, + { + "text": "[1.5e300,-1.5e-300,5e-324,1.7976931348623157e308,9007199254740991,-9007199254740991,4294967296]", + "written": "[1.5e+300,-1.5e-300,5e-324,1.7976931348623157e+308,9007199254740991,-9007199254740991,4294967296]" + }, + { + "text": "[\"\\u2028\\u0000\\u007f é 🎉\\\"\\\\/\",true,false,null,{}]", + "written": "[\"
\\u0000 é 🎉\\\"\\\\/\",true,false,null,{}]" + } + ], + "payload_beyond_doubles": [ + { + "text": "[9007199254740993,-9223372036854775808,0.1000000000000000055511151231257827,1e400]", + "written": "[9007199254740992,-9223372036854776000,0.1,null]" + } + ] +} diff --git a/test/handshake_manager_test.cpp b/test/handshake_manager_test.cpp new file mode 100644 index 0000000..80327a1 --- /dev/null +++ b/test/handshake_manager_test.cpp @@ -0,0 +1,327 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A room's handshakes alone, 0.27.0's handshake manager (`handshake.ts`'s +// `createHandshakeManager`): who initiates, the ready frame before the join, the join once both +// sides are ready, the 16 buffered messages, the 10 s on the virtual clock, and a clear that fails +// a waiting step. The bench records each call the manager makes of its room, and clears a failed +// peer from within the call, as a room does. + +#include + +#include "support/memory_backend.hpp" + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cases.hpp" +#include "require.hpp" + +namespace asio = webcpp::asio; +namespace trystero = webcpp::trystero; +namespace detail = webcpp::trystero::detail; +using namespace std::chrono_literals; +using phase = detail::handshake_manager::phase; + +namespace { + +/** A manager of the handshakes of `self`, on the virtual clock, and what it asked of its room. */ +struct bench { + asio::io_context io; + trystero::test::memory_network net{io}; + // The virtual clock starts with the network's first timer: one made here, so that the clock + // moves with advance() from the start. + std::shared_ptr clock_start; + /** Each call of the room, in order: "steps initiator|responder", "passed ", + * "admit ", "ready ", "activate ", "failed : ". */ + std::vector calls; + /** The steps that run, by peer: `finish` ends them. */ + std::map, std::less<>> steps; + std::shared_ptr hs; + + explicit bench(std::string_view self = "M", bool defer_responder_ready = false) { + net.virtual_clock = true; + auto* const memory = std::pmr::get_default_resource(); + clock_start = net.make_timer(memory); + hs = std::make_shared( + self, defer_responder_ready, + detail::handshake_callbacks{ + .run_steps = + [this](std::string_view peer, bool initiator, + trystero::handler done) { + calls.push_back("steps " + std::string(peer) + + (initiator ? " initiator" : " responder")); + steps.insert_or_assign(std::string(peer), std::move(done)); + }, + .send_ready = + [this](std::string_view peer, std::string_view json) { + calls.push_back("ready " + std::string(peer) + " " + std::string(json)); + }, + .local_passed = + [this](std::string_view peer) { + calls.push_back("passed " + std::string(peer)); + return true; + }, + .admit = + [this](std::string_view peer) { + calls.push_back("admit " + std::string(peer)); + return true; + }, + .activate = + [this](std::string_view peer) { + calls.push_back("activate " + std::string(peer)); + }, + .failed = + [this](std::string_view peer, std::string_view reason) { + calls.push_back("failed " + std::string(peer) + ": " + std::string(reason)); + hs->clear(peer); // as a room lets the peer go + }, + }, + net, memory); + } + + /** Adds and starts `peer`'s handshake. */ + void begin(std::string_view peer) const { + hs->add(peer); + hs->start(peer); + } + + /** Ends `peer`'s steps: "" passes them. */ + void finish(std::string_view peer, std::string_view reason = {}) { + const auto it = steps.find(peer); + webcpp::test::require(BOOST_TEST(it != steps.end())); + auto done = std::move(it->second); + steps.erase(it); + done(reason); + } + + /** How many of the calls start with `prefix`. */ + [[nodiscard]] std::size_t count(std::string_view prefix) const { + return static_cast(std::ranges::count_if( + calls, [prefix](const std::string& c) { return c.starts_with(prefix); })); + } + + void advance(std::chrono::milliseconds by) { + if (!net.advance(by)) { + BOOST_ERROR("the virtual clock fired max_steps timers without moving past them"); + } + } +}; + +// The side whose id is lower initiates, in UTF-16 code unit order, as 0.27.0's `effectiveSelfId < +// id` compares its ids: "Z" is below "a", whatever the letters' case says, and U+FF21, one code +// unit, is above U+1F600, whose first unit is a surrogate, though its UTF-8 bytes are below. +void the_lower_id_initiates() { + const bench b("M"); + b.begin("A"); + b.begin("Z"); + BOOST_TEST(b.calls == (std::vector{"steps A responder", "steps Z initiator"})); + const bench upper("Z"); + upper.begin("a"); + const bench lower("a"); + lower.begin("Z"); + BOOST_TEST(upper.calls == (std::vector{"steps a initiator"})); + BOOST_TEST(lower.calls == (std::vector{"steps Z responder"})); + const std::string fullwidth = "\xef\xbc\xa1"; // U+FF21, UTF-16 FF21 + const std::string emoji = "\xf0\x9f\x98\x80"; // U+1F600, UTF-16 D83D DE00 + BOOST_TEST(fullwidth < emoji); // in bytes + const bench wide(fullwidth); + wide.begin(emoji); + const bench astral(emoji); + astral.begin(fullwidth); + BOOST_TEST(wide.calls == (std::vector{"steps " + emoji + " responder"})); + BOOST_TEST(astral.calls == (std::vector{"steps " + fullwidth + " initiator"})); + // A peer is started once: a second start, or a start before its add, runs nothing. + b.hs->start("A"); + b.hs->start("N"); + BOOST_TEST_EQ(b.count("steps"), 2U); +} + +// With the peer's ready frame in, the steps' end sends this side's ready frame, empty, before the +// peer joins: the room's join, and what its listeners send, follow the frame. +void ready_goes_before_activate() { + bench b; + b.hs->add("A"); + b.hs->receive_ready("A"); // kept until the steps pass + b.hs->start("A"); + BOOST_TEST(b.hs->phase_of("A") == phase::running_steps); + b.finish("A"); + BOOST_TEST(b.calls == (std::vector{"steps A responder", "passed A", "admit A", + "ready A ", "activate A"})); + BOOST_TEST(b.hs->phase_of("A") == phase::active); +} + +// Either side may be ready first: the peer joins once both are, and once only. +void both_ready_activate_once() { + bench b; + b.begin("A"); + b.finish("A"); + BOOST_TEST(b.hs->phase_of("A") == phase::awaiting_peer_ready); + BOOST_TEST_EQ(b.count("ready A"), 1U); + BOOST_TEST_EQ(b.count("activate"), 0U); + b.hs->receive_ready("A"); + b.hs->receive_ready("A"); + BOOST_TEST_EQ(b.count("activate A"), 1U); + BOOST_TEST(b.hs->phase_of("A") == phase::active); + + b.begin("B"); + b.hs->receive_ready("B"); + b.hs->receive_ready("B"); + BOOST_TEST_EQ(b.count("activate B"), 0U); + b.finish("B"); + b.hs->receive_ready("B"); + BOOST_TEST_EQ(b.count("activate B"), 1U); + BOOST_TEST_EQ(b.count("ready B"), 1U); +} + +// A deferred responder, 0.27.0's deferResponderReady (a room with max_users), admits the peer and +// sends its ready frame only once the initiator's arrived; an initiator does not wait. +void a_deferred_responder_waits_for_the_initiators_ready() { + bench b("M", true); + b.begin("A"); // M responds to A + b.finish("A"); + BOOST_TEST(b.hs->phase_of("A") == phase::awaiting_remote_ready); + BOOST_TEST_EQ(b.count("admit"), 0U); + b.hs->receive_ready("A"); + BOOST_TEST((std::vector(b.calls.end() - 3, b.calls.end())) == + (std::vector{"admit A", "ready A ", "activate A"})); + b.begin("Z"); // M initiates with Z + b.finish("Z"); + BOOST_TEST(b.hs->phase_of("Z") == phase::awaiting_peer_ready); + BOOST_TEST_EQ(b.count("ready Z"), 1U); +} + +// Messages wait for the steps in order, 16 at most: a 17th fails the handshake, with 0.27.0's +// reason. A message a step waits for goes to it at once, and is not buffered. +void a_17th_buffered_message_fails_the_handshake() { + bench b; + b.hs->add("A"); + b.hs->receive_data("A", "m0"); // before the start, kept too + b.hs->start("A"); + for (std::size_t i = 1; i < detail::handshake_manager::max_buffered_messages; ++i) { + b.hs->receive_data("A", "m" + std::to_string(i)); + } + BOOST_TEST_EQ(b.count("failed"), 0U); + std::vector read; + const auto next = [&read](boost::system::error_code ec, std::string_view json) { + BOOST_TEST(!ec); + read.emplace_back(json); + }; + b.hs->next_message("A", next); + b.hs->next_message("A", next); + BOOST_TEST(read == (std::vector{"m0", "m1"})); + b.hs->receive_data("A", "m16"); + b.hs->receive_data("A", "m17"); + BOOST_TEST_EQ(b.count("failed"), 0U); + b.hs->receive_data("A", "m18"); + BOOST_TEST(b.calls.back() == "failed A: too many pending handshake messages"); + BOOST_TEST(!b.hs->phase_of("A").has_value()); + + const bench waiting; + waiting.begin("A"); + std::vector got; + waiting.hs->next_message("A", [&got](boost::system::error_code ec, std::string_view json) { + BOOST_TEST(!ec); + got.emplace_back(json); + }); + for (std::size_t i = 0; i <= detail::handshake_manager::max_buffered_messages; ++i) { + waiting.hs->receive_data("A", "w" + std::to_string(i)); + } + BOOST_TEST(got == (std::vector{"w0"})); + BOOST_TEST_EQ(waiting.count("failed"), 0U); +} + +// A handshake not active 10 s after its start fails, with 0.27.0's reason; one that completed, or +// was cleared, does not. A handshake failed by its steps reports their reason. +void the_timer_fails_after_10_s() { + bench b; + b.begin("A"); + b.begin("B"); + b.finish("B"); + b.hs->receive_ready("B"); + b.begin("C"); + b.hs->clear("C"); + b.advance(9'999ms); + BOOST_TEST_EQ(b.count("failed"), 0U); + b.advance(1ms); + BOOST_TEST(b.calls.back() == "failed A: handshake timed out after 10000ms"); + b.advance(20'000ms); + BOOST_TEST_EQ(b.count("failed"), 1U); + BOOST_TEST(b.hs->phase_of("B") == phase::active); + + bench failing; + failing.begin("A"); + failing.finish("A", "peer identity verification failed"); + BOOST_TEST(failing.calls.back() == "failed A: peer identity verification failed"); + failing.advance(20'000ms); + BOOST_TEST_EQ(failing.count("failed"), 1U); +} + +// Clearing a peer fails a step that waits for its message with peer_disconnected (0.27.0's +// "peer disconnected during handshake"); the steps of a cleared or replaced handshake, ending +// later, reach nothing. +void clear_fails_a_waiting_step() { + bench b; + b.begin("A"); + std::optional waited; + b.hs->next_message("A", [&waited](boost::system::error_code ec, std::string_view json) { + waited = ec; + BOOST_TEST(json.empty()); + }); + BOOST_TEST(!waited.has_value()); + b.hs->clear("A"); + BOOST_TEST(waited == trystero::error::peer_disconnected); + BOOST_TEST_EQ(detail::handshake_manager::disconnected_reason, + "peer disconnected during handshake"); + std::optional late; + b.hs->next_message("A", [&late](boost::system::error_code ec, std::string_view) { late = ec; }); + BOOST_TEST(late == trystero::error::peer_disconnected); + b.finish("A"); + BOOST_TEST_EQ(b.count("passed"), 0U); + + // A second add replaces the handshake: the first one's steps and timer reach nothing. + b.begin("B"); + auto first = std::move(b.steps.at("B")); + b.steps.erase("B"); + b.advance(5'000ms); + b.begin("B"); + first(""); + BOOST_TEST_EQ(b.count("passed"), 0U); + b.advance(5'000ms); + BOOST_TEST_EQ(b.count("failed"), 0U); + b.advance(5'000ms); + BOOST_TEST(b.calls.back() == "failed B: handshake timed out after 10000ms"); +} + +} // namespace + +int main() { + using webcpp::test::run_case; + run_case(the_lower_id_initiates); + run_case(ready_goes_before_activate); + run_case(both_ready_activate_once); + run_case(a_deferred_responder_waits_for_the_initiators_ready); + run_case(a_17th_buffered_message_fails_the_handshake); + run_case(the_timer_fails_after_10_s); + run_case(clear_fails_a_waiting_step); + // Under Asyncify, a main that suspended loses what it returns: the status goes first. + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/identity_cache_test.cpp b/test/identity_cache_test.cpp new file mode 100644 index 0000000..d02e20b --- /dev/null +++ b/test/identity_cache_test.cpp @@ -0,0 +1,505 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Tests an app's key records and verified signatures, detail::identity_cache, against 0.27.0's +// `getVerifiedPubKeyRecord`, `verifyWithP256`, `verifyPeerIdKey` and `verifyUserIdKey`, with the +// vectors recorded from its own code (fixtures/expected/trystero-0.27.0.json), the test's one +// argument. + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cases.hpp" + +namespace wd = webcpp::document; +namespace tp = webcpp::trystero::protocol; +namespace td = webcpp::trystero::detail; + +namespace { + +/** A value of the fixture: a read-only handle of an owned document. */ +using fixture_value = wd::basic_const_value<>; + +/** The fixture, which main loads before it runs a case. */ +std::optional& fixture_document() { + static std::optional document; + return document; +} + +/** The named top-level section of the fixture. */ +fixture_value section(std::string_view name) { + return fixture_document()->root()[name]; +} + +/** The text of a fixture value. */ +std::string_view str(const fixture_value& v) { + return v.value_or(std::string_view()); +} + +/** The bytes of a fixture's hexadecimal text. */ +tp::bytes bytes_of(const fixture_value& v) { + const auto decoded = tp::from_hex(str(v)); + BOOST_TEST(decoded.has_value()); + return decoded.value_or(tp::bytes()); +} + +/** The bytes of a text, as a span. */ +std::span bytes_view(std::string_view text) { + return {reinterpret_cast(text.data()), text.size()}; +} + +/** The endpoint key of a scalar, with its compact text, made through trystero's P-256 seam. */ +std::optional key_of(std::span scalar) { + auto key = td::make_endpoint_identity(scalar, std::pmr::get_default_resource()); + BOOST_TEST(key.has_value()); + return key; +} + +/** The endpoint key whose scalar is the big-endian `n`, which is in [1, n - 1]. */ +std::optional key_number(std::uint32_t n) { + std::array scalar{}; + for (std::size_t i = 0; i < 4; ++i) { + scalar[31 - i] = static_cast(n >> (8 * i)); + } + return key_of(scalar); +} + +/** The endpoint key of the fixture's `p256_keys` entry labelled `label`. */ +std::optional fixture_key(std::string_view label) { + for (const auto entry : section("p256_keys")) { + if (str(entry["label"]) == label) { + const auto scalar = tp::from_base64url(str(entry["d"])); + if (!BOOST_TEST(scalar.has_value())) { + return std::nullopt; + } + return key_of(*scalar); + } + } + BOOST_ERROR("p256_keys has no such label"); + return std::nullopt; +} + +/** The bound of the fixture's `identity_limits` named `name`. */ +std::size_t limit(std::string_view name) { + return static_cast(section("identity_limits")[name].value_or(std::int64_t{-1})); +} + +void limits_are_0_27_0s() { + BOOST_TEST_EQ(td::identity_cache::max_records, limit("pub_key_records")); + BOOST_TEST_EQ(td::identity_cache::max_signatures, limit("signature_cache_entries")); + BOOST_TEST_EQ(td::identity_cache::max_signature_bytes, limit("signature_cache_bytes")); + BOOST_TEST_EQ(td::identity_cache::max_cached_payload_bytes, + limit("signature_cache_payload_bytes")); +} + +void records_are_evicted_least_recently_used_at_4096() { + td::identity_cache cache(std::pmr::get_default_resource()); + std::vector compacts; + for (std::uint32_t n = 1; n <= td::identity_cache::max_records + 1; ++n) { + const auto key = key_number(n); + if (!key) { + return; + } + compacts.push_back(key->compact); + } + for (std::size_t i = 0; i < td::identity_cache::max_records; ++i) { + const auto* rec = cache.record(compacts[i]); + if (!BOOST_TEST(rec != nullptr)) { + return; + } + BOOST_TEST_EQ(rec->compact, compacts[i]); + BOOST_TEST_EQ(rec->peer_id, tp::derive_peer_id(compacts[i])); + BOOST_TEST_EQ(rec->user_id, tp::derive_user_id(compacts[i])); + } + BOOST_TEST_EQ(cache.records(), td::identity_cache::max_records); + // A record asked for again is the same, and becomes the most recently used. + const auto* first = cache.record(compacts[0]); + BOOST_TEST(first != nullptr && first->compact == compacts[0]); + BOOST_TEST_EQ(cache.records(), td::identity_cache::max_records); + // One more evicts the least recently used: the second, not the first. + BOOST_TEST(cache.record(compacts.back()) != nullptr); + BOOST_TEST_EQ(cache.records(), td::identity_cache::max_records); + BOOST_TEST(cache.holds_record(compacts[0])); + BOOST_TEST(!cache.holds_record(compacts[1])); + BOOST_TEST(cache.holds_record(compacts[2])); + BOOST_TEST(cache.holds_record(compacts.back())); + // An evicted record is made again on demand. + BOOST_TEST(cache.record(compacts[1]) != nullptr); + BOOST_TEST(!cache.holds_record(compacts[2])); +} + +void an_off_curve_key_has_no_record() { + td::identity_cache cache(std::pmr::get_default_resource()); + const auto key = fixture_key("endpoint-a"); + if (!key) { + return; + } + // (0, 0) and endpoint-a's x with its y changed: compact texts, off the curve. + const std::array zeros{}; + const std::pmr::string origin = tp::to_base64url(zeros) + "." + tp::to_base64url(zeros); + const auto point = tp::parse_compact_public_key(key->compact); + if (!BOOST_TEST(point.has_value())) { + return; + } + auto moved = *point; + moved[64] ^= 1U; + const auto off_curve = tp::compact_public_key(moved); + for (const std::string_view refused : { + std::string_view(origin), + std::string_view(off_curve), + std::string_view("not a key"), + std::string_view(key->compact).substr(1), + std::string_view(), + }) { + BOOST_TEST(cache.record(refused) == nullptr); + BOOST_TEST(!cache.verify_peer_id(tp::derive_peer_id(refused), refused)); + BOOST_TEST(!cache.verify_user_id(tp::derive_user_id(refused), refused)); + } + const auto signature = tp::sign_p256(key->key, bytes_view("payload")); + if (BOOST_TEST(signature.has_value())) { + BOOST_TEST(!cache.verify(off_curve, *signature, bytes_view("payload"))); + } + // A refused text is not remembered. + BOOST_TEST_EQ(cache.records(), 0U); + BOOST_TEST(cache.record(key->compact) != nullptr); + BOOST_TEST_EQ(cache.records(), 1U); +} + +void a_cached_signature_answers_for_its_payload_only() { + td::identity_cache cache(std::pmr::get_default_resource()); + const auto key = fixture_key("endpoint-a"); + const auto other = fixture_key("endpoint-b"); + if (!key || !other) { + return; + } + const auto signature = tp::sign_p256(key->key, bytes_view("payload")); + if (!BOOST_TEST(signature.has_value())) { + return; + } + BOOST_TEST(!cache.holds_signature(key->compact, *signature)); + BOOST_TEST(cache.verify(key->compact, *signature, bytes_view("payload"))); + BOOST_TEST(cache.holds_signature(key->compact, *signature)); + BOOST_TEST_EQ(cache.signatures(), 1U); + BOOST_TEST_EQ(cache.signature_bytes(), 7U); + // The cached signature answers for its payload, and for no other. + BOOST_TEST(cache.verify(key->compact, *signature, bytes_view("payload"))); + BOOST_TEST(!cache.verify(key->compact, *signature, bytes_view("payloaD"))); + BOOST_TEST(!cache.verify(key->compact, *signature, bytes_view("payload!"))); + BOOST_TEST(!cache.verify(key->compact, *signature, {})); + // Nor for another key. + BOOST_TEST(!cache.verify(other->compact, *signature, bytes_view("payload"))); + BOOST_TEST(!cache.holds_signature(other->compact, *signature)); + BOOST_TEST_EQ(cache.signatures(), 1U); + BOOST_TEST_EQ(cache.signature_bytes(), 7U); + // A signature of another length is refused at once. + BOOST_TEST(!cache.verify(key->compact, std::span(*signature).first(63), bytes_view("payload"))); + // The fixture's signatures, WebCrypto's, verify by their keys and are kept. + const auto proof = section("user_proof"); + const auto proof_signature = tp::from_base64url(str(proof["proof"])); + if (BOOST_TEST(proof_signature.has_value())) { + BOOST_TEST(cache.verify(str(proof["user_compact"]), *proof_signature, + bytes_view(str(proof["payload"])))); + BOOST_TEST(cache.holds_signature(str(proof["user_compact"]), *proof_signature)); + BOOST_TEST_EQ(cache.signatures(), 2U); + } +} + +void payloads_over_4096_bytes_are_not_cached() { + td::identity_cache cache(std::pmr::get_default_resource()); + const auto key = fixture_key("endpoint-a"); + if (!key) { + return; + } + std::vector payload(td::identity_cache::max_cached_payload_bytes + 1, 0x5a); + const auto long_signature = tp::sign_p256(key->key, payload); + if (!BOOST_TEST(long_signature.has_value())) { + return; + } + BOOST_TEST(cache.verify(key->compact, *long_signature, payload)); + BOOST_TEST(!cache.holds_signature(key->compact, *long_signature)); + BOOST_TEST_EQ(cache.signatures(), 0U); + payload.back() ^= 1U; + BOOST_TEST(!cache.verify(key->compact, *long_signature, payload)); + // 4096 bytes are kept. + payload.pop_back(); + const auto signature = tp::sign_p256(key->key, payload); + if (!BOOST_TEST(signature.has_value())) { + return; + } + BOOST_TEST(cache.verify(key->compact, *signature, payload)); + BOOST_TEST(cache.holds_signature(key->compact, *signature)); + BOOST_TEST_EQ(cache.signature_bytes(), td::identity_cache::max_cached_payload_bytes); +} + +/** A verifier that accepts every signature it is asked about and counts the asking. */ +struct counting_verifier { + std::size_t* calls; + + bool operator()(std::span /*signature*/, + std::span /*digest*/, + const webcpp::crypto::curves::p256::public_key& /*key*/) const { + ++*calls; + return true; + } +}; + +using counted_cache = td::basic_identity_cache; + +/** A signature of low S that no key made: r is `n + 1` and s is 1, both in range. */ +tp::p256_signature fake_signature(std::size_t n) { + tp::p256_signature signature{}; + for (std::size_t i = 0; i < 4; ++i) { + signature[31 - i] = static_cast((n + 1) >> (8 * i)); + } + signature[63] = 1; + return signature; +} + +void the_cache_holds_at_most_8192_signatures_and_2_mib() { + const auto key = fixture_key("endpoint-a"); + if (!key) { + return; + } + std::size_t calls = 0; + // By bytes: 512 payloads of 4096 bytes are 2 MiB; the 513th evicts the least recently used. + { + counted_cache cache(std::pmr::get_default_resource(), counting_verifier{&calls}); + constexpr std::size_t fit = + td::identity_cache::max_signature_bytes / td::identity_cache::max_cached_payload_bytes; + std::vector> payloads; + std::vector signatures; + for (std::size_t i = 0; i <= fit; ++i) { + payloads.emplace_back(td::identity_cache::max_cached_payload_bytes, + static_cast(i)); + signatures.push_back(fake_signature(i)); + } + for (std::size_t i = 0; i < fit; ++i) { + BOOST_TEST(cache.verify(key->compact, signatures[i], payloads[i])); + } + BOOST_TEST_EQ(calls, fit); + BOOST_TEST_EQ(cache.signatures(), fit); + BOOST_TEST_EQ(cache.signature_bytes(), td::identity_cache::max_signature_bytes); + // The first, used again, stays and is not verified again; the second leaves for the last. + BOOST_TEST(cache.verify(key->compact, signatures[0], payloads[0])); + BOOST_TEST_EQ(calls, fit); + BOOST_TEST(cache.verify(key->compact, signatures[fit], payloads[fit])); + BOOST_TEST_EQ(calls, fit + 1); + BOOST_TEST_EQ(cache.signatures(), fit); + BOOST_TEST_EQ(cache.signature_bytes(), td::identity_cache::max_signature_bytes); + BOOST_TEST(cache.holds_signature(key->compact, signatures[0])); + BOOST_TEST(!cache.holds_signature(key->compact, signatures[1])); + BOOST_TEST(cache.holds_signature(key->compact, signatures[2])); + BOOST_TEST(cache.holds_signature(key->compact, signatures[fit])); + // A hit with another payload answers false, does not verify, and still becomes the most + // recently used, as 0.27.0's `get` makes it: the third, wrongly asked about, outlives the + // fourth. + BOOST_TEST(!cache.verify(key->compact, signatures[2], payloads[3])); + BOOST_TEST_EQ(calls, fit + 1); + // A smaller payload evicts the least recently used only when it does not fit. + const auto small = fake_signature(fit + 1); + BOOST_TEST(cache.verify(key->compact, small, bytes_view("small"))); + BOOST_TEST_EQ(calls, fit + 2); + BOOST_TEST_EQ(cache.signatures(), fit); + BOOST_TEST_EQ(cache.signature_bytes(), td::identity_cache::max_signature_bytes - + td::identity_cache::max_cached_payload_bytes + + 5); + BOOST_TEST(cache.holds_signature(key->compact, signatures[2])); + BOOST_TEST(!cache.holds_signature(key->compact, signatures[3])); + } + // By entries: 8192 signatures of short payloads; the 8193rd evicts the least recently used. + { + calls = 0; + counted_cache cache(std::pmr::get_default_resource(), counting_verifier{&calls}); + std::vector payloads; + std::vector signatures; + for (std::size_t i = 0; i <= td::identity_cache::max_signatures; ++i) { + payloads.push_back("payload " + std::to_string(i)); + signatures.push_back(fake_signature(i)); + } + std::size_t bytes = 0; + for (std::size_t i = 0; i < td::identity_cache::max_signatures; ++i) { + BOOST_TEST(cache.verify(key->compact, signatures[i], bytes_view(payloads[i]))); + bytes += payloads[i].size(); + } + BOOST_TEST_EQ(calls, td::identity_cache::max_signatures); + BOOST_TEST_EQ(cache.signatures(), td::identity_cache::max_signatures); + BOOST_TEST_EQ(cache.signature_bytes(), bytes); + BOOST_TEST(cache.verify(key->compact, signatures[0], bytes_view(payloads[0]))); + BOOST_TEST_EQ(calls, td::identity_cache::max_signatures); + BOOST_TEST(cache.verify(key->compact, signatures.back(), bytes_view(payloads.back()))); + BOOST_TEST_EQ(calls, td::identity_cache::max_signatures + 1); + BOOST_TEST_EQ(cache.signatures(), td::identity_cache::max_signatures); + BOOST_TEST_EQ(cache.signature_bytes(), bytes - payloads[1].size() + payloads.back().size()); + BOOST_TEST(cache.holds_signature(key->compact, signatures[0])); + BOOST_TEST(!cache.holds_signature(key->compact, signatures[1])); + BOOST_TEST(cache.holds_signature(key->compact, signatures.back())); + } +} + +void a_cached_answer_is_given_without_verifying() { + const auto key = fixture_key("endpoint-a"); + if (!key) { + return; + } + std::size_t calls = 0; + counted_cache cache(std::pmr::get_default_resource(), counting_verifier{&calls}); + const auto signature = fake_signature(0); + BOOST_TEST(cache.verify(key->compact, signature, bytes_view("payload"))); + BOOST_TEST_EQ(calls, 1U); + // A hit, whatever the payload, is answered without verifying. + BOOST_TEST(cache.verify(key->compact, signature, bytes_view("payload"))); + BOOST_TEST(!cache.verify(key->compact, signature, bytes_view("other"))); + BOOST_TEST_EQ(calls, 1U); + // Another signature of the same payload is a miss, and so is another key's. + BOOST_TEST(cache.verify(key->compact, fake_signature(1), bytes_view("payload"))); + BOOST_TEST_EQ(calls, 2U); + const auto other = fixture_key("endpoint-b"); + if (BOOST_TEST(other.has_value())) { + BOOST_TEST(cache.verify(other->compact, signature, bytes_view("payload"))); + BOOST_TEST_EQ(calls, 3U); + } + // A payload over 4096 bytes is verified each time, and kept never. + const std::vector long_payload(td::identity_cache::max_cached_payload_bytes + 1); + BOOST_TEST(cache.verify(key->compact, signature, long_payload)); + BOOST_TEST(cache.verify(key->compact, signature, long_payload)); + BOOST_TEST_EQ(calls, 5U); + // A high S, or a signature of another length, or an off-curve key, is refused before the + // verifier is asked. + const auto before = calls; + auto high = signature; + high[32] = 0xff; + BOOST_TEST(!cache.verify(key->compact, high, bytes_view("payload"))); + BOOST_TEST(!cache.verify(key->compact, high, long_payload)); + BOOST_TEST(!cache.verify(key->compact, std::span(signature).first(63), bytes_view("payload"))); + BOOST_TEST(!cache.verify("not a key", signature, bytes_view("payload"))); + BOOST_TEST_EQ(calls, before); +} + +void a_high_s_signature_is_refused_before_verification() { + const auto proof = section("user_proof"); + const auto compact = str(proof["user_compact"]); + const auto payload = bytes_view(str(proof["payload"])); + std::optional low; + std::optional high; + for (const auto c : section("low_s")) { + if (str(c["case"]) == "signed") { + low = bytes_of(c["signature"]); + } else if (str(c["case"]) == "its high form") { + high = bytes_of(c["signature"]); + } + } + if (!BOOST_TEST(low.has_value()) || !BOOST_TEST(high.has_value())) { + return; + } + // The high form of a signature that verifies is refused, and never kept. + td::identity_cache cache(std::pmr::get_default_resource()); + BOOST_TEST(!cache.verify(compact, *high, payload)); + BOOST_TEST(!cache.holds_signature(compact, *high)); + BOOST_TEST_EQ(cache.signatures(), 0U); + // Its low form verifies and is kept; the high form is refused still. + BOOST_TEST(cache.verify(compact, *low, payload)); + BOOST_TEST(!cache.verify(compact, *high, payload)); + BOOST_TEST(!cache.holds_signature(compact, *high)); + BOOST_TEST_EQ(cache.signatures(), 1U); + // Every case of the fixture verifies as 0.27.0's verifyWithP256 says, by a fresh cache and by + // this one. + for (const auto c : section("low_s")) { + const auto signature = bytes_of(c["signature"]); + td::identity_cache fresh(std::pmr::get_default_resource()); + BOOST_TEST_EQ(fresh.verify(compact, signature, payload), c["verifies"].value_or(true)); + BOOST_TEST_EQ(cache.verify(compact, signature, payload), c["verifies"].value_or(true)); + } + BOOST_TEST_EQ(cache.signatures(), 1U); +} + +/** Checks that the peer id and the user id of a fixture key are its own and no other key's. */ +void check_ids_of(const fixture_value& entry) { + const auto compact = str(entry["compact"]); + const auto peer_id = str(entry["peer_id"]); + const auto user_id = str(entry["user_id"]); + td::identity_cache cache(std::pmr::get_default_resource()); + // Ids that are not ids are refused before any lookup. + BOOST_TEST(!cache.verify_peer_id("", compact)); + BOOST_TEST(!cache.verify_user_id(user_id.substr(1), compact)); + BOOST_TEST(!cache.verify_user_id(std::string(user_id) + "0", compact)); + BOOST_TEST(!cache.verify_user_id(std::string(user_id.substr(1)) + "-", compact)); + BOOST_TEST(!cache.verify_user_id(std::string(user_id.substr(1)) + "\xc3", compact)); + BOOST_TEST_EQ(cache.records(), 0U); + // Each id is its own key's. + BOOST_TEST(cache.verify_peer_id(peer_id, compact)); + BOOST_TEST(cache.verify_user_id(user_id, compact)); + BOOST_TEST(!cache.verify_peer_id(user_id, compact)); + BOOST_TEST(!cache.verify_user_id(std::string(peer_id) + "00", compact)); + BOOST_TEST(!cache.verify_peer_id(peer_id.substr(1), compact)); + BOOST_TEST_EQ(cache.records(), 1U); + // And no other key's. + for (const auto other : section("p256_keys")) { + if (str(other["compact"]) != compact) { + BOOST_TEST(!cache.verify_peer_id(peer_id, str(other["compact"]))); + BOOST_TEST(!cache.verify_user_id(user_id, str(other["compact"]))); + } + } +} + +void ids_are_checked_against_their_keys() { + std::size_t keys = 0; + for (const auto entry : section("p256_keys")) { + check_ids_of(entry); + ++keys; + } + BOOST_TEST_GE(keys, 2U); +} + +} // namespace + +int main(int argc, char* argv[]) { + if (!BOOST_TEST_EQ(argc, 2)) { + BOOST_LIGHTWEIGHT_TEST_OSTREAM + << "usage: identity_cache_test \n"; + return boost::report_errors(); + } + const std::ifstream file(argv[1]); + std::stringstream text; + text << file.rdbuf(); + auto loaded = wd::parse(text.str()); + if (!BOOST_TEST(loaded.has_value())) { + return boost::report_errors(); + } + fixture_document().emplace(std::move(*loaded)); + webcpp::test::run_case(limits_are_0_27_0s); + webcpp::test::run_case(records_are_evicted_least_recently_used_at_4096); + webcpp::test::run_case(an_off_curve_key_has_no_record); + webcpp::test::run_case(a_cached_signature_answers_for_its_payload_only); + webcpp::test::run_case(payloads_over_4096_bytes_are_not_cached); + webcpp::test::run_case(the_cache_holds_at_most_8192_signatures_and_2_mib); + webcpp::test::run_case(a_cached_answer_is_given_without_verifying); + webcpp::test::run_case(a_high_s_signature_is_refused_before_verification); + webcpp::test::run_case(ids_are_checked_against_their_keys); + return boost::report_errors(); +} diff --git a/test/memory_backend_test.cpp b/test/memory_backend_test.cpp index 3ba2f4e..3193956 100644 --- a/test/memory_backend_test.cpp +++ b/test/memory_backend_test.cpp @@ -4,12 +4,15 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// The memory backend's hooks, which the tests of shared connections drive: a filter that delivers, +// The memory backend's hooks, which the tests of rooms drive: a filter that delivers, // drops or holds frames in the channel's order, deferred opens, injected frames, a forced failure, // and a channel that buffers and drains. #include "support/memory_backend.hpp" +#include +#include + #include #include @@ -19,10 +22,14 @@ #include #include #include +#include #include #include #include +#include +#include #include +#include #include #include "require.hpp" @@ -34,8 +41,12 @@ using namespace std::chrono_literals; namespace { +/** The wall-clock ceiling of a wait for something that must happen: a hang guard, far above any + * loaded run, never what a case measures. */ +constexpr std::chrono::milliseconds hang_guard = 120s; + bool run_until(asio::io_context& io, const std::function& done, - std::chrono::milliseconds limit = 5s) { + std::chrono::milliseconds limit = hang_guard) { const auto end = std::chrono::steady_clock::now() + limit; while (!done() && std::chrono::steady_clock::now() < end) { io.run_for(10ms); // lint-run: the memory network posts to it @@ -46,6 +57,15 @@ bool run_until(asio::io_context& io, const std::function& done, return done(); } +/** Runs the ready work of `io` until there is none: the memory network posts every frame, so + * what a window of "nothing happens" proves is that nothing is left to run. */ +void settle(asio::io_context& io) { + io.restart(); + while (io.poll() > 0) { + io.restart(); + } +} + /** Two ends of one pair, their channels and what each received. */ struct pair { std::shared_ptr offerer; @@ -57,6 +77,9 @@ struct pair { std::vector offerer_states; std::size_t offerer_id = 0; std::size_t answerer_id = 0; + /** The offerer's description and the answerer's. */ + std::string offer; + std::string answer; }; /** Makes and pairs two peer connections, as two rooms' negotiations do. */ @@ -112,6 +135,8 @@ void connect(memory_network& net, pair& p) { std::string_view sdp) { answer = sdp; }); webcpp::test::require(BOOST_TEST(run_until(net.io(), [&] { return !answer.empty(); }))); p.offerer->set_remote_description("answer", answer, [](trystero::backend::error_code) {}); + p.offer = offer; + p.answer = answer; } void ids_are_sizes_and_peer_of_pairs_them() { @@ -137,7 +162,7 @@ void a_held_frame_holds_every_later_frame_of_its_end() { const std::array b{'B'}; p.offer_end->send(a); p.offer_end->send(b); - run_until(io, [] { return false; }, 100ms); + settle(io); BOOST_TEST(p.at_answerer.empty()); // B waits behind A, as on an ordered channel net.filter = {}; net.release(p.answerer_id); @@ -168,7 +193,7 @@ void deferred_opens_open_one_end_at_a_time() { net.defer_opens = true; pair p; connect(net, p); - run_until(io, [] { return false; }, 100ms); + settle(io); BOOST_TEST(!p.offer_end->is_open()); net.open(p.offerer_id); BOOST_TEST(run_until(io, [&] { return p.offer_end->is_open(); })); @@ -185,14 +210,14 @@ void a_frame_before_the_far_end_opens_waits_for_it() { net.defer_opens = true; pair p; connect(net, p); - run_until(io, [] { return false; }, 100ms); + settle(io); net.open(p.offerer_id); webcpp::test::require(BOOST_TEST(run_until(io, [&] { return p.offer_end->is_open(); }))); const std::array a{'A'}; const std::array b{'B'}; p.offer_end->send(a); p.offer_end->send(b); - run_until(io, [] { return false; }, 100ms); + settle(io); BOOST_TEST(p.at_answerer.empty()); net.open(p.answerer_id); BOOST_TEST(run_until(io, [&] { return p.at_answerer.size() == 2; })); @@ -210,6 +235,62 @@ void an_injected_frame_reaches_the_end_named() { BOOST_TEST(run_until(io, [&] { return p.at_offerer.size() == 1; })); } +/** The fingerprint a memory connection's description carries, computed here apart from the backend: + * the SHA-256 of `mem-fingerprint:`, its bytes as hexadecimal pairs joined by `:`, in + * uppercase as written, or in lowercase as 0.27.0's extractDtlsFingerprints reads it. */ +std::string fingerprint_of(std::size_t id, bool upper) { + const auto digest = trystero::protocol::sha256("mem-fingerprint:" + std::to_string(id)); + std::string out; + for (const auto byte : digest) { + std::array pair{}; + // Two digits and the terminator always fit: the count it returns says nothing new. + static_cast(std::snprintf(pair.data(), pair.size(), upper ? "%02X" : "%02x", byte)); + if (!out.empty()) { + out += ':'; + } + out += pair.data(); + } + return out; +} + +// A memory connection's description carries a DTLS fingerprint, as a browser's does, so that a +// room's handshake binds both ends' (design D20): `mem:`, then `a=fingerprint:sha-256` and the +// connection's own fingerprint. A pair connects through such descriptions, the id read from the +// first line, and a description whose first line names no connection is refused. +void descriptions_carry_a_fingerprint() { + asio::io_context io; + memory_network net{io}; + pair p; + connect(net, p); + const auto check = [](const std::string& sdp, std::size_t id) { + BOOST_TEST_EQ(sdp, "mem:" + std::to_string(id) + "\r\na=fingerprint:sha-256 " + + fingerprint_of(id, true) + "\r\n"); + const auto dtls = + trystero::protocol::dtls_fingerprints(sdp, std::pmr::get_default_resource()); + if (BOOST_TEST_EQ(dtls.size(), 1U)) { + BOOST_TEST_EQ(std::string_view(dtls[0]), "sha-256 " + fingerprint_of(id, false)); + } + BOOST_TEST_EQ(trystero::test::memory_description_id(sdp).value_or(id + 1), id); + }; + check(p.offer, p.offerer_id); + check(p.answer, p.answerer_id); + BOOST_TEST_NE(p.offer, p.answer); + BOOST_TEST(run_until( + io, [&] { return p.offer_end->is_open() && p.answer_end && p.answer_end->is_open(); })); + BOOST_TEST(!trystero::test::memory_description_id("mem:12x\r\n")); + BOOST_TEST(!trystero::test::memory_description_id("v=0\r\nmem:12\r\n")); + BOOST_TEST(!trystero::test::memory_description_id("mem:")); + BOOST_TEST_EQ(trystero::test::memory_description_id("mem:12").value_or(0), 12U); + auto* const memory = std::pmr::get_default_resource(); + const auto stranger = net.make_peer_connection({}, memory); + std::optional applied; + stranger->set_remote_description("offer", "v=0\r\nmem:" + std::to_string(p.offerer_id), + [&](trystero::backend::error_code ec) { applied = ec; }); + BOOST_TEST(run_until(io, [&] { return applied.has_value(); })); + BOOST_TEST(applied.has_value() && *applied); + BOOST_TEST(!stranger->has_remote_description()); +} + // `failed` is reported while the channel is still open, and the channel's close after it. void a_failed_connection_reports_failed_then_closes() { asio::io_context io; @@ -300,7 +381,7 @@ void a_closed_channel_drains_nothing_more() { p.offer_end->close(); io.poll_one(); // the next drain step, queued before the close's handlers BOOST_TEST_EQ(net.buffered(p.offerer_id), 0U); - run_until(io, [] { return false; }, 100ms); + settle(io); BOOST_TEST(p.at_answerer.empty()); } @@ -324,7 +405,7 @@ void a_release_filters_each_frame_again() { }; net.release(p.answerer_id); BOOST_TEST(run_until(io, [&] { return p.at_answerer.size() == 1; })); - run_until(io, [] { return false; }, 100ms); + settle(io); BOOST_TEST_EQ(p.at_answerer.size(), 1U); BOOST_TEST(p.at_answerer.at(0).at(0) == 'A'); net.filter = {}; @@ -350,7 +431,7 @@ void a_release_after_the_sending_channel_was_replaced_drops_its_frames() { const auto replacement = p.offerer->create_data_channel("again"); BOOST_TEST(replacement != p.offer_end); net.release(p.answerer_id); - run_until(io, [] { return false; }, 100ms); + settle(io); BOOST_TEST(p.at_answerer.empty()); } @@ -370,7 +451,7 @@ void a_release_after_the_sender_went_drops_its_frames() { p.offer_end.reset(); p.offerer.reset(); // the sending end is destroyed net.release(p.answerer_id); - run_until(io, [] { return false; }, 100ms); + settle(io); BOOST_TEST(p.at_answerer.empty()); } @@ -557,6 +638,7 @@ int main() { deferred_opens_open_one_end_at_a_time(); a_frame_before_the_far_end_opens_waits_for_it(); an_injected_frame_reaches_the_end_named(); + descriptions_carry_a_fingerprint(); a_failed_connection_reports_failed_then_closes(); a_disconnection_and_a_reconnection_are_reported(); a_buffering_channel_drains_and_says_so(); diff --git a/test/oracle/Jamfile b/test/oracle/Jamfile index b15dad4..6879d19 100644 --- a/test/oracle/Jamfile +++ b/test/oracle/Jamfile @@ -4,11 +4,14 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -# The oracle of trystero: Trystero 0.26.0 itself, pinned by package.json and -# package-lock.json, run by Node. It computes the protocol's values that the -# protocol test must reproduce, runs the twins of the examples, and meets the -# C++ peers in the interop tests. werift, pinned beside it, is the WebRTC the -# twins give Trystero JS in Node, as its README says to. +# The oracle of trystero: Trystero 0.27.0 itself, the published packages +# pinned by package.json and package-lock.json, run by Node. It computes the +# protocol's values that the protocol and signaling tests must reproduce +# (fixtures/oracle), proves that the published packages compute the vectors +# the pinned source recorded (fixtures/expected/trystero-0.27.0.json), runs the +# twins of the examples, and meets the C++ peers in the interop tests. werift, +# pinned beside it, is the WebRTC the twins give Trystero JS in Node, as its +# README says to. import webcpp ; @@ -22,18 +25,24 @@ path-constant ORACLE : . ; # tag::oracle[] webcpp.original node --conditions=development ; webcpp.twins ../../example : twins : .mjs : $(ORACLE)/run_twin.mjs ; -webcpp.cases protocol : oracle.mjs : ../fixtures/cases : ../fixtures/expected ; -webcpp.lane oracle : twins cases-protocol ; +webcpp.cases protocol : oracle.mjs : ../fixtures/cases : ../fixtures/oracle ; +# The recorder of the vectors over the published packages, with the fixture as +# its previous output, writes the fixture again byte for byte (design D19): +# vectors.py runs record_0_27.mjs --dist; update-generated is the fixture's +# only writer here, and keeps its signatures as the recorder does. +webcpp.generated vectors : vectors.py + : ../fixtures/expected/trystero-0.27.0.json : ../fixtures/expected/trystero-0.27.0.json ; +webcpp.lane oracle : twins cases-protocol generated-vectors ; # end::oracle[] -# Trystero JS meets each C++ peer over a relay of its own on 127.0.0.1: the -# browser's peer in headless Chrome, and the native peer as a process, both -# over the platform backend. The native peer is built with the standard -# libraries' own checks, so that a completion that touches a container its -# socket cleared fails at once. Each driver has -# 2400 s for its bounded scenarios and Chrome's start, including the -# wrong-password observation windows and transient-handshake recovery. The -# scenarios report their peer events on failure before this outer bound. +# Trystero 0.27.0 meets each C++ peer over a relay of its own on 127.0.0.1: +# the browser's peer in headless Chrome, and the native peer as a process, +# both over the platform backend (interop/run.mjs names the scenarios). The +# native peer is built with the standard libraries' own checks, so that a +# completion that touches a container its socket cleared fails at once. Each +# driver has 2400 s for its scenarios and Chrome's start; each wait of a +# scenario is bounded far below that, and a scenario that fails reports its +# peers' events before this outer bound. # tag::interop[] webcpp.drive interop_browser : interop/peer.cpp : /webcpp/trystero//platform -sENVIRONMENT=web diff --git a/test/oracle/interop/cpp.html b/test/oracle/interop/cpp.html index c594cac..d505acb 100644 --- a/test/oracle/interop/cpp.html +++ b/test/oracle/interop/cpp.html @@ -23,28 +23,18 @@ console.log(line) document.getElementById('log').append(line + '\n') } -// Counts the page's RTCPeerConnections, for the scenarios that bound them: every one made, as Chromium counts them -// until a garbage collection, the live ones, and the most there were at once. +// Counts the page's RTCPeerConnections, every one made, as Chromium counts them until a garbage collection: the flood +// scenario bounds them. window.madePeerConnections = 0 -window.livePeerConnections = 0 -window.peakPeerConnections = 0 const PeerConnection = window.RTCPeerConnection window.RTCPeerConnection = class extends PeerConnection { constructor(...args) { super(...args) ++window.madePeerConnections - window.peakPeerConnections = Math.max(window.peakPeerConnections, ++window.livePeerConnections) - } - close() { - if (!this.counted) { - this.counted = true - --window.livePeerConnections - } - return super.close() } } -// The program's main starts the peer, runs it for the page's life, and defines window.leave, which -// posts the leave to it. +// The program's main starts the peer, runs it for the page's life, and defines window.leave, +// window.offline and window.online, which post to it. // The program run.mjs serves under /build/, as b2 linked it: interop_browser.js, beside its wasm. const program = document.createElement('script') program.src = '/build/' + new URLSearchParams(location.search).get('program') diff --git a/test/oracle/interop/forger.html b/test/oracle/interop/forger.html index e0e612e..017ae88 100644 --- a/test/oracle/interop/forger.html +++ b/test/oracle/interop/forger.html @@ -5,15 +5,11 @@ accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) -A watcher of the interop test, which run.mjs opens in headless Chrome: it holds no room key, and with `mode=garbage` -(the default) answers every offer the C++ peer (`target`) publishes with a forged answer in the name of the peer the -offer is for. With `mode=replay` it forges nothing: it records the first sealed answer and the first sealed offer each -peer sends the C++ peer, and resends them in that peer's name later, an answer with each new offer of the C++ peer to -that peer, an offer as soon as that peer announces itself or is asked to offer. With `mode=reflect` it sends the -target its own sealed texts back: each offer the target publishes to a peer comes back at once as that peer's answer; -with `decoy`, an id it announces above the target, the target's sealed offer to the decoy comes back as an offer in the -name of each other peer that announces itself. What anyone who reads the relays can do: the topics are public, a peer -id proves nothing, and a sealed offer or answer names neither its offer nor a peer. +A Trystero 0.27.0 peer of the interop test that claims a user it cannot sign for: it joins with a custom +identity (0.27.0's UserIdentity object) whose sign() signs 0.27.0's startup check with the user's key, so that +joinRoom takes it, and every later payload, the handshake's user proof among them, with another key. A peer that +verifies the proof refuses it. Same URL parameters as js.html (app, room, password, relays); its events are +joined {self, user}, signed {count} for each signature made, peer-join {peer, user} and error {code, error, peer}. --> @@ -34,94 +30,36 @@

 
 
 
diff --git a/test/oracle/interop/js.html b/test/oracle/interop/js.html
index d912785..a77728e 100644
--- a/test/oracle/interop/js.html
+++ b/test/oracle/interop/js.html
@@ -5,7 +5,8 @@
 accompanying file LICENSE_1_0.txt or copy at
 https://www.boost.org/LICENSE_1_0.txt)
 
-A Trystero JS peer of the interop test, which run.mjs opens in headless Chrome.
+A Trystero 0.27.0 peer of the interop test, which run.mjs opens in headless Chrome: what the C++ peers do
+(interop/peer_room.hpp), with the same parameters in the URL and the same events in window.events.
 -->
 
 
@@ -26,399 +27,122 @@
 
 

 
 
 
diff --git a/test/oracle/interop/native_peer.cpp b/test/oracle/interop/native_peer.cpp
index 2e1dd52..429c8a7 100644
--- a/test/oracle/interop/native_peer.cpp
+++ b/test/oracle/interop/native_peer.cpp
@@ -4,52 +4,27 @@
 // accompanying file LICENSE_1_0.txt or copy at
 // https://www.boost.org/LICENSE_1_0.txt)
 //
-// The native C++ side of the interop test: the browser peer's behaviour (peer.cpp), as a process.
-// The driver (run.mjs) starts it with the room's parameters, reads one JSON event per line on
-// stdout, and writes "leave" on stdin to make it leave, "replace" to move a room of another room
-// id over the joined one with a receive pending, "leave-room" to leave the first room and go on,
-// or "abort" to make it die by a signal, as a crash does. Diagnostics go to
-// stderr. Its peer connections are bound to 127.0.0.1, so that it meets the other peers of this
-// machine on the loopback alone, with no network beyond it.
-//
-// | Argument        | Meaning                                                            |
-// | --app, --room   | the app id and room id                                             |
-// | --password      | the app password, shared by all its rooms, optional                |
-// | --self          | this peer's id, optional                                           |
-// | --relays        | comma-separated relay URLs, optional (Trystero's default list)     |
-// | --ice           | a STUN or TURN server's URL, optional (Trystero's default list)    |
-// | --room2         | a second room of the same app id to join too, optional             |
-// | --room3         | a third room of the same app, optional                             |
-// | --room2Delay    | the ms before joining room2, optional (0)                          |
-// | --room3Delay    | the ms before joining room3, optional (0)                          |
-// | --idle          | the app's idle_timeout in ms, optional (123,333)                   |
-// | --handshake     | every room's handshake_timeout in ms, optional (10,000)            |
-// | --delayOpen     | defer native open delivery while transport messages arrive, optional |
-// | --ping2         | any value: ping each peer of room2 every second, optional          |
-#include 
-#include 
-#include 
+// The native C++ side of the interop test: the peer of peer_room.hpp as a process. The driver
+// (run.mjs) starts it with the parameters as arguments (`--room ` and so on), reads one JSON
+// event per line on stdout, and writes commands on stdin: "leave" to leave the room, after which
+// the process ends; "offline" and "online" to set the app's relay connectivity; "abort" to make it
+// die by a signal, as a crash does. The app's log goes to stderr. Its peer connections are bound
+// to 127.0.0.1, so that it meets the other peers of this machine on the loopback alone, with no
+// network beyond it, and each one the backend makes is the event `made-connection`, as cpp.html
+// counts the page's.
+#include "peer_room.hpp"
 
-#include 
-#include 
-#include 
-#include 
+#include 
 
 #include 
 #include 
 #include 
-#include 
 #include 
 
 #include 
-#include 
-#include 
-#include 
-#include 
-#include 
+#include 
 #include 
 #include 
-#include 
 #include 
 #include 
 #include 
@@ -57,112 +32,13 @@
 #include 
 #include 
 #include 
-#include 
-#include 
 
 namespace trystero = webcpp::trystero;
 
 namespace {
 
-/** Appends `text` as `JSON.stringify` writes a string; a text that is not UTF-8, which no
- * JavaScript string is, as `null`. */
-void append_string(std::string& out, std::string_view text) {
-    if (!webcpp::document::quote(text, out).has_value()) {
-        out += "null";
-    }
-}
-
-/** A field of an event for the driver: its key, and its value as JSON text. */
-struct field {
-    /** A string. */
-    field(std::string_view name, std::string_view text) : key(name) { append_string(json, text); }
-
-    /** An integer, in decimal. */
-    template 
-        requires(!std::same_as)
-    field(std::string_view name, I number) : key(name) {
-        std::array digits{};
-        const auto written = std::to_chars(digits.data(), digits.data() + digits.size(), number);
-        json.assign(digits.data(), written.ptr);
-    }
-
-    /** Strings, as an array of them. */
-    field(std::string_view name, std::span texts) : key(name) {
-        json += '[';
-        for (const auto& text : texts) {
-            if (json.size() > 1) {
-                json += ',';
-            }
-            append_string(json, text);
-        }
-        json += ']';
-    }
-
-    /** A JSON value, as `JSON.stringify` writes it. */
-    field(std::string_view name, const webcpp::document::document& value)
-        : key(name), json(value.stringify()) {}
-
-    /** The key. */
-    std::string_view key;
-    /** The value, as JSON text. */
-    std::string json;
-};
-
-/** An event for the driver: a kind and fields, one JSON object per line, the kind last. */
-void record(std::string_view kind, std::initializer_list fields = {}) {
-    std::string line = "{";
-    for (const field& f : fields) {
-        append_string(line, f.key);
-        line += ':';
-        line += f.json;
-        line += ',';
-    }
-    append_string(line, "kind");
-    line += ':';
-    append_string(line, kind);
-    line += '}';
-    // flushed: the driver reads each event from a pipe as it comes
-    std::cout << line << '\n' << std::flush;
-}
-
-/** Milliseconds from a parameter's digits, or `fallback` when it has none. */
-std::chrono::milliseconds millis(std::string_view text, std::chrono::milliseconds fallback) {
-    std::int64_t value = 0;
-    const char* const begin = text.data();
-    const char* const end = begin + text.size();
-    const auto [at, ec] = std::from_chars(begin, end, value);
-    return text.empty() || ec != std::errc{} || at != end || value < 0
-               ? fallback
-               : std::chrono::milliseconds(value);
-}
-
-/** The events the driver counts connections by, from the app's log lines
- * `connection with  adopted` and `connection with  ended: `. */
-void record_connection(std::string_view category, std::string_view text) {
-    constexpr std::string_view prefix = "connection with ";
-    constexpr std::string_view adopted = " adopted";
-    constexpr std::string_view ended = " ended: ";
-    if (category != "webrtc" || !text.starts_with(prefix)) {
-        return;
-    }
-    const auto rest = text.substr(prefix.size());
-    if (rest.ends_with(adopted)) {
-        record("adopted", {{"peer", rest.substr(0, rest.size() - adopted.size())}});
-    } else if (const auto at = rest.find(ended); at != std::string_view::npos) {
-        record("ended", {{"peer", rest.substr(0, at)}, {"reason", rest.substr(at + ended.size())}});
-    }
-}
-
-std::uint32_t checksum(const trystero::bytes& data) {
-    std::uint32_t sum = 0;
-    for (std::size_t i = 0; i < data.size(); ++i) {
-        sum += data[i] * static_cast(i + 1);
-    }
-    return sum;
-}
-
-std::map arguments(int argc, char* const* argv) {
-    std::map out;
+std::map> arguments(int argc, char* const* argv) {
+    std::map> out;
     for (int i = 1; i + 1 < argc; i += 2) {
         const std::string_view key = argv[i];
         if (key.starts_with("--")) {
@@ -172,340 +48,72 @@ std::map arguments(int argc, char* const* argv) {
     return out;
 }
 
-/** The app's configuration, from the driver's arguments. */
-trystero::app_config app_config_of(std::map& args) {
-    trystero::app_config config;
-    config.app_id = args["app"];
-    config.self_id = args["self"];
-    config.password = args["password"];
-    for (std::string_view relays = args["relays"]; !relays.empty();) {
-        const auto comma = relays.find(',');
-        config.relay_urls.emplace_back(relays.substr(0, comma));
-        relays = comma == std::string_view::npos ? std::string_view() : relays.substr(comma + 1);
-    }
-    if (!args["ice"].empty()) {
-        config.ice_servers.push_back(
-            {.urls = {std::pmr::string(args["ice"])}, .username = {}, .credential = {}});
-    }
-    config.idle_timeout = millis(args["idle"], std::chrono::milliseconds(123'333));
-    config.log = [](std::string_view category, std::string_view text) {
-        record_connection(category, text);
-        std::cerr << category << ": " << text << '\n';
-    };
-    return config;
+/** Writes one event, a line of JSON, on stdout. */
+void emit(std::string_view event) {
+    std::cout << event << '\n';
+    std::cout.flush();
 }
 
-/** A room's options: the driver's handshake timeout. */
-trystero::room_options options_of(std::map& args) {
-    return {
-        .handshake_timeout = millis(args["handshake"], std::chrono::milliseconds(10'000)),
-    };
-}
-
-/** Joins `room_id` through `app`; when the app refuses, the process ends after an event. */
-trystero::room join(trystero::app& app, const std::string& room_id,
-                    trystero::room_options options) {
-    auto joined = app.join(room_id, options);
-    if (!joined) {
-        record("not-joined", {{"room", room_id}, {"error", joined.error().message()}});
-        std::exit(1);
-    }
-    return std::move(*joined);
-}
-
-// A controlled native handoff: the transport is open, but signaling receives its open event
-// 100 ms later. Real messages still use the backend's WebRTC, including its pre-handoff queue.
-class delayed_channel : public trystero::backend::data_channel,
-                        public std::enable_shared_from_this {
-public:
-    delayed_channel(const boost::asio::any_io_executor& ex,
-                    std::shared_ptr channel)
-        : timer_(ex), channel_(std::move(channel)) {}
-
-    void set_handlers(handlers h) override {
-        timer_.cancel();
-        opening_ =
-            h.open ? std::make_shared>(std::move(h.open)) : nullptr;
-        if (opening_) {
-            const auto weak = weak_from_this();
-            h.open = [weak] {
-                if (const auto self = weak.lock()) {
-                    record("delayed-open");
-                    self->timer_.expires_after(std::chrono::milliseconds(100));
-                    self->timer_.async_wait([weak](boost::system::error_code ec) {
-                        if (const auto channel = weak.lock(); channel && !ec && channel->opening_) {
-                            channel->released_ = true;
-                            const auto callback = channel->opening_;
-                            (*callback)();
-                        }
-                    });
-                }
-            };
-        }
-        channel_->set_handlers(std::move(h));
-    }
-
-    bool is_open() const override { return released_ && channel_->is_open(); }
-
-    void send(std::span frame) override { channel_->send(frame); }
-
-    std::size_t buffered_amount() const override { return channel_->buffered_amount(); }
-
-    void close() override {
-        timer_.cancel();
-        channel_->close();
-    }
-
-private:
-    boost::asio::steady_timer timer_;
-    std::shared_ptr channel_;
-    std::shared_ptr> opening_;
-    bool released_ = false;
-};
-
-// Keeps the fixture's channel observer at both ends without changing SDP or ICE handling.
-class observed_connection : public trystero::backend::peer_connection {
-    using channel = std::shared_ptr;
-    using observer = std::function;
-
-public:
-    observed_connection(std::shared_ptr pc, observer observe)
-        : pc_(std::move(pc)), observe_(std::move(observe)) {}
-
-    void set_handlers(handlers h) override {
-        if (h.data_channel) {
-            h.data_channel = [observe = observe_, deliver = std::move(h.data_channel)](
-                                 channel c) mutable { deliver(observe(std::move(c))); };
-        }
-        pc_->set_handlers(std::move(h));
-    }
-
-    channel create_data_channel(std::string_view label) override {
-        auto c = pc_->create_data_channel(label);
-        return c ? observe_(std::move(c)) : nullptr;
-    }
-
-    void set_local_description(
-        trystero::handler done)
-        override {
-        pc_->set_local_description(std::move(done));
-    }
-
-    void set_remote_description(std::string_view type, std::string_view sdp,
-                                trystero::handler done) override {
-        pc_->set_remote_description(type, sdp, std::move(done));
-    }
-
-    void add_ice_candidate(std::string_view candidate,
-                           trystero::handler done) override {
-        pc_->add_ice_candidate(candidate, std::move(done));
-    }
-
-    [[nodiscard]] bool has_remote_description() const override {
-        return pc_->has_remote_description();
-    }
-
-    void close() override { pc_->close(); }
-
-private:
-    std::shared_ptr pc_;
-    observer observe_;
-};
-
-/** The platform backend, which records each peer connection it makes, for the scenarios that
- * count them. */
+/** The platform backend, whose every connection made is the event `made-connection`. */
 class counting_backend : public trystero::platform::backend {
 public:
-    explicit counting_backend(boost::asio::any_io_executor ex,
-                              const trystero::platform::backend_config& config)
-        : trystero::platform::backend(ex, config), ex_(std::move(ex)) {}
+    using trystero::platform::backend::backend;
 
     std::shared_ptr make_peer_connection(
         std::span servers,
         std::pmr::memory_resource* memory) override {
         auto pc = trystero::platform::backend::make_peer_connection(servers, memory);
         if (pc) {
-            record("made-connection");
-            if (delay_open) {
-                return std::make_shared(pc, [this](auto channel) {
-                    return std::make_shared(ex_, std::move(channel));
-                });
-            }
+            emit(R"({"kind":"made-connection"})");
         }
         return pc;
     }
-
-    bool delay_open = false;
-
-private:
-    boost::asio::any_io_executor ex_;
 };
 
-/**
- * A further room of the app: it sends each peer that joins a chat message and a 100 KB file,
- * echoes each chat message, and records what it sees with `room: `.
- */
-struct extra_room {
-    std::string which;
-    trystero::room room;
-    trystero::action chat = room.make_action("chat");
-    trystero::action file = room.make_action("file");
-
-    extra_room(trystero::app& app, std::string which_room, std::string_view room_id,
-               trystero::room_options options)
-        : which(std::move(which_room)), room(join(app, std::string(room_id), options)) {
-        record("joined", {{"room", which}, {"self", room.self_id()}});
-        room.on_peer_join([this](std::string_view peer_view) {
-            const trystero::peer_id peer(peer_view);
-            record("peer-join", {{"room", which}, {"peer", peer}});
-            chat.async_send("hello from C++",
-                            trystero::send_options{.targets = {peer}, .metadata = {}},
-                            [](boost::system::error_code) {});
-            trystero::bytes big(100'000);
-            for (std::size_t i = 0; i < big.size(); ++i) {
-                big[i] = static_cast((i * 13) % 256);
-            }
-            file.async_send(std::move(big),
-                            trystero::send_options{.targets = {peer}, .metadata = {}},
-                            [](boost::system::error_code) {});
-        });
-        room.on_peer_leave([this](std::string_view peer) {
-            record("peer-leave", {{"room", which}, {"peer", peer}});
-        });
-        room.on_error(
-            [this](std::string_view peer, boost::system::error_code ec, std::string_view what) {
-                record("error",
-                       {{"room", which}, {"peer", peer}, {"error", ec.message()}, {"what", what}});
-            });
-        chat.on_message([this](std::string text, const trystero::message_info& info) {
-            record("chat", {{"room", which}, {"from", info.from}, {"text", text}});
-            if (!text.starts_with("echo: ")) {
-                chat.async_send("echo: " + text,
-                                trystero::send_options{.targets = {info.from}, .metadata = {}},
-                                [](boost::system::error_code) {});
-            }
-        });
-        file.on_message([this](const trystero::bytes& data, const trystero::message_info& info) {
-            record("file", {
-                               {"room", which},
-                               {"from", info.from},
-                               {"size", data.size()},
-                               {"checksum", checksum(data)},
-                           });
-        });
-    }
-};
-
-/**
- * Moves `next` over `joined`, with a receive pending on the joined room: the receive, on an action
- * no peer sends, completes when the joined room is left, while the action keeps its state alive.
- */
-void replace(trystero::room& joined, trystero::room next) {
-    const auto pending =
-        std::make_shared>(joined.make_action("pending"));
-    pending->async_receive([pending](boost::system::error_code ec, const std::string& /*text*/,
-                                     const trystero::message_info& /*info*/) {
-        record("pending", {{"error", ec ? ec.message() : ""}});
-    });
-    joined = std::move(next);
-    record("replaced", {{"self", joined.self_id()}});
-}
-
-/** Leaves with Trystero's farewell, then stops `io`, which ends the process. */
-void leave(trystero::room& room, boost::asio::io_context& io) {
-    room.async_leave([&io](boost::system::error_code ec) {
-        record("left", {{"error", ec ? ec.message() : ""}});
-        io.stop();
-    });
-}
-
-/** Pings every joined peer of room2 once a second, with an id for each start and completion. */
-struct room_pinger {
-    boost::asio::steady_timer timer;
-    const std::unique_ptr& second;
-    std::uint64_t next_ping = 0;
-
-    room_pinger(boost::asio::io_context& io, const std::unique_ptr& room)
-        : timer(io), second(room) {}
-
-    void ping() {
-        if (second) {
-            for (const auto& peer : second->room.peers()) {
-                const auto id = ++next_ping;
-                record("ping-started", {{"room", "second"}, {"peer", peer}, {"id", id}});
-                second->room.async_ping(
-                    peer, [peer = trystero::peer_id(peer), id](boost::system::error_code ec,
-                                                               std::chrono::milliseconds rtt) {
-                        record("ping", {
-                                           {"room", "second"},
-                                           {"peer", peer},
-                                           {"id", id},
-                                           {"error", ec ? ec.message() : ""},
-                                           {"ms", rtt.count()},
-                                       });
-                    });
-            }
-        }
-        timer.expires_after(std::chrono::seconds(1));
-        timer.async_wait([this](boost::system::error_code ec) {
-            if (!ec) {
-                ping();
-            }
-        });
-    }
-};
-
-/** Reads the driver's commands while the rooms and timers continue running. */
+/** Reads the driver's commands while the room runs. */
 struct command_reader {
     boost::asio::io_context& io;
-    trystero::app& app;
-    trystero::room& room;
-    std::map& args;
+    interop::peer& peer;
     boost::asio::posix::stream_descriptor input;
     boost::asio::streambuf line;
-    std::function read_again;
 
-    command_reader(boost::asio::io_context& context, trystero::app& application,
-                   trystero::room& joined, std::map& arguments)
-        : io(context),
-          app(application),
-          room(joined),
-          args(arguments),
-          input(context, ::dup(STDIN_FILENO)),
-          read_again([this] { read(); }) {}
+    command_reader(boost::asio::io_context& context, interop::peer& p)
+        : io(context), peer(p), input(context, ::dup(STDIN_FILENO)) {}
 
     /** Whether another command should be read after this one. */
     bool handle(std::string_view command) {
         if (command.starts_with("abort")) {
             std::abort();
         }
-        if (command.starts_with("leave-room")) {
-            room.async_leave([](boost::system::error_code ec) {
-                record("left", {{"room", "first"}, {"error", ec ? ec.message() : ""}});
-            });
-            return true;
-        }
-        if (command.starts_with("replace")) {
-            replace(room, join(app, args["room"] + "-replaced", options_of(args)));
-            return true;
-        }
-        if (command.starts_with("leave")) {
-            leave(room, io);
+        if (command.starts_with("offline")) {
+            peer.set_connectivity(trystero::relay_connectivity::offline);
+        } else if (command.starts_with("online")) {
+            peer.set_connectivity(trystero::relay_connectivity::online);
+        } else if (command.starts_with("leave")) {
+            peer.leave([this] { io.stop(); });
             return false;
         }
         return true;
     }
 
+    /**
+     * Reads the next command.
+     *
+     * Tip: the reads are a loop of asynchronous operations, not a recursion: each completion runs
+     * once the call that started its read has returned. The next read is started through a
+     * pointer, so that the analysis of calls (misc-no-recursion) sees no cycle through Asio.
+     */
     void read() {
         boost::asio::async_read_until(
-            input, line, '\n', [this](boost::system::error_code ec, std::size_t size) {
+            input, line, '\n',
+            [this, again = &command_reader::read](boost::system::error_code ec, std::size_t size) {
                 if (ec) {
                     return;
                 }
                 const std::string command(static_cast(line.data().data()), size);
                 line.consume(size);
                 if (handle(command)) {
-                    read_again();
+                    (this->*again)();
                 }
             });
     }
@@ -514,109 +122,20 @@ struct command_reader {
 }  // namespace
 
 int main(int argc, char* argv[]) {
-    auto args = arguments(argc, argv);
+    const auto args = arguments(argc, argv);
     boost::asio::io_context io;
     counting_backend backend(io.get_executor(), {.bind_address = "127.0.0.1"});
-    backend.delay_open = !args["delayOpen"].empty();
-    trystero::app app(io.get_executor(), backend, app_config_of(args));
-    app.on_error([](std::string_view peer, boost::system::error_code ec, std::string_view what) {
-        record("error", {{"peer", peer}, {"error", ec.message()}, {"what", what}});
-    });
-    trystero::room room = join(app, args["room"], options_of(args));
-    record("joined", {{"self", room.self_id()}, {"relays", room.relay_urls()}});
-
-    auto chat = room.make_action("chat");
-    auto drink = room.make_action("drink");
-    auto file = room.make_action("file");
-
-    room.on_peer_join([&](std::string_view peer_view) {
-        const trystero::peer_id peer(peer_view);
-        record("peer-join", {{"peer", peer}});
-        // Each handler holds a copy of its own, not const, so that moving the handler moves it.
-        const auto done = [peer](const char* what) {
-            return [peer = trystero::peer_id(peer), what](boost::system::error_code ec) {
-                record("sent", {{"what", what}, {"peer", peer}, {"error", ec ? ec.message() : ""}});
-            };
-        };
-        chat.async_send("hello from C++", trystero::send_options{.targets = {peer}, .metadata = {}},
-                        done("chat"));
-        auto cafezinho =
-            webcpp::document::parse(R"({"drink":"cafezinho","withIce":false,"from":"c++"})");
-        if (cafezinho.has_value()) {
-            drink.async_send(std::move(*cafezinho),
-                             trystero::send_options{.targets = {peer}, .metadata = {}},
-                             done("drink"));
-        } else {
-            done("drink")(cafezinho.error());
-        }
-        trystero::bytes big(100'000);
-        for (std::size_t i = 0; i < big.size(); ++i) {
-            big[i] = static_cast((i * 13) % 256);
-        }
-        file.async_send(
-            std::move(big),
-            trystero::send_options{.targets = {peer}, .metadata = R"({"name":"from-cpp.bin"})"},
-            done("file"));
-        room.async_ping(peer, [peer = trystero::peer_id(peer)](boost::system::error_code ec,
-                                                               std::chrono::milliseconds rtt) {
-            record("ping", {
-                               {"peer", peer},
-                               {"error", ec ? ec.message() : ""},
-                               {"ms", rtt.count()},
-                           });
-        });
-    });
-    room.on_peer_leave([](std::string_view peer) { record("peer-leave", {{"peer", peer}}); });
-    room.on_error([](std::string_view peer, boost::system::error_code ec, std::string_view what) {
-        record("error", {{"peer", peer}, {"error", ec.message()}, {"what", what}});
-    });
-    chat.on_message([&](std::string text, const trystero::message_info& info) {
-        record("chat", {{"from", info.from}, {"text", text}});
-        if (!text.starts_with("echo: ")) {
-            chat.async_send("echo: " + text,
-                            trystero::send_options{.targets = {info.from}, .metadata = {}},
-                            [](boost::system::error_code) {});
-        }
-    });
-    drink.on_message([](const webcpp::document::document& v, const trystero::message_info& info) {
-        record("drink", {{"from", info.from}, {"value", v}});
-    });
-    file.on_message([](const trystero::bytes& data, const trystero::message_info& info) {
-        record("file", {
-                           {"from", info.from},
-                           {"size", data.size()},
-                           {"checksum", checksum(data)},
-                           {"metadata", info.metadata},
-                       });
-    });
-
-    std::unique_ptr second;
-    boost::asio::steady_timer second_delay(io);
-    if (!args["room2"].empty()) {
-        second_delay.expires_after(millis(args["room2Delay"], std::chrono::milliseconds(0)));
-        second_delay.async_wait([&](boost::system::error_code ec) {
-            if (!ec) {
-                second =
-                    std::make_unique(app, "second", args["room2"], options_of(args));
-            }
-        });
-    }
-    std::unique_ptr third;
-    boost::asio::steady_timer third_delay(io);
-    if (!args["room3"].empty()) {
-        third_delay.expires_after(millis(args["room3Delay"], std::chrono::milliseconds(0)));
-        third_delay.async_wait([&](boost::system::error_code ec) {
-            if (!ec) {
-                third = std::make_unique(app, "third", args["room3"], options_of(args));
-            }
+    interop::peer peer(
+        io.get_executor(), backend,
+        [&args](std::string_view name) {
+            const auto found = args.find(name);
+            return found == args.end() ? std::string() : found->second;
+        },
+        emit,
+        [](std::string_view category, std::string_view text) {
+            std::cerr << category << ": " << text << '\n';
         });
-    }
-    room_pinger pinger(io, second);
-    if (!args["room2"].empty() && !args["ping2"].empty()) {
-        pinger.ping();
-    }
-
-    command_reader commands(io, app, room, args);
+    command_reader commands(io, peer);
     commands.read();
     io.run();  // lint-run: a process whose purpose is network I/O, until "leave" stops it
 }
diff --git a/test/oracle/interop/peer.cpp b/test/oracle/interop/peer.cpp
index d75b16a..58cea81 100644
--- a/test/oracle/interop/peer.cpp
+++ b/test/oracle/interop/peer.cpp
@@ -4,90 +4,31 @@
 // accompanying file LICENSE_1_0.txt or copy at
 // https://www.boost.org/LICENSE_1_0.txt)
 //
-// The C++ side of the interop test: a page that joins a room with the library, built for the
-// browser. The driver (run.mjs) configures it through the URL and reads what happened from
-// `window.events`. Its main starts the peer and runs the io_context for the page's life, under a
-// work guard; the driver's one call, `window.leave`, a `platform::page_call`, only posts to it.
-//
-// | Query parameter | Meaning                                                            |
-// | app, room       | the app id and room id                                             |
-// | password        | the app password, shared by all its rooms, optional                |
-// | self            | this peer's id, optional                                           |
-// | relays          | comma-separated relay URLs, optional (Trystero's default list)     |
-// | ice             | a STUN or TURN server's URL, optional (Trystero's default list)    |
-// | room2           | a second room of the same app id to join too, optional             |
-// | room3           | a third room of the same app, optional                             |
-// | room2Delay      | the ms before joining room2, optional (0)                          |
-// | room3Delay      | the ms before joining room3, optional (0)                          |
-// | idle            | the app's idle_timeout in ms, optional (123,333)                   |
-// | handshake       | every room's handshake_timeout in ms, optional (10,000)            |
-// | ping2           | any value: ping each peer of room2 every second, optional          |
-// | program         | the program's JavaScript, which cpp.html loads; not read here      |
-#include 
+// The browser's C++ side of the interop test: the peer of peer_room.hpp in a page (cpp.html),
+// built with Emscripten. The driver (run.mjs) gives the parameters in the page's URL, reads the
+// events from `window.events`, and calls `window.leave`, `window.offline` and `window.online`,
+// each a `platform::page_call` that posts to the io_context, which main runs for the page's life
+// under a work guard. The app's log goes to `window.trysteroLog`. The URL's `program` names the
+// program's JavaScript, which cpp.html loads; the peer does not read it.
+#include "peer_room.hpp"
+
 #include 
 #include 
 
 #include 
 #include 
 
-#include 
-#include 
-#include 
-#include 
-
 #include 
 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
+#include 
 #include 
 #include 
-#include 
 
 using emscripten::val;
 namespace trystero = webcpp::trystero;
 
 namespace {
 
-/** A further room of the app, room2 or room3, and its actions; its events carry `room: `. */
-struct extra_room {
-    std::string which;
-    std::unique_ptr room;
-    std::unique_ptr> chat;
-    std::unique_ptr> file;
-};
-
-/** Everything the page keeps alive: the io_context, the backend, the app, the room and its
- * actions. */
-struct page {
-    webcpp::asio::io_context io;
-    trystero::platform::backend backend{io.get_executor()};
-    std::unique_ptr app;
-    std::unique_ptr room;
-    std::unique_ptr> chat;
-    std::unique_ptr> drink;
-    std::unique_ptr> file;
-    extra_room second{.which = "second", .room = {}, .chat = {}, .file = {}};
-    extra_room third{.which = "third", .room = {}, .chat = {}, .file = {}};
-    std::shared_ptr second_delay;
-    std::shared_ptr third_delay;
-    std::shared_ptr pinger;
-    std::uint64_t next_ping = 0;
-};
-
-/** The page's one state, which main runs and the driver's calls post to, kept as long as the tab.
- */
-page& the_page() {
-    static page state;
-    return state;
-}
-
 std::string param(std::string_view name) {
     const val value = val::global("URLSearchParams")
                           .new_(val::global("location")["search"])
@@ -95,352 +36,45 @@ std::string param(std::string_view name) {
     return value.isNull() ? std::string() : value.as();
 }
 
-/** Appends `text` as `JSON.stringify` writes a string; a text that is not UTF-8, which no
- * JavaScript string is, as `null`. */
-void append_string(std::string& out, std::string_view text) {
-    if (!webcpp::document::quote(text, out).has_value()) {
-        out += "null";
-    }
-}
-
-/** A field of an event for the driver: its key, and its value as JSON text. */
-struct field {
-    /** A string. */
-    field(std::string_view name, std::string_view text) : key(name) { append_string(json, text); }
-
-    /** An integer, in decimal. */
-    template 
-        requires(!std::same_as)
-    field(std::string_view name, I number) : key(name) {
-        std::array digits{};
-        const auto written = std::to_chars(digits.data(), digits.data() + digits.size(), number);
-        json.assign(digits.data(), written.ptr);
-    }
-
-    /** Strings, as an array of them. */
-    field(std::string_view name, std::span texts) : key(name) {
-        json += '[';
-        for (const auto& text : texts) {
-            if (json.size() > 1) {
-                json += ',';
-            }
-            append_string(json, text);
-        }
-        json += ']';
-    }
-
-    /** A JSON value, as `JSON.stringify` writes it. */
-    field(std::string_view name, const webcpp::document::document& value)
-        : key(name), json(value.stringify()) {}
-
-    /** The key. */
-    std::string_view key;
-    /** The value, as JSON text. */
-    std::string json;
+/** What the page keeps for its life, as long as the tab: the io_context, the backend and the
+ * peer. */
+struct page {
+    webcpp::asio::io_context io;
+    trystero::platform::backend backend{io.get_executor()};
+    std::optional peer;
 };
 
-/** An event for the driver: a kind and fields, pushed to `window.events`, the kind last. */
-void record(std::string_view kind, std::initializer_list fields = {}) {
-    std::string text = "{";
-    for (const field& f : fields) {
-        append_string(text, f.key);
-        text += ':';
-        text += f.json;
-        text += ',';
-    }
-    append_string(text, "kind");
-    text += ':';
-    append_string(text, kind);
-    text += '}';
-    val::global("window")["events"].call("push",
-                                               val::global("JSON").call("parse", val(text)));
-}
-
-/** Milliseconds from a parameter's digits, or `fallback` when it has none. */
-std::chrono::milliseconds millis(std::string_view text, std::chrono::milliseconds fallback) {
-    std::int64_t value = 0;
-    const char* const begin = text.data();
-    const char* const end = begin + text.size();
-    const auto [at, ec] = std::from_chars(begin, end, value);
-    return text.empty() || ec != std::errc{} || at != end || value < 0
-               ? fallback
-               : std::chrono::milliseconds(value);
-}
-
-/** The events the driver counts connections by, from the app's log lines
- * `connection with  adopted` and `connection with  ended: `. */
-void record_connection(std::string_view category, std::string_view text) {
-    constexpr std::string_view prefix = "connection with ";
-    constexpr std::string_view adopted = " adopted";
-    constexpr std::string_view ended = " ended: ";
-    if (category != "webrtc" || !text.starts_with(prefix)) {
-        return;
-    }
-    const auto rest = text.substr(prefix.size());
-    if (rest.ends_with(adopted)) {
-        record("adopted", {{"peer", rest.substr(0, rest.size() - adopted.size())}});
-    } else if (const auto at = rest.find(ended); at != std::string_view::npos) {
-        record("ended", {{"peer", rest.substr(0, at)}, {"reason", rest.substr(at + ended.size())}});
-    }
-}
-
-void log(std::string_view category, std::string_view text) {
-    record_connection(category, text);
-    val::global("window").call("trysteroLog", trystero::platform::js_string(category),
-                                     trystero::platform::js_string(text));
-}
-
-/** A checksum the driver can compare without moving the payload: sum of bytes times their position,
- * mod 2^32. */
-std::uint32_t checksum(const trystero::bytes& data) {
-    std::uint32_t sum = 0;
-    for (std::size_t i = 0; i < data.size(); ++i) {
-        sum += data[i] * static_cast(i + 1);
-    }
-    return sum;
-}
-
-/** The app's configuration, from the URL. */
-trystero::app_config config_of_page() {
-    trystero::app_config config;
-    config.app_id = param("app");
-    config.self_id = param("self");
-    config.password = param("password");
-    for (std::string relays = param("relays"); !relays.empty();) {
-        const auto comma = relays.find(',');
-        config.relay_urls.emplace_back(relays.substr(0, comma));
-        relays = comma == std::string::npos ? std::string() : relays.substr(comma + 1);
-    }
-    if (const std::string ice = param("ice"); !ice.empty()) {
-        config.ice_servers.push_back(
-            {.urls = {std::pmr::string(ice)}, .username = {}, .credential = {}});
-    }
-    config.idle_timeout = millis(param("idle"), std::chrono::milliseconds(123'333));
-    config.log = log;
-    return config;
-}
-
-/** A room's options: the page's handshake timeout. */
-trystero::room_options options_of_page() {
-    return {
-        .handshake_timeout = millis(param("handshake"), std::chrono::milliseconds(10'000)),
-    };
-}
-
-/** Joins `room_id` through `app`; null, with an event, when the app refuses. */
-std::unique_ptr join(trystero::app& app, const std::string& room_id,
-                                     std::string_view which) {
-    auto joined = app.join(room_id, options_of_page());
-    if (!joined) {
-        record("not-joined", {{"room", which}, {"error", joined.error().message()}});
-        return nullptr;
-    }
-    return std::make_unique(std::move(*joined));
-}
-
-/**
- * Joins `room_id`, a further room of the app, as `extra`: it sends each peer that joins a chat
- * message and a 100 KB file, echoes each chat message it receives, and records what it sees with
- * `room: `.
- */
-void join_extra(extra_room& extra, std::string_view room_id) {
-    page& app = the_page();
-    auto joined = app.app->join(room_id, options_of_page());
-    if (!joined) {
-        record("error", {
-                            {"room", extra.which},
-                            {"peer", ""},
-                            {"error", joined.error().message()},
-                            {"what", "join"},
-                        });
-        return;
-    }
-    extra.room = std::make_unique(std::move(*joined));
-    extra.chat = std::make_unique>(
-        extra.room->make_action("chat"));
-    extra.file = std::make_unique>(
-        extra.room->make_action("file"));
-    record("joined", {{"room", extra.which}, {"self", extra.room->self_id()}});
-    extra.room->on_peer_join([&extra](std::string_view peer_view) {
-        const trystero::peer_id peer(peer_view);
-        record("peer-join", {{"room", extra.which}, {"peer", peer}});
-        extra.chat->async_send("hello from C++",
-                               trystero::send_options{.targets = {peer}, .metadata = {}},
-                               [](boost::system::error_code) {});
-        trystero::bytes big(100'000);
-        for (std::size_t i = 0; i < big.size(); ++i) {
-            big[i] = static_cast((i * 13) % 256);
-        }
-        extra.file->async_send(std::move(big),
-                               trystero::send_options{.targets = {peer}, .metadata = {}},
-                               [](boost::system::error_code) {});
-    });
-    extra.room->on_peer_leave([&extra](std::string_view peer) {
-        record("peer-leave", {{"room", extra.which}, {"peer", peer}});
-    });
-    extra.room->on_error([&extra](std::string_view peer, boost::system::error_code ec,
-                                  std::string_view what) {
-        record("error",
-               {{"room", extra.which}, {"peer", peer}, {"error", ec.message()}, {"what", what}});
-    });
-    extra.chat->on_message([&extra](std::string text, const trystero::message_info& info) {
-        record("chat", {{"room", extra.which}, {"from", info.from}, {"text", text}});
-        if (!text.starts_with("echo: ")) {
-            extra.chat->async_send("echo: " + text,
-                                   trystero::send_options{.targets = {info.from}, .metadata = {}},
-                                   [](boost::system::error_code) {});
-        }
-    });
-    extra.file->on_message(
-        [&extra](const trystero::bytes& data, const trystero::message_info& info) {
-            record("file", {
-                               {"room", extra.which},
-                               {"from", info.from},
-                               {"size", data.size()},
-                               {"checksum", checksum(data)},
-                           });
-        });
-}
-
-/** Pings every peer of room2, then again a second later, recording each with `room: second`. */
-void ping_second() {
-    page& app = the_page();
-    if (app.second.room) {
-        for (const auto& peer : app.second.room->peers()) {
-            const auto id = ++app.next_ping;
-            record("ping-started", {{"room", "second"}, {"peer", peer}, {"id", id}});
-            app.second.room->async_ping(
-                peer, [peer = trystero::peer_id(peer), id](boost::system::error_code ec,
-                                                           std::chrono::milliseconds rtt) {
-                    record("ping", {
-                                       {"room", "second"},
-                                       {"peer", peer},
-                                       {"id", id},
-                                       {"error", ec ? ec.message() : ""},
-                                       {"ms", rtt.count()},
-                                   });
-                });
-        }
-    }
-    app.pinger->start(std::chrono::seconds(1), [] { ping_second(); });
-}
-
-void start() {
-    page& app = the_page();
-    app.app = std::make_unique(app.io.get_executor(), app.backend, config_of_page());
-    app.app->on_error(
-        [](std::string_view peer, boost::system::error_code ec, std::string_view what) {
-            record("error", {{"peer", peer}, {"error", ec.message()}, {"what", what}});
-        });
-    app.room = join(*app.app, param("room"), "first");
-    if (!app.room) {
-        return;
-    }
-    auto& room = *app.room;
-    record("joined", {{"self", room.self_id()}, {"relays", room.relay_urls()}});
-
-    app.chat =
-        std::make_unique>(room.make_action("chat"));
-    app.drink = std::make_unique>(
-        room.make_action("drink"));
-    app.file = std::make_unique>(
-        room.make_action("file"));
-
-    room.on_peer_join([](std::string_view peer_view) {
-        const trystero::peer_id peer(peer_view);
-        record("peer-join", {{"peer", peer}});
-        // Each handler holds a copy of its own, not const, so that moving the handler moves it.
-        const auto done = [peer](const char* what) {
-            return [peer = trystero::peer_id(peer), what](boost::system::error_code ec) {
-                record("sent", {{"what", what}, {"peer", peer}, {"error", ec ? ec.message() : ""}});
-            };
-        };
-        const trystero::send_options to_peer{.targets = {peer}, .metadata = {}};
-        the_page().chat->async_send("hello from C++", to_peer, done("chat"));
-        auto cafezinho =
-            webcpp::document::parse(R"({"drink":"cafezinho","withIce":false,"from":"c++"})");
-        if (cafezinho.has_value()) {
-            the_page().drink->async_send(std::move(*cafezinho), to_peer, done("drink"));
-        } else {
-            done("drink")(cafezinho.error());
-        }
-        trystero::bytes big(100'000);
-        for (std::size_t i = 0; i < big.size(); ++i) {
-            big[i] = static_cast((i * 13) % 256);
-        }
-        the_page().file->async_send(
-            big,
-            trystero::send_options{.targets = {peer}, .metadata = R"({"name":"from-cpp.bin"})"},
-            done("file"));
-        the_page().room->async_ping(
-            peer, [peer = trystero::peer_id(peer)](boost::system::error_code ec,
-                                                   std::chrono::milliseconds rtt) {
-                record("ping", {
-                                   {"peer", peer},
-                                   {"error", ec ? ec.message() : ""},
-                                   {"ms", rtt.count()},
-                               });
-            });
-    });
-    room.on_peer_leave([](std::string_view peer) { record("peer-leave", {{"peer", peer}}); });
-    room.on_error([](std::string_view peer, boost::system::error_code ec, std::string_view what) {
-        record("error", {{"peer", peer}, {"error", ec.message()}, {"what", what}});
-    });
-    app.chat->on_message([](std::string text, const trystero::message_info& info) {
-        record("chat", {{"from", info.from}, {"text", text}});
-        if (!text.starts_with("echo: ")) {
-            the_page().chat->async_send(
-                "echo: " + text, trystero::send_options{.targets = {info.from}, .metadata = {}},
-                [](boost::system::error_code) {});
-        }
-    });
-    app.drink->on_message(
-        [](const webcpp::document::document& v, const trystero::message_info& info) {
-            record("drink", {{"from", info.from}, {"value", v}});
-        });
-    app.file->on_message([](const trystero::bytes& data, const trystero::message_info& info) {
-        record("file", {
-                           {"from", info.from},
-                           {"size", data.size()},
-                           {"checksum", checksum(data)},
-                           {"metadata", info.metadata},
-                       });
-    });
-    if (!param("room2").empty()) {
-        app.second_delay = app.backend.make_timer(std::pmr::get_default_resource());
-        app.second_delay->start(millis(param("room2Delay"), std::chrono::milliseconds(0)),
-                                [] { join_extra(the_page().second, param("room2")); });
-    }
-    if (!param("room3").empty()) {
-        app.third_delay = app.backend.make_timer(std::pmr::get_default_resource());
-        app.third_delay->start(millis(param("room3Delay"), std::chrono::milliseconds(0)),
-                               [] { join_extra(the_page().third, param("room3")); });
-    }
-    if (!param("ping2").empty()) {
-        app.pinger = app.backend.make_timer(std::pmr::get_default_resource());
-        ping_second();
-    }
-}
-
-/** The driver's call, `window.leave`: leaves the room with Trystero's farewell. */
-void leave() {
-    if (!the_page().room) {
-        return;
-    }
-    the_page().room->async_leave(
-        [](boost::system::error_code ec) { record("left", {{"error", ec ? ec.message() : ""}}); });
+page& the_page() {
+    static page state;
+    return state;
 }
 
 }  // namespace
 
 int main() {
-    page& app = the_page();
+    auto& [io, backend, made] = the_page();
+    auto& peer = made.emplace(
+        io.get_executor(), backend, param,
+        [](std::string_view event) {
+            val::global("window")["events"].call(
+                "push", val::global("JSON").call("parse", val(std::string(event))));
+        },
+        [](std::string_view category, std::string_view text) {
+            val::global("window").call("trysteroLog", trystero::platform::js_string(category),
+                                             trystero::platform::js_string(text));
+        });
     // Between the driver's calls the page may have no work: the guard keeps the run going.
-    const auto guard = webcpp::asio::make_work_guard(app.io);
-    // The driver's one call, a function of webcpp::asio's bridge that posts the leave.
-    const trystero::platform::page_call leave_call(app.io.get_executor(),
-                                                   [](const val& /*argument*/) { leave(); });
-    val::global("window").set("leave", leave_call.function());
-    start();
-    app.io.run();  // lint-run: the page's program, suspended into the browser's event loop
+    const auto guard = webcpp::asio::make_work_guard(io);
+    const trystero::platform::page_call leave(io.get_executor(),
+                                              [&peer](const val& /*argument*/) { peer.leave(); });
+    const trystero::platform::page_call offline(io.get_executor(), [&peer](const val&) {
+        peer.set_connectivity(trystero::relay_connectivity::offline);
+    });
+    const trystero::platform::page_call online(io.get_executor(), [&peer](const val&) {
+        peer.set_connectivity(trystero::relay_connectivity::online);
+    });
+    val::global("window").set("leave", leave.function());
+    val::global("window").set("offline", offline.function());
+    val::global("window").set("online", online.function());
+    io.run();  // lint-run: the page's program, suspended into the browser's event loop
 }
diff --git a/test/oracle/interop/peer_room.hpp b/test/oracle/interop/peer_room.hpp
new file mode 100644
index 0000000..9875bc9
--- /dev/null
+++ b/test/oracle/interop/peer_room.hpp
@@ -0,0 +1,398 @@
+// Copyright (c) 2026 WebCpp.org
+//
+// Distributed under the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// https://www.boost.org/LICENSE_1_0.txt)
+//
+// What both C++ peers of the interop test do, the browser's (peer.cpp) and the native one
+// (native_peer.cpp): one app, one room, its actions and its listeners, configured by named
+// parameters and reporting each event as a line of JSON, as js.html does for Trystero 0.27.0.
+// Each peer gives its parameters, where the events go and where the app's log goes.
+//
+// | Parameter | Meaning                                                                       |
+// | app, room | the app id and room id                                                        |
+// | password  | the app password, optional                                                    |
+// | relays    | comma-separated relay URLs, optional (Trystero's default list)                |
+// | ice       | a STUN or TURN server's URL, optional (Trystero's default list)               |
+// | identity  | a user identity's text (`trystero_uk_...`) the app imports, optional          |
+// | export    | any value: the app's user is a new identity, whose text the `identity` event  |
+// |           | carries, optional                                                             |
+// | maxUsers  | the room's `max_users`, optional                                              |
+// | wide      | any value: each peer that joins is also sent 1 MiB on the action `wide`       |
+// | offline   | any value: the app's relays are offline before it joins, until `online`       |
+// | key       | a label whose SHA-256 is the app's endpoint key, so that the driver knows the |
+// |           | peer id before the peer joins, optional                                       |
+//
+// | Event      | Fields                                                                     |
+// | joined     | self, user (`app::self_id`, `app::user_id`), relays                        |
+// | identity   | text, user: the exported identity (with `export`)                          |
+// | peer-join  | peer, user                                                                 |
+// | peer-leave | peer, user                                                                 |
+// | user-join  | user, peer                                                                 |
+// | user-leave | user, peer                                                                 |
+// | chat, drink, file, wide | from, and the text, the JSON value, or size, checksum, metadata |
+// | request    | from, text: a request this peer answered                                   |
+// | response   | peer, text, error: the answer to this peer's request                       |
+// | ping       | peer, ms, error                                                            |
+// | sent       | what, peer, error                                                          |
+// | error      | code (0.27.0's name, or the code's message), error (the message), peer     |
+// | left       | error                                                                      |
+#ifndef WEBCPP_TRYSTERO_TEST_INTEROP_PEER_ROOM_HPP
+#define WEBCPP_TRYSTERO_TEST_INTEROP_PEER_ROOM_HPP
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace interop {
+
+namespace trystero = webcpp::trystero;
+
+/** Appends `text` as `JSON.stringify` writes a string; a text that is not UTF-8, which no
+ * JavaScript string is, as `null`. */
+inline void append_string(std::string& out, std::string_view text) {
+    if (!webcpp::document::quote(text, out).has_value()) {
+        out += "null";
+    }
+}
+
+/** A field of an event for the driver: its key, and its value as JSON text. */
+struct field {
+    /** A string. */
+    field(std::string_view name, std::string_view text) : key(name) { append_string(json, text); }
+
+    /** An integer, in decimal. */
+    template 
+        requires(!std::same_as)
+    field(std::string_view name, I number) : key(name) {
+        std::array digits{};
+        const auto written = std::to_chars(digits.data(), digits.data() + digits.size(), number);
+        json.assign(digits.data(), written.ptr);
+    }
+
+    /** Strings, as an array of them. */
+    field(std::string_view name, std::span texts) : key(name) {
+        json += '[';
+        for (const auto& text : texts) {
+            if (json.size() > 1) {
+                json += ',';
+            }
+            append_string(json, text);
+        }
+        json += ']';
+    }
+
+    /** A JSON value, as `JSON.stringify` writes it. */
+    field(std::string_view name, const webcpp::document::document& value)
+        : key(name), json(value.stringify()) {}
+
+    /** The key. */
+    std::string_view key;
+    /** The value, as JSON text. */
+    std::string json;
+};
+
+/** The parameters of a peer, by name: empty for one not given. */
+using parameters = std::function;
+
+/** Where a peer's events go, each one JSON object. */
+using event_sink = std::function;
+
+/** The checksum the driver compares payloads by: the sum of each byte times its position, mod
+ * 2^32. */
+inline std::uint32_t checksum(std::span data) {
+    std::uint32_t sum = 0;
+    for (std::size_t i = 0; i < data.size(); ++i) {
+        sum += data[i] * static_cast(i + 1);
+    }
+    return sum;
+}
+
+/** `size` bytes, byte i being (i * step) mod 256: the payloads the driver knows the checksums of.
+ */
+inline trystero::bytes pattern(std::size_t size, std::size_t step) {
+    trystero::bytes out(size);
+    for (std::size_t i = 0; i < size; ++i) {
+        out[i] = static_cast((i * step) % 256);
+    }
+    return out;
+}
+
+/** The app's configuration, from the parameters, its log going to `log`. */
+inline trystero::app_config config_of(const parameters& param, trystero::detail::logger::sink log) {
+    trystero::app_config config;
+    config.app_id = param("app");
+    config.password = param("password");
+    for (std::string relays = param("relays"); !relays.empty();) {
+        const auto comma = relays.find(',');
+        config.relay_urls.emplace_back(relays.substr(0, comma));
+        relays = comma == std::string::npos ? std::string() : relays.substr(comma + 1);
+    }
+    if (const std::string ice = param("ice"); !ice.empty()) {
+        config.ice_servers.push_back(
+            {.urls = {std::pmr::string(ice)}, .username = {}, .credential = {}});
+    }
+    config.log = std::move(log);
+    return config;
+}
+
+/**
+ * A C++ peer of the interop test: its app and its room, which sends each peer that joins a chat
+ * message, a JSON value, a 100 KB file (and 1 MiB with `wide`), a request and a ping, and echoes
+ * each chat message, as js.html's page does.
+ */
+class peer {
+public:
+    /**
+     * Makes the app and joins the room; an app or a room that cannot be made reports `error`
+     * events, and the peer does nothing more.
+     *
+     * @param ex The app's executor.
+     * @param factory The backend.
+     * @param param The parameters.
+     * @param emit Where the events go.
+     * @param log Where the app's log goes.
+     */
+    peer(const trystero::app::executor_type& ex, trystero::backend::factory& factory,
+         const parameters& param, event_sink emit, trystero::detail::logger::sink log)
+        : emit_(std::move(emit)) {
+        auto config = config_of(param, std::move(log));
+        if (const std::string text = param("identity"); !text.empty()) {
+            auto imported = trystero::import_user_identity(text);
+            if (!imported) {
+                record("error",
+                       {{"code", "identity-import"}, {"error", imported.error().message()}});
+                return;
+            }
+            config.identity = *imported;
+        } else if (!param("export").empty()) {
+            auto created = trystero::create_user_identity();
+            if (!created) {
+                record("error",
+                       {{"code", "identity-create"}, {"error", created.error().message()}});
+                return;
+            }
+            record("identity", {
+                                   {"text", trystero::export_user_identity(*created)},
+                                   {"user", created->user_id()},
+                               });
+            config.identity = *created;
+        }
+        if (const std::string key = param("key"); !key.empty()) {
+            // The app's endpoint key, named by its label (its scalar is the label's SHA-256),
+            // through the app's detail seam, which the library keeps for its own tests: 0.27.0 has
+            // no option for it. The driver derives the peer id from the label, to order the peers'
+            // ids.
+            app_.emplace(trystero::detail::app_access::make(ex, factory, std::move(config),
+                                                            trystero::protocol::sha256(key)));
+        } else {
+            app_.emplace(ex, factory, std::move(config));
+        }
+        app_->on_error([this](const trystero::room_error& e) { record_error(e); });
+        if (!param("offline").empty()) {
+            app_->set_relay_connectivity(trystero::relay_connectivity::offline);
+        }
+        trystero::room_options options;
+        if (const std::string max = param("maxUsers"); !max.empty()) {
+            options.max_users = std::stoul(max);
+        }
+        auto joined = app_->join(param("room"), options);
+        if (!joined) {
+            record("error", {{"code", "join"}, {"error", joined.error().message()}});
+            return;
+        }
+        room_.emplace(std::move(*joined));
+        wide_ = !param("wide").empty();
+        record("joined", {
+                             {"self", app_->self_id()},
+                             {"user", app_->user_id()},
+                             {"relays", room_->relay_urls()},
+                         });
+        listen();
+    }
+
+    /** Leaves the room with Trystero's farewell; `then` runs once it is left. */
+    void leave(std::function then = {}) {
+        if (!room_) {
+            return;
+        }
+        room_->async_leave([this, then = std::move(then)](boost::system::error_code ec) {
+            record("left", {{"error", ec ? ec.message() : ""}});
+            if (then) {
+                then();
+            }
+        });
+    }
+
+    /** Sets the app's relay connectivity, `setRelayConnectivity`. */
+    void set_connectivity(trystero::relay_connectivity mode) {
+        if (app_) {
+            app_->set_relay_connectivity(mode);
+            record(
+                "connectivity",
+                {{"mode", mode == trystero::relay_connectivity::offline ? "offline" : "online"}});
+        }
+    }
+
+private:
+    /** An event: a kind and fields, the kind last. */
+    void record(std::string_view kind, std::initializer_list fields = {}) const {
+        std::string text = "{";
+        for (const field& f : fields) {
+            append_string(text, f.key);
+            text += ':';
+            text += f.json;
+            text += ',';
+        }
+        append_string(text, "kind");
+        text += ':';
+        append_string(text, kind);
+        text += '}';
+        emit_(text);
+    }
+
+    /** An error, its code by 0.27.0's name, or by its message for a code 0.27.0 has not. */
+    void record_error(const trystero::room_error& e) const {
+        const std::string_view name = trystero::room_error_code_name(e.code);
+        record("error", {
+                            {"code", name.empty() ? e.code.message() : std::string(name)},
+                            {"error", e.message},
+                            {"peer", e.peer_id},
+                        });
+    }
+
+    /** A completion of a send to `peer` that records it as `what`; it holds its own copies, which
+     * its moves move rather than copy. */
+    [[nodiscard]] auto sent(std::string_view what, const trystero::peer_id& peer) const {
+        return [this, what = std::string(what),
+                peer = trystero::peer_id(peer)](boost::system::error_code ec) {
+            record("sent", {{"what", what}, {"peer", peer}, {"error", ec ? ec.message() : ""}});
+        };
+    }
+
+    void greet(const trystero::peer_id& peer) {
+        const auto to = [&peer](std::string_view metadata = {}) {
+            return trystero::send_options{
+                .targets = {peer},
+                .metadata = std::pmr::string(metadata),
+            };
+        };
+        chat_->async_send("hello from C++", to(), sent("chat", peer));
+        auto cafezinho =
+            webcpp::document::parse(R"({"drink":"cafezinho","withIce":false,"from":"c++"})");
+        if (cafezinho.has_value()) {
+            drink_->async_send(std::move(*cafezinho), to(), sent("drink", peer));
+        }
+        file_->async_send(pattern(100'000, 13), to(R"({"name":"from-cpp.bin"})"),
+                          sent("file", peer));
+        if (wide_) {
+            wide_action_->async_send(pattern(std::size_t{1024} * 1024, 13), to(),
+                                     sent("wide", peer));
+        }
+        question_->async_request(
+            "question from C++", trystero::request_options{.target = peer, .metadata = {}},
+            [this, peer = trystero::peer_id(peer)](boost::system::error_code ec,
+                                                   std::string answer) {
+                record("response",
+                       {{"peer", peer}, {"text", answer}, {"error", ec ? ec.message() : ""}});
+            });
+        room_->async_ping(peer, [this, peer = trystero::peer_id(peer)](
+                                    boost::system::error_code ec, std::chrono::milliseconds rtt) {
+            record("ping",
+                   {{"peer", peer}, {"error", ec ? ec.message() : ""}, {"ms", rtt.count()}});
+        });
+    }
+
+    void listen() {
+        auto& room = *room_;
+        chat_.emplace(room.make_action("chat"));
+        drink_.emplace(room.make_action("drink"));
+        file_.emplace(room.make_action("file"));
+        wide_action_.emplace(room.make_action("wide"));
+        question_.emplace(room.make_request_action("question"));
+        room.on_peer_join([this](const trystero::peer_event& e) {
+            const trystero::peer_id peer(e.peer_id);
+            record("peer-join", {{"peer", e.peer_id}, {"user", e.user_id}});
+            greet(peer);
+        });
+        room.on_peer_leave([this](const trystero::peer_event& e) {
+            record("peer-leave", {{"peer", e.peer_id}, {"user", e.user_id}});
+        });
+        room.on_user_join([this](const trystero::user_event& e) {
+            record("user-join", {{"user", e.user_id}, {"peer", e.peer_id}});
+        });
+        room.on_user_leave([this](const trystero::user_event& e) {
+            record("user-leave", {{"user", e.user_id}, {"peer", e.peer_id}});
+        });
+        room.on_error([this](const trystero::room_error& e) { record_error(e); });
+        chat_->on_message([this](std::string text, const trystero::message_info& info) {
+            record("chat", {{"from", info.from}, {"text", text}});
+            if (!text.starts_with("echo: ")) {
+                chat_->async_send("echo: " + text,
+                                  trystero::send_options{.targets = {info.from}, .metadata = {}},
+                                  [](boost::system::error_code) {});
+            }
+        });
+        drink_->on_message(
+            [this](const webcpp::document::document& v, const trystero::message_info& info) {
+                record("drink", {{"from", info.from}, {"value", v}});
+            });
+        const auto bytes_of = [this](std::string_view kind) {
+            return [this, kind](const trystero::bytes& data, const trystero::message_info& info) {
+                record(kind, {
+                                 {"from", info.from},
+                                 {"size", data.size()},
+                                 {"checksum", checksum(data)},
+                                 {"metadata", info.metadata},
+                             });
+            };
+        };
+        file_->on_message(bytes_of("file"));
+        wide_action_->on_message(bytes_of("wide"));
+        const auto answering =
+            question_->on_request([this](std::string text, const trystero::message_info& info) {
+                record("request", {{"from", info.from}, {"text", text}});
+                return "answer to: " + text;
+            });
+        if (!answering) {
+            record("error", {{"code", "on-request"}, {"error", answering.error().message()}});
+        }
+    }
+
+    event_sink emit_;
+    std::optional app_;
+    std::optional room_;
+    std::optional> chat_;
+    std::optional> drink_;
+    std::optional> file_;
+    std::optional> wide_action_;
+    std::optional> question_;
+    bool wide_ = false;
+};
+
+}  // namespace interop
+
+#endif
diff --git a/test/oracle/interop/relay.mjs b/test/oracle/interop/relay.mjs
index 8767032..11782a7 100644
--- a/test/oracle/interop/relay.mjs
+++ b/test/oracle/interop/relay.mjs
@@ -7,7 +7,9 @@
 // A Nostr relay for the interop test, the examples that run over a relay and their twins, NIP-01 only and in memory:
 // REQ with kinds, since and #x filters, CLOSE, and EVENT, which it verifies like a public relay (the id is the SHA-256
 // of the canonical serialization, the signature a valid BIP-340 one) before forwarding it to the subscriptions open
-// at that moment. Nothing is stored: Trystero's kinds are ephemeral.
+// at that moment. Nothing is stored for the clients: Trystero's kinds are ephemeral. For the interop test's checks
+// it keeps what it was sent (`received`), tells how many clients subscribe to a topic (`subscribed`), and can hold the
+// events a predicate picks back until `release` (`options.hold`).
 import {createHash} from 'node:crypto'
 import {schnorr} from '@noble/secp256k1'
 import {WebSocketServer} from 'ws'
@@ -17,12 +19,20 @@ export const startRelay = (port = 0) =>
         const server = new WebSocketServer({port, host: '127.0.0.1'})
         const subscriptions = new Map() // socket -> Map(subId -> filter)
         const stats = {events: 0, rejected: 0}
+        // Every event forwarded, in the order it was: {topic, peerId, offerId, signal}, of its content as JSON, `signal`
+        // being 'announce' for a content without offer, answer or candidate, else the first of those it has; all null
+        // for a content that is not JSON.
+        const received = []
+        // Events that options.hold picked, in order, forwarded by release().
+        const held = []
         // options.afterSubscribe: a raw text sent after every subscription, when not null.
         // options.strike: {action, delay, topic}, when not null: the next subscription to `topic` takes it, and `delay`
         // milliseconds later the relay resets that client's TCP connection (action 'reset') or sends it a text longer
         // than 1 MiB (action 'too-long'). A C++ peer announces 233 ms after it subscribed, so a delay just below that
         // ends its connection as that write starts.
-        const options = {afterSubscribe: null, strike: null}
+        // options.hold: (topic, content) => boolean, when not null: an event it picks is acknowledged but held back from
+        // the subscriptions until release().
+        const options = {afterSubscribe: null, strike: null, hold: null}
         const tooLong = 'x'.repeat(1024 * 1024 + 1)
         const strikeLater = (socket, {action, delay}) =>
             setTimeout(() => {
@@ -31,6 +41,26 @@ export const startRelay = (port = 0) =>
                 else socket.send(tooLong)
             }, delay)
         const send = (socket, message) => socket.readyState === 1 && socket.send(JSON.stringify(message))
+        const contentOf = event => {
+            try {
+                return JSON.parse(event.content)
+            } catch {
+                return null
+            }
+        }
+        const signalOf = content =>
+            ['offer', 'answer', 'candidate'].find(k => typeof content?.[k] === 'string') ?? 'announce'
+        const forward = (event, topic) => {
+            const content = contentOf(event)
+            received.push({
+                topic, peerId: content?.peerId ?? null, offerId: content?.offerId ?? null, signal: content ? signalOf(content) : null,
+            })
+            for (const [other, subs] of subscriptions) {
+                for (const [subId, filter] of subs) {
+                    if (matches(filter, event, topic)) send(other, ['EVENT', subId, event])
+                }
+            }
+        }
         const matches = (filter, event, topic) =>
             (!filter.kinds || filter.kinds.includes(event.kind)) &&
             (!filter['#x'] || filter['#x'].includes(topic)) &&
@@ -72,13 +102,12 @@ export const startRelay = (port = 0) =>
                         return send(socket, ['OK', event.id, false, problem])
                     }
                     stats.events++
-                    send(socket, ['OK', event.id, true, ''])
+                    // Forwarded before the OK: a client that waits for its OK knows every subscription has the event
+                    // before anything it sends next.
                     const topic = event.tags.find(t => t[0] === 'x')?.[1]
-                    for (const [other, subs] of subscriptions) {
-                        for (const [subId, filter] of subs) {
-                            if (matches(filter, event, topic)) send(other, ['EVENT', subId, event])
-                        }
-                    }
+                    if (options.hold?.(topic, contentOf(event))) held.push([event, topic])
+                    else forward(event, topic)
+                    send(socket, ['OK', event.id, true, ''])
                 }
             })
         })
@@ -86,6 +115,18 @@ export const startRelay = (port = 0) =>
         const broadcast = text => {
             for (const socket of subscriptions.keys()) socket.readyState === 1 && socket.send(text)
         }
+        // release(): ends options.hold and forwards what it held, in order.
+        const release = () => {
+            options.hold = null
+            for (const [event, topic] of held.splice(0)) forward(event, topic)
+        }
+        // subscribed(topic): how many open clients subscribe to `topic`.
+        const subscribed = topic =>
+            [...subscriptions.entries()].filter(([socket, subs]) =>
+                socket.readyState === 1 && [...subs.values()].some(f => f?.['#x']?.includes(topic))).length
         server.on('listening', () =>
-            resolve({url: `ws://127.0.0.1:${server.address().port}`, stats, options, broadcast, close: () => server.close()}))
+            resolve({
+                url: `ws://127.0.0.1:${server.address().port}`, stats, options, received, broadcast, release, subscribed,
+                close: () => server.close(),
+            }))
     })
diff --git a/test/oracle/interop/run.mjs b/test/oracle/interop/run.mjs
index 9864bdf..f2dd52d 100644
--- a/test/oracle/interop/run.mjs
+++ b/test/oracle/interop/run.mjs
@@ -4,8 +4,9 @@
 // accompanying file LICENSE_1_0.txt or copy at
 // https://www.boost.org/LICENSE_1_0.txt)
 
-// The interop test: C++ peers built with Emscripten (peer.cpp) and Trystero JS 0.26 peers in the same rooms, in
-// headless Chrome, over a local Nostr relay (relay.mjs) or, with --public, Trystero's public relays.
+// The interop test: C++ peers (peer_room.hpp), built with Emscripten (peer.cpp) or native (native_peer.cpp), and
+// Trystero 0.27.0 peers (js.html, forger.html) in the same rooms, in headless Chrome, over a local Nostr relay
+// (relay.mjs) or, with --public, Trystero's public relays.
 //
 //   node interop/run.mjs [--public] [--browser ] [--native ] [--chrome ] [--verbose]
 // Add --scenario  to reproduce one scenario; no match fails the run.
@@ -26,13 +27,13 @@
 // scenarios' verdict, a failure outside every scenario, or SIGTERM, SIGINT or SIGHUP (the bound of b2's driven test
 // sends SIGTERM). A SIGKILL leaves the profile, which the next run removes.
 import {spawn} from 'node:child_process'
-import {createHash} from 'node:crypto'
+import {createECDH, createHash} from 'node:crypto'
 import {createInterface} from 'node:readline'
 import {existsSync, mkdtempSync, readFileSync, readdirSync, rmSync} from 'node:fs'
 import {createServer} from 'node:http'
 import {homedir, tmpdir} from 'node:os'
 import {basename, dirname, extname, join, normalize, resolve} from 'node:path'
-import {fileURLToPath} from 'node:url'
+import {fileURLToPath, pathToFileURL} from 'node:url'
 import {startRelay} from './relay.mjs'
 
 const here = dirname(fileURLToPath(import.meta.url))
@@ -46,6 +47,11 @@ const nativePeer = option('--native')
 if (!browserPeer && !nativePeer) throw new Error('pass --browser  or --native ')
 const buildDir = browserPeer && dirname(resolve(browserPeer))
 
+// Every wait of the driver is for something that must happen: its bound only ends a run that hangs, naming what did not
+// happen, so it is far above the time anything takes on the most loaded machine. No scenario waits for something not
+// to happen: what must not happen is checked once what must happen has, and again at the scenario's end.
+const bound = 240_000
+
 const findChrome = () => {
     const explicit = option('--chrome') ?? process.env.CHROME
     if (explicit) return explicit
@@ -141,7 +147,8 @@ const startChrome = async () => {
     // What Chrome says on standard error, the last of it, for a Chrome that does not start.
     let said = ''
     chrome.stderr.on('data', data => (said = (said + data).slice(-2000)))
-    for (let i = 0; ; i++) {
+    const end = Date.now() + bound
+    for (;;) {
         const active = join(left.profile, 'DevToolsActivePort')
         const port = existsSync(active) ? readFileSync(active, 'utf8').split('\n')[0] : ''
         if (/^[0-9]+$/.test(port)) {
@@ -151,7 +158,7 @@ const startChrome = async () => {
                 return
             } catch {}
         }
-        if (i > 100 || exited(chrome)) throw new Error(`Chrome did not start; it said:\n${said}`)
+        if (Date.now() > end || exited(chrome)) throw new Error(`Chrome did not start; it said:\n${said}`)
         await new Promise(r => setTimeout(r, 100))
     }
 }
@@ -162,8 +169,8 @@ const openPage = async (path, label) => {
     let id = 0
     const pending = new Map()
     const problems = []
-    // Every call settles within ms, 10 s unless it says: a closing tab may never answer.
-    const send = (method, params = {}, ms = 10_000) => new Promise(resolve => {
+    // Every call settles within ms, `bound` unless it says: a closing tab may never answer.
+    const send = (method, params = {}, ms = bound) => new Promise(resolve => {
         const i = ++id
         const timer = setTimeout(() => {
             pending.delete(i)
@@ -188,7 +195,7 @@ const openPage = async (path, label) => {
     await send('Runtime.enable')
     await send('Page.navigate', {url: base + path})
     // A call that does not answer in time fails by name, with the expression it ran.
-    const evaluate = async (expression, ms = 10_000) => {
+    const evaluate = async (expression, ms = bound) => {
         const answer = await send('Runtime.evaluate', {expression, returnByValue: true, awaitPromise: true}, ms)
         if (answer === undefined) throw new Error(`${label}: ${expression} did not answer in ${ms / 1000} s`)
         if (answer.exceptionDetails) throw new Error(`${label}: ${expression}: ${answer.exceptionDetails.exception?.description ?? answer.exceptionDetails.text}`)
@@ -200,7 +207,8 @@ const openPage = async (path, label) => {
         events: async () => (await evaluate('window.events ?? []')) ?? [],
         log: async () => (await evaluate("document.getElementById('log')?.innerText ?? ''")) ?? '',
         leave: () => evaluate('window.leave()'),
-        leaveRoom: () => evaluate('window.leave()'),
+        offline: () => evaluate('window.offline()'),
+        online: () => evaluate('window.online()'),
         value: (expression, ms) => evaluate(expression, ms),
         close: async () => {
             ws.close()
@@ -246,8 +254,8 @@ const openNative = (params, label) => {
         log: async () => lines.join('\n'),
         value: async () => undefined,
         leave: async () => child.stdin.write('leave\n'),
-        leaveRoom: async () => child.stdin.write('leave-room\n'),
-        replace: async () => child.stdin.write('replace\n'),
+        offline: async () => child.stdin.write('offline\n'),
+        online: async () => child.stdin.write('online\n'),
         abort: async () => child.stdin.write('abort\n'),
         close: async () => {
             child.kill()
@@ -258,12 +266,15 @@ const openNative = (params, label) => {
 
 // ---- scenarios ---------------------------------------------------------------------------------------------------
 const checksum = bytes => bytes.reduce((sum, b, i) => (sum + b * (i + 1)) >>> 0, 0)
-const fromCpp = {size: 100_000, checksum: checksum(new Uint8Array(100_000).map((_, i) => (i * 13) % 256)), metadata: '{"name":"from-cpp.bin"}'}
-const fromJs = {size: 100_000, checksum: checksum(new Uint8Array(100_000).map((_, i) => (i * 7) % 256)), metadata: '{"name":"from-js.bin"}'}
+const pattern = (size, step) => new Uint8Array(size).map((_, i) => (i * step) % 256)
+const fromCpp = {size: 100_000, checksum: checksum(pattern(100_000, 13)), metadata: '{"name":"from-cpp.bin"}'}
+const fromJs = {size: 100_000, checksum: checksum(pattern(100_000, 7)), metadata: '{"name":"from-js.bin"}'}
+const wideFromCpp = {size: 1024 * 1024, checksum: checksum(pattern(1024 * 1024, 13))}
+const wideFromJs = {size: 1024 * 1024, checksum: checksum(pattern(1024 * 1024, 7))}
 
-// Waits for `condition` for at most `ms`, and no longer once a peer of the scenario died by a signal: what it waits for
+// Waits for `condition`, at most `ms`, and no longer once a peer of the scenario died by a signal: what it waits for
 // may never come, and the death is the failure to name.
-const until = async (condition, ms) => {
+const until = async (condition, ms = bound) => {
     const end = Date.now() + ms
     while (Date.now() < end && deaths === deathsBefore) {
         if (await condition()) return true
@@ -272,48 +283,134 @@ const until = async (condition, ms) => {
     return condition()
 }
 
-// Whether a peer of a mesh of three is joined to both others and has a file from each. Joins are counted as
-// peers present, joins less leaves in their order: Trystero JS gives up a handshake after 10 s and tries
-// again, so a peer may see another leave and join anew, a third join that is still a mesh of three.
-const meshFormed = events => {
-    const present = new Set()
-    for (const e of events) {
-        if (e.kind === 'peer-join') present.add(e.peer)
-        else if (e.kind === 'peer-leave') present.delete(e.peer)
-    }
-    const senders = new Set(events.filter(e => e.kind === 'file').map(e => e.from))
-    return present.size === 2 && senders.size === 2
+const has = (events, kind, f = () => true) => events.some(e => e.kind === kind && f(e))
+const count = (events, kind, f = () => true) => events.filter(e => e.kind === kind && f(e)).length
+// A peer's own ids, once it joined its room: its peer id and its user's.
+const idsOf = async page => {
+    const joined = async () => (await page.events()).find(e => e.kind === 'joined')
+    if (!(await until(async () => Boolean(await joined())))) throw new Error(`${page.label} did not join its room`)
+    const {self, user} = await joined()
+    return {self, user}
 }
 
-/** What a peer must have seen of a partner: the join, both messages, the echo of its own, the file, a ping, its sends. */
-const exchangeComplete = (events, partnerIsCpp) => {
-    const has = (kind, f = () => true) => events.some(e => e.kind === kind && f(e))
+/**
+ * What a peer must have seen of the partner `of` (its ids): its join with its user, its chat message and the echo of
+ * its own, its JSON value and its file, its request, the answer to its own request, a ping, and its own sends.
+ */
+const exchanged = (events, of, partnerIsCpp) => {
+    const from = e => e.from === of.self
     const file = partnerIsCpp ? fromCpp : fromJs
-    return has('peer-join') &&
-        has('chat', e => e.text === (partnerIsCpp ? 'hello from C++' : 'hello from Trystero JS')) &&
-        has('chat', e => e.text === (partnerIsCpp ? 'echo: hello from Trystero JS' : 'echo: hello from C++')) &&
-        has('drink', e => e.value?.drink === (partnerIsCpp ? 'cafezinho' : 'negroni')) &&
-        has('file', e => e.size === file.size && e.checksum === file.checksum && e.metadata === file.metadata) &&
-        has('ping', e => e.error === '') &&
-        ['chat', 'drink', 'file'].every(what => has('sent', e => e.what === what && e.error === ''))
+    const [name, other] = partnerIsCpp ? ['C++', 'Trystero JS'] : ['Trystero JS', 'C++']
+    return has(events, 'peer-join', e => e.peer === of.self && e.user === of.user) &&
+        has(events, 'chat', e => from(e) && e.text === `hello from ${name}`) &&
+        has(events, 'chat', e => from(e) && e.text === `echo: hello from ${other}`) &&
+        has(events, 'drink', e => from(e) && e.value?.drink === (partnerIsCpp ? 'cafezinho' : 'negroni')) &&
+        has(events, 'file', e => from(e) && e.size === file.size && e.checksum === file.checksum && e.metadata === file.metadata) &&
+        has(events, 'request', e => from(e) && e.text === `question from ${name}`) &&
+        has(events, 'response', e => e.peer === of.self && e.error === '' && e.text === `answer to: question from ${other}`) &&
+        has(events, 'ping', e => e.peer === of.self && e.error === '') &&
+        ['chat', 'drink', 'file'].every(what => has(events, 'sent', e => e.peer === of.self && e.what === what && e.error === ''))
+}
+
+// Waits until a C++ peer and a page exchanged everything both ways; names what is missing when they did not.
+const exchange = async (cpp, js) => {
+    const c = await idsOf(cpp), j = await idsOf(js)
+    const done = async () => exchanged(await cpp.events(), j, false) && exchanged(await js.events(), c, true)
+    if (await until(done)) return null
+    const missing = []
+    if (!exchanged(await cpp.events(), j, false)) missing.push(`${cpp.label} of ${js.label}`)
+    if (!exchanged(await js.events(), c, true)) missing.push(`${js.label} of ${cpp.label}`)
+    return `the exchange is incomplete: ${missing.join(', ')}`
 }
 
 const results = []
 // The C++ peers' STUN server: the discard port of the loopback, where nothing answers, so that no peer asks a public
 // one.
 const ice = 'stun:127.0.0.1:9'
+const app = 'webcpp-trystero-interop'
+const freshRoom = () => 'room-' + Math.random().toString(36).slice(2, 10)
+let relayParams
+
+// The peer id 0.27.0 derives from the endpoint key whose scalar is the SHA-256 of `label`, as a C++ peer given
+// that label as its `key` has; and a label whose id is below `id` (`below`) or above it.
+const {getVerifiedPubKeyRecord} = await import(pathToFileURL(join(here, '../node_modules/@trystero-p2p/core/dist/identity.mjs')).href)
+const peerIdOf = async label => {
+    const ecdh = createECDH('prime256v1')
+    ecdh.setPrivateKey(createHash('sha256').update(label).digest())
+    const point = ecdh.getPublicKey()
+    const jwk = {kty: 'EC', crv: 'P-256', x: point.subarray(1, 33).toString('base64url'), y: point.subarray(33).toString('base64url')}
+    return (await getVerifiedPubKeyRecord(jwk)).peerId
+}
+const keyAround = async (id, below) => {
+    for (let i = 0; ; ++i) {
+        const label = `key-${i}-${Math.random().toString(36).slice(2, 10)}`
+        if (((await peerIdOf(label)) < id) === below) return label
+    }
+}
+
+// 0.27.0's topics of a room: the root, hashTopic of topicPath(Trystero, app, room), the base64url SHA-256 of the JSON
+// array of its parts; and a peer's own, hashTopic of topicPath(root's path, peer id).
+const rootPath = room => JSON.stringify(['Trystero', app, room])
+const hashTopic = path => createHash('sha256').update(path).digest('base64url')
+const rootTopicOf = room => hashTopic(rootPath(room))
+const selfTopicOf = (room, peer) => hashTopic(JSON.stringify([rootPath(room), peer]))
+
+// What the local relay forwarded of `peer`'s signals of kind `signal` ('announce', 'offer', 'answer', 'candidate'),
+// on `topic` when given.
+const relayed = (peer, signal, topic) =>
+    left.relay.received.filter(e => e.peerId === peer && e.signal === signal && (topic === undefined || e.topic === topic))
 
-const scenario = async (name, body) => {
-    if (scenarioFilter && !name.includes(scenarioFilter)) return
+// What anyone who reads and writes the relays can send, through a client of the local relay of its own, with 0.27.0's
+// own code: Nostr events (createEvent, signed by a key of its own) and signals sealed under a room's key (genKey,
+// encrypt). Each publish waits for the relay's OK, which the relay gives once every subscription has the event.
+const {createEvent, createSigner} = await import(pathToFileURL(join(here, '../node_modules/@trystero-p2p/nostr/dist/protocol.mjs')).href)
+const {encrypt, genKey} = await import(pathToFileURL(join(here, '../node_modules/@trystero-p2p/core/dist/crypto.mjs')).href)
+const openPublisher = async () => {
+    const socket = new WebSocket(left.relay.url)
+    const acks = new Map()
+    await new Promise((resolve, reject) => {
+        socket.onopen = resolve
+        socket.onerror = () => reject(new Error('the publisher could not reach the relay'))
+    })
+    socket.onmessage = ({data}) => {
+        const [type, id, ok, why] = JSON.parse(data)
+        if (type === 'OK') acks.get(id)?.(ok ? null : why)
+    }
+    socket.onclose = () => {
+        for (const ack of acks.values()) ack('the relay closed the publisher')
+    }
+    const signer = createSigner()
+    return {
+        publish: async (topic, content) => {
+            const text = await createEvent(topic, JSON.stringify(content), signer)
+            const {id} = JSON.parse(text)[1]
+            const refused = await new Promise(resolve => {
+                acks.set(id, resolve)
+                socket.send(text)
+            })
+            acks.delete(id)
+            if (refused) throw new Error(`the relay refused an event: ${refused}`)
+        },
+        close: () => socket.close(),
+    }
+}
+
+// Runs a scenario against the C++ peer of `cppKind`: 'cpp' (the browser's, in a page) or 'native' (a process). Its
+// body gets `open(kind, params)`, which opens a peer, in the scenario's room unless `params.room` names another:
+// 'cpp' (the C++ peer of the lane), 'js' or 'forger' (pages of Trystero 0.27.0).
+const scenario = async (name, cppKind, body) => {
+    const shown = `${name} (${cppKind === 'native' ? 'native' : 'browser'})`
+    if (scenarioFilter && !shown.includes(scenarioFilter)) return
     const started = Date.now()
     deathsBefore = deaths
     const pages = []
-    const open = async (kind, params) => {
-        const all = {app, ice, ...params}
-        const page = kind === 'native'
-            ? openNative(all, `native#${pages.length}`)
-            : await openPage(`/${kind}.html?${new URLSearchParams({...all, program: basename(browserPeer ?? '')})}`,
-                `${kind}#${pages.length}`)
+    const room = freshRoom()
+    const open = async (kind, params = {}) => {
+        const all = {app, room, ...relayParams, ...(kind === 'cpp' ? {ice} : {}), ...params}
+        const label = `${kind === 'cpp' ? cppKind : kind}#${pages.length}`
+        const page = kind === 'cpp' && cppKind === 'native'
+            ? openNative(all, label)
+            : await openPage(`/${kind}.html?${new URLSearchParams({...all, program: basename(browserPeer ?? '')})}`, label)
         pages.push(page)
         return page
     }
@@ -327,8 +424,8 @@ const scenario = async (name, body) => {
     const problems = pages.flatMap(p => p.problems)
     if (problems.length) failure = [failure, ...problems].filter(Boolean).join('\n')
     const seconds = ((Date.now() - started) / 1000).toFixed(1)
-    results.push({name, ok: !failure})
-    console.log(`${failure ? 'FAIL' : 'pass'}  ${name}  (${seconds} s)`)
+    results.push({name: shown, ok: !failure})
+    console.log(`${failure ? 'FAIL' : 'pass'}  ${shown}  (${seconds} s)`)
     if (failure || verbose) {
         if (failure) console.log('  ' + failure)
         for (const p of pages) {
@@ -339,827 +436,583 @@ const scenario = async (name, body) => {
     for (const p of pages) await p.close()
 }
 
-const app = 'webcpp-trystero-interop'
-const room = () => 'room-' + Math.random().toString(36).slice(2, 10)
-let relayParams
-
-const pairScenario = (name, {cppKind = 'cpp', cppSelf, password, leaver}) =>
-    scenario(name, async open => {
-        const params = {room: room(), ...relayParams, ...(password ? {password} : {})}
-        const cpp = await open(cppKind, {...params, self: cppSelf})
-        const js = await open('js', params)
-        const ok = await until(async () => exchangeComplete(await cpp.events(), false) && exchangeComplete(await js.events(), true), 30_000)
-        if (!ok) return 'the exchange did not complete in 30 s'
-        const [stays, goes] = leaver === 'cpp' ? [js, cpp] : [cpp, js]
-        await goes.leave()
-        const left = await until(async () => (await stays.events()).some(e => e.kind === 'peer-leave') && (await goes.events()).some(e => e.kind === 'left'), 10_000)
-        return left ? null : `the ${leaver} peer left but the other did not see it`
-    })
-
-// A Trystero JS peer that also sends the C++ peer malformed candidates (js.html, malformed-candidate-to): the C++
-// peer drops at least one, which its log says, and the exchange completes as it does without them.
-const malformedCandidateScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        const cppSelf = '00000000000000000000'
-        const params = {room: room(), ...relayParams}
-        const cpp = await open(cppKind, {...params, self: cppSelf})
-        const js = await open('js', {...params, 'malformed-candidate-to': cppSelf})
-        const ok = await until(async () => exchangeComplete(await cpp.events(), false) && exchangeComplete(await js.events(), true), 30_000)
-        if (!ok) return 'the exchange did not complete in 30 s'
-        const jsSelf = (await js.events()).find(e => e.kind === 'joined')?.self
-        return (await cpp.log()).includes(`dropped a candidate from ${jsSelf}`) ? null : 'no malformed candidate reached the C++ peer'
-    })
+// The peers of a room that joined `of` (its ids): none must have, checked once what must happen has, and at the end.
+const joinedBy = async (pages, of) => {
+    const joined = []
+    for (const page of pages) {
+        if (has(await page.events(), 'peer-join', e => e.peer === of.self)) joined.push(page.label)
+    }
+    return joined
+}
 
-// The C++ peer's relays begin with a URL no WebSocket can be made to: that relay reports a close, as an unreachable
-// one does, which the C++ peer's log says, and the room goes on over the next one.
-const refusedRelay = 'ftp://relay.invalid'
-const refusedRelayScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        const params = {room: room(), ...relayParams}
-        const cpp = await open(cppKind, {...params, relays: `${refusedRelay},${relayParams.relays}`})
-        const js = await open('js', params)
-        const ok = await until(async () => exchangeComplete(await cpp.events(), false) && exchangeComplete(await js.events(), true), 30_000)
-        if (!ok) return 'the exchange did not complete in 30 s'
-        return (await cpp.log()).includes(`could not reach ${refusedRelay}`) ? null : 'the C++ peer did not report the refused relay'
-    })
+// How many reports of one kind one peer may have made by now, at most one per peer and stage each 60 s (0.27.0's
+// reportDecryptErr): one, and one more for each 60 s since `since`, however slow the machine is.
+const reportsAllowed = since => 1 + Math.floor((Date.now() - since) / 60_000)
 
-// A Trystero JS peer that also sends text messages on its data channel (js.html, text-messages), then a chat message:
-// the C++ peer drops the text messages before reading them, and receives the chat message; no peer leaves.
-const textMessagesScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        const params = {room: room(), ...relayParams}
-        const cpp = await open(cppKind, {...params, self: 'zzzzzzzzzzzzzzzzzzzz'})
-        const js = await open('js', {...params, 'text-messages': '1'})
-        const ok = await until(async () => exchangeComplete(await cpp.events(), false) && exchangeComplete(await js.events(), true) &&
-            (await cpp.events()).some(e => e.kind === 'chat' && e.text === 'after text'), 30_000)
-        if (!ok) return 'the exchange, or the chat message after the text messages, did not complete in 30 s'
-        if (!(await js.events()).some(e => e.kind === 'text-sent' && e.channels > 0)) return 'no text message was sent'
-        if ([...await cpp.events(), ...await js.events()].some(e => e.kind === 'peer-leave')) return 'a peer left'
-        return (await cpp.log()).includes('invalid or incompatible room frame') ? 'the C++ peer took a text message for a frame' : null
-    })
+// The library's offer_ttl, read from its source: an unanswered offer holds its connection that long, and the room may
+// make another max_connections_per_window connections and offer to another max_unconnected_peers peers once it passed.
+const offerTtl = Number(/offer_ttl = std::chrono::milliseconds\(([\d']+)\)/.exec(
+    readFileSync(join(here, '../../../include/webcpp/trystero/detail/signaling.hpp'), 'utf8'))[1].replaceAll("'", ''))
+// How many windows of offer_ttl a run that began at `since` spans, at most: one, and one more for each offer_ttl.
+const windowsSince = since => 1 + Math.floor((Date.now() - since) / offerTtl)
 
-// The C++ peer is given a TURN server without credentials, which WebRTC refuses: the app drops it when it is made and
-// reports it to app::on_error, and the exchange completes over the host candidates.
-const unusableIceScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        const params = {room: room(), ...relayParams}
-        const cpp = await open(cppKind, {...params, ice: 'turn:127.0.0.1:9'})
-        const js = await open('js', params)
-        const ok = await until(async () => exchangeComplete(await cpp.events(), false) && exchangeComplete(await js.events(), true), 30_000)
-        if (!ok) return 'the exchange did not complete in 30 s'
-        const reported = (await cpp.events()).some(e => e.kind === 'error' && e.error === 'the configuration is unusable')
-        return reported ? null : 'the C++ peer did not report the unusable ICE server'
-    })
+// 1. Each side sees the other's peer and user ids (the C++ peer's app::self_id and app::user_id, the page's
+// getSelf()), and text, JSON and binary messages go both ways: with either side offering, as in 0.27.0 the lower id
+// offers, so the C++ peer's id is put below the page's, then above it (its key, `keyAround`), and the local relay
+// shows the offer of the lower. No candidate of either is refused (the malformed candidate scenario's control).
+const idsAndMessages = cppKind => scenario('ids_and_messages_both_ways', cppKind, async open => {
+    for (const cppLower of [true, false]) {
+        const order = cppLower ? 'the C++ peer offering' : 'the page offering'
+        const room = freshRoom()
+        const js = await open('js', {room})
+        const j = await idsOf(js)
+        const cpp = await open('cpp', {room, key: await keyAround(j.self, cppLower)})
+        const c = await idsOf(cpp)
+        if (!/^[0-9A-Za-z]{20}$/.test(c.self) || !/^[0-9A-Za-z]{22}$/.test(c.user)) {
+            return `the C++ peer's ids ${JSON.stringify(c)} are not 0.27.0's`
+        }
+        if ((c.self < j.self) !== cppLower) return `the C++ peer's id ${c.self} is not ${cppLower ? 'below' : 'above'} ${j.self}`
+        const failed = await exchange(cpp, js)
+        if (failed) return `${order}: ${failed}`
+        if (!usePublic) {
+            const [offerer, answerer] = cppLower ? [c, j] : [j, c]
+            if (!relayed(offerer.self, 'offer', selfTopicOf(room, answerer.self)).length) return `${order}: the relay saw no offer of ${offerer.self}`
+        }
+        const seen = await js.value('window.peers()')
+        if (seen[c.self] !== c.user) return `${order}: the page's getPeers() is ${JSON.stringify(seen)}, not ${c.self} of ${c.user}`
+        if (!has(await cpp.events(), 'user-join', e => e.user === j.user && e.peer === j.self)) return `${order}: the C++ peer saw no user join`
+        if (!has(await js.events(), 'user-join', e => e.user === c.user && e.peer === c.self)) return `${order}: the page saw no user join`
+        if ((await cpp.log()).includes('dropped a candidate')) return `${order}: the C++ peer refused a candidate of the page`
+    }
+    return null
+})
 
-// After a Trystero JS peer joined, it floods the C++ peer with what no key is needed for (js.html, window.flood and
-// window.floodOffers): announcements from fresh ids above the C++ peer's, which a watcher (forger.html) answers with
-// garbage in the flooders' names as soon as the C++ peer offers to them, and offers that no key sealed, from fresh ids.
-// The C++ peer offers to at most the room's bound of them at once, makes no connection for a forged offer or answer,
-// logs each id it refuses once, makes at most the room's bound of connections in the window (counted as Chromium
-// counts them, every one made), reports the forged signals once, not once per id, and goes on with the peer that
-// joined. The flood is judged by what happens once it begins: before it, the two peers meet as in any scenario, and a
-// first meeting whose handshake times out (Trystero's 10 s) and meets again is that meeting's, not the flood's.
-const floodCount = 300
-const unconnectedBound = 32
-const floodCallMs = 20_000
-const floodScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        const params = {room: room(), ...relayParams}
-        const self = '00000000000000000000'
-        const forger = await open('forger', {...params, target: self})
-        if (!(await until(async () => (await forger.events()).some(e => e.kind === 'watching'), 10_000))) return 'the forger never watched'
-        const opened = Date.now()
-        const cpp = await open(cppKind, {...params, self})
-        const js = await open('js', params)
-        const ok = await until(async () => exchangeComplete(await cpp.events(), false) && exchangeComplete(await js.events(), true), 30_000)
-        if (!ok) return 'the exchange did not complete in 30 s'
-        const connections = async () => cppKind === 'native'
-            ? (await cpp.events()).filter(e => e.kind === 'made-connection').length
-            : await cpp.value('window.madePeerConnections')
-        const before = {connections: await connections(), cpp: (await cpp.events()).length, js: (await js.events()).length}
-        // Each call answers once its flood is sent, which on a busy machine takes the page more than 10 s.
-        await js.value(`window.flood(${floodCount}, '0000000000')`, floodCallMs)
-        await js.value(`window.floodOffers(${floodCount}, '1111111111', '${self}')`, floodCallMs)
-        const ids = async (prefix, said) =>
-            new Set([...(await cpp.log()).matchAll(new RegExp(`(?:${said}|refusing) (${prefix}\\w{10})`, 'g'))].map(m => m[1]))
-        const floodIds = () => ids('0000000000', 'announcement from')
-        const offerIds = () => ids('1111111111', 'could not open the offer from')
-        const seen = await until(async () => (await floodIds()).size >= floodCount && (await offerIds()).size >= floodCount, 30_000)
-        const log = await cpp.log()
-        const offered = new Set([...log.matchAll(/announcement from (0000000000\w{10}): our id is lower, so we offer/g)].map(m => m[1]))
-        const refused = new Set([...log.matchAll(/refusing ([01]{10}\w{10})/g)].map(m => m[1]))
-        const forged = (await forger.events()).filter(e => e.kind === 'forged').length
-        const made = await connections() - before.connections
-        const peak = await cpp.value('window.peakPeerConnections')
-        const reports = (await cpp.events()).filter(e => e.kind === 'error' && e.error === 'the peer uses another room password').length
-        const facts = `the C++ peer logged ${(await floodIds()).size} of ${floodCount} announcing ids and ` +
-            `${(await offerIds()).size} of ${floodCount} offering ids, offered to ${offered.size}, refused ${refused.size}, ` +
-            `made ${made} connections in the flood, ${before.connections} before it` +
-            (peak === undefined ? '' : `, held at most ${peak}`) +
-            `, reported ${reports} wrong passwords; the watcher forged ${forged} answers`
-        console.log(`  ${facts}`)
-        if (!seen) return `${facts}; not every flooding signal was handled in 30 s`
-        if (offered.size > unconnectedBound) return `${facts}; offered to more than ${unconnectedBound}`
-        if (forged < 1) return `${facts}; the watcher forged no answer`
-        // The flooders' offers alone: the peer that joined is joined before the flood begins.
-        if (made > unconnectedBound) return `${facts}; more than ${unconnectedBound} connections in the flood`
-        // The forged signals are reported once per 10 s, not once per fresh id: the first at once, the rest together.
-        // So at most one report, and one more for each 10 s the C++ peer has been open, however slow the machine is.
-        const reportBound = 1 + Math.floor((Date.now() - opened) / 10_000)
-        if (reports > reportBound) return `${facts}; more than ${reportBound} reports of signals that did not open`
-        const during = [...(await cpp.events()).slice(before.cpp), ...(await js.events()).slice(before.js)]
-        if (during.some(e => e.kind === 'peer-leave')) return `${facts}; a peer left during the flood`
-        return null
-    })
+// 2. The page's onPeerJoin fires for the C++ peer only once the page verified the C++ peer's endpoint and user
+// signatures (0.27.0's handshake), and the C++ peer's on_peer_join for the page only once it verified the page's: each
+// joins the other, with the user the other presents, and neither reports an error.
+const signatures = cppKind => scenario('js_verifies_cpp_signatures', cppKind, async open => {
+    const cpp = await open('cpp')
+    const js = await open('js')
+    const c = await idsOf(cpp), j = await idsOf(js)
+    const joined = async () => has(await js.events(), 'peer-join', e => e.peer === c.self && e.user === c.user) &&
+        has(await cpp.events(), 'peer-join', e => e.peer === j.self && e.user === j.user)
+    if (!(await until(joined))) return 'the peers did not join each other with their users'
+    const errors = [...await cpp.events(), ...await js.events()].filter(e => e.kind === 'error')
+    return errors.length ? `errors: ${JSON.stringify(errors)}` : null
+})
 
-// These pair scenarios have one remote peer. Ignore old joins and any new join followed by a leave.
-const peerPresentAfter = (events, start) => {
-    let present = false
-    for (const event of events.slice(start)) {
-        if (event.kind === 'peer-join') present = true
-        else if (event.kind === 'peer-leave') present = false
+// 3. 1 MiB each way, on the action `wide`, in 0.27.0's wide frames: the page sends and receives frames of 64 KiB
+// (maxBulkFrameBytes, js.html's window.largest), where a link that fell back to the narrow chunks has 16 KiB ones.
+const wideFrame = 64 * 1024
+const wideTransfers = cppKind => scenario('wide_transfers_both_ways', cppKind, async open => {
+    const cpp = await open('cpp', {wide: 1})
+    const js = await open('js', {wide: 1})
+    const c = await idsOf(cpp), j = await idsOf(js)
+    const got = (events, from, payload) =>
+        has(events, 'wide', e => e.from === from && e.size === payload.size && e.checksum === payload.checksum)
+    const done = async () => got(await cpp.events(), j.self, wideFromJs) && got(await js.events(), c.self, wideFromCpp) &&
+        has(await cpp.events(), 'sent', e => e.what === 'wide' && e.error === '') &&
+        has(await js.events(), 'sent', e => e.what === 'wide' && e.error === '')
+    if (!(await until(done))) return 'the 1 MiB transfers did not both complete'
+    const largest = await js.value('window.largest')
+    if (largest.sent !== wideFrame || largest.received !== wideFrame) {
+        return `the page's largest frames are ${JSON.stringify(largest)}, not ${wideFrame} bytes each way`
     }
-    return present
-}
+    return null
+})
 
-// After the exchange, the relay sends every client a text longer than a relay's longest (1 MiB): the C++ peer closes
-// that relay's connection rather than read it, says so, reconnects, and goes on with the peer it joined. Then the relay
-// sends the text after every subscription: each reconnection is closed at once, and the C++ peer tries again within a
-// bound that doubles every time, rather than every few seconds forever.
-const oversizedRelayTextScenario = (name, cppKind, recoverFirst = false, delayRecovery = false) =>
-    scenario(name, async open => {
-        const params = {room: room(), ...relayParams}
-        const cpp = await open(cppKind, {...params, self: '00000000000000000000'})
-        const js = await open('js', params)
-        const ok = await until(async () => exchangeComplete(await cpp.events(), false) && exchangeComplete(await js.events(), true), 30_000)
-        if (!ok) return 'the exchange did not complete in 30 s'
-        if (recoverFirst) {
-            const before = {cpp: (await cpp.events()).length, js: (await js.events()).length}
-            if (delayRecovery) await js.value('window.delayNextRecovery()')
-            await js.value('window.drop()')
-            // A local join does not prove the remote handshake completed. Keep the existing
-            // recovery bound, accepting only fresh joins that have not since left on either side.
-            const recovered = async () => peerPresentAfter(await cpp.events(), before.cpp) &&
-                peerPresentAfter(await js.events(), before.js)
-            if (!(await until(recovered, 30_000))) {
-                return 'both peers did not recover from the initial connection loss within 30 s'
-            }
-            const text = `recovered before relay fault ${params.room}`
-            await js.value(`window.chat1(${JSON.stringify(text)})`)
-            if (!(await until(async () => (await js.events()).some(e => e.kind === 'chat' && e.text === `echo: ${text}`), 10_000))) {
-                return 'the recovered connection did not exchange a fresh message'
-            }
-            if (delayRecovery && !(await js.events()).some(e => e.kind === 'delayed-recovery-closed')) {
-                return 'the controlled one-way handshake delay did not end its connection'
-            }
+// 4. One password meets; another gives decrypt_failed on the C++ side and decrypt-failed on the page (0.27.0's code
+// name both), and no join. Of two peers of different passwords the lower id offers and the higher cannot open the
+// offer, as in 0.27.0: so the C++ peer's id is put below the page's, then above it (its key, `keyAround`), and the
+// higher of the two reports the offer it could not open, naming the lower, once however often the lower offers (the
+// local relay shows a second offer forwarded to it).
+const passwords = cppKind => scenario('passwords', cppKind, async open => {
+    const failed = await exchange(await open('cpp', {password: 'secret'}), await open('js', {password: 'secret'}))
+    if (failed) return `with one password: ${failed}`
+    for (const cppLower of [true, false]) {
+        const room = freshRoom()
+        const since = Date.now()
+        const js = await open('js', {room, password: 'another'})
+        const j = await idsOf(js)
+        const cpp = await open('cpp', {room, password: 'secret', key: await keyAround(j.self, cppLower)})
+        const c = await idsOf(cpp)
+        if ((c.self < j.self) !== cppLower) return `the C++ peer's id ${c.self} is not ${cppLower ? 'below' : 'above'} ${j.self}`
+        const [reporter, offerer, reporterId] = cppLower ? [js, c, j] : [cpp, j, c]
+        const reports = async () => count(await reporter.events(), 'error', e => e.code === 'decrypt-failed' && e.peer === offerer.self)
+        if (!(await until(async () => (await reports()) > 0))) {
+            return `${reporter.label}, the higher id, did not report decrypt-failed for the offer of ${offerer.self}`
         }
-        // Recovery before this fault belongs to setup. Only subsequent departures violate the
-        // guarantee that losing the signaling relay leaves the established data channel intact.
-        const cppStart = (await cpp.events()).length
-        const jsStart = (await js.events()).length
-        left.relay.broadcast(JSON.stringify(['NOTICE', 'x'.repeat(1024 * 1024 + 1)]))
-        const lost = await until(async () => (await cpp.log()).includes(`lost ${left.relay.url}`), 10_000)
-        if (!lost) return 'the C++ peer did not close the relay that sent the long text'
-        const back = await until(async () => (await cpp.log()).includes(`reconnected to ${left.relay.url}`), 15_000)
-        if (!back) return 'the C++ peer did not reconnect to the relay'
-        const bounds = async () =>
-            [...(await cpp.log()).matchAll(new RegExp(`lost ${left.relay.url}, next attempt within (\\d+) ms`, 'g'))].map(m => Number(m[1]))
-        // The text closes the connection open now, and then each new one after its subscription.
-        left.relay.options.afterSubscribe = JSON.stringify(['NOTICE', 'x'.repeat(1024 * 1024 + 1)])
-        left.relay.broadcast(left.relay.options.afterSubscribe)
-        const lostAgain = await until(async () => (await bounds()).length >= 3, 30_000)
-        left.relay.options.afterSubscribe = null
-        const seen = await bounds()
-        console.log(`  the C++ peer lost the relay ${seen.length} times, each time to try again within ${seen.join(', ')} ms`)
-        if (!lostAgain) return 'the C++ peer was not closed three times in 30 s'
-        if (!seen.every((bound, i) => i === 0 || bound > seen[i - 1])) return `the bounds did not grow: ${seen.join(', ')}`
-        const text = `still connected after relay faults ${params.room}`
-        await js.value(`window.chat1(${JSON.stringify(text)})`)
-        if (!(await until(async () => (await js.events()).slice(jsStart).some(e => e.kind === 'chat' && e.text === `echo: ${text}`), 10_000))) {
-            return 'the established data channel stopped exchanging after the relay faults'
-        }
-        if ([...(await cpp.events()).slice(cppStart), ...(await js.events()).slice(jsStart)].some(e => e.kind === 'peer-leave')) {
-            return 'a peer left after the relay fault'
-        }
-        return null
-    })
-
-// A relay that sends a client a text longer than 1 MiB, or resets its connection, just as the client writes: a C++ peer
-// announces 233 ms after it subscribes, and the relay strikes just before. A text that arrives 1 to 2 ms before the
-// write fails the read while Beast holds the write back, so the write completes after the connection ended; measured
-// against the code before the fix, a strike at 232 ms crashed 7 peers in 8, at 231 ms 5 in 8, at 228 or 234 ms none. A
-// reset fails the read and the write at once. One peer at a time, each in a room of its own, which the relay strikes by
-// its topic: each loses the relay once, survives, and reconnects.
-const strikes = [232, 231, 232, 233, 232, 231, 232, 233, 232, 232, 232, 232].map((delay, i) => ({
-    delay,
-    action: i < 8 ? 'too-long' : 'reset',
-}))
-const topicOf = text => Array.from(createHash('sha1').update(text).digest(), b => b.toString(36)).join('')
-const strikeScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        const peers = []
-        for (const {delay, action} of strikes) {
-            const params = {room: room(), ...relayParams}
-            left.relay.options.strike = {action, delay, topic: topicOf(`Trystero@${app}@${params.room}`)}
-            const peer = await open(cppKind, params)
-            peers.push(peer)
-            const lost = await until(async () => (await peer.log()).includes(`lost ${left.relay.url}`), 5_000)
-            left.relay.options.strike = null
-            if (deaths !== deathsBefore) return `a C++ peer died after the relay struck it (${action} at ${delay} ms)`
-            if (!lost) return `${peer.label} did not lose the relay that struck it (${action} at ${delay} ms)`
+        if (!usePublic && !(await until(() => relayed(offerer.self, 'offer', selfTopicOf(room, reporterId.self)).length >= 2))) {
+            return `the relay forwarded no second offer of ${offerer.self}`
         }
-        const back = await until(async () =>
-            (await Promise.all(peers.map(p => p.log()))).every(log => log.includes(`reconnected to ${left.relay.url}`)), 10_000)
-        return back ? null : 'not every C++ peer reconnected to the relay'
-    })
+        const reported = await reports()
+        if (reported > reportsAllowed(since)) return `${reporter.label} reported decrypt-failed ${reported} times`
+        const joined = [...await joinedBy([js], c), ...await joinedBy([cpp], j)]
+        if (joined.length) return `peers with different passwords joined: ${joined.join(', ')}`
+    }
+    return null
+})
 
-// A watcher without the room key (forger.html) answers each offer of the C++ peer with garbage in the name of the peer
-// the offer is for, before that peer's own answer (whose sends js.html holds 1 s): the C++ peer opens an answer before
-// acting on it, so the forged one changes nothing, and the real one joins them.
-const forgedAnswerScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        const cppSelf = '00000000000000000000'
-        const params = {room: room(), ...relayParams}
-        const forger = await open('forger', {...params, target: cppSelf})
-        if (!(await until(async () => (await forger.events()).some(e => e.kind === 'watching'), 10_000))) {
-            return 'the forger did not start watching'
-        }
-        const cpp = await open(cppKind, {...params, self: cppSelf})
-        const js = await open('js', {...params, 'hold-sends': '1'})
-        const ok = await until(async () => exchangeComplete(await cpp.events(), false) && exchangeComplete(await js.events(), true), 30_000)
-        const forged = (await forger.events()).filter(e => e.kind === 'forged').length
-        if (!forged) return 'the forger never answered an offer, so nothing was tested'
-        if (!ok) return `the exchange did not complete in 30 s; the forger answered ${forged} offers`
-        return null
-    })
+// 5. The C++ peer imports a trystero_uk_ text a page exported (createUserIdentity, exportUserIdentity), and a page
+// imports one a C++ peer exported (create_user_identity, export_user_identity): each presents the user it imported,
+// and each sees the other's.
+const identityOf = async page => {
+    if (!(await until(async () => has(await page.events(), 'identity')))) throw new Error(`${page.label} exported no identity`)
+    return (await page.events()).find(e => e.kind === 'identity')
+}
+const importedIdentities = cppKind => scenario('imported_identities', cppKind, async open => {
+    const exporting = freshRoom()
+    const fromPage = await identityOf(await open('js', {room: exporting, export: 1}))
+    const fromCppPeer = await identityOf(await open('cpp', {room: exporting, export: 1}))
+    for (const {text} of [fromPage, fromCppPeer]) {
+        if (!/^trystero_uk_[A-Za-z0-9_-]+$/.test(text)) return `an exported text is not a user key: ${text}`
+    }
+    const cpp = await open('cpp', {identity: fromPage.text})
+    const js = await open('js', {identity: fromCppPeer.text})
+    const c = await idsOf(cpp), j = await idsOf(js)
+    if (c.user !== fromPage.user) return `the C++ peer presents ${c.user}, not the page's ${fromPage.user}`
+    if (j.user !== fromCppPeer.user) return `the page presents ${j.user}, not the C++ peer's ${fromCppPeer.user}`
+    return exchange(cpp, js)
+})
 
-// A watcher without the room key (forger.html, mode=replay) records the sealed answer, or the sealed offer, that a
-// Trystero JS peer sends the C++ peer. Then the JS peer's connections drop (js.html's window.drop), as on a network
-// drop, and Trystero meets the C++ peer again with the same id, its sends held 1 s (hold-sends), so that the watcher
-// resends the recording in its name first: with each new offer of the C++ peer (side 'answer': the C++ peer's id is
-// lower, so it offers), or as soon as the JS peer announces itself or is asked to offer (side 'offer': the C++ peer's
-// id is higher). The recording opens with the room key, but the C++ peer used it before: it refuses it, and the JS
-// peer joins it again.
-const replayScenario = (name, cppKind, side) =>
-    scenario(name, async open => {
-        const cppSelf = side === 'answer' ? '00000000000000000000' : 'zzzzzzzzzzzzzzzzzzzz'
-        const params = {room: room(), ...relayParams}
-        const forger = await open('forger', {...params, target: cppSelf, mode: 'replay'})
-        if (!(await until(async () => (await forger.events()).some(e => e.kind === 'watching'), 10_000))) {
-            return 'the forger did not start watching'
-        }
-        const cpp = await open(cppKind, {...params, self: cppSelf})
-        const js = await open('js', {...params, 'hold-sends': '1'})
-        const ok = await until(async () => exchangeComplete(await cpp.events(), false) && exchangeComplete(await js.events(), true), 30_000)
-        if (!ok) return 'the exchange did not complete in 30 s'
-        if (!(await forger.events()).some(e => e.kind === 'recorded' && e.what === side)) return `the forger recorded no ${side}`
-        await js.value('window.drop()')
-        const back = await until(async () => (await cpp.events()).filter(e => e.kind === 'peer-join').length === 2, 30_000)
-        const replayed = (await forger.events()).filter(e => e.kind === 'replayed' && e.what === side).length
-        if (!replayed) return `the forger resent no ${side}, so nothing was tested`
-        if (!back) return `the Trystero JS peer did not join again in 30 s; the forger resent ${replayed} ${side}s`
-        return (await cpp.log()).includes(`refused the ${side} from`) ? null : `the C++ peer refused no ${side}`
-    })
+// 6. Two C++ apps importing one identity (a third C++ app exported it, in a room of its own), and a page: the page
+// sees two peers and one user.
+const oneUserTwoCppPeers = cppKind => scenario('one_user_two_cpp_peers', cppKind, async open => {
+    const {text, user} = await identityOf(await open('cpp', {room: freshRoom(), export: 1}))
+    const first = await open('cpp', {identity: text})
+    const second = await open('cpp', {identity: text})
+    const js = await open('js')
+    const a = await idsOf(first), b = await idsOf(second)
+    if (a.user !== user || b.user !== user) return `the C++ peers present ${a.user} and ${b.user}, not ${user}`
+    const seen = async () => {
+        const events = await js.events()
+        return has(events, 'peer-join', e => e.peer === a.self && e.user === user) &&
+            has(events, 'peer-join', e => e.peer === b.self && e.user === user)
+    }
+    if (!(await until(seen))) return 'the page did not see both C++ peers join'
+    const users = await js.value('window.users()')
+    if (Object.keys(users).length !== 1 || users[user]?.peerIds?.length !== 2) {
+        return `the page's getUsers() is ${JSON.stringify(users)}, not one user of two peers`
+    }
+    const userJoins = count(await js.events(), 'user-join', e => e.user === user)
+    if (userJoins !== 1) return `the page saw the user join ${userJoins} times`
+    // The two C++ peers are one user: each joins the other, and neither sees a user join of its own user.
+    if (has([...await first.events(), ...await second.events()], 'user-join', e => e.user === user)) {
+        return 'a C++ peer saw its own user join'
+    }
+    return null
+})
 
-// A watcher without the room key (forger.html, mode=reflect) sends the C++ peer its own sealed texts back, in the Trystero
-// JS peer's name: side 'answer' (the C++ peer's id is lower, so it offers), each offer of the C++ peer to the JS peer
-// comes back at once as the JS peer's answer; side 'offer' (its id is higher), the watcher announces a decoy id above
-// it, and the C++ peer's sealed offer to the decoy comes back as the JS peer's offer whenever the JS peer announces,
-// ahead of its own (hold-sends). Each opens with the room key, but the C++ peer made it: it refuses it, and the two
-// peers join.
-const reflectScenario = (name, cppKind, side) =>
-    scenario(name, async open => {
-        // Offer side: the highest id below the decoy's, so that the Trystero JS peer's random id is below it and offers.
-        const cppSelf = side === 'answer' ? '00000000000000000000' : 'zzzzzzzzzzzzzzzzzzzy'
-        const params = {room: room(), ...relayParams}
-        const decoy = side === 'offer' ? {decoy: 'zzzzzzzzzzzzzzzzzzzz'} : {}
-        const forger = await open('forger', {...params, target: cppSelf, mode: 'reflect', ...decoy})
-        if (!(await until(async () => (await forger.events()).some(e => e.kind === 'watching'), 10_000))) {
-            return 'the forger did not start watching'
+// 7. A page room with maxUsers 2 holding two users refuses the C++ peer as a third (room_full on the C++ side), and
+// a C++ room with max_users 2 holding two refuses a page (room-full on the page). What must not happen, the third
+// joining, is checked once the refusal came, and again at the end.
+const maxUsers = cppKind => scenario('max_users_both_ways', cppKind, async open => {
+    const refusedJoins = []
+    {
+        const full = await open('js', {maxUsers: 2})
+        const other = await open('js')
+        const f = await idsOf(full), o = await idsOf(other)
+        if (!(await until(async () => has(await full.events(), 'peer-join', e => e.peer === o.self)))) {
+            return 'the page of maxUsers 2 did not take its second user'
         }
-        const cpp = await open(cppKind, {...params, self: cppSelf})
-        if (side === 'offer' && !(await until(async () => (await forger.events()).some(e => e.kind === 'recorded'), 10_000))) {
-            return 'the C++ peer made no offer to the decoy'
+        const cpp = await open('cpp')
+        const c = await idsOf(cpp)
+        const refused = async () => has(await cpp.events(), 'error', e => e.code === 'room-full' && e.peer === f.self)
+        if (!(await until(refused))) return 'the C++ peer was not refused with room_full by the full page'
+        refusedJoins.push([full, c], [cpp, f])
+    }
+    {
+        const room = freshRoom()
+        const cpp = await open('cpp', {room, maxUsers: 2})
+        const first = await open('js', {room})
+        const c = await idsOf(cpp), j = await idsOf(first)
+        if (!(await until(async () => has(await cpp.events(), 'peer-join', e => e.peer === j.self)))) {
+            return 'the C++ room of max_users 2 did not take its second user'
         }
-        const js = await open('js', {...params, 'hold-sends': '1'})
-        const ok = await until(async () => exchangeComplete(await cpp.events(), false) && exchangeComplete(await js.events(), true), 30_000)
-        const reflected = (await forger.events()).filter(e => e.kind === 'reflected' && e.what === side).length
-        if (!reflected) return `the forger reflected no ${side}, so nothing was tested`
-        if (!ok) return `the exchange did not complete in 30 s; the forger reflected ${reflected} ${side}s`
-        return (await cpp.log()).includes(`refused the ${side} from`) ? null : `the C++ peer refused no ${side}`
-    })
+        const third = await open('js', {room})
+        const t = await idsOf(third)
+        const refused = async () => has(await third.events(), 'error', e => e.code === 'room-full' && e.peer === c.self)
+        if (!(await until(refused))) return 'the page was not refused with room-full by the full C++ room'
+        refusedJoins.push([cpp, t], [third, c])
+    }
+    for (const [page, of] of refusedJoins) {
+        if ((await joinedBy([page], of)).length) return `${page.label} joined ${of.self}, a third user`
+    }
+    return null
+})
 
-// ---- rooms of one app sharing one connection (S:6.4) ---------------------------------------------------------------
-const inRoom = (events, which) => events.filter(e => (e.room ?? 'first') === which)
-const roomComplete = (events, which, file) => {
-    const mine = inRoom(events, which)
-    return mine.some(e => e.kind === 'peer-join') && mine.some(e => e.kind === 'chat') &&
-        mine.some(e => e.kind === 'file' && e.size === file.size && e.checksum === file.checksum)
-}
-// What each side did with connections: the C++ peer's made (Chromium's count in cpp.html, or the native backend's
-// made-connection events) and adopted (its app's log), the page's made and connected (its RTCPeerConnection wrapper).
-const connectionCounts = async (cpp, cppKind, js) => ({
-    cppMade: cppKind === 'native'
-        ? (await cpp.events()).filter(e => e.kind === 'made-connection').length
-        : await cpp.value('window.madePeerConnections'),
-    cppAdopted: (await cpp.events()).filter(e => e.kind === 'adopted').length,
-    jsMade: await js.value('window.connectionStates().length'),
-    jsConnected: await js.value("window.connectionStates().filter(s => s === 'connected').length"),
+// 8. A request each way, answered, and a ping each way.
+const requestsAndPings = cppKind => scenario('requests_and_pings', cppKind, async open => {
+    const cpp = await open('cpp')
+    const js = await open('js')
+    const c = await idsOf(cpp), j = await idsOf(js)
+    const answered = (events, peer, text) => has(events, 'response', e => e.peer === peer && e.error === '' && e.text === text)
+    const pinged = (events, peer) => has(events, 'ping', e => e.peer === peer && e.error === '' && e.ms >= 0)
+    const done = async () => answered(await cpp.events(), j.self, 'answer to: question from C++') &&
+        answered(await js.events(), c.self, 'answer to: question from Trystero JS') &&
+        pinged(await cpp.events(), j.self) && pinged(await js.events(), c.self)
+    return (await until(done)) ? null : 'a request or a ping did not complete both ways'
 })
-// Rooms that negotiate at once can meet the crossed race of S:2.4, where both sides lose both connections and meet
-// again: past this many connections on a side the scenario fails naming the counts, so that a livelock fails by name.
-const crossedBound = 4
-const overBound = c => c.cppMade > crossedBound || c.jsMade > crossedBound || c.cppAdopted > crossedBound
-// Watches `count()` for `ms`, noting the driver's time of each increase: the instants of a peer's reports, within
-// the 250 ms of a poll.
-const instants = async (count, ms) => {
-    const end = Date.now() + ms
-    const seen = []
-    while (Date.now() < end && deaths === deathsBefore) {
-        const n = await count()
-        while (seen.length < n) seen.push(Date.now())
-        await new Promise(r => setTimeout(r, 250))
-    }
-    return seen
-}
-// The exchanges of the first room and of room2, both ways.
-const twoRoomsComplete = async (cpp, js) => {
-    const c = await cpp.events(), j = await js.events()
-    return exchangeComplete(inRoom(c, 'first'), false) && exchangeComplete(inRoom(j, 'first'), true) &&
-        roomComplete(c, 'second', fromJs) && roomComplete(j, 'second', fromCpp)
-}
 
-// 1. Two rooms on one connection, no password: both rooms' exchanges complete both ways; at the end the page holds
-// one connected RTCPeerConnection, and the C++ peer's app adopted one connection, or, when the page made more than one
-// (a crossing), at most crossedBound (the plan's conflict 14).
-const twoRoomsOneConnectionScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        const params = {room: room(), room2: room(), ...relayParams}
-        const cpp = await open(cppKind, params)
-        const js = await open('js', params)
-        const ok = await until(() => twoRoomsComplete(cpp, js), 60_000)
-        const counts = await connectionCounts(cpp, cppKind, js)
-        const facts = `connections ${JSON.stringify(counts)}`
-        if (overBound(counts)) return `${facts}: past the bound of ${crossedBound}`
-        if (!ok) return `the two rooms did not both complete in 60 s; ${facts}`
-        if (counts.jsConnected !== 1) return `the page does not hold exactly one connected connection; ${facts}`
-        if (counts.jsMade === 1 && counts.cppAdopted !== 1) return `no crossing, yet ${counts.cppAdopted} adoptions; ${facts}`
-        return null
-    })
+// 9. A C++ leave is the page's onPeerLeave and onUserLeave, and the page's leave the C++ peer's on_peer_leave and
+// on_user_leave.
+const leaves = cppKind => scenario('leaves', cppKind, async open => {
+    for (const leaver of ['cpp', 'js']) {
+        const room = freshRoom()
+        const cpp = await open('cpp', {room})
+        const js = await open('js', {room})
+        const failed = await exchange(cpp, js)
+        if (failed) return `${leaver} leaving: ${failed}`
+        const [goes, stays] = leaver === 'cpp' ? [cpp, js] : [js, cpp]
+        const g = await idsOf(goes)
+        await goes.leave()
+        const seen = async () => {
+            const events = await stays.events()
+            return has(events, 'peer-leave', e => e.peer === g.self && e.user === g.user) &&
+                has(events, 'user-leave', e => e.user === g.user && e.peer === g.self) &&
+                has(await goes.events(), 'left', e => e.error === '')
+        }
+        if (!(await until(seen))) return `${goes.label} left, and ${stays.label} did not see its peer and its user leave`
+    }
+    return null
+})
 
-// 2. Three rooms on one connection: the C++ peer joins room3 5 s after the others, over the connection already there
-// (by presence): room3 completes both ways, and no side makes a connection for it.
-const threeRoomsScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        const params = {room: room(), room2: room(), room3: room(), ...relayParams}
-        const cpp = await open(cppKind, {...params, room3Delay: 5000})
-        const js = await open('js', params)
-        if (!(await until(() => twoRoomsComplete(cpp, js), 4500))) return 'the first two rooms did not complete before room3 joined'
-        const before = await connectionCounts(cpp, cppKind, js)
-        const joined3 = async () => inRoom(await cpp.events(), 'third').some(e => e.kind === 'joined')
-        if (!(await until(joined3, 20_000))) return 'the C++ peer did not join room3'
-        const ok = await until(async () => (await twoRoomsComplete(cpp, js)) &&
-            roomComplete(await cpp.events(), 'third', fromJs) && roomComplete(await js.events(), 'third', fromCpp), 60_000)
-        const after = await connectionCounts(cpp, cppKind, js)
-        const facts = `connections before room3 joined ${JSON.stringify(before)}, at the end ${JSON.stringify(after)}`
-        if (overBound(after)) return `${facts}: past the bound of ${crossedBound}`
-        if (!ok) return `the three rooms did not all complete in 60 s; ${facts}`
-        if (before.jsConnected !== 1) return `the connection was not up when the C++ peer joined room3; ${facts}`
-        if (after.cppMade !== before.cppMade || after.jsMade !== before.jsMade) return `room3 made a connection; ${facts}`
-        return after.jsConnected === 1 ? null : `the page does not hold one connected connection; ${facts}`
-    })
+// 10. forger.html joins with a custom identity whose sign() passes 0.27.0's startup check and then signs with
+// another key: the C++ peer reports handshake_failed for it, once per handshake run (one per connection the C++
+// peer's log shows negotiated with it, by its offer ids), and never joins it.
+const forgedUserSignature = cppKind => scenario('a_forged_user_signature', cppKind, async open => {
+    const cpp = await open('cpp')
+    const forger = await open('forger')
+    const f = await idsOf(forger)
+    const reports = async () => count(await cpp.events(), 'error', e => e.code === 'handshake-failed' && e.peer === f.self)
+    if (!(await until(async () => (await reports()) > 0))) return 'the C++ peer did not report handshake_failed for the forger'
+    if (count(await forger.events(), 'signed') < 2) return 'the forger signed nothing after its startup check'
+    if ((await joinedBy([cpp], f)).length) return 'the C++ peer joined the forger'
+    const reported = await reports()
+    const log = await cpp.log()
+    const runs = new Set([
+        ...[...log.matchAll(new RegExp(`sending offer (\\S+) to ${f.self}`, 'g'))].map(m => m[1]),
+        ...[...log.matchAll(new RegExp(`offer (\\S+) from ${f.self}`, 'g'))].map(m => m[1]),
+    ]).size
+    if (reported > runs) return `the C++ peer reported handshake_failed ${reported} times for ${runs} connections`
+    return (await joinedBy([cpp], f)).length ? 'the C++ peer joined the forger' : null
+})
 
-// 3. A room the page joined first: the page joins room and room2; 15 s later the C++ peer joins room, then room2:
-// room2 joins within 5 s of the C++ peer's join of it, over the connection, by the page's presence.
-const pageFirstScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        const params = {room: room(), room2: room(), ...relayParams}
-        const js = await open('js', params)
-        await new Promise(r => setTimeout(r, 15_000))
-        const cpp = await open(cppKind, {...params, room2Delay: 5000})
-        const firstComplete = async () => exchangeComplete(inRoom(await cpp.events(), 'first'), false) &&
-            exchangeComplete(inRoom(await js.events(), 'first'), true)
-        if (!(await until(firstComplete, 4500))) return 'room did not complete before the delayed room2 join'
-        const before = await connectionCounts(cpp, cppKind, js)
-        if (before.jsConnected !== 1) return `room2 has no existing connection to reuse: ${JSON.stringify(before)}`
-        const joined2 = async () => inRoom(await cpp.events(), 'second').some(e => e.kind === 'joined')
-        if (!(await until(joined2, 10_000))) return 'the C++ peer did not join room2'
-        const met = async () => inRoom(await cpp.events(), 'second').some(e => e.kind === 'peer-join') &&
-            inRoom(await js.events(), 'second').some(e => e.kind === 'peer-join')
-        if (!(await until(met, 5_000))) return 'room2 did not join within 5 s of the C++ peer joining it'
-        if (!(await until(() => twoRoomsComplete(cpp, js), 30_000))) return 'the two rooms did not complete their exchanges'
-        const after = await connectionCounts(cpp, cppKind, js)
-        const facts = `connections before ${JSON.stringify(before)}, after ${JSON.stringify(after)}`
-        if (overBound(after)) return `${facts}: past the bound of ${crossedBound}`
-        if (after.cppMade !== before.cppMade || after.jsMade !== before.jsMade) return `room2 made a connection; ${facts}`
-        return after.jsConnected === 1 ? null : facts
-    })
+// 11. Two pages and a C++ peer: each joins both others, and exchanges with each.
+const mesh = cppKind => scenario('mesh', cppKind, async open => {
+    const first = await open('js')
+    const cpp = await open('cpp')
+    const second = await open('js')
+    for (const js of [first, second]) {
+        const failed = await exchange(cpp, js)
+        if (failed) return failed
+    }
+    const a = await idsOf(first), b = await idsOf(second)
+    const met = async () => has(await first.events(), 'peer-join', e => e.peer === b.self) &&
+        has(await second.events(), 'peer-join', e => e.peer === a.self)
+    return (await until(met)) ? null : 'the two pages did not join each other'
+})
 
-// 5. One room leaving, either side: the leaver leaves room; the other side sees peer-leave in room only; a chat sent in
-// room2 afterwards crosses both ways (the C++ room2 echoes it); no connection is made.
-const oneRoomLeavingScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        for (const leaver of ['cpp', 'js']) {
-            const params = {room: room(), room2: room(), ...relayParams}
-            const cpp = await open(cppKind, params)
-            const js = await open('js', params)
-            if (!(await until(() => twoRoomsComplete(cpp, js), 60_000))) return `${leaver}: the two rooms did not complete in 60 s`
-            const before = await connectionCounts(cpp, cppKind, js)
-            const [goes, stays] = leaver === 'cpp' ? [cpp, js] : [js, cpp]
-            await goes.leaveRoom()
-            const seen = async () => inRoom(await stays.events(), 'first').some(e => e.kind === 'peer-leave')
-            if (!(await until(seen, 10_000))) return `${leaver} left room, and the other side saw no peer-leave in it`
-            const text = `after ${leaver} left`
-            await js.value(`window.chat2(${JSON.stringify(text)})`)
-            const crossed = async () =>
-                inRoom(await cpp.events(), 'second').some(e => e.kind === 'chat' && e.text === text) &&
-                inRoom(await js.events(), 'second').some(e => e.kind === 'chat' && e.text === `echo: ${text}`)
-            const ok = await until(crossed, 10_000)
-            const after = await connectionCounts(cpp, cppKind, js)
-            const facts = `connections before ${JSON.stringify(before)}, after ${JSON.stringify(after)}`
-            if (!ok) return `${leaver}: a chat in room2 did not cross both ways after the leave; ${facts}`
-            const second = [...inRoom(await cpp.events(), 'second'), ...inRoom(await js.events(), 'second')]
-            if (second.some(e => e.kind === 'peer-leave')) return `${leaver}: room2 saw a peer leave; ${facts}`
-            if (after.cppMade !== before.cppMade || after.jsMade !== before.jsMade) return `${leaver}: a connection was made; ${facts}`
+// 12. Relay connectivity, each side in turn, as the local relay sees it. Two peers meet; one, the holder, goes
+// offline: the relay has its subscriptions closed. The other leaves and a new peer joins in its place, whose
+// announcement the relay forwards to no subscription of the holder, which does not meet it then; the holder goes
+// online, subscribes again, and meets the new peer. Then a late peer of the holder's kind starts offline: once the
+// relay forwarded an announcement of the new peer after the late one joined, the late one has neither subscribed nor
+// sent anything; it goes online, subscribes, and meets the new peer.
+const relayConnectivity = cppKind => scenario('relay_connectivity', cppKind, async open => {
+    for (const offline of ['cpp', 'js']) {
+        const room = freshRoom()
+        const [mine, theirs] = offline === 'cpp' ? ['cpp', 'js'] : ['js', 'cpp']
+        const pair = (a, b) => (offline === 'cpp' ? exchange(a, b) : exchange(b, a))
+        const subscribed = page => left.relay.subscribed(selfTopicOf(room, page.self))
+        const holder = await open(mine, {room})
+        const leaver = await open(theirs, {room})
+        const h = await idsOf(holder), l = await idsOf(leaver)
+        const failed = await pair(holder, leaver)
+        if (failed) return `${offline} offline: ${failed}`
+        await holder.offline()
+        if (!(await until(() => subscribed(h) === 0))) return `${holder.label} went offline, and the relay still has its subscription`
+        await leaver.leave()
+        if (!(await until(async () => has(await holder.events(), 'peer-leave', e => e.peer === l.self)))) {
+            return `${holder.label} did not see ${leaver.label} leave`
         }
-        return null
-    })
-
-// 6. A peer leaving every room: both sides are given an idle time of 2 s; the page leaves both rooms: the C++ peer
-// records both leaves, and the connection closes on both sides after the idle time, not before.
-const leavingEveryRoomScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        const params = {room: room(), room2: room(), idle: 2000, ...relayParams}
-        const cpp = await open(cppKind, params)
-        const js = await open('js', params)
-        if (!(await until(() => twoRoomsComplete(cpp, js), 60_000))) return 'the two rooms did not complete in 60 s'
-        const endedBefore = (await cpp.events()).filter(e => e.kind === 'ended').length
-        await js.value('window.leave()')
-        const leftAt = Date.now()
-        await js.value('window.leave2()')
-        const bothLeft = async () => {
-            const c = await cpp.events()
-            return inRoom(c, 'first').some(e => e.kind === 'peer-leave') && inRoom(c, 'second').some(e => e.kind === 'peer-leave')
+        const next = await open(theirs, {room})
+        const n = await idsOf(next)
+        if (!(await until(() => relayed(n.self, 'announce', rootTopicOf(room)).length > 0))) {
+            return `the relay forwarded no announcement of ${next.label}`
         }
-        if (!(await until(bothLeft, 10_000))) return 'the C++ peer did not see the page leave both rooms'
-        const closed = async () =>
-            (await js.value("window.connectionStates().filter(s => s === 'connected').length")) === 0 &&
-            (await cpp.events()).filter(e => e.kind === 'ended').length > endedBefore
-        if (!(await until(closed, 10_000))) return 'the connection did not close on both sides within 10 s of the leaves'
-        const seconds = (Date.now() - leftAt) / 1000
-        return seconds >= 1.5 ? null : `the connection closed ${seconds} s after the leaves, before the idle time of 2 s`
-    })
+        if (subscribed(h) !== 0) return `${holder.label} subscribed again while offline`
+        if ((await joinedBy([holder], n)).length) return `${holder.label} met ${next.label} while offline`
+        await holder.online()
+        if (!(await until(() => subscribed(h) > 0))) return `${holder.label} went online, and did not subscribe again`
+        const again = await pair(holder, next)
+        if (again) return `${offline} back online: ${again}`
 
-// The negotiations a C++ peer opened with `peer`, by its log: the offers it sent that peer, each once however often it
-// resent it, and the offers of that peer it answered. Each made a connection for that peer, where the counts of
-// connections made (cpp.html's madePeerConnections, the native peer's made-connection events) count every peer's.
-const negotiationsWith = async (cpp, peer) => {
-    const log = await cpp.log()
-    const offers = new Set([...log.matchAll(new RegExp(`sending offer (\\w+) to ${peer}\\b`, 'g'))].map(m => m[1]))
-    return offers.size + [...log.matchAll(new RegExp(`signal: offer \\w+ from ${peer}\\b`, 'g'))].length
-}
+        const late = await open(mine, {room, offline: 1})
+        const t = await idsOf(late)
+        const announced = relayed(n.self, 'announce', rootTopicOf(room)).length
+        if (!(await until(() => relayed(n.self, 'announce', rootTopicOf(room)).length > announced))) {
+            return `the relay forwarded no announcement of ${next.label} after ${late.label} joined`
+        }
+        if (subscribed(t) !== 0) return `${late.label} started offline, and subscribed`
+        if (left.relay.received.some(e => e.peerId === t.self)) return `${late.label} started offline, and sent a signal`
+        await late.online()
+        if (!(await until(() => subscribed(t) > 0))) return `${late.label} went online, and did not subscribe`
+        const met = await pair(late, next)
+        if (met) return `${late.label} online: ${met}`
+    }
+    return null
+})
 
-// 4. A public app exposes its other rooms to a peer on its connection. A separate password-protected app has
-// another peer id, so public-channel presence and readiness injections cannot reach its rooms or broadcasts.
-// The protected app joins the public app's first room once the public connection is up, so that the two apps meet
-// within the window observed: whatever the passwords, the lower id offers to a higher one it sees announced, as
-// Trystero does, and the other cannot open the offer. The public app, when it has the lower id, so makes a connection
-// for the protected app when they meet, and another each time its unanswered offer expires (57 s): its connection with
-// the page is judged by the negotiations it opened with the page, not by every connection it made.
-const openToOtherRoomsScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        for (const protectedSelf of ['00000000000000000000', 'zzzzzzzzzzzzzzzzzzzz']) {
-            const publicSelf = protectedSelf.startsWith('0') ? 'zzzzzzzzzzzzzzzzzzzz' : '00000000000000000000'
-            const rooms = {room: room(), room2: room(), secret: room()}
-            const cpp = await open(cppKind, {room: rooms.room, room2: rooms.room2, self: publicSelf, ...relayParams})
-            // The page knows the protected room id but has no password. It also injects that token over its public
-            // connection, alongside the public app's actual advertisements.
-            const js = await open('js', {room: rooms.room, room3: rooms.secret, ...relayParams})
-            const ok = await until(async () => exchangeComplete(inRoom(await cpp.events(), 'first'), false) &&
-                exchangeComplete(inRoom(await js.events(), 'first'), true), 30_000)
-            if (!ok) return `${protectedSelf}: the public room did not complete in 30 s`
-            if (!(await until(async () => (await js.value('window.advertisedCount()')) >= 2, 10_000))) {
-                return `${protectedSelf}: the public app did not advertise both rooms`
-            }
-            const pageSelf = (await js.events()).find(e => e.kind === 'joined')?.self
-            const publicConnection = async () =>
-                ({withPage: await negotiationsWith(cpp, pageSelf), ...await connectionCounts(cpp, cppKind, js)})
-            const before = await publicConnection()
-            if (before.withPage < 1) return `${protectedSelf}: the public app's log names no negotiation with the page`
-            const protectedCpp = await open(cppKind, {
-                room: rooms.room, room2: rooms.secret, self: protectedSelf, password: 'vault', ...relayParams,
-            })
-            const refused = async () => inRoom(await protectedCpp.events(), 'second').some(e => e.kind === 'error') ||
-                inRoom(await js.events(), 'third').some(e => e.kind === 'error' && e.peer === protectedSelf)
-            if (!(await until(refused, 15_000))) return `${protectedSelf}: the protected room saw no attempted negotiation`
-            // The two apps met: the higher id could not open the lower id's offer, or a candidate of it, whichever came
-            // first (it says so once per negotiation).
-            const higher = protectedSelf > publicSelf ? protectedCpp : cpp
-            const lowerSelf = protectedSelf > publicSelf ? publicSelf : protectedSelf
-            const met = async () => new RegExp(`could not open the \\w+ from ${lowerSelf}`).test(await higher.log())
-            if (!(await until(met, 15_000))) {
-                return `${protectedSelf}: the public and the protected apps did not meet in 15 s`
-            }
-            const echoed = await js.value(`window.echoPresence([${JSON.stringify(rooms.secret)}])`)
-            if (echoed < 3) return `${protectedSelf}: the injection omitted a public or protected token`
-            const joined2 = async () => inRoom(await cpp.events(), 'second').some(e => e.kind === 'peer-join')
-            if (!(await until(joined2, 15_000))) return `${protectedSelf}: the public app's room2 did not admit the page`
-            const sent2 = async () => (await js.value(`window.roomFrames(${JSON.stringify(rooms.room2)}, 'chat')`)) > 0 &&
-                (await js.value(`window.roomFrames(${JSON.stringify(rooms.room2)}, 'file')`)) > 0
-            if (!(await until(sent2, 10_000))) return `${protectedSelf}: the public room2 did not send chat and file frames`
-            await new Promise(r => setTimeout(r, 15_000))
-            const protectedEvents = await protectedCpp.events()
-            if (protectedEvents.some(e => e.kind === 'peer-join' || e.kind === 'adopted')) {
-                return `${protectedSelf}: the protected app admitted a peer without its password`
-            }
-            if (inRoom(await js.events(), 'third').some(e => e.kind === 'peer-join')) {
-                return `${protectedSelf}: the page joined the protected room`
-            }
-            if ((await js.value(`window.roomFrames(${JSON.stringify(rooms.secret)}, 'chat')`)) !== 0 ||
-                (await js.value(`window.roomFrames(${JSON.stringify(rooms.secret)}, 'file')`)) !== 0) {
-                return `${protectedSelf}: protected broadcasts reached the public page`
-            }
-            const after = await publicConnection()
-            if (after.withPage !== before.withPage || after.jsConnected !== 1) {
-                return `${protectedSelf}: the public connection changed: before ${JSON.stringify(before)}, after ${JSON.stringify(after)}`
+// ---- adversarial peers on the relays ------------------------------------------------------------------------------
+// A peer of the room sends the C++ peer candidates that are not candidates, sealed under the room's key for the C++
+// peer's offer to the page in the page's name, as a broken or hostile peer of the room can: a text that is not JSON,
+// and an RTCIceCandidateInit whose candidate WebRTC refuses (in a page, Chrome's addIceCandidate rejects it). The C++
+// peer's id is below the page's, so that it offers; the relay holds the page's answer until the candidates are in, so
+// that the C++ peer holds them until its offer is answered, and then adds them: it drops each, says so, throws
+// nothing into WebAssembly, and the exchange completes. ids_and_messages_both_ways is the control: no candidate of a
+// page is dropped there.
+const malformedCandidates = ['not JSON at all', JSON.stringify({candidate: 'candidate:not a candidate', sdpMid: '0'})]
+const malformedCandidateScenario = cppKind => scenario('a_malformed_candidate', cppKind, async open => {
+    const room = freshRoom()
+    const js = await open('js', {room})
+    const j = await idsOf(js)
+    left.relay.options.hold = (topic, content) => content?.peerId === j.self && typeof content?.answer === 'string'
+    let cpp
+    try {
+        cpp = await open('cpp', {room, key: await keyAround(j.self, true)})
+        const c = await idsOf(cpp)
+        if (!(c.self < j.self)) return `the C++ peer's id ${c.self} is not below ${j.self}`
+        if (!(await until(() => relayed(c.self, 'offer', selfTopicOf(room, j.self)).length > 0))) {
+            return 'the relay forwarded no offer of the C++ peer to the page'
+        }
+        const {offerId} = relayed(c.self, 'offer', selfTopicOf(room, j.self))[0]
+        const key = genKey('', app, room)
+        const publisher = await openPublisher()
+        try {
+            for (const candidate of malformedCandidates) {
+                await publisher.publish(selfTopicOf(room, c.self), {
+                    peerId: j.self, offerId, candidate: await encrypt(key, candidate, `candidate|${j.self}|${offerId}`),
+                })
             }
+        } finally {
+            publisher.close()
         }
-        return null
-    })
+    } finally {
+        left.relay.release()
+    }
+    const failed = await exchange(cpp, js)
+    if (failed) return failed
+    const dropped = (await cpp.log()).split(`dropped a candidate from ${j.self}`).length - 1
+    return dropped >= malformedCandidates.length
+        ? null : `the C++ peer dropped ${dropped} candidates of the page, not the ${malformedCandidates.length} malformed ones`
+})
 
-// 7. A wrong password in room2, in both id orders (ruling 9). With the C++ peer the lower id, it reports
-// wrong_password in room2 3 times in 60 s, at about 0, 11 and 33 s from the first. With it the higher id, the page
-// records Trystero's password error at most 4 times in 60 s, and the C++ peer reports nothing in room2. In both, room
-// keeps exchanging, and no connection is made.
-const wrongPasswordScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        const wrong = 'the peer uses another room password'
-        for (const cppSelf of ['00000000000000000000', 'zzzzzzzzzzzzzzzzzzzz']) {
-            const lower = cppSelf.startsWith('0')
-            const params = {room: room(), room2: room(), ...relayParams}
-            // Both passwords are nonempty: a passwordless C++ room sends readiness, not a password challenge.
-            // The page joins room2 after the C++ room's initial relay announcement warmup has ended.
-            // A later C++ join would send that warmup to JS and trigger extra reuse handshakes by its design.
-            const cpp = await open(cppKind, {...params, self: cppSelf, password: 'p'})
-            const js = await open('js', {...params, password: 'p', password2: 'another', room2Delay: 15000})
-            const cppReports = async () => inRoom(await cpp.events(), 'second').filter(e => e.kind === 'error').length
-            const cppWrong = async () => inRoom(await cpp.events(), 'second').filter(e => e.kind === 'error' && e.error === wrong).length
-            const jsReports = async () => inRoom(await js.events(), 'second').filter(e => e.kind === 'error').length
-            // Watched from the start, so that the first report, which can come before room completes, has its time.
-            const watching = instants(lower ? cppWrong : jsReports, 60_000)
-            const ok = await until(async () => exchangeComplete(inRoom(await cpp.events(), 'first'), false) &&
-                exchangeComplete(inRoom(await js.events(), 'first'), true), 30_000)
-            const before = await connectionCounts(cpp, cppKind, js)
-            const seen = await watching
-            if (!ok) return `${cppSelf}: room did not complete in 30 s`
-            const offsets = seen.map(t => (t - seen[0]) / 1000)
-            if (lower) {
-                const expected = [0, 11, 33]
-                const near = offsets.length === 3 && offsets.every((s, i) => Math.abs(s - expected[i]) <= 3)
-                if (!near) return `the C++ peer, the lower id, reported wrong_password at ${offsets.join(', ')} s, not about 0, 11 and 33`
-            } else {
-                if (seen.length < 1 || seen.length > 4) return `the page reported ${seen.length} password errors in 60 s, not 1 to 4`
-                if ((await cppReports()) !== 0) return 'the C++ peer, the higher id, reported in room2'
-            }
-            const second = [...inRoom(await cpp.events(), 'second'), ...inRoom(await js.events(), 'second')]
-            if (second.some(e => e.kind === 'peer-join')) return `${cppSelf}: room2 joined with different passwords`
-            const text = `still here ${cppSelf}`
-            await js.value(`window.chat1(${JSON.stringify(text)})`)
-            const echoed = async () => inRoom(await js.events(), 'first').some(e => e.kind === 'chat' && e.text === `echo: ${text}`)
-            if (!(await until(echoed, 10_000))) return `${cppSelf}: room stopped exchanging`
-            const after = await connectionCounts(cpp, cppKind, js)
-            if (after.cppMade !== before.cppMade || after.jsMade !== before.jsMade) {
-                return `${cppSelf}: a connection was made: before ${JSON.stringify(before)}, after ${JSON.stringify(after)}`
+// After a page joined the C++ peer, a flooder who reads and writes the relays, with no key, sends what no key is needed
+// for, each from fresh ids: offers sealed by no key to the C++ peer, each twice, from ids below its own, and then
+// announcements on the room's topic from ids above its own, which the C++ peer offers to. The C++ peer handles every
+// one (its log names each id, or its refusal); reports each offer it cannot open as decrypt-failed at most once per
+// peer and stage (0.27.0's reportDecryptErr); offers to at most max_unconnected_peers (32) of the announcing ids, makes
+// at most max_connections_per_window (64) connections in the flood (all three bounds times the offer_ttl windows the
+// run spans, one on a normal run), and every offer of the flood is reported (counted as the platform counts them: cpp.html's
+// RTCPeerConnections, the native backend's made-connection events), and goes on with the page: no peer leaves, and a
+// chat message after the flood is echoed. The page offers to the announcing ids too, as a 0.27.0 peer does.
+const floodCount = 300
+const unconnectedBound = 32
+const connectionBound = 64
+const floodScenario = cppKind => scenario('a_flood_of_signals_from_fresh_ids', cppKind, async open => {
+    const room = freshRoom()
+    const since = Date.now()
+    const cpp = await open('cpp', {room})
+    const js = await open('js', {room})
+    const failed = await exchange(cpp, js)
+    if (failed) return failed
+    const c = await idsOf(cpp)
+    const fresh = prefix => {
+        const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
+        return prefix + Array.from({length: 20 - prefix.length}, () => alphabet[Math.floor(Math.random() * 62)]).join('')
+    }
+    const offering = Array.from({length: floodCount}, () => fresh('0000000000'))
+    const announcing = Array.from({length: floodCount}, () => fresh('zzzzzzzzzz'))
+    if (!(offering.every(id => id < c.self) && announcing.every(id => id > c.self))) {
+        return `the C++ peer's id ${c.self} is not between the flood's`
+    }
+    const connections = async () => cppKind === 'native'
+        ? count(await cpp.events(), 'made-connection')
+        : await cpp.value('window.madePeerConnections')
+    const before = {connections: await connections(), cpp: (await cpp.events()).length, js: (await js.events()).length}
+    const publisher = await openPublisher()
+    try {
+        for (const peerId of offering) {
+            for (let i = 0; i < 2; ++i) {
+                await publisher.publish(selfTopicOf(room, c.self), {peerId, offerId: 'forged', offer: 'not a sealed offer'})
             }
         }
-        return null
-    })
+        for (const peerId of announcing) await publisher.publish(rootTopicOf(room), {peerId})
+    } finally {
+        publisher.close()
+    }
+    const ids = async said => new Set([...(await cpp.log()).matchAll(new RegExp(`(?:${said}|refusing) (\\w{20})`, 'g'))].map(m => m[1]))
+    const handled = async () => {
+        const opened = await ids('could not open the offer from'), heard = await ids('announcement from')
+        return offering.every(id => opened.has(id)) && announcing.every(id => heard.has(id))
+    }
+    if (!(await until(handled))) return 'the C++ peer did not handle every signal of the flood'
+    const log = await cpp.log()
+    const offered = new Set([...log.matchAll(/announcement from (\w{20}): our id is lower, so we offer/g)]
+        .map(m => m[1]).filter(id => announcing.includes(id)))
+    const made = (await connections()) - before.connections
+    const reports = new Map()
+    for (const e of (await cpp.events()).slice(before.cpp)) {
+        if (e.kind === 'error' && e.code === 'decrypt-failed') reports.set(e.peer, (reports.get(e.peer) ?? 0) + 1)
+    }
+    const facts = `the C++ peer offered to ${offered.size} of ${floodCount} announcing ids, made ${made} connections ` +
+        `in the flood, and reported decrypt-failed for ${reports.size} of ${floodCount} offering ids`
+    console.log(`  ${facts}`)
+    const windows = windowsSince(since)
+    if (offered.size > unconnectedBound * windows) return `${facts}; it offered to more than ${unconnectedBound * windows}`
+    if (made > connectionBound * windows) return `${facts}; more than ${connectionBound * windows} connections`
+    if (reports.size !== floodCount) return `${facts}; not every offer of the flood was reported`
+    const allowed = reportsAllowed(since)
+    const often = [...reports].filter(([, n]) => n > allowed)
+    if (often.length) return `${facts}; reported more than ${allowed} times: ${JSON.stringify(often)}`
+    const text = 'still exchanging after the flood'
+    await js.value(`window.chat(${JSON.stringify(text)}, ${JSON.stringify(c.self)})`)
+    const echoed = async () => (await js.events()).slice(before.js).some(e => e.kind === 'chat' && e.text === `echo: ${text}`)
+    if (!(await until(echoed))) return `${facts}; the page's chat message after the flood was not echoed`
+    if ([...(await cpp.events()).slice(before.cpp), ...(await js.events()).slice(before.js)].some(e => e.kind === 'peer-leave')) {
+        return `${facts}; a peer left during the flood`
+    }
+    return null
+})
 
-// 8. A flood in one room: the page sends 5,000 messages on room's chat while the C++ peer pings room2 every second:
-// every ping completes within 2 s, and the C++ peer stays joined in both rooms.
-const roomFloodScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        const params = {room: room(), room2: room(), ...relayParams}
-        const cpp = await open(cppKind, {...params, ping2: 1})
-        const js = await open('js', params)
-        if (!(await until(() => twoRoomsComplete(cpp, js), 60_000))) return 'the two rooms did not complete in 60 s'
-        const started = events => inRoom(events, 'second').filter(e => e.kind === 'ping-started')
-        const before = started(await cpp.events()).length
-        await js.value('window.flood5000()')
-        await new Promise(r => setTimeout(r, 10_000))
-        const issued = started(await cpp.events()).slice(before)
-        if (issued.length < 5) return `only ${issued.length} pings of room2 began during the flood`
-        const pingsOf = async () => inRoom(await cpp.events(), 'second').filter(e => e.kind === 'ping')
-        const completed = await until(async () => {
-            const pings = await pingsOf()
-            return issued.every(start => pings.some(e => e.id === start.id))
-        }, 2000)
-        if (!completed) return 'a ping issued during the flood did not complete within 2 s of its end'
-        const ids = new Set(issued.map(e => e.id))
-        const pings = (await pingsOf()).filter(e => ids.has(e.id))
-        const slow = pings.filter(e => e.error !== '' || e.ms > 2000)
-        if (slow.length) return `pings of room2 failed or took over 2 s during the flood: ${JSON.stringify(slow)}`
-        return (await cpp.events()).some(e => e.kind === 'peer-leave') ? 'the C++ peer saw the page leave a room' : null
-    })
+// ---- the C++ peer's own robustness on the relays ------------------------------------------------------------------
+// The C++ peer's relays begin with a URL no WebSocket can be made to: that relay reports a close, as an unreachable
+// one does, which the C++ peer's log says, and the room goes on over the next one.
+const refusedRelay = 'ftp://relay.invalid'
+const refusedRelayScenario = cppKind => scenario('a_refused_relay_url', cppKind, async open => {
+    const cpp = await open('cpp', {relays: `${refusedRelay},${relayParams.relays}`})
+    const failed = await exchange(cpp, await open('js'))
+    if (failed) return failed
+    return (await cpp.log()).includes(`could not reach ${refusedRelay}`) ? null : 'the C++ peer did not report the refused relay'
+})
 
-// 9. A transient handshake failure with Trystero JS, in both id orders (ruling 9): room2 with a password; the page
-// holds its first @_hsdata of room2 for 12 s (hold-hsdata) and waits 30 s for a handshake, so that the C++ peer, with
-// its 10 s, times out first. With the page the higher id its held answer is accepted; with the page the lower id its
-// held challenge is dropped in the C++ peer's window. Both are joined within 15 s of the C++ peer's kick, or, when the
-// page bound by reuse inside that window (the first residual case of S:4.2), within 50 s, the page having reported
-// one handshake timeout. No password error on either side, and room keeps exchanging.
-const transientHandshakeScenario = (name, cppKind) =>
-    scenario(name, async open => {
-        for (const cppSelf of ['00000000000000000000', 'zzzzzzzzzzzzzzzzzzzz']) {
-            const pageLower = !cppSelf.startsWith('0')
-            const params = {room: room(), room2: room(), password: 'p', ...relayParams}
-            const cpp = await open(cppKind, {...params, self: cppSelf})
-            const js = await open('js', {...params, deferRoom2: 1, 'hold-hsdata': '1', handshake: 30000})
-            // Join room2 explicitly only after both directions of room1's exchange have completed.
-            if (!(await until(async () => exchangeComplete(inRoom(await cpp.events(), 'first'), false) &&
-                exchangeComplete(inRoom(await js.events(), 'first'), true), 30_000))) {
-                return `${cppSelf}: room did not complete before joining room2`
-            }
-            const before = await connectionCounts(cpp, cppKind, js)
-            await js.value('window.join2()')
-            if (!(await until(async () => (await js.events()).some(e => e.kind === 'held' && e.presenceBefore), 10_000))) {
-                return `${cppSelf}: room2 presence did not precede its first held handshake frame`
-            }
-            const cppTimeouts = async () => inRoom(await cpp.events(), 'second')
-                .filter(e => e.kind === 'error' && e.error === 'the handshake timed out').length
-            if (!(await until(async () => (await cppTimeouts()) >= 1, 30_000))) return `${cppSelf}: the C++ peer did not time out in room2`
-            const met = async () => inRoom(await cpp.events(), 'second').some(e => e.kind === 'peer-join') &&
-                inRoom(await js.events(), 'second').some(e => e.kind === 'peer-join')
-            let ok = await until(met, 15_000)
-            const pageTimeouts = async () => inRoom(await js.events(), 'second')
-                .filter(e => e.kind === 'error' && String(e.error).includes('timed out')).length
-            if (!ok && pageLower) ok = (await until(met, 35_000)) && (await pageTimeouts()) === 1
-            if (!ok) return `${cppSelf}: room2 did not join in time; the page reported ${await pageTimeouts()} timeouts`
-            if ((await cppTimeouts()) !== 1) return `${cppSelf}: the C++ peer timed out ${await cppTimeouts()} times`
-            const passwordErrors = [...inRoom(await cpp.events(), 'second'), ...inRoom(await js.events(), 'second')]
-                .filter(e => e.kind === 'error' && String(e.error).includes('password'))
-            if (passwordErrors.length) return `${cppSelf}: password errors ${JSON.stringify(passwordErrors)}`
-            const text = `still here ${cppSelf}`
-            await js.value(`window.chat1(${JSON.stringify(text)})`)
-            const echoed = async () => inRoom(await js.events(), 'first').some(e => e.kind === 'chat' && e.text === `echo: ${text}`)
-            if (!(await until(echoed, 10_000))) return `${cppSelf}: room stopped exchanging`
-            const after = await connectionCounts(cpp, cppKind, js)
-            if (after.cppMade !== before.cppMade || after.jsMade !== before.jsMade || after.jsConnected !== 1) {
-                return `${cppSelf}: the shared connection changed: before ${JSON.stringify(before)}, after ${JSON.stringify(after)}`
-            }
-        }
-        return null
-    })
+// The C++ peer is given a TURN server without credentials, which WebRTC refuses: the app drops it when it is made and
+// reports it to app::on_error, and the exchange completes over the host candidates.
+const unusableIceScenario = cppKind => scenario('an_unusable_ice_server', cppKind, async open => {
+    const cpp = await open('cpp', {ice: 'turn:127.0.0.1:9'})
+    const failed = await exchange(cpp, await open('js'))
+    if (failed) return failed
+    return has(await cpp.events(), 'error', e => e.code === 'the configuration is unusable')
+        ? null : 'the C++ peer did not report the unusable ICE server'
+})
 
-// Every scenario the options ask for, in turn.
-const scenarios = async () => {
-    if (browserPeer) {
-        await pairScenario('C++ offers (lower id), Trystero JS answers; C++ leaves', {cppSelf: '00000000000000000000', leaver: 'cpp'})
-        await pairScenario('Trystero JS offers, C++ answers (higher id), with a password; JS leaves', {cppSelf: 'zzzzzzzzzzzzzzzzzzzz', password: 'secret', leaver: 'js'})
-        if (!usePublic) {
-            await malformedCandidateScenario('A malformed ICE candidate from a peer does not stop C++', 'cpp')
-            await refusedRelayScenario('A relay URL the browser refuses reports a close; C++ goes on', 'cpp')
-            await textMessagesScenario('Text messages on the data channel do not reach or stop C++', 'cpp')
-            await unusableIceScenario('An ICE server WebRTC refuses is reported and dropped; C++ goes on', 'cpp')
-            await forgedAnswerScenario('A forged answer from a watcher without the key changes nothing; C++ joins', 'cpp')
-            await replayScenario('A resent answer from a watcher without the key is refused; C++ joins again', 'cpp', 'answer')
-            await replayScenario('A resent offer from a watcher without the key is refused; C++ joins again', 'cpp', 'offer')
-            await reflectScenario('Its own offer sent back as an answer is refused; C++ joins', 'cpp', 'answer')
-            await reflectScenario('Its own offer sent back as an offer is refused; C++ joins', 'cpp', 'offer')
-            await floodScenario('A flood of announcements from fresh ids is bounded; C++ goes on', 'cpp')
-            await oversizedRelayTextScenario('A relay text longer than 1 MiB is not read; C++ reconnects', 'cpp')
-            await oversizedRelayTextScenario('A recovered browser peer survives oversized relay messages', 'cpp', true)
-            await oversizedRelayTextScenario('Browser relay setup waits for both peers after a one-way handshake delay', 'cpp', true, true)
-            await twoRoomsOneConnectionScenario('C++ and Trystero JS share one connection between two rooms', 'cpp')
-            await threeRoomsScenario('Three rooms share one connection, the third joined later by presence', 'cpp')
-            await pageFirstScenario('A room the page joined first binds over the connection within 5 s', 'cpp')
-            await oneRoomLeavingScenario('One room leaving, either side, leaves the other room and the connection', 'cpp')
-            await leavingEveryRoomScenario('A peer leaving every room closes the connection after the idle time', 'cpp')
-            await openToOtherRoomsScenario('A public app exposes its rooms while a separate protected app stays isolated in both id orders', 'cpp')
-            await wrongPasswordScenario('A wrong password in one room, in both id orders, paced by the rebinding times', 'cpp')
-            await roomFloodScenario('A flood in one room does not delay the pings of another', 'cpp')
-            await transientHandshakeScenario('A transient handshake failure converges, in both id orders', 'cpp')
-        }
+// After the exchange, the relay sends every client a text longer than a relay's longest (1 MiB): the C++ peer closes
+// that relay's connection rather than read it, says so, reconnects, and goes on with the peer it joined. Then the relay
+// sends the text after every subscription: each reconnection is closed at once, and the C++ peer tries again within a
+// bound that doubles every time, rather than every few seconds forever.
+const oversizedRelayTextScenario = cppKind => scenario('a_relay_text_longer_than_1_mib', cppKind, async open => {
+    const cpp = await open('cpp')
+    const js = await open('js')
+    const failed = await exchange(cpp, js)
+    if (failed) return failed
+    const cppStart = (await cpp.events()).length
+    const jsStart = (await js.events()).length
+    left.relay.broadcast(JSON.stringify(['NOTICE', 'x'.repeat(1024 * 1024 + 1)]))
+    if (!(await until(async () => (await cpp.log()).includes(`lost ${left.relay.url}`)))) {
+        return 'the C++ peer did not close the relay that sent the long text'
+    }
+    if (!(await until(async () => (await cpp.log()).includes(`reconnected to ${left.relay.url}`)))) {
+        return 'the C++ peer did not reconnect to the relay'
+    }
+    const bounds = async () =>
+        [...(await cpp.log()).matchAll(new RegExp(`lost ${left.relay.url}, next attempt within (\\d+) ms`, 'g'))].map(m => Number(m[1]))
+    // The text closes the connection open now, and then each new one after its subscription.
+    left.relay.options.afterSubscribe = JSON.stringify(['NOTICE', 'x'.repeat(1024 * 1024 + 1)])
+    left.relay.broadcast(left.relay.options.afterSubscribe)
+    const lostAgain = await until(async () => (await bounds()).length >= 3)
+    left.relay.options.afterSubscribe = null
+    const seen = await bounds()
+    console.log(`  the C++ peer lost the relay ${seen.length} times, each time to try again within ${seen.join(', ')} ms`)
+    if (!lostAgain) return 'the C++ peer was not closed three times'
+    if (!seen.every((b, i) => i === 0 || b > seen[i - 1])) return `the bounds did not grow: ${seen.join(', ')}`
+    const c = await idsOf(cpp)
+    const text = `still connected after relay faults`
+    await js.value(`window.chat(${JSON.stringify(text)}, ${JSON.stringify(c.self)})`)
+    const echoed = async () => (await js.events()).slice(jsStart).some(e => e.kind === 'chat' && e.text === `echo: ${text}`)
+    if (!(await until(echoed))) return 'the established data channel stopped exchanging after the relay faults'
+    if ([...(await cpp.events()).slice(cppStart), ...(await js.events()).slice(jsStart)].some(e => e.kind === 'peer-leave')) {
+        return 'a peer left after the relay fault'
     }
+    return null
+})
 
-    if (nativePeer) {
-        await pairScenario('Native C++ offers (lower id), Trystero JS answers; native leaves', {cppKind: 'native', cppSelf: '00000000000000000000', leaver: 'cpp'})
-        await pairScenario('Trystero JS offers, native C++ answers (higher id), with a password; JS leaves', {cppKind: 'native', cppSelf: 'zzzzzzzzzzzzzzzzzzzz', password: 'secret', leaver: 'js'})
-        if (!usePublic) {
-            await scenario('Native C++ preserves both rooms when presence precedes native open delivery', async open => {
-                const params = {room: room(), room2: room(), ...relayParams}
-                const cpp = await open('native', {...params, self: '00000000000000000000', delayOpen: 1})
-                const js = await open('js', {...params, holdActionsUntilPresence: 1})
-                if (!(await until(() => twoRoomsComplete(cpp, js), 60_000))) {
-                    return 'the two rooms did not complete in 60 s after delayed native open delivery'
-                }
-                if (!(await cpp.events()).some(e => e.kind === 'delayed-open')) return 'no native open was delayed'
-                if (!(await js.events()).some(e => e.kind === 'actions-released-after-presence')) {
-                    return 'no JS actions waited for native presence'
-                }
-                const counts = await connectionCounts(cpp, 'native', js)
-                return overBound(counts) || counts.jsConnected !== 1
-                    ? `connections ${JSON.stringify(counts)}` : null
-            })
-            await malformedCandidateScenario('A malformed ICE candidate from a peer does not stop native C++', 'native')
-            await refusedRelayScenario('A relay URL of another scheme reports a close; native C++ goes on', 'native')
-            await textMessagesScenario('Text messages on the data channel do not reach or stop native C++', 'native')
-            await unusableIceScenario('An ICE server WebRTC refuses is reported and dropped; native C++ goes on', 'native')
-            await forgedAnswerScenario('A forged answer from a watcher without the key changes nothing; native C++ joins', 'native')
-            await replayScenario('A resent answer from a watcher without the key is refused; native C++ joins again', 'native',
-                'answer')
-            await replayScenario('A resent offer from a watcher without the key is refused; native C++ joins again', 'native',
-                'offer')
-            await reflectScenario('Its own offer sent back as an answer is refused; native C++ joins', 'native', 'answer')
-            await reflectScenario('Its own offer sent back as an offer is refused; native C++ joins', 'native', 'offer')
-            await floodScenario('A flood of announcements from fresh ids is bounded; native C++ goes on', 'native')
-            await oversizedRelayTextScenario('A relay text longer than 1 MiB is not read; native C++ reconnects', 'native')
-            await oversizedRelayTextScenario('A recovered native peer survives oversized relay messages', 'native', true)
-            await oversizedRelayTextScenario('Native relay setup waits for both peers after a one-way handshake delay', 'native', true, true)
-            await twoRoomsOneConnectionScenario('Native C++ and Trystero JS share one connection between two rooms', 'native')
-            await threeRoomsScenario('Native C++: three rooms share one connection, the third joined later by presence', 'native')
-            await pageFirstScenario('Native C++: a room the page joined first binds over the connection within 5 s', 'native')
-            await oneRoomLeavingScenario('Native C++: one room leaving, either side, leaves the other room and the connection', 'native')
-            await leavingEveryRoomScenario('Native C++: a peer leaving every room closes the connection after the idle time', 'native')
-            await openToOtherRoomsScenario('Native C++: a public app exposes its rooms while a separate protected app stays isolated in both id orders', 'native')
-            await wrongPasswordScenario('Native C++: a wrong password in one room, in both id orders, paced by the rebinding times', 'native')
-            await roomFloodScenario('Native C++: a flood in one room does not delay the pings of another', 'native')
-            await transientHandshakeScenario('Native C++: a transient handshake failure converges, in both id orders', 'native')
-            await strikeScenario('A relay that ends the connection during a write: native C++ survives and reconnects', 'native')
-            await scenario('A room moved over a joined native C++ one leaves it, as destroying it does', async open => {
-                const params = {room: room(), ...relayParams}
-                const native = await open('native', params)
-                const js = await open('js', params)
-                const ok = await until(async () => exchangeComplete(await native.events(), false) && exchangeComplete(await js.events(), true), 30_000)
-                if (!ok) return 'the exchange did not complete in 30 s'
-                await native.replace()
-                const left = await until(async () => (await js.events()).some(e => e.kind === 'peer-leave') &&
-                    (await native.events()).some(e => e.kind === 'pending' && e.error === 'room left'), 10_000)
-                return left ? null : 'the replaced room did not say goodbye, or its pending receive did not complete with room left'
-            })
-            // The driver's own check: a native peer that dies by a signal, as a crash does, is named at once, and its
-            // scenario does not wait for anything it would have done. The signal is expected here, so this scenario
-            // takes it off the peer's problems once it is named.
-            await scenario('A native C++ peer killed by a signal is named at once', async open => {
-                const native = await open('native', {room: room(), ...relayParams})
-                if (!(await until(async () => (await native.events()).some(e => e.kind === 'joined'), 10_000))) {
-                    return 'the native peer did not start'
-                }
-                const started = Date.now()
-                await native.abort()
-                const named = await until(async () => native.problems.includes(`${native.label}: killed by SIGABRT`), 10_000)
-                if (!named) return 'the driver did not name the signal that killed the native peer'
-                const seconds = (Date.now() - started) / 1000
-                native.problems.length = 0
-                return seconds < 5 ? null : `the driver named the signal only after ${seconds} s`
-            })
-            await scenario('A wrong password keeps native C++ and Trystero JS apart', async open => {
-                const params = {room: room(), ...relayParams}
-                const native = await open('native', {...params, password: 'secret'})
-                const js = await open('js', {...params, password: 'another'})
-                await new Promise(r => setTimeout(r, 8000))
-                const all = [...(await native.events()), ...(await js.events())]
-                if (all.some(e => e.kind === 'peer-join')) return 'peers with different passwords joined'
-                return all.some(e => e.kind === 'error') ? null : 'neither peer reported the wrong password'
-            })
-            await scenario('Two Trystero JS peers and a native C++ peer form a mesh', async open => {
-                const params = {room: room(), ...relayParams}
-                const peers = [await open('js', params), await open('native', params), await open('js', params)]
-                const ok = await until(async () => {
-                    for (const p of peers) {
-                        if (!meshFormed(await p.events())) return false
-                    }
-                    return true
-                }, 30_000)
-                return ok ? null : 'not every peer joined both others and received both files in 30 s'
-            })
-        }
+// A relay that sends a client a text longer than 1 MiB, or resets its connection, just as the client writes: a C++ peer
+// announces 233 ms after it subscribes, and the relay strikes just before. A text that arrives 1 to 2 ms before the
+// write fails the read while Beast holds the write back, so the write completes after the connection ended; measured
+// against the code before the fix, a strike at 232 ms crashed 7 peers in 8, at 231 ms 5 in 8, at 228 or 234 ms none. A
+// reset fails the read and the write at once. One peer at a time, each in a room of its own, which the relay strikes by
+// its topic: each loses the relay once, survives, and reconnects.
+const strikes = [232, 231, 232, 233, 232, 231, 232, 233, 232, 232, 232, 232].map((delay, i) => ({
+    delay,
+    action: i < 8 ? 'too-long' : 'reset',
+}))
+const strikeScenario = cppKind => scenario('a_relay_that_ends_the_connection_during_a_write', cppKind, async open => {
+    const peers = []
+    for (const {delay, action} of strikes) {
+        const room = freshRoom()
+        left.relay.options.strike = {action, delay, topic: rootTopicOf(room)}
+        const peer = await open('cpp', {room})
+        peers.push(peer)
+        const lost = await until(async () => (await peer.log()).includes(`lost ${left.relay.url}`))
+        left.relay.options.strike = null
+        if (deaths !== deathsBefore) return `a C++ peer died after the relay struck it (${action} at ${delay} ms)`
+        if (!lost) return `${peer.label} did not lose the relay that struck it (${action} at ${delay} ms)`
     }
+    const back = async () => (await Promise.all(peers.map(p => p.log()))).every(log => log.includes(`reconnected to ${left.relay.url}`))
+    return (await until(back)) ? null : 'not every C++ peer reconnected to the relay'
+})
 
-    if (!usePublic && browserPeer) {
-        await scenario('A wrong password keeps the peers apart', async open => {
-            const params = {room: room(), ...relayParams}
-            const cpp = await open('cpp', {...params, password: 'secret'})
-            const js = await open('js', {...params, password: 'another'})
-            await new Promise(r => setTimeout(r, 8000))
-            const joined = [...(await cpp.events()), ...(await js.events())].filter(e => e.kind === 'peer-join')
-            const errors = [...(await cpp.events()), ...(await js.events())].filter(e => e.kind === 'error')
-            if (joined.length) return 'peers with different passwords joined'
-            if (!errors.length) return 'neither peer reported the wrong password'
-            return null
-        })
+// The driver's own check: a native peer that dies by a signal, as a crash does, is named at once, and its scenario does
+// not wait for anything it would have done. The signal is expected here, so this scenario takes it off the peer's
+// problems once it is named.
+const killedScenario = cppKind => scenario('a_native_peer_killed_by_a_signal_is_named', cppKind, async open => {
+    const native = await open('cpp')
+    await idsOf(native)
+    await native.abort()
+    const named = await until(async () => native.problems.includes(`${native.label}: killed by SIGABRT`))
+    native.problems.length = 0
+    return named ? null : 'the driver did not name the signal that killed the native peer'
+})
 
-        await scenario('Two Trystero JS peers and a C++ peer form a mesh', async open => {
-            const params = {room: room(), ...relayParams}
-            const peers = [await open('js', params), await open('cpp', params), await open('js', params)]
-            const ok = await until(async () => {
-                for (const p of peers) {
-                    if (!meshFormed(await p.events())) return false
-                }
-                return true
-            }, 30_000)
-            return ok ? null : 'not every peer joined both others and received both files in 30 s'
-        })
+// Every scenario the options ask for, in turn: each of the twelve of 0.27.0's interop against the lane's C++ peer (the
+// twelfth sees the relay's side, so it needs the local relay), then, on the local relay, adversarial peers and the C++
+// peer's own relay robustness.
+const scenarios = async () => {
+    for (const cppKind of [...(browserPeer ? ['cpp'] : []), ...(nativePeer ? ['native'] : [])]) {
+        await idsAndMessages(cppKind)
+        await signatures(cppKind)
+        await wideTransfers(cppKind)
+        await passwords(cppKind)
+        await importedIdentities(cppKind)
+        await oneUserTwoCppPeers(cppKind)
+        await maxUsers(cppKind)
+        await requestsAndPings(cppKind)
+        await leaves(cppKind)
+        await forgedUserSignature(cppKind)
+        await mesh(cppKind)
+        if (!usePublic) {
+            await relayConnectivity(cppKind)
+            await malformedCandidateScenario(cppKind)
+            await floodScenario(cppKind)
+            await refusedRelayScenario(cppKind)
+            await unusableIceScenario(cppKind)
+            await oversizedRelayTextScenario(cppKind)
+            if (cppKind === 'native') {
+                await strikeScenario(cppKind)
+                await killedScenario(cppKind)
+            }
+        }
     }
 }
 
diff --git a/test/oracle/oracle.mjs b/test/oracle/oracle.mjs
index 44f3d53..2421863 100644
--- a/test/oracle/oracle.mjs
+++ b/test/oracle/oracle.mjs
@@ -4,12 +4,17 @@
 // accompanying file LICENSE_1_0.txt or copy at
 // https://www.boost.org/LICENSE_1_0.txt)
 
-// Writes /expected.json: values computed by Trystero JS 0.26 itself, from the inputs of
-// /protocol.json, which the C++ protocol tests must reproduce byte for byte. b2 runs it:
-// `b2 libs/trystero/test/oracle//oracle` compares what it writes with test/fixtures/expected, and
-// `b2 libs/trystero/test/oracle//update-expected` writes that directory again.
+// Writes /expected.json: values computed by Trystero JS 0.27.0 itself, the
+// published @trystero-p2p/core and @trystero-p2p/nostr this directory's package-lock.json pins,
+// from the inputs of /protocol.json, which the C++ protocol and signaling tests must
+// reproduce byte for byte. b2 runs it: `b2 libs/trystero/test/oracle//cases-protocol` compares
+// what it writes with test/fixtures/oracle, and `b2 libs/trystero/test/oracle//update-expected`
+// writes that directory again.
 //
 //   node oracle.mjs  
+//
+// The oracle waits on nothing but what it runs: every value it records is the end of a chain of
+// promises or callbacks of Trystero's own, never a wall-clock delay.
 import {mkdirSync, readFileSync, writeFileSync} from 'node:fs'
 import {dirname, join} from 'node:path'
 import {fileURLToPath} from 'node:url'
@@ -22,281 +27,221 @@ if (process.argv.length !== 4) {
 const [casesDirectory, outputDirectory] = process.argv.slice(2)
 const cases = JSON.parse(readFileSync(join(casesDirectory, 'protocol.json'), 'utf8'))
 
-// Trystero draws its peer id, selfId, from Math.random once, when utils.mjs is loaded: from the
-// answerer fixture's draws while the modules load, so that the signals carrying it are the same
-// every run. Draw i is ((i * multiplier + offset) % 62 + 0.5) / 62, which picks character
-// (i * multiplier + offset) % 62 of Trystero's alphabet.
-const random = Math.random
-{
-    const {multiplier, offset} = cases.answerer.self_id_random
-    let draw = 0
-    Math.random = () => ((((draw++ * multiplier) + offset) % 62) + 0.5) / 62
-}
-const core = join(dirname(fileURLToPath(import.meta.url)), 'node_modules/@trystero-p2p/core/dist')
-const {sha1, hashWith, deriveRoomNamespace, encrypt, decrypt, genKey} = await import(join(core, 'crypto.mjs'))
-const {strToNum, getRelays, toHex, toJson, topicPath, shuffle, selfId} = await import(join(core, 'utils.mjs'))
-const {createActionWireManager} = await import(join(core, 'action-wire.mjs'))
-const {SharedPeerManager} = await import(join(core, 'shared-peer.mjs'))
-const {createSignalHandler} = await import(join(core, 'signal-handler.mjs'))
-Math.random = random
+// The modules of the published packages, by their files: the signal handler and the topics are
+// not exported from the packages' entry points.
+const modules = join(dirname(fileURLToPath(import.meta.url)), 'node_modules/@trystero-p2p')
+const {hashTopic, genKey, encrypt, decrypt} = await import(join(modules, 'core/dist/crypto.mjs'))
+const {topicPath, toJson, libName, candidateType} = await import(join(modules, 'core/dist/utils.mjs'))
+const {createSignalHandler, buildSignalAad, createPeerState} =
+    await import(join(modules, 'core/dist/signal-handler.mjs'))
+const {createEvent, topicToKind} = await import(join(modules, 'nostr/dist/protocol.mjs'))
+const {joinRoom} = await import('@trystero-p2p/nostr')
 
 // The bytes getRandomValues gives while a fixture draws them, the same every run: byte i of a draw
-// is (i * multiplier + offset) % 256. Trystero draws an IV with it when it seals, and noble's
+// is (i * multiplier + offset) % 256. Trystero draws a GCM IV with it when it seals, and noble's
 // secp256k1 a key and a signature's auxiliary bytes.
 const patterned = ({multiplier, offset}) => array => array.map((_, i) => (i * multiplier + offset) % 256)
 const getRandomValues = crypto.getRandomValues.bind(crypto)
 
-// Trystero's Nostr strategy draws its key once, when it is loaded: from the bytes of the event
-// messages' fixture, so that its events are the same every run and the C++ signer can sign them.
-crypto.getRandomValues = patterned(cases.event_messages.random)
-const {defaultRelayUrls, createEvent, joinRoom} = await import('@trystero-p2p/nostr')
-crypto.getRandomValues = getRandomValues
-
 const hex = bytes => Buffer.from(bytes).toString('hex')
 const out = {}
 
-// Topics: Trystero's sha1 text (each digest byte in base 36) of the root and self topic paths.
-out.topics = []
-for (const [appId, roomId, peerId] of cases.topics) {
-    const root = topicPath('Trystero', appId, roomId)
-    out.topics.push({
-        app_id: appId,
-        room_id: roomId,
-        peer_id: peerId,
-        root_topic: await sha1(root),
-        self_topic: await sha1(topicPath(root, peerId)),
-        room_token: await deriveRoomNamespace(appId, roomId),
-    })
-}
-
-// strToNum sums UTF-16 code units, so non-ASCII text must be summed the same way.
-out.str_to_num = cases.str_to_num.map(text => ({
-    text,
-    unbounded: strToNum(text),
-    mod_10000: strToNum(text, 10_000),
-}))
-
-// Relay selection: the default list shuffled with a seed derived from the app id, first five kept.
-out.default_relays = defaultRelayUrls
-out.relays = cases.relays.map(
-    appId => ({app_id: appId, relays: getRelays({appId}, defaultRelayUrls, cases.relay_redundancy, true)}))
-out.shuffle = cases.shuffle.seeds.map(seed => ({seed, order: shuffle([...Array(cases.shuffle.length).keys()], seed)}))
-
-// The password handshake: sha256 hex of "challenge:password:appId:roomId".
-out.handshake = cases.handshake.map(([challenge, password, appId, roomId]) => ({
-    challenge, password, app_id: appId, room_id: roomId,
-}))
-for (const entry of out.handshake) {
-    entry.hash = toHex(await hashWith('SHA-256', `${entry.challenge}:${entry.password}:${entry.app_id}:${entry.room_id}`))
-}
-
-// Sealed signals: "iv,iv,...$base64(ciphertext)" with a 16-byte IV; the tag makes the ciphertext 16 bytes longer.
-const sealed = cases.sealed
-const key = genKey(sealed.password, sealed.app_id, sealed.room_id)
-const plaintext = sealed.plaintext
-// A fixed IV keeps the fixture deterministic; Trystero draws it from getRandomValues.
-crypto.getRandomValues = patterned(sealed.random)
-const sealedText = await encrypt(key, plaintext)
-crypto.getRandomValues = getRandomValues
-out.sealed = {
-    plaintext,
-    text: sealedText,
-    key_material: toHex(await hashWith('SHA-256', `${sealed.password}:${sealed.app_id}:${sealed.room_id}`)),
-}
-
-// Nostr event ids: sha256 of JSON.stringify([0, pubkey, created_at, kind, tags, content]).
-const pubkey = cases.nostr_events.pubkey
-out.nostr_events = []
-for (const content of cases.nostr_events.contents) {
-    const topic = out.topics[0].root_topic
-    const kind = strToNum(topic, 10_000) + 20_000
-    const createdAt = cases.nostr_events.created_at
-    out.nostr_events.push({pubkey, created_at: createdAt, kind, topic, content,
-        id: toHex(await hashWith('SHA-256', toJson([0, pubkey, createdAt, kind, [['x', topic]], content])))})
-}
-
-// Action frames, captured from Trystero's own action wire manager sending to a fake peer.
-const actions = cases.actions
-const chunked = actions.chunked
-const captureActions = async () => {
-    const frames = []
-    let accept = () => {}
-    const peer = {channel: null, sendData: bytes => frames.push(hex(bytes))}
-    const wire = createActionWireManager({
-        getPeer: () => peer,
-        getPeerIds: () => ['peer'],
-        canReceiveFromPeer: () => true,
-        onPeerError: (_, error) => { throw error },
-    })
-    const send = async (type, data, metadata) => {
-        frames.length = 0
-        await wire.makeInternalAction(type).send(data, 'peer', metadata)
-        return [...frames]
-    }
-    const result = {
-        text: await send(...actions.text),
-        json: await send(...actions.json),
-        binary: await send(actions.binary[0], new Uint8Array(actions.binary[1])),
-        text_with_metadata: await send(...actions.text_with_metadata),
-        empty_text: await send(...actions.empty_text),
-        thirty_two_byte_name: await send(...actions.thirty_two_byte_name),
-    }
-    // A payload above the inline limit becomes an offer, then chunks once the receiver accepts.
-    frames.length = 0
-    const big = new Uint8Array(chunked.length).map((_, i) => (i * chunked.multiplier) % 256)
-    const sending = wire.makeInternalAction(chunked.type).send(big, 'peer', chunked.metadata)
-    await new Promise(resolve => setTimeout(resolve, 10))
-    const offer = Buffer.from(frames[0], 'hex')
-    const id = offer.readUInt32BE(36)
-    wire.handleData('peer', new Uint8Array([2, 3, ...[id >>> 24, (id >>> 16) & 255, (id >>> 8) & 255, id & 255]]).buffer)
-    await sending
-    result.chunked = {payload: hex(big), frames: [...frames]}
-    return result
-}
-out.actions = await captureActions()
-
-// The control frames a receiver answers with: accepted, rejected with a reason, cancelled.
-{
-    const frames = []
-    const peer = {channel: null, sendData: bytes => frames.push(hex(bytes))}
-    const receiver = createActionWireManager({
-        getPeer: () => peer,
-        getPeerIds: () => ['peer'],
-        canReceiveFromPeer: () => true,
-        onPeerError: () => {},
-        maxReceiveBytes: cases.controls.max_receive_bytes,
-    })
-    receiver.makeInternalAction(chunked.type).onMessage(() => {})
-    const offer = Buffer.from(out.actions.chunked.frames[0], 'hex')
-    receiver.handleData('peer', new Uint8Array(offer).buffer)  // the chunked payload: above maxReceiveBytes, so rejected
-    out.controls = {rejected_too_large: frames[0]}
-}
+// A room's root topic, as 0.27.0's strategy names it: hashTopic of topicPath(libName, app, room).
+const rootTopicText = (appId, roomId) => topicPath(libName, appId, roomId)
+const rootTopic = (appId, roomId) => hashTopic(rootTopicText(appId, roomId))
 
-// Room envelope and presence frames, captured from Trystero's shared peer manager over a fake physical peer.
-{
-    const envelope = cases.envelope
-    const frames = []
-    const physical = {
-        isDead: false,
-        connection: {connectionState: 'connected', iceConnectionState: 'connected', getSenders: () => []},
-        channel: {readyState: 'open'},
-        sendData: bytes => frames.push(hex(bytes)),
-        setHandlers: () => {},
-        destroy: () => {},
-    }
-    const manager = new SharedPeerManager()
-    const token = await deriveRoomNamespace(envelope.app_id, envelope.room_id)
-    const membership = manager.registerRoom(envelope.app_id, envelope.room_id, Promise.resolve(token), {
-        active: true,
-        onPeer: proxy => proxy.sendData(new Uint8Array(envelope.frame)),
-        onDetach: () => {},
-    })
-    await new Promise(resolve => setTimeout(resolve, 0))
-    membership.connect('remote-peer', physical, envelope.timeout)
-    await new Promise(resolve => setTimeout(resolve, 0))
-    membership.leave()
-    out.envelope = {room_token: token, frames: [...frames]}
-}
-
-// Event messages, written by Trystero's own createEvent, `["EVENT",{kind,tags,created_at,content,
+// Event messages, written by 0.27.0's own createEvent, `["EVENT",{kind,tags,created_at,content,
 // pubkey,id,sig}]`, whose topics and contents hold the characters JSON.stringify escapes and those
 // it writes as they are: the controls U+0000 to U+001F, `"`, `\`, U+2028, U+2029, DEL and astral
-// ones. The key is the one the strategy drew when it was loaded, and the clock and the signature's
-// auxiliary bytes are the fixture's; noble's keygen makes the key again from the same 48 bytes, so
-// that the C++ signer signs with it.
-{
-    const messages = cases.event_messages
-    const draw = patterned(messages.random)
-    const {secretKey} = schnorr.keygen(draw(new Uint8Array(48)))
+// ones. noble's keygen makes the key from the fixture's 48 bytes, so that the C++ signer signs
+// with it, and the clock and the signature's auxiliary bytes are the fixture's.
+const messages = cases.event_messages
+const draw = patterned(messages.random)
+const {secretKey} = schnorr.keygen(draw(new Uint8Array(48)))
+const pinned = async (seconds, f) => {
     const now = Date.now
-    Date.now = () => messages.created_at * 1000
+    Date.now = () => seconds * 1000
     crypto.getRandomValues = draw
-    out.event_messages = {
-        secret_key: hex(secretKey),
-        aux: hex(draw(new Uint8Array(32))),
-        created_at: messages.created_at,
-        events: [],
+    try {
+        return await f()
+    } finally {
+        crypto.getRandomValues = getRandomValues
+        Date.now = now
     }
+}
+out.event_messages = {
+    secret_key: hex(secretKey),
+    aux: hex(draw(new Uint8Array(32))),
+    created_at: messages.created_at,
+    events: [],
+}
+await pinned(messages.created_at, async () => {
+    const signer = {secretKey, pubkey: hex(schnorr.getPublicKey(secretKey))}
     for (const [topic, content] of messages.events) {
-        const message = await createEvent(topic, content)
+        const message = await createEvent(topic, content, signer)
         out.event_messages.events.push({topic, content, id: JSON.parse(message)[1].id, message})
     }
-    crypto.getRandomValues = getRandomValues
-    Date.now = now
+})
+
+// Nostr event ids, sha256 of JSON.stringify([0, pubkey, created_at, kind, tags, content]), as
+// 0.27.0's createEvent computes them for an event of the fixture's room's root topic, under the
+// fixture's public key: createEvent takes the public key it writes from its signer, and the id
+// covers no secret.
+{
+    const events = cases.nostr_events
+    const topic = await rootTopic(events.app_id, events.room_id)
+    const signer = {secretKey, pubkey: events.pubkey}
+    out.nostr_events = []
+    await pinned(events.created_at, async () => {
+        for (const content of events.contents) {
+            const event = JSON.parse(await createEvent(topic, content, signer))[1]
+            out.nostr_events.push({pubkey: event.pubkey, created_at: event.created_at, kind: event.kind,
+                topic, content, id: event.id})
+        }
+    })
+    if (out.nostr_events.some(e => e.kind !== topicToKind(topic))) {
+        throw new Error('createEvent wrote a kind topicToKind does not give')
+    }
 }
 
-// Signals' texts, written as Trystero writes each, with toJson (JSON.stringify), their members in
-// the order Trystero gives them: an announcement {peerId, passive, nonce} (the topic strategy's
-// announce, then the Nostr strategy's nonce), an offer {peerId, offerId, offer} and the offerer's
-// candidate {peerId, offerId, candidate, passive} (handleAnnouncement), an answer to an offer
-// without an id {peerId, answer}, and the answerer's answer and candidate, whose offerId follows
-// them {peerId, answer, offerId} and {peerId, candidate, offerId, passive} (handleOffer's
-// publishAnswerSignal); their strings hold the event messages' characters.
+// Signals' texts, written as 0.27.0 writes each, with toJson (JSON.stringify), their members in
+// the order its signal handler gives them: an announcement {peerId} with the Nostr strategy's
+// nonce after it, an offer {peerId, offerId, offer}, and the offerer's and the answerer's answer
+// and candidate {peerId, offerId, answer} and {peerId, offerId, candidate}; their strings hold the
+// event messages' characters.
 out.signal_texts = cases.signal_texts.map(signal => ({signal, text: toJson(signal)}))
 
-// Signals whose objects hold a key twice, as Trystero's own signal handler reads them: it runs in a
-// room of the oracle's, which records the peer id it looks up (reusePeer), the sealed text it opens
-// (toPlain), by kind, and an offer's id, and opens nothing, so that the handler stops there. A
-// passive room ignores a passive sender before it looks the peer up, which a second run, in such a
-// room, shows. `read` is null when Trystero ignores the signal.
-const readSignal = async text => {
-    const run = async passive => {
+/**
+ * The context of a signal handler of the oracle's: a room of the app, the room and the self id that
+ * `room` names, whose key is that of a room without a password, sealing and opening with each
+ * signal's AAD as the strategy does (toPlain, toCipher), and which makes no offer and no peer.
+ * `hooks` replaces any member.
+ */
+const signalContext = async ({app_id: appId, room_id: roomId, self_id: selfId}, hooks) => {
+    const root = rootTopicText(appId, roomId)
+    const key = genKey('', appId, roomId)
+    const withKey = f => async (signal, peerId, offerId) => ({
+        type: signal.type,
+        sdp: await f(key, signal.sdp, buildSignalAad(signal.type, peerId, offerId)),
+    })
+    return {
+        appId,
+        getRoomId: () => roomId,
+        config: {},
+        peerStates: new Map(),
+        getRootTopicPlaintext: () => root,
+        rootTopicP: hashTopic(root),
+        selfTopicP: hashTopic(topicPath(root, selfId)),
+        toPlain: withKey(decrypt),
+        toCipher: withKey(encrypt),
+        isLeaving: () => false,
+        onError: () => {},
+        checkoutOffers: () => Promise.reject(new Error('the oracle makes no offer')),
+        claimLeasedOffer: () => false,
+        reclaimLeasedOffer: () => {},
+        encryptOffer: () => Promise.reject(new Error('the oracle makes no offer')),
+        initPeer: () => {
+            throw new Error('the oracle makes no peer here')
+        },
+        connectPeer: () => {},
+        disconnectPeer: () => {},
+        announceIntervals: [],
+        announceIntervalMs: 5333,
+        getSelfIdNow: () => selfId,
+        selfIdP: Promise.resolve(selfId),
+        ...hooks,
+    }
+}
+
+// Signals as 0.27.0's own signal handler reads them: each runs in a room of the oracle's, `room`'s
+// app, room and self id, on its root topic, which records the peer id it acts on
+// (onPeerDiscovered) and the sealed text it opens (toPlain), with its offer id, by kind, and opens
+// nothing, so that the handler stops there. The room connects to no peer it would dial
+// (shouldConnectPeer), so that an announcement goes no further; a candidate is opened only for a
+// peer the room answers, so a second run, whose room answers every peer, reads the candidates.
+// `read` is null when 0.27.0 ignores the signal.
+const readSignals = async (room, texts) => {
+    const readSignal = async (text, answering) => {
         const read = {}
-        const ctx = {
-            appId: 'app',
-            roomId: 'room',
-            config: {},
-            peerStates: {},
-            rootTopicPlaintext: topicPath('Trystero', 'app', 'room'),
-            rootTopicP: Promise.resolve('root'),
-            selfTopicP: Promise.resolve('self'),
-            isPassive: passive,
-            isActive: true,
-            // The room leaves once it looked the peer up, so that an announcement makes no offer.
-            isLeaving: () => read.peer_id !== undefined,
-            reusePeer: peerId => {
+        const ctx = await signalContext(room, {
+            onPeerDiscovered: peerId => {
                 read.peer_id = peerId
-                return false
             },
-            toPlain: async ({type, sdp}) => {
+            shouldConnectPeer: (_, direction) => direction === 'inbound',
+            toPlain: async ({type, sdp}, peerId, offerId) => {
                 read[type] = sdp
-                if (type === 'offer') read.offer_id = ctx.peerStates[read.peer_id].answerReplay.offerId
+                read.offer_id = offerId
                 throw new Error('the oracle opens nothing')
             },
-            initPeer: () => ({
-                isDead: false,
-                setHandlers: () => {},
-                signal: async () => {},
-                destroy: () => {},
-            }),
-            offerManager: {checkout: async () => Promise.reject(new Error('the oracle makes no offer'))},
-            connectPeer: () => {},
-            disconnectPeer: () => {},
-            checkDeactivate: () => {},
-            announceIntervals: [],
-            announceIntervalMs: 5333,
+        })
+        if (answering) {
+            // Every peer is one the room answers.
+            const state = createPeerState()
+            const peer = {isDead: false, setHandlers: () => {}, signal: async () => {}, destroy: () => {}}
+            state.inbound = {phase: 'answering', peer, offerId: '', expiryTimer: undefined,
+                didSendAnswer: false, replay: {offer: '', offerId: '', messages: [], lastSentAt: [], relays: []}}
+            ctx.peerStates = new (class extends Map {
+                get(peerId) {
+                    return super.get(peerId) ?? state
+                }
+            })()
         }
-        await createSignalHandler(ctx)(0)('root', text, () => {})
+        const {handleMessage} = createSignalHandler(ctx)
+        await handleMessage(0)(await ctx.rootTopicP, text, async () => {})
         return read
     }
-    const read = await run(false)
-    if (read.peer_id === undefined) return null
-    read.passive = (await run(true)).peer_id === undefined
-    return read
+    const signals = []
+    for (const text of texts) {
+        const read = await readSignal(text, false)
+        const second = await readSignal(text, true)
+        if (second.candidate !== undefined) {
+            read.candidate = second.candidate
+            read.offer_id = second.offer_id
+        }
+        signals.push({text, read: read.peer_id === undefined ? null : read})
+    }
+    return signals
+}
+
+// And each signal's text read back by 0.27.0's own signal handler, in the duplicate keys' room:
+// `read` is null where it refuses the signal, whose ids are no ids of 0.27.0's.
+for (const [i, {text}] of out.signal_texts.entries()) {
+    out.signal_texts[i].read = (await readSignals(cases.duplicate_keys, [text]))[0].read
+}
+
+// Signals whose objects hold a key twice.
+out.duplicate_keys = {
+    self_id: cases.duplicate_keys.self_id,
+    signals: await readSignals(cases.duplicate_keys, cases.duplicate_keys.signals),
 }
-out.duplicate_keys = {signals: []}
-for (const text of cases.duplicate_keys.signals) {
-    out.duplicate_keys.signals.push({text, read: await readSignal(text)})
+
+// Signals whose envelope 0.27.0's parseSignalEnvelope refuses, each of its rules broken once (a
+// peer id that is not 20 base62 characters, an offer id that is not 1 to 64 of [\w.~:!-], present
+// or required by an offer, answer or candidate, a candidate past 4,096 UTF-16 code units), and the
+// last text each bound admits, which it reads.
+out.signal_envelopes = {
+    self_id: cases.signal_envelopes.self_id,
+    signals: await readSignals(cases.signal_envelopes, cases.signal_envelopes.signals),
 }
 
-// Relay events whose objects hold a key twice, as Trystero's own Nostr strategy reads them. A room
+// Relay events whose objects hold a key twice, as 0.27.0's own Nostr strategy reads them. A room
 // of the cases' app joins through a WebSocket of the oracle's, which hands it each case's members
 // as an event of the room's subscription, keys as they are written and values as toJson writes
 // them, `{root}` being the room's root topic. Every content is an answer that does not open, so
-// that the room reports its sender (onJoinError) exactly when it acted on the event: when it read
-// the event's topic as the room's root topic and its content as the signal. After each case comes
-// an event of the oracle's own, whose report closes the case's. `acted` is the sender the room
-// reported, or null; in what is written the subscription's id, which Trystero draws, is `sub`.
+// that the room reports its sender (onError, decrypt-failed) exactly when it acted on the event:
+// when it read the event's topic as the room's root topic and its content as the signal. After
+// each case comes an event of the oracle's own, whose report closes the case's. `acted` is the
+// sender the room reported, or null; in what is written the subscription's id, which Trystero
+// draws, is `sub`. The same room then gets each answer of the signal envelopes' events as the
+// content of an event of its root topic, so that 0.27.0's whole room, not only its signal handler,
+// shows which envelopes it refuses.
+//
+// The order of the reports is what closes a case: the case's event and the closing one are
+// delivered back to back, and both are answers through the same path, the same awaits and the same
+// failing toPlain, so 0.27.0 reports them in the order they came; an envelope it refuses it reports
+// not at all. A case whose event took more awaits than the closing one would be reported after it,
+// recorded as not acted on and counted in the next case; the expected file, compared byte for byte,
+// would show it as a failure of the oracle lane, never as a pass.
 class OracleSocket {
     static opened = []
 
@@ -304,110 +249,116 @@ class OracleSocket {
         this.url = url
         this.readyState = 0
         this.sent = []
+        this.watchers = []
         OracleSocket.opened.push(this)
-        setTimeout(() => {
+        queueMicrotask(() => {
             this.readyState = 1
             this.onopen?.()
-        }, 0)
+        })
+    }
+
+    /** Resolves to the first text sent, or already sent, for which `wanted` holds. */
+    awaitSent(wanted) {
+        const found = this.sent.find(wanted)
+        return found !== undefined ? Promise.resolve(found)
+            : new Promise(resolve => this.watchers.push({wanted, resolve}))
     }
 
     send(text) {
         this.sent.push(text)
+        this.watchers = this.watchers.filter(({wanted, resolve}) => !(wanted(text) && (resolve(text), true)))
     }
 
     close() {
         this.readyState = 3
     }
 }
-const until = async (done, what) => {
-    for (let waited = 0; !done(); waited += 10) {
-        if (waited >= 10_000) throw new Error(`the oracle waited 10 s for ${what}`)
-        await new Promise(resolve => setTimeout(resolve, 10))
-    }
-}
 {
     const events = cases.duplicate_keys.events
-    const rootTopic = await sha1(topicPath('Trystero', events.app_id, events.room_id))
+    const root = await rootTopic(events.app_id, events.room_id)
     const eventText = (subscription, members) => {
         const fields = members.map(([key, value]) => `"${key}":${toJson(value)}`).join(',')
-        return `["EVENT",${toJson(subscription)},{${fields}}]`.replaceAll('{root}', rootTopic)
+        return `["EVENT",${toJson(subscription)},{${fields}}]`.replaceAll('{root}', root)
     }
-    const acted = []
     const WebSocket = globalThis.WebSocket
     globalThis.WebSocket = OracleSocket
     const room = joinRoom({appId: events.app_id, relayConfig: {urls: ['wss://relay.oracle.invalid']}},
-        events.room_id, {onJoinError: ({peerId}) => acted.push(peerId)})
+        events.room_id)
+    // The reports of decrypt-failed, by sender, each resolving whoever waits for it.
+    const acted = []
+    const waiting = new Map()
+    room.onError(error => {
+        if (error.code !== 'decrypt-failed') {
+            return
+        }
+        acted.push(error.peerId)
+        waiting.get(error.peerId)?.()
+    })
+    const reported = peerId => new Promise(resolve => waiting.set(peerId, resolve))
     const [socket] = OracleSocket.opened
-    const subscribed = () => socket.sent.map(text => JSON.parse(text))
-        .find(([type, , filter]) => type === 'REQ' && filter['#x'].includes(rootTopic))
-    await until(subscribed, 'the subscription to the root topic')
-    const subscription = subscribed()[1]
-    out.duplicate_keys.root_topic = rootTopic
-    out.duplicate_keys.events = []
-    for (const [i, members] of events.texts.entries()) {
-        acted.length = 0
-        socket.onmessage({data: eventText(subscription, members)})
-        const closing = `oracle-${i}`
-        socket.onmessage({data: eventText(subscription, [
-            ['tags', [['x', '{root}']]],
-            ['content', toJson({peerId: closing, answer: 'x'})],
-        ])})
-        await until(() => acted.includes(closing), `the report of ${closing}`)
-        const senders = acted.filter(peerId => peerId !== closing)
-        if (senders.length > 1) throw new Error(`one event reported ${senders.length} senders`)
-        out.duplicate_keys.events.push({text: eventText('sub', members), acted: senders[0] ?? null})
+    const request = await socket.awaitSent(text => {
+        const [type, , filter] = JSON.parse(text)
+        return type === 'REQ' && filter['#x'].includes(root)
+    })
+    const subscription = JSON.parse(request)[1]
+    const actOn = async (cases, closingPrefix) => {
+        const results = []
+        for (const [i, members] of cases.entries()) {
+            acted.length = 0
+            const closing = `${closingPrefix}${i}`.padEnd(20, '0')
+            const closed = reported(closing)
+            socket.onmessage({data: eventText(subscription, members)})
+            socket.onmessage({data: eventText(subscription, [
+                ['tags', [['x', '{root}']]],
+                ['content', toJson({peerId: closing, offerId: events.offer_id, answer: 'x'})],
+            ])})
+            await closed
+            const senders = acted.filter(peerId => peerId !== closing)
+            if (senders.length > 1) throw new Error(`one event reported ${senders.length} senders`)
+            results.push({text: eventText('sub', members), acted: senders[0] ?? null})
+        }
+        return results
     }
+    out.duplicate_keys.root_topic = root
+    out.duplicate_keys.events = await actOn(events.texts, events.closing_prefix)
+    out.signal_envelopes.root_topic = root
+    const envelopeEvent = content => [['tags', [['x', '{root}']]], ['content', content]]
+    out.signal_envelopes.events =
+        await actOn(cases.signal_envelopes.events.map(envelopeEvent), `${events.closing_prefix}E`)
     await room.leave()
     globalThis.WebSocket = WebSocket
 }
 
-// The answerer's signals, as Trystero's own signal handler publishes them (handleOffer): for each
-// case, a room of the oracle's, as readSignal's, gets an offer on its self topic, sealed under the
-// room's key, opens it, and hands it to its answering peer, a stand-in that gives an answer and
-// then a candidate, as an RTCIceCandidate's toJSON in JSON.stringify's text (peer.mjs); the room
-// seals each with Trystero's encrypt, the fixture's IV drawn every time, and publishes the answer,
-// then the candidate it held. `sealed` holds every text sealed, the offers' and the room's, with
-// its plaintext; `published`, the topic and the text of each signal the room sent, in order.
+// The answerer's signals, as 0.27.0's own signal handler publishes them (handleOffer): for each
+// case, a room of the oracle's gets an offer on its self topic, sealed under the room's key with
+// the offer's AAD, opens it, and hands it to its answering peer, a stand-in that gives an answer
+// and then a candidate, as an RTCIceCandidate's toJSON in JSON.stringify's text (peer.mjs); the
+// room seals each with its AAD, the fixture's IV drawn every time, and publishes the answer, then
+// the candidate it held, on the offerer's topic. Each published signal carries the plaintext its
+// sealed text holds and that sealed text, so that a test can put its own in its place.
 {
     const answerer = cases.answerer
-    const key = genKey(answerer.password, answerer.app_id, answerer.room_id)
-    const root = topicPath('Trystero', answerer.app_id, answerer.room_id)
     const candidate = JSON.stringify(answerer.candidate)
-    const sealed = []
-    const seal = async plaintext => {
-        const text = await encrypt(key, plaintext)
-        if (!sealed.some(entry => entry.plaintext === plaintext)) sealed.push({plaintext, text})
-        return text
-    }
-    crypto.getRandomValues = patterned(answerer.random)
-    const offer = await seal(answerer.offer_sdp)
     out.answerer = {
-        self_id: selfId,
+        self_id: answerer.self_id,
         app_id: answerer.app_id,
         room_id: answerer.room_id,
+        offer_sdp: answerer.offer_sdp,
         answer_sdp: answerer.answer_sdp,
         candidate,
-        sealed,
         cases: [],
     }
+    crypto.getRandomValues = patterned(answerer.random)
     for (const {peerId, offerId} of answerer.offers) {
-        const handlers = {}
-        const errors = []
+        const sealed = new Map()
         const published = []
-        const ctx = {
-            appId: answerer.app_id,
-            roomId: answerer.room_id,
-            config: {},
-            peerStates: {},
-            rootTopicPlaintext: root,
-            rootTopicP: sha1(root),
-            selfTopicP: sha1(topicPath(root, selfId)),
-            isPassive: false,
-            isActive: true,
-            isLeaving: () => false,
-            reusePeer: () => false,
-            toPlain: async ({type, sdp}) => ({type, sdp: await decrypt(key, sdp)}),
-            toCipher: async ({type, sdp}) => ({type, sdp: await seal(sdp)}),
+        let settle
+        const settled = new Promise((resolve, reject) => {
+            settle = {resolve, reject}
+        })
+        const handlers = {}
+        const ctx = await signalContext(answerer, {
+            onError: error => settle.reject(new Error(`the room reported ${error.code}`)),
             initPeer: () => ({
                 isDead: false,
                 setHandlers: given => Object.assign(handlers, given),
@@ -416,29 +367,33 @@ const until = async (done, what) => {
                         throw new Error('the oracle answers its own offer alone')
                     }
                     handlers.signal({type: 'answer', sdp: answerer.answer_sdp})
-                    handlers.signal({type: 'candidate', sdp: candidate})
+                    handlers.signal({type: candidateType, sdp: candidate})
                 },
                 destroy: () => {},
             }),
-            offerManager: {checkout: async () => Promise.reject(new Error('the oracle makes no offer'))},
-            connectPeer: () => {},
-            disconnectPeer: () => {},
-            checkDeactivate: () => {},
-            onJoinError: ({error}) => errors.push(error),
-            announceIntervals: [],
-            announceIntervalMs: 5333,
+        })
+        const toCipher = ctx.toCipher
+        ctx.toCipher = async (signal, ...rest) => {
+            const cipher = await toCipher(signal, ...rest)
+            sealed.set(cipher.sdp, signal.sdp)
+            return cipher
         }
-        const text = toJson({peerId, ...(offerId === undefined ? {} : {offerId}), offer})
-        await createSignalHandler(ctx)(0)(await ctx.selfTopicP, text,
-            (topic, message) => published.push({topic, text: message}))
-        await until(() => published.length === 2 || errors.length > 0, `the answer to ${peerId}`)
-        if (errors.length > 0) throw new Error(`the room reported ${errors[0]}`)
+        const offer = (await ctx.toCipher({type: 'offer', sdp: answerer.offer_sdp}, peerId, offerId)).sdp
+        const text = toJson({peerId, offerId, offer})
+        const {handleMessage} = createSignalHandler(ctx)
+        await handleMessage(0)(await ctx.selfTopicP, text, async (topic, message) => {
+            const signal = JSON.parse(message)
+            const text = signal.answer ?? signal.candidate
+            published.push({topic, text: message, sealed: text, plaintext: sealed.get(text)})
+            if (published.length === 2) settle.resolve()
+        })
+        await settled
         out.answerer.cases.push({offer: text, published})
     }
     crypto.getRandomValues = getRandomValues
 }
 
-// JSON payloads, as Trystero sends one: the value an action is given, written by toJson
+// JSON payloads, as 0.27.0 sends one: the value an action is given, written by toJson
 // (JSON.stringify), here each case's text as JSON.parse reads it. Their numbers are those a double
 // holds, written as JavaScript writes them, and their keys in JavaScript's order: array indices
 // first, in increasing order, then the other keys in the order they were written.
diff --git a/test/oracle/package-lock.json b/test/oracle/package-lock.json
index 6f47d97..82dcf17 100644
--- a/test/oracle/package-lock.json
+++ b/test/oracle/package-lock.json
@@ -7,9 +7,9 @@
       "name": "webcpp-trystero-tests",
       "devDependencies": {
         "@noble/secp256k1": "3.2.0",
-        "@trystero-p2p/core": "0.26.0",
-        "@trystero-p2p/nostr": "0.26.0",
-        "trystero": "0.26.0",
+        "@trystero-p2p/core": "0.27.0",
+        "@trystero-p2p/nostr": "0.27.0",
+        "trystero": "0.27.0",
         "werift": "0.24.4",
         "ws": "8.22.0"
       }
@@ -298,21 +298,27 @@
       }
     },
     "node_modules/@trystero-p2p/core": {
-      "version": "0.26.0",
-      "resolved": "https://registry.npmjs.org/@trystero-p2p/core/-/core-0.26.0.tgz",
-      "integrity": "sha512-CZpeXPgfbDdFKrGxfD98F9tn/fTjya4mQ2o/Ax6H0qpBaJXCBz5+jyPtjsYEPAAcKRK/btOatCetFiQ5qIMCOA==",
+      "version": "0.27.0",
+      "resolved": "https://registry.npmjs.org/@trystero-p2p/core/-/core-0.27.0.tgz",
+      "integrity": "sha512-8e85VEYLMOUSwBZDr9D+StbMrRYQRWn1egWvgdqHG1OwO//eZEwG9CvslY60D+Yqnq8XhkDobuIdXdBjNu/gnA==",
       "dev": true,
-      "license": "MIT"
+      "license": "MIT",
+      "engines": {
+        "node": ">=22"
+      }
     },
     "node_modules/@trystero-p2p/nostr": {
-      "version": "0.26.0",
-      "resolved": "https://registry.npmjs.org/@trystero-p2p/nostr/-/nostr-0.26.0.tgz",
-      "integrity": "sha512-HArp9fonBkqFZgw3U2D823fCePQv7haKkvjtwbGRkWzy+Wo9G3cCDEnG/GENDWwzERHrhRcRacpFsFt4JpwRJQ==",
+      "version": "0.27.0",
+      "resolved": "https://registry.npmjs.org/@trystero-p2p/nostr/-/nostr-0.27.0.tgz",
+      "integrity": "sha512-ZkuF64wCwtibGVnKzhrJXsq7DbrT/yNbaeUT9/hUcVZ1SiDAbjSQ5KzJh1lNgnUTKvSG00dqO4hNPbf4KuLuAw==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
         "@noble/secp256k1": "^3.2.0",
-        "@trystero-p2p/core": "0.26.0"
+        "@trystero-p2p/core": "0.27.0"
+      },
+      "engines": {
+        "node": ">=22"
       }
     },
     "node_modules/@types/dom-mediacapture-transform": {
@@ -560,13 +566,16 @@
       "license": "MIT"
     },
     "node_modules/trystero": {
-      "version": "0.26.0",
-      "resolved": "https://registry.npmjs.org/trystero/-/trystero-0.26.0.tgz",
-      "integrity": "sha512-M6NsoGmAkAy72K4YiPj0iGbd9hyuAGJpIBm0wL6f0g6bP/nCsMtbJKM8VpcxexK61HaQ5q5KDVnqFZogXGIolQ==",
+      "version": "0.27.0",
+      "resolved": "https://registry.npmjs.org/trystero/-/trystero-0.27.0.tgz",
+      "integrity": "sha512-2oUTc/G7K8/l5DOXA6pajFBMXKPuy7WcU1So1S+NVFvzL5xy7DlbIVSBQkIkV7ALL9uBEuFuCuacvKuUWxNdlw==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
-        "@trystero-p2p/nostr": "0.26.0"
+        "@trystero-p2p/nostr": "0.27.0"
+      },
+      "engines": {
+        "node": ">=22"
       }
     },
     "node_modules/tslib": {
diff --git a/test/oracle/package.json b/test/oracle/package.json
index f50e3a7..89e08f8 100644
--- a/test/oracle/package.json
+++ b/test/oracle/package.json
@@ -2,12 +2,12 @@
   "name": "webcpp-trystero-tests",
   "private": true,
   "type": "module",
-  "description": "The JavaScript side of the tests: Trystero JS 0.26 as the oracle, as the twins of the examples and as the interop peer, werift as its WebRTC in Node, and a local Nostr relay.",
+  "description": "The JavaScript side of the tests: Trystero JS 0.27.0 as the oracle, as the twins of the examples and as the interop peer, werift as its WebRTC in Node, and a local Nostr relay.",
   "devDependencies": {
     "@noble/secp256k1": "3.2.0",
-    "@trystero-p2p/core": "0.26.0",
-    "@trystero-p2p/nostr": "0.26.0",
-    "trystero": "0.26.0",
+    "@trystero-p2p/core": "0.27.0",
+    "@trystero-p2p/nostr": "0.27.0",
+    "trystero": "0.27.0",
     "werift": "0.24.4",
     "ws": "8.22.0"
   }
diff --git a/test/oracle/page.mjs b/test/oracle/page.mjs
index 5a24796..3a0cd24 100644
--- a/test/oracle/page.mjs
+++ b/test/oracle/page.mjs
@@ -4,16 +4,16 @@
 // accompanying file LICENSE_1_0.txt or copy at
 // https://www.boost.org/LICENSE_1_0.txt)
 
-// Another page for a twin whose room must meet a peer. Trystero JS has one self id per page, its
-// module's selfId, so two rooms of one twin's module would be the same peer; a C++ program makes
-// a second app instead. The other peer runs in a worker thread, with module instances of its own,
-// as a second page would:
+// Another page for a twin whose room must meet a peer. Trystero JS 0.27.0 has one endpoint key, so
+// one peer id, per app and page (its module's client id), so two rooms of one twin's module would
+// be the same peer; a C++ program makes a second app instead. The other peer runs in a worker
+// thread, with module instances of its own, as a second page would:
 //
 //   import {openPage} from '../page.mjs'
 //   const other = openPage(async ({joinRoom, RTCPeerConnection, data, post, next}) => { ... }, data)
 //
 // The function is the page's program, written in the twin and run in the worker from its source,
-// so it reaches nothing of the twin's but what it is given: Trystero's joinRoom and selfId,
+// so it reaches nothing of the twin's but what it is given: Trystero's joinRoom,
 // werift's RTCPeerConnection (the WebRTC Trystero's README names for Node, as rtcPolyfill), the
 // data given to openPage, which must be cloneable, post(message), which sends the twin a message,
 // and next(), which resolves to the next message the twin sends it. The twin's side holds
@@ -41,12 +41,11 @@ export const openPage = (program, data) => {
 }
 
 if (!isMainThread) {
-    const {joinRoom, selfId} = await import('trystero')
+    const {joinRoom} = await import('trystero')
     const {RTCPeerConnection} = await import('werift')
     const program = (0, eval)(`(${workerData.source})`)
     await program({
         joinRoom,
-        selfId,
         RTCPeerConnection,
         data: workerData.data,
         post: message => parentPort.postMessage(message),
diff --git a/test/oracle/record_0_27.mjs b/test/oracle/record_0_27.mjs
new file mode 100644
index 0000000..ea3a355
--- /dev/null
+++ b/test/oracle/record_0_27.mjs
@@ -0,0 +1,616 @@
+// Copyright (c) 2026 WebCpp.org
+//
+// Distributed under the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// https://www.boost.org/LICENSE_1_0.txt)
+
+// Records webcpp::trystero's test vectors, for both phases of the port, from Trystero 0.27.0's own
+// code, run in Node (>= 23.6, which strips TypeScript's types). Usage:
+//   node record.mjs  [] > trystero-0.27.0.json
+//   node record.mjs --dist  [] > trystero-0.27.0.json
+// The first form imports packages/core/src/*.ts and packages/nostr/src/protocol.ts of the pinned
+// checkout unchanged; extensionless relative imports are resolved to .ts by the hook below. The
+// second imports the same modules from the published packages' dist/*.mjs under 
+// (@trystero-p2p/core and @trystero-p2p/nostr 0.27.0), so that the oracle lane proves the packages
+// a JavaScript peer runs equal the pinned source: both forms write the same bytes.
+// Randomness is pinned only around the calls whose output it decides (the GCM IV, genId's bytes, a
+// request's id, the handshake's UUID nonces), by replacing crypto.getRandomValues or
+// crypto.randomUUID for that call and restoring it after. WebCrypto's ECDSA signatures are random:
+// with , each signature recorded there is kept when 0.27.0's own verification
+// still accepts it, and only a missing one is signed anew, so that a run over the previous output
+// writes it again byte for byte.
+import {registerHooks} from 'node:module'
+import {pathToFileURL} from 'node:url'
+import path from 'node:path'
+import fs from 'node:fs'
+import {createECDH, createHash} from 'node:crypto'
+
+const distMode = process.argv[2] === '--dist'
+const argv = distMode ? process.argv.slice(3) : process.argv.slice(2)
+const rootUrl = pathToFileURL(path.resolve(argv[0] ?? '.') + '/')
+const corePrimitives = distMode
+  ? new URL('@trystero-p2p/core/dist/primitives.mjs', rootUrl).href
+  : new URL('packages/core/src/primitives.ts', rootUrl).href
+
+registerHooks({
+  resolve(specifier, context, next) {
+    // nostr's protocol imports two packages: Trystero's core, whose encodeBytes and toJson
+    // are primitives's, and the Schnorr signer, which topicToKind does not use.
+    if (specifier === '@trystero-p2p/core') {
+      return next(corePrimitives, context)
+    }
+    if (specifier === '@noble/secp256k1') {
+      return {url: 'data:text/javascript,export const schnorr = {}', shortCircuit: true}
+    }
+    if (!distMode && specifier.startsWith('.') && !path.extname(specifier)) {
+      const parent = new URL(context.parentURL)
+      const candidate = new URL(specifier + '.ts', parent)
+      if (fs.existsSync(candidate)) {
+        return next(candidate.href, context)
+      }
+    }
+    return next(specifier, context)
+  }
+})
+
+const root = path.resolve(argv[0] ?? '.')
+// A source path of the checkout, or the same module of the published packages in --dist mode.
+const src = p => {
+  if (!distMode) return pathToFileURL(path.join(root, p)).href
+  const [, pkg, file] = /^packages\/(core|nostr)\/src\/(.+)\.ts$/.exec(p)
+  return pathToFileURL(path.join(root, '@trystero-p2p', pkg, 'dist', file + '.mjs')).href
+}
+const previous = argv[1] ? JSON.parse(fs.readFileSync(argv[1], 'utf8')) : null
+const prim = await import(src('packages/core/src/primitives.ts'))
+const cry = await import(src('packages/core/src/crypto.ts'))
+const utils = await import(src('packages/core/src/utils.ts'))
+
+const nostr = await import(src('packages/nostr/src/protocol.ts'))
+const pkg = JSON.parse(fs.readFileSync(path.join(root, distMode ? '@trystero-p2p/core/package.json' : 'packages/core/package.json'), 'utf8'))
+const hex = b => Buffer.from(b).toString('hex')
+// The published dist inlines primitives.ts's id lengths, which it then does not export.
+const peerIdLength = prim.peerIdLength ?? 20
+const userIdLength = prim.userIdLength ?? 22
+const fromHex = h => new Uint8Array(Buffer.from(h, 'hex'))
+
+const withRandom = async (bytes, f) => {
+  const original = crypto.getRandomValues.bind(crypto)
+  let at = 0
+  crypto.getRandomValues = view => {
+    for (let i = 0; i < view.length; i++) view[i] = bytes[(at++) % bytes.length]
+    return view
+  }
+  try {
+    return await f()
+  } finally {
+    crypto.getRandomValues = original
+  }
+}
+
+const out = {trystero: pkg.version, recorded_with: `node ${process.version}`}
+
+// Domain tags and topic texts.
+const tagVersions = {'room-aes': 3, 'room-hmac': 3, 'pbkdf2-master': 3, 'ov-auth': 3, 'e2e-salt': 2,
+  'e2e-info': 2, pid: 1, uid: 1, 'user-proof': 3, 'id-hs': 2, 'identity-self-test': 1}
+out.domain_tags = Object.entries(tagVersions).map(([n, version]) => ({name: n, version,
+  tag: prim.domainTag(n, version)}))
+
+const texts = ['', 'lobby', 'Trystero', '["Trystero","app","room"]', 'café \u{1F600}',
+  'x'.repeat(200)]
+out.hash_topic = []
+for (const t of texts) out.hash_topic.push({text: t, topic: await cry.hashTopic(t)})
+
+out.topic_path = [
+  {parts: ['Trystero', 'example.com/app', 'lobby']},
+  {parts: ['Trystero', 'a"b\\c', 'café']},
+  {parts: ['["Trystero","app","room"]', 'peer0123456789abcdef']}
+].map(c => ({...c, path: utils.topicPath(...c.parts)}))
+
+// A room's two topics, as strategy.ts derives them: the root from topicPath(libName, app, room),
+// a peer's from topicPath(, peerId), each through hashTopic.
+out.room_topics = []
+for (const [a, r, p] of [['example.com/app', 'lobby', 'T5sdTwb84yyey80e4qjv'],
+  ['webcpp-trystero-quick-start', 'caf\u00e9', 'AbCdEfGhIjKlMnOpQrSt']]) {
+  const rootText = utils.topicPath(prim.libName, a, r)
+  const peerText = utils.topicPath(rootText, p)
+  out.room_topics.push({app: a, room: r, peer_id: p, root_text: rootText,
+    root_topic: await cry.hashTopic(rootText), peer_text: peerText,
+    peer_topic: await cry.hashTopic(peerText), root_kind: nostr.topicToKind(await cry.hashTopic(rootText))})
+}
+
+// Base64url, strict.
+out.base64url = [[], [0], [0xff, 0xfe], [1, 2, 3], [0xfb, 0xff, 0xbf], [...Array(33).keys()]]
+  .map(b => ({bytes: hex(b), text: prim.toBase64Url(new Uint8Array(b))}))
+
+// hash32, strToNum, shuffle, Nostr kinds.
+out.hash32 = texts.map(t => ({text: t, value: prim.hash32(t)}))
+out.str_to_num = texts.map(t => ({text: t, limit: 10000, value: utils.strToNum(t, 10000)}))
+const relays = Array.from({length: 30}, (_, i) => `wss://relay${i}.example`)
+out.shuffle = ['example.com/app', 'webcpp-trystero-quick-start', '', 'café'].map(app => ({
+  app, seed: utils.strToNum(app), order: utils.shuffle(relays.map((_, i) => i), utils.strToNum(app))
+}))
+out.topic_to_kind = texts.map(t => ({topic: t, kind: nostr.topicToKind(t)}))
+
+// Base62 ids: genId over pinned bytes (bytes >= 248 rejected).
+const idBytes = [0, 1, 61, 62, 123, 247, 248, 249, 255, 10, 200, 100, 33, 34, 35, 36, 37, 38, 39, 40]
+out.gen_id = [8, 12, 20, 22, 64].map(n => ({n, random_cycle: hex(idBytes),
+  id: null}))
+for (const c of out.gen_id) c.id = await withRandom(idBytes, () => utils.genId(c.n))
+
+// encodeBase62 of a SHA-256 digest and the pid/uid derivation from a compact public key.
+const compactPubs = ['WKn-ZIGevcwGIyyrzFoZNBdQq79v3jZ8Nl3S1Jvxm7I.HdKAMKoHOpFkK-nMlm9JN6qzGlcrJ8nd5I4L8ss1V40']
+out.identity_ids = []
+for (const cp of compactPubs) {
+  const pd = await cry.sha256(`${prim.domainTag('pid', 1)}:${cp}`)
+  const ud = await cry.sha256(`${prim.domainTag('uid', 1)}:${cp}`)
+  const enc = (bytes, len) => {
+    const m = 62n ** BigInt(len)
+    let v = prim.bytesToBigInt(bytes) % m
+    let s = ''
+    for (let i = 0; i < len; i++) { s = prim.base62Alphabet[Number(v % 62n)] + s; v /= 62n }
+    return s
+  }
+  out.identity_ids.push({compact_pub: cp, pid_digest: hex(pd), uid_digest: hex(ud),
+    peer_id: enc(pd, peerIdLength), user_id: enc(ud, userIdLength)})
+}
+
+// Room keys: exported by wrapping the derivation's CryptoKeys in raw exports where WebCrypto allows.
+const exportRaw = async k => hex(new Uint8Array(await crypto.subtle.exportKey('raw', k)))
+const rooms = [['example.com/app', 'lobby'], ['webcpp-trystero-quick-start', 'café']]
+out.room_key_no_password = []
+for (const [a, r] of rooms) {
+  const raw = await cry.sha256(prim.toJson([prim.domainTag('room-aes', 3), a, r]))
+  out.room_key_no_password.push({app: a, room: r,
+    preimage: prim.toJson([prim.domainTag('room-aes', 3), a, r]), key: hex(raw)})
+}
+
+// With a password the keys are not extractable; the vectors recompute them with WebCrypto
+// step by step, as crypto.ts derives them, and prove the result against crypto.ts by sealing.
+const passwords = ['hunter2', 'päss wörd']
+out.room_keys_password = []
+for (const [a, r] of rooms) for (const pw of passwords) {
+  const salt = await cry.sha256(prim.toJson([prim.domainTag('pbkdf2-master', 3), a, r]))
+  const base = await crypto.subtle.importKey('raw', prim.encodeBytes(pw), 'PBKDF2', false, ['deriveBits'])
+  const master = new Uint8Array(await crypto.subtle.deriveBits(
+    {name: 'PBKDF2', salt, iterations: 600_000, hash: 'SHA-256'}, base, 256))
+  const hk = await crypto.subtle.importKey('raw', master, 'HKDF', false, ['deriveBits'])
+  const derive = async info => hex(new Uint8Array(await crypto.subtle.deriveBits(
+    {name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(32), info: prim.encodeBytes(info)}, hk, 256)))
+  const iv = fromHex('000102030405060708090a0b')
+  const sealed = await withRandom(iv, () => cry.encrypt(cry.genKey(pw, a, r), 'probe', 'offer|p|o'))
+  out.room_keys_password.push({app: a, room: r, password: pw, salt: hex(salt),
+    master: hex(master), aes_key: await derive(prim.domainTag('room-aes', 3)),
+    hmac_key: await derive(prim.domainTag('room-hmac', 3)), probe_sealed: sealed})
+}
+
+// Room auth tokens (HMAC-SHA-256 under the password's HMAC key).
+out.room_auth = []
+for (const [a, r] of rooms) {
+  const pw = passwords[0]
+  for (const [peer, seq] of [['@topology', 0], ['AbCdEfGhIjKlMnOpQrSt', 7]]) {
+    const token = await cry.signRoomAuth(pw, a, r, peer, seq)
+    out.room_auth.push({app: a, room: r, password: pw, peer_id: peer, seq,
+      payload: prim.toJson([prim.domainTag('ov-auth', 3), a, r, peer, seq]), token,
+      verifies: await cry.verifyRoomAuth(pw, a, r, peer, seq, token),
+      wrong_seq_verifies: await cry.verifyRoomAuth(pw, a, r, peer, seq + 1, token)})
+  }
+}
+
+// AES-256-GCM sealing: base64url(iv || ciphertext || tag), with and without AAD.
+out.seal = []
+const ivs = ['000102030405060708090a0b', 'ffffffffffffffffffffffff']
+const plains = ['', 'v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\n', 'café \u{1F600}']
+for (const [a, r] of rooms) for (const pw of ['', passwords[0]]) for (const ivh of ivs)
+  for (const p of plains) for (const aad of [undefined, 'offer|AbCdEfGhIjKlMnOpQrSt|0123456789ab']) {
+    const sealed = await withRandom(fromHex(ivh), () => cry.encrypt(cry.genKey(pw, a, r), p, aad))
+    const opened = await cry.decrypt(cry.genKey(pw, a, r), sealed, aad)
+    out.seal.push({app: a, room: r, password: pw, iv: ivh, plaintext: p,
+      aad: aad ?? null, sealed, opened_equal: opened === p})
+  }
+
+// Texts decrypt refuses: each one must be refused by the port too.
+const k0 = cry.genKey('', ...rooms[0])
+const good = out.seal.find(s => s.password === '' && s.app === rooms[0][0] && s.aad === null && s.plaintext === 'café \u{1F600}').sealed
+const refusals = ['', 'not base64!', good.slice(0, 20), good + '=', good.slice(0, -1) + (good.at(-1) === 'A' ? 'B' : 'A'),
+  good.replace(/^./, c => (c === 'A' ? 'B' : 'A'))]
+out.open_refused = []
+for (const t of refusals) {
+  let refused = false
+  try { await cry.decrypt(k0, t) } catch { refused = true }
+  out.open_refused.push({app: rooms[0][0], room: rooms[0][1], password: '', sealed: t, refused})
+}
+
+// The signal AAD.
+const sh = await import(src('packages/core/src/signal-handler.ts')).catch(() => null)
+out.signal_aad = sh ? [['offer', 'AbCdEfGhIjKlMnOpQrSt', '0123456789ab'], ['answer', 'x', 'y']]
+  .map(([t, p, o]) => ({type: t, peer_id: p, offer_id: o, aad: sh.buildSignalAad(t, p, o)})) : null
+
+// The action wire: frames of packages/core/src/action-wire.ts, between two of its managers, A and
+// B, whose transports record each frame and hand it to the other manager's handleData a microtask
+// later. A transport reports maxBulkFrameBytes only in the wide cases, as a connection whose SCTP
+// takes 64 KiB messages does. A frame is recorded as hex, a chunk as its 14-byte header, its size
+// and the SHA-256 of the whole frame, which proves it as well as its hex and keeps the fixture
+// small; a payload of more than 64 bytes is named by its size, its bytes being (i * 31) mod 256.
+const wire = await import(src('packages/core/src/action-wire.ts'))
+const actionsMod = await import(src('packages/core/src/actions.ts'))
+const patterned = n => Uint8Array.from({length: n}, (_, i) => (i * 31) & 255)
+const settle = () => new Promise(resolve => setTimeout(resolve, 0))
+const recordFrame = async (from, bytes, transferId, isOffer) => {
+  const entry = {from, size: bytes.length}
+  if (transferId !== undefined) entry.transfer_id = transferId
+  if (isOffer) entry.is_offer = true
+  if ((bytes[1] & 15) === 2) {
+    entry.head = hex(bytes.subarray(0, 14))
+    entry.sha256 = hex(await cry.sha256(bytes))
+  } else {
+    entry.hex = hex(bytes)
+  }
+  return entry
+}
+
+// Two peers whose managers (made by `make`, given its dependencies) exchange frames.
+const wirePair = (make, wide, onFrame = () => {}) => {
+  const frames = []
+  const pending = []
+  const managers = {}
+  const transport = (from, to) => ({
+    isOpen: true,
+    bufferedAmount: 0,
+    ...(wide ? {maxBulkFrameBytes: 64 * 1024} : {}),
+    sendFrame: (bytes, transferId, isOffer) => {
+      const copy = bytes.slice()
+      const at = frames.push(null) - 1
+      pending.push(recordFrame(from, copy, transferId, isOffer).then(e => { frames[at] = e }))
+      onFrame(from, copy)
+      queueMicrotask(() => managers[to].handleData(from, copy.buffer))
+    },
+    waitForDrain: () => true
+  })
+  const deps = (self, other) => ({
+    resolveTransport: id => (id === other ? transport(self, other) : undefined),
+    getTransport: id => (id === other ? transport(self, other) : undefined),
+    getPeerIds: () => [other],
+    canReceiveFromPeer: () => true,
+    onPeerError: (id, e) => { throw new Error(`${self} dropped ${id}: ${e.message}`) }
+  })
+  managers.A = make(deps('A', 'B'))
+  managers.B = make(deps('B', 'A'))
+  return {managers, frames: async () => { await settle(); await Promise.all(pending); return frames }}
+}
+
+const payloadOf = (format, data) => format === 2
+  ? (data.length > 64 ? {payload_size: data.length} : {payload_hex: hex(data)})
+  : {payload_text: format === 0 ? data : prim.toJson(data)}
+
+out.action_frames = []
+const recordSend = async (name, action, data, format, {metadata, wide = false, gate, abortAfterChunk = false} = {}) => {
+  const controller = new AbortController()
+  const pair = wirePair(d => wire.createActionWireManager(d), wide, (from, bytes) => {
+    if (abortAfterChunk && from === 'A' && (bytes[1] & 15) === 2) controller.abort()
+  })
+  const a = pair.managers.A.makeWireAction(action)
+  const b = pair.managers.B.makeWireAction(action)
+  let received = null
+  b.onMessage((value, peer, meta) => { received = {value, peer, meta} })
+  if (gate) b.onReceive(gate)
+  let error = null
+  await a.send(data, 'B', metadata, undefined, controller.signal).catch(e => { error = e.message })
+  const frames = await pair.frames()
+  out.action_frames.push({case: name, action, format, metadata: metadata === undefined ? null : prim.toJson(metadata),
+    ...payloadOf(format, data), wide, frames, delivered: received !== null, send_error: error})
+}
+
+await recordSend('text', 'chat', 'hello, café', 0)
+await recordSend('json', 'json', {n: 1, list: [true, null, 'x']}, 1)
+await recordSend('binary', 'bin', Uint8Array.from({length: 10}, (_, i) => i), 2)
+await recordSend('metadata', 'chat', 'hi', 0, {metadata: {a: 1}})
+await recordSend('bulk', 'file', patterned(200 * 1024), 2, {metadata: {name: 'big.bin'}})
+await recordSend('bulk_wide', 'file', patterned(200 * 1024), 2, {metadata: {name: 'big.bin'}, wide: true})
+await recordSend('declined', 'file', patterned(20000), 2, {gate: () => false})
+await recordSend('cancelled', 'file', patterned(200 * 1024), 2, {abortAfterChunk: true})
+
+// A request and its response, through actions.ts's request action: the request's metadata names
+// its id (crypto.randomUUID, pinned here), the response travels as the internal action
+// "@_response" with that id, and a failure as a JSON null with the error's text.
+const requestId = '0b1c2d3e-4f50-4617-8899-aabbccddeeff'
+for (const [name, fails] of [['request', false], ['request_failed', true]]) {
+  const pair = wirePair(d => actionsMod.createActionManager(d), false)
+  const asker = pair.managers.A.makeAction('ask', {kind: 'request'})
+  const answerer = pair.managers.B.makeAction('ask', {kind: 'request'})
+  answerer.onRequest(async data => {
+    if (fails) throw new Error('no answer')
+    return `pong:${data}`
+  })
+  const uuid = crypto.randomUUID
+  crypto.randomUUID = () => requestId
+  let response = null
+  let error = null
+  try {
+    response = await asker.request('ping', {target: 'B', metadata: {x: 1}})
+  } catch (e) {
+    error = e.message
+  } finally {
+    crypto.randomUUID = uuid
+  }
+  out.action_frames.push({case: name, action: 'ask', format: 0, metadata: prim.toJson({r: requestId, m: {x: 1}}),
+    payload_text: 'ping', wide: false, frames: await pair.frames(), response, send_error: error,
+    answer: {action: '@_response', format: fails ? 1 : 0,
+      metadata: prim.toJson(fails ? {r: requestId, e: 'no answer'} : {r: requestId}),
+      payload_text: fails ? 'null' : 'pong:ping'}})
+}
+
+// ---------------------------------------------------------------------------------------------
+// Phase 2: identity, signatures and the handshake (identity.ts, crypto.ts, handshake.ts).
+// Every key is fixed: its secret scalar is SHA-256 of a label, its point computed by node:crypto.
+// A signature is WebCrypto's, made by 0.27.0's ecdsaSign (low S) and kept across runs by `signed`.
+const ident = await import(src('packages/core/src/identity.ts'))
+const hs = await import(src('packages/core/src/handshake.ts'))
+const b64 = prim.toBase64Url
+const p256N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n
+const bigHex = v => v.toString(16).padStart(64, '0')
+
+const fixedKey = label => {
+  const d = createHash('sha256').update(`webcpp-trystero-vector:${label}`).digest()
+  const ecdh = createECDH('prime256v1')
+  ecdh.setPrivateKey(d)
+  const point = new Uint8Array(ecdh.getPublicKey(null, 'uncompressed'))
+  const x = b64(point.subarray(1, 33))
+  const y = b64(point.subarray(33))
+  return {label, d: b64(new Uint8Array(d)), x, y, point, compact: `${x}.${y}`,
+    jwk: {kty: 'EC', crv: 'P-256', d: b64(new Uint8Array(d)), x, y}}
+}
+const signingKeyOf = async k => crypto.subtle.importKey('jwk', {...k.jwk, ext: true, key_ops: ['sign']},
+  cry.ecdsaKeyAlgo, false, ['sign'])
+const verifyKeyOf = async k => crypto.subtle.importKey('raw', k.point, cry.ecdsaKeyAlgo, false, ['verify'])
+
+// Signatures of the previous output, by label, and those this run records.
+const previousSignatures = previous?.signatures ?? {}
+out.signatures = {}
+const signed = async (label, key, payload) => {
+  const kept = previousSignatures[label]
+  if (kept && await cry.ecdsaVerify(await verifyKeyOf(key), prim.fromBase64Url(kept), payload)) {
+    out.signatures[label] = kept
+    return prim.fromBase64Url(kept)
+  }
+  const sig = await cry.ecdsaSign(await signingKeyOf(key), payload)
+  out.signatures[label] = b64(sig)
+  return sig
+}
+
+const keys = Object.fromEntries(['endpoint-a', 'user-a', 'endpoint-b', 'user-b', 'user-export']
+  .map(l => [l, fixedKey(l)]))
+
+// The ids of each fixed key, through 0.27.0's getVerifiedPubKeyRecord (its peerId and userId).
+out.p256_keys = []
+for (const k of Object.values(keys)) {
+  const rec = await ident.getVerifiedPubKeyRecord(k.compact)
+  out.p256_keys.push({label: k.label, d: k.d, uncompressed: hex(k.point), compact: k.compact,
+    peer_id: rec.peerId, user_id: rec.userId})
+}
+
+// Compact keys 0.27.0 refuses (pubJwkToUncompressedBytes) and one it takes; a point off the curve
+// passes the text check and fails only at the key's import (getVerifiedPubKeyRecord gives null).
+const goodCompact = keys['user-a'].compact
+const offCurve = `${goodCompact.slice(0, 44)}${b64(new Uint8Array(32).fill(1))}`
+out.compact_keys = []
+for (const text of [goodCompact, goodCompact.slice(0, 86), goodCompact + 'A', goodCompact.replace('.', '_'),
+  `${goodCompact.slice(0, 42)}=.${goodCompact.slice(44)}`, offCurve]) {
+  out.compact_keys.push({text, text_valid: ident.pubJwkToUncompressedBytes(text) !== null,
+    record: (await ident.getVerifiedPubKeyRecord(text)) !== null})
+}
+
+// The exported user identity: `trystero_uk_` + base64url(JSON {d, x, y}), and what import takes.
+const exportKey = keys['user-export']
+const imported = await ident.importUserIdentity(exportKey.jwk)
+const userKeyText = ident.exportUserIdentity(imported)
+out.user_identity = {label: exportKey.label, jwk: {d: exportKey.d, x: exportKey.x, y: exportKey.y},
+  user_id: imported.userId, text: userKeyText,
+  json: prim.toJson({d: exportKey.d, x: exportKey.x, y: exportKey.y})}
+const wrap = obj => `trystero_uk_${b64(prim.encodeBytes(prim.toJson(obj)))}`
+const otherKey = keys['user-a']
+const nBytes = prim.fromBase64Url(b64(Uint8Array.from(Buffer.from(bigHex(p256N), 'hex'))))
+const importCases = [
+  ['the exported text', userKeyText],
+  ['the text with spaces around it', `  ${userKeyText}\n`],
+  ['the JSON text', prim.toJson({kty: 'EC', crv: 'P-256', d: exportKey.d, x: exportKey.x, y: exportKey.y})],
+  ['another prefix', userKeyText.replace('trystero_uk_', 'trystero_pk_')],
+  ['the payload padded', userKeyText + '='],
+  ['d of another key', wrap({d: otherKey.d, x: exportKey.x, y: exportKey.y})],
+  ['d zero', wrap({d: b64(new Uint8Array(32)), x: exportKey.x, y: exportKey.y})],
+  ['d the group order', wrap({d: b64(nBytes), x: exportKey.x, y: exportKey.y})],
+  ['d of 31 bytes', wrap({d: b64(prim.fromBase64Url(exportKey.d).subarray(1)), x: exportKey.x, y: exportKey.y})],
+  ['crv P-384', wrap({crv: 'P-384', d: exportKey.d, x: exportKey.x, y: exportKey.y})],
+  ['no y', wrap({d: exportKey.d, x: exportKey.x})],
+  ['empty', '']
+]
+out.user_identity_imports = []
+for (const [name, text] of importCases) {
+  let userId = null
+  try { userId = (await ident.importUserIdentity(text)).userId } catch {}
+  out.user_identity_imports.push({case: name, text, accepted: userId !== null, user_id: userId})
+}
+
+// The user-proof: 0.27.0 exports its payload, signature and verification (identity.ts) but its
+// core never sends one; the port keeps the protocol functions, proven here.
+const proofParams = {appId: 'example.com/app', roomId: 'lobby', peerId: out.p256_keys[0].peer_id,
+  peerPubJwk: keys['endpoint-a'].compact, seq: 7}
+const proofPayload = ident.userEndpointProofPayload(proofParams)
+const proofSig = await signed('user_proof', keys['user-a'], proofPayload)
+out.user_proof = {app: proofParams.appId, room: proofParams.roomId, peer_id: proofParams.peerId,
+  peer_compact: proofParams.peerPubJwk, seq: proofParams.seq, user_id: out.p256_keys[1].user_id,
+  user_compact: keys['user-a'].compact, payload: prim.decodeBytes(proofPayload),
+  digest: hex(await cry.sha256(prim.decodeBytes(proofPayload))), proof: b64(proofSig),
+  verifies: await ident.verifyUserEndpointProof({...proofParams, userId: out.p256_keys[1].user_id,
+    userPubJwk: keys['user-a'].compact, proof: b64(proofSig)}),
+  other_seq_verifies: await ident.verifyUserEndpointProof({...proofParams, seq: 8,
+    userId: out.p256_keys[1].user_id, userPubJwk: keys['user-a'].compact, proof: b64(proofSig)})}
+
+// Low S: 0.27.0 signs low (ecdsaSign normalizes) and verifyWithP256 refuses a high S.
+const sAt = sig => prim.bytesToBigInt(sig.subarray(32))
+const withS = (sig, s) => { const o = sig.slice(); o.set(Buffer.from(bigHex(s), 'hex'), 32); return o }
+const withR = (sig, r) => { const o = sig.slice(); o.set(Buffer.from(bigHex(r), 'hex'), 0); return o }
+const lowSig = proofSig
+const highSig = withS(lowSig, p256N - sAt(lowSig))
+const halfN = p256N >> 1n
+out.low_s = []
+for (const [name, sig] of [['signed', lowSig], ['its high form', highSig], ['s = (n - 1) / 2', withS(lowSig, halfN)],
+  ['s = (n + 1) / 2', withS(lowSig, halfN + 1n)], ['s = n - 1', withS(lowSig, p256N - 1n)],
+  ['s = 0', withS(lowSig, 0n)], ['r = 0', withR(lowSig, 0n)], ['r = n', withR(lowSig, p256N)]]) {
+  out.low_s.push({case: name, signature: hex(sig), is_low_s: cry.isLowSP256Signature(sig),
+    normalized: hex(cry.normalizeLowSP256Signature(sig)),
+    verifies: await ident.verifyWithP256(sig, proofPayload, keys['user-a'].compact)})
+}
+
+// The handshake's DTLS fingerprints: every `a=fingerprint:` line's value, trimmed, lowercased,
+// deduplicated and sorted, as extractDtlsFingerprints reads a description. It is private to
+// handshake.ts, so a run of the handshake below proves it: each side sends what it read.
+const fpA = 'sha-256 4F:2A:9C:11:00:7B:EE:31:58:AA:0D:6C:93:12:47:BF:C8:21:5E:70:66:D4:3A:91:0B:CF:28:7E:55:19:A3:F0'
+const fpB = 'sha-256 0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9:0A:1B:2C:3D:4E:5F:60:71:82:93:A4:B5:C6:D7:E8:F9'
+const fpA2 = 'sha-1 11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44'
+const sdpA = `v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:${fpA}\r\na=fingerprint:${fpA2}\r\na=fingerprint:${fpA.toLowerCase()}\r\n`
+const sdpB = `v=0\r\no=- 3 4 IN IP4 127.0.0.1\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint: ${fpB} \r\n`
+
+// One run of createIdentityHandshake between A (the initiator) and B, over queues, each side's
+// connection described by the SDPs above; `tamper` may change a message on its way.
+const nonces = ['5a1f0c2e-8b3d-4e6f-9a70-b1c2d3e4f506', 'c0ffee00-1234-4abc-8def-0123456789ab']
+const identityOf = (endpoint, user, prefix) => ({
+  endpoint: {peerId: out.p256_keys.find(k => k.label === endpoint.label).peer_id,
+    signPubJwk: {kty: 'EC', crv: 'P-256', x: endpoint.x, y: endpoint.y},
+    sign: payload => signed(`${prefix}:endpoint`, endpoint, payload)},
+  user: {userId: out.p256_keys.find(k => k.label === user.label).user_id,
+    signPubJwk: {kty: 'EC', crv: 'P-256', x: user.x, y: user.y},
+    sign: payload => signed(`${prefix}:user`, user, payload)}
+})
+const runHandshake = async (name, {tamper = (from, step, msg) => msg, sdps = [sdpA, sdpB, sdpB, sdpA]} = {}) => {
+  const a = identityOf(keys['endpoint-a'], keys['user-a'], `${name}:a`)
+  const b = identityOf(keys['endpoint-b'], keys['user-b'], `${name}:b`)
+  const app = 'example.com/app'
+  const room = 'lobby'
+  const queues = {A: [], B: []}
+  const waiters = {A: [], B: []}
+  const messages = []
+  const deliver = (to, payload) => {
+    const w = waiters[to].shift()
+    if (w) w(payload)
+    else queues[to].push(payload)
+  }
+  const sender = (from, to) => async data => {
+    const step = data[`__trystero_id`]
+    const sent = tamper(from, step, structuredClone(data))
+    messages.push({from, step, json: prim.toJson(sent)})
+    deliver(to, {data: sent})
+  }
+  const receiver = side => () => new Promise(resolve => {
+    const queued = queues[side].shift()
+    if (queued) resolve(queued)
+    else waiters[side].push(resolve)
+  })
+  const peerHandle = (local, remote) => ({connection: {localDescription: {sdp: local}, remoteDescription: {sdp: remote}}})
+  const verified = {}
+  const make = (side, id) => hs.createIdentityHandshake({endpointIdentityP: Promise.resolve(id.endpoint), appId: app,
+    roomId: room, getUserIdentity: () => Promise.resolve(id.user),
+    onVerified: (peerId, v) => { verified[side] = {peer_id: peerId, user_id: v.userId} }})
+  const uuid = crypto.randomUUID
+  let at = 0
+  crypto.randomUUID = () => nonces[at++]
+  const results = {}
+  // A side that fails sends nothing more: the other one waits (until room.ts's 10 s timeout),
+  // recorded as 'waits'; the run unblocks it with a message it refuses.
+  let firstFailure = null
+  const fail = (side, other, e) => {
+    results[side] = firstFailure && firstFailure !== side ? 'waits' : e.message
+    if (!firstFailure) {
+      firstFailure = side
+      deliver(other, {data: null})
+    }
+  }
+  try {
+    await Promise.all([
+      make('A', a).run(b.endpoint.peerId, sender('A', 'B'), receiver('A'), true, peerHandle(sdps[0], sdps[1]))
+        .then(() => { results.A = null }, e => fail('A', 'B', e)),
+      make('B', b).run(a.endpoint.peerId, sender('B', 'A'), receiver('B'), false, peerHandle(sdps[2], sdps[3]))
+        .then(() => { results.B = null }, e => fail('B', 'A', e))
+    ])
+  } finally {
+    crypto.randomUUID = uuid
+  }
+  return {case: name, app, room, initiator: {peer_id: a.endpoint.peerId, user_id: a.user.userId,
+    endpoint: keys['endpoint-a'].label, user: keys['user-a'].label, sdp_local: sdps[0], sdp_remote: sdps[1]},
+  responder: {peer_id: b.endpoint.peerId, user_id: b.user.userId, endpoint: keys['endpoint-b'].label,
+    user: keys['user-b'].label, sdp_local: sdps[2], sdp_remote: sdps[3]},
+  nonces, messages, initiator_error: results.A, responder_error: results.B, verified}
+}
+
+out.handshake = []
+const ok = await runHandshake('verified')
+// The transcript both sides sign: toJson([domainTag('id-hs', 2), app, room, init peer, resp peer,
+// init nonce, resp nonce, init dtls, resp dtls, init user, resp user]), as encodeTranscript writes it.
+const step1 = JSON.parse(ok.messages[0].json)
+const step2 = JSON.parse(ok.messages[1].json)
+const transcript = prim.toJson([prim.domainTag('id-hs', 2), ok.app, ok.room, ok.initiator.peer_id,
+  ok.responder.peer_id, step1.n, step2.n, step1.dtls, step2.dtls, ok.initiator.user_id, ok.responder.user_id])
+ok.transcript = transcript
+ok.transcript_digest = hex(await cry.sha256(transcript))
+ok.transcript_verified = {
+  step2_endpoint: await ident.verifyWithP256(prim.fromBase64Url(step2.ps), prim.encodeBytes(transcript), keys['endpoint-b'].compact),
+  step2_user: await ident.verifyWithP256(prim.fromBase64Url(step2.us), prim.encodeBytes(transcript), keys['user-b'].compact)}
+out.handshake.push(ok)
+const swapStep = (side, step, edit) => (from, s, msg) => (from === side && s === step ? edit(msg) : msg)
+out.handshake.push(await runHandshake('another remote fingerprint', {sdps: [sdpA, sdpB, sdpB, sdpA.replace(/4F:2A/g, '4F:2B')]}))
+out.handshake.push(await runHandshake('a user id of another key', {tamper: swapStep('A', 1, m => ({...m, uid: out.p256_keys[3].user_id}))}))
+out.handshake.push(await runHandshake('an endpoint key of another peer id', {tamper: swapStep('B', 2, m => ({...m, pk: keys['endpoint-a'].compact}))}))
+out.handshake.push(await runHandshake('a short nonce', {tamper: swapStep('A', 1, m => ({...m, n: '0123456789abcde'}))}))
+out.handshake.push(await runHandshake('a user signature of another key', {tamper: swapStep('B', 2, m => ({...m, us: m.ps}))}))
+out.handshake.push(await runHandshake('a high-S endpoint signature', {tamper: swapStep('A', 3, m => {
+  const sig = prim.fromBase64Url(m.ps)
+  return {...m, ps: b64(withS(sig, p256N - sAt(sig)))}
+})}))
+out.handshake.push(await runHandshake('no fingerprint in the remote description', {sdps: [sdpA, 'v=0\r\n', sdpB, sdpA]}))
+
+// The handshake's frames, as room.ts sends them through its internal actions `@_hsdata` (a step,
+// JSON) and `@_hsready` ('' when admitted, {ok: false, err} when refused), between two managers.
+out.handshake_frames = []
+for (const [name, action, data] of [['step 1', 'hsdata', JSON.parse(ok.messages[0].json)],
+  ['ready', 'hsready', ''], ['room full', 'hsready', {ok: false, err: 'room full'}],
+  ['banned', 'hsready', {ok: false, err: 'peer banned', reason: 'spam'}]]) {
+  const pair = wirePair(d => actionsMod.createActionManager(d), false)
+  const sending = pair.managers.A.makeInternalAction(action)
+  const receiving = pair.managers.B.makeInternalAction(action)
+  let received = null
+  receiving.onMessage(value => { received = value })
+  await sending.send(data, {target: 'B'})
+  const frames = await pair.frames()
+  out.handshake_frames.push({case: name, action: `@_${action}`, payload_json: prim.toJson(data), frames,
+    delivered: received !== null && prim.toJson(received) === prim.toJson(data)})
+}
+
+// A ping: room.ts's internal request action `@_ping`, a request of '' answered '' through
+// `@_response` (0.26.0's `@_pong` is gone), its id pinned as a request's is above.
+{
+  const pair = wirePair(d => actionsMod.createActionManager(d), false)
+  const asker = pair.managers.A.makeInternalRequestAction('ping')
+  const answerer = pair.managers.B.makeInternalRequestAction('ping')
+  answerer.onRequest(() => '')
+  const uuid = crypto.randomUUID
+  crypto.randomUUID = () => requestId
+  let response = null
+  try {
+    response = await asker.request('', {target: 'B'})
+  } finally {
+    crypto.randomUUID = uuid
+  }
+  out.ping_frames = {action: '@_ping', request_id: requestId, response, frames: await pair.frames()}
+}
+
+// The bounds of 0.27.0's identity caches and handshake: constants identity.ts, handshake.ts and
+// room.ts do not export, copied from them (identity.ts's maxSig*, createBoundedCache's 4096 default,
+// handshake.ts's defaultHandshakeTimeoutMs, maxBufferedHandshakeMessages and n.length < 16, and the
+// maxPayloadBytes of room.ts's hsdata and hsready actions).
+out.identity_limits = {pub_key_records: 4096, signature_cache_entries: 8192,
+  signature_cache_bytes: 2 * 1024 * 1024, signature_cache_payload_bytes: 4096,
+  handshake_timeout_ms: 10000, buffered_handshake_messages: 16, handshake_nonce_min_chars: 16,
+  hsdata_max_payload_bytes: 64 * 1024, hsready_max_payload_bytes: 128 * 1024}
+
+// Signatures in the order of their labels: concurrent signing finishes in any order.
+out.signatures = Object.fromEntries(Object.entries(out.signatures).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
+process.stdout.write(JSON.stringify(out, null, 1) + '\n')
diff --git a/test/oracle/twins/diff_already_joined.expected b/test/oracle/twins/diff_already_joined.expected
deleted file mode 100644
index 50acfd3..0000000
--- a/test/oracle/twins/diff_already_joined.expected
+++ /dev/null
@@ -1,2 +0,0 @@
-the first join: a room
-the second join: the room of the first join
diff --git a/test/oracle/twins/diff_already_joined.mjs b/test/oracle/twins/diff_already_joined.mjs
deleted file mode 100644
index fb4115c..0000000
--- a/test/oracle/twins/diff_already_joined.mjs
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright (c) 2026 WebCpp.org
-//
-// Distributed under the Boost Software License, Version 1.0. (See
-// accompanying file LICENSE_1_0.txt or copy at
-// https://www.boost.org/LICENSE_1_0.txt)
-
-import {joinRoom} from 'trystero'
-
-const config = {appId: 'webcpp-trystero-differences', relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]}}
-const first = joinRoom(config, 'lobby')
-const second = joinRoom(config, 'lobby')
-console.log('the first join: a room')
-console.log(`the second join: ${second === first ? 'the room of the first join' : 'another room'}`)
-await first.leave()
diff --git a/test/oracle/twins/diff_json_numbers.mjs b/test/oracle/twins/diff_json_numbers.mjs
index 45c1405..111a066 100644
--- a/test/oracle/twins/diff_json_numbers.mjs
+++ b/test/oracle/twins/diff_json_numbers.mjs
@@ -17,7 +17,7 @@ const config = {
 // The other peer, another page, which posts what it receives for this page to print.
 const other = openPage(async ({joinRoom, RTCPeerConnection, data, post, next}) => {
     const room = joinRoom({...data, rtcPolyfill: RTCPeerConnection}, 'lobby')
-    room.makeAction('payload').onMessage = received => post(received)
+    room.makeAction('payload').onMessage(received => post(received))
     await next()
     await room.leave()
 }, config)
@@ -30,7 +30,7 @@ const numbers = ['9007199254740993', '0.1000000000000000000000000000000001', '1e
 const text = `[${numbers.join(',')}]`
 // This page sends the payload its JSON text makes, once it meets the other peer.
 const payload = room.makeAction('payload')
-await new Promise(joined => (room.onPeerJoin = joined))
+await new Promise(joined => room.onPeerJoin(joined))
 await payload.send(JSON.parse(text))
 // What the other peer receives, number by number.
 const received = await other.next()
diff --git a/test/oracle/twins/diff_json_refused.mjs b/test/oracle/twins/diff_json_refused.mjs
index e207ef4..ff6dda8 100644
--- a/test/oracle/twins/diff_json_refused.mjs
+++ b/test/oracle/twins/diff_json_refused.mjs
@@ -28,7 +28,7 @@ const payloads = [
 const other = openPage(async ({joinRoom, RTCPeerConnection, data: {config, texts}, next}) => {
     const room = joinRoom({...config, rtcPolyfill: RTCPeerConnection}, 'lobby')
     const payload = room.makeAction('payload')
-    await new Promise(joined => (room.onPeerJoin = joined))
+    await new Promise(joined => room.onPeerJoin(joined))
     for (const text of texts) await payload.send(JSON.parse(text))
     await next()
     await room.leave()
@@ -40,10 +40,10 @@ const room = joinRoom({...config, rtcPolyfill: RTCPeerConnection}, 'lobby')
 const payload = room.makeAction('payload')
 const delivered = []
 await new Promise(last => {
-    payload.onMessage = ([label]) => {
+    payload.onMessage(([label]) => {
         delivered.push(label)
         if (label === payloads.at(-1)[0]) last()
-    }
+    })
 })
 for (const [label] of payloads) {
     console.log(`the payload ${label}: ${delivered.includes(label) ? 'delivered' : 'not delivered'}`)
diff --git a/test/oracle/twins/diff_passwords.mjs b/test/oracle/twins/diff_passwords.mjs
index 26ebc3d..fb78758 100644
--- a/test/oracle/twins/diff_passwords.mjs
+++ b/test/oracle/twins/diff_passwords.mjs
@@ -27,7 +27,7 @@ const other = openPage(async ({joinRoom, RTCPeerConnection, data, next}) => {
 const lobby = joinRoom({...config, password: 'one', rtcPolyfill: RTCPeerConnection}, 'lobby')
 const kitchen = joinRoom({...config, password: 'two', rtcPolyfill: RTCPeerConnection}, 'kitchen')
 // What the two rooms meet.
-const met = room => new Promise(joined => (room.onPeerJoin = joined))
+const met = room => new Promise(joined => room.onPeerJoin(({peerId}) => joined(peerId)))
 const [inLobby, inKitchen] = await Promise.all([met(lobby), met(kitchen)])
 console.log('the lobby, with the password "one": joined')
 console.log('the kitchen, with the password "two": joined')
diff --git a/test/oracle/twins/diff_peer_join.expected b/test/oracle/twins/diff_peer_join.expected
deleted file mode 100644
index a3a2255..0000000
--- a/test/oracle/twins/diff_peer_join.expected
+++ /dev/null
@@ -1,3 +0,0 @@
-the handler set before the join: called
-the handler set after the join: called
-peers: 1
diff --git a/test/oracle/twins/diff_peer_join.mjs b/test/oracle/twins/diff_peer_join.mjs
deleted file mode 100644
index a7d6e42..0000000
--- a/test/oracle/twins/diff_peer_join.mjs
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (c) 2026 WebCpp.org
-//
-// Distributed under the Boost Software License, Version 1.0. (See
-// accompanying file LICENSE_1_0.txt or copy at
-// https://www.boost.org/LICENSE_1_0.txt)
-
-import {joinRoom} from 'trystero'
-import {RTCPeerConnection} from 'werift'
-import {openPage} from '../page.mjs'
-
-// The peers meet on this machine alone: no ICE server, werift's WebRTC for Node.
-const config = {
-    appId: 'webcpp-trystero-differences',
-    relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]},
-    rtcConfig: {iceServers: []},
-}
-const other = openPage(async ({joinRoom, RTCPeerConnection, data, next}) => {
-    const room = joinRoom({...data, rtcPolyfill: RTCPeerConnection}, 'lobby')
-    await next()
-    await room.leave()
-}, config)
-const room = joinRoom({...config, rtcPolyfill: RTCPeerConnection}, 'lobby')
-
-// tag::example[]
-await new Promise(joined => {
-    room.onPeerJoin = () => {
-        console.log('the handler set before the join: called')
-        joined()
-    }
-})
-let lateCalls = 0
-room.onPeerJoin = () => ++lateCalls
-console.log(`the handler set after the join: ${lateCalls === 0 ? 'not called' : 'called'}`)
-console.log(`peers: ${Object.keys(room.getPeers()).length}`)
-// end::example[]
-other.post('leave')
-await Promise.all([room.leave(), other.done])
diff --git a/test/oracle/twins/diff_peers.expected b/test/oracle/twins/diff_peers.expected
index cb96a48..9c343c6 100644
--- a/test/oracle/twins/diff_peers.expected
+++ b/test/oracle/twins/diff_peers.expected
@@ -1,2 +1,2 @@
 peers: 1
-the joined peer's entry: its RTCPeerConnection
+the joined peer's entry: its user id, with its RTCPeerConnection
diff --git a/test/oracle/twins/diff_peers.mjs b/test/oracle/twins/diff_peers.mjs
index 0927f6c..885228a 100644
--- a/test/oracle/twins/diff_peers.mjs
+++ b/test/oracle/twins/diff_peers.mjs
@@ -23,11 +23,12 @@ const room = joinRoom({...config, rtcPolyfill: RTCPeerConnection}, 'lobby')
 
 // tag::example[]
 const peerId = await new Promise(joined => {
-    room.onPeerJoin = joined
+    room.onPeerJoin(({peerId}) => joined(peerId))
 })
 const peers = room.getPeers()
 console.log(`peers: ${Object.keys(peers).length}`)
-console.log(`the joined peer's entry: its ${peers[peerId].constructor.name}`)
+const {userId, connection} = peers[peerId]
+console.log(`the joined peer's entry: its ${userId ? 'user id' : 'nothing'}, with its ${connection.constructor.name}`)
 // end::example[]
 other.post('leave')
 await Promise.all([room.leave(), other.done])
diff --git a/test/oracle/twins/diff_relay_config.expected b/test/oracle/twins/diff_relay_config.expected
deleted file mode 100644
index 0e8fada..0000000
--- a/test/oracle/twins/diff_relay_config.expected
+++ /dev/null
@@ -1,4 +0,0 @@
-the lobby's relays: the first configuration's
-the kitchen's relays: the first configuration's
-the lobby's connection: the first configuration's ICE servers
-the kitchen's connection: the first configuration's ICE servers
diff --git a/test/oracle/twins/diff_relay_config.mjs b/test/oracle/twins/diff_relay_config.mjs
deleted file mode 100644
index 2559ffd..0000000
--- a/test/oracle/twins/diff_relay_config.mjs
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright (c) 2026 WebCpp.org
-//
-// Distributed under the Boost Software License, Version 1.0. (See
-// accompanying file LICENSE_1_0.txt or copy at
-// https://www.boost.org/LICENSE_1_0.txt)
-
-import {getRelaySockets, joinRoom} from 'trystero'
-import {RTCPeerConnection} from 'werift'
-import {openPage} from '../page.mjs'
-
-const relay = process.env.TRYSTERO_RELAY_URL
-const config = {appId: 'webcpp-trystero-differences', rtcPolyfill: RTCPeerConnection}
-// Two configurations. The second relay is the same local relay under a path, which it accepts as
-// it accepts any, and its STUN server one where nothing answers; the first has no ICE server, so
-// that the peers meet on this machine alone.
-const first = {relayConfig: {urls: [relay]}, rtcConfig: {iceServers: []}}
-const second = {
-    relayConfig: {urls: [`${relay}/second`]},
-    rtcConfig: {iceServers: [{urls: 'stun:127.0.0.1:19'}]},
-}
-// The other peer, another page: the lobby with the first configuration, then, once this page asks,
-// the kitchen with the second.
-const other = openPage(async ({joinRoom, RTCPeerConnection, data: {first, second}, next}) => {
-    const config = {appId: 'webcpp-trystero-differences', rtcPolyfill: RTCPeerConnection}
-    const lobby = joinRoom({...config, ...first}, 'lobby')
-    await next()
-    const kitchen = joinRoom({...config, ...second}, 'kitchen')
-    await next()
-    await Promise.all([lobby.leave(), kitchen.leave()])
-}, {first, second})
-// The configuration whose URLs, and only they, are `urls`, each configuration's read by `urlsOf`.
-const which = (urls, urlsOf) => {
-    const same = c => JSON.stringify([...urls].sort()) === JSON.stringify([...urlsOf(c)].sort())
-    return same(first) ? "the first configuration's" : same(second) ? "the second configuration's" : 'another'
-}
-// The relays the rooms use: the page's relay sockets, which every room of the page shares.
-const relaysOf = () => which(Object.keys(getRelaySockets()), c => c.relayConfig.urls)
-// The ICE servers of the connection a room meets a peer on.
-const iceUrls = rtcConfig => rtcConfig.iceServers.flatMap(server => [server.urls].flat())
-const iceServersOf = (room, peer) =>
-    which(iceUrls(room.getPeers()[peer].getConfiguration()), c => iceUrls(c.rtcConfig))
-const met = room => new Promise(joined => (room.onPeerJoin = joined))
-
-// tag::example[]
-// A configuration is a room's: each room is joined with its own.
-const lobby = joinRoom({...config, ...first}, 'lobby')
-const lobbyPeer = await met(lobby)
-// The kitchen, joined with the second configuration once the lobby has met the other peer.
-other.post('kitchen')
-const kitchen = joinRoom({...config, ...second}, 'kitchen')
-const kitchenPeer = await met(kitchen)
-console.log(`the lobby's relays: ${relaysOf()}`)
-console.log(`the kitchen's relays: ${relaysOf()}`)
-console.log(`the lobby's connection: ${iceServersOf(lobby, lobbyPeer)} ICE servers`)
-console.log(`the kitchen's connection: ${iceServersOf(kitchen, kitchenPeer)} ICE servers`)
-// end::example[]
-other.post('leave')
-await Promise.all([lobby.leave(), kitchen.leave(), other.done])
diff --git a/test/oracle/twins/diff_rooms_per_app.expected b/test/oracle/twins/diff_rooms_per_app.expected
deleted file mode 100644
index ba57790..0000000
--- a/test/oracle/twins/diff_rooms_per_app.expected
+++ /dev/null
@@ -1,4 +0,0 @@
-joins 1 to 64: 64 rooms
-join 65: a room
-join 66, while room 1 is leaving: a room
-join 67, once room 1 has left: a room
diff --git a/test/oracle/twins/diff_rooms_per_app.mjs b/test/oracle/twins/diff_rooms_per_app.mjs
deleted file mode 100644
index e54c353..0000000
--- a/test/oracle/twins/diff_rooms_per_app.mjs
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright (c) 2026 WebCpp.org
-//
-// Distributed under the Boost Software License, Version 1.0. (See
-// accompanying file LICENSE_1_0.txt or copy at
-// https://www.boost.org/LICENSE_1_0.txt)
-
-import {joinRoom} from 'trystero'
-
-const config = {appId: 'webcpp-trystero-differences', relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]}}
-const rooms = []
-// What a join gives, a room kept until the end or the error that refused it.
-const join = roomId => {
-    try {
-        rooms.push(joinRoom(config, roomId))
-        return 'a room'
-    } catch (error) {
-        return error.message
-    }
-}
-// tag::example[]
-for (let n = 1; n <= 64; ++n) join(`room-${n}`)
-console.log(`joins 1 to 64: ${rooms.length} rooms`)
-console.log(`join 65: ${join('room-65')}`)
-const leaving = rooms[0].leave()
-console.log(`join 66, while room 1 is leaving: ${join('room-66')}`)
-await leaving
-console.log(`join 67, once room 1 has left: ${join('room-67')}`)
-// end::example[]
-await Promise.all(rooms.slice(1).map(room => room.leave()))
diff --git a/test/oracle/twins/diff_self_id.expected b/test/oracle/twins/diff_self_id.expected
deleted file mode 100644
index c36229e..0000000
--- a/test/oracle/twins/diff_self_id.expected
+++ /dev/null
@@ -1,2 +0,0 @@
-two rooms of one app: one id
-rooms of two apps: one id
diff --git a/test/oracle/twins/diff_self_id.mjs b/test/oracle/twins/diff_self_id.mjs
deleted file mode 100644
index 56259df..0000000
--- a/test/oracle/twins/diff_self_id.mjs
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2026 WebCpp.org
-//
-// Distributed under the Boost Software License, Version 1.0. (See
-// accompanying file LICENSE_1_0.txt or copy at
-// https://www.boost.org/LICENSE_1_0.txt)
-
-import {joinRoom} from 'trystero'
-import {RTCPeerConnection} from 'werift'
-import {openPage} from '../page.mjs'
-
-// The peers meet on this machine alone: no ICE server, werift's WebRTC for Node.
-const config = {
-    relayConfig: {urls: [process.env.TRYSTERO_RELAY_URL]},
-    rtcConfig: {iceServers: []},
-}
-const firstApp = 'webcpp-trystero-differences'
-const secondApp = 'webcpp-trystero-differences-second'
-// The other peer, another page, in the rooms this page joins: it posts the id it meets first in
-// each.
-const other = openPage(async ({joinRoom, RTCPeerConnection, data, post, next}) => {
-    const {config, firstApp, secondApp} = data
-    const join = (appId, roomId) => joinRoom({...config, appId, rtcPolyfill: RTCPeerConnection}, roomId)
-    const rooms = [join(firstApp, 'lobby'), join(firstApp, 'kitchen'), join(secondApp, 'lobby')]
-    post(await Promise.all(rooms.map(room => new Promise(met => (room.onPeerJoin = met)))))
-    await next()
-    await Promise.all(rooms.map(room => room.leave()))
-}, {config, firstApp, secondApp})
-
-// tag::example[]
-// Every room of the page announces the page's selfId, which Trystero draws once, as it loads.
-const join = (appId, roomId) => joinRoom({...config, appId, rtcPolyfill: RTCPeerConnection}, roomId)
-const rooms = [join(firstApp, 'lobby'), join(firstApp, 'kitchen'), join(secondApp, 'lobby')]
-// What the other peer meets in those three rooms.
-const [inLobby, inKitchen, inSecondLobby] = await other.next()
-console.log(`two rooms of one app: ${inLobby === inKitchen ? 'one id' : 'two ids'}`)
-console.log(`rooms of two apps: ${inLobby === inSecondLobby ? 'one id' : 'two ids'}`)
-// end::example[]
-other.post('leave')
-await Promise.all([...rooms.map(room => room.leave()), other.done])
diff --git a/test/oracle/twins/diff_send_to_absent_peer.expected b/test/oracle/twins/diff_send_to_absent_peer.expected
index a4169e1..172bfba 100644
--- a/test/oracle/twins/diff_send_to_absent_peer.expected
+++ b/test/oracle/twins/diff_send_to_absent_peer.expected
@@ -1 +1 @@
-the send to a peer that has not joined: succeeded
+the send to a peer that has not joined: failed: Trystero: no active peer with id a-peer-that-has-not-joined
diff --git a/test/oracle/twins/quick_start.mjs b/test/oracle/twins/quick_start.mjs
index 3d2a7ec..bcbee16 100644
--- a/test/oracle/twins/quick_start.mjs
+++ b/test/oracle/twins/quick_start.mjs
@@ -8,8 +8,8 @@ import {joinRoom} from 'trystero'
 import {RTCPeerConnection} from 'werift'
 import {openPage} from '../page.mjs'
 
-// Trystero draws one selfId per page, so bob is another page, and each peer prints the other's
-// name where the C++ program prints the ids it gave its apps. The peers meet on this machine
+// Trystero has one peer id per app and page, so bob is another page, and each peer prints the
+// other's name where the C++ program prints the ids it gave its apps. The peers meet on this machine
 // alone: no ICE server, werift's WebRTC for Node.
 const config = {
     appId: 'webcpp-trystero-quick-start',
@@ -23,7 +23,7 @@ const bob = openPage(async ({joinRoom, RTCPeerConnection, data, post}) => {
     const room = joinRoom({...data, rtcPolyfill: RTCPeerConnection}, 'lobby')
     const chat = room.makeAction('chat')
     const [text, {peerId}] = await new Promise(received => {
-        chat.onMessage = (...message) => received(message)
+        chat.onMessage((...message) => received(message))
     })
     post(`alice: ${text}`)
     await chat.send('hello back', {target: peerId})
@@ -33,9 +33,9 @@ const bob = openPage(async ({joinRoom, RTCPeerConnection, data, post}) => {
 // alice greets each peer that joins, prints the answer, and leaves.
 const room = joinRoom({...config, rtcPolyfill: RTCPeerConnection}, 'lobby')
 const chat = room.makeAction('chat')
-room.onPeerJoin = peerId => chat.send('hello', {target: peerId})
+room.onPeerJoin(({peerId}) => chat.send('hello', {target: peerId}))
 const answer = new Promise(received => {
-    chat.onMessage = text => received(text)
+    chat.onMessage(text => received(text))
 })
 console.log(await bob.next())
 console.log(`bob: ${await answer}`)
diff --git a/test/oracle/twins/without-twin.txt b/test/oracle/twins/without-twin.txt
index b34e059..d4a5669 100644
--- a/test/oracle/twins/without-twin.txt
+++ b/test/oracle/twins/without-twin.txt
@@ -9,4 +9,3 @@
 # runs over a relay of its own on 127.0.0.1 (../run_twin.mjs): a relay is not
 # what keeps those below from one.
 chat/chat: a page: its program draws what happens in the room into the page, prints nothing, and runs as long as the tab; a twin would be a page too, with nothing printed to compare
-diff_self_id_not_utf8: Trystero JS draws its selfId when its module loads and takes none from a program, so no program of Trystero's can give it an id, nor one that is not UTF-8
diff --git a/test/oracle/vectors.py b/test/oracle/vectors.py
new file mode 100644
index 0000000..d63b6b5
--- /dev/null
+++ b/test/oracle/vectors.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python3
+# Copyright (c) 2026 WebCpp.org
+#
+# Distributed under the Boost Software License, Version 1.0. (See
+# accompanying file LICENSE_1_0.txt or copy at
+# https://www.boost.org/LICENSE_1_0.txt)
+
+"""Writes trystero's test vectors again from the published Trystero 0.27.0 packages.
+
+Usage: vectors.py PREVIOUS OUTPUT
+
+Runs `node record_0_27.mjs --dist node_modules PREVIOUS` beside this file, the recorder over the
+packages package-lock.json pins (@trystero-p2p/core and @trystero-p2p/nostr 0.27.0), and writes
+what it prints at OUTPUT. PREVIOUS is the committed fixture, test/fixtures/expected/
+trystero-0.27.0.json, whose WebCrypto signatures the recorder keeps while 0.27.0 still verifies
+them (design D19), so that the run writes the fixture again byte for byte exactly when the
+published packages compute what the pinned source computed: webcpp.generated runs it as the check
+generated-vectors of the oracle lane, and update-generated writes the fixture with it.
+
+One member is not 0.27.0's: `recorded_with`, the Node that recorded the fixture, which the
+recorder writes from the Node that runs it. The fixture's own value is kept, so that the check
+compares what the packages compute on any Node, the CI's pinned one included.
+
+The packages are installed first, as the oracle's other targets have them installed
+(tools/node/install.py, which installs once per lockfile and lets runs at once wait for one
+another), since webcpp.generated gives a generator no dependency on the install. Exit 0 when the
+output is written, 1 when the install or the recorder fails, 2 on a usage error.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+INSTALLER = HERE.parents[3] / 'tools/node/install.py'
+# The recorder's own line for the member: one space of indentation, as JSON.stringify(out, null, 1)
+# writes it, the second line of the file.
+RECORDED_WITH = re.compile(r'^ "recorded_with": (".*"),$', re.MULTILINE)
+
+
+def main(arguments: list[str]) -> int:
+    if len(arguments) != 2:
+        print('usage: vectors.py PREVIOUS OUTPUT', file=sys.stderr)
+        return 2
+    previous, output = (Path(a).resolve() for a in arguments)
+    installed = subprocess.run([sys.executable, str(INSTALLER), str(HERE)], check=False)
+    if installed.returncode != 0:
+        print(f'vectors.py: {INSTALLER} failed', file=sys.stderr)
+        return 1
+    recorded = subprocess.run(
+        ['node', 'record_0_27.mjs', '--dist', 'node_modules', str(previous)],
+        cwd=HERE, check=False, stdout=subprocess.PIPE)
+    if recorded.returncode != 0:
+        print('vectors.py: record_0_27.mjs failed', file=sys.stderr)
+        return 1
+    text = recorded.stdout.decode('utf-8')
+    kept = json.dumps(json.loads(previous.read_text(encoding='utf-8'))['recorded_with'])
+    text, replaced = RECORDED_WITH.subn(lambda _: f' "recorded_with": {kept},', text, count=1)
+    if replaced != 1:
+        print('vectors.py: the recorder wrote no recorded_with line', file=sys.stderr)
+        return 1
+    output.write_text(text, encoding='utf-8', newline='')
+    return 0
+
+
+if __name__ == '__main__':
+    sys.exit(main(sys.argv[1:]))
diff --git a/test/peer_link_test.cpp b/test/peer_link_test.cpp
new file mode 100644
index 0000000..ec0c98f
--- /dev/null
+++ b/test/peer_link_test.cpp
@@ -0,0 +1,409 @@
+// Copyright (c) 2026 WebCpp.org
+//
+// Distributed under the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// https://www.boost.org/LICENSE_1_0.txt)
+
+// One room's connection to one peer alone, over a memory pair: the frames it keeps before its room
+// binds it and 0.27.0's bounds on them (`peer.ts`'s `failData`), the bound on a frame once bound,
+// the drain waiters, and a disconnection's grace.
+
+#include 
+
+#include "support/memory_backend.hpp"
+
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "cases.hpp"
+#include "require.hpp"
+
+namespace asio = webcpp::asio;
+namespace trystero = webcpp::trystero;
+namespace detail = webcpp::trystero::detail;
+using namespace std::chrono_literals;
+
+namespace {
+
+/** The wall-clock ceiling of a wait for something that must happen: a hang guard, far above any
+ * loaded run, never what a case measures. */
+constexpr std::chrono::milliseconds hang_guard = 120s;
+
+bool run_until(asio::io_context& io, const std::function& done,
+               std::chrono::milliseconds limit = hang_guard) {
+    const auto end = std::chrono::steady_clock::now() + limit;
+    while (!done() && std::chrono::steady_clock::now() < end) {
+        io.run_for(10ms);  // lint-run: the memory network posts to it
+        if (io.stopped()) {
+            io.restart();
+        }
+    }
+    return done();
+}
+
+/** Runs the ready work of `io` until there is none: the memory network posts every frame. */
+void settle(asio::io_context& io) {
+    io.restart();
+    while (io.poll() > 0) {
+        io.restart();
+    }
+}
+
+/** A link to "B" over one end of a memory pair, on the virtual clock, and what its room heard: the
+ * frames handed over and the reason of its end. */
+struct link_pair {
+    asio::io_context io;
+    trystero::test::memory_network net{io};
+    std::size_t local_id = 0;  // the memory network's id of the link's connection
+    std::shared_ptr remote_pc;
+    std::shared_ptr remote;
+    std::shared_ptr link;
+    std::vector> got;
+    std::string ended;
+    std::size_t ends = 0;
+
+    link_pair();
+
+    /** Binds the link, recording what it hands over. */
+    void bind() {
+        const std::pmr::polymorphic_allocator<> alloc(std::pmr::get_default_resource());
+        link->bind({
+            .frame =
+                {
+                    std::allocator_arg,
+                    alloc,
+                    [this](trystero::backend::bytes frame) {
+                        got.emplace_back(frame.begin(), frame.end());
+                    },
+                },
+            .ended =
+                {
+                    std::allocator_arg,
+                    alloc,
+                    [this](std::string_view why) {
+                        ended = why;
+                        ++ends;
+                    },
+                },
+        });
+    }
+
+    /** Has the other end send a frame of `size` bytes, all `fill`, and delivers it. */
+    void receive(std::size_t size, std::uint8_t fill = 0) {
+        remote->send(std::vector(size, fill));
+        settle(io);
+    }
+};
+
+link_pair::link_pair() {
+    net.virtual_clock = true;  // the link's timers wait for advance()
+    auto* m = std::pmr::get_default_resource();
+    auto pc = net.make_peer_connection({}, m);
+    remote_pc = net.make_peer_connection({}, m);
+    local_id = std::static_pointer_cast(pc)->id();
+    auto local = pc->create_data_channel("data");
+    remote_pc->set_handlers({
+        .ice_candidate = {},
+        .data_channel =
+            [this](std::shared_ptr c) { remote = std::move(c); },
+        .state = {},
+    });
+    std::pmr::string offer(m);
+    std::pmr::string answer(m);
+    pc->set_local_description([&offer](trystero::backend::error_code, std::string_view,
+                                       std::string_view sdp) { offer = sdp; });
+    webcpp::test::require(BOOST_TEST(run_until(io, [&] { return !offer.empty(); })));
+    remote_pc->set_remote_description("offer", offer, [](trystero::backend::error_code) {});
+    remote_pc->set_local_description([&answer](trystero::backend::error_code, std::string_view,
+                                               std::string_view sdp) { answer = sdp; });
+    webcpp::test::require(BOOST_TEST(run_until(io, [&] { return !answer.empty(); })));
+    pc->set_remote_description("answer", answer, [](trystero::backend::error_code) {});
+    webcpp::test::require(
+        BOOST_TEST(run_until(io, [&] { return local->is_open() && remote && remote->is_open(); })));
+    remote_pc->set_handlers({});
+    link = detail::peer_link::make("B", std::move(pc), std::move(local), net, m);
+}
+
+// Frames that arrive before the room binds the link are kept, and handed over in their order when
+// it binds; a frame after the bind goes straight through.
+void frames_before_bind_are_kept_in_order() {
+    link_pair p;
+    p.receive(3, 1);
+    p.receive(4, 2);
+    p.receive(5, 3);
+    BOOST_TEST_EQ(p.link->pending_count(), 3U);
+    BOOST_TEST(p.got.empty());
+    p.bind();
+    BOOST_TEST_EQ(p.link->pending_count(), 0U);
+    webcpp::test::require(BOOST_TEST_EQ(p.got.size(), 3U));
+    BOOST_TEST(p.got[0] == (std::vector(3, 1)));
+    BOOST_TEST(p.got[1] == (std::vector(4, 2)));
+    BOOST_TEST(p.got[2] == (std::vector(5, 3)));
+    p.receive(6, 4);
+    BOOST_TEST_EQ(p.got.size(), 4U);
+    BOOST_TEST(p.link->live());
+    BOOST_TEST_EQ(p.ends, 0U);
+}
+
+// A frame whose call ends the link stops the replay of the frames kept: none after it is handed
+// over, and the end is reported once.
+void a_frame_that_ends_the_link_stops_the_replay() {
+    link_pair p;
+    p.receive(1, 1);
+    p.receive(1, 2);
+    p.receive(1, 3);
+    const std::pmr::polymorphic_allocator<> alloc(std::pmr::get_default_resource());
+    p.link->bind({
+        .frame =
+            {
+                std::allocator_arg,
+                alloc,
+                [&p](trystero::backend::bytes frame) {
+                    p.got.emplace_back(frame.begin(), frame.end());
+                    if (p.got.size() == 2) {
+                        p.link->end("ended by the room");
+                    }
+                },
+            },
+        .ended =
+            {
+                std::allocator_arg,
+                alloc,
+                [&p](std::string_view why) {
+                    p.ended = why;
+                    ++p.ends;
+                },
+            },
+    });
+    BOOST_TEST_EQ(p.got.size(), 2U);
+    BOOST_TEST_EQ(p.ends, 1U);
+    BOOST_TEST_EQ(p.ended, "ended by the room");
+    BOOST_TEST(!p.link->live());
+}
+
+// The link keeps 64 frames before its bind, 0.27.0's maxQueuedDataFrames; a 65th ends it, and a
+// room that binds it then hears of its end at once.
+void a_65th_pending_frame_ends_the_link() {
+    link_pair p;
+    for (std::size_t i = 0; i < detail::peer_link::max_pending_frames; ++i) {
+        p.receive(1);
+    }
+    BOOST_TEST_EQ(p.link->pending_count(), 64U);
+    BOOST_TEST(p.link->live());
+    p.receive(1);
+    BOOST_TEST(!p.link->live());
+    BOOST_TEST_EQ(p.link->pending_count(), 0U);
+    BOOST_TEST(!p.remote->is_open());  // the other end sees the close
+    p.bind();
+    BOOST_TEST_EQ(p.ends, 1U);
+    BOOST_TEST_EQ(p.ended, "excessive pre-handler data");
+    BOOST_TEST(p.got.empty());
+}
+
+// The first frame kept starts 10 s, 0.27.0's pendingDataTimeoutMs, after which the link ends
+// unless its room has bound it.
+void pending_frames_end_the_link_after_10_s() {
+    {
+        link_pair p;
+        p.receive(1);
+        BOOST_TEST(p.net.advance(9'999ms));
+        BOOST_TEST(p.link->live());
+        BOOST_TEST(p.net.advance(1ms));
+        BOOST_TEST(!p.link->live());
+    }
+    {
+        link_pair p;
+        p.receive(1);
+        BOOST_TEST(p.net.advance(5'000ms));
+        p.bind();
+        BOOST_TEST(p.net.advance(10'000ms));
+        BOOST_TEST(p.link->live());
+        BOOST_TEST_EQ(p.got.size(), 1U);
+        BOOST_TEST_EQ(p.ends, 0U);
+    }
+}
+
+// Before its bind the link keeps a frame of at most 17,408 bytes, 0.27.0's maxRoomFrameBytes; one
+// byte more ends it.
+void an_unbound_frame_above_17_kib_ends_the_link() {
+    {
+        link_pair p;
+        p.receive(17'408);
+        BOOST_TEST(p.link->live());
+        BOOST_TEST_EQ(p.link->pending_count(), 1U);
+    }
+    link_pair p;
+    p.receive(17'409);
+    BOOST_TEST(!p.link->live());
+    p.bind();
+    BOOST_TEST_EQ(p.ended, "excessive pre-handler data");
+}
+
+// Once bound, a frame of 65,536 bytes, 0.27.0's maxBulkFrameBytes, goes through, and one byte more
+// ends the link.
+void a_bound_frame_above_64_kib_ends_the_link() {
+    link_pair p;
+    p.bind();
+    p.receive(65'536);
+    BOOST_TEST_EQ(p.got.size(), 1U);
+    BOOST_TEST(p.link->live());
+    p.receive(65'537);
+    BOOST_TEST_EQ(p.got.size(), 1U);
+    BOOST_TEST(!p.link->live());
+    BOOST_TEST_EQ(p.ends, 1U);
+    BOOST_TEST_EQ(p.ended, "excessive pre-handler data");
+}
+
+// A disconnection ends the link after 5 s, as 0.27.0's grace; a reconnection before then cancels
+// it, and a second disconnection while the grace runs does not extend it, as 0.27.0 starts the
+// grace only from an open connection (its connection and ICE states both report one).
+void a_disconnected_state_ends_after_its_grace() {
+    {
+        link_pair p;
+        p.bind();
+        p.net.disconnect(p.local_id);
+        BOOST_TEST(p.net.advance(4'000ms));
+        p.net.disconnect(p.local_id);
+        BOOST_TEST(p.net.advance(999ms));
+        BOOST_TEST_EQ(p.ends, 0U);
+        BOOST_TEST(p.net.advance(1ms));
+        BOOST_TEST_EQ(p.ended, "connection lost");
+    }
+    {
+        // Once a reconnection cancelled it, the next disconnection has a grace of its own.
+        link_pair p;
+        p.bind();
+        p.net.disconnect(p.local_id);
+        BOOST_TEST(p.net.advance(4'000ms));
+        p.net.reconnect(p.local_id);
+        p.net.disconnect(p.local_id);
+        BOOST_TEST(p.net.advance(4'999ms));
+        BOOST_TEST_EQ(p.ends, 0U);
+        BOOST_TEST(p.net.advance(1ms));
+        BOOST_TEST_EQ(p.ended, "connection lost");
+    }
+    {
+        link_pair p;
+        p.bind();
+        p.net.disconnect(p.local_id);
+        BOOST_TEST(p.net.advance(4'999ms));
+        BOOST_TEST_EQ(p.ends, 0U);
+        BOOST_TEST(p.net.advance(1ms));
+        BOOST_TEST_EQ(p.ended, "connection lost");
+    }
+    link_pair p;
+    p.bind();
+    p.net.disconnect(p.local_id);
+    BOOST_TEST(p.net.advance(4'000ms));
+    p.net.reconnect(p.local_id);
+    BOOST_TEST(p.net.advance(10'000ms));
+    BOOST_TEST_EQ(p.ends, 0U);
+    BOOST_TEST(p.link->live());
+}
+
+// A failed connection, and a closed channel, end the link at once, once.
+void the_transport_ends_the_link_once() {
+    {
+        link_pair p;
+        p.bind();
+        p.net.fail(p.local_id);
+        settle(p.io);
+        BOOST_TEST_EQ(p.ends, 1U);
+        BOOST_TEST_EQ(p.ended, "connection failed");
+    }
+    link_pair p;
+    p.bind();
+    p.remote->close();
+    settle(p.io);
+    BOOST_TEST_EQ(p.ends, 1U);
+    BOOST_TEST_EQ(p.ended, "data channel closed");
+    p.link->end("again");
+    BOOST_TEST_EQ(p.ends, 1U);
+}
+
+/** A waiter that records `name`, or `!name` when told the channel closed. */
+trystero::handler record(std::vector& turns, std::string name) {
+    return {std::allocator_arg, std::pmr::polymorphic_allocator<>(std::pmr::get_default_resource()),
+            [&turns, name = std::move(name)](bool open) {
+                turns.emplace_back(open ? name : "!" + name);
+            }};
+}
+
+// The drain waiters complete in the order they began to wait once the channel drains; the end
+// fails those still waiting, and every later wait at once.
+void drain_waiters_complete_in_order_and_fail_at_the_end() {
+    link_pair p;
+    p.bind();
+    std::vector turns;
+    p.link->wait_drained(record(turns, "empty"));
+    BOOST_TEST(turns == (std::vector{"empty"}));
+    p.net.channel_capacity = 1;
+    const std::vector frame(16'000, 0);
+    const auto fill = [&] {
+        for (std::size_t i = 0; i < 5; ++i) {
+            BOOST_TEST(p.link->send(frame));
+        }
+        webcpp::test::require(BOOST_TEST_GT(p.link->buffered_amount(),
+                                            trystero::backend::data_channel::low_threshold));
+    };
+    fill();
+    p.link->wait_drained(record(turns, "a"));
+    p.link->wait_drained(record(turns, "b"));
+    BOOST_TEST(run_until(p.io, [&] { return turns.size() == 3; }));
+    BOOST_TEST(turns == (std::vector{"empty", "a", "b"}));
+    fill();
+    p.link->wait_drained(record(turns, "c"));
+    p.link->end("test");
+    BOOST_TEST(turns == (std::vector{"empty", "a", "b", "!c"}));
+    BOOST_TEST_EQ(p.ended, "test");
+    BOOST_TEST(!p.link->send(frame));
+    BOOST_TEST_EQ(p.link->buffered_amount(), 0U);
+    p.link->wait_drained(record(turns, "late"));
+    BOOST_TEST_EQ(turns.back(), "!late");
+}
+
+// A transfer's chunks may fill 64 KiB, 0.27.0's maxBulkFrameBytes getter, when the connection's
+// SCTP takes messages of 64 KiB at least, and 16 KiB otherwise or when it does not say.
+void the_bulk_frame_bound_follows_the_connections_message_size() {
+    link_pair p;
+    namespace tp = trystero::protocol;
+    BOOST_TEST_EQ(p.link->max_bulk_frame_bytes(), tp::max_bulk_frame_bytes);
+    p.net.max_message_size = tp::max_bulk_frame_bytes;
+    BOOST_TEST_EQ(p.link->max_bulk_frame_bytes(), tp::max_bulk_frame_bytes);
+    p.net.max_message_size = tp::max_bulk_frame_bytes - 1;
+    BOOST_TEST_EQ(p.link->max_bulk_frame_bytes(), tp::max_action_frame_bytes);
+    p.net.max_message_size = std::nullopt;
+    BOOST_TEST_EQ(p.link->max_bulk_frame_bytes(), tp::max_action_frame_bytes);
+}
+
+}  // namespace
+
+int main() {
+    using webcpp::test::run_case;
+    run_case(frames_before_bind_are_kept_in_order);
+    run_case(a_frame_that_ends_the_link_stops_the_replay);
+    run_case(a_65th_pending_frame_ends_the_link);
+    run_case(pending_frames_end_the_link_after_10_s);
+    run_case(an_unbound_frame_above_17_kib_ends_the_link);
+    run_case(a_bound_frame_above_64_kib_ends_the_link);
+    run_case(a_disconnected_state_ends_after_its_grace);
+    run_case(the_transport_ends_the_link_once);
+    run_case(drain_waiters_complete_in_order_and_fail_at_the_end);
+    run_case(the_bulk_frame_bound_follows_the_connections_message_size);
+    // Under Asyncify, a main that suspended loses what it returns: the status goes first.
+    return webcpp::test::exit_status(boost::report_errors());
+}
diff --git a/test/platform_backend_test.cpp b/test/platform_backend_test.cpp
index dc43d1a..6a89e13 100644
--- a/test/platform_backend_test.cpp
+++ b/test/platform_backend_test.cpp
@@ -12,13 +12,22 @@
 //   and its runtime in the default resource.
 // - Its clocks are the standard library's: the wall clock's whole seconds, as the test reads them,
 //   and the steady clock, which a 20 ms wait moves forward.
-// - Its randomness fills what it is given, differently each time, also beyond a piece of the
-//   platform's source (65536 bytes in a page).
+// - Its randomness, webcpp::crypto's random_device, fills what it is given, differently each time,
+//   also beyond a piece of the platform's source (256 bytes of the system's entropy call).
+// - Its PBKDF2 of a room's password is 0.27.0's master, derived off the room's thread, natively on
+//   a thread of its own and in a page through WebCrypto, and completes on its executor after the
+//   call returned; destroyed during a derivation, it waits for it.
 // - Its executor is the one it was given, and its relays' TLS context was made.
+// - It watches no connectivity natively, where no `online` or `offline` event exists, nor under
+//   node, whose global object takes no listener: an app's automatic relays stay online
+//   (platform_page_connectivity tests a page's events).
 //
-// main runs the io_context for the wait; a wait that does not come within 10 s fails by name.
+// main runs the io_context for the wait; a wait that does not come within 10 s fails by name. A
+// derivation's run waits for its completion however long the loaded machine takes.
 
 #include 
+#include 
+#include 
 
 #include 
 #include 
@@ -35,6 +44,8 @@
 #include 
 #include 
 #include 
+#include 
+#include 
 #include 
 
 #include "bookkeeping.hpp"
@@ -161,6 +172,72 @@ void its_randomness_fills_more_than_a_piece() {
     BOOST_TEST_EQ(repeated, 0U);
 }
 
+/** The bytes of a text, as a span. */
+std::span bytes_of(std::string_view text) {
+    return {reinterpret_cast(text.data()), text.size()};
+}
+
+// The master of the password "hunter2" in the room "lobby" of "example.com/app", as 0.27.0
+// derived it (fixtures/expected/trystero-0.27.0.json, room_keys_password), completed after the
+// call returned and on the io_context's thread; natively the io_context runs one handler for it.
+// Where the 600,000 iterations run (the backend's own thread natively, crypto.subtle in a page)
+// is the backend's design, which this case does not observe.
+void its_pbkdf2_is_trysteros_and_completes_on_the_io_context() {
+    asio::io_context io;
+    trystero::platform::backend backend(io.get_executor());
+    const auto salt = trystero::protocol::pbkdf2_salt("example.com/app", "lobby");
+    std::array master{};
+    bool returned = false;
+    std::optional done;
+    std::thread::id ran_on;
+    backend.derive_password_master(bytes_of("hunter2"), salt, master,
+                                   [&](boost::system::error_code ec) {
+                                       BOOST_TEST(returned);
+                                       done = ec;
+                                       ran_on = std::this_thread::get_id();
+                                   });
+    returned = true;
+#ifndef WEBCPP_TARGET_EMSCRIPTEN
+    BOOST_TEST_EQ(io.run_one(), 1U);  // lint-run: one handler, however long the work takes
+    BOOST_TEST(done.has_value());
+#endif
+    io.run();  // lint-run: the derivation's completion, however long it takes
+    if (BOOST_TEST(done.has_value())) {
+        BOOST_TEST(!*done);
+    }
+    BOOST_TEST(ran_on == std::this_thread::get_id());
+    BOOST_TEST_EQ(trystero::protocol::to_hex(master),
+                  "0a9daa6bbfe5e7a974b8ab2030704abcd09c0451a3e189a4bf5cda230e8fa8a7");
+}
+
+// A backend destroyed while its thread derives, a second derivation queued behind the first,
+// waits for both, whose completions then wait in the io_context, which runs them.
+void its_destruction_waits_for_a_derivation() {
+    asio::io_context io;
+    const auto salt = trystero::protocol::pbkdf2_salt("example.com/app", "lobby");
+    std::array first{};
+    std::array second{};
+    std::optional first_done;
+    std::optional second_done;
+    {
+        trystero::platform::backend backend(io.get_executor());
+        backend.derive_password_master(bytes_of("hunter2"), salt, first,
+                                       [&](boost::system::error_code ec) { first_done = ec; });
+        backend.derive_password_master(bytes_of("hunter2"), salt, second,
+                                       [&](boost::system::error_code ec) { second_done = ec; });
+    }
+    io.run();  // lint-run: the derivations' completions
+    for (const auto* done : {&first_done, &second_done}) {
+        if (BOOST_TEST(done->has_value())) {
+            BOOST_TEST(!**done);
+        }
+    }
+    for (const auto* master : {&first, &second}) {
+        BOOST_TEST_EQ(trystero::protocol::to_hex(*master),
+                      "0a9daa6bbfe5e7a974b8ab2030704abcd09c0451a3e189a4bf5cda230e8fa8a7");
+    }
+}
+
 void its_executor_and_tls_context_are_there() {
     asio::io_context io;
     trystero::platform::backend backend(io.get_executor());
@@ -168,6 +245,17 @@ void its_executor_and_tls_context_are_there() {
     BOOST_TEST(backend.tls_context().has_value());
 }
 
+void it_watches_no_connectivity_without_a_page() {
+    asio::io_context io;
+    trystero::platform::backend backend(io.get_executor());
+    bool called = false;
+    const auto watch = backend.watch_connectivity([&called](bool) { called = true; },
+                                                  std::pmr::get_default_resource());
+    BOOST_TEST(watch == nullptr);
+    io.run_for(20ms);  // lint-run: nothing is posted
+    BOOST_TEST(!called);
+}
+
 }  // namespace
 
 int main() {
@@ -177,6 +265,9 @@ int main() {
     run_case(its_clocks_are_the_standard_librarys);
     run_case(its_randomness_fills_and_differs);
     run_case(its_randomness_fills_more_than_a_piece);
+    run_case(its_pbkdf2_is_trysteros_and_completes_on_the_io_context);
+    run_case(its_destruction_waits_for_a_derivation);
     run_case(its_executor_and_tls_context_are_there);
+    run_case(it_watches_no_connectivity_without_a_page);
     return webcpp::test::exit_status(boost::report_errors());
 }
diff --git a/test/platform_page_connectivity_test.cpp b/test/platform_page_connectivity_test.cpp
new file mode 100644
index 0000000..a02a7d0
--- /dev/null
+++ b/test/platform_page_connectivity_test.cpp
@@ -0,0 +1,101 @@
+// Copyright (c) 2026 WebCpp.org
+//
+// Distributed under the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// https://www.boost.org/LICENSE_1_0.txt)
+
+// Tests that the platform backend in a page watches the page's `online` and `offline` events,
+// under node, over a stand-in for a window's events on the global object (node's takes no
+// listener): the watch adds a listener of each, each event posts its handler with `true` or
+// `false` to the io_context, which runs it after the event, never inside it, and the watch's
+// destruction removes both listeners, so that a later event reaches nothing.
+
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+namespace asio = webcpp::asio;
+namespace trystero = webcpp::trystero;
+
+// The stand-in: the global object takes listeners as a window does, counts those added and not
+// removed, the same function, and fires an event of a type on demand.
+// clang-format off
+// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type)
+EM_JS(void, install_page_events, (), {
+    const target = new EventTarget();
+    const held = new Map();  // by type, the functions added and not removed
+    globalThis.addEventListener = (type, f) => {
+        if (!held.has(type)) held.set(type, new Set());
+        held.get(type).add(f);
+        target.addEventListener(type, f);
+    };
+    globalThis.removeEventListener = (type, f) => {
+        if (held.has(type)) held.get(type).delete(f);
+        target.removeEventListener(type, f);
+    };
+    globalThis.heldListeners = () => [...held.values()].reduce((n, s) => n + s.size, 0);
+    globalThis.firePageEvent = type => target.dispatchEvent(new Event(type));
+});
+// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type)
+EM_JS(int, held_listeners, (), { return globalThis.heldListeners(); });
+// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type)
+EM_JS(void, fire_page_event, (const char* type), { globalThis.firePageEvent(UTF8ToString(type)); });
+// clang-format on
+
+namespace {
+
+/** Runs what is ready on `io` until nothing is. */
+void settle(asio::io_context& io) {
+    io.restart();
+    while (io.poll() > 0) {  // lint-run: the page's events post to it
+        io.restart();
+    }
+}
+
+}  // namespace
+
+int main() {
+    install_page_events();
+    asio::io_context io;
+    trystero::platform::backend backend(io.get_executor());
+    std::vector changes;
+    bool inside_an_event = false;
+    auto watch = backend.watch_connectivity(
+        [&](bool online) {
+            changes.push_back(online);
+            inside_an_event =
+                inside_an_event || asio::use_service(io).delivering();
+        },
+        std::pmr::get_default_resource());
+    if (!BOOST_TEST(watch != nullptr)) {
+        return webcpp::test::exit_status(boost::report_errors());
+    }
+    BOOST_TEST_EQ(held_listeners(), 2);
+
+    fire_page_event("offline");
+    fire_page_event("online");
+    BOOST_TEST(changes.empty());  // each event only posts
+    settle(io);
+    BOOST_TEST((changes == std::vector{false, true}));
+    BOOST_TEST(!inside_an_event);
+
+    fire_page_event("visibilitychange");  // not watched
+    settle(io);
+    BOOST_TEST_EQ(changes.size(), 2U);
+
+    fire_page_event("offline");
+    watch.reset();  // the posted call reaches nothing once the watch is gone
+    BOOST_TEST_EQ(held_listeners(), 0);
+    fire_page_event("online");
+    settle(io);
+    BOOST_TEST_EQ(changes.size(), 2U);
+    return webcpp::test::exit_status(boost::report_errors());
+}
diff --git a/test/platform_page_data_channel_test.cpp b/test/platform_page_data_channel_test.cpp
index b413cce..055d92d 100644
--- a/test/platform_page_data_channel_test.cpp
+++ b/test/platform_page_data_channel_test.cpp
@@ -5,15 +5,15 @@
 // https://www.boost.org/LICENSE_1_0.txt)
 
 // Tests the platform backend's data channels in a page, webcpp::webrtc's, under node, over plain
-// objects in
-// place of the page's RTCPeerConnection and RTCDataChannel: what a peer can send that is no frame
-// is dropped. A text message "1e300" once threw a RangeError out of `new Uint8Array`, and
-// "300000000" made a 300 MB frame: webcpp::webrtc delivers a text as the few bytes it holds, which
-// the channel drops; a binary message larger than any room frame is dropped too. Only the frame
-// sent last reaches the handler, and nothing larger than the largest message sent is allocated.
+// objects in place of the page's RTCPeerConnection and RTCDataChannel: what a peer can send that
+// is no frame closes the channel, as 0.27.0's failData closes it, and reaches no handler. A text
+// message "1e300" once threw a RangeError out of `new Uint8Array`, and "300000000" made a 300 MB
+// frame: webcpp::webrtc delivers a text as the few bytes it holds, which closes the channel; so
+// does a binary message larger than any frame, a wide chunk's 64 KiB. A frame of 3 bytes reaches
+// the handler, and nothing larger than the largest message sent is allocated.
 //
-// main runs the io_context under a work guard, which the verdict releases when the last frame
-// arrives; a frame that does not come within 10 s fails by name.
+// Each case runs its io_context under a work guard, which the verdict releases when the frame
+// arrives or the channel closes; a verdict that does not come within 10 s fails by name.
 
 #include 
 
@@ -69,6 +69,7 @@ struct state {
     std::shared_ptr wrapper;
     std::size_t messages = 0;
     std::size_t last_size = 0;
+    std::size_t closes = 0;
 };
 
 /** Delivers `data` to the channel's `onmessage` from a timer, as the page delivers a message. */
@@ -78,12 +79,52 @@ void deliver(const val& data) {
     val::global("setTimeout")(val::global("lastChannel")["onmessage"], val(0), event);
 }
 
+/** Makes a channel, hands it `data` as the page's only message, and runs until the frame arrives
+ * or the channel closes. */
+void receive_one(state& s, const val& data) {
+    s.connection = s.backend.make_peer_connection({}, &s.memory);
+    webcpp::test::require(BOOST_TEST(s.connection != nullptr));
+    s.wrapper = s.connection->create_data_channel("data");
+    webcpp::test::require(BOOST_TEST(s.wrapper != nullptr));
+    s.wrapper->set_handlers({
+        .open = {},
+        .message =
+            [&s](const trystero::backend::bytes& frame) {
+                ++s.messages;
+                s.last_size = frame.size();
+                s.guard.reset();
+                s.io.stop();
+            },
+        .close =
+            [&s] {
+                ++s.closes;
+                s.guard.reset();
+                s.io.stop();
+            },
+        .buffered_amount_low = {},
+    });
+    deliver(data);
+    s.io.run_for(10s);  // lint-run: the case's event loop, held by its work guard until the verdict
+    if (s.messages + s.closes == 0) {
+        BOOST_ERROR("the message neither arrived nor closed the channel");
+    }
+}
+
+/** What is no frame closes the channel, and reaches no handler. */
+void no_frame_closes_the_channel(const val& data) {
+    state s;
+    receive_one(s, data);
+    BOOST_TEST_EQ(s.messages, 0U);
+    BOOST_TEST_EQ(s.closes, 1U);
+    BOOST_TEST(!s.wrapper->is_open());
+    BOOST_TEST_LE(s.memory.largest, std::size_t{70'000});
+}
+
 }  // namespace
 
 int main() {
-    state s;
-    // A connection whose channel is open from the start, and which the test reaches as
-    // lastChannel.
+    // A connection whose channel is open from the start, which the test reaches as lastChannel,
+    // and whose close is reported after it, as a page's is.
     EM_ASM({
         globalThis.RTCPeerConnection = class {
             constructor() {
@@ -98,42 +139,29 @@ int main() {
                 channel.readyState = 'open';
                 channel.bufferedAmount = 0;
                 channel.send = function(){};
-                channel.close = function(){};
+                // clang-format off
+                channel.close = function() {
+                    if (channel.readyState != 'closed') {
+                        channel.readyState = 'closed';
+                        setTimeout(function() { if (channel.onclose) channel.onclose(); }, 0);
+                    }
+                };
+                // clang-format on
                 globalThis.lastChannel = channel;
                 return channel;
             }
             close() {}
         };
     });
-    s.connection = s.backend.make_peer_connection({}, &s.memory);
-    webcpp::test::require(BOOST_TEST(s.connection != nullptr));
-    s.wrapper = s.connection->create_data_channel("data");
-    webcpp::test::require(BOOST_TEST(s.wrapper != nullptr));
-    s.wrapper->set_handlers({
-        .open = {},
-        .message =
-            [&s](const trystero::backend::bytes& frame) {
-                ++s.messages;
-                s.last_size = frame.size();
-                s.guard.reset();
-                s.io.stop();
-            },
-        .close = {},
-        .buffered_amount_low = {},
-    });
-
-    deliver(val("1e300"));
-    deliver(val("300000000"));
-    deliver(val::global("ArrayBuffer").new_(val(20'000)));
-    deliver(val::global("ArrayBuffer").new_(val(3)));
-
-    s.io.run_for(10s);  // lint-run: the test's event loop, held by its work guard until the verdict
-    if (s.messages == 0) {
-        BOOST_ERROR("the frame sent last never arrived");
+    no_frame_closes_the_channel(val("1e300"));
+    no_frame_closes_the_channel(val("300000000"));
+    no_frame_closes_the_channel(val::global("ArrayBuffer").new_(val(70'000)));
+    {
+        state s;
+        receive_one(s, val::global("ArrayBuffer").new_(val(3)));
+        BOOST_TEST_EQ(s.messages, 1U);
+        BOOST_TEST_EQ(s.last_size, 3U);
+        BOOST_TEST_EQ(s.closes, 0U);
     }
-    // The first frame to arrive is the last one sent: the run stopped there.
-    BOOST_TEST_EQ(s.messages, 1U);
-    BOOST_TEST_EQ(s.last_size, 3U);
-    BOOST_TEST_LE(s.memory.largest, std::size_t{20'000});
     return webcpp::test::exit_status(boost::report_errors());
 }
diff --git a/test/platform_page_entropy_test.cpp b/test/platform_page_entropy_test.cpp
new file mode 100644
index 0000000..f5171aa
--- /dev/null
+++ b/test/platform_page_entropy_test.cpp
@@ -0,0 +1,91 @@
+// Copyright (c) 2026 WebCpp.org
+//
+// Distributed under the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// https://www.boost.org/LICENSE_1_0.txt)
+
+// Tests an app in a page without the browser's generator, under node: once with no `crypto` at
+// all, and once with a `crypto.getRandomValues` that throws, as a page whose generator is missing
+// or broken has it. The app cannot make its endpoint key nor its ephemeral user's, so each room it
+// joins reports `error::identity_failed`, as 0.27.0's `failSetup` reports `identity-failed`, and
+// no JavaScript exception enters WebAssembly: one would end main unfinished, and the run with it.
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+
+namespace asio = webcpp::asio;
+namespace trystero = webcpp::trystero;
+
+// The page's generator, taken away (`mode` 0: no `crypto`) or broken (1: its `getRandomValues`
+// throws), and given back.
+// clang-format off
+// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type)
+EM_JS(void, break_generator, (int mode), {
+    if (globalThis.savedCrypto === undefined) globalThis.savedCrypto = globalThis.crypto;
+    const broken = mode === 0 ? undefined : {
+        getRandomValues() { throw new Error('the generator is broken'); },
+        subtle: globalThis.savedCrypto.subtle,
+    };
+    Object.defineProperty(globalThis, 'crypto', {value: broken, configurable: true, writable: true});
+});
+// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type)
+EM_JS(void, restore_generator, (), {
+    Object.defineProperty(globalThis, 'crypto', {value: globalThis.savedCrypto, configurable: true, writable: true});
+});
+// clang-format on
+
+namespace {
+
+/** Runs what is ready on `io` until nothing is. */
+void settle(asio::io_context& io) {
+    io.restart();
+    while (io.poll() > 0) {  // lint-run: the room's reports post to it
+        io.restart();
+    }
+}
+
+/** Joins a room of an app made without a generator, and checks what the room reports. */
+void without_generator(int mode) {
+    break_generator(mode);
+    asio::io_context io;
+    trystero::platform::backend backend(io.get_executor());
+    trystero::app_config config;
+    config.app_id = "webcpp-trystero-entropy";
+    config.relay_urls.emplace_back("ws://127.0.0.1:9");
+    std::optional app;
+    app.emplace(io.get_executor(), backend, std::move(config));
+    BOOST_TEST(app->self_id().empty());
+    BOOST_TEST(app->user_id().empty());
+    std::vector reports;
+    auto joined = app->join("room");
+    BOOST_TEST(joined.has_value());
+    if (joined) {
+        joined->on_error([&](const trystero::room_error& e) {
+            reports.emplace_back(trystero::room_error_code_name(e.code));
+        });
+    }
+    settle(io);
+    restore_generator();
+    BOOST_TEST_EQ(reports.size(), 1U);
+    BOOST_TEST(!reports.empty() && reports.front() == "identity-failed");
+}
+
+}  // namespace
+
+int main() {
+    without_generator(0);
+    without_generator(1);
+    return webcpp::test::exit_status(boost::report_errors());
+}
diff --git a/test/platform_page_handlers_test.cpp b/test/platform_page_handlers_test.cpp
index 6cf91e9..1547227 100644
--- a/test/platform_page_handlers_test.cpp
+++ b/test/platform_page_handlers_test.cpp
@@ -6,18 +6,18 @@
 
 // Tests that the platform backend's handlers in a page run outside the page's events, under node:
 // a relay socket's open, message and close handlers, over a stand-in for the page's WebSocket, and
-// a sealer's completions of a seal and an open, through the page's Web Crypto, each find
-// webcpp::asio's bridge delivering nothing (`bridge::delivering()` false): the page's event, or the
+// the completion of a password's PBKDF2, through the page's WebCrypto, each find webcpp::asio's
+// bridge delivering nothing (`bridge::delivering()` false): the page's event, or the
 // settlement of a promise, only posts to the io_context, and the run family runs the handler after
 // it. A probe proves that the check sees a delivery: inside a call of a bridge's function, which a
 // page's event is, `delivering()` is true.
 //
 // main runs the io_context under a work guard, as a page's program does; once the socket reported
-// its close and the sealer opened what it sealed, the verdict releases the guard. A step that does
+// its close and the derivation completed, the verdict releases the guard. A step that does
 // not come within 10 s fails by name.
 
 #include 
-#include 
+#include 
 
 #include 
 #include 
@@ -29,10 +29,13 @@
 #include 
 #include 
 
+#include 
+#include 
 #include 
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 
@@ -108,16 +111,13 @@ struct state {
     asio::executor_work_guard guard{io.get_executor()};
     trystero::platform::backend backend{io.get_executor()};
     std::shared_ptr socket;
-    std::shared_ptr sealer =
-        backend.make_sealer(trystero::protocol::seal_key("secret", "my-app", "room-1"),
-                            std::pmr::get_default_resource());
+    std::array salt = trystero::protocol::pbkdf2_salt("my-app", "room-1");
+    std::array master{};
     std::string echoed;
-    std::string opened;
     seen open;
     seen message;
     seen close;
-    seen sealed;
-    seen opened_text;
+    seen derived;
     bool judged = false;
 };
 
@@ -127,9 +127,9 @@ void record(state& s, seen& into) {
     into.inside_an_event = asio::use_service(s.io).delivering();
 }
 
-/** Once the socket closed and the sealer opened what it sealed: the verdict. */
+/** Once the socket closed and the derivation completed: the verdict. */
 void judge(state& s) {
-    if (!s.close.ran || !s.opened_text.ran) {
+    if (!s.close.ran || !s.derived.ran) {
         return;
     }
     s.socket.reset();
@@ -137,18 +137,16 @@ void judge(state& s) {
     s.guard.reset();
 }
 
-/** Seals a text, and opens what was sealed, recording where each completion ran. */
-void seal_and_open(state& s) {
-    s.sealer->seal("a candidate", [&s](boost::system::error_code ec, std::string_view text) {
-        record(s, s.sealed);
-        BOOST_TEST(!ec);
-        s.sealer->open(text, [&s](boost::system::error_code ec, std::string_view plain) {
-            record(s, s.opened_text);
+/** Derives a password's master, recording where its completion ran. */
+void derive(state& s) {
+    constexpr std::string_view password = "secret";
+    s.backend.derive_password_master(
+        std::span(reinterpret_cast(password.data()), password.size()), s.salt,
+        s.master, [&s](boost::system::error_code ec) {
+            record(s, s.derived);
             BOOST_TEST(!ec);
-            s.opened = plain;
             judge(s);
         });
-    });
 }
 
 /** Checks that a handler ran outside every event of the page's. */
@@ -193,17 +191,16 @@ int main() {
                                          },
                                  },
                                  std::pmr::get_default_resource());
-    seal_and_open(s);
+    derive(s);
     s.io.run_for(10s);  // lint-run: the test's event loop, held by its work guard until the verdict
     if (!s.judged) {
-        BOOST_ERROR("the socket's close or the sealer's open never came");
+        BOOST_ERROR("the socket's close or the derivation's completion never came");
     }
     expect_outside(s.open, "the socket's open handler never ran");
     expect_outside(s.message, "the socket's message handler never ran");
     expect_outside(s.close, "the socket's close handler never ran");
-    expect_outside(s.sealed, "the seal never completed");
-    expect_outside(s.opened_text, "the open never completed");
+    expect_outside(s.derived, "the derivation never completed");
     BOOST_TEST_EQ(s.echoed, "hello");
-    BOOST_TEST_EQ(s.opened, "a candidate");
+    BOOST_TEST(std::ranges::any_of(s.master, [](std::uint8_t b) { return b != 0; }));
     return webcpp::test::exit_status(boost::report_errors());
 }
diff --git a/test/platform_page_peer_connection_test.cpp b/test/platform_page_peer_connection_test.cpp
index 488c22d..aa03806 100644
--- a/test/platform_page_peer_connection_test.cpp
+++ b/test/platform_page_peer_connection_test.cpp
@@ -9,7 +9,8 @@
 // throws, as for a server it cannot use or with as many connections as the browser allows), the
 // backend makes none and says so with a null connection, which the room reports, rather than
 // letting the exception through; a connection whose `createDataChannel` throws, as a closed one's
-// does, opens no channel.
+// does, opens no channel. A connection's largest message is its SCTP transport's, unknown while it
+// has none (max_message_size_is_the_transports).
 //
 // The page holds at most `runtime_options::max_peer_connections` of them, 256 by default, the cap
 // of the backend's webcpp::webrtc runtime, counted by webcpp::webrtc's census of the page from
@@ -40,8 +41,10 @@
 
 #include 
 #include 
+#include 
 #include 
 #include 
+#include 
 #include 
 
 namespace asio = webcpp::asio;
@@ -95,6 +98,33 @@ void look_for_release(state& s) {
     s.io.stop();
 }
 
+/** The `sctp` of the page's last connection, the stand-in's: `null`, or a transport whose
+ * `maxMessageSize` is `size`. */
+void set_sctp(std::optional size) {
+    if (size) {
+        EM_ASM({ globalThis.lastConnection.sctp = {maxMessageSize : $0}; }, *size);
+    } else {
+        EM_ASM({ globalThis.lastConnection.sctp = null; });
+    }
+}
+
+// The connection's largest message is the page's own `sctp.maxMessageSize`, as webcpp::webrtc's
+// max_message_size() reads it, within webcpp::webrtc's 256 KiB: nothing while the connection has
+// no SCTP transport, then what the transport says, at most 256 KiB for a larger size or none.
+void max_message_size_is_the_transports(const trystero::backend::peer_connection& pc) {
+    BOOST_TEST(!pc.max_message_size().has_value());
+    set_sctp(16384);
+    BOOST_TEST(pc.max_message_size() == std::optional(16384));
+    set_sctp(65536);
+    BOOST_TEST(pc.max_message_size() == std::optional(65536));
+    set_sctp(1073741823);
+    BOOST_TEST(pc.max_message_size() == std::optional(262144));
+    set_sctp(std::numeric_limits::infinity());
+    BOOST_TEST(pc.max_message_size() == std::optional(262144));
+    set_sctp(std::nullopt);
+    BOOST_TEST(!pc.max_message_size().has_value());
+}
+
 }  // namespace
 
 int main() {
@@ -113,7 +143,8 @@ int main() {
     BOOST_TEST(s.backend.make_peer_connection({}, memory) == nullptr);
     BOOST_TEST_EQ(held(), 0);
 
-    // One that is made, whose createDataChannel throws, as a closed connection's does.
+    // One that is made, whose createDataChannel throws, as a closed connection's does, and whose
+    // SCTP transport is the test's to set.
     EM_ASM({
         globalThis.RTCPeerConnection = class {
             constructor() {
@@ -121,6 +152,8 @@ int main() {
                 this.iceConnectionState = 'new';
                 this.localDescription = null;
                 this.remoteDescription = null;
+                this.sctp = null;
+                globalThis.lastConnection = this;
             }
             createDataChannel() { throw new DOMException('closed', 'InvalidStateError'); }
             close() {}
@@ -130,6 +163,7 @@ int main() {
         const auto pc = s.backend.make_peer_connection({}, memory);
         if (BOOST_TEST(pc != nullptr)) {
             BOOST_TEST(pc->create_data_channel("data") == nullptr);
+            max_message_size_is_the_transports(*pc);
             pc->close();
         }
     }
diff --git a/test/platform_page_relay_allocation_test.cpp b/test/platform_page_relay_allocation_test.cpp
index 84687c3..7306320 100644
--- a/test/platform_page_relay_allocation_test.cpp
+++ b/test/platform_page_relay_allocation_test.cpp
@@ -172,9 +172,8 @@ int posix_memalign(void** out, std::size_t alignment, std::size_t size) {
 
 // Emscripten's select() is a poll() over an array of pollfd it callocs on every call
 // (system/lib/libc/musl/src/select/select.c), and Asio's reactor calls it on every wait of the
-// io_context, once in each seal and each open (measured): the C library's wait, not the sealer's.
-// This one keeps the array on the stack, as webcpp::asio's allocation test does, so that the count
-// sees the sealer's allocations.
+// io_context: the C library's wait, not the relay's. This one keeps the array on the stack, as
+// webcpp::asio's allocation test does, so that the count sees the relay's allocations.
 namespace {
 
 /** The poll() event `event` when `set` holds `fd`, else none. */
diff --git a/test/platform_page_sealer_allocation_test.cpp b/test/platform_page_sealer_allocation_test.cpp
deleted file mode 100644
index a71f75f..0000000
--- a/test/platform_page_sealer_allocation_test.cpp
+++ /dev/null
@@ -1,409 +0,0 @@
-// Copyright (c) 2026 WebCpp.org
-//
-// Distributed under the Boost Software License, Version 1.0. (See
-// accompanying file LICENSE_1_0.txt or copy at
-// https://www.boost.org/LICENSE_1_0.txt)
-
-// Tests that a page's sealer allocates nothing outside the room's resource while it seals and
-// opens, under node: from the start of a seal to its completion, and from the start of an open to
-// its, the global operator new, replaced here, and the C library's allocation functions, which
-// Emscripten's dlmalloc defines weak and the test replaces, count none, while the room's resource
-// sees each Web Crypto wait and its completion. A first seal and open come before, uncounted: they
-// import the key and make the io_context's once-per-context allocations (the bridge, its map, the
-// scheduler's first operation). Before the fix the sealer awaited each Web Crypto promise through
-// its type-erased executor, `webcpp::asio::any_io_executor`, through which Asio posts the
-// settlement in a function object and an operation of `std::allocator`, which Asio takes from the
-// C library when its per-run cache has none (measured: two for a seal, two for an open).
-//
-// Two allocations of the platform's are kept out of the count, as allocation_test does: the test
-// replaces select(), which Asio's reactor calls on every wait of the io_context and which
-// Emscripten implements with an array it callocs on every call; and under Asyncify, where the run
-// suspends while a promise is pending and Asyncify allocates the unwind data of the suspension with
-// the C library's malloc, the test marks that allocation and counts it apart.
-//
-// main runs the io_context; each step starts from the completion of the one before, and the run
-// ends when the last completes. A step that does not come within 10 s fails by name.
-
-#include 
-#include 
-#include 
-
-#include 
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-namespace asio = webcpp::asio;
-namespace trystero = webcpp::trystero;
-using namespace std::chrono_literals;
-
-namespace {
-
-// What the replaced operator new and the C library's allocation functions count while counting is
-// set: global and mutable, since an operator new can reach nothing else.
-// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
-std::size_t global_allocations = 0;
-// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
-std::size_t c_allocations = 0;
-// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
-bool counting = false;
-// Set, from JavaScript, while Asyncify allocates the unwind data of a call that suspends: that
-// allocation is the platform's (webcpp::asio's page "Allocation"), counted apart. A char, which
-// JavaScript writes through HEAPU8.
-// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
-std::uint8_t inside_runtime = 0;
-// The C library's allocations made while inside_runtime is set.
-// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
-std::size_t runtime_allocations = 0;
-
-void* counted(void* pointer) {
-    if (counting) {
-        ++(inside_runtime != 0 ? runtime_allocations : c_allocations);
-    }
-    return pointer;
-}
-
-}  // namespace
-
-// The C library's allocation functions, replaced for this program alone, forwarding to
-// Emscripten's own: the C library declares them with parameter names of its own, and cert-dcl58-cpp
-// takes a replacement of what  declares for a change to namespace std.
-// NOLINTBEGIN(readability-inconsistent-declaration-parameter-name,cert-dcl58-cpp)
-extern "C" {
-void* malloc(std::size_t size) {
-    return counted(emscripten_builtin_malloc(size));
-}
-
-void* calloc(std::size_t count, std::size_t size) {
-    return counted(emscripten_builtin_calloc(count, size));
-}
-
-void* realloc(void* pointer, std::size_t size) {
-    return counted(emscripten_builtin_realloc(pointer, size));
-}
-
-void free(void* pointer) {
-    emscripten_builtin_free(pointer);
-}
-
-void* memalign(std::size_t alignment, std::size_t size) {
-    return counted(emscripten_builtin_memalign(alignment, size));
-}
-
-void* aligned_alloc(std::size_t alignment, std::size_t size) {
-    return counted(emscripten_builtin_memalign(alignment, size));
-}
-
-int posix_memalign(void** out, std::size_t alignment, std::size_t size) {
-    *out = counted(emscripten_builtin_memalign(alignment, size));
-    return *out == nullptr ? ENOMEM : 0;
-}
-}
-// NOLINTEND(readability-inconsistent-declaration-parameter-name,cert-dcl58-cpp)
-
-// Emscripten's select() is a poll() over an array of pollfd it callocs on every call
-// (system/lib/libc/musl/src/select/select.c), and Asio's reactor calls it on every wait of the
-// io_context, once in each seal and each open (measured): the C library's wait, not the sealer's.
-// This one keeps the array on the stack, as webcpp::asio's allocation test does, so that the count
-// sees the sealer's allocations.
-namespace {
-
-/** The poll() event `event` when `set` holds `fd`, else none. */
-std::uint32_t requested_event(int fd, const fd_set* set, std::uint32_t event) {
-    return set != nullptr && FD_ISSET(fd, set) ? event : 0U;
-}
-
-void clear_set(fd_set* set) {
-    if (set != nullptr) {
-        FD_ZERO(set);
-    }
-}
-
-/** Adds the descriptor to `set` when poll() reported one of `events` on it; 1 when it did. */
-int ready_event(const pollfd& descriptor, fd_set* set, std::uint32_t events) {
-    if (set != nullptr && (static_cast(descriptor.revents) & events) != 0) {
-        FD_SET(descriptor.fd, set);
-        return 1;
-    }
-    return 0;
-}
-
-}  // namespace
-
-// select's C declaration requires a mutable timeval pointer, although this implementation
-// does not change it.
-extern "C" int select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds,
-                      timeval* timeout) {  // NOLINT(misc-const-correctness)
-    if (nfds < 0 || nfds > FD_SETSIZE) {
-        errno = EINVAL;
-        return -1;
-    }
-    std::array fds{};
-    std::size_t n = 0;
-    for (int fd = 0; fd < nfds; ++fd) {
-        const std::uint32_t events = requested_event(fd, readfds, POLLIN) |
-                                     requested_event(fd, writefds, POLLOUT) |
-                                     requested_event(fd, exceptfds, POLLPRI);
-        if (events != 0) {
-            fds[n++] = pollfd{.fd = fd, .events = static_cast(events), .revents = 0};
-        }
-    }
-    const int milliseconds =
-        timeout == nullptr ? -1
-                           : static_cast((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
-    const int ready = poll(fds.data(), static_cast(n), milliseconds);
-    if (ready < 0) {
-        return ready;
-    }
-    clear_set(readfds);
-    clear_set(writefds);
-    clear_set(exceptfds);
-    int count = 0;
-    for (std::size_t i = 0; i < n && ready > 0; ++i) {
-        count += ready_event(fds[i], readfds, POLLIN | POLLHUP | POLLERR);
-        count += ready_event(fds[i], writefds, POLLOUT | POLLERR);
-        count += ready_event(fds[i], exceptfds, POLLPRI);
-    }
-    return count;
-}
-
-namespace {
-
-/** What the replaced operator new does: counts, then takes the memory from the C library, uncounted
- * there. */
-void* allocate(std::size_t size, std::size_t alignment) {
-    if (counting) {
-        ++global_allocations;
-    }
-    alignment = alignment < sizeof(void*) ? sizeof(void*) : alignment;
-    void* pointer = emscripten_builtin_memalign(alignment, size == 0 ? alignment : size);
-    if (pointer == nullptr) {
-        boost::throw_exception(std::bad_alloc());
-    }
-    return pointer;
-}
-
-}  // namespace
-
-// The standard library declares the replaceable allocation functions with parameter names reserved
-// to the implementation, which a program may not use, hence the exemption on each.
-
-// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name)
-void* operator new(std::size_t size) {
-    return allocate(size, alignof(std::max_align_t));
-}
-
-// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name)
-void* operator new(std::size_t size, std::align_val_t alignment) {
-    return allocate(size, static_cast(alignment));
-}
-
-// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name)
-void operator delete(void* pointer) noexcept {
-    emscripten_builtin_free(pointer);
-}
-
-// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name)
-void operator delete(void* pointer, std::size_t /*size*/) noexcept {
-    emscripten_builtin_free(pointer);
-}
-
-// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name)
-void operator delete(void* pointer, std::align_val_t /*alignment*/) noexcept {
-    emscripten_builtin_free(pointer);
-}
-
-// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name)
-void operator delete(void* pointer, std::size_t /*size*/, std::align_val_t /*alignment*/) noexcept {
-    emscripten_builtin_free(pointer);
-}
-
-namespace {
-
-/**
- * The room's resource: a buffer made before anything is counted, which counts what it gives.
- */
-class counting_resource final : public std::pmr::memory_resource {
-public:
-    std::size_t allocations = 0;
-
-private:
-    std::vector storage_ = std::vector(std::size_t{1} << 20U);
-    std::pmr::monotonic_buffer_resource buffer_{storage_.data(), storage_.size(),
-                                                std::pmr::null_memory_resource()};
-
-    void* do_allocate(std::size_t bytes, std::size_t alignment) override {
-        ++allocations;
-        return buffer_.allocate(bytes, alignment);
-    }
-
-    void do_deallocate(void* /*pointer*/, std::size_t /*bytes*/,
-                       std::size_t /*alignment*/) override {}
-
-    [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override {
-        return this == &other;
-    }
-};
-
-/** What one counted operation saw, from its start to its completion. */
-struct counts {
-    bool completed = false;
-    boost::system::error_code ec;
-    std::size_t global = 0;
-    std::size_t c_library = 0;
-    std::size_t room = 0;
-};
-
-/** The plaintext sealed and opened: a candidate's JSON, as a room seals it. */
-constexpr std::string_view plaintext =
-    R"({"candidate":"candidate:1 1 udp 2122260223 192.0.2.1 54321 typ host"})";
-
-struct state {
-    counting_resource room;
-    asio::io_context io;
-    std::shared_ptr sealer =
-        std::allocate_shared(
-            std::pmr::polymorphic_allocator<>(&room), io.get_executor(),
-            trystero::protocol::seal_key("secret", "my-app", "room-1"), &room);
-    std::pmr::string sealed{&room};
-    std::pmr::string opened{&room};
-    bool warmed_up = false;
-    counts seal;
-    counts open;
-};
-
-using done_handler = trystero::platform::sealer::done_handler;
-
-/** A completion of the sealer's, allocated in the room's resource. */
-template 
-done_handler completion(state& s, F f) {
-    return {std::allocator_arg, std::pmr::polymorphic_allocator<>(&s.room), f};
-}
-
-/** Starts counting what `into` will report, from zero. */
-void start_counting(const state& s, counts& into) {
-    global_allocations = 0;
-    c_allocations = 0;
-    into.room = s.room.allocations;
-    counting = true;
-}
-
-/** Stops counting, and records what was counted since start_counting into `into`. */
-void stop_counting(const state& s, counts& into, boost::system::error_code ec) {
-    counting = false;
-    into.completed = true;
-    into.ec = ec;
-    into.global = global_allocations;
-    into.c_library = c_allocations;
-    into.room = s.room.allocations - into.room;
-}
-
-/** Opens the counted seal's text, counting from the start of the open to its completion. */
-void counted_open(state& s) {
-    start_counting(s, s.open);
-    s.sealer->open(s.sealed,
-                   completion(s, [&s](boost::system::error_code ec, std::string_view text) {
-                       stop_counting(s, s.open, ec);
-                       s.opened.assign(text);
-                   }));
-}
-
-/** Seals, counting from the start of the seal to its completion. */
-void counted_seal(state& s) {
-    start_counting(s, s.seal);
-    s.sealer->seal(plaintext,
-                   completion(s, [&s](boost::system::error_code ec, std::string_view text) {
-                       stop_counting(s, s.seal, ec);
-                       s.sealed.assign(text);
-                       counted_open(s);
-                   }));
-}
-
-/** A first seal and open, uncounted, which import the key and make what an io_context makes once.
- */
-void warm_up(state& s) {
-    s.sealer->seal(
-        plaintext, completion(s, [&s](boost::system::error_code ec, std::string_view text) {
-            BOOST_TEST(!ec);
-            s.sealed.assign(text);
-            s.sealer->open(s.sealed,
-                           completion(s, [&s](boost::system::error_code ec, std::string_view text) {
-                               BOOST_TEST(!ec);
-                               BOOST_TEST_EQ(text, plaintext);
-                               s.warmed_up = true;
-                               counted_seal(s);
-                           }));
-        }));
-}
-
-/**
- * Marks Asyncify's allocation of a suspension's unwind data, on emscripten under Asyncify, as
- * allocation_test does: the C library's allocations made during it are counted apart.
- */
-void mark_the_runtime_allocations() {
-    // clang-format off
-    EM_ASM({
-        if (typeof Asyncify !== "object" || typeof Asyncify.allocateData !== "function") {
-            return;
-        }
-        const flag = $0;
-        const allocate = Asyncify.allocateData;
-        Asyncify.allocateData = function(...values) {
-            const previous = HEAPU8[flag];
-            HEAPU8[flag] = 1;
-            try {
-                return allocate.apply(this, values);
-            } finally {
-                HEAPU8[flag] = previous;
-            }
-        };
-    }, &inside_runtime);
-    // clang-format on
-}
-
-/** Checks that one counted operation completed with no allocation outside the room's resource. */
-void expect_none_outside(const counts& got, const char* name) {
-    if (!got.completed) {
-        BOOST_ERROR(name);
-        return;
-    }
-    BOOST_TEST(!got.ec);
-    BOOST_TEST_EQ(got.global, 0U);
-    BOOST_TEST_EQ(got.c_library, 0U);
-    // The Web Crypto wait, at least, is the room's.
-    BOOST_TEST_GT(got.room, 0U);
-}
-
-}  // namespace
-
-int main() {
-    mark_the_runtime_allocations();
-    state s;
-    warm_up(s);
-    s.io.run_for(10s);  // lint-run: the test's event loop, held by the sealer's Web Crypto waits
-    counting = false;
-    if (!s.warmed_up) {
-        BOOST_ERROR("the first seal and open did not complete");
-    }
-    expect_none_outside(s.seal, "the counted seal did not complete");
-    expect_none_outside(s.open, "the counted open did not complete");
-    BOOST_TEST_EQ(s.opened, plaintext);
-    return webcpp::test::exit_status(boost::report_errors());
-}
diff --git a/test/platform_page_sealer_test.cpp b/test/platform_page_sealer_test.cpp
deleted file mode 100644
index 1cfc695..0000000
--- a/test/platform_page_sealer_test.cpp
+++ /dev/null
@@ -1,231 +0,0 @@
-// Copyright (c) 2026 WebCpp.org
-//
-// Distributed under the Boost Software License, Version 1.0. (See
-// accompanying file LICENSE_1_0.txt or copy at
-// https://www.boost.org/LICENSE_1_0.txt)
-
-// Tests a page's randomness and sealer against a page whose crypto misbehaves, under node: no
-// JavaScript exception enters WebAssembly, and each failure is the error the backend interface
-// has.
-//
-// - When the page's `crypto.getRandomValues` throws, or is missing, the platform's source of
-//   randomness reports that it filled nothing, and a seal completes with `error::backend_failure`,
-//   after its call; once the function is back, both work again. Before the fix the C library's
-//   entropy call, Emscripten's, let the function's exception through into WebAssembly, and the
-//   program ended with it.
-// - When `crypto.subtle.encrypt` or `decrypt` settles with something other than an ArrayBuffer, the
-//   seal or the open completes with `error::backend_failure`. Before the fix the sealer read the
-//   settlement as an ArrayBuffer whatever it was: a seal's -1 threw a RangeError into WebAssembly,
-//   and an open's undefined opened as an empty text.
-//
-// main runs the io_context; each step starts from the completion of the one before, and the last
-// stops the run. A step that does not come within 10 s fails by name.
-
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#include 
-
-#include 
-#include 
-#include 
-#include 
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-namespace asio = webcpp::asio;
-namespace trystero = webcpp::trystero;
-using namespace std::chrono_literals;
-
-// What the page's crypto does: 0, as the page has it; 1, getRandomValues throws; 2, it is missing;
-// 3, subtle.encrypt settles with -1; 4, subtle.decrypt settles with undefined. node's own crypto
-// object will not take another getRandomValues, so the page's is replaced by one that calls node's,
-// but for what it changes, and put back for 0.
-// clang-format off
-// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,modernize-use-trailing-return-type)
-EM_JS(void, misbehave, (int what), {
-    if (!globalThis.pageCrypto) globalThis.pageCrypto = globalThis.crypto;
-    const page = globalThis.pageCrypto;
-    let crypto = page;
-    if (what !== 0) {
-        crypto = {
-            getRandomValues: view => page.getRandomValues(view),
-            subtle: {
-                importKey: (...values) => page.subtle.importKey(...values),
-                encrypt: (...values) => page.subtle.encrypt(...values),
-                decrypt: (...values) => page.subtle.decrypt(...values),
-            },
-        };
-    }
-    if (what === 1) {
-        crypto.getRandomValues = () => { throw new Error("no entropy"); };
-    } else if (what === 2) {
-        crypto.getRandomValues = undefined;
-    } else if (what === 3) {
-        crypto.subtle.encrypt = async () => -1;
-    } else if (what === 4) {
-        crypto.subtle.decrypt = async () => undefined;
-    }
-    Object.defineProperty(globalThis, "crypto", {value: crypto, configurable: true, writable: true});
-});
-// clang-format on
-
-namespace {
-
-/** What the page's crypto does, as misbehave() takes it. */
-enum class page_crypto : std::uint8_t {
-    working = 0,
-    throwing_random = 1,
-    missing_random = 2,
-    encrypt_not_a_buffer = 3,
-    decrypt_not_a_buffer = 4,
-};
-
-void set(page_crypto what) {
-    misbehave(static_cast(what));
-}
-
-/** What a completion saw: its error, its text, and whether it ran inside the call. */
-struct outcome {
-    boost::system::error_code ec;
-    std::string text;
-    bool inline_call = false;
-};
-
-struct state {
-    asio::io_context io;
-    std::shared_ptr sealer =
-        std::make_shared(
-            io.get_executor(), trystero::protocol::seal_key("secret", "my-app", "room-1"),
-            std::pmr::get_default_resource());
-    bool in_call = false;
-    bool judged = false;
-    std::optional imported;
-    std::optional filled_while_throwing;
-    std::optional sealed_while_throwing;
-    std::optional filled_while_missing;
-    std::optional sealed_while_missing;
-    std::optional filled_once_back;
-    std::optional sealed_once_back;
-    std::optional sealed_not_a_buffer;
-    std::optional opened_not_a_buffer;
-};
-
-/** The plaintext sealed: a candidate's JSON, as a room seals it. */
-constexpr std::string_view plaintext =
-    R"({"candidate":"candidate:1 1 udp 2122260223 192.0.2.1 54321 typ host"})";
-
-/** Fills a buffer from the platform's source of randomness, as the backend's `random()` does. */
-bool fill() {
-    std::array bytes{};
-    return trystero::platform::detail::fill_random(bytes);
-}
-
-/** A completion that records what it saw into `into`, then runs `next`. */
-trystero::platform::sealer::done_handler record(state& s, std::optional& into,
-                                                void (*next)(state&)) {
-    return [&s, &into, next](boost::system::error_code ec, std::string_view text) {
-        into = outcome{.ec = ec, .text = std::string(text), .inline_call = s.in_call};
-        next(s);
-    };
-}
-
-/** Seals with `in_call` raised, so that a completion run inside the call says so. */
-void seal(state& s, std::optional& into, void (*next)(state&)) {
-    s.in_call = true;
-    s.sealer->seal(plaintext, record(s, into, next));
-    s.in_call = false;
-}
-
-/** Checks that a completion came, after its call, with `expected`. */
-void expect(const std::optional& got, boost::system::error_code expected,
-            const char* name) {
-    if (!got) {
-        BOOST_ERROR(name);
-        return;
-    }
-    BOOST_TEST(got->ec == expected);
-    BOOST_TEST(!got->inline_call);
-}
-
-void verdict(state& s) {
-    set(page_crypto::working);
-    expect(s.imported, {}, "the first seal did not complete");
-    BOOST_TEST(s.filled_while_throwing == std::optional(false));
-    expect(s.sealed_while_throwing, trystero::error::backend_failure,
-           "the seal without randomness, getRandomValues throwing, did not complete");
-    BOOST_TEST(s.filled_while_missing == std::optional(false));
-    expect(s.sealed_while_missing, trystero::error::backend_failure,
-           "the seal without randomness, getRandomValues missing, did not complete");
-    BOOST_TEST(s.filled_once_back == std::optional(true));
-    expect(s.sealed_once_back, {}, "the seal with randomness back did not complete");
-    expect(s.sealed_not_a_buffer, trystero::error::backend_failure,
-           "the seal whose encrypt settled with no ArrayBuffer did not complete");
-    expect(s.opened_not_a_buffer, trystero::error::backend_failure,
-           "the open whose decrypt settled with no ArrayBuffer did not complete");
-    s.judged = true;
-    s.io.stop();
-}
-
-/** decrypt settles with undefined: the text sealed once randomness was back does not open. */
-void open_not_a_buffer(state& s) {
-    set(page_crypto::decrypt_not_a_buffer);
-    if (!s.sealed_once_back || s.sealed_once_back->ec) {
-        verdict(s);
-        return;
-    }
-    s.in_call = true;
-    s.sealer->open(s.sealed_once_back->text, record(s, s.opened_not_a_buffer, verdict));
-    s.in_call = false;
-}
-
-/** encrypt settles with -1: the seal fails. */
-void seal_not_a_buffer(state& s) {
-    set(page_crypto::encrypt_not_a_buffer);
-    seal(s, s.sealed_not_a_buffer, open_not_a_buffer);
-}
-
-/** getRandomValues is back: the source fills again, and a seal works. */
-void seal_once_back(state& s) {
-    set(page_crypto::working);
-    s.filled_once_back = fill();
-    seal(s, s.sealed_once_back, seal_not_a_buffer);
-}
-
-/** getRandomValues is missing: the source fills nothing, and the seal fails. */
-void seal_while_missing(state& s) {
-    set(page_crypto::missing_random);
-    s.filled_while_missing = fill();
-    seal(s, s.sealed_while_missing, seal_once_back);
-}
-
-/** getRandomValues throws: the source fills nothing, and the seal fails. */
-void seal_while_throwing(state& s) {
-    set(page_crypto::throwing_random);
-    s.filled_while_throwing = fill();
-    seal(s, s.sealed_while_throwing, seal_while_missing);
-}
-
-}  // namespace
-
-int main() {
-    state s;
-    // The first seal imports the key, with the page's crypto working.
-    seal(s, s.imported, seal_while_throwing);
-    s.io.run_for(10s);  // lint-run: the test's event loop, held by the sealer's Web Crypto waits
-    if (!s.judged) {
-        set(page_crypto::working);
-        BOOST_ERROR("the steps stopped before the verdict");
-    }
-    return webcpp::test::exit_status(boost::report_errors());
-}
diff --git a/test/platform_page_test.cpp b/test/platform_page_test.cpp
index c68710c..47ebd7d 100644
--- a/test/platform_page_test.cpp
+++ b/test/platform_page_test.cpp
@@ -65,8 +65,8 @@ namespace {
 struct page {
     test::fixture f;
     asio::executor_work_guard guard{f.io.get_executor()};
-    std::optional a_app;
-    std::optional z_app;
+    std::optional a_app;
+    std::optional z_app;
     std::optional a;
     std::optional z;
     std::optional> chat_a;
@@ -117,8 +117,8 @@ void join(page& p) {
     p.z.emplace(test::join(*p.z_app, "lobby"));
     p.chat_a.emplace(p.a->make_action("chat"));
     p.chat_z.emplace(p.z->make_action("chat"));
-    p.a->on_peer_join([&p](std::string_view /*peer*/) { met(p); });
-    p.z->on_peer_join([&p](std::string_view /*peer*/) { met(p); });
+    p.a->on_peer_join([&p](const trystero::peer_event&) { met(p); });
+    p.z->on_peer_join([&p](const trystero::peer_event&) { met(p); });
     p.chat_z->on_message([&p](std::string text, const trystero::message_info& /*info*/) {
         p.received.push_back(std::move(text));
         if (p.received.size() == 2) {
diff --git a/test/platform_peer_connection_test.cpp b/test/platform_peer_connection_test.cpp
index 2a3f6ff..dc5a8e9 100644
--- a/test/platform_peer_connection_test.cpp
+++ b/test/platform_peer_connection_test.cpp
@@ -12,7 +12,7 @@
 // and holds at most its runtime's `max_peer_connections` at once.
 
 #include 
-#include 
+#include 
 #include 
 #include 
 #include 
@@ -60,8 +60,12 @@ namespace {
 
 constexpr const char* loopback = "127.0.0.1";
 
+/** The wall-clock ceiling of a wait for something that must happen: a hang guard, far above any
+ * loaded run, never what a case measures. */
+constexpr std::chrono::milliseconds hang_guard = 120s;
+
 bool run_until(asio::io_context& io, const std::function& done,
-               std::chrono::milliseconds limit = 10s) {
+               std::chrono::milliseconds limit = hang_guard) {
     const auto end = std::chrono::steady_clock::now() + limit;
     while (!done() && std::chrono::steady_clock::now() < end) {
         io.run_for(10ms);  // lint-run: libdatachannel's threads post the connections' events to it
@@ -101,9 +105,9 @@ struct pair {
                   const executor_wrapper& wrap = {})
         : offerer(made(trystero::webrtc::peer_connection::make(
               program_runtime(runtime), wrap ? wrap(io.get_executor()) : io.get_executor(), {},
-              loopback, factory, offer_memory))),
+              loopback, offer_memory))),
           answerer(made(trystero::webrtc::peer_connection::make(
-              program_runtime(runtime), io.get_executor(), {}, loopback, factory,
+              program_runtime(runtime), io.get_executor(), {}, loopback,
               std::pmr::get_default_resource()))) {}
 
     pair(const pair&) = delete;
@@ -314,7 +318,7 @@ struct queued_pair : pair {
         require(BOOST_TEST(until([&] { return offer_open && answer_open; })));
     }
 
-    bool until(const std::function& done, std::chrono::milliseconds limit = 10s) {
+    bool until(const std::function& done, std::chrono::milliseconds limit = hang_guard) {
         return run_until(
             io,
             [&] {
@@ -346,18 +350,21 @@ void two_connections_open_a_data_channel_and_exchange_bytes() {
     BOOST_TEST(p.answer_end->is_open());
     const backend::bytes hello{1, 2, 3, 250};
     p.offer_end->send(hello);
-    // One byte more than any room frame is dropped before it is read; the largest one arrives.
-    p.answer_end->send(backend::bytes(protocol::max_room_frame_bytes + 1, 6));
-    p.answer_end->send(backend::bytes(protocol::max_room_frame_bytes, 7));
+    // The largest frame arrives.
+    p.answer_end->send(backend::bytes(protocol::max_bulk_frame_bytes, 7));
     if (!BOOST_TEST(run_until(
             p.io, [&] { return p.at_answerer.size() == 1 && p.at_offerer.size() == 1; }))) {
         return;
     }
     BOOST_TEST_ALL_EQ(p.at_answerer.front().begin(), p.at_answerer.front().end(), hello.begin(),
                       hello.end());
-    BOOST_TEST_EQ(p.at_offerer.size(), 1U);
-    BOOST_TEST_EQ(p.at_offerer.front().size(), protocol::max_room_frame_bytes);
+    BOOST_TEST_EQ(p.at_offerer.front().size(), protocol::max_bulk_frame_bytes);
     BOOST_TEST_LE(p.offer_end->buffered_amount(), backend::data_channel::low_threshold);
+    // One byte more than any frame reaches no handler and closes the channel, as 0.27.0's
+    // failData closes it; the other end sees the close.
+    p.answer_end->send(backend::bytes(protocol::max_bulk_frame_bytes + 1, 6));
+    BOOST_TEST(run_until(p.io, [&] { return !p.offer_end->is_open() && p.answer_closes == 1; }));
+    BOOST_TEST_EQ(p.at_offerer.size(), 1U);
     // Every handler ran on the executor, never on libdatachannel's threads.
     BOOST_TEST(!p.off_thread);
 }
@@ -373,7 +380,7 @@ void closing_one_end_is_seen_by_the_other() {
     BOOST_TEST(!p.off_thread);
 }
 
-// Presence can reach the native executor before the posted open event hands a channel over
+// A frame can reach the native executor before the posted open event hands a channel over
 // from signaling. Installing the receiver afterwards must deliver those frames in order.
 void messages_wait_for_the_receiver_during_handoff() {
     queued_pair p;
@@ -460,11 +467,17 @@ void a_pending_queue_overflow_closes_the_channel() {
     for (std::uint8_t i = 0; i < 65; ++i) {
         p.answer_end->send(backend::bytes{i});
     }
-    require(BOOST_TEST(p.until([&] { return closed; }, 5s)));
+    require(BOOST_TEST(p.until([&] { return closed; }, hang_guard)));
     BOOST_TEST(!p.offer_end->is_open());
 }
 
-void pending_messages_expire_without_a_receiver() {
+// A frame kept for a receiver is at most 0.27.0's maxRoomFrameBytes, 17 KiB, as the room's link
+// keeps before its room binds it: one byte more closes the channel, as the link would end on it.
+// A frame of that size is kept, with no time bound of its own.
+void a_pending_frame_past_the_room_frame_bound_closes_the_channel() {
+    namespace webrtc = trystero::webrtc;
+    BOOST_TEST_EQ(webrtc::data_channel::max_pending_frame_bytes, std::size_t{17} * 1024);
+    BOOST_TEST_EQ(webrtc::data_channel::max_pending_frames, 64U);
     queued_pair p;
     p.open();
     require(BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; })));
@@ -475,10 +488,49 @@ void pending_messages_expire_without_a_receiver() {
         .close = [&] { closed = true; },
         .buffered_amount_low = {},
     });
-    const auto started = std::chrono::steady_clock::now();
-    p.answer_end->send(backend::bytes{1});
-    require(BOOST_TEST(p.until([&] { return closed; }, 12s)));
-    BOOST_TEST(std::chrono::steady_clock::now() - started >= 10s);
+    p.answer_end->send(backend::bytes(webrtc::data_channel::max_pending_frame_bytes, 1));
+    p.receive(1);
+    BOOST_TEST(p.offer_end->is_open());
+    p.answer_end->send(backend::bytes(webrtc::data_channel::max_pending_frame_bytes + 1, 2));
+    require(BOOST_TEST(p.until([&] { return closed; })));
+    BOOST_TEST(!p.offer_end->is_open());
+    BOOST_TEST_EQ(p.kept(), 0U);
+}
+
+// The connection's largest message is webcpp::webrtc's max_message_size(): nothing before a
+// remote description, then 256 KiB on both ends (libdatachannel's announcement and webcpp::webrtc's
+// bound), a peer that takes wide chunks. It is what the channel sends: a wide chunk arrives whole,
+// a message of exactly that size is taken, and one byte more is refused, which closes the channel
+// and reports the close, so that a transfer never waits on a chunk that was not sent.
+void max_message_size_is_what_the_channel_sends() {
+    pair p;
+    BOOST_TEST(!p.offerer->max_message_size().has_value());
+    BOOST_TEST(!p.answerer->max_message_size().has_value());
+    p.connect();
+    require(BOOST_TEST(run_until(p.io, [&] { return p.offer_open && p.answer_open; })));
+    const std::optional expected = std::size_t{256} * 1024;
+    BOOST_TEST(p.offerer->max_message_size() == expected);
+    BOOST_TEST(p.answerer->max_message_size() == expected);
+
+    p.offer_end->send(backend::bytes(protocol::max_bulk_frame_bytes, 3));
+    require(BOOST_TEST(run_until(p.io, [&] { return p.at_answerer.size() == 1; })));
+    BOOST_TEST_EQ(p.at_answerer.front().size(), protocol::max_bulk_frame_bytes);
+
+    std::size_t offer_closes = 0;
+    p.offer_end->set_handlers({
+        .open = {},
+        .message = {},
+        .close = [&] { ++offer_closes; },
+        .buffered_amount_low = {},
+    });
+    // Taken: the channel stays open (the offerer then closes it, since no frame is that long).
+    p.answer_end->send(backend::bytes(*expected, 4));
+    BOOST_TEST(p.answer_end->is_open());
+    // Refused: the channel closes at once, and both ends report it.
+    p.offer_end->send(backend::bytes(*expected + 1, 5));
+    BOOST_TEST(!p.offer_end->is_open());
+    require(BOOST_TEST(run_until(p.io, [&] { return offer_closes == 1 && p.answer_closes == 1; })));
+    BOOST_TEST_EQ(p.at_answerer.size(), 1U);
 }
 
 void a_receiver_can_close_and_destroy_its_channel_during_pending_delivery() {
@@ -608,7 +660,7 @@ std::string padded(std::string_view json, std::size_t size) {
     return out;
 }
 
-// A remote candidate of protocol::max_sealed_candidate_bytes, a host candidate's JSON with spaces
+// A remote candidate of protocol::max_sealed_candidate_chars, a host candidate's JSON with spaces
 // before its closing brace, is added once an offer is the connection's remote description; one
 // byte longer fails with error::backend_failure before it is read.
 void a_candidate_past_its_bound_fails() {
@@ -638,7 +690,7 @@ void a_candidate_past_its_bound_fails() {
     const std::string candidate =
         R"({"candidate":"candidate:1 1 UDP 2122317823 127.0.0.1 9 typ host","sdpMid":")" + mid +
         R"("})";
-    constexpr std::size_t bound = protocol::max_sealed_candidate_bytes;
+    constexpr std::size_t bound = protocol::max_sealed_candidate_chars;
     std::vector results;
     answerer->add_ice_candidate(padded(candidate, bound),
                                 [&](backend::error_code ec) { results.push_back(ec); });
@@ -762,6 +814,7 @@ struct mixed_pair {
     std::optional sender;
     std::shared_ptr channel;
     std::vector received;
+    std::size_t closes = 0;  // the closes the backend's channel reported
     bool negotiated = false;
     std::vector to_remote;
     std::vector to_local;
@@ -869,7 +922,7 @@ struct mixed_pair {
         channel->set_handlers({
             .open = {},
             .message = [this](backend::bytes frame) { received.push_back(std::move(frame)); },
-            .close = {},
+            .close = [this] { ++closes; },
             .buffered_amount_low = {},
         });
         local->set_local_description(
@@ -885,9 +938,9 @@ struct mixed_pair {
 };
 
 // A peer may send what is no frame: a text message, which a data channel of webcpp::webrtc
-// delivers as text, is dropped, and the frames around it arrive. The remote peer is
-// webcpp::webrtc's own, which sends text.
-void a_text_message_is_dropped_and_the_frames_around_it_arrive() {
+// delivers as text, closes the channel, as 0.27.0's failData closes it; the frame before it
+// arrives, and nothing after it. The remote peer is webcpp::webrtc's own, which sends text.
+void a_text_message_closes_the_channel() {
     mixed_pair p;
     p.connect();
     const std::vector before{1, 2, 3};
@@ -895,12 +948,10 @@ void a_text_message_is_dropped_and_the_frames_around_it_arrive() {
     BOOST_TEST(!p.sender->send(asio::buffer(before)));
     BOOST_TEST(!p.sender->send_text("1e300"));
     BOOST_TEST(!p.sender->send(asio::buffer(after)));
-    require(BOOST_TEST(run_until(p.io, [&] { return p.received.size() == 2; })));
+    require(BOOST_TEST(run_until(p.io, [&] { return p.closes == 1; })));
+    BOOST_TEST(!p.channel->is_open());
+    require(BOOST_TEST_EQ(p.received.size(), 1U));
     BOOST_TEST_ALL_EQ(p.received[0].begin(), p.received[0].end(), before.begin(), before.end());
-    BOOST_TEST_ALL_EQ(p.received[1].begin(), p.received[1].end(), after.begin(), after.end());
-    // Nothing more arrives: the text was dropped, not delivered late.
-    run_until(p.io, [] { return false; }, 200ms);
-    BOOST_TEST_EQ(p.received.size(), 2U);
 }
 
 }  // namespace
@@ -911,7 +962,8 @@ int main() {
     messages_wait_for_the_receiver_during_handoff();
     a_full_pending_queue_drains_in_order_and_uses_replacement_handlers();
     a_pending_queue_overflow_closes_the_channel();
-    pending_messages_expire_without_a_receiver();
+    a_pending_frame_past_the_room_frame_bound_closes_the_channel();
+    max_message_size_is_what_the_channel_sends();
     a_receiver_can_close_and_destroy_its_channel_during_pending_delivery();
     a_malformed_candidate_fails_without_throwing();
     a_candidate_past_its_bound_fails();
@@ -919,7 +971,7 @@ int main() {
     the_backend_makes_at_most_its_budget_in_a_minute();
     the_runtime_holds_at_most_its_cap_at_once();
     a_url_libdatachannel_cannot_parse_is_left_out();
-    a_text_message_is_dropped_and_the_frames_around_it_arrive();
+    a_text_message_closes_the_channel();
     pending_frames_and_delivery_use_the_channels_resource();
     return boost::report_errors();
 }
diff --git a/test/platform_room_test.cpp b/test/platform_room_test.cpp
index 81f0b8a..9e87251 100644
--- a/test/platform_room_test.cpp
+++ b/test/platform_room_test.cpp
@@ -5,12 +5,16 @@
 // https://www.boost.org/LICENSE_1_0.txt)
 
 // Tests whole rooms over the platform backend natively: real WebRTC through libdatachannel, AES-GCM
-// through OpenSSL, webcpp::asio's timers. Only the relays are the memory ones of
-// support/memory_backend.hpp, and the backend binds every connection to 127.0.0.1, so the loopback
-// is the only network needed.
+// through webcpp::crypto's OpenSSL, a password's PBKDF2 on the backend's thread, webcpp::asio's
+// timers. Only the relays are the memory ones of support/memory_backend.hpp, and the backend binds
+// every connection to 127.0.0.1, so the loopback is the only network needed. A room with a
+// password announces once its PBKDF2 of 600,000 iterations completed, seconds in a debug build on
+// a loaded machine: its waits are hang guards of `derivation_bound`, never what the case measures.
 
 #include 
+#include 
 #include 
+#include 
 #include 
 
 #include 
@@ -42,6 +46,9 @@ namespace {
 
 constexpr const char* relay_url = "wss://relay.test";
 
+/** How long a case waits, at most, for what follows the PBKDF2 of its rooms' password. */
+constexpr std::chrono::milliseconds derivation_bound = 120s;
+
 /** The platform backend bound to the loopback, with the memory relays instead of the network's. */
 class native_over_memory_relays : public trystero::platform::backend {
 public:
@@ -67,18 +74,26 @@ struct fixture {
     fixture() { relays.relay(relay_url); }
 };
 
-trystero::app_config app_config(std::string_view self_id, std::string_view password = {}) {
+/** The configuration of a test's app, whose endpoint key `make_app` gives it. */
+trystero::app_config app_config(std::string_view password = {}) {
     trystero::app_config c;
     c.app_id = "webcpp-trystero-native-tests";
     c.relay_urls = {relay_url};
     // Nothing answers there: with every connection bound to 127.0.0.1, the loopback's host
     // candidate is the only one, and it is enough.
     c.ice_servers = {{.urls = {"stun:127.0.0.1:9"}, .username = {}, .credential = {}}};
-    c.self_id = self_id;
     c.password = password;
     return c;
 }
 
+/** An app whose endpoint key is named `label` (its scalar the label's SHA-256), through the
+ * detail seam the library keeps for its own tests, so that its peer id is known. */
+trystero::app make_app(trystero::app::executor_type ex, trystero::backend::factory& backend,
+                       std::string_view label, std::string_view password = {}) {
+    return trystero::detail::app_access::make(std::move(ex), backend, app_config(password),
+                                              trystero::protocol::sha256(label));
+}
+
 /** Joins `room_id`, which must succeed: a failure ends the test. */
 trystero::room join(trystero::app& a, std::string_view room_id,
                     trystero::room_options options = {}) {
@@ -88,7 +103,7 @@ trystero::room join(trystero::app& a, std::string_view room_id,
 }
 
 bool run_until(asio::io_context& io, const std::function& done,
-               std::chrono::milliseconds limit = 15s) {
+               std::chrono::milliseconds limit = derivation_bound) {
     const auto end = std::chrono::steady_clock::now() + limit;
     while (!done() && std::chrono::steady_clock::now() < end) {
         io.run_for(10ms);  // lint-run: libdatachannel's threads post the connections' events to it
@@ -101,11 +116,10 @@ bool run_until(asio::io_context& io, const std::function& done,
 
 void native_rooms_join_and_exchange_every_format() {
     fixture f;
-    trystero::app a_app(f.io.get_executor(), f.backend,
-                        app_config("AAAAAAAAAAAAAAAAAAAA", "s3cret"));
+    // Labels name the keys only: whichever peer's id is the lower offers, and either works here.
+    auto a_app = make_app(f.io.get_executor(), f.backend, "exchange-a", "s3cret");
     auto a = join(a_app, "lobby");
-    trystero::app z_app(f.io.get_executor(), f.backend,
-                        app_config("zzzzzzzzzzzzzzzzzzzz", "s3cret"));
+    auto z_app = make_app(f.io.get_executor(), f.backend, "exchange-z", "s3cret");
     auto z = join(z_app, "lobby");
     std::string text;
     std::optional json;
@@ -120,8 +134,9 @@ void native_rooms_join_and_exchange_every_format() {
             file = std::move(v);
             metadata = info.metadata;
         });
-    if (!BOOST_TEST(
-            run_until(f.io, [&] { return a.peers().size() == 1 && z.peers().size() == 1; }))) {
+    if (!BOOST_TEST(run_until(
+            f.io, [&] { return a.peers().size() == 1 && z.peers().size() == 1; },
+            derivation_bound))) {
         return;
     }
 
@@ -160,31 +175,32 @@ void native_rooms_join_and_exchange_every_format() {
 
 void another_password_never_joins() {
     fixture f;
-    trystero::app a_app(f.io.get_executor(), f.backend,
-                        app_config("BBBBBBBBBBBBBBBBBBBB", "s3cret"));
+    auto a_app = make_app(f.io.get_executor(), f.backend, "BBBBBBBBBBBBBBBBBBBB", "s3cret");
     const auto a = join(a_app, "private");
-    trystero::app b_app(f.io.get_executor(), f.backend,
-                        app_config("CCCCCCCCCCCCCCCCCCCC", "guess"));
+    auto b_app = make_app(f.io.get_executor(), f.backend, "CCCCCCCCCCCCCCCCCCCC", "guess");
+    // The labels were chosen for the ids they derive: A's is the lower, so A offers.
+    webcpp::test::require(BOOST_TEST_LT(a_app.self_id(), b_app.self_id()));
     auto b = join(b_app, "private");
     std::vector errors;
-    b.on_error([&](std::string_view, boost::system::error_code ec, std::string_view) {
-        errors.push_back(ec);
-    });
-    run_until(f.io, [] { return false; }, 2s);
+    b.on_error([&](const trystero::room_error& e) { errors.push_back(e.code); });
+    // Once both derived their keys, A offers, and B cannot open the offer.
+    BOOST_TEST(run_until(f.io, [&] { return !errors.empty(); }, derivation_bound));
     BOOST_TEST(a.peers().empty());
     BOOST_TEST(b.peers().empty());
-    BOOST_TEST(!errors.empty());
+    for (const auto& ec : errors) {
+        BOOST_TEST(ec == trystero::error::decrypt_failed);
+    }
 }
 
 void leaving_is_seen_over_a_real_connection() {
     fixture f;
-    trystero::app a_app(f.io.get_executor(), f.backend, app_config("DDDDDDDDDDDDDDDDDDDD"));
+    auto a_app = make_app(f.io.get_executor(), f.backend, "DDDDDDDDDDDDDDDDDDDD");
     auto a = join(a_app, "leave");
     std::vector left;
-    a.on_peer_leave([&](std::string_view p) { left.emplace_back(p); });
+    a.on_peer_leave([&](const trystero::peer_event& e) { left.emplace_back(e.peer_id); });
     {
         // The leaver's app goes with its room, as a program that leaves for good ends it.
-        trystero::app b_app(f.io.get_executor(), f.backend, app_config("EEEEEEEEEEEEEEEEEEEE"));
+        auto b_app = make_app(f.io.get_executor(), f.backend, "EEEEEEEEEEEEEEEEEEEE");
         auto b = join(b_app, "leave");
         if (!BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1; }))) {
             return;
diff --git a/test/platform_sealer_test.cpp b/test/platform_sealer_test.cpp
deleted file mode 100644
index ec54a27..0000000
--- a/test/platform_sealer_test.cpp
+++ /dev/null
@@ -1,289 +0,0 @@
-// Copyright (c) 2026 WebCpp.org
-//
-// Distributed under the Boost Software License, Version 1.0. (See
-// accompanying file LICENSE_1_0.txt or copy at
-// https://www.boost.org/LICENSE_1_0.txt)
-
-// Tests the platform backend's sealer on both targets, natively OpenSSL's AES-GCM and on
-// emscripten the page's Web Crypto under node, against text Trystero JS sealed with WebCrypto,
-// which the original's oracle wrote into fixtures/expected/expected.json, the test's one argument:
-// it opens what Trystero JS sealed, a text it seals opens again in Trystero's form, a text sealed
-// under another key or that is no sealed text is a wrong password, and every completion runs after
-// the call that started it, never inside it, as the backend interface says; a fresh sealer given
-// two seals and two opens in one call, which in a page wait while it imports its key, completes
-// each with its own result. On emscripten, without crypto.subtle, as on a page that is not a secure
-// context, the key cannot be imported: the first operation and one after the failure complete
-// after their calls with a backend failure. Before the fix, three of the page's completions ran
-// inside the call.
-//
-// main starts the first step and runs the io_context, which each completion the sealer posts, or
-// each Web Crypto promise it awaits, holds; each step starts from the completion of the one before,
-// and the last ends the run. A step that does not come within 10 s fails by name.
-
-#include 
-#include 
-
-#include 
-
-#ifdef WEBCPP_TARGET_EMSCRIPTEN
-#include 
-#endif
-#include 
-#include 
-#include 
-
-#include 
-#include 
-#include 
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-namespace asio = webcpp::asio;
-namespace tp = webcpp::trystero::protocol;
-namespace trystero = webcpp::trystero;
-using namespace std::chrono_literals;
-
-namespace {
-
-/** The fixture at `path`, read with webcpp::document; nothing when it does not parse. */
-std::optional load(const char* path) {
-    const std::ifstream file(path);
-    std::stringstream text;
-    text << file.rdbuf();
-    auto parsed = webcpp::document::parse(text.str());
-    if (!parsed.has_value()) {
-        return std::nullopt;
-    }
-    return std::move(parsed).unsafe_value();
-}
-
-/** The resource of every sealer and text of the test. */
-std::pmr::memory_resource* memory() {
-    return std::pmr::get_default_resource();
-}
-
-/** What a completion saw: its error, its text, and whether it ran inside the call. */
-struct outcome {
-    boost::system::error_code ec;
-    std::string text;
-    bool inline_call = false;
-};
-
-struct state {
-    explicit state(webcpp::document::document fixture) : fixture(std::move(fixture)) {}
-
-    /** The fixture's string `key` of what Trystero JS sealed; empty when it holds none. */
-    [[nodiscard]] std::string_view sealed_by_js(std::string_view key) const {
-        return fixture["sealed"][key].value_or(std::string_view());
-    }
-
-    webcpp::document::document fixture;
-    asio::io_context io;
-    trystero::platform::backend backend{io.get_executor()};
-    std::shared_ptr sealer =
-        backend.make_sealer(tp::seal_key("secret", "my-app", "room-1"), memory());
-    std::shared_ptr intruder =
-        backend.make_sealer(tp::seal_key("guess", "my-app", "room-1"), memory());
-    std::shared_ptr fresh =
-        backend.make_sealer(tp::seal_key("", "app", "room"), memory());
-    bool in_call = false;
-    bool judged = false;
-    std::optional opened_js;
-    std::optional sealed;
-    std::optional opened;
-    std::optional wrong_key;
-    std::optional garbage;
-    std::optional without_subtle;
-    std::optional after_failure;
-    // A sealer given four operations in one call, while it imports its key in a page.
-    std::shared_ptr queued;
-    std::array, 4> queued_outcomes;
-};
-
-/** The plaintext sealed and opened again: a candidate's JSON, as a room seals it. */
-constexpr std::string_view plaintext =
-    R"({"candidate":"candidate:1 1 udp 2122260223 192.0.2.1 54321 typ host"})";
-
-/** A completion that records what it saw into `into`, then runs `next`. */
-trystero::handler record(
-    state& s, std::optional& into, void (*next)(state&)) {
-    return [&s, &into, next](boost::system::error_code ec, std::string_view text) {
-        into = outcome{.ec = ec, .text = std::string(text), .inline_call = s.in_call};
-        next(s);
-    };
-}
-
-/** Calls `f` with `in_call` raised, so that a completion run inside it says so. */
-template 
-void call(state& s, F f) {
-    s.in_call = true;
-    f();
-    s.in_call = false;
-}
-
-/** Checks that a completion came, after its call, with `expected`. */
-void expect(const std::optional& got, boost::system::error_code expected) {
-    if (BOOST_TEST(got.has_value())) {
-        BOOST_TEST(got->ec == expected);
-        BOOST_TEST(!got->inline_call);
-    }
-}
-
-void verdict(state& s) {
-    expect(s.opened_js, {});
-    if (s.opened_js) {
-        BOOST_TEST_EQ(s.opened_js->text, s.sealed_by_js("plaintext"));
-    }
-    expect(s.sealed, {});
-    if (s.sealed) {
-        const auto parts = tp::parse_sealed(s.sealed->text);
-        if (BOOST_TEST(parts.has_value())) {
-            BOOST_TEST_EQ(parts->iv.size(), tp::seal_iv_size);
-            // The GCM tag follows, as WebCrypto writes it.
-            BOOST_TEST_EQ(parts->ciphertext.size(), plaintext.size() + 16);
-        }
-    }
-    expect(s.opened, {});
-    if (s.opened) {
-        BOOST_TEST_EQ(s.opened->text, plaintext);
-    }
-    expect(s.wrong_key, trystero::error::wrong_password);
-    expect(s.garbage, trystero::error::wrong_password);
-    const auto& queued = s.queued_outcomes;
-    expect(queued[0], {});
-    expect(queued[1], {});
-    if (queued[0] && queued[1]) {
-        const auto first = tp::parse_sealed(queued[0]->text);
-        const auto second = tp::parse_sealed(queued[1]->text);
-        if (BOOST_TEST(first.has_value() && second.has_value())) {
-            BOOST_TEST(first->iv != second->iv);  // a fresh IV each
-        }
-    }
-    expect(queued[2], {});
-    if (queued[2]) {
-        BOOST_TEST_EQ(queued[2]->text, s.sealed_by_js("plaintext"));
-    }
-    expect(queued[3], trystero::error::wrong_password);
-#ifdef WEBCPP_TARGET_EMSCRIPTEN
-    expect(s.without_subtle, trystero::error::backend_failure);
-    expect(s.after_failure, trystero::error::backend_failure);
-#endif
-    s.judged = true;
-    s.io.stop();
-}
-
-#ifdef WEBCPP_TARGET_EMSCRIPTEN
-/** Once the key could not be imported: an operation after the failure completes after its call. */
-void open_after_failure(state& s) {
-    call(s, [&s] { s.fresh->open("x$AAAA", record(s, s.after_failure, verdict)); });
-}
-
-/**
- * Without crypto.subtle, as outside a secure context: the key cannot be imported, and the first
- * operation completes after its call.
- */
-void seal_without_subtle(state& s) {
-    emscripten::val descriptor = emscripten::val::object();
-    descriptor.set("value", emscripten::val::object());
-    emscripten::val::global("Object").call("defineProperty", emscripten::val::global(),
-                                                 emscripten::val("crypto"), descriptor);
-    s.fresh = s.backend.make_sealer(tp::seal_key("", "app", "room"), memory());
-    call(s, [&s] { s.fresh->seal("hello", record(s, s.without_subtle, open_after_failure)); });
-}
-#endif
-
-/** Once every queued operation completed: on emscripten, a page without crypto.subtle. */
-void queued_completed(state& s) {
-    for (const auto& got : s.queued_outcomes) {
-        if (!got) {
-            return;
-        }
-    }
-#ifdef WEBCPP_TARGET_EMSCRIPTEN
-    seal_without_subtle(s);
-#else
-    verdict(s);
-#endif
-}
-
-/**
- * A fresh sealer given two seals and two opens in one call, which in a page wait while it imports
- * its key, started by the first: each completes, after the call, with its own result.
- */
-void queue_during_import(state& s) {
-    s.queued = s.backend.make_sealer(tp::seal_key("secret", "my-app", "room-1"), memory());
-    call(s, [&s] {
-        s.queued->seal(plaintext, record(s, s.queued_outcomes[0], queued_completed));
-        s.queued->seal(plaintext, record(s, s.queued_outcomes[1], queued_completed));
-        s.queued->open(s.sealed_by_js("text"), record(s, s.queued_outcomes[2], queued_completed));
-        s.queued->open("not a sealed text", record(s, s.queued_outcomes[3], queued_completed));
-    });
-}
-
-/** Once the wrong key and the garbage are refused. */
-void refused(state& s) {
-    if (!s.wrong_key || !s.garbage) {
-        return;
-    }
-    queue_during_import(s);
-}
-
-/**
- * Another key's sealer opens what Trystero JS sealed as a wrong password, and the room's opens a
- * text that is no sealed one so too.
- */
-void refuse(state& s) {
-    call(s, [&s] {
-        s.intruder->open(s.sealed_by_js("text"), record(s, s.wrong_key, refused));
-        s.sealer->open("not a sealed text", record(s, s.garbage, refused));
-    });
-}
-
-/** Once its text is sealed, the sealer opens it again. */
-void open_sealed(state& s) {
-    if (!s.sealed || s.sealed->ec) {
-        verdict(s);
-        return;
-    }
-    call(s, [&s] { s.fresh->open(s.sealed->text, record(s, s.opened, refuse)); });
-}
-
-/** Once Trystero JS's text is opened, a sealer under another key seals one of its own. */
-void seal(state& s) {
-    call(s, [&s] { s.fresh->seal(plaintext, record(s, s.sealed, open_sealed)); });
-}
-
-/** Opens what Trystero JS sealed under the room's key. */
-void open_what_js_sealed(state& s) {
-    call(s, [&s] { s.sealer->open(s.sealed_by_js("text"), record(s, s.opened_js, seal)); });
-}
-
-}  // namespace
-
-int main(int argc, char* argv[]) {
-    if (!BOOST_TEST_EQ(argc, 2)) {
-        BOOST_LIGHTWEIGHT_TEST_OSTREAM
-            << "usage: platform_sealer_test \n";
-        return webcpp::test::exit_status(boost::report_errors());
-    }
-    auto fixture = load(argv[1]);
-    if (!BOOST_TEST(fixture.has_value() && (*fixture)["sealed"].is_object())) {
-        return webcpp::test::exit_status(boost::report_errors());
-    }
-    state s(std::move(*fixture));
-    open_what_js_sealed(s);
-    s.io.run_for(10s);  // lint-run: the test's event loop, held by the sealers' completions
-    if (!s.judged) {
-        BOOST_ERROR("the steps stopped before the verdict");
-    }
-    return webcpp::test::exit_status(boost::report_errors());
-}
diff --git a/test/platform_websocket_test.cpp b/test/platform_websocket_test.cpp
index 8fb964a..7a50b9d 100644
--- a/test/platform_websocket_test.cpp
+++ b/test/platform_websocket_test.cpp
@@ -342,8 +342,12 @@ struct stalled_server {
     std::vector>> held;
 };
 
+/** The wall-clock ceiling of a wait for something that must happen: a hang guard, far above any
+ * loaded run, never what a case measures. */
+constexpr std::chrono::milliseconds hang_guard = 120s;
+
 bool run_until(asio::io_context& io, const std::function& done,
-               std::chrono::milliseconds limit = 5s) {
+               std::chrono::milliseconds limit = hang_guard) {
     const auto end = std::chrono::steady_clock::now() + limit;
     while (!done() && std::chrono::steady_clock::now() < end) {
         io.run_for(10ms);  // lint-run: the client and the echo server do loopback network I/O
@@ -866,7 +870,7 @@ void a_relay_that_stops_answering_times_out() {
     if (!BOOST_TEST(run_until(io, [&] { return opened; }))) {
         return;
     }
-    BOOST_TEST(run_until(io, [&] { return closes == 1; }, 10s));
+    BOOST_TEST(run_until(io, [&] { return closes == 1; }, hang_guard));
 }
 
 // A relay that is quiet but healthy: it sends nothing, but reads, so it answers each keep-alive
diff --git a/test/protocol_test.cpp b/test/protocol_test.cpp
index 6b77dc2..9db8f9d 100644
--- a/test/protocol_test.cpp
+++ b/test/protocol_test.cpp
@@ -4,17 +4,18 @@
 // accompanying file LICENSE_1_0.txt or copy at
 // https://www.boost.org/LICENSE_1_0.txt)
 
-// Tests the protocol layer against values Trystero JS 0.26 computed itself, which the original's
-// oracle wrote into fixtures/expected/expected.json. The fixture's path is the test's one argument,
+// Tests the protocol layer against values Trystero JS 0.27.0 computed itself, which the original's
+// oracle wrote into fixtures/oracle/expected.json. The fixture's path is the test's one argument,
 // as webcpp.run passes its input file. The fixture is read with webcpp::document, and every text
 // the protocol writes is read back as a room reads it, with webcpp::document::parse into a
 // pmr::document, within protocol::json::protocol_limits of its bound.
 
 #include 
-#include 
 #include 
 #include 
 #include 
+#include 
+#include 
 #include 
 #include 
 
@@ -33,6 +34,7 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -124,67 +126,6 @@ class counting_resource final : public std::pmr::memory_resource {
     }
 };
 
-void topics(const fixture_value& fixture) {
-    for (const auto t : fixture["topics"]) {
-        const auto app = str(t["app_id"]);
-        const auto room = str(t["room_id"]);
-        BOOST_TEST_EQ(tp::root_topic(app, room), str(t["root_topic"]));
-        BOOST_TEST_EQ(tp::peer_topic(app, room, str(t["peer_id"])), str(t["self_topic"]));
-        BOOST_TEST_EQ(tp::room_token(app, room), str(t["room_token"]));
-    }
-    for (const auto t : fixture["str_to_num"]) {
-        BOOST_TEST_EQ(tp::str_to_num(str(t["text"])), static_cast(integer(t["unbounded"])));
-        BOOST_TEST_EQ(tp::str_to_num(str(t["text"]), 10000),
-                      static_cast(integer(t["mod_10000"])));
-    }
-}
-
-void relays(const fixture_value& fixture) {
-    std::vector defaults;
-    for (const auto url : fixture["default_relays"]) {
-        defaults.push_back(str(url));
-    }
-    BOOST_TEST(std::ranges::equal(defaults, tp::default_nostr_relays));
-    for (const auto entry : fixture["relays"]) {
-        std::vector expected;
-        for (const auto url : entry["relays"]) {
-            expected.push_back(str(url));
-        }
-        const auto derived = tp::derive_relays(str(entry["app_id"]), tp::default_nostr_relays, 5);
-        BOOST_TEST_ALL_EQ(derived.begin(), derived.end(), expected.begin(), expected.end());
-    }
-    for (const auto entry : fixture["shuffle"]) {
-        std::vector order(29);
-        for (int i = 0; i < 29; ++i) {
-            order[i] = i;
-        }
-        std::vector expected;
-        for (const auto i : entry["order"]) {
-            expected.push_back(static_cast(integer(i)));
-        }
-        const auto shuffled = tp::shuffle(order, static_cast(integer(entry["seed"])));
-        BOOST_TEST_ALL_EQ(shuffled.begin(), shuffled.end(), expected.begin(), expected.end());
-    }
-}
-
-void handshake_and_sealing(const fixture_value& fixture) {
-    for (const auto entry : fixture["handshake"]) {
-        BOOST_TEST_EQ(tp::handshake_proof(str(entry["challenge"]), str(entry["password"]),
-                                          str(entry["app_id"]), str(entry["room_id"])),
-                      str(entry["hash"]));
-    }
-    const auto sealed = fixture["sealed"];
-    BOOST_TEST_EQ(tp::to_hex(tp::seal_key("secret", "my-app", "room-1")),
-                  str(sealed["key_material"]));
-    const auto parts = tp::parse_sealed(str(sealed["text"]));
-    BOOST_TEST(parts.has_value());
-    BOOST_TEST_EQ(parts->iv.size(), tp::seal_iv_size);
-    BOOST_TEST_EQ(parts->ciphertext.size(), str(sealed["plaintext"]).size() + 16);
-    BOOST_TEST_EQ(tp::format_sealed(parts->iv, parts->ciphertext), str(sealed["text"]));
-    BOOST_TEST(!tp::parse_sealed("1,2,300$AAAA").has_value());
-    BOOST_TEST(!tp::parse_sealed("no dollar").has_value());
-}
-
 /** A relay's echo of a client's `["EVENT",]`: the event's text whole, less the client's
  * first 9 bytes and its last, in `["EVENT","sub",]`. */
 std::string echo_of(std::string_view message) {
@@ -201,7 +142,7 @@ std::int64_t integer_of(const tp::json::const_value& v) {
 
 void nostr_events(const fixture_value& fixture) {
     for (const auto e : fixture["nostr_events"]) {
-        BOOST_TEST_EQ(tp::nostr::topic_kind(str(e["topic"])), integer(e["kind"]));
+        BOOST_TEST_EQ(integer(e["kind"]), std::int64_t{tp::nostr::topic_kind(str(e["topic"]))});
         const auto created_at =
             std::chrono::sys_seconds(std::chrono::seconds(integer(e["created_at"])));
         const auto id = tp::nostr::event_id(str(e["pubkey"]), created_at,
@@ -214,10 +155,10 @@ void nostr_events(const fixture_value& fixture) {
     secret.fill(7);
     const auto key = tp::nostr::signer::from_secret(secret);
     BOOST_TEST(key.has_value());
-    std::array aux{};
     const auto message =
         tp::nostr::event_message(*key, std::chrono::sys_seconds(std::chrono::seconds(1759700000)),
-                                 "topic-a", R"({"peerId":"p"})", aux);
+                                 "topic-a", R"({"peerId":"p"})")
+            .value();
     const auto parsed = parse_text(message, tp::nostr::max_parsed_relay_text_bytes).value();
     const auto event = parsed.root()[1];
     const auto id = tp::from_hex(tp::json::text_of(event["id"])).value();
@@ -247,20 +188,15 @@ void nostr_events(const fixture_value& fixture) {
 // An event message and a subscription write the values they are given, read back as a relay reads
 // them: the kind Trystero gives the topic, `created_at` and `since` the time, the fixture's and one
 // past 2^32 seconds, which 32 bits would not hold, and an id computed again from the message's own
-// fields. A subscription lists each kind once, in increasing order, and the topics as given.
+// fields. A subscription lists each kind once, in the order of its first topic, and the topics as
+// given.
 void nostr_message_fields(const fixture_value& fixture) {
     const auto first = fixture["nostr_events"][0];
     const auto topic = str(first["topic"]);
-    const auto kind = integer(first["kind"]);
-    // A topic of another kind, which Trystero's own event message for it holds.
-    const auto other = fixture["event_messages"]["events"][0];
-    const auto other_topic = str(other["topic"]);
-    const auto other_message =
-        parse_text(str(other["message"]), tp::nostr::max_parsed_relay_text_bytes);
-    if (!BOOST_TEST(other_message.has_value())) {
-        return;
-    }
-    const auto other_kind = integer_of(other_message->root()[1]["kind"]);
+    const std::int64_t kind = tp::nostr::topic_kind(topic);
+    // A topic of another kind.
+    const auto other_topic = str(fixture["event_messages"]["events"][0]["topic"]);
+    const std::int64_t other_kind = tp::nostr::topic_kind(other_topic);
     BOOST_TEST_NE(kind, other_kind);
     std::array secret{};
     secret.fill(7);
@@ -268,10 +204,9 @@ void nostr_message_fields(const fixture_value& fixture) {
     if (!BOOST_TEST(key.has_value())) {
         return;
     }
-    const std::array aux{};
     for (const std::int64_t seconds : {integer(first["created_at"]), std::int64_t{4'354'000'000}}) {
         const auto at = std::chrono::sys_seconds(std::chrono::seconds(seconds));
-        const auto message = tp::nostr::event_message(*key, at, topic, R"({"peerId":"p"})", aux);
+        const auto message = tp::nostr::event_message(*key, at, topic, R"({"peerId":"p"})").value();
         const auto document = parse_text(message, tp::nostr::max_parsed_relay_text_bytes);
         if (!BOOST_TEST(document.has_value())) {
             continue;
@@ -285,7 +220,7 @@ void nostr_message_fields(const fixture_value& fixture) {
         BOOST_TEST_EQ(tp::json::text_of(tags[0][0]), "x");
         BOOST_TEST_EQ(tp::json::text_of(tags[0][1]), topic);
         BOOST_TEST_EQ(tp::json::text_of(event["content"]), R"({"peerId":"p"})");
-        BOOST_TEST_EQ(tp::json::text_of(event["pubkey"]), key->pubkey());
+        BOOST_TEST_EQ(tp::json::text_of(event["pubkey"]), key->pubkey_hex());
         const auto id = tp::nostr::event_id(
             tp::json::text_of(event["pubkey"]),
             std::chrono::sys_seconds(std::chrono::seconds(integer_of(event["created_at"]))),
@@ -313,11 +248,9 @@ void nostr_message_fields(const fixture_value& fixture) {
         for (const auto k : filter["kinds"]) {
             kinds.push_back(integer_of(k));
         }
-        const std::array increasing{
-            std::min(kind, other_kind),
-            std::max(kind, other_kind),
-        };
-        BOOST_TEST_ALL_EQ(kinds.begin(), kinds.end(), increasing.begin(), increasing.end());
+        // Once each, in the order of their first topic, as Trystero's `new Set` keeps them.
+        const std::array first_seen{kind, other_kind};
+        BOOST_TEST_ALL_EQ(kinds.begin(), kinds.end(), first_seen.begin(), first_seen.end());
         std::vector named;
         for (const auto t : filter["#x"]) {
             named.push_back(tp::json::text_of(t));
@@ -382,16 +315,15 @@ void event_ids_are_their_own(const fixture_value& fixture) {
     if (!BOOST_TEST(key.has_value())) {
         return;
     }
-    const std::array aux{};
     const auto at = std::chrono::sys_seconds(std::chrono::seconds(1759700000));
     const std::string message(
-        tp::nostr::event_message(*key, at, "topic-a", R"({"peerId":"p"})", aux));
+        tp::nostr::event_message(*key, at, "topic-a", R"({"peerId":"p"})").value());
     const std::string kind = R"("kind":)" + std::to_string(tp::nostr::topic_kind("topic-a"));
     const std::string other_kind =
         R"("kind":)" + std::to_string(tp::nostr::topic_kind("topic-a") + 1);
     const std::string created_at = R"("created_at":1759700000)";
     const std::string forged_from(
-        tp::nostr::event_message(*key, at, "topic-a", R"({"peerId":"forged"})", aux));
+        tp::nostr::event_message(*key, at, "topic-a", R"({"peerId":"forged"})").value());
     const std::string forged = replaced(forged_from, id_in(forged_from), id_in(message));
 
     BOOST_TEST(own_id(message));
@@ -407,122 +339,58 @@ void event_ids_are_their_own(const fixture_value& fixture) {
     BOOST_TEST(!own_id(replaced(message, created_at, R"("created_at":1759700000.5)")));
     BOOST_TEST(!own_id(replaced(message, created_at, R"("created_at":1e30)")));
     BOOST_TEST(!own_id(replaced(message, kind, R"("kind":4294967296)")));
-    BOOST_TEST(!own_id(replaced(message, key->pubkey(), uppercase(key->pubkey()))));
+    BOOST_TEST(!own_id(replaced(message, key->pubkey_hex(), uppercase(key->pubkey_hex()))));
     BOOST_TEST(!own_id(replaced(message, id_in(message), uppercase(id_in(message)))));
 }
 
-void inline_frames(const fixture_value& fixture) {
-    const auto actions = fixture["actions"];
-    const auto encode = [](std::string_view name, tp::payload_format format,
-                           std::string_view metadata, std::string_view payload) {
-        return tp::encode_inline(
-            name, format, metadata,
-            std::span(reinterpret_cast(payload.data()), payload.size()));
-    };
-    const auto text = encode("chat", tp::payload_format::text, "", "hello from Trystero JS");
-    const auto expected_text = hex(actions["text"][0]);
-    BOOST_TEST_ALL_EQ(text.begin(), text.end(), expected_text.begin(), expected_text.end());
-    const auto json_frame = encode("drink", tp::payload_format::json, "",
-                                   R"({"drink":"negroni","withIce":true,"n":[1,2.5,null]})");
-    const auto expected_json = hex(actions["json"][0]);
-    BOOST_TEST_ALL_EQ(json_frame.begin(), json_frame.end(), expected_json.begin(),
-                      expected_json.end());
-    const tp::bytes binary{0, 1, 2, 253, 254, 255};
-    const auto binary_frame = tp::encode_inline("pic", tp::payload_format::binary, "", binary);
-    const auto expected_binary = hex(actions["binary"][0]);
-    BOOST_TEST_ALL_EQ(binary_frame.begin(), binary_frame.end(), expected_binary.begin(),
-                      expected_binary.end());
-    const auto with_metadata =
-        encode("chat", tp::payload_format::text, R"({"from":"js","n":7})", "hi");
-    const auto expected_with_metadata = hex(actions["text_with_metadata"][0]);
-    BOOST_TEST_ALL_EQ(with_metadata.begin(), with_metadata.end(), expected_with_metadata.begin(),
-                      expected_with_metadata.end());
-    const auto empty = encode("@_hsready", tp::payload_format::text, "", "");
-    const auto expected_empty = hex(actions["empty_text"][0]);
-    BOOST_TEST_ALL_EQ(empty.begin(), empty.end(), expected_empty.begin(), expected_empty.end());
-    const auto long_name =
-        encode("abcdefghijklmnopqrstuvwxyz012345", tp::payload_format::text, "", "x");
-    const auto expected_long_name = hex(actions["thirty_two_byte_name"][0]);
-    BOOST_TEST_ALL_EQ(long_name.begin(), long_name.end(), expected_long_name.begin(),
-                      expected_long_name.end());
-
-    const auto frame = hex(actions["text_with_metadata"][0]);
-    const auto decoded = tp::decode_action(frame);
-    const auto& p = std::get(*decoded.frame);
-    BOOST_TEST_EQ(p.name, "chat");
-    BOOST_TEST(p.kind == tp::frame_kind::inline_payload);
-    BOOST_TEST(p.format == tp::payload_format::text);
-    BOOST_TEST_EQ(p.metadata, R"({"from":"js","n":7})");
-    BOOST_TEST_EQ(std::string(p.payload.begin(), p.payload.end()), "hi");
+// The frames of Trystero 0.27.0's action wire are proven against its recorded frames in
+// crypto_layer_test.cpp (action_frames_match); these are the rules no recorded frame shows.
+void action_names() {
     BOOST_TEST(tp::valid_action_name("abcdefghijklmnopqrstuvwxyz012345"));
     BOOST_TEST(!tp::valid_action_name("abcdefghijklmnopqrstuvwxyz0123456"));
     BOOST_TEST(!tp::valid_action_name(""));
+    BOOST_TEST(!tp::valid_action_name(std::string_view("a\0b", 3)));
 }
 
-void chunked_frames(const fixture_value& fixture) {
-    const auto chunked = fixture["actions"]["chunked"];
-    const auto payload = hex(chunked["payload"]);
-    const auto frames = chunked["frames"];
-    const auto offer = hex(frames[0]);
-    const auto decoded = tp::decode_action(offer);
-    const auto& p = std::get(*decoded.frame);
-    BOOST_TEST(p.kind == tp::frame_kind::offer);
-    BOOST_TEST_EQ(p.size, payload.size());
-    BOOST_TEST_EQ(p.metadata, R"({"name":"big.bin"})");
-    const auto encoded_offer = tp::encode_offer("file", tp::payload_format::binary,
-                                                R"({"name":"big.bin"})", p.id, payload.size());
-    BOOST_TEST_ALL_EQ(encoded_offer.begin(), encoded_offer.end(), offer.begin(), offer.end());
-    std::size_t offset = 0;
-    for (std::size_t i = 1; i < frames.size(); ++i) {
-        const auto length = std::min(tp::chunk_size, payload.size() - offset);
-        const auto expected = hex(frames[i]);
-        const auto encoded =
-            tp::encode_chunk(p.id, offset, std::span(payload).subspan(offset, length));
-        BOOST_TEST_ALL_EQ(encoded.begin(), encoded.end(), expected.begin(), expected.end());
-        const auto c = std::get(*tp::decode_action(expected).frame);
-        BOOST_TEST_EQ(c.offset, static_cast(offset));
-        BOOST_TEST_EQ(c.data.size(), length);
-        offset += length;
+// Only a chunk may be longer than 16 KiB, up to 64 KiB, and only an offer may carry the wide flag,
+// as 0.27.0's handleData checks: any other frame, or any other flag, is invalid.
+void wide_bulk_frames_are_bounded() {
+    const auto is_invalid = [](const tp::bytes& frame) {
+        const auto decoded = tp::decode_action(frame);
+        return !decoded.frame.has_value() && decoded.error == tp::wire_error::invalid_frame;
+    };
+    const auto wide_offer =
+        tp::encode_offer("file", tp::payload_format::binary, "", 1, 200'000, tp::chunk_width::wide);
+    BOOST_TEST_EQ(wide_offer[1], 0x61U);
+    const auto offer = tp::decode_action(wide_offer);
+    if (BOOST_TEST(offer.frame.has_value())) {
+        BOOST_TEST(std::get(*offer.frame).wide);
     }
-    BOOST_TEST_EQ(offset, payload.size());
-    const auto rejected = hex(fixture["controls"]["rejected_too_large"]);
-    const auto encoded_rejected = tp::encode_rejected(p.id, "payload exceeds receiver size limit");
-    BOOST_TEST_ALL_EQ(encoded_rejected.begin(), encoded_rejected.end(), rejected.begin(),
-                      rejected.end());
-    const auto control = std::get(*tp::decode_action(rejected).frame);
-    BOOST_TEST(control.kind == tp::frame_kind::rejected);
-    BOOST_TEST_EQ(control.reason, "payload exceeds receiver size limit");
-    BOOST_TEST_EQ(tp::encode_accepted(p.id).size(), tp::control_header_size);
-}
-
-void envelopes(const fixture_value& fixture) {
-    const auto env = fixture["envelope"];
-    const auto token = str(env["room_token"]);
-    BOOST_TEST_EQ(token, tp::room_token("my-app", "room-1"));
-    const auto frames = env["frames"];
-    const auto present = tp::presence_frame(token, true);
-    const auto expected_present = hex(frames[0]);
-    BOOST_TEST_ALL_EQ(present.begin(), present.end(), expected_present.begin(),
-                      expected_present.end());
-    const tp::bytes action{2, 0, 99, 104, 97, 116};
-    const auto room_frame = tp::room_frame(token, action);
-    const auto expected_room = hex(frames[1]);
-    BOOST_TEST_ALL_EQ(room_frame.begin(), room_frame.end(), expected_room.begin(),
-                      expected_room.end());
-    const auto absent = tp::presence_frame(token, false);
-    const auto expected_absent = hex(frames[2]);
-    BOOST_TEST_ALL_EQ(absent.begin(), absent.end(), expected_absent.begin(), expected_absent.end());
-    const auto room = hex(frames[1]);
-    const auto decoded = tp::decode_envelope(room);
-    BOOST_TEST(decoded->type == tp::envelope::kind::room);
-    BOOST_TEST_EQ(decoded->token, token);
-    BOOST_TEST_ALL_EQ(decoded->payload.begin(), decoded->payload.end(), action.begin(),
-                      action.end());
-    const auto presence = tp::decode_envelope(hex(frames[2]));
-    BOOST_TEST(presence->type == tp::envelope::kind::presence);
-    BOOST_TEST(!presence->present);
-    BOOST_TEST(!tp::decode_envelope(tp::bytes{1, 0, 0}).has_value());
-    BOOST_TEST(!tp::decode_envelope(tp::bytes{9, 0, 1, 65}).has_value());
+    BOOST_TEST(!std::get(
+                    *tp::decode_action(
+                         tp::encode_offer("file", tp::payload_format::binary, "", 1, 200'000))
+                         .frame)
+                    .wide);
+    auto high_flag = wide_offer;
+    high_flag[1] = static_cast(high_flag[1] | 0x80U);
+    BOOST_TEST(is_invalid(high_flag));
+    auto flagged_inline = tp::encode_inline("chat", tp::payload_format::text, "", tp::bytes{65});
+    flagged_inline[1] = static_cast(flagged_inline[1] | tp::wide_bulk_flag);
+    BOOST_TEST(is_invalid(flagged_inline));
+    auto flagged_accepted = tp::encode_accepted(1);
+    flagged_accepted[1] = static_cast(flagged_accepted[1] | tp::wide_bulk_flag);
+    BOOST_TEST(is_invalid(flagged_accepted));
+
+    const tp::bytes wide_data(tp::wide_chunk_size, 7);
+    const auto widest = tp::encode_chunk(1, 0, wide_data);
+    BOOST_TEST_EQ(widest.size(), tp::max_bulk_frame_bytes);
+    const auto chunk = tp::decode_action(widest);
+    if (BOOST_TEST(chunk.frame.has_value())) {
+        BOOST_TEST_EQ(std::get(*chunk.frame).data.size(), tp::wide_chunk_size);
+    }
+    BOOST_TEST(is_invalid(tp::encode_chunk(1, 0, tp::bytes(tp::wide_chunk_size + 1, 7))));
+    const tp::bytes long_payload(tp::max_action_frame_bytes - tp::inline_header_size + 1, 7);
+    BOOST_TEST(is_invalid(tp::encode_inline("chat", tp::payload_format::binary, "", long_payload)));
 }
 
 void signals() {
@@ -534,23 +402,36 @@ void signals() {
         }
         return tp::read_signal(std::as_const(document.emplace(std::move(parsed).value())).root());
     };
-    const auto announce = read(R"({"peerId":"abc","nonce":"x1"})");
+    const auto announce = read(R"({"peerId":"peerAAAAAAAAAAAAAAAA","nonce":"x1"})");
     if (!BOOST_TEST(announce.has_value())) {
         return;
     }
     BOOST_TEST(announce->is_announcement());
-    BOOST_TEST(!read(R"({"peerId":"abc","offer":""})").has_value());
-    BOOST_TEST(!read(R"({"offer":"x"})").has_value());
+    BOOST_TEST(announce->offer_id.empty());
+    BOOST_TEST(!read(R"({"peerId":"peerAAAAAAAAAAAAAAAA","offerId":"o","offer":""})").has_value());
+    BOOST_TEST(!read(R"({"offerId":"o","offer":"x"})").has_value());
     BOOST_TEST(!read(R"(["peerId"])").has_value());
+    // 0.27.0's rules: a peer id of 20 base62 characters, an offer id of 1 to 64 of [\w.~:!-],
+    // required with an offer, answer or candidate and refusing whenever present and not one.
+    BOOST_TEST(!read(R"({"peerId":"abc"})").has_value());
+    BOOST_TEST(!read(R"({"peerId":"peerAAAAAAAAAAAAAAA-"})").has_value());
+    BOOST_TEST(!read(R"({"peerId":"peerAAAAAAAAAAAAAAAA","offer":"x"})").has_value());
+    BOOST_TEST(!read(R"({"peerId":"peerAAAAAAAAAAAAAAAA","offerId":""})").has_value());
+    BOOST_TEST(!read(R"({"peerId":"peerAAAAAAAAAAAAAAAA","offerId":5})").has_value());
+    BOOST_TEST(
+        !read(R"({"peerId":"peerAAAAAAAAAAAAAAAA","offerId":"a b","answer":"x"})").has_value());
+    const auto with_id = read(R"({"peerId":"peerAAAAAAAAAAAAAAAA","offerId":"a_.~:!-Z9"})");
+    BOOST_TEST(with_id.has_value() && with_id->offer_id == "a_.~:!-Z9");
     const auto written = tp::write_signal(
-        {.peer_id = "me", .offer_id = "o1", .candidate = "1,2$AA==", .passive = true}, "n0nce");
-    BOOST_TEST_EQ(
-        written,
-        R"({"peerId":"me","offerId":"o1","candidate":"1,2$AA==","passive":true,"nonce":"n0nce"})");
+        {.peer_id = "peerAAAAAAAAAAAAAAAA", .offer_id = "o1", .candidate = "1,2$AA=="}, "n0nce");
+    BOOST_TEST_EQ(written,
+                  R"({"peerId":"peerAAAAAAAAAAAAAAAA","offerId":"o1","candidate":"1,2$AA==",)"
+                  R"("nonce":"n0nce"})");
     const auto back = read(written);
-    BOOST_TEST_EQ(back->candidate, "1,2$AA==");
-    BOOST_TEST_EQ(back->offer_id, "o1");
-    BOOST_TEST(back->passive);
+    if (BOOST_TEST(back.has_value())) {
+        BOOST_TEST_EQ(back->candidate, "1,2$AA==");
+        BOOST_TEST_EQ(back->offer_id, "o1");
+    }
     // Escaping matches JSON.stringify, so a sealed text or a candidate with quotes survives the
     // round trip. The expected text is named outside the macro: MSVC 14.3's preprocessor, which
     // stringizes the macro's arguments, reads a raw string's \" as an escape and stops (C2017).
@@ -558,23 +439,6 @@ void signals() {
     BOOST_TEST_EQ(tp::write_signal({.peer_id = "q\"\\\n"}), escaped);
 }
 
-// An id has one character of Trystero's 62 for each random byte, the byte's remainder in 62: the
-// first and the last character, and the remainders 0 and 61 of larger bytes.
-void random_ids() {
-    const std::array random{0, 61, 62, 123, 124, 255};
-    BOOST_TEST_EQ(tp::random_id(random), "0z0z07");
-    BOOST_TEST_EQ(tp::random_id(std::span{}), "");
-    std::array all{};
-    for (std::size_t i = 0; i < all.size(); ++i) {
-        all[i] = static_cast(i * 13);
-    }
-    std::pmr::monotonic_buffer_resource memory;
-    const auto id = tp::random_id(all, &memory);
-    BOOST_TEST(id.get_allocator().resource() == &memory);
-    BOOST_TEST_EQ(id.size(), tp::peer_id_size);
-    BOOST_TEST_EQ(id.find_first_not_of(tp::id_alphabet), std::string::npos);
-}
-
 // An offer's size is a float64 that Trystero accepts up to Number.MAX_SAFE_INTEGER, 2^53 - 1, the
 // bytes 43 3f ff ff ff ff ff ff, and refuses from 2^53, 43 40 00 00 00 00 00 00, as any size that
 // is not a positive integer: the largest is read whole on every target, a 32-bit one too.
@@ -612,7 +476,7 @@ void offer_sizes_at_two_to_the_53() {
 }
 
 // Every field wider than a byte is big-endian, as DataView writes it, high bytes included: the
-// oracle's frames have a short metadata, small ids, offsets and sizes, and a token of 64 bytes.
+// oracle's frames have a short metadata, small ids, offsets and sizes.
 void wide_fields_are_big_endian() {
     const std::string metadata(0x0102, 'm');
     const auto offer =
@@ -631,36 +495,21 @@ void wide_fields_are_big_endian() {
     const tp::bytes data{9};
     const auto chunk = tp::encode_chunk(0x0a0b0c0d, 0x12345678, data);
     const tp::bytes expected_chunk{
-        2, 2, 0x0a, 0x0b, 0x0c, 0x0d, 0x41, 0xb2, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 9,
+        3, 2, 0x0a, 0x0b, 0x0c, 0x0d, 0x41, 0xb2, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 9,
     };
     BOOST_TEST_ALL_EQ(chunk.begin(), chunk.end(), expected_chunk.begin(), expected_chunk.end());
     const auto c = std::get(*tp::decode_action(chunk).frame);
     BOOST_TEST_EQ(c.id, 0x0a0b0c0dU);
     BOOST_TEST_EQ(c.offset, 305419896.0);
     const auto accepted = tp::encode_accepted(0xfffefdfc);
-    const tp::bytes expected_accepted{2, 3, 0xff, 0xfe, 0xfd, 0xfc};
+    const tp::bytes expected_accepted{3, 3, 0xff, 0xfe, 0xfd, 0xfc};
     BOOST_TEST_ALL_EQ(accepted.begin(), accepted.end(), expected_accepted.begin(),
                       expected_accepted.end());
-
-    const std::string token(0x012c, 't');
-    const auto presence = tp::presence_frame(token, true);
-    BOOST_TEST_EQ(presence.size(), 4 + token.size());
-    BOOST_TEST_EQ(presence[2], 0x01);
-    BOOST_TEST_EQ(presence[3], 0x2c);
-    const auto room = tp::room_frame(token, data);
-    BOOST_TEST_EQ(room.size(), 3 + token.size() + data.size());
-    BOOST_TEST_EQ(room[1], 0x01);
-    BOOST_TEST_EQ(room[2], 0x2c);
-    const std::string longest(tp::max_room_token_bytes, 't');
-    const auto longest_frame = tp::room_frame(longest, data);
-    const auto envelope = tp::decode_envelope(longest_frame);
-    if (BOOST_TEST(envelope.has_value())) {
-        BOOST_TEST_EQ(envelope->token.size(), tp::max_room_token_bytes);
-    }
 }
 
-// Each field of a signal is bounded, and the bound refuses nothing Trystero sends: its longest
-// candidate, 8192 bytes of plaintext, sealed with the longest IV in decimal, is read.
+// Each field of a signal is bounded as 0.27.0 bounds it, in UTF-16 code units: a candidate of
+// 3044 bytes of plaintext, sealed, is the longest read; a text that is not ASCII counts as
+// JavaScript counts it, a character beyond U+FFFF two units.
 void signal_bounds() {
     std::optional document;
     const auto read = [&document](const tp::signal_message& m) {
@@ -671,36 +520,57 @@ void signal_bounds() {
         return tp::read_signal(std::as_const(document.emplace(std::move(parsed).value())).root())
             .has_value();
     };
-    std::array iv{};
-    iv.fill(255);
-    const tp::bytes ciphertext(8192 + 16, 7);
-    const auto longest_candidate = tp::format_sealed(iv, ciphertext);
-    BOOST_TEST_EQ(longest_candidate.size(), tp::sealed_size(8192));
-    BOOST_TEST(read({.peer_id = "p", .offer_id = "o", .candidate = longest_candidate}));
+    constexpr std::string_view peer = "peerAAAAAAAAAAAAAAAA";
+    const auto key = tp::room_aes_key_without_password("my-app", "room-1");
+    const std::array iv{};
+    const auto sealed_candidate = [&](std::size_t plaintext) {
+        return std::string(tp::seal(key, iv, std::string(plaintext, 'c'),
+                                    std::string_view("candidate|peerAAAAAAAAAAAAAAAA|o"))
+                               .value());
+    };
+    const auto longest_candidate = sealed_candidate(3044);
+    BOOST_TEST_EQ(longest_candidate.size(), tp::max_sealed_candidate_chars);
+    BOOST_TEST(read({.peer_id = peer, .offer_id = "o", .candidate = longest_candidate}));
+    BOOST_TEST(!read({.peer_id = peer, .offer_id = "o", .candidate = sealed_candidate(3045)}));
 
     const auto of = [](std::size_t n) { return std::string(n, 'a'); };
-    const auto candidate = of(tp::max_sealed_candidate_bytes);
-    const auto description = of(tp::max_sealed_description_bytes);
-    const auto offer_id = of(tp::max_offer_id_bytes);
-    BOOST_TEST(read({.peer_id = "p", .offer_id = "o", .candidate = candidate}));
-    BOOST_TEST(!read({.peer_id = "p", .offer_id = "o", .candidate = candidate + "a"}));
-    BOOST_TEST(read({.peer_id = "p", .offer_id = "o", .offer = description}));
-    BOOST_TEST(!read({.peer_id = "p", .offer_id = "o", .offer = description + "a"}));
-    BOOST_TEST(read({.peer_id = "p", .offer_id = "o", .answer = description}));
-    BOOST_TEST(!read({.peer_id = "p", .offer_id = "o", .answer = description + "a"}));
-    BOOST_TEST(read({.peer_id = "p", .offer_id = offer_id, .offer = "x"}));
-    BOOST_TEST(!read({.peer_id = "p", .offer_id = offer_id + "a", .offer = "x"}));
+    const auto candidate = of(tp::max_sealed_candidate_chars);
+    const auto description = of(tp::max_sealed_description_chars);
+    const auto offer_id = of(tp::max_offer_id_chars);
+    BOOST_TEST(read({.peer_id = peer, .offer_id = "o", .candidate = candidate}));
+    BOOST_TEST(!read({.peer_id = peer, .offer_id = "o", .candidate = candidate + "a"}));
+    BOOST_TEST(read({.peer_id = peer, .offer_id = "o", .offer = description}));
+    BOOST_TEST(!read({.peer_id = peer, .offer_id = "o", .offer = description + "a"}));
+    BOOST_TEST(read({.peer_id = peer, .offer_id = "o", .answer = description}));
+    BOOST_TEST(!read({.peer_id = peer, .offer_id = "o", .answer = description + "a"}));
+    BOOST_TEST(read({.peer_id = peer, .offer_id = offer_id, .offer = "x"}));
+    BOOST_TEST(!read({.peer_id = peer, .offer_id = offer_id + "a", .offer = "x"}));
+    // U+00E9 is 2 bytes and 1 unit; U+1F600 is 4 bytes and 2 units.
+    const auto units = [](std::size_t n, std::string_view character) {
+        std::string out;
+        for (std::size_t i = 0; i < n; ++i) {
+            out += character;
+        }
+        return out;
+    };
+    BOOST_TEST(read({.peer_id = peer, .offer_id = "o", .candidate = units(4096, "\xc3\xa9")}));
+    BOOST_TEST(!read({.peer_id = peer, .offer_id = "o", .candidate = units(4097, "\xc3\xa9")}));
+    BOOST_TEST(
+        read({.peer_id = peer, .offer_id = "o", .candidate = units(2048, "\xf0\x9f\x98\x80")}));
+    BOOST_TEST(!read(
+        {.peer_id = peer, .offer_id = "o", .candidate = units(2048, "\xf0\x9f\x98\x80") + "a"}));
 }
 
-// An event message is Trystero's createEvent's, byte for byte, signed with the oracle's key, clock
-// and auxiliary bytes: its topic and content hold every control character, `"`, `\`, U+2028,
-// U+2029, DEL and astral characters, which document's quoting writes as JSON.stringify does, and
-// its id is the one the protocol computes.
+// Trystero's createEvent signed each of the oracle's events with its key, clock and auxiliary
+// bytes: its topic and content hold every control character, `"`, `\`, U+2028, U+2029, DEL and
+// astral characters. Each kind is the one the protocol gives the topic, each id the one it computes
+// over the event's fields, each signature verifies, and the signer made from the oracle's secret
+// has the event's public key. An event the protocol writes for the same topic and content holds the
+// same fields, an id of its own and a signature that verifies.
 void event_messages(const fixture_value& fixture) {
     const auto messages = fixture["event_messages"];
     const auto secret = hex(messages["secret_key"]);
-    const auto aux = hex(messages["aux"]);
-    if (!BOOST_TEST_EQ(secret.size(), 32U) || !BOOST_TEST_EQ(aux.size(), 32U)) {
+    if (!BOOST_TEST_EQ(secret.size(), 32U)) {
         return;
     }
     const auto key =
@@ -708,59 +578,83 @@ void event_messages(const fixture_value& fixture) {
     if (!BOOST_TEST(key.has_value())) {
         return;
     }
-    const std::span aux_bytes(aux.data(), 32);
     const auto created_at =
         std::chrono::sys_seconds(std::chrono::seconds(integer(messages["created_at"])));
+    // Whether an event's signature verifies under its public key, over its id.
+    const auto verifies = [](const tp::json::const_value& event) {
+        const auto id = tp::from_hex(tp::json::text_of(event["id"])).value_or(tp::bytes());
+        const auto sig = tp::from_hex(tp::json::text_of(event["sig"])).value_or(tp::bytes());
+        const auto pub = tp::from_hex(tp::json::text_of(event["pubkey"])).value_or(tp::bytes());
+        return id.size() == 32 && sig.size() == 64 && pub.size() == 32 &&
+               tp::nostr::verify(std::span(sig.data(), 64),
+                                 std::span(id.data(), 32),
+                                 std::span(pub.data(), 32));
+    };
     BOOST_TEST_EQ(messages["events"].size(), 6U);
     for (const auto e : messages["events"]) {
         const auto topic = str(e["topic"]);
         const auto content = str(e["content"]);
-        BOOST_TEST_EQ(tp::nostr::event_message(*key, created_at, topic, content, aux_bytes),
-                      str(e["message"]));
-        const auto id = tp::nostr::event_id(key->pubkey(), created_at, tp::nostr::topic_kind(topic),
-                                            topic, content);
+        const auto theirs = parse_text(str(e["message"]), tp::nostr::max_parsed_relay_text_bytes);
+        if (!BOOST_TEST(theirs.has_value())) {
+            continue;
+        }
+        const auto event = theirs->root()[1];
+        BOOST_TEST_EQ(tp::json::text_of(event["pubkey"]), key->pubkey_hex());
+        const auto kind = static_cast(integer_of(event["kind"]));
+        BOOST_TEST_EQ(kind, tp::nostr::topic_kind(topic));
+        const auto id = tp::nostr::event_id(key->pubkey_hex(), created_at, kind, topic, content);
         BOOST_TEST_EQ(tp::to_hex(id), str(e["id"]));
+        BOOST_TEST(verifies(event));
+
+        const auto written = tp::nostr::event_message(*key, created_at, topic, content);
+        if (!BOOST_TEST(written.has_value())) {
+            continue;
+        }
+        const auto ours = parse_text(*written, tp::nostr::max_parsed_relay_text_bytes);
+        if (!BOOST_TEST(ours.has_value())) {
+            continue;
+        }
+        const auto mine = ours->root()[1];
+        BOOST_TEST_EQ(integer_of(mine["kind"]), std::int64_t{tp::nostr::topic_kind(topic)});
+        BOOST_TEST_EQ(tp::json::text_of(mine["tags"][0][1]), topic);
+        BOOST_TEST_EQ(tp::json::text_of(mine["content"]), content);
+        BOOST_TEST_EQ(integer_of(mine["created_at"]), integer_of(event["created_at"]));
+        BOOST_TEST(own_id(*written));
+        BOOST_TEST(verifies(mine));
     }
 }
 
-// A signal's text is JSON.stringify's of Trystero's object, member for member, with the same
-// strings, every byte of their quoting included, and the protocol reads the same fields back.
+// A signal's text is JSON.stringify's of 0.27.0's object, member for member, with the same
+// strings, every byte of their quoting included, and the protocol reads the same fields back
+// where 0.27.0's signal handler read the signal; it refused the three whose peer ids are none.
 void signal_texts(const fixture_value& fixture) {
     BOOST_TEST_EQ(fixture["signal_texts"].size(), 7U);
+    std::size_t read_back = 0;
     for (const auto entry : fixture["signal_texts"]) {
         const auto s = entry["signal"];
-        // The answerer's messages are those whose second member is the answer or the candidate.
-        std::string_view second;
-        std::size_t at = 0;
-        for (const std::string_view key : s.keys()) {
-            if (at++ == 1) {
-                second = key;
-            }
-        }
         const tp::signal_message m{
             .peer_id = str(s["peerId"]),
             .offer_id = str(s["offerId"]),
             .offer = str(s["offer"]),
             .answer = str(s["answer"]),
             .candidate = str(s["candidate"]),
-            .passive = s["passive"].value_or(false),
-            .answering =
-                second == "answer" || (second == "candidate" && !s["offerId"].is_undefined()),
         };
         const auto text = str(entry["text"]);
         BOOST_TEST_EQ(tp::write_signal(m, str(s["nonce"])), text);
         const auto document = parse_text(text, tp::max_parsed_signal_bytes).value();
         const auto read = tp::read_signal(document.root());
-        if (!BOOST_TEST(read.has_value())) {
+        // Read back where 0.27.0 read it, refused where its ids are none of 0.27.0's.
+        if (!BOOST_TEST_EQ(read.has_value(), !entry["read"].is_null()) || !read.has_value()) {
             continue;
         }
+        ++read_back;
         BOOST_TEST_EQ(read->peer_id, m.peer_id);
         BOOST_TEST_EQ(read->offer_id, m.offer_id);
         BOOST_TEST_EQ(read->offer, m.offer);
         BOOST_TEST_EQ(read->answer, m.answer);
         BOOST_TEST_EQ(read->candidate, m.candidate);
-        BOOST_TEST_EQ(read->passive, m.passive);
     }
+    BOOST_TEST_EQ(read_back, 4U);
 }
 
 /** `text` read as an action of JSON reads its payload, then written back as one sends it: once
@@ -827,40 +721,64 @@ std::string answer_sender(std::string_view text, std::string_view root_topic) {
     return std::string(signal->peer_id);
 }
 
-// A key written twice keeps its last value, as JSON.parse keeps it, an escaped key included: a
-// signal reads what Trystero's own signal handler read from the same text, and a relay's event is
-// acted on, with the same sender, exactly when Trystero's room acted on it.
-void duplicate_keys(const fixture_value& fixture) {
-    const auto cases = fixture["duplicate_keys"];
-    BOOST_TEST_EQ(cases["signals"].size(), 13U);
-    for (const auto entry : cases["signals"]) {
+/**
+ * Each signal of an oracle's list is read as 0.27.0's own signal handler read it: refused where
+ * `read` is null, otherwise with the same peer id and sealed texts, and the offer id of what it
+ * opened.
+ */
+void signals_read_as_0_27_0_read(const fixture_value& signals) {
+    for (const auto entry : signals) {
         const auto document = parse_text(str(entry["text"]), tp::max_parsed_signal_bytes).value();
         const auto read = tp::read_signal(document.root());
         const auto expected = entry["read"];
-        if (expected.is_null()) {
-            BOOST_TEST(!read.has_value());
-            continue;
+        if (!BOOST_TEST_EQ(read.has_value(), !expected.is_null())) {
+            std::cerr << "  the signal: " << str(entry["text"]).substr(0, 100) << '\n';
         }
-        if (!BOOST_TEST(read.has_value())) {
+        if (!read.has_value() || expected.is_null()) {
             continue;
         }
         BOOST_TEST_EQ(read->peer_id, str(expected["peer_id"]));
         BOOST_TEST_EQ(read->offer, str(expected["offer"]));
         BOOST_TEST_EQ(read->answer, str(expected["answer"]));
         BOOST_TEST_EQ(read->candidate, str(expected["candidate"]));
-        BOOST_TEST_EQ(read->passive, expected["passive"].value_or(false));
-        // Trystero shows an offer's id, which it keeps to answer with.
+        // 0.27.0 shows the offer id of what it opens; an announcement's it never reads.
         if (expected.contains("offer_id")) {
             BOOST_TEST_EQ(read->offer_id, str(expected["offer_id"]));
         }
     }
-    const auto root_topic = str(cases["root_topic"]);
-    BOOST_TEST_EQ(cases["events"].size(), 6U);
-    for (const auto entry : cases["events"]) {
+}
+
+/** Each relay event of an oracle's list is acted on, with the same sender, exactly when 0.27.0's
+ * room acted on it. */
+void events_acted_on_as_0_27_0_acted(const fixture_value& events, std::string_view root_topic) {
+    for (const auto entry : events) {
         BOOST_TEST_EQ(answer_sender(str(entry["text"]), root_topic), str(entry["acted"]));
     }
 }
 
+// A key written twice keeps its last value, as JSON.parse keeps it, an escaped key included: a
+// signal reads what 0.27.0's own signal handler read from the same text, and a relay's event is
+// acted on, with the same sender, exactly when 0.27.0's room acted on it.
+void duplicate_keys(const fixture_value& fixture) {
+    const auto cases = fixture["duplicate_keys"];
+    BOOST_TEST_EQ(cases["signals"].size(), 13U);
+    signals_read_as_0_27_0_read(cases["signals"]);
+    BOOST_TEST_EQ(cases["events"].size(), 6U);
+    events_acted_on_as_0_27_0_acted(cases["events"], str(cases["root_topic"]));
+}
+
+// A room refuses every signal 0.27.0's parseSignalEnvelope refuses, as 0.27.0's handler and room
+// showed on each: a peer id that is not 20 base62 characters, or no string; an offer id that is not
+// 1 to 64 characters of [\w.~:!-], present or needed by an offer, answer or candidate; a candidate
+// past 4,096 UTF-16 code units, a character beyond U+FFFF two. The last text of each bound is read.
+void signal_envelopes(const fixture_value& fixture) {
+    const auto cases = fixture["signal_envelopes"];
+    BOOST_TEST_EQ(cases["signals"].size(), 26U);
+    signals_read_as_0_27_0_read(cases["signals"]);
+    BOOST_TEST_EQ(cases["events"].size(), 8U);
+    events_acted_on_as_0_27_0_acted(cases["events"], str(cases["root_topic"]));
+}
+
 /** `text` with spaces after its value, which JSON allows, up to `size` bytes. */
 std::string padded(std::string_view text, std::size_t size) {
     std::string out(text);
@@ -868,26 +786,24 @@ std::string padded(std::string_view text, std::size_t size) {
     return out;
 }
 
-/** The longest signal the bounds of its fields admit: a passive room's sealed offer. */
+/** The longest signal the bounds of its fields admit: a sealed answer, whose key is the longest. */
 std::string longest_signal() {
-    const std::string peer(tp::max_peer_id_bytes, 'p');
-    const std::string offer_id(tp::max_offer_id_bytes, 'o');
-    const std::string description(tp::max_sealed_description_bytes, 'a');
-    return std::string(tp::write_signal(
-        {.peer_id = peer, .offer_id = offer_id, .offer = description, .passive = true}));
+    const std::string peer(tp::peer_id_size, 'p');
+    const std::string offer_id(tp::max_offer_id_chars, 'o');
+    const std::string description(tp::max_sealed_description_chars, 'a');
+    return std::string(
+        tp::write_signal({.peer_id = peer, .offer_id = offer_id, .answer = description}));
 }
 
 // The bounds a room parses with refuse no text Trystero sends, and the relay's is under the length
 // that closes a relay's connection, so that a text between the two is dropped and the room goes on.
-static_assert(tp::max_parsed_signal_bytes == tp::max_sealed_description_bytes + 1024);
+static_assert(tp::max_parsed_signal_bytes == tp::max_sealed_description_chars + 1024);
 static_assert(tp::max_parsed_signal_bytes == 66560);
-static_assert(tp::max_sealed_description_bytes + tp::max_peer_id_bytes + tp::max_offer_id_bytes +
-                  64 <=
+static_assert(tp::max_sealed_description_chars + tp::peer_id_size + tp::max_offer_id_chars + 64 <=
               tp::max_parsed_signal_bytes);
 static_assert(tp::nostr::max_parsed_relay_text_bytes == tp::max_parsed_signal_bytes + 2048);
 static_assert(tp::nostr::max_parsed_relay_text_bytes == 68608);
 static_assert(tp::nostr::max_parsed_relay_text_bytes < tp::max_relay_message_bytes);
-static_assert(tp::max_handshake_bytes == 1024);
 // A parse reads at most its bound of text, into an image of at most twice that and 64 KiB more.
 static_assert(tp::json::protocol_limits(1000).max_bytes == 1000);
 static_assert(tp::json::protocol_limits(1000).max_document_bytes == 2000 + 65536);
@@ -907,7 +823,7 @@ static_assert(tp::json::payload_limits(0, 1000).max_document_bytes == 1000);
 // Each text a room parses is read up to its bound, to the byte, and one byte more is refused
 // before anything of it is read: no buffer is made, and a text that is not JSON at all is refused
 // for its length, not its syntax. The relay's bound reads an event that carries the longest
-// signal, which the signal's bound reads in turn, and the handshake's reads Trystero's message.
+// signal, which the signal's bound reads in turn.
 void parse_bounds() {
     const auto refused_unread = [](std::string_view text, std::size_t max_bytes) {
         counting_resource memory;
@@ -926,8 +842,9 @@ void parse_bounds() {
     {
         const auto document = parse_text(longest, tp::max_parsed_signal_bytes).value();
         const auto read = tp::read_signal(document.root());
-        BOOST_TEST(read.has_value() && read->offer.size() == tp::max_sealed_description_bytes &&
-                   read->peer_id.size() == tp::max_peer_id_bytes && read->passive);
+        BOOST_TEST(read.has_value() && read->answer.size() == tp::max_sealed_description_chars &&
+                   read->peer_id.size() == tp::peer_id_size &&
+                   read->offer_id.size() == tp::max_offer_id_chars);
     }
     BOOST_TEST(refused_unread(longest + " ", tp::max_parsed_signal_bytes));
 
@@ -939,10 +856,11 @@ void parse_bounds() {
     if (!BOOST_TEST(key.has_value())) {
         return;
     }
-    const std::array aux{};
-    const auto topic = tp::peer_topic("my-app", "room-1", std::string(tp::max_peer_id_bytes, 'p'));
-    const auto message = tp::nostr::event_message(
-        *key, std::chrono::sys_seconds(std::chrono::seconds(1759700000)), topic, signal, aux);
+    const auto topic = tp::peer_topic("my-app", "room-1", std::string(tp::peer_id_size, 'p'));
+    const auto message =
+        tp::nostr::event_message(*key, std::chrono::sys_seconds(std::chrono::seconds(1759700000)),
+                                 topic, signal)
+            .value();
     const std::string_view written = message;
     std::string echo = R"(["EVENT",")" + std::string(64, 's') + R"(",)";
     echo += written.substr(9, written.size() - 10);
@@ -963,17 +881,6 @@ void parse_bounds() {
         }
     }
     BOOST_TEST(refused_unread(event_text + " ", tp::nostr::max_parsed_relay_text_bytes));
-
-    // Trystero's handshake message: `{"__trystero_pw":"response","h":"<64 hexadecimal digits>"}`.
-    const auto proof = tp::handshake_proof("ch4ll3ng3", "secret", "my-app", "room-1");
-    const auto handshake =
-        padded(R"({"__trystero_pw":"response","h":")" + std::string(proof) + "\"}",
-               tp::max_handshake_bytes);
-    {
-        const auto document = parse_text(handshake, tp::max_handshake_bytes).value();
-        BOOST_TEST_EQ(tp::json::text_of(document.root()["h"]), proof);
-    }
-    BOOST_TEST(refused_unread(handshake + " ", tp::max_handshake_bytes));
 }
 
 /** `["EVENT","sub",]` whose event holds `members` more after its tags and content. */
@@ -1163,8 +1070,7 @@ void text() {
 
 int main(int argc, char* argv[]) {
     if (!BOOST_TEST_EQ(argc, 2)) {
-        BOOST_LIGHTWEIGHT_TEST_OSTREAM
-            << "usage: protocol_test \n";
+        BOOST_LIGHTWEIGHT_TEST_OSTREAM << "usage: protocol_test \n";
         return boost::report_errors();
     }
     const auto loaded = load(argv[1]);
@@ -1172,24 +1078,20 @@ int main(int argc, char* argv[]) {
         return boost::report_errors();
     }
     const auto fixture = loaded->root();
-    topics(fixture);
-    relays(fixture);
-    handshake_and_sealing(fixture);
     nostr_events(fixture);
     nostr_message_fields(fixture);
     event_ids_are_their_own(fixture);
-    inline_frames(fixture);
-    chunked_frames(fixture);
-    envelopes(fixture);
+    action_names();
+    wide_bulk_frames_are_bounded();
     offer_sizes_at_two_to_the_53();
     wide_fields_are_big_endian();
     signals();
-    random_ids();
     signal_bounds();
     event_messages(fixture);
     signal_texts(fixture);
     payload_texts(fixture);
     duplicate_keys(fixture);
+    signal_envelopes(fixture);
     parse_bounds();
     parse_cost();
     parse_depth();
diff --git a/test/room_test.cpp b/test/room_test.cpp
index c34daf2..535bb78 100644
--- a/test/room_test.cpp
+++ b/test/room_test.cpp
@@ -9,6 +9,11 @@
 // log on the standard error.
 
 #include 
+#include 
+#include 
+#include 
+#include 
+#include 
 #include 
 #include 
 
@@ -30,6 +35,7 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -37,10 +43,12 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
 #include 
+#include 
 #include 
 
 #include "cases.hpp"
@@ -54,59 +62,118 @@ using namespace std::chrono_literals;
 
 namespace {
 
-using trystero::test::advance;
 using trystero::test::app_config;
 using trystero::test::app_id;
+using trystero::test::config_of;
 using trystero::test::counting_resource;
 using trystero::test::document_of;
+using trystero::test::endpoint_scalar;
 using trystero::test::fixture;
 using trystero::test::flooder;
 using trystero::test::join;
+using trystero::test::label_beside;
+using trystero::test::ordered_labels;
+using trystero::test::peer_id_of;
 using trystero::test::relay_a;
 using trystero::test::relay_b;
 using trystero::test::relayed_signal;
 using trystero::test::run_until;
+using trystero::test::signal_id;
 
-/** An app's state and a room of it, without their handles, for a case that reaches the app's
- * connections or calls the room as its app does. The case abandons the room before the fixture
- * goes. */
+/** An app's state and a room of it, without their handles, for a case that calls the room as its
+ * signaling does. The case abandons the room before the fixture goes. */
 struct app_room {
     std::shared_ptr app;
     std::shared_ptr room;
 };
 
-app_room make_app_room(
-    fixture& f, std::string_view self_id, std::string_view room_id,
-    const std::function& edit = {}) {
-    const std::pmr::polymorphic_allocator<> alloc(std::pmr::get_default_resource());
-    trystero::app_config config{
-        .app_id = app_id,
-        .self_id = std::pmr::string(self_id),
-        .relay_urls = {relay_a, relay_b},
-    };
-    trystero::room_options options;
-    if (edit) {
-        edit(config, options);
-    }
+app_room make_app_room(fixture& f, std::string_view label, std::string_view room_id,
+                       std::pmr::memory_resource* memory = std::pmr::get_default_resource()) {
+    const std::pmr::polymorphic_allocator<> alloc(memory);
     app_room out;
-    out.app = std::allocate_shared(alloc, f.io.get_executor(), f.net,
-                                                               std::move(config));
-    out.room = trystero::detail::room_impl::make(out.app, options, room_id);
+    const auto scalar = trystero::test::endpoint_scalar(label);
+    out.app =
+        std::allocate_shared(alloc, f.io.get_executor(), f.net,
+                                                         trystero::app_config{
+                                                             .app_id = app_id,
+                                                             .relay_urls = {relay_a, relay_b},
+                                                             .memory = memory,
+                                                         },
+                                                         std::span(scalar));
+    out.room = trystero::detail::room_impl::make(out.app, trystero::room_options(), room_id);
     return out;
 }
 
+/** A connection negotiated over the memory network outside any room: its local end, which a case
+ * hands a room as its signaling would, and the remote end's channel, which records what it
+ * receives. */
+struct raw_pair {
+    std::shared_ptr local_pc;
+    std::shared_ptr local;
+    std::shared_ptr remote_pc;
+    std::shared_ptr remote;
+    std::shared_ptr>> received =
+        std::make_shared>>();
+    /** The local end's descriptions: its offer, and the answer it applied. */
+    std::string offer;
+    std::string answer;
+};
+
+raw_pair negotiate(fixture& f) {
+    auto* m = std::pmr::get_default_resource();
+    raw_pair p;
+    p.local_pc = f.net.make_peer_connection({}, m);
+    p.remote_pc = f.net.make_peer_connection({}, m);
+    p.local = p.local_pc->create_data_channel("data");
+    auto remote = std::make_shared>();
+    p.remote_pc->set_handlers({
+        .ice_candidate = {},
+        .data_channel =
+            [remote](std::shared_ptr c) {
+                *remote = std::move(c);
+            },
+        .state = {},
+    });
+    std::pmr::string offer(m);
+    std::pmr::string answer(m);
+    p.local_pc->set_local_description([&offer](trystero::backend::error_code, std::string_view,
+                                               std::string_view sdp) { offer = sdp; });
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return !offer.empty(); })));
+    p.remote_pc->set_remote_description("offer", offer, [](trystero::backend::error_code) {});
+    p.remote_pc->set_local_description([&answer](trystero::backend::error_code, std::string_view,
+                                                 std::string_view sdp) { answer = sdp; });
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return !answer.empty(); })));
+    p.local_pc->set_remote_description("answer", answer, [](trystero::backend::error_code) {});
+    webcpp::test::require(BOOST_TEST(
+        run_until(f, [&] { return p.local->is_open() && *remote && (*remote)->is_open(); })));
+    p.remote_pc->set_handlers({});
+    p.offer = offer;
+    p.answer = answer;
+    p.remote = *remote;
+    p.remote->set_handlers({
+        .open = {},
+        .message =
+            [received = p.received](trystero::backend::bytes frame) {
+                received->emplace_back(frame.begin(), frame.end());
+            },
+        .close = {},
+        .buffered_amount_low = {},
+    });
+    return p;
+}
+
 void two_peers_join_and_exchange_every_payload_format() {
-    fixture f;
-    // "A..." sorts below "z...", so A offers and z answers; the other test below swaps nothing but
-    // the ids.
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("AAAAAAAAAAAAAAAAAAAA"));
+    fixture f{true};
+    // A's id sorts below z's, so A offers and z answers.
+    const auto labels = ordered_labels(2, "lobby");
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config(labels[0]));
     auto a = join(a_app, "lobby");
-    trystero::app z_app(f.io.get_executor(), f.net, app_config("zzzzzzzzzzzzzzzzzzzz"));
+    trystero::test::app z_app(f.io.get_executor(), f.net, app_config(labels[1]));
     auto z = join(z_app, "lobby");
     std::vector joined_a;
     std::vector joined_z;
-    a.on_peer_join([&](std::string_view p) { joined_a.emplace_back(p); });
-    z.on_peer_join([&](std::string_view p) { joined_z.emplace_back(p); });
+    a.on_peer_join([&](const trystero::peer_event& e) { joined_a.emplace_back(e.peer_id); });
+    z.on_peer_join([&](const trystero::peer_event& e) { joined_z.emplace_back(e.peer_id); });
 
     auto chat_a = a.make_action("chat");
     auto chat_z = z.make_action("chat");
@@ -124,12 +191,13 @@ void two_peers_join_and_exchange_every_payload_format() {
     // end::json-receive[]
     pic_z.on_message([&](trystero::bytes b, const trystero::message_info&) { pic = std::move(b); });
 
-    BOOST_TEST(run_until(f.io, [&] { return joined_a.size() == 1 && joined_z.size() == 1; }));
-    BOOST_TEST_EQ(joined_a.at(0), "zzzzzzzzzzzzzzzzzzzz");
-    BOOST_TEST_EQ(joined_z.at(0), "AAAAAAAAAAAAAAAAAAAA");
+    BOOST_TEST(run_until(f, [&] { return joined_a.size() == 1 && joined_z.size() == 1; }));
+    BOOST_TEST_EQ(joined_a.at(0), z_app.self_id());
+    BOOST_TEST_EQ(joined_z.at(0), a_app.self_id());
     const auto peers = a.peers();
-    const std::vector only_z{"zzzzzzzzzzzzzzzzzzzz"};
-    BOOST_TEST_ALL_EQ(peers.begin(), peers.end(), only_z.begin(), only_z.end());
+    webcpp::test::require(BOOST_TEST_EQ(peers.size(), 1U));
+    BOOST_TEST_EQ(peers.begin()->first, z_app.self_id());
+    BOOST_TEST_EQ(peers.begin()->second.user_id, z_app.user_id());
 
     std::vector sent;
     chat_a.async_send("hello", trystero::send_options{.targets = {}, .metadata = R"({"n":1})"},
@@ -143,14 +211,14 @@ void two_peers_join_and_exchange_every_payload_format() {
     a.make_action("pic").async_send(
         trystero::bytes{0, 1, 255}, [&](boost::system::error_code ec) { sent.push_back(ec); });
 
-    BOOST_TEST(run_until(
-        f.io, [&] { return chats_z.size() == 1 && drink.has_value() && pic.size() == 3; }));
+    BOOST_TEST(
+        run_until(f, [&] { return chats_z.size() == 1 && drink.has_value() && pic.size() == 3; }));
     BOOST_TEST_EQ(sent.size(), 3U);
     for (const auto& ec : sent) {
         BOOST_TEST(!ec);
     }
     BOOST_TEST_EQ(chats_z.at(0).first, "hello");
-    BOOST_TEST_EQ(chats_z.at(0).second.from, "AAAAAAAAAAAAAAAAAAAA");
+    BOOST_TEST_EQ(chats_z.at(0).second.from, a_app.self_id());
     BOOST_TEST_EQ(chats_z.at(0).second.metadata, R"({"n":1})");
     const trystero::bytes sent_pic{0, 1, 255};
     BOOST_TEST_ALL_EQ(pic.begin(), pic.end(), sent_pic.begin(), sent_pic.end());
@@ -163,10 +231,10 @@ void two_peers_join_and_exchange_every_payload_format() {
 }
 
 void large_payloads_travel_in_chunks_both_ways() {
-    fixture f;
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("BBBBBBBBBBBBBBBBBBBB"));
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("BBBBBBBBBBBBBBBBBBBB"));
     auto a = join(a_app, "files");
-    trystero::app b_app(f.io.get_executor(), f.net, app_config("CCCCCCCCCCCCCCCCCCCC"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("CCCCCCCCCCCCCCCCCCCC"));
     auto b = join(b_app, "files");
     auto file_a = a.make_action("file");
     auto file_b = b.make_action("file");
@@ -179,7 +247,7 @@ void large_payloads_travel_in_chunks_both_ways() {
         got_b = std::move(v);
         meta_b = info.metadata;
     });
-    BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1 && b.peers().size() == 1; }));
+    BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; }));
 
     trystero::bytes big(100'000);
     for (std::size_t i = 0; i < big.size(); ++i) {
@@ -196,113 +264,769 @@ void large_payloads_travel_in_chunks_both_ways() {
         BOOST_TEST(!ec);
         ++done;
     });
-    BOOST_TEST(run_until(f.io, [&] { return done == 2 && !got_a.empty() && !got_b.empty(); }));
+    BOOST_TEST(run_until(f, [&] { return done == 2 && !got_a.empty() && !got_b.empty(); }));
     BOOST_TEST_ALL_EQ(got_b.begin(), got_b.end(), big.begin(), big.end());
     const trystero::bytes reversed(big.rbegin(), big.rend());
     BOOST_TEST_ALL_EQ(got_a.begin(), got_a.end(), reversed.begin(), reversed.end());
     BOOST_TEST_EQ(meta_b, R"({"name":"big.bin"})");
 }
 
-void ping_measures_a_round_trip() {
-    fixture f;
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("DDDDDDDDDDDDDDDDDDDD"));
-    auto a = join(a_app, "ping");
-    trystero::app b_app(f.io.get_executor(), f.net, app_config("EEEEEEEEEEEEEEEEEEEE"));
-    const auto b = join(b_app, "ping");
-    BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1; }));
-    std::optional result;
-    a.async_ping(b.self_id(), [&](boost::system::error_code ec, std::chrono::milliseconds rtt) {
-        result = ec;
-        BOOST_TEST_GE(rtt.count(), 0);
-    });
-    BOOST_TEST(run_until(f.io, [&] { return result.has_value(); }));
-    BOOST_TEST(!*result);
-    std::optional missing;
-    a.async_ping("nobody",
-                 [&](boost::system::error_code ec, std::chrono::milliseconds) { missing = ec; });
-    BOOST_TEST(run_until(f.io, [&] { return missing.has_value(); }));
-    BOOST_TEST(*missing == trystero::error::no_such_peer);
+/** The vectors recorded from 0.27.0's code (fixtures/expected/trystero-0.27.0.json), which main
+ * loads from the path it is given before it runs a case. */
+std::optional& vectors() {
+    static std::optional document;
+    return document;
+}
+
+/** The bytes of a text of hexadecimal digits, as the vectors write a frame. */
+std::vector bytes_of_hex(std::string_view hex) {
+    std::vector out;
+    for (std::size_t i = 0; i + 1 < hex.size(); i += 2) {
+        out.push_back(
+            static_cast(std::stoi(std::string(hex.substr(i, 2)), nullptr, 16)));
+    }
+    return out;
+}
+
+/** `frame` in lowercase hexadecimal, as the vectors write a frame. */
+std::string hex_of(std::span frame) {
+    static constexpr std::string_view digits = "0123456789abcdef";
+    std::string out;
+    out.reserve(frame.size() * 2);
+    for (const auto b : frame) {
+        out += digits[b >> 4U];
+        out += digits[b & 15U];
+    }
+    return out;
+}
+
+/** The vectors' transfer case `name` of `action_frames`; a case missing ends the test. */
+webcpp::document::basic_const_value<> recorded_transfer(std::string_view name) {
+    webcpp::test::require(BOOST_TEST(vectors().has_value()));
+    webcpp::document::basic_const_value<> recorded;
+    for (const auto entry : vectors()->root()["action_frames"]) {
+        if (entry["case"].value_or(std::string_view()) == name) {
+            recorded = entry;
+        }
+    }
+    webcpp::test::require(BOOST_TEST(recorded["frames"].is_array()));
+    return recorded;
+}
+
+/** Checks the frames of a transfer, each with the connection that sent it, against the recorded
+ * case's: who sent it, its size, and its bytes or its header. */
+void check_transfer_frames(
+    const webcpp::document::basic_const_value<>& recorded,
+    const std::vector>>& frames) {
+    std::size_t i = 0;
+    for (const auto expected : recorded["frames"]) {
+        if (!BOOST_TEST_LT(i, frames.size())) {
+            break;
+        }
+        const auto& [from, frame] = frames[i];
+        const bool from_a = from == frames.front().first;
+        BOOST_TEST_EQ(from_a ? "A" : "B", expected["from"].value_or(std::string_view()));
+        BOOST_TEST_EQ(static_cast(frame.size()),
+                      expected["size"].value_or(std::int64_t{-1}));
+        const auto hex = hex_of(frame);
+        if (expected["hex"].is_string()) {
+            BOOST_TEST_EQ(hex, expected["hex"].value_or(std::string_view()));
+        } else {
+            const auto head = expected["head"].value_or(std::string_view());
+            BOOST_TEST(!head.empty());
+            BOOST_TEST_EQ(std::string_view(hex).substr(0, head.size()), head);
+        }
+        ++i;
+    }
+    BOOST_TEST_EQ(frames.size(), i);
+}
+
+/**
+ * Sends, from A to B over `f`'s network, the 200 KiB binary message of the vectors' transfer case
+ * `name` of `action_frames` ("file", `{"name":"big.bin"}`), and checks every frame of its transfer
+ * against the case's, in order: who sent it, its size, and its bytes where the case recorded them
+ * whole (the offer, "accepted") or its header where it recorded only that (a chunk). The payload
+ * arrives whole.
+ */
+void a_transfer_sends_the_frames_of(fixture& f, std::string_view name) {
+    namespace tp = trystero::protocol;
+    const auto recorded = recorded_transfer(name);
+    // The frames of a transfer: its offer, its answer and its chunks, with the connection that
+    // sent each.
+    std::vector>> frames;
+    f.net.filter = [&](std::size_t from, std::size_t, std::span frame) {
+        if (const auto decoded = tp::decode_action(frame).frame) {
+            const auto* p = std::get_if(&*decoded);
+            if (p == nullptr || p->kind == tp::frame_kind::offer) {
+                frames.emplace_back(from, std::vector(frame.begin(), frame.end()));
+            }
+        }
+        return trystero::test::memory_network::verdict::deliver;
+    };
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("AAAAAAAAAAAAAAAAAAAA"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("BBBBBBBBBBBBBBBBBBBB"));
+    auto a = join(a_app, "wide");
+    auto b = join(b_app, "wide");
+    trystero::bytes got;
+    b.make_action("file").on_message(
+        [&](trystero::bytes v, const trystero::message_info&) { got = std::move(v); });
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })));
+    trystero::bytes payload(
+        static_cast(recorded["payload_size"].value_or(std::int64_t{0})));
+    for (std::size_t i = 0; i < payload.size(); ++i) {
+        payload[i] = static_cast(i * 31);
+    }
+    std::optional sent;
+    a.make_action("file").async_send(
+        payload,
+        trystero::send_options{
+            .targets = {},
+            .metadata = std::pmr::string(recorded["metadata"].value_or(std::string_view())),
+        },
+        [&](boost::system::error_code ec) { sent = ec; });
+    BOOST_TEST(run_until(f, [&] { return sent.has_value() && !got.empty(); }));
+    BOOST_TEST(sent.has_value() && !*sent);
+    BOOST_TEST_ALL_EQ(got.begin(), got.end(), payload.begin(), payload.end());
+    check_transfer_frames(recorded, frames);
+}
+
+// 0.27.0 sends a transfer's chunks wide to a peer whose connection's SCTP takes 64 KiB messages
+// (`peer-transport.ts`'s `maxBulkFrameBytes`), as the memory network's does by default, Chrome's
+// 256 KiB: the offer carries the flag 64 and each chunk fills a 64 KiB message.
+void a_wide_link_sends_wide_chunks() {
+    fixture f{true};
+    a_transfer_sends_the_frames_of(f, "bulk_wide");
+}
+
+// To a peer whose connection takes smaller messages, or does not say, 0.27.0 sends its chunks
+// narrow, each a 16 KiB frame.
+void a_narrow_link_sends_narrow_chunks() {
+    for (const auto size : {
+             std::optional(std::size_t{16} * 1024),
+             std::optional(trystero::protocol::max_bulk_frame_bytes - 1),
+             std::optional(),
+         }) {
+        fixture f{true};
+        f.net.max_message_size = size;
+        a_transfer_sends_the_frames_of(f, "bulk");
+    }
+}
+
+// A channel that refuses a chunk its connection announced it takes (the memory network says 256 KiB
+// and its channels send at most a narrow frame) closes, as the platform's channel closes on a
+// refused send: the transfer ends with the peer (peer_disconnected), rather than waiting on a chunk
+// that was never sent until it times out (transfer_timed_out).
+void a_refused_chunk_ends_the_transfer_with_the_peer() {
+    fixture f{true};
+    f.net.send_limit = trystero::protocol::max_action_frame_bytes;
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("AAAAAAAAAAAAAAAAAAAA"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("BBBBBBBBBBBBBBBBBBBB"));
+    auto a = join(a_app, "refused");
+    auto b = join(b_app, "refused");
+    bool got = false;
+    b.make_action("file").on_message(
+        [&](const trystero::bytes&, const trystero::message_info&) { got = true; });
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })));
+    // The peers' departure is seen as events: the apps meet again by their announcements, so that
+    // "no peers" is a state that a reconnection may already have left by the time it is looked at.
+    std::size_t a_left = 0;
+    std::size_t b_left = 0;
+    a.on_peer_leave([&](const trystero::peer_event&) { ++a_left; });
+    b.on_peer_leave([&](const trystero::peer_event&) { ++b_left; });
+    std::optional sent;
+    a.make_action("file").async_send(
+        trystero::bytes(std::size_t{200} * 1024, 7), trystero::send_options(),
+        [&](boost::system::error_code ec) { sent = ec; });
+    BOOST_TEST(run_until(f, [&] { return sent.has_value() && a_left == 1 && b_left == 1; }));
+    BOOST_TEST(sent == std::optional(
+                           make_error_code(trystero::error::peer_disconnected)));
+    BOOST_TEST(a_left == 1);
+    BOOST_TEST(b_left == 1);
+    BOOST_TEST(!got);
+}
+
+// The action wire of a room alone, fed a peer's frames as a data channel hands them over: what it
+// sends back, what it delivers, and the peers it drops.
+struct wire_bench {
+    // A channel whose buffered bytes the case sets; channel_link's destructor is protected.
+    struct link final : trystero::detail::channel_link {
+        std::vector sent;
+        std::size_t buffered = 0;
+
+        bool send(std::span frame) override {
+            sent.emplace_back(frame.begin(), frame.end());
+            return true;
+        }
+
+        [[nodiscard]] std::size_t buffered_amount() const override { return buffered; }
+
+        void wait_drained(trystero::handler done) override { done(true); }
+
+        /** Narrow, as a transport that says no SCTP size: the bench's transfers are its cases'. */
+        [[nodiscard]] std::size_t max_bulk_frame_bytes() const override {
+            return trystero::protocol::max_action_frame_bytes;
+        }
+    };
+
+    fixture f{true};
+    std::shared_ptr channel = std::make_shared();
+    /** The actions the room made, and those of them that listen. */
+    std::set> actions{"file"};
+    std::set> listeners{"file"};
+    /** Whether dropping a peer clears it from the wire at once, as a room's kick does. */
+    bool clear_dropped = false;
+    std::vector delivered;
+    std::vector dropped;
+    /** The reasons the wire gave for refusing a message. */
+    std::vector refused;
+    std::shared_ptr wire;
+    // The virtual clock starts with the network's first timer: one made here, so that the clock
+    // the wire reads moves with advance() before the wire makes a timer of its own.
+    std::shared_ptr clock_start;
+
+    /** @param max_receive_bytes The wire's bound, the room's default unless a case lowers it. */
+    explicit wire_bench(
+        std::size_t max_receive_bytes = trystero::room_options{}.max_receive_bytes) {
+        using trystero::detail::action_wire;
+        auto* const memory = std::pmr::get_default_resource();
+        clock_start = f.net.make_timer(memory);
+        wire = std::make_shared(
+            f.net, max_receive_bytes,
+            action_wire::callbacks{
+                .find_link = [this](std::string_view, bool) -> std::optional {
+                    return action_wire::link{
+                        std::weak_ptr(channel),
+                    };
+                },
+                .peers = [memory](bool) { return std::pmr::vector(memory); },
+                .may_receive = [](std::string_view, std::string_view) { return true; },
+                .has_action = [this](std::string_view name) { return actions.contains(name); },
+                .has_listener = [this](std::string_view name) { return listeners.contains(name); },
+                .deliver =
+                    [this](trystero::detail::incoming&& m) { delivered.push_back(std::move(m)); },
+                .fail_peer =
+                    [this](std::string_view peer, std::string_view reason) {
+                        dropped.emplace_back(reason);
+                        if (clear_dropped) {
+                            wire->clear_peer(peer,
+                                             make_error_code(trystero::error::peer_disconnected));
+                        }
+                    },
+                .rejected = [this](std::string_view, std::string_view, std::string_view,
+                                   std::string_view reason) { refused.emplace_back(reason); },
+            },
+            memory);
+    }
+
+    /** Hands the wire an action frame of `peer`. */
+    void receive(std::string_view peer, trystero::backend::bytes frame) const {
+        wire->handle(peer, std::move(frame));
+    }
+
+    /** The action frames the wire sent, bare as it writes them. */
+    [[nodiscard]] std::vector sent() const {
+        std::vector out;
+        for (const auto& frame : channel->sent) {
+            out.push_back(*trystero::protocol::decode_action(frame).frame);
+        }
+        return out;
+    }
+};
+
+// A transfer offered with 0.27.0's wide flag arrives in chunks of 65,522 bytes, which may come in
+// any order, each once; a chunk of another length, or one that came already, drops the peer.
+void a_wide_transfer_arrives_in_wide_chunks_in_any_order() {
+    namespace tp = trystero::protocol;
+    trystero::bytes payload(std::size_t{200} * 1024);
+    for (std::size_t i = 0; i < payload.size(); ++i) {
+        payload[i] = static_cast(i * 31);
+    }
+    wire_bench b;
+    b.receive("A", tp::encode_offer("file", tp::payload_format::binary, R"({"n":1})", 5,
+                                    payload.size(), tp::chunk_width::wide));
+    const auto answers = b.sent();
+    if (!BOOST_TEST_EQ(answers.size(), 1U)) {
+        return;
+    }
+    const auto& accepted = std::get(answers[0]);
+    BOOST_TEST(accepted.kind == tp::frame_kind::accepted);
+    BOOST_TEST_EQ(accepted.id, 5U);
+    for (const std::size_t index : {3U, 1U, 0U, 2U}) {
+        const auto offset = index * tp::wide_chunk_size;
+        const auto length = std::min(tp::wide_chunk_size, payload.size() - offset);
+        b.receive("A", tp::encode_chunk(5, offset, std::span(payload).subspan(offset, length)));
+    }
+    BOOST_TEST(b.dropped.empty());
+    if (BOOST_TEST_EQ(b.delivered.size(), 1U)) {
+        const auto got = b.delivered[0].payload();
+        BOOST_TEST_ALL_EQ(got.begin(), got.end(), payload.begin(), payload.end());
+        BOOST_TEST_EQ(b.delivered[0].metadata(), R"({"n":1})");
+        BOOST_TEST_EQ(b.delivered[0].name(), "file");
+    }
+
+    wire_bench narrow;
+    narrow.receive("A", tp::encode_offer("file", tp::payload_format::binary, "", 6, payload.size(),
+                                         tp::chunk_width::wide));
+    narrow.receive("A", tp::encode_chunk(6, 0, std::span(payload).first(tp::chunk_size)));
+    if (BOOST_TEST_EQ(narrow.dropped.size(), 1U)) {
+        BOOST_TEST_EQ(narrow.dropped[0], "invalid action chunk");
+    }
+
+    wire_bench twice;
+    twice.receive("A", tp::encode_offer("file", tp::payload_format::binary, "", 7, payload.size()));
+    twice.receive("A",
+                  tp::encode_chunk(7, tp::chunk_size,
+                                   std::span(payload).subspan(tp::chunk_size, tp::chunk_size)));
+    BOOST_TEST(twice.dropped.empty());
+    twice.receive("A",
+                  tp::encode_chunk(7, tp::chunk_size,
+                                   std::span(payload).subspan(tp::chunk_size, tp::chunk_size)));
+    BOOST_TEST_EQ(twice.dropped.size(), 1U);
+    if (!twice.dropped.empty()) {
+        BOOST_TEST_EQ(twice.dropped[0], "invalid action chunk");
+    }
 }
 
-void the_same_password_joins_and_another_does_not() {
+// 0.27.0 keeps at most 1024 transfers pending across peers and 64 of one peer, and rejects the
+// next offer as "too many pending transfers"; it keeps at most 32 messages of one action and peer
+// until the action listens, a newer one dropping the oldest, for 10 s, and no bound across actions.
+void the_wire_keeps_0_27_0s_bounds() {
+    namespace tp = trystero::protocol;
+    const auto rejections = [](const wire_bench& b) {
+        std::size_t n = 0;
+        for (const auto& frame : b.sent()) {
+            const auto* m = std::get_if(&frame);
+            n += m != nullptr && m->kind == tp::frame_kind::rejected &&
+                         m->reason == "too many pending transfers"
+                     ? 1
+                     : 0;
+        }
+        return n;
+    };
+    {
+        wire_bench b;
+        b.actions.insert("later");
+        for (std::uint32_t id = 0; id <= tp::max_pending_transfers_per_peer; ++id) {
+            b.receive("A", tp::encode_offer("later", tp::payload_format::binary, "", id, 20000));
+        }
+        BOOST_TEST_EQ(rejections(b), 1U);
+        for (std::size_t peer = 1;
+             peer < tp::max_pending_transfers / tp::max_pending_transfers_per_peer; ++peer) {
+            for (std::uint32_t id = 0; id < tp::max_pending_transfers_per_peer; ++id) {
+                b.receive("P" + std::to_string(peer),
+                          tp::encode_offer("later", tp::payload_format::binary, "", id, 20000));
+            }
+        }
+        BOOST_TEST_EQ(rejections(b), 1U);
+        b.receive("Z", tp::encode_offer("later", tp::payload_format::binary, "", 0, 20000));
+        BOOST_TEST_EQ(rejections(b), 2U);
+        BOOST_TEST(b.dropped.empty());
+    }
+    {
+        wire_bench b;
+        b.actions.insert({"later", "other"});
+        for (std::size_t i = 0; i <= tp::max_pre_listener_messages; ++i) {
+            b.receive("A", tp::encode_inline("later", tp::payload_format::binary, "",
+                                             trystero::bytes{static_cast(i)}));
+        }
+        b.receive("A",
+                  tp::encode_inline("other", tp::payload_format::binary, "", trystero::bytes{99}));
+        b.listeners.insert("later");
+        b.wire->listener_added();
+        if (BOOST_TEST_EQ(b.delivered.size(), tp::max_pre_listener_messages)) {
+            for (std::size_t i = 0; i < b.delivered.size(); ++i) {
+                BOOST_TEST_EQ(b.delivered[i].payload()[0], i + 1);
+            }
+        }
+        trystero::test::advance(b.f, 10'001ms);
+        b.listeners.insert("other");
+        b.wire->listener_added();
+        BOOST_TEST_EQ(b.delivered.size(), tp::max_pre_listener_messages);
+    }
+    {
+        // Each action of a peer has a ring of its own: three full ones keep 96 messages.
+        wire_bench b;
+        const std::array names{"n0", "n1", "n2"};
+        for (const auto& name : names) {
+            b.actions.insert(name);
+            for (std::size_t i = 0; i < tp::max_pre_listener_messages; ++i) {
+                b.receive("A", tp::encode_inline(name, tp::payload_format::binary, "",
+                                                 trystero::bytes{1}));
+            }
+        }
+        b.listeners.insert(names.begin(), names.end());
+        b.wire->listener_added();
+        BOOST_TEST_EQ(b.delivered.size(), names.size() * tp::max_pre_listener_messages);
+        BOOST_TEST(b.dropped.empty());
+    }
+}
+
+// As 0.27.0's handleData: an inline frame of an action the room has not made is dropped, and not
+// delivered once it is made; an offer of one is rejected at once as an "unregistered action", and
+// takes no pending slot.
+void frames_of_an_action_not_made_are_dropped_or_rejected() {
+    namespace tp = trystero::protocol;
+    wire_bench b;
+    b.receive("A", tp::encode_inline("late", tp::payload_format::text, "", trystero::bytes{'x'}));
+    BOOST_TEST(b.channel->sent.empty());
+    b.actions.insert("late");
+    b.listeners.insert("late");
+    b.wire->listener_added();
+    BOOST_TEST(b.delivered.empty());
+
+    wire_bench offered;
+    offered.receive("A", tp::encode_offer("late", tp::payload_format::binary, "", 3, 20000));
+    const auto answers = offered.sent();
+    if (BOOST_TEST_EQ(answers.size(), 1U)) {
+        const auto& m = std::get(answers[0]);
+        BOOST_TEST(m.kind == tp::frame_kind::rejected);
+        BOOST_TEST_EQ(m.id, 3U);
+        BOOST_TEST_EQ(m.reason, "unregistered action");
+    }
+    offered.actions.insert("later");
+    for (std::uint32_t id = 0; id < tp::max_pending_transfers_per_peer; ++id) {
+        offered.receive("A", tp::encode_offer("later", tp::payload_format::binary, "", id, 20000));
+    }
+    BOOST_TEST_EQ(offered.sent().size(), 1U);
+    BOOST_TEST(offered.dropped.empty());
+}
+
+// An inline frame whose payload is above `max_receive_bytes` is dropped, reported as "payload
+// exceeds receiver size limit", as 0.27.0's payloadLimit applies to it; one at the bound is
+// delivered. Nothing is sent back for an inline frame, and the peer is kept.
+void an_inline_frame_above_the_receive_bound_is_dropped() {
+    namespace tp = trystero::protocol;
+    wire_bench b(8);
+    b.receive("A", tp::encode_inline("file", tp::payload_format::binary, "",
+                                     trystero::bytes(9, std::uint8_t{1})));
+    BOOST_TEST(b.delivered.empty());
+    if (BOOST_TEST_EQ(b.refused.size(), 1U)) {
+        BOOST_TEST_EQ(b.refused.front(), "payload exceeds receiver size limit");
+    }
+    b.receive("A", tp::encode_inline("file", tp::payload_format::binary, "",
+                                     trystero::bytes(8, std::uint8_t{2})));
+    BOOST_TEST_EQ(b.delivered.size(), 1U);
+    BOOST_TEST_EQ(b.refused.size(), 1U);
+    BOOST_TEST(b.channel->sent.empty());
+    BOOST_TEST(b.dropped.empty());
+}
+
+// A control frame goes out only while the channel buffers at most 1 MiB, as 0.27.0's
+// sendControlFrame checks: past it, the peer is dropped. A room drops it at once, from within the
+// wire's drain, which goes on to the next peer.
+void a_control_frame_into_a_full_channel_drops_the_peer() {
+    namespace tp = trystero::protocol;
+    wire_bench b;
+    b.channel->buffered = tp::max_control_buffered_bytes + 1;
+    b.receive("A", tp::encode_offer("file", tp::payload_format::binary, "", 1, 20000));
+    BOOST_TEST(b.channel->sent.empty());
+    if (BOOST_TEST_EQ(b.dropped.size(), 1U)) {
+        BOOST_TEST_EQ(b.dropped[0], "unable to send action control");
+    }
+    const wire_bench at_bound;
+    at_bound.channel->buffered = tp::max_control_buffered_bytes;
+    at_bound.receive("A", tp::encode_offer("file", tp::payload_format::binary, "", 1, 20000));
+    BOOST_TEST_EQ(at_bound.channel->sent.size(), 1U);
+    BOOST_TEST(at_bound.dropped.empty());
+
+    wire_bench cleared;
+    cleared.clear_dropped = true;
+    cleared.actions.insert("later");
+    cleared.receive("A", tp::encode_offer("later", tp::payload_format::binary, "", 1, 20000));
+    cleared.receive("B", tp::encode_offer("later", tp::payload_format::binary, "", 1, 20000));
+    cleared.channel->buffered = tp::max_control_buffered_bytes + 1;
+    cleared.listeners.insert("later");
+    cleared.wire->listener_added();
+    BOOST_TEST(cleared.channel->sent.empty());
+    BOOST_TEST_EQ(cleared.dropped.size(), 2U);
+    cleared.channel->buffered = 0;
+    cleared.receive("A", tp::encode_offer("later", tp::payload_format::binary, "", 1, 20000));
+    BOOST_TEST_EQ(cleared.channel->sent.size(), 1U);  // A's transfer is gone: id 1 is new again
+}
+
+// Peers of another password never meet: 0.27.0 keeps them out by the sealing of their signals
+// alone, with no password challenge on the connection, which is never made.
+void two_passwords_never_meet() {
     fixture f{true};
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("FFFFFFFFFFFFFFFFFFFF", "s3cret"));
+    const auto labels = ordered_labels(3, "private");
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config(labels[0], "s3cret"));
     auto a = join(a_app, "private");
-    trystero::app b_app(f.io.get_executor(), f.net, app_config("GGGGGGGGGGGGGGGGGGGG", "s3cret"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(labels[1], "s3cret"));
     auto b = join(b_app, "private");
     BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; }));
 
     // A and B, whose ids are lower, offer to the intruder, which cannot open their offers with its
-    // room key, so it never connects. It reports both: the first at once, with its peer, and the
-    // other with their number when the interval of its reports ends, 10 s later.
+    // room key, so it never connects. It reports each of them, with its peer.
     std::vector errors;
-    std::size_t refused = 0;
-    trystero::app intruder_app(f.io.get_executor(), f.net,
-                               app_config("HHHHHHHHHHHHHHHHHHHH", "guess"));
+    std::set refused;
+    trystero::test::app intruder_app(f.io.get_executor(), f.net, app_config(labels[2], "guess"));
     auto intruder = join(intruder_app, "private");
-    intruder.on_error(
-        [&](std::string_view peer, boost::system::error_code ec, std::string_view what) {
-            errors.push_back(ec);
-            if (ec == trystero::error::wrong_password) {
-                refused += peer.empty() ? std::stoul(std::string(what)) : 1;
-            }
-        });
-    a.on_error([&](std::string_view, boost::system::error_code ec, std::string_view) {
-        errors.push_back(ec);
+    intruder.on_error([&](const trystero::room_error& e) {
+        errors.push_back(e.code);
+        if (e.code == trystero::error::decrypt_failed) {
+            refused.emplace(e.peer_id);
+        }
     });
-    BOOST_TEST(run_until(f, [&] { return refused == 2; }, 20'000ms));
+    a.on_error([&](const trystero::room_error& e) { errors.push_back(e.code); });
+    BOOST_TEST(run_until(f, [&] { return refused.size() == 2; }, 20'000ms));
+    BOOST_TEST(refused ==
+               (std::set{std::string(a_app.self_id()), std::string(b_app.self_id())}));
     BOOST_TEST(intruder.peers().empty());
     BOOST_TEST_EQ(a.peers().size(), 1U);
     BOOST_TEST(!errors.empty());
     for (const auto& ec : errors) {
-        BOOST_TEST(ec == trystero::error::wrong_password);
+        BOOST_TEST(ec == trystero::error::decrypt_failed);
+    }
+}
+
+/** How many announcements of `peers` a watcher of `room`'s root topic sees. */
+struct announcement_watcher {
+    announcement_watcher(fixture& f, std::string_view room, std::vector peers)
+        : socket(f, room), of(std::move(peers)) {
+        socket.on_text = [this](std::string_view text) {
+            const auto signal = relayed_signal(text);
+            if (signal && signal->announcement && std::ranges::find(of, signal->peer) != of.end()) {
+                ++seen;
+            }
+        };
+        socket.watch(trystero::protocol::root_topic(app_id, room));
+    }
+
+    flooder socket;
+    std::vector of;
+    std::size_t seen = 0;
+};
+
+// Two rooms of apps with one password, over a memory backend that holds their derivations, as a
+// page's WebCrypto takes seconds: each join returns before its derivation completes, and while
+// they are held, for as long as their announcements would have gone out many times, no room
+// announces anything. Released, the two derive the same keys and meet.
+void password_room_keys_complete_after_the_join_returns() {
+    fixture f{true};
+    f.net.derive_delay = true;
+    const announcement_watcher watcher(f, "keyed", {peer_id_of("keyed-a"), peer_id_of("keyed-b")});
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("keyed-a", "s3cret"));
+    auto a = join(a_app, "keyed");
+    BOOST_TEST_EQ(f.net.derivations, 1U);
+    BOOST_TEST_EQ(f.net.held_derivations(), 1U);
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("keyed-b", "s3cret"));
+    auto b = join(b_app, "keyed");
+    BOOST_TEST_EQ(f.net.derivations, 2U);
+    // Qualified: a std::chrono argument finds std::advance by ADL, which libstdc++ prefers.
+    trystero::test::advance(f, 30s);
+    BOOST_TEST_EQ(f.net.held_derivations(), 2U);
+    BOOST_TEST_EQ(watcher.seen, 0U);
+    BOOST_TEST(a.peers().empty());
+    BOOST_TEST(b.peers().empty());
+
+    f.net.derive_delay = false;
+    f.net.release_derivations();
+    BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; }));
+    BOOST_TEST_GE(watcher.seen, 1U);
+    BOOST_TEST_EQ(f.net.derivations, 2U);
+}
+
+// An app derives a room's keys once per room id: two rooms, two derivations; the first room left
+// and joined again, none, its keys kept by the app. A room without a password derives none.
+void rooms_of_one_password_derive_once_per_room() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net,
+                              app_config("0aaaaaaaaaaaaaaaaaaa", "s3cret"));
+    {
+        auto first = join(a_app, "first");
+        const auto second = join(a_app, "second");
+        webcpp::test::require(BOOST_TEST(f.net.poll_ready()));
+        BOOST_TEST_EQ(f.net.derivations, 2U);
+        bool left = false;
+        first.async_leave([&](boost::system::error_code ec) { left = !ec; });
+        BOOST_TEST(run_until(f, [&] { return left; }));
+    }
+    const auto again = join(a_app, "first");
+    webcpp::test::require(BOOST_TEST(f.net.poll_ready()));
+    BOOST_TEST_EQ(f.net.derivations, 2U);
+
+    trystero::test::app open_app(f.io.get_executor(), f.net, app_config("0ccccccccccccccccccc"));
+    const auto open = join(open_app, "first");
+    webcpp::test::require(BOOST_TEST(f.net.poll_ready()));
+    BOOST_TEST_EQ(f.net.derivations, 2U);
+}
+
+// A derivation that fails, as WebCrypto's may: the room reports error::backend_failure through
+// its error handler and announces nothing; joined again, the room derives again, the failure
+// forgotten, and announces.
+void a_failed_derivation_is_retried() {
+    fixture f{true};
+    const std::string a_label = "failing-a";
+    announcement_watcher watcher(f, "failing", {peer_id_of(a_label)});
+    f.net.fail_derivations = 1;
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config(a_label, "s3cret"));
+    std::vector errors;
+    {
+        auto a = join(a_app, "failing");
+        a.on_error([&](const trystero::room_error& e) {
+            BOOST_TEST(e.peer_id.empty());
+            errors.push_back(e.code);
+        });
+        trystero::test::advance(f, 30s);
+        BOOST_TEST_EQ(f.net.derivations, 1U);
+        if (BOOST_TEST_EQ(errors.size(), 1U)) {
+            BOOST_TEST(errors.front() == trystero::error::backend_failure);
+        }
+        BOOST_TEST_EQ(watcher.seen, 0U);
+        bool left = false;
+        a.async_leave([&](boost::system::error_code ec) { left = !ec; });
+        BOOST_TEST(run_until(f, [&] { return left; }));
     }
+    const auto again = join(a_app, "failing");
+    BOOST_TEST(run_until(f, [&] { return watcher.seen >= 1; }));
+    BOOST_TEST_EQ(f.net.derivations, 2U);
+    BOOST_TEST_EQ(errors.size(), 1U);
+}
+
+// A room left, and its app ended, while the room's derivation is held: once released, the
+// derivation completes into nothing, as the room and the app are gone. No announcement leaves, no
+// handler of the room runs, and nothing it allocated is touched (the allocation test covers its
+// memory; here the room's own resource is checked empty). A
+// room of the same id joined again while the derivation is still held completes from it.
+void a_room_left_while_its_keys_derive_announces_nothing() {
+    counting_resource memory;  // first: the io_context's pending operations free into it
+    fixture f{true};
+    f.net.derive_delay = true;
+    const std::string a_id = "leaving-a";  // the label of A's endpoint key
+    announcement_watcher watcher(f, "leaving", {peer_id_of(a_id)});
+    std::size_t errors = 0;
+    {
+        auto c = app_config(a_id, "s3cret");
+        c.memory = &memory;
+        trystero::test::app a_app(f.io.get_executor(), f.net, std::move(c));
+        {
+            auto a = join(a_app, "leaving");
+            a.on_error([&errors](const trystero::room_error&) { ++errors; });
+            bool left = false;
+            a.async_leave([&](boost::system::error_code ec) { left = !ec; });
+            BOOST_TEST(run_until(f, [&] { return left; }));
+        }
+        BOOST_TEST_EQ(f.net.held_derivations(), 1U);
+        // Joined again while the first derivation is held: it waits for that one.
+        const auto again = join(a_app, "leaving");
+        webcpp::test::require(BOOST_TEST(f.net.poll_ready()));
+        BOOST_TEST_EQ(f.net.derivations, 1U);
+        f.net.derive_delay = false;
+        f.net.release_derivations();
+        BOOST_TEST(run_until(f, [&] { return watcher.seen >= 1; }));
+        BOOST_TEST_EQ(f.net.derivations, 1U);
+    }
+    // And once more, the app ended while held.
+    watcher.seen = 0;
+    f.net.derive_delay = true;
+    {
+        auto c = app_config(a_id, "s3cret");
+        c.memory = &memory;
+        trystero::test::app a_app(f.io.get_executor(), f.net, std::move(c));
+        auto a = join(a_app, "leaving");
+        a.on_error([&errors](const trystero::room_error&) { ++errors; });
+        BOOST_TEST_EQ(f.net.held_derivations(), 1U);
+    }
+    f.net.derive_delay = false;
+    f.net.release_derivations();
+    trystero::test::advance(f, 30'000ms);
+    BOOST_TEST_EQ(f.net.derivations, 2U);
+    BOOST_TEST_EQ(watcher.seen, 0U);
+    BOOST_TEST_EQ(errors, 0U);
+    BOOST_TEST_EQ(memory.in_use, 0U);
+}
+
+// The app's cache keeps the keys of 64 rooms, the least recently asked for leaving first, as
+// 0.27.0's derivedRoomKeysCache: 65 rooms derive 65 times, the first, asked for again, once more,
+// and the last, asked for again, not at all; a room asked for again while it derives waits for
+// that derivation. Every key of one room is the same, and two rooms' keys differ.
+void the_room_keys_cache_keeps_64_rooms() {
+    fixture f{true};
+    const auto cache = std::allocate_shared(
+        std::pmr::polymorphic_allocator<>(std::pmr::get_default_resource()), f.io.get_executor(),
+        f.net, app_id, "s3cret", std::pmr::get_default_resource());
+    std::map>> keys;
+    const auto get = [&](const std::string& room) {
+        // The room's list, made now: the completion holds a pointer, which moves without
+        // allocating, where a copy of the name would.
+        auto* const list = &keys[room];
+        cache->get(room,
+                   [list](boost::system::error_code ec, const trystero::protocol::room_keys& k) {
+                       BOOST_TEST(!ec);
+                       std::array aes{};
+                       std::ranges::copy(k.aes.bytes(), aes.begin());
+                       list->push_back(aes);
+                   });
+    };
+    constexpr std::size_t capacity = trystero::detail::room_keys_cache::capacity;
+    BOOST_TEST_EQ(capacity, 64U);
+    get("room0");
+    get("room0");  // while it derives
+    for (std::size_t i = 1; i <= capacity; ++i) {
+        get("room" + std::to_string(i));
+    }
+    webcpp::test::require(BOOST_TEST(f.net.poll_ready()));
+    BOOST_TEST_EQ(f.net.derivations, capacity + 1);
+    BOOST_TEST_EQ(cache->size(), capacity);
+    get(std::string("room") + std::to_string(capacity));
+    webcpp::test::require(BOOST_TEST(f.net.poll_ready()));
+    BOOST_TEST_EQ(f.net.derivations, capacity + 1);
+    get("room0");
+    webcpp::test::require(BOOST_TEST(f.net.poll_ready()));
+    BOOST_TEST_EQ(f.net.derivations, capacity + 2);
+    BOOST_TEST_EQ(cache->size(), capacity);
+    BOOST_TEST_EQ(keys["room0"].size(), 3U);
+    BOOST_TEST(keys["room0"][0] == keys["room0"][1]);
+    BOOST_TEST(keys["room0"][0] == keys["room0"][2]);
+    BOOST_TEST(keys["room0"][0] != keys["room1"][0]);
 }
 
 void leaving_is_seen_by_the_others_and_a_return_reconnects() {
-    fixture f;
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("IIIIIIIIIIIIIIIIIIII"));
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("IIIIIIIIIIIIIIIIIIII"));
     auto a = join(a_app, "leave");
     std::vector left;
     std::vector joined;
-    a.on_peer_leave([&](std::string_view p) { left.emplace_back(p); });
-    a.on_peer_join([&](std::string_view p) { joined.emplace_back(p); });
+    a.on_peer_leave([&](const trystero::peer_event& e) { left.emplace_back(e.peer_id); });
+    a.on_peer_join([&](const trystero::peer_event& e) { joined.emplace_back(e.peer_id); });
     {
         // B's app goes with its room, so that its return negotiates again: a living app would keep
         // the connection, idle, and bind the returning room over it.
-        trystero::app b_app(f.io.get_executor(), f.net, app_config("JJJJJJJJJJJJJJJJJJJJ"));
+        trystero::test::app b_app(f.io.get_executor(), f.net, app_config("JJJJJJJJJJJJJJJJJJJJ"));
         auto b = join(b_app, "leave");
-        BOOST_TEST(run_until(f.io, [&] { return joined.size() == 1; }));
+        BOOST_TEST(run_until(f, [&] { return joined.size() == 1; }));
         bool done = false;
         b.async_leave([&](boost::system::error_code ec) { done = !ec; });
-        BOOST_TEST(run_until(f.io, [&] { return done && left.size() == 1; }));
+        BOOST_TEST(run_until(f, [&] { return done && left.size() == 1; }));
         BOOST_TEST(a.peers().empty());
     }
-    trystero::app b2_app(f.io.get_executor(), f.net, app_config("JJJJJJJJJJJJJJJJJJJJ"));
+    trystero::test::app b2_app(f.io.get_executor(), f.net, app_config("JJJJJJJJJJJJJJJJJJJJ"));
     const auto b2 = join(b2_app, "leave");
-    BOOST_TEST(run_until(f.io, [&] { return joined.size() == 2; }));
+    BOOST_TEST(run_until(f, [&] { return joined.size() == 2; }));
 }
 
 // A room moved over a joined one leaves it as destroying it does: the other peer sees it go, and
 // its pending operations complete with room_left, while an action of it still holds its state.
 void moving_a_room_over_a_joined_one_leaves_it() {
-    fixture f;
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("KKKKKKKKKKKKKKKKKKKK"));
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("KKKKKKKKKKKKKKKKKKKK"));
     auto a = join(a_app, "move");
     std::vector left;
     std::vector joined;
-    a.on_peer_leave([&](std::string_view p) { left.emplace_back(p); });
-    a.on_peer_join([&](std::string_view p) { joined.emplace_back(p); });
-    trystero::app b_app(f.io.get_executor(), f.net, app_config("LLLLLLLLLLLLLLLLLLLL"));
+    a.on_peer_leave([&](const trystero::peer_event& e) { left.emplace_back(e.peer_id); });
+    a.on_peer_join([&](const trystero::peer_event& e) { joined.emplace_back(e.peer_id); });
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("LLLLLLLLLLLLLLLLLLLL"));
     auto b = join(b_app, "move");
     auto pending = b.make_action("pending");
     std::optional received;
     pending.async_receive([&](boost::system::error_code ec, const std::string& /*text*/,
                               const trystero::message_info& /*info*/) { received = ec; });
-    BOOST_TEST(run_until(f.io, [&] { return joined.size() == 1; }));
+    BOOST_TEST(run_until(f, [&] { return joined.size() == 1; }));
 
     b = join(b_app, "elsewhere");
-    BOOST_TEST(run_until(f.io, [&] { return left.size() == 1 && received.has_value(); }));
+    BOOST_TEST(run_until(f, [&] { return left.size() == 1 && received.has_value(); }));
     BOOST_TEST(a.peers().empty());
     if (BOOST_TEST(received.has_value())) {
         BOOST_TEST(*received == trystero::error::room_left);
@@ -346,7 +1070,7 @@ void ice_urls_are_checked_as_webrtc_checks_them() {
 // A server WebRTC would refuse is dropped when the app is made, and reported to the app's on_error
 // with no peer, after the constructor returns; its room goes on with the usable one, and joins.
 void unusable_ice_servers_are_dropped_and_reported() {
-    fixture f;
+    fixture f{true};
     f.net.record_servers = true;
     auto c = app_config("NNNNNNNNNNNNNNNNNNNN");
     const auto server = [](const char* url, const char* username, const char* credential) {
@@ -361,16 +1085,19 @@ void unusable_ice_servers_are_dropped_and_reported() {
     c.ice_servers.push_back(server("turn:127.0.0.1:9", "", ""));    // no credentials
     c.ice_servers.push_back(server("turn:127.0.0.1:9", "user", "secret"));
     c.ice_servers.push_back(server("STUN:127.0.0.2:9", "", ""));  // a scheme in capitals
-    trystero::app a_app(f.io.get_executor(), f.net, std::move(c));
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(c));
     auto a = join(a_app, "ice");
     std::vector> errors;
-    a_app.on_error([&](std::string_view peer, boost::system::error_code ec,
-                       std::string_view /*what*/) { errors.emplace_back(peer, ec); });
+    a_app.on_error([&](const trystero::room_error& e) {
+        BOOST_TEST_EQ(e.app_id, app_id);
+        BOOST_TEST(e.room_id.empty());
+        errors.emplace_back(e.peer_id, e.code);
+    });
     std::vector joined;
-    a.on_peer_join([&](std::string_view p) { joined.emplace_back(p); });
-    trystero::app b_app(f.io.get_executor(), f.net, app_config("OOOOOOOOOOOOOOOOOOOO"));
+    a.on_peer_join([&](const trystero::peer_event& e) { joined.emplace_back(e.peer_id); });
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("OOOOOOOOOOOOOOOOOOOO"));
     const auto b = join(b_app, "ice");
-    BOOST_TEST(run_until(f.io, [&] { return joined.size() == 1 && errors.size() == 2; }));
+    BOOST_TEST(run_until(f, [&] { return joined.size() == 1 && errors.size() == 2; }));
     for (const auto& [peer, ec] : errors) {
         BOOST_TEST(peer.empty());
         BOOST_TEST(ec == trystero::error::invalid_configuration);
@@ -387,20 +1114,19 @@ void unusable_ice_servers_are_dropped_and_reported() {
 // negotiation with that peer reported to on_error; the next announcement starts another, which
 // connects.
 void a_refused_peer_connection_is_reported_and_tried_again() {
-    fixture f;
+    fixture f{true};
     f.net.refuse_peer_connections = 1;
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("PPPPPPPPPPPPPPPPPPPP"));
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("PPPPPPPPPPPPPPPPPPPP"));
     auto a = join(a_app, "refused");
-    trystero::app b_app(f.io.get_executor(), f.net, app_config("QQQQQQQQQQQQQQQQQQQQ"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("QQQQQQQQQQQQQQQQQQQQ"));
     auto b = join(b_app, "refused");
     std::vector errors;
-    const auto on_error = [&](std::string_view /*peer*/, boost::system::error_code ec,
-                              std::string_view /*what*/) { errors.push_back(ec); };
+    const auto on_error = [&](const trystero::room_error& e) { errors.push_back(e.code); };
     a.on_error(on_error);
     b.on_error(on_error);
     std::vector joined;
-    a.on_peer_join([&](std::string_view p) { joined.emplace_back(p); });
-    BOOST_TEST(run_until(f.io, [&] { return joined.size() == 1; }, 30s));
+    a.on_peer_join([&](const trystero::peer_event& e) { joined.emplace_back(e.peer_id); });
+    BOOST_TEST(run_until(f, [&] { return joined.size() == 1; }, 30s));
     if (BOOST_TEST_EQ(errors.size(), 1U)) {
         BOOST_TEST(errors.at(0) == trystero::error::backend_failure);
     }
@@ -433,12 +1159,12 @@ void a_flood_of_announcements_is_bounded() {
     fixture f{true};
     auto c = app_config("00000000000000000000");  // lower than every flooder: it offers to each
     c.memory = &memory;
-    trystero::app a_app(f.io.get_executor(), f.net, std::move(c));
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(c));
     auto a = join(a_app, "flood");
-    trystero::app b_app(f.io.get_executor(), f.net, app_config("BBBBBBBBBBBBBBBBBBBB"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("BBBBBBBBBBBBBBBBBBBB"));
     auto b = join(b_app, "flood");
     std::vector joined;
-    a.on_peer_join([&](std::string_view p) { joined.emplace_back(p); });
+    a.on_peer_join([&](const trystero::peer_event& e) { joined.emplace_back(e.peer_id); });
     auto chat_a = a.make_action("chat");
     auto chat_b = b.make_action("chat");
     std::vector heard;
@@ -465,7 +1191,7 @@ void a_flood_of_announcements_is_bounded() {
         constexpr std::size_t batch = 1000;
         for (std::size_t sent = 0; sent < count; sent += batch) {
             if (sent > 0) {
-                advance(f, minute);
+                trystero::test::advance(f, minute);
             }
             const std::size_t now = std::min(batch, count - sent);
             const auto before = f.net.relay(relay_a).events_seen;
@@ -484,7 +1210,7 @@ void a_flood_of_announcements_is_bounded() {
     // Once every offer to a flooder expired, its negotiation is gone, and a new peer joins.
     BOOST_TEST(
         run_until(f, [&] { return f.net.live_connections() == joined_connections; }, minute));
-    trystero::app late_app(f.io.get_executor(), f.net, app_config("CCCCCCCCCCCCCCCCCCCC"));
+    trystero::test::app late_app(f.io.get_executor(), f.net, app_config("CCCCCCCCCCCCCCCCCCCC"));
     const auto late = join(late_app, "flood");
     BOOST_TEST(run_until(f, [&] { return joined.size() == 2; }));
     BOOST_TEST_EQ(heard.size(), 1U);
@@ -500,18 +1226,33 @@ void a_flood_of_announcements_is_bounded() {
 
 // A watcher without the room key answers every offer of A to B with garbage, in B's name, before
 // B's own answer: A opens an answer before acting on it, so the forged ones change nothing, A and
-// B join, and A reports the failed open at most once for B.
+// B join, and A reports the failed open once for B, at the answer stage, with 0.27.0's message.
 void a_forged_answer_changes_nothing() {
-    fixture f;
-    const std::string_view a_id = "AAAAAAAAAAAAAAAAAAAA";
-    const std::string_view b_id = "BBBBBBBBBBBBBBBBBBBB";
-    trystero::app a_app(f.io.get_executor(), f.net, app_config(a_id));
+    fixture f{true};
+    const auto labels = ordered_labels(2, "forged");  // A offers to B
+    const std::string a_id = peer_id_of(labels[0]);
+    const std::string b_id = peer_id_of(labels[1]);
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config(labels[0]));
     auto a = join(a_app, "forged");
     std::vector joined;
-    a.on_peer_join([&](std::string_view p) { joined.emplace_back(p); });
-    std::vector errors;
-    a.on_error([&](std::string_view /*peer*/, boost::system::error_code ec,
-                   std::string_view /*what*/) { errors.push_back(ec); });
+    a.on_peer_join([&](const trystero::peer_event& e) { joined.emplace_back(e.peer_id); });
+
+    struct report {
+        boost::system::error_code code;
+        std::string message;
+        std::string peer_id;
+        std::optional stage;
+    };
+
+    std::vector errors;
+    a.on_error([&](const trystero::room_error& e) {
+        errors.push_back({
+            .code = e.code,
+            .message = std::string(e.message),
+            .peer_id = std::string(e.peer_id),
+            .stage = e.stage,
+        });
+    });
     flooder attacker(f, "forged");
     const auto a_topic = trystero::protocol::peer_topic(app_id, "forged", a_id);
     std::size_t forged = 0;
@@ -525,11 +1266,19 @@ void a_forged_answer_changes_nothing() {
         }
     };
     attacker.watch(trystero::protocol::peer_topic(app_id, "forged", b_id));
-    trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(labels[1]));
     const auto b = join(b_app, "forged");
-    BOOST_TEST(run_until(f.io, [&] { return joined.size() == 1; }));
+    BOOST_TEST(run_until(f, [&] { return joined.size() == 1; }));
     BOOST_TEST_GE(forged, 1U);
-    BOOST_TEST_LE(errors.size(), 1U);
+    // The forged answers reach A before B's own, so the first one is reported, and only it.
+    BOOST_TEST_EQ(errors.size(), 1U);
+    for (const auto& e : errors) {
+        BOOST_TEST(e.code == trystero::error::decrypt_failed);
+        BOOST_TEST_EQ(e.peer_id, b_id);
+        BOOST_TEST(e.stage == trystero::signal_stage::answer);
+        BOOST_TEST_EQ(e.message,
+                      "failed to decrypt answer (incorrect password or corrupted signal)");
+    }
 }
 
 // Offers from fresh ids that are not sealed with the room key make no connection: a negotiation
@@ -538,22 +1287,22 @@ void a_forged_answer_changes_nothing() {
 void forged_offers_make_no_connection() {
     constexpr std::size_t flood = 200;
     fixture f{true};
-    auto c = app_config("zzzzzzzzzzzzzzzzzzzz");
+    auto c = app_config(label_beside("1", false));  // above the flood's ids, which offer
     std::size_t refused = 0;
     c.log = [&](std::string_view /*category*/, std::string_view text) {
         refused += text.starts_with("could not open the offer from 0offer") ? 1 : 0;
     };
-    trystero::app a_app(f.io.get_executor(), f.net, std::move(c));
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(c));
     const auto a = join(a_app, "offers");
     flooder attacker(f, "offers");
-    const auto a_topic = trystero::protocol::peer_topic(app_id, "offers", "zzzzzzzzzzzzzzzzzzzz");
+    const auto a_topic = trystero::protocol::peer_topic(app_id, "offers", a_app.self_id());
     // Twenty at a time, all at one instant, each twenty refused before the next comes. A new id
     // beyond the room's 32 negotiations takes the place of one already refused, which is idle: one
     // whose offer is being opened keeps its place. More than 32 at once would have the later ids
     // refused at the bound, unopened (a_flood_of_offers_at_one_instant_is_bounded).
     const auto instant = f.net.steady_now();
     for (std::size_t i = 0; i < flood; ++i) {
-        const std::string id = "0offer" + std::to_string(i);
+        const std::string id = signal_id("0offer", i);
         attacker.publish(a_topic,
                          {.peer_id = id, .offer_id = "offer", .offer = "not a sealed offer"});
         if (i % 20 == 19 && !BOOST_TEST(run_until(f, [&] { return refused == i + 1; }))) {
@@ -565,248 +1314,132 @@ void forged_offers_make_no_connection() {
     BOOST_TEST(f.net.steady_now() == instant);
 }
 
-// Two peers offer to a room at one instant, and the room's sealer takes its time to open their
-// offers, as Web Crypto's does in a page; meanwhile, at the same instant, as many new ids announce
-// as the room holds negotiations (max_unconnected_peers): they fill every other place, and the last
-// two take the places of idle negotiations. One whose offer is being opened is not idle, so both
-// peers join at that instant, as with Trystero, which bounds nothing. At one instant no negotiation
-// has been idle longer than another, and the peers' ids sort before the others'. When a
-// negotiation was idle as soon as it held no connection, the tie went to the first in id order:
-// the last two ids took the peers' places, the room dropped both offers unopened, and the peers
-// joined only when they offered again, 2 s later (measured).
-void an_offer_being_opened_keeps_its_place() {
-    constexpr std::size_t bound = trystero::detail::signaling::max_unconnected_peers;
-    fixture f{true};
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("0aaaaaaaaaaaaaaaaaaa"));
-    const auto a = join(a_app, "opening");
-    trystero::app b_app(f.io.get_executor(), f.net, app_config("0bbbbbbbbbbbbbbbbbbb"));
-    const auto b = join(b_app, "opening");
-    webcpp::test::require(
-        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })));
-
-    // From here on the clock stands still: only what is ready runs.
-    const auto instant = f.net.steady_now();
-    const auto settle = [&] { webcpp::test::require(BOOST_TEST(f.net.poll_ready())); };
-    f.net.hold_sealer_opens = true;
-    auto c = app_config("zzzzzzzzzzzzzzzzzzzz");
-    std::size_t refusals = 0;
-    c.log = [&](std::string_view /*category*/, std::string_view text) {
-        refusals += text.starts_with("refusing ") ? 1 : 0;
-    };
-    trystero::app z_app(f.io.get_executor(), f.net, std::move(c));
-    auto z = join(z_app, "opening");
-    std::vector joined;
-    z.on_peer_join([&](std::string_view p) { joined.emplace_back(p); });
-    // Its announcement reaches both peers, whose ids are below its own: each offers to it and sends
-    // its candidate, and the room's opens of the two offers and the two candidates wait. (Each
-    // signal comes through both relays, as one event, which the room acts on once.)
-    settle();
-    BOOST_TEST_EQ(f.net.held_sealer_opens(), 4U);
-    flooder crowd(f, "opening");
-    crowd.announce(bound, "1crowd");
-    settle();
-    f.net.hold_sealer_opens = false;
-    f.net.release_sealer_opens();
-    settle();
-    BOOST_TEST(f.net.steady_now() == instant);
-    std::ranges::sort(joined);
-    const std::vector both{"0aaaaaaaaaaaaaaaaaaa", "0bbbbbbbbbbbbbbbbbbb"};
-    BOOST_TEST_ALL_EQ(joined.begin(), joined.end(), both.begin(), both.end());
-    BOOST_TEST_EQ(refusals, 0U);
-}
-
-// Forged offers from fresh ids, all at one instant, while the room's sealer takes its time to open
-// them: the room opens the offers of at most max_unconnected_peers negotiations, and refuses every
-// other id, each logged once, so that each offer is accounted for, refused for not opening or at
-// the bound. None makes a connection, and a peer who comes next takes the place of a refused one.
-// When each new id could take the place of a negotiation whose offer was being opened, the room
-// opened all 200 at once, and dropped 168 of them unopened, with no log (measured).
+// Forged offers from fresh ids, all at one instant: the room opens each in the call that reads it,
+// as 0.27.0 opens a signal, and refuses it for not opening, each logged once. A refused offer
+// leaves its negotiation idle, so that the next id takes its place and none is refused at the
+// bound. None makes a connection, and a peer who comes next joins.
 void a_flood_of_offers_at_one_instant_is_bounded() {
     constexpr std::size_t flood = 200;
-    constexpr std::size_t bound = trystero::detail::signaling::max_unconnected_peers;
     fixture f{true};
-    const std::string_view z_id = "zzzzzzzzzzzzzzzzzzzz";
-    auto c = app_config(z_id);
+    const auto z_label = label_beside("1", false);  // above the flood's ids, which offer
+    const auto z_id = peer_id_of(z_label);
+    auto c = app_config(z_label);
     std::size_t not_opened = 0;
     std::size_t refused = 0;
     c.log = [&](std::string_view /*category*/, std::string_view text) {
         not_opened += text.starts_with("could not open the offer from 0offer") ? 1 : 0;
         refused += text.starts_with("refusing 0offer") ? 1 : 0;
     };
-    trystero::app z_app(f.io.get_executor(), f.net, std::move(c));
+    trystero::test::app z_app(f.io.get_executor(), f.net, std::move(c));
     auto z = join(z_app, "instant");
     std::vector joined;
-    z.on_peer_join([&](std::string_view p) { joined.emplace_back(p); });
+    z.on_peer_join([&](const trystero::peer_event& e) { joined.emplace_back(e.peer_id); });
+    webcpp::test::require(BOOST_TEST(f.net.poll_ready()));
     flooder attacker(f, "instant");
     const auto z_topic = trystero::protocol::peer_topic(app_id, "instant", z_id);
     const auto instant = f.net.steady_now();
-    f.net.hold_sealer_opens = true;
     for (std::size_t i = 0; i < flood; ++i) {
         attacker.publish(z_topic, {
-                                      .peer_id = "0offer" + std::to_string(i),
+                                      .peer_id = signal_id("0offer", i),
                                       .offer_id = "offer",
                                       .offer = "not a sealed offer",
                                   });
     }
     webcpp::test::require(BOOST_TEST(f.net.poll_ready()));
-    BOOST_TEST_EQ(f.net.held_sealer_opens(), bound);
-    BOOST_TEST_EQ(refused, flood - bound);
-    f.net.hold_sealer_opens = false;
-    f.net.release_sealer_opens();
-    webcpp::test::require(BOOST_TEST(f.net.poll_ready()));
-    BOOST_TEST_EQ(not_opened, bound);
+    BOOST_TEST_EQ(not_opened, flood);
+    BOOST_TEST_EQ(refused, 0U);
     BOOST_TEST_EQ(f.net.made_connections, 0U);
     BOOST_TEST(f.net.steady_now() == instant);
 
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("0aaaaaaaaaaaaaaaaaaa"));
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config(label_beside(z_id, true)));
     const auto a = join(a_app, "instant");
     BOOST_TEST(run_until(f, [&] { return joined.size() == 1; }));
 }
 
-// Offers in one peer's name, all at one instant, while the room's sealer takes its time to open
-// them: first one sealed with the room key, then 40 others, each a text of its own and 48 KiB
-// long, and the first again, as an event of its own through the other relay. The room opens one
-// offer of a peer at a time, as Trystero answers one at a time, and ignores the others in that name
-// until it is opened: one open, and one copy of an offer, the first, in the room's resource. The
-// first again has the answer sent through its relay too, as Trystero's replay records the relay.
-// When each offer started an open of its own, holding its copy, only the relays' rate bounded
-// them: 42 opens, some 1.9 MiB, and an answer through the first relay alone (measured).
-void offers_in_one_name_are_opened_one_at_a_time() {
+// Offers in one peer's name, all at one instant: first one sealed with the room key, then 40
+// others, each a text of its own and 48 KiB long, and the first again, as an event of its own
+// through the other relay. The first opens and is answered at once, and the room then answers
+// only the same offer again, as Trystero answers one at a time: the others are ignored unopened,
+// and none is kept in the room's resource. The first again has the answer sent through its relay
+// too, as Trystero's replay records the relay.
+void offers_in_one_name_are_answered_one_at_a_time() {
     constexpr std::size_t offers = 40;
     const std::string padding(std::size_t{48} * 1024, 'x');
     counting_resource memory;  // first: the io_context's pending operations free into it
     fixture f{true};
-    const std::string_view z_id = "zzzzzzzzzzzzzzzzzzzz";
-    auto c = app_config(z_id);
+    const auto z_label = label_beside("1", false);  // above 0name, which offers
+    const auto z_id = peer_id_of(z_label);
+    auto c = app_config(z_label);
     c.memory = &memory;
-    trystero::app z_app(f.io.get_executor(), f.net, std::move(c));
+    trystero::test::app z_app(f.io.get_executor(), f.net, std::move(c));
     const auto z = join(z_app, "one");
     const auto z_topic = trystero::protocol::peer_topic(app_id, "one", z_id);
     // Two sockets in the name of 0name, one on each relay, which see the room's answers to it.
+    const auto name = signal_id("0name");
     std::set answered_through;
     flooder on_a(f, "one");
     flooder on_b(f, "one", relay_b);
     for (auto [socket, relay] : {std::pair{&on_a, relay_a}, std::pair{&on_b, relay_b}}) {
-        socket->on_text = [&answered_through, relay, z_id](std::string_view text) {
+        socket->on_text = [&answered_through, relay, &z_id](std::string_view text) {
             const auto signal = relayed_signal(text);
             if (signal && signal->peer == z_id && !signal->answer.empty()) {
                 answered_through.emplace(relay);
             }
         };
-        socket->watch(trystero::protocol::peer_topic(app_id, "one", "0name"));
+        socket->watch(trystero::protocol::peer_topic(app_id, "one", name));
     }
     webcpp::test::require(BOOST_TEST(f.net.poll_ready()));
     const std::size_t joined = memory.in_use;
-    f.net.hold_sealer_opens = true;
-    const auto sealed = flooder::sealed("one", "mem:999");
+    const auto sealed = flooder::sealed("one", "mem:999", name, "first");
     const trystero::protocol::signal_message first{
-        .peer_id = "0name",
+        .peer_id = name,
         .offer_id = "first",
         .offer = sealed,
     };
     on_a.publish(z_topic, first);
     for (std::size_t i = 0; i < offers; ++i) {
         on_a.publish(z_topic, {
-                                  .peer_id = "0name",
+                                  .peer_id = name,
                                   .offer_id = "o" + std::to_string(i),
                                   .offer = padding + std::to_string(i),
                               });
     }
     on_b.publish(z_topic, first, "again");
     webcpp::test::require(BOOST_TEST(f.net.poll_ready()));
-    BOOST_TEST_EQ(f.net.held_sealer_opens(), 1U);
     BOOST_TEST_LT(memory.in_use - joined, padding.size());
-    f.net.hold_sealer_opens = false;
-    f.net.release_sealer_opens();
-    webcpp::test::require(BOOST_TEST(f.net.poll_ready()));
     BOOST_TEST_EQ(f.net.made_connections, 1U);
     const std::set both{relay_a, relay_b};
     BOOST_TEST_ALL_EQ(answered_through.begin(), answered_through.end(), both.begin(), both.end());
 }
 
-// Unsealed offers from 2000 fresh ids, which anyone who reads the relays can send: the room reports
-// the first at once, with its peer, and the rest together, at most once per interval, with no peer
-// and their number, so that the application is not handed one report per id. On the virtual
-// clock, the flood spans two and a half intervals.
-void signals_that_do_not_open_are_reported_once_per_interval() {
-    constexpr std::size_t flood = 2000;
-    fixture f{true};
-    const std::string a_id = "zzzzzzzzzzzzzzzzzzzz";
-    trystero::app a_app(f.io.get_executor(), f.net, app_config(a_id));
-    auto a = join(a_app, "reports");
-
-    struct report {
-        std::string peer;
-        std::string what;
-    };
-
-    std::vector reports;
-    a.on_error([&](std::string_view peer, boost::system::error_code ec, std::string_view what) {
-        if (ec == trystero::error::wrong_password) {
-            reports.push_back({.peer = std::string(peer), .what = std::string(what)});
-        }
-    });
-    flooder attacker(f, "reports");
-    const auto a_topic = trystero::protocol::peer_topic(app_id, "reports", a_id);
-    const auto started = f.net.steady_now();
-    const auto before = f.net.relay(relay_a).events_seen;
-    // Paced, twenty at a time, fewer than the room's 32 negotiations, so that every offer is opened
-    // rather than refused at the bound: every twenty, everything ready runs, the relay, the room
-    // and the sealer's opens, and then the clock moves 250 ms, 25 s for the whole flood.
-    for (std::size_t i = 0; i < flood; ++i) {
-        attacker.publish(a_topic, {
-                                      .peer_id = "0garbage" + std::to_string(i),
-                                      .offer_id = "o",
-                                      .offer = "not a sealed offer",
-                                  });
-        if (i % 20 == 19) {
-            advance(f, 250ms);
-        }
-    }
-    BOOST_TEST(run_until(f, [&] { return f.net.relay(relay_a).events_seen >= before + flood; }));
-    // Every failed open is counted once its interval ends.
-    const auto counted = [&] {
-        std::size_t sum = 0;
-        for (const auto& r : reports) {
-            sum += r.peer.empty() ? std::stoul(r.what) : 1;
-        }
-        return sum;
-    };
-    BOOST_TEST(run_until(f, [&] { return counted() == flood; }));
-    const auto elapsed = f.net.steady_now() - started;
-    BOOST_TEST_LE(reports.size(), 2 + static_cast(elapsed / 10s));
-    if (BOOST_TEST(!reports.empty())) {
-        BOOST_TEST_EQ(reports.front().peer, "0garbage0");
-    }
-}
-
 // A room member, who holds the key, sends offers from fresh ids whose SDP every connection refuses:
 // each ends its negotiation at once and frees its place, but the room makes no more than
 // max_connections_per_window connections in the window, and refuses the rest.
 void sealed_offers_that_fail_at_once_are_bounded() {
     constexpr std::size_t flood = 500;
     constexpr std::size_t bound = trystero::detail::signaling::max_connections_per_window;
-    fixture f;
-    auto c = app_config("zzzzzzzzzzzzzzzzzzzz");
+    fixture f{true};
+    auto c = app_config(label_beside("2", false));  // above the member's ids, which offer
     std::size_t refusals = 0;
     c.log = [&](std::string_view /*category*/, std::string_view text) {
         refusals +=
             text.find(" connections were made in the last ") != std::string_view::npos ? 1 : 0;
     };
-    trystero::app a_app(f.io.get_executor(), f.net, std::move(c));
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(c));
     const auto a = join(a_app, "churn");
     flooder member(f, "churn");
-    const auto a_topic = trystero::protocol::peer_topic(app_id, "churn", "zzzzzzzzzzzzzzzzzzzz");
+    const auto a_topic = trystero::protocol::peer_topic(app_id, "churn", a_app.self_id());
     // One at a time, each once the previous one made its connection or was refused: sent at once,
     // the ids beyond the room's 32 negotiations would be refused at the bound before their offers
     // open, and the window would go untested. Each is a text of its own, as a member makes them:
     // the room refuses an offer it used before.
     for (std::size_t i = 0; i < flood; ++i) {
         const auto offer =
-            flooder::sealed("churn", "not an SDP the connection takes " + std::to_string(i));
+            flooder::sealed("churn", "not an SDP the connection takes " + std::to_string(i),
+                            signal_id("1churn", i), "o");
         member.publish(a_topic,
-                       {.peer_id = "1churn" + std::to_string(i), .offer_id = "o", .offer = offer});
-        if (!BOOST_TEST(run_until(f.io, [&] { return f.net.made_connections + refusals > i; }))) {
+                       {.peer_id = signal_id("1churn", i), .offer_id = "o", .offer = offer});
+        if (!BOOST_TEST(run_until(f, [&] { return f.net.made_connections + refusals > i; }))) {
             break;
         }
     }
@@ -820,14 +1453,15 @@ void sealed_offers_that_fail_at_once_are_bounded() {
 void announcements_with_forged_answers_are_bounded() {
     constexpr std::size_t flood = 300;
     constexpr std::size_t bound = trystero::detail::signaling::max_unconnected_peers;
-    fixture f;
-    const std::string_view a_id = "00000000000000000000";
-    auto c = app_config(a_id);
+    fixture f{true};
+    const auto a_label = label_beside("1", true);  // below the ids it offers to
+    const auto a_id = peer_id_of(a_label);
+    auto c = app_config(a_label);
     std::size_t refusals = 0;
     c.log = [&](std::string_view /*category*/, std::string_view text) {
         refusals += text.starts_with("refusing ") ? 1 : 0;
     };
-    trystero::app a_app(f.io.get_executor(), f.net, std::move(c));
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(c));
     const auto a = join(a_app, "churn");
     flooder attacker(f, "churn");
     const auto a_topic = trystero::protocol::peer_topic(app_id, "churn", a_id);
@@ -849,13 +1483,13 @@ void announcements_with_forged_answers_are_bounded() {
         }
     };
     for (std::size_t i = 0; i < flood; ++i) {
-        const auto id = "1churn" + std::to_string(i);
+        const auto id = signal_id("1churn", i);
         const auto topic = trystero::protocol::peer_topic(app_id, "churn", id);
         attacker.watch(topic);
         owners.emplace(std::string(topic), id);
         attacker.announce_as(id, 1);
     }
-    BOOST_TEST(run_until(f.io, [&] { return forged >= bound && refusals >= flood - bound; }));
+    BOOST_TEST(run_until(f, [&] { return forged >= bound && refusals >= flood - bound; }));
     BOOST_TEST_LE(f.net.made_connections, bound);
 }
 
@@ -957,9 +1591,10 @@ void the_event_id_hash_is_keyed() {
     BOOST_TEST_EQ(under_one(id), trystero::detail::recent_event_ids::keyed_hash(one)(id));
 }
 
-// A strategy draws its index's key from the backend's randomness when it is made, after its
-// signer's secret: a relay cannot know it. Its index hashes under those 16 bytes, read again from
-// a twin of the backend's stream, so that strategies over other streams hash an id elsewhere.
+// A strategy draws its index's key from the backend's randomness when it is made, and nothing
+// else: a relay cannot know it, and the room's signer is made at its first event from
+// webcpp::crypto's generator. Its index hashes under those 16 bytes, read again from a twin of the
+// backend's stream, so that strategies over other streams hash an id elsewhere.
 void a_strategy_draws_the_key_of_its_event_ids() {
     constexpr std::size_t key_size = trystero::detail::recent_event_ids::key_size;
     const auto id = event_id_of('e');
@@ -969,14 +1604,12 @@ void a_strategy_draws_the_key_of_its_event_ids() {
         trystero::test::memory_network net(io, seed);
         const auto strategy = std::make_shared(
             net, std::span(), std::pmr::vector(), "topic",
-            trystero::handler(),
+            trystero::detail::nostr_strategy::announcement_handler(),
             trystero::detail::nostr_strategy::message_handler(), trystero::detail::logger(),
             std::pmr::get_default_resource());
-        BOOST_TEST_EQ(net.random_bytes, 32U + key_size);  // the secret, the key
+        BOOST_TEST_EQ(net.random_bytes, key_size);
         asio::io_context twin_io;
         trystero::test::memory_network twin(twin_io, seed);
-        std::array secret{};
-        twin.random(secret);
         std::array key{};
         twin.random(key);
         const std::size_t hash = strategy->seen().hash_function()(id);
@@ -1018,7 +1651,8 @@ void a_forged_event_under_a_genuine_id_hides_nothing() {
     topics.emplace_back(topic);
     const auto strategy = std::make_shared(
         f.net, urls, std::move(topics), "another-topic",
-        trystero::handler([] { return std::pmr::string("{}"); }),
+        trystero::detail::nostr_strategy::announcement_handler(
+            [](std::string_view /*nonce*/) { return std::pmr::string("{}"); }),
         trystero::detail::nostr_strategy::message_handler(
             [&heard](std::size_t /*relay*/, std::string_view /*topic*/, std::string_view content) {
                 heard.emplace_back(content);
@@ -1036,9 +1670,9 @@ void a_forged_event_under_a_genuine_id_hides_nothing() {
     const auto key = trystero::protocol::nostr::signer::from_secret(secret);
     webcpp::test::require(BOOST_TEST(key.has_value()));
     const auto event = [&](std::string_view content) {
-        const std::array aux{};
         return std::string(trystero::protocol::nostr::event_message(
-            *key, trystero::detail::unix_now(f.net), topic, content, aux));
+                               *key, trystero::detail::unix_now(f.net), topic, content)
+                               .value());
     };
     const std::string genuine = event("genuine");
     std::string forged = event("forged");
@@ -1058,57 +1692,152 @@ void a_forged_event_under_a_genuine_id_hides_nothing() {
     strategy->stop();
 }
 
-// A boost::circular_buffer moves by swapping its allocators, which std::pmr's cannot: the classes
-// that hold one over the room's resource say they cannot move, rather than fail to compile when
-// moved.
-void classes_over_a_pmr_circular_buffer_do_not_move() {
-    BOOST_TEST(!std::is_move_constructible_v);
-    BOOST_TEST(!std::is_move_assignable_v);
-    BOOST_TEST(!std::is_move_constructible_v);
-    BOOST_TEST(!std::is_move_assignable_v);
-    BOOST_TEST(!std::is_move_constructible_v);
-    BOOST_TEST(!std::is_move_assignable_v);
+/** The public keys that signed the events on `topic` the relay `url` took, in order. */
+std::vector signers_of(fixture& f, std::string_view url, std::string_view topic) {
+    std::vector keys;
+    for (const auto& e : f.net.relay(url).published) {
+        if (e.topic == topic) {
+            keys.emplace_back(e.pubkey);
+        }
+    }
+    return keys;
 }
 
-/** Joins B to A, records what `record` keeps of the relays meanwhile, and has B leave; B's app goes
- * with it, so that B's return negotiates again. */
-void join_and_leave(fixture& f, std::string_view b_id, std::string_view room_id,
-                    const std::vector& joined, const std::vector& left,
-                    const std::function& recorded) {
-    trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id));
-    auto b = join(b_app, room_id);
-    webcpp::test::require(
-        BOOST_TEST(run_until(f, [&] { return joined.size() == 1 && recorded(); })));
-    bool done = false;
+// Each room signs its events with a key of its own, as 0.27.0 keeps a signer per room: the
+// announcements of one room carry one key on every relay, another room of the same app another
+// key, and a room joined again after it left, a new one. A rejoin makes a strategy of its own, so
+// this does not tell a key made at the first event and dropped on stop from one made with the
+// strategy: signaling_test's the_room_key_is_made_at_the_first_event_and_dropped_on_stop does.
+void each_room_signs_with_its_own_key() {
+    fixture f(true);
+    f.net.relay(relay_a).record_published = true;
+    f.net.relay(relay_b).record_published = true;
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("SSSSSSSSSSSSSSSSSSSS"));
+    const auto one_topic = trystero::protocol::root_topic(app_id, "one");
+    const auto two_topic = trystero::protocol::root_topic(app_id, "two");
+    const auto announced_twice = [&f](std::string_view topic) {
+        return [&f, topic] {
+            return signers_of(f, relay_a, topic).size() >= 2 &&
+                   signers_of(f, relay_b, topic).size() >= 2;
+        };
+    };
+    std::set keys;
+    {
+        auto one = join(a_app, "one");
+        const auto two = join(a_app, "two");
+        webcpp::test::require(BOOST_TEST(run_until(f, announced_twice(one_topic))));
+        webcpp::test::require(BOOST_TEST(run_until(f, announced_twice(two_topic))));
+        for (const auto& topic : {one_topic, two_topic}) {
+            std::set room_keys;
+            for (const auto* const url : {relay_a, relay_b}) {
+                const auto signers = signers_of(f, url, topic);
+                room_keys.insert(signers.begin(), signers.end());
+            }
+            BOOST_TEST_EQ(room_keys.size(), 1U);
+            keys.insert(room_keys.begin(), room_keys.end());
+        }
+        BOOST_TEST_EQ(keys.size(), 2U);
+        bool left = false;
+        one.async_leave([&left](boost::system::error_code ec) { left = !ec; });
+        webcpp::test::require(BOOST_TEST(run_until(f, [&left] { return left; })));
+    }
+    f.net.relay(relay_a).published.clear();
+    f.net.relay(relay_b).published.clear();
+    const auto again = join(a_app, "one");
+    webcpp::test::require(BOOST_TEST(run_until(f, announced_twice(one_topic))));
+    const auto signers = signers_of(f, relay_a, one_topic);
+    BOOST_TEST(!keys.contains(signers.front()));
+    BOOST_TEST(
+        std::ranges::all_of(signers, [&](const std::string& k) { return k == signers.front(); }));
+}
+
+// A room subscribes its own topic before its root topic, as Trystero's rooms do: its REQ lists
+// them in that order, and their kinds in the same order, as 0.27.0's batcher writes them.
+void a_room_subscribes_its_self_topic_before_its_root_topic() {
+    fixture f(true);
+    auto& relay = f.net.relay(relay_a);
+    relay.record_requests = true;
+    auto c = app_config("TTTTTTTTTTTTTTTTTTTT");
+    c.relay_urls = {relay_a};
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(c));
+    const auto r = join(a_app, "ordered");
+    webcpp::test::require(BOOST_TEST(run_until(f, [&relay] { return !relay.requests.empty(); })));
+    const auto request = webcpp::document::parse(relay.requests.front());
+    webcpp::test::require(BOOST_TEST(request.has_value()));
+    const auto filter = request->root()[2];
+    const std::array topics{
+        std::string(trystero::protocol::peer_topic(app_id, "ordered", a_app.self_id())),
+        std::string(trystero::protocol::root_topic(app_id, "ordered")),
+    };
+    std::vector listed;
+    for (const auto t : filter["#x"]) {
+        listed.emplace_back(t.value_or(std::string_view()));
+    }
+    BOOST_TEST_ALL_EQ(listed.begin(), listed.end(), topics.begin(), topics.end());
+    std::vector kinds;
+    for (const auto k : filter["kinds"]) {
+        kinds.push_back(k.value_or(std::int64_t{-1}));
+    }
+    std::vector expected;
+    for (const auto& t : topics) {
+        if (const std::int64_t k = trystero::protocol::nostr::topic_kind(t);
+            std::ranges::find(expected, k) == expected.end()) {
+            expected.push_back(k);
+        }
+    }
+    BOOST_TEST_ALL_EQ(kinds.begin(), kinds.end(), expected.begin(), expected.end());
+}
+
+// A boost::circular_buffer moves by swapping its allocators, which std::pmr's cannot: the classes
+// that hold one over the room's resource say they cannot move, rather than fail to compile when
+// moved.
+void classes_over_a_pmr_circular_buffer_do_not_move() {
+    BOOST_TEST(!std::is_move_constructible_v);
+    BOOST_TEST(!std::is_move_assignable_v);
+    BOOST_TEST(!std::is_move_constructible_v);
+    BOOST_TEST(!std::is_move_assignable_v);
+}
+
+/** Joins B to A, records what `record` keeps of the relays meanwhile, and has B leave; B's app goes
+ * with it, so that B's return negotiates again. */
+void join_and_leave(fixture& f, std::string_view b_id, std::string_view room_id,
+                    const std::vector& joined, const std::vector& left,
+                    const std::function& recorded) {
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(b_id));
+    auto b = join(b_app, room_id);
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return joined.size() == 1 && recorded(); })));
+    bool done = false;
     b.async_leave([&](boost::system::error_code) { done = true; });
     webcpp::test::require(BOOST_TEST(run_until(f, [&] { return done && left.size() == 1; })));
 }
 
 // A watcher without the room key records B's sealed answer to A. Once B has left and come back with
 // the same id, as a Trystero JS page does after a network drop, it sends that answer in B's name
-// with each of A's new offers to B, before B's own answer. The answer opens with the room key, but
-// A used it before: A refuses it, blames no one, and B joins again.
+// with each of A's new offers to B, before B's own answer. The answer was sealed for its own offer
+// id, which its AAD binds (0.27.0's `buildSignalAad`), so it does not open: A counts it as a signal
+// that did not open, changes nothing else, and B joins again.
 //
 // The watcher is armed as A sees B leave: an announcement B made before leaving may still reach A
 // after it, and A's offer to that announcement is the one the returning B answers, on a relay
 // where A does not send it again.
-void a_replayed_answer_is_refused() {
+void a_replayed_answer_does_not_open() {
     fixture f{true};
-    const std::string a_id = "00000000000000000000";
-    const std::string b_id = "BBBBBBBBBBBBBBBBBBBB";
-    trystero::app a_app(f.io.get_executor(), f.net, app_config(a_id));
+    const auto labels = ordered_labels(2, "replay");  // the apps, by ascending peer id
+    const std::string a_id = peer_id_of(labels[0]);
+    const std::string b_id = peer_id_of(labels[1]);
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config(labels[0]));
     auto a = join(a_app, "replay");
     std::vector joined;
     std::vector left;
     std::vector errors;
     bool armed = false;
-    a.on_peer_join([&](std::string_view p) { joined.emplace_back(p); });
-    a.on_peer_leave([&](std::string_view p) {
-        left.emplace_back(p);
+    a.on_peer_join([&](const trystero::peer_event& e) { joined.emplace_back(e.peer_id); });
+    a.on_peer_leave([&](const trystero::peer_event& e) {
+        left.emplace_back(e.peer_id);
         armed = true;
     });
-    a.on_error([&](std::string_view /*peer*/, boost::system::error_code ec,
-                   std::string_view /*what*/) { errors.push_back(ec); });
+    a.on_error([&](const trystero::room_error& e) { errors.push_back(e.code); });
     flooder watcher(f, "replay");
     const auto a_topic = std::string(trystero::protocol::peer_topic(app_id, "replay", a_id));
     const auto b_topic = std::string(trystero::protocol::peer_topic(app_id, "replay", b_id));
@@ -1130,66 +1859,75 @@ void a_replayed_answer_is_refused() {
     };
     watcher.watch(a_topic);
     watcher.watch(b_topic);
-    join_and_leave(f, b_id, "replay", joined, left, [&] { return !recorded.empty(); });
-    trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id));
+    join_and_leave(f, labels[1], "replay", joined, left, [&] { return !recorded.empty(); });
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(labels[1]));
     const auto b = join(b_app, "replay");
     BOOST_TEST(run_until(f, [&] { return joined.size() == 2; }));
     BOOST_TEST_GE(replays, 1U);
-    BOOST_TEST(std::ranges::none_of(errors, [](boost::system::error_code ec) {
-        return ec == trystero::error::wrong_password;
+    BOOST_TEST(std::ranges::any_of(errors, [](boost::system::error_code ec) {
+        return ec == trystero::error::decrypt_failed;
     }));
 }
 
-// The same for an offer: B is lower and offers. The watcher records B's sealed offer to A, and once
-// B is back, sends it in B's name every 0.5 s of the virtual clock, with fresh offer ids. A
-// answered that offer before, so it refuses each replay, and B's own offer joins them.
+// The same for an offer: B is lower and offers. The watcher records B's sealed offer to A and its
+// offer id, and once B is back, sends both in B's name every 0.5 s of the virtual clock. Its AAD
+// is B's and its id's, so it opens with the room key, but A answered that offer before: A refuses
+// each replay, and B's own offer joins them.
 void a_replayed_offer_is_refused() {
     fixture f{true};
-    const std::string a_id = "zzzzzzzzzzzzzzzzzzzz";
-    const std::string b_id = "BBBBBBBBBBBBBBBBBBBB";
-    trystero::app a_app(f.io.get_executor(), f.net, app_config(a_id));
+    const auto labels = ordered_labels(2, "replayo");  // the apps, by ascending peer id
+    const std::string a_id = peer_id_of(labels[1]);
+    const std::string b_id = peer_id_of(labels[0]);
+    auto c = app_config(labels[1]);
+    std::size_t refused = 0;
+    c.log = [&](std::string_view /*category*/, std::string_view text) {
+        refused += text.starts_with("refused the offer from " + b_id) ? 1 : 0;
+    };
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(c));
     auto a = join(a_app, "replayo");
     std::vector joined;
     std::vector left;
-    a.on_peer_join([&](std::string_view p) { joined.emplace_back(p); });
-    a.on_peer_leave([&](std::string_view p) { left.emplace_back(p); });
+    a.on_peer_join([&](const trystero::peer_event& e) { joined.emplace_back(e.peer_id); });
+    a.on_peer_leave([&](const trystero::peer_event& e) { left.emplace_back(e.peer_id); });
     flooder watcher(f, "replayo");
     const auto a_topic = std::string(trystero::protocol::peer_topic(app_id, "replayo", a_id));
     std::string recorded;
+    std::string recorded_id;
     watcher.on_text = [&](std::string_view text) {
         const auto s = relayed_signal(text);
         if (s && s->topic == a_topic && s->peer == b_id && !s->offer.empty() && recorded.empty()) {
             recorded = s->offer;
+            recorded_id = s->offer_id;
         }
     };
     watcher.watch(a_topic);
-    join_and_leave(f, b_id, "replayo", joined, left, [&] { return !recorded.empty(); });
-    trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id));
+    join_and_leave(f, labels[0], "replayo", joined, left, [&] { return !recorded.empty(); });
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(labels[0]));
     const auto b = join(b_app, "replayo");
     std::size_t replays = 0;
     const auto end = f.net.steady_now() + 10s;
     while (joined.size() < 2 && f.net.steady_now() < end) {
-        watcher.publish(a_topic, {
-                                     .peer_id = b_id,
-                                     .offer_id = "replay" + std::to_string(replays++),
-                                     .offer = recorded,
-                                 });
-        advance(f, 500ms);
+        watcher.publish(a_topic, {.peer_id = b_id, .offer_id = recorded_id, .offer = recorded},
+                        std::to_string(replays++));
+        trystero::test::advance(f, 500ms);
     }
     BOOST_TEST_EQ(joined.size(), 2U);
     BOOST_TEST_GE(replays, 1U);
+    BOOST_TEST_GE(refused, 1U);
 }
 
 // A watcher without the room key sends A's own sealed offer to B back to A, at once, as B's answer
-// to it. It opens with the room key, but A made it: A refuses it, and B's own answer joins them.
+// to it. Sealed as A's offer, which its AAD binds, it does not open as B's answer: A changes
+// nothing, and B's own answer joins them.
 void a_reflected_offer_is_refused_as_an_answer() {
-    fixture f;
-    const std::string a_id = "00000000000000000000";
-    const std::string b_id = "BBBBBBBBBBBBBBBBBBBB";
-    trystero::app a_app(f.io.get_executor(), f.net, app_config(a_id));
+    fixture f{true};
+    const auto labels = ordered_labels(2, "reflect");  // the apps, by ascending peer id
+    const std::string a_id = peer_id_of(labels[0]);
+    const std::string b_id = peer_id_of(labels[1]);
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config(labels[0]));
     auto a = join(a_app, "reflect");
     std::vector joined;
-    a.on_peer_join([&](std::string_view p) { joined.emplace_back(p); });
+    a.on_peer_join([&](const trystero::peer_event& e) { joined.emplace_back(e.peer_id); });
     flooder watcher(f, "reflect");
     const auto a_topic = std::string(trystero::protocol::peer_topic(app_id, "reflect", a_id));
     const auto b_topic = std::string(trystero::protocol::peer_topic(app_id, "reflect", b_id));
@@ -1203,29 +1941,31 @@ void a_reflected_offer_is_refused_as_an_answer() {
         }
     };
     watcher.watch(b_topic);
-    trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(labels[1]));
     const auto b = join(b_app, "reflect");
-    BOOST_TEST(run_until(f.io, [&] { return joined.size() == 1; }));
+    BOOST_TEST(run_until(f, [&] { return joined.size() == 1; }));
     BOOST_TEST_GE(reflected, 1U);
 }
 
 // A watcher without the room key announces a decoy id above A, records A's sealed offer to it, and
-// sends that offer to A in B's name whenever B announces itself, before B's own offer. A made that
-// offer: A refuses it, never answers one in B's name but B's own, and B's own offer joins them.
+// sends that offer to A in B's name whenever B announces itself, before B's own offer. Sealed as
+// A's, which its AAD binds, it does not open as B's: A never answers one in B's name but B's own,
+// and B's own offer joins them.
 void a_reflected_offer_is_refused_as_an_offer() {
     fixture f{true};
-    const std::string a_id = "yyyyyyyyyyyyyyyyyyyy";
-    const std::string b_id = "BBBBBBBBBBBBBBBBBBBB";
+    const auto labels = ordered_labels(2, "reflecto");  // the apps, by ascending peer id
+    const std::string a_id = peer_id_of(labels[1]);
+    const std::string b_id = peer_id_of(labels[0]);
     const std::string decoy = "zzzzzzzzzzzzzzzzzzzz";
-    auto c = app_config(a_id);
+    auto c = app_config(labels[1]);
     std::size_t answered_reflections = 0;
     c.log = [&](std::string_view /*category*/, std::string_view text) {
         answered_reflections += text.starts_with("offer reflected") ? 1 : 0;
     };
-    trystero::app a_app(f.io.get_executor(), f.net, std::move(c));
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(c));
     auto a = join(a_app, "reflecto");
     std::vector joined;
-    a.on_peer_join([&](std::string_view p) { joined.emplace_back(p); });
+    a.on_peer_join([&](const trystero::peer_event& e) { joined.emplace_back(e.peer_id); });
     flooder watcher(f, "reflecto");
     const auto root = std::string(trystero::protocol::root_topic(app_id, "reflecto"));
     const auto a_topic = std::string(trystero::protocol::peer_topic(app_id, "reflecto", a_id));
@@ -1252,7 +1992,7 @@ void a_reflected_offer_is_refused_as_an_offer() {
     watcher.watch(decoy_topic);
     watcher.announce_as(decoy, 1);
     webcpp::test::require(BOOST_TEST(run_until(f, [&] { return !recorded.empty(); })));
-    trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(labels[0]));
     const auto b = join(b_app, "reflecto");
     BOOST_TEST(run_until(f, [&] { return joined.size() == 1; }));
     BOOST_TEST_GE(reflected, 1U);
@@ -1260,22 +2000,24 @@ void a_reflected_offer_is_refused_as_an_offer() {
 }
 
 // A answers B (B's id is lower), then offers to C (C's id is higher). A watcher without the room
-// key sends A's own sealed answer to B back to A as C's answer to that offer. A made it: A refuses
-// it, and C's own answer joins them.
-void a_reflected_answer_is_refused_as_an_answer() {
-    fixture f;
-    const std::string a_id = "MMMMMMMMMMMMMMMMMMMM";
-    const std::string b_id = "BBBBBBBBBBBBBBBBBBBB";
-    const std::string c_id = "ZZZZZZZZZZZZZZZZZZZZ";
-    auto c = app_config(a_id);
+// key sends A's own sealed answer to B back to A as C's answer to that offer. Sealed as A's answer
+// to B's offer, which its AAD binds, it does not open as C's: A changes nothing, and C's own answer
+// joins them.
+void a_reflected_answer_does_not_open_as_an_answer() {
+    fixture f{true};
+    const auto labels = ordered_labels(3, "reflans");  // the apps, by ascending peer id
+    const std::string a_id = peer_id_of(labels[1]);
+    const std::string b_id = peer_id_of(labels[0]);
+    const std::string c_id = peer_id_of(labels[2]);
+    auto c = app_config(labels[1]);
     bool refused = false;
     c.log = [&](std::string_view /*category*/, std::string_view text) {
-        refused = refused || text.starts_with("refused the answer from " + c_id);
+        refused = refused || text.starts_with("could not open the answer from " + c_id);
     };
-    trystero::app a_app(f.io.get_executor(), f.net, std::move(c));
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(c));
     auto a = join(a_app, "reflans");
     std::vector joined;
-    a.on_peer_join([&](std::string_view p) { joined.emplace_back(p); });
+    a.on_peer_join([&](const trystero::peer_event& e) { joined.emplace_back(e.peer_id); });
     flooder watcher(f, "reflans");
     const auto a_topic = std::string(trystero::protocol::peer_topic(app_id, "reflans", a_id));
     const auto b_topic = std::string(trystero::protocol::peer_topic(app_id, "reflans", b_id));
@@ -1298,13 +2040,13 @@ void a_reflected_answer_is_refused_as_an_answer() {
     };
     watcher.watch(b_topic);
     watcher.watch(c_topic);
-    trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(labels[0]));
     const auto b = join(b_app, "reflans");
     webcpp::test::require(
-        BOOST_TEST(run_until(f.io, [&] { return joined.size() == 1 && !a_answer.empty(); })));
-    trystero::app peer_c_app(f.io.get_executor(), f.net, app_config(c_id));
+        BOOST_TEST(run_until(f, [&] { return joined.size() == 1 && !a_answer.empty(); })));
+    trystero::test::app peer_c_app(f.io.get_executor(), f.net, app_config(labels[2]));
     const auto peer_c = join(peer_c_app, "reflans");
-    BOOST_TEST(run_until(f.io, [&] { return joined.size() == 2; }));
+    BOOST_TEST(run_until(f, [&] { return joined.size() == 2; }));
     BOOST_TEST_GE(reflected, 1U);
     BOOST_TEST(refused);
 }
@@ -1329,7 +2071,7 @@ void a_relay_that_closes_at_once_is_tried_less_and_less_often() {
         }
         reconnections += text.starts_with("reconnected to ") ? 1 : 0;
     };
-    trystero::app a_app(f.io.get_executor(), f.net, std::move(c));
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(c));
     const auto a = join(a_app, "backoff");
     BOOST_TEST(run_until(f, [&] { return bounds.size() >= 6; }, 2min));
     const std::vector growing{3333, 6666, 13332, 26664, 53328, 60000};
@@ -1337,15 +2079,12 @@ void a_relay_that_closes_at_once_is_tried_less_and_less_often() {
                       bounds.begin() + std::min(6, std::ssize(bounds)),
                       growing.begin(), growing.end());
 
-    // A connection that lasts: once the first of the steady announcements, 60 s after the warm-up,
-    // is on the relay, the relay goes away.
+    // A connection that lasts: once it has been open for 60 s, the relay goes away.
     relay.close_after_subscribe = false;
     const std::size_t before = reconnections;
     BOOST_TEST(run_until(f, [&] { return reconnections > before; }, 1min));
-    // The warm-up's first announcement went as the connection opened, before the clock moved: its
-    // four others, then the first steady one.
-    const auto seen = relay.events_seen;
-    BOOST_TEST(run_until(f, [&] { return relay.events_seen >= seen + 5; }, 2min));
+    const auto opened = f.net.steady_now();
+    BOOST_TEST(run_until(f, [&] { return f.net.steady_now() - opened >= 60s; }, 2min));
     const auto lost = bounds.size();
     relay.close_all();
     BOOST_TEST(run_until(f, [&] { return bounds.size() > lost; }));
@@ -1366,7 +2105,7 @@ void counter_announcements_are_paced() {
     c.log = [&](std::string_view /*category*/, std::string_view text) {
         asked += text.ends_with("asking them to offer") ? 1 : 0;
     };
-    trystero::app a_app(f.io.get_executor(), f.net, std::move(c));
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(c));
     const auto a = join(a_app, "counter");
     flooder attacker(f, "counter");
     // Announces `count` fresh ids, and returns once the relay took them and the room handled them,
@@ -1379,10 +2118,10 @@ void counter_announcements_are_paced() {
     };
     announced(flood, "0low");
     BOOST_TEST_EQ(asked, 1U);
-    advance(f, 5332ms);
+    trystero::test::advance(f, 5332ms);
     announced(1, "0early");
     BOOST_TEST_EQ(asked, 1U);
-    advance(f, 1ms);
+    trystero::test::advance(f, 1ms);
     announced(1, "0due");
     BOOST_TEST_EQ(asked, 2U);
 }
@@ -1390,33 +2129,34 @@ void counter_announcements_are_paced() {
 // Beyond the bound, a new peer is refused, and one refused again and again is logged once: the
 // offers to the first ids hold their places (the clock runs at its own pace here).
 void a_refused_peer_is_logged_once() {
-    fixture f;
-    auto c = app_config("00000000000000000000");
+    fixture f{true};
+    auto c = app_config(label_beside("1", true));  // below the announced ids, to which it offers
     std::size_t refusals_of_one = 0;
     std::size_t refusals = 0;
     c.log = [&](std::string_view /*category*/, std::string_view text) {
         refusals += text.starts_with("refusing ") ? 1 : 0;
         refusals_of_one += text.starts_with("refusing 1same") ? 1 : 0;
     };
-    trystero::app a_app(f.io.get_executor(), f.net, std::move(c));
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(c));
     const auto a = join(a_app, "refusal");
     flooder attacker(f, "refusal");
     const auto before = f.net.relay(relay_a).events_seen;
     const std::size_t bound = trystero::detail::signaling::max_unconnected_peers;
     attacker.announce(bound + 8, "1fill");
-    attacker.announce_as("1same", 5);
-    BOOST_TEST(run_until(
-        f.io, [&] { return f.net.relay(relay_a).events_seen >= before + bound + 8 + 5; }));
-    BOOST_TEST(run_until(f.io, [&] { return refusals == 9; }));
+    attacker.announce_as(signal_id("1same"), 5);
+    BOOST_TEST(
+        run_until(f, [&] { return f.net.relay(relay_a).events_seen >= before + bound + 8 + 5; }));
+    BOOST_TEST(run_until(f, [&] { return refusals == 9; }));
     BOOST_TEST_EQ(refusals_of_one, 1U);
     BOOST_TEST_LE(f.net.live_connections(), 2 * bound);
 }
 
-// A peer id longer than protocol::max_peer_id_bytes is ignored in a signal; an app configured with
-// one uses a random id instead, in its rooms too, and reports it.
+// A peer id of other than protocol::peer_id_size characters is ignored in a signal, as 0.27.0
+// ignores it; an app's own, drawn, is 20 characters, in its rooms too.
 void long_peer_ids_are_bounded() {
-    const std::string longest(trystero::protocol::max_peer_id_bytes, 'x');
-    const std::string too_long(trystero::protocol::max_peer_id_bytes + 1, 'x');
+    const std::string longest(trystero::protocol::peer_id_size, 'x');
+    const std::string too_long(trystero::protocol::peer_id_size + 1, 'x');
+    const std::string too_short(trystero::protocol::peer_id_size - 1, 'x');
     // {"peerId":}, read as a room reads a signal.
     const auto signal = [](std::string_view id) {
         std::pmr::string text("{");
@@ -1432,32 +2172,28 @@ void long_peer_ids_are_bounded() {
     };
     const auto longest_signal = signal(longest);
     const auto too_long_signal = signal(too_long);
+    const auto too_short_signal = signal(too_short);
     BOOST_TEST(trystero::protocol::read_signal(longest_signal.root()).has_value());
     BOOST_TEST(!trystero::protocol::read_signal(too_long_signal.root()).has_value());
+    BOOST_TEST(!trystero::protocol::read_signal(too_short_signal.root()).has_value());
 
-    fixture f;
-    trystero::app a_app(f.io.get_executor(), f.net, app_config(too_long));
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config(""));
     const auto a = join(a_app, "long");
-    std::vector errors;
-    a_app.on_error([&](std::string_view /*peer*/, boost::system::error_code ec,
-                       std::string_view /*what*/) { errors.push_back(ec); });
     BOOST_TEST_EQ(a.self_id().size(), trystero::protocol::peer_id_size);
-    BOOST_TEST(run_until(f.io, [&] { return errors.size() == 1; }));
-    if (!errors.empty()) {
-        BOOST_TEST(errors.front() == trystero::error::invalid_configuration);
-    }
+    BOOST_TEST_EQ(a.self_id(), a_app.self_id());
 }
 
 void three_peers_form_a_mesh() {
-    fixture f;
-    std::vector apps;
+    fixture f{true};
+    std::vector apps;
     std::vector rooms;
     for (const char* id :
          {"KKKKKKKKKKKKKKKKKKKK", "LLLLLLLLLLLLLLLLLLLL", "MMMMMMMMMMMMMMMMMMMM"}) {
         apps.emplace_back(f.io.get_executor(), f.net, app_config(id));
         rooms.push_back(join(apps.back(), "mesh"));
     }
-    BOOST_TEST(run_until(f.io, [&] {
+    BOOST_TEST(run_until(f, [&] {
         return std::ranges::all_of(rooms,
                                    [](const trystero::room& r) { return r.peers().size() == 2; });
     }));
@@ -1471,14 +2207,222 @@ void three_peers_form_a_mesh() {
             });
     }
     shout.async_send("all", [](boost::system::error_code ec) { BOOST_TEST(!ec); });
-    BOOST_TEST(run_until(f.io, [&] { return heard == 2; }));
+    BOOST_TEST(run_until(f, [&] { return heard == 2; }));
+}
+
+// A room keeps one connection per peer, as 0.27.0's connectPeer keeps a connected peer that is not
+// stale: a second connection that opens while the peer's link is live is closed, and the peer
+// stays; once the link is no longer live, the next connection replaces it, the peer leaving first.
+void a_room_keeps_one_connection_per_peer() {
+    counting_resource a_memory;  // first: A's connections are made in it, which names A's ends
+    fixture f{true};
+    const auto labels = ordered_labels(2, "one");  // A's id below B's: A offers
+    const std::string b_id = peer_id_of(labels[1]);
+    const auto a = make_app_room(f, labels[0], "one", &a_memory);
+    std::size_t a_leaves = 0;
+    a.room->on_peer_leave(a.room->bind(
+                              [&](const trystero::peer_event&) { ++a_leaves; }),
+                          {});
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(labels[1]));
+    auto b = join(b_app, "one");
+    std::size_t b_leaves = 0;
+    b.on_peer_leave([&](const trystero::peer_event&) { ++b_leaves; });
+    webcpp::test::require(BOOST_TEST(
+        run_until(f, [&] { return a.room->peers().size() == 1 && b.peers().size() == 1; })));
+    // The connection the room uses: the one open pair left once the negotiations settled.
+    const auto live_before = f.net.live_connections();
+    {
+        auto second = negotiate(f);
+        a.room->on_connected(b_id, second.local_pc, second.local, second.offer, second.answer);
+        BOOST_TEST(!second.local->is_open());
+        BOOST_TEST(run_until(f, [&] { return !second.remote->is_open(); }));
+        trystero::test::advance(f, 1000ms);
+        BOOST_TEST_EQ(a.room->peers().size(), 1U);
+        BOOST_TEST_EQ(b.peers().size(), 1U);
+        BOOST_TEST_EQ(a_leaves, 0U);
+        BOOST_TEST_EQ(b_leaves, 0U);
+        BOOST_TEST(second.received->empty());
+    }
+    BOOST_TEST(run_until(f, [&] { return f.net.live_connections() == live_before; }));
+    // The live link's channel closes at A's end; its close is still to be reported when the next
+    // connection opens, which replaces it.
+    std::shared_ptr a_end;
+    for (std::size_t id = 0; id < f.net.made_connections && !a_end; ++id) {
+        const auto pc = f.net.find(id);
+        const auto channel = pc ? pc->channel() : nullptr;
+        const auto remote = channel ? channel->remote() : nullptr;
+        // A's end of the pair the rooms use: in A's resource, both ends open.
+        if (channel && channel->is_open() && remote && remote->is_open() &&
+            channel->memory() == &a_memory) {
+            a_end = channel;
+        }
+    }
+    auto third = negotiate(f);
+    webcpp::test::require(BOOST_TEST(a_end != nullptr));
+    a_end->close();
+    a.room->on_connected(b_id, third.local_pc, third.local, third.offer, third.answer);
+    BOOST_TEST(third.local->is_open());
+    BOOST_TEST(run_until(f, [&] { return a_leaves == 1; }));
+    // The new link carries the room's handshake: A, whose id is lower, sends its step 1.
+    BOOST_TEST(run_until(f, [&] { return !third.received->empty(); }));
+    if (!third.received->empty()) {
+        BOOST_TEST_EQ(static_cast(third.received->front().front()),
+                      static_cast(trystero::protocol::action_wire_version));
+    }
+    a.room->abandon();
+}
+
+// A room that starts to leave negotiates nothing more, as 0.27.0's signal handler drops every
+// signal while its room is leaving: a peer that announces itself during the farewell, with an id
+// above the room's own, gets no offer, and no connection is made for it.
+void a_leaving_room_negotiates_nothing() {
+    fixture f{true};
+    const auto a_label = label_beside("y", true);  // below the newcomers' ids, to which A offers
+    const std::string a_id = peer_id_of(a_label);
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config(a_label));
+    auto a = join(a_app, "farewell");
+    flooder peer(f, "farewell");
+    std::size_t offers = 0;
+    peer.on_text = [&](std::string_view text) {
+        if (const auto s = relayed_signal(text); s && s->peer == a_id && !s->offer.empty()) {
+            ++offers;
+        }
+    };
+    const std::string newcomer = "zzzzzzzzzzzzzzzzzzzz";
+    peer.watch(trystero::protocol::peer_topic(app_id, "farewell", newcomer));
+    // A answers a newcomer while joined: the case would see its offer.
+    peer.announce_as(newcomer, 1);
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return offers == 1; })));
+    const auto made = f.net.made_connections;
+    bool gone = false;
+    peer.watch(trystero::protocol::peer_topic(app_id, "farewell", "yyyyyyyyyyyyyyyyyyyy"));
+    webcpp::test::require(BOOST_TEST(f.net.poll_ready()));
+    a.async_leave([&](boost::system::error_code) { gone = true; });
+    peer.announce_as("yyyyyyyyyyyyyyyyyyyy", 1);
+    BOOST_TEST(run_until(f, [&] { return gone; }));
+    BOOST_TEST_EQ(offers, 1U);
+    BOOST_TEST_EQ(f.net.made_connections, made);
+}
+
+/** Two apps, A and B, whose rooms "r1" and "r2" have met: each room sees the other app's peer. */
+struct two_rooms_each {
+    fixture f{true};
+    trystero::test::app a_app{f.io.get_executor(), f.net, app_config("AAAAAAAAAAAAAAAAAAAA")};
+    trystero::test::app b_app{f.io.get_executor(), f.net, app_config("BBBBBBBBBBBBBBBBBBBB")};
+    std::optional a1;
+    std::optional a2;
+    std::optional b1;
+    std::optional b2;
+
+    two_rooms_each() {
+        a1.emplace(join(a_app, "r1"));
+        a2.emplace(join(a_app, "r2"));
+        b1.emplace(join(b_app, "r1"));
+        b2.emplace(join(b_app, "r2"));
+        webcpp::test::require(BOOST_TEST(run_until(f, [&] {
+            return a1->peers().size() == 1 && a2->peers().size() == 1 && b1->peers().size() == 1 &&
+                   b2->peers().size() == 1;
+        })));
+    }
+};
+
+// Each room of an app has its own connection to each peer, as 0.27.0's rooms do: two apps that
+// share two rooms hold two connections, one per room, both ends of each open.
+void rooms_of_one_app_have_their_own_connections() {
+    two_rooms_each t;
+    // The negotiations' losing connections close; the two connections the rooms use stay.
+    BOOST_TEST(run_until(t.f, [&] { return t.f.net.live_connections() == 4; }));
+    // Each room's messages travel on its own connection.
+    std::vector heard;
+    t.b1->make_action("say").on_message(
+        [&](const std::string& text, const trystero::message_info&) {
+            heard.push_back("1" + text);
+        });
+    t.b2->make_action("say").on_message(
+        [&](const std::string& text, const trystero::message_info&) {
+            heard.push_back("2" + text);
+        });
+    t.a1->make_action("say").async_send(
+        "a", [](boost::system::error_code ec) { BOOST_TEST(!ec); });
+    t.a2->make_action("say").async_send(
+        "b", [](boost::system::error_code ec) { BOOST_TEST(!ec); });
+    BOOST_TEST(run_until(t.f, [&] { return heard.size() == 2; }));
+    std::ranges::sort(heard);
+    BOOST_TEST(heard == (std::vector{"1a", "2b"}));
+}
+
+// Leaving one room ends that room's connection alone: the app's other room keeps its connection to
+// the peer, its messages flow, and no departure is seen there.
+void leaving_one_room_keeps_the_other_rooms_connection() {
+    two_rooms_each t;
+    BOOST_TEST(run_until(t.f, [&] { return t.f.net.live_connections() == 4; }));
+    std::size_t left_r1 = 0;
+    std::size_t left_r2 = 0;
+    t.b1->on_peer_leave([&](const trystero::peer_event&) { ++left_r1; });
+    t.b2->on_peer_leave([&](const trystero::peer_event&) { ++left_r2; });
+    bool done = false;
+    t.a1->async_leave([&](boost::system::error_code ec) {
+        BOOST_TEST(!ec);
+        done = true;
+    });
+    BOOST_TEST(run_until(t.f, [&] { return done && left_r1 == 1; }));
+    // r1's connection is closed at both ends; r2's stays.
+    BOOST_TEST(run_until(t.f, [&] { return t.f.net.live_connections() == 2; }));
+    std::string heard;
+    t.b2->make_action("say").on_message(
+        [&](const std::string& text, const trystero::message_info&) { heard = text; });
+    t.a2->make_action("say").async_send(
+        "still here", [](boost::system::error_code ec) { BOOST_TEST(!ec); });
+    BOOST_TEST(run_until(t.f, [&] { return heard == "still here"; }));
+    BOOST_TEST_EQ(left_r2, 0U);
+    BOOST_TEST_EQ(t.b2->peers().size(), 1U);
+    BOOST_TEST_EQ(t.a2->peers().size(), 1U);
+}
+
+// A room writes its action frames bare on its connection, as 0.27.0's sendFrame does: every frame
+// starts with the action wire's version, 3, and decodes as an action frame, with no envelope
+// around it.
+void frames_travel_bare() {
+    fixture f{true};
+    std::vector> frames;
+    f.net.filter = [&](std::size_t, std::size_t, std::span frame) {
+        frames.emplace_back(frame.begin(), frame.end());
+        return trystero::test::memory_network::verdict::deliver;
+    };
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("AAAAAAAAAAAAAAAAAAAA"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("BBBBBBBBBBBBBBBBBBBB"));
+    auto a = join(a_app, "bare");
+    auto b = join(b_app, "bare");
+    BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; }));
+    webcpp::test::require(BOOST_TEST(!frames.empty()));
+    for (const auto& frame : frames) {
+        BOOST_TEST_EQ(static_cast(frame.front()),
+                      static_cast(trystero::protocol::action_wire_version));
+        BOOST_TEST(trystero::protocol::decode_action(frame).frame.has_value());
+    }
+}
+
+// An app joins as many rooms as it is asked to, as 0.27.0's joinRoom does: no room bound, since no
+// connection carries several rooms' tokens any more.
+void an_app_joins_more_than_64_rooms() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("AAAAAAAAAAAAAAAAAAAA"));
+    std::vector rooms;
+    for (std::size_t i = 0; i < 65; ++i) {
+        auto r = a_app.join("room-" + std::to_string(i));
+        if (!BOOST_TEST(r.has_value())) {
+            return;
+        }
+        rooms.push_back(std::move(*r));
+    }
+    BOOST_TEST_EQ(rooms.size(), 65U);
 }
 
 void async_receive_works_in_a_coroutine() {
-    fixture f;
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("NNNNNNNNNNNNNNNNNNNN"));
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("NNNNNNNNNNNNNNNNNNNN"));
     auto a = join(a_app, "coro");
-    trystero::app b_app(f.io.get_executor(), f.net, app_config("OOOOOOOOOOOOOOOOOOOO"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("OOOOOOOOOOOOOOOOOOOO"));
     auto b = join(b_app, "coro");
     auto inbox = b.make_action("any");
     std::vector seen;
@@ -1497,11 +2441,11 @@ void async_receive_works_in_a_coroutine() {
             }
         },
         asio::detached);
-    BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1; }));
+    BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; }));
     a.make_action("any").async_send("text", asio::detached);
     a.make_action("any").async_send(document_of("[1,2]"),
                                                                 asio::detached);
-    BOOST_TEST(run_until(f.io, [&] { return seen.size() == 2; }));
+    BOOST_TEST(run_until(f, [&] { return seen.size() == 2; }));
     const std::vector both{"text", "[1,2]"};
     BOOST_TEST_ALL_EQ(seen.begin(), seen.end(), both.begin(), both.end());
 }
@@ -1513,10 +2457,10 @@ void async_receive_works_in_a_coroutine() {
 void json_payloads_are_read_in_the_rooms_resource_up_to_its_bound() {
     constexpr std::uint64_t bound = std::uint64_t{256} << 10U;
     std::pmr::unsynchronized_pool_resource z_memory;  // outlives the io_context
-    fixture f;
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("TTTTTTTTTTTTTTTTTTTT"));
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("TTTTTTTTTTTTTTTTTTTT"));
     auto a = join(a_app, "json");
-    trystero::app z_app(f.io.get_executor(), f.net, app_config("UUUUUUUUUUUUUUUUUUUU"));
+    trystero::test::app z_app(f.io.get_executor(), f.net, app_config("UUUUUUUUUUUUUUUUUUUU"));
     auto z = join(z_app, "json",
                   trystero::room_options{.max_json_document_bytes = bound, .memory = &z_memory});
     std::vector in_resource;
@@ -1531,7 +2475,7 @@ void json_payloads_are_read_in_the_rooms_resource_up_to_its_bound() {
         [&](const webcpp::document::document& v, const trystero::message_info&) {
             in_heap.push_back(v.root().size());
         });
-    BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1; }));
+    BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; }));
     const auto zeros = [](std::size_t n) {
         std::string text = "[0";
         for (std::size_t i = 1; i < n; ++i) {
@@ -1560,7 +2504,7 @@ void json_payloads_are_read_in_the_rooms_resource_up_to_its_bound() {
         }
     }
     // A data channel keeps its order: the last of each action arrives after the other three.
-    BOOST_TEST(run_until(f.io, [&] { return in_resource.size() >= 3 && in_heap.size() >= 3; }));
+    BOOST_TEST(run_until(f, [&] { return in_resource.size() >= 3 && in_heap.size() >= 3; }));
     const std::vector delivered{1000, at_bound, 3};
     BOOST_TEST_ALL_EQ(in_resource.begin(), in_resource.end(), delivered.begin(), delivered.end());
     BOOST_TEST_ALL_EQ(in_heap.begin(), in_heap.end(), delivered.begin(), delivered.end());
@@ -1571,10 +2515,10 @@ void json_payloads_are_read_in_the_rooms_resource_up_to_its_bound() {
 // document type: its parse recurses once a level, on the room's executor, on every target and in
 // both suspension variants, within the engine's default stack (doc: #trystero-protocol-json).
 void a_json_payload_nested_256_deep_is_delivered() {
-    fixture f;
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("XXXXXXXXXXXXXXXXXXXX"));
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("XXXXXXXXXXXXXXXXXXXX"));
     auto a = join(a_app, "deep");
-    trystero::app z_app(f.io.get_executor(), f.net, app_config("YYYYYYYYYYYYYYYYYYYY"));
+    trystero::test::app z_app(f.io.get_executor(), f.net, app_config("YYYYYYYYYYYYYYYYYYYY"));
     auto z = join(z_app, "deep");
     std::size_t delivered = 0;
     z.make_action("pmr").on_message(
@@ -1585,13 +2529,13 @@ void a_json_payload_nested_256_deep_is_delivered() {
         [&](const webcpp::document::document& v, const trystero::message_info&) {
             delivered += v.root().is_array() ? 1 : 0;
         });
-    BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1; }));
+    BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; }));
     const std::string deepest = std::string(256, '[') + std::string(256, ']');
     for (const char* name : {"pmr", "std"}) {
         a.make_action(name).async_send(document_of(deepest),
                                                                    asio::detached);
     }
-    BOOST_TEST(run_until(f.io, [&] { return delivered == 2; }));
+    BOOST_TEST(run_until(f, [&] { return delivered == 2; }));
 }
 
 // A message of another format than a document action's completes its receive with
@@ -1599,10 +2543,10 @@ void a_json_payload_nested_256_deep_is_delivered() {
 // reads undefined and it has no image, in the room's resource for a pmr::document.
 void a_rejected_document_receive_holds_nothing() {
     std::pmr::unsynchronized_pool_resource z_memory;  // outlives the io_context
-    fixture f;
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("VVVVVVVVVVVVVVVVVVVV"));
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("VVVVVVVVVVVVVVVVVVVV"));
     auto a = join(a_app, "rejected");
-    trystero::app z_app(f.io.get_executor(), f.net, app_config("WWWWWWWWWWWWWWWWWWWW"));
+    trystero::test::app z_app(f.io.get_executor(), f.net, app_config("WWWWWWWWWWWWWWWWWWWW"));
     auto z = join(z_app, "rejected", trystero::room_options{.memory = &z_memory});
     std::size_t completed = 0;
     z.make_action("pmr").async_receive(
@@ -1613,7 +2557,7 @@ void a_rejected_document_receive_holds_nothing() {
             BOOST_TEST(v.root().is_undefined());
             BOOST_TEST(v.image().empty());
             BOOST_TEST(v.get_allocator().resource() == &z_memory);
-            BOOST_TEST_EQ(info.from, "VVVVVVVVVVVVVVVVVVVV");
+            BOOST_TEST_EQ(info.from, a_app.self_id());
         });
     z.make_action("std").async_receive(
         [&](boost::system::error_code ec, webcpp::document::document v,
@@ -1623,17 +2567,17 @@ void a_rejected_document_receive_holds_nothing() {
             BOOST_TEST(v.root().is_undefined());
             BOOST_TEST(v.image().empty());
         });
-    BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1; }));
+    BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; }));
     a.make_action("pmr").async_send("not JSON", asio::detached);
     a.make_action("std").async_send("not JSON", asio::detached);
-    BOOST_TEST(run_until(f.io, [&] { return completed == 2; }));
+    BOOST_TEST(run_until(f, [&] { return completed == 2; }));
 }
 
 void view_handlers_read_the_frame_without_copying() {
-    fixture f;
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("RRRRRRRRRRRRRRRRRRRR"));
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("RRRRRRRRRRRRRRRRRRRR"));
     auto a = join(a_app, "views");
-    trystero::app b_app(f.io.get_executor(), f.net, app_config("SSSSSSSSSSSSSSSSSSSS"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("SSSSSSSSSSSSSSSSSSSS"));
     auto b = join(b_app, "views");
     std::string text_seen;
     std::size_t bytes_seen = 0;
@@ -1645,275 +2589,3261 @@ void view_handlers_read_the_frame_without_copying() {
             bytes_seen = data.size();
             metadata_seen = info.metadata;
         });
-    BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1; }));
+    BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; }));
     a.make_action("note").async_send(
         std::string_view("a view, copied once at the call"), asio::detached);
     a.make_action("blob").async_send(
         trystero::bytes(50'000, 7), trystero::send_options{.targets = {}, .metadata = R"({"k":1})"},
         asio::detached);
-    BOOST_TEST(run_until(f.io, [&] { return !text_seen.empty() && bytes_seen != 0; }));
+    BOOST_TEST(run_until(f, [&] { return !text_seen.empty() && bytes_seen != 0; }));
     BOOST_TEST_EQ(text_seen, "a view, copied once at the call");
     BOOST_TEST_EQ(bytes_seen, 50'000U);
     BOOST_TEST_EQ(metadata_seen, R"({"k":1})");
 }
 
 void a_rate_limited_relay_does_not_stop_discovery() {
-    fixture f;
+    fixture f{true};
     f.net.relay(relay_a).rate_limit_next = 1000;  // relay A refuses everything; B carries the room
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("PPPPPPPPPPPPPPPPPPPP"));
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("PPPPPPPPPPPPPPPPPPPP"));
     auto a = join(a_app, "limits");
-    trystero::app b_app(f.io.get_executor(), f.net, app_config("QQQQQQQQQQQQQQQQQQQQ"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("QQQQQQQQQQQQQQQQQQQQ"));
     auto b = join(b_app, "limits");
-    BOOST_TEST(run_until(f.io, [&] { return a.peers().size() == 1 && b.peers().size() == 1; }));
+    BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; }));
     // Backoff: after the first refusal each peer stops publishing on relay A, so it sees only a
     // handful of attempts.
     BOOST_TEST_LT(1000 - f.net.relay(relay_a).rate_limit_next, 12U);
 }
 
-// A connection's end is every room's (one room here): a forced failure, a frame that does not
-// decode, and a 65th advertised token each end it; the peers then meet again over a new one.
-void a_connections_end_is_seen_and_the_peers_meet_again() {
-    for (std::size_t way = 0; way < 3; ++way) {
-        fixture f{true};
-        trystero::app a_app(f.io.get_executor(), f.net, app_config("NNNNNNNNNNNNNNNNNNNN"));
-        auto a = join(a_app, "ends");
-        std::vector a_pcs;
-        f.net.on_made = [&](std::size_t pc, std::span) {
-            a_pcs.push_back(pc);
-        };
-        trystero::app b_app(f.io.get_executor(), f.net, app_config("OOOOOOOOOOOOOOOOOOOO"));
-        const auto b = join(b_app, "ends");
-        std::size_t joins = 0;
-        std::size_t leaves = 0;
-        a.on_peer_join([&](std::string_view) { ++joins; });
-        a.on_peer_leave([&](std::string_view) { ++leaves; });
-        webcpp::test::require(BOOST_TEST(run_until(f, [&] { return joins == 1; })));
-        const auto open_pc = f.net.live_connections();  // the pair, both ends
-        BOOST_TEST_EQ(open_pc, 2U);
-        // The first connection made once A's room exists: A's offer in practice, A's id being the
-        // lower; an end of either side ends the pair, so every way holds for either.
-        const std::size_t a_end = a_pcs.front();
-        if (way == 0) {
-            f.net.fail(a_end);
-        } else if (way == 1) {
-            const std::array bad{3, 0, 1, 'x'};
-            f.net.inject(a_end, bad);
-        } else {
-            for (std::size_t i = 0; i < 65; ++i) {
-                f.net.inject(a_end,
-                             trystero::protocol::presence_frame("X" + std::to_string(i), true));
+// A join listener added with `replay` is called at once, within the call, with each peer already
+// joined, and its user, before it is in place; without `replay` it waits for the next join. Several
+// listeners run in the order added, the user's join after its peer's.
+void replay_reports_current_peers() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("RRRRRRRRRRRRRRRRRRRR"));
+    auto a = join(a_app, "replay");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("SSSSSSSSSSSSSSSSSSSS"));
+    const auto b = join(b_app, "replay");
+    std::vector order;
+    a.on_peer_join(
+        [&](const trystero::peer_event& e) { order.push_back("peer " + std::string(e.peer_id)); });
+    a.on_user_join(
+        [&](const trystero::user_event& e) { order.push_back("user " + std::string(e.user_id)); });
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return order.size() == 2; })));
+    const std::string b_id(b_app.self_id());
+    const std::string b_user(b_app.user_id());
+    const std::vector first{"peer " + b_id, "user " + b_user};
+    BOOST_TEST_ALL_EQ(order.begin(), order.end(), first.begin(), first.end());
+
+    std::vector> replayed;
+    const auto all = a.on_peer_join(
+        [&](const trystero::peer_event& e) { replayed.emplace_back(e.peer_id, e.user_id); },
+        {.once = false, .replay = true});
+    // Within the call: B, with the user its handshake verified.
+    if (BOOST_TEST_EQ(replayed.size(), 1U)) {
+        BOOST_TEST_EQ(replayed[0].first, b_id);
+        BOOST_TEST_EQ(replayed[0].second, b_user);
+    }
+    std::vector users;
+    const auto user_once =
+        a.on_user_join([&](const trystero::user_event& e) { users.emplace_back(e.user_id); },
+                       {.once = true, .replay = true});
+    const std::vector only_b{b_user};
+    BOOST_TEST_ALL_EQ(users.begin(), users.end(), only_b.begin(), only_b.end());
+    BOOST_TEST(!user_once.active());  // removed before its replay ran
+    std::size_t later = 0;
+    const auto plain = a.on_peer_join([&](const trystero::peer_event&) { ++later; });
+    BOOST_TEST_EQ(later, 0U);
+
+    // The next join reaches every listener still in place, the once one excepted.
+    trystero::test::app c_app(f.io.get_executor(), f.net, app_config("TTTTTTTTTTTTTTTTTTTT"));
+    const auto c = join(c_app, "replay");
+    BOOST_TEST(run_until(f, [&] { return later == 1 && replayed.size() == 2; }));
+    BOOST_TEST_EQ(replayed.back().first, c_app.self_id());
+    BOOST_TEST_EQ(users.size(), 1U);
+    BOOST_TEST(all.active());
+    BOOST_TEST(plain.active());
+}
+
+// A request action takes one request listener at a time, and one receive gate, as Trystero's
+// throws "handler already registered; unsubscribe first"; once it is removed, another is taken.
+void second_on_request_is_refused() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("UUUUUUUUUUUUUUUUUUUU"));
+    auto a = join(a_app, "requests");
+    auto ask = a.make_request_action("ask");
+    auto first = ask.on_request([](std::string q, const trystero::message_info&) { return q; });
+    webcpp::test::require(BOOST_TEST(first.has_value()));
+    const auto second =
+        ask.on_request([](std::string q, const trystero::message_info&) { return q; });
+    BOOST_TEST(second.has_error() && second.error() == trystero::error::already_subscribed);
+    // Another handle of the action meets the same listener.
+    const auto through_another = a.make_request_action("ask").on_request(
+        [](std::string q, const trystero::message_info&) { return q; });
+    BOOST_TEST(through_another.has_error());
+    first->unsubscribe();
+    const auto third =
+        ask.on_request([](std::string q, const trystero::message_info&) { return q; });
+    BOOST_TEST(third.has_value() && third->active());
+
+    const auto gate = ask.on_receive([](const trystero::receive_info&) { return true; });
+    webcpp::test::require(BOOST_TEST(gate.has_value()));
+    BOOST_TEST(ask.on_receive([](const trystero::receive_info&) { return true; }).has_error());
+    auto chat = a.make_action("chat");
+    BOOST_TEST(chat.on_receive([](const trystero::receive_info&) { return true; }).has_value());
+    BOOST_TEST(chat.on_receive([](const trystero::receive_info&) { return true; }).has_error());
+}
+
+// A request is answered by the peer asked, with the request's own metadata; an answer that is an
+// error refuses it; a peer with no listener lets it wait, so that it times out; an absent target is
+// not connected. The request travels in 0.27.0's envelope, `{"r":,"m":}`.
+void a_request_is_answered_or_refused() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("VVVVVVVVVVVVVVVVVVVV"));
+    auto a = join(a_app, "answers");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("WWWWWWWWWWWWWWWWWWWW"));
+    auto b = join(b_app, "answers");
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })));
+    std::string seen_metadata;
+    std::string seen_from;
+    auto upper = b.make_request_action("upper");
+    const auto answering = upper.on_request(
+        [&](std::string q,
+            const trystero::message_info& info) -> boost::system::result {
+            seen_metadata = info.metadata;
+            seen_from = info.from;
+            if (q == "no") {
+                return make_error_code(trystero::error::backend_failure);
             }
+            std::ranges::transform(q, q.begin(), [](char c) { return c == 'a' ? 'A' : c; });
+            return q;
+        });
+    BOOST_TEST(answering.has_value());
+    // Without a listener, B's requests of "later" wait for one, as messages do.
+    const auto later_b = b.make_request_action("later");
+
+    auto ask = a.make_request_action("upper");
+    std::optional> answered;
+    ask.async_request(
+        "banana",
+        trystero::request_options{
+            .target = trystero::peer_id(b.self_id()),
+            .metadata = R"({"k":[1,2]})",
+            .timeout = std::nullopt,
+        },
+        [&](boost::system::error_code ec, std::string r) { answered.emplace(ec, std::move(r)); });
+    BOOST_TEST(run_until(f, [&] { return answered.has_value(); }));
+    BOOST_TEST(!answered->first);
+    BOOST_TEST_EQ(answered->second, "bAnAnA");
+    BOOST_TEST_EQ(seen_metadata, R"({"k":[1,2]})");
+    BOOST_TEST_EQ(seen_from, a.self_id());
+
+    std::optional refused;
+    ask.async_request("no", trystero::request_options{.target = trystero::peer_id(b.self_id())},
+                      [&](boost::system::error_code ec, const std::string& r) {
+                          refused = ec;
+                          BOOST_TEST(r.empty());
+                      });
+    BOOST_TEST(run_until(f, [&] { return refused.has_value(); }));
+    BOOST_TEST(*refused == trystero::error::request_rejected);
+    BOOST_TEST(seen_metadata.empty());  // the request named none
+
+    std::optional timed_out;
+    a.make_request_action("later").async_request(
+        "hello",
+        trystero::request_options{
+            .target = trystero::peer_id(b.self_id()),
+            .metadata = {},
+            .timeout = 50ms,
+        },
+        [&](boost::system::error_code ec, const std::string&) { timed_out = ec; });
+    BOOST_TEST(run_until(f, [&] { return timed_out.has_value(); }));
+    BOOST_TEST(*timed_out == trystero::error::request_timed_out);
+
+    std::optional absent;
+    ask.async_request("x", trystero::request_options{.target = "nobody"},
+                      [&](boost::system::error_code ec, const std::string&) { absent = ec; });
+    BOOST_TEST(run_until(f, [&] { return absent.has_value(); }));
+    BOOST_TEST(*absent == trystero::error::not_connected);
+}
+
+// An action without a listener lets its messages wait, as 0.27.0's pre-listener ring does, and
+// delivers them once a listener comes; a listener removed makes them wait again. Several listeners
+// each read every message, in the order added, a binary one each in a copy of its own.
+void messages_wait_for_a_listener() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("XXXXXXXXXXXXXXXXXXXX"));
+    auto a = join(a_app, "waiting");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("YYYYYYYYYYYYYYYYYYYY"));
+    auto b = join(b_app, "waiting");
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })));
+    auto send = a.make_action("bin");
+    auto receive = b.make_action("bin");
+    std::size_t sent = 0;
+    for (std::uint8_t i = 0; i < 3; ++i) {
+        send.async_send(trystero::pmr_bytes(1, i), [&](boost::system::error_code ec) {
+            BOOST_TEST(!ec);
+            ++sent;
+        });
+    }
+    BOOST_TEST(run_until(f, [&] { return sent == 3; }));
+    run_until(f, [] { return false; }, 100ms);  // they arrive, and wait
+    std::vector got;
+    auto first =
+        receive.on_message([&](const trystero::pmr_bytes& v, const trystero::message_info&) {
+            got.push_back("first " + std::to_string(v.at(0)));
+        });
+    auto second =
+        receive.on_message([&](const trystero::pmr_bytes& v, const trystero::message_info&) {
+            got.push_back("second " + std::to_string(v.at(0)));
+        });
+    BOOST_TEST(run_until(f, [&] { return got.size() == 6; }));
+    const std::vector both{
+        "first 0", "second 0", "first 1", "second 1", "first 2", "second 2",
+    };
+    BOOST_TEST_ALL_EQ(got.begin(), got.end(), both.begin(), both.end());
+
+    first.unsubscribe();
+    second.unsubscribe();
+    got.clear();
+    send.async_send(trystero::pmr_bytes(1, 9), [&](boost::system::error_code) { ++sent; });
+    BOOST_TEST(run_until(f, [&] { return sent == 4; }));
+    run_until(f, [] { return false; }, 100ms);
+    BOOST_TEST(got.empty());
+    const auto once = receive.on_message(
+        [&](const trystero::pmr_bytes& v, const trystero::message_info&) {
+            got.push_back("once " + std::to_string(v.at(0)));
+        },
+        {.once = true, .replay = false});
+    BOOST_TEST(run_until(f, [&] { return got.size() == 1; }));
+    BOOST_TEST_EQ(got.at(0), "once 9");
+    BOOST_TEST(!once.active());
+}
+
+// A receive gate decides before the action receives: a refused inline message is dropped, a
+// refused transfer rejected, whose send fails; the progress of an accepted transfer is reported
+// after its chunks, rising, and 1 once it is whole.
+void a_receive_gate_decides_and_progress_is_reported() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("ZZZZZZZZZZZZZZZZZZZY"));
+    auto a = join(a_app, "gate");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("ZZZZZZZZZZZZZZZZZZZX"));
+    auto b = join(b_app, "gate");
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })));
+    auto send = a.make_action("file");
+    auto receive = b.make_action("file");
+    std::vector asked;
+    const auto gate = receive.on_receive([&](const trystero::receive_info& info) {
+        asked.push_back(info.byte_length);
+        BOOST_TEST_EQ(info.peer_id, a.self_id());
+        BOOST_TEST_EQ(info.user_id, a.self().user_id);
+        return info.metadata != R"({"keep":false})";
+    });
+    BOOST_TEST(gate.has_value());
+    std::vector got;
+    receive.on_message(
+        [&](const trystero::bytes& v, const trystero::message_info&) { got.push_back(v.size()); });
+    std::vector shares;
+    receive.on_receive_progress([&](double share, const trystero::progress_info& info) {
+        shares.push_back(share);
+        BOOST_TEST_EQ(info.peer_id, a.self_id());
+    });
+    std::vector sent;
+    const auto drop = trystero::send_options{.targets = {}, .metadata = R"({"keep":false})"};
+    send.async_send(trystero::bytes(10, 1), drop,
+                    [&](boost::system::error_code ec) { sent.push_back(ec); });
+    send.async_send(trystero::bytes(100'000, 2), drop,
+                    [&](boost::system::error_code ec) { sent.push_back(ec); });
+    BOOST_TEST(run_until(f, [&] { return sent.size() == 2; }));
+    // The inline frame went into the channel; the transfer was rejected.
+    BOOST_TEST(!sent.at(0));
+    BOOST_TEST(sent.at(1) == trystero::error::transfer_rejected);
+    // Four wide chunks, as the memory network's connections take 64 KiB messages.
+    send.async_send(trystero::bytes(200'000, 3),
+                    [&](boost::system::error_code ec) { sent.push_back(ec); });
+    BOOST_TEST(
+        run_until(f, [&] { return got.size() == 1 && !shares.empty() && shares.back() == 1.0; }));
+    BOOST_TEST_EQ(got.at(0), 200'000U);
+    const std::vector sizes{10, 100'000, 200'000};
+    BOOST_TEST_ALL_EQ(asked.begin(), asked.end(), sizes.begin(), sizes.end());
+    BOOST_TEST_GT(shares.size(), 2U);
+    BOOST_TEST(std::ranges::is_sorted(shares));
+    BOOST_TEST_LT(shares.front(), 1.0);
+}
+
+// A listener may release the last handles of its room while it is reported: the room stays whole
+// until the emission ends, whose other listeners run, as Trystero's leave clears listeners only
+// once it completes; nothing is reported after it. A progress listener that drops its room and its
+// action at the first share, as a page torn down on a finished upload would, and a join listener
+// that drops its room.
+void a_listener_may_end_its_room_while_it_is_reported() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("endsAAAAAAAAAAAAAAAA"));
+    std::optional a(join(a_app, "teardown"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("endsBBBBBBBBBBBBBBBB"));
+    std::optional b(join(b_app, "teardown"));
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a->peers().size() == 1 && b->peers().size() == 1; })));
+    std::optional> send(a->make_action("file"));
+    std::optional> receive(
+        b->make_action("file"));
+    bool b_ended = false;
+    std::size_t rest_b = 0;
+    std::size_t after_b = 0;
+    receive->on_message([&](const trystero::bytes&, const trystero::message_info&) { ++after_b; });
+    receive->on_receive_progress([&](double, const trystero::progress_info&) {
+        b_ended = true;
+        receive.reset();
+        b.reset();
+    });
+    receive->on_receive_progress([&](double, const trystero::progress_info&) { ++rest_b; });
+    send->async_send(trystero::bytes(100'000, 1), [](boost::system::error_code) {});
+    BOOST_TEST(run_until(f, [&] { return b_ended; }));
+    run_until(f, [] { return false; }, 100ms);
+    BOOST_TEST_EQ(rest_b, 1U);
+    BOOST_TEST_EQ(after_b, 0U);
+
+    bool a_ended = false;
+    std::size_t rest_a = 0;
+    a->on_peer_join([&](const trystero::peer_event&) {
+        a_ended = true;
+        send.reset();
+        a.reset();
+    });
+    a->on_peer_join([&](const trystero::peer_event&) { ++rest_a; });
+    a->on_user_join([&](const trystero::user_event&) { ++rest_a; });
+    trystero::test::app c_app(f.io.get_executor(), f.net, app_config("endsCCCCCCCCCCCCCCCC"));
+    const auto c = join(c_app, "teardown");
+    BOOST_TEST(run_until(f, [&] { return a_ended; }));
+    run_until(f, [] { return false; }, 100ms);
+    BOOST_TEST_EQ(rest_a, 2U);  // the peer's join, then its user's, once each
+}
+
+// A subscription may outlive its room: it is inactive once the room's last handles are gone, or
+// once the room is left, as Trystero clears its listeners then, and unsubscribing does nothing.
+void a_subscription_outlives_its_room() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("outlivesAAAAAAAAAAAA"));
+    std::optional a(join(a_app, "outlives"));
+    std::optional> chat(a->make_action("chat"));
+    auto joined = a->on_peer_join([](const trystero::peer_event&) {});
+    auto said = chat->on_message([](const std::string&, const trystero::message_info&) {});
+    auto gate = chat->on_receive([](const trystero::receive_info&) { return true; });
+    webcpp::test::require(BOOST_TEST(gate.has_value()));
+    BOOST_TEST(joined.active() && said.active() && gate->active());
+    chat.reset();
+    a.reset();
+    run_until(f, [] { return false; }, 50ms);
+    BOOST_TEST(!joined.active());
+    BOOST_TEST(!said.active());
+    BOOST_TEST(!gate->active());
+    joined.unsubscribe();
+    said.unsubscribe();
+    gate->unsubscribe();
+    BOOST_TEST(!joined.active());
+
+    auto b = join(a_app, "left");
+    const auto left = b.on_peer_leave([](const trystero::peer_event&) {});
+    bool done = false;
+    b.async_leave([&](boost::system::error_code) { done = true; });
+    BOOST_TEST(run_until(f, [&] { return done; }));
+    BOOST_TEST(!left.active());
+}
+
+// A join the room posted just before it was left is not reported, as 0.27.0 reports none once its
+// room is leaving; the listeners go with the leave.
+void a_join_posted_before_the_leave_is_not_reported() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("postedAAAAAAAAAAAAAA"));
+    auto a = join(a_app, "posted");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("postedBBBBBBBBBBBBBB"));
+    const auto b = join(b_app, "posted");
+    std::size_t joins = 0;
+    const auto peers = a.on_peer_join([&](const trystero::peer_event&) { ++joins; });
+    const auto users = a.on_user_join([&](const trystero::user_event&) { ++joins; });
+    // One handler at a time, until A has B: the join it posted then has not run yet.
+    const auto end = std::chrono::steady_clock::now() + 10s;
+    while (a.peers().empty() && std::chrono::steady_clock::now() < end) {
+        f.io.run_one_for(20ms);
+        if (f.io.stopped()) {
+            f.io.restart();
         }
-        BOOST_TEST(run_until(f, [&] { return leaves == 1; }));
-        BOOST_TEST(run_until(f, [&] { return joins == 2; }, 20s));
     }
+    webcpp::test::require(BOOST_TEST_EQ(a.peers().size(), 1U));
+    BOOST_TEST_EQ(joins, 0U);
+    bool left = false;
+    a.async_leave([&](boost::system::error_code) { left = true; });
+    BOOST_TEST(run_until(f, [&] { return left; }));
+    BOOST_TEST_EQ(joins, 0U);
+    BOOST_TEST(!peers.active());
+    BOOST_TEST(!users.active());
 }
 
-// A frame naming a token no room of the app has is dropped, the connection stays, and the app's
-// resource keeps none of them (64 kept frames of 4,000 bytes would hold over 256 KB).
-void a_frame_of_an_unknown_token_is_dropped() {
-    counting_resource memory;
+// A receive gate asked about the messages that waited, as a listener is added, may release the
+// room's last handles, that of the action being listened to among them: the room stays whole until
+// the call returns.
+void a_gate_may_end_its_room_while_waiting_messages_are_delivered() {
     fixture f{true};
-    auto a_config = app_config("PPPPPPPPPPPPPPPPPPPP");
-    a_config.memory = &memory;
-    trystero::app a_app(f.io.get_executor(), f.net, std::move(a_config));
-    auto a = join(a_app, "unknown");
-    std::vector pcs;
-    f.net.on_made = [&](std::size_t pc, std::span) {
-        pcs.push_back(pc);
-    };
-    trystero::app b_app(f.io.get_executor(), f.net, app_config("QQQQQQQQQQQQQQQQQQQQ"));
-    const auto b = join(b_app, "unknown");
-    std::size_t leaves = 0;
-    a.on_peer_leave([&](std::string_view) { ++leaves; });
-    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; })));
-    const std::vector action(4'000, 2);
-    advance(f, 300ms);
-    const auto before = memory.in_use;
-    for (std::size_t i = 0; i < 1000; ++i) {
-        f.net.inject(pcs.front(), trystero::protocol::room_frame("unknown-token", action));
-    }
-    advance(f, 300ms);
-    BOOST_TEST_EQ(leaves, 0U);
-    BOOST_TEST_EQ(a.peers().size(), 1U);
-    BOOST_TEST_LT(memory.in_use, before + (std::size_t{64} * 1024));
-}
-
-// Malformed envelopes end the connection; a frame of exactly 16,515 bytes does not.
-void malformed_envelopes_end_the_connection() {
-    const auto zero_token = std::vector{2, 1, 0, 0};
-    std::vector long_token{2, 1, 0, 129};
-    long_token.resize(4 + 129, 'x');
-    const auto kind_3 = std::vector{3, 1, 0, 1, 'x'};
-    std::vector too_big{1, 0, 1, 'x'};
-    too_big.resize(16'516, 0);
-    for (const auto& bad : {zero_token, long_token, kind_3, too_big}) {
-        fixture f{true};
-        trystero::app a_app(f.io.get_executor(), f.net, app_config("RRRRRRRRRRRRRRRRRRRR"));
-        auto a = join(a_app, "bad");
-        std::vector pcs;
-        f.net.on_made = [&](std::size_t pc, std::span) {
-            pcs.push_back(pc);
-        };
-        trystero::app b_app(f.io.get_executor(), f.net, app_config("SSSSSSSSSSSSSSSSSSSS"));
-        const auto b = join(b_app, "bad");
-        std::size_t leaves = 0;
-        a.on_peer_leave([&](std::string_view) { ++leaves; });
-        webcpp::test::require(BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; })));
-        f.net.inject(pcs.front(), bad);
-        BOOST_TEST(run_until(f, [&] { return leaves == 1; }));
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("gateAAAAAAAAAAAAAAAA"));
+    auto a = join(a_app, "gated");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("gateBBBBBBBBBBBBBBBB"));
+    std::optional b(join(b_app, "gated"));
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b->peers().size() == 1; })));
+    auto send = a.make_action("kept");
+    std::optional> receive(
+        b->make_action("kept"));
+    std::size_t sent = 0;
+    for (std::uint8_t i = 0; i < 2; ++i) {
+        send.async_send(trystero::bytes(1, i), [&](boost::system::error_code) { ++sent; });
     }
+    BOOST_TEST(run_until(f, [&] { return sent == 2; }));
+    run_until(f, [] { return false; }, 100ms);  // they arrive, and wait for a listener
+    std::size_t asked = 0;
+    const auto gate = receive->on_receive([&](const trystero::receive_info&) {
+        ++asked;
+        receive.reset();
+        b.reset();
+        return false;
+    });
+    BOOST_TEST(gate.has_value());
+    BOOST_TEST_EQ(asked, 0U);  // nothing is delivered yet: the action listens to nothing
+    std::size_t got = 0;
+    const auto listening =
+        receive->on_message([&](const trystero::bytes&, const trystero::message_info&) { ++got; });
+    BOOST_TEST_EQ(asked, 2U);  // each message that waited, the room gone after the first
+    BOOST_TEST(!listening.active());
+    BOOST_TEST(!receive.has_value() && !b.has_value());
+    run_until(f, [] { return false; }, 100ms);
+    BOOST_TEST_EQ(got, 0U);
+}
+
+// Leaves are reported as joins are: the peer's, then its user's.
+void leaves_are_reported_peer_then_user() {
     fixture f{true};
-    trystero::app a_app(f.io.get_executor(), f.net, app_config("RRRRRRRRRRRRRRRRRRRR"));
-    auto a = join(a_app, "bad");
-    std::vector pcs;
-    f.net.on_made = [&](std::size_t pc, std::span) {
-        pcs.push_back(pc);
-    };
-    trystero::app b_app(f.io.get_executor(), f.net, app_config("SSSSSSSSSSSSSSSSSSSS"));
-    const auto b = join(b_app, "bad");
-    std::size_t leaves = 0;
-    a.on_peer_leave([&](std::string_view) { ++leaves; });
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("leavesAAAAAAAAAAAAAA"));
+    auto a = join(a_app, "leaves");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("leavesBBBBBBBBBBBBBB"));
+    std::optional b(join(b_app, "leaves"));
+    std::vector order;
+    a.on_user_leave(
+        [&](const trystero::user_event& e) { order.push_back("user " + std::string(e.user_id)); });
+    a.on_peer_leave(
+        [&](const trystero::peer_event& e) { order.push_back("peer " + std::string(e.peer_id)); });
     webcpp::test::require(BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; })));
-    std::vector largest{1, 0, 1, 'x'};
-    largest.resize(16'515, 0);
-    f.net.inject(pcs.front(), largest);
-    advance(f, 300ms);
-    BOOST_TEST_EQ(leaves, 0U);
+    b.reset();
+    BOOST_TEST(run_until(f, [&] { return order.size() == 2; }));
+    const std::string b_id(b_app.self_id());
+    const std::vector expected{"peer " + b_id, "user " + std::string(b_app.user_id())};
+    BOOST_TEST_ALL_EQ(order.begin(), order.end(), expected.begin(), expected.end());
+}
+
+/** An app's setup of `label` that presents `identity`. */
+trystero::test::app_setup app_config_of(std::string_view label,
+                                        const trystero::user_identity& identity) {
+    auto config = app_config(label);
+    config.identity = identity;
+    return config;
+}
+
+/** A user identity of the tests, made or the case ends. */
+trystero::user_identity make_user_identity() {
+    auto made = trystero::create_user_identity();
+    webcpp::test::require(BOOST_TEST(made.has_value()));
+    return *made;
 }
 
-// A room acts on the end of the connection its peer is bound to, and on no other: a late end of
-// the peer's first connection keeps the peer, bound to the second; the second's end removes it.
-void a_late_end_of_another_connection_keeps_the_peer() {
+// Two peers of one user, two apps that import one user identity, and a peer of a user of its own.
+struct one_user_two_peers {
+    explicit one_user_two_peers(fixture& f)
+        : identity(make_user_identity()),
+          user(identity.user_id()),
+          a_app(f.io.get_executor(), f.net, app_config("usersAAAAAAAAAAAAAAA")),
+          b1_app(f.io.get_executor(), f.net, app_config_of("usersBBBBBBBBBBBBBB1", identity)),
+          b2_app(f.io.get_executor(), f.net, app_config_of("usersBBBBBBBBBBBBBB2", identity)),
+          a(join(a_app, "users")) {
+        a.on_peer_join([this](const trystero::peer_event& e) {
+            events.push_back("peer join " + std::string(e.peer_id) + " " + std::string(e.user_id));
+        });
+        a.on_user_join([this](const trystero::user_event& e) {
+            events.push_back("user join " + std::string(e.user_id));
+        });
+        a.on_peer_leave([this](const trystero::peer_event& e) {
+            events.push_back("peer leave " + std::string(e.peer_id) + " " + std::string(e.user_id));
+        });
+        a.on_user_leave([this](const trystero::user_event& e) {
+            events.push_back("user leave " + std::string(e.user_id) + " " + std::string(e.peer_id));
+        });
+        b1.emplace(join(b1_app, "users"));
+        webcpp::test::require(BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; })));
+        b2.emplace(join(b2_app, "users"));
+        webcpp::test::require(BOOST_TEST(run_until(f, [&] {
+            // A's join events are posted, so they can trail its peers: wait for all three.
+            return a.peers().size() == 2 && b1->peers().size() == 2 && b2->peers().size() == 2 &&
+                   events.size() == 3;
+        })));
+    }
+
+    trystero::user_identity identity;
+    std::string user;  // the identity's id, which b1 and b2 present
+    trystero::test::app a_app;
+    trystero::test::app b1_app;
+    trystero::test::app b2_app;
+    trystero::room a;
+    std::optional b1;
+    std::optional b2;
+    std::vector events;
+};
+
+// A user id as a send's target reaches each of its peers; `users()` and `peers()` list them, and
+// the user joined once, after its first peer.
+void send_to_a_user_reaches_each_of_its_peers() {
     fixture f{true};
-    const std::string b_id = "UUUUUUUUUUUUUUUUUUUU";
-    const auto a = make_app_room(f, "TTTTTTTTTTTTTTTTTTTT", "late");
-    std::vector pcs;
-    f.net.on_made = [&](std::size_t pc, std::span) {
-        pcs.push_back(pc);
+    one_user_two_peers t(f);
+    const std::string b1_id(t.b1_app.self_id());
+    const std::string b2_id(t.b2_app.self_id());
+    const std::string user = t.user;
+    const std::vector joins{
+        "peer join " + b1_id + " " + user,
+        "user join " + user,
+        "peer join " + b2_id + " " + user,
     };
-    trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id));
-    auto b = join(b_app, "late");
-    std::size_t b_joins = 0;
-    std::size_t b_leaves = 0;
-    b.on_peer_join([&](std::string_view) { ++b_joins; });
-    b.on_peer_leave([&](std::string_view) { ++b_leaves; });
-    webcpp::test::require(BOOST_TEST(
-        run_until(f, [&] { return a.room->active_peers().size() == 1 && b_joins == 1; })));
-    const auto first = a.app->find(b_id);
-    webcpp::test::require(BOOST_TEST(first != nullptr));
-    f.net.fail(pcs.front());
-    webcpp::test::require(BOOST_TEST(
-        run_until(f, [&] { return a.room->active_peers().size() == 1 && b_joins == 2; }, 30s)));
-    const auto second = a.app->find(b_id);
-    webcpp::test::require(BOOST_TEST(second != nullptr && second != first));
-    a.room->connection_ended(first, b_id, "a late end of the first connection");
-    advance(f, 5000ms);
-    BOOST_TEST_EQ(a.room->active_peers().size(), 1U);
-    BOOST_TEST_EQ(b_leaves, 1U);
-    second->end("test");
-    BOOST_TEST(a.room->active_peers().empty());
-    a.room->abandon();
+    BOOST_TEST_ALL_EQ(t.events.begin(), t.events.end(), joins.begin(), joins.end());
+
+    const auto users = t.a.users();
+    webcpp::test::require(BOOST_TEST_EQ(users.size(), 1U));
+    const auto it = users.find(std::string_view(user));
+    webcpp::test::require(BOOST_TEST(it != users.end()));
+    const std::vector both{b1_id, b2_id};
+    BOOST_TEST_ALL_EQ(it->second.peer_ids.begin(), it->second.peer_ids.end(), both.begin(),
+                      both.end());
+    BOOST_TEST(it->second.roles.empty());
+    const auto peers = t.a.peers();
+    webcpp::test::require(BOOST_TEST_EQ(peers.size(), 2U));
+    for (const auto& id : both) {
+        const auto peer = peers.find(id);
+        webcpp::test::require(BOOST_TEST(peer != peers.end()));
+        BOOST_TEST_EQ(peer->second.user_id, std::string_view(user));
+        BOOST_TEST(peer->second.direct);
+        BOOST_TEST_EQ(peer->second.hops, 1U);
+        BOOST_TEST(peer->second.roles.empty());
+    }
+
+    // A replay reports the user once, with its first peer.
+    std::vector replayed;
+    const auto replay = t.a.on_user_join(
+        [&](const trystero::user_event& e) {
+            replayed.push_back(std::string(e.user_id) + " " + std::string(e.peer_id));
+        },
+        {.once = false, .replay = true});
+    const std::vector once{user + " " + b1_id};
+    BOOST_TEST_ALL_EQ(replayed.begin(), replayed.end(), once.begin(), once.end());
+
+    auto note = t.a.make_action("note");
+    std::vector heard;
+    t.b1->make_action("note").on_message(
+        [&](const std::string& text, const trystero::message_info&) {
+            heard.push_back("b1 " + text);
+        });
+    t.b2->make_action("note").on_message(
+        [&](const std::string& text, const trystero::message_info&) {
+            heard.push_back("b2 " + text);
+        });
+    std::optional sent;
+    note.async_send("to the user",
+                    trystero::send_options{.targets = {trystero::peer_id(user)}, .metadata = {}},
+                    [&](boost::system::error_code ec) { sent = ec; });
+    BOOST_TEST(run_until(f, [&] { return sent.has_value() && heard.size() == 2; }));
+    BOOST_TEST(sent && !*sent);
+    std::ranges::sort(heard);
+    const std::vector expected{"b1 to the user", "b2 to the user"};
+    BOOST_TEST_ALL_EQ(heard.begin(), heard.end(), expected.begin(), expected.end());
+
+    // A user and one of its peers together reach each peer once.
+    heard.clear();
+    sent.reset();
+    note.async_send("once each",
+                    trystero::send_options{
+                        .targets =
+                            {
+                                trystero::peer_id(b2_id),
+                                trystero::peer_id(user),
+                                trystero::peer_id(b1_id),
+                            },
+                        .metadata = {},
+                    },
+                    [&](boost::system::error_code ec) { sent = ec; });
+    BOOST_TEST(run_until(f, [&] { return sent.has_value() && heard.size() == 2; }));
+    run_until(f, [] { return false; }, 100ms);
+    BOOST_TEST_EQ(heard.size(), 2U);
+    BOOST_TEST(sent && !*sent);
+
+    // A request to the user asks one of its peers, the first by id, as 0.27.0 picks it.
+    auto ask = t.a.make_request_action("ask");
+    for (auto* b : {&*t.b1, &*t.b2}) {
+        const auto answered = b->make_request_action("ask").on_request(
+            [b](const std::string&, const trystero::message_info&) {
+                return std::string(b->self_id());
+            });
+        webcpp::test::require(BOOST_TEST(answered.has_value()));
+    }
+    std::optional answer;
+    ask.async_request("who", trystero::request_options{.target = trystero::peer_id(user)},
+                      [&](boost::system::error_code ec, std::string who) {
+                          BOOST_TEST(!ec);
+                          answer = std::move(who);
+                      });
+    BOOST_TEST(run_until(f, [&] { return answer.has_value(); }));
+    BOOST_TEST_EQ(answer.value_or(""), std::min(b1_id, b2_id));
 }
 
-// A remote's presence(0) for the room is a departure: the peer leaves, and the connection, which
-// another room of the app could use, idles instead of ending.
-void a_withdrawn_presence_is_a_departure() {
+// The scenario of the specification: of two peers of one user, the first leaves and its user
+// stays; the second leaves and its user leaves after it.
+void a_user_leaves_with_its_last_peer() {
     fixture f{true};
-    const std::string b_id = "WWWWWWWWWWWWWWWWWWWW";
-    const auto a = make_app_room(f, "VVVVVVVVVVVVVVVVVVVV", "withdraw");
-    std::size_t leaves = 0;
-    a.room->on_peer_leave(
-        a.room->bind([&](std::string_view) { ++leaves; }));
-    std::vector pcs;
-    f.net.on_made = [&](std::size_t pc, std::span) {
-        pcs.push_back(pc);
+    one_user_two_peers t(f);
+    const std::string b1_id(t.b1_app.self_id());
+    const std::string b2_id(t.b2_app.self_id());
+    const std::string user = t.user;
+    t.events.clear();
+    t.b1.reset();
+    BOOST_TEST(run_until(f, [&] { return t.a.peers().size() == 1; }));
+    run_until(f, [] { return false; }, 100ms);
+    const std::vector first{"peer leave " + b1_id + " " + user};
+    BOOST_TEST_ALL_EQ(t.events.begin(), t.events.end(), first.begin(), first.end());
+    BOOST_TEST_EQ(t.a.users().size(), 1U);
+    t.b2.reset();
+    BOOST_TEST(run_until(f, [&] { return t.events.size() == 3; }));
+    const std::vector all{
+        "peer leave " + b1_id + " " + user,
+        "peer leave " + b2_id + " " + user,
+        "user leave " + user + " " + b2_id,
     };
-    trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id));
-    const auto b = join(b_app, "withdraw");
-    webcpp::test::require(
-        BOOST_TEST(run_until(f, [&] { return a.room->active_peers().size() == 1; })));
-    const auto c = a.app->find(b_id);
-    webcpp::test::require(BOOST_TEST(c != nullptr));
-    f.net.inject(pcs.front(), trystero::protocol::presence_frame(
-                                  trystero::protocol::room_token(app_id, "withdraw"), false));
-    BOOST_TEST(run_until(f, [&] { return leaves == 1; }));
-    BOOST_TEST(a.room->active_peers().empty());
-    BOOST_TEST(c->live());
-    BOOST_TEST(a.app->find(b_id) == c);
-    a.room->abandon();
+    BOOST_TEST_ALL_EQ(t.events.begin(), t.events.end(), all.begin(), all.end());
+    BOOST_TEST(t.a.users().empty());
+    BOOST_TEST(t.a.peers().empty());
 }
 
-// A kick by the connection's last room ends the connection at once, rather than idling it: the
-// handshake times out, since every room frame to A is dropped.
-void a_kick_by_the_last_room_ends_the_connection() {
+// A peer of this room's own user is a peer and no other user, as 0.27.0 leaves its own user out
+// of `getUsers` and of `onUserJoin`.
+void a_peer_of_its_own_user_is_no_other_user() {
     fixture f{true};
-    const std::string b_id = "YYYYYYYYYYYYYYYYYYYY";
-    std::vector log;
-    const auto a = make_app_room(
-        f, "XXXXXXXXXXXXXXXXXXXX", "kick", [&](trystero::app_config& c, trystero::room_options&) {
-            c.log = [&log](std::string_view category, std::string_view text) {
-                log.push_back(std::string(category) + ": " + std::string(text));
-            };
-        });
-    std::vector pcs;
-    f.net.on_made = [&](std::size_t pc, std::span) {
-        pcs.push_back(pc);
-    };
-    f.net.filter = [&](std::size_t, std::size_t to, std::span frame) {
-        const bool room_frame_to_a = !pcs.empty() && to == pcs.front() && frame[0] == 1;
-        return room_frame_to_a ? trystero::test::memory_network::verdict::drop
-                               : trystero::test::memory_network::verdict::deliver;
-    };
-    trystero::app b_app(f.io.get_executor(), f.net, app_config(b_id));
-    const auto b = join(b_app, "kick");
-    const std::string kicked =
-        "webrtc: connection with " + b_id + " ended: its last room kicked the peer";
-    BOOST_TEST(run_until(f, [&] { return std::ranges::count(log, kicked) > 0; }, 20s));
-    a.room->abandon();
+    const auto identity = make_user_identity();
+    trystero::test::app a_app(f.io.get_executor(), f.net,
+                              app_config_of("ownUserAAAAAAAAAAAAA", identity));
+    auto a = join(a_app, "own");
+    trystero::test::app b_app(f.io.get_executor(), f.net,
+                              app_config_of("ownUserBBBBBBBBBBBBB", identity));
+    std::size_t user_events = 0;
+    a.on_user_join([&](const trystero::user_event&) { ++user_events; });
+    a.on_user_leave([&](const trystero::user_event&) { ++user_events; });
+    std::optional b(join(b_app, "own"));
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; })));
+    BOOST_TEST_EQ(a.peers().begin()->second.user_id, a_app.user_id());
+    BOOST_TEST(a.users().empty());
+    std::size_t replayed = 0;
+    a.on_user_join([&](const trystero::user_event&) { ++replayed; },
+                   {.once = false, .replay = true});
+    BOOST_TEST_EQ(replayed, 0U);
+    b.reset();
+    BOOST_TEST(run_until(f, [&] { return a.peers().empty(); }));
+    run_until(f, [] { return false; }, 100ms);
+    BOOST_TEST_EQ(user_events, 0U);
 }
 
-// A room left with no idle time still says so on the connection, before its departure ends it:
-// Trystero's idle close is always a later timer.
-void a_room_left_with_no_idle_time_sends_its_presence() {
+// A send to a target that is neither an active peer nor a user of one completes with
+// `not_connected`, alone or in a list; a broadcast to a room without peers succeeds.
+void send_to_an_absent_target_fails() {
     fixture f{true};
-    const auto a = make_app_room(f, "ZZZZZZZZZZZZZZZZZZZZ", "no-idle",
-                                 [](trystero::app_config& c, trystero::room_options&) {
-                                     c.idle_timeout = std::chrono::milliseconds::zero();
-                                 });
-    trystero::app b_app(f.io.get_executor(), f.net, app_config("zzzzzzzzzzzzzzzzzzzz"));
-    const auto b = join(b_app, "no-idle");
-    webcpp::test::require(BOOST_TEST(
-        run_until(f, [&] { return a.room->active_peers().size() == 1 && b.peers().size() == 1; })));
-    const auto absent = trystero::protocol::presence_frame(
-        trystero::protocol::room_token(app_id, "no-idle"), false);
-    std::size_t seen = 0;
-    f.net.filter = [&](std::size_t, std::size_t, std::span frame) {
-        if (std::ranges::equal(frame, absent)) {
-            ++seen;
-        }
-        return trystero::test::memory_network::verdict::deliver;
-    };
-    a.room->abandon();
-    advance(f, 1000ms);
-    BOOST_TEST_EQ(seen, 1U);
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("absentAAAAAAAAAAAAAA"));
+    auto a = join(a_app, "absent");
+    auto note = a.make_action("note");
+    std::vector sent;
+    const auto record = [&](boost::system::error_code ec) { sent.push_back(ec); };
+    note.async_send("anyone", record);
+    note.async_send("nobody", trystero::send_options{.targets = {"nobody"}, .metadata = {}},
+                    record);
+    BOOST_TEST(run_until(f, [&] { return sent.size() == 2; }));
+    if (sent.size() == 2) {
+        BOOST_TEST(!sent[0]);
+        BOOST_TEST(sent[1] == trystero::error::not_connected);
+    }
+
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("absentBBBBBBBBBBBBBB"));
+    auto b = join(b_app, "absent");
+    std::size_t heard = 0;
+    b.make_action("note").on_message(
+        [&](const std::string&, const trystero::message_info&) { ++heard; });
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; })));
+    sent.clear();
+    note.async_send("both",
+                    trystero::send_options{
+                        .targets = {trystero::peer_id(b_app.self_id()), "nobody"},
+                        .metadata = {},
+                    },
+                    record);
+    BOOST_TEST(run_until(f, [&] { return sent.size() == 1 && heard == 1; }));
+    if (!sent.empty()) {
+        BOOST_TEST(sent[0] == trystero::error::not_connected);
+    }
 }
 
-// The errors' values are fixed and never reused; their messages name what failed.
-void the_errors_have_their_values() {
-    BOOST_TEST_EQ(static_cast(trystero::error::already_joined), 14);
-    BOOST_TEST_EQ(static_cast(trystero::error::too_many_rooms), 15);
-    BOOST_TEST_EQ(make_error_code(trystero::error::already_joined).message(),
-                  "the app has already joined a room of that id");
-    BOOST_TEST_EQ(make_error_code(trystero::error::too_many_rooms).message(),
-                  "the app holds as many rooms as a peer accepts, 64");
-    BOOST_TEST_EQ(make_error_code(trystero::error::invalid_configuration).message(),
-                  "the configuration is unusable");
+/** How many subscriptions the two memory relays hold, each. */
+std::pair subscriptions(fixture& f) {
+    return {f.net.relay(relay_a).subscription_count(), f.net.relay(relay_b).subscription_count()};
 }
 
-}  // namespace
+// Offline closes the app's relay sockets and holds them closed: no reconnection is tried however
+// long it lasts, a room joined meanwhile opens none, and a peer online in that room is not met.
+// Online reconnects them at once: the room joined before subscribes again, the one joined
+// offline subscribes for the first time, and the two peers meet. Another app's room never moves.
+void offline_holds_and_online_reconnects() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("heldAAAAAAAAAAAAAAAA"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("heldBBBBBBBBBBBBBBBB"));
+    const auto first = join(a_app, "first");
+    webcpp::test::require(BOOST_TEST(run_until(
+        f, [&] { return subscriptions(f) == std::pair{1, 1}; })));
+    BOOST_TEST_EQ(f.net.websocket_connects, 2U);
 
-int main() {
+    BOOST_TEST(a_app.set_relay_connectivity(trystero::relay_connectivity::offline) ==
+               trystero::relay_connectivity::offline);
+    BOOST_TEST(a_app.relay_connectivity() == trystero::relay_connectivity::offline);
+    BOOST_TEST((subscriptions(f) == std::pair{0, 0}));
+    auto a = join(a_app, "lobby");
+    auto b = join(b_app, "lobby");
+    trystero::test::advance(f, 10min);
+    BOOST_TEST_EQ(f.net.websocket_connects, 4U);  // b's two, and none of a's
+    BOOST_TEST((subscriptions(f) == std::pair{1, 1}));
+    BOOST_TEST(a.peers().empty());
+    BOOST_TEST(b.peers().empty());
+
+    BOOST_TEST(a_app.set_relay_connectivity(trystero::relay_connectivity::online) ==
+               trystero::relay_connectivity::online);
+    BOOST_TEST(a_app.relay_connectivity() == trystero::relay_connectivity::online);
+    BOOST_TEST_EQ(f.net.websocket_connects, 8U);  // each room of a, on each relay, at once
+    BOOST_TEST(run_until(
+        f, [&] { return subscriptions(f) == std::pair{3, 3}; }));
+    BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; }, 1min));
+    BOOST_TEST(b_app.relay_connectivity() == trystero::relay_connectivity::automatic);
+}
+
+// Offline also holds a relay waiting to reconnect: the reconnection pending when the app goes
+// offline never fires, however long the app stays offline.
+void offline_holds_a_relay_waiting_to_reconnect() {
+    fixture f{true};
+    f.net.make_unreachable(relay_a);
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("backoffAAAAAAAAAAAAA"));
+    const auto a = join(a_app, "backoff");
+    // relay_b subscribed and relay_a's first attempt failed: its reconnection is pending.
+    webcpp::test::require(BOOST_TEST(run_until(
+        f, [&] { return subscriptions(f) == std::pair{0, 1}; })));
+    BOOST_TEST_EQ(f.net.websocket_connects, 2U);
+    a_app.set_relay_connectivity(trystero::relay_connectivity::offline);
+    trystero::test::advance(f, 10min);
+    BOOST_TEST_EQ(f.net.websocket_connects, 2U);
+    BOOST_TEST((subscriptions(f) == std::pair{0, 0}));
+}
+
+// Online reconnects a relay waiting in its backoff at once, and its delay bound is back at its
+// least, 3333 ms, as 0.27.0's `reconnectRelaySockets` clears `socketRetryPeriods`: the attempt
+// that fails right after waits within 3333 ms, not within the minute the backoff had reached.
+void online_reconnects_a_backoff_relay_at_once() {
+    fixture f{true};
+    f.net.make_unreachable(relay_a);
+    auto config = app_config("backoffAAAAAAAAAAAAA");
+    std::vector waits;
+    config.log = [&](std::string_view category, std::string_view text) {
+        const std::string_view lost = "could not reach wss://relay-a.test, next attempt within ";
+        if (category == "nostr" && text.starts_with(lost)) {
+            waits.emplace_back(text.substr(lost.size()));
+        }
+    };
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(config));
+    const auto a = join(a_app, "backoff");
+    // Ten minutes of failures take relay_a's bound to its most, 60 s.
+    trystero::test::advance(f, 10min);
+    webcpp::test::require(BOOST_TEST(!waits.empty()));
+    BOOST_TEST_EQ(waits.front(), "3333 ms");
+    BOOST_TEST_EQ(waits.back(), "60000 ms");
+    const auto connects = f.net.websocket_connects;
+    const auto failures = waits.size();
+    a_app.set_relay_connectivity(trystero::relay_connectivity::online);
+    BOOST_TEST_EQ(f.net.websocket_connects, connects + 1);  // relay_a alone, at once
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return waits.size() == failures + 1; })));
+    BOOST_TEST_EQ(waits.back(), "3333 ms");
+    trystero::test::advance(f, 3333ms);
+    BOOST_TEST_EQ(f.net.websocket_connects, connects + 2);
+    BOOST_TEST((subscriptions(f) == std::pair{0, 1}));
+}
+
+// Online while online leaves the connected relays alone: no socket is closed or opened, and their
+// subscriptions stay.
+void online_while_online_leaves_connected_relays_alone() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("steadyAAAAAAAAAAAAAA"));
+    const auto a = join(a_app, "steady");
+    webcpp::test::require(BOOST_TEST(run_until(
+        f, [&] { return subscriptions(f) == std::pair{1, 1}; })));
+    BOOST_TEST_EQ(f.net.websocket_connects, 2U);
+    a_app.set_relay_connectivity(trystero::relay_connectivity::online);
+    a_app.set_relay_connectivity(trystero::relay_connectivity::online);
+    trystero::test::advance(f, 1min);
+    BOOST_TEST_EQ(f.net.websocket_connects, 2U);
+    BOOST_TEST((subscriptions(f) == std::pair{1, 1}));
+}
+
+// Natively the app has no page to follow, as the memory network has none unless asked: it is
+// automatic from the start and its relays connect, automatic again reconnects nothing, and
+// automatic after offline reconnects the relays, as 0.27.0's `'auto'` does after a program's
+// `'offline'`.
+void automatic_is_online_natively() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("autoAAAAAAAAAAAAAAAA"));
+    BOOST_TEST(a_app.relay_connectivity() == trystero::relay_connectivity::automatic);
+    const auto a = join(a_app, "auto");
+    webcpp::test::require(BOOST_TEST(run_until(
+        f, [&] { return subscriptions(f) == std::pair{1, 1}; })));
+    BOOST_TEST(a_app.set_relay_connectivity(trystero::relay_connectivity::automatic) ==
+               trystero::relay_connectivity::automatic);
+    trystero::test::advance(f, 1min);
+    BOOST_TEST_EQ(f.net.websocket_connects, 2U);
+    a_app.set_relay_connectivity(trystero::relay_connectivity::offline);
+    trystero::test::advance(f, 1min);
+    BOOST_TEST((subscriptions(f) == std::pair{0, 0}));
+    BOOST_TEST(a_app.set_relay_connectivity(trystero::relay_connectivity::automatic) ==
+               trystero::relay_connectivity::automatic);
+    BOOST_TEST(run_until(
+        f, [&] { return subscriptions(f) == std::pair{1, 1}; }));
+    BOOST_TEST_EQ(f.net.websocket_connects, 4U);
+}
+
+// Where the page has `online` and `offline` events, an automatic app follows them: its relays
+// close after `offline` and stay closed, and reconnect after `online`.
+void automatic_follows_the_pages_events() {
+    fixture f{true};
+    f.net.page_events = true;
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("pageAAAAAAAAAAAAAAAA"));
+    const auto a = join(a_app, "page");
+    webcpp::test::require(BOOST_TEST(run_until(
+        f, [&] { return subscriptions(f) == std::pair{1, 1}; })));
+    f.net.page_connectivity(false);
+    BOOST_TEST(run_until(
+        f, [&] { return subscriptions(f) == std::pair{0, 0}; }));
+    trystero::test::advance(f, 10min);
+    BOOST_TEST_EQ(f.net.websocket_connects, 2U);
+    BOOST_TEST(a_app.relay_connectivity() == trystero::relay_connectivity::automatic);
+    f.net.page_connectivity(true);
+    BOOST_TEST(run_until(
+        f, [&] { return subscriptions(f) == std::pair{1, 1}; }));
+    BOOST_TEST_EQ(f.net.websocket_connects, 4U);
+}
+
+// `self()` names this peer, its user, the room and the room it was joined as, synchronously.
+void self_names_the_room() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("selfAAAAAAAAAAAAAAAA"));
+    const auto a = join(a_app, "kitchen");
+    const trystero::self_info self = a.self();
+    BOOST_TEST_EQ(self.peer_id, a_app.self_id());
+    BOOST_TEST_EQ(self.user_id, a_app.user_id());
+    BOOST_TEST(self.persistence == trystero::identity_persistence::ephemeral);
+    BOOST_TEST_EQ(self.room_id, "kitchen");
+    BOOST_TEST_EQ(self.base_room_id, "kitchen");
+    BOOST_TEST(!self.is_admin);
+    BOOST_TEST(self.roles.empty());
+}
+
+// An app's peer id derives from its endpoint key and its user id from its user key, as 0.27.0
+// derives them: two apps of fixed endpoint keys have the ids of those keys, and users of their
+// own.
+void an_apps_ids_derive_from_its_keys() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("derive-a"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("derive-b"));
+    BOOST_TEST_EQ(a_app.self_id(), trystero::test::peer_id_of("derive-a"));
+    BOOST_TEST_EQ(b_app.self_id(), trystero::test::peer_id_of("derive-b"));
+    for (const auto* app : {&a_app, &b_app}) {
+        BOOST_TEST_EQ(app->self_id().size(), trystero::protocol::peer_id_size);
+        BOOST_TEST_EQ(app->user_id().size(), trystero::protocol::user_id_size);
+        BOOST_TEST_EQ(app->user_id().find_first_not_of(trystero::protocol::base62_alphabet),
+                      std::string_view::npos);
+        // The user key is another key than the endpoint's.
+        BOOST_TEST_NE(app->user_id().substr(0, trystero::protocol::peer_id_size), app->self_id());
+    }
+    BOOST_TEST_NE(a_app.user_id(), b_app.user_id());
+    // An app of the same endpoint key has the same peer id, and a user of its own.
+    const trystero::test::app again(f.io.get_executor(), f.net, app_config("derive-a"));
+    BOOST_TEST_EQ(again.self_id(), a_app.self_id());
+    BOOST_TEST_NE(again.user_id(), a_app.user_id());
+    // An app whose key is drawn has a peer id of its own.
+    const trystero::test::app drawn(f.io.get_executor(), f.net, app_config(""));
+    BOOST_TEST_EQ(drawn.self_id().size(), trystero::protocol::peer_id_size);
+    BOOST_TEST_NE(drawn.self_id(), a_app.self_id());
+}
+
+// Two apps given one user identity are two endpoints of one user: their peer ids differ, their
+// user ids are the identity's, as two pages of one imported identity are in 0.27.0.
+void two_apps_of_one_imported_identity_share_a_user_id() {
+    fixture f{true};
+    const auto identity = trystero::create_user_identity();
+    webcpp::test::require(BOOST_TEST(identity.has_value()));
+    auto a_config = app_config("shared-a");
+    a_config.identity = *identity;
+    auto b_config = app_config("shared-b");
+    b_config.identity = *identity;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    trystero::test::app b_app(f.io.get_executor(), f.net, std::move(b_config));
+    BOOST_TEST_NE(a_app.self_id(), b_app.self_id());
+    BOOST_TEST_EQ(a_app.user_id(), identity->user_id());
+    BOOST_TEST_EQ(b_app.user_id(), identity->user_id());
+    const auto a = join(a_app, "shared");
+    const auto b = join(b_app, "shared");
+    BOOST_TEST_EQ(a.self().user_id, b.self().user_id);
+    BOOST_TEST_NE(a.self().peer_id, b.self().peer_id);
+    // An identity imported from the text of another is that user.
+    auto c_config = app_config("shared-c");
+    const auto imported = trystero::import_user_identity(trystero::export_user_identity(*identity));
+    webcpp::test::require(BOOST_TEST(imported.has_value()));
+    c_config.identity = *imported;
+    const trystero::test::app c_app(f.io.get_executor(), f.net, std::move(c_config));
+    BOOST_TEST_EQ(c_app.user_id(), identity->user_id());
+}
+
+// `self()` reports where the user identity comes from: made with the app, `ephemeral`; given by
+// the program, `imported`, 0.27.0's 'none' and 'custom'.
+void self_reports_the_identity() {
+    fixture f{true};
+    trystero::test::app plain(f.io.get_executor(), f.net, app_config("identity-plain"));
+    const auto made = join(plain, "identity");
+    BOOST_TEST(made.self().persistence == trystero::identity_persistence::ephemeral);
+    BOOST_TEST_EQ(made.self().user_id, plain.user_id());
+    BOOST_TEST_EQ(made.self().peer_id, plain.self_id());
+
+    const auto identity = trystero::create_user_identity();
+    webcpp::test::require(BOOST_TEST(identity.has_value()));
+    auto config = app_config("identity-given");
+    config.identity = *identity;
+    trystero::test::app given(f.io.get_executor(), f.net, std::move(config));
+    const auto imported = join(given, "identity");
+    BOOST_TEST(imported.self().persistence == trystero::identity_persistence::imported);
+    BOOST_TEST_EQ(imported.self().user_id, identity->user_id());
+    BOOST_TEST_EQ(imported.self().peer_id, given.self_id());
+}
+
+// An endpoint key that cannot be made leaves the app without a peer id, and each room it joins
+// reports `identity_failed` once the join has returned, with 0.27.0's message, then ends without
+// a word to a relay, as 0.27.0's failSetup.
+void an_endpoint_that_cannot_be_made_reports_identity_failed() {
+    fixture f{true};
+    const std::array zero{};
+    auto a_app = trystero::detail::app_access::make(f.io.get_executor(), f.net,
+                                                    config_of(app_config("unused")), zero);
+    BOOST_TEST(a_app.self_id().empty());
+    auto a = join(a_app, "failed");
+
+    struct reported {
+        boost::system::error_code code;
+        std::string message;
+        std::string room_id;
+        std::string peer_id;
+    };
+
+    std::vector errors;
+    a.on_error([&](const trystero::room_error& e) {
+        errors.push_back({
+            .code = e.code,
+            .message = std::string(e.message),
+            .room_id = std::string(e.room_id),
+            .peer_id = std::string(e.peer_id),
+        });
+    });
+    BOOST_TEST(errors.empty());  // posted: the join has returned before it is reported
+    const auto& impl = trystero::detail::app_access::impl(a_app);
+    BOOST_TEST(run_until(f, [&] { return impl.counted_rooms() == 0; }));
+    if (BOOST_TEST_EQ(errors.size(), 1U)) {
+        BOOST_TEST(errors[0].code == trystero::error::identity_failed);
+        BOOST_TEST_EQ(trystero::room_error_code_name(errors[0].code), "identity-failed");
+        BOOST_TEST_EQ(errors[0].message, "endpoint identity resolution failed");
+        BOOST_TEST_EQ(errors[0].room_id, "failed");
+        BOOST_TEST(errors[0].peer_id.empty());
+    }
+    BOOST_TEST_EQ(f.net.websocket_connects, 0U);
+    // The room ended: a leave completes at once, and the room can be joined again, failing again.
+    bool left = false;
+    a.async_leave([&](boost::system::error_code ec) { left = !ec; });
+    BOOST_TEST(run_until(f, [&] { return left; }));
+    auto again = join(a_app, "failed");
+    std::size_t again_errors = 0;
+    again.on_error([&](const trystero::room_error& e) {
+        again_errors += e.code == trystero::error::identity_failed ? 1 : 0;
+    });
+    BOOST_TEST(run_until(f, [&] { return again_errors == 1 && impl.counted_rooms() == 0; }));
+    BOOST_TEST_EQ(f.net.websocket_connects, 0U);
+}
+
+// A user key that cannot be made keeps the app's peer id and leaves it without a user id; each
+// room it joins reports `identity_failed` with 0.27.0's message for the user identity, then ends
+// without a word to a relay, as 0.27.0's failSetup.
+void a_user_key_that_cannot_be_made_reports_identity_failed() {
+    fixture f{true};
+    const std::array zero{};
+    const auto scalar = endpoint_scalar("user-failed");
+    auto a_app = trystero::detail::app_access::make(
+        f.io.get_executor(), f.net, config_of(app_config("user-failed")), scalar, zero);
+    BOOST_TEST_EQ(a_app.self_id(), peer_id_of("user-failed"));
+    BOOST_TEST(a_app.user_id().empty());
+    auto a = join(a_app, "failed");
+
+    struct reported {
+        boost::system::error_code code;
+        std::string message;
+        std::string room_id;
+        std::string peer_id;
+    };
+
+    std::vector errors;
+    a.on_error([&](const trystero::room_error& e) {
+        errors.push_back({
+            .code = e.code,
+            .message = std::string(e.message),
+            .room_id = std::string(e.room_id),
+            .peer_id = std::string(e.peer_id),
+        });
+    });
+    BOOST_TEST(errors.empty());  // posted: the join has returned before it is reported
+    const auto& impl = trystero::detail::app_access::impl(a_app);
+    BOOST_TEST(run_until(f, [&] { return impl.counted_rooms() == 0; }));
+    if (BOOST_TEST_EQ(errors.size(), 1U)) {
+        BOOST_TEST(errors[0].code == trystero::error::identity_failed);
+        BOOST_TEST_EQ(errors[0].message, "identity resolution failed");
+        BOOST_TEST_EQ(errors[0].room_id, "failed");
+        BOOST_TEST(errors[0].peer_id.empty());
+    }
+    BOOST_TEST_EQ(f.net.websocket_connects, 0U);
+
+    // A user scalar fixes the user id as the endpoint scalar fixes the peer id; a given identity
+    // takes its place.
+    const auto user_scalar = endpoint_scalar("user-fixed");
+    const auto fixed = trystero::detail::app_access::make(
+        f.io.get_executor(), f.net, config_of(app_config("user-fixed")), scalar, user_scalar);
+    const auto expected =
+        trystero::detail::user_identity_access::make(user_scalar, std::pmr::get_default_resource());
+    webcpp::test::require(BOOST_TEST(expected.has_value()));
+    BOOST_TEST_EQ(fixed.user_id(), expected->user_id());
+    BOOST_TEST_NE(fixed.user_id(), fixed.self_id());
+    auto config = app_config("user-given");
+    const auto given_identity = trystero::create_user_identity();
+    webcpp::test::require(BOOST_TEST(given_identity.has_value()));
+    config.identity = *given_identity;
+    const auto given = trystero::detail::app_access::make(f.io.get_executor(), f.net,
+                                                          std::move(config), scalar, zero);
+    BOOST_TEST_EQ(given.user_id(), given_identity->user_id());
+}
+
+/** Refusals of a request with long reasons. */
+class reasons final : public boost::system::error_category {
+public:
+    const char* name() const noexcept override { return "reasons"; }
+
+    std::string message(int ev) const override {
+        // 511 UTF-16 code units, then a character of two of them, which the cut splits.
+        return ev == 1 ? std::string(511, 'x') + "\xF0\x9F\x98\x80tail" : std::string(600, 'y');
+    }
+};
+
+// A request whose listener is removed after it arrived, before its post runs, is refused with "no
+// active request handler"; one that the gate refuses with "payload rejected by receiver"; a
+// listener's reason is cut at 512 UTF-16 code units, as 0.27.0 cuts it, a pair cut in two leaving
+// its high surrogate, which the requester reads. The requester's request completes with
+// `request_rejected`, and the reason is logged.
+void a_request_is_refused_by_a_gone_listener_or_the_gate() {
+    fixture f{true};
+    auto config = app_config("refusedAAAAAAAAAAAAA");
+    std::vector reasons_logged;
+    config.log = [&](std::string_view category, std::string_view text) {
+        if (category == "action" && text.find(" refused by ") != std::string_view::npos) {
+            reasons_logged.emplace_back(text.substr(text.find(": ") + 2));
+        }
+    };
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(config));
+    auto a = join(a_app, "refused");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("refusedBBBBBBBBBBBBB"));
+    auto b = join(b_app, "refused");
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })));
+    const auto echo = [](std::string q, const trystero::message_info&) { return q; };
+
+    // The progress of 1 is posted before the request: its listener removes the request's.
+    auto gone = b.make_request_action("gone");
+    auto answering = gone.on_request(echo);
+    webcpp::test::require(BOOST_TEST(answering.has_value()));
+    gone.on_receive_progress([&](double share, const trystero::progress_info&) {
+        if (share == 1.0) {
+            answering->unsubscribe();
+        }
+    });
+    auto gated = b.make_request_action("gated");
+    BOOST_TEST(gated.on_request(echo).has_value());
+    BOOST_TEST(gated.on_receive([](const trystero::receive_info&) { return false; }).has_value());
+    static const reasons category{};
+    auto cut = b.make_request_action("cut");
+    BOOST_TEST(
+        cut.on_request([](const std::string& q,
+                          const trystero::message_info&) -> boost::system::result {
+               return boost::system::error_code(q == "pair" ? 1 : 2, category);
+           })
+            .has_value());
+
+    std::vector results;
+    const auto ask = [&](std::string_view name, std::string q) {
+        a.make_request_action(name).async_request(
+            std::move(q), trystero::request_options{.target = trystero::peer_id(b.self_id())},
+            [&](boost::system::error_code ec, const std::string&) { results.push_back(ec); });
+        return run_until(f, [&, n = results.size() + 1] { return results.size() == n; });
+    };
+    BOOST_TEST(ask("gone", "q"));
+    BOOST_TEST(ask("gated", "q"));
+    BOOST_TEST(ask("cut", "pair"));
+    BOOST_TEST(ask("cut", "ascii"));
+    for (const auto& ec : results) {
+        BOOST_TEST(ec == trystero::error::request_rejected);
+    }
+    if (BOOST_TEST_EQ(reasons_logged.size(), 4U)) {
+        BOOST_TEST_EQ(reasons_logged[0], "no active request handler");
+        BOOST_TEST_EQ(reasons_logged[1], "payload rejected by receiver");
+        // The high surrogate left alone is read as the replacement character.
+        BOOST_TEST_EQ(reasons_logged[2], std::string(511, 'x') + "\xEF\xBF\xBD");
+        BOOST_TEST_EQ(reasons_logged[3], std::string(512, 'y'));
+    }
+}
+
+// A request fails with `peer_disconnected` when the peer asked leaves first, and with `room_left`
+// when the requester's room is left first. The room is left at once, by its destruction: during an
+// `async_leave`'s farewell the peer, told `\@_leave`, closes the room's connection to it, and a
+// request still waiting then fails with `peer_disconnected`, as 0.27.0's exitPeer fails it.
+void a_request_fails_when_its_peer_or_its_room_goes() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("goesAAAAAAAAAAAAAAAA"));
+    auto a1 = join(a_app, "goes-peer");
+    std::optional a2(join(a_app, "goes-room"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("goesBBBBBBBBBBBBBBBB"));
+    std::optional b1(join(b_app, "goes-peer"));
+    auto b2 = join(b_app, "goes-room");
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] {
+        return a1.peers().size() == 1 && a2->peers().size() == 1 && b2.peers().size() == 1;
+    })));
+    // B makes the actions but answers nothing: the requests wait.
+    const auto slow1 = b1->make_request_action("slow");
+    const auto slow2 = b2.make_request_action("slow");
+    std::optional peer_gone;
+    a1.make_request_action("slow").async_request(
+        "q", trystero::request_options{.target = trystero::peer_id(b2.self_id())},
+        [&](boost::system::error_code ec, const std::string&) { peer_gone = ec; });
+    std::optional room_gone;
+    a2->make_request_action("slow").async_request(
+        "q", trystero::request_options{.target = trystero::peer_id(b2.self_id())},
+        [&](boost::system::error_code ec, const std::string&) { room_gone = ec; });
+    run_until(f, [] { return false; }, 100ms);
+    BOOST_TEST(!peer_gone && !room_gone);
+    b1.reset();
+    BOOST_TEST(run_until(f, [&] { return peer_gone.has_value(); }));
+    BOOST_TEST(*peer_gone == trystero::error::peer_disconnected);
+    a2.reset();
+    BOOST_TEST(run_until(f, [&] { return room_gone.has_value(); }));
+    BOOST_TEST(*room_gone == trystero::error::room_left);
+}
+
+// A name keeps the kind of action it was made first, as 0.27.0 refuses to redefine it ("action
+// type cannot be redefined", which it throws): a handle of the other kind fails each operation with
+// `action_redefined` and adds no listener; another of the first kind is the same action.
+void an_action_name_keeps_its_first_kind() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("kindAAAAAAAAAAAAAAAA"));
+    auto a = join(a_app, "kinds");
+    std::vector failed;
+
+    auto chat = a.make_action("chat");
+    BOOST_TEST(chat.on_message([](const std::string&, const trystero::message_info&) {}).active());
+    auto ask_chat = a.make_request_action("chat");
+    const auto request_listener =
+        ask_chat.on_request([](std::string q, const trystero::message_info&) { return q; });
+    BOOST_TEST(request_listener.has_error() &&
+               request_listener.error() == trystero::error::action_redefined);
+    const auto request_gate =
+        ask_chat.on_receive([](const trystero::receive_info&) { return true; });
+    BOOST_TEST(request_gate.has_error() &&
+               request_gate.error() == trystero::error::action_redefined);
+    BOOST_TEST(
+        !ask_chat.on_receive_progress([](double, const trystero::progress_info&) {}).active());
+    ask_chat.async_request("q", trystero::request_options{.target = "anyone"},
+                           [&](boost::system::error_code ec, const std::string& r) {
+                               failed.push_back(ec);
+                               BOOST_TEST(r.empty());
+                           });
+
+    auto ask = a.make_request_action("ask");
+    auto say_ask = a.make_action("ask");
+    BOOST_TEST(
+        !say_ask.on_message([](const std::string&, const trystero::message_info&) {}).active());
+    BOOST_TEST(
+        !say_ask.on_receive_progress([](double, const trystero::progress_info&) {}).active());
+    const auto message_gate =
+        say_ask.on_receive([](const trystero::receive_info&) { return true; });
+    BOOST_TEST(message_gate.has_error() &&
+               message_gate.error() == trystero::error::action_redefined);
+    say_ask.async_send("hello", [&](boost::system::error_code ec) { failed.push_back(ec); });
+    say_ask.async_receive(
+        [&](boost::system::error_code ec, const std::string& v, const trystero::message_info&) {
+            failed.push_back(ec);
+            BOOST_TEST(v.empty());
+        });
+    BOOST_TEST(run_until(f, [&] { return failed.size() == 3; }));
+    for (const auto& ec : failed) {
+        BOOST_TEST(ec == trystero::error::action_redefined);
+    }
+    // The first kind stays whole: another handle of it is the same action.
+    BOOST_TEST(a.make_request_action("ask")
+                   .on_request([](std::string q, const trystero::message_info&) { return q; })
+                   .has_value());
+    BOOST_TEST(ask.on_request([](std::string q, const trystero::message_info&) { return q; })
+                   .has_error());  // already_subscribed, through the other handle
+}
+
+// The errors' values are fixed and never reused; their messages name what failed.
+/** A room error, its views copied, and when it was reported. */
+struct reported_error {
+    boost::system::error_code code;
+    std::string message;
+    std::string app_id;
+    std::string room_id;
+    std::string peer_id;
+    std::optional stage;
+    bool turn_configured = false;
+    std::string reason;
+    std::chrono::steady_clock::time_point at;
+};
+
+/** A listener that records every report of `code` into `to`, with the fixture's time. */
+auto record_errors(fixture& f, std::vector& to, trystero::error code) {
+    return [&f, &to, code](const trystero::room_error& e) {
+        if (e.code != code) {
+            return;
+        }
+        to.push_back({
+            .code = e.code,
+            .message = std::string(e.message),
+            .app_id = std::string(e.app_id),
+            .room_id = std::string(e.room_id),
+            .peer_id = std::string(e.peer_id),
+            .stage = e.stage,
+            .turn_configured = e.turn_configured,
+            .reason = std::string(e.reason),
+            .at = f.net.steady_now(),
+        });
+    };
+}
+
+// Two apps whose passwords differ, on the virtual clock: A, the lower id, offers, and B cannot open
+// its offers. B reports decrypt_failed once, with A's id, the stage and 0.27.0's message, though A
+// sends its offer again and again within the minute; once the minute has passed, A's next offer
+// is reported again. A, which receives nothing sealed from B, reports nothing, and neither joins.
+void decrypt_failed_is_reported_once_a_minute() {
+    fixture f{true};
+    const auto labels = ordered_labels(2, "private");  // the apps, by ascending peer id
+    const std::string a_id = peer_id_of(labels[0]);
+    const std::string b_id = peer_id_of(labels[1]);
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config(labels[0], "s3cret"));
+    auto a = join(a_app, "private");
+    std::vector a_reports;
+    a.on_error([&](const trystero::room_error& e) {
+        a_reports.push_back({});
+        a_reports.back().code = e.code;
+    });
+    flooder watcher(f, "private");
+    std::vector offers;
+    watcher.on_text = [&](std::string_view text) {
+        const auto s = relayed_signal(text);
+        if (s && s->peer == a_id && !s->offer.empty()) {
+            offers.push_back(f.net.steady_now());
+        }
+    };
+    watcher.watch(trystero::protocol::peer_topic(app_id, "private", b_id));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(labels[1], "guess"));
+    auto b = join(b_app, "private");
+    std::vector reports;
+    b.on_error(record_errors(f, reports, trystero::error::decrypt_failed));
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return !reports.empty(); }, 30s)));
+    const auto& first = reports.front();
+    BOOST_TEST_EQ(trystero::room_error_code_name(first.code), "decrypt-failed");
+    BOOST_TEST_EQ(first.message,
+                  "failed to decrypt offer (incorrect password or corrupted signal)");
+    BOOST_TEST_EQ(first.app_id, app_id);
+    BOOST_TEST_EQ(first.room_id, "private");
+    BOOST_TEST_EQ(first.peer_id, a_id);
+    BOOST_TEST(first.stage == trystero::signal_stage::offer);
+    const auto reported = first.at;
+
+    // A minute but a millisecond after the report, A has sent its offer again, and B reported none
+    // of them.
+    trystero::test::advance(f, std::chrono::duration_cast(
+                                   reported + 59'999ms - f.net.steady_now()));
+    BOOST_TEST_EQ(reports.size(), 1U);
+    BOOST_TEST_GE(std::ranges::count_if(offers, [&](auto t) { return t > reported; }), 1);
+    BOOST_TEST(run_until(f, [&] { return reports.size() == 2; }, 3min));
+    if (reports.size() == 2) {
+        BOOST_TEST(reports[1].at - reported >= 60s);
+        BOOST_TEST_EQ(reports[1].peer_id, a_id);
+        BOOST_TEST(reports[1].stage == trystero::signal_stage::offer);
+    }
+    BOOST_TEST(a_reports.empty());
+    BOOST_TEST(a.peers().empty());
+    BOOST_TEST(b.peers().empty());
+}
+
+// Offers that do not open, from fresh ids: each id is reported once, however often it sends, and
+// the room remembers the last 512 ids it reported, as 0.27.0's cache does: past them, the first
+// is forgotten and reported again.
+void signals_that_do_not_open_are_reported_once_per_peer_and_stage() {
+    constexpr std::size_t remembered = 512;
+    fixture f{true};
+    const auto a_label = label_beside("1", false);  // above the garbage's ids, which offer
+    const std::string a_id = peer_id_of(a_label);
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config(a_label));
+    auto a = join(a_app, "reports");
+    std::vector reports;
+    a.on_error(record_errors(f, reports, trystero::error::decrypt_failed));
+    flooder attacker(f, "reports");
+    const auto a_topic = trystero::protocol::peer_topic(app_id, "reports", a_id);
+    const auto offer = [&](std::size_t i) {
+        const auto since_epoch = f.net.steady_now().time_since_epoch();
+        attacker.publish(a_topic,
+                         {
+                             .peer_id = signal_id("0garbage", i),
+                             .offer_id = "o",
+                             .offer = "not a sealed offer",
+                         },
+                         std::to_string(i) + "-" + std::to_string(since_epoch.count()));
+    };
+    for (std::size_t i = 0; i < 2 * remembered; ++i) {
+        offer(i % remembered);
+        if (i % 32 == 31) {
+            trystero::test::advance(f, 100ms);
+        }
+    }
+    BOOST_TEST(run_until(f, [&] { return reports.size() >= remembered; }));
+    trystero::test::advance(f, 1s);
+    BOOST_TEST_EQ(reports.size(), remembered);
+    for (std::size_t i = 0; i < std::min(reports.size(), remembered); ++i) {
+        BOOST_TEST_EQ(reports[i].peer_id, signal_id("0garbage", i));
+        BOOST_TEST(reports[i].stage == trystero::signal_stage::offer);
+    }
+    // An id seen again within the minute becomes the most recent: offered alone now, the first is
+    // not reported, and the second is the least recent.
+    offer(0);
+    trystero::test::advance(f, 100ms);
+    BOOST_TEST_EQ(reports.size(), remembered);
+    // One more id makes the room forget the second, which it then reports again within the minute,
+    // and not the first, which the room would forget were the ids kept in the order they came.
+    offer(remembered);
+    BOOST_TEST(run_until(f, [&] { return reports.size() == remembered + 1; }));
+    offer(0);
+    offer(1);
+    BOOST_TEST(run_until(f, [&] { return reports.size() == remembered + 2; }));
+    trystero::test::advance(f, 1s);
+    BOOST_TEST_EQ(reports.size(), remembered + 2);
+    if (reports.size() == remembered + 2) {
+        BOOST_TEST_EQ(reports[remembered].peer_id, signal_id("0garbage", remembered));
+        BOOST_TEST_EQ(reports.back().peer_id, signal_id("0garbage", 1));
+    }
+}
+
+// A room whose relays are all unreachable reports relay_failed once, with no peer, however often it
+// tries them again; a room that reaches one of its relays reports nothing.
+void relay_failed_when_every_relay_fails() {
+    {
+        fixture f{true};
+        f.net.make_unreachable(relay_a);
+        f.net.make_unreachable(relay_b);
+        trystero::test::app a_app(f.io.get_executor(), f.net, app_config("relaysAAAAAAAAAAAAAA"));
+        auto a = join(a_app, "unreachable");
+        std::vector reports;
+        a.on_error(record_errors(f, reports, trystero::error::relay_failed));
+        webcpp::test::require(BOOST_TEST(run_until(f, [&] { return !reports.empty(); })));
+        BOOST_TEST_EQ(trystero::room_error_code_name(reports[0].code), "relay-failed");
+        BOOST_TEST_EQ(reports[0].message, "all signaling relays failed");
+        BOOST_TEST_EQ(reports[0].app_id, app_id);
+        BOOST_TEST_EQ(reports[0].room_id, "unreachable");
+        BOOST_TEST(reports[0].peer_id.empty());
+        BOOST_TEST(!reports[0].stage.has_value());
+        trystero::test::advance(f, 3min);
+        BOOST_TEST_EQ(reports.size(), 1U);
+    }
+    {
+        fixture f{true};
+        f.net.make_unreachable(relay_a);
+        trystero::test::app a_app(f.io.get_executor(), f.net, app_config("relaysAAAAAAAAAAAAAA"));
+        auto a = join(a_app, "half");
+        std::size_t reports = 0;
+        a.on_error([&](const trystero::room_error&) { ++reports; });
+        trystero::test::advance(f, 3min);
+        BOOST_TEST_EQ(reports, 0U);
+    }
+}
+
+// Two peers whose data channels never open, on the virtual clock: once the offer is answered,
+// each side reports peer_connect_failed for the other when its connection expires, with
+// whether a TURN server was configured, and 0.27.0's message.
+void peer_connect_failed_says_whether_turn_was_configured() {
+    for (const bool turn : {false, true}) {
+        fixture f{true};
+        f.net.defer_opens = true;
+        const std::string a_id = peer_id_of("connect-a");
+        const std::string b_id = peer_id_of("connect-b");
+        const auto config = [&](std::string_view label) {
+            auto c = app_config(label);
+            if (turn) {
+                c.ice_servers.push_back({
+                    .urls =
+                        {
+                            std::pmr::string("stun:stun.example:3478"),
+                            std::pmr::string("TURNS:turn.example:5349"),
+                        },
+                    .username = std::pmr::string("user"),
+                    .credential = std::pmr::string("secret"),
+                });
+            }
+            return c;
+        };
+        trystero::test::app a_app(f.io.get_executor(), f.net, config("connect-a"));
+        auto a = join(a_app, "connect");
+        trystero::test::app b_app(f.io.get_executor(), f.net, config("connect-b"));
+        auto b = join(b_app, "connect");
+        std::vector a_reports;
+        std::vector b_reports;
+        a.on_error(record_errors(f, a_reports, trystero::error::peer_connect_failed));
+        b.on_error(record_errors(f, b_reports, trystero::error::peer_connect_failed));
+        webcpp::test::require(BOOST_TEST(
+            run_until(f, [&] { return !a_reports.empty() && !b_reports.empty(); }, 2min)));
+        const std::string hint = turn ? "verify TURN server URLs and credentials"
+                                      : "configure TURN via app_config::ice_servers";
+        for (const auto& [reports, peer] :
+             {std::pair{&a_reports, b_id}, std::pair{&b_reports, a_id}}) {
+            const auto& e = reports->front();
+            BOOST_TEST_EQ(trystero::room_error_code_name(e.code), "peer-connect-failed");
+            BOOST_TEST_EQ(e.peer_id, peer);
+            BOOST_TEST_EQ(e.turn_configured, turn);
+            std::string expected = "could not connect to peer ";
+            expected += peer;
+            expected += " after exchanging SDP; ";
+            expected += hint;
+            BOOST_TEST_EQ(e.message, expected);
+            BOOST_TEST_EQ(e.room_id, "connect");
+        }
+        BOOST_TEST(a.peers().empty());
+    }
+}
+
+/** The name of an action frame's action, or empty for a chunk, a control frame or no frame. */
+std::string action_name(std::span frame) {
+    const auto decoded = trystero::protocol::decode_action(frame);
+    const auto* p =
+        decoded.frame ? std::get_if(&*decoded.frame) : nullptr;
+    return p != nullptr ? std::string(p->name) : std::string();
+}
+
+/** Whether the memory network's connection `pc` has its channel in `memory`: in a case that gives
+ * one app a resource of its own, whether `pc` is that app's end. */
+bool end_in(fixture& f, std::size_t pc, const std::pmr::memory_resource* memory) {
+    const auto connection = f.net.find(pc);
+    const auto channel = connection ? connection->channel() : nullptr;
+    return channel && channel->memory() == memory;
+}
+
+/** The ready frame of the fixture's `handshake_frames` entry `ready`, which 0.27.0 writes:
+ * `\@_hsready` with an empty text (crypto_layer's `handshake_frames_match` reads it from the
+ * fixture). */
+std::vector recorded_ready_frame() {
+    return bytes_of_hex("0300405f6873726561647900000000000000000000000000000000000000000000000000");
+}
+
+// A handshake that never completes fails after 0.27.0's 10 s: A's end of the connection opens and
+// B's never does, so that only A runs a handshake, its frames waiting at B's end; A reports
+// handshake_failed with 0.27.0's reason and B's id when its timer expires, and lets B go. B starts
+// no handshake and has no timer, so which side expires first is not a question. Neither reports a
+// join. All of it on the virtual clock.
+void a_handshake_that_never_completes_fails_after_10_s() {
+    counting_resource a_memory;  // first: A's connection ends are made in it, which names them
+    fixture f{true};
+    f.net.defer_opens = true;
+    const auto labels = ordered_labels(2, "slow");  // the apps, by ascending peer id
+    const std::string b_id = peer_id_of(labels[1]);
+    auto a_config = app_config(labels[0]);
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    auto a = join(a_app, "slow");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(labels[1]));
+    auto b = join(b_app, "slow");
+    std::vector a_reports;
+    a.on_error(record_errors(f, a_reports, trystero::error::handshake_failed));
+    std::vector b_reports;
+    b.on_error(record_errors(f, b_reports, trystero::error::handshake_failed));
+    std::size_t joins = 0;
+    a.on_peer_join([&](const trystero::peer_event&) { ++joins; });
+    b.on_peer_join([&](const trystero::peer_event&) { ++joins; });
+    // The first pair negotiated, both ends made and neither open.
+    std::optional a_pc;
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] {
+        for (std::size_t id = 0; id < f.net.made_connections && !a_pc; ++id) {
+            if (end_in(f, id, &a_memory) && f.net.peer_of(id) != id) {
+                a_pc = id;
+            }
+        }
+        return a_pc.has_value();
+    })));
+    f.net.open(*a_pc);  // B's end stays closed
+    trystero::test::advance(f, 9'500ms);
+    BOOST_TEST(a_reports.empty());  // 9.5 s after A's handshake started
+    trystero::test::advance(f, 1000ms);
+    if (BOOST_TEST_EQ(a_reports.size(), 1U)) {
+        const auto& e = a_reports.front();
+        BOOST_TEST_EQ(trystero::room_error_code_name(e.code), "handshake-failed");
+        BOOST_TEST_EQ(e.message, "handshake timed out after 10000ms");
+        BOOST_TEST_EQ(e.peer_id, b_id);
+        BOOST_TEST_EQ(e.room_id, "slow");
+    }
+    trystero::test::advance(f, 5000ms);
+    BOOST_TEST_EQ(a_reports.size(), 1U);
+    BOOST_TEST(b_reports.empty());
+    BOOST_TEST_EQ(joins, 0U);
+    BOOST_TEST(a.peers().empty());
+    BOOST_TEST(b.peers().empty());
+}
+
+// The ready frame a room sends is 0.27.0's, byte for byte: `@_hsready` with an empty text, as
+// 0.27.0's handshake manager sends `payload || ''`.
+void ready_frames_carry_an_empty_text() {
+    counting_resource a_memory;
+    fixture f{true};
+    std::vector> from_a;
+    f.net.filter = [&](std::size_t from, std::size_t, std::span frame) {
+        if (end_in(f, from, &a_memory) && action_name(frame) == "@_hsready") {
+            from_a.emplace_back(frame.begin(), frame.end());
+        }
+        return trystero::test::memory_network::verdict::deliver;
+    };
+    auto a_config = app_config("readyAAAAAAAAAAAAAAA");
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    auto a = join(a_app, "ready");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("readyBBBBBBBBBBBBBBB"));
+    auto b = join(b_app, "ready");
+    BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; }));
+    const auto expected = recorded_ready_frame();
+    if (BOOST_TEST_EQ(from_a.size(), 1U)) {
+        BOOST_TEST_ALL_EQ(from_a[0].begin(), from_a[0].end(), expected.begin(), expected.end());
+    }
+}
+
+// A room sends its ready frame before the peer joins, so that what a listener of on_peer_join
+// sends follows it on the wire, as 0.27.0's manager enqueues the frame before onActivate. B's end
+// of the connection opens first, so that B's ready frame is already at A's end when A's handshake
+// starts: A then sends its ready frame and activates the peer in one call, where the order matters.
+void sends_inside_on_peer_join_follow_the_ready_frame() {
+    counting_resource a_memory;
+    fixture f{true};
+    f.net.defer_opens = true;
+    std::vector from_a;
+    f.net.filter = [&](std::size_t from, std::size_t, std::span frame) {
+        if (end_in(f, from, &a_memory)) {
+            from_a.push_back(action_name(frame));
+        }
+        return trystero::test::memory_network::verdict::deliver;
+    };
+    auto a_config = app_config("joinAAAAAAAAAAAAAAAA");
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    auto a = join(a_app, "greet");
+    auto greet = a.make_action("greet");
+    a.on_peer_join([&](const trystero::peer_event& e) {
+        greet.async_send("hello", trystero::send_options{.targets = {trystero::peer_id(e.peer_id)}},
+                         [](boost::system::error_code ec) { BOOST_TEST(!ec); });
+    });
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("joinBBBBBBBBBBBBBBBB"));
+    auto b = join(b_app, "greet");
+    std::vector heard;
+    auto greeted = b.make_action("greet");
+    greeted.on_message(
+        [&](const std::string& text, const trystero::message_info&) { heard.push_back(text); });
+    std::optional a_pc;
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] {
+        for (std::size_t id = 0; id < f.net.made_connections && !a_pc; ++id) {
+            if (end_in(f, id, &a_memory) && f.net.peer_of(id) != id) {
+                a_pc = id;
+            }
+        }
+        return a_pc.has_value();
+    })));
+    f.net.open(f.net.peer_of(*a_pc));
+    trystero::test::advance(f, 100ms);  // B's handshake runs, its ready frame waits for A's end
+    BOOST_TEST(from_a.empty());
+    f.net.open(*a_pc);
+    BOOST_TEST(run_until(f, [&] { return heard.size() == 1; }));
+    const auto ready = std::ranges::find(from_a, "@_hsready");
+    const auto hello = std::ranges::find(from_a, "greet");
+    BOOST_TEST(ready != from_a.end());
+    BOOST_TEST(hello != from_a.end());
+    BOOST_TEST(ready < hello);
+}
+
+/** A side's answer to an offer: whether it accepted or rejected it, and why. */
+struct offer_answer {
+    trystero::protocol::frame_kind kind{};
+    std::string reason;
+};
+
+/** Checks that the offers 1 and 3 were rejected as too large and 2 and 4 accepted. */
+void check_bound_answers(const std::map& answers) {
+    for (const std::uint32_t refused : {1U, 3U}) {
+        if (BOOST_TEST(answers.contains(refused))) {
+            BOOST_TEST(answers.at(refused).kind == trystero::protocol::frame_kind::rejected);
+            BOOST_TEST_EQ(answers.at(refused).reason, "payload exceeds receiver size limit");
+        }
+    }
+    for (const std::uint32_t taken : {2U, 4U}) {
+        if (BOOST_TEST(answers.contains(taken))) {
+            BOOST_TEST(answers.at(taken).kind == trystero::protocol::frame_kind::accepted);
+        }
+    }
+}
+
+// A handshake message is at most 64 KiB and a ready frame's payload 128 KiB, 0.27.0's
+// maxPayloadBytes of `@_hsdata` and `@_hsready`: an offer of one byte more is rejected as "payload
+// exceeds receiver size limit", one at the bound accepted.
+void handshake_messages_keep_0_27_0s_bounds() {
+    namespace tp = trystero::protocol;
+    counting_resource a_memory;
+    fixture f{true};
+    std::map from_a;  // A's answers, by transfer id
+    f.net.filter = [&](std::size_t from, std::size_t, std::span frame) {
+        if (end_in(f, from, &a_memory)) {
+            const auto decoded = tp::decode_action(frame);
+            if (const auto* m =
+                    decoded.frame ? std::get_if(&*decoded.frame) : nullptr) {
+                from_a.insert_or_assign(
+                    m->id, offer_answer{.kind = m->kind, .reason = std::string(m->reason)});
+            }
+        }
+        return trystero::test::memory_network::verdict::deliver;
+    };
+    auto a_config = app_config("boundAAAAAAAAAAAAAAA");
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    auto a = join(a_app, "bound");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("boundBBBBBBBBBBBBBBB"));
+    auto b = join(b_app, "bound");
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })));
+    std::optional a_pc;
+    for (std::size_t id = 0; id < f.net.made_connections && !a_pc; ++id) {
+        const auto connection = f.net.find(id);
+        if (end_in(f, id, &a_memory) && connection->channel()->is_open()) {
+            a_pc = id;
+        }
+    }
+    webcpp::test::require(BOOST_TEST(a_pc.has_value()));
+    const std::size_t hsdata = std::size_t{64} * 1024;
+    const std::size_t hsready = std::size_t{128} * 1024;
+    f.net.inject(*a_pc, tp::encode_offer("@_hsdata", tp::payload_format::json, "", 1, hsdata + 1));
+    f.net.inject(*a_pc, tp::encode_offer("@_hsdata", tp::payload_format::json, "", 2, hsdata));
+    f.net.inject(*a_pc,
+                 tp::encode_offer("@_hsready", tp::payload_format::json, "", 3, hsready + 1));
+    BOOST_TEST(run_until(f, [&] { return from_a.size() == 3; }));
+    // A peer's transfers are received one at a time: the second goes, then the fourth is taken.
+    f.net.inject(*a_pc, tp::encode_cancelled(2));
+    f.net.inject(*a_pc, tp::encode_offer("@_hsready", tp::payload_format::json, "", 4, hsready));
+    BOOST_TEST(run_until(f, [&] { return from_a.size() == 4; }));
+    check_bound_answers(from_a);
+    BOOST_TEST_EQ(a.peers().size(), 1U);
+}
+
+/** The JSON of an inline `\@_hsdata` frame, a step of the identity handshake; empty for another
+ * frame. */
+std::string handshake_step(std::span frame) {
+    const auto decoded = trystero::protocol::decode_action(frame);
+    const auto* p =
+        decoded.frame ? std::get_if(&*decoded.frame) : nullptr;
+    if (p == nullptr || p->kind != trystero::protocol::frame_kind::inline_payload ||
+        p->name != "@_hsdata") {
+        return {};
+    }
+    return {reinterpret_cast(p->payload.data()), p->payload.size()};
+}
+
+/** The number of a step's JSON, its `__trystero_id`, as the port writes it first; 0 for none. */
+int step_number(std::string_view json) {
+    constexpr std::string_view head = R"({"__trystero_id":)";
+    return json.starts_with(head) && json.size() > head.size() ? json[head.size()] - '0' : 0;
+}
+
+/** The inline `\@_hsdata` frame of a step's JSON, as a room sends it. */
+std::vector step_frame(std::string_view json) {
+    const auto frame = trystero::protocol::encode_inline(
+        "@_hsdata", trystero::protocol::payload_format::json, "",
+        std::span(reinterpret_cast(json.data()), json.size()));
+    return {frame.begin(), frame.end()};
+}
+
+/** The DTLS fingerprints of the description the memory connection `pc` writes, as a room reads
+ * them. */
+std::pmr::vector dtls_of_connection(std::size_t pc) {
+    auto* const memory = std::pmr::get_default_resource();
+    return trystero::protocol::dtls_fingerprints(trystero::test::memory_description(pc, memory),
+                                                 memory);
+}
+
+/** `text` with its first `from` replaced by `to`; the case ends when `from` is not in it. */
+std::string replaced(std::string text, std::string_view from, std::string_view to) {
+    const auto at = text.find(from);
+    webcpp::test::require(BOOST_TEST(at != std::string::npos));
+    return text.replace(at, from.size(), to);
+}
+
+/** The inline frame of `text` on the user action `chat`, as a room sends it. */
+std::vector chat_frame(std::string_view text) {
+    const auto frame = trystero::protocol::encode_inline(
+        "chat", trystero::protocol::payload_format::text, "",
+        std::span(reinterpret_cast(text.data()), text.size()));
+    return {frame.begin(), frame.end()};
+}
+
+/** Whether `frame` is a user action's: a proposal whose name is not one of the room's own. */
+bool user_frame(std::span frame) {
+    const auto name = action_name(frame);
+    return !name.empty() && !name.starts_with("@_");
+}
+
+/**
+ * Checks that two rooms whose handshake is under way hold each other as pending only: neither
+ * lists a peer or a user, and a user action's frames pass neither way. Each room sends on `chat`
+ * to all and the send completes; `inject` delivers a `chat` frame at each of the pair's ends,
+ * `ends`, as if the other had sent it. The case's filter counts the user frames it sees in
+ * `user_frames`, and the `chat` listeners count what reaches them in `delivered`.
+ */
+void check_pending_pair(fixture& f, trystero::room& a, trystero::room& b,
+                        std::array ends, const std::size_t& user_frames,
+                        const std::size_t& delivered) {
+    BOOST_TEST(a.peers().empty());
+    BOOST_TEST(b.peers().empty());
+    BOOST_TEST(a.users().empty());
+    BOOST_TEST(b.users().empty());
+    std::size_t sent = 0;
+    a.make_action("chat").async_send("from a",
+                                                  [&](boost::system::error_code) { ++sent; });
+    b.make_action("chat").async_send("from b",
+                                                  [&](boost::system::error_code) { ++sent; });
+    for (const auto end : ends) {
+        f.net.inject(end, chat_frame("injected"));
+    }
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return sent == 2; })));
+    trystero::test::advance(f, 100ms);
+    BOOST_TEST_EQ(user_frames, 0U);
+    BOOST_TEST_EQ(delivered, 0U);
+}
+
+/** A step of the identity handshake as the network saw it: whether A sent it, the connection
+ * that sent it and the one it went to, and its JSON. */
+struct sent_step {
+    bool from_a = false;
+    std::size_t from = 0;
+    std::size_t to = 0;
+    std::string json;
+};
+
+/** Checks the steps of one run between `impl_a`, the initiator, and `impl_b`: steps 1 and 3 from
+ * A, 2 from B, each claiming its sender's keys and fingerprints. */
+void check_identity_steps(const std::vector& steps,
+                          const trystero::detail::app_impl& impl_a,
+                          const trystero::detail::app_impl& impl_b) {
+    namespace tp = trystero::protocol;
+    webcpp::test::require(BOOST_TEST_EQ(steps.size(), 3U));
+    for (int n = 1; n <= 3; ++n) {
+        const auto& step = steps.at(static_cast(n - 1));
+        BOOST_TEST_EQ(step_number(step.json), n);
+        BOOST_TEST_EQ(step.from_a, n != 2);
+        if (n == 3) {
+            continue;
+        }
+        const auto sender = dtls_of_connection(step.from);
+        const auto receiver = dtls_of_connection(step.to);
+        webcpp::test::require(BOOST_TEST_EQ(sender.size(), 1U));
+        BOOST_TEST_NE(sender.front(), receiver.front());
+        const auto read = tp::read_handshake_step(step.json, n, sender, receiver,
+                                                  std::pmr::get_default_resource());
+        webcpp::test::require(BOOST_TEST(read.claims.has_value()));
+        const auto& claims = *read.claims;
+        BOOST_TEST_ALL_EQ(claims.dtls.begin(), claims.dtls.end(), sender.begin(), sender.end());
+        const auto& by = n == 1 ? impl_a : impl_b;
+        BOOST_TEST_EQ(claims.user_id, by.user_id());
+        BOOST_TEST_EQ(claims.endpoint_key, by.endpoint_key());
+        BOOST_TEST_EQ(claims.user_key, by.user().public_key());
+    }
+}
+
+// Two peers run 0.27.0's identity handshake, and each joins the other's room under the user it
+// proved, the other app's `user_id()`. A, whose id is lower, sends steps 1 and 3, B step 2; each
+// step claims the fingerprints of the description its sender wrote, which its receiver applied
+// (design D20), and its sender's ids and keys. Each run draws its nonces afresh from the backend's
+// randomness, each the UUID of a 16-byte draw of it: a second meeting's are new, and none is the
+// UUID of zero bytes.
+void peers_verify_each_other_and_join_with_their_user_ids() {
+    namespace tp = trystero::protocol;
+    counting_resource a_memory;  // first: A's connection ends are made in it, which names them
+    fixture f{true};
+    std::vector steps;
+    f.net.filter = [&](std::size_t from, std::size_t to, std::span frame) {
+        if (auto json = handshake_step(frame); !json.empty()) {
+            steps.push_back({
+                .from_a = end_in(f, from, &a_memory),
+                .from = from,
+                .to = to,
+                .json = std::move(json),
+            });
+        }
+        return trystero::test::memory_network::verdict::deliver;
+    };
+    const auto labels = ordered_labels(2, "verify");  // A's id below B's: A initiates
+    auto a_config = app_config(labels[0]);
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    auto a = join(a_app, "verify");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(labels[1]));
+    std::optional b(join(b_app, "verify"));
+    std::vector a_joins;
+    a.on_peer_join([&](const trystero::peer_event& e) {
+        a_joins.push_back(std::string(e.peer_id) + " " + std::string(e.user_id));
+    });
+    std::vector b_joins;
+    b->on_peer_join([&](const trystero::peer_event& e) {
+        b_joins.push_back(std::string(e.peer_id) + " " + std::string(e.user_id));
+    });
+    std::vector failures;
+    const auto record_failure = [&](const trystero::room_error& e) {
+        failures.emplace_back(e.message);
+    };
+    a.on_error(record_failure);
+    b->on_error(record_failure);
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a_joins.size() == 1 && b_joins.size() == 1; })));
+    const std::string_view a_id = a_app.self_id();
+    const std::string_view b_id = b_app.self_id();
+    const std::string a_user(a_app.user_id());
+    const std::string b_user(b_app.user_id());
+    BOOST_TEST_NE(a_user, b_user);
+    BOOST_TEST_EQ(a_joins.front(), std::string(b_id) + " " + b_user);
+    BOOST_TEST_EQ(b_joins.front(), std::string(a_id) + " " + a_user);
+    const auto a_peers = a.peers();
+    const auto b_peers = b->peers();
+    webcpp::test::require(BOOST_TEST(a_peers.contains(b_id) && b_peers.contains(a_id)));
+    BOOST_TEST_EQ(std::string_view(a_peers.find(b_id)->second.user_id), b_user);
+    BOOST_TEST_EQ(std::string_view(b_peers.find(a_id)->second.user_id), a_user);
+    if (const auto users = a.users(); BOOST_TEST_EQ(users.size(), 1U)) {
+        BOOST_TEST_EQ(std::string_view(users.begin()->first), b_user);
+    }
+    BOOST_TEST(failures.empty());
+
+    // Steps 1 and 3 from A, 2 from B, each claiming its sender's keys and fingerprints.
+    check_identity_steps(steps, trystero::detail::app_access::impl(a_app),
+                         trystero::detail::app_access::impl(b_app));
+
+    // B meets A again: the second run's nonces are new.
+    std::set drawn_uuids;  // the UUID of every 16-byte draw of the backend's
+    f.net.on_random = [&](std::span drawn) {
+        if (drawn.size() == 16) {
+            std::array bytes{};
+            std::ranges::copy(drawn, bytes.begin());
+            const auto uuid = tp::uuid_v4(bytes);
+            drawn_uuids.emplace(uuid.data(), uuid.size());
+        }
+    };
+    const auto nonce_of = [](const std::string& json) {
+        const auto read = tp::read_handshake_step(json, step_number(json), {}, {},
+                                                  std::pmr::get_default_resource());
+        return read.claims ? std::string(read.claims->nonce) : std::string();
+    };
+    b.reset();
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return a.peers().empty(); })));
+    b.emplace(join(b_app, "verify"));
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return a_joins.size() == 2; })));
+    f.net.on_random = {};
+    std::vector nonces;
+    for (const auto& step : steps) {
+        if (step_number(step.json) != 3) {
+            nonces.push_back(nonce_of(step.json));
+        }
+    }
+    webcpp::test::require(BOOST_TEST_EQ(nonces.size(), 4U));
+    // The second meeting's nonces, steps 1 and 2 of its run, are each the UUID of a draw of the
+    // backend's randomness made during that meeting.
+    for (std::size_t i = 2; i < nonces.size(); ++i) {
+        BOOST_TEST(drawn_uuids.contains(nonces[i]));
+    }
+    const auto zero = tp::uuid_v4({});
+    for (const auto& nonce : nonces) {
+        BOOST_TEST_EQ(nonce.size(), tp::uuid_text_size);
+        BOOST_TEST_NE(nonce, std::string(zero.data(), zero.size()));
+    }
+    std::ranges::sort(nonces);
+    BOOST_TEST(std::ranges::adjacent_find(nonces) == nonces.end());
+    BOOST_TEST(failures.empty());
+}
+
+/**
+ * A, whose id is lower, initiates; its step 1 to B is dropped, and `forge` of it is injected at
+ * B's end in its place. Until then each holds the other as pending only: no peer, no user, no
+ * user frame either way. B reports handshake_failed once, with `reason` and A's id, and kicks A
+ * as 0.27.0's `kickPeer` does: one `\@_leave` to A (dropped on its way), and B's end of the
+ * connection closed by B. A reports
+ * nothing, and neither side reports a join. Once A's room is gone, B reports nothing more: the
+ * failed run's timer went with it.
+ */
+void a_forged_step_1_fails_with(
+    const std::function& forge,
+    std::string_view reason) {
+    counting_resource a_memory;
+    fixture f{true};
+    std::optional> dropped;  // B's end, and the step
+    std::size_t user_frames = 0;
+    // B's farewells to A, counted and dropped: B's end of the connection must close because B
+    // ends it, not because A ends its own on the farewell.
+    std::size_t b_leaves = 0;
+    f.net.filter = [&](std::size_t from, std::size_t to, std::span frame) {
+        user_frames += user_frame(frame) ? 1 : 0;
+        if (!end_in(f, from, &a_memory) && action_name(frame) == "@_leave") {
+            ++b_leaves;
+            return trystero::test::memory_network::verdict::drop;
+        }
+        const auto json = handshake_step(frame);
+        if (end_in(f, from, &a_memory) && step_number(json) == 1) {
+            if (!dropped) {
+                dropped.emplace(to, json);
+            }
+            return trystero::test::memory_network::verdict::drop;
+        }
+        return trystero::test::memory_network::verdict::deliver;
+    };
+    const auto labels = ordered_labels(2, "forge");
+    auto a_config = app_config(labels[0]);
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    std::optional a(join(a_app, "forge"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(labels[1]));
+    auto b = join(b_app, "forge");
+    std::vector a_reports;
+    a->on_error(record_errors(f, a_reports, trystero::error::handshake_failed));
+    std::vector b_reports;
+    b.on_error(record_errors(f, b_reports, trystero::error::handshake_failed));
+    std::size_t joins = 0;
+    a->on_peer_join([&](const trystero::peer_event&) { ++joins; });
+    b.on_peer_join([&](const trystero::peer_event&) { ++joins; });
+    std::size_t delivered = 0;
+    a->make_action("chat").on_message(
+        [&](const std::string&, const trystero::message_info&) { ++delivered; });
+    b.make_action("chat").on_message(
+        [&](const std::string&, const trystero::message_info&) { ++delivered; });
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return dropped.has_value(); })));
+    const std::size_t b_end = dropped->first;
+    check_pending_pair(f, *a, b, {b_end, f.net.peer_of(b_end)}, user_frames, delivered);
+    BOOST_TEST_EQ(b_leaves, 0U);
+    f.net.inject(b_end, step_frame(forge(dropped->second, a_app, b_app)));
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return !b_reports.empty(); })));
+    trystero::test::advance(f, 1000ms);
+    // Kicked: one farewell to A, and B's end of the connection closed.
+    BOOST_TEST_EQ(b_leaves, 1U);
+    const auto b_connection = f.net.find(b_end);
+    BOOST_TEST(!b_connection || !b_connection->channel() || !b_connection->channel()->is_open());
+    BOOST_TEST_EQ(user_frames, 0U);
+    BOOST_TEST_EQ(delivered, 0U);
+    if (BOOST_TEST_EQ(b_reports.size(), 1U)) {
+        const auto& e = b_reports.front();
+        BOOST_TEST_EQ(trystero::room_error_code_name(e.code), "handshake-failed");
+        BOOST_TEST_EQ(e.message, reason);
+        BOOST_TEST_EQ(e.peer_id, a_app.self_id());
+        BOOST_TEST_EQ(e.room_id, "forge");
+    }
+    BOOST_TEST(a_reports.empty());
+    BOOST_TEST_EQ(joins, 0U);
+    BOOST_TEST(a->peers().empty());
+    BOOST_TEST(b.peers().empty());
+    a.reset();
+    trystero::test::advance(f, 15'000ms);
+    BOOST_TEST_EQ(b_reports.size(), 1U);
+    BOOST_TEST_EQ(joins, 0U);
+}
+
+// A step 1 that claims B's user id with A's own keys fails B's handshake as 0.27.0's
+// verifyUserIdKey fails it: "peer identity verification failed".
+void a_forged_step_fails_the_handshake() {
+    a_forged_step_1_fails_with(
+        [](const std::string& genuine, const trystero::test::app& a, const trystero::test::app& b) {
+            return replaced(genuine, a.user_id(), b.user_id());
+        },
+        trystero::protocol::handshake_reason::identity);
+}
+
+// A step 1 that claims fingerprints other than those of the description B applied fails B's
+// handshake, as a relay-side man in the middle's would: "DTLS fingerprint mismatch".
+void another_fingerprint_fails_the_handshake() {
+    a_forged_step_1_fails_with(
+        [](const std::string& genuine, const trystero::test::app&, const trystero::test::app&) {
+            const auto open = genuine.find(R"("dtls":[)");
+            const auto close = genuine.find(']', open);
+            webcpp::test::require(
+                BOOST_TEST(open != std::string::npos && close != std::string::npos));
+            std::string out = genuine.substr(0, open);
+            out += R"("dtls":["sha-256 00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:)"
+                   R"(33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff"])";
+            out += genuine.substr(close + 1);
+            return out;
+        },
+        trystero::protocol::handshake_reason::dtls_mismatch);
+}
+
+/**
+ * B leaves while step `held_step` of the handshake is held on its way: step 2, which B sent, so
+ * that neither side has verified the other, or step 3, which A sent, so that A, the initiator, has
+ * verified B and B has not verified A. Either way, while it is held, each holds the other as
+ * pending only: no peer, no user, no user frame either way. B reports nothing after the leave,
+ * through its farewell and past the handshake's 10 s, and once its room is gone nothing runs on it
+ * when the held step is released. No one joins.
+ */
+void a_handshake_left_at_step(int held_step) {
+    counting_resource b_memory;
+    fixture f{true};
+    bool holding = true;
+    std::optional held_at;  // the receiving end
+    std::size_t user_frames = 0;
+    f.net.filter = [&](std::size_t from, std::size_t to, std::span frame) {
+        user_frames += user_frame(frame) ? 1 : 0;
+        const bool from_b = end_in(f, from, &b_memory);
+        if (holding && from_b == (held_step == 2) &&
+            step_number(handshake_step(frame)) == held_step) {
+            held_at = to;
+            return trystero::test::memory_network::verdict::hold;
+        }
+        return trystero::test::memory_network::verdict::deliver;
+    };
+    const auto labels = ordered_labels(2, "midway");
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config(labels[0]));
+    auto a = join(a_app, "midway");
+    auto b_config = app_config(labels[1]);
+    b_config.memory = &b_memory;
+    trystero::test::app b_app(f.io.get_executor(), f.net, std::move(b_config));
+    std::optional b(join(b_app, "midway"));
+    std::size_t joins = 0;
+    a.on_peer_join([&](const trystero::peer_event&) { ++joins; });
+    b->on_peer_join([&](const trystero::peer_event&) { ++joins; });
+    std::size_t delivered = 0;
+    a.make_action("chat").on_message(
+        [&](const std::string&, const trystero::message_info&) { ++delivered; });
+    b->make_action("chat").on_message(
+        [&](const std::string&, const trystero::message_info&) { ++delivered; });
+    bool left = false;
+    std::size_t b_after_leave = 0;
+    b->on_error([&](const trystero::room_error&) { b_after_leave += left ? 1 : 0; });
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return held_at.has_value(); })));
+    check_pending_pair(f, a, *b, {*held_at, f.net.peer_of(*held_at)}, user_frames, delivered);
+    std::optional leave;
+    left = true;
+    b->async_leave([&](boost::system::error_code ec) { leave = ec; });
+    trystero::test::advance(f, 12'000ms);  // past the farewell and the handshake's 10 s
+    BOOST_TEST(leave.has_value() && !*leave);
+    b.reset();
+    holding = false;
+    f.net.release(*held_at);
+    trystero::test::advance(f, 15'000ms);
+    BOOST_TEST_EQ(b_after_leave, 0U);
+    BOOST_TEST_EQ(joins, 0U);
+    BOOST_TEST_EQ(delivered, 0U);
+    BOOST_TEST(a.peers().empty());
+}
+
+// B leaves while the step 2 it sent is held on its way to A, its handshake waiting for step 3.
+void leaving_during_a_handshake_reports_nothing() {
+    a_handshake_left_at_step(2);
+}
+
+// B leaves while A's step 3 is held on its way to B: A has verified B, B has not verified A.
+void leaving_after_one_side_verified_reports_nothing() {
+    a_handshake_left_at_step(3);
+}
+
+/** A room's options with `max_users` set to `n`. */
+trystero::room_options at_most(std::size_t n) {
+    trystero::room_options options;
+    options.max_users = n;
+    return options;
+}
+
+/** The payload of an inline `\@_hsready` frame, as text; empty for another frame. */
+std::optional ready_payload(std::span frame) {
+    const auto decoded = trystero::protocol::decode_action(frame);
+    const auto* p =
+        decoded.frame ? std::get_if(&*decoded.frame) : nullptr;
+    if (p == nullptr || p->kind != trystero::protocol::frame_kind::inline_payload ||
+        p->name != "@_hsready") {
+        return std::nullopt;
+    }
+    return std::string(reinterpret_cast(p->payload.data()), p->payload.size());
+}
+
+/** An app's setup of `label` whose connections are made with an ICE server of its own, `url`, so
+ * that the memory network's `on_made` tells them apart. */
+trystero::test::app_setup app_config_tagged(std::string_view label, std::string_view url) {
+    auto config = app_config(label);
+    config.ice_servers.push_back({
+        .urls = {std::pmr::string(url)},
+        .username = std::pmr::string(),
+        .credential = std::pmr::string(),
+    });
+    return config;
+}
+
+/** Records every report of a room, whatever its code. */
+auto record_all_errors(fixture& f, std::vector& to) {
+    return [&f, &to](const trystero::room_error& e) {
+        to.push_back({
+            .code = e.code,
+            .message = std::string(e.message),
+            .app_id = std::string(e.app_id),
+            .room_id = std::string(e.room_id),
+            .peer_id = std::string(e.peer_id),
+            .stage = e.stage,
+            .turn_configured = e.turn_configured,
+            .reason = std::string(e.reason),
+            .at = f.net.steady_now(),
+        });
+    };
+}
+
+/** Checks that every report of `reports` is 0.27.0's `room-full` of room `room_id`, one from each
+ * of `peers`. */
+void check_room_full_reports(const std::vector& reports, std::string_view room_id,
+                             const std::set& peers) {
+    std::set from;
+    for (const auto& e : reports) {
+        BOOST_TEST_EQ(trystero::room_error_code_name(e.code), "room-full");
+        BOOST_TEST_EQ(e.message, "room full");
+        BOOST_TEST_EQ(e.room_id, room_id);
+        from.insert(e.peer_id);
+    }
+    BOOST_TEST_EQ(reports.size(), peers.size());
+    BOOST_TEST(from == peers);
+}
+
+// A room of at most 2 users that holds 2 refuses a third user once its handshake passed: the
+// newcomer reports room_full from each of the two, with 0.27.0's message and the refusing peer's
+// id, and leaves; the two report nothing, and never report it joining. The newcomer is unbounded,
+// so that the refusals are the two rooms' alone.
+void a_full_room_refuses_a_new_user() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("fullAAAAAAAAAAAAAAAA"));
+    auto a = join(a_app, "full", at_most(2));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("fullBBBBBBBBBBBBBBBB"));
+    auto b = join(b_app, "full", at_most(2));
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })));
+    std::vector ab_reports;
+    a.on_error(record_all_errors(f, ab_reports));
+    b.on_error(record_all_errors(f, ab_reports));
+    trystero::test::app c_app(f.io.get_executor(), f.net, app_config("fullCCCCCCCCCCCCCCCC"));
+    const std::string c_id(c_app.self_id());
+    std::size_t c_joins = 0;
+    const auto count_c = [&](const trystero::peer_event& e) { c_joins += e.peer_id == c_id; };
+    a.on_peer_join(count_c);
+    b.on_peer_join(count_c);
+    auto c = join(c_app, "full");
+    std::vector c_reports;
+    c.on_error(record_all_errors(f, c_reports));
+    BOOST_TEST(run_until(f, [&] { return c_reports.size() == 2; }));
+    trystero::test::advance(f, 30'000ms);  // announcements come and go: nothing more
+    check_room_full_reports(c_reports, "full",
+                            {std::string(a_app.self_id()), std::string(b_app.self_id())});
+    BOOST_TEST(ab_reports.empty());
+    BOOST_TEST_EQ(c_joins, 0U);
+    BOOST_TEST_EQ(a.peers().size(), 1U);
+    BOOST_TEST_EQ(b.peers().size(), 1U);
+    BOOST_TEST(c.peers().empty());
+}
+
+// The room counts users, not peers: a second peer of a user already in a full room of at most 2
+// users, an app importing that user's identity, is admitted by every room, its own included,
+// whose own user is that user.
+void another_peer_of_a_present_user_is_admitted() {
+    fixture f{true};
+    const auto identity = make_user_identity();
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("presentAAAAAAAAAAAAA"));
+    auto a = join(a_app, "present", at_most(2));
+    trystero::test::app b1_app(f.io.get_executor(), f.net,
+                               app_config_of("presentBBBBBBBBBBBB1", identity));
+    auto b1 = join(b1_app, "present", at_most(2));
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b1.peers().size() == 1; })));
+    std::vector reports;
+    a.on_error(record_all_errors(f, reports));
+    b1.on_error(record_all_errors(f, reports));
+    trystero::test::app b2_app(f.io.get_executor(), f.net,
+                               app_config_of("presentBBBBBBBBBBBB2", identity));
+    auto b2 = join(b2_app, "present", at_most(2));
+    b2.on_error(record_all_errors(f, reports));
+    BOOST_TEST(run_until(f, [&] {
+        return a.peers().size() == 2 && b1.peers().size() == 2 && b2.peers().size() == 2;
+    }));
+    BOOST_TEST_EQ(a.users().size(), 1U);
+    BOOST_TEST(a.users().contains(identity.user_id()));
+    BOOST_TEST(reports.empty());
+}
+
+// Two newcomers, B and C, whose handshakes with A, a room of at most 2 users alone in it, pass
+// while neither has joined: A admits B first and waits for its ready frame, which the network
+// holds; C's handshake then passes, and the place B holds is taken, as 0.27.0's
+// reservedAdmissionUsers counts it: C is refused at admission, its only ready frame from A the
+// refusal, and B joins once its ready frame arrives. A, the lowest id, initiates both handshakes;
+// B and C are unbounded.
+void concurrent_admissions_respect_the_limit() {
+    counting_resource a_memory;  // first: the apps' connection ends are made in them
+    counting_resource b_memory;
+    counting_resource c_memory;
+    fixture f{true};
+    const auto labels = ordered_labels(3, "race");
+    bool holding = true;
+    std::optional held_at;  // A's end of its connection to B
+    std::vector to_c;       // the ready payloads A sends C
+    f.net.filter = [&](std::size_t from, std::size_t to, std::span frame) {
+        const auto ready = ready_payload(frame);
+        if (ready && end_in(f, from, &a_memory) && end_in(f, to, &c_memory)) {
+            to_c.push_back(*ready);
+        }
+        if (ready && holding && end_in(f, from, &b_memory) && end_in(f, to, &a_memory)) {
+            holding = false;
+            held_at = to;
+            return trystero::test::memory_network::verdict::hold;
+        }
+        return trystero::test::memory_network::verdict::deliver;
+    };
+    auto a_config = app_config(labels[0]);
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    auto a = join(a_app, "race", at_most(2));
+    auto b_config = app_config(labels[1]);
+    b_config.memory = &b_memory;
+    trystero::test::app b_app(f.io.get_executor(), f.net, std::move(b_config));
+    const auto b = join(b_app, "race");
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return held_at.has_value(); })));
+    BOOST_TEST(a.peers().empty());  // B is admitted, not joined
+    auto c_config = app_config(labels[2]);
+    c_config.memory = &c_memory;
+    trystero::test::app c_app(f.io.get_executor(), f.net, std::move(c_config));
+    auto c = join(c_app, "race");
+    std::vector c_reports;
+    c.on_error(record_errors(f, c_reports, trystero::error::room_full));
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return !c_reports.empty(); })));
+    check_room_full_reports(c_reports, "race", {std::string(a_app.self_id())});
+    f.net.release(*held_at);
+    BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; }));
+    trystero::test::advance(f, 1000ms);
+    if (BOOST_TEST_EQ(a.peers().size(), 1U)) {
+        BOOST_TEST_EQ(a.peers().begin()->first, b_app.self_id());
+    }
+    const std::vector refusal{R"({"ok":false,"err":"room full"})"};
+    BOOST_TEST_ALL_EQ(to_c.begin(), to_c.end(), refusal.begin(), refusal.end());
+    BOOST_TEST_EQ(c_reports.size(), 1U);
+}
+
+// A room that refused a user does not connect to it again while it stays full, as 0.27.0's
+// canConnectPeer gates its signaling: a minute of the newcomer's announcements and offers, which
+// it goes on making with connections of its own, makes no connection in either full room. Once one
+// of them leaves, the other has a place, and the newcomer joins it.
+void refused_user_is_not_dialed_again(bool newcomer_offers) {
+    fixture f{true};
+    // The newcomer's id is the lowest, so that it offers to both rooms, or the highest, so that
+    // both offer to it: the signaling gate answers each direction.
+    const auto labels = ordered_labels(3, "dial");
+    const std::string newcomer = newcomer_offers ? labels[0] : labels[2];
+    const std::string full_a = newcomer_offers ? labels[1] : labels[0];
+    const std::string full_b = newcomer_offers ? labels[2] : labels[1];
+    std::map made;  // connections made, by the ICE server of their app
+    f.net.on_made = [&](std::size_t, std::span servers) {
+        if (!servers.empty() && !servers.front().urls.empty()) {
+            ++made[std::string(servers.front().urls.front())];
+        }
+    };
+    trystero::test::app a_app(f.io.get_executor(), f.net,
+                              app_config_tagged(full_a, "stun:a.test:3478"));
+    auto a = join(a_app, "dial", at_most(2));
+    trystero::test::app b_app(f.io.get_executor(), f.net,
+                              app_config_tagged(full_b, "stun:b.test:3478"));
+    std::optional b(join(b_app, "dial", at_most(2)));
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b->peers().size() == 1; })));
+    trystero::test::app c_app(f.io.get_executor(), f.net, app_config(newcomer));
+    auto c = join(c_app, "dial");
+    std::vector c_reports;
+    c.on_error(record_errors(f, c_reports, trystero::error::room_full));
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return c_reports.size() == 2; })));
+    const auto a_made = made["stun:a.test:3478"];
+    const auto b_made = made["stun:b.test:3478"];
+    const auto c_made = made["stun:stun.l.google.com:19302"];  // the newcomer's, the default ones
+    trystero::test::advance(f, 60'000ms);
+    BOOST_TEST_EQ(made["stun:a.test:3478"], a_made);
+    BOOST_TEST_EQ(made["stun:b.test:3478"], b_made);
+    if (newcomer_offers) {
+        BOOST_TEST_GT(made["stun:stun.l.google.com:19302"], c_made);  // it went on trying
+    } else {
+        BOOST_TEST_EQ(made["stun:stun.l.google.com:19302"], c_made);  // it only answers, and is not
+    }
+    BOOST_TEST_EQ(c_reports.size(), 2U);
+    BOOST_TEST(c.peers().empty());
+    b.reset();
+    BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && c.peers().size() == 1; }, 60s));
+    if (BOOST_TEST_EQ(a.peers().size(), 1U)) {
+        BOOST_TEST_EQ(a.peers().begin()->first, c_app.self_id());
+    }
+}
+
+void a_refused_user_is_not_dialed_again() {
+    refused_user_is_not_dialed_again(true);
+    refused_user_is_not_dialed_again(false);
+}
+
+// A connection a full room refuses when its channel opens lets the peer negotiate again, as
+// 0.27.0's onPeer destroys it and its close prunes the peer's signaling state: A, a room of at most
+// 2 users, refuses C while B is in it; B leaves, and C's next negotiation with A is made, its
+// channels held closed; D fills A's place before they open, so that A refuses C's connection at
+// its open; D leaves, and C joins A. B and C are unbounded.
+void a_connection_refused_at_its_open_lets_the_peer_back() {
+    counting_resource a_memory;  // first: the apps' connection ends are made in them
+    counting_resource c_memory;
+    fixture f{true};
+    auto a_config = app_config("reopenAAAAAAAAAAAAAA");
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    auto a = join(a_app, "reopen", at_most(2));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("reopenBBBBBBBBBBBBBB"));
+    std::optional b(join(b_app, "reopen"));
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b->peers().size() == 1; })));
+    auto c_config = app_config("reopenCCCCCCCCCCCCCC");
+    c_config.memory = &c_memory;
+    trystero::test::app c_app(f.io.get_executor(), f.net, std::move(c_config));
+    auto c = join(c_app, "reopen");
+    std::vector c_reports;
+    c.on_error(record_errors(f, c_reports, trystero::error::room_full));
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return c_reports.size() == 1; })));
+    check_room_full_reports(c_reports, "reopen", {std::string(a_app.self_id())});
+    // B leaves: A has a place, and C's next negotiation with A is made with its channels closed.
+    const auto made_before = f.net.made_connections;
+    f.net.defer_opens = true;
+    b.reset();
+    std::optional a_end;
+    webcpp::test::require(BOOST_TEST(run_until(
+        f,
+        [&] {
+            for (std::size_t id = made_before; id < f.net.made_connections && !a_end; ++id) {
+                const auto other = f.net.peer_of(id);
+                if (other != id && end_in(f, id, &a_memory) && end_in(f, other, &c_memory)) {
+                    a_end = id;
+                }
+            }
+            return a_end.has_value();
+        },
+        60s)));
+    const auto c_end = f.net.peer_of(*a_end);
+    f.net.defer_opens = false;
+    // D fills the place before the channels open.
+    trystero::test::app d_app(f.io.get_executor(), f.net, app_config("reopenDDDDDDDDDDDDDD"));
+    std::optional d(join(d_app, "reopen"));
+    webcpp::test::require(BOOST_TEST(run_until(
+        f, [&] { return a.peers().size() == 1 && a.peers().contains(d_app.self_id()); })));
+    f.net.open(*a_end);
+    f.net.open(c_end);
+    const auto a_end_open = [&] {
+        const auto connection = f.net.find(*a_end);
+        const auto channel = connection ? connection->channel() : nullptr;
+        return channel && channel->is_open();
+    };
+    // A refused the connection at its open: its end closes, and C is not among A's peers.
+    BOOST_TEST(run_until(f, [&] { return !a_end_open(); }));
+    BOOST_TEST_EQ(a.peers().size(), 1U);
+    BOOST_TEST(!a.peers().contains(c_app.self_id()));
+    // D leaves: C's next negotiation reaches A, which has a place for it again. (C and D, both
+    // unbounded, are each other's peers meanwhile.)
+    d.reset();
+    BOOST_TEST(run_until(f, [&] { return a.peers().contains(c_app.self_id()); }, 60s));
+    BOOST_TEST_EQ(a.peers().size(), 1U);
+    BOOST_TEST(c.peers().contains(a_app.self_id()));
+}
+
+// A full room's refusal that reaches a peer before it verified the refusing peer waits for the
+// verification, as 0.27.0 keeps it as the entry's deferredReady: A, the initiator, gets the
+// refusal while B's step 2 is held, reports nothing, and reports room_full with B's id once step 2
+// arrives and verifies B, before either joins.
+void a_refusal_waits_for_the_peers_verification() {
+    counting_resource b_memory;
+    fixture f{true};
+    bool holding = true;
+    std::optional held_at;  // A's end
+    f.net.filter = [&](std::size_t from, std::size_t to, std::span frame) {
+        if (holding && end_in(f, from, &b_memory) && step_number(handshake_step(frame)) == 2) {
+            holding = false;
+            held_at = to;
+            return trystero::test::memory_network::verdict::hold;
+        }
+        return trystero::test::memory_network::verdict::deliver;
+    };
+    const auto labels = ordered_labels(2, "deferred");
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config(labels[0]));
+    auto a = join(a_app, "deferred");
+    auto b_config = app_config(labels[1]);
+    b_config.memory = &b_memory;
+    trystero::test::app b_app(f.io.get_executor(), f.net, std::move(b_config));
+    auto b = join(b_app, "deferred");
+    std::vector a_reports;
+    a.on_error(record_all_errors(f, a_reports));
+    std::size_t joins = 0;
+    a.on_peer_join([&](const trystero::peer_event&) { ++joins; });
+    b.on_peer_join([&](const trystero::peer_event&) { ++joins; });
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return held_at.has_value(); })));
+    const std::string_view refusal = R"({"ok":false,"err":"room full"})";
+    const auto frame = trystero::protocol::encode_inline(
+        "@_hsready", trystero::protocol::payload_format::json, "",
+        std::span(reinterpret_cast(refusal.data()), refusal.size()));
+    f.net.inject(*held_at, frame);
+    trystero::test::advance(f, 100ms);
+    BOOST_TEST(a_reports.empty());
+    f.net.release(*held_at);
+    BOOST_TEST(run_until(f, [&] { return !a_reports.empty(); }));
+    check_room_full_reports(a_reports, "deferred", {std::string(b_app.self_id())});
+    BOOST_TEST_EQ(joins, 0U);
+    BOOST_TEST(a.peers().empty());
+    // A is not full itself: B's next announcement, once its connection ended, meets it again.
+}
+
+// The refusal of a full room outlives the room's let-go of the peer, as 0.27.0's destroyAfterFlush
+// has it: with a channel that delivers a byte per post, the frame is still on its way when the
+// room removes the refused peer, and the newcomer reports room_full all the same. A link ended at
+// once would drop what it buffered.
+void a_refusal_survives_the_close() {
+    fixture f{true};
+    f.net.channel_capacity = 1;
+    f.net.drain_per_post = 1;
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("flushAAAAAAAAAAAAAAAA"));
+    const auto a = join(a_app, "flush", at_most(1));
+    trystero::test::app c_app(f.io.get_executor(), f.net, app_config("flushCCCCCCCCCCCCCCCC"));
+    auto c = join(c_app, "flush");
+    std::vector c_reports;
+    c.on_error(record_errors(f, c_reports, trystero::error::room_full));
+    BOOST_TEST(run_until(f, [&] { return !c_reports.empty(); }));
+    check_room_full_reports(c_reports, "flush", {std::string(a_app.self_id())});
+    trystero::test::advance(f, 1000ms);
+    BOOST_TEST(a.peers().empty());
+    BOOST_TEST(c.peers().empty());
+}
+
+// A link a full room let go flushes for 0.27.0's destroyAfterFlush grace, 40 ms, and is ended then
+// as its channel has drained: until then it is open, and a frame that arrives on it acts on
+// nothing, the room no longer holding the peer.
+void a_refused_link_ends_after_its_grace() {
+    counting_resource a_memory;  // first: the app's connection end is made in it
+    fixture f{true};
+    std::vector made;
+    f.net.on_made = [&](std::size_t pc, std::span) {
+        made.push_back(pc);
+    };
+    auto a_config = app_config("graceAAAAAAAAAAAAAAAAA");
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    auto a = join(a_app, "grace", at_most(1));
+    std::size_t delivered = 0;
+    a.make_action("chat").on_message(
+        [&](const std::string&, const trystero::message_info&) { ++delivered; });
+    trystero::test::app c_app(f.io.get_executor(), f.net, app_config("graceCCCCCCCCCCCCCCCCC"));
+    auto c = join(c_app, "grace");
+    std::vector c_reports;
+    c.on_error(record_errors(f, c_reports, trystero::error::room_full));
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return !c_reports.empty(); })));
+    // A's end of the refused link, open until the flush ends it.
+    const auto a_end = [&]() -> std::optional {
+        for (const auto pc : made) {
+            if (end_in(f, pc, &a_memory)) {
+                return pc;
+            }
+        }
+        return std::nullopt;
+    }();
+    webcpp::test::require(BOOST_TEST(a_end.has_value()));
+    const auto is_open = [&] {
+        const auto connection = f.net.find(*a_end);  // gone with its end
+        const auto channel = connection ? connection->channel() : nullptr;
+        return channel && channel->is_open();
+    };
+    BOOST_TEST(is_open());
+    f.net.inject(*a_end, chat_frame("too late"));
+    trystero::test::advance(f, 30ms);
+    BOOST_TEST_EQ(delivered, 0U);
+    BOOST_TEST(is_open());  // still inside the grace
+    trystero::test::advance(f, 20ms);
+    BOOST_TEST(!is_open());  // drained, so ended with the grace
+    BOOST_TEST_EQ(delivered, 0U);
+    BOOST_TEST(a.peers().empty());
+}
+
+// `max_users` is 0.27.0's positive safe integer: 0 and 2^53 are refused with invalid_max_users,
+// before the app looks for a room of that id, and 1 and 2^53 - 1 are taken.
+void max_users_zero_is_refused() {
+    fixture f{true};
+    trystero::test::app app(f.io.get_executor(), f.net, app_config("maxUsersAAAAAAAAAAAA"));
+    const auto zero = app.join("bounded", at_most(0));
+    BOOST_TEST(zero.has_error() && zero.error() == trystero::error::invalid_max_users);
+    BOOST_TEST_EQ(make_error_code(trystero::error::invalid_max_users).message(),
+                  "maxUsers must be a positive safe integer");
+    const auto one = app.join("bounded", at_most(1));
+    BOOST_TEST(one.has_value());
+    const auto again = app.join("bounded", at_most(0));
+    BOOST_TEST(again.has_error() && again.error() == trystero::error::invalid_max_users);
+    if constexpr (sizeof(std::size_t) > 4) {
+        constexpr auto limit = trystero::room_options::max_users_limit;
+        const auto above = app.join("above", at_most(static_cast(limit + 1)));
+        BOOST_TEST(above.has_error() && above.error() == trystero::error::invalid_max_users);
+        const auto at = app.join("at", at_most(static_cast(limit)));
+        BOOST_TEST(at.has_value());
+    }
+}
+
+// The names of the codes are 0.27.0's RoomErrorCode, and every other code has none.
+void error_names_match_trystero() {
+    using trystero::error;
+    const std::array, 9> named{
+        {
+            {error::room_full, "room-full"},
+            {error::banned, "banned"},
+            {error::relay_failed, "relay-failed"},
+            {error::identity_failed, "identity-failed"},
+            {error::plugin_failed, "plugin-failed"},
+            {error::decrypt_failed, "decrypt-failed"},
+            {error::peer_connect_failed, "peer-connect-failed"},
+            {error::handshake_failed, "handshake-failed"},
+            {error::peer_error, "peer-error"},
+        },
+    };
+    for (const auto& [e, name] : named) {
+        BOOST_TEST_EQ(trystero::room_error_code_name(e), name);
+    }
+    for (int value = 1; value <= static_cast(error::invalid_max_users); ++value) {
+        const auto e = static_cast(value);
+        if (std::ranges::none_of(named, [&](const auto& n) { return n.first == e; })) {
+            BOOST_TEST(trystero::room_error_code_name(e).empty());
+        }
+    }
+    // A code of another category with a value of the same number is no room error of Trystero's.
+    BOOST_TEST(
+        trystero::room_error_code_name(boost::system::error_code(static_cast(error::room_full),
+                                                                 boost::system::generic_category()))
+            .empty());
+    BOOST_TEST(trystero::room_error_code_name({}).empty());
+    // The messages are 0.27.0's, where it has one.
+    BOOST_TEST_EQ(make_error_code(error::relay_failed).message(), "all signaling relays failed");
+    BOOST_TEST_EQ(make_error_code(error::peer_connect_failed).message(),
+                  "could not connect to peer after exchanging SDP");
+    BOOST_TEST_EQ(make_error_code(error::handshake_failed).message(), "handshake failed");
+}
+
+// Messages that queued for async_receive when the room was left go with it, as 0.27.0 drops each
+// peer's pending data at its leave: a listener added afterwards gets none of them.
+void messages_waiting_at_a_leave_are_dropped() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("droppedAAAAAAAAAAAAA"));
+    auto a = join(a_app, "dropped");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("droppedBBBBBBBBBBBBB"));
+    auto b = join(b_app, "dropped");
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })));
+    auto send = a.make_action("chat");
+    auto receive = b.make_action("chat");
+    // A receive makes the action listen: what arrives once it completed queues for the next.
+    std::vector got;
+    receive.async_receive(
+        [&](boost::system::error_code ec, const std::string& text, const trystero::message_info&) {
+            BOOST_TEST(!ec);
+            got.push_back(text);
+        });
+    std::size_t sent = 0;
+    for (int i = 0; i < 3; ++i) {
+        send.async_send("waiting " + std::to_string(i), [&](boost::system::error_code ec) {
+            BOOST_TEST(!ec);
+            ++sent;
+        });
+    }
+    BOOST_TEST(run_until(f, [&] { return sent == 3 && got.size() == 1; }));
+    run_until(f, [] { return false; }, 100ms);  // the others arrive, and queue
+    bool left = false;
+    b.async_leave([&](boost::system::error_code) { left = true; });
+    BOOST_TEST(run_until(f, [&] { return left; }));
+    const auto late = receive.on_message(
+        [&](const std::string& text, const trystero::message_info&) { got.push_back(text); });
+    run_until(f, [] { return false; }, 100ms);
+    BOOST_TEST_EQ(got.size(), 1U);
+    bool received = false;
+    receive.async_receive(
+        [&](boost::system::error_code ec, const std::string&, const trystero::message_info&) {
+            BOOST_TEST(ec == trystero::error::room_left);
+            received = true;
+        });
+    BOOST_TEST(run_until(f, [&] { return received; }));
+}
+
+// A message posted to its listener before the room ended, whose listener is gone once the post
+// runs, goes with the room as well: a progress listener removes the message listener and drops
+// the room's handle, which ends it at once, before the message's post runs; a listener added
+// afterwards gets nothing.
+void a_message_posted_before_the_room_ended_is_dropped() {
+    fixture f{true};
+    trystero::test::app a_app(f.io.get_executor(), f.net, app_config("postedAAAAAAAAAAAAAA"));
+    auto a = join(a_app, "posted");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("postedBBBBBBBBBBBBBB"));
+    std::optional b(join(b_app, "posted"));
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b->peers().size() == 1; })));
+    auto send = a.make_action("chat");
+    auto receive = b->make_action("chat");
+    std::vector got;
+    auto first = receive.on_message(
+        [&](const std::string& text, const trystero::message_info&) { got.push_back(text); });
+    bool ended = false;
+    receive.on_receive_progress([&](double share, const trystero::progress_info&) {
+        if (share == 1.0 && !ended) {
+            ended = true;
+            first.unsubscribe();
+            b.reset();
+        }
+    });
+    send.async_send("posted", [](boost::system::error_code) {});
+    BOOST_TEST(run_until(f, [&] { return ended; }));
+    run_until(f, [] { return false; }, 100ms);
+    const auto late = receive.on_message(
+        [&](const std::string& text, const trystero::message_info&) { got.push_back(text); });
+    run_until(f, [] { return false; }, 100ms);
+    BOOST_TEST(got.empty());
+}
+
+/** The frame of the vectors' `handshake_frames` entry `name`, which 0.27.0 wrote. */
+std::vector recorded_handshake_frame(std::string_view name) {
+    webcpp::test::require(BOOST_TEST(vectors().has_value()));
+    for (const auto entry : vectors()->root()["handshake_frames"]) {
+        if (entry["case"].value_or(std::string_view()) == name) {
+            return bytes_of_hex(entry["frames"].at(0)["hex"].value_or(std::string_view()));
+        }
+    }
+    BOOST_ERROR("handshake_frames has no such case");
+    return {};
+}
+
+/** The connection end of `memory`'s app whose channel is open, the first made; the case ends when
+ * there is none. */
+std::size_t open_end_in(fixture& f, const std::pmr::memory_resource* memory) {
+    for (std::size_t id = 0; id < f.net.made_connections; ++id) {
+        const auto connection = f.net.find(id);
+        if (end_in(f, id, memory) && connection->channel()->is_open()) {
+            return id;
+        }
+    }
+    webcpp::test::require(BOOST_TEST(false));
+    return 0;
+}
+
+// A frame that breaks the action wire's protocol, injected at A's end of its connection to B, an
+// active peer: A reports peer_error once, with 0.27.0's reason as its message and B's id, as
+// 0.27.0's onPeerError reports it, then tells B to leave and drops it; B hears the farewell and
+// drops A. A frame of an unknown version is reported in 0.27.0's words for it.
+void a_protocol_violation_reports_peer_error() {
+    for (const auto& [frame, reason] :
+         std::vector, std::string_view>>{
+             {{3, 15}, "invalid action frame"},
+             {{7, 0}, "incompatible action protocol version"},
+         }) {
+        counting_resource a_memory;  // first: A's connection ends are made in it
+        fixture f{true};
+        std::size_t a_leaves = 0;  // A's farewells to B
+        f.net.filter = [&](std::size_t from, std::size_t, std::span sent) {
+            a_leaves += end_in(f, from, &a_memory) && action_name(sent) == "@_leave" ? 1 : 0;
+            return trystero::test::memory_network::verdict::deliver;
+        };
+        auto a_config = app_config("violationAAAAAAAAAAA");
+        a_config.memory = &a_memory;
+        trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+        auto a = join(a_app, "violation");
+        trystero::test::app b_app(f.io.get_executor(), f.net, app_config("violationBBBBBBBBBBB"));
+        auto b = join(b_app, "violation");
+        webcpp::test::require(BOOST_TEST(
+            run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })));
+        std::vector a_reports;
+        a.on_error(record_all_errors(f, a_reports));
+        std::size_t a_lost = 0;
+        std::size_t b_lost = 0;
+        a.on_peer_leave([&](const trystero::peer_event&) { ++a_lost; });
+        b.on_peer_leave([&](const trystero::peer_event&) { ++b_lost; });
+        f.net.inject(open_end_in(f, &a_memory), frame);
+        BOOST_TEST(run_until(f, [&] { return !a_reports.empty() && a_lost == 1 && b_lost == 1; }));
+        trystero::test::advance(f, 1000ms);
+        if (BOOST_TEST_EQ(a_reports.size(), 1U)) {
+            const auto& e = a_reports.front();
+            BOOST_TEST_EQ(trystero::room_error_code_name(e.code), "peer-error");
+            BOOST_TEST_EQ(e.message, reason);
+            BOOST_TEST_EQ(e.peer_id, b_app.self_id());
+            BOOST_TEST_EQ(e.room_id, "violation");
+        }
+        BOOST_TEST_EQ(a_leaves, 1U);
+    }
+}
+
+/** The JSON text of `letters` then `emoji` times U+1F600 (UTF-8, written in bytes for a compiler
+ * whose narrow literals are not UTF-8), quoted. */
+std::string quoted_emoji(std::string_view letters, std::size_t emoji) {
+    std::string out = "\"";
+    out += letters;
+    for (std::size_t i = 0; i < emoji; ++i) {
+        out += "\xF0\x9F\x98\x80";
+    }
+    out += '"';
+    return out;
+}
+
+/** Checks that ready frames other than a refusal, and a refusal's JSON sent as a text, are read as
+ * plain ready frames. */
+void check_plain_ready_frames(const trystero::detail::decoding& to) {
+    namespace td = trystero::detail;
+    for (const auto* plain : {
+             R"({"ok":true})",
+             R"({"ok":false,"err":"other"})",
+             R"({"ok":"false","err":"peer banned"})",
+             R"({"err":"peer banned"})",
+             R"(["ok",false])",
+             R"("")",
+             "not json",
+         }) {
+        BOOST_TEST(!td::read_refusal(trystero::protocol::payload_format::json, plain, to));
+    }
+    const std::string_view as_text = R"({"ok":false,"err":"peer banned"})";
+    BOOST_TEST(!td::read_refusal(trystero::protocol::payload_format::text, as_text, to));
+}
+
+// A ban's refusal is read as 0.27.0's processHandshakeReady reads `{ok: false, err}`: a JSON
+// object whose `ok` is false and whose `err` is "peer banned", its reason kept when it is a text
+// of at most 512 UTF-16 code units, a character beyond the basic plane counting two; "room full"
+// is the other refusal, and anything else a plain ready frame.
+void ready_refusals_are_read_as_0_27_0_reads_them() {
+    namespace td = trystero::detail;
+    using kind = td::ready_refusal::kind;
+    auto* const memory = std::pmr::get_default_resource();
+    const td::decoding to{.memory = memory, .max_json_document_bytes = 1U << 20U};
+    const auto read = [&](std::string_view json) {
+        return td::read_refusal(trystero::protocol::payload_format::json, json, to);
+    };
+    const auto ban = [&](std::string_view reason_json) {
+        std::string json(R"({"ok":false,"err":"peer banned","reason":)");
+        json += reason_json;
+        json += '}';
+        return read(json);
+    };
+    const auto banned = read(R"({"ok":false,"err":"peer banned","reason":"spam"})");
+    if (BOOST_TEST(banned.has_value())) {
+        BOOST_TEST(banned->why == kind::banned);
+        BOOST_TEST(banned->reason == std::optional("spam"));
+    }
+    const auto full = read(R"({"ok":false,"err":"room full"})");
+    BOOST_TEST(full.has_value() && full->why == kind::room_full && !full->reason);
+    const auto bare = read(R"({"ok":false,"err":"peer banned"})");
+    BOOST_TEST(bare.has_value() && bare->why == kind::banned && !bare->reason);
+    const auto empty = ban(R"("")");
+    BOOST_TEST(empty.has_value() && empty->reason == std::optional(""));
+    const std::string at_bound = '"' + std::string(512, 'x') + '"';
+    const std::string past_bound = '"' + std::string(513, 'x') + '"';
+    // 255 emoji and two letters are 512 units; 256 emoji, 512 units; and one letter more, 513.
+    const std::string emoji_at_bound = quoted_emoji("xx", 255);
+    const std::string emoji_past_bound = quoted_emoji("x", 256);
+    for (const auto& [json, kept] : std::vector>{
+             {at_bound, true},
+             {past_bound, false},
+             {emoji_at_bound, true},
+             {emoji_past_bound, false},
+             {"7", false},
+             {"null", false},
+         }) {
+        const auto r = ban(json);
+        if (BOOST_TEST(r.has_value()) && BOOST_TEST(r->why == kind::banned)) {
+            BOOST_TEST_EQ(r->reason.has_value(), kept);
+        }
+    }
+    // A reason that ends in a lone surrogate, as a cut at 512 units leaves it, is kept, read with
+    // the replacement character in its place.
+    const auto lone = ban(R"("spam\ud83d")");
+    BOOST_TEST(lone.has_value() &&
+               lone->reason == std::optional("spam\xEF\xBF\xBD"));
+    check_plain_ready_frames(to);
+}
+
+/**
+ * A, whose id is lower, initiates the handshake with B, and B bans A: the frame of the vectors'
+ * `handshake_frames` entry `banned`, `{"ok":false,"err":"peer banned","reason":"spam"}` as 0.27.0
+ * writes it, injected byte for byte at A's end while B is pending at A, B's ready frames dropped
+ * until A's farewell. With `deferred`, it arrives before A verified B, B's step 2 held meanwhile,
+ * and waits, as 0.27.0's deferredReady, until A verifies B; otherwise A verified B and waits for
+ * B's ready frame. A reports banned once, with 0.27.0's message, the reason and B's id, B gone from
+ * it and never joined, tells B to leave, and reports no handshake_failed later. A keeps no ban, as
+ * 0.27.0 keeps none without its roles: B, told to leave, announces itself again, and the two meet
+ * and join.
+ */
+void a_ban_from_a_peer_reports_banned_when(bool deferred) {
+    counting_resource a_memory;  // first: A's connection ends are made in it
+    fixture f{true};
+    const auto labels = ordered_labels(2, "ban");
+    std::optional held_at;  // A's end, where B's step 2 waits
+    std::size_t a_leaves = 0;  // A's farewells to B, until which B's ready frames to A are dropped
+    f.net.filter = [&](std::size_t from, std::size_t to, std::span frame) {
+        if (end_in(f, from, &a_memory)) {
+            a_leaves += action_name(frame) == "@_leave" ? 1 : 0;
+            return trystero::test::memory_network::verdict::deliver;
+        }
+        if (deferred && !held_at && step_number(handshake_step(frame)) == 2) {
+            held_at = to;
+            return trystero::test::memory_network::verdict::hold;
+        }
+        return a_leaves == 0 && action_name(frame) == "@_hsready"
+                   ? trystero::test::memory_network::verdict::drop
+                   : trystero::test::memory_network::verdict::deliver;
+    };
+    auto a_config = app_config(labels[0]);
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    auto a = join(a_app, "ban");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(labels[1]));
+    auto b = join(b_app, "ban");
+    std::size_t a_joins = 0;
+    a.on_peer_join([&](const trystero::peer_event&) { ++a_joins; });
+    std::vector a_reports;
+    // A's joins and peers when it reports the ban, before B hears A's farewell and comes back.
+    std::optional> at_ban;
+    a.on_error([&, record = record_all_errors(f, a_reports)](const trystero::room_error& e) {
+        record(e);
+        at_ban.emplace(a_joins, a.peers().size());
+    });
+    const auto ban = recorded_handshake_frame("banned");
+    if (deferred) {
+        webcpp::test::require(BOOST_TEST(run_until(f, [&] { return held_at.has_value(); })));
+        f.net.inject(*held_at, ban);
+        trystero::test::advance(f, 100ms);
+        BOOST_TEST(a_reports.empty());  // A has not verified B: the ban waits
+        f.net.release(*held_at);
+    } else {
+        // B verified A once it is active: A, which verified B before its step 3, waits for B's
+        // ready frame.
+        webcpp::test::require(BOOST_TEST(run_until(f, [&] { return b.peers().size() == 1; })));
+        f.net.inject(open_end_in(f, &a_memory), ban);
+    }
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return at_ban.has_value() && a_leaves == 1; })));
+    BOOST_TEST_EQ(at_ban->first, 0U);
+    BOOST_TEST_EQ(at_ban->second, 0U);
+    // Past the handshake's 10 s: the failed run reports nothing, and B's announcements meet A
+    // again.
+    trystero::test::advance(f, 15'000ms);
+    if (BOOST_TEST_EQ(a_reports.size(), 1U)) {
+        const auto& e = a_reports.front();
+        BOOST_TEST_EQ(trystero::room_error_code_name(e.code), "banned");
+        BOOST_TEST_EQ(e.message, "peer banned: spam");
+        BOOST_TEST_EQ(e.reason, "spam");
+        BOOST_TEST_EQ(e.peer_id, b_app.self_id());
+        BOOST_TEST_EQ(e.room_id, "ban");
+    }
+    BOOST_TEST_EQ(a_leaves, 1U);
+    BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1; }));
+}
+
+void a_ban_from_a_peer_reports_banned() {
+    a_ban_from_a_peer_reports_banned_when(false);
+    a_ban_from_a_peer_reports_banned_when(true);
+}
+
+// A frame that breaks the protocol is reported for a pending peer too, as 0.27.0's hasAnyPeer
+// takes either kind: B's step 2 is held, so A holds B as pending, and a frame of an unknown
+// version injected there is reported as peer_error with B's id, B told to leave.
+void a_pending_peer_breaking_the_protocol_reports_peer_error() {
+    counting_resource a_memory;  // first: A's connection ends are made in it
+    fixture f{true};
+    const auto labels = ordered_labels(2, "pending");
+    std::optional held_at;  // A's end, where B's step 2 waits
+    std::size_t a_leaves = 0;
+    f.net.filter = [&](std::size_t from, std::size_t to, std::span frame) {
+        if (end_in(f, from, &a_memory)) {
+            a_leaves += action_name(frame) == "@_leave" ? 1 : 0;
+            return trystero::test::memory_network::verdict::deliver;
+        }
+        if (!held_at && step_number(handshake_step(frame)) == 2) {
+            held_at = to;
+            return trystero::test::memory_network::verdict::hold;
+        }
+        return trystero::test::memory_network::verdict::deliver;
+    };
+    auto a_config = app_config(labels[0]);
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    auto a = join(a_app, "pending");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config(labels[1]));
+    const auto b = join(b_app, "pending");
+    std::vector reports;
+    a.on_error(record_all_errors(f, reports));
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return held_at.has_value(); })));
+    BOOST_TEST_EQ(a.peers().size(), 0U);
+    f.net.inject(*held_at, std::vector{7, 0});
+    BOOST_TEST(run_until(f, [&] { return !reports.empty() && a_leaves == 1; }));
+    if (BOOST_TEST_EQ(reports.size(), 1U)) {
+        BOOST_TEST_EQ(trystero::room_error_code_name(reports[0].code), "peer-error");
+        BOOST_TEST_EQ(reports[0].message, "incompatible action protocol version");
+        BOOST_TEST_EQ(reports[0].peer_id, b_app.self_id());
+    }
+}
+
+// A ban frame from an active peer is ignored, as 0.27.0's processHandshakeReady ignores a refusal
+// from a peer that is not still being verified: nothing is reported and the peer stays.
+void a_ban_from_an_active_peer_is_ignored() {
+    counting_resource a_memory;  // first: A's connection ends are made in it
+    fixture f{true};
+    auto a_config = app_config("activeBanAAAAAAAAAAA");
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    auto a = join(a_app, "activeban");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("activeBanBBBBBBBBBBB"));
+    auto b = join(b_app, "activeban");
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })));
+    std::vector reports;
+    a.on_error(record_all_errors(f, reports));
+    f.net.inject(open_end_in(f, &a_memory), recorded_handshake_frame("banned"));
+    trystero::test::advance(f, 15'000ms);
+    BOOST_TEST(reports.empty());
+    BOOST_TEST_EQ(a.peers().size(), 1U);
+    BOOST_TEST_EQ(b.peers().size(), 1U);
+}
+
+// A ping that gets no answer fails when the room is left, with room_left, and when the peer goes,
+// with peer_disconnected, as 0.27.0's request fails (the room left by its destruction, as a
+// request's test explains); and a `@_ping` whose metadata names no
+// request is dropped, as 0.27.0 drops a request it cannot read: no answer, the peer stays.
+void a_ping_fails_when_the_room_or_the_peer_goes() {
+    namespace tp = trystero::protocol;
+    counting_resource a_memory;  // first: A's connection ends are made in it
+    fixture f{true};
+    bool silent = false;  // B's answers are dropped
+    std::size_t a_answers = 0;
+    f.net.filter = [&](std::size_t from, std::size_t, std::span frame) {
+        const bool from_a = end_in(f, from, &a_memory);
+        a_answers += from_a && action_name(frame) == "@_response" ? 1 : 0;
+        return silent && !from_a && action_name(frame) == "@_response"
+                   ? trystero::test::memory_network::verdict::drop
+                   : trystero::test::memory_network::verdict::deliver;
+    };
+    auto a_config = app_config("pingFailAAAAAAAAAAA");
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    std::optional a(join(a_app, "pingfail"));
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("pingFailBBBBBBBBBBB"));
+    auto b = join(b_app, "pingfail");
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a->peers().size() == 1 && b.peers().size() == 1; })));
+    const std::string_view unreadable = "not json";
+    f.net.inject(open_end_in(f, &a_memory),
+                 tp::encode_inline("@_ping", tp::payload_format::text, unreadable, {}));
+    trystero::test::advance(f, 1000ms);
+    BOOST_TEST_EQ(a_answers, 0U);
+    BOOST_TEST_EQ(a->peers().size(), 1U);
+
+    silent = true;
+    std::optional gone;
+    a->async_ping(b.self_id(),
+                  [&](boost::system::error_code ec, std::chrono::milliseconds) { gone = ec; });
+    trystero::test::advance(f, 1000ms);
+    BOOST_TEST(!gone.has_value());
+    bool b_left = false;
+    b.async_leave([&](boost::system::error_code ec) { b_left = !ec; });
+    BOOST_TEST(run_until(f, [&] { return gone.has_value(); }));
+    BOOST_TEST(*gone == trystero::error::peer_disconnected);
+    BOOST_TEST(run_until(f, [&] { return b_left; }));
+
+    trystero::test::app c_app(f.io.get_executor(), f.net, app_config("pingFailCCCCCCCCCCC"));
+    const auto c = join(c_app, "pingfail");
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return a->peers().size() == 1; })));
+    std::optional left;
+    a->async_ping(c.self_id(),
+                  [&](boost::system::error_code ec, std::chrono::milliseconds) { left = ec; });
+    trystero::test::advance(f, 1000ms);
+    BOOST_TEST(!left.has_value());
+    a.reset();  // the room is left at once by its destruction, as a request's test explains
+    BOOST_TEST(run_until(f, [&] { return left.has_value(); }));
+    BOOST_TEST(*left == trystero::error::room_left);
+}
+
+// Every relay opens but takes no event, its socket's writes failing: no relay's first announcement
+// is written, so the room reports relay_failed once, as 0.27.0's queueAnnounce reports it, though
+// the cadence goes on announcing. One relay that never opens and one whose first announcement
+// fails are reported once too. A relay whose first announcement was written keeps the room from
+// reporting it.
+void relay_failed_when_no_first_announcement_succeeds() {
+    {
+        fixture f{true};
+        f.net.fail_publish(relay_a);
+        f.net.fail_publish(relay_b);
+        trystero::test::app a_app(f.io.get_executor(), f.net, app_config("silentAAAAAAAAAAAAAA"));
+        auto a = join(a_app, "silent");
+        std::vector reports;
+        a.on_error(record_all_errors(f, reports));
+        webcpp::test::require(BOOST_TEST(run_until(f, [&] { return !reports.empty(); })));
+        trystero::test::advance(f, 3min);
+        if (BOOST_TEST_EQ(reports.size(), 1U)) {
+            BOOST_TEST_EQ(trystero::room_error_code_name(reports[0].code), "relay-failed");
+            // The failure's text, as 0.27.0's toErrorMessage(cause, ...); the constant is only
+            // for a failure with no text, a relay that never opened.
+            BOOST_TEST_EQ(reports[0].message, "the relay's connection cannot take the event");
+            BOOST_TEST_EQ(reports[0].app_id, app_id);
+            BOOST_TEST_EQ(reports[0].room_id, "silent");
+            BOOST_TEST(reports[0].peer_id.empty());
+        }
+    }
+    {
+        // Relay A's first connection closes before relay B opens: relay B's failed first
+        // announcement settles the last relay.
+        fixture f{true};
+        f.net.make_unreachable(relay_a);
+        f.net.fail_publish(relay_b);
+        trystero::test::app a_app(f.io.get_executor(), f.net, app_config("silentAAAAAAAAAAAAAA"));
+        auto a = join(a_app, "mixed");
+        std::vector reports;
+        a.on_error(record_all_errors(f, reports));
+        webcpp::test::require(BOOST_TEST(run_until(f, [&] { return !reports.empty(); })));
+        trystero::test::advance(f, 3min);
+        if (BOOST_TEST_EQ(reports.size(), 1U)) {
+            BOOST_TEST_EQ(trystero::room_error_code_name(reports[0].code), "relay-failed");
+            BOOST_TEST_EQ(reports[0].message, "the relay's connection cannot take the event");
+        }
+    }
+    {
+        fixture f{true};
+        f.net.fail_publish(relay_a);
+        trystero::test::app a_app(f.io.get_executor(), f.net, app_config("silentAAAAAAAAAAAAAA"));
+        auto a = join(a_app, "heard");
+        std::size_t reports = 0;
+        a.on_error([&](const trystero::room_error&) { ++reports; });
+        trystero::test::advance(f, 3min);
+        BOOST_TEST_EQ(reports, 0U);
+    }
+}
+
+// A ping is 0.27.0's internal request action `@_ping` (the vectors' `ping_frames`): A sends B the
+// request, an empty text whose metadata names it, and B answers through `@_response` with an
+// empty text under the same metadata, each frame 0.27.0's byte for byte but for the request's
+// random id; async_ping completes with the round trip, on the virtual clock 0 ms. A user's id
+// pings its peer; a target that is not active fails with no_such_peer.
+void ping_is_a_request_action() {
+    namespace tp = trystero::protocol;
+    counting_resource a_memory;  // first: A's connection ends are made in it
+    fixture f{true};
+    std::vector a_frames;  // A's frames of `@_ping`, in hexadecimal
+    std::vector b_frames;  // B's frames of `@_response`, in hexadecimal
+    std::size_t pongs = 0;
+    f.net.filter = [&](std::size_t from, std::size_t, std::span frame) {
+        const auto name = action_name(frame);
+        if (name == "@_ping" && end_in(f, from, &a_memory)) {
+            a_frames.push_back(hex_of(frame));
+        } else if (name == "@_response" && !end_in(f, from, &a_memory)) {
+            b_frames.push_back(hex_of(frame));
+        }
+        pongs += name == "@_pong" ? 1 : 0;
+        return trystero::test::memory_network::verdict::deliver;
+    };
+    auto a_config = app_config("pingAAAAAAAAAAAAAAAA");
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    auto a = join(a_app, "ping");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("pingBBBBBBBBBBBBBBBB"));
+    const auto b = join(b_app, "ping");
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })));
+    std::optional> result;
+    a.async_ping(b.self_id(), [&](boost::system::error_code ec, std::chrono::milliseconds rtt) {
+        result.emplace(ec, rtt);
+    });
+    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return result.has_value(); })));
+    BOOST_TEST(!result->first);
+    BOOST_TEST_EQ(result->second.count(), 0);
+    webcpp::test::require(BOOST_TEST_EQ(a_frames.size(), 1U));
+    webcpp::test::require(BOOST_TEST_EQ(b_frames.size(), 1U));
+    BOOST_TEST_EQ(pongs, 0U);
+
+    // The request's id is the one random part: written as 0.27.0's in the recorded frames, each
+    // port frame equals its recorded one.
+    webcpp::test::require(BOOST_TEST(vectors().has_value()));
+    const auto recorded = vectors()->root()["ping_frames"];
+    const std::string recorded_id(recorded["request_id"].value_or(std::string_view()));
+    const auto request_bytes = bytes_of_hex(a_frames[0]);
+    const auto request = tp::decode_action(request_bytes);
+    const auto* p = request.frame ? std::get_if(&*request.frame) : nullptr;
+    webcpp::test::require(BOOST_TEST(p != nullptr));
+    const auto metadata = std::string(p->metadata);
+    // The texts are named outside the test macros, whose arguments MSVC's preprocessor misreads
+    // with these raw literals in them.
+    const std::string_view head = R"({"r":")";
+    webcpp::test::require(BOOST_TEST(metadata.starts_with(head)));
+    const std::string id = metadata.substr(head.size(), recorded_id.size());
+    const std::string expected_metadata = std::string(head) + id + "\"}";
+    BOOST_TEST_EQ(metadata, expected_metadata);
+    const auto as_recorded = [&](std::string frame) {
+        const auto at = frame.find(
+            hex_of(std::span(reinterpret_cast(id.data()), id.size())));
+        webcpp::test::require(BOOST_TEST(at != std::string::npos));
+        return frame.replace(
+            at, id.size() * 2,
+            hex_of(std::span(reinterpret_cast(recorded_id.data()),
+                             recorded_id.size())));
+    };
+    const auto frames = recorded["frames"];
+    BOOST_TEST_EQ(frames.at(0)["from"].value_or(std::string_view()), "A");
+    BOOST_TEST_EQ(as_recorded(a_frames[0]), frames.at(0)["hex"].value_or(std::string_view()));
+    BOOST_TEST_EQ(frames.at(1)["from"].value_or(std::string_view()), "B");
+    BOOST_TEST_EQ(as_recorded(b_frames[0]), frames.at(1)["hex"].value_or(std::string_view()));
+
+    std::optional by_user;
+    a.async_ping(b_app.user_id(),
+                 [&](boost::system::error_code ec, std::chrono::milliseconds) { by_user = ec; });
+    BOOST_TEST(run_until(f, [&] { return by_user.has_value(); }));
+    BOOST_TEST(!*by_user);
+    std::optional missing;
+    a.async_ping("nobody",
+                 [&](boost::system::error_code ec, std::chrono::milliseconds) { missing = ec; });
+    BOOST_TEST(run_until(f, [&] { return missing.has_value(); }));
+    BOOST_TEST(*missing == trystero::error::no_such_peer);
+}
+
+// An offer of `@_response` that answers no request of A's sent to its sender is rejected with
+// 0.27.0's "unexpected response" (its resolveAdmission): one naming no request, one naming no
+// request of A's, and one without metadata. B stays, and nothing is reported. An answer of a
+// request of A's that comes as a transfer, B's 100 KB, is taken.
+void an_unexpected_response_offer_is_rejected() {
+    namespace tp = trystero::protocol;
+    counting_resource a_memory;  // first: A's connection ends are made in it
+    fixture f{true};
+    std::map> from_a;  // by transfer id
+    f.net.filter = [&](std::size_t from, std::size_t, std::span frame) {
+        if (end_in(f, from, &a_memory)) {
+            const auto decoded = tp::decode_action(frame);
+            if (const auto* m =
+                    decoded.frame ? std::get_if(&*decoded.frame) : nullptr) {
+                from_a.insert_or_assign(m->id, std::pair(m->kind, std::string(m->reason)));
+            }
+        }
+        return trystero::test::memory_network::verdict::deliver;
+    };
+    auto a_config = app_config("unexpectedAAAAAAAAAA");
+    a_config.memory = &a_memory;
+    trystero::test::app a_app(f.io.get_executor(), f.net, std::move(a_config));
+    auto a = join(a_app, "unexpected");
+    trystero::test::app b_app(f.io.get_executor(), f.net, app_config("unexpectedBBBBBBBBBB"));
+    auto b = join(b_app, "unexpected");
+    webcpp::test::require(
+        BOOST_TEST(run_until(f, [&] { return a.peers().size() == 1 && b.peers().size() == 1; })));
+    std::vector reports;
+    a.on_error(record_all_errors(f, reports));
+    const auto a_end = open_end_in(f, &a_memory);
+    const std::array metadata{
+        R"({"r":"0b1c2d3e-4f50-4617-8899-aabbccddeeff"})",
+        R"({"x":1})",
+        "",
+    };
+    for (std::uint32_t id = 0; id < metadata.size(); ++id) {
+        f.net.inject(a_end, tp::encode_offer("@_response", tp::payload_format::binary,
+                                             metadata.at(id), id, 100'000));
+    }
+    BOOST_TEST(run_until(f, [&] { return from_a.size() == metadata.size(); }));
+    for (std::uint32_t id = 0; id < metadata.size(); ++id) {
+        if (BOOST_TEST(from_a.contains(id))) {
+            BOOST_TEST(from_a.at(id).first == tp::frame_kind::rejected);
+            BOOST_TEST_EQ(from_a.at(id).second, "unexpected response");
+        }
+    }
+    const std::string big(100'000, 'x');
+    const auto answering = b.make_request_action("big").on_request(
+        [&](const std::string&,
+            const trystero::message_info&) -> boost::system::result { return big; });
+    BOOST_TEST(answering.has_value());
+    std::optional> answered;
+    a.make_request_action("big").async_request(
+        "q", trystero::request_options{.target = trystero::peer_id(b.self_id())},
+        [&](boost::system::error_code ec, std::string r) { answered.emplace(ec, std::move(r)); });
+    BOOST_TEST(run_until(f, [&] { return answered.has_value(); }));
+    BOOST_TEST(!answered->first);
+    BOOST_TEST(answered->second == big);
+    trystero::test::advance(f, 1000ms);
+    BOOST_TEST_EQ(a.peers().size(), 1U);
+    BOOST_TEST(reports.empty());
+}
+
+void the_errors_have_their_values() {
+    // wrong_password and handshake_timed_out went with 0.26.0's password handshake: a handshake's
+    // failures are handshake_failed, as 0.27.0 reports them.
+    BOOST_TEST_EQ(static_cast(trystero::error::handshake_failed), 9);
+    BOOST_TEST_EQ(static_cast(trystero::error::already_joined), 12);
+    BOOST_TEST_EQ(make_error_code(trystero::error::already_joined).message(),
+                  "the app has already joined a room of that id");
+    BOOST_TEST_EQ(make_error_code(trystero::error::invalid_configuration).message(),
+                  "the configuration is unusable");
+    // After already_joined, in 0.27.0's order of room errors, with its messages: too_many_rooms,
+    // which went with the shared connection, no longer comes between.
+    BOOST_TEST_EQ(static_cast(trystero::error::room_full), 13);
+    BOOST_TEST_EQ(static_cast(trystero::error::request_timed_out), 25);
+    BOOST_TEST_EQ(make_error_code(trystero::error::room_full).message(), "room full");
+    BOOST_TEST_EQ(make_error_code(trystero::error::banned).message(), "peer banned");
+    BOOST_TEST_EQ(make_error_code(trystero::error::decrypt_failed).message(),
+                  "failed to decrypt offer or answer (incorrect password or corrupted signal)");
+    BOOST_TEST_EQ(make_error_code(trystero::error::action_aborted).message(), "operation aborted");
+    // Appended after them: 0.27.0 throws it.
+    BOOST_TEST_EQ(static_cast(trystero::error::action_redefined), 26);
+    BOOST_TEST_EQ(make_error_code(trystero::error::action_redefined).message(),
+                  "action type cannot be redefined");
+    BOOST_TEST_EQ(static_cast(trystero::error::invalid_user_identity), 27);
+    BOOST_TEST_EQ(make_error_code(trystero::error::invalid_user_identity).message(),
+                  "invalid user identity key material; expected exported userKey or P-256 JWK");
+    BOOST_TEST_EQ(static_cast(trystero::error::invalid_max_users), 28);
+}
+
+}  // namespace
+
+int main(int argc, char* argv[]) {
+    if (!BOOST_TEST_EQ(argc, 2)) {
+        BOOST_LIGHTWEIGHT_TEST_OSTREAM
+            << "usage: room_test \n";
+        return webcpp::test::exit_status(boost::report_errors());
+    }
+    {
+        const std::ifstream file(argv[1]);
+        std::stringstream text;
+        text << file.rdbuf();
+        auto loaded = webcpp::document::parse(text.str());
+        if (!BOOST_TEST(loaded.has_value())) {
+            return webcpp::test::exit_status(boost::report_errors());
+        }
+        vectors().emplace(std::move(*loaded));
+    }
     // Some forty cases of two or three apps each: under Asyncify a debug build takes 54 s of the
     // processor, more than a third of node's default bound of 120 s, and 74 to 168 s on a loaded
     // machine, past it (measured on 2026-11-15 with 18 cores at load averages of 50 to 230; under
@@ -1926,8 +5856,38 @@ int main() {
     run_case(a_json_payload_nested_256_deep_is_delivered);
     run_case(two_peers_join_and_exchange_every_payload_format);
     run_case(large_payloads_travel_in_chunks_both_ways);
-    run_case(ping_measures_a_round_trip);
-    run_case(the_same_password_joins_and_another_does_not);
+    run_case(a_wide_transfer_arrives_in_wide_chunks_in_any_order);
+    run_case(a_wide_link_sends_wide_chunks);
+    run_case(a_refused_chunk_ends_the_transfer_with_the_peer);
+    run_case(a_narrow_link_sends_narrow_chunks);
+    run_case(the_wire_keeps_0_27_0s_bounds);
+    run_case(frames_of_an_action_not_made_are_dropped_or_rejected);
+    run_case(an_inline_frame_above_the_receive_bound_is_dropped);
+    run_case(a_control_frame_into_a_full_channel_drops_the_peer);
+    run_case(two_passwords_never_meet);
+    run_case(a_handshake_that_never_completes_fails_after_10_s);
+    run_case(ready_frames_carry_an_empty_text);
+    run_case(sends_inside_on_peer_join_follow_the_ready_frame);
+    run_case(handshake_messages_keep_0_27_0s_bounds);
+    run_case(peers_verify_each_other_and_join_with_their_user_ids);
+    run_case(a_forged_step_fails_the_handshake);
+    run_case(another_fingerprint_fails_the_handshake);
+    run_case(leaving_during_a_handshake_reports_nothing);
+    run_case(leaving_after_one_side_verified_reports_nothing);
+    run_case(a_full_room_refuses_a_new_user);
+    run_case(another_peer_of_a_present_user_is_admitted);
+    run_case(concurrent_admissions_respect_the_limit);
+    run_case(a_refused_user_is_not_dialed_again);
+    run_case(a_connection_refused_at_its_open_lets_the_peer_back);
+    run_case(a_refusal_waits_for_the_peers_verification);
+    run_case(a_refusal_survives_the_close);
+    run_case(a_refused_link_ends_after_its_grace);
+    run_case(max_users_zero_is_refused);
+    run_case(password_room_keys_complete_after_the_join_returns);
+    run_case(rooms_of_one_password_derive_once_per_room);
+    run_case(a_failed_derivation_is_retried);
+    run_case(a_room_left_while_its_keys_derive_announces_nothing);
+    run_case(the_room_keys_cache_keeps_64_rooms);
     run_case(leaving_is_seen_by_the_others_and_a_return_reconnects);
     run_case(moving_a_room_over_a_joined_one_leaves_it);
     run_case(ice_urls_are_checked_as_webrtc_checks_them);
@@ -1938,10 +5898,9 @@ int main() {
     run_case(a_refused_peer_is_logged_once);
     run_case(a_forged_answer_changes_nothing);
     run_case(forged_offers_make_no_connection);
-    run_case(an_offer_being_opened_keeps_its_place);
     run_case(a_flood_of_offers_at_one_instant_is_bounded);
-    run_case(offers_in_one_name_are_opened_one_at_a_time);
-    run_case(signals_that_do_not_open_are_reported_once_per_interval);
+    run_case(offers_in_one_name_are_answered_one_at_a_time);
+    run_case(signals_that_do_not_open_are_reported_once_per_peer_and_stage);
     run_case(sealed_offers_that_fail_at_once_are_bounded);
     run_case(announcements_with_forged_answers_are_bounded);
     run_case(the_replay_cache_remembers_the_last_ones);
@@ -1950,28 +5909,73 @@ int main() {
     run_case(the_event_id_hash_is_keyed);
     run_case(a_strategy_draws_the_key_of_its_event_ids);
     run_case(a_forged_event_under_a_genuine_id_hides_nothing);
+    run_case(each_room_signs_with_its_own_key);
+    run_case(a_room_subscribes_its_self_topic_before_its_root_topic);
     run_case(classes_over_a_pmr_circular_buffer_do_not_move);
-    run_case(a_replayed_answer_is_refused);
+    run_case(a_replayed_answer_does_not_open);
     run_case(a_replayed_offer_is_refused);
     run_case(a_reflected_offer_is_refused_as_an_answer);
     run_case(a_reflected_offer_is_refused_as_an_offer);
-    run_case(a_reflected_answer_is_refused_as_an_answer);
+    run_case(a_reflected_answer_does_not_open_as_an_answer);
     run_case(a_relay_that_closes_at_once_is_tried_less_and_less_often);
     run_case(counter_announcements_are_paced);
     run_case(three_peers_form_a_mesh);
+    run_case(rooms_of_one_app_have_their_own_connections);
+    run_case(a_room_keeps_one_connection_per_peer);
+    run_case(a_leaving_room_negotiates_nothing);
+    run_case(leaving_one_room_keeps_the_other_rooms_connection);
+    run_case(frames_travel_bare);
+    run_case(an_app_joins_more_than_64_rooms);
     run_case(async_receive_works_in_a_coroutine);
     run_case(json_payloads_are_read_in_the_rooms_resource_up_to_its_bound);
     run_case(a_rejected_document_receive_holds_nothing);
     run_case(view_handlers_read_the_frame_without_copying);
     run_case(a_rate_limited_relay_does_not_stop_discovery);
-    run_case(a_connections_end_is_seen_and_the_peers_meet_again);
-    run_case(a_frame_of_an_unknown_token_is_dropped);
-    run_case(malformed_envelopes_end_the_connection);
-    run_case(a_late_end_of_another_connection_keeps_the_peer);
-    run_case(a_withdrawn_presence_is_a_departure);
-    run_case(a_kick_by_the_last_room_ends_the_connection);
-    run_case(a_room_left_with_no_idle_time_sends_its_presence);
+    run_case(replay_reports_current_peers);
+    run_case(second_on_request_is_refused);
+    run_case(a_request_is_answered_or_refused);
+    run_case(messages_wait_for_a_listener);
+    run_case(a_receive_gate_decides_and_progress_is_reported);
+    run_case(a_listener_may_end_its_room_while_it_is_reported);
+    run_case(a_subscription_outlives_its_room);
+    run_case(a_join_posted_before_the_leave_is_not_reported);
+    run_case(a_gate_may_end_its_room_while_waiting_messages_are_delivered);
+    run_case(leaves_are_reported_peer_then_user);
+    run_case(send_to_a_user_reaches_each_of_its_peers);
+    run_case(a_user_leaves_with_its_last_peer);
+    run_case(a_peer_of_its_own_user_is_no_other_user);
+    run_case(send_to_an_absent_target_fails);
+    run_case(self_names_the_room);
+    run_case(an_apps_ids_derive_from_its_keys);
+    run_case(two_apps_of_one_imported_identity_share_a_user_id);
+    run_case(self_reports_the_identity);
+    run_case(an_endpoint_that_cannot_be_made_reports_identity_failed);
+    run_case(a_user_key_that_cannot_be_made_reports_identity_failed);
+    run_case(a_request_is_refused_by_a_gone_listener_or_the_gate);
+    run_case(a_request_fails_when_its_peer_or_its_room_goes);
+    run_case(an_action_name_keeps_its_first_kind);
     run_case(the_errors_have_their_values);
+    run_case(decrypt_failed_is_reported_once_a_minute);
+    run_case(relay_failed_when_every_relay_fails);
+    run_case(relay_failed_when_no_first_announcement_succeeds);
+    run_case(a_protocol_violation_reports_peer_error);
+    run_case(ready_refusals_are_read_as_0_27_0_reads_them);
+    run_case(a_ban_from_a_peer_reports_banned);
+    run_case(a_pending_peer_breaking_the_protocol_reports_peer_error);
+    run_case(a_ban_from_an_active_peer_is_ignored);
+    run_case(a_ping_fails_when_the_room_or_the_peer_goes);
+    run_case(ping_is_a_request_action);
+    run_case(an_unexpected_response_offer_is_rejected);
+    run_case(peer_connect_failed_says_whether_turn_was_configured);
+    run_case(error_names_match_trystero);
+    run_case(messages_waiting_at_a_leave_are_dropped);
+    run_case(a_message_posted_before_the_room_ended_is_dropped);
+    run_case(offline_holds_and_online_reconnects);
+    run_case(offline_holds_a_relay_waiting_to_reconnect);
+    run_case(online_reconnects_a_backoff_relay_at_once);
+    run_case(online_while_online_leaves_connected_relays_alone);
+    run_case(automatic_is_online_natively);
+    run_case(automatic_follows_the_pages_events);
     // Under Asyncify, a main that suspended loses what it returns: the status goes first.
     return webcpp::test::exit_status(boost::report_errors());
 }
diff --git a/test/shared_test.cpp b/test/shared_test.cpp
deleted file mode 100644
index 3a3bba1..0000000
--- a/test/shared_test.cpp
+++ /dev/null
@@ -1,2073 +0,0 @@
-// Copyright (c) 2026 WebCpp.org
-//
-// Distributed under the Boost Software License, Version 1.0. (See
-// accompanying file LICENSE_1_0.txt or copy at
-// https://www.boost.org/LICENSE_1_0.txt)
-
-// Rooms of one app sharing one connection per remote peer, over the memory backend, on its virtual
-// clock (doc: #trystero-design-sharing).
-
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#include "support/memory_backend.hpp"
-#include "support/rooms.hpp"
-
-#include 
-
-#include 
-#include 
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#include "require.hpp"
-
-namespace trystero = webcpp::trystero;
-using namespace webcpp::trystero::test;
-using namespace std::chrono_literals;
-
-namespace {
-
-// Every room reports the app's id; an over-long one is replaced, and it and a negative idle time
-// are reported to the app's handler, set after the app is made, once each.
-void every_room_has_the_apps_id() {
-    fixture f{true};
-    trystero::app a(f.io.get_executor(), f.net, app_config("AAAAAAAAAAAAAAAAAAAA"));
-    const auto r1 = join(a, "r1");
-    const auto r2 = join(a, "r2");
-    BOOST_TEST_EQ(r1.self_id(), "AAAAAAAAAAAAAAAAAAAA");
-    BOOST_TEST_EQ(r2.self_id(), a.self_id());
-    auto long_id = app_config(std::string(65, 'x'));
-    long_id.idle_timeout = -1ms;
-    std::vector> reports;
-    trystero::app b(f.io.get_executor(), f.net, std::move(long_id));
-    b.on_error([&](std::string_view peer, boost::system::error_code ec, std::string_view what) {
-        BOOST_TEST(peer.empty());
-        reports.emplace_back(ec, what);
-    });
-    BOOST_TEST_EQ(b.self_id().size(), trystero::protocol::peer_id_size);
-    BOOST_TEST(run_until(f, [&] { return reports.size() == 2; }));
-    webcpp::trystero::test::advance(f, 100ms);
-    webcpp::test::require(BOOST_TEST_EQ(reports.size(), 2U));
-    for (const auto& [ec, what] : reports) {
-        BOOST_TEST(ec == trystero::error::invalid_configuration);
-    }
-    BOOST_TEST(reports[0].second.starts_with("self_id "));
-    BOOST_TEST(reports[1].second.starts_with("idle_timeout "));
-}
-
-// A report reaches only the handler set when it is delivered, and each is delivered once: a handler
-// replaced before the delivery gets none, and one set after it gets none again.
-void each_setup_report_reaches_the_current_handler_once() {
-    fixture f{true};
-    auto long_id = app_config(std::string(65, 'x'));
-    long_id.idle_timeout = -1ms;
-    trystero::app b(f.io.get_executor(), f.net, std::move(long_id));
-    std::array calls{};
-    b.on_error([&](std::string_view, boost::system::error_code, std::string_view) { ++calls[0]; });
-    b.on_error([&](std::string_view, boost::system::error_code, std::string_view) { ++calls[1]; });
-    webcpp::trystero::test::advance(f, 100ms);
-    b.on_error([&](std::string_view, boost::system::error_code, std::string_view) { ++calls[2]; });
-    webcpp::trystero::test::advance(f, 100ms);
-    BOOST_TEST_EQ(calls[0], 0U);
-    BOOST_TEST_EQ(calls[1], 2U);
-    BOOST_TEST_EQ(calls[2], 0U);
-}
-
-// A room joined twice is refused while it is joined, and so is a 65th room.
-void joining_is_refused_twice_and_beyond_64() {
-    fixture f{true};
-    trystero::app a(f.io.get_executor(), f.net, app_config("BBBBBBBBBBBBBBBBBBBB"));
-    const auto r = join(a, "r");
-    const auto again = a.join("r");
-    BOOST_TEST(!again && again.error() == trystero::error::already_joined);
-    std::vector rooms;
-    for (std::size_t i = 1; i < 64; ++i) {
-        rooms.push_back(join(a, "x" + std::to_string(i)));
-    }
-    const auto too_many = a.join("x64");
-    BOOST_TEST(!too_many && too_many.error() == trystero::error::too_many_rooms);
-}
-
-// Two apps of one app id with the same self id never meet, and nothing loops.
-void two_apps_with_one_id_never_meet() {
-    fixture f{true};
-    trystero::app a(f.io.get_executor(), f.net, app_config("CCCCCCCCCCCCCCCCCCCC"));
-    trystero::app b(f.io.get_executor(), f.net, app_config("CCCCCCCCCCCCCCCCCCCC"));
-    const auto ra = join(a, "same");
-    const auto rb = join(b, "same");
-    webcpp::trystero::test::advance(f, 2000ms);
-    BOOST_TEST(ra.peers().empty() && rb.peers().empty());
-    BOOST_TEST_EQ(f.net.made_connections, 0U);
-}
-
-/** Two apps, A and B, on the virtual clock, and their rooms. */
-struct two_apps {
-    fixture f{true};
-    trystero::app a;
-    trystero::app b;
-    std::vector a_rooms;
-    std::vector b_rooms;
-
-    two_apps(std::string_view a_id, std::string_view b_id, std::string_view password = {})
-        : a(f.io.get_executor(), f.net, app_config(a_id, password)),
-          b(f.io.get_executor(), f.net, app_config(b_id, password)) {}
-
-    ~two_apps() {
-        // Observers often capture locals declared after this fixture; room teardown still sends.
-        f.net.filter = {};
-        f.net.on_made = {};
-    }
-
-    [[nodiscard]] bool all_joined() const {
-        const auto one = [](const trystero::room& r) { return r.peers().size() == 1; };
-        return std::ranges::all_of(a_rooms, one) && std::ranges::all_of(b_rooms, one);
-    }
-};
-
-/** Joins A and B to each room given, in that order, and waits until every room of both has the
- * other. */
-void joined_in(two_apps& t, std::initializer_list rooms) {
-    for (const auto* id : rooms) {
-        t.a_rooms.push_back(join(t.a, id));
-        t.b_rooms.push_back(join(t.b, id));
-    }
-    webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); })));
-}
-
-// Two rooms, one connection; each room's action of one name reaches only its room, both ways.
-void two_rooms_share_one_connection() {
-    two_apps t("DDDDDDDDDDDDDDDDDDDD", "EEEEEEEEEEEEEEEEEEEE");
-    joined_in(t, {"r1", "r2"});
-    BOOST_TEST(run_until(t.f, [&] { return t.f.net.live_connections() == 2U; }));  // one pair
-    std::array, 2> at_b;
-    std::array, 2> at_a;
-    std::vector> actions;
-    for (std::size_t i = 0; i < 2; ++i) {
-        actions.push_back(t.b_rooms[i].make_action("chat"));
-        actions.back().on_message([&at_b, i](std::string s, const trystero::message_info&) {
-            at_b[i].push_back(std::move(s));
-        });
-        actions.push_back(t.a_rooms[i].make_action("chat"));
-        actions.back().on_message([&at_a, i](std::string s, const trystero::message_info&) {
-            at_a[i].push_back(std::move(s));
-        });
-    }
-    t.a_rooms[0].make_action("chat").async_send("a1",
-                                                             [](boost::system::error_code) {});
-    t.a_rooms[1].make_action("chat").async_send("a2",
-                                                             [](boost::system::error_code) {});
-    t.b_rooms[0].make_action("chat").async_send("b1",
-                                                             [](boost::system::error_code) {});
-    t.b_rooms[1].make_action("chat").async_send("b2",
-                                                             [](boost::system::error_code) {});
-    BOOST_TEST(run_until(t.f, [&] {
-        return at_b[0].size() == 1 && at_b[1].size() == 1 && at_a[0].size() == 1 &&
-               at_a[1].size() == 1;
-    }));
-    BOOST_TEST(at_b[0].at(0) == "a1" && at_b[1].at(0) == "a2");
-    BOOST_TEST(at_a[0].at(0) == "b1" && at_a[1].at(0) == "b2");
-}
-
-// Three rooms, joined in another order on each side, one connection.
-void three_rooms_share_one_connection() {
-    two_apps t("FFFFFFFFFFFFFFFFFFFF", "GGGGGGGGGGGGGGGGGGGG");
-    for (const auto* id : {"r1", "r2", "r3"}) {
-        t.a_rooms.push_back(join(t.a, id));
-    }
-    for (const auto* id : {"r3", "r1", "r2"}) {
-        t.b_rooms.push_back(join(t.b, id));
-    }
-    BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }));
-    BOOST_TEST(run_until(t.f, [&] { return t.f.net.live_connections() == 2U; }));
-}
-
-// Both rooms negotiate at once; one connection stays, both rooms join over it.
-void a_second_connection_is_dropped() {
-    two_apps t("JJJJJJJJJJJJJJJJJJJJ", "KKKKKKKKKKKKKKKKKKKK");
-    joined_in(t, {"r1", "r2"});
-    BOOST_TEST(run_until(t.f, [&] { return t.f.net.live_connections() == 2U; }));
-}
-
-// An app moved from is only destroyed: its state, moved, still counts its handle once, so the room
-// keeps its peer and its connection when the moved-from handle and the new one are both gone, which
-// the other side sees as no departure and no new connection.
-void a_moved_from_app_releases_nothing() {
-    fixture f{true};
-    std::optional a(std::in_place, f.io.get_executor(), f.net,
-                                   app_config("LLLLLLLLLLLLLLLLLLLL"));
-    trystero::app b(f.io.get_executor(), f.net, app_config("MMMMMMMMMMMMMMMMMMMM"));
-    auto ra = join(*a, "r");
-    auto rb = join(b, "r");
-    std::size_t leaves = 0;
-    rb.on_peer_leave([&](std::string_view) { ++leaves; });
-    webcpp::test::require(
-        BOOST_TEST(run_until(f, [&] { return ra.peers().size() == 1 && rb.peers().size() == 1; })));
-    const auto made = f.net.made_connections;
-    {
-        const trystero::app moved(std::move(*a));
-        // A moved-from app takes another's state by assignment, and releases only that one.
-        *a = trystero::app(f.io.get_executor(), f.net, app_config("UUUUUUUUUUUUUUUUUUUU"));
-        BOOST_TEST_EQ(a->self_id(), "UUUUUUUUUUUUUUUUUUUU");
-        a.reset();
-        BOOST_TEST_EQ(moved.self_id(), "LLLLLLLLLLLLLLLLLLLL");
-    }
-    webcpp::trystero::test::advance(f, 1000ms);
-    BOOST_TEST_EQ(leaves, 0U);
-    BOOST_TEST_EQ(f.net.made_connections, made);
-    BOOST_TEST_EQ(ra.peers().size(), 1U);
-}
-
-// An app destroyed while its room remains changes nothing for the room; the room's departure, the
-// last user of the state, then ends the connection at once rather than idling it.
-void an_app_destroyed_leaves_its_rooms_going() {
-    fixture f{true};
-    std::optional a(std::in_place, f.io.get_executor(), f.net,
-                                   app_config("SSSSSSSSSSSSSSSSSSSS"));
-    trystero::app b(f.io.get_executor(), f.net, app_config("TTTTTTTTTTTTTTTTTTTT"));
-    std::optional ra(join(*a, "r"));
-    auto rb = join(b, "r");
-    std::size_t leaves = 0;
-    rb.on_peer_leave([&](std::string_view) { ++leaves; });
-    webcpp::test::require(BOOST_TEST(
-        run_until(f, [&] { return ra->peers().size() == 1 && rb.peers().size() == 1; })));
-    const auto made = f.net.made_connections;
-    a.reset();
-    webcpp::trystero::test::advance(f, 1000ms);
-    BOOST_TEST_EQ(leaves, 0U);
-    BOOST_TEST_EQ(f.net.made_connections, made);
-    BOOST_TEST_EQ(ra->peers().size(), 1U);
-    ra.reset();
-    BOOST_TEST(run_until(f, [&] { return f.net.live_connections() == 0U; }, 1000ms));
-}
-
-// An app assigned over releases the state it held: that state's rooms go on, and when the last of
-// them goes, its connections end at once rather than idling.
-void an_app_assigned_over_releases_its_state() {
-    fixture f{true};
-    trystero::app a(f.io.get_executor(), f.net, app_config("NNNNNNNNNNNNNNNNNNNN"));
-    trystero::app b(f.io.get_executor(), f.net, app_config("OOOOOOOOOOOOOOOOOOOO"));
-    std::optional ra(join(a, "r"));
-    auto rb = join(b, "r");
-    std::size_t leaves = 0;
-    rb.on_peer_leave([&](std::string_view) { ++leaves; });
-    webcpp::test::require(BOOST_TEST(
-        run_until(f, [&] { return ra->peers().size() == 1 && rb.peers().size() == 1; })));
-    const auto made = f.net.made_connections;
-    a = trystero::app(f.io.get_executor(), f.net, app_config("PPPPPPPPPPPPPPPPPPPP"));
-    BOOST_TEST_EQ(a.self_id(), "PPPPPPPPPPPPPPPPPPPP");
-    webcpp::trystero::test::advance(f, 1000ms);
-    BOOST_TEST_EQ(leaves, 0U);
-    BOOST_TEST_EQ(f.net.made_connections, made);
-    BOOST_TEST_EQ(ra->peers().size(), 1U);
-    ra.reset();
-    BOOST_TEST(run_until(f, [&] { return f.net.live_connections() == 0U; }, 1000ms));
-}
-
-// An app assigned to itself keeps its state and its count: its room's departure idles the
-// connection, which the app's handle still holds.
-void an_app_assigned_to_itself_keeps_its_state() {
-    fixture f{true};
-    trystero::app a(f.io.get_executor(), f.net, app_config("QQQQQQQQQQQQQQQQQQQQ"));
-    trystero::app b(f.io.get_executor(), f.net, app_config("RRRRRRRRRRRRRRRRRRRR"));
-    std::optional ra(join(a, "r"));
-    auto rb = join(b, "r");
-    webcpp::test::require(BOOST_TEST(
-        run_until(f, [&] { return ra->peers().size() == 1 && rb.peers().size() == 1; })));
-    auto& same = a;  // through a reference: the compiler warns of a move to itself written out
-    a = std::move(same);
-    BOOST_TEST_EQ(a.self_id(), "QQQQQQQQQQQQQQQQQQQQ");
-    ra.reset();
-    webcpp::trystero::test::advance(f, 1000ms);
-    BOOST_TEST_EQ(f.net.live_connections(), 2U);
-}
-
-/** A's end of the first pair made, recorded by on_made: A, the lower id, offers first. */
-struct ends {
-    std::vector made;
-
-    explicit ends(two_apps& t) {
-        t.f.net.on_made = [this](std::size_t pc, std::span) {
-            made.push_back(pc);
-        };
-    }
-
-    [[nodiscard]] std::size_t a() const { return made.at(0); }
-};
-
-/** The action an inline room frame of `room` carries (`\@_hsdata`, `\@_leave`, `chat`, ...), or
- * empty. */
-std::string internal_name(std::span frame, std::string_view room) {
-    const auto env = trystero::protocol::decode_envelope(frame);
-    if (!env || env->type != trystero::protocol::envelope::kind::room ||
-        env->token != trystero::protocol::room_token(app_id, room)) {
-        return {};
-    }
-    const auto d = trystero::protocol::decode_action(env->payload);
-    const auto* p = d.frame ? std::get_if(&*d.frame) : nullptr;
-    return p != nullptr ? std::string(p->name) : std::string();
-}
-
-/** What a frame of `room` is, for a record of what one end sent: its inline action's name,
- * `presence(1)` or `presence(0)`, or empty for a frame of another room or not inline. */
-std::string what_of(std::span frame, std::string_view room) {
-    const auto env = trystero::protocol::decode_envelope(frame);
-    if (env && env->type == trystero::protocol::envelope::kind::presence &&
-        env->token == trystero::protocol::room_token(app_id, room)) {
-        return env->present ? "presence(1)" : "presence(0)";
-    }
-    return internal_name(frame, room);
-}
-
-/** A room frame of `room`'s token holding the inline action `name`, with `json` as its payload
- * (none when empty), as a peer's room sends an internal action. */
-trystero::protocol::bytes internal_frame(std::string_view room, std::string_view name,
-                                         std::string_view json = {}) {
-    const auto token = trystero::protocol::room_token(app_id, room);
-    const std::span payload(reinterpret_cast(json.data()),
-                                                json.size());
-    auto frame = trystero::protocol::begin_room_frame(
-        token, trystero::protocol::inline_header_size + payload.size());
-    trystero::protocol::append_inline(frame, name,
-                                      json.empty() ? trystero::protocol::payload_format::text
-                                                   : trystero::protocol::payload_format::json,
-                                      {}, payload);
-    return frame;
-}
-
-/** Replaces r2's proof responses with an incorrect proof, leaving its challenges and every
- * other room unchanged. The peers have already authenticated the shared app password. */
-void corrupt_r2_responses(two_apps& t) {
-    t.f.net.filter = [&t](std::size_t, std::size_t to, std::span frame) {
-        const std::string_view text(reinterpret_cast(frame.data()), frame.size());
-        if (internal_name(frame, "r2") == "@_hsdata" &&
-            text.find(R"("__trystero_pw":"response")") != std::string_view::npos) {
-            t.f.net.inject(to, internal_frame("r2", "@_hsdata",
-                                              R"({"__trystero_pw":"response","h":"incorrect"})"));
-            return trystero::test::memory_network::verdict::drop;
-        }
-        return trystero::test::memory_network::verdict::deliver;
-    };
-}
-
-// Frames of r2 that reach A before B's presence, as a Trystero JS peer sends its handshake before
-// its presence: the first is B's own advertisement of r2, on which A binds, and A delivers it after
-// making B's state, so the handshake completes on it. B's presence is held until both have joined,
-// so the frame alone bound A. B, whose join finds A's presence for r2, binds during the join, as
-// Trystero JS does: its handshake goes out first, then its presence. The 64-frame bound and the
-// 10 s expiry are the connection's, tested in connection_test.cpp.
-void frames_before_presence_bind_their_room() {
-    two_apps t("HHHHHHHHHHHHHHHHHHHH", "IIIIIIIIIIIIIIIIIIII");
-    const ends e(t);
-    joined_in(t, {"r1"});
-    t.a_rooms.push_back(join(t.a, "r2"));
-    webcpp::trystero::test::advance(t.f, 200ms);
-    std::vector b_sent;
-    t.f.net.filter = [&](std::size_t, std::size_t to, std::span frame) {
-        if (to != e.a()) {
-            return trystero::test::memory_network::verdict::deliver;
-        }
-        auto what = what_of(frame, "r2");
-        const bool presence = what == "presence(1)";
-        if (!what.empty()) {
-            b_sent.push_back(std::move(what));
-        }
-        return presence ? trystero::test::memory_network::verdict::hold
-                        : trystero::test::memory_network::verdict::deliver;
-    };
-    t.b_rooms.push_back(join(t.b, "r2"));
-    BOOST_TEST((b_sent == std::vector{"@_hsready", "presence(1)"}));
-    BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 1ms));
-    t.f.net.filter = nullptr;  // the rooms' farewells go through the network after `e` is gone
-    t.f.net.release(e.a());
-    webcpp::trystero::test::advance(t.f, 1000ms);
-    BOOST_TEST(t.all_joined());
-}
-
-// A kept frame that makes A kick B while A binds (an undecodable action frame of r2, then B's
-// presence for r2): A kicks B from r2 only, nothing else happens, and nothing touches the peer's
-// removed state (shared_hardened and the sanitizers see it).
-void a_kept_frame_that_kicks_during_a_binding() {
-    two_apps t("HHHHHHHHHHHHHHHHHHH1", "IIIIIIIIIIIIIIIIIII2");
-    const ends e(t);
-    joined_in(t, {"r1"});
-    t.a_rooms.push_back(join(t.a, "r2"));
-    webcpp::trystero::test::advance(t.f, 200ms);
-    std::size_t leaves_sent = 0;
-    std::vector a_sent;
-    t.f.net.filter = [&](std::size_t from, std::size_t, std::span frame) {
-        leaves_sent += from == e.a() && internal_name(frame, "r2") == "@_leave" ? 1 : 0;
-        if (auto what = what_of(frame, "r2"); from == e.a() && !what.empty()) {
-            a_sent.push_back(std::move(what));
-        }
-        return trystero::test::memory_network::verdict::deliver;
-    };
-    const auto token = trystero::protocol::room_token(app_id, "r2");
-    const std::array garbage{9, 9, 9};
-    t.f.net.inject(e.a(), trystero::protocol::room_frame(token, garbage));
-    t.f.net.inject(e.a(), trystero::protocol::presence_frame(token, true));
-    BOOST_TEST(run_until(t.f, [&] { return leaves_sent == 1; }));
-    webcpp::trystero::test::advance(t.f, 1000ms);
-    // The kick came before the handshake's first message, which the removed peer never got.
-    BOOST_TEST((a_sent == std::vector{"@_leave"}));
-    BOOST_TEST(t.a_rooms[1].peers().empty());
-    BOOST_TEST_EQ(t.a_rooms[0].peers().size(), 1U);
-    BOOST_TEST_EQ(t.f.net.live_connections(), 2U);
-    // The rooms' farewells go through the network after `e` and `leaves_sent` are gone.
-    t.f.net.filter = nullptr;
-}
-
-// A frame of a room from a peer that advertised it binds the room, as its presence does: after B's
-// `@_leave` of r2, which leaves the connection and B's presence for r2 as they were, B's next frame
-// of r2 binds A's r2 to it again.
-void a_kept_frame_binds_its_room() {
-    two_apps t("LLLLLLLLLLLLLLLLLLL1", "MMMMMMMMMMMMMMMMMMM2");
-    const ends e(t);
-    joined_in(t, {"r1", "r2"});
-    t.f.net.inject(e.a(), internal_frame("r2", "@_leave"));
-    BOOST_TEST(run_until(t.f, [&] { return t.a_rooms[1].peers().empty(); }));
-    t.f.net.inject(e.a(), internal_frame("r2", "@_hsready"));
-    BOOST_TEST(run_until(t.f, [&] { return t.a_rooms[1].peers().size() == 1; }, 12s));
-    BOOST_TEST_EQ(t.a_rooms[0].peers().size(), 1U);
-    BOOST_TEST_EQ(t.f.net.live_connections(), 2U);
-}
-
-// A room that is leaving binds no one: B, which joins r2 during A's farewell from it, finds A's
-// presence and binds A at once, but A, which hears B's presence and B's handshake then, binds
-// neither, so B never sees A join; A's presence(0) then ends B's binding.
-void a_leaving_room_binds_no_one() {
-    two_apps t("NNNNNNNNNNNNNNNNNNN1", "OOOOOOOOOOOOOOOOOOO2");
-    joined_in(t, {"r1"});
-    t.a_rooms.push_back(join(t.a, "r2"));
-    webcpp::trystero::test::advance(t.f, 200ms);
-    bool left = false;
-    t.a_rooms[1].async_leave([&left](boost::system::error_code) { left = true; });
-    t.b_rooms.push_back(join(t.b, "r2"));
-    std::size_t joins = 0;
-    t.b_rooms[1].on_peer_join([&joins](std::string_view) { ++joins; });
-    BOOST_TEST(run_until(t.f, [&] { return left; }));
-    webcpp::trystero::test::advance(t.f, 1000ms);
-    BOOST_TEST_EQ(joins, 0U);
-    BOOST_TEST(t.b_rooms[1].peers().empty());
-    BOOST_TEST_EQ(t.b_rooms[0].peers().size(), 1U);
-}
-
-// A forced failure, a frame that does not decode, and a 65th advertised token each end the
-// connection for both rooms, which then meet again over one new connection.
-void a_connections_end_is_every_rooms() {
-    for (std::size_t way = 0; way < 3; ++way) {
-        two_apps t("JJJJJJJJJJJJJJJJJJJ1", "KKKKKKKKKKKKKKKKKKK2");
-        const ends e(t);
-        joined_in(t, {"r1", "r2"});
-        std::size_t leaves = 0;
-        for (auto& r : t.a_rooms) {
-            r.on_peer_leave([&leaves](std::string_view) { ++leaves; });
-        }
-        if (way == 0) {
-            t.f.net.fail(e.a());
-        } else if (way == 1) {
-            const std::array bad{3, 0, 1, 'x'};
-            t.f.net.inject(e.a(), bad);
-        } else {
-            for (std::size_t i = 0; i < 65; ++i) {
-                t.f.net.inject(e.a(),
-                               trystero::protocol::presence_frame("X" + std::to_string(i), true));
-            }
-        }
-        BOOST_TEST(run_until(t.f, [&] { return leaves == 2; }));
-        BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 30s));
-        BOOST_TEST(run_until(t.f, [&] { return t.f.net.live_connections() == 2U; }));
-    }
-}
-
-/** Every relay text of `topics` the watcher reads: whether an offer or an answer was published. */
-struct offers_on {
-    std::vector seen;
-
-    [[nodiscard]] bool offer_or_answer() const {
-        return std::ranges::any_of(
-            seen, [](const relayed& r) { return !r.offer.empty() || !r.answer.empty(); });
-    }
-};
-
-// a late join, both directions: r2 joins over the existing connection, no connection is
-// made, and no offer and no answer is published on r2's topics for the whole case.
-void a_late_join_binds_over_the_connection() {
-    for (const bool a_first : {true, false}) {
-        two_apps t("LLLLLLLLLLLLLLLLLLLL", "MMMMMMMMMMMMMMMMMMMM");
-        t.a_rooms.push_back(join(t.a, "r1"));
-        t.b_rooms.push_back(join(t.b, "r1"));
-        webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); })));
-        flooder watcher(t.f, "r2");
-        offers_on r2;
-        watcher.on_text = [&](std::string_view text) {
-            if (auto s = relayed_signal(text)) {
-                r2.seen.push_back(std::move(*s));
-            }
-        };
-        watcher.watch(trystero::protocol::root_topic(app_id, "r2"));
-        watcher.watch(trystero::protocol::peer_topic(app_id, "r2", t.a.self_id()));
-        watcher.watch(trystero::protocol::peer_topic(app_id, "r2", t.b.self_id()));
-        const auto made = t.f.net.made_connections;
-        if (a_first) {
-            t.a_rooms.push_back(join(t.a, "r2"));
-            webcpp::trystero::test::advance(t.f, 500ms);
-            t.b_rooms.push_back(join(t.b, "r2"));
-        } else {
-            t.b_rooms.push_back(join(t.b, "r2"));
-            webcpp::trystero::test::advance(t.f, 500ms);
-            t.a_rooms.push_back(join(t.a, "r2"));
-        }
-        BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }));
-        webcpp::trystero::test::advance(
-            t.f,
-            70s);  // past r2's regular announcements, at once, 233, 533, 1333, 5333 ms, 60 s
-        BOOST_TEST_EQ(t.f.net.made_connections, made);
-        BOOST_TEST(!r2.offer_or_answer());
-    }
-}
-
-// an announcement forged in X's name in r2, before X joins r2, binds nothing, reports
-// nothing and publishes no offer; X then joins within a round trip (no timer runs meanwhile).
-void a_forged_announcement_binds_nothing() {
-    two_apps t("PPPPPPPPPPPPPPPPPPPP", "QQQQQQQQQQQQQQQQQQQQ");
-    joined_in(t, {"r1"});
-    t.a_rooms.push_back(join(t.a, "r2"));
-    std::vector errors;
-    t.a_rooms[1].on_error([&](std::string_view, boost::system::error_code ec, std::string_view) {
-        errors.push_back(ec);
-    });
-    const auto made = t.f.net.made_connections;
-    flooder forger(t.f, "r2");
-    forger.announce_as(t.b.self_id(), 3);
-    webcpp::trystero::test::advance(t.f, 15s);
-    BOOST_TEST(t.a_rooms[1].peers().empty());
-    BOOST_TEST(errors.empty());
-    BOOST_TEST_EQ(t.f.net.made_connections, made);
-    t.b_rooms.push_back(join(t.b, "r2"));
-    BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 1ms));
-}
-
-/** Runs one ready handler at a time until `done` holds, for at most `limit` handlers, moving no
- * clock. Tip: a buffering channel's drain posts itself again, so io_context::poll would drain it
- * whole; this one stops while the channel is still full. */
-bool poll_until(fixture& f, const std::function& done, std::size_t limit = 1'000'000) {
-    for (std::size_t i = 0; i < limit && !done(); ++i) {
-        f.io.restart();
-        if (f.io.poll_one() == 0) {
-            break;
-        }
-    }
-    return done();
-}
-
-/** Whether `frame` is a presence frame of `room` saying `present`. */
-bool is_presence(std::span frame, std::string_view room, bool present) {
-    const auto env = trystero::protocol::decode_envelope(frame);
-    return env && env->type == trystero::protocol::envelope::kind::presence &&
-           env->token == trystero::protocol::room_token(app_id, room) && env->present == present;
-}
-
-// one room leaves (by async_leave, by its destruction, by a room moved over it): only that
-// room sees the peer go, presence(0, r1) arrives, r2 keeps exchanging, the connection stays, and a
-// send in the room left completes with room_left.
-void one_room_leaves() {
-    for (std::size_t way = 0; way < 3; ++way) {
-        two_apps t("RRRRRRRRRRRRRRRRRRRR", "SSSSSSSSSSSSSSSSSSSS");
-        const ends e(t);
-        joined_in(t, {"r1", "r2"});
-        std::size_t b_r1_leaves = 0;
-        std::size_t b_r2_leaves = 0;
-        t.b_rooms[0].on_peer_leave([&](std::string_view) { ++b_r1_leaves; });
-        t.b_rooms[1].on_peer_leave([&](std::string_view) { ++b_r2_leaves; });
-        bool withdrawn = false;
-        t.f.net.filter = [&](std::size_t from, std::size_t, std::span frame) {
-            withdrawn = withdrawn || (from == e.a() && is_presence(frame, "r1", false));
-            return trystero::test::memory_network::verdict::deliver;
-        };
-        auto r1_chat = t.a_rooms[0].make_action("chat");
-        if (way == 0) {
-            bool done = false;
-            t.a_rooms[0].async_leave([&](boost::system::error_code) { done = true; });
-            BOOST_TEST(run_until(t.f, [&] { return done; }));
-        } else if (way == 1) {
-            t.a_rooms.erase(t.a_rooms.begin());
-        } else {
-            t.a_rooms[0] = join(t.a, "elsewhere");
-        }
-        BOOST_TEST(run_until(t.f, [&] { return b_r1_leaves == 1 && withdrawn; }));
-        webcpp::trystero::test::advance(t.f, 1s);
-        BOOST_TEST_EQ(b_r2_leaves, 0U);
-        BOOST_TEST_EQ(t.f.net.live_connections(), 2U);
-        std::vector got;
-        auto in_r2 = t.b_rooms[1].make_action("chat");
-        in_r2.on_message(
-            [&](const std::string& s, const trystero::message_info&) { got.push_back(s); });
-        auto& a_r2 = way == 1 ? t.a_rooms[0] : t.a_rooms[1];  // the erase moved r2 to the front
-        a_r2.make_action("chat").async_send("still", [](boost::system::error_code) {});
-        BOOST_TEST(run_until(t.f, [&] { return got.size() == 1; }));
-        if (way == 0) {
-            std::optional sent;
-            r1_chat.async_send("late", [&](boost::system::error_code ec) { sent = ec; });
-            BOOST_TEST(run_until(t.f, [&] { return sent.has_value(); }));
-            BOOST_TEST(*sent == trystero::error::room_left);
-        }
-    }
-}
-
-// the peer leaves every room: the connection closes after idle_timeout (200 ms), not
-// before, on the virtual clock; a room joined again within it reuses it; with 0 it closes at once.
-void a_peer_leaving_every_room_idles_the_connection() {
-    for (const auto idle : {200ms, 0ms}) {
-        fixture f{true};
-        auto a_config = app_config("TTTTTTTTTTTTTTTTTTTT");
-        a_config.idle_timeout = idle;
-        trystero::app a(f.io.get_executor(), f.net, std::move(a_config));
-        trystero::app b(f.io.get_executor(), f.net, app_config("UUUUUUUUUUUUUUUUUUUU"));
-        auto a1 = join(a, "r1");
-        auto a2 = join(a, "r2");
-        std::optional b1 = join(b, "r1");
-        std::optional b2 = join(b, "r2");
-        webcpp::test::require(BOOST_TEST(
-            run_until(f, [&] { return a1.peers().size() == 1 && a2.peers().size() == 1; })));
-        b1.reset();
-        b2.reset();
-        BOOST_TEST(run_until(f, [&] { return a1.peers().empty() && a2.peers().empty(); }, 1ms));
-        if (idle == 0ms) {
-            BOOST_TEST(run_until(f, [&] { return f.net.live_connections() == 0; }, 1ms));
-            continue;
-        }
-        webcpp::trystero::test::advance(f, 100ms);
-        BOOST_TEST_EQ(f.net.live_connections(), 2U);
-        const auto made = f.net.made_connections;
-        b1 = join(b, "r1");  // within the idle time: the connection is reused
-        BOOST_TEST(run_until(f, [&] { return a1.peers().size() == 1; }, 1ms));
-        BOOST_TEST_EQ(f.net.made_connections, made);
-        b1.reset();
-        BOOST_TEST(run_until(f, [&] { return a1.peers().empty(); }, 1ms));
-        webcpp::trystero::test::advance(f, 199ms);
-        BOOST_TEST_EQ(f.net.live_connections(), 2U);  // not before
-        webcpp::trystero::test::advance(f, 1ms);
-        BOOST_TEST(run_until(f, [&] { return f.net.live_connections() == 0; }, 1ms));
-    }
-}
-
-/** Drops the first \@_hsdata of r2 on any end, B's challenge when B is the lower id. */
-void drop_first_challenge(two_apps& t) {
-    const auto dropped = std::make_shared(false);
-    t.f.net.filter = [dropped](std::size_t, std::size_t, std::span frame) {
-        if (*dropped || internal_name(frame, "r2") != "@_hsdata") {
-            return trystero::test::memory_network::verdict::deliver;
-        }
-        *dropped = true;
-        return trystero::test::memory_network::verdict::drop;
-    };
-}
-
-// an action-level kick is per room: an undecodable action frame of r2 kicks B from r2
-// only; r1 keeps exchanging.
-void an_action_level_kick_is_per_room() {
-    two_apps t("CCCCCCCCCCCCCCCCCCC1", "DDDDDDDDDDDDDDDDDDD2");
-    const ends e(t);
-    joined_in(t, {"r1", "r2"});
-    std::size_t r2_leaves = 0;
-    t.a_rooms[1].on_peer_leave([&](std::string_view) { ++r2_leaves; });
-    const std::array garbage{9, 9, 9};
-    t.f.net.inject(e.a(), trystero::protocol::room_frame(
-                              trystero::protocol::room_token(app_id, "r2"), garbage));
-    BOOST_TEST(run_until(t.f, [&] { return r2_leaves == 1; }));
-    std::vector got;
-    auto in_r1 = t.b_rooms[0].make_action("chat");
-    in_r1.on_message(
-        [&](const std::string& s, const trystero::message_info&) { got.push_back(s); });
-    t.a_rooms[0].make_action("chat").async_send("still",
-                                                             [](boost::system::error_code) {});
-    BOOST_TEST(run_until(t.f, [&] { return got.size() == 1; }));
-    BOOST_TEST_EQ(t.f.net.live_connections(), 2U);
-}
-
-// the connection fails while a transfer of r2 waits on the full channel. Its
-// end fails the drain waiter, whose completion fails the transfer and may send on the ended
-// connection: the transfer completes once with an error, both rooms see B leave, and they meet
-// again. Run under shared_hardened and the sanitizers too.
-void a_connection_failing_under_a_waiting_transfer() {
-    two_apps t("EEEEEEEEEEEEEEEEEEE1", "FFFFFFFFFFFFFFFFFFF2");
-    t.f.net.channel_capacity = 1;
-    const ends e(t);
-    joined_in(t, {"r1", "r2"});
-    auto receiver = t.b_rooms[1].make_action("big");
-    receiver.on_message([](const trystero::bytes&, const trystero::message_info&) {});
-    std::size_t completions = 0;
-    std::optional sent;
-    t.a_rooms[1].make_action("big").async_send(
-        trystero::bytes(1'000'000, std::uint8_t{4}), [&](boost::system::error_code ec) {
-            ++completions;
-            sent = ec;
-        });
-    webcpp::test::require(BOOST_TEST(poll_until(t.f, [&] {
-        return t.f.net.buffered(e.a()) > std::size_t{64} * 1024;  // a chunk waits on the drain
-    })));
-    std::size_t leaves = 0;
-    for (auto& r : t.a_rooms) {
-        r.on_peer_leave([&leaves](std::string_view) { ++leaves; });
-    }
-    t.f.net.fail(e.a());
-    BOOST_TEST(run_until(t.f, [&] { return leaves == 2 && sent.has_value(); }));
-    BOOST_TEST(*sent == trystero::error::peer_disconnected);
-    BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 30s));
-    BOOST_TEST_EQ(completions, 1U);
-}
-
-// A kick is per room. B sends an incorrect r2 proof and A is the lower id:
-// A reports wrong_password in r2 only and r1 stays joined over the same connection. Then a
-// handshake that times out: B the lower id, its challenge dropped once by the filter; B reports
-// handshake_timed_out in r2 only, 10 s after binding, and r1 stays. (The rest of case 10, the kick
-// that closes the connection and the renegotiation after it use the rebinding times.)
-void a_kick_is_per_room() {
-    {
-        two_apps t("AAAAAAAAAAAAAAAAAAA1", "BBBBBBBBBBBBBBBBBBB2", "pw");
-        joined_in(t, {"r1"});
-        corrupt_r2_responses(t);
-        std::vector r2_errors;
-        t.a_rooms.push_back(join(t.a, "r2"));
-        t.a_rooms[1].on_error([&](std::string_view, boost::system::error_code ec,
-                                  std::string_view) { r2_errors.push_back(ec); });
-        const auto made = t.f.net.made_connections;
-        t.b_rooms.push_back(join(t.b, "r2"));
-        BOOST_TEST(run_until(t.f, [&] { return !r2_errors.empty(); }));
-        BOOST_TEST(r2_errors.at(0) == trystero::error::wrong_password);
-        BOOST_TEST_EQ(t.a_rooms[0].peers().size(), 1U);
-        BOOST_TEST_EQ(t.b_rooms[0].peers().size(), 1U);
-        BOOST_TEST_EQ(t.f.net.made_connections, made);
-        BOOST_TEST_EQ(t.f.net.live_connections(), 2U);
-    }
-    {
-        two_apps t("BBBBBBBBBBBBBBBBBBB1", "AAAAAAAAAAAAAAAAAAA2", "pw");  // B the lower id
-        joined_in(t, {"r1"});
-        drop_first_challenge(t);
-        std::vector b_errors;
-        t.a_rooms.push_back(join(t.a, "r2", {.handshake_timeout = 30s}));
-        const auto joined = t.f.net.steady_now();
-        t.b_rooms.push_back(join(t.b, "r2"));
-        t.b_rooms[1].on_error([&](std::string_view, boost::system::error_code ec,
-                                  std::string_view) { b_errors.push_back(ec); });
-        BOOST_TEST(run_until(t.f, [&] { return !b_errors.empty(); }, 11s));
-        BOOST_TEST(b_errors.at(0) == trystero::error::handshake_timed_out);
-        BOOST_TEST(t.f.net.steady_now() - joined == 10s);
-        BOOST_TEST_EQ(t.a_rooms[0].peers().size(), 1U);
-        BOOST_TEST_EQ(t.f.net.live_connections(), 2U);
-    }
-}
-
-// join of a room id succeeds once async_leave has completed.
-void a_room_left_can_be_joined_again() {
-    fixture f{true};
-    trystero::app a(f.io.get_executor(), f.net, app_config("GGGGGGGGGGGGGGGGGGG1"));
-    auto r = join(a, "r");
-    bool done = false;
-    r.async_leave([&](boost::system::error_code) { done = true; });
-    BOOST_TEST(run_until(f, [&] { return done; }));
-    BOOST_TEST(a.join("r").has_value());
-}
-
-// Review Focus 4 and case 15's farewell half: join, async_leave twice, join during the farewell
-// (which finishes it: both leaves complete, once each), the room destroyed during its farewell,
-// join again. presence(0) and presence(1) go out in that order, and max_rooms counts a leaving
-// room until its presence(0).
-void join_and_leave_sequences_on_one_id() {
-    two_apps t("IIIIIIIIIIIIIIIIIII1", "JJJJJJJJJJJJJJJJJJJ2");
-    const ends e(t);
-    joined_in(t, {"lobby"});
-    std::vector presences;  // A's presence frames of r, in the order sent
-    t.f.net.filter = [&](std::size_t from, std::size_t, std::span frame) {
-        if (from == e.a() && is_presence(frame, "r", true)) {
-            presences.push_back(true);
-        } else if (from == e.a() && is_presence(frame, "r", false)) {
-            presences.push_back(false);
-        }
-        return trystero::test::memory_network::verdict::deliver;
-    };
-    std::vector others;
-    others.reserve(62);
-    for (std::size_t i = 0; i < 62; ++i) {
-        others.push_back(join(t.a, "x" + std::to_string(i)));  // with lobby and r: 64 rooms
-    }
-    std::optional r(join(t.a, "r"));
-    t.b_rooms.push_back(join(t.b, "r"));
-    webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return r->peers().size() == 1; })));
-    std::size_t first = 0;
-    std::size_t second = 0;
-    r->async_leave([&](boost::system::error_code ec) { first += ec ? 100 : 1; });
-    r->async_leave([&](boost::system::error_code ec) { second += ec ? 100 : 1; });
-    const auto refused = t.a.join("x62");
-    BOOST_TEST(!refused && refused.error() == trystero::error::too_many_rooms);  // r still counts
-    webcpp::trystero::test::advance(t.f, 50ms);
-    BOOST_TEST_EQ(first + second, 0U);  // the second leave waits for the farewell with the first
-    BOOST_TEST((presences == std::vector{true}));
-    auto again = t.a.join("r");  // finishes r's farewell at once
-    webcpp::test::require(BOOST_TEST(again.has_value()));
-    BOOST_TEST((presences == std::vector{true, false, true}));
-    BOOST_TEST(run_until(t.f, [&] { return first == 1 && second == 1; }, 1ms));
-    r.reset();  // the old handle, its room ended: nothing more
-    std::optional r2(std::move(*again));
-    BOOST_TEST(run_until(t.f, [&] { return r2->peers().size() == 1; }));
-    std::size_t third = 0;
-    r2->async_leave([&](boost::system::error_code ec) { third += ec ? 100 : 1; });
-    r2.reset();  // destroyed during its farewell: the farewell ends at once
-    BOOST_TEST((presences == std::vector{true, false, true, false}));
-    const auto last_join = t.a.join("r");
-    BOOST_TEST(last_join.has_value());
-    BOOST_TEST((presences == std::vector{true, false, true, false, true}));
-    webcpp::trystero::test::advance(t.f, 1s);
-    BOOST_TEST_EQ(first, 1U);
-    BOOST_TEST_EQ(second, 1U);
-    BOOST_TEST_EQ(third, 1U);
-}
-
-// during a room's 99 ms farewell, B's presence and B's frames for it bind nothing
-// (B binds A on A's earlier presence and is dropped when A's presence(0) goes out); and a
-// connection the leaving room's own negotiation opens is closed, not adopted.
-void the_farewell_binds_nothing() {
-    {
-        two_apps t("KKKKKKKKKKKKKKKKKKK1", "LLLLLLLLLLLLLLLLLLL2");
-        joined_in(t, {"r1"});
-        t.a_rooms.push_back(join(t.a, "r2"));
-        bool left = false;
-        t.a_rooms[1].async_leave([&](boost::system::error_code) { left = true; });
-        std::size_t b_joins = 0;
-        t.b_rooms.push_back(join(t.b, "r2"));  // B's presence, announcement and handshake now
-        t.b_rooms[1].on_peer_join([&](std::string_view) { ++b_joins; });
-        BOOST_TEST(run_until(t.f, [&] { return left; }));
-        webcpp::trystero::test::advance(t.f, 1s);
-        BOOST_TEST(t.a_rooms[1].peers().empty());
-        BOOST_TEST(t.b_rooms[1].peers().empty());
-        BOOST_TEST_EQ(b_joins, 0U);
-        BOOST_TEST_EQ(t.f.net.live_connections(), 2U);
-    }
-    {
-        fixture f{true};
-        std::vector a_log;
-        auto a_config = app_config("MMMMMMMMMMMMMMMMMMM1");
-        a_config.log = [&a_log](std::string_view, std::string_view text) {
-            a_log.emplace_back(text);
-        };
-        trystero::app a(f.io.get_executor(), f.net, std::move(a_config));
-        trystero::app b(f.io.get_executor(), f.net, app_config("NNNNNNNNNNNNNNNNNNN2"));
-        std::vector made;
-        f.net.on_made = [&](std::size_t pc, std::span) {
-            made.push_back(pc);
-        };
-        f.net.defer_opens = true;
-        auto a2 = join(a, "r2");
-        const auto b2 = join(b, "r2");
-        webcpp::test::require(BOOST_TEST(
-            run_until(f, [&] { return made.size() == 2 && f.net.peer_of(made[0]) == made[1]; })));
-        bool left = false;
-        a2.async_leave([&](boost::system::error_code) { left = true; });
-        f.net.open(made[0]);
-        f.net.open(made[1]);
-        BOOST_TEST(run_until(f, [&] { return left; }));
-        webcpp::trystero::test::advance(f, 1s);
-        BOOST_TEST(std::ranges::none_of(a_log, [](const std::string& line) {
-            return line.find(" adopted") != std::string::npos;
-        }));
-        BOOST_TEST(b2.peers().empty());
-        BOOST_TEST(run_until(f, [&] { return f.net.live_connections() == 0; }, 1s));
-    }
-}
-
-// the app handle destroyed before its rooms: they go on; the last room destroyed: every
-// connection closes at that call.
-void the_last_user_closes_every_connection() {
-    fixture f{true};
-    std::vector a_log;
-    auto a_config = app_config("OOOOOOOOOOOOOOOOOOO1");
-    a_config.log = [&a_log](std::string_view, std::string_view text) { a_log.emplace_back(text); };
-    std::optional a(std::in_place, f.io.get_executor(), f.net, std::move(a_config));
-    trystero::app b(f.io.get_executor(), f.net, app_config("PPPPPPPPPPPPPPPPPPP2"));
-    std::optional a1(join(*a, "r1"));
-    std::optional a2(join(*a, "r2"));
-    const auto b1 = join(b, "r1");
-    const auto b2 = join(b, "r2");
-    webcpp::test::require(BOOST_TEST(
-        run_until(f, [&] { return a1->peers().size() == 1 && a2->peers().size() == 1; })));
-    const auto ended = [&a_log] {
-        return std::ranges::count_if(a_log, [](const std::string& line) {
-            return line.find(" ended: ") != std::string::npos;
-        });
-    };
-    a.reset();
-    a1.reset();
-    webcpp::trystero::test::advance(f, 1s);
-    BOOST_TEST_EQ(a2->peers().size(), 1U);
-    BOOST_TEST_EQ(ended(), 0);
-    a2.reset();                 // the last user
-    BOOST_TEST_EQ(ended(), 1);  // at that call, before the io_context runs
-    BOOST_TEST(run_until(f, [&] { return f.net.live_connections() == 0; }, 1ms));
-}
-
-// a room handle destroyed during its
-// farewell, the handles gone, then the io_context destroyed with the rooms' operations pending:
-// nothing is closed, logged or posted from a destructor, and the app's resource reaches zero.
-void the_io_context_destroyed_with_operations_pending() {
-    counting_resource memory;
-    std::vector late;
-    bool destroying = false;
-    {
-        std::optional f(std::in_place, true);
-        auto a_config = app_config("QQQQQQQQQQQQQQQQQQQ1");
-        a_config.memory = &memory;
-        a_config.log = [&](std::string_view, std::string_view text) {
-            if (destroying) {
-                late.emplace_back(text);
-            }
-        };
-        std::optional a(std::in_place, f->io.get_executor(), f->net,
-                                       std::move(a_config));
-        std::optional b(std::in_place, f->io.get_executor(), f->net,
-                                       app_config("RRRRRRRRRRRRRRRRRRR2"));
-        std::optional a1(join(*a, "r1"));
-        std::optional a2(join(*a, "r2"));
-        std::optional b1(join(*b, "r1"));
-        webcpp::test::require(BOOST_TEST(run_until(*f, [&] { return a1->peers().size() == 1; })));
-        a1->async_leave([](boost::system::error_code) {});
-        a1.reset();  // during its farewell: ended at once, its completion posted
-        a2->async_ping(b->self_id(), [](boost::system::error_code, std::chrono::milliseconds) {});
-        a2.reset();
-        b1.reset();
-        a.reset();
-        b.reset();
-        destroying = true;
-        f.reset();  // the network, then the io_context and the operations still pending in it
-    }
-    BOOST_TEST(late.empty());
-    BOOST_TEST_EQ(memory.in_use, 0U);
-}
-
-void the_rebinding_step() {
-    using trystero::detail::rebinding_step;
-    BOOST_TEST(rebinding_step(10s, 1) == 11s);
-    BOOST_TEST(rebinding_step(10s, 2) == 22s);
-    BOOST_TEST(rebinding_step(10s, 3) == 44s);
-    BOOST_TEST(rebinding_step(10s, 5) == 176s);
-    BOOST_TEST(rebinding_step(10s, 6) == 300s);
-    BOOST_TEST(rebinding_step(10s, 40) == 300s);
-    BOOST_TEST(rebinding_step(2s, 1) == 11s);  // never below Trystero's 10 s keep time
-    BOOST_TEST(rebinding_step(30s, 1) == 31s);
-    BOOST_TEST(rebinding_step(std::chrono::milliseconds::max(),
-                              std::numeric_limits::max()) == 300s);
-}
-
-// the lower id reports wrong_password at 0, 11, 33 and 77 s after the first, exactly,
-// and the fifth at 165 s, not before; the higher id reports nothing; r2's topics carry the regular
-// announcements only, no offer and no answer.
-void check_incorrect_proof_rebinding(bool a_lower) {
-    two_apps t(a_lower ? "AAAAAAAAAAAAAAAAAAA1" : "ZZZZZZZZZZZZZZZZZZZ1",
-               a_lower ? "ZZZZZZZZZZZZZZZZZZZ2" : "AAAAAAAAAAAAAAAAAAA2", "pw");
-    joined_in(t, {"r1"});
-    corrupt_r2_responses(t);
-    flooder watcher(t.f, "r2");
-    std::size_t r2_announcements = 0;
-    bool offer_or_answer = false;
-    watcher.on_text = [&](std::string_view text) {
-        if (auto s = relayed_signal(text)) {
-            r2_announcements += s->announcement ? 1 : 0;
-            offer_or_answer = offer_or_answer || !s->offer.empty() || !s->answer.empty();
-        }
-    };
-    watcher.watch(trystero::protocol::root_topic(app_id, "r2"));
-    watcher.watch(trystero::protocol::peer_topic(app_id, "r2", t.a.self_id()));
-    watcher.watch(trystero::protocol::peer_topic(app_id, "r2", t.b.self_id()));
-    std::vector a_reports;
-    std::vector b_reports;
-    const auto recorder = [&t](std::vector& to) {
-        return [&t, &to](std::string_view, boost::system::error_code ec, std::string_view) {
-            if (ec == trystero::error::wrong_password) {
-                to.push_back(t.f.net.steady_now());
-            }
-        };
-    };
-    t.a_rooms.push_back(join(t.a, "r2"));
-    t.b_rooms.push_back(join(t.b, "r2"));
-    t.a_rooms[1].on_error(recorder(a_reports));
-    t.b_rooms[1].on_error(recorder(b_reports));
-    const auto& lower = a_lower ? a_reports : b_reports;
-    const auto& higher = a_lower ? b_reports : a_reports;
-    webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return !lower.empty(); }, 1s)));
-    const auto first = lower.front();
-    webcpp::trystero::test::advance(t.f, std::chrono::duration_cast(
-                                             first + 100s - t.f.net.steady_now()));
-    const std::size_t announced_in_100_s = r2_announcements;
-    webcpp::trystero::test::advance(t.f, 64'999ms);  // to 164.999 s after the first
-    BOOST_TEST_EQ(lower.size(), 4U);
-    const std::array expected{0s, 11s, 33s, 77s};
-    for (std::size_t i = 0; i < std::min(lower.size(), 4); ++i) {
-        BOOST_TEST(lower[i] - first == expected[i]);
-    }
-    BOOST_TEST(run_until(t.f, [&] { return lower.size() == 5; }, 1ms));
-    BOOST_TEST(lower.back() - first == 165s);
-    BOOST_TEST(higher.empty());
-    BOOST_TEST(!offer_or_answer);
-    // Each room's regular cadence on the relay the watcher reads: at once, after 233, 533,
-    // 1333 and 5333 ms, then every 60 s: at most 6 each in 100 s, and no restart after a kick.
-    BOOST_TEST_LE(announced_in_100_s, 12U);
-}
-
-void an_incorrect_proof_rebinds_at_the_steps() {
-    for (const bool a_lower : {true, false}) {
-        check_incorrect_proof_rebinding(a_lower);
-    }
-}
-
-// A binds r2 again at its rebinding time, 11 s after its first kick, kicks B, and with
-// no room left in common that kick closes the connection at once; the peers then renegotiate
-// through r2 with their common app password, and its incorrect proofs still prevent joining. (b)
-// Only r2 in common, B the lower id, its challenge dropped once: B's timeout kick closes the
-// connection, the rebinding counts go with it, and B renegotiates through r2's signaling: the new
-// connection is adopted and bound with a count of zero, so the rooms join within 5 s of the kick,
-// before the 11 s a kept count would impose.
-void a_kick_that_closes_the_connection() {
-    {
-        std::optional kicked_connection_at;
-        two_apps t("AAAAAAAAAAAAAAAAAAK1", "BBBBBBBBBBBBBBBBBBK2", "pw");
-        auto a_config = app_config("AAAAAAAAAAAAAAAAAAK1", "pw");
-        a_config.log = [&](std::string_view category, std::string_view text) {
-            if (!kicked_connection_at && category == "webrtc" &&
-                text.ends_with("ended: its last room kicked the peer")) {
-                kicked_connection_at = t.f.net.steady_now();
-            }
-        };
-        t.a = trystero::app(t.f.io.get_executor(), t.f.net, std::move(a_config));
-        // B's connections carry B's own ICE server, so the test can tell them apart.
-        auto b_config = app_config("BBBBBBBBBBBBBBBBBBK2", "pw");
-        b_config.ice_servers = {{.urls = {"stun:b.test"}, .username = {}, .credential = {}}};
-        t.b = trystero::app(t.f.io.get_executor(), t.f.net, std::move(b_config));
-        std::size_t b_made = 0;
-        t.f.net.on_made = [&](std::size_t, std::span servers) {
-            b_made += !servers.empty() && servers[0].urls.at(0) == "stun:b.test" ? 1 : 0;
-        };
-        joined_in(t, {"r1"});
-        corrupt_r2_responses(t);
-        std::vector kicks;
-        t.a_rooms.push_back(join(t.a, "r2"));
-        t.a_rooms[1].on_error(
-            [&](std::string_view, boost::system::error_code ec, std::string_view) {
-                if (ec == trystero::error::wrong_password) {
-                    kicks.push_back(t.f.net.steady_now());
-                }
-            });
-        t.b_rooms.push_back(join(t.b, "r2"));
-        webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return kicks.size() == 1; }, 1s)));
-        t.b_rooms.erase(t.b_rooms.begin());  // r1 left on both sides: r2 is all they share
-        t.a_rooms.erase(t.a_rooms.begin());
-        const auto b_made_before = b_made;
-        BOOST_TEST(run_until(t.f, [&] { return kicked_connection_at.has_value(); }, 12s));
-        webcpp::test::require(BOOST_TEST_GE(kicks.size(), 2U));
-        BOOST_TEST(kicks[1] - kicks.front() == 11s);
-        BOOST_TEST(kicked_connection_at && *kicked_connection_at - kicks.front() == 11s);
-        webcpp::trystero::test::advance(t.f, 60s);
-        BOOST_TEST_GT(b_made, b_made_before);
-        BOOST_TEST(t.a_rooms[0].peers().empty());
-    }
-    {
-        two_apps t("BBBBBBBBBBBBBBBBBBL1", "AAAAAAAAAAAAAAAAAAL2", "pw");  // B the lower id
-        drop_first_challenge(t);
-        std::vector b_timeouts;
-        t.a_rooms.push_back(join(t.a, "r2", {.handshake_timeout = 30s}));
-        t.b_rooms.push_back(join(t.b, "r2"));
-        t.b_rooms[0].on_error(
-            [&](std::string_view, boost::system::error_code ec, std::string_view) {
-                if (ec == trystero::error::handshake_timed_out) {
-                    b_timeouts.push_back(t.f.net.steady_now());
-                }
-            });
-        webcpp::test::require(
-            BOOST_TEST(run_until(t.f, [&] { return t.f.net.live_connections() == 2; }, 1s)));
-        const auto made = t.f.net.made_connections;
-        webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return !b_timeouts.empty(); }, 30s)));
-        BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 5s));
-        BOOST_TEST(t.f.net.steady_now() - b_timeouts.front() < 5s);
-        BOOST_TEST_GE(t.f.net.made_connections, made + 2);  // a new pair, adopted
-        BOOST_TEST(run_until(t.f, [&] { return t.f.net.live_connections() == 2U; }, 1ms));
-        BOOST_TEST_EQ(b_timeouts.size(), 1U);
-    }
-}
-
-/** Holds, at the receiving end, the first frame from `from` that carries the internal action
- * `message` of r2, and, as the channel delivers in order, every later frame of that end .
- * Counts, in `challenges`, every \@_hsdata of r2 that `counted` sends. */
-void hold_first(two_apps& t, std::size_t from, std::string message, std::size_t counted = 0,
-                std::size_t* challenges = nullptr) {
-    const auto held = std::make_shared(false);
-    t.f.net.filter = [from, message = std::move(message), held, counted, challenges](
-                         std::size_t sender, std::size_t, std::span frame) {
-        const auto name = internal_name(frame, "r2");
-        if (challenges != nullptr && sender == counted && name == "@_hsdata") {
-            ++*challenges;
-        }
-        if (*held || sender != from || name != message) {
-            return trystero::test::memory_network::verdict::deliver;
-        }
-        *held = true;
-        return trystero::test::memory_network::verdict::hold;
-    };
-}
-
-// a lost presence is replaced by the peer's own frames. Trystero JS advertises a room once per
-// connection, and Chrome can drop what a page sends on an answering channel as it opens (its log
-// says "Send failed INVALID_STATE"; the interop test measured it), so the filter drops every
-// presence(1, r2) of B, which joins r2 after A: B binds at its join, on A's presence, and its
-// handshake frames reach A, which binds on the first, as on B's presence. Both join at once, with
-// no handshake timed out on either side; B's announcements in r2 still bind nothing and start no
-// negotiation.
-void a_lost_presence_is_replaced_by_the_peers_frames() {
-    two_apps t("NNNNNNNNNNNNNNNNNNNN", "OOOOOOOOOOOOOOOOOOOO");
-    const ends e(t);
-    joined_in(t, {"r1"});
-    t.a_rooms.push_back(join(t.a, "r2"));
-    webcpp::trystero::test::advance(t.f, 300ms);
-    std::size_t dropped = 0;
-    t.f.net.filter = [&](std::size_t from, std::size_t, std::span frame) {
-        if (from != e.a() && is_presence(frame, "r2", true)) {
-            ++dropped;
-            return trystero::test::memory_network::verdict::drop;
-        }
-        return trystero::test::memory_network::verdict::deliver;
-    };
-    flooder watcher(t.f, "r2");
-    bool offer_or_answer = false;
-    watcher.on_text = [&](std::string_view text) {
-        if (auto s = relayed_signal(text)) {
-            offer_or_answer = offer_or_answer || !s->offer.empty() || !s->answer.empty();
-        }
-    };
-    watcher.watch(trystero::protocol::peer_topic(app_id, "r2", t.a.self_id()));
-    watcher.watch(trystero::protocol::peer_topic(app_id, "r2", t.b.self_id()));
-    std::vector errors;
-    const auto recorder = [&errors](std::string_view, boost::system::error_code ec,
-                                    std::string_view) { errors.push_back(ec); };
-    t.a_rooms[1].on_error(recorder);
-    t.b_rooms.push_back(join(t.b, "r2"));
-    t.b_rooms[1].on_error(recorder);
-    BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 1ms));
-    webcpp::trystero::test::advance(t.f, 11s);  // past both handshake timeouts
-    BOOST_TEST(t.all_joined());
-    BOOST_TEST(errors.empty());
-    BOOST_TEST_EQ(dropped, 1U);
-    BOOST_TEST(!offer_or_answer);
-}
-
-void check_transient_failure(bool password, bool lower_times_out, bool release_after_rebinding) {
-    two_apps t("AAAAAAAAAAAAAAAAAAD1", "ZZZZZZZZZZZZZZZZZZD2",
-               password ? "p" : "");  // A the lower id
-    const ends e(t);
-    joined_in(t, {"r1"});
-    const auto a_end = e.a();
-    const auto b_end = t.f.net.peer_of(a_end);
-    // A times out on B's answer (without a password, B's @_hsready); B on A's
-    // challenge (or A's @_hsready).
-    hold_first(t, lower_times_out ? b_end : a_end, password ? "@_hsdata" : "@_hsready");
-    const trystero::room_options patient{
-        .handshake_timeout = 30s,
-    };
-    const trystero::room_options normal{};
-    std::vector a_errors;
-    std::vector b_errors;
-    t.a_rooms.push_back(join(t.a, "r2", lower_times_out ? normal : patient));
-    t.b_rooms.push_back(join(t.b, "r2", lower_times_out ? patient : normal));
-    t.a_rooms[1].on_error([&](std::string_view, boost::system::error_code ec, std::string_view) {
-        a_errors.push_back(ec);
-    });
-    t.b_rooms[1].on_error([&](std::string_view, boost::system::error_code ec, std::string_view) {
-        b_errors.push_back(ec);
-    });
-    const auto& timed_out = lower_times_out ? a_errors : b_errors;
-    webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return !timed_out.empty(); }, 11s)));
-    const auto kick = t.f.net.steady_now();
-    const std::chrono::milliseconds release_after = release_after_rebinding ? 13s : 2s;
-    webcpp::trystero::test::advance(t.f, release_after);
-    t.f.net.filter = {};
-    t.f.net.release(lower_times_out ? a_end : b_end);  // held at the receiving end
-    BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 12s));
-    BOOST_TEST(t.f.net.steady_now() - kick ==
-               std::max(11s, release_after));
-    BOOST_TEST_EQ(timed_out.size(), 1U);
-    BOOST_TEST(timed_out.at(0) == trystero::error::handshake_timed_out);
-    BOOST_TEST_EQ(a_errors.size() + b_errors.size(), 1U);  // no other report
-}
-
-void a_transient_failure_converges() {
-    for (const bool password : {true, false}) {
-        for (const bool lower_times_out : {true, false}) {
-            for (const bool release_after_rebinding : {false, true}) {
-                check_transient_failure(password, lower_times_out, release_after_rebinding);
-            }
-        }
-    }
-}
-
-// an answer to a challenge two bindings old passes a bound
-// initiator; one to a challenge nine bindings old, no longer among the last 8, is wrong_password.
-void an_answer_to_an_old_challenge() {
-    for (const std::size_t binding : {3U, 9U}) {
-        two_apps t("AAAAAAAAAAAAAAAAAAJ1", "ZZZZZZZZZZZZZZZZZZJ2", "pw");
-        const ends e(t);
-        joined_in(t, {"r1"});
-        const auto a_end = e.a();
-        const auto b_end = t.f.net.peer_of(a_end);
-        std::size_t a_challenges = 0;
-        hold_first(t, b_end, "@_hsdata", a_end, &a_challenges);  // B's first answer and after
-        std::vector a_errors;
-        t.a_rooms.push_back(join(t.a, "r2"));
-        t.b_rooms.push_back(join(t.b, "r2", {.handshake_timeout = 30s}));
-        t.a_rooms[1].on_error([&](std::string_view, boost::system::error_code ec,
-                                  std::string_view) { a_errors.push_back(ec); });
-        // A's bindings start at 0, 21, 53, 107, 205, 391, 701, 1011 and 1321 s.
-        webcpp::test::require(
-            BOOST_TEST(run_until(t.f, [&] { return a_challenges == binding; }, 1400s)));
-        BOOST_TEST_EQ(std::ranges::count(a_errors, trystero::error::handshake_timed_out),
-                      static_cast(binding - 1));
-        t.f.net.filter = {};
-        t.f.net.release(a_end);
-        const auto wrong = [&] {
-            return std::ranges::count(a_errors, trystero::error::wrong_password);
-        };
-        if (binding == 3) {
-            BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 1ms));
-            BOOST_TEST_EQ(wrong(), 0);
-        } else {
-            BOOST_TEST(run_until(t.f, [&] { return wrong() == 1; }, 1ms));
-            BOOST_TEST(t.a_rooms[1].peers().empty());
-        }
-    }
-}
-
-// A is the lower id and r2 responses are corrupted: after A's third kick at 33 s, B leaves r2
-// and rejoins with intact responses at 35 s; B joins at 77 s, A's rebinding time, exactly, having
-// reported at most two handshake_timed_out. With B the lower id rejecting corrupted responses, B's
-// new join joins at once: its rebinding count was its old room's.
-void a_corrected_response_rejoins() {
-    {
-        two_apps t("AAAAAAAAAAAAAAAAAAB1", "ZZZZZZZZZZZZZZZZZZB2", "pw");
-        joined_in(t, {"r1"});
-        corrupt_r2_responses(t);
-        std::vector a_kicks;
-        t.a_rooms.push_back(join(t.a, "r2"));
-        t.a_rooms[1].on_error(
-            [&](std::string_view, boost::system::error_code ec, std::string_view) {
-                if (ec == trystero::error::wrong_password) {
-                    a_kicks.push_back(t.f.net.steady_now());
-                }
-            });
-        std::optional b2(join(t.b, "r2"));
-        webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return a_kicks.size() == 3; }, 40s)));
-        const auto first = a_kicks.front();
-        BOOST_TEST(a_kicks.back() - first == 33s);
-        webcpp::trystero::test::advance(t.f, 2s);
-        b2.reset();
-        t.f.net.filter = {};
-        b2.emplace(join(t.b, "r2"));
-        std::vector b_errors;
-        b2->on_error([&](std::string_view, boost::system::error_code ec, std::string_view) {
-            b_errors.push_back(ec);
-        });
-        BOOST_TEST(run_until(t.f, [&] { return b2->peers().size() == 1; }, 45s));
-        BOOST_TEST(t.f.net.steady_now() - first == 77s);
-        BOOST_TEST_LE(std::ranges::count(b_errors, trystero::error::handshake_timed_out), 2);
-        BOOST_TEST_EQ(a_kicks.size(), 3U);
-    }
-    {
-        two_apps t("ZZZZZZZZZZZZZZZZZZC1", "AAAAAAAAAAAAAAAAAAC2", "pw");  // B the lower id
-        joined_in(t, {"r1"});
-        corrupt_r2_responses(t);
-        std::vector b_errors;
-        t.a_rooms.push_back(join(t.a, "r2"));
-        std::optional b2(join(t.b, "r2"));
-        b2->on_error([&](std::string_view, boost::system::error_code ec, std::string_view) {
-            b_errors.push_back(ec);
-        });
-        webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return !b_errors.empty(); }, 1s)));
-        webcpp::trystero::test::advance(t.f, 3s);
-        b2.reset();
-        t.f.net.filter = {};
-        b2.emplace(join(t.b, "r2"));
-        BOOST_TEST(run_until(t.f, [&] { return b2->peers().size() == 1; }, 1ms));
-    }
-}
-
-// A, the lower id, kicks B from r2 (an action frame of r2 that does not decode) and refuses it
-// until its rebinding time; meanwhile inject delivers on A's end B's @_hsready and @_leave of r2,
-// which A keeps without binding. At its rebinding time A binds, discards both, and the handshake
-// completes on what follows, with no second leave: A's log names B gone once, for the kick.
-void a_kept_leave_discards_what_came_before() {
-    std::vector a_log;
-    auto a_config = app_config("AAAAAAAAAAAAAAAAAAE1");
-    a_config.log = [&a_log](std::string_view, std::string_view text) { a_log.emplace_back(text); };
-    two_apps t("AAAAAAAAAAAAAAAAAAE1", "ZZZZZZZZZZZZZZZZZZE2");
-    t.a = trystero::app(t.f.io.get_executor(), t.f.net, std::move(a_config));
-    const ends e(t);
-    joined_in(t, {"r1", "r2"});
-    const std::array garbage{9, 9, 9};
-    t.f.net.inject(e.a(), trystero::protocol::room_frame(
-                              trystero::protocol::room_token(app_id, "r2"), garbage));
-    webcpp::test::require(
-        BOOST_TEST(run_until(t.f, [&] { return t.a_rooms[1].peers().empty(); }, 1ms)));
-    for (const auto* name : {"@_hsready", "@_leave"}) {
-        t.f.net.inject(e.a(), internal_frame("r2", name));
-    }
-    webcpp::trystero::test::advance(t.f, 200ms);
-    BOOST_TEST(t.a_rooms[1].peers().empty());  // refused, and kept
-    BOOST_TEST(run_until(t.f, [&] { return t.all_joined(); }, 11s));
-    const auto gone = std::ranges::count_if(
-        a_log, [](const std::string& line) { return line.find(" gone: ") != std::string::npos; });
-    BOOST_TEST_EQ(gone, 1);
-}
-
-// crossed connections recover: A's end of r1's pair and B's end of r2's open first, so each side
-// keeps another connection and holds the other as its second. B, the higher id, takes its second
-// once A sends on it, and its first's end closes A's second: both rooms join within 15 s of
-// virtual time, over one connection, and A never loses the peer.
-void crossed_connections_recover() {
-    fixture f{true};
-    auto a_config = app_config("AAAAAAAAAAAAAAAAAAF1");
-    a_config.ice_servers = {{.urls = {"stun:a.test"}, .username = {}, .credential = {}}};
-    std::vector a_log;
-    a_config.log = [&a_log](std::string_view, std::string_view text) { a_log.emplace_back(text); };
-    auto b_config = app_config("ZZZZZZZZZZZZZZZZZZF2");
-    b_config.ice_servers = {{.urls = {"stun:b.test"}, .username = {}, .credential = {}}};
-    trystero::app a(f.io.get_executor(), f.net, std::move(a_config));
-    trystero::app b(f.io.get_executor(), f.net, std::move(b_config));
-    std::vector a_made;
-    f.net.on_made = [&](std::size_t pc, std::span servers) {
-        if (!servers.empty() && servers[0].urls.at(0) == "stun:a.test") {
-            a_made.push_back(pc);
-        }
-    };
-    f.net.defer_opens = true;
-    auto a1 = join(a, "r1");
-    auto b1 = join(b, "r1");
-    webcpp::test::require(BOOST_TEST(
-        run_until(f, [&] { return !a_made.empty() && f.net.peer_of(a_made[0]) != a_made[0]; })));
-    const auto a_r1 = a_made[0];
-    const auto b_r1 = f.net.peer_of(a_r1);
-    auto a2 = join(a, "r2");
-    auto b2 = join(b, "r2");
-    webcpp::test::require(BOOST_TEST(
-        run_until(f, [&] { return a_made.size() >= 2 && f.net.peer_of(a_made[1]) != a_made[1]; })));
-    const auto a_r2 = a_made[1];
-    const auto b_r2 = f.net.peer_of(a_r2);
-    f.net.open(a_r1);
-    f.net.open(b_r2);
-    webcpp::trystero::test::advance(f, 100ms);
-    f.net.open(b_r1);
-    f.net.open(a_r2);
-    f.net.defer_opens = false;
-    const auto opened = f.net.steady_now();
-    BOOST_TEST(run_until(
-        f,
-        [&] {
-            return a1.peers().size() == 1 && a2.peers().size() == 1 && b1.peers().size() == 1 &&
-                   b2.peers().size() == 1;
-        },
-        15s));
-    BOOST_TEST(f.net.steady_now() - opened <= 15s);
-    BOOST_TEST(run_until(f, [&] { return f.net.live_connections() == 2U; }));
-    BOOST_TEST(std::ranges::none_of(
-        a_log, [](const std::string& line) { return line.find(" gone: ") != std::string::npos; }));
-}
-
-// A native channel can close on its transport thread during the adoption log, before the
-// room gets a binding. The queued close must not leave signaling permanently connected.
-void a_connection_closed_during_adoption_can_reconnect() {
-    fixture f{true};
-    auto config = app_config("AAAAAAAAAAAAAAAAAAF3");
-    std::vector made;
-    bool closed = false;
-    f.net.on_made = [&](std::size_t pc, std::span) {
-        made.push_back(pc);
-    };
-    config.log = [&](std::string_view category, std::string_view text) {
-        if (!closed && category == "webrtc" && text.ends_with(" adopted")) {
-            closed = true;
-            for (const auto pc : made) {
-                if (const auto connection = f.net.find(pc)) {
-                    connection->close();
-                }
-            }
-        }
-    };
-    trystero::app a(f.io.get_executor(), f.net, std::move(config));
-    trystero::app b(f.io.get_executor(), f.net, app_config("ZZZZZZZZZZZZZZZZZZF4"));
-    const auto a1 = join(a, "r1");
-    const auto b1 = join(b, "r1");
-    BOOST_TEST(run_until(f, [&] { return a1.peers().size() == 1 && b1.peers().size() == 1; }, 15s));
-    BOOST_TEST(closed);
-    BOOST_TEST_EQ(f.net.live_connections(), 2U);
-}
-
-// flood isolation. B floods r1 with 10,000 inline messages to an action without a handler
-// (A's queue keeps 1024) while r2 pings and chats: every r2 message arrives and every ping
-// completes without error while r1's flood is queued. The virtual clock stays fixed while posts
-// run; the interop test measures wall-clock latency.
-// Then, with a buffering channel, B sends a 5 MB transfer in r1 and, once
-// the channel holds more than 64 KiB, 20 chats in r2, which must wait for the drain :
-// none enters the channel at once, and every chat completes before the transfer does.
-void a_flood_in_one_room_does_not_starve_another() {
-    two_apps t("AAAAAAAAAAAAAAAAAAG1", "ZZZZZZZZZZZZZZZZZZG2");
-    const ends e(t);
-    joined_in(t, {"r1", "r2"});
-    const auto b_end = t.f.net.peer_of(e.a());
-    static_cast(t.a_rooms[0].make_action("unread"));  // made, no handler: queued
-    auto flood = t.b_rooms[0].make_action("unread");
-    for (std::size_t i = 0; i < 10'000; ++i) {
-        flood.async_send("x", [](boost::system::error_code) {});
-    }
-    std::vector r2_got;
-    auto r2_in = t.a_rooms[1].make_action("chat");
-    r2_in.on_message(
-        [&](const std::string& s, const trystero::message_info&) { r2_got.push_back(s); });
-    auto r2_out = t.b_rooms[1].make_action("chat");
-    for (std::size_t i = 0; i < 100; ++i) {
-        r2_out.async_send(std::to_string(i), [](boost::system::error_code) {});
-    }
-    std::vector pings;
-    for (std::size_t i = 0; i < 5; ++i) {
-        t.b_rooms[1].async_ping(t.a.self_id(),
-                                [&](boost::system::error_code ec, std::chrono::milliseconds rtt) {
-                                    if (!ec) {
-                                        pings.push_back(rtt);
-                                    }
-                                });
-    }
-    // A ping is recorded only without an error: five of them, and every r2 message, arrive while
-    // r1's 10,000 are queued at A.
-    BOOST_TEST(run_until(t.f, [&] { return pings.size() == 5 && r2_got.size() == 100; }, 10s));
-    t.f.net.channel_capacity = 1;
-    bool transfer_done = false;
-    std::size_t chats_done = 0;
-    bool chats_first = false;
-    auto big_in = t.a_rooms[0].make_action("big");
-    big_in.on_message([](const trystero::bytes&, const trystero::message_info&) {});
-    t.b_rooms[0].make_action("big").async_send(
-        trystero::bytes(5'000'000, std::uint8_t{1}),
-        [&](boost::system::error_code) { transfer_done = true; });
-    webcpp::test::require(BOOST_TEST(
-        poll_until(t.f, [&] { return t.f.net.buffered(b_end) > std::size_t{64} * 1024; })));
-    r2_got.clear();
-    const auto full = t.f.net.buffered(b_end);
-    for (std::size_t i = 0; i < 20; ++i) {
-        r2_out.async_send("c", [&](boost::system::error_code) {
-            if (++chats_done == 20) {
-                chats_first = !transfer_done;
-            }
-        });
-    }
-    BOOST_TEST_EQ(t.f.net.buffered(b_end), full);  // the chats wait for the drain, not inline
-    BOOST_TEST(run_until(t.f, [&] { return transfer_done && chats_done == 20; }, 60s));
-    BOOST_TEST(chats_first);
-    BOOST_TEST_EQ(r2_got.size(), 20U);
-}
-
-// A public app's rooms share one admission domain: B, already in lobby, can announce secret
-// and complete its passwordless handshake, so secret's broadcasts reach that shared peer.
-void a_passwordless_room_is_open_to_the_apps_other_rooms() {
-    two_apps t("AAAAAAAAAAAAAAAAAAH1", "ZZZZZZZZZZZZZZZZZZH2");
-    const ends e(t);
-    t.a_rooms.push_back(join(t.a, "lobby"));
-    t.a_rooms.push_back(join(t.a, "secret"));
-    t.b_rooms.push_back(join(t.b, "lobby"));
-    webcpp::test::require(BOOST_TEST(run_until(t.f, [&] {
-        return t.a_rooms[0].peers().size() == 1 && t.b_rooms[0].peers().size() == 1;
-    })));
-    std::size_t secret_broadcasts = 0;
-    t.f.net.filter = [&](std::size_t from, std::size_t, std::span frame) {
-        secret_broadcasts += from == e.a() && internal_name(frame, "secret") == "chat" ? 1 : 0;
-        return trystero::test::memory_network::verdict::deliver;
-    };
-    std::size_t secret_joins = 0;
-    t.a_rooms[1].on_peer_join([&](std::string_view) { ++secret_joins; });
-    t.f.net.inject(e.a(), trystero::protocol::presence_frame(
-                              trystero::protocol::room_token(app_id, "secret"), true));
-    t.f.net.inject(e.a(), internal_frame("secret", "@_hsready"));
-    BOOST_TEST(run_until(t.f, [&] { return secret_joins == 1; }, 1ms));
-    t.a_rooms[1].make_action("chat").async_send("to all",
-                                                             [](boost::system::error_code) {});
-    BOOST_TEST(run_until(t.f, [&] { return secret_broadcasts == 1; }, 1ms));
-}
-
-// A peer authenticated on r1 can still send a missing or incorrect room proof on r2. Those
-// failures keep their precise timeout and error behavior without mixing password domains.
-void invalid_room_proofs_fail_within_one_password_domain() {
-    for (const bool wrong_response : {false, true}) {
-        two_apps t("AAAAAAAAAAAAAAAAAAH3", "ZZZZZZZZZZZZZZZZZZH4", "pw");
-        joined_in(t, {"r1"});
-        if (wrong_response) {
-            corrupt_r2_responses(t);
-        } else {
-            drop_first_challenge(t);
-        }
-        t.a_rooms.push_back(join(t.a, "r2"));
-        std::vector errors;
-        t.a_rooms[1].on_error([&](std::string_view, boost::system::error_code ec,
-                                  std::string_view) { errors.push_back(ec); });
-        const auto joined = t.f.net.steady_now();
-        t.b_rooms.push_back(join(t.b, "r2", {.handshake_timeout = 30s}));
-        webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return !errors.empty(); }, 11s)));
-        BOOST_TEST(errors.front() == (wrong_response ? trystero::error::wrong_password
-                                                     : trystero::error::handshake_timed_out));
-        BOOST_TEST(t.f.net.steady_now() - joined == (wrong_response ? 0s : 10s));
-        BOOST_TEST(t.a_rooms[1].peers().empty());
-        BOOST_TEST_EQ(t.a_rooms[0].peers().size(), 1U);
-    }
-}
-
-// A's r2, in a resource of its own, sends 1 MB that waits on the full channel; A destroys
-// r2 while r1 goes on: once the posts have run, r2's resource has no bytes out, and r1 still
-// exchanges.
-void a_rooms_own_resource_returns_to_zero() {
-    counting_resource r2_memory;
-    two_apps t("AAAAAAAAAAAAAAAAAAI1", "ZZZZZZZZZZZZZZZZZZI2");
-    const ends e(t);
-    t.a_rooms.push_back(join(t.a, "r1"));
-    t.b_rooms.push_back(join(t.b, "r1"));
-    std::optional r2(join(t.a, "r2", {.memory = &r2_memory}));
-    t.b_rooms.push_back(join(t.b, "r2"));
-    webcpp::test::require(
-        BOOST_TEST(run_until(t.f, [&] { return t.all_joined() && r2->peers().size() == 1; })));
-    auto big_in = t.b_rooms[1].make_action("big");
-    big_in.on_message([](const trystero::bytes&, const trystero::message_info&) {});
-    t.f.net.channel_capacity = 1;
-    r2->make_action("big").async_send(trystero::bytes(1'000'000, std::uint8_t{3}),
-                                                       [](boost::system::error_code) {});
-    webcpp::test::require(BOOST_TEST(
-        poll_until(t.f, [&] { return t.f.net.buffered(e.a()) > std::size_t{64} * 1024; })));
-    r2.reset();
-    webcpp::trystero::test::advance(t.f, 1s);
-    BOOST_TEST_EQ(r2_memory.in_use, 0U);
-    std::vector got;
-    auto chat = t.b_rooms[0].make_action("chat");
-    chat.on_message([&](const std::string& s, const trystero::message_info&) { got.push_back(s); });
-    t.a_rooms[0].make_action("chat").async_send("after",
-                                                             [](boost::system::error_code) {});
-    BOOST_TEST(run_until(t.f, [&] { return got.size() == 1; }));
-}
-
-// Construction reserves the room before invoking a user log sink, including a reentrant join.
-void a_joining_log_cannot_join_the_same_room_twice() {
-    fixture f{true};
-    bool tried = false;
-    std::optional refused;
-    std::optional duplicate;
-    std::optional app;
-    auto config = app_config("AAAAAAAAAAAAAAAAAAT1");
-    config.log = [&](std::string_view, std::string_view text) {
-        if (!tried && app && text.starts_with("joining room r ")) {
-            tried = true;
-            auto again = app->join("r");
-            if (again) {
-                duplicate.emplace(std::move(*again));
-            } else {
-                refused = again.error();
-            }
-        }
-    };
-    app.emplace(f.io.get_executor(), f.net, std::move(config));
-    const auto room = join(*app, "r");
-    BOOST_TEST(tried);
-    BOOST_TEST(refused.has_value());
-    if (refused) {
-        BOOST_TEST(*refused == trystero::error::already_joined);
-    }
-    BOOST_TEST(!duplicate);
-}
-
-// A rejoin from the farewell log completes the old farewell; it must not gain a new timer when
-// that log returns to the original leave call.
-void a_leaving_log_can_finish_the_farewell_by_rejoining() {
-    fixture f{true};
-    bool acted = false;
-    std::size_t timers_after_rejoin = 0;
-    std::optional replacement;
-    std::optional app;
-    auto config = app_config("AAAAAAAAAAAAAAAAAAU1");
-    config.log = [&](std::string_view, std::string_view text) {
-        if (!acted && text == "leaving room r") {
-            acted = true;
-            replacement.emplace(join(*app, "r"));
-            timers_after_rejoin = f.net.scheduled();
-        }
-    };
-    app.emplace(f.io.get_executor(), f.net, std::move(config));
-    auto room = join(*app, "r");
-    std::size_t completions = 0;
-    room.async_leave([&](boost::system::error_code ec) {
-        BOOST_TEST(!ec);
-        ++completions;
-    });
-    BOOST_TEST(acted);
-    BOOST_TEST_EQ(f.net.scheduled(), timers_after_rejoin);
-    webcpp::trystero::test::advance(f, 200ms);
-    BOOST_TEST_EQ(completions, 1U);
-    BOOST_TEST(replacement.has_value());
-}
-
-// A join log runs user code before the join notification is posted. Leaving there must prevent
-// that notification, and destroying the room must not invalidate the peer identifier in use.
-void check_leaving_from_join_log(bool destroy) {
-    fixture f{true};
-    bool acted = false;
-    std::size_t joins = 0;
-    std::optional room;
-    auto config = app_config("AAAAAAAAAAAAAAAAAAQ1");
-    config.log = [&](std::string_view, std::string_view text) {
-        if (!acted && room && text.starts_with("peer joined: ")) {
-            acted = true;
-            if (destroy) {
-                room.reset();
-            } else {
-                room->async_leave([](boost::system::error_code) {});
-            }
-        }
-    };
-    trystero::app a(f.io.get_executor(), f.net, std::move(config));
-    trystero::app b(f.io.get_executor(), f.net, app_config("ZZZZZZZZZZZZZZZZZZQ2"));
-    room = join(a, "r");
-    room->on_peer_join([&](std::string_view) { ++joins; });
-    const auto remote = join(b, "r");
-    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return acted; })));
-    webcpp::trystero::test::advance(f, 200ms);
-    BOOST_TEST_EQ(joins, 0U);
-    BOOST_TEST(remote.peers().empty());
-}
-
-void a_join_log_can_leave_or_destroy_its_room() {
-    for (const bool destroy : {true, false}) {
-        check_leaving_from_join_log(destroy);
-    }
-}
-
-// The error callback selected after logging receives owned diagnostic text even if the sink
-// destroys the offending binding. A replacement callback installed by the sink takes effect.
-void check_leaving_from_error_log(bool destroy) {
-    bool acted = false;
-    std::size_t old_errors = 0;
-    std::size_t new_errors = 0;
-    std::optional room;
-    two_apps t("AAAAAAAAAAAAAAAAAAR1", "ZZZZZZZZZZZZZZZZZZR2", "pw");
-    auto config = app_config("AAAAAAAAAAAAAAAAAAR1", "pw");
-    config.log = [&](std::string_view, std::string_view text) {
-        if (!acted && room && text.ends_with("incorrect password for overlapping room")) {
-            acted = true;
-            room->on_error(
-                [&](std::string_view peer, boost::system::error_code ec, std::string_view what) {
-                    ++new_errors;
-                    BOOST_TEST_EQ(peer, "ZZZZZZZZZZZZZZZZZZR2");
-                    BOOST_TEST(ec == trystero::error::wrong_password);
-                    BOOST_TEST_EQ(what, "incorrect password for overlapping room");
-                });
-            if (destroy) {
-                room.reset();
-            } else {
-                room->async_leave([](boost::system::error_code) {});
-            }
-        }
-    };
-    t.a = trystero::app(t.f.io.get_executor(), t.f.net, std::move(config));
-    joined_in(t, {"r1"});
-    corrupt_r2_responses(t);
-    room = join(t.a, "r2");
-    room->on_error(
-        [&](std::string_view, boost::system::error_code, std::string_view) { ++old_errors; });
-    t.b_rooms.push_back(join(t.b, "r2"));
-    webcpp::test::require(BOOST_TEST(run_until(t.f, [&] { return acted; })));
-    webcpp::trystero::test::advance(t.f, 200ms);
-    BOOST_TEST_EQ(old_errors, 0U);
-    BOOST_TEST_EQ(new_errors, 1U);
-    BOOST_TEST_EQ(t.a_rooms[0].peers().size(), 1U);
-}
-
-void an_error_log_can_leave_or_destroy_its_room() {
-    for (const bool destroy : {true, false}) {
-        check_leaving_from_error_log(destroy);
-    }
-}
-
-// Installing a handler from the queue-limit log drains the existing queue synchronously. The
-// in-flight message must use that handler, or be discarded when the sink also leaves the room.
-void check_draining_from_queue_log(bool leave) {
-    fixture f{true};
-    bool acted = false;
-    std::size_t received = 0;
-    std::optional room;
-    std::optional> inbox;
-    auto config = app_config("AAAAAAAAAAAAAAAAAAS1");
-    config.log = [&](std::string_view, std::string_view text) {
-        if (!acted && text.starts_with("dropping the oldest unread message of ")) {
-            acted = true;
-            inbox->on_message(
-                [&](const std::string&, const trystero::message_info&) { ++received; });
-            if (leave) {
-                room.reset();
-            }
-        }
-    };
-    trystero::app a(f.io.get_executor(), f.net, std::move(config));
-    trystero::app b(f.io.get_executor(), f.net, app_config("ZZZZZZZZZZZZZZZZZZS2"));
-    room = join(a, "r");
-    auto remote = join(b, "r");
-    webcpp::test::require(BOOST_TEST(
-        run_until(f, [&] { return room->peers().size() == 1 && remote.peers().size() == 1; })));
-    inbox.emplace(room->make_action("unread"));
-    auto out = remote.make_action("unread");
-    for (std::size_t i = 0; i < 1025; ++i) {
-        out.async_send("x", [](boost::system::error_code) {});
-    }
-    webcpp::test::require(BOOST_TEST(run_until(f, [&] { return acted; })));
-    webcpp::trystero::test::advance(f, 200ms);
-    BOOST_TEST_EQ(received, leave ? 1024U : 1025U);
-}
-
-void a_queue_log_can_drain_or_destroy_its_room() {
-    for (const bool leave : {false, true}) {
-        check_draining_from_queue_log(leave);
-    }
-}
-
-// A synchronous log sink may end the room whose connection is being adopted. Neither a
-// destroyed room nor one in its farewell may regain a binding after the sink returns.
-void a_log_sink_can_leave_during_adoption() {
-    for (const bool destroy : {false, true}) {
-        fixture f{true};
-        std::optional leaving;
-        bool acted = false;
-        auto config = app_config("AAAAAAAAAAAAAAAAAAL1");
-        config.idle_timeout = 200ms;
-        config.log = [&](std::string_view category, std::string_view text) {
-            if (!acted && leaving && category == "webrtc" && text.ends_with(" adopted")) {
-                acted = true;
-                if (destroy) {
-                    leaving.reset();
-                } else {
-                    leaving->async_leave([](boost::system::error_code) {});
-                }
-            }
-        };
-        trystero::app a(f.io.get_executor(), f.net, std::move(config));
-        trystero::app b(f.io.get_executor(), f.net, app_config("ZZZZZZZZZZZZZZZZZZL2"));
-        const auto survivor = join(a, "survivor");
-        leaving = join(a, "departing");
-        auto remote = join(b, "departing");
-        std::size_t remote_joins = 0;
-        remote.on_peer_join([&](std::string_view) { ++remote_joins; });
-        webcpp::test::require(BOOST_TEST(run_until(f, [&] { return acted; }, 1s)));
-        webcpp::trystero::test::advance(f, 1ms);
-        if (leaving) {
-            BOOST_TEST(leaving->peers().empty());
-        }
-        BOOST_TEST_EQ(remote_joins, 0U);
-        webcpp::trystero::test::advance(f, 200ms);
-        BOOST_TEST_EQ(remote_joins, 0U);
-        webcpp::trystero::test::advance(f, 200ms);
-        BOOST_TEST_EQ(f.net.live_connections(), 0U);
-        auto other = join(b, "survivor");
-        BOOST_TEST(run_until(
-            f, [&] { return survivor.peers().size() == 1 && other.peers().size() == 1; }));
-    }
-}
-
-// Destroying another room from the adoption log must not leave a dangling token in the
-// advertised snapshot, or advertise that departed room after its withdrawal.
-void a_log_sink_can_destroy_another_room_during_adoption() {
-    fixture f{true};
-    std::optional retired;
-    bool acted = false;
-    auto config = app_config("AAAAAAAAAAAAAAAAAAM1");
-    config.idle_timeout = 0ms;
-    config.log = [&](std::string_view category, std::string_view text) {
-        if (!acted && retired && category == "webrtc" && text.ends_with(" adopted")) {
-            acted = true;
-            retired.reset();
-        }
-    };
-    trystero::app a(f.io.get_executor(), f.net, std::move(config));
-    trystero::app b(f.io.get_executor(), f.net, app_config("ZZZZZZZZZZZZZZZZZZM2"));
-    retired = join(a, "retired");
-    auto lobby = join(a, "lobby");
-    auto remote = join(b, "lobby");
-    std::size_t invalid_frames = 0;
-    std::size_t retired_after_leave = 0;
-    const auto retired_token = trystero::protocol::room_token(app_id, "retired");
-    f.net.filter = [&](std::size_t, std::size_t, std::span frame) {
-        const auto env = trystero::protocol::decode_envelope(frame);
-        invalid_frames += !env ? 1 : 0;
-        if (acted && env && env->type == trystero::protocol::envelope::kind::presence &&
-            env->token == retired_token && env->present) {
-            ++retired_after_leave;
-        }
-        return trystero::test::memory_network::verdict::deliver;
-    };
-    BOOST_TEST(
-        run_until(f, [&] { return lobby.peers().size() == 1 && remote.peers().size() == 1; }));
-    BOOST_TEST(acted);
-    BOOST_TEST_EQ(invalid_frames, 0U);
-    BOOST_TEST_EQ(retired_after_leave, 0U);
-    f.net.filter = {};
-}
-
-// A password challenge has a string nonce, as Trystero's handshake requires. A number or
-// null must not be silently converted into an empty challenge by the responder.
-void a_password_challenge_requires_a_string() {
-    for (const auto* const malformed :
-         {R"({"__trystero_pw":"challenge","c":null})", R"({"__trystero_pw":"challenge","c":42})"}) {
-        two_apps t("ZZZZZZZZZZZZZZZZZZN1", "AAAAAAAAAAAAAAAAAAN2", "pw");
-        const ends e(t);
-        joined_in(t, {"r1"});
-        t.f.net.filter = [](std::size_t, std::size_t, std::span frame) {
-            return internal_name(frame, "r2") == "@_hsdata"
-                       ? trystero::test::memory_network::verdict::drop
-                       : trystero::test::memory_network::verdict::deliver;
-        };
-        t.a_rooms.push_back(join(t.a, "r2"));
-        std::vector errors;
-        t.a_rooms[1].on_error([&](std::string_view, boost::system::error_code ec,
-                                  std::string_view) { errors.push_back(ec); });
-        t.b_rooms.push_back(join(t.b, "r2"));
-        webcpp::trystero::test::advance(t.f, 1ms);
-        t.f.net.filter = {};
-        t.f.net.inject(t.f.net.peer_of(e.a()), internal_frame("r2", "@_hsdata", malformed));
-        webcpp::trystero::test::advance(t.f, 1ms);
-        BOOST_TEST_EQ(errors.size(), 1U);
-        if (!errors.empty()) {
-            BOOST_TEST(errors.front() == trystero::error::wrong_password);
-        }
-        BOOST_TEST(t.a_rooms[1].peers().empty());
-        BOOST_TEST_EQ(t.a_rooms[0].peers().size(), 1U);
-    }
-}
-
-// A handshake message of protocol::max_handshake_bytes, a challenge with spaces before its closing
-// brace, is read and answered: A, the higher id, whose end is the other of the first connection
-// made, sends its proof and reports nothing. One byte longer fails the handshake before it is
-// read, as a message of the wrong shape does.
-void a_handshake_message_past_its_bound_fails() {
-    constexpr std::string_view challenge = R"({"__trystero_pw":"challenge","c":"nonce"})";
-    for (const std::size_t size :
-         {trystero::protocol::max_handshake_bytes, trystero::protocol::max_handshake_bytes + 1}) {
-        two_apps t("ZZZZZZZZZZZZZZZZZZN1", "AAAAAAAAAAAAAAAAAAN2", "pw");
-        const ends e(t);
-        joined_in(t, {"r1"});
-        std::size_t proofs = 0;
-        t.f.net.filter = [&](std::size_t from, std::size_t, std::span frame) {
-            if (internal_name(frame, "r2") != "@_hsdata") {
-                return trystero::test::memory_network::verdict::deliver;
-            }
-            const std::string_view text(reinterpret_cast(frame.data()), frame.size());
-            if (from == t.f.net.peer_of(e.a()) &&
-                text.find(R"("__trystero_pw":"response")") != std::string_view::npos) {
-                ++proofs;
-            }
-            return trystero::test::memory_network::verdict::drop;
-        };
-        t.a_rooms.push_back(join(t.a, "r2"));
-        std::vector errors;
-        t.a_rooms[1].on_error([&](std::string_view, boost::system::error_code ec,
-                                  std::string_view) { errors.push_back(ec); });
-        t.b_rooms.push_back(join(t.b, "r2"));
-        webcpp::trystero::test::advance(t.f, 1ms);
-        std::string message(challenge.substr(0, challenge.size() - 1));
-        message.append(size - challenge.size(), ' ');
-        message += '}';
-        BOOST_TEST_EQ(message.size(), size);
-        t.f.net.inject(t.f.net.peer_of(e.a()), internal_frame("r2", "@_hsdata", message));
-        webcpp::trystero::test::advance(t.f, 1ms);
-        if (size == trystero::protocol::max_handshake_bytes) {
-            BOOST_TEST_EQ(proofs, 1U);
-            BOOST_TEST(errors.empty());
-        } else {
-            BOOST_TEST_EQ(proofs, 0U);
-            BOOST_TEST_EQ(errors.size(), 1U);
-            if (!errors.empty()) {
-                BOOST_TEST(errors.front() == trystero::error::wrong_password);
-            }
-            BOOST_TEST(t.a_rooms[1].peers().empty());
-        }
-        BOOST_TEST_EQ(t.a_rooms[0].peers().size(), 1U);
-    }
-}
-
-// Connections and room tokens from a passwordless app never reach a protected app's registry,
-// in either peer-id order. Different password domains have distinct app states and peer ids.
-void check_public_connection_isolation(bool protected_lower) {
-    two_apps t("MMMMMMMMMMMMMMMMMMM1", "NNNNNNNNNNNNNNNNNNN2");
-    const ends e(t);
-    t.a_rooms.push_back(join(t.a, "lobby"));
-    t.a_rooms.push_back(join(t.a, "secret"));
-    t.b_rooms.push_back(join(t.b, "lobby"));
-    webcpp::test::require(BOOST_TEST(run_until(t.f, [&] {
-        return t.a_rooms[0].peers().size() == 1 && t.b_rooms[0].peers().size() == 1;
-    })));
-    trystero::app protected_app(
-        t.f.io.get_executor(), t.f.net,
-        app_config(protected_lower ? "AAAAAAAAAAAAAAAAAAA3" : "ZZZZZZZZZZZZZZZZZZZ3", "pw"));
-    auto vault = join(protected_app, "vault");
-    const auto protected_lobby = join(protected_app, "lobby");
-    BOOST_TEST(protected_app.self_id() != t.a.self_id());
-    BOOST_TEST(protected_app.self_id() != t.b.self_id());
-    std::size_t secret_frames = 0;
-    std::size_t vault_frames = 0;
-    t.f.net.filter = [&](std::size_t, std::size_t, std::span frame) {
-        secret_frames += internal_name(frame, "secret") == "chat" ? 1 : 0;
-        vault_frames += internal_name(frame, "vault") == "private" ? 1 : 0;
-        return trystero::test::memory_network::verdict::deliver;
-    };
-    for (const auto* const room : {"secret", "vault"}) {
-        t.f.net.inject(e.a(), trystero::protocol::presence_frame(
-                                  trystero::protocol::room_token(app_id, room), true));
-        t.f.net.inject(e.a(), internal_frame(room, "@_hsdata",
-                                             R"({"__trystero_pw":"challenge","c":"unverified"})"));
-        t.f.net.inject(e.a(), internal_frame(room, "@_hsready"));
-    }
-    webcpp::trystero::test::advance(t.f, 1ms);
-    BOOST_TEST_EQ(t.a_rooms[1].peers().size(), 1U);
-    BOOST_TEST(vault.peers().empty());
-    BOOST_TEST(protected_lobby.peers().empty());
-    t.a_rooms[1].make_action("chat").async_send("public",
-                                                             [](boost::system::error_code) {});
-    vault.make_action("private").async_send("protected",
-                                                         [](boost::system::error_code) {});
-    webcpp::trystero::test::advance(t.f, 12s);
-    BOOST_TEST_EQ(secret_frames, 1U);
-    BOOST_TEST_EQ(vault_frames, 0U);
-    BOOST_TEST(vault.peers().empty());
-    BOOST_TEST(protected_lobby.peers().empty());
-    BOOST_TEST_EQ(t.a_rooms[0].peers().size(), 1U);
-    t.f.net.filter = {};
-}
-
-void a_public_connection_never_reaches_a_protected_app() {
-    for (const bool protected_lower : {true, false}) {
-        check_public_connection_isolation(protected_lower);
-    }
-}
-
-}  // namespace
-
-int main(int argc, const char* const argv[]) {
-    const auto cases = std::to_array>({
-        {
-            "a_joining_log_cannot_join_the_same_room_twice",
-            a_joining_log_cannot_join_the_same_room_twice,
-        },
-        {
-            "a_leaving_log_can_finish_the_farewell_by_rejoining",
-            a_leaving_log_can_finish_the_farewell_by_rejoining,
-        },
-        {"a_join_log_can_leave_or_destroy_its_room", a_join_log_can_leave_or_destroy_its_room},
-        {"an_error_log_can_leave_or_destroy_its_room", an_error_log_can_leave_or_destroy_its_room},
-        {"a_queue_log_can_drain_or_destroy_its_room", a_queue_log_can_drain_or_destroy_its_room},
-        {"a_password_challenge_requires_a_string", a_password_challenge_requires_a_string},
-        {"a_handshake_message_past_its_bound_fails", a_handshake_message_past_its_bound_fails},
-        {
-            "invalid_room_proofs_fail_within_one_password_domain",
-            invalid_room_proofs_fail_within_one_password_domain,
-        },
-        {"a_log_sink_can_leave_during_adoption", a_log_sink_can_leave_during_adoption},
-        {
-            "a_log_sink_can_destroy_another_room_during_adoption",
-            a_log_sink_can_destroy_another_room_during_adoption,
-        },
-        {
-            "a_public_connection_never_reaches_a_protected_app",
-            a_public_connection_never_reaches_a_protected_app,
-        },
-        {"a_rooms_own_resource_returns_to_zero", a_rooms_own_resource_returns_to_zero},
-        {
-            "a_passwordless_room_is_open_to_the_apps_other_rooms",
-            a_passwordless_room_is_open_to_the_apps_other_rooms,
-        },
-        {"crossed_connections_recover", crossed_connections_recover},
-        {
-            "a_connection_closed_during_adoption_can_reconnect",
-            a_connection_closed_during_adoption_can_reconnect,
-        },
-        {
-            "a_flood_in_one_room_does_not_starve_another",
-            a_flood_in_one_room_does_not_starve_another,
-        },
-        {"every_room_has_the_apps_id", every_room_has_the_apps_id},
-        {
-            "each_setup_report_reaches_the_current_handler_once",
-            each_setup_report_reaches_the_current_handler_once,
-        },
-        {"joining_is_refused_twice_and_beyond_64", joining_is_refused_twice_and_beyond_64},
-        {"two_apps_with_one_id_never_meet", two_apps_with_one_id_never_meet},
-        {"two_rooms_share_one_connection", two_rooms_share_one_connection},
-        {"three_rooms_share_one_connection", three_rooms_share_one_connection},
-        {"a_second_connection_is_dropped", a_second_connection_is_dropped},
-        {"a_moved_from_app_releases_nothing", a_moved_from_app_releases_nothing},
-        {"an_app_destroyed_leaves_its_rooms_going", an_app_destroyed_leaves_its_rooms_going},
-        {"an_app_assigned_over_releases_its_state", an_app_assigned_over_releases_its_state},
-        {"an_app_assigned_to_itself_keeps_its_state", an_app_assigned_to_itself_keeps_its_state},
-        {"frames_before_presence_bind_their_room", frames_before_presence_bind_their_room},
-        {"a_kept_frame_that_kicks_during_a_binding", a_kept_frame_that_kicks_during_a_binding},
-        {"a_kept_frame_binds_its_room", a_kept_frame_binds_its_room},
-        {"a_leaving_room_binds_no_one", a_leaving_room_binds_no_one},
-        {"a_connections_end_is_every_rooms", a_connections_end_is_every_rooms},
-        {"a_late_join_binds_over_the_connection", a_late_join_binds_over_the_connection},
-        {"a_forged_announcement_binds_nothing", a_forged_announcement_binds_nothing},
-        {"a_kick_is_per_room", a_kick_is_per_room},
-        {"one_room_leaves", one_room_leaves},
-        {
-            "a_peer_leaving_every_room_idles_the_connection",
-            a_peer_leaving_every_room_idles_the_connection,
-        },
-        {"an_action_level_kick_is_per_room", an_action_level_kick_is_per_room},
-        {
-            "a_connection_failing_under_a_waiting_transfer",
-            a_connection_failing_under_a_waiting_transfer,
-        },
-        {"a_room_left_can_be_joined_again", a_room_left_can_be_joined_again},
-        {"join_and_leave_sequences_on_one_id", join_and_leave_sequences_on_one_id},
-        {"the_farewell_binds_nothing", the_farewell_binds_nothing},
-        {"the_last_user_closes_every_connection", the_last_user_closes_every_connection},
-        {
-            "the_io_context_destroyed_with_operations_pending",
-            the_io_context_destroyed_with_operations_pending,
-        },
-        {"the_rebinding_step", the_rebinding_step},
-        {"an_incorrect_proof_rebinds_at_the_steps", an_incorrect_proof_rebinds_at_the_steps},
-        {"a_kick_that_closes_the_connection", a_kick_that_closes_the_connection},
-        {
-            "a_lost_presence_is_replaced_by_the_peers_frames",
-            a_lost_presence_is_replaced_by_the_peers_frames,
-        },
-        {"a_transient_failure_converges", a_transient_failure_converges},
-        {"an_answer_to_an_old_challenge", an_answer_to_an_old_challenge},
-        {"a_corrected_response_rejoins", a_corrected_response_rejoins},
-        {"a_kept_leave_discards_what_came_before", a_kept_leave_discards_what_came_before},
-    });
-    std::size_t ran = 0;
-    for (const auto& [name, run] : cases) {
-        if (argc == 1 || name == argv[1]) {
-            run();
-            ++ran;
-        }
-    }
-    BOOST_TEST(ran != 0);
-    // Under Asyncify, a main that suspended loses what it returns: the status goes first.
-    return webcpp::test::exit_status(boost::report_errors());
-}
diff --git a/test/signaling_test.cpp b/test/signaling_test.cpp
index 32d4302..e2a521e 100644
--- a/test/signaling_test.cpp
+++ b/test/signaling_test.cpp
@@ -5,11 +5,12 @@
 // https://www.boost.org/LICENSE_1_0.txt)
 
 // Tests the signaling and the Nostr strategy alone, over the memory backend, on both targets. As
-// an answerer, the signaling publishes the bytes Trystero JS 0.26.0's own signal handler published
-// for the same offers, which the original's oracle wrote into fixtures/expected/expected.json, the
-// test's one argument: its sealer gives Trystero's sealed texts, and its peer connections the
-// oracle's answer and candidate. Each text a strategy or a signaling reads is bounded: a relay's
-// text or a signal at its bound is read, one byte longer is dropped.
+// an answerer, the signaling publishes the bytes Trystero JS 0.27.0's own signal handler published
+// for the same offers, which the original's oracle wrote into fixtures/oracle/expected.json, the
+// test's one argument, but for each sealed text, sealed under an IV of its own: it opens, with its
+// AAD, to the plaintext 0.27.0 sealed there; its peer connections give the oracle's answer and
+// candidate. Each text a strategy or a signaling reads is bounded: a relay's text or a signal at
+// its bound is read, one byte longer is dropped.
 
 #include 
 #include 
@@ -19,8 +20,12 @@
 #include 
 #include 
 #include 
+#include 
+#include 
 #include 
 
+#include 
+
 #include "support/memory_backend.hpp"
 
 #include 
@@ -33,11 +38,18 @@
 #include 
 #include 
 
+#include 
+#include 
+#include 
 #include 
+#include 
+#include 
 #include 
+#include 
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -126,6 +138,11 @@ class answering_connection final : public backend::peer_connection,
 
     [[nodiscard]] bool has_remote_description() const override { return !remote_sdp.empty(); }
 
+    /** No SCTP transport: the signaling never asks. */
+    [[nodiscard]] std::optional max_message_size() const override {
+        return std::nullopt;
+    }
+
     void close() override {}
 
     /** The description the signaling applied: the offer it opened. */
@@ -164,62 +181,34 @@ class answering_network final : public memory_network {
     std::string candidate_;
 };
 
-/**
- * A sealer that seals and opens as Trystero JS did for the oracle: each plaintext the oracle
- * sealed becomes the text Trystero's encrypt made of it, and that text opens to it again. Any
- * other text fails, as one sealed under another key does, and is counted.
- */
-class oracle_sealer final : public backend::sealer {
-public:
-    oracle_sealer(asio::io_context& io, const fixture_value& sealed) : io_(io) {
-        for (const auto entry : sealed) {
-            table_.emplace_back(str(entry["plaintext"]), str(entry["text"]));
-        }
-    }
-
-    void seal(std::string_view plaintext,
-              trystero::handler done) override {
-        reply(find(plaintext, true), std::move(done));
-    }
-
-    void open(std::string_view sealed,
-              trystero::handler done) override {
-        ++opened;
-        reply(find(sealed, false), std::move(done));
-    }
-
-    /** How many texts it was asked to open. */
-    std::size_t opened = 0;
-    /** How many texts it did not know, which a test of Trystero's texts never gives. */
-    std::size_t unknown = 0;
+/** The key of the oracle's room, which has no password. */
+webcpp::crypto::secret<32> room_key(const fixture_value& oracle) {
+    return tp::room_aes_key_without_password(str(oracle["app_id"]), str(oracle["room_id"]));
+}
 
-private:
-    /** The sealed text of a plaintext, or the plaintext of a sealed text; nothing for another. */
-    [[nodiscard]] std::optional find(std::string_view text, bool plaintext) const {
-        for (const auto& [plain, sealed] : table_) {
-            if ((plaintext ? plain : sealed) == text) {
-                return plaintext ? sealed : plain;
-            }
-        }
-        return std::nullopt;
-    }
+/** `text` with its one `from` replaced by `to`; the case fails when it holds none. */
+std::string replaced(std::string_view text, std::string_view from, std::string_view to) {
+    std::string out(text);
+    const auto at = out.find(from);
+    require(BOOST_TEST(!from.empty() && at != std::string::npos));
+    out.replace(at, from.size(), to);
+    return out;
+}
 
-    void reply(std::optional text,
-               trystero::handler done) {
-        if (!text) {
-            ++unknown;
-        }
-        post_in(io_, memory(), [text = std::move(text), done = std::move(done)]() mutable {
-            if (text) {
-                done({}, *text);
-            } else {
-                done(make_error_code(trystero::error::wrong_password), {});
-            }
-        });
+/** A signal's text, read as a room reads it; the case fails when it is not one. */
+struct read_signal_text {
+    explicit read_signal_text(std::string_view text)
+        : document(webcpp::document::parse(text,
+                                           tp::json::protocol_limits(tp::max_parsed_signal_bytes),
+                                           std::pmr::polymorphic_allocator(memory()))) {
+        require(BOOST_TEST(document.has_value()));
+        message = tp::read_signal(document->root());
+        require(BOOST_TEST(message.has_value()));
     }
 
-    asio::io_context& io_;
-    std::vector> table_;
+    decltype(webcpp::document::parse(std::string_view(), tp::json::protocol_limits(0),
+                                     std::pmr::polymorphic_allocator())) document;
+    std::optional message;
 };
 
 /** A signal the signaling published. */
@@ -229,23 +218,22 @@ struct published_signal {
     std::string text;
 };
 
-/** A signaling of the oracle's room and self id, over its sealer and an answering network. */
+/** A signaling of the oracle's room and self id, under its room key, over an answering network. */
 struct answerer {
     asio::io_context io;
     answering_network net;
-    std::shared_ptr sealer;
     std::vector published;
     std::vector failures;
+    /** What the signaling's should_connect answers. */
+    bool wanted = true;
     std::shared_ptr signaling;
 
     explicit answerer(const fixture_value& oracle)
-        : net(io, str(oracle["answer_sdp"]), str(oracle["candidate"])),
-          sealer(std::make_shared(io, oracle["sealed"])) {
+        : net(io, str(oracle["answer_sdp"]), str(oracle["candidate"])) {
         signaling = std::make_shared(
-            net, sealer, str(oracle["app_id"]), str(oracle["room_id"]), str(oracle["self_id"]),
+            net, str(oracle["app_id"]), str(oracle["room_id"]), str(oracle["self_id"]),
             std::span(),
             detail::signaling::callbacks{
-                .claim = {},
                 .publish =
                     [this](std::size_t relay, std::string_view topic, std::string_view content) {
                         published.push_back({
@@ -255,10 +243,11 @@ struct answerer {
                         });
                     },
                 .connected = {},
-                .failed = [this](std::string_view, boost::system::error_code ec,
-                                 std::string_view) { failures.push_back(ec); },
+                .failed = [this](const trystero::room_error& e) { failures.push_back(e.code); },
+                .should_connect = [this](std::string_view) { return wanted; },
             },
-            detail::logger(), memory(), memory());
+            detail::logger(), memory());
+        signaling->set_key(room_key(oracle));
     }
 
     /** Hands `text` to the signaling, as a relay's on the room's self topic, then runs what is
@@ -269,10 +258,30 @@ struct answerer {
     }
 };
 
+/** Checks a published signal against the one 0.27.0 published: its relay, its topic, what its
+ * sealed text opens to, and its bytes but for that text. */
+void check_published(const fixture_value& oracle, const published_signal& published,
+                     const fixture_value& signal) {
+    BOOST_TEST_EQ(published.relay, 0U);
+    BOOST_TEST_EQ(published.topic, str(signal["topic"]));
+    const read_signal_text read(published.text);
+    const auto& m = *read.message;
+    const bool answer = !m.answer.empty();
+    const auto sealed = answer ? m.answer : m.candidate;
+    const auto aad =
+        tp::signal_aad(answer ? "answer" : "candidate", str(oracle["self_id"]), m.offer_id);
+    const auto plain = tp::open(room_key(oracle), sealed, std::string_view(aad));
+    if (BOOST_TEST(plain.has_value())) {
+        BOOST_TEST_EQ(*plain, str(signal["plaintext"]));
+        BOOST_TEST_EQ(published.text, replaced(str(signal["text"]), str(signal["sealed"]), sealed));
+    }
+}
+
 // For each offer, the signaling opens it, applies it to an answering connection, and publishes the
-// answer, then the candidate it held, on the offerer's topic, each written as Trystero's answerer
-// writes it: {peerId, answer, offerId} and {peerId, candidate, offerId}, its offerId last, or none
-// for an offer that had none. The bytes are Trystero's, member for member.
+// answer, then the candidate it held, on the offerer's topic, each written as 0.27.0's answerer
+// writes it: {peerId, offerId, answer} and {peerId, offerId, candidate}. The bytes are 0.27.0's,
+// member for member, but for each sealed text, which opens with the AAD of its type, the answerer
+// and the offer id to what 0.27.0 sealed there.
 void an_answerers_signals_are_trysteros(const fixture_value& oracle) {
     const auto cases = oracle["cases"];
     BOOST_TEST_EQ(cases.size(), 2U);
@@ -282,20 +291,17 @@ void an_answerers_signals_are_trysteros(const fixture_value& oracle) {
         BOOST_TEST_EQ(a.net.connections.size(), 1U);
         if (!a.net.connections.empty()) {
             BOOST_TEST_EQ(a.net.connections[0]->remote_type, "offer");
-            BOOST_TEST_EQ(a.net.connections[0]->remote_sdp, str(oracle["sealed"][0]["plaintext"]));
+            BOOST_TEST_EQ(a.net.connections[0]->remote_sdp, str(oracle["offer_sdp"]));
         }
         const auto expected = c["published"];
         BOOST_TEST_EQ(a.published.size(), expected.size());
         std::size_t i = 0;
         for (const auto signal : expected) {
             if (i < a.published.size()) {
-                BOOST_TEST_EQ(a.published[i].relay, 0U);
-                BOOST_TEST_EQ(a.published[i].topic, str(signal["topic"]));
-                BOOST_TEST_EQ(a.published[i].text, str(signal["text"]));
+                check_published(oracle, a.published[i], signal);
             }
             ++i;
         }
-        BOOST_TEST_EQ(a.sealer->unknown, 0U);
         BOOST_TEST(a.failures.empty());
     }
 }
@@ -310,29 +316,48 @@ std::string padded(std::string_view text, std::size_t size) {
 }
 
 // A signal of protocol::max_parsed_signal_bytes, the oracle's first offer with spaces, is read and
-// answered; one byte longer is dropped before it is read: nothing is opened, made or published.
+// answered; one byte longer is dropped before it is read: nothing is made or published.
 void a_signal_past_its_bound_is_dropped(const fixture_value& oracle) {
-    const auto offer = str(oracle["cases"][0]["offer"]);
+    const std::string offer(str(oracle["cases"][0]["offer"]));
     {
         answerer a(oracle);
         a.receive(padded(offer, tp::max_parsed_signal_bytes));
-        BOOST_TEST_EQ(a.sealer->opened, 1U);
         BOOST_TEST_EQ(a.net.connections.size(), 1U);
         BOOST_TEST_EQ(a.published.size(), 2U);
     }
     {
         answerer a(oracle);
         a.receive(padded(offer, tp::max_parsed_signal_bytes + 1));
-        BOOST_TEST_EQ(a.sealer->opened, 0U);
         BOOST_TEST(a.net.connections.empty());
         BOOST_TEST(a.published.empty());
+        BOOST_TEST(a.failures.empty());
     }
 }
 
+// The offer of a peer its room does not want, as 0.27.0's signal handler asks shouldConnectPeer
+// (a full room's refused user), is ignored: no connection, no answer, no report. The same offer
+// once the peer is wanted is answered.
+void an_unwanted_peers_offer_is_ignored(const fixture_value& oracle) {
+    const std::string offer(str(oracle["cases"][0]["offer"]));
+    answerer a(oracle);
+    a.wanted = false;
+    a.receive(offer);
+    BOOST_TEST(a.net.connections.empty());
+    BOOST_TEST(a.published.empty());
+    BOOST_TEST(a.failures.empty());
+    a.wanted = true;
+    a.receive(offer);
+    BOOST_TEST_EQ(a.net.connections.size(), 1U);
+    BOOST_TEST_EQ(a.published.size(), 2U);
+}
+
 /** A relay's connection that keeps what the strategy sends it. */
 class recording_socket final : public backend::websocket {
 public:
-    void send(std::string_view text) override { sent.emplace_back(text); }
+    bool send(std::string_view text) override {
+        sent.emplace_back(text);
+        return true;
+    }
 
     void close() override { closed = true; }
 
@@ -353,9 +378,12 @@ class relaying_network final : public memory_network {
                                                 std::pmr::memory_resource* /*memory*/) override {
         handlers = std::move(h);
         socket = std::make_shared();
+        ++connects;
         return socket;
     }
 
+    /** How many connections were made. */
+    std::size_t connects = 0;
     /** The handlers of the last connection made. */
     backend::websocket::handlers handlers;
     /** That connection. */
@@ -392,7 +420,7 @@ void a_relay_text_past_its_bound_is_dropped() {
     const auto strategy = std::make_shared(
         net, std::span(&url, 1),
         std::pmr::vector({std::pmr::string(topic, memory())}, memory()), topic,
-        [] { return std::pmr::string(R"({"peerId":"p"})", memory()); },
+        [](std::string_view /*nonce*/) { return std::pmr::string(R"({"peerId":"p"})", memory()); },
         [&contents](std::size_t, std::string_view, std::string_view content) {
             contents.push_back(content.size());
         },
@@ -448,7 +476,7 @@ void a_relay_text_past_its_depth_is_dropped() {
     const auto strategy = std::make_shared(
         net, std::span(&url, 1),
         std::pmr::vector({std::pmr::string(topic, memory())}, memory()), topic,
-        [] { return std::pmr::string(R"({"peerId":"p"})", memory()); },
+        [](std::string_view /*nonce*/) { return std::pmr::string(R"({"peerId":"p"})", memory()); },
         [&contents](std::size_t, std::string_view, std::string_view content) {
             contents.emplace_back(content);
         },
@@ -471,12 +499,662 @@ void a_relay_text_past_its_depth_is_dropped() {
     strategy->stop();
 }
 
+/**
+ * A strategy over one relay of the test's, on the virtual clock, open unless asked otherwise: it
+ * subscribed and made its first announcement. It announces `{"peerId":"p","nonce":}`, as a
+ * room does, and keeps what it logs and the messages it hands on.
+ */
+struct relay_harness {
+    explicit relay_harness(std::pmr::vector topics, bool open = true) {
+        strategy = std::make_shared(
+            net, std::span(&url, 1), std::move(topics), announce_topic,
+            [](std::string_view nonce) {
+                return tp::write_signal({.peer_id = "p"}, nonce, memory());
+            },
+            [this](std::size_t, std::string_view topic, std::string_view) {
+                heard.emplace_back(topic);
+            },
+            detail::logger(
+                [this](std::string_view, std::string_view text) { logged.emplace_back(text); },
+                memory()),
+            memory());
+        strategy->start();
+        if (open) {
+            opens();
+        }
+    }
+
+    /** A strategy of one other topic and the root topic, open unless `open` is false. */
+    explicit relay_harness(bool open = true)
+        : relay_harness(
+              std::pmr::vector(
+                  {std::pmr::string("self", memory()), std::pmr::string(announce_topic, memory())},
+                  memory()),
+              open) {}
+
+    relay_harness(const relay_harness&) = delete;
+    relay_harness& operator=(const relay_harness&) = delete;
+
+    // The strategy's stop allocates the CLOSE messages it sends; a failure to allocate there ends
+    // the test, as in any destructor.
+    // NOLINTNEXTLINE(bugprone-exception-escape)
+    ~relay_harness() { strategy->stop(); }
+
+    /** The texts of `type` the strategy sent, parsed, in order. */
+    [[nodiscard]] std::vector sent(std::string_view type) const {
+        std::vector out;
+        for (const auto& text : net.socket->sent) {
+            auto parsed = webcpp::document::parse(text);
+            if (parsed.has_value() && str(parsed->root()[0]) == type) {
+                out.push_back(std::move(*parsed));
+            }
+        }
+        return out;
+    }
+
+    /** The id of the strategy's first subscription. */
+    [[nodiscard]] std::string subscription() const {
+        const auto requests = sent("REQ");
+        require(BOOST_TEST(!requests.empty()));
+        return std::string(str(requests.front().root()[1]));
+    }
+
+    /** How many events the strategy sent. */
+    [[nodiscard]] std::size_t events() const { return sent("EVENT").size(); }
+
+    /** Whether a signal published now goes out: it is the last text sent. */
+    [[nodiscard]] bool publishes() const {
+        const auto before = net.socket->sent.size();
+        strategy->publish(0, "a-peer-topic", "probe");
+        return net.socket->sent.size() == before + 1;
+    }
+
+    /** Opens the strategy's last connection, as the relay accepts it. */
+    void opens() {
+        require(BOOST_TEST(net.socket != nullptr && static_cast(net.handlers.open)));
+        net.handlers.open();
+        require(BOOST_TEST(net.poll_ready()));
+    }
+
+    /** Closes the strategy's connection, as the relay goes away, and opens the one it makes
+     * next, which comes within the first reconnection bound, 3333 ms. */
+    void reopens() {
+        net.handlers.close();
+        wait(std::chrono::milliseconds(3333));
+        require(BOOST_TEST_EQ(net.connects, 2U));
+        opens();
+    }
+
+    /** How many REQs the strategy sent on its connection. */
+    [[nodiscard]] std::size_t requests() const { return sent("REQ").size(); }
+
+    /** Hands the strategy `text` as the relay's. */
+    void relay_says(std::string_view text) { net.handlers.message(text); }
+
+    /** Moves the virtual clock by `by`. */
+    void wait(std::chrono::milliseconds by) { require(BOOST_TEST(net.advance(by))); }
+
+    /** Whether a logged sentence holds `part`. */
+    [[nodiscard]] bool logged_with(std::string_view part) const {
+        return std::ranges::any_of(logged, [part](const std::string& line) {
+            return line.find(part) != std::string::npos;
+        });
+    }
+
+    static constexpr std::string_view announce_topic = "the-room-topic";
+    asio::io_context io;
+    relaying_network net{io};
+    const std::pmr::string url{"wss://relay.test", memory()};
+    std::vector logged;
+    std::vector heard;
+    std::shared_ptr strategy;
+};
+
+/** A relay's OK of an event, refused with `reason`, or accepted. */
+std::string ok_text(bool accepted, std::string_view reason) {
+    std::pmr::string out(R"(["OK",")", memory());
+    out.append(64, 'a');
+    out += accepted ? R"(",true,)" : R"(",false,)";
+    require(BOOST_TEST(webcpp::document::quote(reason, out).has_value()));
+    out += ']';
+    return std::string(out);
+}
+
+/** A relay's `[type, subscription, reason]`, or `[type, subscription]` with no reason. */
+std::string relay_text(std::string_view type, std::string_view subscription,
+                       std::optional reason = std::nullopt) {
+    std::pmr::string out("[", memory());
+    require(BOOST_TEST(webcpp::document::quote(type, out).has_value()));
+    out += ',';
+    require(BOOST_TEST(webcpp::document::quote(subscription, out).has_value()));
+    if (reason) {
+        out += ',';
+        require(BOOST_TEST(webcpp::document::quote(*reason, out).has_value()));
+    }
+    out += ']';
+    return std::string(out);
+}
+
+// A strategy of 600 topics subscribes on a relay in three REQs, of 250, 250 and 100 topics, each
+// under an id of its own of 64 characters, since a minute before now. Each lists the kinds of its
+// topics once, in the order of their first topic, which are fewer than its topics where two share
+// a kind; an event of a topic of the third reaches the room under the third's id. Stopping closes
+// all three; a time before a minute after the epoch subscribes since the epoch.
+void subscriptions_hold_250_topics_and_distinct_kinds() {
+    std::pmr::vector topics(memory());
+    for (std::size_t i = 0; i < 600; ++i) {
+        topics.emplace_back("topic-" + std::to_string(i));
+    }
+    const std::vector names(topics.begin(), topics.end());
+    relay_harness h(std::move(topics));
+    const auto requests = h.sent("REQ");
+    require(BOOST_TEST_EQ(requests.size(), 3U));
+    std::set ids;
+    bool shared_kind = false;
+    const auto since = h.net.unix_now() - std::chrono::seconds(60);
+    for (std::size_t r = 0; r < requests.size(); ++r) {
+        const auto req = requests[r].root();
+        const auto id = str(req[1]);
+        BOOST_TEST_EQ(id.size(), 64U);
+        ids.emplace(id);
+        const auto filter = req[2];
+        BOOST_TEST_EQ(filter["since"].value_or(std::int64_t{-1}), since.time_since_epoch().count());
+        const std::size_t first = r * 250;
+        const std::size_t count = std::min(250, names.size() - first);
+        BOOST_TEST_EQ(filter["#x"].size(), count);
+        std::vector expected;
+        for (std::size_t i = 0; i < count; ++i) {
+            BOOST_TEST_EQ(str(filter["#x"][i]), names[first + i]);
+            const std::int64_t k = tp::nostr::topic_kind(names[first + i]);
+            if (std::ranges::find(expected, k) == expected.end()) {
+                expected.push_back(k);
+            }
+        }
+        shared_kind = shared_kind || expected.size() < count;
+        std::vector kinds;
+        for (const auto k : filter["kinds"]) {
+            kinds.push_back(k.value_or(std::int64_t{-1}));
+        }
+        BOOST_TEST_ALL_EQ(kinds.begin(), kinds.end(), expected.begin(), expected.end());
+    }
+    BOOST_TEST_EQ(ids.size(), 3U);
+    BOOST_TEST(shared_kind);
+    const auto third = std::string(str(requests[2].root()[1]));
+    h.relay_says(relay_event(third, names[599], std::string(64, '3'), 300));
+    h.relay_says(relay_event("not-ours", names[599], std::string(64, '4'), 300));
+    const std::vector heard{names[599]};
+    BOOST_TEST_ALL_EQ(h.heard.begin(), h.heard.end(), heard.begin(), heard.end());
+    h.strategy->stop();
+    const auto closes = h.sent("CLOSE");
+    BOOST_TEST_EQ(closes.size(), 3U);
+    for (const auto& c : closes) {
+        BOOST_TEST(ids.contains(std::string(str(c.root()[1]))));
+    }
+    BOOST_TEST(tp::nostr::subscribe_since(std::chrono::sys_seconds(std::chrono::seconds(30))) ==
+               std::chrono::sys_seconds());
+}
+
+// Each announcement is `{"peerId":,"nonce":}`, its nonce 8 base62 characters drawn when
+// it is published, so that no two of them are one event, as Trystero adds a nonce at each publish.
+void announcements_carry_a_fresh_nonce() {
+    relay_harness h;
+    h.wait(std::chrono::milliseconds(233 + 533 + 1333));
+    const auto events = h.sent("EVENT");
+    require(BOOST_TEST_EQ(events.size(), 4U));
+    std::set nonces;
+    for (const auto& e : events) {
+        const auto content = str(e.root()[1]["content"]);
+        constexpr std::string_view head = R"({"peerId":"p","nonce":")";
+        BOOST_TEST(content.starts_with(head) && content.ends_with(R"("})"));
+        BOOST_TEST_EQ(content.size(), head.size() + 8 + 2);
+        const auto nonce = content.substr(head.size(), 8);
+        BOOST_TEST(std::ranges::all_of(nonce, [](char c) {
+            return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
+        }));
+        nonces.emplace(nonce);
+    }
+    BOOST_TEST_EQ(nonces.size(), events.size());
+}
+
+// Once told to stop announcing, as a room is when it starts to leave, the strategy publishes no
+// announcement more: neither at its cadence, nor when the relay asks it to replay, nor when a peer
+// leaves; it still publishes a signal, and its subscription stays.
+void a_strategy_that_stops_announcing_announces_nothing() {
+    relay_harness h;
+    h.wait(std::chrono::milliseconds(233));
+    const auto events = h.events();
+    BOOST_TEST_EQ(events, 2U);  // at once, and after 233 ms
+    h.strategy->stop_announcing();
+    h.wait(std::chrono::milliseconds(60'000));
+    h.relay_says(relay_text("EOSE", h.subscription()));
+    h.strategy->restart_announcements();
+    BOOST_TEST_EQ(h.events(), events);
+    BOOST_TEST(h.publishes());
+    BOOST_TEST_EQ(h.requests(), 1U);
+}
+
+// A refused event or a closed subscription whose reason starts with "blocked:", "restricted:",
+// "auth-required:" or "pow:" retires the relay: the strategy closes it, publishes nothing on it
+// and never connects to it again.
+void terminal_rejections_retire_a_relay() {
+    for (const std::string_view prefix : {"blocked:", "restricted:", "auth-required:", "pow:"}) {
+        for (const bool closed : {false, true}) {
+            relay_harness h;
+            const std::string reason = std::string(prefix) + " not here";
+            h.relay_says(closed ? relay_text("CLOSED", h.subscription(), reason)
+                                : ok_text(false, reason));
+            BOOST_TEST(h.net.socket->closed);
+            BOOST_TEST(h.logged_with("retiring wss://relay.test"));
+            BOOST_TEST(!h.publishes());
+            const auto sent = h.net.socket->sent.size();
+            h.net.handlers.close();
+            h.wait(std::chrono::minutes(20));
+            BOOST_TEST_EQ(h.net.connects, 1U);
+            BOOST_TEST_EQ(h.net.socket->sent.size(), sent);
+        }
+    }
+    // Accepted, an event is no rejection, whatever its text.
+    relay_harness h;
+    h.relay_says(ok_text(true, "blocked: nothing"));
+    BOOST_TEST(!h.net.socket->closed);
+    BOOST_TEST(h.publishes());
+}
+
+// A rate limit cools a relay down for 60 s, in which it publishes nothing; then it is on probation,
+// where another rate limit doubles the cooldown, up to 15 min, and an accepted event makes it
+// healthy, so that the next rate limit cools it for 60 s again. An accepted event during a
+// cooldown does not end it, and a "duplicate:" rejection neither cools it nor is logged.
+void rate_limits_cool_a_relay_down_and_probation_ends_on_ok() {
+    using std::chrono::milliseconds;
+    relay_harness h;
+    const auto cooled_for = [&h](milliseconds length) {
+        h.relay_says(ok_text(false, "rate-limited: slow down"));
+        BOOST_TEST(!h.publishes());
+        h.wait(length - milliseconds(1));
+        BOOST_TEST(!h.publishes());
+        h.wait(milliseconds(1));
+        BOOST_TEST(h.publishes());
+    };
+    cooled_for(milliseconds(60'000));
+    for (const auto length : {120'000, 240'000, 480'000, 900'000, 900'000}) {
+        cooled_for(milliseconds(length));
+    }
+    h.relay_says(ok_text(true, ""));
+    cooled_for(milliseconds(60'000));
+    // Healthy again, then cooled: an accepted event during the cooldown leaves it.
+    h.relay_says(ok_text(true, ""));
+    h.relay_says(ok_text(false, "rate-limited: slow down"));
+    h.relay_says(ok_text(true, ""));
+    BOOST_TEST(!h.publishes());
+    h.wait(milliseconds(60'000));
+    BOOST_TEST(h.publishes());
+    BOOST_TEST(h.logged_with("rate-limits us"));
+    h.relay_says(ok_text(true, ""));
+    h.relay_says(ok_text(false, "duplicate: already have it"));
+    BOOST_TEST(h.publishes());
+    BOOST_TEST(!h.logged_with("duplicate"));
+    h.relay_says(ok_text(false, "invalid: bad"));
+    BOOST_TEST(h.logged_with("refused an event: invalid: bad"));
+}
+
+// A CLOSED of a subscription that is not the strategy's is ignored, whatever its reason: the relay
+// is neither retired nor cooled, and nothing is asked again. A CLOSED of its own is asked again
+// under the same id after 5333 ms, with the room's announcement.
+void closed_of_another_subscription_is_ignored() {
+    relay_harness h;
+    const auto subscription = h.subscription();
+    h.relay_says(relay_text("CLOSED", "not-ours", "blocked: you"));
+    h.relay_says(relay_text("CLOSED", "not-ours", "rate-limited: you"));
+    h.relay_says(relay_text("CLOSED", "not-ours", "error: gone"));
+    BOOST_TEST(!h.net.socket->closed);
+    BOOST_TEST(h.publishes());
+    BOOST_TEST(!h.logged_with("closed our subscription"));
+    h.wait(std::chrono::milliseconds(10'000));
+    BOOST_TEST_EQ(h.sent("REQ").size(), 1U);
+
+    h.relay_says(relay_text("CLOSED", subscription, "error: shutting down"));
+    BOOST_TEST(h.logged_with("closed our subscription: error: shutting down"));
+    h.wait(std::chrono::milliseconds(5332));
+    BOOST_TEST_EQ(h.sent("REQ").size(), 1U);
+    const auto events = h.events();
+    h.wait(std::chrono::milliseconds(1));
+    const auto requests = h.sent("REQ");
+    require(BOOST_TEST_EQ(requests.size(), 2U));
+    BOOST_TEST_EQ(str(requests[1].root()[1]), subscription);
+    BOOST_TEST_EQ(h.events(), events + 1);
+}
+
+// An EOSE that ends the last pending subscription 1 s or more after its REQ replays the room's
+// announcement at once, outside its cadence; one sooner, a second one, or one of an id not the
+// strategy's replays nothing.
+void slow_eose_replays_announcements() {
+    {
+        relay_harness h;
+        h.wait(std::chrono::milliseconds(100));
+        const auto events = h.events();
+        h.relay_says(relay_text("EOSE", h.subscription()));
+        BOOST_TEST_EQ(h.events(), events);
+    }
+    relay_harness h;
+    h.wait(std::chrono::milliseconds(1000));
+    const auto events = h.events();
+    BOOST_TEST_EQ(events, 3U);  // at once, after 233 ms and after 766 ms
+    h.relay_says(relay_text("EOSE", "not-ours"));
+    BOOST_TEST_EQ(h.events(), events);
+    h.relay_says(relay_text("EOSE", h.subscription()));
+    BOOST_TEST_EQ(h.events(), events + 1);
+    h.relay_says(relay_text("EOSE", h.subscription()));
+    BOOST_TEST_EQ(h.events(), events + 1);
+}
+
+// A CLOSED of the strategy's own subscription is asked again after 5333 ms, then after twice the
+// last delay each time, up to 60 s; the EOSE of the subscription asked again brings the delay back
+// to 5333 ms.
+void closed_subscriptions_are_asked_again_less_and_less_often() {
+    using std::chrono::milliseconds;
+    relay_harness h;
+    const auto subscription = h.subscription();
+    const auto asked_again_after = [&h, &subscription](milliseconds delay) {
+        const auto before = h.requests();
+        h.relay_says(relay_text("CLOSED", subscription, "error: try later"));
+        h.wait(delay - milliseconds(1));
+        BOOST_TEST_EQ(h.requests(), before);
+        h.wait(milliseconds(1));
+        BOOST_TEST_EQ(h.requests(), before + 1);
+    };
+    for (const auto delay : {5333, 10666, 21332, 42664, 60'000, 60'000}) {
+        asked_again_after(milliseconds(delay));
+    }
+    h.relay_says(relay_text("EOSE", subscription));
+    asked_again_after(milliseconds(5333));
+}
+
+// A rate-limited CLOSED cools the relay down and asks for the subscription again only once the
+// 60 s cooldown ends, with the room's announcement.
+void a_rate_limited_closed_waits_out_the_cooldown() {
+    using std::chrono::milliseconds;
+    relay_harness h;
+    h.relay_says(relay_text("CLOSED", h.subscription(), "rate-limited: slow down"));
+    BOOST_TEST(h.logged_with("rate-limits us, pausing it for 60 s"));
+    BOOST_TEST(!h.publishes());
+    h.wait(milliseconds(59'999));
+    BOOST_TEST_EQ(h.requests(), 1U);
+    const auto events = h.events();
+    h.wait(milliseconds(1));
+    BOOST_TEST_EQ(h.requests(), 2U);
+    BOOST_TEST_EQ(h.events(), events + 1);
+    BOOST_TEST(h.publishes());
+}
+
+// A relay that comes back is asked for the subscription again, under its id, and given the room's
+// announcement once; the cadence goes on from where it was, rather than starting its warm-up over.
+void a_reopened_relay_subscribes_again_and_announces_once() {
+    using std::chrono::milliseconds;
+    relay_harness h;
+    const auto subscription = h.subscription();
+    // The warm-up: at once, then after 233, 533, 1333 and 5333 ms; the next is 60 s after it.
+    h.wait(milliseconds(233 + 533 + 1333 + 5333));
+    BOOST_TEST_EQ(h.events(), 5U);
+    h.reopens();
+    const auto requests = h.sent("REQ");
+    require(BOOST_TEST_EQ(requests.size(), 1U));
+    BOOST_TEST_EQ(str(requests[0].root()[1]), subscription);
+    BOOST_TEST_EQ(h.events(), 1U);
+    h.wait(milliseconds(60'000 - 3333 - 1));
+    BOOST_TEST_EQ(h.events(), 1U);
+    h.wait(milliseconds(1));
+    BOOST_TEST_EQ(h.events(), 2U);
+}
+
+// A relay that comes back while it cools down is asked for nothing, and given nothing, until its
+// cooldown ends.
+void a_relay_that_reopens_cooling_down_waits_for_the_cooldown() {
+    using std::chrono::milliseconds;
+    relay_harness h;
+    h.relay_says(ok_text(false, "rate-limited: slow down"));
+    h.reopens();
+    BOOST_TEST_EQ(h.requests(), 0U);
+    h.wait(milliseconds(60'000 - 3333 - 1));
+    BOOST_TEST_EQ(h.requests(), 0U);
+    BOOST_TEST_EQ(h.events(), 0U);
+    h.wait(milliseconds(1));
+    BOOST_TEST_EQ(h.requests(), 1U);
+    BOOST_TEST_EQ(h.events(), 1U);
+}
+
+// Over several subscriptions, an EOSE of some of them neither ends the wait nor replays the
+// announcement, and leaves the delay of the next retry where it was; the EOSE of the last one
+// does both and brings the delay back to 5333 ms.
+void an_eose_of_some_subscriptions_neither_syncs_nor_replays() {
+    using std::chrono::milliseconds;
+    std::pmr::vector topics(memory());
+    for (std::size_t i = 0; i < 600; ++i) {
+        topics.emplace_back("topic-" + std::to_string(i));
+    }
+    relay_harness h(std::move(topics));
+    std::vector ids;
+    for (const auto& req : h.sent("REQ")) {
+        ids.emplace_back(str(req.root()[1]));
+    }
+    require(BOOST_TEST_EQ(ids.size(), 3U));
+    const auto eose = [&h](std::string_view id) { h.relay_says(relay_text("EOSE", id)); };
+    h.wait(milliseconds(1000));
+    auto events = h.events();
+    eose(ids[0]);
+    eose(ids[1]);
+    eose(ids[0]);
+    BOOST_TEST_EQ(h.events(), events);
+    // Closed, the subscriptions are asked again after 5333 ms; the next delay is 10666 ms.
+    h.relay_says(relay_text("CLOSED", ids[0], "error: try later"));
+    h.wait(milliseconds(5333));
+    BOOST_TEST_EQ(h.requests(), 6U);
+    h.wait(milliseconds(1000));
+    events = h.events();
+    eose(ids[0]);
+    eose(ids[1]);
+    BOOST_TEST_EQ(h.events(), events);
+    h.relay_says(relay_text("CLOSED", ids[1], "error: try later"));
+    h.wait(milliseconds(10'665));
+    BOOST_TEST_EQ(h.requests(), 6U);
+    h.wait(milliseconds(1));
+    BOOST_TEST_EQ(h.requests(), 9U);
+    // All three end, 1 s after their REQs: the announcement once, and the delay back to 5333 ms.
+    h.wait(milliseconds(1000));
+    events = h.events();
+    for (const auto& id : ids) {
+        eose(id);
+    }
+    BOOST_TEST_EQ(h.events(), events + 1);
+    h.relay_says(relay_text("CLOSED", ids[2], "error: try later"));
+    h.wait(milliseconds(5332));
+    BOOST_TEST_EQ(h.requests(), 9U);
+    h.wait(milliseconds(1));
+    BOOST_TEST_EQ(h.requests(), 12U);
+}
+
+// The room's key is made at its first event, not with the strategy, and signs it; the strategy
+// drops it when it stops.
+void the_room_key_is_made_at_the_first_event_and_dropped_on_stop() {
+    relay_harness h(false);
+    BOOST_TEST(h.strategy->current_signer() == nullptr);
+    h.opens();
+    const auto events = h.sent("EVENT");
+    require(BOOST_TEST_EQ(events.size(), 1U));
+    const auto* key = h.strategy->current_signer();
+    require(BOOST_TEST(key != nullptr));
+    BOOST_TEST_EQ(str(events[0].root()[1]["pubkey"]), key->pubkey_hex());
+    h.strategy->stop();
+    BOOST_TEST(h.strategy->current_signer() == nullptr);
+}
+
+/** Two signalings of one room over the memory network, A (`ids[0]`, whose id is lower, so it
+ * offers) and B; each publishes on the other's self topic, through a queue `deliver` empties,
+ * `tamper` first rewriting what goes to A. */
+struct signaling_pair {
+    static constexpr std::array ids{
+        "aPeer000000000000000",
+        "bPeer000000000000000",
+    };
+    static constexpr std::string_view app_id = "pair-app";
+    static constexpr std::string_view room_id = "pair-room";
+
+    /** A negotiation that ended connected: its connection and the descriptions it was given. */
+    struct connection {
+        std::shared_ptr pc;
+        std::shared_ptr channel;
+        std::string local_sdp;
+        std::string remote_sdp;
+    };
+
+    signaling_pair() {
+        net.virtual_clock = true;
+        for (std::size_t i = 0; i < 2; ++i) {
+            sides[i] = std::make_shared(
+                net, app_id, room_id, ids[i], std::span(),
+                detail::signaling::callbacks{
+                    .publish =
+                        [this, i](std::size_t, std::string_view topic, std::string_view content) {
+                            const std::size_t to = 1 - i;
+                            BOOST_TEST_EQ(topic, tp::peer_topic(app_id, room_id, ids[to]));
+                            queue.emplace_back(to, std::string(content));
+                        },
+                    .connected =
+                        [this, i](std::string_view, std::shared_ptr pc,
+                                  std::shared_ptr channel,
+                                  std::string_view local_sdp, std::string_view remote_sdp) {
+                            connected[i].push_back({
+                                .pc = std::move(pc),
+                                .channel = std::move(channel),
+                                .local_sdp = std::string(local_sdp),
+                                .remote_sdp = std::string(remote_sdp),
+                            });
+                        },
+                    .failed = [](const trystero::room_error&) {},
+                    .should_connect = [this, i](std::string_view) { return wanted[i]; },
+                },
+                detail::logger(), memory());
+            sides[i]->set_key(key);
+        }
+    }
+
+    /** Delivers what was published, and what that publishes, until nothing is left. */
+    void deliver() {
+        require(BOOST_TEST(net.poll_ready()));
+        while (!queue.empty()) {
+            auto [to, text] = std::move(queue.front());
+            queue.pop_front();
+            if (to == 0 && tamper) {
+                text = tamper(text);
+            }
+            sides[to]->handle(0, text);
+            require(BOOST_TEST(net.poll_ready()));
+        }
+    }
+
+    /** A hears B's announcement, and they negotiate. */
+    void announce_b() {
+        sides[0]->handle(0, tp::write_signal({.peer_id = ids[1]}, {}, memory()));
+        deliver();
+    }
+
+    asio::io_context io;
+    memory_network net{io};
+    webcpp::crypto::secret<32> key = tp::room_aes_key_without_password(app_id, room_id);
+    std::array, 2> sides;
+    std::deque> queue;
+    std::function tamper;
+    std::array, 2> connected;
+    /** What each side's should_connect answers. */
+    std::array wanted{true, true};
+};
+
+// An offerer whose connection refuses the answer it is sent (its first line names no connection)
+// starts over with a new offer once its peer's answer has expired; when that negotiation opens,
+// each side is given the descriptions of the connection that opened: the one it set itself and
+// the one it applied, its peer's, never the answer it refused.
+void connected_carries_the_descriptions_applied() {
+    signaling_pair p;
+    std::string refused;
+    p.tamper = [&](std::string text) {
+        const read_signal_text read(text);
+        const auto& m = *read.message;
+        if (m.answer.empty() || !refused.empty()) {
+            return text;
+        }
+        const auto aad = tp::signal_aad("answer", signaling_pair::ids[1], m.offer_id);
+        const auto sdp = tp::open(p.key, m.answer, std::string_view(aad));
+        require(BOOST_TEST(sdp.has_value()));
+        refused = replaced(*sdp, "mem:", "nil:");
+        const std::array iv{9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2};
+        const auto sealed = tp::seal(p.key, iv, refused, std::string_view(aad));
+        require(BOOST_TEST(sealed.has_value()));
+        return replaced(text, m.answer, *sealed);
+    };
+    std::vector made;
+    p.net.on_made = [&](std::size_t pc, std::span) {
+        made.push_back(pc);
+    };
+    p.announce_b();
+    require(BOOST_TEST(!refused.empty()));
+    BOOST_TEST(p.connected[0].empty() && p.connected[1].empty());
+    require(BOOST_TEST_EQ(made.size(), 2U));  // A's first offer, B's answer to it
+    require(BOOST_TEST(p.net.advance(std::chrono::milliseconds(24'000))));
+    p.deliver();
+    p.announce_b();
+    require(BOOST_TEST_EQ(p.connected[0].size(), 1U));
+    require(BOOST_TEST_EQ(p.connected[1].size(), 1U));
+    for (std::size_t i = 0; i < 2; ++i) {
+        const auto& c = p.connected[i].front();
+        const auto pc = std::dynamic_pointer_cast(c.pc);
+        require(BOOST_TEST(pc != nullptr && pc->remote_id().has_value()));
+        BOOST_TEST_EQ(c.local_sdp,
+                      std::string_view(trystero::test::memory_description(pc->id(), memory())));
+        BOOST_TEST_EQ(c.remote_sdp, std::string_view(trystero::test::memory_description(
+                                        *pc->remote_id(), memory())));
+        BOOST_TEST_NE(c.remote_sdp, refused);
+        // The connection that opened is a new one, not one of the first negotiation's.
+        BOOST_TEST(std::ranges::find(made.begin(), made.begin() + 2, pc->id()) == made.begin() + 2);
+    }
+    const auto a_pc =
+        std::dynamic_pointer_cast(p.connected[0][0].pc);
+    const auto b_pc =
+        std::dynamic_pointer_cast(p.connected[1][0].pc);
+    BOOST_TEST_EQ(*a_pc->remote_id(), b_pc->id());
+    BOOST_TEST_EQ(*b_pc->remote_id(), a_pc->id());
+}
+
+// An offerer whose room stops wanting its peer between its offer and the peer's answer (a full
+// room's refusal of that peer's user) ends the offer the answer is for, as 0.27.0 tears down the
+// offer an unwanted answer answers: its connection closes at once, and no connection opens. Once
+// the peer is wanted again, a new announcement negotiates normally.
+void a_refused_answer_ends_the_offer() {
+    signaling_pair p;
+    p.tamper = [&](std::string text) {
+        const read_signal_text read(text);
+        if (!read.message->answer.empty()) {
+            p.wanted[0] = false;  // the room is full by the time the answer arrives
+        }
+        return text;
+    };
+    p.announce_b();
+    BOOST_TEST(p.connected[0].empty());
+    BOOST_TEST(p.connected[1].empty());
+    // A's offer is gone; B's connection that answered it stays until its answer expires.
+    BOOST_TEST_EQ(p.net.live_connections(), 1U);
+    p.tamper = {};
+    p.wanted[0] = true;
+    require(BOOST_TEST(p.net.advance(std::chrono::milliseconds(24'000))));
+    p.deliver();
+    p.announce_b();
+    BOOST_TEST_EQ(p.connected[0].size(), 1U);
+    BOOST_TEST_EQ(p.connected[1].size(), 1U);
+}
+
 }  // namespace
 
 int main(int argc, char* argv[]) {
     if (!BOOST_TEST_EQ(argc, 2)) {
-        BOOST_LIGHTWEIGHT_TEST_OSTREAM
-            << "usage: signaling_test \n";
+        BOOST_LIGHTWEIGHT_TEST_OSTREAM << "usage: signaling_test \n";
         return webcpp::test::exit_status(boost::report_errors());
     }
     const auto fixture = load(argv[1]);
@@ -486,7 +1164,23 @@ int main(int argc, char* argv[]) {
     const auto oracle = fixture->root()["answerer"];
     an_answerers_signals_are_trysteros(oracle);
     a_signal_past_its_bound_is_dropped(oracle);
+    an_unwanted_peers_offer_is_ignored(oracle);
     a_relay_text_past_its_bound_is_dropped();
     a_relay_text_past_its_depth_is_dropped();
+    subscriptions_hold_250_topics_and_distinct_kinds();
+    announcements_carry_a_fresh_nonce();
+    a_strategy_that_stops_announcing_announces_nothing();
+    terminal_rejections_retire_a_relay();
+    rate_limits_cool_a_relay_down_and_probation_ends_on_ok();
+    closed_of_another_subscription_is_ignored();
+    slow_eose_replays_announcements();
+    closed_subscriptions_are_asked_again_less_and_less_often();
+    a_rate_limited_closed_waits_out_the_cooldown();
+    a_reopened_relay_subscribes_again_and_announces_once();
+    a_relay_that_reopens_cooling_down_waits_for_the_cooldown();
+    an_eose_of_some_subscriptions_neither_syncs_nor_replays();
+    the_room_key_is_made_at_the_first_event_and_dropped_on_stop();
+    connected_carries_the_descriptions_applied();
+    a_refused_answer_ends_the_offer();
     return webcpp::test::exit_status(boost::report_errors());
 }
diff --git a/test/subscription_test.cpp b/test/subscription_test.cpp
new file mode 100644
index 0000000..b18c9d0
--- /dev/null
+++ b/test/subscription_test.cpp
@@ -0,0 +1,283 @@
+// Copyright (c) 2026 WebCpp.org
+//
+// Distributed under the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// https://www.boost.org/LICENSE_1_0.txt)
+
+// Tests the listeners of an event alone, as Trystero 0.27.0's event emitter (emitter.ts) runs
+// them: in the order added, a listener added while an event is reported waits for the next one, a
+// listener removed before its turn does not run, `once` removes before it runs, `replay` calls at
+// once with what is current, and dropping a subscription leaves its listener.
+
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "cases.hpp"
+
+namespace trystero = webcpp::trystero;
+
+namespace {
+
+using event = trystero::detail::listeners;
+
+event make_event() {
+    return event(std::pmr::polymorphic_allocator<>(std::pmr::new_delete_resource()));
+}
+
+void listeners_run_in_order() {
+    auto e = make_event();
+    std::vector calls;
+    e.add([&](int v) { calls.push_back("a" + std::to_string(v)); }, {});
+    e.add([&](int v) { calls.push_back("b" + std::to_string(v)); }, {});
+    e.add([&](int v) { calls.push_back("c" + std::to_string(v)); }, {});
+    e.emit(1);
+    e.emit(2);
+    const std::vector expected{"a1", "b1", "c1", "a2", "b2", "c2"};
+    BOOST_TEST_ALL_EQ(calls.begin(), calls.end(), expected.begin(), expected.end());
+    BOOST_TEST_EQ(e.size(), 3U);
+}
+
+// The scenario of the specification: the first of two join listeners unsubscribes itself and the
+// second while it runs; the second does not run, and neither runs again.
+void listeners_unsubscribe_while_dispatching() {
+    auto e = make_event();
+    std::vector calls;
+    trystero::subscription first;
+    trystero::subscription second;
+    first = e.add(
+        [&](int) {
+            calls.emplace_back("first");
+            first.unsubscribe();
+            second.unsubscribe();
+        },
+        {});
+    second = e.add([&](int) { calls.emplace_back("second"); }, {});
+    const auto third = e.add([&](int) { calls.emplace_back("third"); }, {});
+    BOOST_TEST(first.active());
+    BOOST_TEST(second.active());
+    e.emit(1);
+    e.emit(2);
+    const std::vector expected{"first", "third", "third"};
+    BOOST_TEST_ALL_EQ(calls.begin(), calls.end(), expected.begin(), expected.end());
+    BOOST_TEST(!first.active());
+    BOOST_TEST(!second.active());
+    BOOST_TEST(third.active());
+    BOOST_TEST_EQ(e.size(), 1U);
+    // A second unsubscribe, and one of a subscription of no listener, do nothing.
+    first.unsubscribe();
+    trystero::subscription().unsubscribe();
+}
+
+// `once` removes the listener before it runs: an event it reports itself does not reach it again.
+void once_runs_once() {
+    auto e = make_event();
+    std::vector calls;
+    std::optional s;
+    s = e.add(
+        [&](int v) {
+            calls.push_back(v);
+            if (v == 1) {
+                e.emit(10);  // reported from within: the listener is already gone
+            }
+        },
+        {.once = true, .replay = false});
+    BOOST_TEST(s->active());
+    e.emit(1);
+    e.emit(2);
+    const std::vector expected{1};
+    BOOST_TEST_ALL_EQ(calls.begin(), calls.end(), expected.begin(), expected.end());
+    BOOST_TEST(!s->active());
+    BOOST_TEST(e.empty());
+}
+
+// A listener added while an event is reported runs from the next one on.
+void added_while_dispatching_waits() {
+    auto e = make_event();
+    std::vector calls;
+    bool added = false;
+    e.add(
+        [&](int v) {
+            calls.push_back("outer" + std::to_string(v));
+            if (!added) {
+                added = true;
+                e.add([&](int w) { calls.push_back("inner" + std::to_string(w)); }, {});
+            }
+        },
+        {});
+    e.emit(1);
+    e.emit(2);
+    const std::vector expected{"outer1", "outer2", "inner2"};
+    BOOST_TEST_ALL_EQ(calls.begin(), calls.end(), expected.begin(), expected.end());
+}
+
+// A subscription destroyed, or moved from, leaves its listener in place, as dropping the function
+// Trystero returns does; the one it was moved to removes it.
+void dropping_a_subscription_keeps_the_listener() {
+    auto e = make_event();
+    int calls = 0;
+    {
+        const auto dropped = e.add([&](int) { ++calls; }, {});
+    }
+    static_cast(e.add([&](int) { ++calls; }, {}));
+    e.emit(1);
+    BOOST_TEST_EQ(calls, 2);
+    auto moved_from = e.add([&](int) { ++calls; }, {});
+    trystero::subscription moved_to = std::move(moved_from);
+    BOOST_TEST(!moved_from.active());  // NOLINT(bugprone-use-after-move): refers to none
+    BOOST_TEST(moved_to.active());
+    e.emit(2);
+    BOOST_TEST_EQ(calls, 5);
+    moved_to.unsubscribe();
+    e.emit(3);
+    BOOST_TEST_EQ(calls, 7);
+}
+
+// `replay` calls the listener with each current item within `add`, before it is in place; with
+// `once`, only with the first; an event reported meanwhile does not reach it.
+void replay_reports_what_is_current() {
+    auto e = make_event();
+    const std::array current{1, 2, 3};
+    std::vector replayed;
+    const auto all =
+        e.add([&](int v) { replayed.push_back(v); }, {.once = false, .replay = true}, current);
+    const std::vector expected{1, 2, 3};
+    BOOST_TEST_ALL_EQ(replayed.begin(), replayed.end(), expected.begin(), expected.end());
+    BOOST_TEST(all.active());
+    std::vector first_only;
+    const auto once =
+        e.add([&](int v) { first_only.push_back(v); }, {.once = true, .replay = true}, current);
+    BOOST_TEST_EQ(first_only.size(), 1U);
+    BOOST_TEST(!once.active());
+    // An event reported during the replay does not reach the listener, not yet in place.
+    std::vector during;
+    const auto nested = e.add(
+        [&](int v) {
+            during.push_back(v);
+            if (v == 1) {
+                e.emit(100);
+            }
+        },
+        {.once = false, .replay = true}, current);
+    BOOST_TEST_ALL_EQ(during.begin(), during.end(), expected.begin(), expected.end());
+    BOOST_TEST(nested.active());
+    BOOST_TEST_EQ(e.size(), 2U);
+    // The first listener, in place, saw the event reported during the replay.
+    const std::vector with_nested{1, 2, 3, 100};
+    BOOST_TEST_ALL_EQ(replayed.begin(), replayed.end(), with_nested.begin(), with_nested.end());
+    // Without `replay` the items are not read.
+    std::vector none;
+    static_cast(
+        e.add([&](int v) { none.push_back(v); }, {.once = false, .replay = false}, current));
+    BOOST_TEST(none.empty());
+}
+
+// A listener taken one at a time answers through `call_first`; `once` removes it first.
+void call_first_answers_once() {
+    trystero::detail::listeners gate{
+        std::pmr::polymorphic_allocator<>(std::pmr::new_delete_resource())};
+    const auto s = gate.add([](int v) { return v > 1; }, {.once = true, .replay = false});
+    BOOST_TEST(!gate.empty());
+    BOOST_TEST(gate.call_first(2));
+    BOOST_TEST(gate.empty());
+    BOOST_TEST(!s.active());
+}
+
+// Clearing, as a room does when it is left, removes every listener, even within an emission: those
+// whose turn had not come do not run, and every subscription is inactive.
+void clearing_removes_every_listener() {
+    auto e = make_event();
+    std::vector calls;
+    const auto first = e.add(
+        [&](int) {
+            calls.emplace_back("first");
+            e.clear();
+        },
+        {});
+    const auto second = e.add([&](int) { calls.emplace_back("second"); }, {});
+    e.emit(1);
+    e.emit(2);
+    const std::vector expected{"first"};
+    BOOST_TEST_ALL_EQ(calls.begin(), calls.end(), expected.begin(), expected.end());
+    BOOST_TEST(e.empty());
+    BOOST_TEST(!first.active());
+    BOOST_TEST(!second.active());
+    const auto later = e.add([&](int) { calls.emplace_back("later"); }, {});
+    e.emit(3);
+    BOOST_TEST_EQ(calls.back(), "later");
+    BOOST_TEST(later.active());
+
+    // A clear during a replay removes the listener being added, which replays no further.
+    std::size_t replayed = 0;
+    const std::array current{1, 2};
+    const auto replaying = e.add(
+        [&](int) {
+            ++replayed;
+            e.clear();
+        },
+        {.once = false, .replay = true}, current);
+    BOOST_TEST_EQ(replayed, 1U);
+    BOOST_TEST(!replaying.active());
+    BOOST_TEST(e.empty());
+}
+
+#ifndef WEBCPP_TRYSTERO_NO_EXCEPTIONS
+// A listener that throws ends the emission, which still forgets the listeners removed meanwhile:
+// what a removed listener holds is released, as after an emission that ends normally.
+void a_throwing_listener_ends_the_emission_cleanly() {
+    auto e = make_event();
+    const auto held = std::make_shared(0);
+    auto removed = e.add([held](int) {}, {});
+    // It removes the first listener, then throws.
+    e.add(
+        [&](int v) {
+            if (v == 1) {
+                removed.unsubscribe();
+                throw std::runtime_error("listener failed");
+            }
+        },
+        {});
+    bool thrown = false;
+    try {
+        e.emit(1);
+    } catch (const std::runtime_error&) {
+        thrown = true;
+    }
+    BOOST_TEST(thrown);
+    BOOST_TEST_EQ(held.use_count(), 1);  // the removed listener was forgotten
+    std::size_t runs = 0;
+    e.add([&](int) { ++runs; }, {});
+    e.emit(2);
+    BOOST_TEST_EQ(runs, 1U);
+    BOOST_TEST_EQ(e.size(), 2U);
+}
+#endif
+
+}  // namespace
+
+int main() {
+    // Each case in a frame of its own, which main's never holds (cases.hpp).
+    using webcpp::test::run_case;
+    run_case(listeners_run_in_order);
+    run_case(listeners_unsubscribe_while_dispatching);
+    run_case(once_runs_once);
+    run_case(added_while_dispatching_waits);
+    run_case(dropping_a_subscription_keeps_the_listener);
+    run_case(replay_reports_what_is_current);
+    run_case(call_first_answers_once);
+    run_case(clearing_removes_every_listener);
+#ifndef WEBCPP_TRYSTERO_NO_EXCEPTIONS
+    run_case(a_throwing_listener_ends_the_emission_cleanly);
+#endif
+    return webcpp::test::exit_status(boost::report_errors());
+}
diff --git a/test/support/memory_backend.hpp b/test/support/memory_backend.hpp
index 62529c0..9223467 100644
--- a/test/support/memory_backend.hpp
+++ b/test/support/memory_backend.hpp
@@ -13,8 +13,14 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
+#include 
+
+#include 
+#include 
+#include 
 
 #include 
 #include 
@@ -45,15 +51,15 @@
 /**
  * A backend in memory, for running whole rooms in one process: Nostr relays that forward ephemeral
  * events to matching subscriptions, peer connections that pair through their descriptions, data
- * channels that deliver in order, and a sealer that only opens what was sealed under the same key.
- * Every event is posted to the io_context, never delivered from inside the call that caused it, as
- * in a browser.
+ * channels that deliver in order, and a password's PBKDF2 computed at once, in the call, and
+ * completed through a post. Every event is posted to the io_context, never delivered from inside
+ * the call that caused it, as in a browser.
  *
  * Tip: what a room makes, and what a room receives, is allocated in that room's resource, which
  * each factory method is given; the network's own state (its relays, their subscriptions, its
  * record of the connections) is in the resource the network is constructed with, and changes only
  * when a room joins, connects or leaves. The state of the hooks a test drives (held frames,
- * deferred opens, held sealer opens, a buffering channel's queue, the virtual clock) is in the
+ * deferred opens, held derivations, a buffering channel's queue, the virtual clock) is in the
  * default resource and is made only when the test sets the hook.
  */
 namespace webcpp::trystero::test {
@@ -180,7 +186,7 @@ class memory_relay {
     };
 
     explicit memory_relay(std::pmr::memory_resource* memory)
-        : memory_(memory), subscriptions_(memory) {}
+        : published(memory), requests(memory), memory_(memory), subscriptions_(memory) {}
 
     void receive(const std::shared_ptr& from, std::string_view text);
 
@@ -194,16 +200,41 @@ class memory_relay {
     /** Closes every connection that has a subscription, as a relay that goes away does. */
     void close_all();
 
+    /** How many subscriptions the relay holds, of every socket. */
+    [[nodiscard]] std::size_t subscription_count() const { return subscriptions_.size(); }
+
     std::size_t events_seen = 0;
     /** How many texts went through the relay: each text it received from a socket, and each text
      * a socket of it handed to its room. A test that measures a window of a room's life reads it
      * to know whether relay traffic, which parses JSON at both ends, happened in that window. */
     std::size_t texts = 0;
+    /** Whether a socket of the relay drops each EVENT it is sent, its `send` returning false, as
+     * a connection whose writes fail; memory_network::fail_publish sets it. */
+    bool fail_events = false;
     /** Answers this many EVENTs with "rate-limited:", to exercise the strategy's backoff. */
     std::size_t rate_limit_next = 0;
     /** Closes each connection right after its subscription, as a relay does after a text longer
      * than a room reads. */
     bool close_after_subscribe = false;
+    /** Whether to keep, for each event the relay takes, its topic and its signer's public key in
+     * `published`; off, the relay allocates nothing for it. */
+    bool record_published = false;
+
+    /** An event the relay took: its topic and the public key that signed it. */
+    struct published_event {
+        std::pmr::string topic;
+        std::pmr::string pubkey;
+    };
+
+    /** The events taken while `record_published` is on, in order, in the relay's resource. */
+    std::pmr::vector published;
+
+    /** Whether to keep the text of each REQ the relay takes in `requests`; off, the relay
+     * allocates nothing for it. */
+    bool record_requests = false;
+
+    /** The REQs taken while `record_requests` is on, in order, in the relay's resource. */
+    std::pmr::vector requests;
 
 private:
     using key = std::pair;
@@ -237,15 +268,17 @@ class memory_websocket : public backend::websocket,
         });
     }
 
-    void send(std::string_view text) override {
-        if (!open_) {
-            return;
+    bool send(std::string_view text) override {
+        if (!open_ ||
+            (relay_ != nullptr && relay_->fail_events && text.starts_with(R"(["EVENT")"))) {
+            return false;
         }
         post_in(io_, memory_, [self = shared_from_this(), text = std::pmr::string(text, memory_)] {
             if (self->open_ && self->relay_) {
                 self->relay_->receive(self, text);
             }
         });
+        return true;
     }
 
     /** Delivers a text the relay made in this socket's resource; the relay counts it in its
@@ -338,6 +371,9 @@ inline void memory_relay::receive(const std::shared_ptr& from,
     }
     const std::string_view type = protocol::json::text_of(message.at(0));
     if (type == "REQ" && message.size() >= 3) {
+        if (record_requests) {
+            requests.emplace_back(text);
+        }
         subscriptions_.insert_or_assign(
             key{from.get(), std::pmr::string(protocol::json::text_of(message.at(1)), memory_)},
             subscription_of(from, message.at(2), memory_));
@@ -370,6 +406,12 @@ inline void memory_relay::receive(const std::shared_ptr& from,
         }
         // The event's first tag, ["x", ].
         const std::string_view topic = protocol::json::text_of(event["tags"].at(0).at(1));
+        if (record_published) {
+            published.push_back({
+                .topic = std::pmr::string(topic, memory_),
+                .pubkey = std::pmr::string(protocol::json::text_of(event["pubkey"]), memory_),
+            });
+        }
         for (auto& [subscribed, s] : subscriptions_) {
             const auto socket = s.socket.lock();
             if (!socket || !s.kinds.contains(*kind) || !s.topics.contains(topic)) {
@@ -528,8 +570,56 @@ class memory_data_channel : public backend::data_channel,
     bool draining_ = false;
 };
 
-/** Peer connections pair through their descriptions: "mem:" names the connection that wrote it.
+/**
+ * The description a memory connection writes: `mem:`, which names it, then a DTLS fingerprint
+ * line, `a=fingerprint:sha-256 `, `F` the 32 bytes of the SHA-256 of `mem-fingerprint:` in
+ * uppercase hexadecimal pairs joined by `:`, as a browser writes its certificate's.
+ *
+ * @param id The connection's id.
+ * @param memory The resource of the text.
+ * @return The description, its lines ended by CRLF.
+ */
+inline std::pmr::string memory_description(std::size_t id, std::pmr::memory_resource* memory) {
+    std::pmr::string label("mem-fingerprint:", memory);
+    protocol::json::append_integer(label, static_cast(id));
+    const auto digest = protocol::sha256(label);
+    std::pmr::string sdp("mem:", memory);
+    protocol::json::append_integer(sdp, static_cast(id));
+    sdp += "\r\na=fingerprint:sha-256 ";
+    constexpr std::string_view digits = "0123456789ABCDEF";
+    for (std::size_t i = 0; i < digest.size(); ++i) {
+        if (i != 0) {
+            sdp += ':';
+        }
+        sdp += digits[digest[i] >> 4U];
+        sdp += digits[digest[i] & 0x0fU];
+    }
+    sdp += "\r\n";
+    return sdp;
+}
+
+/**
+ * The id of the connection that wrote a description: the number of its first line, `mem:`.
+ *
+ * @param sdp The description.
+ * @return The id; nothing when the first line is not `mem:` and a number.
  */
+inline std::optional memory_description_id(std::string_view sdp) {
+    const auto first_line = sdp.substr(0, sdp.find_first_of("\r\n"));
+    if (!first_line.starts_with("mem:")) {
+        return std::nullopt;
+    }
+    std::size_t id = 0;
+    const auto* const end = first_line.data() + first_line.size();
+    const auto [at, ec] = std::from_chars(first_line.data() + 4, end, id);
+    if (ec != std::errc{} || at != end) {
+        return std::nullopt;
+    }
+    return id;
+}
+
+/** Peer connections pair through their descriptions, which @ref memory_description writes; the
+ * first line, `mem:`, names the connection that wrote it. */
 class memory_peer_connection : public backend::peer_connection,
                                public std::enable_shared_from_this {
 public:
@@ -567,8 +657,7 @@ class memory_peer_connection : public backend::peer_connection,
                 return;
             }
             self->local_set_ = true;
-            std::pmr::string sdp("mem:", self->memory_);
-            protocol::json::append_integer(sdp, static_cast(self->id_));
+            const auto sdp = memory_description(self->id_, self->memory_);
             done({}, self->remote_id_ ? "answer" : "offer", sdp);
             post_in(self->io_, self->memory_, [self] {
                 if (self->closed_ || !self->h_.ice_candidate) {
@@ -588,12 +677,8 @@ class memory_peer_connection : public backend::peer_connection,
         post_in(io_, memory_,
                 [self = shared_from_this(), sdp = std::pmr::string(sdp_view, memory_),
                  done = std::move(done)]() mutable {
-                    std::size_t remote = 0;
-                    const bool ours =
-                        sdp.starts_with("mem:") &&
-                        std::from_chars(sdp.data() + 4, sdp.data() + sdp.size(), remote).ec ==
-                            std::errc{};
-                    if (self->closed_ || !ours) {
+                    const auto remote = memory_description_id(sdp);
+                    if (self->closed_ || !remote) {
                         done(make_error_code(error::backend_failure));
                         return;
                     }
@@ -611,6 +696,10 @@ class memory_peer_connection : public backend::peer_connection,
 
     bool has_remote_description() const override { return remote_id_.has_value(); }
 
+    /** The network's `max_message_size` once a remote description is applied, as a browser's
+     * `sctp` appears with it; nothing before. */
+    [[nodiscard]] std::optional max_message_size() const override;
+
     void close() override {
         if (closed_) {
             return;
@@ -709,11 +798,47 @@ class memory_network : public backend::factory {
         auto socket = std::allocate_shared(
             std::pmr::polymorphic_allocator<>(memory), io_, relay, std::move(h), memory);
         socket->open();
+        ++websocket_connects;
         return socket;
     }
 
+    /** How many WebSockets were asked for, of every relay, reachable or not. */
+    std::size_t websocket_connects = 0;
+
+    /** When true, the network has a page's `online` and `offline` events, which
+     * page_connectivity() fires; false, as natively, it watches nothing. */
+    bool page_events = false;
+
+    /** A watch while `page_events` holds, its handler kept in `memory`; else none. */
+    std::shared_ptr watch_connectivity(handler changed,
+                                             std::pmr::memory_resource* memory) override {
+        if (!page_events) {
+            return nullptr;
+        }
+        auto watch = std::allocate_shared>(
+            std::pmr::polymorphic_allocator<>(memory), std::move(changed));
+        watches_.push_back(watch);
+        return watch;
+    }
+
+    /** Fires the page's `online` (`online` true) or `offline` event: each watch not destroyed is
+     * called after it, posted, as a page's listener posts. */
+    void page_connectivity(bool online) {
+        for (const auto& w : watches_) {
+            webcpp::asio::post(io_, [w, online] {
+                if (const auto watch = w.lock()) {
+                    (*watch)(online);
+                }
+            });
+        }
+    }
+
     void make_unreachable(std::string_view url) { unreachable_.emplace(url); }
 
+    /** Makes every write of an event to the relay at `url` fail from now on: its sockets drop each
+     * EVENT, their `send` returning false, as a connection whose writes fail. */
+    void fail_publish(std::string_view url) { relay(url).fail_events = true; }
+
     std::shared_ptr make_peer_connection(
         std::span servers, std::pmr::memory_resource* memory) override {
         if (record_servers) {
@@ -752,14 +877,41 @@ class memory_network : public backend::factory {
                                                   std::weak_ptr(clock_));
     }
 
-    std::shared_ptr make_sealer(std::array key,
-                                                 std::pmr::memory_resource* memory) override;
+    /**
+     * PBKDF2-HMAC-SHA-256 of `password` with `salt` and @ref pbkdf2_iterations iterations, computed
+     * in the call with webcpp::hash; `done` posted, or held while @ref derive_delay is set.
+     */
+    void derive_password_master(std::span password,
+                                std::span salt,
+                                std::span out,
+                                handler done) override {
+        ++derivations;
+        boost::system::error_code ec;
+        if (fail_derivations > 0) {
+            --fail_derivations;
+            ec = make_error_code(error::backend_failure);
+        } else if (!webcpp::hash::pbkdf2(out, password, salt,
+                                                                      pbkdf2_iterations)) {
+            ec = make_error_code(error::backend_failure);
+        }
+        if (ec) {
+            webcpp::trystero::detail::wipe(out.data(), out.size());
+        }
+        if (derive_delay) {
+            held_derivations_.push_back({.ec = ec, .done = std::move(done)});
+            return;
+        }
+        complete_derivation(ec, std::move(done));
+    }
 
     void random(std::span out) override {
         random_bytes += out.size();
         for (auto& b : out) {
             b = static_cast(random_());
         }
+        if (on_random) {
+            on_random(out);
+        }
     }
 
     /** A wall clock that moves with steady_now(), from 2025-10-05T21:33:20Z at its origin, in whole
@@ -794,6 +946,43 @@ class memory_network : public backend::factory {
     std::size_t peak_connections = 0;
     /** How many random bytes were drawn. */
     std::size_t random_bytes = 0;
+    /** Called with every draw of random bytes once it is made: a test checks that a value came
+     * from the backend's randomness. */
+    std::function)> on_random;
+    /** How many derivations of a password's master were asked for. */
+    std::size_t derivations = 0;
+    /** How many of the next derivations to fail, with `error::backend_failure`. */
+    std::size_t fail_derivations = 0;
+    /**
+     * The iterations of the network's PBKDF2. Its rooms meet only each other, so that the count
+     * need not be 0.27.0's 600,000, which takes seconds in a debug build: the platform backend's
+     * is (`protocol::pbkdf2_iterations`), and crypto_layer proves its master against the vectors.
+     */
+    std::uint64_t pbkdf2_iterations = 1'000;
+    /** When true, every derivation's completion waits until release_derivations(), as a page's
+     * WebCrypto takes its time. */
+    bool derive_delay = false;
+
+    /** Completes the derivations held, in the order they were asked for. */
+    void release_derivations() {
+        for (auto& held : std::exchange(held_derivations_, {})) {
+            complete_derivation(held.ec, std::move(held.done));
+        }
+    }
+
+    /** How many derivations wait to be released. */
+    [[nodiscard]] std::size_t held_derivations() const { return held_derivations_.size(); }
+
+    /** What every connection's `max_message_size()` says once it has a remote description:
+     * Chrome's 256 KiB by default, which takes wide chunks; a test sets less, or nothing, for a
+     * transport that takes only narrow ones. */
+    std::optional max_message_size = std::size_t{256} * 1024;
+
+    /** The longest frame a channel sends, when set: a longer one is refused and closes the
+     * sending channel, as the platform's channel closes on a send its transport refuses. A test
+     * sets it below `max_message_size` for a transport that refuses what it announced. */
+    std::optional send_limit;
+
     /** How many of the next peer connections to refuse, as a browser at its limit does. */
     std::size_t refuse_peer_connections = 0;
     /** Whether to record the URL of every ICE server a peer connection is made with. */
@@ -822,15 +1011,6 @@ class memory_network : public backend::factory {
     void open(std::size_t pc);
     /** Delivers `frame` on the channel of `pc`, as if its other end had sent it. */
     void inject(std::size_t pc, std::span frame);
-    /** When true, every sealer's opens wait until release_sealer_opens(), as Web Crypto's take
-     * their time in a page while the relays' texts keep coming. */
-    bool hold_sealer_opens = false;
-    /** Completes the sealer opens held, in the order they were asked for. */
-    void release_sealer_opens();
-
-    /** How many sealer opens wait to be released. */
-    [[nodiscard]] std::size_t held_sealer_opens() const { return held_sealer_opens_.size(); }
-
     /** Reports `failed` on `pc`, then closes its channel. */
     void fail(std::size_t pc);
     /** Reports `disconnected` on `pc`; its channel stays open. */
@@ -870,7 +1050,6 @@ class memory_network : public backend::factory {
 private:
     friend class memory_data_channel;
     friend class memory_peer_connection;
-    friend class memory_sealer;
 
     /** A frame held by the filter, and every frame its sending end sent after it. */
     struct held_frame {
@@ -878,15 +1057,20 @@ class memory_network : public backend::factory {
         std::vector bytes;
     };
 
-    /** A sealer's open held by `hold_sealer_opens`: its result, made when it was asked for, and
-     * what it completes, in the resource of the room that asked. */
-    struct held_open {
-        std::pmr::memory_resource* memory;
-        bool ours;
-        std::pmr::string plain;
-        handler done;
+    /** A derivation held by `derive_delay`: its result, made when it was asked for, and what it
+     * completes. */
+    struct held_derivation {
+        boost::system::error_code ec;
+        handler done;
     };
 
+    /** Posts a derivation's completion, allocated as its handler's allocator says. */
+    void complete_derivation(boost::system::error_code ec,
+                             handler done) {
+        auto* const memory = done.get_allocator().resource();
+        post_in(io_, memory, [ec, done = std::move(done)]() mutable { done(ec); });
+    }
+
     /** Holds, drops or delivers `frame`, as the filter and the frames held before it say. */
     void route(std::size_t from, std::size_t to, std::span frame);
     /** Hands `frame` to the other end of the channel of `from`, or to that channel's queue when
@@ -905,8 +1089,9 @@ class memory_network : public backend::factory {
     std::size_t next_pc_ = 0;
     std::map> held_;                  // by the receiving end
     std::map> deferred_;  // ends waiting for open()
-    std::deque held_sealer_opens_;
+    std::deque held_derivations_;
     std::shared_ptr clock_;
+    std::vector>> watches_;  // made by watch_connectivity
 };
 
 inline memory_peer_connection::~memory_peer_connection() {
@@ -915,6 +1100,10 @@ inline memory_peer_connection::~memory_peer_connection() {
     }
 }
 
+inline std::optional memory_peer_connection::max_message_size() const {
+    return remote_id_ ? net_.max_message_size : std::nullopt;
+}
+
 inline void memory_peer_connection::try_connect() {
     if (connected_ || !remote_id_ || !ready()) {
         return;
@@ -978,6 +1167,10 @@ inline void memory_data_channel::send(std::span frame) {
     if (!open_ || !remote || registry_.expired()) {
         return;
     }
+    if (net_->send_limit && frame.size() > *net_->send_limit) {
+        close();
+        return;
+    }
     bytes_sent += frame.size();
     net_->route(pc_, remote->pc_, frame);
 }
@@ -1208,75 +1401,6 @@ inline std::size_t memory_network::scheduled() const {
     return clock_ ? clock_->due.size() : 0;
 }
 
-/** Seals as "$" whose IV is the key's first 16 bytes: only the same key
- * opens it. */
-class memory_sealer : public backend::sealer {
-public:
-    memory_sealer(memory_network& net, std::array key,
-                  std::pmr::memory_resource* memory)
-        : net_(net), io_(net.io()), key_(key), memory_(memory) {}
-
-    /** Posts the completion of an open whose result is known: `plain` when the text was `ours`. */
-    static void complete(webcpp::asio::io_context& io, std::pmr::memory_resource* memory, bool ours,
-                         std::pmr::string plain,
-                         handler done) {
-        post_in(io, memory, [ours, plain = std::move(plain), done = std::move(done)]() mutable {
-            done(ours ? backend::error_code{} : make_error_code(error::wrong_password), plain);
-        });
-    }
-
-    void seal(std::string_view plaintext,
-              handler done) override {
-        auto text = protocol::format_sealed(
-            std::span(key_).first(16),
-            std::span(reinterpret_cast(plaintext.data()), plaintext.size()),
-            memory_);
-        post_in(io_, memory_,
-                [text = std::move(text), done = std::move(done)]() mutable { done({}, text); });
-    }
-
-    void open(std::string_view sealed,
-              handler done) override {
-        const auto parts = protocol::parse_sealed(sealed, memory_);
-        const auto iv = std::span(key_).first(16);
-        const bool ours =
-            parts && std::equal(parts->iv.begin(), parts->iv.end(), iv.begin(), iv.end());
-        std::pmr::string plain(memory_);
-        if (ours) {
-            plain.assign(parts->ciphertext.begin(), parts->ciphertext.end());
-        }
-        if (net_.hold_sealer_opens) {
-            net_.held_sealer_opens_.push_back({
-                .memory = memory_,
-                .ours = ours,
-                .plain = std::move(plain),
-                .done = std::move(done),
-            });
-            return;
-        }
-        complete(io_, memory_, ours, std::move(plain), std::move(done));
-    }
-
-private:
-    memory_network& net_;
-    webcpp::asio::io_context& io_;
-    std::array key_;
-    std::pmr::memory_resource* memory_;
-};
-
-inline std::shared_ptr memory_network::make_sealer(
-    std::array key, std::pmr::memory_resource* memory) {
-    return std::allocate_shared(std::pmr::polymorphic_allocator<>(memory), *this,
-                                               key, memory);
-}
-
-inline void memory_network::release_sealer_opens() {
-    for (auto& held : std::exchange(held_sealer_opens_, {})) {
-        memory_sealer::complete(io_, held.memory, held.ours, std::move(held.plain),
-                                std::move(held.done));
-    }
-}
-
 }  // namespace webcpp::trystero::test
 
 #endif
diff --git a/test/support/rooms.hpp b/test/support/rooms.hpp
index 321a698..9b3eb22 100644
--- a/test/support/rooms.hpp
+++ b/test/support/rooms.hpp
@@ -14,9 +14,13 @@
 #include 
 #include 
 #include 
+#include 
+#include 
 #include 
 #include 
 #include 
+#include 
+#include 
 #include 
 #include 
 
@@ -42,11 +46,12 @@
 #include 
 #include 
 #include 
+#include 
 
 // The rooms' shared test helpers: a memory network with two relays, an app over them and a join
 // that must succeed, a watcher of a room's relay traffic, a flood of announcements, the virtual
-// clock's own waits, and a JSON document to send. A case of room_test.cpp, connection_test.cpp or
-// shared_test.cpp includes this header for them.
+// clock's own waits, and a JSON document to send. A case of room_test.cpp includes this header for
+// them.
 namespace webcpp::trystero::test {
 
 using namespace std::chrono_literals;
@@ -55,22 +60,131 @@ constexpr const char* relay_a = "wss://relay-a.test";
 constexpr const char* relay_b = "wss://relay-b.test";
 constexpr const char* app_id = "webcpp-trystero-tests";
 
-/** An app of the tests' app id over the two memory relays, with `self_id`; with
+/** The scalar of the endpoint key a test names by `label`: the SHA-256 of the label, a valid
+ * P-256 scalar for every label the tests use. */
+inline std::array endpoint_scalar(std::string_view label) {
+    return protocol::sha256(label);
+}
+
+/** The peer id an app whose endpoint key is named `label` derives. */
+inline std::string peer_id_of(std::string_view label) {
+    const auto scalar = endpoint_scalar(label);
+    const auto key =
+        trystero::detail::make_endpoint_identity(scalar, std::pmr::get_default_resource());
+    webcpp::test::require(BOOST_TEST(key.has_value()));
+    return std::string(key->peer_id);
+}
+
+/** A peer id a signal may carry, 20 base62 characters as 0.27.0 requires
+ * (protocol::is_signal_peer_id): `stem`, then '0's, then `number`, so that the ids of a stem differ
+ * and keep its first characters, which order them among the tests' apps. */
+inline std::string signal_id(std::string_view stem, std::size_t number) {
+    const auto digits = std::to_string(number);
+    webcpp::test::require(BOOST_TEST_LE(stem.size() + digits.size(), protocol::peer_id_size));
+    std::string id(stem);
+    id.append(protocol::peer_id_size - stem.size() - digits.size(), '0');
+    id += digits;
+    webcpp::test::require(BOOST_TEST(protocol::is_signal_peer_id(id)));
+    return id;
+}
+
+/** A peer id a signal may carry, `stem` and '0's to 20 base62 characters. */
+inline std::string signal_id(std::string_view stem) {
+    webcpp::test::require(BOOST_TEST_LE(stem.size(), protocol::peer_id_size));
+    std::string id(stem);
+    id.append(protocol::peer_id_size - stem.size(), '0');
+    webcpp::test::require(BOOST_TEST(protocol::is_signal_peer_id(id)));
+    return id;
+}
+
+/** `n` labels, `prefix` and a number each, ordered by the peer ids they derive, lowest first: a
+ * test that needs one peer to initiate, the lower id, names its apps with them. */
+inline std::vector ordered_labels(std::size_t n, std::string_view prefix = "peer") {
+    std::vector> by_id;
+    for (std::size_t i = 0; i < n; ++i) {
+        std::string label(prefix);
+        label += '-';
+        label += std::to_string(i);
+        by_id.emplace_back(peer_id_of(label), std::move(label));
+    }
+    std::ranges::sort(by_id);
+    std::vector out;
+    out.reserve(by_id.size());
+    for (auto& [id, label] : by_id) {
+        out.push_back(std::move(label));
+    }
+    return out;
+}
+
+/** A label, `prefix` and a number, whose peer id is below `id` (`below`) or above it: a test whose
+ * peer must offer to, or be offered by, peers of given ids names its app with it. */
+inline std::string label_beside(std::string_view id, bool below, std::string_view prefix = "side") {
+    for (std::size_t i = 0;; ++i) {
+        std::string label(prefix);
+        label += '-';
+        label += std::to_string(i);
+        const auto derived = peer_id_of(label);
+        if (below ? derived < id : derived > id) {
+            return label;
+        }
+    }
+}
+
+/** What an app of the tests is made with: its configuration, and the label of its endpoint key,
+ * so that its peer id is known. */
+struct app_setup : trystero::app_config {
+    /** The label of the app's endpoint key (@ref endpoint_scalar); empty draws a key. */
+    std::pmr::string label;
+};
+
+/** The configuration of a setup, without its label: for a test that names its keys itself. */
+inline trystero::app_config config_of(app_setup setup) {
+    return std::move(static_cast(setup));
+}
+
+/** An app of the tests' app id over the two memory relays, its endpoint key named `label`; with
  * WEBCPP_TEST_TRYSTERO_VERBOSE in the environment, its log goes to the standard error. */
-inline trystero::app_config app_config(std::string_view self_id, std::string_view password = {}) {
-    trystero::app_config c;
+inline app_setup app_config(std::string_view label, std::string_view password = {}) {
+    app_setup c;
     c.app_id = app_id;
     c.relay_urls = {relay_a, relay_b};
-    c.self_id = self_id;
+    c.label = label;
     c.password = password;
     if (std::getenv("WEBCPP_TEST_TRYSTERO_VERBOSE") != nullptr) {
-        c.log = [id = std::pmr::string(self_id)](std::string_view category, std::string_view text) {
+        c.log = [id = std::pmr::string(label)](std::string_view category, std::string_view text) {
             std::cerr << "  [" << id << "] " << category << ": " << text << "\n";
         };
     }
     return c;
 }
 
+/** A `trystero::app` whose endpoint key is named `label`, through the detail seam the library
+ * keeps for its own tests, since 0.27.0 has no custom endpoint key; an empty label draws one. */
+inline trystero::app make_app_with(std::string_view label, trystero::app::executor_type ex,
+                                   backend::factory& factory, trystero::app_config config) {
+    if (label.empty()) {
+        return {std::move(ex), factory, std::move(config)};
+    }
+    return trystero::detail::app_access::make(std::move(ex), factory, std::move(config),
+                                              endpoint_scalar(label));
+}
+
+/** An app of the tests: a `trystero::app` whose endpoint key is named by its setup's label. */
+class app : public trystero::app {
+public:
+    /** Makes the app of `setup` over `factory`; an empty label draws a key, as an app draws it. */
+    app(trystero::app::executor_type ex, backend::factory& factory, app_setup setup)
+        : trystero::app(make(std::move(ex), factory, std::move(setup))) {}
+
+private:
+    static trystero::app make(trystero::app::executor_type ex, backend::factory& factory,
+                              app_setup setup) {
+        const std::pmr::string label = std::move(setup.label);
+        return make_app_with(label, std::move(ex), factory,
+                             std::move(static_cast(setup)));
+    }
+};
+
 /** The owned document of a JSON text, as an action of JSON sends it; a text that does not parse
  * ends the test. */
 inline webcpp::document::document document_of(std::string_view text) {
@@ -87,9 +201,14 @@ inline trystero::room join(trystero::app& a, std::string_view room_id,
     return std::move(*r);
 }
 
+/** The wall-clock ceiling of a wait for something that must happen: a hang guard, far above any
+ * loaded run, never what a case measures. What must not happen within a time is waited for on
+ * the virtual clock. */
+constexpr std::chrono::milliseconds hang_guard = 120s;
+
 /** Runs the io_context until `done` holds or `limit` passes; whether `done` held. */
 inline bool run_until(webcpp::asio::io_context& io, const std::function& done,
-                      std::chrono::milliseconds limit = 10s) {
+                      std::chrono::milliseconds limit = hang_guard) {
     const auto end = std::chrono::steady_clock::now() + limit;
     while (!done() && std::chrono::steady_clock::now() < end) {
         io.run_for(20ms);  // lint-run: the memory relays and the rooms' timers post to it
@@ -113,13 +232,13 @@ struct fixture {
 };
 
 /** Runs until `done` holds, for at most `limit`: of the virtual clock when the fixture has one,
- * moving it from timer to timer, else of the wall clock. On the virtual clock it fires at most
- * `max_steps` timers, and fails the case by name past them: a timer re-armed without delay would
- * otherwise hold the clock still forever. */
+ * moving it from timer to timer, else of the wall clock, where it is at least `hang_guard`. On the
+ * virtual clock it fires at most `max_steps` timers, and fails the case by name past them: a timer
+ * re-armed without delay would otherwise hold the clock still forever. */
 inline bool run_until(fixture& f, const std::function& done,
                       std::chrono::milliseconds limit = std::chrono::seconds(10)) {
     if (!f.net.virtual_clock) {
-        return run_until(f.io, done, limit);
+        return run_until(f.io, done, std::max(limit, hang_guard));
     }
     const auto end = f.net.steady_now() + limit;
     for (std::size_t steps = 0; !done(); ++steps) {
@@ -210,44 +329,51 @@ class flooder {
     /** Publishes a signal on a topic, in any peer's name; with a nonce, as an event of its own. */
     void publish(std::string_view topic, const protocol::signal_message& m,
                  std::string_view nonce = {}) {
-        const std::array aux{};
-        socket_->send(protocol::nostr::event_message(*signer_, detail::unix_now(f_.net), topic,
-                                                     protocol::write_signal(m, nonce), aux));
+        socket_->send(signed_event(topic, protocol::write_signal(m, nonce)));
     }
 
-    /** `plain` sealed under the room key of `room`, with no password, as the memory sealer seals.
-     */
-    static std::string sealed(std::string_view room, std::string_view plain) {
-        const auto key = protocol::seal_key("", app_id, room);
-        return std::string(protocol::format_sealed(
-            std::span(key).first(16),
-            std::span(reinterpret_cast(plain.data()), plain.size())));
+    /** `plain` sealed under the room key of `room`, with no password, as `peer`'s signal of
+     * `type` for the offer `offer_id`, as a room seals it, under an IV of its own. */
+    static std::string sealed(std::string_view room, std::string_view plain, std::string_view peer,
+                              std::string_view offer_id, std::string_view type = "offer") {
+        static std::uint64_t seals = 0;
+        std::array iv{};
+        const auto n = ++seals;
+        for (std::size_t i = 0; i < sizeof(n); ++i) {
+            iv.at(i) = static_cast(n >> (8 * i));
+        }
+        const auto key = protocol::room_aes_key_without_password(app_id, room);
+        const auto aad = protocol::signal_aad(type, peer, offer_id);
+        auto text = protocol::seal(key, iv, plain, std::string_view(aad));
+        webcpp::test::require(BOOST_TEST(text.has_value()));
+        return std::string(*text);
     }
 
     /** Announces one id `times` times. */
     void announce_as(std::string_view id, std::size_t times) {
-        const std::array aux{};
         for (std::size_t i = 0; i < times; ++i) {
             const auto nonce = std::to_string(next_++);
-            const auto content = protocol::write_signal({.peer_id = id}, nonce);
-            socket_->send(protocol::nostr::event_message(*signer_, detail::unix_now(f_.net), topic_,
-                                                         content, aux));
+            socket_->send(signed_event(topic_, protocol::write_signal({.peer_id = id}, nonce)));
         }
     }
 
-    /** Announces `count` ids, each `prefix` and a number. */
+    /** Announces `count` ids, each `prefix` and a number (@ref signal_id). */
     void announce(std::size_t count, std::string_view prefix) {
-        const std::array aux{};
         for (std::size_t i = 0; i < count; ++i) {
-            std::pmr::string id(prefix);
-            id += std::to_string(next_++);
-            const auto content = protocol::write_signal({.peer_id = id});
-            socket_->send(protocol::nostr::event_message(*signer_, detail::unix_now(f_.net), topic_,
-                                                         content, aux));
+            const auto id = signal_id(prefix, next_++);
+            socket_->send(signed_event(topic_, protocol::write_signal({.peer_id = id})));
         }
     }
 
 private:
+    /** The client message of an event of `content` on `topic`, signed with the flooder's key. */
+    std::pmr::string signed_event(std::string_view topic, std::string_view content) {
+        auto message =
+            protocol::nostr::event_message(*signer_, detail::unix_now(f_.net), topic, content);
+        webcpp::test::require(BOOST_TEST(message.has_value()));
+        return std::move(*message);
+    }
+
     fixture& f_;
     std::pmr::string topic_;
     std::shared_ptr socket_;
diff --git a/test/timer_test.cpp b/test/timer_test.cpp
index 1b312a6..372d1a4 100644
--- a/test/timer_test.cpp
+++ b/test/timer_test.cpp
@@ -71,7 +71,7 @@ void both_expired(asio::io_context& io, trystero::detail::timer& first,
                   trystero::detail::timer& second, std::size_t& second_fired, Then then) {
     first.start(0ms, then);
     second.start(0ms, [&second_fired] { ++second_fired; });
-    io.run_for(100ms);  // lint-run: the timers' expiries are the events under test
+    io.run();  // lint-run: ends when both waits have completed, whatever the load
     io.restart();
 }
 
@@ -82,7 +82,7 @@ void an_uncancelled_wait_fires_once() {
     const std::size_t made = memory.allocations;
     std::size_t fired = 0;
     timer->start(1ms, [&] { ++fired; });
-    io.run_for(100ms);  // lint-run: the wait expires
+    io.run();  // lint-run: ends when the wait has completed
     BOOST_TEST_EQ(fired, 1U);
     // The wait was allocated in the timer's resource, and given back once it completed.
     BOOST_TEST_GT(memory.allocations, made);
@@ -117,7 +117,7 @@ void a_restarted_timer_fires_only_its_new_wait() {
     std::size_t fired = 0;
     std::size_t restarted = 0;
     both_expired(io, *first, *second, fired, [&] { second->start(10ms, [&] { ++restarted; }); });
-    io.run_for(100ms);  // lint-run: the restarted wait expires
+    io.run();  // lint-run: ends when the restarted wait has completed
     BOOST_TEST_EQ(fired, 0U);
     BOOST_TEST_EQ(restarted, 1U);
 }
diff --git a/test/user_table_test.cpp b/test/user_table_test.cpp
new file mode 100644
index 0000000..8a76d42
--- /dev/null
+++ b/test/user_table_test.cpp
@@ -0,0 +1,87 @@
+// Copyright (c) 2026 WebCpp.org
+//
+// Distributed under the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// https://www.boost.org/LICENSE_1_0.txt)
+
+// Tests a room's users and their peers alone, as 0.27.0's room counts them: a user joins with its
+// first peer and leaves with its last, and a peer belongs to one user.
+
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+#include "cases.hpp"
+
+namespace trystero = webcpp::trystero;
+
+namespace {
+
+std::vector peers_of(const trystero::detail::user_table& t, std::string_view user) {
+    const auto peers = t.peers_of(user);
+    return {peers.begin(), peers.end()};
+}
+
+void first_peer_joins_the_user() {
+    trystero::detail::user_table t(std::pmr::new_delete_resource());
+    BOOST_TEST(t.add("p1", "u"));
+    BOOST_TEST(!t.add("p2", "u"));
+    BOOST_TEST(t.add("p3", "v"));
+    const std::vector both{"p1", "p2"};
+    const auto of_u = peers_of(t, "u");
+    BOOST_TEST_ALL_EQ(of_u.begin(), of_u.end(), both.begin(), both.end());
+    BOOST_TEST_EQ(peers_of(t, "v").size(), 1U);
+    BOOST_TEST(peers_of(t, "w").empty());
+    BOOST_TEST_EQ(t.user_of("p2").value_or(""), "u");
+    BOOST_TEST_EQ(t.user_of("p3").value_or(""), "v");
+    BOOST_TEST(!t.user_of("p4"));
+    BOOST_TEST_EQ(t.users().size(), 2U);
+}
+
+void last_peer_leaves_the_user() {
+    trystero::detail::user_table t(std::pmr::new_delete_resource());
+    t.add("p1", "u");
+    t.add("p2", "u");
+    BOOST_TEST(!t.remove("p1"));
+    BOOST_TEST(!t.user_of("p1"));
+    const std::vector left{"p2"};
+    const auto of_u = peers_of(t, "u");
+    BOOST_TEST_ALL_EQ(of_u.begin(), of_u.end(), left.begin(), left.end());
+    const auto gone = t.remove("p2");
+    BOOST_TEST_EQ(gone.value_or("none"), "u");
+    BOOST_TEST(peers_of(t, "u").empty());
+    BOOST_TEST(t.users().empty());
+    BOOST_TEST(!t.remove("p2"));   // a peer not in the table makes no user leave
+    BOOST_TEST(t.add("p2", "u"));  // and a user that left joins again with its next peer
+}
+
+void a_peer_moves_nowhere() {
+    trystero::detail::user_table t(std::pmr::new_delete_resource());
+    BOOST_TEST(t.add("p1", "u"));
+    BOOST_TEST(!t.add("p1", "v"));  // refused: p1 is u's
+    BOOST_TEST(!t.add("p1", "u"));
+    BOOST_TEST_EQ(t.user_of("p1").value_or(""), "u");
+    BOOST_TEST(peers_of(t, "v").empty());
+    BOOST_TEST_EQ(peers_of(t, "u").size(), 1U);
+    BOOST_TEST_EQ(t.users().size(), 1U);
+    t.clear();
+    BOOST_TEST(t.users().empty());
+    BOOST_TEST(!t.user_of("p1"));
+}
+
+}  // namespace
+
+int main() {
+    // Each case in a frame of its own, which main's never holds (cases.hpp).
+    using webcpp::test::run_case;
+    run_case(first_peer_joins_the_user);
+    run_case(last_peer_leaves_the_user);
+    run_case(a_peer_moves_nowhere);
+    return webcpp::test::exit_status(boost::report_errors());
+}