diff --git a/README.md b/README.md
index d8cb388..0178bbc 100644
--- a/README.md
+++ b/README.md
@@ -4,6 +4,8 @@ A repository of experimental Tentacles for Cthulhu, maintained by Storm
Dragon. It contains [Hello World](hello-world/README.md), the development
[Wormhole tentacle](wormhole/README.md), and
[Battery Status](battery-status/README.md).
+The [Remote implementation](remote/README.md) is in progress as a tested relay
+library; it is not yet installable or able to control a desktop.
Repository material and these Tentacles are licensed under GPL-3.0-or-later; see
[LICENSE](LICENSE) and [CONTRIBUTING.md](CONTRIBUTING.md).
diff --git a/go.mod b/go.mod
index a6f2069..9e324e7 100644
--- a/go.mod
+++ b/go.mod
@@ -6,6 +6,8 @@ require git.stormux.org/storm/cthulhu v0.0.0
require github.com/godbus/dbus/v5 v5.1.0
+require github.com/pelletier/go-toml/v2 v2.4.3
+
// The experimental SDK is developed alongside this repository.
replace git.stormux.org/storm/cthulhu => ../cthulhu
diff --git a/go.sum b/go.sum
index 024b269..9eba027 100644
--- a/go.sum
+++ b/go.sum
@@ -1,2 +1,4 @@
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
+github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
+github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
diff --git a/remote.md b/remote.md
new file mode 100644
index 0000000..4a59e3d
--- /dev/null
+++ b/remote.md
@@ -0,0 +1,859 @@
+# Cthulhu Remote implementation plan
+
+Status: implementation started; remote control is not yet available.
+Research date: 2026-11-03. Unchecked checklist items describe future work. API
+names and limits below remain proposed contracts unless an implementation
+increment explicitly records them as implemented and tested.
+
+First implementation increment (2026-11-03):
+`cthulhu-tentacles/remote/src` contains a bounded NVDA-v2 codec, TLS transport,
+one-peer session validation and private protocol/transport tests. See
+[implementation status](remote/README.md) and
+[the relay contract](remote/protocol.md). This is a source
+library, not an installable Tentacle. Phase A remains open: fixtures are synthetic
+source-derived examples, and production Xorg crash recovery/virtual Braille
+feasibility had not been demonstrated. At that increment, reader protocol 1.1,
+desktop integration and live interoperability remained unimplemented/unverified; the fifth increment below
+now supplies the protocol 1.1 lifecycle foundation. No release gate is complete.
+
+Second implementation increment (2026-11-03): the reader's transient forms now
+support secret entries, including masked editing/speech/Braille, blocked copy/cut,
+explicit paste, and values returned only on successful submission. Persistent
+preference pages reject secrets. Both SDKs have IPC conformance coverage and the
+private Xorg form harness exercises the keyboard and clipboard behavior. See
+[the secret-entry contract](../cthulhu/docs/tentacle-secret-entries.md).
+Audible speech and physical Braille acceptance remain pending. This prerequisite
+does not add Remote connection controls or complete Phase B.
+
+Third implementation increment (2026-11-03): an isolated Xorg input feasibility
+harness now demonstrates exclusive capture, grab release after owner SIGKILL,
+and independent injected-key cleanup on writer death or three-second heartbeat
+expiry. It also confirms XTEST connection closure alone leaves keys held and
+current input events cannot establish local origin. Already-held collisions are
+rejected in the prototype; later same-code collisions remain unresolved. See
+[the evidence and limitations](../cthulhu/docs/testing/remote-input-feasibility.md).
+The helper is test-only. Production input integration, physical-device collision
+safety, trusted origin and virtual Braille feasibility remain open; Phase A and
+all release gates are still incomplete.
+Verification: ten private Python experiments and three native Go tests with the
+race detector passed; the Tentacles repository's `make check` also passed.
+
+Fourth implementation increment (2026-11-03): the existing Braille viewport now
+has internal raw-cell export using the physical writer's shared dot-mask logic.
+Eight new tests establish exact cell masks, independent virtual/local widths,
+real liblouis contraction, mapped selection/cursor cells, panning and routing
+without opening a physical display. See
+[the Braille feasibility evidence](../cthulhu/docs/testing/remote-braille-feasibility.md).
+Default and brlapi-tagged Braille package suites passed with the race detector;
+tagged vet, a helper build and the Tentacles repository's `make check` passed.
+Ordinary text still needs an explicit
+virtual translation-table policy, and the tested cursor overlay is static, not
+BRLTTY cursor/blink parity. Virtual helper IPC, session integration, raw receiving
+and physical-display acceptance remain pending. Phase A and all release gates
+remain incomplete.
+
+Fifth implementation increment (2026-11-03): opt-in reader protocol 1.1 now
+supports explicit API/grant sets, bounded bidirectional calls, lifecycle events,
+and core-issued expiring leases. Both Go and Python SDKs have real-process
+conformance tests, including stalled input/output, consent denial, stale epochs,
+heartbeat expiry, exclusive ownership and queue overflow. Grants persist through
+package/registry/launch paths and appear with direction and consent wording in
+install/update confirmations. Update preparation now revokes remote access before
+any download, including failed preparation; a focused application regression test
+covers this. Existing 1.0 SDK/command behavior remains supported.
+See [the implemented session contract](../cthulhu/docs/tentacle-sessions.md).
+Reader wire/host/preferences race suites, focused application Tentacle race tests,
+focused vet and four private GTK Tentacle workflows passed. The full host race
+suite took 131 seconds; an initial 90-second suite timeout was insufficient and
+the completed run used 240 seconds. A blocked Go stdin shutdown defect exposed by
+the new timeout fixture was fixed and rechecked in both SDKs.
+There is no production local consent issuer or desktop service behind these
+leases. Input/output/clipboard/Braille operations, origin-aware consent and
+lock/handoff integration remain pending. Phase B and all release gates remain open.
+
+Sixth implementation increment (2026-11-03): Remote now has validated versioned
+TOML settings and separate, explicitly remembered channel-key storage. Pins and
+saved keys are bound to the relay host/port. Directory-relative operations reject
+symlinks, hard links, special files and unsafe permissions; writes use private
+atomic replacement with file/directory sync and cooperating-process locking.
+Errors omit paths, parser excerpts and secrets. Storage performs no networking
+and persists no lease, peer or session consent. See
+[the storage contract](remote/storage.md).
+The complete Remote race suite and Tentacles `make check` passed after the
+storage changes. Connection UI and local trust/Remember key actions still need
+integration. This is another prerequisite, not a usable Remote release.
+
+## 1. Intended result and recommended approach
+
+Build a native Go Tentacle named **Remote**, with package ID `remote`, in this
+repository. It should let Cthulhu control another computer or allow a helper to
+control the local computer, using an NVDA Remote protocol-v2 relay. Support
+Cthulhu-to-Cthulhu sessions and both directions with NVDA. Test Orca Remote
+interoperability as a separate target, recording the exact Orca build and plugin
+revision because their available hooks differ.
+
+Keep relay connections, protocol conversion, connection settings, and session
+workflow in the Tentacle. Extend the reader with reusable, permission-controlled
+streaming, keyboard, and Braille operations. The reader continues to own desktop
+input, output arbitration, lock state, consent, and emergency recovery.
+
+Use the newer Orca projects as references for the wire protocol, key mappings,
+failure cases, and test ideas. Port small, understood pieces when provenance
+permits; do not import an entire Orca extension or monkey-patch Cthulhu. A Go
+implementation matches the existing native package workflow and avoids shipping
+Python, GTK bindings, external key-injection commands, or an Orca runtime.
+
+### First complete release
+
+- Controller and controlled roles, with one active peer of the opposite role.
+- Speech mirroring and cancellation in both pairings; explicit handling of
+ pause/resume and unsupported speech commands.
+- Xorg keyboard forwarding and injection, including screen-reader shortcuts.
+- A reliable local escape and disconnect path, with held-key cleanup.
+- Explicit text clipboard transfer in either direction, with per-session consent.
+- Single-line raw Braille output, geometry negotiation, routing and panning,
+ verified with a physical display. Broader Braille keyboard support is tracked
+ separately and must not be implied by output support.
+- Accessible connection/settings/status controls, install/disable/update cleanup,
+ and tested recovery from network and process failures.
+
+A speech-only development milestone is useful, but it does not complete this
+release. The test matrix must distinguish speech, keyboard, Braille output,
+Braille input, and clipboard support.
+
+### Deliberately outside the first release
+
+Unattended startup connections; login/greeter/lock-screen control; Windows secure
+desktop bridging; embedded relay hosting; automatic clipboard monitoring; file
+transfer; desktop video/audio streaming; mouse control; multiple controllers;
+remote command execution; and new Wayland injection backends. Remote can connect
+to an independently hosted compatible relay without implementing a relay itself.
+Retain usable non-keyboard functionality on unsupported platforms, but never
+claim forwarding works if keys also reach the local application.
+
+## 2. Evidence and upstream comparison
+
+### Reviewed revisions
+
+The maintained local branches matched their remote tips when checked:
+
+| Project | Branch | Reviewed commit |
+| --- | --- | --- |
+| `cthulhu-tentacles` | `master` | `bc305993b8ad5c2374c8fc2c8b886c9cd6697b52` |
+| `cthulhu` | `testing` | `a47253d697c1aa44dea80646cad99a4fe163c7f1` |
+| `churst90/orca-remote` | fetched default branch | `391f0c52044071e7cd34e3900fc13474826c312d` |
+| `serrebidev/orca-remote` | fetched default branch | `9260d8284bb9f0761633dca958f5e1d9ccc37485` |
+| `thgcode/orca-remote` | `master` | `6fcf58dd060d79addba61767a964ea9da948ea39` |
+| NVDA local reference | local checkout | `2843e703ce19757711e976ebb6e9c5b689fc2017` |
+| NVDA Remote add-on | fetched default branch | `301248945481e462601248c5e423731bd58d5e0a` |
+
+This was source review, not a live remote-control trial. Freshen these references
+before implementation; do not infer acceptance from repository claims.
+
+### Which Orca work is useful
+
+| Project | Confirmed source/design evidence | Use in this project |
+| --- | --- | --- |
+| [churst90/orca-remote](https://github.com/churst90/orca-remote/tree/391f0c52044071e7cd34e3900fc13474826c312d) | Version 0.8.2; separate protocol, transport and keymap modules; modern controller hooks; client and host paths; key-release tracking. | Primary small reference for protocol decomposition, VK mapping, bypass chords and regression cases. Its README has stale pairing instructions, so inspect handlers and tests. |
+| [serrebidev/orca-remote](https://github.com/serrebidev/orca-remote/tree/9260d8284bb9f0761633dca958f5e1d9ccc37485) | Contains modern and legacy implementations, external injection backends, more transport/session tests, and a Windows-to-Linux Braille guide. | Reference for reconnect/session cleanup, practical interoperability failures and acceptance procedures. Avoid carrying over legacy installers, monkey patches and backend fallback chains. |
+| [thgcode/orca-remote](https://github.com/thgcode/orca-remote/tree/6fcf58dd060d79addba61767a964ea9da948ea39) | README explicitly calls it a proof of concept; customizations patch Orca speech methods and send speech/cancel. No incoming keyboard-control implementation. | Historical context only; do not use as the implementation base. |
+
+The two newer trees contain substantially similar modules. Do not count them as
+two independent demonstrations of protocol correctness. Neither replaces testing
+against NVDA's implementation.
+
+The newer projects declare LGPL-2.1-or-later; this repository declares
+GPL-3.0-or-later. The older project declares GPL version 2 and credits NVDA
+Remote. The newer fork also carries legacy files whose provenance needs checking.
+Before copying code, tables, fixtures, or documentation, record the exact source,
+copyright notices, license terms and modifications. Keep required notices and
+license texts in the distributed source/package. Resolve any unclear rights before
+reuse; repository-level labels alone are insufficient. The preferred starting
+point is a fresh implementation of the protocol with independently written tests.
+
+### Authoritative interoperability references
+
+- [NVDA serializer at the local reviewed revision](https://github.com/nvaccess/nvda/blob/2843e703ce19757711e976ebb6e9c5b689fc2017/source/_remoteClient/serializer.py)
+ defines speech-command serialization.
+- [NVDA session handling](https://github.com/nvaccess/nvda/blob/2843e703ce19757711e976ebb6e9c5b689fc2017/source/_remoteClient/session.py)
+ defines actual role/message behavior and Braille negotiation.
+- [NVDA local operations](https://github.com/nvaccess/nvda/blob/2843e703ce19757711e976ebb6e9c5b689fc2017/source/_remoteClient/localMachine.py)
+ show receiving behavior; [its input adapter](https://github.com/nvaccess/nvda/blob/2843e703ce19757711e976ebb6e9c5b689fc2017/source/_remoteClient/input.py)
+ is needed for Braille gesture fields and Windows key semantics.
+- [NVDA Remote protocol overview](https://github.com/NVDARemote/NVDARemote/blob/301248945481e462601248c5e423731bd58d5e0a/protocol.md)
+ is a useful message inventory, but field optionality/types must be checked
+ against executable source and real frames.
+- [Orca protocol notes](https://github.com/churst90/orca-remote/blob/391f0c52044071e7cd34e3900fc13474826c312d/docs/wire-protocol.md)
+ and [fork transport](https://github.com/serrebidev/orca-remote/blob/9260d8284bb9f0761633dca958f5e1d9ccc37485/transport.py)
+ provide comparison points, not the final wire contract.
+
+In particular, NVDA serializes speech commands as `[commandName, fields]` arrays.
+The Orca notes show dictionary-shaped commands in one example and flatten speech
+to text. Support the actual NVDA form; do not build the codec around that example.
+Likewise, do not require `scan_code` or string-valued speech priorities merely
+because the protocol overview describes them that way. Capture frames from the
+specific supported versions and freeze generic, non-private fixtures.
+
+## 3. Current Cthulhu support and missing interfaces
+
+Paths in this section are relative to the adjacent `../cthulhu` checkout.
+
+| Existing area | What can be reused | Required enhancement |
+| --- | --- | --- |
+| `internal/tentacle`, `internal/tentaclewire` | External supervised process; bounded newline JSON-RPC; commands; cancellation and lifecycle ownership. | Bidirectional session operations and unsolicited bounded events. Protocol 1.1 now provides lifecycle requests/events; desktop streaming services remain pending. |
+| `sdk/go/tentacle/tentacle.go`, Python SDK | Command handlers and declarative extensions. | Protocol 1.1 client/events and lifecycle conformance now exist; typed desktop operations remain pending. No private reader imports from Remote. |
+| `internal/tentaclewire/presentation.go` | Command-result speech/Braille text, limited to 8,192 UTF-8 bytes per channel. | Continuous remote presentation and output observation. Existing `Presentation` is explicitly a command result, not a streaming interface. |
+| `internal/tentaclewire/interaction.go`, `internal/interaction` | Forms including transient secret entries, status polling while a form is open, explicit clipboard exchange. | Background session status and Remote connection controls. One-second form polling cannot carry speech or keyboard traffic. |
+| Reader extension/preferences machinery | Declarative native pages, settings validation, command registration and remapping. | Remote-specific grants/status and session consent; no speech-configuration override is needed. |
+| `internal/platform/xorg/listener.go`, `commands_owner*.go`, `commands_security.go` | XRecord observation, command grabs, secure-input gating and owner loop. | Exclusive controller capture, balanced bypass chords, and serialized XTEST injection with reliable ownership. Observation alone does not consume keys. |
+| `internal/app/speech_worker.go`, `speech_delivery.go`, interruption code | Ordered presentation, speech modes, voice selection, read-all and cancellation. | Origin-tagged output events and remote-owned input to the normal output policy. |
+| `internal/app/braille_*`, `internal/braille` | Frames, liblouis translation, helper, routing and panning. | Raw rendered cells, virtual remote display geometry, remote display ownership, and portable gestures. `Frame.Dots` is an overlay, not a raw remote frame. |
+| Registry/install/update and Preferences confirmation | Native packages, digest verification, explicit capabilities and cleanup. | Persist/disclose new grants, reject unsupported reader versions, and revoke active remote access before updates. |
+
+Protocol 1.0 retains an exact version and an ordered API prefix:
+`commands`, `presentation`, `interaction`, `reader-settings`. `ValidAPIs`, SDK
+length checks, launch `Spec`/registry fields, installer validation, and confirmation
+text all embody that model. Opt-in protocol 1.1 now adds explicit grant sets and lifecycle IPC through both
+SDKs, installer, registry and command host; see the implemented session contract.
+Adding a manifest string alone will not enable desktop Remote services.
+Default ordinary command RPCs time out after two seconds, so a connection or
+session must not live inside a command invocation.
+
+The existing same-user Tentacle process model is not a security sandbox. New
+grants control reader-mediated access; they do not prevent a malicious installed
+executable from using the user's other desktop facilities. Preserve existing
+process supervision and optional cgroup resource limits without requiring a
+particular init system, root, or administrator setup.
+
+## 4. Ownership, consent and recovery contract
+
+### Data path
+
+```text
+Local keyboard / Cthulhu output
+ |
+Cthulhu input and presentation owners
+ | bounded, consented session API
+Remote Tentacle: session state + NVDA codec + TLS transport
+ |
+NVDA Remote v2 relay
+ |
+Remote Tentacle, NVDA Remote Access, or compatible Orca Remote
+```
+
+The Tentacle owns network state. Cthulhu owns an ephemeral access lease attached
+to its Tentacle process session, selected role, current connection generation and
+explicitly approved operations. The lease contains no reusable network secret.
+Only one Tentacle may own keyboard capture/injection or remote Braille at a time.
+Initially, disallow simultaneous controller and controlled sessions on one reader.
+
+### Consent and transport trust
+
+1. Enabling/installing Remote does not connect or grant an active control session.
+2. A local user opens the connection UI and chooses **Control another computer**
+ or **Allow this computer to be controlled**. Explain that the latter shares
+ reader output and, when enabled, permits keyboard control.
+3. Consent is issued by the reader from a local action. A child RPC or remotely
+ injected shortcut cannot mint consent, accept a certificate, change grants,
+ save a key, reconnect, or authorize clipboard sharing.
+4. Use normal CA/hostname verification for a valid certificate. For a self-signed
+ relay, offer an accessible fingerprint review and explicit trust decision,
+ bound to host and port. Verify the approved certificate before sending the
+ channel key. A changed pin stops connection; never silently replace it.
+5. Show trust failure details locally. Do not automatically overwrite the
+ clipboard or create a fingerprint file. Provide an explicit Copy fingerprint
+ button; a displayed fingerprint still needs independent verification.
+6. TLS authenticates/encrypts the connection to the relay. Protocol v2 does not
+ provide end-to-end encryption or authenticated human identities: the relay
+ sees the channel key, speech, keys, Braille and clipboard. Anyone with the key
+ can attempt to join. Explain this accurately in help and consent wording.
+7. Use a strong randomly generated channel key. Default to session-only secrets;
+ offer explicit Remember key with owner-only, atomic storage. Never place keys
+ in process arguments, command descriptions, URLs, diagnostics or fixtures.
+8. Limit the initial session to one controller and one controlled peer. Track
+ relay-assigned origins and roles. Unexpected membership or ambiguous routing
+ suspends access and requires a new session; do not silently select the latest
+ peer. A relay can already have broadcast data before a membership notice, so
+ this is not a confidentiality guarantee against other channel participants.
+
+### Lease lifetime and emergency behavior
+
+- A new connection epoch invalidates all earlier events, operations and consent.
+ Reconnection can restore a connection dialog/status, but never silently resume
+ capture, injection, clipboard sharing or output export. Require local Resume.
+- Controller starts in local focus. A local toggle enters remote focus only after
+ peer readiness and capture capability are confirmed. Local focus stops input
+ forwarding and remote output presentation; mute remains a separate saved
+ in-session choice. An optional listen-only mode can be added explicitly later.
+- Reserve an always-local escape in core while capture is active. Proposed
+ default: F11, plus the registered Disconnect command. Verify conflicts and
+ remapping before adoption; the escape remains available even if the Tentacle
+ is hung. It must work on a press without waiting for the network.
+- Disconnect, disable, uninstall, update, Tentacle crash, reader exit, lock,
+ secure-input transition, terminal-reader handoff, capture failure or queue
+ overflow revokes the lease and restores local input/output. Unlocking or
+ returning from handoff does not resume control automatically.
+- Opening local settings/consent, learn mode, or another exclusive reader UI
+ first returns to local focus. Preserve a local path to disable all Tentacles.
+- Heartbeat each second; expire an unrefreshed lease after three seconds. This
+ detects a hung Tentacle, not a vanished relay: track network/peer liveness too,
+ using tested keepalive/read deadlines compatible with the relay. A known
+ transport failure revokes access immediately. Never wait for backoff to release
+ local capture or remote held keys.
+- Keep a held-key ledger per lease and direction. Release owned keys before
+ forgetting the ledger; invalidate queued downs before cleanup, and prioritize
+ cleanup over normal traffic. Handle duplicate downs/repeats, unmatched ups and
+ disconnect with modifiers held. Do not release physically held local keys as
+ if Remote owned them; test collisions explicitly.
+- Reader SIGKILL requires an independent cleanup mechanism for injected XTEST
+ keys. Prototype a reader-owned input helper, launched through a private
+ inherited descriptor with no network interface, that owns injection and its
+ ledger and releases keys on parent EOF/heartbeat expiry. Reuse existing process
+ lifetime mechanisms where suitable. X connection closure releases keyboard
+ grabs, but is not proof that injected modifier state is cleared. Inability to
+ recover from reader death blocks declaring keyboard control ready.
+
+## 5. Proposed reusable Tentacle API
+
+### Negotiation and capability changes
+
+- [x] Specify an opt-in protocol 1.1 for session transport; keep existing 1.0
+ packages working unchanged. An old reader must reject a 1.1 package clearly,
+ before activation, rather than partially enabling it. No polling compatibility
+ shim or alternate implementation for old readers.
+- [x] Replace API-count assumptions for 1.1 with explicit API/grant sets and
+ dependency validation. Retain strict validation of known operations, required
+ fields, duplicate keys, depth, frame length and registration identities.
+- [x] Implement APIs `session-events` and `remote-access` for lifecycle transport. Grant operations
+ separately: `output-observe`, `remote-present`, `keyboard-capture`,
+ `keyboard-inject`, `braille-stream`, and `clipboard-exchange`. Explain direction
+ in confirmation text; owning one grant must not imply another. Resolve the
+ existing manifest-versus-initialize capability representation explicitly.
+- [x] Carry grants through discovery, install, registry, local launch, activation,
+ update and confirmation. Increased access on update requires a fresh grant
+ review. Runtime consent remains ephemeral even when installation grants persist.
+- [x] Add the same lifecycle wire contract to Go and Python SDKs and the command-host tool.
+ New functionality is not implemented by exposing internal reader structs.
+
+### Session operations
+
+`remote.open`, `remote.close` and `remote.heartbeat` now have the implemented
+lifecycle contract in [tentacle-sessions.md](../cthulhu/docs/tentacle-sessions.md).
+Only core test fixtures can issue local approval so far. The remaining operations
+below are still proposed and return unsupported-operation errors.
+
+Proposed child-to-host requests, each answered promptly with a typed result/error:
+
+| Operation | Purpose and gate |
+| --- | --- |
+| `remote.open` | Complete a pending local connection action and acquire the approved lease; role and grant subset are validated by core. |
+| `remote.close` | Idempotently revoke a lease and restore local ownership. |
+| `remote.heartbeat` | Refresh a current lease; does not renew consent or change epoch. |
+| `remote.state` | Report connection/peer state to core; never asserts that remote capture is physically active. |
+| `remote.focus` | Request the locally approved controller focus transition; core owns the grab and actual result. |
+| `remote.present` | Queue typed remote speech/cancel/pause or Braille under the active lease. |
+| `remote.key` | Inject one validated key transition in controlled role; held-key state belongs to the input owner. |
+| `remote.braille` | Process an allowlisted Braille gesture against the current remote viewport. |
+| `remote.clipboard` | Explicit read/write of text, only for the approved local action or permitted session receive. |
+
+Host-to-child events include local connection actions, lease revocation, input
+transitions, speech output/cancellation, Braille cells/geometry/gestures and
+explicit clipboard-send actions. An idle session blocks on channels/pipes; it
+does not poll reader state. Commands stay short and return accepted/pending
+status; network work runs in cancellable session workers.
+
+### Framing, ordering and capacity
+
+- [x] Extend the host's original reply-only decoder to distinguish replies,
+ requests and negotiated notifications. Use unambiguous request-ID namespaces
+ for each direction, validate method-specific fields, and never hold a session
+ mutex while waiting for a reply or invoking reader services.
+- [x] Implement one serialized writer per endpoint, bounded pending calls,
+ deadlines, cancellation, and session-scoped shutdown. Control operations must
+ remain serviceable while a command handler or network worker is blocked.
+- [ ] Attach core-issued lease ID, connection epoch and sequence to session
+ traffic. Reject old epochs after revoke/reconnect. Origin metadata is trusted
+ only when assigned by core; do not accept a child's claim that input is local.
+- [ ] Retain the 64 KiB host frame bound. Initially cap speech text and clipboard
+ at 8 KiB per operation, Braille at 4,096 cells, and key operations at one
+ transition each. Split valid longer speech at UTF-8/semantic boundaries before
+ IPC, preserving cancel order; reject oversized clipboard content explicitly.
+- [ ] Start with separate bounded control/input/output queues: 32 control
+ operations, 256 key transitions, 64 speech events, latest Braille frame only,
+ and a 256 KiB aggregate queued-byte ceiling per lease. Treat these as tunable
+ initial limits; measure memory and latency before freezing them.
+- [ ] A full input/control queue revokes the lease rather than dropping a key-up.
+ Speech overflow cancels the remote speech generation and reports loss;
+ coalesce superseded Braille frames. Cleanup must have a separate immediate
+ path and cannot be blocked by the queue it is trying to drain.
+- [ ] Every queued effect rechecks lease/epoch at delivery, not only at enqueue.
+ Test revocation racing with output, an injection helper, and pending clipboard
+ operations. Slow pipes or a relay must never block Cthulhu's event loop.
+
+## 6. NVDA protocol implementation contract
+
+Use UTF-8 newline-delimited JSON over TLS; this is a separate framing protocol
+from host JSON-RPC. Send protocol version 2 and join with wire role `master` for
+controller or `slave` for controlled. Present plain-language role labels in UI.
+
+| Message family | Planned handling |
+| --- | --- |
+| `protocol_version`, `join`, `channel_joined` | Validate handshake and membership before enabling any sharing/control. TLS connected, channel joined, peer present and control active are distinct states. |
+| `client_joined`, `client_left`, `origin` | Maintain bounded peer registry and role checks. Permit effects only from the expected opposite-role peer in the active connection. Relay metadata is not cryptographic peer identity. |
+| `speak` | Accept strings and allowlisted NVDA command arrays; preserve order, priority and supported semantics. Send text-only sequences initially from Cthulhu. Never instantiate remote-named classes. |
+| `cancel`, `pause_speech` | Apply only to the current remote-owned output generation. If true pause is unavailable, use a documented cancel-on-pause policy and resume with future speech; do not pretend old speech resumes. |
+| `key` | Convert Windows VK plus `extended` and any supported scan-code metadata into typed core key events; accept actual version-specific optional fields. |
+| `set_braille_info`, `set_display_size`, `display` | Negotiate positive single-line width, handle absent displays, and exchange final dot cells. Do not confuse display text with cells or translate received cells again. |
+| `braille_input` | Parse actual NVDA gesture fields, including fixed `scriptPath` forms where used. Map a finite known subset to core actions. Never dispatch arbitrary method/module names. |
+| `set_clipboard_text` | Bound UTF-8 text and honor explicit transfer consent; never interpret paths, links or commands. |
+| `ping`, `error`, `version_mismatch`, `motd` | Bounded handling; sanitize server text; terminal protocol errors stop reconnect attempts. Relay text cannot authorize UI actions. |
+| `tone`, `wave`, `send_SAS`, `index`, unknown extensions | Inventory real usage. Initially ignore unsupported optional output with bounded counters; never open a peer-supplied path/URL or execute a secure-attention request on Linux. Record any resulting functional gap. |
+
+- [ ] Use a bounded reader: proposed 1 MiB maximum relay line with an explicit
+ limit on decoded collection sizes and processing time. Do not allocate without
+ bound waiting for LF. A relay frame may need several smaller host operations.
+- [ ] Validate known payloads but tolerate harmless additional relay fields;
+ rejecting every unknown field would prevent interoperability. Reject malformed
+ required values, duplicate JSON keys and invalid types; bound diagnostics for
+ ignored unknown message types. Distinguish optional-message loss from fatal
+ framing or authorization failures.
+- [ ] Record actual priority representations and language/character-mode command
+ payloads from supported NVDA versions. Initially implement text, cancellation,
+ character mode and language changes where the reader supports them. Count and
+ document unsupported commands; never silently claim full speech fidelity.
+- [ ] Preserve whitespace across speech fragments. Do not concatenate unrelated
+ utterances, strip meaningful spaces, apply punctuation expansion twice, or
+ substitute a local key name for an intentional character command.
+- [ ] Use bounded dial/TLS/join/write deadlines and cancellable reconnect backoff
+ with jitter. Proposed dial/join deadline: 15 seconds each; write deadline: five
+ seconds; backoff steps: 1, 2, 5, 10, 30 seconds. Explicit Disconnect cancels
+ pending dial, reads, writes and sleeps. Authentication/certificate failures
+ require local correction rather than endless retries.
+- [ ] Freeze fixtures for membership variants, absent optional fields, real
+ speech arrays, numeric priorities, extended keys and Braille gestures. Do not
+ ship a novel wire extension for essential functionality; NVDA peers must work
+ without changes. Custom Cthulhu extensions, if later needed, require explicit
+ negotiation and a separate plan.
+
+## 7. Speech and Braille integration
+
+### Speech
+
+- [ ] Add a core output observer near the policy-resolved delivery path, after
+ password/secure-input and speech-mode decisions. Cover ordinary reading, key
+ echo, spelling, context, read-all parts, explicit stop and interruption. Do not
+ scrape logs or speech history, and do not depend on Speech Dispatcher alone:
+ hardware synthesizers also use core output policy.
+- [ ] Define whether an event means accepted-for-delivery or backend completion.
+ Mirror accepted semantic output plus cancel events; it is not evidence that
+ audio was heard. Ensure fast synchronous read-all backends cannot outrun the
+ bounded stream indefinitely; profile congestion and report loss.
+- [ ] Core tags output origin and session ownership. Received remote speech,
+ Remote's own connection messages, secret-entry feedback and consent dialogs
+ never re-enter exported output. Initially exporting only from controlled role
+ further reduces loops but does not replace origin tracking.
+- [ ] Route incoming speech through the normal configured voice/backend and
+ output arbitration. Respect local speech disable and modes; never mark network
+ output uninterruptible. Local escape/status must remain audible when enabled.
+- [ ] Retain local speech on the controlled computer by default. Do not change
+ persisted speech settings or use the speech-override API to mute it.
+- [ ] Keep remote cancel/pause from cancelling unrelated local announcements.
+ Switching to local focus or disconnecting drops pending remote speech and
+ restores normal output immediately.
+- [ ] Exclude secrets and remote payloads from Remote diagnostics, including
+ diagnostic errors. Decide explicitly whether remote speech enters local
+ history; default to exclusion so a session does not create a persistent copy.
+
+### Braille
+
+- [ ] Extract/reuse a renderer that produces translated cells, cursor treatment,
+ viewport state and routing maps without requiring a physical controlled-side
+ display. Current translation/viewport work crosses the helper boundary; choose
+ a reusable renderer or typed helper event rather than a second translator.
+- [ ] Maintain a virtual remote viewport at the negotiated controller width.
+ Preserve the controlled user's physical display width and routing independently.
+ A controller with no display advertises zero; do not fabricate a default width
+ and call it hardware support.
+- [ ] Export final cells after liblouis translation and cursor/attribute handling.
+ Keep original routing targets inside Cthulhu; no AT-SPI identities, object paths
+ or native handles cross into the Tentacle or relay.
+- [ ] Add a raw-cell display mode to the helper/backend protocol. Existing
+ `Frame.Text` and `Frame.Dots` cannot be assumed to write an arbitrary incoming
+ cell array unchanged. Bypass translation for raw cells; pad/clip according to
+ the negotiated width and restore the local frame on exit.
+- [ ] Local consent/status messages temporarily own the display. On dismissal,
+ show the latest permitted remote frame or current local frame as appropriate;
+ do not let incoming traffic erase an emergency message.
+- [ ] Map routing and pan gestures to the virtual viewport, not the physical
+ local document. Tag local IPC with a viewport generation and invalidate pending
+ routes on replacement. Protocol v2 does not supply an end-to-end frame ID, so
+ absolute stale-route detection against a delayed NVDA gesture is unproven;
+ serialize against the latest viewport and document this limitation.
+- [ ] Start with routing and pan-left/pan-right mappings, then inventory dots,
+ space, enter, backspace and navigation gestures. Current backend keys expose
+ panning/routing only; full Braille keyboard input requires another core change.
+ Report unsupported gestures, and keep unknown script paths inert.
+- [ ] Validate contracted/uncontracted text, Unicode, non-Latin tables, cursor
+ dots, width changes and device unplug/replug. Do not reuse the Orca reference's
+ ASCII-only text-to-cell mapping as production Braille.
+
+## 8. Xorg keyboard implementation
+
+- [ ] Put capture/injection in the existing input ownership layer, with work
+ serialized onto its Xlib owner thread. Prototype interaction with current
+ command grabs before committing to XGrabKeyboard or a different consume path.
+ Do not treat XRecord, AT-SPI observation, or a list of reader chords as full
+ desktop consumption.
+- [ ] Acquire capture atomically before reporting remote focus. If another client
+ owns the keyboard or required capture fails, remain local and announce why.
+ Restore prior command grabs and modifiers on every exit path.
+- [ ] Forward ordinary application keys and Cthulhu/NVDA modifier chords. Keep
+ only core escape and explicit Remote control commands local. Check registered
+ bindings and user remaps; avoid a hard-coded bypass list that becomes stale.
+- [ ] Balance modifiers around bypass chords: prevent a prefix already sent to
+ the remote from remaining held, and prevent a bypass key's release from leaking
+ to an app that never received its press. Test entry/exit with a modifier held.
+- [ ] Make key provenance explicit. XTEST events do not reliably identify
+ themselves through the ordinary X `send_event` flag. Prototype XInput device
+ identity and ordered broker acknowledgements; prove how injected events reach
+ target reader commands without becoming trusted local consent/emergency input.
+ Timing-only suppression of all nearby physical keys is unacceptable.
+- [ ] Scope the guarantee honestly: Xorg does not isolate this mechanism from
+ malicious same-user desktop clients. Provenance protects our own routing and
+ accidental loops; it is not an OS security boundary.
+- [ ] Build bidirectional VK/XKB mapping with extended-key distinctions, left and
+ right modifiers, Insert/CapsLock reader modifiers, keypad/navigation, function
+ keys, OEM punctuation, AltGr and keyboard-layout changes. Unknown keys produce
+ bounded diagnostics instead of a guessed character. Never assume X keycodes
+ equal Windows virtual-key or scan codes.
+- [ ] Separate duplicate-down repeat from a fresh press; verify autorepeat
+ behavior on injection. Handle lock-key state without surprising local toggles.
+ Do not depend on temporarily rewriting global keymaps for ordinary input.
+- [ ] Inject through XTEST in controlled role via the core-owned helper/owner.
+ Show an unavailable capability if it cannot work. Do not silently invoke
+ `xdotool`, a root daemon, `/dev/uinput`, or a Wayland portal fallback.
+- [ ] Verify remote keys reach both ordinary applications and Cthulhu command
+ handling exactly once. If physical/injected held-key collisions cannot be
+ resolved safely, suspend input and report the limitation; do not clear all
+ system modifier state indiscriminately.
+- [ ] On Wayland, expose actual capabilities individually and leave exclusive
+ keyboard control unavailable until implemented/tested. XWayland success is
+ insufficient evidence for native Wayland applications.
+
+## 9. User interface and stored settings
+
+Use existing host-owned accessible forms/pages where suitable. The shared
+transient Entry model now supports `secret: true`; use it for channel keys.
+Persistent preference pages reject secret fields. Keep live verification of echo,
+review, copy, speech, Braille, accessibility exposure and debug logging pending
+until the connection UI exists. Do not simulate secrecy by replacing visible
+text while leaving the actual value in a normal control.
+
+The connection UI needs:
+
+- Role, relay host, port, channel key, Generate key and Remember key.
+- Certificate status, fingerprint details and explicit trust/copy controls.
+- A concise description of what the chosen role permits, including relay trust.
+- Separate per-session permissions for keyboard control and receiving clipboard.
+- Connect, Disconnect, Return to local, Mute remote output, Send clipboard and
+ Status actions, with descriptive enabled/disabled state.
+
+Propose unbound commands initially: `remote-menu`, `connect`, `disconnect`,
+`toggle-remote-focus`, `toggle-remote-mute`, `send-clipboard`, `session-status`.
+Add one suggested menu shortcut only after checking desktop/laptop binding
+conflicts. The core escape must be independent of command registration success.
+
+Distinguish disconnected, connecting, certificate approval required, joined/waiting
+for peer, connected/local focus, controlling remote, controlled/input enabled,
+suspended and failed states. Announce changes once through normal Cthulhu output;
+avoid repeated connected announcements during reconnect. Status must remain
+available after the connection form closes without one-second background polling.
+
+Store versioned, validated TOML settings in an owner-only Remote data directory.
+Persist role/relay/preferences separately from transient peer/lease state. Do not
+auto-connect on startup. If Remember key is selected, use an owner-only file and
+directory with atomic replacement, reject unsafe links, and omit secrets from
+exported diagnostics. Do not store the key in generic reader-page values unless
+that store has explicitly acquired equivalent secret-handling support.
+
+Text clipboard transfer is an explicit action, not continuous synchronization.
+Read clipboard text only when Send clipboard is chosen; require receive permission
+before writing incoming text. Report oversized or unavailable text. Keep the
+clipboard owner alive as needed by X11 selection semantics. Do not alter PRIMARY,
+share file lists, automatically paste text, or echo received text into diagnostics.
+
+## 10. Implementation sequence and reviewable deliverables
+
+### Phase A: Freeze contracts and build protocol fixtures
+
+- [ ] Refresh branches without discarding work; record exact reader, SDK, NVDA,
+ relay and Orca versions. Read both contributing guides.
+- [x] Reconfirm the missing host interfaces listed above and inventory all
+ permission, protocol and UI validators that need changes.
+- [ ] Capture sanitized NVDA handshakes, output and gestures using a private test
+ relay and test documents. Record omitted fields, priorities and role routing.
+- [ ] Write `remote/protocol.md` with supported message semantics, limits and
+ explicit unsupported features. Resolve provenance before importing material.
+- [ ] Review the lease, origin, threading, heartbeat and crash-cleanup designs.
+ Prototype Xorg consume/inject/provenance and virtual Braille rendering early:
+ these are the highest-risk dependencies, not finishing touches.
+ Partial evidence is now recorded in the reader's
+ [Xorg feasibility checks](../cthulhu/docs/testing/remote-input-feasibility.md);
+ origin and later same-key collisions remain unresolved. The
+ [Braille feasibility checks](../cthulhu/docs/testing/remote-braille-feasibility.md)
+ now demonstrate independent translated viewports without a physical display;
+ virtual table/cursor policy and helper integration remain unresolved.
+
+Exit: frozen fixtures and concrete feasibility evidence for input recovery and
+Braille without a controlled-side physical display. Record unresolved results;
+do not claim them from a design diagram.
+
+### Phase B: Extend host transport and SDKs
+
+- [x] Add protocol 1.1 negotiation, grants, bidirectional calls/events and bounded
+ queues. Extend host harness with an inert session-service implementation.
+- [x] Add core lease state/revocation and Go/Python SDK conformance fixtures.
+- [ ] Integrate verified local consent and lock/handoff revocation with production
+ reader owners. The core-only authorizer currently has no production caller.
+- [x] Update registry/install/update grant persistence and access descriptions.
+ Existing Hello World, Wormhole and Battery Status actual-host checks passed.
+- [ ] Add production first-use consent and per-session access controls.
+- [x] Add transient secret-entry schema/editor support, reject persistent secret
+ preference controls, and test both SDKs and private Xorg form behavior. Live
+ audible speech/physical Braille acceptance remains pending with connection UI.
+- [x] Document implemented public lifecycle operations, errors, ownership and
+ limits in the reader repository. Runtime Remote code stays external.
+- [ ] Implement and document typed desktop services and their delivery-time checks.
+
+Exit: permission denials, timeout/overflow, stale epochs and process failures are
+tested; existing Tentacles still install, register, run, disable and update.
+
+### Phase C: External transport and speech milestone
+
+- [ ] Add `remote/src` state/codec/transport with explicit Connect/Disconnect.
+- [x] Add secure settings and separate explicit saved-key storage, with no
+ startup networking or persisted session consent.
+- [ ] Add the local CA/pin trust and Remember key UI workflows.
+- [ ] Add core output observation and incoming remote presentation with origin
+ tracking, cancel order and lock/handoff revocation.
+- [ ] Demonstrate controlled Cthulhu speech to NVDA and NVDA speech to controlling
+ Cthulhu, then Cthulhu-to-Cthulhu. Verify read-all, spelling and ordinary stop.
+
+Exit: source and private tests pass; live speech results are recorded separately.
+This remains a development milestone, not a remote-control release.
+
+### Phase D: Keyboard control and crash recovery
+
+- [ ] Complete capture, bypass, VK/XKB mapping, injection helper and held-key
+ ledgers. Add core-owned emergency escape and input-origin routing.
+- [ ] Integrate local/remote focus transitions and capability reporting.
+- [ ] Verify target reader shortcuts, ordinary typing, Shift+Tab and modifier
+ combinations. Exercise lock/handoff and every process/network failure path.
+- [ ] Prove recovery from Tentacle hang/kill, reader kill, relay death and abrupt
+ cable/network loss. No held key or local grab may survive the recovery bound.
+
+Exit: the user can reliably regain local control and both applications and screen
+reader commands work over Xorg. Failed provenance/recovery checks block progress
+to a keyboard-control release.
+
+### Phase E: Clipboard and complete Braille milestone
+
+- [ ] Add explicit send/receive text operations, permissions and ownership tests.
+- [ ] Add virtual Braille viewport, final-cell export, raw-cell input to the local
+ helper, display negotiation, panning and routing.
+- [ ] Add allowlisted NVDA Braille gesture conversion in both directions and
+ document any unsupported device/input actions.
+- [ ] Test on physical Braille displays, including controlled-side no-display,
+ translation tables and unplug/replug. Keep output/input claims separate.
+
+Exit: the first-release capability matrix is complete or names specific blocked
+features. A synthetic cell recorder cannot close physical Braille acceptance.
+
+### Phase F: Packaging and final acceptance
+
+- [ ] Add catalog/manifest only once the required reader API exists. Record the
+ minimum supported reader/protocol and reject older hosts clearly.
+- [ ] Extend `Makefile`, `tools/check.py`, `tools/package.py` and `.gitignore` for
+ Remote. The checker currently hard-codes three Tentacles and their grants;
+ the packager has special binary-name handling. Update both deliberately.
+- [ ] Package Linux amd64/arm64 native executables, README, license and required
+ attribution; keep secret state and test certificates out of archives.
+- [ ] Test extracted packages through the host and installer on the matching
+ architecture. Cross-compilation alone does not establish ARM64 execution.
+- [ ] Review access changes and verify active-session revocation on disable,
+ remove, update, failed update and rollback. Retain manual reconnect semantics.
+- [ ] Have the contributor review both diffs and perform the live tests below.
+ Only then prepare release assets/checksums; publication, commits and submission
+ remain separate actions. Publish verified immutable downloads before advertising
+ the matching catalog entries.
+
+## 11. Proposed source layout
+
+Follow the repository's existing `src` convention; these are cohesive files in
+one package initially, not an instruction to create a package per concern.
+
+```text
+cthulhu-tentacles/
+ remote.md this plan
+ remote/
+ tentacle.toml added after API support is available
+ README.md
+ LICENSE
+ THIRD_PARTY_NOTICES.md if external material is incorporated
+ protocol.md
+ src/
+ main.go SDK wiring and process lifetime
+ session.go state, role, peer and epoch ownership
+ protocol.go typed NVDA messages and validation
+ transport.go TLS, framing, deadlines and reconnect
+ speech.go speech-command conversion
+ keyboard.go portable VK/event conversion
+ braille.go wire cells, geometry and gestures
+ settings.go validation and owner-only persistence
+ ui.go host-owned forms and command actions
+ clipboard.go explicit text exchange
+ *_test.go
+ testdata/ sanitized frames and private test certificates
+```
+
+Reader changes belong principally in `internal/tentaclewire`,
+`internal/tentacle`, both SDKs, `internal/app/tentacle_*` and new cohesive
+`remote_*` orchestration files. Input changes belong with the Xorg input owner;
+output changes with speech/Braille owners. Extend shared interaction/preferences
+schemas for secret controls. Extend the existing helper protocol and process
+supervision where required. Keep relay implementation details out of core.
+
+## 12. Verification and acceptance
+
+### Focused automated checks during implementation
+
+From the reader checkout, start with the affected packages and existing fixtures:
+
+```sh
+go test ./internal/tentaclewire ./internal/tentacle ./sdk/... -count=1
+go test ./internal/input ./internal/interaction ./internal/preferences -count=1
+go test ./internal/app ./internal/braille ./internal/platform/xorg -count=1
+```
+
+Use `go test -race` for the modified host/session/output owners and external
+session package. Extend existing SDK fixtures to exercise both directions of IPC,
+not just a fake in-process Remote service. Run `make check` in this repository.
+At integration/submission, run the existing reader suite and `go vet ./...` where
+practical, plus `python3 tests/check_speech.py` for output regressions. Document
+skipped native or hardware checks instead of counting their skipped results as
+passes. Run `shellcheck` if implementation edits shell scripts.
+
+Existing native Tentacle harnesses to extend/run where affected:
+
+```sh
+CTHULHU_PREFS_TENTACLES_ONLY=1 python3 tests/native_preferences.py
+CTHULHU_PREFS_TENTACLE_UPDATES_ONLY=1 python3 tests/native_preferences.py
+CTHULHU_PREFS_TENTACLE_SETTINGS_ONLY=1 python3 tests/native_preferences.py
+CTHULHU_PREFS_EXTENSIONS_ONLY=1 python3 tests/native_preferences.py
+```
+
+Build new private remote fixtures on `tests/native_test_session.py`, with Xvfb
+started before private D-Bus, disposable runtime/config directories, a private
+TLS relay and test applications. Never attach automated key injection to the
+active reader/display. Public relay testing is a separate deliberate live step.
+
+Required focused cases:
+
+| Area | Tests that establish the intended property |
+| --- | --- |
+| Negotiation/grants | Old 1.0 package unchanged; new package rejected by old host; missing/unknown grants rejected; install grant cannot mint session consent; update access increase reviewed. |
+| Host transport | Fragmented/interleaved frames; unsolicited/unknown methods; duplicate keys; bad IDs; 64 KiB boundary; concurrent requests; blocked reader/writer; queue saturation; EOF and cancellation. |
+| Relay transport | Valid CA; approved self-signed pin; wrong hostname/pin; changed certificate; no channel key before verification; IPv4/IPv6; partial/no-newline frames; oversized collections; peer/role/origin mismatch; reconnect cancellation. |
+| Session lifecycle | Disconnect during dial/handshake; peer departure; extra peer; late old-epoch result; repeated Connect; Suspend/Resume; lock/handoff; disable/remove/update/crash; heartbeat expiry. |
+| Speech | No output loops; spelling/language/priority handling; significant whitespace; read-all; cancel-before-next ordering; muted/local focus behavior; local status survives remote cancel; secret/password exclusion. |
+| Xorg input | Focused local test app receives zero forwarded keys; remote app receives correct transitions; target Cthulhu command exactly once; no echo-back; bypass and remap; held/repeated keys; left/right modifiers; keypad; layout/OEM keys; collision recovery. |
+| Recovery | Escape works with Tentacle hung; queued ups cannot be lost; kill Tentacle, kill reader, kill relay, sever network; verify X key state/grabs and input to a local app afterward; no automatic control resume. |
+| Braille | Exact raw cells; no double translation; virtual viewport without physical target display; geometry zero/change; contracted maps; cursor/attributes; pan/route allowlist; stale pending route; local message priority; restore on revoke. |
+| Clipboard/settings | Explicit read only; receive denied by default; size/UTF-8 limits; no PRIMARY/file transfer; owner-only atomic files; symlink rejection; settings/diagnostics/packages omit keys; disabled startup makes no connection. |
+| Responsiveness | Slow relay and stalled Tentacle do not delay ordinary reading/input; queues remain bounded; no worker/descriptor/process leaks over repeated connect/disconnect. |
+
+### Live interoperability matrix
+
+For each row, record exact reader/plugin/relay versions, platform, keyboard layout,
+speech result, key result, clipboard result, Braille output result and Braille
+input result. Mark untested features explicitly.
+
+| Controller | Controlled computer | Minimum release evidence |
+| --- | --- | --- |
+| Cthulhu Remote on Xorg | Cthulhu Remote on Xorg | Both directions of text entry and reader commands; all recovery tests; speech; clipboard; physical Braille. |
+| NVDA Remote Access on Windows | Cthulhu Remote on Xorg | NVDA hears Cthulhu and controls Linux apps/reader; Braille display connected to Windows; local Linux escape/disconnect. |
+| Cthulhu Remote on Xorg | NVDA Remote Access on Windows | Linux keys control Windows apps/NVDA; NVDA speech reaches Cthulhu; physical Braille connected to Linux. |
+| Compatible Orca Remote | Cthulhu Remote on Xorg | Record Orca/plugin revisions and available hooks; exercise actual supported paths rather than infer from NVDA success. |
+| Cthulhu Remote on Xorg | Compatible Orca Remote | Same explicit evidence, including hook-dependent capture/injection/Braille limits. |
+
+Test the maintained integrated NVDA Remote Access version and the standalone
+add-on separately if claiming both; do not run both at once on the same NVDA
+instance. Use a private compatible relay first, then a selected deployed relay.
+
+### Human test procedure and likely regressions
+
+1. Use two test desktops and a non-private text document. Keep an accessible local
+ terminal ready with a tested command to disable Remote/restart the reader if
+ needed. Establish local keyboard/speech/Braille operation before connecting.
+2. Connect using each role. Review the role and certificate prompts entirely by
+ keyboard; Tab/Shift+Tab must reach every control. Cancel/close must leave local
+ input working. Confirm secret entry is not echoed or exposed in review.
+3. Enter remote focus, type a short line, use Shift+Tab, selection, editing,
+ application switching, Insert/CapsLock reader commands, keypad and ordinary
+ arrows. Confirm nothing was typed into the controller's local application.
+4. Stop speech, read continuously, spell text, switch language where supported,
+ mute/unmute, and return to local. Confirm local status is understandable and
+ disconnect immediately restores normal reading.
+5. Hold Shift/Control/Alt while disconnecting or losing the peer. Test core escape
+ while the Tentacle is unresponsive. On disposable sessions, exercise process
+ kills/network loss and confirm normal modifier state afterward. Record the
+ observed recovery time; unit timers alone do not prove desktop recovery.
+6. Lock either desktop, enter secure input, and trigger terminal-reader handoff.
+ Verify sharing/input stops and no lock-screen data is exported. Unlock/return
+ must require local reconnection/resumption.
+7. Transfer harmless text explicitly each direction. Confirm clipboard receive
+ denial works and text does not transfer merely because the clipboard changed.
+8. With physical Braille, test routing, panning, contractions, non-Latin text,
+ cursor indicators, unequal display widths and unplug/replug. Repeat with no
+ display attached to the controlled computer. Record Braille keyboard support
+ separately from successful output/routing.
+9. Disable/re-enable Remote, restart the reader, and exercise an update/rollback.
+ Confirm no unattended reconnection, leaked grabs, old output or held keys.
+10. With Remote disabled and then idle-enabled, verify existing ordinary reading,
+ key echo, speech interruption/read-all, browser navigation, learn mode,
+ remapped shortcuts, Preferences traversal, XTerm handoff and local Braille
+ routing/panning. Run Hello World, Wormhole and Battery Status. These share the
+ changed host/input/output paths and are plausible regressions.
+
+Passing source tests and private fixtures is necessary evidence, but does not
+establish installed-binary behavior, audible speech, physical keyboard recovery,
+physical Braille, public-relay compatibility or publication. Keep each pending
+acceptance item visible until it has its own recorded result.
+
+## 13. Decisions to close before implementation
+
+The plan recommends these defaults; implementation must resolve the associated
+questions with evidence rather than quietly widening scope:
+
+- **Protocol/API:** opt-in host protocol 1.1 with explicit grants. Finalize names,
+ negotiation and errors together with both SDKs and installer behavior.
+- **Input feasibility:** prove capture coexistence, injection provenance and
+ independent crash cleanup before treating Xorg remote control as available.
+- **Consent:** host-owned local actions create leases; one opposite-role peer;
+ no automatic control resume. Confirm the exact local escape after binding tests.
+- **Braille:** share the actual renderer, support a virtual remote viewport, and
+ display raw cells. Decide the helper IPC change after inspecting translation
+ ownership; do not substitute an ASCII table.
+- **Speech fidelity:** freeze supported NVDA command/priority forms and document
+ pause/language limitations. No promise of full NVDA synthesis semantics.
+- **Trust/storage:** normal CA validation plus explicit pinned-certificate support;
+ session-only keys by default. No plaintext transport or automatic clipboard
+ overwrite during certificate discovery.
+- **Release scope:** speech, keyboard and core Braille workflows are separate
+ acceptance gates. Any reduced release must be named and documented explicitly.
+
+Review [CONTRIBUTING.md](CONTRIBUTING.md) before submitting implementation work.
+The human contributor remains responsible for reviewing the generated diff,
+testing the changed behavior and plausible regressions, and describing what was
+actually verified. This planning change does not authorize installation, active
+reader replacement, deployment, publication or submission.
diff --git a/remote/LICENSE b/remote/LICENSE
new file mode 100644
index 0000000..f6cdd22
--- /dev/null
+++ b/remote/LICENSE
@@ -0,0 +1,232 @@
+GNU GENERAL PUBLIC LICENSE
+Version 3, 29 June 2007
+
+Copyright © 2007 Free Software Foundation, Inc.
+
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
+
+Preamble
+
+The GNU General Public License is a free, copyleft license for software and other kinds of works.
+
+The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
+
+When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
+
+To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
+
+For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
+
+Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
+
+For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
+
+Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
+
+Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
+
+The precise terms and conditions for copying, distribution and modification follow.
+
+TERMS AND CONDITIONS
+
+0. Definitions.
+
+“This License” refers to version 3 of the GNU General Public License.
+
+“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
+
+“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
+
+To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
+
+A “covered work” means either the unmodified Program or a work based on the Program.
+
+To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
+
+To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
+
+An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
+
+1. Source Code.
+The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
+
+A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
+
+The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
+
+The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
+
+The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
+
+The Corresponding Source for a work in source code form is that same work.
+
+2. Basic Permissions.
+All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
+
+You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
+
+Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
+
+3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
+
+When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
+
+4. Conveying Verbatim Copies.
+You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
+
+You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
+
+5. Conveying Modified Source Versions.
+You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
+
+ c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
+
+A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
+
+6. Conveying Non-Source Forms.
+You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
+
+ d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
+
+A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
+
+A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
+
+“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
+
+If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
+
+The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
+
+Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
+
+7. Additional Terms.
+“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
+
+When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
+
+Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
+
+All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
+
+If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
+
+Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
+
+8. Termination.
+You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
+
+However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
+
+Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
+
+Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
+
+9. Acceptance Not Required for Having Copies.
+You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
+
+10. Automatic Licensing of Downstream Recipients.
+Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
+
+An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
+
+You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
+
+11. Patents.
+A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
+
+A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
+
+Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
+
+In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
+
+If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
+
+If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
+
+A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
+
+Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
+
+12. No Surrender of Others' Freedom.
+If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
+
+13. Use with the GNU Affero General Public License.
+Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
+
+14. Revised Versions of this License.
+The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
+
+If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
+
+Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
+
+15. Disclaimer of Warranty.
+THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+16. Limitation of Liability.
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+17. Interpretation of Sections 15 and 16.
+If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
+
+END OF TERMS AND CONDITIONS
+
+How to Apply These Terms to Your New Programs
+
+If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
+
+To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
+
+You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see .
+
+The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read .
diff --git a/remote/README.md b/remote/README.md
new file mode 100644
index 0000000..af8e14f
--- /dev/null
+++ b/remote/README.md
@@ -0,0 +1,87 @@
+# Remote — implementation in progress
+
+Remote will connect Cthulhu to an NVDA Remote protocol-v2 relay, as either a
+controller or a controlled computer. The first implementation increment is a
+tested Go relay library in `src/`. It is not yet a runnable or installable
+Tentacle. There is no manifest, catalog entry, connection UI or desktop access.
+
+Implemented:
+
+- Bounded newline JSON framing, duplicate-key and collection validation, and
+ typed speech, keyboard, membership, clipboard and Braille decoding.
+- TLS with normal certificate/hostname validation or an already-approved,
+ endpoint-bound SHA-256 certificate pin. Authentication sends no channel key
+ before verification. Channel keys can be generated with 256 bits of entropy.
+- Cancellable dial, TLS, join, read and write operations; serialized, bounded
+ writes; transport closure on failure or overflow.
+- Relay session validation for one opposite-role peer, origin checks, direction
+ checks, stale-generation rejection and suspension on membership changes.
+- Validated settings and separate, explicit saved-key storage with endpoint-bound
+ pins, owner-only files, symlink/hardlink rejection and atomic replacement.
+ Storage does no network I/O; see [storage.md](storage.md).
+
+The adjacent reader now also supports secret entries in transient Tentacle forms:
+masked speech/Braille editing, copy/cut denial, explicit paste and cancellation
+without returning values. Persistent preference pages reject secret entries.
+This prerequisite is covered by both SDKs and a private Xorg form harness; it
+does not yet provide Remote's connection UI. Credential storage is now supplied
+by the separate library described above.
+
+A subsequent [private Xorg feasibility increment](../../cthulhu/docs/testing/remote-input-feasibility.md)
+demonstrates exclusive capture and independent test-helper cleanup after writer
+death or heartbeat expiry. It also records why connection closure and ordinary
+input-event flags are insufficient for safe remote injection. The helper is
+test-only; trusted origin, physical-key collisions and production integration
+remain unresolved. This is partial Phase A evidence, not keyboard readiness.
+
+The reader's [Braille feasibility increment](../../cthulhu/docs/testing/remote-braille-feasibility.md)
+now reuses its existing liblouis viewport and physical writer's cell-mask logic
+to export translated virtual cells without opening a display. Private tests
+cover independent widths, contracted routing, attributes and cursor overlays.
+Virtual table/cursor policy, helper IPC, raw receiving and physical-display
+acceptance remain pending; this is not yet Remote Braille support.
+
+The reader now also implements opt-in protocol 1.1 lifecycle IPC, both SDK clients,
+explicit install grants, and expiring core-issued leases. See
+[the session contract](../../cthulhu/docs/tentacle-sessions.md). Private conformance
+and GTK tests cover this foundation. There is no production consent issuer or
+reader desktop service yet; this library is not connected to those leases.
+
+This implements relay data handling and storage only. Parsing a key, speech fragment or
+Braille gesture does not execute it. Network readiness is not consent. The
+reader must supply locally authorized leases and recheck them when effects are
+delivered. See [protocol.md](protocol.md) for the wire contract and
+[implementation.md](implementation.md) for the reader integration dependencies.
+
+## Verification
+
+From the `cthulhu-tentacles` repository:
+
+```sh
+GOCACHE=/tmp/cthulhu-cache GOPROXY=off go test -race ./remote/src -count=1 -timeout=60s
+make check
+```
+
+Tests create private loopback TLS listeners and in-memory test certificates.
+They do not connect to public relays, the active reader, an accessibility bus,
+the desktop display or a clipboard. Fixtures are independently written examples
+based on source review, **not captured NVDA sessions**. There is no live desktop
+test to run for this increment.
+
+Pending: actual NVDA/add-on/Orca interoperability, production local consent and
+reader session integration, speech delivery/export, exclusive keyboard capture,
+injection provenance and reader-death recovery, clipboard permission, connection/trust UI
+and saved-key UI actions, virtual Braille integration, physical displays and packaging. The
+full remote-control release must not be advertised until those gates pass.
+
+## Relay trust
+
+TLS protects the connection to the relay. NVDA Remote v2 is not end-to-end
+encrypted: the relay can see the channel key and session contents. Relay origin
+IDs do not authenticate human identities. Rejecting extra peers cannot undo data
+the relay already sent to them. The future UI must explain these properties
+before issuing consent.
+
+The code is an independent implementation licensed under GPL-3.0-or-later;
+see [LICENSE](LICENSE). Reference implementations, revisions and fixture
+provenance are recorded in [protocol.md](protocol.md).
diff --git a/remote/implementation.md b/remote/implementation.md
new file mode 100644
index 0000000..072827a
--- /dev/null
+++ b/remote/implementation.md
@@ -0,0 +1,104 @@
+# Remote implementation and remaining integration
+
+The design plan is [`../remote.md`](../remote.md) in this repository. This
+increment implements part of phases A and C. **Phase A is not complete**: actual
+captured NVDA fixtures and complete Xorg/Braille feasibility evidence are missing.
+It does not establish any of the release acceptance gates.
+
+## Confirmed reader boundaries
+
+Source inspection began at reader revision
+`a47253d697c1aa44dea80646cad99a4fe163c7f1`; the table includes subsequent local
+implementation increments recorded in the parent plan. Paths below
+are relative to the adjacent `cthulhu` checkout.
+
+| Area | Existing boundary to extend |
+| --- | --- |
+| Negotiation | Protocol 1.0 retains its strict prefix. Opt-in 1.1 validates explicit API/grant sets in `internal/tentaclewire/session.go`. |
+| Host transport | Bounded bidirectional lifecycle calls/events now exist, retaining the 64 KiB frame bound. Desktop streaming services remain pending. |
+| Go SDK | `ServeSession` and `SessionClient` provide 1.1 calls/events; legacy Serve remains unchanged. Real-process tests include blocked pipes and command concurrency. |
+| Python SDK | `serve(session_client=...)` provides the same 1.1 lifecycle contract and conformance fixtures as Go, with a cancellable nonblocking pipe transport. |
+| Installation | Installer, registry, discovery-to-package checks, local launch and command host now carry 1.1 install grants. Grants do not create session consent. |
+| Updates/access | Install/update confirmations disclose grant direction and fresh local approval; disable/failure cancels leases. Updates revoke access before download, including failed preparation. Production consent, lock/handoff and desktop owner integration remain pending. |
+| Secret controls | Transient entries now support `secret: true`, with masked editing/speech/Braille, copy/cut denial and no values on cancellation. Persistent preference pages reject secrets. Private Xorg/SDK tests cover this prerequisite; a Remote connection UI, audible speech and physical Braille acceptance remain pending. See [the contract](../../cthulhu/docs/tentacle-secret-entries.md). |
+| Input | `internal/platform/xorg/listener.go` uses XRecord observation. That does not consume desktop keys. A private prototype now demonstrates exclusive capture and helper EOF/watchdog cleanup; production ownership, trusted origin and physical collisions remain unresolved. See [the feasibility record](../../cthulhu/docs/testing/remote-input-feasibility.md). |
+| Braille | `internal/braille/client.go` writes text/overlay dots through a helper. Shared viewport/cell-mask feasibility tests now demonstrate translated virtual cells and independent routing without a physical display. Virtual table/cursor policy, helper IPC and raw receiving remain open. See [the evidence](../../cthulhu/docs/testing/remote-braille-feasibility.md). |
+
+Do not relax the 1.0 validators piecemeal or add a manifest claiming these APIs
+before the full reader/SDK/installer path exists. API availability and stored
+grants must be separate from ephemeral consent; a child request or injected key
+must never mint consent.
+
+## Next implementation gates
+
+1. Complete Xorg capture coexistence and physical/injected event provenance.
+ The private reader harness demonstrates grab-owner death and independent
+ helper cleanup on writer EOF/watchdog expiry, but does not establish a
+ production helper or physical-key collision safety. Shared Braille viewport
+ tests now operate without a physical target display; resolve virtual
+ table/cursor policy and implement isolated helper integration. These remaining
+ feasibility gates are not assumptions established by the relay library.
+2. The [protocol 1.1 lifecycle foundation](../../cthulhu/docs/tentacle-sessions.md)
+ now exists through both SDKs and installation. Complete production local
+ consent, lock/handoff revocation and typed desktop operations; no child request
+ may create approval. The internal authorizer currently has only test callers.
+3. Use the secret-entry support and [secure storage](storage.md) for host-issued
+ connection, certificate-review and explicit saved-key actions. Integrate the relay
+ coordinator so all transport/session failures revoke the current lease and
+ close the connection before any retry or local Resume action.
+4. Add policy-resolved output observation and remote presentation with origin
+ ownership, secure-input/lock/handoff exclusion and local status priority.
+5. Complete keyboard recovery, explicit clipboard transfer and virtual/raw
+ Braille workflows. Record physical keyboard, audible speech and physical
+ display results separately from private automated checks.
+6. Add the manifest, catalog and package tooling only after required reader APIs
+ and acceptance gates exist. No commit, installation or publication is part
+ of this increment.
+
+## Checks for this increment
+
+The lifecycle increment passed reader wire/host/preferences race suites, focused
+application Tentacle race tests and vet, and four private GTK workflows covering
+install/update confirmations, settings and extension pages. The storage increment
+adds real filesystem tests for atomic replacement, endpoint scoping, permissions,
+links, FIFO rejection, locking, malformed/oversized files and secret-free errors.
+Neither increment installs Remote or establishes live desktop acceptance.
+
+The Braille feasibility increment passed both default and brlapi-tagged Braille
+package suites with the race detector, tagged vet and a helper build. Eight new
+tests exercise shared cell masks and real liblouis viewports without opening
+BrlAPI. Physical display behavior remains pending; see the
+[evidence and regression procedure](../../cthulhu/docs/testing/remote-braille-feasibility.md).
+
+The subsequent Xorg feasibility increment adds
+`python3 -B tests/native_remote_input.py` in the reader checkout. It exercises
+private capture, key state, process death, heartbeat expiry, malformed input,
+collision limitations and restoration of application input, then runs real
+Xorg observer/internal-form/learn-mode tests with the race detector. See the
+[reader evidence record](../../cthulhu/docs/testing/remote-input-feasibility.md)
+for precise claims and pending production/physical-device gates.
+
+The secret-entry prerequisite passed focused reader race tests for interaction,
+wire validation, host/SDK conformance and internal forms; preferences unit tests;
+the private Xorg internal-UI harness; and the Tentacles repository's `make check`.
+The native harness includes existing ordinary entry, action menu, emoji picker
+and clipboard regressions. It records speech requests, not audible output, and
+does not establish physical Braille acceptance.
+
+The Remote tests cover bounded/malformed frames; exact speech command shapes;
+allowlisted gestures; one-peer roles and epochs; private CA and explicit-pin TLS;
+no application data on certificate failure; cancellation during TLS/join/read/
+write; read timeout; short/concurrent writes; and writer overflow cleanup.
+They do not implement a production relay or establish interoperability with an
+actual NVDA process. Fixture provenance is in [protocol.md](protocol.md).
+
+`make check` also builds and invokes Hello World, Wormhole and Battery Status
+through the existing command host. This checks existing SDK/registration behavior
+without installing or replacing the active reader. Review the generated diff
+before any later submission. Live desktop testing becomes meaningful only after
+reader integration; the current source library provides no command to launch.
+
+The first repository check exposed a pre-existing dependency metadata gap: the
+adjacent SDK imports reader configuration, which depends on go-toml v2.4.3.
+The Tentacles module now records that dependency (also directly used by Remote settings) and the same checksums
+already present in the reader's `go.sum`; no dependency version was upgraded.
diff --git a/remote/protocol.md b/remote/protocol.md
new file mode 100644
index 0000000..f4a27c0
--- /dev/null
+++ b/remote/protocol.md
@@ -0,0 +1,138 @@
+# Remote relay contract, first implementation increment
+
+This describes the implemented relay library, not a promise of usable desktop
+control. The host streaming API remains unimplemented. All payloads stay in the
+external Tentacle; no reader internals or output backends are imported here.
+
+## Sources and provenance
+
+Reference heads were checked on 2026-11-03:
+
+- Cthulhu `testing`: `a47253d697c1aa44dea80646cad99a4fe163c7f1`.
+- Cthulhu Tentacles `master`: `bc305993b8ad5c2374c8fc2c8b886c9cd6697b52`.
+- NVDA current head: `84756356cd19a57cfeb4ef265619e54850e06568`.
+- NVDA local reference: `2843e703ce19757711e976ebb6e9c5b689fc2017`.
+- NVDA Remote add-on: `301248945481e462601248c5e423731bd58d5e0a`.
+- churst90/orca-remote: `391f0c52044071e7cd34e3900fc13474826c312d`.
+- serrebidev/orca-remote: `9260d8284bb9f0761633dca958f5e1d9ccc37485`.
+
+The current NVDA
+[serializer](https://github.com/nvaccess/nvda/blob/84756356cd19a57cfeb4ef265619e54850e06568/source/_remoteClient/serializer.py),
+[session](https://github.com/nvaccess/nvda/blob/84756356cd19a57cfeb4ef265619e54850e06568/source/_remoteClient/session.py),
+[transport](https://github.com/nvaccess/nvda/blob/84756356cd19a57cfeb4ef265619e54850e06568/source/_remoteClient/transport.py),
+[server](https://github.com/nvaccess/nvda/blob/84756356cd19a57cfeb4ef265619e54850e06568/source/_remoteClient/server.py)
+and [input adapter](https://github.com/nvaccess/nvda/blob/84756356cd19a57cfeb4ef265619e54850e06568/source/_remoteClient/input.py)
+were downloaded for source review. Speech command fields and priorities were
+also inspected in the local NVDA reference. The current serializer, session and
+input adapter matched that local revision; the server now bounds incoming
+messages but retains the reviewed membership fields.
+
+No implementation, mapping table or test fixture was copied from NVDA or Orca.
+`src/testdata/nvda-v2.jsonl` contains independently authored synthetic examples
+of reviewed field shapes, with generic IDs and text. The optional `scan_code`
+example exercises a documented optional field, not an observed NVDA emission.
+Private test certificates are generated in memory, never distributed. No Windows
+NVDA process, standalone add-on or Orca plugin has been run against this code.
+Live captured fixtures and versioned interoperability results remain required.
+
+## Framing and validation
+
+TLS is mandatory. Each frame is a UTF-8 JSON object followed by LF. A relay frame
+may contain at most 1 MiB before LF. EOF with a partial frame fails. Parsing
+rejects invalid UTF-8, duplicate keys at every depth, trailing values, nesting
+beyond 24, more than 4,096 members per collection or more than 16,384 values.
+Additional fields are allowed but still undergo structural validation.
+
+The `type` is a nonempty printable ASCII string of at most 64 bytes. `origin`,
+when present, is a positive 32-bit integer. Boolean and numeric types are not
+interchangeable. Required values cannot be null. Errors contain fixed local
+messages; they never include channel keys, remote output or server text.
+
+| Message | Implemented representation and limits |
+| --- | --- |
+| `protocol_version`, `join` | Outbound authentication only: version 2, channel and `connection_type` of `master` or `slave`. |
+| `channel_joined` | Matching channel required. Missing `clients` means empty. A maximum of 16 peers may be parsed; session policy accepts at most one. `user_ids`, if present, must exactly match typed peers. Nonempty legacy IDs without roles fail. The echoed key is removed from returned membership. |
+| `client_joined`, `client_left` | Typed `client` requires positive `id` and known `connection_type`. Optional `user_id` must agree. ID-only legacy membership is unsupported. |
+| `speak` | Up to 1,024 sequence entries. Strings preserve whitespace and order. Numeric priority 0, 1 or 2; absence defaults to 0. Null and string priorities fail. |
+| `cancel`, `pause_speech` | Typed cancel or required boolean `switch`. No output backend is called. |
+| `key` | Required integer `vk_code` 1–255 and booleans `extended`, `pressed`. Optional integer `scan_code` 0–65,535. No VK/XKB mapping or injection yet. |
+| `set_braille_info` | Name at most 256 UTF-8 bytes; width 0–4,096. Absent fields permit the controlled peer's geometry request. Zero means no display. |
+| `set_display_size` | Required `sizes` array, at most 16 widths, each 0–4,096. |
+| `display` | Required array of at most 4,096 integer cells, each 0–255. Null cells and base64 strings fail. |
+| `braille_input` | Only the fixed global-command pan/route paths described below produce actions. Other gestures remain inert. |
+| `set_clipboard_text` | Required string, at most 8,192 UTF-8 bytes. No clipboard access is performed. |
+| `ping`, `motd` | Relay-only housekeeping. Required `motd` text is bounded and discarded; optional boolean `force_display` cannot authorize an action. |
+| `error`, `version_mismatch`, `nvda_not_connected` | Terminal session failures; no automatic reconnect. Server error text is discarded. |
+| Other types | Structurally validated and inert. Post-join peer extensions require the selected peer origin. Includes `tone`, `wave`, `send_SAS` and `index`; no path is opened or script executed. |
+
+NVDA speech commands use `[name, fields]` arrays. The parser recognizes
+`CharacterModeCommand.state`, `LangChangeCommand.lang` (null restores the
+default language) and `EndUtteranceCommand`. Extra fields such as `isDefault`
+are tolerated. Unsupported command arrays increment an utterance-local bounded
+count without retaining their names or executing them. Dictionary-shaped command
+objects are rejected. Backend language, priority and character-mode conversion,
+UTF-8 splitting into host operations, cancellation ownership and cancel-on-pause
+policy still need reader integration. The 1 MiB relay limit is not permission to
+send a 1 MiB host presentation.
+
+Braille scripts must have exactly the form
+`["globalCommands", "GlobalCommands", name]`. The only recognized names are
+`braille_scrollBack`, `braille_scrollForward` and `braille_routeTo`. Routing
+accepts a single `cellIndexes` item or legacy `routingIndex`, each 0–4,095.
+When both are supplied they must agree. Multiple routing cells are unsupported.
+Unknown modules, plugins, arbitrary script names and `kb:` commands are inert.
+Actual viewport width and generation must still be checked in core.
+
+## Session policy and ownership
+
+The external `session` state has one owner and no locks or background workers.
+It starts `joining`, becomes `waiting` after an empty channel acknowledgement,
+and becomes `ready` only with one opposite-role peer. Additional/repeated joins,
+same-role peers, peer departure, ambiguous origins and wrong-direction effects
+suspend it and clear peer identity. A suspended or closed session cannot resume;
+a local action must create a new connection and core-issued epoch. Stale-epoch
+events are rejected without changing the current state.
+
+Speech/cancel/pause/display travel from controlled to controller. Keys, Braille
+input and display sizes travel from controller to controlled. Clipboard and
+Braille information can travel both ways. None of this grants desktop access.
+Core consent and per-operation grants must be checked separately at delivery.
+
+`relayConn` owns one reader, a serialized writer and a lifetime context. Its
+context remains active after `connect` returns. Read/decode failure closes the
+socket. Explicit close and cancellation interrupt blocked I/O. Writes have a
+five-second deadline covering queue wait and transmission, at most 32 admitted
+calls and a 256 KiB aggregate byte ceiling. Overflow closes the connection;
+cleanup does not wait for writer admission. Concurrent writes cannot interleave
+frames; their relative order is unspecified, so the session owner must sequence
+speech/cancel and key transitions before submitting them.
+
+The future coordinator must close the transport immediately when `session`
+returns a terminal error, revoke the core lease on transport failure, and reject
+late network-worker results. The current tests exercise these layers separately;
+there is not yet a running Tentacle/coordinator. Transport write capacity does
+not replace the proposed separate host control/input/output queues.
+
+## Timeouts, trust and liveness
+
+Dial plus TLS has a 15-second bound. Join has a separate 15-second bound and at
+most 32 pre-join notices. Unexpected pre-join peer effects fail. Disconnect
+cancels the entire connection lifetime. No reconnect/backoff is implemented;
+authentication/trust failures require a fresh explicit attempt.
+
+CA mode uses normal system roots and hostname/IP checks. Pin mode accepts only
+the exact SHA-256 leaf certificate digest previously approved for that exact
+host string and port, replacing CA/name validation for that endpoint. Even a
+CA-valid replacement certificate fails an existing pin. Pin approval, display,
+fingerprint discovery and persistence are not implemented; callers cannot obtain
+consent merely by constructing a pin. There is no plaintext or generic insecure
+mode. Host names are separate from ports; bare IPv6 literals use `JoinHostPort`.
+
+NVDA's embedded relay sends one-way `ping` every 300 seconds. Accordingly the
+initial read deadline is six minutes; receiving a complete next frame resets it.
+TCP keepalive requests idle 10 seconds, interval 3 seconds and three probes.
+These are development transport settings, **not a proven desktop recovery
+bound**. A relay process can hang while its kernel still acknowledges probes;
+the separate core one-second heartbeat/three-second lease expiry and remote-peer
+liveness design remain required. Idle/dead relay trials, abrupt network loss,
+IPv6 connections and installed-package behavior have not been verified.
diff --git a/remote/src/braille.go b/remote/src/braille.go
new file mode 100644
index 0000000..506cc04
--- /dev/null
+++ b/remote/src/braille.go
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package remote
+
+type gesture struct {
+ action string // Empty means unsupported; never dispatch the wire script name.
+ index int
+}
+
+func decodeGesture(f fields) (gesture, error) {
+ var g gesture
+ var path []string
+ if f.optional("scriptPath", &path) != nil {
+ return g, errProtocol
+ }
+ if len(path) != 0 && len(path) != 3 {
+ return g, errProtocol
+ }
+ for _, part := range path {
+ if len(part) == 0 || !boundedText(part, 128) {
+ return g, errProtocol
+ }
+ }
+ var indexes []int
+ if _, ok := f["cellIndexes"]; ok {
+ var err error
+ indexes, err = f.integers("cellIndexes", maxCells, 0, maxCells-1)
+ if err != nil {
+ return g, err
+ }
+ }
+ index, hasLegacy := 0, false
+ if _, hasLegacy = f["routingIndex"]; hasLegacy {
+ var err error
+ index, err = f.number("routingIndex", 0, maxCells-1, false)
+ if err != nil {
+ return g, err
+ }
+ }
+ if hasLegacy && len(indexes) > 0 && (len(indexes) != 1 || indexes[0] != index) {
+ return g, errProtocol
+ }
+ if len(path) != 3 || path[0] != "globalCommands" || path[1] != "GlobalCommands" {
+ return g, nil
+ }
+ switch path[2] {
+ case "braille_scrollBack":
+ g.action = "pan-left"
+ case "braille_scrollForward":
+ g.action = "pan-right"
+ case "braille_routeTo":
+ if len(indexes) == 1 {
+ index = indexes[0]
+ } else if len(indexes) > 1 || !hasLegacy {
+ return g, nil
+ }
+ g.action, g.index = "route", index
+ }
+ return g, nil
+}
diff --git a/remote/src/protocol.go b/remote/src/protocol.go
new file mode 100644
index 0000000..62a27f7
--- /dev/null
+++ b/remote/src/protocol.go
@@ -0,0 +1,391 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+// Package remote implements the relay side of the Remote Tentacle. It has no
+// desktop access; reader integration must supply consent and effect ownership.
+package remote
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "errors"
+ "io"
+ "unicode/utf8"
+)
+
+const (
+ maxRelayFrame = 1 << 20 // Excludes the terminating LF.
+ maxTextBytes = 8192
+ maxCells = 4096
+ maxSequence = 1024
+ maxPeers = 16 // Parsing bound; session policy permits only one peer.
+)
+
+// Errors deliberately contain no server-controlled text, credentials or output.
+var (
+ errProtocol = errors.New("invalid remote relay message")
+ errLimit = errors.New("remote relay limit exceeded")
+ errPeer = errors.New("remote peer membership or origin changed")
+ errState = errors.New("remote connection is not ready")
+ errStale = errors.New("stale remote connection generation")
+)
+
+type role string
+
+const (
+ controller role = "master"
+ controlled role = "slave"
+)
+
+func (r role) valid() bool { return r == controller || r == controlled }
+
+type peer struct {
+ ID int `json:"id"`
+ Role role `json:"connection_type"`
+}
+
+type message struct {
+ kind string
+ origin int // Zero denotes absent metadata, never a peer identity.
+ payload any
+}
+
+type membership struct {
+ channel string
+ peers []peer
+}
+
+type keyTransition struct {
+ VK int `json:"vk_code"`
+ Extended bool `json:"extended"`
+ Pressed bool `json:"pressed"`
+ Scan *int `json:"scan_code,omitempty"`
+}
+
+type brailleInfo struct {
+ Name string `json:"name"`
+ Cells int `json:"numCells"`
+}
+
+// readFrame also rejects a final, unterminated fragment on EOF.
+func readFrame(r *bufio.Reader) ([]byte, error) {
+ var frame []byte
+ for {
+ part, err := r.ReadSlice('\n')
+ if len(frame)+len(part) > maxRelayFrame+1 {
+ return nil, errLimit
+ }
+ frame = append(frame, part...)
+ if err == nil {
+ return frame[:len(frame)-1], nil
+ }
+ if errors.Is(err, bufio.ErrBufferFull) {
+ continue
+ }
+ if errors.Is(err, io.EOF) && len(frame) != 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ return nil, err
+ }
+}
+
+// Validate before unmarshalling, including ignored fields. JSON object keys
+// must be unique even when escaped differently; every collection is bounded.
+func validateJSON(data []byte) error {
+ if len(data) > maxRelayFrame {
+ return errLimit
+ }
+ if !utf8.Valid(data) {
+ return errProtocol
+ }
+ d := json.NewDecoder(bytes.NewReader(data))
+ d.UseNumber()
+ nodes := 0
+ var walk func(int) error
+ walk = func(depth int) error {
+ nodes++
+ if depth > 24 || nodes > 16384 {
+ return errLimit
+ }
+ token, err := d.Token()
+ if err != nil {
+ return errProtocol
+ }
+ delim, composite := token.(json.Delim)
+ if !composite {
+ return nil
+ }
+ if delim != '[' && delim != '{' {
+ return errProtocol
+ }
+ keys := make(map[string]bool)
+ for count := 0; d.More(); count++ {
+ if count >= maxCells {
+ return errLimit
+ }
+ if delim == '{' {
+ key, err := d.Token()
+ name, ok := key.(string)
+ if err != nil || !ok || keys[name] {
+ return errProtocol
+ }
+ keys[name] = true
+ }
+ if err := walk(depth + 1); err != nil {
+ return err
+ }
+ }
+ end, err := d.Token()
+ if err != nil || delim == '[' && end != json.Delim(']') || delim == '{' && end != json.Delim('}') {
+ return errProtocol
+ }
+ return nil
+ }
+ if err := walk(0); err != nil {
+ return err
+ }
+ if _, err := d.Token(); err != io.EOF {
+ return errProtocol
+ }
+ return nil
+}
+
+type fields map[string]json.RawMessage
+
+func object(data []byte) (fields, error) {
+ var f fields
+ if json.Unmarshal(data, &f) != nil || f == nil {
+ return nil, errProtocol
+ }
+ return f, nil
+}
+
+func (f fields) required(name string, dst any) error {
+ data, ok := f[name]
+ if !ok || bytes.Equal(data, []byte("null")) || json.Unmarshal(data, dst) != nil {
+ return errProtocol
+ }
+ return nil
+}
+
+func (f fields) optional(name string, dst any) error {
+ if _, ok := f[name]; !ok {
+ return nil
+ }
+ return f.required(name, dst)
+}
+
+func (f fields) number(name string, min, max int, optional bool) (int, error) {
+ var n int
+ var err error
+ if optional {
+ err = f.optional(name, &n)
+ } else {
+ err = f.required(name, &n)
+ }
+ if err != nil || n < min || n > max {
+ return 0, errProtocol
+ }
+ return n, nil
+}
+
+func boundedText(s string, limit int) bool { return len(s) <= limit && utf8.ValidString(s) }
+
+func (f fields) integers(name string, count, min, max int) ([]int, error) {
+ var raw []json.RawMessage
+ if f.required(name, &raw) != nil {
+ return nil, errProtocol
+ }
+ if len(raw) > count {
+ return nil, errLimit
+ }
+ values := make([]int, 0, len(raw))
+ for _, item := range raw {
+ n, err := (fields{"value": item}).number("value", min, max, false)
+ if err != nil {
+ return nil, err
+ }
+ values = append(values, n)
+ }
+ return values, nil
+}
+
+func decodePeer(raw []byte) (peer, error) {
+ f, err := object(raw)
+ if err != nil {
+ return peer{}, err
+ }
+ var p peer
+ p.ID, err = f.number("id", 1, 2147483647, false)
+ if err != nil || f.required("connection_type", &p.Role) != nil || !p.Role.valid() {
+ return peer{}, errProtocol
+ }
+ return p, nil
+}
+
+func decodeMessage(data []byte) (message, error) {
+ if err := validateJSON(data); err != nil {
+ return message{}, err
+ }
+ f, err := object(data)
+ if err != nil {
+ return message{}, err
+ }
+ var m message
+ if f.required("type", &m.kind) != nil || len(m.kind) == 0 || len(m.kind) > 64 {
+ return m, errProtocol
+ }
+ for _, c := range m.kind {
+ if c < 33 || c > 126 {
+ return m, errProtocol
+ }
+ }
+ if _, ok := f["origin"]; ok {
+ m.origin, err = f.number("origin", 1, 2147483647, false)
+ if err != nil {
+ return message{}, err
+ }
+ }
+ switch m.kind {
+ case "channel_joined":
+ var v membership
+ if f.required("channel", &v.channel) != nil || len(v.channel) == 0 || !boundedText(v.channel, 512) {
+ return m, errProtocol
+ }
+ var clients []json.RawMessage
+ if f.optional("clients", &clients) != nil || len(clients) > maxPeers {
+ return m, errProtocol
+ }
+ ids := make(map[int]bool)
+ for _, raw := range clients {
+ p, err := decodePeer(raw)
+ if err != nil || ids[p.ID] {
+ return m, errProtocol
+ }
+ ids[p.ID] = true
+ v.peers = append(v.peers, p)
+ }
+ // Legacy IDs alone cannot establish a peer's role. If both variants are
+ // present, they must describe exactly the same membership.
+ if _, ok := f["user_ids"]; ok {
+ var legacy []int
+ if f.required("user_ids", &legacy) != nil || len(legacy) != len(ids) {
+ return m, errProtocol
+ }
+ for _, id := range legacy {
+ if !ids[id] {
+ return m, errProtocol
+ }
+ delete(ids, id)
+ }
+ }
+ m.payload = v
+ case "client_joined", "client_left":
+ p, err := decodePeer(f["client"])
+ if err != nil {
+ return m, err
+ }
+ if _, ok := f["user_id"]; ok {
+ id, err := f.number("user_id", 1, 2147483647, false)
+ if err != nil || id != p.ID {
+ return m, errProtocol
+ }
+ }
+ m.payload = p
+ case "speak":
+ m.payload, err = decodeSpeech(f)
+ case "cancel", "ping", "version_mismatch", "nvda_not_connected":
+ case "pause_speech":
+ var pause bool
+ err = f.required("switch", &pause)
+ m.payload = pause
+ case "key":
+ var k keyTransition
+ k.VK, err = f.number("vk_code", 1, 255, false)
+ if err != nil || f.required("extended", &k.Extended) != nil || f.required("pressed", &k.Pressed) != nil {
+ return m, errProtocol
+ }
+ if _, ok := f["scan_code"]; ok {
+ scan, err := f.number("scan_code", 0, 65535, false)
+ if err != nil {
+ return m, err
+ }
+ k.Scan = &scan
+ }
+ m.payload = k
+ case "set_braille_info":
+ // A controlled peer also sends this with no fields to request geometry.
+ var v brailleInfo
+ if f.optional("name", &v.Name) != nil || !boundedText(v.Name, 256) {
+ return m, errProtocol
+ }
+ v.Cells, err = f.number("numCells", 0, maxCells, true)
+ m.payload = v
+ case "set_display_size":
+ m.payload, err = f.integers("sizes", maxPeers, 0, maxCells)
+ case "display":
+ // []byte would encode as base64, not NVDA's integer array.
+ m.payload, err = f.integers("cells", maxCells, 0, 255)
+ case "braille_input":
+ m.payload, err = decodeGesture(f)
+ case "set_clipboard_text":
+ var text string
+ if f.required("text", &text) != nil {
+ return m, errProtocol
+ }
+ if !boundedText(text, maxTextBytes) {
+ return m, errLimit
+ }
+ m.payload = text
+ case "motd":
+ var text string
+ var force bool
+ if f.required("motd", &text) != nil || !boundedText(text, maxTextBytes) || f.optional("force_display", &force) != nil {
+ return m, errProtocol
+ }
+ // Neither the text nor force_display may authorize a local UI action.
+ case "error":
+ var text string
+ if f.required("message", &text) != nil || !boundedText(text, maxTextBytes) {
+ return m, errProtocol
+ }
+ // Server text is untrusted and never becomes an error or UI instruction.
+ default:
+ // Optional extensions (including wave, tone, send_SAS and index) are
+ // inert. Their JSON still passed all structural/resource checks.
+ }
+ return m, err
+}
+
+// encodeMessage is for peer traffic only; the transport owns authentication.
+// It refuses origin metadata because the relay assigns that field.
+func encodeMessage(kind string, payload any) ([]byte, error) {
+ data, err := json.Marshal(payload)
+ if err != nil {
+ return nil, errProtocol
+ }
+ f, err := object(data)
+ if err != nil {
+ return nil, err
+ }
+ if _, exists := f["origin"]; exists {
+ return nil, errProtocol
+ }
+ if _, exists := f["type"]; exists {
+ return nil, errProtocol
+ }
+ f["type"], _ = json.Marshal(kind)
+ data, err = json.Marshal(f)
+ if err != nil {
+ return nil, errProtocol
+ }
+ if _, err = decodeMessage(data); err != nil {
+ return nil, err
+ }
+ switch kind {
+ case "speak", "cancel", "pause_speech", "key", "set_braille_info", "set_display_size", "display", "braille_input", "set_clipboard_text":
+ return append(data, '\n'), nil
+ default:
+ return nil, errProtocol
+ }
+}
diff --git a/remote/src/protocol_test.go b/remote/src/protocol_test.go
new file mode 100644
index 0000000..66cdbc5
--- /dev/null
+++ b/remote/src/protocol_test.go
@@ -0,0 +1,236 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package remote
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "errors"
+ "io"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func mustMessage(t *testing.T, data string) message {
+ t.Helper()
+ m, err := decodeMessage([]byte(data))
+ if err != nil {
+ t.Fatalf("decode fixture: %v", err)
+ }
+ return m
+}
+
+func TestProtocolFixtures(t *testing.T) {
+ f, err := os.Open("testdata/nvda-v2.jsonl")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ r := bufio.NewReader(f)
+ count := 0
+ for {
+ frame, err := readFrame(r)
+ if errors.Is(err, io.EOF) {
+ break
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := decodeMessage(frame); err != nil {
+ t.Fatalf("fixture %d: %v", count+1, err)
+ }
+ count++
+ }
+ if count != 23 {
+ t.Fatalf("fixture count: %d", count)
+ }
+}
+
+func TestSpeechSemantics(t *testing.T) {
+ m := mustMessage(t, `{"type":"speak","origin":7,"priority":2,"sequence":[" hello ",["CharacterModeCommand",{"state":true,"isDefault":false}],"é ",["LangChangeCommand",{"lang":"fr_FR","isDefault":false}],"monde",["LangChangeCommand",{"lang":null}],["EndUtteranceCommand",{}],["PitchCommand",{"offset":4}]," "]}`)
+ s := m.payload.(speech)
+ want := []speechPart{
+ {kind: "text", text: " hello "}, {kind: "characters", characters: true},
+ {kind: "text", text: "é "}, {kind: "language", text: "fr_FR"},
+ {kind: "text", text: "monde"}, {kind: "language"}, {kind: "end"}, {kind: "text", text: " "},
+ }
+ if !reflect.DeepEqual(s.parts, want) || s.priority != 2 || s.unsupported != 1 {
+ t.Fatalf("speech semantics: %#v", s)
+ }
+ if s := mustMessage(t, `{"type":"speak","sequence":["text"]}`).payload.(speech); s.priority != 0 {
+ t.Fatal("absent priority must default to normal")
+ }
+}
+
+func TestMembershipVariants(t *testing.T) {
+ for _, fixture := range []string{
+ `{"type":"channel_joined","channel":"fixture","user_ids":[]}`,
+ `{"type":"channel_joined","channel":"fixture","clients":[]}`,
+ `{"type":"channel_joined","channel":"fixture","clients":[{"id":7,"connection_type":"slave","version":"extra"}],"user_ids":[7]}`,
+ `{"type":"client_left","client":{"id":7,"connection_type":"slave"},"user_id":7}`,
+ } {
+ mustMessage(t, fixture)
+ }
+ for _, fixture := range []string{
+ `{"type":"channel_joined","channel":"fixture","user_ids":[7]}`,
+ `{"type":"channel_joined","channel":"fixture","clients":null}`,
+ `{"type":"channel_joined","channel":"fixture","clients":[{"id":7,"connection_type":"slave"},{"id":7,"connection_type":"slave"}]}`,
+ `{"type":"channel_joined","channel":"fixture","clients":[{"id":7,"connection_type":"slave"}],"user_ids":[8]}`,
+ `{"type":"client_joined","client":{"id":7,"connection_type":"other"}}`,
+ `{"type":"client_joined","client":{"id":7,"connection_type":"slave"},"user_id":8}`,
+ `{"type":"client_left","user_id":7}`,
+ } {
+ if _, err := decodeMessage([]byte(fixture)); err == nil {
+ t.Errorf("accepted invalid membership: %s", fixture)
+ }
+ }
+}
+
+func TestRejectMalformedMessages(t *testing.T) {
+ for _, fixture := range []string{
+ `null`, `[]`, `{}`, `{"type":null}`, `{"type":"key","type":"cancel"}`,
+ `{"type":"cancel","\u0074ype":"speak"}`, `{"type":"cancel"} {}`,
+ `{"type":"cancel","extra":{"x":1,"x":2}}`, `{"type":"cancel","origin":0}`,
+ `{"type":"cancel","origin":true}`, `{"type":"cancel","origin":1.0}`,
+ `{"type":"key","vk_code":65,"extended":false}`,
+ `{"type":"key","vk_code":256,"extended":false,"pressed":true}`,
+ `{"type":"key","vk_code":65,"extended":0,"pressed":true}`,
+ `{"type":"key","vk_code":65,"extended":false,"pressed":true,"scan_code":null}`,
+ `{"type":"speak","priority":"normal","sequence":[]}`,
+ `{"type":"speak","priority":null,"sequence":[]}`,
+ `{"type":"speak","priority":3,"sequence":[]}`,
+ `{"type":"speak","sequence":[null]}`,
+ `{"type":"speak","sequence":[{"name":"CharacterModeCommand","state":true}]}`,
+ `{"type":"speak","sequence":[["CharacterModeCommand",{}]]}`,
+ `{"type":"speak","sequence":[["LangChangeCommand",{"lang":{}}]]}`,
+ `{"type":"speak","sequence":[["LangChangeCommand",{"lang":"en\n"}]]}`,
+ `{"type":"pause_speech","switch":1}`, `{"type":"display","cells":[256]}`,
+ `{"type":"display","cells":"AA=="}`, `{"type":"display","cells":[-1]}`,
+ `{"type":"display","cells":[null]}`, `{"type":"display","cells":null}`,
+ `{"type":"set_display_size","sizes":[-1]}`,
+ `{"type":"set_braille_info","numCells":4097}`,
+ `{"type":"set_clipboard_text","text":false}`,
+ `{"type":"motd","message":"incorrect field"}`,
+ `{"type":"motd","motd":"text","force_display":1}`,
+ `{"type":"braille_input","scriptPath":["globalCommands"]}`,
+ `{"type":"braille_input","routingIndex":-1}`,
+ `{"type":"braille_input","routingIndex":2,"cellIndexes":[3]}`,
+ } {
+ if _, err := decodeMessage([]byte(fixture)); err == nil {
+ t.Errorf("accepted malformed fixture: %s", fixture)
+ }
+ }
+ if _, err := decodeMessage([]byte("{\"type\":\"cancel\",\"x\":\"\xff\"}")); err == nil {
+ t.Fatal("accepted invalid UTF-8")
+ }
+}
+
+func TestCollectionAndTextBounds(t *testing.T) {
+ for _, fixture := range []string{
+ `{"type":"unknown","extra":` + strings.Repeat("[", 26) + "0" + strings.Repeat("]", 26) + "}",
+ `{"type":"display","cells":[` + strings.Repeat("0,", maxCells) + "0]}",
+ `{"type":"speak","sequence":[` + strings.Repeat(`"",`, maxSequence) + `""]}`,
+ `{"type":"set_clipboard_text","text":"` + strings.Repeat("x", maxTextBytes+1) + `"}`,
+ } {
+ if _, err := decodeMessage([]byte(fixture)); err == nil {
+ t.Fatal("accepted oversized content")
+ }
+ }
+ mustMessage(t, `{"type":"set_clipboard_text","text":"`+strings.Repeat("é", maxTextBytes/2)+`"}`)
+}
+
+func TestBrailleAllowlist(t *testing.T) {
+ cases := []struct {
+ fields string
+ want gesture
+ }{
+ {`"scriptPath":["globalCommands","GlobalCommands","braille_scrollBack"]`, gesture{action: "pan-left"}},
+ {`"scriptPath":["globalCommands","GlobalCommands","braille_scrollForward"]`, gesture{action: "pan-right"}},
+ {`"scriptPath":["globalCommands","GlobalCommands","braille_routeTo"],"routingIndex":3`, gesture{action: "route", index: 3}},
+ {`"scriptPath":["globalCommands","GlobalCommands","braille_routeTo"],"cellIndexes":[3],"routingIndex":3`, gesture{action: "route", index: 3}},
+ {`"scriptPath":["globalCommands","GlobalCommands","braille_routeTo"],"cellIndexes":[3,4]`, gesture{}},
+ {`"scriptPath":["globalCommands","GlobalCommands","kb:windows+r"]`, gesture{}},
+ {`"scriptPath":["plugin","GlobalPlugin","braille_scrollBack"]`, gesture{}},
+ {`"dots":7,"space":true`, gesture{}},
+ }
+ for _, tc := range cases {
+ g := mustMessage(t, `{"type":"braille_input",`+tc.fields+`}`).payload.(gesture)
+ if g != tc.want {
+ t.Errorf("gesture: got %#v want %#v", g, tc.want)
+ }
+ }
+}
+
+type fragmentReader struct{ io.Reader }
+
+func (r fragmentReader) Read(p []byte) (int, error) {
+ if len(p) > 3 {
+ p = p[:3]
+ }
+ return r.Reader.Read(p)
+}
+
+func TestFraming(t *testing.T) {
+ r := bufio.NewReaderSize(fragmentReader{strings.NewReader("first\nsecond\npartial")}, 16)
+ for _, want := range []string{"first", "second"} {
+ got, err := readFrame(r)
+ if err != nil || string(got) != want {
+ t.Fatalf("fragmented read: %q %v", got, err)
+ }
+ }
+ if _, err := readFrame(r); !errors.Is(err, io.ErrUnexpectedEOF) {
+ t.Fatalf("unterminated frame: %v", err)
+ }
+ for _, n := range []int{maxRelayFrame, maxRelayFrame + 1} {
+ got, err := readFrame(bufio.NewReader(strings.NewReader(strings.Repeat("x", n) + "\n")))
+ if n == maxRelayFrame && (err != nil || len(got) != n) || n > maxRelayFrame && !errors.Is(err, errLimit) {
+ t.Fatalf("boundary %d: %v", n, err)
+ }
+ }
+ if _, err := readFrame(bufio.NewReader(strings.NewReader(strings.Repeat("x", maxRelayFrame+8192)))); !errors.Is(err, errLimit) {
+ t.Fatalf("unbounded no-newline read: %v", err)
+ }
+}
+
+func TestOutboundFrames(t *testing.T) {
+ frame, err := encodeMessage("key", keyTransition{VK: 65, Pressed: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ m, err := decodeMessage(bytes.TrimSuffix(frame, []byte{'\n'}))
+ if err != nil || m.payload.(keyTransition).Scan != nil {
+ t.Fatalf("key roundtrip: %v", err)
+ }
+ frame, err = encodeMessage("display", struct {
+ Cells []int `json:"cells"`
+ }{[]int{0, 128, 255}})
+ if err != nil || !bytes.Contains(frame, []byte(`[0,128,255]`)) {
+ t.Fatal("cells must remain JSON integers")
+ }
+ for _, p := range []any{map[string]any{"origin": 7}, map[string]any{"type": "key"}, nil} {
+ if _, err := encodeMessage("cancel", p); err == nil {
+ t.Fatal("accepted metadata override")
+ }
+ }
+ if _, err := encodeMessage("send_SAS", struct{}{}); err == nil {
+ t.Fatal("encoded unsupported effect")
+ }
+}
+
+func FuzzDecodeMessage(f *testing.F) {
+ for _, s := range []string{`{"type":"cancel","origin":7}`, `{"type":"speak","sequence":["text"]}`, `{"type":"display","cells":[0,255]}`, `null`} {
+ f.Add([]byte(s))
+ }
+ f.Fuzz(func(t *testing.T, data []byte) {
+ m, err := decodeMessage(data)
+ if err != nil {
+ return
+ }
+ if !json.Valid(data) || m.kind == "" {
+ t.Fatal("accepted invalid message")
+ }
+ })
+}
diff --git a/remote/src/session.go b/remote/src/session.go
new file mode 100644
index 0000000..2d5e693
--- /dev/null
+++ b/remote/src/session.go
@@ -0,0 +1,124 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package remote
+
+// session is a single-owner relay membership state machine, not a reader access
+// lease. Only core may authorize desktop effects. Every delivery and send must
+// separately recheck that lease after this layer has checked the relay epoch.
+type session struct {
+ role role
+ epoch uint64
+ state string // joining, waiting, ready, suspended, closed
+ peer peer
+ ignored uint64 // Saturating counter; never stores untrusted diagnostic text.
+}
+
+func newSession(r role, epoch uint64) (*session, error) {
+ if !r.valid() || epoch == 0 {
+ return nil, errProtocol
+ }
+ return &session{role: r, epoch: epoch, state: "joining"}, nil
+}
+
+func (s *session) suspend(err error) (bool, error) {
+ s.state, s.peer = "suspended", peer{}
+ return false, err
+}
+
+func (s *session) close() { s.state, s.peer = "closed", peer{} }
+
+// accept returns true only for an understood peer payload. Membership and
+// keepalive messages update state but never become desktop effects. A rejected
+// current-epoch message suspends the connection until an explicit new session.
+func (s *session) accept(epoch uint64, m message) (bool, error) {
+ if epoch != s.epoch {
+ return false, errStale
+ }
+ if s.state == "closed" || s.state == "suspended" {
+ return false, errState
+ }
+ switch m.kind {
+ case "channel_joined":
+ v, ok := m.payload.(membership)
+ if !ok || s.state != "joining" || len(v.peers) > 1 {
+ return s.suspend(errPeer)
+ }
+ s.state = "waiting"
+ if len(v.peers) == 1 {
+ if v.peers[0].Role == s.role {
+ return s.suspend(errPeer)
+ }
+ s.peer, s.state = v.peers[0], "ready"
+ }
+ return false, nil
+ case "client_joined":
+ p, ok := m.payload.(peer)
+ if !ok || s.state != "waiting" || p.Role == s.role || m.origin != 0 && m.origin != p.ID {
+ return s.suspend(errPeer)
+ }
+ s.peer, s.state = p, "ready"
+ return false, nil
+ case "client_left":
+ // Even an unexpected departure signals an ambiguous membership history.
+ return s.suspend(errPeer)
+ case "error", "version_mismatch", "nvda_not_connected":
+ return s.suspend(errProtocol)
+ case "ping", "motd":
+ if m.origin != 0 {
+ return s.suspend(errPeer)
+ }
+ return false, nil
+ }
+ if s.state != "ready" || m.origin != s.peer.ID {
+ return s.suspend(errPeer)
+ }
+ if !knownEffect(m.kind) {
+ if s.ignored != ^uint64(0) {
+ s.ignored++
+ }
+ return false, nil
+ }
+ if !roleCanSend(s.peer.Role, m.kind) {
+ return s.suspend(errPeer)
+ }
+ if g, ok := m.payload.(gesture); ok && g.action == "" {
+ if s.ignored != ^uint64(0) {
+ s.ignored++
+ }
+ return false, nil
+ }
+ return true, nil
+}
+
+func knownEffect(kind string) bool {
+ switch kind {
+ case "speak", "cancel", "pause_speech", "display", "key", "braille_input", "set_display_size", "set_braille_info", "set_clipboard_text":
+ return true
+ }
+ return false
+}
+
+func roleCanSend(r role, kind string) bool {
+ switch kind {
+ case "set_braille_info", "set_clipboard_text":
+ return r.valid()
+ case "speak", "cancel", "pause_speech", "display":
+ return r == controlled
+ case "key", "braille_input", "set_display_size":
+ return r == controller
+ }
+ return false
+}
+
+func (s *session) allowSend(epoch uint64, kind string) error {
+ if epoch != s.epoch {
+ return errStale
+ }
+ if s.state != "ready" {
+ return errState
+ }
+ if !roleCanSend(s.role, kind) {
+ return errProtocol
+ }
+ return nil
+}
diff --git a/remote/src/session_test.go b/remote/src/session_test.go
new file mode 100644
index 0000000..bbd3c38
--- /dev/null
+++ b/remote/src/session_test.go
@@ -0,0 +1,119 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package remote
+
+import (
+ "errors"
+ "testing"
+)
+
+func readySession(t *testing.T, r role) *session {
+ t.Helper()
+ s, err := newSession(r, 1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ opposite := controller
+ if r == controller {
+ opposite = controlled
+ }
+ _, err = s.accept(1, message{kind: "channel_joined", payload: membership{peers: []peer{{ID: 7, Role: opposite}}}})
+ if err != nil || s.state != "ready" {
+ t.Fatalf("ready: %v", err)
+ }
+ return s
+}
+
+func TestSessionRoleDirections(t *testing.T) {
+ for _, r := range []role{controller, controlled} {
+ for _, kind := range []string{"speak", "cancel", "pause_speech", "display", "key", "braille_input", "set_braille_info", "set_display_size", "set_clipboard_text"} {
+ s := readySession(t, r)
+ want := roleCanSend(s.peer.Role, kind)
+ accepted, err := s.accept(1, message{kind: kind, origin: 7})
+ if accepted != want || (err == nil) != want {
+ t.Fatalf("role %s kind %s: %v %v", r, kind, accepted, err)
+ }
+ if !want && s.state != "suspended" {
+ t.Fatal("wrong role did not suspend")
+ }
+ }
+ }
+}
+
+func TestSessionMembershipAndEpoch(t *testing.T) {
+ s, _ := newSession(controller, 9)
+ if _, err := s.accept(8, message{kind: "client_left"}); !errors.Is(err, errStale) || s.state != "joining" {
+ t.Fatal("old epoch changed session")
+ }
+ if _, err := s.accept(9, mustMessage(t, `{"type":"channel_joined","channel":"fixture","user_ids":[]}`)); err != nil || s.state != "waiting" {
+ t.Fatal("empty channel should wait")
+ }
+ if err := s.allowSend(9, "key"); !errors.Is(err, errState) {
+ t.Fatal("sent without peer")
+ }
+ if _, err := s.accept(9, mustMessage(t, `{"type":"client_joined","origin":7,"user_id":7,"client":{"id":7,"connection_type":"slave"}}`)); err != nil || s.state != "ready" {
+ t.Fatal("peer did not become ready")
+ }
+ if err := s.allowSend(8, "key"); !errors.Is(err, errStale) {
+ t.Fatal("sent old epoch")
+ }
+ if err := s.allowSend(9, "key"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.accept(9, mustMessage(t, `{"type":"client_left","origin":7,"client":{"id":7,"connection_type":"slave"}}`)); !errors.Is(err, errPeer) || s.peer.ID != 0 || s.state != "suspended" {
+ t.Fatal("departure did not revoke peer")
+ }
+ if _, err := s.accept(9, mustMessage(t, `{"type":"client_joined","client":{"id":8,"connection_type":"slave"}}`)); !errors.Is(err, errState) {
+ t.Fatal("silently resumed")
+ }
+ if err := s.allowSend(9, "key"); !errors.Is(err, errState) {
+ t.Fatal("sent after departure")
+ }
+}
+
+func TestSessionFailsClosed(t *testing.T) {
+ for _, fixture := range []string{
+ `{"type":"speak","sequence":["text"]}`,
+ `{"type":"speak","origin":8,"sequence":["text"]}`,
+ `{"type":"client_joined","client":{"id":8,"connection_type":"slave"}}`,
+ `{"type":"client_joined","client":{"id":7,"connection_type":"slave"}}`,
+ `{"type":"channel_joined","channel":"fixture"}`,
+ `{"type":"ping","origin":7}`,
+ `{"type":"error","message":"private server content"}`,
+ } {
+ s := readySession(t, controller)
+ if ok, err := s.accept(1, mustMessage(t, fixture)); err == nil || ok || s.state != "suspended" {
+ t.Errorf("did not suspend: %s", fixture)
+ }
+ }
+ for _, peers := range [][]peer{{{ID: 7, Role: controller}}, {{ID: 7, Role: controlled}, {ID: 8, Role: controlled}}} {
+ s, _ := newSession(controller, 1)
+ if _, err := s.accept(1, message{kind: "channel_joined", payload: membership{peers: peers}}); err == nil {
+ t.Fatal("accepted unsafe membership")
+ }
+ }
+ s, _ := newSession(controlled, 1)
+ if _, err := s.accept(1, mustMessage(t, `{"type":"key","origin":7,"vk_code":65,"pressed":true,"extended":false}`)); err == nil {
+ t.Fatal("effect before handshake")
+ }
+}
+
+func TestSessionIgnoresUnsupportedEffects(t *testing.T) {
+ s := readySession(t, controlled)
+ for _, fixture := range []string{
+ `{"type":"send_SAS","origin":7}`,
+ `{"type":"wave","origin":7,"fileName":"do-not-open.wav"}`,
+ `{"type":"braille_input","origin":7,"scriptPath":["globalCommands","GlobalCommands","kb:windows+r"]}`,
+ } {
+ if ok, err := s.accept(1, mustMessage(t, fixture)); ok || err != nil {
+ t.Fatalf("unsupported effect: %v %v", ok, err)
+ }
+ }
+ if s.ignored != 3 {
+ t.Fatal("missing bounded diagnostic count")
+ }
+ s.close()
+ if _, err := s.accept(1, mustMessage(t, `{"type":"cancel","origin":7}`)); !errors.Is(err, errState) {
+ t.Fatal("closed session accepted output")
+ }
+}
diff --git a/remote/src/settings.go b/remote/src/settings.go
new file mode 100644
index 0000000..971f37e
--- /dev/null
+++ b/remote/src/settings.go
@@ -0,0 +1,308 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package remote
+
+import (
+ "bytes"
+ "crypto/rand"
+ "encoding/hex"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "syscall"
+
+ "github.com/pelletier/go-toml/v2"
+)
+
+var errSettings = errors.New("remote settings are unavailable or unsafe")
+
+const maxSettingsBytes = 8 * 1024
+
+// No key, lease, peer, startup-connect or reusable session consent belongs in
+// ordinary settings. Saved pins are trust decisions bound to a single endpoint.
+type settings struct {
+ Version int `toml:"version"`
+ Role string `toml:"role"`
+ Host string `toml:"host"`
+ Port int `toml:"port"`
+ Pin *savedPin `toml:"pin,omitempty"`
+}
+
+type savedPin struct {
+ Host string `toml:"host"`
+ Port int `toml:"port"`
+ SHA256 string `toml:"sha256"`
+}
+
+type savedKey struct {
+ Version int `toml:"version"`
+ Host string `toml:"host"`
+ Port int `toml:"port"`
+ Key string `toml:"key"`
+}
+
+func (value settings) endpoint() (endpoint, error) {
+ e := endpoint{host: value.Host, port: value.Port}
+ if value.Version != 1 || (value.Role != "controller" && value.Role != "controlled") {
+ return endpoint{}, errSettings
+ }
+ if value.Pin != nil {
+ digest, err := hex.DecodeString(value.Pin.SHA256)
+ if err != nil || len(digest) != 32 || hex.EncodeToString(digest) != value.Pin.SHA256 {
+ return endpoint{}, errSettings
+ }
+ pin := certificatePin{host: value.Pin.Host, port: value.Pin.Port}
+ copy(pin.sha256[:], digest)
+ e.pin = &pin
+ }
+ if _, err := e.tlsConfig(); err != nil {
+ return endpoint{}, errSettings
+ }
+ return e, nil
+}
+
+// settingsStore owns a directory descriptor, not a pathname reopened per write.
+// Opening/loading it does no network I/O. The caller chooses when to read a saved
+// key; there is no automatic connection or restore of session permissions.
+type settingsStore struct {
+ mu sync.Mutex
+ directory *os.File
+}
+
+// Parents must already exist. Reject symlinks in every path component and require
+// a private, current-user final directory. This deliberately refuses a symlinked
+// settings location instead of silently weakening credential handling.
+func openSettingsStore(path string) (*settingsStore, error) {
+ if !filepath.IsAbs(path) || filepath.Clean(path) != path || path == "/" {
+ return nil, errSettings
+ }
+ fd, err := syscall.Open("/", syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_CLOEXEC, 0)
+ if err != nil {
+ return nil, errSettings
+ }
+ components := strings.Split(strings.TrimPrefix(path, "/"), "/")
+ for index, component := range components {
+ next, openErr := syscall.Openat(fd, component, syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0)
+ if openErr == syscall.ENOENT && index == len(components)-1 {
+ mkdirErr := syscall.Mkdirat(fd, component, 0700)
+ if mkdirErr != nil && mkdirErr != syscall.EEXIST {
+ syscall.Close(fd)
+ return nil, errSettings
+ }
+ next, openErr = syscall.Openat(fd, component, syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0)
+ }
+ syscall.Close(fd)
+ if openErr != nil {
+ return nil, errSettings
+ }
+ fd = next
+ }
+ directory := os.NewFile(uintptr(fd), "remote-settings")
+ if !privateFile(directory, true) {
+ directory.Close()
+ return nil, errSettings
+ }
+ return &settingsStore{directory: directory}, nil
+}
+
+func privateFile(file *os.File, directory bool) bool {
+ var stat syscall.Stat_t
+ if syscall.Fstat(int(file.Fd()), &stat) != nil || stat.Uid != uint32(os.Getuid()) || stat.Mode&0077 != 0 {
+ return false
+ }
+ if directory {
+ return stat.Mode&syscall.S_IFMT == syscall.S_IFDIR
+ }
+ return stat.Mode&syscall.S_IFMT == syscall.S_IFREG && stat.Nlink == 1
+}
+
+func (store *settingsStore) close() {
+ store.mu.Lock()
+ defer store.mu.Unlock()
+ if store.directory != nil {
+ store.directory.Close()
+ store.directory = nil
+ }
+}
+
+// Lock cooperating processes as well as callers. Existing unsafe lock files are
+// rejected; diagnostics never include a path, credential, or parser excerpt.
+func (store *settingsStore) lock() (*os.File, error) {
+ if store.directory == nil || !privateFile(store.directory, true) {
+ return nil, errSettings
+ }
+ fd, err := syscall.Openat(int(store.directory.Fd()), ".lock", syscall.O_RDWR|syscall.O_CREAT|syscall.O_NONBLOCK|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0600)
+ if err != nil {
+ return nil, errSettings
+ }
+ lock := os.NewFile(uintptr(fd), "remote-settings-lock")
+ if !privateFile(lock, false) || syscall.Flock(fd, syscall.LOCK_EX|syscall.LOCK_NB) != nil {
+ lock.Close()
+ return nil, errSettings
+ }
+ return lock, nil // Close releases flock.
+}
+
+func (store *settingsStore) read(name string) ([]byte, error) {
+ fd, err := syscall.Openat(int(store.directory.Fd()), name, syscall.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0)
+ if err == syscall.ENOENT {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, errSettings
+ }
+ file := os.NewFile(uintptr(fd), "remote-settings-data")
+ defer file.Close()
+ if !privateFile(file, false) {
+ return nil, errSettings
+ }
+ data, err := io.ReadAll(io.LimitReader(file, maxSettingsBytes+1))
+ if err != nil || len(data) > maxSettingsBytes {
+ return nil, errSettings
+ }
+ return data, nil
+}
+
+func (store *settingsStore) replace(name string, value any) error {
+ data, err := toml.Marshal(value)
+ if err != nil || len(data) > maxSettingsBytes {
+ return errSettings
+ }
+ // Refuse existing links/special files rather than replacing them silently.
+ if _, err := store.read(name); err != nil {
+ return err
+ }
+ var nonce [16]byte
+ if _, err := rand.Read(nonce[:]); err != nil {
+ return errSettings
+ }
+ temporary := ".pending-" + hex.EncodeToString(nonce[:])
+ dirfd := int(store.directory.Fd())
+ fd, err := syscall.Openat(dirfd, temporary, syscall.O_WRONLY|syscall.O_CREAT|syscall.O_EXCL|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0600)
+ if err != nil {
+ return errSettings
+ }
+ file := os.NewFile(uintptr(fd), "remote-settings-pending")
+ defer file.Close()
+ defer syscall.Unlinkat(dirfd, temporary)
+ if _, err := file.Write(data); err != nil {
+ return errSettings
+ }
+ if file.Sync() != nil || file.Close() != nil {
+ return errSettings
+ }
+ if syscall.Renameat(dirfd, temporary, dirfd, name) != nil || store.directory.Sync() != nil {
+ return errSettings
+ }
+ return nil
+}
+
+func decodeSettings(data []byte, value any) error {
+ if toml.NewDecoder(bytes.NewReader(data)).DisallowUnknownFields().Decode(value) != nil {
+ return errSettings
+ }
+ return nil
+}
+
+func (store *settingsStore) save(value settings) error {
+ if _, err := value.endpoint(); err != nil {
+ return err
+ }
+ store.mu.Lock()
+ defer store.mu.Unlock()
+ lock, err := store.lock()
+ if err != nil {
+ return err
+ }
+ defer lock.Close()
+ return store.replace("settings.toml", value)
+}
+
+func (store *settingsStore) load() (settings, bool, error) {
+ store.mu.Lock()
+ defer store.mu.Unlock()
+ lock, err := store.lock()
+ if err != nil {
+ return settings{}, false, err
+ }
+ defer lock.Close()
+ data, err := store.read("settings.toml")
+ if err != nil || data == nil {
+ return settings{}, false, err
+ }
+ var value settings
+ if decodeSettings(data, &value) != nil {
+ return settings{}, false, errSettings
+ }
+ if _, err := value.endpoint(); err != nil {
+ return settings{}, false, err
+ }
+ return value, true, nil
+}
+
+// rememberKey must be called only for an explicit local Remember key decision.
+// Pins are stored only in settings; secret state is independently replaceable.
+func (store *settingsStore) rememberKey(e endpoint, key string) error {
+ if _, err := e.tlsConfig(); err != nil || !validChannelKey(key) {
+ return errSettings
+ }
+ store.mu.Lock()
+ defer store.mu.Unlock()
+ lock, err := store.lock()
+ if err != nil {
+ return err
+ }
+ defer lock.Close()
+ return store.replace("channel-key.toml", savedKey{Version: 1, Host: e.host, Port: e.port, Key: key})
+}
+
+func (store *settingsStore) loadKey(e endpoint) (string, error) {
+ if _, err := e.tlsConfig(); err != nil {
+ return "", errSettings
+ }
+ store.mu.Lock()
+ defer store.mu.Unlock()
+ lock, err := store.lock()
+ if err != nil {
+ return "", err
+ }
+ defer lock.Close()
+ data, err := store.read("channel-key.toml")
+ if err != nil || data == nil {
+ return "", err
+ }
+ var value savedKey
+ if decodeSettings(data, &value) != nil || value.Version != 1 || !validChannelKey(value.Key) {
+ return "", errSettings
+ }
+ if _, err := (endpoint{host: value.Host, port: value.Port}).tlsConfig(); err != nil {
+ return "", errSettings
+ }
+ if value.Host != e.host || value.Port != e.port {
+ return "", nil
+ }
+ return value.Key, nil
+}
+
+// forgetKey reports failure; callers must not claim forgetting succeeded if it
+// could not remove/sync the credential. Removal is not secure disk erasure.
+func (store *settingsStore) forgetKey() error {
+ store.mu.Lock()
+ defer store.mu.Unlock()
+ lock, err := store.lock()
+ if err != nil {
+ return err
+ }
+ defer lock.Close()
+ data, err := store.read("channel-key.toml")
+ if err != nil || data == nil {
+ return err
+ }
+ if syscall.Unlinkat(int(store.directory.Fd()), "channel-key.toml") != nil || store.directory.Sync() != nil {
+ return errSettings
+ }
+ return nil
+}
diff --git a/remote/src/settings_test.go b/remote/src/settings_test.go
new file mode 100644
index 0000000..43391d2
--- /dev/null
+++ b/remote/src/settings_test.go
@@ -0,0 +1,268 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package remote
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "testing"
+)
+
+func settingsFixture(t *testing.T) (*settingsStore, string, settings) {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "remote")
+ store, err := openSettingsStore(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(store.close)
+ return store, path, settings{Version: 1, Role: "controller", Host: "relay.invalid", Port: 6837}
+}
+
+func TestSettingsAndExplicitSavedKeyRoundTrip(t *testing.T) {
+ store, path, value := settingsFixture(t)
+ if _, exists, err := store.load(); err != nil || exists {
+ t.Fatal("new store has settings", exists, err)
+ }
+ e, err := value.endpoint()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if key, err := store.loadKey(e); err != nil || key != "" {
+ t.Fatal("key stored by default")
+ }
+ if err := store.save(value); err != nil {
+ t.Fatal(err)
+ }
+ key := "private-fixture-猫-key"
+ if err := store.rememberKey(e, key); err != nil {
+ t.Fatal(err)
+ }
+ ordinary, err := os.ReadFile(filepath.Join(path, "settings.toml"))
+ if err != nil || strings.Contains(string(ordinary), key) {
+ t.Fatal("ordinary settings contain secret")
+ }
+ for _, name := range []string{"settings.toml", "channel-key.toml", ".lock"} {
+ info, err := os.Stat(filepath.Join(path, name))
+ if err != nil || info.Mode().Perm() != 0600 {
+ t.Fatal("file permissions", name, err)
+ }
+ }
+ info, err := os.Stat(path)
+ if err != nil || info.Mode().Perm() != 0700 {
+ t.Fatal("directory permissions", err)
+ }
+ store.close()
+ reopened, err := openSettingsStore(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reopened.close()
+ got, exists, err := reopened.load()
+ if err != nil || !exists || got != value {
+ t.Fatal("settings restart", got, exists, err)
+ }
+ saved, err := reopened.loadKey(e)
+ if err != nil || saved != key {
+ t.Fatal("credential restart failed")
+ }
+ for _, other := range []endpoint{{host: "other.invalid", port: e.port}, {host: e.host, port: e.port + 1}} {
+ saved, err := reopened.loadKey(other)
+ if err != nil || saved != "" {
+ t.Fatal("credential crossed endpoint")
+ }
+ }
+ before, err := os.Stat(filepath.Join(path, "channel-key.toml"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reopened.rememberKey(e, "replacement-fixture"); err != nil {
+ t.Fatal(err)
+ }
+ after, err := os.Stat(filepath.Join(path, "channel-key.toml"))
+ if err != nil || os.SameFile(before, after) {
+ t.Fatal("credential was not atomically replaced")
+ }
+ files, err := os.ReadDir(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, file := range files {
+ if strings.HasPrefix(file.Name(), ".pending-") {
+ t.Fatal("temporary credential retained")
+ }
+ }
+ if err := reopened.forgetKey(); err != nil {
+ t.Fatal(err)
+ }
+ if err := reopened.forgetKey(); err != nil {
+ t.Fatal("forget not idempotent", err)
+ }
+ if key, err := reopened.loadKey(e); err != nil || key != "" {
+ t.Fatal("forgotten credential returned")
+ }
+}
+
+func TestSettingsPinIsBoundToEndpoint(t *testing.T) {
+ store, _, value := settingsFixture(t)
+ value.Pin = &savedPin{Host: value.Host, Port: value.Port, SHA256: strings.Repeat("ab", 32)}
+ if err := store.save(value); err != nil {
+ t.Fatal(err)
+ }
+ got, exists, err := store.load()
+ if err != nil || !exists {
+ t.Fatal(err)
+ }
+ e, err := got.endpoint()
+ if err != nil || e.pin == nil || e.pin.host != value.Host || e.pin.port != value.Port {
+ t.Fatal("pin lost", err)
+ }
+ for _, variant := range []string{"host", "port", "zero", "invalid", "uppercase"} {
+ t.Run(variant, func(t *testing.T) {
+ copyValue := value
+ pin := *value.Pin
+ copyValue.Pin = &pin
+ switch variant {
+ case "host":
+ pin.Host = "other.invalid"
+ case "port":
+ pin.Port++
+ case "zero":
+ pin.SHA256 = strings.Repeat("0", 64)
+ case "invalid":
+ pin.SHA256 = "not-a-fingerprint"
+ case "uppercase":
+ pin.SHA256 = strings.ToUpper(pin.SHA256)
+ }
+ if err := store.save(copyValue); !errors.Is(err, errSettings) {
+ t.Fatal("unsafe pin accepted", err)
+ }
+ })
+ }
+}
+
+func TestSettingsRejectUnsafeStorage(t *testing.T) {
+ for _, variant := range []string{"directory mode", "directory symlink", "ancestor symlink", "file mode", "file symlink", "hardlink", "fifo", "lock symlink", "lock mode", "lock busy"} {
+ t.Run(variant, func(t *testing.T) {
+ store, path, value := settingsFixture(t)
+ e, _ := value.endpoint()
+ sentinel := filepath.Join(t.TempDir(), "sentinel")
+ if err := os.WriteFile(sentinel, []byte("unrelated sentinel"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ keyPath := filepath.Join(path, "channel-key.toml")
+ var failure error
+ switch variant {
+ case "directory mode":
+ if err := os.Chmod(path, 0755); err != nil {
+ t.Fatal(err)
+ }
+ _, failure = store.loadKey(e)
+ if other, err := openSettingsStore(path); err == nil {
+ other.close()
+ t.Fatal("unsafe directory opened")
+ }
+ case "directory symlink":
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(path, link); err != nil {
+ t.Fatal(err)
+ }
+ _, failure = openSettingsStore(link)
+ case "ancestor symlink":
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(filepath.Dir(path), link); err != nil {
+ t.Fatal(err)
+ }
+ _, failure = openSettingsStore(filepath.Join(link, "remote"))
+ case "file mode":
+ if err := os.WriteFile(keyPath, []byte("private-fixture"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ failure = store.rememberKey(e, "new-fixture")
+ case "file symlink":
+ if err := os.Symlink(sentinel, keyPath); err != nil {
+ t.Fatal(err)
+ }
+ failure = store.rememberKey(e, "new-fixture")
+ case "hardlink":
+ if err := os.Link(sentinel, keyPath); err != nil {
+ t.Fatal(err)
+ }
+ failure = store.rememberKey(e, "new-fixture")
+ case "fifo":
+ if err := syscall.Mkfifo(keyPath, 0600); err != nil {
+ t.Fatal(err)
+ }
+ _, failure = store.loadKey(e)
+ case "lock symlink":
+ if err := os.Symlink(sentinel, filepath.Join(path, ".lock")); err != nil {
+ t.Fatal(err)
+ }
+ failure = store.save(value)
+ case "lock mode":
+ if err := os.WriteFile(filepath.Join(path, ".lock"), nil, 0644); err != nil {
+ t.Fatal(err)
+ }
+ failure = store.save(value)
+ case "lock busy":
+ lock, err := store.lock()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer lock.Close()
+ failure = store.save(value)
+ }
+ if !errors.Is(failure, errSettings) {
+ t.Fatal("unsafe storage accepted", failure)
+ }
+ data, err := os.ReadFile(sentinel)
+ if err != nil || string(data) != "unrelated sentinel" {
+ t.Fatal("unrelated file changed")
+ }
+ })
+ }
+}
+
+func TestSettingsRejectUnknownMalformedAndOversizedValues(t *testing.T) {
+ for _, data := range []string{
+ "version=2\nrole='controller'\nhost='relay.invalid'\nport=6837\n",
+ "version=1\nrole='controller'\nhost='relay.invalid'\nport=6837\nauto-connect=true\n",
+ "version=1\nrole='controller'\nhost='relay.invalid'\nport=6837\nkey='private-fixture'\n",
+ "version=1\nrole='other'\nhost='relay.invalid'\nport=6837\n",
+ "version=1\nrole='controller'\nhost='relay.invalid'\nport=0\n",
+ "version=1\nrole='controller'\nhost='relay.invalid/path'\nport=6837\n",
+ "version=1\nrole='controller'\nhost='relay.invalid'\nport=6837\nport=6838\n",
+ "private-fixture='unterminated",
+ strings.Repeat("private-fixture", maxSettingsBytes),
+ } {
+ t.Run("invalid", func(t *testing.T) {
+ store, path, _ := settingsFixture(t)
+ if err := os.WriteFile(filepath.Join(path, "settings.toml"), []byte(data), 0600); err != nil {
+ t.Fatal(err)
+ }
+ _, exists, err := store.load()
+ if exists || !errors.Is(err, errSettings) || strings.Contains(err.Error(), "private-fixture") {
+ t.Fatal("invalid settings accepted or leaked")
+ }
+ })
+ }
+ store, path, value := settingsFixture(t)
+ e, _ := value.endpoint()
+ for _, key := range []string{"", "line\nbreak", strings.Repeat("x", 513), string([]byte{0xff})} {
+ if err := store.rememberKey(e, key); !errors.Is(err, errSettings) {
+ t.Fatal("invalid credential saved")
+ }
+ }
+ if err := os.WriteFile(filepath.Join(path, "channel-key.toml"), []byte("key='private-fixture'"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if key, err := store.loadKey(e); key != "" || !errors.Is(err, errSettings) || strings.Contains(err.Error(), "private-fixture") {
+ t.Fatal("invalid key file accepted or exposed")
+ }
+ store.close()
+ if err := store.save(value); !errors.Is(err, errSettings) {
+ t.Fatal("closed store accepted write")
+ }
+}
diff --git a/remote/src/speech.go b/remote/src/speech.go
new file mode 100644
index 0000000..4d94812
--- /dev/null
+++ b/remote/src/speech.go
@@ -0,0 +1,90 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package remote
+
+import (
+ "bytes"
+ "encoding/json"
+)
+
+type speechPart struct {
+ kind string // text, characters, language, end
+ text string
+ characters bool
+}
+
+type speech struct {
+ parts []speechPart
+ priority int // NVDA NORMAL=0, NEXT=1, NOW=2; absent means NORMAL.
+ unsupported int
+}
+
+func decodeSpeech(f fields) (speech, error) {
+ var s speech
+ var err error
+ s.priority, err = f.number("priority", 0, 2, true)
+ if err != nil {
+ return s, err
+ }
+ var sequence []json.RawMessage
+ if f.required("sequence", &sequence) != nil {
+ return s, errProtocol
+ }
+ if len(sequence) > maxSequence {
+ return s, errLimit
+ }
+ textBytes := 0
+ for _, item := range sequence {
+ var text string
+ if len(item) > 0 && item[0] == '"' && json.Unmarshal(item, &text) == nil {
+ textBytes += len(text)
+ if textBytes > maxRelayFrame {
+ return s, errLimit
+ }
+ s.parts = append(s.parts, speechPart{kind: "text", text: text})
+ continue
+ }
+ var command []json.RawMessage
+ if json.Unmarshal(item, &command) != nil || len(command) != 2 {
+ return s, errProtocol
+ }
+ var name string
+ if json.Unmarshal(command[0], &name) != nil || len(name) == 0 || len(name) > 128 {
+ return s, errProtocol
+ }
+ values, err := object(command[1])
+ if err != nil {
+ return s, err
+ }
+ switch name {
+ case "CharacterModeCommand":
+ var state bool
+ if values.required("state", &state) != nil {
+ return s, errProtocol
+ }
+ s.parts = append(s.parts, speechPart{kind: "characters", characters: state})
+ case "LangChangeCommand":
+ raw, ok := values["lang"]
+ if !ok {
+ return s, errProtocol
+ }
+ var language string
+ if !bytes.Equal(raw, []byte("null")) {
+ if json.Unmarshal(raw, &language) != nil || len(language) > 64 {
+ return s, errProtocol
+ }
+ for _, c := range language {
+ if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_') {
+ return s, errProtocol
+ }
+ }
+ }
+ s.parts = append(s.parts, speechPart{kind: "language", text: language})
+ case "EndUtteranceCommand":
+ s.parts = append(s.parts, speechPart{kind: "end"})
+ default:
+ s.unsupported++
+ }
+ }
+ return s, nil
+}
diff --git a/remote/src/testdata/nvda-v2.jsonl b/remote/src/testdata/nvda-v2.jsonl
new file mode 100644
index 0000000..b014ce8
--- /dev/null
+++ b/remote/src/testdata/nvda-v2.jsonl
@@ -0,0 +1,23 @@
+{"type":"channel_joined","channel":"synthetic-fixture","user_ids":[]}
+{"type":"channel_joined","channel":"synthetic-fixture","user_ids":[7],"clients":[{"id":7,"connection_type":"slave"}]}
+{"type":"client_joined","origin":7,"user_id":7,"client":{"id":7,"connection_type":"slave"}}
+{"type":"client_left","origin":7,"user_id":7,"client":{"id":7,"connection_type":"slave"}}
+{"type":"speak","origin":7,"priority":0,"sequence":[" hello ",["CharacterModeCommand",{"state":true,"isDefault":false}],"a",["CharacterModeCommand",{"state":false,"isDefault":true}],["LangChangeCommand",{"lang":"fr_FR","isDefault":false}],"monde",["LangChangeCommand",{"lang":null,"isDefault":true}]]}
+{"type":"speak","origin":7,"priority":1,"sequence":["next"]}
+{"type":"speak","origin":7,"priority":2,"sequence":["now",["EndUtteranceCommand",{}]]}
+{"type":"cancel","origin":7}
+{"type":"pause_speech","origin":7,"switch":true}
+{"type":"key","origin":7,"vk_code":65,"extended":false,"pressed":true}
+{"type":"key","origin":7,"vk_code":163,"extended":true,"pressed":false,"scan_code":29}
+{"type":"set_braille_info","origin":7,"name":"synthetic-display","numCells":40}
+{"type":"set_braille_info","origin":7}
+{"type":"set_display_size","origin":7,"sizes":[40]}
+{"type":"display","origin":7,"cells":[0,1,127,128,255]}
+{"type":"braille_input","origin":7,"source":"synthetic","scriptPath":["globalCommands","GlobalCommands","braille_scrollBack"]}
+{"type":"braille_input","origin":7,"source":"synthetic","scriptPath":["globalCommands","GlobalCommands","braille_routeTo"],"routingIndex":3}
+{"type":"braille_input","origin":7,"source":"synthetic","scriptPath":["globalCommands","GlobalCommands","braille_routeTo"],"cellIndexes":[3],"routingIndex":3}
+{"type":"set_clipboard_text","origin":7,"text":"Harmless test text."}
+{"type":"ping"}
+{"type":"motd","motd":"Synthetic relay","force_display":false}
+{"type":"error","message":"incorrect_password"}
+{"type":"version_mismatch"}
diff --git a/remote/src/transport.go b/remote/src/transport.go
new file mode 100644
index 0000000..6386ed5
--- /dev/null
+++ b/remote/src/transport.go
@@ -0,0 +1,316 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package remote
+
+import (
+ "bufio"
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "io"
+ "net"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+const (
+ dialTimeout = 15 * time.Second
+ joinTimeout = 15 * time.Second
+ writeTimeout = 5 * time.Second
+ // NVDA's embedded relay sends ping every 300 seconds. A short application
+ // read deadline would incorrectly disconnect idle but healthy sessions.
+ idleTimeout = 6 * time.Minute
+ maxPendingWrites = 32
+ maxQueuedBytes = 256 << 10
+)
+
+var (
+ errEndpoint = errors.New("invalid remote relay endpoint")
+ errTrust = errors.New("remote relay certificate verification failed")
+ errNetwork = errors.New("remote relay connection failed")
+ errTimeout = errors.New("remote relay operation timed out")
+ errClosed = errors.New("remote relay connection closed")
+)
+
+// A pin is an already-approved decision, not permission to ask a peer for trust.
+// There is deliberately no insecure flag, trust-on-first-use or auto-reconnect.
+type certificatePin struct {
+ host string
+ port int
+ sha256 [32]byte
+}
+
+type endpoint struct {
+ host string
+ port int
+ roots *x509.CertPool // nil uses system roots; tests supply a private CA.
+ pin *certificatePin
+}
+
+func (e endpoint) tlsConfig() (*tls.Config, error) {
+ if e.host == "" || len(e.host) > 253 || strings.TrimSpace(e.host) != e.host || strings.ContainsAny(e.host, "/\\@\x00\r\n\t []") || e.port < 1 || e.port > 65535 {
+ return nil, errEndpoint
+ }
+ // Colons are accepted only in bare IPv6 literals; JoinHostPort adds brackets.
+ if strings.Contains(e.host, ":") && net.ParseIP(e.host) == nil {
+ return nil, errEndpoint
+ }
+ cfg := &tls.Config{MinVersion: tls.VersionTLS12, ServerName: e.host, RootCAs: e.roots}
+ if e.pin != nil {
+ pin := *e.pin // Freeze the trust decision for this connection.
+ if pin.host != e.host || pin.port != e.port || pin.sha256 == [32]byte{} {
+ return nil, errTrust
+ }
+ // Exact leaf-certificate identity replaces CA/hostname validation only
+ // for this explicitly approved host and port. TLS still proves key ownership.
+ cfg.InsecureSkipVerify = true
+ cfg.VerifyConnection = func(state tls.ConnectionState) error {
+ if len(state.PeerCertificates) == 0 {
+ return errTrust
+ }
+ digest := sha256.Sum256(state.PeerCertificates[0].Raw)
+ if subtle.ConstantTimeCompare(digest[:], pin.sha256[:]) != 1 {
+ return errTrust
+ }
+ return nil
+ }
+ }
+ return cfg, nil
+}
+
+func generateChannelKey() (string, error) {
+ var entropy [32]byte
+ if _, err := rand.Read(entropy[:]); err != nil {
+ return "", errors.New("remote channel key generation failed")
+ }
+ return hex.EncodeToString(entropy[:]), nil
+}
+
+type relayConn struct {
+ conn net.Conn
+ reader *bufio.Reader // One reader owner only.
+ ctx context.Context
+ cancel context.CancelFunc
+ stop func() bool
+ once sync.Once
+ writeGate chan struct{}
+ mu sync.Mutex
+ pending, bytes int
+}
+
+func newRelayConn(ctx context.Context, conn net.Conn) *relayConn {
+ lifetime, cancel := context.WithCancel(ctx)
+ c := &relayConn{conn: conn, reader: bufio.NewReaderSize(conn, 4096), ctx: lifetime, cancel: cancel, writeGate: make(chan struct{}, 1)}
+ c.stop = context.AfterFunc(lifetime, func() { _ = conn.Close() })
+ return c
+}
+
+func (c *relayConn) close() {
+ c.once.Do(func() {
+ c.cancel()
+ c.stop()
+ _ = c.conn.Close()
+ })
+}
+
+// connect performs TLS authentication before writing any protocol bytes. It
+// returns only after a matching channel_joined; peer readiness is separate.
+// The supplied context owns the entire connection, including after return.
+func connect(ctx context.Context, e endpoint, r role, key string) (*relayConn, message, error) {
+ cfg, err := e.tlsConfig()
+ if err != nil {
+ return nil, message{}, err
+ }
+ if !r.valid() || !validChannelKey(key) {
+ return nil, message{}, errProtocol
+ }
+ dialCtx, cancel := context.WithTimeout(ctx, dialTimeout)
+ defer cancel()
+ dialer := &net.Dialer{KeepAliveConfig: net.KeepAliveConfig{Enable: true, Idle: 10 * time.Second, Interval: 3 * time.Second, Count: 3}}
+ raw, err := dialer.DialContext(dialCtx, "tcp", net.JoinHostPort(e.host, strconv.Itoa(e.port)))
+ if err != nil {
+ return nil, message{}, networkError(ctx, err)
+ }
+ tlsConn := tls.Client(raw, cfg)
+ if err := tlsConn.HandshakeContext(dialCtx); err != nil {
+ _ = raw.Close()
+ var verify *tls.CertificateVerificationError
+ if errors.As(err, &verify) || errors.Is(err, errTrust) {
+ return nil, message{}, errTrust
+ }
+ return nil, message{}, networkError(ctx, err)
+ }
+ c := newRelayConn(ctx, tlsConn)
+ success := false
+ defer func() {
+ if !success {
+ c.close()
+ }
+ }()
+ joinCtx, cancelJoin := context.WithTimeout(ctx, joinTimeout)
+ defer cancelJoin()
+ // Cancellation closes the connection even while a read/write is blocked.
+ stop := context.AfterFunc(joinCtx, c.close)
+ defer stop()
+ version := []byte("{\"type\":\"protocol_version\",\"version\":2}\n")
+ join, _ := json.Marshal(struct {
+ Type string `json:"type"`
+ Channel string `json:"channel"`
+ Role role `json:"connection_type"`
+ }{"join", key, r})
+ if err := c.write(joinCtx, version); err != nil {
+ return nil, message{}, err
+ }
+ if err := c.write(joinCtx, append(join, '\n')); err != nil {
+ return nil, message{}, err
+ }
+ deadline, _ := joinCtx.Deadline()
+ // Bound pre-join notices as well as elapsed time.
+ for count := 0; count < 32; count++ {
+ m, err := c.readUntil(deadline)
+ if err != nil {
+ return nil, message{}, err
+ }
+ switch m.kind {
+ case "ping", "motd":
+ if m.origin != 0 {
+ return nil, message{}, errPeer
+ }
+ continue
+ case "channel_joined":
+ v := m.payload.(membership)
+ if v.channel != key {
+ return nil, message{}, errProtocol
+ }
+ v.channel = "" // Do not retain the echoed credential in session state.
+ m.payload = v
+ if !stop() || joinCtx.Err() != nil {
+ return nil, message{}, errTimeout
+ }
+ success = true
+ return c, m, nil
+ default:
+ return nil, message{}, errProtocol
+ }
+ }
+ return nil, message{}, errLimit
+}
+
+func networkError(ctx context.Context, err error) error {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ var timeout net.Error
+ if errors.As(err, &timeout) && timeout.Timeout() {
+ return errTimeout
+ }
+ if errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) {
+ return errClosed
+ }
+ return errNetwork
+}
+
+func (c *relayConn) read() (message, error) { return c.readUntil(time.Now().Add(idleTimeout)) }
+
+func (c *relayConn) readUntil(deadline time.Time) (message, error) {
+ if c.ctx.Err() != nil {
+ c.close()
+ return message{}, errClosed
+ }
+ if err := c.conn.SetReadDeadline(deadline); err != nil {
+ c.close()
+ return message{}, errClosed
+ }
+ frame, err := readFrame(c.reader)
+ if err != nil {
+ mapped := networkError(c.ctx, err)
+ if errors.Is(err, errLimit) || errors.Is(err, io.ErrUnexpectedEOF) {
+ mapped = errProtocol
+ }
+ c.close()
+ return message{}, mapped
+ }
+ m, err := decodeMessage(frame)
+ // bufio may have another complete frame even after lifetime cancellation.
+ if c.ctx.Err() != nil {
+ c.close()
+ return message{}, errClosed
+ }
+ if err != nil {
+ c.close()
+ }
+ return m, err
+}
+
+// write serializes complete frames and bounds waiting callers and retained
+// bytes. Overflow closes the transport rather than silently losing a key-up.
+// Callers must not invoke it from the reader's event/input thread.
+func (c *relayConn) write(ctx context.Context, frame []byte) error {
+ c.mu.Lock()
+ if len(frame) > maxQueuedBytes || c.pending >= maxPendingWrites || c.bytes+len(frame) > maxQueuedBytes {
+ c.mu.Unlock()
+ c.close()
+ return errLimit
+ }
+ c.pending++
+ c.bytes += len(frame)
+ queuedBytes := len(frame)
+ c.mu.Unlock()
+ defer func() { c.mu.Lock(); c.pending--; c.bytes -= queuedBytes; c.mu.Unlock() }()
+ op, cancel := context.WithTimeout(ctx, writeTimeout)
+ defer cancel()
+ select {
+ case c.writeGate <- struct{}{}:
+ defer func() { <-c.writeGate }()
+ case <-op.Done():
+ c.close()
+ return op.Err()
+ case <-c.ctx.Done():
+ return errClosed
+ }
+ if op.Err() != nil || c.ctx.Err() != nil {
+ c.close()
+ return errClosed
+ }
+ stop := context.AfterFunc(op, c.close)
+ defer stop()
+ deadline, _ := op.Deadline()
+ if c.conn.SetWriteDeadline(deadline) != nil {
+ c.close()
+ return errClosed
+ }
+ for len(frame) > 0 {
+ n, err := c.conn.Write(frame)
+ if err != nil || n == 0 {
+ mapped := networkError(op, err)
+ c.close()
+ return mapped
+ }
+ frame = frame[n:]
+ }
+ if !stop() || op.Err() != nil {
+ c.close()
+ return errTimeout
+ }
+ return nil
+}
+
+func validChannelKey(key string) bool {
+ if key == "" || !boundedText(key, 512) {
+ return false
+ }
+ for _, ch := range key {
+ if ch < 32 || ch == 127 {
+ return false
+ }
+ }
+ return true
+}
diff --git a/remote/src/transport_test.go b/remote/src/transport_test.go
new file mode 100644
index 0000000..4ece359
--- /dev/null
+++ b/remote/src/transport_test.go
@@ -0,0 +1,554 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+package remote
+
+import (
+ "bufio"
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/json"
+ "errors"
+ "io"
+ "math/big"
+ "net"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// All certificates and keys are generated in memory for a private loopback
+// relay. Nothing connects to the user's display, reader or a public relay.
+func testCertificate(t *testing.T, validHost bool) (tls.Certificate, *x509.CertPool) {
+ t.Helper()
+ pub, key, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ template := &x509.Certificate{
+ SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "Remote test relay"},
+ NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
+ KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+ BasicConstraintsValid: true, IsCA: true, DNSNames: []string{"localhost"},
+ }
+ if validHost {
+ template.IPAddresses = []net.IP{net.ParseIP("127.0.0.1")}
+ }
+ der, err := x509.CreateCertificate(rand.Reader, template, template, pub, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ leaf, err := x509.ParseCertificate(der)
+ if err != nil {
+ t.Fatal(err)
+ }
+ roots := x509.NewCertPool()
+ roots.AddCert(leaf)
+ return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key, Leaf: leaf}, roots
+}
+
+func testRelay(t *testing.T, cert tls.Certificate, serve func(net.Conn)) endpoint {
+ t.Helper()
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ e := endpoint{host: "127.0.0.1", port: listener.Addr().(*net.TCPAddr).Port}
+ var wg sync.WaitGroup
+ var mu sync.Mutex
+ var connections []net.Conn
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for {
+ conn, err := listener.Accept()
+ if err != nil {
+ return
+ }
+ mu.Lock()
+ connections = append(connections, conn)
+ mu.Unlock()
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ defer conn.Close()
+ _ = conn.SetDeadline(time.Now().Add(5 * time.Second))
+ serve(tls.Server(conn, &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12}))
+ }()
+ }
+ }()
+ t.Cleanup(func() {
+ _ = listener.Close()
+ mu.Lock()
+ for _, conn := range connections {
+ _ = conn.Close()
+ }
+ mu.Unlock()
+ wg.Wait()
+ })
+ return e
+}
+
+func relayHandshake(t *testing.T, conn net.Conn, r role) *bufio.Reader {
+ t.Helper()
+ reader := bufio.NewReader(conn)
+ version, err := readFrame(reader)
+ if err != nil {
+ t.Errorf("relay version read: %v", err)
+ return nil
+ }
+ var v struct {
+ Type string `json:"type"`
+ Version int `json:"version"`
+ }
+ if json.Unmarshal(version, &v) != nil || v.Type != "protocol_version" || v.Version != 2 {
+ t.Error("wrong protocol greeting")
+ return nil
+ }
+ join, err := readFrame(reader)
+ if err != nil {
+ t.Errorf("relay join read: %v", err)
+ return nil
+ }
+ var j struct {
+ Type string `json:"type"`
+ Channel string `json:"channel"`
+ Role role `json:"connection_type"`
+ }
+ if json.Unmarshal(join, &j) != nil || j.Type != "join" || j.Channel != "synthetic-fixture" || j.Role != r {
+ t.Error("wrong join fields")
+ return nil
+ }
+ return reader
+}
+
+func TestTLSJoinAndPeerSession(t *testing.T) {
+ cert, roots := testCertificate(t, true)
+ for _, r := range []role{controller, controlled} {
+ t.Run(string(r), func(t *testing.T) {
+ e := testRelay(t, cert, func(conn net.Conn) {
+ reader := relayHandshake(t, conn, r)
+ if reader == nil {
+ return
+ }
+ _, _ = io.WriteString(conn, "{\"type\":\"motd\",\"motd\":\"Synthetic relay\",\"force_display\":true}\n")
+ if r == controller {
+ _, _ = io.WriteString(conn, "{\"type\":\"ping\"}\n{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[{\"id\":7,\"connection_type\":\"slave\"}]}\n{\"type\":\"speak\",\"origin\":7,\"sequence\":[\" hello \"],\"priority\":2}\n{\"type\":\"cancel\",\"origin\":7}\n")
+ } else {
+ _, _ = io.WriteString(conn, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[{\"id\":7,\"connection_type\":\"master\"}]}\n{\"type\":\"key\",\"origin\":7,\"vk_code\":65,\"extended\":false,\"pressed\":true}\n{\"type\":\"key\",\"origin\":7,\"vk_code\":65,\"extended\":false,\"pressed\":false}\n")
+ }
+ _, _ = reader.ReadByte() // Wait until client closes.
+ })
+ e.roots = roots
+ conn, joined, err := connect(context.Background(), e, r, "synthetic-fixture")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.close()
+ if joined.payload.(membership).channel != "" {
+ t.Fatal("credential retained in returned membership")
+ }
+ s, _ := newSession(r, 1)
+ if _, err := s.accept(1, joined); err != nil {
+ t.Fatal(err)
+ }
+ for range 2 {
+ m, err := conn.read()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if accepted, err := s.accept(1, m); err != nil || !accepted {
+ t.Fatalf("peer data: %v %v", accepted, err)
+ }
+ }
+ })
+ }
+}
+
+func TestTLSRejectsBeforeChannelDisclosure(t *testing.T) {
+ for _, mode := range []string{"unknown-ca", "wrong-host", "wrong-pin", "changed-certificate"} {
+ t.Run(mode, func(t *testing.T) {
+ cert, roots := testCertificate(t, mode != "wrong-host")
+ read := make(chan int, 1)
+ e := testRelay(t, cert, func(conn net.Conn) {
+ buf := make([]byte, 4096)
+ n, _ := conn.Read(buf)
+ read <- n
+ })
+ switch mode {
+ case "wrong-host":
+ e.roots = roots
+ case "wrong-pin", "changed-certificate":
+ digest := sha256.Sum256(cert.Certificate[0])
+ if mode == "changed-certificate" {
+ old, _ := testCertificate(t, true)
+ digest = sha256.Sum256(old.Certificate[0])
+ } else {
+ digest[0] ^= 1
+ }
+ e.roots = roots // A valid CA must not override a mismatched saved pin.
+ e.pin = &certificatePin{host: e.host, port: e.port, sha256: digest}
+ }
+ conn, _, err := connect(context.Background(), e, controller, "synthetic-fixture")
+ if conn != nil || !errors.Is(err, errTrust) {
+ t.Fatalf("expected trust failure: %v", err)
+ }
+ select {
+ case n := <-read:
+ if n != 0 {
+ t.Fatal("sent application data before verification")
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("server did not observe failure")
+ }
+ })
+ }
+}
+
+func TestExplicitPinAndEndpointBinding(t *testing.T) {
+ cert, _ := testCertificate(t, false)
+ e := testRelay(t, cert, func(conn net.Conn) {
+ reader := relayHandshake(t, conn, controller)
+ if reader == nil {
+ return
+ }
+ _, _ = io.WriteString(conn, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"user_ids\":[]}\n")
+ _, _ = reader.ReadByte()
+ })
+ e.pin = &certificatePin{host: e.host, port: e.port, sha256: sha256.Sum256(cert.Certificate[0])}
+ conn, _, err := connect(context.Background(), e, controller, "synthetic-fixture")
+ if err != nil {
+ t.Fatal(err)
+ }
+ conn.close()
+ wrong := *e.pin
+ wrong.port++
+ e.pin = &wrong
+ if _, err := e.tlsConfig(); !errors.Is(err, errTrust) {
+ t.Fatal("pin escaped port binding")
+ }
+ wrong.port = e.port
+ wrong.host = "localhost"
+ if _, err := e.tlsConfig(); !errors.Is(err, errTrust) {
+ t.Fatal("pin escaped host binding")
+ }
+}
+
+func TestJoinRejectsUnexpectedTraffic(t *testing.T) {
+ cert, roots := testCertificate(t, true)
+ for _, reply := range []string{
+ `{"type":"channel_joined","channel":"wrong-fixture"}`,
+ `{"type":"error","message":"do not expose this text"}`,
+ `{"type":"speak","origin":7,"sequence":["before join"]}`,
+ `{"type":"ping","origin":7}`,
+ strings.Repeat("{\"type\":\"ping\"}\n", 32),
+ } {
+ e := testRelay(t, cert, func(conn net.Conn) {
+ if relayHandshake(t, conn, controller) == nil {
+ return
+ }
+ _, _ = io.WriteString(conn, reply+"\n")
+ })
+ e.roots = roots
+ conn, _, err := connect(context.Background(), e, controller, "synthetic-fixture")
+ if conn != nil || err == nil || strings.Contains(err.Error(), "expose") {
+ t.Fatalf("unsafe join: %v", err)
+ }
+ }
+}
+
+func TestCancelDuringJoin(t *testing.T) {
+ cert, roots := testCertificate(t, true)
+ joined := make(chan struct{})
+ closed := make(chan struct{})
+ e := testRelay(t, cert, func(conn net.Conn) {
+ reader := relayHandshake(t, conn, controller)
+ if reader == nil {
+ return
+ }
+ close(joined)
+ _, _ = reader.ReadByte()
+ close(closed)
+ })
+ e.roots = roots
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ result := make(chan error, 1)
+ go func() {
+ conn, _, err := connect(ctx, e, controller, "synthetic-fixture")
+ if conn != nil {
+ conn.close()
+ }
+ result <- err
+ }()
+ select {
+ case <-joined:
+ case <-time.After(3 * time.Second):
+ t.Fatal("join did not start")
+ }
+ cancel()
+ select {
+ case err := <-result:
+ if err == nil {
+ t.Fatal("canceled join succeeded")
+ }
+ case <-time.After(time.Second):
+ t.Fatal("join did not cancel")
+ }
+ select {
+ case <-closed:
+ case <-time.After(time.Second):
+ t.Fatal("join left connection open")
+ }
+}
+
+func TestCancelDuringTLSHandshake(t *testing.T) {
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer listener.Close()
+ accepted := make(chan net.Conn, 1)
+ go func() {
+ conn, err := listener.Accept()
+ if err == nil {
+ accepted <- conn
+ }
+ }()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ result := make(chan error, 1)
+ go func() {
+ conn, _, err := connect(ctx, endpoint{host: "127.0.0.1", port: listener.Addr().(*net.TCPAddr).Port}, controller, "synthetic-fixture")
+ if conn != nil {
+ conn.close()
+ }
+ result <- err
+ }()
+ select {
+ case conn := <-accepted:
+ defer conn.Close()
+ case <-time.After(3 * time.Second):
+ t.Fatal("dial did not reach relay")
+ }
+ cancel()
+ select {
+ case err := <-result:
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("handshake cancellation: %v", err)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("TLS handshake did not cancel")
+ }
+}
+
+func TestReadDeadlineClosesTransport(t *testing.T) {
+ left, right := net.Pipe()
+ defer right.Close()
+ conn := newRelayConn(context.Background(), left)
+ defer conn.close()
+ if _, err := conn.readUntil(time.Now().Add(-time.Second)); !errors.Is(err, errTimeout) {
+ t.Fatalf("read timeout: %v", err)
+ }
+ if conn.ctx.Err() == nil {
+ t.Fatal("expired read left transport active")
+ }
+}
+
+func TestCanceledLifetimeRejectsBufferedFrames(t *testing.T) {
+ left, right := net.Pipe()
+ defer right.Close()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ conn := newRelayConn(ctx, left)
+ defer conn.close()
+ go func() { _, _ = io.WriteString(right, "{\"type\":\"cancel\"}\n{\"type\":\"cancel\"}\n") }()
+ if _, err := conn.read(); err != nil {
+ t.Fatal(err)
+ }
+ cancel()
+ if _, err := conn.read(); !errors.Is(err, errClosed) {
+ t.Fatalf("buffered frame survived cancellation: %v", err)
+ }
+}
+
+type shortWriteConn struct{ net.Conn }
+
+func (c shortWriteConn) Write(p []byte) (int, error) {
+ if len(p) > 3 {
+ p = p[:3]
+ }
+ return c.Conn.Write(p)
+}
+
+func TestShortWritesPreserveFrame(t *testing.T) {
+ left, right := net.Pipe()
+ defer right.Close()
+ conn := newRelayConn(context.Background(), shortWriteConn{left})
+ defer conn.close()
+ result := make(chan error, 1)
+ go func() { result <- conn.write(context.Background(), []byte("{\"type\":\"cancel\"}\n")) }()
+ _ = right.SetReadDeadline(time.Now().Add(time.Second))
+ frame, err := readFrame(bufio.NewReader(right))
+ if err != nil || string(frame) != `{"type":"cancel"}` {
+ t.Fatalf("short write: %q %v", frame, err)
+ }
+ if err := <-result; err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestTransportCancellationAndFraming(t *testing.T) {
+ for _, fragment := range []string{"", `{"type":"cancel"`, strings.Repeat("x", maxRelayFrame+4096)} {
+ left, right := net.Pipe()
+ ctx, cancel := context.WithCancel(context.Background())
+ conn := newRelayConn(ctx, left)
+ result := make(chan error, 1)
+ go func() { _, err := conn.read(); result <- err }()
+ if fragment != "" {
+ go func() { _, _ = io.WriteString(right, fragment); _ = right.Close() }()
+ } else {
+ cancel()
+ }
+ select {
+ case err := <-result:
+ if err == nil {
+ t.Fatal("accepted partial/oversized/canceled read")
+ }
+ case <-time.After(time.Second):
+ t.Fatal("read remained blocked")
+ }
+ cancel()
+ conn.close()
+ _ = right.Close()
+ }
+}
+
+func TestTransportSerializesConcurrentWriters(t *testing.T) {
+ left, right := net.Pipe()
+ defer right.Close()
+ conn := newRelayConn(context.Background(), left)
+ defer conn.close()
+ const count = 16
+ result := make(chan error, count)
+ for i := range count {
+ go func() {
+ frame, err := encodeMessage("key", keyTransition{VK: i + 1, Pressed: true})
+ if err == nil {
+ err = conn.write(context.Background(), frame)
+ }
+ result <- err
+ }()
+ }
+ reader := bufio.NewReader(right)
+ seen := map[int]bool{}
+ _ = right.SetReadDeadline(time.Now().Add(3 * time.Second))
+ for range count {
+ frame, err := readFrame(reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ m, err := decodeMessage(frame)
+ if err != nil {
+ t.Fatal("interleaved frames")
+ }
+ seen[m.payload.(keyTransition).VK] = true
+ }
+ for range count {
+ if err := <-result; err != nil {
+ t.Fatal(err)
+ }
+ }
+ if len(seen) != count {
+ t.Fatal("lost writes")
+ }
+ conn.mu.Lock()
+ defer conn.mu.Unlock()
+ if conn.pending != 0 || conn.bytes != 0 {
+ t.Fatalf("write accounting leak: %d %d", conn.pending, conn.bytes)
+ }
+}
+
+type blockedWriteConn struct {
+ net.Conn
+ entered chan struct{}
+ once sync.Once
+}
+
+func (c *blockedWriteConn) Write(p []byte) (int, error) {
+ c.once.Do(func() { close(c.entered) })
+ return c.Conn.Write(p)
+}
+
+func TestBlockedWriterCancellationAndOverflow(t *testing.T) {
+ for _, mode := range []string{"cancel", "bytes", "operations"} {
+ t.Run(mode, func(t *testing.T) {
+ left, right := net.Pipe()
+ defer right.Close()
+ entered := make(chan struct{})
+ conn := newRelayConn(context.Background(), &blockedWriteConn{Conn: left, entered: entered})
+ defer conn.close()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ result := make(chan error, 1)
+ go func() { result <- conn.write(ctx, []byte("blocked\n")) }()
+ select {
+ case <-entered:
+ case <-time.After(time.Second):
+ t.Fatal("writer did not start")
+ }
+ switch mode {
+ case "cancel":
+ cancel()
+ case "bytes":
+ if err := conn.write(context.Background(), make([]byte, maxQueuedBytes)); !errors.Is(err, errLimit) {
+ t.Fatal("byte ceiling did not fail closed")
+ }
+ case "operations":
+ // Reserve the remaining queue slots without scheduling dependence.
+ conn.mu.Lock()
+ conn.pending = maxPendingWrites
+ conn.mu.Unlock()
+ if err := conn.write(context.Background(), []byte("next\n")); !errors.Is(err, errLimit) {
+ t.Fatal("operation ceiling did not fail closed")
+ }
+ }
+ select {
+ case err := <-result:
+ if err == nil {
+ t.Fatal("blocked write succeeded")
+ }
+ case <-time.After(time.Second):
+ t.Fatal("cleanup blocked behind writer")
+ }
+ if conn.ctx.Err() == nil {
+ t.Fatal("transport remained active")
+ }
+ })
+ }
+}
+
+func TestChannelKeysAndEndpointValidation(t *testing.T) {
+ a, err := generateChannelKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := generateChannelKey()
+ if err != nil || len(a) != 64 || len(b) != 64 || a == b {
+ t.Fatal("invalid random keys")
+ }
+ for _, host := range []string{"", "relay:6837", "https://relay", "user@relay", "relay/path", "relay\n", "[::1]"} {
+ if _, err := (endpoint{host: host, port: 6837}).tlsConfig(); err == nil {
+ t.Errorf("accepted endpoint %q", host)
+ }
+ }
+ if _, err := (endpoint{host: "::1", port: 6837}).tlsConfig(); err != nil {
+ t.Fatal("bare IPv6 rejected")
+ }
+}
diff --git a/remote/storage.md b/remote/storage.md
new file mode 100644
index 0000000..c836a4d
--- /dev/null
+++ b/remote/storage.md
@@ -0,0 +1,69 @@
+# Remote settings and remembered credentials
+
+The source library now includes Linux filesystem storage. It is not connected to
+a command or connection UI yet. Opening, reading and writing this store performs
+no network I/O and creates no session consent. Nothing auto-connects at startup.
+
+`settings.toml` contains format version 1, plain-language role (`controller` or
+`controlled`), relay host/port and an optional previously approved SHA-256 pin.
+The pin repeats its host and port; a mismatch or invalid/zero digest is rejected.
+Pin validation uses the same endpoint contract as the TLS transport. There is no
+trust-on-first-use, changed-pin replacement, or certificate approval action in
+this storage layer. A future local UI must obtain that decision explicitly.
+
+The schema contains no channel key, connection epoch, peer, lease, keyboard grant,
+clipboard consent, reconnect switch or startup-connect switch. Unknown fields,
+duplicate fields, unsupported versions and invalid endpoints are rejected.
+
+`channel-key.toml` is separate and written only by an explicit `rememberKey`
+call. It contains version 1, relay host/port and the key. A key is returned only
+for the exact saved endpoint. Changing relay settings does not copy a key to the
+new endpoint; the old saved key remains unused until explicitly replaced or
+forgotten. `forgetKey` removes and syncs the credential file and is idempotent.
+Removal is not a promise of secure disk erasure. Saving ordinary settings never
+saves a key, and there is no saved-key flag that silently triggers a connection.
+
+Keys use the transport's existing validation: nonempty valid UTF-8, at most 512
+bytes, without C0 controls or DEL. The transport and store share that validator.
+Settings and credential files are each bounded to 8 KiB on read. Parser errors
+are replaced with a generic error, without the file path, parser excerpt or key.
+Ordinary settings can therefore be inspected separately from credential content.
+
+The caller supplies an absolute, clean directory path whose parents already
+exist. The final directory is created with mode 0700 if absent. Every component
+is opened relative to the preceding directory with no symlink following. A
+symlinked settings location is refused. The final directory must belong to the
+current user and have no group/other permissions; existing unsafe permissions
+are rejected rather than changed automatically.
+
+All files, including the cooperating-process lock, must be current-user regular
+files with no group/other permissions and exactly one hard link. Symlinks, FIFOs,
+devices and hard links are refused. File opens use nonblocking/no-follow flags so
+an unexpected FIFO cannot hang the reader. Credential operations run on a future
+session worker, not an input or native UI callback.
+
+Writers use an exclusive mode-0600 temporary file under the owned directory
+descriptor, sync it, rename within the directory, and sync the directory. They
+never follow or truncate an existing destination. A mutex serializes callers;
+a nonblocking flock excludes cooperating processes. Temporary files are removed
+after normal failures. Abrupt process death can leave an owner-only `.pending-*`
+file; it is never read as live settings. A directory-sync failure after rename
+can leave the new version present despite an error, so the UI must report the
+failure and re-read before claiming which value was saved. The two files are
+independent atomic records, not a cross-file transaction.
+
+The key is plaintext protected by filesystem ownership and permissions. This is
+not encryption, an OS keyring, or protection against malicious same-user code.
+No runtime data is added to release archives; Remote still has no package entry.
+
+Tests use disposable directories and synthetic keys. They cover restart, exact
+endpoint scoping, atomic inode replacement, permission modes, temporary-file
+cleanup, explicit forgetting, host/port pin mismatch, unknown fields/versions,
+malformed and oversized files, symlinked ancestors, file symlinks, hard links,
+FIFOs, unsafe lock files, competing locks and secret-free errors. They do not
+establish a completed Remember key UI or power-loss durability on every filesystem.
+
+```sh
+GOCACHE=/tmp/cthulhu-cache GOPROXY=off go test -race ./remote/src -count=1 -timeout=60s
+make check
+```