From 889d0629c8a9112867feaf3e1fb0ce5a8a571ed3 Mon Sep 17 00:00:00 2001 From: R Date: Fri, 20 Nov 2026 22:50:20 -0300 Subject: [PATCH 1/9] trystero: the change trystero-0-27, the port to Trystero 0.27.0 on one branch merged once, with Phase 1 planned in full over webcpp::hash and webcpp::crypto and its vectors recorded from 0.27.0's own code --- README.md | 1 + .../changes/trystero-0-27/.openspec.yaml | 11 + .../openspec/changes/trystero-0-27/design.md | 201 ++++ .../changes/trystero-0-27/proposal.md | 67 ++ .../changes/trystero-0-27/reference/STATUS.md | 29 + .../changes/trystero-0-27/reference/plan.md | 663 +++++++++++ .../reference/vectors/phase1.json | 1058 +++++++++++++++++ .../reference/vectors/record.mjs | 198 +++ .../trystero-0-27/specs/trystero/spec.md | 217 ++++ .../openspec/changes/trystero-0-27/tasks.md | 46 + 10 files changed, 2491 insertions(+) create mode 100644 libraries/trystero/openspec/changes/trystero-0-27/.openspec.yaml create mode 100644 libraries/trystero/openspec/changes/trystero-0-27/design.md create mode 100644 libraries/trystero/openspec/changes/trystero-0-27/proposal.md create mode 100644 libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md create mode 100644 libraries/trystero/openspec/changes/trystero-0-27/reference/plan.md create mode 100644 libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/phase1.json create mode 100644 libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/record.mjs create mode 100644 libraries/trystero/openspec/changes/trystero-0-27/specs/trystero/spec.md create mode 100644 libraries/trystero/openspec/changes/trystero-0-27/tasks.md diff --git a/README.md b/README.md index ad9b5c94..18144534 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,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..c7fdda5e --- /dev/null +++ b/libraries/trystero/openspec/changes/trystero-0-27/design.md @@ -0,0 +1,201 @@ +## 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 (default; confirmed by Task 2.1) + +0.27.0 removed 0.26.0's `shared-peer.ts`: each room negotiates its own peer connection, and the +handshake binds app and room. The default ruling is that the port follows: the app keeps one +identity, its relays and its key cache, and each room its own connections; the archived +`shared-connection` change's sharing of connections across rooms, its presence frames and +`room_token` are retired. Phase 2's first task reads 0.27.0's peer and transport code and records +a room's data-channel frames; if 0.27.0 shares after all, this decision is amended before any +code is removed. + +### 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 seven tasks, some 5,000 to 7,000; Phase 3 three changes, some 10,000 to 14,000. + +## 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 is confirmed by reading 0.27.0 first. + +## 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)? Default: check in + Task 6 and keep a guard of trystero's if it does not. +2. Is the action wire's request/response protocol carried in metadata or in frames of its own? + Task 8's recorded frames answer it. 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..9132694b --- /dev/null +++ b/libraries/trystero/openspec/changes/trystero-0-27/proposal.md @@ -0,0 +1,67 @@ +## 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:** none yet; `reference/plan.md` is the plan (Phase 1 in full, Phases 2 and 3 + outlined), `reference/vectors/` the recorder and the vectors it recorded from 0.27.0's code. + 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 unless Phase 2's Task 2.1 finds 0.27.0 shares connections. 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..69808699 --- /dev/null +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md @@ -0,0 +1,29 @@ +# webcpp::trystero, port to Trystero 0.27.0: where it stands, and how to resume + +Written 2026-11-20. Nothing is implemented. `plan.md` is the plan (Phase 1 in full, Phases 2 +and 3 outlined); `vectors/record.mjs` is the recorder and `vectors/phase1.json` what it recorded. + +## Where it stands + +| What | Where | +| --- | --- | +| The plan | `plan.md` | +| The vectors | `vectors/phase1.json`, recorded 2026-11-20 with node v26.13.0 from Trystero 0.27.0 at `8d3f57e` | +| The code | none; branches `port/trystero-0.27` (library) and `trystero/port-0.27` (superproject) are created by Task 1 | +| Blocking Phase 2 | webcpp::crypto's foundation increment 3, P-256 (its plan's Tasks 3.1 to 3.3) | + +## How the vectors were recorded + + node reference/vectors/record.mjs > reference/vectors/phase1.json + +The recorder imports 0.27.0's TypeScript sources directly (node strips the types), resolves +extensionless relative imports to `.ts`, maps `@trystero-p2p/core` to `primitives.ts` and stubs +`@noble/secp256k1` for `nostr/src/protocol.ts`, whose `topicToKind` it calls. It replaces +`crypto.getRandomValues` only inside the calls whose output it pins (GCM's IV, `genId`'s bytes). +It runs in about half a second. Task 8 extends it with the action wire's frames. + +## How to resume + +Start at `plan.md` Task 1. Phase 2 is written in full, task by task, when webcpp::crypto's P-256 +part merges; its first task (2.1) confirms or amends design D9 before any code of the shared +connection is removed. 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..39a2bf2b --- /dev/null +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/plan.md @@ -0,0 +1,663 @@ +# 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 (outlined) adds identity and the +dual-signature handshake on webcpp::crypto's P-256 (its foundation increment 3). 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 D16), `../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/phase1.json`, regenerated only by `test/oracle/record_0_27.mjs` (a copy of + `reference/vectors/record.mjs`) run against that pin: `node test/oracle/record_0_27.mjs `. +- 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`), + `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 (outlined; written in full when crypto's increment 3 P-256 part merges) + +Depends on webcpp::crypto `curves::p256` (``): +`keypair::generate()`, `keypair::make(scalar)`, `keypair::secret_scalar()`, +`keypair::public_key().uncompressed()`, `public_key::make(65 bytes)`, `keypair::sign_ecdsa(digest)`, +`verify_ecdsa(signature, digest, key)`, `normalize_ecdsa`, `check_low_s` (crypto's plan, +Tasks 3.1 and 3.2). Each task records its vectors in the recorder first; P-256 signatures are +random in WebCrypto, so vectors fix keys and check that each side verifies the other's +signatures, never signature bytes. + +- **2.1 The connection model.** Read 0.27.0's `peer.ts`, `peer-transport.ts`, `room.ts` and + `strategy.ts` and record the frames of one room's data channel. 0.27.0 has no connection shared + across rooms (0.26.0's `shared-peer.ts` is gone); the default ruling (design D9) is one + connection per room and remote peer, the app-level sharing of the change `shared-connection`, + its presence frames and `room_token` retired. The task confirms or amends D9 before 2.2. +- **2.2 Endpoint and user keys.** `detail/identity.hpp`: an endpoint key pair per app (`peerId` + from its compact key, Task 3's `derive_peer_id`), a user key pair (`userId`), the + `user-proof` binding (`domainTag('user-proof', 3)`), `identity` option: `ephemeral` (default), + `imported(user_identity)`; `create_user_identity()`, `export_user_identity()` (0.27.0's + `trystero_uk_` text, vectors from `exportUserIdentity`) and `import_user_identity()`; no + implicit persistence (design D15). Needs P-256 `generate`, `make`, `secret_scalar`. +- **2.3 Signed key records and their cache.** `getVerifiedPubKeyRecord`, `verifyWithP256` with + low S required (`check_low_s` before `verify_ecdsa`), signing with `normalize_ecdsa`; the + bounded signature cache (8,192 entries, 2 MiB). +- **2.4 The dual-signature handshake.** `handshake.ts`: init and response with UUID nonces + (Task 3), both endpoint and user signatures over a payload that binds app, room and both + SDP DTLS fingerprints; `handshake_failed` on any mismatch; the signal's 0.27.0 fields. +- **2.5 Users for real.** The user table fed by verified user ids; `max_users` (`room_full`, + refresh-safe per user id); multi-endpoint users (several apps of one user identity in one or + several processes are "tabs"). +- **2.6 Interop.** The oracle lane pinned to 0.27.0 (the npm packages `trystero@0.27.0` and + `@trystero-p2p/core@0.27.0`), the twins rewritten, the interop scenarios against Chrome on + both lanes, turned back on; vectors regenerated and byte-identical. +- **2.7 The merge.** Docs whole (README, every page, chapter 15), the changelog's entry, one + merge of `port/trystero-0.27` into trystero `main`, the superproject's pointer, both CIs green + (design D1). + +## Phase 3 (outlined; after Phase 2 merges, each a change of its own on `main`) + +- **3.1 Signed records and shared state.** `signed-record.ts`, `state.ts`, `anti-entropy.ts`: + `make_state` and `make_user_state` (JSON values through webcpp::document), late joiners, + `validate`. Needs P-256 sign and verify only. +- **3.2 Roles and moderation.** `authority.ts`: `roles(...)` with `self_as_admin` (the + `~` room id), `admins`, role certificates (`RoleCertificate` v1), `grant_role`, + `revoke_role`, `ban`, `unban`, role-gated actions and state. +- **3.3 scale().** `scale/*`: topology, routing, descriptors with `verifyRoomAuth`, + `crypto-frame.ts`'s pairwise keys (`derivePairwiseAesKey`: P-256 `ecdh_x`, HKDF with the + `e2e-salt` and `e2e-info` v2 tags), multi-hop data plane. Needs crypto Task 3.3 (`ecdh_x`). diff --git a/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/phase1.json b/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/phase1.json new file mode 100644 index 00000000..3dd220fa --- /dev/null +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/phase1.json @@ -0,0 +1,1058 @@ +{ + "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" + } + ], + "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" + } + ] +} diff --git a/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/record.mjs b/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/record.mjs new file mode 100644 index 00000000..72153053 --- /dev/null +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/record.mjs @@ -0,0 +1,198 @@ +// Records webcpp::trystero's Phase 1 test vectors from Trystero 0.27.0's own code, run in Node +// (>= 23.6, which strips TypeScript's types). Usage: +// node record.mjs > phase1.json +// It imports packages/core/src/{primitives,crypto,utils}.ts and packages/nostr/src/protocol.ts +// unchanged; extensionless relative imports are resolved to .ts by the hook below. Randomness is +// pinned only around the calls whose output it decides (the GCM IV, genId's bytes), by replacing +// crypto.getRandomValues for that call and restoring it after. +import {registerHooks} from 'node:module' +import {pathToFileURL} from 'node:url' +import path from 'node:path' +import fs from 'node:fs' + +const rootUrl = pathToFileURL(path.resolve(process.argv[2] ?? '.') + '/') + +registerHooks({ + resolve(specifier, context, next) { + // nostr/src/protocol.ts imports two packages: Trystero's core, whose encodeBytes and toJson + // are primitives.ts's, and the Schnorr signer, which topicToKind does not use. + if (specifier === '@trystero-p2p/core') { + return next(new URL('packages/core/src/primitives.ts', rootUrl).href, context) + } + if (specifier === '@noble/secp256k1') { + return {url: 'data:text/javascript,export const schnorr = {}', shortCircuit: true} + } + if (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(process.argv[2] ?? '.') +const src = p => pathToFileURL(path.join(root, p)).href +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, 'packages/core/package.json'), 'utf8')) +const hex = b => Buffer.from(b).toString('hex') +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. +out.domain_tags = ['room-aes', 'room-hmac', 'pbkdf2-master', 'ov-auth', 'e2e-salt', 'e2e-info', + 'pid', 'uid', 'user-proof'].map(n => ({name: n, version: n.startsWith('e2e') ? 2 : n === 'pid' || n === 'uid' ? 1 : 3, + tag: prim.domainTag(n, n.startsWith('e2e') ? 2 : n === 'pid' || n === 'uid' ? 1 : 3)})) + +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, prim.peerIdLength), user_id: enc(ud, prim.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 + +process.stdout.write(JSON.stringify(out, null, 1) + '\n') diff --git a/libraries/trystero/openspec/changes/trystero-0-27/specs/trystero/spec.md b/libraries/trystero/openspec/changes/trystero-0-27/specs/trystero/spec.md new file mode 100644 index 00000000..5b578ab1 --- /dev/null +++ b/libraries/trystero/openspec/changes/trystero-0-27/specs/trystero/spec.md @@ -0,0 +1,217 @@ +## ADDED Requirements + +### Requirement: Port: Trystero pinned at 0.27.0 and proven by its own code +The library SHALL port Trystero 0.27.0 (`dmotz/trystero` commit `8d3f57e`), Nostr strategy only. Every value a peer exchanges MUST equal what 0.27.0's own code computes for the same inputs, as recorded in `test/fixtures/expected/trystero-0.27.0.json` by `test/oracle/record_0_27.mjs`, which imports 0.27.0's `packages/core/src` and `packages/nostr/src` unchanged and pins randomness only around the calls whose output it decides. + +#### Scenario: The fixture names its version +- **WHEN** the `crypto_layer` test reads the fixture +- **THEN** its `trystero` member is `0.27.0` + +#### Scenario: The recorder reproduces the fixture +- **WHEN** `node test/oracle/record_0_27.mjs` runs against a checkout of the pinned commit +- **THEN** its output equals the fixture byte for byte + +### Requirement: Port: One branch, merged once +The port SHALL be developed on the library branch `port/trystero-0.27` and the superproject branch `trystero/port-0.27`, and MUST NOT reach either `main` before the interop lane against Trystero 0.27.0 JS peers and every CI check of both repositories are green on the branch. While the branch cannot interoperate, its oracle and interop lanes MUST be turned off by `explicit` targets that name the task that turns them back on. + +#### Scenario: Phase 1 on the branch +- **WHEN** Phase 1 is complete +- **THEN** both branches are pushed with draft pull requests, and neither `main` holds any of it + +### Requirement: Protocol: Strict base64url +`protocol::to_base64url` SHALL write RFC 4648's URL alphabet without padding, and `protocol::from_base64url` MUST accept a text only when it is nonempty, holds only `[A-Za-z0-9_-]`, has no padding, and re-encoding its bytes gives the same text, as Trystero's `fromBase64Url` followed by its re-encoding check accepts it. + +#### Scenario: Canonical and non-canonical texts +- **WHEN** `from_base64url` reads `AQID`, `AR`, `AB==` and `A B` +- **THEN** the first gives `01 02 03` and the other three are refused + +### Requirement: Protocol: Topics of 0.27.0 +`protocol::topic_path(parts)` SHALL write the parts as `JSON.stringify` writes an array of strings, `protocol::hash_topic(text)` MUST be the base64url SHA-256 of the text's UTF-8 bytes, a room's root topic MUST be `hash_topic(topic_path({"Trystero", app_id, room_id}))` and a peer's topic `hash_topic(topic_path({, peer_id}))`. + +#### Scenario: The lobby of example.com/app +- **WHEN** the root topic of app `example.com/app` and room `lobby` is computed +- **THEN** its path is `["Trystero","example.com/app","lobby"]` and the topic is `Ez_9ACs-onxWTTRRn7pFD2rqRce5y0HrAay9k2X7Ip0`, and the peer topic for `T5sdTwb84yyey80e4qjv` is `j0YMUkrR_ecDTTcdbXvJV9GW8StO2JaSN1Do2CyT75w` + +### Requirement: Protocol: hash32, strToNum and topic kinds +`protocol::hash32` SHALL be FNV-1a 32 over UTF-8 bytes followed by MurmurHash3's fmix32, `protocol::str_to_num(text, limit)` MUST be `hash32(text) % limit`, and `protocol::topic_kind(topic)` MUST be FNV-1a 32 over the topic's UTF-16 code units, modulo 10000, plus 20000, without fmix. + +#### Scenario: lobby +- **WHEN** `hash32("lobby")` and `topic_kind("lobby")` are computed +- **THEN** they are 1937637236 and 24083 + +### Requirement: Protocol: Relays of 0.27.0 in their seeded order +`protocol::default_nostr_relays` SHALL hold 0.27.0's 30 default relays in its order, and `derive_relays` MUST shuffle them with 0.27.0's seeded shuffle (the 32-bit generator `state += 0x6d2b79f5` and its two mixing steps, a Fisher-Yates from the end) seeded with `str_to_num(app_id)`, and take the first `relay_redundancy`. + +#### Scenario: example.com/app +- **WHEN** the indexes 0 to 29 are shuffled with `str_to_num("example.com/app")` = 3213600185 +- **THEN** the order begins `24, 4, 9, 29, 12` and equals the fixture's whole order + +### Requirement: Protocol: Base62 ids, UUIDs and derived ids +`protocol::gen_id(n, draw)` SHALL draw `ceil(n * 1.15) + 4` bytes a round and append `base62_alphabet[b % 62]` for each byte below 248, skipping the others, until `n` characters, with the alphabet `0-9A-Za-z`; peer ids are 20, user ids 22, offer ids 12, nonces 8 and subscription ids 64 characters. `uuid_v4` MUST format 16 random bytes as RFC 9562's version 4. `derive_peer_id(compact)` MUST be the low 20 base-62 digits of SHA-256 of `trystero:pid:v1:` and `derive_user_id` the low 22 of `trystero:uid:v1:`, where a compact key is `base64url(x).base64url(y)` of an uncompressed P-256 point. + +#### Scenario: Bytes 248 and above are skipped +- **WHEN** `gen_id(8, draw)` draws the cycle `00 01 3d 3e 7b f7 f8 f9 ff 0a ...` +- **THEN** the id is `01z0zzAE` + +#### Scenario: The ids of a compact key +- **WHEN** the fixture's compact key is derived +- **THEN** the peer id is `T5sdTwb84yyey80e4qjv` and the user id `2Ag9nxCt2tqpTCQ2x1bNyf` + +### Requirement: Protocol: Room keys and room authentication +Without a password a room's AES key SHALL be SHA-256 of `JSON.stringify(["trystero:room-aes:v3", app_id, room_id])`. With one, the master MUST be PBKDF2-HMAC-SHA-256 of the password's UTF-8 with salt SHA-256 of `JSON.stringify(["trystero:pbkdf2-master:v3", app_id, room_id])`, 600,000 iterations, 32 bytes, and the AES and HMAC keys HKDF-SHA-256 of the master with 32 zero bytes of salt and the infos `trystero:room-aes:v3` and `trystero:room-hmac:v3`. A room auth token MUST be the base64url HMAC-SHA-256 of `JSON.stringify(["trystero:ov-auth:v3", app_id, room_id, peer_id, seq])`, and verification MUST refuse a token that is not strict base64url of 32 bytes and compare MACs in constant time. + +#### Scenario: The keys of example.com/app's lobby +- **WHEN** the room key without password and the keys for password `hunter2` are derived +- **THEN** they are `b03810047a4001c5c48b2a81106f3649447465c05eca736b56c02f94facf207a` and, for the AES key with the password, `4ae994c98ce84eb65c425d575f6041fd4b2d746e9aeadf55e8f5dec459b63f05`, as the fixture holds + +#### Scenario: A token for another sequence number +- **WHEN** a token signed for `seq` is verified for `seq + 1` +- **THEN** it is refused + +### Requirement: Protocol: Sealing as 0.27.0 seals +`protocol::seal(key, iv, plaintext, aad)` SHALL be AES-256-GCM with a 12-byte IV and the AAD, written as base64url of `iv || ciphertext || tag`, and `protocol::open` MUST refuse a text that is not strict base64url, shorter than 28 bytes, whose tag fails, or whose plaintext is not UTF-8. A signal's AAD is `||`. Each seal draws its IV from the backend's randomness. + +#### Scenario: Every sealed vector +- **WHEN** each fixture entry is sealed with its key, IV and AAD, and opened again +- **THEN** the texts equal the fixture's and open to the plaintexts, and the fixture's refused texts are refused + +### Requirement: Backend: The key derivation seam +`backend::factory` SHALL have no `sealer` and no `make_sealer`, and MUST offer `derive_password_master(password, salt, out, done)`, completing on the room's executor after the call returns, with `out` zeroed on error. The platform backend MUST run it off the room's thread: natively `webcpp::hash::async_pbkdf2` on a one-thread pool it owns, on Emscripten through WebCrypto (`backends::webcrypto`). Its randomness MUST be `webcpp::crypto::random_device`. + +#### Scenario: A password room joins at once +- **WHEN** a room of an app with a password is joined over a memory backend that holds the derivation +- **THEN** `join` returns before the derivation completes, nothing is announced until it does, and two such peers then meet + +### Requirement: Room: Room keys are cached per app +An app SHALL derive a password room's keys once per room id and keep at most 64 rooms' keys, least recently used out, wipe the PBKDF2 master after HKDF, and forget a failed derivation so that a later join derives again; a failed derivation MUST be reported as `error::backend_failure`. + +#### Scenario: Rejoining a room +- **WHEN** a room is left and joined again within the app +- **THEN** no second derivation runs + +### Requirement: Signaling: Nostr as 0.27.0 speaks it +The Nostr strategy SHALL sign with one BIP-340 key per room (webcpp::crypto's `curves::secp256k1`), made on the room's first publish; subscribe with `since` = `max(0, now - 60)` and the deduplicated kinds of its topics, at most 250 topics per subscription; add a fresh 8-character nonce to every announcement (`{"peerId":...,"nonce":...}`); retire a relay on a rejection starting `blocked:`, `restricted:`, `auth-required:` or `pow:`; cool a relay down on `rate-limited:` for 60 s doubling up to 15 minutes, then probe it, an `OK true` ending the probation; ignore a CLOSED of a subscription not its own; and replay its announcements when the last pending EOSE arrives 1 s or more after its REQ. + +#### Scenario: A terminal rejection +- **WHEN** a relay answers an EVENT with `["OK", id, false, "blocked: no"]` +- **THEN** the relay is retired and closed, and the room goes on over its other relays + +### Requirement: Actions: The action wire version 3 +Action frames SHALL be byte-identical to 0.27.0's `action-wire.ts`: version byte 3, the kinds inline, offer, chunk, accepted, rejected and cancelled, the wide bulk flag 64 for chunks of up to 65,536 bytes, and its limits, as the fixture's recorded frames show. + +#### Scenario: Recorded frames +- **WHEN** the port encodes each message the recorder sent +- **THEN** it writes the recorded frames and decodes them back to the messages + +### Requirement: Room: Listeners return a subscription +`on_peer_join`, `on_peer_leave`, `on_user_join`, `on_user_leave`, `on_error` and an action's `on_message` and `on_receive_progress` SHALL add a listener and return a `subscription`; several listeners of one event MUST run in the order added; `listen_options::once` removes a listener before its first run and `replay` reports the current peers or users within the call; a listener added while an event is emitted MUST NOT run for it, and one removed before its turn MUST NOT run; destroying a `subscription` leaves its listener. `on_request` and `on_receive` MUST refuse a second listener while one is active with `error::already_subscribed`. + +#### Scenario: A listener removes the next +- **WHEN** the first of two join listeners unsubscribes the second while it runs +- **THEN** the second does not run for that join + +### Requirement: Room: 0.27.0's room errors +`room::on_error` SHALL report a `room_error` with a code of the `webcpp.trystero` category among `room_full`, `banned`, `relay_failed`, `identity_failed`, `plugin_failed`, `decrypt_failed`, `peer_connect_failed`, `handshake_failed` and `peer_error`, whose `room_error_code_name` is 0.27.0's (`room-full` and so on), with the app id, the room id, the peer id where 0.27.0 gives one, the stage of a `decrypt_failed`, and `turn_configured` for a `peer_connect_failed`. A `decrypt_failed` MUST be reported at most once per peer and stage per 60 s. + +#### Scenario: Another password +- **WHEN** two apps with different passwords join one room and their offers keep arriving +- **THEN** each reports `decrypt_failed` once a minute for the other, and neither joins + +### Requirement: Room: Users and peers +A room SHALL keep its users and their peers: `on_user_join` fires after the `on_peer_join` of a user's first peer, `on_user_leave` after the `on_peer_leave` of its last; `users()` and `peers()` list them (a peer with its user id, `direct`, `hops` and roles; no connection); `self()` gives the peer id, user id, persistence, room id and base room id; an action's send MUST take a user id (all its peers), a peer id or a list, and MUST complete with `error::not_connected` for a target not connected, while a broadcast to an empty room succeeds. + +#### Scenario: A user with two peers +- **WHEN** two peers of one user are in a room and one leaves +- **THEN** `on_peer_leave` fires and `on_user_leave` does not, until the second leaves too + +### Requirement: App: Relay connectivity +`app::set_relay_connectivity` SHALL take `online`, `offline` or `automatic`: `offline` closes the app's relay sockets and holds them closed, `online` reconnects them, and `automatic` follows the page's `online` and `offline` events on Emscripten and is `online` natively. + +#### Scenario: Offline and back +- **WHEN** an app goes offline, then online +- **THEN** its relays close and no reconnection is tried until it is online, when they reconnect and resubscribe + +### Requirement: App: Options 0.27.0 removed are gone +`app_config::self_id` and `room_options::handshake_timeout` SHALL NOT exist, and joining a room id already active in the app MUST fail with `error::already_joined`, as 0.27.0 throws. + +#### Scenario: A second join +- **WHEN** an app joins `lobby` twice without leaving +- **THEN** the second join fails with `already_joined` + +### Requirement: Identity: Endpoint and user keys (Phase 2) +Each app SHALL hold an endpoint key pair and a user key pair on ECDSA P-256 (webcpp::crypto's `curves::p256`), its peer id derived from the endpoint key's compact form and its user id from the user key's, the user key binding the endpoint key by a `trystero:user-proof:v3` signature; an identity is ephemeral by default, and `create_user_identity`, `export_user_identity` (0.27.0's text form) and `import_user_identity` let a program keep a user across apps and runs. Signatures MUST be normalized to low S before they are sent and refused when their S is high. + +#### Scenario: Two apps of one user +- **WHEN** two apps import one user identity and join one room with a third peer +- **THEN** the third peer sees two peers and one user + +### Requirement: Identity: The dual-signature handshake (Phase 2) +A room SHALL admit a peer only after 0.27.0's handshake: nonces, endpoint and user signatures over a payload binding the app, the room and both connection's DTLS fingerprints, each verified; any failure MUST be reported as `handshake_failed` and the connection closed. `max_users` MUST refuse a user beyond the limit with `room_full`, counting users, not peers. + +#### Scenario: A forged user signature +- **WHEN** a peer presents a user id whose signature does not verify +- **THEN** the room reports `handshake_failed` and the peer never joins + +### Requirement: Tests: Interop with Trystero 0.27.0 (Phase 2) +The oracle lane SHALL pin Trystero 0.27.0 and the interop lane MUST meet Trystero 0.27.0 JS peers in headless Chrome over a local relay, on both lanes, before the branch merges. + +#### Scenario: A C++ peer and a JS peer +- **WHEN** a native peer and a Chrome page running Trystero 0.27.0 join one room +- **THEN** each sees the other's user and peer ids and they exchange messages both ways + +### Requirement: Plugins: State, roles and scale (Phase 3) +After the port merges, separate changes SHALL add signed shared and per-user state (`make_state`, `make_user_state`), roles and moderation (`roles` with admins, role certificates, ban), and `scale()` with its pairwise ECDH keys, each against vectors and interop with 0.27.0. + +#### Scenario: Phase 3 waits for the merge +- **WHEN** the port has not merged +- **THEN** no plugin is on the branch + +## REMOVED Requirements + +### Requirement: Protocol: Id alphabet and lengths +**Reason**: 0.27.0 draws ids from `0-9A-Za-z` without bias and has user ids. +**Migration**: "Protocol: Base62 ids, UUIDs and derived ids". + +### Requirement: Protocol: Topic names +**Reason**: 0.27.0's topics are base64url SHA-256, not SHA-1 in base 36. +**Migration**: "Protocol: Topics of 0.27.0". + +### Requirement: Protocol: Root and peer topics +**Reason**: the topic texts are JSON paths in 0.27.0. +**Migration**: "Protocol: Topics of 0.27.0". + +### Requirement: Protocol: Seeded shuffle +**Reason**: 0.27.0 replaced the sine generator by a 32-bit integer generator. +**Migration**: "Protocol: Relays of 0.27.0 in their seeded order". + +### Requirement: Protocol: The seal key and the handshake proof +**Reason**: 0.27.0 derives room keys by SHA-256 of a domain-tagged path or PBKDF2 and HKDF, and its handshake is the dual-signature one. +**Migration**: "Protocol: Room keys and room authentication", "Identity: The dual-signature handshake (Phase 2)". + +### Requirement: Protocol: The text form of a sealed signal +**Reason**: 0.27.0 seals with a 12-byte IV and AAD and packs base64url(iv || ct || tag). +**Migration**: "Protocol: Sealing as 0.27.0 seals". + +### Requirement: Protocol: The BIP-340 signer +**Reason**: the signer is webcpp::crypto's, one per room. +**Migration**: "Signaling: Nostr as 0.27.0 speaks it". + +### Requirement: Backend: sealer +**Reason**: sealing is synchronous protocol code over webcpp::crypto. +**Migration**: "Backend: The key derivation seam". + +### Requirement: Native: The sealer is AES-256-GCM in Trystero's sealed text form +**Reason**: the backend has no sealer. +**Migration**: "Protocol: Sealing as 0.27.0 seals". + +### Requirement: Browser: The sealer is crypto.subtle's AES-GCM under a key imported once +**Reason**: the backend has no sealer; WebCrypto is used only for PBKDF2. +**Migration**: "Backend: The key derivation seam". + +### Requirement: Room: Self id +**Reason**: 0.27.0 removed custom peer ids; ids derive from keys. +**Migration**: "Room: Users and peers", "Identity: Endpoint and user keys (Phase 2)". + +### Requirement: Oracle: Trystero pinned at 0.26.0 +**Reason**: the port follows 0.27.0. +**Migration**: "Port: Trystero pinned at 0.27.0 and proven by its own code". diff --git a/libraries/trystero/openspec/changes/trystero-0-27/tasks.md b/libraries/trystero/openspec/changes/trystero-0-27/tasks.md new file mode 100644 index 00000000..204e1d5c --- /dev/null +++ b/libraries/trystero/openspec/changes/trystero-0-27/tasks.md @@ -0,0 +1,46 @@ +# Tasks + +`reference/plan.md` is the plan: Phase 1 in full (its Tasks 1 to 13), Phases 2 and 3 outlined. +Nothing is implemented yet. The library branch is `port/trystero-0.27`, the superproject's +`trystero/port-0.27`; neither merges before group 5 (design D1). + +## 1. Phase 1: the crypto layer (plan Tasks 1 to 6) + +- [ ] 1.1 Branches, webcpp::hash and webcpp::crypto linked, the vectors and the `crypto_layer` test (Task 1) +- [ ] 1.2 Strict base64url and 0.27.0's topics, `hash32`, `str_to_num` (Task 2) +- [ ] 1.3 Relays, base62 ids, UUID v4, compact keys and derived ids (Task 3) +- [ ] 1.4 Room keys and room authentication (Task 4) +- [ ] 1.5 Sealing and opening, the signal AAD (Task 5) +- [ ] 1.6 The key derivation seam, the key cache, the backend without a sealer (Task 6) + +## 2. Phase 1: the wire and the surface (plan Tasks 7 to 13) + +- [ ] 2.1 Nostr as 0.27.0 speaks it (Task 7) +- [ ] 2.2 The action wire version 3 (Task 8) +- [ ] 2.3 Listeners returning a subscription (Task 9) +- [ ] 2.4 Room errors (Task 10) +- [ ] 2.5 Users and peers, `self()`, targeted sends (Task 11) +- [ ] 2.6 Options, joins and relay connectivity (Task 12) +- [ ] 2.7 Phase 1's pages, its gate, the draft pull requests (Task 13) + +## 3. Phase 2: identity and the handshake (after webcpp::crypto's P-256 merges) + +- [ ] 3.1 The connection model confirmed or amended (design D9) (Task 2.1) +- [ ] 3.2 Endpoint and user keys, import and export (Task 2.2) +- [ ] 3.3 Signed key records, low S, the signature cache (Task 2.3) +- [ ] 3.4 The dual-signature handshake (Task 2.4) +- [ ] 3.5 Verified users, `max_users` (Task 2.5) + +## 4. Phase 2: interop + +- [ ] 4.1 The oracle and interop lanes on 0.27.0, the twins rewritten (Task 2.6) + +## 5. The merge + +- [ ] 5.1 The pages whole, the changelog, chapter 15, one merge of each branch, both CIs green (Task 2.7) + +## 6. Phase 3: plugins (separate changes after the merge) + +- [ ] 6.1 Signed records and shared state (Task 3.1) +- [ ] 6.2 Roles and moderation (Task 3.2) +- [ ] 6.3 `scale()` (Task 3.3, after webcpp::crypto's `ecdh_x`) From 49ecd70e473e1963d6a5cb599284358282eb3c62 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 06:44:11 -0300 Subject: [PATCH 2/9] trystero: the 0.27 change's vectors gain the action frames, recorded from 0.27.0's action wire --- .../reference/vectors/phase1.json | 358 ++++++++++++++++++ .../reference/vectors/record.mjs | 123 +++++- 2 files changed, 477 insertions(+), 4 deletions(-) diff --git a/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/phase1.json b/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/phase1.json index 3dd220fa..9eb6d876 100644 --- a/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/phase1.json +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/phase1.json @@ -1054,5 +1054,363 @@ "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" + } + } ] } diff --git a/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/record.mjs b/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/record.mjs index 72153053..f5406745 100644 --- a/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/record.mjs +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/record.mjs @@ -1,10 +1,11 @@ // Records webcpp::trystero's Phase 1 test vectors from Trystero 0.27.0's own code, run in Node // (>= 23.6, which strips TypeScript's types). Usage: // node record.mjs > phase1.json -// It imports packages/core/src/{primitives,crypto,utils}.ts and packages/nostr/src/protocol.ts -// unchanged; extensionless relative imports are resolved to .ts by the hook below. Randomness is -// pinned only around the calls whose output it decides (the GCM IV, genId's bytes), by replacing -// crypto.getRandomValues for that call and restoring it after. +// It imports packages/core/src/{primitives,crypto,utils,action-wire,actions}.ts and +// packages/nostr/src/protocol.ts unchanged; extensionless relative imports are resolved to .ts by +// the hook below. Randomness is pinned only around the calls whose output it decides (the GCM IV, +// genId's bytes, a request's id), by replacing crypto.getRandomValues or crypto.randomUUID for that +// call and restoring it after. import {registerHooks} from 'node:module' import {pathToFileURL} from 'node:url' import path from 'node:path' @@ -195,4 +196,118 @@ const sh = await import(src('packages/core/src/signal-handler.ts')).catch(() => 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'}}) +} + process.stdout.write(JSON.stringify(out, null, 1) + '\n') From 0bb83cd322d8f0fa1c3f6969f333a8ef5b0cc494 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 01:20:21 -0300 Subject: [PATCH 3/9] trystero: the 0.27 change's status says what Phase 1 built and what Phase 2 inherits --- .../changes/trystero-0-27/reference/STATUS.md | 118 +++++++++++++++--- 1 file changed, 101 insertions(+), 17 deletions(-) diff --git a/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md b/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md index 69808699..2cff3dee 100644 --- a/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md @@ -1,29 +1,113 @@ -# webcpp::trystero, port to Trystero 0.27.0: where it stands, and how to resume +# webcpp::trystero, port to Trystero 0.27.0: as built after Phase 1 -Written 2026-11-20. Nothing is implemented. `plan.md` is the plan (Phase 1 in full, Phases 2 -and 3 outlined); `vectors/record.mjs` is the recorder and `vectors/phase1.json` what it recorded. +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/phase1.json` what it recorded. ## Where it stands | What | Where | | --- | --- | -| The plan | `plan.md` | -| The vectors | `vectors/phase1.json`, recorded 2026-11-20 with node v26.13.0 from Trystero 0.27.0 at `8d3f57e` | -| The code | none; branches `port/trystero-0.27` (library) and `trystero/port-0.27` (superproject) are created by Task 1 | -| Blocking Phase 2 | webcpp::crypto's foundation increment 3, P-256 (its plan's Tasks 3.1 to 3.3) | +| 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/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` | -## How the vectors were recorded +## Phase 1, task by task (library commits) - node reference/vectors/record.mjs > reference/vectors/phase1.json +| 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 | -The recorder imports 0.27.0's TypeScript sources directly (node strips the types), resolves -extensionless relative imports to `.ts`, maps `@trystero-p2p/core` to `primitives.ts` and stubs -`@noble/secp256k1` for `nostr/src/protocol.ts`, whose `topicToKind` it calls. It replaces -`crypto.getRandomValues` only inside the calls whose output it pins (GCM's IV, `genId`'s bytes). -It runs in about half a second. Task 8 extends it with the action wire's frames. +## 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. + +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`. +- The reference of trystero's page (`b2 libs/trystero/doc`) does not build on the branch: it is + read for Emscripten's target with the native platform's dependencies, and webcpp::hash's MrDocs + configuration defines `WEBCPP_HASH_HAS_OPENSSL` (and its other backends) unconditionally, which + its own `#error` refuses on Emscripten, while webcpp::crypto refuses `WEBCPP_CRYPTO_HAS_OPENSSL` + there and needs BearSSL linked for its default AES-GCM. It needs webcpp::hash and + webcpp::crypto to accept a reference parse for Emscripten, then trystero's `doc/Jamfile` to give + the reference Emscripten's backends. The page itself, its doc-check and its rendered check pass + with a stub reference. + +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. +- 2.7 writes the docs whole (README, every page, chapter 15), the changelog's entry, and merges. ## How to resume -Start at `plan.md` Task 1. Phase 2 is written in full, task by task, when webcpp::crypto's P-256 -part merges; its first task (2.1) confirms or amends design D9 before any code of the shared -connection is removed. +Phase 2 is written in full, task by task, when webcpp::crypto's P-256 part merges; 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). From 224b77d5aebac8edef2f7513bd091333be16625b Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 03:42:36 -0300 Subject: [PATCH 4/9] trystero: the 0.27 change's status records the doc reference as the hash stream's merge blocker and the remaining parks --- .../changes/trystero-0-27/reference/STATUS.md | 29 ++++++++++++++----- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md b/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md index 2cff3dee..224f6abb 100644 --- a/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md @@ -56,6 +56,8 @@ the recorder and `vectors/phase1.json` what it recorded. 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. @@ -71,14 +73,19 @@ Dependencies outside trystero: - 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`. -- The reference of trystero's page (`b2 libs/trystero/doc`) does not build on the branch: it is - read for Emscripten's target with the native platform's dependencies, and webcpp::hash's MrDocs - configuration defines `WEBCPP_HASH_HAS_OPENSSL` (and its other backends) unconditionally, which - its own `#error` refuses on Emscripten, while webcpp::crypto refuses `WEBCPP_CRYPTO_HAS_OPENSSL` - there and needs BearSSL linked for its default AES-GCM. It needs webcpp::hash and - webcpp::crypto to accept a reference parse for Emscripten, then trystero's `doc/Jamfile` to give - the reference Emscripten's backends. The page itself, its doc-check and its rendered check pass - with a stub reference. +- **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. Carries inside trystero: @@ -103,6 +110,12 @@ Carries inside trystero: - 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). - 2.7 writes the docs whole (README, every page, chapter 15), the changelog's entry, and merges. ## How to resume From 62080d3b4956bfda49f0d66c6ce2f75ef715ebc7 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 03:48:12 -0300 Subject: [PATCH 5/9] trystero: the 0.27 change's status parks the removal of Phase 1's not-interoperable clauses for 2.6 --- .../trystero/openspec/changes/trystero-0-27/reference/STATUS.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md b/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md index 224f6abb..75955714 100644 --- a/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md @@ -116,6 +116,8 @@ Carries inside trystero: - 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 From a31178706f6722fd88a70f3690a4fd6ba6c7183a Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 05:17:19 -0300 Subject: [PATCH 6/9] trystero: the 0.27 change's vector recorder opens with the WebCpp.org licence notice, as the library's copy now does for webcpp's lint --- .../changes/trystero-0-27/reference/vectors/record.mjs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/record.mjs b/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/record.mjs index f5406745..cd519b33 100644 --- a/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/record.mjs +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/record.mjs @@ -1,3 +1,9 @@ +// 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 Phase 1 test vectors from Trystero 0.27.0's own code, run in Node // (>= 23.6, which strips TypeScript's types). Usage: // node record.mjs > phase1.json From eb1a607237f3f62f46ad523a5c91e4fdd9608588 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 07:04:45 -0300 Subject: [PATCH 7/9] trystero: the 0.27 change's status names the second merge blocker, the secp256k1 canary's clang-tidy finding, owned by the crypto stream --- .../openspec/changes/trystero-0-27/reference/STATUS.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md b/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md index 75955714..c47f16b0 100644 --- a/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md @@ -87,6 +87,13 @@ Dependencies outside trystero: 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 From f91a24acd3f48a4372eefd07d302ca251156c86e Mon Sep 17 00:00:00 2001 From: R Date: Sun, 22 Nov 2026 10:49:35 -0300 Subject: [PATCH 8/9] trystero: the plan writes Phase 2 of the port to 0.27.0 in full, with its vectors --- .../openspec/changes/trystero-0-27/design.md | 114 +- .../changes/trystero-0-27/proposal.md | 7 +- .../changes/trystero-0-27/reference/STATUS.md | 9 +- .../changes/trystero-0-27/reference/plan.md | 890 ++++++- .../reference/vectors/phase1.json | 1416 ----------- .../reference/vectors/record.mjs | 337 ++- .../reference/vectors/trystero-0.27.0.json | 2080 +++++++++++++++++ .../trystero-0-27/specs/trystero/spec.md | 224 +- .../openspec/changes/trystero-0-27/tasks.md | 25 +- 9 files changed, 3587 insertions(+), 1515 deletions(-) delete mode 100644 libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/phase1.json create mode 100644 libraries/trystero/openspec/changes/trystero-0-27/reference/vectors/trystero-0.27.0.json diff --git a/libraries/trystero/openspec/changes/trystero-0-27/design.md b/libraries/trystero/openspec/changes/trystero-0-27/design.md index c7fdda5e..190c847c 100644 --- a/libraries/trystero/openspec/changes/trystero-0-27/design.md +++ b/libraries/trystero/openspec/changes/trystero-0-27/design.md @@ -117,15 +117,22 @@ Before P-256, a room's peer id is 20 base62 characters drawn at random and its u 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 (default; confirmed by Task 2.1) - -0.27.0 removed 0.26.0's `shared-peer.ts`: each room negotiates its own peer connection, and the -handshake binds app and room. The default ruling is that the port follows: the app keeps one -identity, its relays and its key cache, and each room its own connections; the archived -`shared-connection` change's sharing of connections across rooms, its presence frames and -`room_token` are retired. Phase 2's first task reads 0.27.0's peer and transport code and records -a room's data-channel frames; if 0.27.0 shares after all, this decision is amended before any -code is removed. +### 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 @@ -174,7 +181,81 @@ Phase 1: everything without P-256 (this plan's Tasks 1 to 13). Phase 2: identity 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 seven tasks, some 5,000 to 7,000; Phase 3 three changes, some 10,000 to 14,000. +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 @@ -184,7 +265,9 @@ Phase 2 seven tasks, some 5,000 to 7,000; Phase 3 three changes, some 10,000 to 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 is confirmed by reading 0.27.0 first. +- [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 @@ -195,7 +278,10 @@ README and the pages carry a migration section modelled on Trystero's `MIGRATION ## 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)? Default: check in - Task 6 and keep a guard of trystero's if it does not. + 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? - Task 8's recorded frames answer it. + 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 index 9132694b..112e037c 100644 --- a/libraries/trystero/openspec/changes/trystero-0-27/proposal.md +++ b/libraries/trystero/openspec/changes/trystero-0-27/proposal.md @@ -54,8 +54,9 @@ None. ## Impact - **Kind:** port, of Trystero 0.27.0 (`port_of`), from 0.26.0. -- **Implementation:** none yet; `reference/plan.md` is the plan (Phase 1 in full, Phases 2 and 3 - outlined), `reference/vectors/` the recorder and the vectors it recorded from 0.27.0's code. +- **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 @@ -64,4 +65,4 @@ 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 unless Phase 2's Task 2.1 finds 0.27.0 shares connections. + 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 index c47f16b0..23dbdd81 100644 --- a/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/STATUS.md @@ -3,7 +3,8 @@ 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/phase1.json` what it recorded. +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 @@ -11,7 +12,7 @@ the recorder and `vectors/phase1.json` what it recorded. | --- | --- | | 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/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 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` | @@ -129,7 +130,9 @@ Carries inside trystero: ## How to resume -Phase 2 is written in full, task by task, when webcpp::crypto's P-256 part merges; its first task +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). diff --git a/libraries/trystero/openspec/changes/trystero-0-27/reference/plan.md b/libraries/trystero/openspec/changes/trystero-0-27/reference/plan.md index 39a2bf2b..fd76a1c2 100644 --- a/libraries/trystero/openspec/changes/trystero-0-27/reference/plan.md +++ b/libraries/trystero/openspec/changes/trystero-0-27/reference/plan.md @@ -11,24 +11,28 @@ room joined from C++ and the same room joined from Trystero 0.27.0's JavaScript 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 (outlined) adds identity and the -dual-signature handshake on webcpp::crypto's P-256 (its foundation increment 3). Phase 3 (outlined) -adds the plugins: signed state, roles, then `scale()`. +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 D16), `../specs/trystero/spec.md`. +**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/phase1.json`, regenerated only by `test/oracle/record_0_27.mjs` (a copy of - `reference/vectors/record.mjs`) run against that pin: `node test/oracle/record_0_27.mjs `. + `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`. @@ -105,7 +109,8 @@ library's `main` and is off on the branch until Task 2.6. **Files:** - Modify: `build.jam` (the `parts` alias), `test/Jamfile` -- Create: `test/fixtures/expected/trystero-0.27.0.json` (copy of `reference/vectors/phase1.json`), +- 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` @@ -613,42 +618,841 @@ library's `main` and is off on the branch until Task 2.6. --- -## Phase 2 (outlined; written in full when crypto's increment 3 P-256 part merges) - -Depends on webcpp::crypto `curves::p256` (``): -`keypair::generate()`, `keypair::make(scalar)`, `keypair::secret_scalar()`, -`keypair::public_key().uncompressed()`, `public_key::make(65 bytes)`, `keypair::sign_ecdsa(digest)`, -`verify_ecdsa(signature, digest, key)`, `normalize_ecdsa`, `check_low_s` (crypto's plan, -Tasks 3.1 and 3.2). Each task records its vectors in the recorder first; P-256 signatures are -random in WebCrypto, so vectors fix keys and check that each side verifies the other's -signatures, never signature bytes. - -- **2.1 The connection model.** Read 0.27.0's `peer.ts`, `peer-transport.ts`, `room.ts` and - `strategy.ts` and record the frames of one room's data channel. 0.27.0 has no connection shared - across rooms (0.26.0's `shared-peer.ts` is gone); the default ruling (design D9) is one - connection per room and remote peer, the app-level sharing of the change `shared-connection`, - its presence frames and `room_token` retired. The task confirms or amends D9 before 2.2. -- **2.2 Endpoint and user keys.** `detail/identity.hpp`: an endpoint key pair per app (`peerId` - from its compact key, Task 3's `derive_peer_id`), a user key pair (`userId`), the - `user-proof` binding (`domainTag('user-proof', 3)`), `identity` option: `ephemeral` (default), - `imported(user_identity)`; `create_user_identity()`, `export_user_identity()` (0.27.0's - `trystero_uk_` text, vectors from `exportUserIdentity`) and `import_user_identity()`; no - implicit persistence (design D15). Needs P-256 `generate`, `make`, `secret_scalar`. -- **2.3 Signed key records and their cache.** `getVerifiedPubKeyRecord`, `verifyWithP256` with - low S required (`check_low_s` before `verify_ecdsa`), signing with `normalize_ecdsa`; the - bounded signature cache (8,192 entries, 2 MiB). -- **2.4 The dual-signature handshake.** `handshake.ts`: init and response with UUID nonces - (Task 3), both endpoint and user signatures over a payload that binds app, room and both - SDP DTLS fingerprints; `handshake_failed` on any mismatch; the signal's 0.27.0 fields. -- **2.5 Users for real.** The user table fed by verified user ids; `max_users` (`room_full`, - refresh-safe per user id); multi-endpoint users (several apps of one user identity in one or - several processes are "tabs"). -- **2.6 Interop.** The oracle lane pinned to 0.27.0 (the npm packages `trystero@0.27.0` and - `@trystero-p2p/core@0.27.0`), the twins rewritten, the interop scenarios against Chrome on - both lanes, turned back on; vectors regenerated and byte-identical. -- **2.7 The merge.** Docs whole (README, every page, chapter 15), the changelog's entry, one - merge of `port/trystero-0.27` into trystero `main`, the superproject's pointer, both CIs green - (design D1). +## 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: