winzik/docs/ide-remote.md

144 lines
14 KiB
Markdown

# IDE Remote: the JumPHP IDE shown on a phone or another PC (contract v1)
The desktop IDE (`ide/`, `games/ide`) can be **shared**: a phone or another computer opens a JumPHP application
(`apps/jumphp-ide-remote`, project folder `/home/david/JumPHP-Projects/jumPhpIdeRemote`, published on jumphp.net) that shows the IDE's
contents (Claude conversation, terminal, files...) as a responsive page, and lets the person type into the active panel in real time.
It is a remote IDE, not a screen capture: only **data** crosses (conversation items, terminal bytes, text), never pixels.
```
IDE page (ide/ui, webview) <== encrypted frames ==> relay (server) or direct TCP (LAN) <==> jumphp-ide-remote (browser / app)
remote-host.js (WebCrypto, deny-by-default) pages + channel.js (WebCrypto)
PHP side (ide/src/Remote): only a dumb TCP pipe for the direct mode
```
## Principles (do not break)
1. **End-to-end encryption**: the key never goes to a server. The pairing URL carries it in the **fragment**: `<app>#r=<room>&k=<key>[&d=<host:port,...>]`
(`room` = 24 random bytes, `key` = 32 random bytes, both base64url without padding). AES-256-GCM. The relay only moves ciphertext.
2. **Consent on the PC**: a first `hello` from a device opens a dialog on the IDE ("Allow <device> to use <scope>?"): Allow / Deny. Nothing is
answered before. Sharing is opt-in (the screen icon), has an expiry (default 8 h), a list of connected devices, Revoke, Stop sharing.
3. **Deny by default**: the host only runs the commands of the scope's allowlist (below). Everything else answers `{ok:false, error:'denied'}`.
4. **One Claude per session**: remote input to Claude goes through the existing `claude.send` (the IDE's lock refuses a second claude); when the
Terminal's Remote Control claude holds the session, the text is typed into that terminal tab instead (same as the panel does).
5. Never block the frame; the browser has 32-bit ints (no `pack('J')`, no 64-bit math in PHP side of the app); network from the app only through
`$engine->tcp()` / `net()` (AGENTS.md rule 4) or the page's own WebSocket to the relay.
## Channel (library `channel.js`, one file used by both ends)
Frame on the wire (relay binary frame, or on a TCP stream prefixed by a 4-byte big-endian length):
`[1B version=1][1B flags: bit0 = more parts follow][12B IV][ciphertext+16B tag]`. IV = 4 bytes (0x01 host->remote, 0x02 remote->host, then 3 random bytes = the sender's session nonce, so several devices never reuse an IV under the shared key) + 8-byte
big-endian counter (strictly increasing per (direction, sender nonce): a repeated or lower counter is dropped = replay protection). AAD = the 2 first bytes.
Plaintext = UTF-8 JSON of ONE message (or part of it). A message above 48 KB is cut in parts (flag bit0 on all but the last).
API (the same everywhere):
```js
const ch = await Channel.open({role: 'host'|'remote', key, transport}) // transport: relayTransport({url, room}) | streamTransport({send, onData})
ch.send(obj) // JSON object; queued until open; resolves when sent
ch.on('open'|'close'|'error'|'peer'|'message', fn) // 'message' gets the decoded object
ch.close()
```
Transports: `relayTransport` speaks the php-wasm-network relay protocol (read `vendor/davidnurdin/php-wasm-network` server + client JS), using the
room named by the pairing `room` (the server must accept a client-chosen long room id; if the stock relay only gives 4-letter codes, extend the relay
server accordingly: see the relay task). `streamTransport` wraps any byte stream (direct TCP through the PHP pipe on the host; the JumPHP runtime /
`Tcp` on the remote).
## Relay protocol (php-wasm-network RelayServer + `docker/relay/room-id.patch`)
WebSocket (any path; the playground exposes `/ide-relay/ws`). Text frames = JSON control, binary frames = payload.
- Server -> client on connect: `{t:'hello', v:1}`. Client keeps alive with `{t:'ping', id:0}` every 15 s (server drops 60 s of silence).
- Host: `{t:'create', room:<ROOM>, max:16}`. Stock relay ignores `room` and invents a 4-letter code, and `join` upper-cases ids: the patch makes
`create` accept a client-chosen id of 32-64 chars `[A-Za-z0-9_-]` (case kept, never listed as public); creating an id that exists enters it again
(host reconnecting; `room-full` error if 16 peers). Short ids behave as before.
- Remote: `{t:'join', room:<ROOM>}`; unknown id -> `{t:'error', code:'no-room'}` (the client retries every 2 s); full -> `room-full`.
- Server -> client: `{t:'room', room, peer, host, peers:[ids]}` (entered), `{t:'peer-join', peer}`, `{t:'peer-leave', peer}`, `{t:'host', peer}`, `{t:'error', code, message}`.
- Binary: client sends `[to:1B][payload]` (`to` = peer id, or 255 = every other peer); receiver gets `[from:1B][payload]`. Max 65536 bytes per frame
(channel parts stay below 49 KB). The relay's own "host" notion is not used: host/remote are the Channel roles. A room is deleted 90 s after its last peer leaves.
- `relayTransport` reconnects with backoff (0.5 s doubling to 15 s): the host re-creates/enters the room, a remote re-joins; Channel emits `close` then `open`.
Frames sent while nobody is in the room are lost: the app sends its `hello` after the `peer` event.
## Messages (JSON, field `t`)
Remote -> host:
- `{t:'hello', v:1, name:'Pixel 8', want:'claude'|'terminal'|'all'}` (first message; the host asks consent)
- `{t:'invoke', id, name, payload}` a command of the allowlist
- `{t:'sub', panels:['claude','terminal']}` which live streams the device wants (default: those of its scope)
- `{t:'bye'}`
Host -> remote:
- `{t:'welcome', v:1, scope, project:{name, root_name}, panels:[{id:'claude', title}, {id:'terminal', title}, ...], expires: <unix seconds>}`
- `{t:'denied', reason:'refused'|'revoked'|'expired'|'version'}` then the host closes
- `{t:'result', id, ok:true, result}` / `{t:'result', id, ok:false, error}`
- `{t:'event', name, payload}` the IDE's events of the subscribed panels, same names/payloads as `backend.on` (`claude.event`, `claude.exit`, `terminal.output`
(data base64 as the IDE sends it), `terminal.exit`, `run.output`...)
- `{t:'snap', panel:'terminal', id: <terminal id>, data: <base64 of the last <=256 KB of output>, cols, rows}` and
`{t:'snap', panel:'claude', conv, items:[...]}`: the state a late joiner needs (sent after `welcome`, and on `{t:'invoke', name:'snap', payload:{panel}}`)
- `{t:'ping'}` / `{t:'pong'}` every 20 s each way; 60 s without anything = closed.
## Allowlist per scope (v1)
- `claude`: `claude.send`, `claude.stop`, `claude.stopAll`, `claude.status`, `claude.history.list`, `claude.history.read` (only these). Events: `claude.event`, `claude.exit`.
- `terminal`: `terminal.open`, `terminal.write`, `terminal.resize`, `terminal.close`; events `terminal.output`, `terminal.exit`; `snap`.
- `all`: `claude` + `terminal` + read-only `file.read`, `file.list` / tree listing, `git.status`, `project.info` (reduced), `run.output` events, `snap`.
Never remote: `file.write`, `file.delete`, `git.push`/`commit`, `run.start`, `tool.install`, settings, MCP/agent commands, plugins, `update.*`, anything not listed.
(The exact command names are the ones registered in `ide/src/Ide.php` and `games/ide/src/Main.php`: the host implementer reads them and writes the list in
ONE constant, `REMOTE_ALLOW`, in `ide/ui/js/remote-host.js`, with a test that every name exists.)
## Direct (same network) mode
The IDE, only when sharing is on and the person allowed "Direct", listens on a TCP port of its own (`ide/src/Remote/DirectListener.php`, opt-in, ephemeral port,
all interfaces) and puts its LAN addresses in the pairing URL (`d=192.168.1.20:41233,...`). PHP only pipes bytes to the page (events
`remote.direct.data` {conn, data base64}, `remote.direct.close`; commands `remote.direct.listen` / `.write` / `.close` / `.stop`): all crypto stays in JS.
The remote races direct against the relay (direct first, 1.5 s) when the page's runtime state allows it; a native JumPHP app on another PC just uses `Tcp`;
a phone browser needs the JumPHP runtime (`net_mode: auto`, never defaulted to `local`, never bypass its consent).
## Files
- `ide/ui/js/remote/channel.js` (+ copy in the app `ui/js/channel.js`, kept identical by a script), `ide/ui/js/remote-host.js`, `ide/src/Remote/`,
the header icon `screen` next to `rcBtn` of the Claude panel (`ide/ui/js/claude.js`), `ICONS.screen` in `ide/ui/js/ui.js`.
- The app: `/home/david/JumPHP-Projects/jumPhpIdeRemote/apps/jumphp-ide-remote/` (kind app / `ui: webview`, AGENTS.md §16), pages in `ui/`.
- Relay: the playground repo (`/home/david/Projets/jumphp-playground`: compose service + Caddy path `/ide-relay/ws`), image from `docker/relay`.
- Tests: `ide/tests/`, node tests for channel.js, the app's `AppTestCase`, a two-process test through the local `bin/jumphp relay up`.
## Relay deployment (playground, `wss://jumphp.net/ide-relay/ws`)
Source of truth: the playground repo (`/home/david/Projets/jumphp-playground`): `docker/relay/` (Dockerfile, `ide-relay.php`, README), service `relay` in
`deploy/compose.yaml` and `compose.yaml` (dev), routes in `docker/Caddyfile`. Nothing new in DNS, certificates or Traefik: the relay is a path of the main host,
the app's Caddy (behind Traefik's TLS passthrough) proxies it to the `relay` service on a private `internal: true` network (no way out to the internet).
- URLs: `wss://jumphp.net/ide-relay/ws` (WebSocket), `https://jumphp.net/ide-relay/health` (counts JSON; the room list is never exposed; also `docker compose ps` shows the
relay's healthcheck).
- Image: the engine's recipe (php-wasm-network at the same commit) + `docker/relay/room-id.patch` **if present in the playground's `docker/relay/`**. Copy it from
`JumPHP/docker/relay/room-id.patch` (applied with `patch -p1` from php-wasm-network's root, `-p0` as fallback; the build fails if it does not apply). Without it rooms are only 4-letter
codes: IDE Remote needs it (the pairing room is 24 random bytes).
- Limits: unprivileged (`nobody`), read-only fs, cap_drop ALL, no-new-privileges, 32 pids, 256 MB, 0.5 CPU. In the relay: `RELAY_MAX_PEERS` (peers per room, **2** = host + one device;
raise it if several devices share a pairing), `RELAY_MAX_CLIENTS` (400 sockets), `RELAY_IDLE_SECONDS` (60 s without a frame: the channel pings every 20 s), 64 KB per frame (relay protocol).
Caddy: streams cut after 12 h. Logs: stdout/stderr only, never a payload, room codes masked (`created *`), json-file 3 x 10 MB.
- Origin: a request with an `Origin` is refused (403) unless it matches `IDE_RELAY_ORIGINS` (default: any `*.jumphp.net`, `*.jumphp.localhost`, `localhost`, `127.0.0.1`, `tauri://localhost`,
`http(s)://tauri.localhost`, `null`); no `Origin` (native client) passes. If the IDE webview sends another origin, set `IDE_RELAY_ORIGINS` in the app's environment. The relay trusts nothing
anyway: everything is end-to-end encrypted.
- NOT done: a per-IP connection limit (stock Caddy has no rate-limit module, Traefik is in TCP passthrough). Add a Cloudflare rate-limiting rule on `jumphp.net/ide-relay/*` if abused.
Run locally: in the playground, `docker compose up -d --build app relay`, then `docker compose exec app php tools/ide-relay-smoke.php ws://localhost/ide-relay/ws` (two sockets, one room,
a frame each way; optional args: Origin header, room id). Or JumPHP's own `bin/jumphp relay up` (`ws://localhost:8090/ws`, no Caddy).
Production check: `php tools/ide-relay-smoke.php wss://jumphp.net/ide-relay/ws` (from any PHP with openssl) and `curl https://jumphp.net/ide-relay/health`.
Deploy (the lead, after review; the memory'd flow): copy `room-id.patch` into the playground's `docker/relay/`, commit and push the playground, then on the server:
`git pull` in the playground checkout, `docker compose -f deploy/compose.yaml --env-file deploy/.env up -d --build relay`, then the app (its Caddyfile changed): `deploy/rolling-deploy.sh`
(or `docker compose -f deploy/compose.yaml --env-file deploy/.env up -d --build`), and finally `docker restart` Traefik (if it loops, `compose down/up` in its folder). No new `.env` key is required.
## Direct mode findings (app shell + transport, checked against runtime docs and the playground sources)
- The app never opens sockets itself: the page asks its PHP side (`direct.open|write|close`, events `direct`), which uses `JumPHP\Net\Tcp`
(AGENTS.md rule 4). Desktop run: a plain socket, any LAN address and port, nothing else needed. Browser: `Tcp` goes to the JumPHP runtime
(`net_mode: auto`, `RuntimeClient` created by `Main` in the browser) when it is `ready`, else to the server bridge.
- The runtime accepts private LAN addresses after the person confirms the target once ("app wants to reach 192.168.x.x:port"); `Origin` must be
whitelisted and the runtime listens on 127.0.0.1 only. The server bridge never accepts private addresses (so with `net_mode: server` direct is
impossible, by design: the page skips direct then).
- The administrator ticket (`TcpGrants::ticket`) allows private addresses in a ticket (syntax check only) and a host list per grant (empty = any host),
but until now limited `tcp` to database ports (3306...): the IDE's ephemeral port was refused. The lead is relaxing that policy (any TCP port);
once done, the same ticket and approval per commit apply, and direct from a phone browser works when the runtime is installed and ready.
The app must request the `tcp` right with an empty / private-range host list, since the IDE's LAN address is not known in advance.
- The page only tries direct when: the PHP side is a desktop run, or the runtime state is `ready` and `net_mode` is not `server`; otherwise it
goes straight to the relay. Any direct failure (ticket refused, runtime refused, timeout) falls back to the relay with no user-visible error.
- The app is not served from the playground origin when framed: a pairing fragment is not passed to the frame, so the page also takes the link
pasted into its form (and keeps it in localStorage until Disconnect / denied).