diff --git a/README.md b/README.md index 304bf10e..5fd986e4 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ tag is placed. | pratt | [genesis](libraries/pratt/openspec/changes/archive/2026-10-08-genesis) | pratt: a generic Pratt parser engine for C++20, with a decimal calculator | own | implemented | 0.1.0 | 2026-10-08 | [code](https://github.com/webcpporg/pratt/tree/d78451b) | | trystero | [genesis](libraries/trystero/openspec/changes/archive/2026-10-09-genesis) | trystero: serverless WebRTC rooms, wire compatible with Trystero | port of Trystero 0.26.0 | implemented | 0.1.0 | 2026-10-09 | [code](https://github.com/webcpporg/trystero/tree/160f431) | | trystero | [bounded-json-parse](libraries/trystero/openspec/changes/bounded-json-parse) | trystero: bound the text and the objects a room parses | port of Trystero 0.26.0 | draft | | | | +| trystero | [trystero-0-27](libraries/trystero/openspec/changes/trystero-0-27) | trystero: port to Trystero 0.27.0 | port of Trystero 0.27.0 | draft | | | | | trystero | [shared-connection](libraries/trystero/openspec/changes/archive/2026-11-14-shared-connection) | trystero: one connection shared by the rooms of an app | port of Trystero 0.26.0 | implemented | 0.1.0 | 2026-10-11 | [code](https://github.com/webcpporg/trystero/tree/e9326e94c06cfa9ffdbd0a8d3c8d72b80b3b9b59) | | wasi | [genesis](libraries/wasi/openspec/changes/archive/2026-10-08-genesis) | wasi: the HTTP handler a WebAssembly component exports, for C++ on wasip2 and wasip3 | own | implemented | 0.1.0 | 2026-10-08 | [code](https://github.com/webcpporg/wasi/tree/6e3c529) | | wasi | [redesign](libraries/wasi/openspec/changes/redesign) | wasi: one namespace per WASI version, one entry point, target features and run scripts | own | accepted | | 2026-10-09 | | diff --git a/libraries/trystero/openspec/changes/trystero-0-27/.openspec.yaml b/libraries/trystero/openspec/changes/trystero-0-27/.openspec.yaml new file mode 100644 index 00000000..ee64e5fa --- /dev/null +++ b/libraries/trystero/openspec/changes/trystero-0-27/.openspec.yaml @@ -0,0 +1,11 @@ +schema: spec-driven +created: 2026-11-20 +webcpp: + library: trystero + title: "trystero: port to Trystero 0.27.0" + kind: port + port_of: "Trystero 0.27.0" + status: draft + release: null + implementation: null + decided: null diff --git a/libraries/trystero/openspec/changes/trystero-0-27/design.md b/libraries/trystero/openspec/changes/trystero-0-27/design.md new file mode 100644 index 00000000..190c847c --- /dev/null +++ b/libraries/trystero/openspec/changes/trystero-0-27/design.md @@ -0,0 +1,287 @@ +## Context + +webcpp::trystero 0.1.0 ports Trystero 0.26.0's serverless WebRTC rooms over Nostr, byte for byte +on the wire, with two backends folded into one platform backend (webcpp::webrtc, webcpp::beast, +webcpp::asio). Its cryptography is its own: SHA-1 and SHA-256 from Boost.Hash2, a `sealer` per +backend (OpenSSL's AES-GCM natively, `crypto.subtle` through EM_ASM in a page), randomness from +OpenSSL's `RAND_bytes` or the page's `getRandomValues`, and a BIP-340 signer on libsecp256k1. + +Trystero 0.27.0 (upstream commit `8d3f57e`) changes the wire throughout. Everything it computes +with WebCrypto is available in webcpp::hash and webcpp::crypto today except ECDSA P-256 and P-256 +ECDH, which webcpp::crypto's foundation increment 3 plans (`curves::p256`, design D36 there). The +P-256 handshake runs on every room, so no 0.27.0 room can be joined before it exists. + +The owner asked for the port on 2026-11-20 and is on autopilot: the rulings below are the +controller's, recorded here. + +## Goals / Non-Goals + +**Goals:** + +- A room joined from C++ and the same room joined from Trystero 0.27.0's JavaScript are one room. +- Every value of the wire is proven against 0.27.0's own code, run in Node (`reference/vectors/`). +- trystero's cryptography is webcpp::hash's and webcpp::crypto's, on every target. +- The port reaches `main` once, whole and interoperable. + +**Non-Goals:** + +- The strategies other than Nostr (BitTorrent, MQTT, Supabase, Firebase, the WebSocket relay and + its server): D3. +- Media (`addStream`, `onPeerStream`), as in 0.1.0. +- Persistence of an identity by the library (IndexedDB's `identity: 'local'`): D15. +- Compatibility with 0.26.x peers: 0.27.0 has none either. + +## Decisions + +### D1. One long-lived branch, merged once + +0.27.0's wire is incompatible with 0.26.0 and its handshake needs P-256 on every room, so any +partial merge would leave `main` meeting nobody. The port lives on the library branch +`port/trystero-0.27` and the superproject branch `trystero/port-0.27`, both from `main`, rebased +onto `main` at each phase's end. Phase 1 turns off the oracle and interop lanes on the branch (an +`explicit` on their targets) and Phase 2's Task 2.6 turns them back on against 0.27.0; nothing is +merged until they are green and the CI of both repositories is green. Draft pull requests carry +the branch for review. Phase 3's plugins are features on top of an interoperable library and +merge as separate changes after it. Rejected: merging Phase 1 behind a macro (two wires in one +library, and a `main` whose default meets nobody); waiting with all work until P-256 merges +(Phase 1 is half the port and needs nothing of P-256). + +### D2. trystero moves onto webcpp::crypto and webcpp::hash (supersedes 2026-11-17) + +On 2026-11-17 the owner dropped trystero's migration onto webcpp::crypto (crypto genesis D23, +Tasks 31 and 32). On 2026-11-20 he asked for the 0.27.0 port on webcpp::crypto; that request +supersedes the earlier decision, and this change is "the later change of trystero's own" crypto's +genesis anticipated. The mapping: + +| 0.27.0 through WebCrypto | webcpp | +| --- | --- | +| SHA-256 | `webcpp::hash::digest_of` | +| HMAC-SHA-256 sign and verify | `webcpp::hash::hmac_sha2_256`, `webcpp::crypto::equal` | +| HKDF-SHA-256 | `webcpp::hash::hkdf` | +| PBKDF2-SHA-256, 600,000 iterations | `webcpp::hash::async_pbkdf2` (D5) | +| AES-256-GCM, 12-byte IV, AAD | `webcpp::crypto::aes256_gcm` | +| `getRandomValues`, `randomUUID` | `webcpp::crypto::random_device`, `protocol::uuid_v4` | +| BIP-340 (noble's `schnorr`) | `webcpp::crypto::curves::secp256k1::keypair::sign_schnorr`, `verify_schnorr` | +| ECDSA P-256, raw `r || s`, low S | `webcpp::crypto::curves::p256` (increment 3): `sign_ecdsa`, `verify_ecdsa`, `normalize_ecdsa`, `check_low_s` | +| ECDH P-256 raw x (scale) | `curves::p256::keypair::ecdh_x` | + +### D3. Nostr only + +Today only Nostr is ported, and the library's tests run a Nostr relay of their own. 0.27.0's other +strategies share the core, so a later change can add one by porting its `init`, `subscribeTopic` +and `publishTopic`; none is in scope, and the WebSocket relay's server is not ported either. + +### D4. The crypto layer is synchronous protocol code, in the core + +Hashing, key derivation from a master, sealing and opening, room auth and ids are pure functions +in `protocol/` (`topics.hpp`, `ids.hpp`, `room_keys.hpp`, `seal.hpp`), tested against the +vectors on both targets. The backend's `sealer` and `factory::make_sealer` are removed: a signal +of a few kilobytes seals in microseconds with BearSSL or OpenSSL, and an asynchronous seal only +existed because the page's WebCrypto is asynchronous. webcpp::crypto's browser backend (its +increment 4, part B) is therefore not needed; its asynchronous family (increment 4, part A) is +not used either. + +### D5. PBKDF2 never runs on a room's thread + +600,000 iterations take about 0.2 s natively and several seconds in WebAssembly; Trystero runs +them in WebCrypto, off the page's thread. The platform backend implements +`factory::derive_password_master`: natively with `webcpp::hash::async_pbkdf2` on a +one-thread `webcpp::asio::thread_pool` it owns (made on first use; the native backend already +requires threads), on Emscripten with `async_pbkdf2` on the +page's loop executor. Everything else of the crypto layer is synchronous with webcpp's default +backends (BearSSL on Emscripten and WASI, as webcpp::crypto's defaults pick). Rejected: a +synchronous PBKDF2 on the room's executor (stalls a page for seconds); a work executor in +`app_config` (an option every native program would have to fill for a once-per-room cost). + +### D6. Room keys, their cache and their failure + +A room without a password keys AES with SHA-256 of `["trystero:room-aes:v3",app,room]`; with one, +the app derives a PBKDF2 master (salt SHA-256 of `["trystero:pbkdf2-master:v3",app,room]`), then +HKDF to the AES key and the HMAC key, wipes the master, and keeps at most 64 rooms' keys (least +recently used out), as 0.27.0's `derivedRoomKeysCache`; a failed derivation is forgotten. The +password stays per app (0.1.0's ruling: one password per app), so the cache is keyed by room id. +A room announces nothing before its key exists. A failed derivation is reported as +`error::backend_failure`, since 0.27.0 has no room error code for it. + +### D7. Dependencies and allocation + +`parts` links webcpp::hash and webcpp::crypto (`crypto`, `gcm-default`, `secp256k1-default`); +libsecp256k1 arrives through webcpp::crypto, with the same `webcpp-secp256k1-tables` feature. +OpenSSL stays natively for TLS and libdatachannel, but trystero's own code no longer calls it. +What webcpp::crypto's secp256k1 context or webcpp::hash's WebCrypto bridge allocates outside a +room's resource is measured by the allocation tests and listed in the allocation page. + +### D8. Phase 1 runs on a provisional identity + +Before P-256, a room's peer id is 20 base62 characters drawn at random and its user id equals it. +The values have 0.27.0's form, the rooms meet each other over the memory backend and local +relays, and nothing claims interoperability until Phase 2. + +### D9. One connection per room and remote peer (confirmed 2026-11-22, plan Task 2.1a) + +0.27.0 removed 0.26.0's `shared-peer.ts`, and reading 0.27.0's `strategy.ts`, `signal-handler.ts`, +`peer.ts`, `peer-transport.ts` and `room.ts` confirms it shares nothing: each room makes its own +offers (`createOfferManager(() => initPeer(true, ...))`) and answers (`initPeerFn(false, ...)`), +keeps one connected peer per remote id (`connectPeer` keeps a live one and replaces a stale +one), writes its action frames bare on the channel (`sendFrame`), and binds its handshake to that +connection's DTLS fingerprints and to its app and room. The port follows: the app keeps one +identity, its relays and its key cache; each room its own connections, in the room's resource. The +archived `shared-connection` change's sharing, its presence frames, `room_token`, rebinding, the +idle time of a connection, the 64-room bound (`max_rooms`, `too_many_rooms`) and the password +handshake (`__trystero_pw`, which 0.27.0 dropped: a password keys the signals only) are retired. +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, 64 KiB after. Rejected: keeping the sharing as a C++ extension (a JS peer's +connection belongs to one room: another room's frames on it would be read as this room's); keeping the +64-room bound (it existed for 0.26.0's token limit). + +### D10. Listeners return a subscription + +`on_*` adds a listener and returns a move-only `subscription` whose `unsubscribe()` removes it; +destroying the token leaves the listener, as dropping the function Trystero returns does (a +RAII token would silently remove listeners whose token a program did not keep). `listen_options` +has `once` and `replay`; Trystero's `signal` (an `AbortSignal`) has no C++ counterpart and +`unsubscribe` replaces it. `on_request` and `on_receive` take one listener at a time and refuse a +second with `error::already_subscribed` (Trystero throws). + +### D11. self(), users() and peers() + +`self()` is synchronous: an app's identity exists once it is constructed (Trystero's `getSelf()` +is a promise because WebCrypto's key generation is). `peers()` has no `connection` member: the +backend's peer connection is not public in C++. + +### D12. An opened text must be UTF-8 + +Trystero decodes a plaintext with `TextDecoder`, which replaces invalid UTF-8 by U+FFFD. The port +refuses such a plaintext as `decrypt_failed`: an SDP is ASCII and a replaced text would be another +text than the peer sealed. Listed as a difference. + +### D13. Relay connectivity belongs to the app + +Trystero's `setRelayConnectivity` is process-wide; a C++ process may hold several independent +apps, so it is `app::set_relay_connectivity`. `automatic` follows the page's `online` and +`offline` events on Emscripten and is `online` natively, where no such signal exists. + +### D14. The differences page + +Removed: `diff_already_joined` (0.27.0 now refuses a second join too), `diff_self_id` and +`diff_self_id_not_utf8` (no custom self id in 0.27.0), `diff_peer_join` if its listener model is +now the same. Added: D10's token and `signal`, D11's synchronous `self()` and missing +`connection`, D12, D13, D15, and the password per app (kept from 0.1.0). Each added difference +gets its program and its twin as today. + +### D15. No implicit identity persistence + +0.27.0's default `identity: 'local'` keeps the user key in IndexedDB. C++ has no such store: the +default is an ephemeral identity, and a program keeps one across runs with +`export_user_identity` and `import_user_identity` (Phase 2), storing the text where it wants. + +### D16. Where 0.27.0's features land + +Phase 1: everything without P-256 (this plan's Tasks 1 to 13). Phase 2: identity, the handshake, +verified users, `max_users`, interop. Phase 3: `make_state` and `make_user_state` (core in +0.27.0, but signed records need P-256 and the shared-state machinery is large), `roles()`, then +`scale()`. Rough size: Phase 1 thirteen tasks, some 6,000 to 8,000 lines changed with tests; +Phase 2 twelve tasks (plan 2.1a to 2.7), some 5,000 lines deleted with the shared connection and +5,000 to 7,000 written; Phase 3 three changes, some 10,000 to 14,000. + +### D17. Identity belongs to the app + +0.27.0 caches one endpoint identity per app id and page (`getDefaultEndpointIdentity(appId, +clientId)`) 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 (`p256::keypair::generate`), whose +compact key derives `self_id()`, and one user identity, `app_config::identity` or an ephemeral one +made with the app. `user_identity` is a copyable handle to an immutable key, so that several apps +(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. +Persistence is `ephemeral` (0.27.0's `'none'`) or `imported` (its `'custom'`); there is no +`'local'` (D15). Rejected: an identity per room (0.27.0's per-room `identity` option exists, but a +C++ program that wants two users makes two apps; listed as a difference); a process-wide cache of +endpoints (state outside every app's resource). + +### D18. Signatures are synchronous, deterministic and checked as 0.27.0 checks them + +ECDSA P-256 is webcpp::crypto's on BearSSL on every target, synchronous like the rest of the crypto +layer (D4): signing normalizes to low S (`normalize_ecdsa`), verification refuses a high S +(`check_low_s`) before `verify_ecdsa`. 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-record cache (4,096) and the verified-signature cache (8,192 entries, 2 MiB, payloads of at +most 4,096 bytes) are 0.27.0's bounds, per app rather than per page. 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; a +difference. Rejected: webcpp::crypto's asynchronous family (nothing to gain off a page's thread +for a few signatures per peer); a process-wide cache. + +### D19. One vectors file, its signatures kept, proven against the published packages too + +The recorder writes one file for both phases, `trystero-0.27.0.json` like the library's fixture +(Phase 1's `phase1.json`, renamed). WebCrypto's ECDSA is random, so the recorder takes its +previous output and keeps each signature recorded there that 0.27.0's own verification still +accepts, signing only what is missing: a run over the fixture writes it again byte for byte, and +every kept signature is verified again by 0.27.0's code on every run. With `--dist ` +the same recorder imports the published `@trystero-p2p/core` and `@trystero-p2p/nostr` 0.27.0 +instead of the checkout; the oracle lane runs it so, proving that what a JS peer installs equals +the pinned source. JS verifies the C++ side's signatures in the interop lane. Rejected: a +deterministic signer in the recorder (it would not be 0.27.0's code); vectors without signatures +(the C++ side would never verify a JS signature outside the interop lane). + +### D20. The handshake reads its fingerprints from the descriptions the signaling handled + +0.27.0 reads `a=fingerprint:` lines from `localDescription.sdp` and `remoteDescription.sdp`. The +port's signaling hands its room the last local description `set_local_description` gave 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. Rejected: a backend call returning fingerprints (two platform implementations for +what the signaling already holds). + +### D21. The user-proof is protocol code only + +0.27.0's `identity.ts` defines `userEndpointProofPayload`, `signUserEndpointProof` and +`verifyUserEndpointProof`, but its core neither sends nor checks one: the handshake's dual +signatures over the transcript bind the user key to the endpoint. The port keeps the payload and +proves it with the vectors, for Phase 3's plugins if they use it. Rejected: inventing a use 0.27.0 +does not make. + +### D22. Wide chunks follow the connection's largest message + +0.27.0 sends 64 KiB chunks to a peer whose `RTCPeerConnection.sctp.maxMessageSize` is at least +65,536. `backend::peer_connection::max_message_size()` reports it (libdatachannel's +`remoteMaxMessageSize()`, a page's `pc.sctp.maxMessageSize`), and the action wire offers wide +transfers on such a connection. Rejected: always narrow (Phase 1's state, slower and not 0.27.0's +frames). + +### D23. The error list loses what 0.27.0 lost before the merge + +`wrong_password`, `handshake_timed_out` and `too_many_rooms` name what 0.27.0 no longer has (the +password handshake, its timeout as a code of its own, the 64-room bound): they are removed before +the port merges, and the values after them move; nothing on `main` has seen the 0.27.0 values. +`invalid_user_identity` and `invalid_max_users` are appended for what 0.27.0 throws. Rejected: +keeping retired values reserved (R2 kept numbering stable within the branch only). + +## Risks / Trade-offs + +- [P-256 slips] Phase 2 and the merge wait; Phase 1 stays on its branch and is rebased onto + `main` as `main` moves. +- [0.27.x patch releases change the wire again] the pin is `8d3f57e`; a later patch is a + follow-up change, its vectors regenerated by the recorder. +- [WebCrypto's PBKDF2 under node] Emscripten tests run under node, which has WebCrypto; the + memory backend's synchronous PBKDF2 keeps unit tests independent of it. +- [The retired shared connection] D9 removes 0.1.0 work; it was confirmed by reading 0.27.0 first. +- [Interop timing] the handshake adds a round trip and two signatures per peer; Chrome's and the + native peer's scenarios are bounded and use completions, never margins. + +## Migration Plan + +Programs replace setters by `on_*` calls, read `self()` instead of `self_id()`, drop +`self_id` and `handshake_timeout` from their configuration, and handle the new error codes. The +README and the pages carry a migration section modelled on Trystero's `MIGRATION.md`. + +## Open Questions + +1. Does webcpp::crypto's `random_device` on Emscripten keep a JavaScript exception out of + WebAssembly when the page has no `crypto` (0.1.0's entropy caught it)? Phase 2's Task 2.6b + tests it (`platform_page_entropy`); if it does not, the guard is the crypto stream's and the + test stays explicit until it lands (it does not block the merge: Trystero JS cannot run in + such a page either). +2. Is the action wire's request/response protocol carried in metadata or in frames of its own? + Answered by Task 8's recorded frames: metadata (`{"r":}`) and the internal action + `@_response`; 0.27.0's ping is such a request (`ping_frames`). diff --git a/libraries/trystero/openspec/changes/trystero-0-27/proposal.md b/libraries/trystero/openspec/changes/trystero-0-27/proposal.md new file mode 100644 index 00000000..112e037c --- /dev/null +++ b/libraries/trystero/openspec/changes/trystero-0-27/proposal.md @@ -0,0 +1,68 @@ +## Why + +Trystero 0.27.0 (2026-11-11) is a major release with a new wire protocol that is not compatible +with 0.26.x peers: topics, ids, relay order, Nostr kinds, sealing and the action wire all changed, +and every room now runs a dual-signature handshake over ECDSA P-256 that binds unforgeable user +and endpoint identities to the WebRTC connection. webcpp::trystero ports 0.26.0, so a C++ peer no +longer meets a current Trystero JS peer. The owner asked on 2026-11-20 for the port to 0.27.0, and +for it to rest on webcpp::crypto and webcpp::hash; that supersedes his decision of 2026-11-17 +(webcpp::crypto's genesis, design D23) that trystero would not move onto webcpp::crypto. + +## What Changes + +- **BREAKING (wire):** every value a peer exchanges follows 0.27.0: topics are the base64url + SHA-256 of a JSON path (`["Trystero",app,room]`), ids are unbiased base62 (peer ids 20 and user + ids 22 characters), relays are 0.27.0's 30 defaults in a new seeded order, Nostr kinds are + FNV-1a, a REQ asks `since` a minute ago, announcements carry a nonce, signals are sealed with + AES-256-GCM under a 12-byte IV with the signal's AAD and packed as base64url(iv || ct || tag), + a password derives the room's keys by PBKDF2-SHA-256 (600,000 iterations) then HKDF, the action + wire is version 3. +- **BREAKING (wire, Phase 2):** identity and the handshake: an endpoint key and a user key + (ECDSA P-256) per peer, `peerId` and `userId` derived from them, a dual-signature handshake + binding both SDP fingerprints; import and export of a user identity. +- **BREAKING (API):** listeners are `on_*` calls returning a `subscription` (several per event, + `once`, `replay`); `on_user_join`/`on_user_leave` beside `on_peer_join`/`on_peer_leave`; + `on_error` reports 0.27.0's room error codes (`room-full`, `banned`, `relay-failed`, + `identity-failed`, `plugin-failed`, `decrypt-failed`, `peer-connect-failed`, + `handshake-failed`, `peer-error`) with their context; `self()`, `users()`, `peers()`; + sends target a user or a peer and fail on an absent target; `set_relay_connectivity`; + `handshake_timeout` and a custom self id removed. +- **Dependencies:** trystero's sealer, randomness and Nostr signer move onto webcpp::crypto + (`aes256_gcm`, `random_device`, `curves::secp256k1`) and its hashing onto webcpp::hash + (SHA-256, HMAC, HKDF, PBKDF2; WebCrypto's PBKDF2 on Emscripten); the backend's `sealer` and + the EM_ASM WebCrypto and OpenSSL code of trystero's own are removed; Phase 2 needs + webcpp::crypto's P-256 (its foundation increment 3). +- **Plugins (Phase 3):** signed shared and per-user state, roles and moderation, then `scale()`. +- **Scope:** the Nostr strategy only, as today; media stays unported. +- **One merge:** the port lives on the branch `port/trystero-0.27` and reaches `main` once, when + interop with Trystero 0.27.0 JS peers is green. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `trystero`: ADDED requirements for 0.27.0's crypto layer, topics, ids, relays, Nostr details, + action wire v3, listeners, room errors, users and peers, relay connectivity, the key + derivation seam, the dependencies, the vectors, the branch and the Phase 2 and 3 features; + REMOVED requirements for 0.26.0's ids, topics, shuffle, sealing, sealer backends, signer, + self id and oracle pin. + +## Impact + +- **Kind:** port, of Trystero 0.27.0 (`port_of`), from 0.26.0. +- **Implementation:** Phase 1 built on the branches; `reference/plan.md` is the plan (Phases 1 + and 2 in full, Phase 3 outlined), `reference/vectors/` the recorder and the vectors it recorded + from 0.27.0's code (`trystero-0.27.0.json`). + Library branch `port/trystero-0.27`, superproject branch `trystero/port-0.27`. +- **Dependencies:** webcpp::hash and webcpp::crypto (new); libsecp256k1 through webcpp::crypto + instead of directly; Phase 2 waits on webcpp::crypto's P-256 (foundation increment 3, Tasks + 3.1 to 3.3 of its plan). +- **Status:** draft; release none. +- **Other proposals:** supersedes the part of webcpp::crypto's genesis D23 that kept trystero off + webcpp::crypto; `bounded-json-parse` (draft) applies to the same parser and is rebased on this + branch if it is accepted first; the archived `shared-connection`'s app-level sharing is retired + by design D9, which Phase 2's reading of 0.27.0 confirmed. diff --git a/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md b/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md new file mode 100644 index 00000000..371b3e6d --- /dev/null +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md @@ -0,0 +1,172 @@ +# webcpp::trystero, port to Trystero 0.27.0: as built after Phase 1 + +Written 2026-11-22. Phase 1 (plan Tasks 1 to 13) is built on its branches, not interoperable +before Phase 2, and merged nowhere (design D1). Phase 2 waits for webcpp::crypto's P-256 +(foundation increment 3, its plan's Tasks 3.1 to 3.3). `plan.md` is the plan, `vectors/record.mjs` +the recorder and `vectors/trystero-0.27.0.json` what it recorded (named `phase1.json` until +Phase 2 was written in full, 2026-11-22, with Phase 2's vectors added). + +## Where it stands + +| What | Where | +| --- | --- | +| The library | `webcpporg/trystero`, branch `port/trystero-0.27`, from `main` `0f7e6f4` | +| The superproject | `webcpporg/webcpp`, branch `trystero/port-0.27`, from `main` `4c5cfcc`: chapter 15's trystero section and the library's pointer | +| The vectors | `vectors/trystero-0.27.0.json` (was `phase1.json`), recorded 2026-11-20 with node v26.13.0 from Trystero 0.27.0 at `8d3f57e`, with the action frames since Task 8 (`49ecd70` here); the library's copy is `test/fixtures/expected/trystero-0.27.0.json`, written only by `test/oracle/record_0_27.mjs` | +| The lanes | the oracle and interop lanes are `explicit` on the branch (their Trystero is 0.26.0); every other test and example passes natively and on emscripten | +| Blocking Phase 2 | webcpp::crypto's `curves::p256` | + +## Phase 1, task by task (library commits) + +| Task | Commits | What | +| --- | --- | --- | +| 1 | `0f7e6f4..5b3087d` | the build moves onto webcpp::hash and webcpp::crypto; the fixture and its `section()` | +| 2 | `5b3087d..07c19ee` | topics, `hash32`, `str_to_num`, strict base64url, domain tags; one JSON string writer | +| 3 | `07c19ee..93fc181` | base62 ids, `gen_id`, UUIDs, derived ids; relays by `str_to_num` | +| 4 | `93fc181..1a8d3a6` | room keys, PBKDF2 master, HKDF, room auth tokens | +| 5 | `1a8d3a6..6578725` | sealing as 0.27.0 seals, with the signal's AAD; the whole error list (R2) | +| 6 | `6578725..38d82e4` | no sealer: the key derivation seam, PBKDF2 off the room's thread, the keys cache | +| 7 | `38d82e4..fbc66a1` | 0.27.0's Nostr: a signer per room over webcpp::crypto, kinds by FNV-1a, subscriptions since a minute ago, relay health | +| 8 | `fbc66a1..38d087f` | the action wire, version 3, its limits and the wide flag (received only) | +| 9 | `38d087f..487c99e` | listeners and subscriptions, receive gates, progress, request actions | +| 10 | `487c99e..ea6f2d1` | 0.27.0's room errors, `room_error`, `decrypt_failed` paced per peer and stage | +| 11 | `ea6f2d1..b4b87e9` | users and peers, `self()`, sends to users, `not_connected` | +| 12 | `b4b87e9..5c7f578` | relay connectivity per app; `self_id` and `handshake_timeout` gone | +| 12b | `5c7f578..9741f9b` | trystero's own `detail::wipe` (R19) | +| 13 | `9741f9b..1994bf2` | the pages, the README and AGENTS.md say what Phase 1 changed; `diff_peer_join` retired | + +## Rulings that changed the plan + +- **R2.** Task 5 appended Task 10's whole error list (`room_full` to `request_timed_out`, with + 0.27.0's messages), so that numbering never changes; `action_redefined` (R15) is 29. +- **R11, amended.** `signer::generate` draws 32 bytes from `webcpp::crypto::random_device` and + makes the key with `keypair::make`, at most 4 draws, completing with `entropy_unavailable` + otherwise, as webcpp::crypto's coming secp256k1 `keypair::generate` does. **Phase 2's merge-main + step switches `signer::generate` to crypto's `keypair::generate` (one line).** +- **R14.** Frames of an action the room has not made follow 0.27.0: inline frames are dropped and + offers rejected at once as "unregistered action"; the 32-per-action-and-peer buffer for 10 s is + only for actions made that do not listen yet. +- **R15.** A name made both a message and a request action fails with `error::action_redefined`, + where 0.27.0 throws. A lone surrogate is refused in a peer's JSON metadata and payload, and read + as U+FFFD in a refusal's reason that 0.27.0's 512-unit cut left ending in one. +- **R16.** The `peer_connect_failed` hint names the port's option, "configure TURN via + app_config::ice_servers"; `turn_configured` counts only the TURN servers the app kept. +- **R17.** The test user mapping is a detail seam (no public `factory::user_of`); `users()` and + `peers()` return a `std::pmr::map` with `std::less<>`, a transparent comparator. +- **R18.** `visibilitychange` is not followed in Phase 1 (design D13 names `online` and `offline` + only); a `relay_connectivity` value outside the enum is taken as `online`, where 0.27.0 throws. +- **R19** (supersedes R10). trystero calls no `webcpp::crypto::detail`: its own `detail::wipe` + (`detail/wipe.hpp`) wipes every variable-size secret buffer. +- **R20.** The doc reference's failure is a merge blocker owned by the hash stream; trystero + gives its reference BearSSL now, and the draft PRs' docs check is expected red until hash's fix. + +Each is a row of the differences page where it differs from 0.27.0. + +## What Phase 2 inherits + +Dependencies outside trystero: + +- webcpp::crypto's `curves::p256` (its increment 3), for 2.2 to 2.4. +- webcpp::crypto's secp256k1 `keypair::generate` (max_draws 4, `entropy_unavailable`), for the + R11 switch. +- A public wipe in webcpp::crypto (or hash) for variable-size buffers, which trystero then calls + in place of its own `detail::wipe` (R19). +- A guard in webcpp::crypto's `random_device` on Emscripten against a missing or throwing + `crypto.getRandomValues` (design Open Question 1): trystero 0.1.0's own guard went with + `entropy.hpp`. +- **Merge blocker, owned by the hash stream (R20):** the reference of trystero's page + (`b2 libs/trystero/doc`) does not build, so the CI's docs check of both draft PRs is red and + the spec's "One branch, merged once" cannot be met until it does. The reference is read for + Emscripten's target (`/webcpp//emscripten-reference`) with the native platform's dependencies; + under `__MRDOCS__` webcpp::hash's `config.hpp` defines `WEBCPP_HASH_HAS_OPENSSL` (and BLAKE3, + XKCP, sodium) unconditionally, so its own Emscripten `#error` fires and `` is + missing. The fix is the hash stream's: keep each `WEBCPP_HASH_HAS_` under `__MRDOCS__` + only when the build defines it, as webcpp::crypto does (or skip OpenSSL's on + `WEBCPP_TARGET_EMSCRIPTEN`). trystero's half is done: its reference gets BearSSL, Emscripten's + GCM default, rather than the native `gcm-default`'s OpenSSL, which webcpp::crypto refuses there + (`on` in `doc/Jamfile`, `rooms-gcm` in `build.jam`); with it the + crypto errors are gone, trystero's doc comments pass `doc_comments.py`, and the only failure + left is webcpp::hash's. Once the hash fix lands, the doc target is run again before the merge. + +- **Merge blocker, owned by the crypto stream (R21):** the lint's clang-tidy fails on + webcpp::crypto's `backends/secp256k1.hpp:66` (`bugprone-dynamic-static-initializers` on the + secp256k1 canary) in every trystero translation unit that includes it, natively on the Linux + lint and with Emscripten's flags on crypto's own `secp256k1_keys_test.cpp`. main's lint does not + meet it only because no other library includes that header in a unit the lint analyses so. The + fix is crypto's; trystero's own sources pass the whole lint. + +Carries inside trystero: + +- **2.1** confirms or amends design D9 before the shared connection, its presence frames, room + tokens, the 64-room bound (`too_many_rooms`) and the password handshake `__trystero_pw` are + removed; their rows move off the differences page. +- **2.4** gives `handshake_failed` its emitter and replaces the provisional private + `room_impl::handshake_proof` (0.26.0's `hashChallenge`) by the dual-signature handshake; + `wrong_password` and `handshake_timed_out` go with the shared handshake. +- **2.5** replaces the `user_resolver` seam (the memory backend's `assign_user`, + `test::group_users`) with the handshake's verified user ids, and adds `max_users`. +- Wide bulk sending, once the room envelope goes and frames may reach + `max_bulk_frame_bytes`: the wire receives wide transfers and offers every one narrow. +- Emitters for `peer_error`, `room_full`, `banned`, `identity_failed` and `plugin_failed` + (Phases 2 and 3); `relay_failed` has only its boot path (every relay's first connection failed), + not 0.27.0's "every initial announcement failed". +- The receive decision limits (128 across peers, 8 per peer) and 64 concurrent requests per peer, + once `on_receive` and `on_request` may answer asynchronously; a gate set after an offer arrived + should then be asked of it at its next drain, as 0.27.0 asks. +- `requestMany`, a send's and a request's progress and `signal`, and rejecting an unexpected + `@_response` offer "unexpected response" (the port drops it); no test sends one yet. +- 2.6 pins the oracle to 0.27.0, rewrites every twin (`diff_peers.mjs` reads `PeerInfo`), records + their outputs again, and retires `diff_relay_config` if 0.27.0's per-room configuration then + prints what the C++ program prints; `diff_rooms_per_app` goes with the shared connection. +- A test of a page whose `crypto.getRandomValues` is missing or throws (no JavaScript exception + enters WebAssembly) comes back with the guard in `random_device` above: the deleted + `platform_page_sealer` test covered it for 0.1.0's sealer, and nothing replaces it yet. +- Commit subjects of the review-fix commits (`5c7f578`, `ea6f2d1`, `b4b87e9`, `487c99e`) are + paragraphs; Phase 2's commits take a one-sentence subject and the list in the body (no history + rewrite). +- The clauses "not interoperable before Phase 2" in `room.hpp`'s doc comments, and the same + marking on the library's pages, come out in 2.6 once the interop lanes pass. +- 2.7 writes the docs whole (README, every page, chapter 15), the changelog's entry, and merges. + +## How to resume + +Phase 2 is written in full in `plan.md` (2026-11-22, Tasks 2.1a to 2.7, every carry above placed +there or marked for after the merge; Phase 2's vectors recorded with node v26.13.0). Before that: +Phase 2 was to be written in full, task by task, when webcpp::crypto's P-256 part merged; its first task +(2.1) confirms or amends design D9 before any code of the shared connection is removed. Each task +records its vectors in `vectors/record.mjs` first (P-256 signatures are random in WebCrypto: +vectors fix keys and check each side verifies the other's signatures). + +## Phase 2, as built (2026-11-23) + +Phase 2 (plan Tasks 2.1a to 2.7) is built on the branches, reviewed task by task and as a whole, +interoperable with Trystero 0.27.0 (the interop lane: 19 native and 17 browser scenarios against +0.27.0 JS, green), and merged nowhere: the owner holds the merge until webcpp::crypto's +sign-unified, uniform-types, formats, backend-concepts and DIT on Windows ARM64 changes are on +crypto's `main` (ruling P2-R33); the P-256 calls then migrate once, to the final crypto API. + +| Task | Library commits | What | +| --- | --- | --- | +| 2.1a | `11ed315..32a5ca2` | one connection per room and remote peer (D9 confirmed); the shared connection, presence frames, room tokens gone | +| 2.1b | `32a5ca2..ef73e00` | 0.27.0's handshake frame and timer, no password challenge; the Nostr signer on secp256k1 `keypair::generate` (R11) | +| 2.1c | `ef73e00..bd69bee` | wide bulk chunks, the size read through webcpp::webrtc's new `max_message_size()` (webrtc `8983e3b`, branch `trystero/max-message-size`) | +| 2.2 | `bd69bee..a01ebfc` | endpoint and user keys, ids derived from P-256 keys, user identity create, import, export | +| 2.3 | `a01ebfc..b77e7e7` | key records and the verification caches; tests on the virtual clock throughout | +| 2.4a | `b77e7e7..3f6c5b0` | the dual-signature handshake's messages and each side's run, against recorded JS sides | +| 2.4b | `3f6c5b0..c819ca3` | the handshake in the room; users are the ids it verified | +| 2.5a | `c819ca3..8ea1c8e` | `max_users` and `room_full` | +| 2.5b | `8ea1c8e..44da7af` | `peer_error`, `banned`, `relay_failed`'s announcement path, `@_ping` as a request | +| 2.6a | `44da7af..3fdda0b` | the oracle on 0.27.0, the recorder over the published packages, the twins; signals refused as `parseSignalEnvelope` refuses | +| 2.6b | `3fdda0b..09f45aa` | interop with 0.27.0 in Chrome and in a process, every lane on | +| 2.7 | `09f45aa..0d1387e` | the pages whole, the changelog lines, the final review's fixes, webcpp's lint and MSVC clean | + +Lanes at `0d1387e` (superproject `4040794`): native clang, gcc-15 and Emscripten, the oracle and +interop lanes, the Linux and macOS lint, MSVC 14.3 and 14.5 (one flaky webcpp::webrtc case on +14.3, `native.run`'s `a_full_exchange`, predating the branch). The reference (`b2 libs/trystero/doc`) +still stops on webcpp::crypto's `config.hpp:202` under MrDocs (crypto's fix); trystero's own doc +comments pass. + +What remains: the migration of `protocol/ecdsa.hpp`, `identity.hpp` and the signer to the final +crypto API (the call sites are listed in the ledger, ruling P2-R33), the interop rerun, the docs +target, the PRs out of draft and the merge. Phase 3 inherits the items in the final reports +(`p2-task-2.7-report.md`, "What Phase 3 inherits"). diff --git a/libraries/trystero/openspec/changes/trystero-0-27/reference/plan.md b/libraries/trystero/openspec/changes/trystero-0-27/reference/plan.md new file mode 100644 index 00000000..fd76a1c2 --- /dev/null +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/plan.md @@ -0,0 +1,1467 @@ +# webcpp::trystero to Trystero 0.27.0: Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development +> (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use +> checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Port webcpp::trystero from Trystero 0.26.0 to Trystero 0.27.0 (Nostr strategy), so that a +room joined from C++ and the same room joined from Trystero 0.27.0's JavaScript are one room. + +**Architecture:** Three phases on one long-lived branch, merged to `main` once, when the interop +lane is green against 0.27.0 JS peers (design D1). Phase 1 (this plan in full) builds everything +that needs no P-256: the 0.27.0 crypto layer over webcpp::hash and webcpp::crypto, the new topics, +ids, relays and Nostr details, the action wire v3, and the room's new public surface (listeners, +errors, users and peers, self, relay connectivity). Phase 2 (in full since 2026-11-22) gives +each room its own connections, adds identity and the dual-signature handshake on webcpp::crypto's +P-256, `max_users` and the remaining room errors, and turns interop on. Phase 3 (outlined) adds +the plugins: signed state, roles, then `scale()`. + +**Tech Stack:** C++20, header-only; webcpp::hash (SHA-256, HMAC-SHA-256, HKDF, PBKDF2, async +PBKDF2 over WebCrypto on Emscripten); webcpp::crypto (`aes256_gcm`, `random_device`, +`curves::secp256k1` BIP-340; in Phase 2 `curves::p256`); webcpp::asio, webcpp::webrtc, +webcpp::beast, webcpp::document; b2; Node for the vectors and the interop lane. + +**Spec:** `../proposal.md`, `../design.md` (decisions D1 to D23), `../specs/trystero/spec.md`. + +## Global Constraints + +- Upstream pin: Trystero 0.27.0, `dmotz/trystero` commit `8d3f57e` (merge of PR #212), its + `packages/core/src` and `packages/nostr/src`. Every wire value is proven against that code. +- Vectors: `test/fixtures/expected/trystero-0.27.0.json`, a copy of this change's + `reference/vectors/trystero-0.27.0.json` (named `phase1.json` until Phase 2 was written), + regenerated only by `test/oracle/record_0_27.mjs` (a copy of `reference/vectors/record.mjs`) + run against that pin with the fixture as its previous output, which keeps its recorded P-256 + signatures (design D19): `node test/oracle/record_0_27.mjs `, or + `--dist ` for the published packages. +- Header-only, namespace `webcpp::trystero`; every public symbol has its doc comment (chapter 7 of + `CODING-GUIDELINES.md`); English, never the em dash; no exception of trystero's own; every + operation that can fail returns `boost::system::result` or completes with an `error_code`. +- Every allocation of a room goes through its `std::pmr::memory_resource` (guarantee 6); what a + dependency allocates outside it is listed in the page's "What stays outside the resource". +- Secrets (room keys, PBKDF2 master, HMAC key, Nostr secret key) are held in + `webcpp::crypto::secret` or wiped with `webcpp::crypto::wipe` before release. +- Comparisons of MACs and tags are constant time (`webcpp::crypto::equal`). +- Branches: library `port/trystero-0.27` from trystero `main`; superproject + `trystero/port-0.27` from webcpp `main`. Nothing reaches either `main` before Phase 2's + interop is green (design D1). Commit subjects are sentences starting `trystero: `, no trailer. +- Run the CI's Linux lint locally in Docker before every push (the owner's rule); sizes and + speeds are measured on release builds only. +- Every test target builds natively and with `toolset=emscripten`, with and without exceptions + where the Jamfile already doubles a target. + +## Review Focus + +1. **Strict base64url.** A sealed text, a room auth token or a compact key with padding, a + non-canonical last character or a character outside `[A-Za-z0-9_-]` is refused, as + `fromBase64Url` + re-encode refuses it; tests `open_refuses_what_trystero_refuses` (Task 5) + and `room_auth_token_is_strict` (Task 4). +2. **Non-ASCII app ids, room ids and passwords.** `JSON.stringify` writes them raw in UTF-8 and + escapes only `"`, `\` and controls (and lone surrogates as `\udXXX`, which UTF-8 input cannot + hold); tests on `café` and the emoji vectors in Tasks 2, 4 and 5. +3. **PBKDF2 off the room's thread.** 600,000 iterations must never block a page or a room's + executor; test `password_room_keys_complete_after_the_join_returns` (Task 6). +4. **A wrong password.** A signal sealed under another key is reported once per peer and stage per + 60 s as `decrypt_failed`, and the room goes on; test `decrypt_failed_is_reported_once_a_minute` + (Task 10). +5. **Listener lifetime.** A listener that unsubscribes itself, or another, while it runs, and a + `once` listener, each run exactly as many times as Trystero's emitter runs them; test + `listeners_unsubscribe_while_dispatching` (Task 9). + +--- + +## File Structure (Phase 1) + +| File (library `libs/trystero`) | Responsibility | Task | +| --- | --- | --- | +| `build.jam` | `parts` links `/webcpp/hash//hash`, `/webcpp/crypto//crypto`, `/webcpp/crypto//gcm-default`, `/webcpp/crypto//secp256k1-default`; drops `/third_party//secp256k1` | 1 | +| `test/Jamfile`, `test/crypto_layer_test.cpp`, `test/fixtures/expected/trystero-0.27.0.json`, `test/oracle/record_0_27.mjs` | the vectors and the test that reads them | 1 | +| `include/webcpp/trystero/protocol/text.hpp` | add strict base64url | 2 | +| `include/webcpp/trystero/protocol/topics.hpp` | rewritten: domain tags, `topic_path`, `hash_topic`, root and peer topics, `hash32`, `str_to_num` | 2 | +| `include/webcpp/trystero/protocol/relays.hpp` | 0.27.0's relay list and seeded shuffle | 3 | +| `include/webcpp/trystero/protocol/ids.hpp` (new) | base62 ids, `encode_base62`, UUID v4, compact public keys, peer and user id derivation | 3 | +| `include/webcpp/trystero/protocol/room_keys.hpp` (new) | room AES key without password, PBKDF2 salt, HKDF room keys, room auth | 4 | +| `include/webcpp/trystero/protocol/seal.hpp` (new) | AES-256-GCM seal and open, base64url(iv \|\| ct \|\| tag), the signal AAD | 5 | +| `include/webcpp/trystero/protocol/signal.hpp` | loses `seal_key`, `format_sealed`, `parse_sealed`, `seal_iv_size`; bounds recomputed | 5 | +| `include/webcpp/trystero/backend.hpp` | `sealer` and `make_sealer` removed; `derive_password_master` added | 6 | +| `include/webcpp/trystero/detail/room_keys_cache.hpp` (new) | the app's bounded cache of derived room keys (64, LRU) | 6 | +| `include/webcpp/trystero/platform/backend.hpp` | `random` from `crypto::random_device`; `derive_password_master` natively on a worker, on Emscripten through WebCrypto | 6 | +| `include/webcpp/trystero/platform/sealer.hpp`, `platform/entropy.hpp` | deleted | 6 | +| `include/webcpp/trystero/protocol/nostr.hpp` | `topic_kind` (FNV-1a), signer over webcpp::crypto, REQ with `since` and deduplicated kinds, 250 topics per subscription | 7 | +| `include/webcpp/trystero/detail/nostr_strategy.hpp` | per-room signer, relay health (healthy, cooldown, probation, retired), EOSE replay, announcement nonce | 7 | +| `include/webcpp/trystero/protocol/action_wire.hpp`, `detail/action_wire.hpp` | action wire version 3 (wide bulk frames) | 8 | +| `include/webcpp/trystero/subscription.hpp` (new) | `subscription`, `listen_options`, `detail::listeners` | 9 | +| `include/webcpp/trystero/room_error.hpp` (new), `error.hpp` | 0.27.0's room error codes and `room_error` | 10 | +| `include/webcpp/trystero/detail/user_table.hpp` (new) | users and their peers, join and leave by user | 11 | +| `include/webcpp/trystero/room.hpp`, `app.hpp`, `options.hpp` | the new surface: `on_*`, `self()`, `users()`, `peers()`, `set_relay_connectivity`, removed options | 9 to 12 | +| `test/support/memory_backend.hpp` | `derive_password_master` (synchronous, posted), deterministic `random` | 6 | +| `doc/*.adoc`, `README.md`, `AGENTS.md` | Phase 1's part of the pages (Task 13) | 13 | + +Phase 1 builds on a provisional identity: a room's peer id is 20 base62 characters drawn at +random and its user id equals its peer id, until Phase 2 derives both from keys. The branch does +not interoperate with JS 0.27.0 before Phase 2 (design D1), so the interop lane stays on the +library's `main` and is off on the branch until Task 2.6. + +--- + +## Phase 1 + +### Task 1: Dependencies, the vectors and their test + +**Files:** +- Modify: `build.jam` (the `parts` alias), `test/Jamfile` +- Create: `test/fixtures/expected/trystero-0.27.0.json` (copy of `reference/vectors/phase1.json`, now + `trystero-0.27.0.json`), + `test/oracle/record_0_27.mjs` (copy of `reference/vectors/record.mjs`), + `test/crypto_layer_test.cpp` + +**Interfaces:** +- Produces: the program `crypto_layer`, run as `webcpp.run crypto_layer : crypto_layer_test.cpp : + fixtures/expected/trystero-0.27.0.json ;`, with a helper + `fixture_value section(std::string_view name)` that later tasks' test cases read. + +- [ ] **Step 1:** Create the branches: in the superproject `git switch -c trystero/port-0.27 + origin/main`; in `libs/trystero` `git switch -c port/trystero-0.27 origin/main`. +- [ ] **Step 2:** Write `crypto_layer_test.cpp` with one case, `fixture_is_trystero_0_27_0`: + `BOOST_TEST_EQ(root["trystero"].as_string(), "0.27.0")`. Load the fixture as + `protocol_test.cpp`'s `load` does (webcpp::document). +- [ ] **Step 3:** Add the Jamfile line above; run `b2 libs/trystero/test//crypto_layer`; + expected: PASS. +- [ ] **Step 4:** In `build.jam`'s `parts`, replace `/third_party//secp256k1` by + `/webcpp/hash//hash /webcpp/crypto//crypto + /webcpp/crypto//gcm-default /webcpp/crypto//secp256k1-default`; keep the + `webcpp-secp256k1-tables` comment, now about crypto's secp256k1 backend. Run + `b2 libs/trystero/test//crypto_layer` and `b2 toolset=emscripten + libs/trystero/test//crypto_layer`; expected: PASS on both (the protocol headers still include + libsecp256k1's headers, which crypto's alias brings). +- [ ] **Step 5:** Commit: `trystero: the port to Trystero 0.27.0 starts from its vectors, recorded + from its own code, and links webcpp::hash and webcpp::crypto`. + +### Task 2: Strict base64url and the 0.27.0 topics + +**Files:** +- Modify: `include/webcpp/trystero/protocol/text.hpp`, `include/webcpp/trystero/protocol/topics.hpp` +- Test: `test/crypto_layer_test.cpp`; `test/protocol_test.cpp` loses its 0.26 topic cases + +**Interfaces:** +- Produces, in `webcpp::trystero::protocol`: + - `void append_base64url(std::pmr::string& out, std::span in);` + - `std::pmr::string to_base64url(std::span in, std::pmr::memory_resource* memory = std::pmr::get_default_resource());` + - `std::optional from_base64url(std::string_view text, std::pmr::memory_resource* memory = std::pmr::get_default_resource());` + strict: nonempty, only `[A-Za-z0-9_-]`, no padding, length mod 4 not 1, and re-encoding the + bytes gives `text` (the unused low bits of the last character are zero). + - `inline constexpr std::string_view lib_name = "Trystero";`, `lib_id = "trystero";` + - `std::pmr::string domain_tag(std::string_view name, unsigned version, memory)`: + `"trystero::v"`. + - `void append_json_string(std::pmr::string& out, std::string_view utf8)`: `JSON.stringify`'s + string form (escapes `"`, `\`, `\b \f \n \r \t`, other controls as `\u00XX` lowercase; all + else raw). If `protocol/json.hpp` already has it, reuse that one. + - `std::pmr::string topic_path(std::initializer_list parts, memory)`: + `JSON.stringify(parts)`, `["a","b"]`. + - `std::pmr::string hash_topic(std::string_view text, memory)`: base64url of SHA-256 of the + UTF-8 bytes, through `webcpp::hash::digest_of`; 43 chars. + - `std::pmr::string root_topic_text(std::string_view app_id, std::string_view room_id, memory)` + = `topic_path({lib_name, app_id, room_id})`; + `root_topic(app_id, room_id, memory)` = `hash_topic(root_topic_text(...))`; + `peer_topic(app_id, room_id, peer_id, memory)` = `hash_topic(topic_path({root_topic_text(...), peer_id}))`. + - `std::uint32_t hash32(std::string_view utf8)`: FNV-1a 32 over the UTF-8 bytes, then + MurmurHash3's fmix32 (`h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; + h ^= h >> 16`), as `primitives.ts`. + - `std::uint64_t str_to_num(std::string_view utf8, std::uint64_t limit = 9007199254740991)` + = `hash32(utf8) % limit`. The 0.26 `double str_to_num`, `sha1_topic*`, the 0.26 + `root_topic`/`peer_topic` and `id_alphabet` are removed; `room_token` stays until Task 2.1 + decides it (design D9). +- [ ] **Step 1:** Write the failing cases in `crypto_layer_test.cpp`, each looping over its + fixture section: `base64url_matches` (`base64url`: `to_base64url(hex(bytes)) == text` and + `from_base64url(text) == bytes`), `base64url_is_strict` (`from_base64url` refuses `""`, `"A"`, + `"AB=="`, `"AB+/"`, `"AR"` (non-zero unused bits) and `"A B"`), `topic_path_matches` + (`topic_path`), `hash_topic_matches` (`hash_topic`), `room_topics_match` (`room_topics`: + `root_topic_text == root_text`, `root_topic == root_topic`, `peer_topic == peer_topic`), + `hash32_matches` (`hash32`), `str_to_num_matches` (`str_to_num`, limit 10000), and + `domain_tags_match` (`domain_tags`). +- [ ] **Step 2:** Run `b2 libs/trystero/test//crypto_layer`; expected: compile errors. +- [ ] **Step 3:** Implement the interfaces above. +- [ ] **Step 4:** Run `b2 libs/trystero/test//crypto_layer libs/trystero/test//protocol`; + expected: PASS (remove the 0.26 topic and `strToNum` cases from `protocol_test.cpp` and their + entries in the 0.26 fixture's reader in the same step). +- [ ] **Step 5:** Commit: `trystero: topics are 0.27.0's, the base64url SHA-256 of a JSON path, + and base64url is read strictly`. + +### Task 3: Relays and ids + +**Files:** +- Modify: `include/webcpp/trystero/protocol/relays.hpp`, `include/webcpp/trystero/detail/random_id.hpp` +- Create: `include/webcpp/trystero/protocol/ids.hpp` +- Test: `test/crypto_layer_test.cpp` + +**Interfaces:** +- Consumes: `hash32`, `str_to_num`, `to_base64url`, `from_base64url`, `domain_tag` (Task 2). +- Produces: + - `relays.hpp`: `default_nostr_relays` becomes the 30 URLs of `packages/nostr/src/index.ts` + (`wss://bucket.coracle.social` to `wss://yabu.me`, in that order); + `template void seeded_shuffle(std::span xs, std::uint32_t seed)`: + ```text + state = (trunc(seed) || 1) >>> 0 + rand(): state = (state + 0x6d2b79f5) mod 2^32 + t = imul(state ^ (state >>> 15), 1 | state) + t = (t + imul(t ^ (t >>> 7), 61 | t)) ^ t + return ((t ^ (t >>> 14)) >>> 0) / 2^32 + i = n; while (i) { j = floor(rand() * i); i -= 1; swap(xs[i], xs[j]) } + ``` + (`j` is computed with the `i` before the decrement, as `floor(rand() * i--)`); + `derive_relays(app_id, redundancy, memory)` shuffles with `str_to_num(app_id)` (an unsigned + 32-bit value, so the seed is exact) and takes the first `redundancy`. + - `ids.hpp`: `base62_alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"`; + `peer_id_size = 20`, `user_id_size = 22`, `offer_id_size = 12`, `nonce_size = 8`, + `subscription_id_size = 64`, `uuid_text_size = 36`; + `constexpr std::size_t gen_id_draw_size(std::size_t n)` = `ceil(n * 1.15) + 4` computed in + integers as `(n * 115 + 99) / 100 + 4`; + `template std::pmr::string gen_id(std::size_t n, Draw&& draw, memory)`: `draw` + is `void(std::span)` called with `gen_id_draw_size(n)` bytes each round; a byte + `b < 248` appends `base62_alphabet[b % 62]`, a byte `>= 248` is skipped; rounds repeat until + `n` characters; + `std::pmr::string encode_base62(std::span big_endian, std::size_t length, memory)`: + the low `length` base-62 digits of the number, most significant first (long division by 62, + `length` times, over a copy); + `std::array uuid_v4(std::array random)`: RFC 9562 version 4 + (`random[6] = (random[6] & 0x0f) | 0x40`, `random[8] = (random[8] & 0x3f) | 0x80`), lowercase + `8-4-4-4-12`, as `crypto.randomUUID()`; + `std::pmr::string compact_public_key(std::span uncompressed, memory)`: + `to_base64url(x) + "." + to_base64url(y)`, 87 characters; + `std::optional> parse_compact_public_key(std::string_view)`: + 87 characters, `.` at 43, both halves strict base64url of 32 bytes (no curve check here: + Phase 2's `p256::public_key::make` checks the point); + `std::pmr::string derive_peer_id(std::string_view compact, memory)` = + `encode_base62(sha256(domain_tag("pid", 1) + ":" + compact), 20)`; + `derive_user_id(...)` the same with `"uid"` and 22. + - `detail/random_id.hpp`: `random_id(factory, n, memory)` calls `protocol::gen_id` with + `factory.random`; `max_random_id_size` stays 64. +- [ ] **Step 1:** Failing cases: `shuffle_matches` (`shuffle`: indices 0 to 29 shuffled with + `seed` equal `order`; `str_to_num(app) == seed`), `gen_id_matches` (`gen_id`: a `draw` that + cycles `random_cycle`, as the recorder's `withRandom` does, gives `id` for each `n`), + `identity_ids_match` (`identity_ids`: `parse_compact_public_key` then `compact_public_key` + round-trips; `derive_peer_id == peer_id`, `derive_user_id == user_id`), + `uuid_v4_has_its_form` (16 bytes of `0xff` give `ffffffff-ffff-4fff-bfff-ffffffffffff`, 16 zero + bytes `00000000-0000-4000-8000-000000000000`), `compact_key_is_strict` (refuses 86 and 88 + characters, `.` elsewhere, a padded half). +- [ ] **Step 2:** Run `b2 libs/trystero/test//crypto_layer`; expected: compile errors. +- [ ] **Step 3:** Implement. +- [ ] **Step 4:** Run `b2 libs/trystero/test//crypto_layer libs/trystero/test//protocol + libs/trystero/test//room`; expected: PASS (the room's provisional self id is now base62). +- [ ] **Step 5:** Commit: `trystero: ids are unbiased base62, relays are 0.27.0's list in its + seeded order, and peer and user ids derive from a compact key`. + +### Task 4: Room keys and room authentication + +**Files:** +- Create: `include/webcpp/trystero/protocol/room_keys.hpp` +- Test: `test/crypto_layer_test.cpp` + +**Interfaces:** +- Consumes: `domain_tag`, `append_json_string`, `to_base64url`, `from_base64url` (Task 2). +- Produces, in `webcpp::trystero::protocol`: + - `inline constexpr std::uint64_t pbkdf2_iterations = 600'000;` + - `webcpp::crypto::secret<32> room_aes_key_without_password(std::string_view app_id, std::string_view room_id);` + = SHA-256 of `JSON.stringify(["trystero:room-aes:v3", app_id, room_id])`. + - `std::array pbkdf2_salt(std::string_view app_id, std::string_view room_id);` + = SHA-256 of `JSON.stringify(["trystero:pbkdf2-master:v3", app_id, room_id])`. + - `struct room_keys { webcpp::crypto::secret<32> aes; webcpp::crypto::secret<32> hmac; };` + - `boost::system::result derive_room_keys(std::span master);` + two `webcpp::hash::hkdf` calls, salt 32 zero bytes, IKM the + master, info `"trystero:room-aes:v3"` and `"trystero:room-hmac:v3"`, 32 bytes each (WebCrypto's + `deriveKey` of a 256-bit AES or HMAC key is HKDF's first 32 bytes). + - `std::pmr::string room_auth_payload(app_id, room_id, peer_id, std::uint64_t seq, memory)` + = `JSON.stringify(["trystero:ov-auth:v3", app_id, room_id, peer_id, seq])`; `seq` at most + 2^53 - 1, written as a decimal integer. + - `std::pmr::string sign_room_auth(const webcpp::crypto::secret<32>& hmac_key, app_id, room_id, peer_id, seq, memory)`: + base64url of HMAC-SHA-256 over the payload (43 characters). + - `bool verify_room_auth(const webcpp::crypto::secret<32>& hmac_key, app_id, room_id, peer_id, seq, std::string_view token)`: + false unless `from_base64url(token)` holds 32 bytes, then `webcpp::crypto::equal` with the + recomputed MAC. +- [ ] **Step 1:** Failing cases: `room_key_without_password_matches` (`room_key_no_password`), + `room_keys_from_master_match` (`room_keys_password`: `pbkdf2_salt == salt`; + `derive_room_keys(master)` gives `aes_key` and `hmac_key`), `pbkdf2_master_matches` (one + vector only, `webcpp::hash::pbkdf2` of the password's UTF-8 with `salt` and + 600,000 iterations gives `master`; the case is in the release variant's run, as it takes about + 0.2 s natively), `room_auth_matches` (`room_auth`: `room_auth_payload == payload`, + `sign_room_auth == token`, `verify_room_auth` true and false for `seq + 1`), + `room_auth_token_is_strict` (the token with `=` appended, with its last character changed to + another that decodes to the same bytes, and 42 characters, are refused). +- [ ] **Step 2:** Run; expected: compile errors. +- [ ] **Step 3:** Implement. +- [ ] **Step 4:** Run `b2 libs/trystero/test//crypto_layer` and the emscripten build of it; + expected: PASS. +- [ ] **Step 5:** Commit: `trystero: a room's keys are 0.27.0's, SHA-256 without a password and + PBKDF2 then HKDF with one, and its auth tokens are HMACs read strictly`. + +### Task 5: Sealing and opening signals + +**Files:** +- Create: `include/webcpp/trystero/protocol/seal.hpp` +- Modify: `include/webcpp/trystero/protocol/signal.hpp` +- Test: `test/crypto_layer_test.cpp`, `test/protocol_test.cpp` + +**Interfaces:** +- Consumes: Task 2's base64url; Task 4's keys. +- Produces, in `webcpp::trystero::protocol`: + - `inline constexpr std::size_t gcm_iv_size = 12, gcm_tag_size = 16;` + - `constexpr std::size_t sealed_size(std::size_t plaintext)` = base64url length of + `12 + plaintext + 16` (`(4 * k + 2) / 3` for `k` bytes). + - `boost::system::result seal(const webcpp::crypto::secret<32>& key, std::span iv, std::string_view plaintext, std::optional aad, memory);` + `webcpp::crypto::aes256_gcm::make(key)`, `seal(iv, aad bytes or empty, data)`, then + base64url(iv || ciphertext || tag). An absent AAD and an empty AAD are the same to GCM; + the parameter keeps Trystero's distinction readable. + - `boost::system::result open(const webcpp::crypto::secret<32>& key, std::string_view sealed, std::optional aad, memory);` + refuses (`error::decrypt_failed`, Task 10's code; until then a local placeholder) what + `from_base64url` refuses, fewer than 28 bytes, a failed tag, and a plaintext that is not + UTF-8 (design D12). + - `std::pmr::string signal_aad(std::string_view type, std::string_view peer_id, std::string_view offer_id, memory)` + = `type + "|" + peer_id + "|" + offer_id`. + - `signal.hpp`: `seal_key`, `seal_iv_size`, `format_sealed`, `parse_sealed`, `sealed_parts` + and `handshake_proof` are removed; `max_sealed_description_bytes` and + `max_sealed_candidate_bytes` keep their values, now in base64url characters; the reading of + a signal is unchanged in this task (its 0.27.0 fields are Task 2.4's). +- [ ] **Step 1:** Failing cases: `seal_matches` (`seal`: for each entry the key is + `room_key_no_password` or the password vector's `aes_key`, `seal(key, iv, plaintext, aad) + == sealed` and `open(...) == plaintext`), `password_probe_opens` (each `room_keys_password` + entry's `probe_sealed` opens to `"probe"` with AAD `"offer|p|o"`), + `open_refuses_what_trystero_refuses` (`open_refused`: every text refused), + `open_refuses_another_aad` (a `seal` entry opened with the other AAD fails), + `signal_aad_matches` (`signal_aad`). +- [ ] **Step 2:** Run; expected: compile errors. +- [ ] **Step 3:** Implement; delete the 0.26 sealing cases of `protocol_test.cpp`. +- [ ] **Step 4:** Run `b2 libs/trystero/test//crypto_layer libs/trystero/test//protocol` on both + targets; expected: PASS. The room does not build until Task 6 replaces the sealer: build only + these two programs. +- [ ] **Step 5:** Commit: `trystero: signals are sealed as 0.27.0 seals them, AES-256-GCM with a + 12-byte IV and the signal's AAD, in base64url`. + +### Task 6: The room's keys in the room, the backend without a sealer + +**Files:** +- Modify: `include/webcpp/trystero/backend.hpp`, `include/webcpp/trystero/platform/backend.hpp`, + `include/webcpp/trystero/detail/signaling.hpp`, `include/webcpp/trystero/room.hpp`, + `include/webcpp/trystero/detail/app_impl.hpp`, `test/support/memory_backend.hpp`, `test/Jamfile` +- Create: `include/webcpp/trystero/detail/room_keys_cache.hpp` +- Delete: `include/webcpp/trystero/platform/sealer.hpp`, `platform/entropy.hpp`, + `test/platform_sealer_test.cpp`, `test/platform_page_sealer_test.cpp`, + `test/platform_page_sealer_allocation_test.cpp` +- Test: `test/room_test.cpp`, `test/platform_backend_test.cpp` + +**Interfaces:** +- Consumes: Tasks 4 and 5. +- Produces: + - `backend::factory`: `make_sealer` and `class sealer` removed; added + `virtual void derive_password_master(std::span password, std::span salt, std::span out, handler done) = 0;` + with the contract of every factory completion: `done` runs on the room's executor after the + call returns; `password` and `salt` are the caller's until `done`; on error `out` is zeroed. + - `platform::backend`: `random` fills from `webcpp::crypto::random_device::fill` (a failure + is fatal as today's is); natively `derive_password_master` runs + `webcpp::hash::async_pbkdf2` on a one-thread + `webcpp::asio::thread_pool` the backend owns (created on first use, joined by its + destructor), and on Emscripten + `async_pbkdf2` on the loop's executor + (design D5). + - `detail::room_keys_cache` (in the app's resource): `void get(std::string_view room_id, handler)` + without a password returns `room_aes_key_without_password` synchronously (posted); with + one, derives once per room id, queues waiters while it runs, keeps at most 64 rooms (least + recently used out), and forgets a failed derivation, as `derivedRoomKeysCache` does. The + PBKDF2 master is wiped after HKDF. + - The signaling seals and opens with Task 5's functions under the room's AES key; it waits for + the key before its first announcement (0.27.0's room waits for `genKey`). + - `memory_backend`: `derive_password_master` computes synchronously with + `webcpp::hash::pbkdf2` and posts `done`; a test can set `derive_delay` to hold it. +- [ ] **Step 1:** Failing cases in `room_test.cpp`: + `password_room_keys_complete_after_the_join_returns` (a room of an app with a password, over a + memory backend whose `derive_delay` holds the derivation: no announcement leaves before the + derivation completes, `join` returned first, and two peers with that password meet); + `rooms_of_one_password_derive_once_per_room` (two rooms of one app derive twice, a third join + of the first room's id after its leave derives none); `a_failed_derivation_is_retried` (the + memory backend fails the first derivation: the room reports `error::backend_failure` through + its error handler, announces nothing, and a rejoin derives again; 0.27.0 has no room error + code for it, design D6). +- [ ] **Step 2:** Run `b2 libs/trystero/test//room`; expected: compile errors. +- [ ] **Step 3:** Implement; delete the files listed and their Jamfile targets; the + `headers-alone` list loses `platform/sealer.hpp` and `platform/entropy.hpp`. +- [ ] **Step 4:** Run `b2 libs/trystero/test libs/trystero/example` and `b2 toolset=emscripten + libs/trystero/test libs/trystero/example`; expected: every test passes but the interop and + oracle lanes, which the branch turns off until Task 2.6 (`test/oracle/Jamfile`: an + `explicit` on their targets, with a comment naming Task 2.6). +- [ ] **Step 5:** Commit: `trystero: a room's keys come from webcpp::hash, PBKDF2 off the room's + thread, and the backend keeps no sealer and no randomness of its own`. + +### Task 7: Nostr as 0.27.0 speaks it + +**Files:** +- Modify: `include/webcpp/trystero/protocol/nostr.hpp`, `include/webcpp/trystero/detail/nostr_strategy.hpp` +- Test: `test/crypto_layer_test.cpp`, `test/signaling_test.cpp`, `test/room_test.cpp` + +**Interfaces:** +- Consumes: Task 3's `gen_id`; webcpp::crypto's `curves::secp256k1::keypair` (`make`, + `generate`, `xonly_public_key`, `sign_schnorr`) and `verify_schnorr`. +- Produces: + - `std::uint32_t topic_kind(std::string_view topic)`: FNV-1a 32 over the topic's UTF-16 code + units (`h = 0x811c9dc5; h = (h ^ unit) * 0x01000193`), then `h % 10000 + 20000` (no fmix, + unlike `hash32`). + - `class signer`: over `webcpp::crypto::curves::secp256k1::keypair`; `signer::generate()` + returns `boost::system::result`; `pubkey_hex()`, `sign(event_id)`. The libsecp256k1 + includes leave trystero. + - `subscribe_message(sub_id, topics, since, memory)`: `["REQ", sub_id, {"kinds": [...], + "since": since, "#x": [...]}]`, kinds deduplicated in first-seen order; `since` = + `max(0, unix_now - 60)`; at most `max_topics_per_subscription = 250` topics per REQ, extra + REQs for the rest, surplus subscriptions closed. + - The announcement's content is `{"peerId":"","nonce":""}` (Trystero adds the + nonce at publish time on every announcement). + - The strategy: one signer per room (keyed by root topic and self topic, made on first + publish, dropped with the room's last subscription), relay health `healthy`, `cooldown` + (`60 s` doubling to `15 min`), `probation`, `retired`; `OK true` ends probation; a CLOSED + or rejected OK whose reason starts with `blocked:`, `restricted:`, `auth-required:` or + `pow:` retires the relay; `rate-limited:` cools it down; a CLOSED of a subscription id not + ours is ignored; an `EOSE` closing the last pending subscription 1 s or more after the REQ + replays the announcements; `duplicate:` rejections are not logged. +- [ ] **Step 1:** Failing cases: `topic_kind_matches` (`topic_to_kind`, and + `room_topics[*].root_kind`), in `signaling_test.cpp` + `subscriptions_hold_250_topics_and_distinct_kinds`, `announcements_carry_a_fresh_nonce`, + `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`; in + `room_test.cpp` `each_room_signs_with_its_own_key`. +- [ ] **Step 2:** Run `b2 libs/trystero/test//crypto_layer libs/trystero/test//signaling + libs/trystero/test//room`; expected: failures. +- [ ] **Step 3:** Implement. +- [ ] **Step 4:** Run the whole `libs/trystero/test` on both targets; expected: PASS (the lanes + off). Run the allocation tests and record in `doc/allocation.adoc`'s "What stays outside the + resource" what webcpp::crypto's secp256k1 context allocates, if anything (design D7). +- [ ] **Step 5:** Commit: `trystero: Nostr is 0.27.0's, a signer per room over webcpp::crypto, + kinds by FNV-1a, subscriptions since a minute ago, and relays retired, cooled and probed`. + +### Task 8: The action wire, version 3 + +**Files:** +- Modify: `test/oracle/record_0_27.mjs` (and this change's `reference/vectors/record.mjs`), + `test/fixtures/expected/trystero-0.27.0.json`, + `include/webcpp/trystero/protocol/action_wire.hpp`, `include/webcpp/trystero/detail/action_wire.hpp` +- Test: `test/crypto_layer_test.cpp`, `test/room_test.cpp` + +**Interfaces:** +- Produces: frames byte-identical to 0.27.0's `action-wire.ts`: version byte 3; kinds inline 0, + offer 1, chunk 2, accepted 3, rejected 4, cancelled 5 in the low four bits of byte 1, the + format (text 0, JSON 1, binary 2) above them as today, and the flag `wide_bulk_flag = 64` on + a chunk of a transfer whose chunks may be up to `max_bulk_frame_bytes = 65536` bytes; header + sizes 36, 48, 6 and 14 unchanged; 0.27.0's limits (`maxPendingTransfers` 1024, per peer 64, + decisions 128, per peer 8, pre-listener messages 32, control buffer 1 MiB, receive budget + 256 MiB). +- [ ] **Step 1:** Extend the recorder: import `packages/core/src/action-wire.ts`, make two + managers whose `resolveTransport` returns a transport that records `sendFrame(bytes, + transferId, isOffer)` and delivers to the other manager's `handleData`; record, as hex, the + frames of: a text, a JSON value and a 10-byte binary message; a message with metadata + `{"a":1}`; a 200 KiB binary message (offer, chunks, accepted); a transfer the receiver's + `onReceive` declines (rejected); a request and its response (`kind: 'request'`); a cancelled + send (abort signal). Add the section `action_frames` to the fixture. +- [ ] **Step 2:** Failing case `action_frames_match`: the port's encoder writes each recorded + frame from the same inputs, and its decoder reads each back to the same message. +- [ ] **Step 3:** Run; expected: FAIL (version 2). +- [ ] **Step 4:** Implement the deltas the vectors show. +- [ ] **Step 5:** Run `b2 libs/trystero/test` on both targets; expected: PASS. +- [ ] **Step 6:** Commit: `trystero: the action wire is version 3, with wide bulk frames, proven + against 0.27.0's frames`. + +### Task 9: Listeners that return a subscription + +**Files:** +- Create: `include/webcpp/trystero/subscription.hpp` +- Modify: `include/webcpp/trystero/room.hpp`, `include/webcpp/trystero/app.hpp`, + `include/webcpp/trystero.hpp`, `example/*.cpp`, `example/chat/chat.cpp` +- Test: `test/subscription_test.cpp` (new, `webcpp.run subscription`), `test/room_test.cpp` + +**Interfaces:** +- Produces: + - `struct listen_options { bool once = false; bool replay = false; };` + - `class subscription` (move-only): `void unsubscribe() noexcept;` `[[nodiscard]] bool + active() const noexcept;` destruction leaves the listener in place, as dropping the function + Trystero returns does (design D10). + - `template class detail::listeners`: `subscription add(handler, + listen_options)`, `void emit(Args...)`; listeners run in the order added; a listener added + while emitting does not run for that emission; one removed while emitting does not run if + not yet run; `once` removes before it runs. + - Room: `subscription on_peer_join(handler, listen_options = {})`, + `on_peer_leave`, `on_user_join(handler, ...)`, `on_user_leave`; + `struct peer_event { std::string_view peer_id; std::string_view user_id; };` + `struct user_event { std::string_view user_id; std::string_view peer_id; };` `replay` + emits the current peers or users at once, inside the call. + - Actions: `subscription on_message(handler<...>, listen_options = {})` (several); + `boost::system::result on_request(...)` and `on_receive(...)` (one at a time; + a second while one is active is `error::already_subscribed`); `on_receive_progress(...)`. + The setters of 0.1.0 (`on_peer_join(f)` returning `void`) are removed. +- [ ] **Step 1:** Failing cases in `subscription_test.cpp`: `listeners_run_in_order`, + `listeners_unsubscribe_while_dispatching` (a listener that removes itself and the next one; + the next does not run), `once_runs_once`, `added_while_dispatching_waits`, + `dropping_a_subscription_keeps_the_listener`; in `room_test.cpp` + `replay_reports_current_peers`, `second_on_request_is_refused`. +- [ ] **Step 2 to 4:** Run (fail), implement, run `b2 libs/trystero/test libs/trystero/example` + on both targets (PASS). +- [ ] **Step 5:** Commit: `trystero: listeners are added with on_ and return a subscription, as + 0.27.0's are`. + +### Task 10: Room errors + +**Files:** +- Create: `include/webcpp/trystero/room_error.hpp` +- Modify: `include/webcpp/trystero/error.hpp`, `room.hpp`, `app.hpp`, `detail/signaling.hpp`, + `detail/nostr_strategy.hpp` +- Test: `test/room_test.cpp`, `test/config_test.cpp` + +**Interfaces:** +- Produces: + - `error` gains, after `too_many_rooms`: `room_full`, `banned`, `relay_failed`, + `identity_failed`, `plugin_failed`, `decrypt_failed`, `peer_connect_failed`, `peer_error`, + `already_subscribed`, `not_connected`, `action_aborted`, `request_rejected`, + `request_timed_out`; `handshake_failed` is no longer reserved. Values are appended, so + existing values keep their numbers. Each message is 0.27.0's (`"room full"`, + `"peer banned"`, `"failed to decrypt offer (incorrect password or corrupted signal)"` and so + on, read from `utils.ts` and `signal-handler.ts`). + - `std::string_view room_error_code_name(boost::system::error_code)`: `"room-full"`, + `"banned"`, `"relay-failed"`, `"identity-failed"`, `"plugin-failed"`, `"decrypt-failed"`, + `"peer-connect-failed"`, `"handshake-failed"`, `"peer-error"`, else `""`. + - `struct room_error { boost::system::error_code code; std::string_view message; std::string_view app_id; std::string_view room_id; std::string_view peer_id; std::optional stage; bool turn_configured = false; std::string_view reason; std::string_view plugin; };` + with `enum class signal_stage { offer, answer };` + - `subscription room::on_error(handler, listen_options = {})`; + `app::on_error` likewise (configuration reports). + - `decrypt_failed` is reported at most once per (peer, stage) per 60 s; + `peer_connect_failed` carries `turn_configured` (any ICE URL `turn:` or `turns:`); + `relay_failed` is reported once when every relay of the room has failed. +- [ ] **Step 1:** Failing cases: `decrypt_failed_is_reported_once_a_minute` (two apps with + different passwords, virtual clock), `relay_failed_when_every_relay_fails`, + `peer_connect_failed_says_whether_turn_was_configured`, `error_names_match_trystero`. +- [ ] **Step 2 to 4:** Run (fail), implement, run the whole test directory on both targets. +- [ ] **Step 5:** Commit: `trystero: a room reports 0.27.0's error codes through on_error, each + with its context`. + +### Task 11: Users and peers + +**Files:** +- Create: `include/webcpp/trystero/detail/user_table.hpp` +- Modify: `include/webcpp/trystero/room.hpp`, `include/webcpp/trystero/app.hpp` +- Test: `test/user_table_test.cpp` (new, `webcpp.run user_table`), `test/room_test.cpp` + +**Interfaces:** +- Produces: + - `detail::user_table` (in the room's resource): `bool add(std::string_view peer_id, std::string_view user_id)` + (true when the user is new), `std::optional remove(std::string_view peer_id)` + (the user when its last peer left), `std::span peers_of(user_id)`, + `std::optional user_of(peer_id)`. + - `struct user_info { std::pmr::vector peer_ids; std::pmr::vector roles; };` + `struct peer_info { std::pmr::string user_id; bool direct = true; std::uint32_t hops = 1; std::pmr::vector roles; };` + `room::users()` -> `std::pmr::map`, `room::peers()` -> + `std::pmr::map` (no `connection`: design D11). + - `struct self_info { std::string_view peer_id; std::string_view user_id; identity_persistence persistence; std::string_view room_id; std::string_view base_room_id; bool is_admin = false; std::span roles; };` + `room::self()`, synchronous (design D11); `enum class identity_persistence { ephemeral, imported };` + Phase 1 fills `user_id = peer_id`, `ephemeral`. + - `on_user_join` fires when a user's first peer joins, after `on_peer_join`; `on_user_leave` + when its last peer leaves, after `on_peer_leave`. + - `action.send(data, target)`: `target` is a user id (all its peers), a peer id, or a list; + a target not connected completes with `error::not_connected`; a broadcast with no peer + completes with success. +- [ ] **Step 1:** Failing cases: `user_table_test.cpp` `first_peer_joins_the_user`, + `last_peer_leaves_the_user`, `a_peer_moves_nowhere` (adding a known peer under another user is + refused); `room_test.cpp` `send_to_a_user_reaches_each_of_its_peers` (the memory backend's + test hook `assign_user(peer, user)` maps two peers to one user), + `send_to_an_absent_target_fails`, `self_names_the_room`. +- [ ] **Step 2 to 4:** Run (fail), implement, run the whole test directory on both targets. +- [ ] **Step 5:** Commit: `trystero: a room knows its users and their peers, and sends to either`. + +### Task 12: Options, joins and relay connectivity + +**Files:** +- Modify: `include/webcpp/trystero/options.hpp`, `app.hpp`, `room.hpp`, + `detail/nostr_strategy.hpp`, `detail/app_impl.hpp`, `example/diff_*.cpp` and their twins +- Test: `test/app_impl_test.cpp`, `test/room_test.cpp` + +**Interfaces:** +- Produces: + - `room_options`: `handshake_timeout` removed (0.27.0 removed `handshakeTimeoutMs`); + `max_receive_bytes` stays; `app_config::self_id` removed (0.27.0 removed a custom + `peerId`; Phase 1 draws it, Phase 2 derives it); `app_config::identity` reserved for + Phase 2 (absent in Phase 1). + - `enum class relay_connectivity { online, offline, automatic };` + `relay_connectivity app::set_relay_connectivity(relay_connectivity)` and + `relay_connectivity app::relay_connectivity() const`: `offline` closes the relays' sockets + and holds them, `online` reconnects, `automatic` is `online` natively and on Emscripten + follows the page's `online` and `offline` events (design D13). + - A join of a room id already active in the app keeps returning `error::already_joined` (0.27.0 + now throws there too: the difference `diff_already_joined` is removed with its twin). +- [ ] **Step 1:** Failing cases: `offline_holds_and_online_reconnects`, + `automatic_is_online_natively`, `no_custom_self_id`. +- [ ] **Step 2 to 4:** Run (fail), implement, run tests and examples on both targets. +- [ ] **Step 5:** Commit: `trystero: relays go offline and online on request, and the options + 0.27.0 removed are gone`. + +### Task 13: Phase 1's pages and its gate + +**Files:** +- Modify: `README.md`, `doc/differences.adoc`, `doc/design.adoc`, `doc/protocol.adoc`, + `doc/allocation.adoc`, `doc/usage.adoc`, `doc/guarantees.adoc`, `AGENTS.md`; superproject + `CODING-GUIDELINES.md` chapter 15's trystero section (on the superproject branch) + +- [ ] **Step 1:** Write what Phase 1 changed, marked "on the branch `port/trystero-0.27`, not + interoperable before Phase 2": the protocol page's topics, keys, sealing, ids and relays; the + design page's D5, D6 and D7 (the backend without a sealer, the key derivation, the + dependencies); the differences that Phase 1 adds or removes (design D14's table); the + allocation page's list; chapter 15's lines that name the sealer, OpenSSL's AES-GCM and + `RAND_bytes`, libsecp256k1 as a direct dependency, and the 2026-11-17 decision (superseded, + design D2). README's dependency table moves to webcpp::hash and webcpp::crypto. +- [ ] **Step 2:** Run `b2 libs/trystero/test libs/trystero/example libs/trystero/doc` and + `b2 toolset=emscripten libs/trystero/test libs/trystero/example`; the lint in Docker + (`local-linux-lint`); expected: all green but the two lanes turned off. +- [ ] **Step 3:** Push both branches (not `main`); open draft pull requests titled + `trystero: port to Trystero 0.27.0 (draft, merges after its interop)`; the CI must be green + except the lanes marked off. +- [ ] **Step 4:** Commit: `trystero: the pages say what Phase 1 of the port to 0.27.0 changed`. + +--- + +## Phase 2 + +Written in full on 2026-11-22, once webcpp::crypto's P-256 (``, +BearSSL on every target, the alias `/webcpp/crypto//p256-default`) and its secp256k1 +`keypair::generate` reached `main` and the branch. Its rulings are the notes P2-R1 to P2-R24 +(`.superpowers/sdd/plan2/plan-writer-notes.md` of the superproject's worktree) and design D17 to +D23. Every task runs on the library branch `port/trystero-0.27`, and the superproject branch +`trystero/port-0.27` for chapter 15 and the pointer. + +**How to run (every task).** `lanes.sh [targets]` and `heavy.sh` are the +port's helpers, named with their full paths in the implementers' context file +(`.superpowers/sdd/plan2/context.md` of the port's superproject worktree); targets are relative to +the superproject, for instance `libs/trystero/test//room`; with none, `lanes.sh` runs +`libs/trystero/test libs/trystero/example`. A full lane, a lint, MSVC or an interop lane goes +through `heavy.sh trystero-027 `, its output in the port's `logs/` directory. "Run both" below means the focused targets on +clang and on emscripten; "Run all" means the whole `libs/trystero/test` and +`libs/trystero/example` on clang and emscripten through `heavy.sh`. Ruling R1 of Phase 1 holds: +a task that removes or renames something moves every caller in the same task, and the whole +library builds after every task. + +**The vectors.** `reference/vectors/trystero-0.27.0.json` (this change; Phase 1's `phase1.json` +renamed, its sections unchanged but `domain_tags`, which gained `id-hs` and +`identity-self-test`) holds Phase 2's sections too: `signatures`, `p256_keys`, `compact_keys`, +`user_identity`, `user_identity_imports`, `user_proof`, `low_s`, `handshake`, +`handshake_frames`, `ping_frames`, `identity_limits`. Task 2.2's implementer copies it over +`test/fixtures/expected/trystero-0.27.0.json` and `reference/vectors/record.mjs` over +`test/oracle/record_0_27.mjs`; nothing else writes either file. Keys are fixed (a key's scalar is +SHA-256 of `webcpp-trystero-vector: