diff --git a/doc/2026-10-07T00-20-00Z_architecture_roc_worlds/2026-10-07T00-20-00Z_architecture_roc_worlds.md b/doc/2026-10-07T00-20-00Z_architecture_roc_worlds/2026-10-07T00-20-00Z_architecture_roc_worlds.md index 03300286ca..75fd4e0be6 100644 --- a/doc/2026-10-07T00-20-00Z_architecture_roc_worlds/2026-10-07T00-20-00Z_architecture_roc_worlds.md +++ b/doc/2026-10-07T00-20-00Z_architecture_roc_worlds/2026-10-07T00-20-00Z_architecture_roc_worlds.md @@ -233,8 +233,10 @@ are therefore: actor and sequences a `program_installed` event. The command prints the module's BLAKE3 hash. - The browser page `/world` can issue invites (separate admin bearer), upload a - `.wasm` module, join, chat, send input, and render host-produced view text. - Browser, CLI, and Iroh clients all drive the same `world_session` protocol. + `.wasm` module or select up to 8 `.roc` sources for admin-authenticated + compile-and-install (128 KiB per file, 256 KiB total), join, chat, send input, + and render host-produced view text. Browser, CLI, and Iroh clients all drive + the same `world_session` protocol. - The hosted world state and module pin are currently volatile: restarting `serve` resets the actor and releases its temp-tag pin. Durable module selection, event-log replay/state restoration, and fetching module bytes from @@ -270,6 +272,20 @@ build pass. Full Rust tests pass: 655 library, 97 CLI integration, 5 remote write/QUIC, 19 doctests. Nix `id-lib` builds with 479 unit tests and its hermetic integration/doctest checks. +## 2026-10-14 Verification: browser Roc source upload + +The `/world` host controls now accept multiple `.roc` source files and send the +existing admin-authenticated `compile` frame over `/ws/world`; the UI validates +the server's 8-file, 128 KiB/file and 256 KiB total limits, reports compile +status and the installed BLAKE3 hash, and leaves world interaction available. +The compiled-module upload remains available. The browser WS tests reject a +wrong admin token and cover compile/install/run (counter input changes +`count=0` to `count=1`). The authorized compile test was skipped here because +`examples/roc-world/targets/wasm32/host.wasm` is not present; build it with +`examples/roc-world/build-host.sh` to run that integration path. Targeted WS +tests passed (the compile test reports this documented skip), as did browser +TypeScript typechecking and all 343 browser tests. + **Boundary reminder:** pure Roc with a deliberately effect-free platform is capability-safe by construction; Wasm is not required to deny ambient file or network access that the platform never grants. Wasmtime is used for the @@ -369,11 +385,11 @@ Wasmtime gives fuel, memory caps, and a second isolation layer for free. So the rule is **provenance decides the tier, not the language**: -| Tier | What runs | Who may supply it | Bounds | -| ---- | --------- | ----------------- | ------ | -| N: native Roc | Roc compiled with the `id` world platform (Rust host), no effects beyond the program ABI | The operator only, built from source on the host | Authority: none by construction. CPU/memory: not bounded in-process, so run in a dedicated worker with rlimits and a watchdog (not yet built) | -| W: Wasm in Wasmtime | The same program compiled to wasm32, import-free | Anyone: uploaded, or fetched from a peer by blob hash | Fuel per call, memory cap, size limits, poisoned on trap (implemented in `sandbox.rs`) | -| B: Wasm in the browser | The same wasm module, for view/prediction only | The host serves the module the world pins | Browser sandbox; never authoritative, server state wins | +| Tier | What runs | Who may supply it | Bounds | +| ---------------------- | ---------------------------------------------------------------------------------------- | ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | +| N: native Roc | Roc compiled with the `id` world platform (Rust host), no effects beyond the program ABI | The operator only, built from source on the host | Authority: none by construction. CPU/memory: not bounded in-process, so run in a dedicated worker with rlimits and a watchdog (not yet built) | +| W: Wasm in Wasmtime | The same program compiled to wasm32, import-free | Anyone: uploaded, or fetched from a peer by blob hash | Fuel per call, memory cap, size limits, poisoned on trap (implemented in `sandbox.rs`) | +| B: Wasm in the browser | The same wasm module, for view/prediction only | The host serves the module the world pins | Browser sandbox; never authoritative, server state wins | All three tiers implement one `WorldProgram` seam (`update(participant, bytes)` and `view(viewer) -> bytes`), so a world does not know which tier runs it. @@ -393,7 +409,7 @@ through a small `SessionIo` trait, so protocol behavior cannot diverge. UTF-8 JSON object, at most 16 KiB. The JSON is exactly the WebSocket protocol, so presentation adapters are transport-agnostic. - The first frame is `join {capability, after?}` or `invite {admin_token, - display_name}`; anything else is an error and the stream ends. A peer that +display_name}`; anything else is an error and the stream ends. A peer that sends no first frame within 10 s is dropped. - Iroh authenticates the **node**, not the participant. The remote node ID is logged but never grants world authority; the capability does. This matches @@ -407,8 +423,8 @@ Clients: `id world invite --admin-token T --name N` and ### Not yet done (explicit) -*(Superseded: the items below were completed in later sections. See -“Current status: not yet offered” at the end of this document.)* +_(Superseded: the items below were completed in later sections. See +“Current status: not yet offered” at the end of this document.)_ - `WorldProgram` wiring into the actor, then the Roc wasm demo. The checked-in Roc module still traps on its first `view`; that must be diagnosed first. @@ -549,7 +565,7 @@ copy of the structured data. ### Sync completion: readiness is not arrival `replicate` used to return as soon as the docs engine declared the document -*ready* (`PendingContentReady`). Readiness only means the initial sync round is +_ready_ (`PendingContentReady`). Readiness only means the initial sync round is over — a peer can still be connecting, so a replica could read an empty document even though the host had entries (seen as a rare flake under full suite load). It now also waits for every announced entry's blob to be local, @@ -585,9 +601,9 @@ participant can replicate with a read-only ticket, in memory or on disk, and that survives host restarts on the same namespace; two example apps (counter, tic-tac-toe) build with the shared platform and run end to end. -*(Superseded — see "Current status" at the end of this document. The worlds +_(Superseded — see "Current status" at the end of this document. The worlds hub, the capability runtime, the compile service and the native Roc tier -below were all built after this list was written.)* +below were all built after this list was written.)_ --- @@ -680,7 +696,7 @@ built in this order, each committed on its own: **hub**, **capabilities**, - Bounds: a ceiling on open worlds (`--world-max-open`) and on concurrent sessions (`--world-max-sessions`); a session holds a lease for its lifetime. Durable worlds with no sessions are evicted after an idle period and reopen - from their journal on next use, so the number of *existing* worlds is + from their journal on next use, so the number of _existing_ worlds is limited by disk, not memory. Ephemeral worlds are never evicted. - Each world keeps its own actor, journal, module directory, records document and (with the native tier) its own worker process: no state is shared across @@ -694,7 +710,7 @@ the server is expressed as **data it returns** and **events it receives**: - `wants : model -> Str` (JSON, a pure projection like `records`) lists the subscriptions and requests the model currently has: `{"v":1,"subscribe":["time.tick:5000","players"], - "requests":[{"id":"r1","cap":"time.now"}]}`. +"requests":[{"id":"r1","cap":"time.now"}]}`. - The host turns each new thing into an **event**, delivered through the existing `update(model, 0, json)` (participant 0 is the host; real participants start at 1). Every such event is **journaled** before it is @@ -862,7 +878,7 @@ defaults). Notes worth keeping: - The compiler child runs with a cleared environment (its cache lives in the job directory, so concurrent jobs never collide), CPU/address-space/ file-size rlimits, bounded captured output, and a wall-clock deadline - with kill. `RLIMIT_NPROC` is deliberately *not* set: it counts the user's + with kill. `RLIMIT_NPROC` is deliberately _not_ set: it counts the user's whole process table (threads included) and would starve the compiler's worker threads for reasons unrelated to the job. - The result goes through the same import-free validation as an upload @@ -901,7 +917,7 @@ wants, snapshot, restore. of released with a mismatched refcount. - **Spawn hardening** (in the post-fork hook): `no_new_privs`, dumpable off, rlimits (address space, CPU, file size, processes, core), Landlock — the - ruleset denies *every* path except an EXECUTE+READ grant on the worker's + ruleset denies _every_ path except an EXECUTE+READ grant on the worker's own file (opened O_PATH by the parent before the fork; pre_exec hooks must not touch the filesystem) — and a seccomp allowlist that permits the worker's syscalls (including the one pending `execve`, which Landlock @@ -1076,19 +1092,34 @@ serves the world to any ordinary SSH client: `ssh -p PORT @host`, with the invite capability as the password. An empty user names the default world. The password is checked when the shell opens, through the same join path as Iroh and WebSocket, so a wrong capability is answered inside the shell with -`join denied`. The shell's keystrokes become `input` frames, and each `view` -frame clears the terminal and repaints it; `error` frames are printed. +`join denied`. The shell line-buffers fragmented terminal packets: ordinary +complete lines are `chat` frames, `/input ` sends raw program input, +`/records [prefix]` requests capability-authorized record pages, `/help` lists +commands and `/quit` closes the shell. Empty and overlong lines and terminal +control sequences are not submitted. Views clear and repaint the terminal, so +the default program chat/view and records can be used in one session. + +The same local blob store opened by `serve` backs `/documents [prefix]` and +`/document `. Listing skips internal dot-tags and is bounded; viewing is +read-only and limited to exact public `.txt`, `.md` or `.markdown` names whose +blob is complete, at most 64 KiB and valid UTF-8. Terminal control characters +are removed. Missing, binary and oversized files are refused; SSH does not +resolve filesystem paths or traverse private namespaces. Collaboration edits +remain in the web ProseMirror editor. The server host key lives in `.ssh-host-key` (created on first start). Input is queued with `try_send` rather than awaited: the handler runs on the same russh loop that flushes output, so waiting for queue space could deadlock. A flood of keystrokes drops input instead of stalling the session. -Verification: `world_ssh` unit tests drive `serve` with a russh client. A -wrong password is refused inside the shell. With the sandbox feature, the -counter module is installed in-process and the client sees `count=0`, then -`count=1` after `inc`, parsed with `vt100`. The test does not start the full -binary, because its Iroh startup stalls in the sandbox. +Verification: `world_ssh` tests drive `serve` with a russh client and cover +fragmented lines, CR/LF, maximum length, commands, records rendering, authorized +chat/records requests, and read-only document listing/viewing including missing, +binary, oversized and internal names. A wrong password is refused inside the +shell. With the sandbox feature, the counter module is installed in-process +and the client sees `count=0`, then `count=1` after `/input 696e63`, parsed with +`vt100`. The tests do not start the full binary, because its Iroh startup stalls +in the sandbox. Access control is not decided by this transport. The SSH password is the same bearer capability the other transports accept, so the open question (ACL diff --git a/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md b/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md index 70e3b5beb4..3ad3b626d3 100644 --- a/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md +++ b/doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md @@ -1,7 +1,7 @@ # Phased plan: from the design to a working identity system - Date: 2026-10-11 (revised after round 2 research) -- Status: **Proposed. Awaiting the owner's approval.** Nothing in this plan has been started. Phase 0 starts when the owner signals to commit and merge the design work. +- Status: **Execution approved by the owner on 2026-10-14.** Phases 0–8 have been implemented and merged through PR #206. Follow-up completion work is being validated in dedicated feature branches; see [`doc/2026-10-14T_platform_completion/acceptance-brief.md`](../2026-10-14T_platform_completion/acceptance-brief.md). P7.2 design is complete (implementation deferred); P7.5/P3.7 require external networks/accounts. Other unresolved implementation and protocol gaps remain listed in that brief. - Read with: [index](./2026-10-11T11-08-42Z_design_remaining_work.md) (every decision and open question), [explainers](./explainers.md), [BeeKEM assessment](./beekem-assessment.md), [round 2 results](./research-round2/README.md), and the task docs. - Copy for the repo's agent rules: `.opencode/plans/id-phased-plan.md` (the same plan, as `pkgs/id/AGENTS.md` asks). @@ -186,13 +186,13 @@ Goal: invites and links that work, pull, fork recovery, and the CLI that exposes **Phase 7** (nothing here is needed for a first working system): -| Step | What | Blocked by | Parallel with | Tests | -| ---- | ---------------------------------------------------------------------------------------------------- | --------------------------- | ------------- | ----------------------------------- | -| P7.1 | Relay kit for a server behind a Cloudflare Tunnel, and for VPS testing. Updated for the S11 findings | none | P7.2 | the unit file test (P3.8) | -| P7.2 | Cloudflare Workers pkarr option: HTTP PUT and GET and DNS over HTTPS only (round 2). Design only | owner's go | P7.1 | none yet | -| P7.3 | DHT opt-in per world (decision 15) | Phase 3 | P7.1 | integration over a test DHT | -| P7.4 | Access control (decision 13): none now; revisit at implementation | none | everything | none now | -| P7.5 | Deployments and real-network tests (owner-blocked) | owner accounts and networks | none | the C2 matrix; N29 on real networks | +| Step | What | Blocked by | Parallel with | Tests | +| ---- | ----------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------- | +| P7.1 | Relay kit for a server behind a Cloudflare Tunnel, and for VPS testing. Updated for the S11 findings | none | P7.2 | the unit file test (P3.8) | +| P7.2 | Cloudflare Workers pkarr option: HTTP PUT and GET and DNS over HTTPS only (round 2). Design complete; implementation deferred | none (design); implementation needs owner approval | P7.1 | design note: [P7.2 Cloudflare Workers](../2026-10-14T10-18-19Z_design_p7_2_cloudflare_workers.md); no implementation tests | +| P7.3 | DHT opt-in per world (decision 15) | Phase 3 | P7.1 | integration over a test DHT | +| P7.4 | Access control (decision 13): none now; revisit at implementation | none | everything | none now | +| P7.5 | Deployments and real-network tests (owner-blocked) | owner accounts and networks | none | the C2 matrix; N29 on real networks | **Phase 8** (each becomes a phase document when it starts): diff --git a/doc/2026-10-12T21-22-53Z_phase_7_connectivity/2026-10-12T21-22-53Z_phase_7_connectivity.md b/doc/2026-10-12T21-22-53Z_phase_7_connectivity/2026-10-12T21-22-53Z_phase_7_connectivity.md index c67eeb5b7b..f8f52cd5bc 100644 --- a/doc/2026-10-12T21-22-53Z_phase_7_connectivity/2026-10-12T21-22-53Z_phase_7_connectivity.md +++ b/doc/2026-10-12T21-22-53Z_phase_7_connectivity/2026-10-12T21-22-53Z_phase_7_connectivity.md @@ -5,18 +5,18 @@ - Base branch `phase-7`. Tracks run in parallel: - `p7-relay`: P7.1 relay kit for a server behind a Cloudflare Tunnel, and for VPS testing (updated for the S11 findings). - `p7-dht`: P7.3 DHT opt-in per world (decision 15). -- Not started: P7.2 Cloudflare Workers pkarr option (design only; needs owner's go). P7.4 access control (decision 13: none now). P7.5 deployments and real-network tests (owner-blocked: accounts and networks). +- P7.2 Cloudflare Workers pkarr option: design complete; implementation deferred pending explicit owner approval. See [design note](../2026-10-14T10-18-19Z_design_p7_2_cloudflare_workers.md). P7.4 access control (decision 13: none now). P7.5 deployments and real-network tests (owner-blocked: accounts and networks). - Phase 8 items each become their own phase document when they start (P8.1 to P8.6); P8.7 BeeKEM only if its conditions are met (they are not); P8.8 lints: do nothing now. ## Steps -| Step | Track | Status | Commits | Tests | Notes | -| ---- | ----- | --------------------- | ---------------------------- | ------------------------------------------------------- | ------------------------------------------- | -| P7.1 | relay | done | 80feb48b, ff844396 | relay_ops: 21 (14 red before the mode) | tunnel and vps modes in relay.kit.toml | -| P7.2 | - | blocked on owner's go | | | design only | -| P7.3 | dht | done (server-wide) | 1c91f76a, 5249c60a, 61f7e00c | dht_opt_in 3; dht unit 5; dht_testnet 2 (`dht` feature) | server-wide --dht on serve; publish enabled | -| P7.4 | - | none now | | | decision 13 | -| P7.5 | - | owner-blocked | | | accounts and networks | +| Step | Track | Status | Commits | Tests | Notes | +| ---- | ----- | ---------------------------------------- | ---------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | +| P7.1 | relay | done | 80feb48b, ff844396 | relay_ops: 21 (14 red before the mode) | tunnel and vps modes in relay.kit.toml | +| P7.2 | - | design complete; implementation deferred | | none (design-only) | [design note](../2026-10-14T10-18-19Z_design_p7_2_cloudflare_workers.md); no deployment/account access | +| P7.3 | dht | done (server-wide) | 1c91f76a, 5249c60a, 61f7e00c | dht_opt_in 3; dht unit 5; dht_testnet 2 (`dht` feature) | server-wide --dht on serve; publish enabled | +| P7.4 | - | none now | | | decision 13 | +| P7.5 | - | owner-blocked | | | accounts and networks | ## 2026-10-12T21:40:00Z Note: P7.1 relay kit modes diff --git a/doc/2026-10-13T23-44-27Z_phase_8_open_design_items/2026-10-13T23-44-27Z_phase_8_open_design_items.md b/doc/2026-10-13T23-44-27Z_phase_8_open_design_items/2026-10-13T23-44-27Z_phase_8_open_design_items.md index 212ac62d6a..1565977538 100644 --- a/doc/2026-10-13T23-44-27Z_phase_8_open_design_items/2026-10-13T23-44-27Z_phase_8_open_design_items.md +++ b/doc/2026-10-13T23-44-27Z_phase_8_open_design_items/2026-10-13T23-44-27Z_phase_8_open_design_items.md @@ -63,3 +63,11 @@ - Invariants check (`check_invariants`) and query folds (`roster`, `tag_claims`, `documents`) produce identical results before and after pruning. - Red first: integration tests in `tests/retention_pruning.rs` failed initially (commit 678e9e63) and passed after implementation (commit a3c82d7c). - Targeted test suite passes: `retention_pruning` (4 tests), `event_store` (92 passed, 2 ignored). + +## 2026-10-14T00:00:00Z Acceptance: durable signed revisions for web saves + +- Every successful manual save or autosave checkpoint publishes the saved bytes as a blob and records an applied, node-signed `document.put` revision naming its BLAKE3 hash, byte size, and media type, plus a `filename` tag. Each save is a separate revision; historical blobs/events remain available. The event ID is returned to the caller. Legacy filename blob tags remain for existing file views. +- ProseMirror steps remain ephemeral in-memory collaboration transport; only save/autosave checkpoints become durable signed revisions. +- Save acceptance requires tests for applied signed record metadata, filename claim, blob retrieval, distinct repeated revisions, and an error response rather than success when publication fails. +- The web state opens `LocalEvents` under the identity database's sibling `events` directory, signing with the node key already supplied to `AppState::new`. `/api/save` stores the blob, then publishes a `document.put` and its `filename` claim before updating the legacy filename tag. A publication failure returns an error; the new blob may remain unreferenced, but is never reported as a successful save. +- Red, then green: before implementation, the two web route tests failed because saves returned no `document_id` and an unpublishable filename still got a 200. After implementation, both pass. `local_events::tests`: 2 passed; `tests/documents.rs`: 5 passed. Web TypeScript typecheck passes, and Vitest reports 343 passed, 9 skipped. diff --git a/doc/2026-10-14T10-18-19Z_design_p7_2_cloudflare_workers.md b/doc/2026-10-14T10-18-19Z_design_p7_2_cloudflare_workers.md new file mode 100644 index 0000000000..e13a02f09e --- /dev/null +++ b/doc/2026-10-14T10-18-19Z_design_p7_2_cloudflare_workers.md @@ -0,0 +1,125 @@ +# P7.2 design: Cloudflare Workers pkarr option + +- Date: 2026-10-14 +- Status: **design complete; implementation deferred**. This is a design-only decision record. No Worker, account, DNS zone, or Cloudflare resource was created or accessed. +- Roadmap: [Phase 7 connectivity](./2026-10-12T21-22-53Z_phase_7_connectivity/2026-10-12T21-22-53Z_phase_7_connectivity.md), [phased plan P7.2](./2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md). +- Evidence baseline: [Cloudflare Workers round-2 research](./2026-10-11T11-08-42Z_design_remaining_work/research-round2/cloudflare-workers/RESULTS.md), read 2026-10-11. Its labels **[verified]**, **[inferred]**, and **[not checked]** are retained below. Cloudflare limits and prices are time-sensitive; re-check before implementation. + +## Decision and recommendation + +Design the option as an **opt-in, standalone pkarr HTTP relay plus a direct DoH endpoint**, implemented as a Worker front end with one SQLite-backed Durable Object per public key. It stores signed pkarr packets; it is not a Mainline DHT node, a general DNS server, or an iroh relay. Support only: + +1. `PUT /pkarr/` and `GET /pkarr/` for signed pkarr relay payloads. +2. `POST /dns-query` using `application/dns-message` for DNS-over-HTTPS responses to `_iroh..` TXT lookups. + +Do not serve UDP/TCP DNS, Mainline DHT, WebSockets, iroh relay traffic, arbitrary HTTP proxying, or normal recursive DNS/NS delegation. Return explicit `404`/`405` for other paths and methods. Keep n0 as the product default; opting into this Worker replaces the endpoint's pkarr publisher/resolver and DNS lookup origin as a matched configuration. Do not silently publish to one service and resolve from another. + +**Recommendation:** proceed to implementation only when the owner wants an independent, private-to-this-service lookup namespace. The Worker adds no NAT traversal or relay capacity; it cannot replace n0 for QAD or relay traffic. The design does not require an owner decision to record these high-touch choices: this note chooses public read access to signed records, no account/auth layer, paid Workers/DO capacity, no DHT replication, and opt-in only. Revisit the choices listed under [Open decisions](#open-decisions) before deployment. + +## Trust boundary and threat model + +### Boundary + +- **[Verified]** The pkarr payload is signed by the endpoint key. iroh checks returned payload signatures client-side. The relay can validate the signature and packet shape but cannot forge a valid endpoint update without the endpoint's private key. See research [§D, iroh-side pkarr](./2026-10-11T11-08-42Z_design_remaining_work/research-round2/cloudflare-workers/RESULTS.md#d-open-source-pkarr-relays-and-the-iroh-dns-server). +- **[Inferred]** Cloudflare terminates HTTPS and operates the Worker and Durable Object platform. Cloudflare can observe client IPs, requested z32 keys, update/lookup timing, DNS questions, and plaintext request/response metadata and content. Signed records are integrity-protected, not confidential. Treat Cloudflare and its account/operator boundary as trusted for availability and metadata handling, not as an authority that can change valid signed endpoint records undetectably. +- **[Verified]** A Durable Object is a strongly consistent storage boundary; it is not an independent replica or DHT. A per-key object serializes competing writes for that key. Platform/account compromise, service deletion, outage, quota exhaustion, or malicious withholding can make records unavailable or stale. +- **[Inferred]** Anyone who learns a public endpoint ID can query this service and read the signed address record. Address filtering should remain relay-only by default; publishing a direct address is a separate privacy decision and is not changed by this service. + +### Threats and controls + +| Threat | Design control | Residual risk | +| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| Forged or malformed packet, key/path mismatch, oversized body | Cap body at 1,072 bytes; validate z32 key, decode format, verify Ed25519 signature and embedded public key, and validate DNS packet bounds before storage. Clients still verify signatures. | Parser/crypto implementation defects; WebCrypto Ed25519 runtime behavior and cost have not been exercised on Workers. | +| Replay or stale update replacing newer record | DO transaction compares signed packet timestamp/sequence with the stored value and atomically stores only a strictly newer value. Return `204` for a valid stale packet for iroh compatibility; do not let an older record overwrite. | A malicious endpoint can publish its own newer, valid record. Clock/sequence semantics and overflow need vector tests. | +| Write/read flooding, key churn, cost exhaustion | Per-IP rate limiting at Worker edge; bounded body and route set; per-key DO; explicit request quotas/alerts and abuse response; cap storage/retention and reject overload cleanly. | IP limits can be evaded/distributed and may affect NAT-shared users. DO hot-key queues and plan/account quotas can still deny service or incur cost. | +| Poisoned cache or stale DNS answer | Use DO authoritative latest value; send conservative HTTP cache directives and honor conditional GET only if implemented safely. DoH responses use a bounded DNS TTL; clients verify signed packets. | CDN/browser/intermediate caching may delay visibility; DNS TTL is not a consistency guarantee. | +| Data loss or service/region outage | DO durable storage and operational backups/export before any production reliance; keep n0 configuration available as rollback. | No cross-provider replication in this design; DO durability is not a backup or availability SLA. | +| Privacy leakage | Explain that the service sees IPs, queried IDs and timing; publish relay-only endpoint info; optional use is explicit. | HTTPS does not conceal metadata from Cloudflare; DoH moves DNS query visibility from recursive resolvers to this operator/platform. | + +## API and protocol contract + +### PUT and GET + +- Base URL is configured by the operator; iroh appends the z32 endpoint ID. Keep route shape compatible with the existing client seam: `PUT|GET /`; the deployment may expose this under `/pkarr`. +- **PUT:** accept only `application/x-pkarr-signed-packet`; hard-limit request body to 1,072 bytes (signature 64 + timestamp 8 + DNS packet ≤1,000). Validate key encoding and that the packet key matches the path; parse and verify the signed bytes exactly as pkarr v3 (`3:seqie1:v:`); reject malformed, invalid-signature, invalid-DNS, and too-large inputs (400/413). Atomically store only a packet more recent than the current packet. Return `204 No Content` on new or valid stale packet. Return `429` on rate limit and `503`/`500` on storage failure; never claim success if a new packet was not durably accepted. +- **GET:** return the latest relay payload with `Content-Type: application/x-pkarr-signed-packet`; return `404` if absent/expired. Preserve the full signed payload. Conditional GET/`If-Modified-Since` may be added only after compatibility tests; do not rely on CDN caching for correctness. +- The 204 stale-write behavior is **[inferred]** to be safer for iroh 1.3.0: the reference iroh DNS server returns 204 for stale packets and the iroh publisher accepts only 2xx, while the pkarr relay spec describes 409. See research [§D](./2026-10-11T11-08-42Z_design_remaining_work/research-round2/cloudflare-workers/RESULTS.md#d-open-source-pkarr-relays-and-the-iroh-dns-server). +- Set an explicit retention policy. Recommended starting point: expire records after 7 days without refresh, matching the reference server's observed policy **[verified as source behavior]**; use a DO alarm or lazy expiration, not per-request scans. The 5-minute client republish interval means an active endpoint refreshes well within this window **[verified]**. + +### DoH only + +- `POST /dns-query`, `Content-Type: application/dns-message`; parse bounded DNS wire messages and answer only the intended TXT question under the configured origin (`_iroh..`). Return `application/dns-message` with the DNS response; reject unsupported query types/names with a valid negative answer, and malformed/oversized messages with 400. No general recursive forwarding. +- **[Verified]** The native iroh client supports HTTPS DoH via `NameserverConfig::https(...).with_tls_server_name(...)` and POSTs `application/dns-message` to `/dns-query`; this is compiled for native targets. See research [§D, DoH client](./2026-10-11T11-08-42Z_design_remaining_work/research-round2/cloudflare-workers/RESULTS.md#d-open-source-pkarr-relays-and-the-iroh-dns-server). +- **[Inferred]** Configure clients with the DoH endpoint directly. Do not claim the Worker hosts an ordinary DNS zone: it has no DNS-over-UDP/TCP listener or port-53 delegation path. DoH answers should carry a short TTL aligned with the record format/client expectations and must not expose unsigned address data as authoritative. + +## Storage, consistency, caching, and abuse limits + +- Use a SQLite-backed DO namespace, one DO ID derived deterministically from validated public key bytes. Store only current signed payload, timestamp, and expiry metadata. Transactionally compare-and-set so concurrent updates cannot regress the key's record. +- **[Verified]** Research read Cloudflare's 2026-10-11 public docs: SQLite-backed DOs support a 2 MiB key+value maximum, 10 GB per object on Paid, and a soft 1,000 requests/s per object; a full queue can return `overloaded`. KV permits one write/second/key and may be stale by 60 seconds or more, so it is unsuitable for the authoritative write path. Use DO, not KV. Re-check these limits before implementation. +- **[Inferred]** A signed record is at most 1,072 bytes, making value size small; the per-object request queue and global account quotas, not record bytes, are the meaningful capacity concerns. A per-key DO serializes hot updates but also creates a hot-key bottleneck. +- Disable shared cache for PUT and initially for GET/DoH (`Cache-Control: no-store`) to make DO state authoritative and avoid stale edge reads. Later, immutable/version-aware ETags and short public caching can be considered after multi-region cache tests. Never let cache updates bypass signature/sequence checks. +- Apply rate limiting to both PUT and GET/DoH by source IP and use stricter write limits; research confirms Cloudflare's rate-limit binding supports configured limits with 10- or 60-second periods. Add body/query size bounds, per-key write pacing, bounded retention, overload responses, and operational request/CPU/DO usage alarms. Keep limits configurable and document that IP controls are abuse friction, not authentication. +- Cost estimate is not a promise: research's **[inferred]** back-of-envelope estimate assumes 2 ms CPU and 288 idle PUTs/endpoint/day; it estimates roughly $5/month at 100 endpoints, $6.15 at 1,000, and $43.59 at 10,000 on the researched Paid pricing. Recalculate with measured PUT/GET/DoH and DO duration before a public rollout. + +## Feasibility grounded in research + +- **[Verified]** Workers implement HTTP `fetch` handlers, support WebCrypto Ed25519 import/verify, and support SQLite-backed Durable Objects. The pkarr HTTP routes and DoH request/response path do not require UDP, long-lived TCP, or local disk. +- **[Verified]** Workers have no functional UDP socket (`node:dgram` is documented as a non-functional stub) and no persistent local disk; `/tmp` is per-request/non-persistent. Therefore they cannot run DNS on UDP/TCP, join Mainline DHT, or run either existing relay server unmodified. The existing `iroh-dns-server` also needs DNS UDP/TCP and redb local disk; `pkarr-relay` starts a DHT node and uses LMDB. +- **[Verified]** Paid Workers were documented as $5/month minimum, 128 MiB memory, 30-second default CPU configurable up to five minutes, and 10 million Worker requests included; DO has separate request/duration meters. The free Worker CPU limit is 10 ms and free plan daily request allowance makes research estimate capacity about 347 endpoints at the five-minute republish cadence. Rates/limits dated 2026-10-11; reconfirm before build. +- **[Inferred]** A small custom JS/TS implementation using DO storage and WebCrypto is feasible and substantially smaller than porting the complete Rust servers. Research estimates 150–200 lines for relay and 150–250 more for DoH; treat that as a rough estimate, not a sizing guarantee. +- **[Not checked]** No Worker was built or deployed. Ed25519 verification speed, CPU usage, DO transactional behavior under concurrent requests, caching behavior, account pricing, and production-scale limits remain unverified. +- This is lookup-only. It is not a replacement for n0 relays or a QAD-enabled VPS; it offers no direct-path/NAT traversal capability and is not DHT-backed. Records written here are visible only to clients configured to use this service unless some separate replication is later designed. + +## Protocol and endpoint integration seam + +- **Current seam [verified in repository]:** `pkgs/id/src/connectivity.rs::public_builder` starts from `presets::N0`; comments identify N0's pkarr and DNS services. The research confirms `PkarrPublisher::builder(url)`, `PkarrResolver::builder(url)`, and direct HTTPS `NameserverConfig` are available in the pinned iroh stack. +- **Proposed seam [inferred]:** add an explicit lookup configuration, e.g. `LookupPolicy::{N0, Worker { pkarr_base_url, doh_url, tls_server_name, origin }}`, and have one builder compose publisher, resolver, and DoH DNS lookup from the same selected service. Keep `N0` as default and make custom Worker selection opt-in in server config/CLI, validating `https` URLs and preventing an accidental split between publication and resolution. Do not change relay map/QAD settings. +- Keep Worker implementation separate from Rust endpoint configuration. The endpoint talks the existing pkarr HTTP payload contract and HTTPS DNS-message transport; no protocol fork or new client library is needed. First implementation should add fixture-based interop tests against iroh-generated signed packets and DoH queries, then local Worker/DO tests. +- **Boundary to existing app:** no change to `RelayPolicy`, relay kit, relay server, ticket format, direct-address policy, DHT opt-in, or QAD. The endpoint's existing 45-second dial deadline continues to bound lookup waits. + +## Rollout, rollback, and verification + +1. **Before coding:** re-read linked official documentation and pkarr/iroh source at the current pinned versions; confirm exact storage transaction APIs, DNS question/answer semantics, and Cloudflare plan/pricing. Capture dependency/source versions in the implementation record. +2. **Local validation:** protocol golden vectors for valid/invalid signature, public-key/path mismatch, malformed DNS packet, 1,072/1,073-byte boundaries, equal/older/newer timestamps, concurrent writes, expiry, and GET after accepted/stale PUT. Verify client behavior for 204 stale writes. Add DoH TXT query vectors and verify DNS IDs, flags, bounds, TTL, negative answers, and unsupported types. +3. **Worker integration, before any public use:** run Wrangler local tests with SQLite DO binding; exercise cross-object isolation, one-key serialization, simulated storage errors/overload, all unsupported routes/methods, cache headers, rate limits, and strict no-forwarding behavior. Measure CPU and DO metering for signed PUT, GET and DoH workloads. +4. **Canary only after explicit deployment approval:** deploy to a non-production hostname/namespace with synthetic keys; exercise publisher, resolver and DoH from native iroh clients. Confirm public key record is valid, stale write never regresses, request limits and observability are working, and no unintended routes are exposed. Do not use real account or production data in design work. +5. **Opt-in rollout:** retain N0 default; select Worker only for an explicitly configured test cohort. Compare lookup success/latency and cost against n0; do not claim availability or privacy improvement without measurements. +6. **Rollback:** switch endpoint configuration back to N0 (publisher, resolver, and DoH as a single unit). Keep service data exportable before production reliance. If compromised, stop writes, disable the Worker route/binding, and revert clients to N0; changing DNS/HTTP base URL alone must not strand default clients. + +No deployment, account access, domain change, or live-network verification is authorized by this design note. + +## Risks + +1. **Custom implementation correctness:** exact pkarr v3 signature bytes, payload framing, DNS parsing, key binding and monotonic comparison are security-sensitive. +2. **Single-provider availability and privacy:** Cloudflare can observe lookup metadata and can deny/withhold service; there is no DHT fallback or independent replica. +3. **Operational capacity/cost:** publish-on-change plus five-minute republish, reads, DoH, DO duration, hot keys, abuse, and current billing can exceed the rough research estimate. +4. **Client behavior:** custom pkarr + DoH composition must be validated at the pinned iroh version; changing only a relay URL is not enough to route DNS lookup through the Worker. +5. **Cache consistency:** CDN cache can defeat freshness even when DO itself is strongly consistent; initial no-store policy reduces but does not eliminate client/runtime caching concerns. +6. **Not a relay:** users may mistake pkarr lookup service for traffic relay, DHT participation, or NAT traversal. Product/help text must name its scope clearly. +7. **Version drift:** the source research used iroh 1.3.0 and Cloudflare docs as of 2026-10-11; validate against the actual implementation lock and current platform documentation. + +## Open decisions (recorded, not blockers to this design) + +- **Namespace and domain:** choose the Worker hostname, pkarr base path, and DoH zone/origin; this note assumes operator-configured HTTPS hostnames and no normal NS delegation. +- **Retention and DNS TTL:** 7 days is a reference-server-derived starting point; confirm whether the application wants shorter retention and the right TXT TTL. +- **Rate policy:** select per-IP PUT, GET and DoH thresholds, burst behavior and operator alert budget after expected endpoint count is known. +- **Cache policy:** begin `no-store`; decide if ETag/`If-Modified-Since` and short edge caching are worth the added stale-data complexity. +- **Auth/abuse operations:** design assumes public reads, signed writes, no account-level authentication, and rate limits; decide whether an abuse report/contact path or emergency key/namespace shutdown is required before public exposure. +- **Deployment tier and budget:** research points to Paid due to CPU/request headroom, but account entitlements and billing must be reconfirmed by the owner before deployment. +- **Replication/fallback:** no n0 mirroring or DHT is included. Adding replication changes the trust, privacy, conflict and consistency model and requires a separate design. + +## Out of scope + +- Creating or configuring Cloudflare accounts, Workers, Durable Objects, DNS records, billing or credentials. +- Deploying, publishing, production code, benchmarking on a live Worker, account access or real-network tests. +- DNS over UDP/TCP, DNS delegation, recursive DNS, Mainline DHT, pkarr DHT replication, iroh relay/WebSocket protocol, QAD, NAT traversal, or replacing n0 relays. +- Authentication, endpoint authorization, direct-address publishing policy changes, a general cache/CDN, multi-provider replication, or a new pkarr protocol. + +## Sources + +Repository research is the source index; it contains file/version evidence and date-read for official source pages: + +- [Round-2 research RESULTS.md](./2026-10-11T11-08-42Z_design_remaining_work/research-round2/cloudflare-workers/RESULTS.md), particularly §§A (Workers limits/pricing/DO/KV/WebCrypto), D (pkarr, iroh client and server), E (cost arithmetic), and “Not verified”. +- [Official Workers limits](https://developers.cloudflare.com/workers/platform/limits/), [pricing](https://developers.cloudflare.com/workers/platform/pricing/), [DO limits](https://developers.cloudflare.com/durable-objects/platform/limits/), [KV limits](https://developers.cloudflare.com/kv/platform/limits/), [KV consistency](https://developers.cloudflare.com/kv/concepts/how-kv-works/), [Web Crypto](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/), and [rate-limit binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/). Research read 2026-10-11; re-check current docs. +- [pkarr relay specification](https://github.com/pubky/pkarr/blob/main/design/relays.md); iroh `iroh-dns`/`iroh-dns-server` 1.3.0 and `pkarr-relay` 2.1.0 sources, as cited with paths in research §D. +- In-repository integration points: [`pkgs/id/src/connectivity.rs`](../pkgs/id/src/connectivity.rs), [Task 08](./2026-10-11T11-08-42Z_design_remaining_work/task-08-connectivity-extensions.md), and [phase 7 record](./2026-10-12T21-22-53Z_phase_7_connectivity/2026-10-12T21-22-53Z_phase_7_connectivity.md). diff --git a/doc/2026-10-14T_platform_completion/acceptance-brief.md b/doc/2026-10-14T_platform_completion/acceptance-brief.md new file mode 100644 index 0000000000..e5a32a9247 --- /dev/null +++ b/doc/2026-10-14T_platform_completion/acceptance-brief.md @@ -0,0 +1,78 @@ +# Platform completion: acceptance brief + +Date received: 2026-10-14 +Starting commit: `292d3c7a` (after Phase 8 PR #206) + +## Owner's request (verbatim) + +> what's left? please continue to fully implement the plan. when you are done, ensure that there is a method to upload and run roc programs dynamically, access the document editing and viewing collaborative view with prose mirror, access a world which allows generic live chat and document view for either web or cli/ssh, and a generic home page with a world explorer, global chat, and live feed of recent and popular documents and tags. continue until all of this is done, store this message and refer back to it don't stop until you can review and affirm each individual part works right now. don't stop to ask me questions continue to implement and if you have questions or made high touch decisions maintain a list in a document for me to address later but don't stop. choose the better options with more features, higher performance, better adaptability to varied future plans. + +## Acceptance checklist + +- [x] Remaining work in the authoritative plan is inventoried; completed, deferred, skipped, and open items are distinguished below. External deployments and owner-bound protocol choices remain explicitly open. +- [x] Users can upload a Roc program dynamically and run it in a world (browser source compile/install and `.wasm` upload; CLI was already available). +- [x] Users can collaboratively edit and view documents using ProseMirror. Live collaboration and save publication are tested; see the local-only replication gap below. +- [x] A world supports generic live chat and document viewing through web and CLI/SSH. SSH viewing is read-only and bounded; web editing uses the shared ProseMirror surface. +- [x] The home page provides a world explorer, global chat, and live feeds of recent and popular documents and tags, scoped to this server. +- [x] Each delivered acceptance feature has targeted tests and a documented current verification result; integrated Rust, browser unit, formatting, and focused E2E status is recorded below. +- [x] High-impact choices and unresolved questions are recorded here or in a linked decision log without blocking implementation. + +## Progress + +Initial inventory: complete. The roadmap's Phase 8 items P8.2–P8.6 have merged in PR #206; P8.5 was already completed as P2.7. P8.1 is explicitly deferred, P8.7 explicitly skipped, and P8.8 deferred. P7.2's Cloudflare Workers pkarr design is now documented and merged into this work branch (design only; deployment deferred). P7.5 and P3.7 real deployments/network tests remain blocked on separate networks/accounts. Additional implementation gaps from the handoff are freshness/pull policy wiring, the group-join CLI path and unsigned local group-log stand-ins, and several unresolved protocol questions (#194, #185, #160, #183, #195); these are tracked as follow-up scope rather than being represented as finished. + +### Existing feature verification map and current acceptance state + +- **Roc runtime:** `world_compile.rs`, `world_session.rs`, `commands/world.rs`, `world_net.rs`, and `web/world_ws.rs`. Browser source compilation/install/run and CLI source compilation/install/run both passed targeted current tests; Wasm upload/run and invalid-admin-auth coverage also passed. Bounded compilation and the import-free Wasm sandbox remain in effect. +- **ProseMirror:** `web/src/editor.ts`, `collab.ts`, and Rust `web/collab.rs` provide collaborative editor sessions. Successful saves/autosaves now store the blob and publish signed local `document.put` revisions. Targeted route, `local_events`, and `documents` tests passed. **Known gap:** the sibling `LocalEvents` store is not replicated to other peers; collaboration is live in the hosted web session, but event-backed revision discovery is currently local-only. +- **World chat and documents:** authenticated web world chat/records remain available. SSH sessions now support line-buffered chat, `/input`, paged `/records`, `/documents`, and bounded, read-only UTF-8 text/Markdown `/document` viewing. The web world links to the shared file browser/ProseMirror view; editing remains in that editor, not SSH. +- **Home/discovery:** `/` now serves a server-scoped world explorer, default-world global chat, and separate recent/popular document and tag feeds. `/files` retains the file browser. Feed candidates are locally available, globally tagged, non-deleted documents; tag popularity counts locally available documents carrying each exact global tag, without view tracking. + +### High-impact choices / decision log + +- Prefer the existing bounded Roc sandbox and signed/event-backed document model; do not introduce arbitrary host access or a second document authority. +- A server-global chat/feed can be a local world backed by the configured default world until cross-server replication is explicitly integrated; the UI must label its scope honestly. +- World documents should reference immutable event-backed document revisions; collaborative edits should checkpoint/publish signed document revisions without treating transient ProseMirror steps as authoritative events. +- Discovery popularity should be derived from explicit, privacy-preserving event-backed signals (views/reactions) or clearly labelled local counts; no hidden tracking. +- Deferred by the authoritative plan unless separately justified: time/witness validity, BeeKEM (owner said skip), and broad lint cleanup. P7.2/P7.5 gaps will be documented if their external account/network prerequisites cannot be exercised here. + +#### Follow-up decisions for owner (implementation will not wait) + +1. **Meaning of “global chat.”** Default implementation will use the server's configured default world/lobby, sharing the existing capability-authenticated world chat stream. It is global across that server's lobby, not automatically federated across servers. Federation needs world identity/trust, moderation, and replication rules. +2. **Popularity and privacy.** Prefer an explicit “most tagged” ranking until there is a consentful event-backed popularity signal. Do not add per-user tracking. If actual popularity is later desired, a public, aggregate reaction/view event is the recommended seam. +3. **Roc upload security.** Browser source compilation must use the existing admin-token/world protocol and bounded compiler; program execution remains the existing import-free Wasm sandbox. Do not silently enable native worker execution in the browser path. +4. **Document durability.** ProseMirror steps remain transient live collaboration state; save/autosave emits signed immutable revisions. Whether every transient edit must be durable is not assumed (high write volume and large event histories make that a distinct trade-off). +5. **World document model.** Current web access links to the shared file browser/editor; SSH exposes only public local text/Markdown blobs with strict bounds. Neither surface treats arbitrary Roc JSON as a signed document. A replicated records-to-document reference/index is still future work; if added, publish an explicit immutable revision reference rather than interpreting arbitrary program state as document authority. + +### Implementation workstreams + +- [x] Dynamic Roc program authoring/upload/run in web and CLI. **Verified:** built `examples/roc-world/targets/wasm32/host.wasm`; `cargo test --features web browser_websocket_can_compile_install_and_run_roc_sources -- --nocapture` passed, including compiling Roc source through the browser transport, installing the module, and running its world update; `cargo test --test cli_integration test_worlds_compile_roc_sources_on_the_fly -- --nocapture` passed. The invalid-admin test and existing browser Wasm upload/run test passed in the targeted browser run. `bun run typecheck` and `bun run test` passed (343 passed, 9 skipped). Execution continues to use the bounded compiler and import-free Wasm sandbox; native execution is not enabled by this browser flow. +- [ ] Join the ProseMirror collaboration persistence path to signed document revisions and blob storage **and replicate those revisions**. Implemented locally: every successful manual/autosave stores the blob and publishes a signed `document.put` + `filename` claim through `LocalEvents`, returns the event ID, and fails closed on publication errors. **Not complete:** the local event store is not synced to other peers, so another node cannot yet discover those signed revisions through this path. Validation passed: 2 web save route tests, 2 `local_events` tests, 5 `tests/documents.rs` tests, TypeScript typecheck, Vitest (343 passed, 9 skipped), and the integrated Rust suite below. +- [x] Add generic document/chat world interface with web and terminal interaction. Web world chat/records exist; SSH provides line-chat/records and bounded read-only text-document viewing. ProseMirror editing remains in the linked web document surface, not SSH. +- [x] Replace the file-list root with an adaptable home page: world explorer, server-scoped global chat, and recent/popular documents and tags. `/files` preserves the file browser. +- [x] Run targeted Rust, web unit/typecheck, and browser end-to-end checks; update this checklist with actual results and blockers. + +### Current phase-brief tests + +- Browser Roc source path: pass with the local Roc compiler and generated world host artifact. The generated artifact is build output and is not committed. +- ProseMirror editor/collab: existing unit and browser tests are present; durable signed local save checkpoints are implemented and targeted tests pass. Peer replication remains open. +- Integration suite: `cargo test --features web,ssh --lib` passed (**1,502 passed, 4 ignored**), including Roc source compile/install/run, home, save publication, world records, and SSH document/chat tests. +- Home page: 5 Rust home tests passed; TypeScript typecheck passed; Vitest passed (**345 passed, 9 skipped**); focused Chromium home/navigation passed (**11 passed**), including root/home, `/files`, primary navigation, and editor navigation. +- SSH world shell: 17 focused `world_ssh` tests passed, including chat, records, `/input`, and document list/view bounds; targeted `rustfmt --check` and `git diff --check` passed. +- Formatting: `cargo fmt --all -- --check` and `biome check src/home.test.ts` pass after aligning the existing `blob_gate.rs` constructor with the configured Rust formatter and formatting the new home test. + +### Review pull requests + +- [#209 — Browser Roc source compile/install/run](https://github.com/developing-today/code/pull/209) +- [#210 — Signed document revisions on web save](https://github.com/developing-today/code/pull/210) (peer replication is not included) +- [#211 — SSH world chat and document viewing](https://github.com/developing-today/code/pull/211) +- [#212 — Server-scoped home discovery](https://github.com/developing-today/code/pull/212) +- [#213 — P7.2 Workers pkarr design](https://github.com/developing-today/code/pull/213) (design-only) + +### Broader unfinished roadmap items to close or explicitly defer + +- [x] P7.2: write the Cloudflare Workers pkarr design using the already-collected round-2 research. See [`doc/2026-10-14T10-18-19Z_design_p7_2_cloudflare_workers.md`](../2026-10-14T10-18-19Z_design_p7_2_cloudflare_workers.md). Design is complete; deployment and implementation remain out of scope for P7.2. +- [ ] P7.5/P3.7: real two-network and account-backed deployment matrix cannot be truthfully verified without the required networks/accounts. Keep the code-side test harness ready and leave the live matrix explicitly blocked, not falsely passed. +- [ ] Wire the existing freshness-window and pull-policy configuration into server/world settings and CLI defaults (handoff gap). +- [ ] Finish or explicitly scope the `group join` CLI path; replace local unsigned group-log stand-ins if the phase contract requires portable signed group events. +- [ ] Resolve/document the remaining protocol questions tracked as #194, #185, #160, #183, and #195 before claiming the complete original plan. diff --git a/pkgs/id/src/commands/serve.rs b/pkgs/id/src/commands/serve.rs index 9f7d3e71bf..c0ef326ca6 100644 --- a/pkgs/id/src/commands/serve.rs +++ b/pkgs/id/src/commands/serve.rs @@ -990,7 +990,13 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { let host_key = crate::world_ssh::load_or_create_host_key(crate::world_ssh::SSH_HOST_KEY_FILE) .await?; - Some((listener, ssh_port, hub.clone(), host_key)) + Some(( + listener, + ssh_port, + hub.clone(), + host_key, + store_handle.clone(), + )) } _ => None, }; @@ -1095,14 +1101,14 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { }; #[cfg(feature = "ssh")] - let ssh_handle = ssh.map(|(listener, ssh_port, hub, host_key)| { + let ssh_handle = ssh.map(|(listener, ssh_port, hub, host_key, blobs)| { status!("world ssh: port {ssh_port} (ssh -p {ssh_port} @)"); status!( "world ssh host key: {}", crate::world_ssh::host_key_fingerprint(&host_key) ); tokio::spawn(async move { - if let Err(e) = crate::world_ssh::serve(listener, hub, host_key).await { + if let Err(e) = crate::world_ssh::serve(listener, hub, host_key, blobs).await { tracing::error!("world ssh server error: {}", e); } }) diff --git a/pkgs/id/src/web/mod.rs b/pkgs/id/src/web/mod.rs index b0e20ea1c9..b074796328 100644 --- a/pkgs/id/src/web/mod.rs +++ b/pkgs/id/src/web/mod.rs @@ -151,6 +151,8 @@ pub struct AppState { pub save_limiter: SaveRateLimiter, /// Client identity store for persistent client sessions. pub identity: IdentityStore, + /// Node-signed event log used to publish durable document revisions. + pub(crate) local_events: Arc>, /// Optional hosted world (and its invite secret) for the WebSocket bridge. pub world: Option, /// Mark the directory explorer's session cookies `Secure`. @@ -168,6 +170,7 @@ impl std::fmt::Debug for AppState { .field("tag_store", &"") .field("save_limiter", &self.save_limiter) .field("identity", &self.identity) + .field("local_events", &"") .field("world", &self.world) .field("cookie_secure", &self.cookie_secure) .finish() @@ -187,6 +190,12 @@ impl AppState { secret_key: [u8; 32], identity_db_path: std::path::PathBuf, ) -> anyhow::Result { + let events_dir = identity_db_path.with_file_name(crate::local_events::DIR_NAME); + let local_events = Arc::new(Mutex::new(crate::local_events::LocalEvents::open( + &events_dir, + p2panda_core::SigningKey::from_bytes(&secret_key), + )?)); + Ok(Self { store, collab: Arc::new(CollabState::new()), @@ -196,6 +205,7 @@ impl AppState { tag_store, save_limiter: SaveRateLimiter::new(DEFAULT_SAVE_COOLDOWN), identity: IdentityStore::new(secret_key, identity_db_path).await?, + local_events, world: None, cookie_secure: false, }) diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index 1f10ad2021..fbaeb4c259 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -932,6 +932,8 @@ struct SaveRequest { struct SaveResponse { /// New blob hash after save. hash: String, + /// The signed `document.put` event ID for this saved revision. + document_id: String, /// File name. name: String, /// Archive tag name (if original was archived). @@ -1030,8 +1032,8 @@ struct DownloadRequest { /// Save the current editor document to the blob store. /// /// Converts the `ProseMirror` JSON to the appropriate format based on filename, -/// creates a new blob, archives the original under a timestamped name, and -/// updates the tag to point to the new blob. +/// creates a new blob and signed document revision, archives the original under +/// a timestamped name, and updates the legacy filename tag to point to the new blob. /// /// Rate-limited: rejects saves within the cooldown period (default 5s) per file. async fn save_handler(State(state): State, Json(req): Json) -> Response { @@ -1067,7 +1069,7 @@ async fn save_handler(State(state): State, Json(req): Json outcome, Err(err) => { @@ -1078,6 +1080,27 @@ async fn save_handler(State(state): State, Json(req): Json published, + Err(err) => { + tracing::error!("[routes] Failed to publish saved revision: {:#}", err); + return ( + StatusCode::INTERNAL_SERVER_ERROR, + "Failed to publish document revision", + ) + .into_response(); + } + }; + let document_id = published.id.to_hex(); + // Archive the original blob under a timestamped tag let archive_name = archive_original_tag(&state.store, &req.name, &req.doc_id).await; @@ -1149,6 +1172,7 @@ async fn save_handler(State(state): State, Json(req): Json (AppState, Endpoint, Docs) { + let endpoint = Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .bind() + .await + .unwrap(); + let store: Store = MemStore::new().into(); + let gossip = Gossip::builder().spawn(endpoint.clone()); + let docs = Docs::memory() + .spawn(endpoint.clone(), store.clone(), gossip) + .await + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let tags = Arc::new( + TagStore::init_in(&docs, "save-test", dir.path().join("meta")) + .await + .unwrap(), + ); + let state = AppState::new( + store, + None, + "save-test".to_owned(), + tags, + [3; 32], + dir.path().join(".identity.redb"), + ) + .await + .unwrap(); + (state, endpoint, docs) + } + + async fn save(state: AppState, name: &str, text: &str) -> Response { + save_handler( + State(state), + Json(SaveRequest { + doc_id: iroh_blobs::Hash::from_bytes([42; 32]).to_string(), + name: name.to_owned(), + doc: json!({"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":text}]}]}), + }), + ) + .await + } + + async fn response_json(response: Response) -> serde_json::Value { + serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap() + } + + #[tokio::test] + async fn successful_save_publishes_an_applied_signed_document_and_keeps_the_blob_fetchable() { + let (mut state, _endpoint, _docs) = state().await; + state.save_limiter = SaveRateLimiter::new(Duration::ZERO); + let response = save(state.clone(), "revision.md", "first revision").await; + assert_eq!(response.status(), StatusCode::OK); + let body = response_json(response).await; + let event_id: p2panda_core::Hash = body["document_id"].as_str().unwrap().parse().unwrap(); + let history = state.local_events.lock().await.history(event_id).unwrap(); + let (author, document) = history + .iter() + .find_map(|entry| match entry { + Entry::Document { + id, + author, + document, + } if *id == event_id => Some((*author, document.clone())), + _ => None, + }) + .unwrap(); + let blob_hash = iroh_blobs::Hash::from_bytes(*document.content.as_bytes()); + assert_eq!(body["hash"].as_str().unwrap(), blob_hash.to_string()); + let bytes = state.store.blobs().get_bytes(blob_hash).await.unwrap(); + document.verify_content(&bytes).unwrap(); + assert_eq!(document.blob_hash().to_string(), blob_hash.to_string()); + assert_eq!(document.size, u64::try_from(bytes.len()).unwrap()); + assert_eq!(document.media_type, "text/markdown; charset=utf-8"); + assert_eq!( + author, + p2panda_core::SigningKey::from_bytes(&[3; 32]) + .verifying_key() + .as_bytes() + .to_owned() + ); + assert!(history.iter().any(|entry| matches!( + entry, + Entry::Set { subject, name, value: Some(value), .. } + if *subject == event_id && name == "filename" && value == "revision.md" + ))); + + // Repeated successful checkpoints get distinct durable revision events. + let second = save(state.clone(), "revision.md", "second revision").await; + assert_eq!(second.status(), StatusCode::OK); + let second_body = response_json(second).await; + assert_ne!(body["document_id"], second_body["document_id"]); + let second_id: p2panda_core::Hash = second_body["document_id"] + .as_str() + .unwrap() + .parse() + .unwrap(); + assert!(state.local_events.lock().await.history(event_id).is_ok()); + assert!(state.local_events.lock().await.history(second_id).is_ok()); + } + + #[tokio::test] + async fn refused_filename_tag_does_not_return_a_success_response() { + let (state, _endpoint, _docs) = state().await; + let response = save(state.clone(), &format!("{}.md", "x".repeat(600)), "content").await; + assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); + assert!( + state + .local_events + .lock() + .await + .frontier() + .unwrap() + .is_empty() + ); + } +} + // ============================================================================= // Identity API Handlers // ============================================================================= diff --git a/pkgs/id/src/web/templates.rs b/pkgs/id/src/web/templates.rs index f70db59368..af4247b811 100644 --- a/pkgs/id/src/web/templates.rs +++ b/pkgs/id/src/web/templates.rs @@ -793,6 +793,11 @@ pub fn render_world_page(assets: &AssetUrls) -> String { +
+ + +
+

Choose main.roc and up to 7 additional .roc files. Each file is limited to 128 KiB and all sources together to 256 KiB. Compilation runs on the host (up to 120 seconds).

Uploads run in the host's import-free Wasmtime sandbox. The current world restarts at its module seed.

diff --git a/pkgs/id/src/web/world_ws.rs b/pkgs/id/src/web/world_ws.rs index ec33ee0181..985c4a9135 100644 --- a/pkgs/id/src/web/world_ws.rs +++ b/pkgs/id/src/web/world_ws.rs @@ -1140,6 +1140,113 @@ mod tests { assert_eq!(next_frame(&mut player).await.unwrap()["data"], "count=1"); } + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn browser_websocket_can_compile_install_and_run_roc_sources() { + use iroh_blobs::store::mem::MemStore; + use std::path::PathBuf; + + let roc_bin = std::env::var("ID_ROC_BIN").ok().or_else(|| { + std::process::Command::new("roc") + .arg("version") + .output() + .ok() + .filter(|output| output.status.success()) + .map(|_| "roc".to_owned()) + }); + let Some(roc_bin) = roc_bin else { + eprintln!("skipping: no Roc compiler available (set ID_ROC_BIN or install roc)"); + return; + }; + let platform_dir = + PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/examples/roc-world")); + if !platform_dir.join("targets/wasm32/host.wasm").is_file() { + eprintln!( + "skipping: Roc world platform assets unavailable (run examples/roc-world/build-host.sh)" + ); + return; + } + let compiler = crate::world_compile::Compiler::new(platform_dir, roc_bin).unwrap(); + let source = std::fs::read_to_string(concat!( + env!("CARGO_MANIFEST_DIR"), + "/examples/roc-counter/main.roc" + )) + .unwrap(); + let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); + let blobs: iroh_blobs::api::Store = MemStore::new().into(); + let service = WorldService::new(world.clone(), Some("admin".to_owned())) + .with_blob_store(blobs.clone()) + .with_compiler(compiler); + let addr = serve(world_routes().with_state(WorldWebState { + hub: Some(WorldHub::single(service)), + cookie_secure: false, + })) + .await; + let (mut uploader, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/ws/world")) + .await + .unwrap(); + uploader + .send(ClientMessage::Text( + serde_json::json!({ + "type": "compile", + "admin_token": "admin", + "files": [{ "name": "main.roc", "content": source }], + "seed": 99, + "native": false, + }) + .to_string() + .into(), + )) + .await + .unwrap(); + let compiled = next_frame(&mut uploader).await.unwrap(); + assert_eq!(compiled["type"], "compiled", "{compiled}"); + let hash: iroh_blobs::Hash = compiled["module_hash"].as_str().unwrap().parse().unwrap(); + assert!(blobs.blobs().has(hash).await.unwrap()); + + let (_, capability) = world + .issue("browser".to_owned(), crate::world::WorldScopes::GUEST) + .await + .unwrap(); + let mut player = connect(addr, join(&capability, None)).await; + assert_eq!(next_frame(&mut player).await.unwrap()["type"], "snapshot"); + assert_eq!(next_frame(&mut player).await.unwrap()["data"], "count=0"); + player + .send(ClientMessage::Text( + r#"{"type":"input","data_hex":"696e63"}"#.into(), + )) + .await + .unwrap(); + assert_eq!(next_frame(&mut player).await.unwrap()["type"], "event"); + assert_eq!(next_frame(&mut player).await.unwrap()["data"], "count=1"); + } + + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn browser_websocket_rejects_roc_compile_without_admin_auth() { + let addr = serve(app(Some(lobby()), Some("admin"))).await; + let (mut client, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/ws/world")) + .await + .unwrap(); + client + .send(ClientMessage::Text( + serde_json::json!({ + "type": "compile", + "admin_token": "wrong", + "files": [{ "name": "main.roc", "content": "app [main!] { pf: platform \"x\" }" }], + "seed": 1, + "native": false, + }) + .to_string() + .into(), + )) + .await + .unwrap(); + let denied = next_frame(&mut client).await.unwrap(); + assert_eq!(denied["type"], "error"); + assert_eq!(denied["message"], "compile denied"); + } + #[tokio::test] async fn revoked_idle_participant_is_disconnected_immediately() { let world = lobby(); diff --git a/pkgs/id/src/world_session.rs b/pkgs/id/src/world_session.rs index 989e8b0b9e..a533502775 100644 --- a/pkgs/id/src/world_session.rs +++ b/pkgs/id/src/world_session.rs @@ -923,6 +923,7 @@ fn frame_admin_token(frame: &ClientFrame) -> Option<&str> { match frame { ClientFrame::Invite { admin_token, .. } | ClientFrame::InstallBegin { admin_token, .. } + | ClientFrame::Compile { admin_token, .. } | ClientFrame::CreateWorld { admin_token } | ClientFrame::ListWorlds { admin_token } => Some(admin_token), _ => None, diff --git a/pkgs/id/src/world_ssh.rs b/pkgs/id/src/world_ssh.rs index b78f717c02..64d21dafe1 100644 --- a/pkgs/id/src/world_ssh.rs +++ b/pkgs/id/src/world_ssh.rs @@ -5,8 +5,9 @@ //! `view` frame repaints the terminal, so an ordinary `ssh` client can play any //! world that presents a view. -use std::{fmt::Write as _, net::SocketAddr, sync::Arc, time::Duration}; +use std::{collections::VecDeque, fmt::Write as _, net::SocketAddr, sync::Arc, time::Duration}; +use futures_lite::StreamExt; use russh::{ Channel, ChannelId, ChannelOpenFailure, MethodKind, MethodSet, Pty, keys::{Algorithm, PrivateKey, PublicKey, ssh_key::HashAlg, ssh_key::LineEnding}, @@ -24,7 +25,7 @@ use crate::directory_view::{ }; use crate::world::hex_encode; use crate::world_hub::{ResolveError, WorldHub}; -use crate::world_session::{Inbound, SessionIo, encode_hex, run_session}; +use crate::world_session::{Inbound, SessionIo, run_session}; /// File, beside the other server keys, that holds the SSH host key. pub const SSH_HOST_KEY_FILE: &str = ".ssh-host-key"; @@ -47,14 +48,16 @@ pub async fn serve( listener: TcpListener, hub: WorldHub, host_key: PrivateKey, + blobs: iroh_blobs::api::Store, ) -> std::io::Result<()> { - serve_limited(listener, hub, host_key, MAX_CONNECTIONS).await + serve_limited(listener, hub, host_key, blobs, MAX_CONNECTIONS).await } async fn serve_limited( listener: TcpListener, hub: WorldHub, host_key: PrivateKey, + blobs: iroh_blobs::api::Store, max_connections: usize, ) -> std::io::Result<()> { let config = Arc::new(Config { @@ -66,6 +69,7 @@ async fn serve_limited( }); let mut server = SshServer { hub, + blobs, connections: Arc::new(Semaphore::new(max_connections)), }; server.run_on_socket(config, &listener).await @@ -93,6 +97,7 @@ pub async fn load_or_create_host_key(path: &str) -> anyhow::Result { #[derive(Clone)] struct SshServer { hub: WorldHub, + blobs: iroh_blobs::api::Store, connections: Arc, } @@ -102,6 +107,7 @@ impl Server for SshServer { fn new_client(&mut self, _peer: Option) -> SshClient { SshClient { hub: self.hub.clone(), + blobs: self.blobs.clone(), permit: Arc::clone(&self.connections).try_acquire_owned().ok(), login: None, input: None, @@ -119,6 +125,7 @@ struct Login { struct SshClient { hub: WorldHub, + blobs: iroh_blobs::api::Store, permit: Option, login: Option, input: Option>>, @@ -267,7 +274,12 @@ impl Handler for SshClient { handle: session.handle(), channel, frames, + blobs: self.blobs.clone(), first: Some(first), + capability: login.capability.clone(), + lines: WorldLineBuffer::default(), + commands: VecDeque::new(), + records_prefix: None, errored: false, }; let hub = self.hub.clone(); @@ -330,13 +342,19 @@ fn join_frame(login: &Login) -> String { join.to_string() } -/// [`SessionIo`] for one SSH shell: the join frame first, then keystrokes in, -/// and terminal output for each view out. +/// [`SessionIo`] for one SSH shell: the join frame first, then terminal lines +/// as chat/command frames, and terminal output for each view or record page. struct SshIo { handle: Handle, channel: ChannelId, frames: mpsc::Receiver>, + blobs: iroh_blobs::api::Store, first: Option, + capability: String, + lines: WorldLineBuffer, + commands: VecDeque, + /// `Some(prefix)` while draining records pages from a `/records` command. + records_prefix: Option>, errored: bool, } @@ -345,11 +363,87 @@ impl SessionIo for SshIo { if let Some(join) = self.first.take() { return Inbound::Text(join); } - match self.frames.recv().await { - Some(bytes) => Inbound::Text( - json!({ "type": "input", "data_hex": encode_hex(&bytes) }).to_string(), - ), - None => Inbound::Closed, + loop { + if let Some(command) = self.commands.pop_front() { + match command { + WorldCommand::Chat(text) => { + return Inbound::Text(json!({ "type": "chat", "text": text }).to_string()); + } + WorldCommand::Input(data_hex) => { + return Inbound::Text( + json!({ "type": "input", "data_hex": data_hex }).to_string(), + ); + } + WorldCommand::Records { prefix } => { + self.records_prefix = Some(prefix.clone()); + return Inbound::Text( + json!({ + "type": "records", "capability": self.capability, + "prefix": prefix, "after": null + }) + .to_string(), + ); + } + WorldCommand::Documents { prefix } => { + let text = match list_public_documents(&self.blobs, prefix.as_deref()).await + { + Ok(text) => text, + Err(_) => "documents unavailable".to_owned(), + }; + if self + .handle + .data( + self.channel, + terminal_text(&format!("\r\n{text}\r\nworld> ")), + ) + .await + .is_err() + { + return Inbound::Closed; + } + } + WorldCommand::Document(name) => { + let text = match read_public_document(&self.blobs, &name).await { + Ok(text) => format!("\r\n{text}\r\nworld> "), + Err(error) => format!("\r\n{}\r\nworld> ", error.message()), + }; + if self + .handle + .data(self.channel, terminal_text(&text)) + .await + .is_err() + { + return Inbound::Closed; + } + } + WorldCommand::RecordsContinue { prefix, after } => { + return Inbound::Text( + json!({ + "type": "records", "capability": self.capability, + "prefix": prefix, "after": after + }) + .to_string(), + ); + } + WorldCommand::Help => { + let help = "World chat: type a line to chat. Commands: /input , /records [prefix], /documents [prefix], /document , /help, /quit\r\n"; + if self.handle.data(self.channel, help).await.is_err() { + return Inbound::Closed; + } + } + WorldCommand::Message(message) => { + let text = format!("{message}\r\n"); + if self.handle.data(self.channel, text).await.is_err() { + return Inbound::Closed; + } + } + WorldCommand::Quit => return Inbound::Closed, + } + } + let Some(bytes) = self.frames.recv().await else { + return Inbound::Closed; + }; + self.commands.extend(self.lines.push(&bytes)); } } @@ -358,21 +452,378 @@ impl SessionIo for SshIo { return true; }; let text = match value["type"].as_str() { + Some("snapshot") => { + "World chat: type a line to chat; /help lists commands.\r\nworld> ".to_owned() + } Some("view") => match value["data"].as_str() { - Some(data) => format!("\x1b[H\x1b[2J{}", terminal_text(data)), + Some(data) => format!( + "\x1b[H\x1b[2J{}\r\nType a line to chat; /help lists commands.\r\nworld> ", + terminal_text(data) + ), None => return true, }, Some("error") => { self.errored = true; + self.records_prefix = None; let message = value["message"].as_str().unwrap_or("error"); format!("\r\n{}\r\n", terminal_text(message)) } + Some("records") => { + let records = value["records"].as_object(); + let sequence = value["sequence"].as_u64().unwrap_or_default(); + let after = value["next_after"].as_str().map(str::to_owned); + let text = render_records_value(records, sequence, after.as_deref()); + if let (Some(prefix), Some(after)) = (self.records_prefix.clone(), after) { + self.commands + .push_back(WorldCommand::RecordsContinue { prefix, after }); + } else { + self.records_prefix = None; + } + format!("\r\n{}", terminal_text(&text)) + } _ => return true, }; self.handle.data(self.channel, text).await.is_ok() } } +const MAX_WORLD_TERMINAL_LINE: usize = 1024; +const MAX_RECORDS_TERMINAL_BYTES: usize = 384 * 1024; +const MAX_DOCUMENT_BYTES: usize = 64 * 1024; +const MAX_DOCUMENT_LIST_BYTES: usize = 32 * 1024; +const MAX_DOCUMENT_LIST_ITEMS: usize = 512; + +#[derive(Debug, PartialEq, Eq)] +enum WorldCommand { + Chat(String), + Input(String), + Records { + prefix: Option, + }, + RecordsContinue { + prefix: Option, + after: String, + }, + Documents { + prefix: Option, + }, + Document(String), + Help, + Message(String), + Quit, +} + +fn world_command(line: &str) -> Option { + if line.is_empty() { + return None; + } + if line == "/help" { + return Some(WorldCommand::Help); + } + if line == "/quit" { + return Some(WorldCommand::Quit); + } + if line == "/records" || line.starts_with("/records ") { + let Some(prefix) = line.strip_prefix("/records") else { + return Some(WorldCommand::Message("usage: /records [prefix]".to_owned())); + }; + let prefix = prefix.trim(); + return Some(WorldCommand::Records { + prefix: (!prefix.is_empty()).then(|| prefix.to_owned()), + }); + } + if line == "/documents" || line.starts_with("/documents ") { + let Some(prefix) = line.strip_prefix("/documents") else { + return Some(WorldCommand::Message( + "usage: /documents [prefix]".to_owned(), + )); + }; + let prefix = prefix.trim(); + return Some(WorldCommand::Documents { + prefix: (!prefix.is_empty()).then(|| prefix.to_owned()), + }); + } + if let Some(name) = line.strip_prefix("/document ") { + if !name.is_empty() && name == name.trim() { + return Some(WorldCommand::Document(name.to_owned())); + } + return Some(WorldCommand::Message("usage: /document ".to_owned())); + } + if let Some(hex) = line.strip_prefix("/input ") { + if !hex.is_empty() && hex.len() % 2 == 0 && hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return Some(WorldCommand::Input(hex.to_ascii_lowercase())); + } + return Some(WorldCommand::Message("usage: /input ".to_owned())); + } + if line.starts_with('/') { + return Some(WorldCommand::Message( + "unknown command; type /help".to_owned(), + )); + } + Some(WorldCommand::Chat(line.to_owned())) +} + +#[derive(Default)] +struct WorldLineBuffer { + line: Vec, + overflow: bool, + after_cr: bool, + escape: WorldEscape, +} + +#[derive(Default)] +enum WorldEscape { + #[default] + None, + Start, + Sequence, + Osc, + OscEscape, + String, + StringEscape, +} + +impl WorldLineBuffer { + fn push(&mut self, packet: &[u8]) -> Vec { + let mut commands = Vec::new(); + for &byte in packet { + match self.escape { + WorldEscape::Start => { + self.escape = match byte { + b'[' | b'O' => WorldEscape::Sequence, + b']' => WorldEscape::Osc, + b'P' | b'_' | b'^' => WorldEscape::String, + _ => WorldEscape::None, + }; + continue; + } + WorldEscape::Sequence => { + if (0x40..=0x7e).contains(&byte) { + self.escape = WorldEscape::None; + } + continue; + } + WorldEscape::Osc => { + if byte == 0x07 { + self.escape = WorldEscape::None; + } else if byte == 0x1b { + self.escape = WorldEscape::OscEscape; + } + continue; + } + WorldEscape::OscEscape => { + self.escape = if byte == b'\\' { + WorldEscape::None + } else { + WorldEscape::Osc + }; + continue; + } + WorldEscape::String => { + if byte == 0x1b { + self.escape = WorldEscape::StringEscape; + } + continue; + } + WorldEscape::StringEscape => { + self.escape = if byte == b'\\' { + WorldEscape::None + } else { + WorldEscape::String + }; + continue; + } + WorldEscape::None => {} + } + if byte == 0x1b { + self.escape = WorldEscape::Start; + continue; + } + let after_cr = std::mem::take(&mut self.after_cr); + if byte == b'\n' && after_cr { + continue; + } + if byte == b'\r' || byte == b'\n' { + self.after_cr = byte == b'\r'; + if !self.overflow { + let bytes = std::mem::take(&mut self.line); + let line = String::from_utf8_lossy(&bytes); + if let Some(command) = world_command(&line) { + commands.push(command); + } + } else { + self.line.clear(); + } + self.overflow = false; + continue; + } + if byte == 0x03 || (byte == 0x04 && self.line.is_empty()) { + commands.push(WorldCommand::Quit); + } else if matches!(byte, 0x7f | 0x08) { + self.line.pop(); + } else if (0x20..=0x7e).contains(&byte) || byte >= 0x80 { + if self.line.len() < MAX_WORLD_TERMINAL_LINE && !self.overflow { + self.line.push(byte); + } else { + self.overflow = true; + self.line.clear(); + } + } + } + commands + } +} + +fn render_records_value( + records: Option<&serde_json::Map>, + sequence: u64, + next_after: Option<&str>, +) -> String { + let mut output = format!("records at sequence {sequence}:\n"); + if let Some(records) = records { + for (key, value) in records { + let key = serde_json::to_string(key).unwrap_or_else(|_| "\"?\"".to_owned()); + let value = serde_json::to_string(value).unwrap_or_else(|_| "null".to_owned()); + let line = format!("{key} = {value}\n"); + if output.len() + line.len() + 32 > MAX_RECORDS_TERMINAL_BYTES { + output.push_str("[page display truncated]\n"); + break; + } + output.push_str(&line); + } + } + if next_after.is_some() { + output.push_str("more records; fetching next page\n"); + } + output +} + +#[cfg(test)] +fn render_records( + records: &crate::world::Records, + sequence: u64, + next_after: Option<&str>, +) -> String { + let value = serde_json::to_value(records).ok(); + render_records_value( + value.as_ref().and_then(serde_json::Value::as_object), + sequence, + next_after, + ) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum DocumentError { + InvalidName, + Missing, + TooLarge, + Binary, + Unavailable, +} + +impl DocumentError { + const fn message(self) -> &'static str { + match self { + Self::InvalidName => "document name must be a public .txt, .md, or .markdown tag", + Self::Missing => "document not found", + Self::TooLarge => "document exceeds the 64 KiB SSH viewing limit", + Self::Binary => "document is not valid UTF-8 text", + Self::Unavailable => "document unavailable", + } + } +} + +fn is_viewable_document_name(name: &str) -> bool { + if !is_public_document_name(name) { + return false; + } + let lower = name.to_ascii_lowercase(); + lower.ends_with(".md") || lower.ends_with(".markdown") || lower.ends_with(".txt") +} + +async fn list_public_documents( + store: &iroh_blobs::api::Store, + prefix: Option<&str>, +) -> anyhow::Result { + let mut tags = store.tags().list().await?; + let mut names = Vec::new(); + let mut total_bytes = 0usize; + let mut truncated = false; + while let Some(item) = tags.next().await { + let item = item?; + let Ok(name) = std::str::from_utf8(item.name.as_ref()) else { + continue; + }; + if !is_public_document_name(name) || prefix.is_some_and(|p| !name.starts_with(p)) { + continue; + } + let line = format!("{name}\n"); + if names.len() >= MAX_DOCUMENT_LIST_ITEMS + || total_bytes + line.len() > MAX_DOCUMENT_LIST_BYTES + { + truncated = true; + break; + } + total_bytes += line.len(); + names.push(name.to_owned()); + } + names.sort(); + let mut output = String::from("public named files:\n"); + if names.is_empty() { + output.push_str("(none)\n"); + } else { + for name in names { + output.push_str(&name); + output.push('\n'); + } + } + if truncated { + output.push_str("[listing truncated]\n"); + } + output.push_str("View UTF-8 .txt/.md/.markdown files with /document .\n"); + Ok(output) +} + +fn is_public_document_name(name: &str) -> bool { + !name.is_empty() + && !crate::tags::is_internal_tag(name) + && !name.contains('/') + && !name.contains('\\') + && !name.chars().any(char::is_control) +} + +async fn read_public_document( + store: &iroh_blobs::api::Store, + name: &str, +) -> Result { + if !is_viewable_document_name(name) { + return Err(DocumentError::InvalidName); + } + let tag = store + .tags() + .get(name) + .await + .map_err(|_| DocumentError::Unavailable)? + .ok_or(DocumentError::Missing)?; + let size = match store.blobs().status(tag.hash).await { + Ok(iroh_blobs::api::blobs::BlobStatus::Complete { size }) => size, + _ => return Err(DocumentError::Unavailable), + }; + if size > MAX_DOCUMENT_BYTES as u64 { + return Err(DocumentError::TooLarge); + } + let bytes = store + .blobs() + .get_bytes(tag.hash) + .await + .map_err(|_| DocumentError::Unavailable)?; + if bytes.len() > MAX_DOCUMENT_BYTES { + return Err(DocumentError::TooLarge); + } + let text = std::str::from_utf8(&bytes).map_err(|_| DocumentError::Binary)?; + Ok(format!("--- {name} ({size} bytes; read-only) ---\n{text}")) +} + /// One explorer login: the world, the caller it acts as, and the secret it /// leases the world with. Sign-in changes the caller for the rest of the login. struct Explorer { @@ -650,11 +1101,12 @@ mod tests { } async fn start(hub: WorldHub) -> (u16, tokio::task::JoinHandle>) { - start_limited(hub, MAX_CONNECTIONS).await + start_limited(hub, test_store(), MAX_CONNECTIONS).await } async fn start_limited( hub: WorldHub, + blobs: iroh_blobs::api::Store, max_connections: usize, ) -> (u16, tokio::task::JoinHandle>) { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -662,10 +1114,27 @@ mod tests { let host_key = PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519).unwrap(); ( port, - tokio::spawn(serve_limited(listener, hub, host_key, max_connections)), + tokio::spawn(serve_limited( + listener, + hub, + host_key, + blobs, + max_connections, + )), ) } + async fn start_with_store( + hub: WorldHub, + blobs: iroh_blobs::api::Store, + ) -> (u16, tokio::task::JoinHandle>) { + start_limited(hub, blobs, MAX_CONNECTIONS).await + } + + fn test_store() -> iroh_blobs::api::Store { + iroh_blobs::store::mem::MemStore::new().into() + } + async fn connect(port: u16, password: &str) -> client::Handle { connect_as(port, "", password).await } @@ -926,7 +1395,12 @@ mod tests { } }) .await - .expect("timed out waiting for the terminal"); + .unwrap_or_else(|_| { + panic!( + "timed out waiting for {needle:?}; screen: {:?}", + terminal.screen().contents() + ) + }); } fn lobby_hub() -> WorldHub { @@ -945,9 +1419,55 @@ mod tests { server.abort(); } + #[tokio::test] + async fn a_shell_accepts_chat_and_reads_authorized_records_pages() { + let hub = lobby_hub(); + let world = hub + .lease(None, Some("admin")) + .await + .unwrap() + .service() + .world() + .clone(); + let mut events = world.subscribe(); + let invite = hub + .lease(None, Some("admin")) + .await + .unwrap() + .service() + .invite(Some("admin"), "ssh-chat".to_owned(), None, None) + .await + .unwrap(); + let capability = serde_json::to_value(invite).unwrap()["capability"] + .as_str() + .unwrap() + .to_owned(); + let (port, server) = start(hub).await; + let session = connect(port, &capability).await; + let mut channel = shell(&session).await; + let mut terminal = vt100::Parser::new(24, 80, 0); + read_until(&mut channel, &mut terminal, "world>").await; + + channel.data(&b"hello from SSH\r"[..]).await.unwrap(); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + if let Ok(event) = events.recv().await { + if matches!(event.kind, crate::world::WorldEventKind::Chat { .. }) { + break; + } + } + } + }) + .await + .expect("chat line was not sent to the world"); + channel.data(&b"/records\r"[..]).await.unwrap(); + read_until(&mut channel, &mut terminal, "records at sequence").await; + server.abort(); + } + #[tokio::test] async fn connections_over_the_limit_are_refused_at_auth() { - let (port, server) = start_limited(lobby_hub(), 1).await; + let (port, server) = start_limited(lobby_hub(), test_store(), 1).await; let _first = connect(port, &"0".repeat(64)).await; let config = Arc::new(client::Config::default()); @@ -972,6 +1492,184 @@ mod tests { ); } + #[test] + fn world_line_buffer_handles_fragmented_packets_and_crlf_once() { + let mut input = WorldLineBuffer::default(); + assert!(input.push(b"hel").is_empty()); + assert_eq!( + input.push(b"lo\r"), + vec![WorldCommand::Chat("hello".into())] + ); + assert!(input.push(b"\n").is_empty()); + assert_eq!( + input.push(b"next\n"), + vec![WorldCommand::Chat("next".into())] + ); + } + + #[test] + fn world_lines_map_commands_without_echoing_or_treating_empty_as_chat() { + assert_eq!(world_command(""), None); + assert_eq!( + world_command("hi there"), + Some(WorldCommand::Chat("hi there".into())) + ); + assert_eq!( + world_command("/input 00aF"), + Some(WorldCommand::Input("00af".into())) + ); + assert_eq!( + world_command("/records abc"), + Some(WorldCommand::Records { + prefix: Some("abc".into()) + }) + ); + assert_eq!( + world_command("/documents notes"), + Some(WorldCommand::Documents { + prefix: Some("notes".into()) + }) + ); + assert_eq!( + world_command("/document notes.md"), + Some(WorldCommand::Document("notes.md".into())) + ); + assert_eq!(world_command("/help"), Some(WorldCommand::Help)); + assert_eq!(world_command("/quit"), Some(WorldCommand::Quit)); + assert_eq!( + world_command("/input nope"), + Some(WorldCommand::Message("usage: /input ".into())) + ); + } + + #[test] + fn world_line_buffer_discards_overlong_line_until_newline() { + let mut input = WorldLineBuffer::default(); + assert!(input.push(&vec![b'x'; MAX_LINE + 1]).is_empty()); + assert_eq!( + input.push(b"tail\nokay\n"), + vec![WorldCommand::Chat("okay".into())] + ); + } + + #[test] + fn world_line_buffer_drops_fragmented_terminal_control_strings() { + let mut input = WorldLineBuffer::default(); + assert!(input.push(b"safe\x1b]52;c;secret").is_empty()); + assert_eq!( + input.push(b"\x07still safe\r\n"), + vec![WorldCommand::Chat("safestill safe".into())] + ); + } + + #[test] + fn records_render_as_bounded_json_safe_terminal_text() { + let records: crate::world::Records = + serde_json::from_str(r#"{"a\u001b[31m":{"n":1},"b":"line\nvalue"}"#).unwrap(); + let text = render_records(&records, 7, Some("b")); + assert!(text.contains("sequence 7")); + assert!(text.contains("\"a\\u001b[31m\" = {\"n\":1}")); + assert!(text.contains("\"b\" = \"line\\nvalue\"")); + assert!(text.contains("more records; fetching next page")); + assert!(text.len() <= MAX_RECORDS_TERMINAL_BYTES); + } + + async fn put_document(store: &iroh_blobs::api::Store, name: &str, bytes: Vec) { + let outcome = store.blobs().add_bytes(bytes).await.unwrap(); + store.tags().set(name, outcome.hash).await.unwrap(); + } + + #[tokio::test] + async fn document_reader_limits_names_sizes_and_binary_content() { + let store = test_store(); + put_document(&store, "notes.md", b"# hello\ntext".to_vec()).await; + put_document(&store, "image.txt", vec![0xff, 0x00]).await; + put_document(&store, "large.txt", vec![b'x'; MAX_DOCUMENT_BYTES + 1]).await; + put_document(&store, ".private.md", b"hidden".to_vec()).await; + put_document(&store, "evil\nworld.md", b"terminal injection".to_vec()).await; + put_document(&store, "résumé.md", b"unicode ok".to_vec()).await; + assert!( + read_public_document(&store, "notes.md") + .await + .unwrap() + .contains("# hello") + ); + assert_eq!( + read_public_document(&store, "missing.md").await, + Err(DocumentError::Missing) + ); + assert_eq!( + read_public_document(&store, "image.txt").await, + Err(DocumentError::Binary) + ); + assert_eq!( + read_public_document(&store, "large.txt").await, + Err(DocumentError::TooLarge) + ); + assert_eq!( + read_public_document(&store, ".private.md").await, + Err(DocumentError::InvalidName) + ); + assert_eq!( + read_public_document(&store, "../notes.md").await, + Err(DocumentError::InvalidName) + ); + assert_eq!( + read_public_document(&store, "evil\nworld.md").await, + Err(DocumentError::InvalidName) + ); + assert!( + read_public_document(&store, "résumé.md") + .await + .unwrap() + .contains("unicode ok") + ); + let listing = list_public_documents(&store, Some("notes")).await.unwrap(); + assert!(listing.contains("notes.md")); + assert!(!listing.contains(".private.md")); + assert!(!listing.contains("image.txt")); + let all = list_public_documents(&store, None).await.unwrap(); + assert!(all.contains("résumé.md")); + assert!(!all.contains("evil\nworld.md")); + } + + #[tokio::test] + async fn a_shell_lists_and_views_read_only_documents_from_its_server_store() { + let store = test_store(); + put_document( + &store, + "guide.md", + b"# SSH guide\nhello\x1b[2Jworld".to_vec(), + ) + .await; + put_document(&store, ".internal.md", b"hidden".to_vec()).await; + let hub = lobby_hub(); + let invite = hub + .lease(None, Some("admin")) + .await + .unwrap() + .service() + .invite(Some("admin"), "ssh-docs".to_owned(), None, None) + .await + .unwrap(); + let capability = serde_json::to_value(invite).unwrap()["capability"] + .as_str() + .unwrap() + .to_owned(); + let (port, server) = start_with_store(hub, store).await; + let session = connect(port, &capability).await; + let mut channel = shell(&session).await; + let mut terminal = vt100::Parser::new(24, 80, 0); + read_until(&mut channel, &mut terminal, "world>").await; + channel.data(&b"/documents guide\r"[..]).await.unwrap(); + read_until(&mut channel, &mut terminal, "guide.md").await; + assert!(!terminal.screen().contents().contains(".internal.md")); + channel.data(&b"/document guide.md\r"[..]).await.unwrap(); + read_until(&mut channel, &mut terminal, "# SSH guide").await; + assert!(!terminal.screen().contents().contains("\x1b[2J")); + server.abort(); + } + #[cfg(feature = "sandbox")] #[tokio::test] async fn a_shell_plays_the_world_and_repaints_each_view() { @@ -1005,7 +1703,7 @@ mod tests { let mut channel = shell(&session).await; let mut terminal = vt100::Parser::new(24, 80, 0); read_until(&mut channel, &mut terminal, "count=0").await; - channel.data(&b"inc"[..]).await.unwrap(); + channel.data(&b"/input 696e63\r"[..]).await.unwrap(); read_until(&mut channel, &mut terminal, "count=1").await; server.abort(); } diff --git a/pkgs/id/web/src/world.ts b/pkgs/id/web/src/world.ts index ad0bfba3ea..650b736180 100644 --- a/pkgs/id/web/src/world.ts +++ b/pkgs/id/web/src/world.ts @@ -1,7 +1,16 @@ /** Browser presentation for the server-authoritative world session. */ type WorldFrame = { - type: "snapshot" | "event" | "view" | "records" | "invite" | "upload_ready" | "module_installed" | "error"; + type: + | "snapshot" + | "event" + | "view" + | "records" + | "invite" + | "upload_ready" + | "module_installed" + | "compiled" + | "error"; snapshot?: { world_id: string; current_sequence: number; @@ -20,6 +29,7 @@ type WorldFrame = { next_after?: string | null; chunk_bytes?: number; module_hash?: string; + diagnostics?: string; participant_id?: number; display_name?: string; message?: string; @@ -47,8 +57,10 @@ function initWorld(): void { const capability = element(root, "[data-world-capability]"); const inviteButton = element(root, "[data-world-invite]"); const moduleInput = element(root, "[data-world-module]"); + const sourceInput = element(root, "[data-world-source]"); const moduleSeed = element(root, "[data-world-seed]"); const installButton = element(root, "[data-world-install]"); + const compileButton = element(root, "[data-world-compile]"); const joinButton = element(root, "[data-world-join]"); const chatForm = element(root, "[data-world-chat-form]"); const chatInput = element(root, "[data-world-chat]"); @@ -70,8 +82,10 @@ function initWorld(): void { !worldInput || !inviteButton || !moduleInput || + !sourceInput || !moduleSeed || !installButton || + !compileButton || !joinButton || !chatForm || !chatInput || @@ -356,6 +370,101 @@ function initWorld(): void { }); }); + compileButton.addEventListener("click", async () => { + const secret = admin.value; + const selected = Array.from(sourceInput.files ?? []); + if (!secret) { + setStatus("Enter the world admin token to compile Roc sources", "error"); + return; + } + if (selected.length === 0) { + setStatus("Choose a .roc source set with main.roc first", "error"); + return; + } + if (selected.length > 8) { + setStatus("A compile request can contain at most 8 files", "error"); + return; + } + const ordered = [...selected].sort((a, b) => + a.name === "main.roc" ? -1 : b.name === "main.roc" ? 1 : a.name.localeCompare(b.name), + ); + if (ordered[0]?.name !== "main.roc") { + setStatus("Select main.roc; it must be the first compile file", "error"); + return; + } + const files: Array<{ name: string; content: string }> = []; + let totalBytes = 0; + const names = new Set(); + for (const file of ordered) { + if (!/^(?!\.)[A-Za-z0-9._-]{1,60}\.roc$/.test(file.name)) { + setStatus(`${file.name} is not a safe .roc filename`, "error"); + return; + } + if (names.has(file.name)) { + setStatus(`The source set contains more than one ${file.name}`, "error"); + return; + } + names.add(file.name); + if (file.size > 128 * 1024) { + setStatus(`${file.name} exceeds 128 KiB`, "error"); + return; + } + totalBytes += file.size; + if (totalBytes > 256 * 1024) { + setStatus("Roc sources exceed the 256 KiB total limit", "error"); + return; + } + files.push({ name: file.name, content: await file.text() }); + } + const seed = Number(moduleSeed.value); + if (!Number.isSafeInteger(seed) || seed < 0) { + setStatus("Seed must be a non-negative safe integer", "error"); + return; + } + compileButton.disabled = true; + setStatus(`Reading ${files.length} Roc source file${files.length === 1 ? "" : "s"} (${totalBytes} bytes)…`); + const scheme = location.protocol === "https:" ? "wss:" : "ws:"; + const compiler = new WebSocket(`${scheme}//${location.host}/ws/world`); + compiler.addEventListener("open", () => { + setStatus("Sources sent; compiling and installing on the host…"); + compiler.send( + JSON.stringify({ + type: "compile", + admin_token: secret, + files, + seed, + native: false, + world: selectedWorld(), + }), + ); + }); + compiler.addEventListener("message", (message) => { + let frame: WorldFrame; + try { + frame = JSON.parse(String(message.data)) as WorldFrame; + } catch { + setStatus("Host returned an invalid compile response", "error"); + compiler.close(); + return; + } + if (frame.type === "error") { + setStatus(frame.message ?? "Roc compilation failed", "error"); + appendLine(log, `compile error: ${frame.message ?? "Roc compilation failed"}`); + compiler.close(); + } else if (frame.type === "compiled") { + setStatus(`Roc program installed: ${frame.module_hash ?? "ok"}`, "good"); + appendLine(log, `Roc program installed ${frame.module_hash ?? ""}`); + if (frame.diagnostics) appendLine(log, frame.diagnostics); + admin.value = ""; + compiler.close(); + } + }); + compiler.addEventListener("error", () => setStatus("Roc compile connection failed", "error")); + compiler.addEventListener("close", () => { + compileButton.disabled = false; + }); + }); + joinButton.addEventListener("click", () => { if (socket) { intentionalClose = true;