diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 075665dff..c1d5c1c06 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -61,7 +61,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘ | bus | Post-commit business events and their in-memory ring | [bus](../../src/bus/AGENTS.md) | | state | `state.db`: opens it, refuses an old file, damage and a newer version, migrates each owner's tables | [state](../../src/state/AGENTS.md) | | history | The durable event history: `history.db`, prune, set-aside, projections (usage: request, minute and device fact rows) | [history](../../src/history/AGENTS.md) | -| ports | Every external API behind an interface, with a fake | [ports](../../src/ports/AGENTS.md) | +| ports | Every external API behind an interface, with a fake; `ws` loads lazily, in the CLI only for `simlock tunnel` | [ports](../../src/ports/AGENTS.md) | | host-load | CPU, memory and disk load samples | [host-load](../../src/host-load/AGENTS.md) | | instructions | The static rules text for agents: `simlock instructions`, the MCP server instructions and resource; `simlock setup`, which installs the router skill | [instructions](../../src/instructions/AGENTS.md) | | agent-identity | Default requester id for CLI and MCP | [agent-identity](../../src/agent-identity/AGENTS.md) | diff --git a/e2e/slow-android-tunnel.test.ts b/e2e/slow-android-tunnel.test.ts new file mode 100644 index 000000000..3c56e35d9 --- /dev/null +++ b/e2e/slow-android-tunnel.test.ts @@ -0,0 +1,108 @@ +import { existsSync } from "node:fs"; +import { createServer } from "node:http"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +import { DEVICE_READY_MS, freeLoopbackPort, waitFor, withHttpDaemon } from "./helpers/index.js"; + +const ANDROID_HOME = + process.env.ANDROID_HOME ?? + process.env.ANDROID_SDK_ROOT ?? + join(homedir(), "Library/Android/sdk"); +const hasAndroidSdk = + existsSync(ANDROID_HOME) && existsSync(join(ANDROID_HOME, "platform-tools", "adb")); + +const BODY = "simlock-tunnel-ok"; + +// why: only a real emulator proves that `adb reverse` reaches the caller's loopback listener through the tunnel socket; the fast end-to-end test fakes the device side. +describe.skipIf(!hasAndroidSdk)( + "simlock tunnel reverse on a real emulator against a lone worker", + { tags: ["slow", "android"] }, + () => { + it( + "serves a page held on the caller's loopback port to the emulator through reverse", + { timeout: 420_000 }, + async () => { + const { env, port } = await withHttpDaemon((httpPort) => ({ + configOverrides: { + capabilities: { tunnel: { enabled: true } }, + http: { enabled: true, host: "127.0.0.1", port: httpPort }, + idle: { shutdownAfterMs: 300_000 }, + warmPool: { learn: false }, + }, + driver: "real", + })); + const page = createServer((_request, response) => { + response.writeHead(200, { "content-type": "text/plain" }).end(BODY); + }); + try { + const callerPort = await freeLoopbackPort(); + await new Promise((resolve) => page.listen(callerPort, "127.0.0.1", resolve)); + + const lease = await env.cli( + [ + "lease", + "--platform", + "android", + "--device", + "Pixel 9", + "--agent-id", + "tunnel", + "--detach", + ], + { timeout: DEVICE_READY_MS }, + ); + expect(lease.code, `lease failed: ${lease.stderr}`).toBe(0); + const leaseId = (lease.json as { lease: { id: string } }).lease.id; + + const created = await env.cli(["token", "create", "--role", "operator"]); + expect(created.code, created.stderr).toBe(0); + const secret = (created.json as { secret: string }).secret; + + const tunnel = env.cliBackground([ + "--token", + secret, + "tunnel", + "reverse", + String(callerPort), + "--url", + `http://127.0.0.1:${String(port)}`, + "--lease", + leaseId, + ]); + expect(await tunnel.firstStdoutLine(60_000)).toBe( + `reverse device:${String(callerPort)} -> localhost:${String(callerPort)} (lease ${leaseId})`, + ); + + let answer = ""; + await waitFor( + async () => { + const fetched = await env.cli([ + "adb", + "shell", + `(printf 'GET / HTTP/1.0\\r\\n\\r\\n'; sleep 2) | nc 127.0.0.1 ${String(callerPort)}`, + ]); + answer = fetched.stdout; + return answer.includes(BODY); + }, + { + interval: 1_000, + label: "the device reading the caller's page through reverse", + timeout: 60_000, + }, + ); + expect(answer).toContain(BODY); + + tunnel.kill("SIGINT"); + expect((await tunnel.waitForExit(10_000)).code).toBe(0); + } finally { + await new Promise((resolve) => page.close(() => resolve())); + await env + .cli(["nuke", "--delete-devices", "--yes"], { timeout: 120_000 }) + .catch(() => undefined); + } + }, + ); + }, +); diff --git a/src/cli/AGENTS.md b/src/cli/AGENTS.md index 288362759..188504b0a 100644 --- a/src/cli/AGENTS.md +++ b/src/cli/AGENTS.md @@ -19,26 +19,26 @@ Surface: [cli.mdx](../../website/src/content/docs/docs/reference/cli.mdx) — ev ## Files -| File | Role | -| ----------------- | ------------------------------------------------------------------------------------------------- | -| `index.ts` | `runCli`: the global `--token`, `--gateway` and `--local`, the command lookup, the error boundary | -| `tree.ts` | The command tree — each node names the module that implements it | -| `environment.ts` | `buildCliEnvironment`: the ports a command may reach, from the ports it is handed | -| `types.ts` | `CliEnvironment` and its ports — types only, so routing loads no code | -| `errors.ts` | The error → code/exit mapping | -| `usage-error.ts` | `UsageError` and `withHelpHint`, the help pointer's one wording | -| `connect.ts` | `connectDaemonClient`: credential order, the admin session, the notice | -| `args.ts` | `commandArgs` / `requiredPositional` / `subcommandOrUsage` / `writeResult` | -| `commands/*.ts` | One module per command, `run(argv, context)`; loaded by the tree on a hit | -| `format.ts` | The human renderers for `status`, `worker list`, `daemon start`, etc. | -| `duration.ts` | `parseDuration` for `--ttl`-style flags | -| `termination.ts` | The signals and parent-exit wait a held lease blocks on | -| `log-file.ts` | `readLogFile`: `daemon.log` plus a rotated generation | -| `stdio.ts` | `readPipedStdin`: stdin for `simctl`/`adb --stdin`, read to EOF, a terminal included | -| `remote-lease.ts` | `resolveRemoteLeaseId`: the requester's only lease, shared by `simctl`/`adb` and `rotate` | -| `passthrough.ts` | `spawnPassthrough`: runs a resolved simctl/adb command, stdio inherited | -| `follow-log.ts` | `followLog`: `daemon logs --follow` across rotations | -| `main.ts` | The bin; sets `process.exitCode` | +| File | Role | +| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | +| `index.ts` | `runCli`: the global `--token`, `--gateway` and `--local`, the command lookup, the error boundary | +| `tree.ts` | The command tree — each node names the module that implements it | +| `environment.ts` | `buildCliEnvironment`: the ports a command may reach, from the ports it is handed | +| `types.ts` | `CliEnvironment` and its ports — types only, so routing loads no code | +| `errors.ts` | The error → code/exit mapping | +| `usage-error.ts` | `UsageError` and `withHelpHint`, the help pointer's one wording | +| `connect.ts` | `connectDaemonClient`: credential order, the admin session, the notice | +| `args.ts` | `commandArgs` / `requiredPositional` / `subcommandOrUsage` / `writeResult` | +| `commands/*.ts` | One module per command, `run(argv, context)`; loaded by the tree on a hit | +| `format.ts` | The human renderers for `status`, `worker list`, `daemon start`, etc. | +| `duration.ts` | `parseDuration` for `--ttl`-style flags | +| `termination.ts` | The signals and parent-exit wait a held lease blocks on | +| `log-file.ts` | `readLogFile`: `daemon.log` plus a rotated generation | +| `stdio.ts` | `readPipedStdin`: stdin for `simctl`/`adb --stdin`, read to EOF, a terminal included | +| `remote-lease.ts` | `resolveRemoteLeaseId`: the requester's only lease, shared by `simctl`/`adb` and `rotate`; `selectOnlyLease` words a token's errors for `tunnel` | +| `passthrough.ts` | `spawnPassthrough`: runs a resolved simctl/adb command, stdio inherited | +| `follow-log.ts` | `followLog`: `daemon logs --follow` across rotations | +| `main.ts` | The bin; sets `process.exitCode` | `format.ts`, `duration.ts` and `termination.ts` are reached only from a command module, and `follow-log.ts` and `passthrough.ts` only from a dynamic import inside `environment.ts`. @@ -96,6 +96,14 @@ Surface: [cli.mdx](../../website/src/content/docs/docs/reference/cli.mdx) — ev orientation, an unknown one is a usage error (exit 2); the lease is `--lease` (anywhere on the line) or the requester's only lease (`resolveRemoteLeaseId`); `device.rotate` answers, and the line printed is `Rotated lease to ` from the answer. Worker or gateway alike. + 5b. **`simlock tunnel reverse [:] … [--lease ] [--url ]`** — talks to a worker or gateway over + HTTP and a WebSocket, never the local daemon: `--url`/`SIMLOCK_URL` (`https://`, or `http://` on loopback only; the origin, no path, query or fragment) + and `--token`/`SIMLOCK_TOKEN`. Without `--lease`, `GET /v1/identity` and `/v1/leases` pick an agent token's only + lease (`selectOnlyLease`; an operator token must name one). One line per tunnel on `READY`; each `OPEN` connects + to the caller's loopback port (no listener: `RESET` and a stderr warning per tunnel every 10 s), and `CREDIT` + flows both ways. Failures print one JSON line itself: a refused upgrade or `REFUSED` frame with the worker's code, + close 4001 exit 14 `TUNNEL_LEASE_ENDED`, a lost socket, 45 s of silence or 90 s without `READY` `TUNNEL_DISCONNECTED`. + Ctrl-C and SIGTERM close the socket, wait at most 2 s, exit 0. `ws` loads on the first connect, for this command only. 6. **`simlock events --follow`** — subscribe, then replay, then print buffered pushes not already replayed (by `eventKey`). `--since` without `--follow` never launches a daemon; with none running it reads `history.db` itself (read-only; no file is empty, an unreadable diff --git a/src/cli/commands/tunnel.ts b/src/cli/commands/tunnel.ts new file mode 100644 index 000000000..13c0e3c9d --- /dev/null +++ b/src/cli/commands/tunnel.ts @@ -0,0 +1,505 @@ +import { + decodeTunnelFrame, + encodeTunnelFrame, + ERROR_TABLE, + type SimlockErrorCode, + TUNNEL_MAX_DATA_BYTES, + TUNNEL_MAX_DEVICE_PORT, + TUNNEL_MAX_TUNNELS, + TUNNEL_TAG, + TUNNEL_WINDOW_BYTES, +} from "../../contract/index.js"; +import { + type TcpStream, + type TimerHandle, + type WebSocketClient, + WebSocketRefusedError, +} from "../../ports/index.js"; +import { commandArgs, UsageError } from "../args.js"; +import { selectOnlyLease } from "../remote-lease.js"; +import type { CommandContext } from "../tree.js"; +import type { CliEnvironment } from "../types.js"; + +const HANDSHAKE_TIMEOUT_MS = 10_000; +const CALLER_CONNECT_TIMEOUT_MS = 5_000; +const CLOSE_NORMAL = 1000; +const WARN_EVERY_MS = 10_000; +const MAX_URL_CHARS = 2048; +const MAX_TOKEN_CHARS = 4096; +const MAX_LEASE_CHARS = 256; + +interface ReverseSpec { + readonly devicePort: number; + readonly callerPort: number; +} + +function portOf(text: string, what: string): number { + const port = /^\d+$/.test(text) ? Number(text) : 0; + if (port < 1 || port > TUNNEL_MAX_DEVICE_PORT) { + throw new UsageError(`${what} port "${text}" is not an integer from 1 to 65535`); + } + return port; +} + +function parseReverse(words: readonly string[], index: number): ReverseSpec { + const kind = words[index] as string; + if (kind !== "reverse") { + throw new UsageError(`Unknown tunnel kind "${kind}": only reverse is available`); + } + const text = words[index + 1] ?? ""; + const colon = text.indexOf(":"); + const device = colon === -1 ? text : text.slice(0, colon); + const devicePort = portOf(device, "device"); + return { + callerPort: portOf(colon === -1 ? device : text.slice(colon + 1), "caller"), + devicePort, + }; +} + +function parseReverses(words: readonly string[]): readonly ReverseSpec[] { + if (words.length === 0) { + throw new UsageError("Name at least one tunnel: reverse [:]"); + } + const specs: ReverseSpec[] = []; + for (let index = 0; index < words.length; index += 2) specs.push(parseReverse(words, index)); + if (specs.length > TUNNEL_MAX_TUNNELS) + throw new UsageError(`At most ${String(TUNNEL_MAX_TUNNELS)} tunnels`); + const callerPorts = specs.map(({ callerPort }) => callerPort); + const repeated = callerPorts.find((port, at) => callerPorts.indexOf(port) !== at); + if (repeated !== undefined) { + throw new UsageError(`Caller port ${String(repeated)} is named by two tunnels`); + } + return specs; +} + +const LOOPBACK_HOSTS: ReadonlySet = new Set(["127.0.0.1", "[::1]", "localhost"]); + +function parsedUrl(text: string): URL { + const refusal = new UsageError( + "--url must be https://, or http:// only for 127.0.0.1, [::1] or localhost", + ); + let parsed: URL; + try { + parsed = new URL(text); + } catch { + throw refusal; + } + const allowed = + parsed.protocol === "https:" || + (parsed.protocol === "http:" && LOOPBACK_HOSTS.has(parsed.hostname)); + if (!allowed || text.length > MAX_URL_CHARS) throw refusal; + return parsed; +} + +function checkedOrigin(parsed: URL, text: string): void { + if (parsed.pathname !== "/" || /[?#]/.test(text)) { + throw new UsageError("--url must be the worker's origin only: no path, query or fragment"); + } +} + +function checkedUrl(text: string | undefined): string { + if (text === undefined || text === "") { + throw new UsageError("No worker URL: pass --url or set SIMLOCK_URL"); + } + checkedOrigin(parsedUrl(text), text); + return text.replace(/\/$/, ""); +} + +function checkedToken(text: string | undefined): string { + if (text === undefined || text === "" || text.length > MAX_TOKEN_CHARS) { + throw new UsageError("No token: pass --token or set SIMLOCK_TOKEN"); + } + return text; +} + +function checkedLease(text: string | undefined): string | undefined { + if (text !== undefined && (text === "" || text.length > MAX_LEASE_CHARS)) { + throw new UsageError(`--lease must be 1 to ${String(MAX_LEASE_CHARS)} characters`); + } + return text; +} + +// why: a frame's JSON body comes off the wire, so a body that does not parse is read as having no fields instead of throwing out of the socket's listener. +function payloadJson(payload: Uint8Array): unknown { + try { + return JSON.parse(new TextDecoder().decode(payload)); + } catch { + return undefined; + } +} + +function field(value: unknown, name: string): unknown { + return typeof value === "object" && value !== null ? Reflect.get(value, name) : undefined; +} + +// why: one caller connection per device connection. The stream's writes are chained so bytes reach the caller's port in the order the worker sent them, and each write is followed by a CREDIT that returns its bytes to the worker's window; the caller's own bytes leave only while the worker's window for them has room. +function relayConnections( + socket: WebSocketClient, + environment: CliEnvironment, + warn: (devicePort: number, callerPort: number) => void, +) { + interface Relayed { + readonly stream: TcpStream; + writes: Promise; + window: number; + wake: (() => void) | undefined; + } + const streams = new Map(); + const pump = async (conn: number, relayed: Relayed): Promise => { + const reader = relayed.stream.readable.getReader(); + for (;;) { + const step = await reader.read(); + if (step.done) break; + for (let at = 0; at < step.value.length;) { + const size = Math.min(TUNNEL_MAX_DATA_BYTES, step.value.length - at, relayed.window); + if (size === 0) { + await new Promise((resume) => { + relayed.wake = resume; + }); + continue; + } + if (streams.get(conn) !== relayed) return; + relayed.window -= size; + socket.send(encodeTunnelFrame(TUNNEL_TAG.data, conn, step.value.subarray(at, at + size))); + at += size; + } + } + if (streams.get(conn) === relayed) socket.send(encodeTunnelFrame(TUNNEL_TAG.end, conn)); + }; + // why: a write the caller's port refused (it ended the connection) resets that one connection and leaves the tunnel and its other connections up. + const failed = (conn: number, relayed: Relayed): void => { + if (streams.get(conn) !== relayed) return; + streams.delete(conn); + relayed.stream.close(); + socket.send(encodeTunnelFrame(TUNNEL_TAG.reset, conn)); + }; + const grant = (conn: number, size: number): void => { + const credit = new Uint8Array(4); + new DataView(credit.buffer).setUint32(0, size); + socket.send(encodeTunnelFrame(TUNNEL_TAG.credit, conn, credit)); + }; + const openConnection = async (spec: ReverseSpec, conn: number): Promise => { + let stream: TcpStream; + try { + stream = await environment.tcpStreams.connect(spec.callerPort, CALLER_CONNECT_TIMEOUT_MS); + } catch { + warn(spec.devicePort, spec.callerPort); + socket.send(encodeTunnelFrame(TUNNEL_TAG.reset, conn)); + return; + } + const relayed: Relayed = { + stream, + wake: undefined, + window: TUNNEL_WINDOW_BYTES, + writes: Promise.resolve(), + }; + streams.set(conn, relayed); + void pump(conn, relayed); + }; + const onFrame = ( + connection: Relayed, + frame: { tag: number; conn: number; payload: Uint8Array }, + ): void => { + if (frame.tag === TUNNEL_TAG.data) { + connection.writes = connection.writes + .then(() => connection.stream.write(frame.payload)) + .then(() => grant(frame.conn, frame.payload.length)) + .catch(() => failed(frame.conn, connection)); + } else if (frame.tag === TUNNEL_TAG.credit) { + connection.window += new DataView( + frame.payload.buffer, + frame.payload.byteOffset, + frame.payload.length, + ).getUint32(0); + connection.wake?.(); + } else if (frame.tag === TUNNEL_TAG.end) { + connection.writes = connection.writes + .then(() => connection.stream.end()) + .catch(() => failed(frame.conn, connection)); + } else if (frame.tag === TUNNEL_TAG.reset) { + connection.stream.close(); + streams.delete(frame.conn); + } + }; + const handle = async ( + spec: ReverseSpec | undefined, + frame: { tag: number; conn: number; payload: Uint8Array }, + ): Promise => { + if (frame.tag === TUNNEL_TAG.open) { + if (spec !== undefined) await openConnection(spec, frame.conn); + return; + } + const connection = streams.get(frame.conn); + if (connection !== undefined) onFrame(connection, frame); + }; + const closeAll = (): void => { + const open = [...streams.values()]; + streams.clear(); + for (const { stream, wake } of open) { + stream.close(); + wake?.(); + } + }; + return { closeAll, handle }; +} + +const HELLO_TIMEOUT_MS = 90_000; +const SILENCE_TIMEOUT_MS = 45_000; +const CLOSE_WAIT_MS = 2_000; +const CLOSE_LEASE_ENDED = 4001; + +// why: a failure here carries the worker's own code, which can be one the contract's table does not hold (an HTTP 401 answers `UNAUTHENTICATED`), so the command prints its one JSON line itself. +class TunnelFailure extends Error { + constructor( + readonly code: string, + message: string, + readonly exitCode: number, + ) { + super(message); + } +} + +function disconnected(message: string): TunnelFailure { + return new TunnelFailure("TUNNEL_DISCONNECTED", message, 1); +} + +function bodyError(body: unknown): { code: string; message: string } | undefined { + const error = field(body, "error"); + const code = field(error, "code"); + const message = field(error, "message"); + return typeof code === "string" && typeof message === "string" ? { code, message } : undefined; +} + +function refusedTo(status: number, text: string, leaseId: string): TunnelFailure { + let body: unknown; + try { + body = JSON.parse(text); + } catch { + body = undefined; + } + const answered = bodyError(body); + if (answered !== undefined) { + return new TunnelFailure( + answered.code, + answered.message, + answered.code in ERROR_TABLE ? ERROR_TABLE[answered.code as SimlockErrorCode].cliExitCode : 1, + ); + } + return status === 404 + ? new TunnelFailure("UNKNOWN_LEASE", `Lease ${leaseId} is not known to this worker`, 1) + : disconnected(`Lease ${leaseId}: the worker answered ${String(status)}`); +} + +async function lookup(environment: CliEnvironment, url: string, token: string) { + let answer: Awaited>; + try { + answer = await environment.httpJson.get(url, token); + } catch { + throw disconnected(`No answer from ${new URL(url).origin}`); + } + if (answer.status < 200 || answer.status > 299) { + const failed = bodyError(answer.body); + throw new TunnelFailure( + failed?.code ?? "TUNNEL_DISCONNECTED", + failed?.message ?? `The worker answered ${String(answer.status)}`, + 1, + ); + } + return answer; +} + +async function leaseToUse( + environment: CliEnvironment, + base: string, + token: string, + lease: string | undefined, +): Promise { + if (lease !== undefined) return lease; + const identity = await lookup(environment, `${base}/v1/identity`, token); + const leases = await lookup(environment, `${base}/v1/leases`, token); + return selectOnlyLease( + (field(leases.body, "leases") as { id: string; requesterId: string }[] | undefined) ?? [], + field(identity.body, "role") === "admin" ? "admin" : "agent", + ); +} + +async function openSocket( + environment: CliEnvironment, + base: string, + secret: string, + leaseId: string, +): Promise { + try { + return await environment.webSocket.connect( + `${base.replace(/^http/, "ws")}/v1/leases/${encodeURIComponent(leaseId)}/tunnel`, + { + handshakeTimeoutMs: HANDSHAKE_TIMEOUT_MS, + headers: { authorization: `Bearer ${secret}` }, + }, + ); + } catch (error) { + if (error instanceof WebSocketRefusedError) throw refusedTo(error.status, error.body, leaseId); + throw disconnected(`Lease ${leaseId}: no connection to the worker`); + } +} + +function frameFailure(frame: { payload: Uint8Array }, leaseId: string): TunnelFailure { + const refusal = payloadJson(frame.payload); + const code = field(refusal, "code"); + const message = field(refusal, "message"); + const known = + typeof code === "string" && code in ERROR_TABLE ? (code as SimlockErrorCode) : "TUNNEL_FAILED"; + return new TunnelFailure( + known, + `Lease ${leaseId}: ${typeof message === "string" ? message : "the worker refused the tunnel"}`, + ERROR_TABLE[known].cliExitCode, + ); +} + +function serve( + environment: CliEnvironment, + socket: WebSocketClient, + specs: readonly ReverseSpec[], + leaseId: string, + base: string, +): Promise { + const warned = new Map(); + const relay = relayConnections(socket, environment, (devicePort, callerPort) => { + const now = environment.clock.now(); + const last = warned.get(devicePort); + if (last !== undefined && now - last < WARN_EVERY_MS) return; + warned.set(devicePort, now); + environment.stderr.write( + `reverse ${String(devicePort)}: nothing listening on localhost:${String(callerPort)}\n`, + ); + }); + // why: an OPEN waits for its loopback connect, and the DATA behind it must not overtake it, so frames are handled one at a time. + let handled = Promise.resolve(); + let socketClosed = false; + return new Promise((resolve, reject) => { + let silence: TimerHandle | undefined; + let finished = false; + let stopping = false; + let closeTimer: TimerHandle | undefined; + const helloTimer = environment.clock.setTimer(HELLO_TIMEOUT_MS, () => { + end(disconnected(`Lease ${leaseId}: no READY from the worker within 90 s`), true); + }); + const heard = () => { + if (silence !== undefined) environment.clock.cancel(silence); + silence = environment.clock.setTimer(SILENCE_TIMEOUT_MS, () => { + end(disconnected(`Lease ${leaseId}: nothing was heard from the worker for 45 s`), true); + }); + }; + function end(failure: TunnelFailure | undefined, unresponsive = false): void { + if (finished) return; + finished = true; + environment.signals.off("SIGINT", stop); + environment.signals.off("SIGTERM", stop); + environment.clock.cancel(helloTimer); + if (silence !== undefined) environment.clock.cancel(silence); + if (closeTimer !== undefined) environment.clock.cancel(closeTimer); + relay.closeAll(); + if (!socketClosed) { + socket.close(CLOSE_NORMAL, ""); + // why: a worker that never answers the close would leave the socket holding the process open for 30 s past the bound. + if (unresponsive) socket.terminate(); + } + if (failure === undefined) resolve(0); + else reject(failure); + } + function stop(): void { + if (finished) return; + stopping = true; + closeTimer = environment.clock.setTimer(CLOSE_WAIT_MS, () => end(undefined, true)); + socket.close(CLOSE_NORMAL, ""); + } + environment.signals.on("SIGINT", stop); + environment.signals.on("SIGTERM", stop); + heard(); + socket.onPing(heard); + socket.onClose((code, reason) => { + socketClosed = true; + if (stopping) { + end(undefined); + return; + } + end( + code === CLOSE_LEASE_ENDED + ? new TunnelFailure( + "TUNNEL_LEASE_ENDED", + `Lease ${leaseId} ended: ${reason}`, + ERROR_TABLE.TUNNEL_LEASE_ENDED.cliExitCode, + ) + : disconnected(`Lease ${leaseId}: the connection to ${base} was lost`), + ); + }); + socket.onMessage((bytes) => { + heard(); + const frame = decodeTunnelFrame(bytes); + if (frame === undefined) return; + if (frame.tag === TUNNEL_TAG.refused) { + end(frameFailure(frame, leaseId)); + return; + } + if (frame.tag === TUNNEL_TAG.ready) { + environment.clock.cancel(helloTimer); + for (const { callerPort, devicePort } of specs) { + environment.stdout.write( + `reverse device:${String(devicePort)} -> localhost:${String(callerPort)} (lease ${leaseId})\n`, + ); + } + return; + } + const opened = + frame.tag === TUNNEL_TAG.open + ? specs.find( + ({ devicePort }) => field(payloadJson(frame.payload), "devicePort") === devicePort, + ) + : undefined; + handled = handled.then(() => relay.handle(opened, frame)).catch(() => undefined); + }); + socket.send( + encodeTunnelFrame( + TUNNEL_TAG.hello, + 0, + JSON.stringify({ + tunnels: specs.map(({ devicePort }) => ({ devicePort, kind: "reverse" })), + }), + ), + ); + }); +} + +async function run( + argv: readonly string[], + { environment, token }: CommandContext, +): Promise { + const { help, lease, positionals, url } = commandArgs(argv, { + help: { type: "boolean", short: "h" }, + lease: { type: "string" }, + url: { type: "string" }, + }); + if (help) { + environment.stdout.write( + "Usage: simlock tunnel reverse [:] [reverse ...] [--lease ] [--url ]\n", + ); + return 0; + } + const specs = parseReverses(positionals); + const base = checkedUrl(typeof url === "string" ? url : environment.tunnelUrl); + const secret = checkedToken(token ?? environment.tunnelToken); + const named = checkedLease(typeof lease === "string" ? lease : undefined); + try { + const leaseId = await leaseToUse(environment, base, secret, named); + const socket = await openSocket(environment, base, secret, leaseId); + return await serve(environment, socket, specs, leaseId, base); + } catch (error) { + if (!(error instanceof TunnelFailure)) throw error; + environment.stderr.write( + `${JSON.stringify({ error: { code: error.code, message: error.message } })}\n`, + ); + return error.exitCode; + } +} + +export { run }; diff --git a/src/cli/environment.ts b/src/cli/environment.ts index 6c9121216..e9e5b4230 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -407,6 +407,26 @@ export function buildCliEnvironment( ((command) => import("./passthrough.js").then(({ spawnPassthrough }) => spawnPassthrough(command))), readStdin: ports.readStdin ?? readPipedStdin, + webSocket: ports.webSocket ?? { + connect: async (url, options) => { + const { NodeWebSocketClientConnector } = await import("../ports/index.js"); + return new NodeWebSocketClientConnector().connect(url, options); + }, + }, + httpJson: ports.httpJson ?? { + get: async (url, token) => { + const { FetchHttpJsonClient } = await import("../ports/index.js"); + return new FetchHttpJsonClient().get(url, token); + }, + }, + tcpStreams: ports.tcpStreams ?? { + connect: async (port, timeoutMs) => { + const { NodeTcpStreamConnector } = await import("../ports/index.js"); + return new NodeTcpStreamConnector().connect(port, timeoutMs); + }, + }, + ...(env.SIMLOCK_URL === undefined ? {} : { tunnelUrl: env.SIMLOCK_URL }), + ...(env.SIMLOCK_TOKEN === undefined ? {} : { tunnelToken: env.SIMLOCK_TOKEN }), writeConfigFile: async (contents) => { const { DATA_DIRECTORY_MODE } = await import("../ports/index.js"); await filesystem.mkdirp(dataDirectory, { mode: DATA_DIRECTORY_MODE }); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 333d80bb8..56a0aae0c 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -38,7 +38,12 @@ import { type IpcConnection, type IpcConnector, } from "../ports/index.js"; -import { FakeSystemStats } from "../ports/index.js"; +import { + FakeHttpJsonClient, + FakeSystemStats, + FakeTcpStreamConnector, + FakeWebSocketClientConnector, +} from "../ports/index.js"; import { type Auth, createAuth, tokensOwner } from "../auth/index.js"; import { openMemoryStateDatabase } from "../auth/testing.js"; import { DaemonEndpointHost } from "../daemon/connection-host.js"; @@ -8501,6 +8506,9 @@ function outputCapture(ports?: CliEnvironmentPorts, env: NodeJS.ProcessEnv = {}) stderr: stderrOut, stdout: stdoutOut, confirm: async () => true, + webSocket: new FakeWebSocketClientConnector(), + httpJson: new FakeHttpJsonClient(), + tcpStreams: new FakeTcpStreamConnector(), ...overrides, }; } diff --git a/src/cli/index.ts b/src/cli/index.ts index 5af26b66f..b4370111b 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -36,6 +36,8 @@ Commands: rotate [--lease ] Turn the leased iOS simulator: portrait, portrait-upside-down, landscape-left or landscape-right + tunnel reverse [:] [reverse ...] [--lease ] [--url ] + Reach this machine's ports from a leased Android device simctl Run xcrun simctl against Simlock's iOS device set adb Run adb against Simlock's adb server mcp Start the stdio MCP server @@ -45,9 +47,8 @@ Commands: Run 'simlock --help' for command usage. Run 'simlock --version' (or -v) to print the installed version. -Pass --token anywhere on the command line to connect as admin -explicitly; see https://github.com/callstackincubator/simlock for the default -resolution order. +Pass --token anywhere on the command line to set the credential a command +sends; the CLI reference lists the default resolution order. Pass --gateway anywhere on the command line to reach this machine's gateway in place of its worker. Pass --local anywhere on the command line to reach this machine's worker even when only a gateway has run here.`; diff --git a/src/cli/lazy-loading.test.ts b/src/cli/lazy-loading.test.ts index 3289a1105..cbb2a36f8 100644 --- a/src/cli/lazy-loading.test.ts +++ b/src/cli/lazy-loading.test.ts @@ -42,6 +42,10 @@ vi.mock("../contract/index.js", async (importOriginal) => { loaded.add("contract"); return await importOriginal(); }); +vi.mock("ws", async (importOriginal) => { + loaded.add("ws"); + return await importOriginal(); +}); vi.mock("../ports/index.js", async (importOriginal) => { loaded.add("ports"); return await importOriginal(); @@ -55,7 +59,7 @@ async function loadsDuring(run: () => Promise): Promise { const home = mkdtempSync(join(tmpdir(), "simlock-cli-lazy-")); -async function environment(): Promise { +async function environment(env: NodeJS.ProcessEnv = {}): Promise { const ports: CliEnvironmentPorts = { clock: new FakeClock(0), daemonHome: { role: "worker", dataDirectory: home, gatewayPresent: false }, @@ -71,7 +75,7 @@ async function environment(): Promise { systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * 1024 ** 3 }), }; const { buildCliEnvironment } = await import("./environment.js"); - return buildCliEnvironment(ports, {}); + return buildCliEnvironment(ports, env); } describe("the CLI loads what a command asks for, not the whole control plane", () => { @@ -114,4 +118,27 @@ describe("the CLI loads what a command asks for, not the whole control plane", ( expect(module.run, node.name).toBeTypeOf("function"); } }); + + it("loads ws for simlock tunnel alone, not for any other command nor the MCP entry", async () => { + const { runCli } = await import("./index.js"); + const others = [["--help"], ["config", "set", "leaseTtlMs", "60000"], ["bogus"]]; + for (const argv of others) { + const cli = await environment(); + expect(await loadsDuring(() => runCli(argv, cli))).not.toContain("ws"); + } + expect(await loadsDuring(() => import("../mcp/main.js"))).not.toContain("ws"); + const { COMMANDS } = await import("./tree.js"); + const nodes = COMMANDS.flatMap((node) => [node, ...(node.children ?? [])]); + expect(await loadsDuring(() => Promise.all(nodes.map((node) => node.load())))).not.toContain( + "ws", + ); + + const cli = await environment({ + SIMLOCK_TOKEN: "sk_agent_x", + SIMLOCK_URL: "http://127.0.0.1:1", + }); + expect( + await loadsDuring(() => runCli(["tunnel", "reverse", "5173", "--lease", "L1"], cli)), + ).toContain("ws"); + }); }); diff --git a/src/cli/remote-lease.ts b/src/cli/remote-lease.ts index 8f874b8f3..91933ebcb 100644 --- a/src/cli/remote-lease.ts +++ b/src/cli/remote-lease.ts @@ -2,13 +2,30 @@ import type { SimlockAdminClient } from "../admin/index.js"; import { UsageError } from "./errors.js"; import type { CommandContext } from "./tree.js"; -export async function resolveRemoteLeaseId( - client: SimlockAdminClient, - environment: CommandContext["environment"], -): Promise { - const { leases } = await client.listLeases(); +// why: a caller on another machine has no requester id to filter by, so with no `environment` the errors name the token and `--lease`, and an operator token must name its lease. +export function selectOnlyLease( + leases: readonly { readonly id: string; readonly requesterId: string }[], + role: "admin" | "agent", + environment?: CommandContext["environment"], +): string { + if (environment === undefined) { + if (role === "admin") { + throw new UsageError("An operator token must name its lease: pass --lease "); + } + if (leases.length === 0) { + throw new UsageError( + "This token holds no lease: start one with `simlock lease` on the worker, or pass --lease ", + ); + } + if (leases.length > 1) { + throw new UsageError( + `This token holds more than one lease (${leases.map((lease) => lease.id).join(", ")}); pass --lease to name the device you mean`, + ); + } + return (leases[0] as { readonly id: string }).id; + } const own = - client.role === "admin" + role === "admin" ? leases.filter((lease) => lease.requesterId === environment.requesterId) : leases; if (own.length === 0) { @@ -23,3 +40,11 @@ export async function resolveRemoteLeaseId( } return (own[0] as { readonly id: string }).id; } + +export async function resolveRemoteLeaseId( + client: SimlockAdminClient, + environment: CommandContext["environment"], +): Promise { + const { leases } = await client.listLeases(); + return selectOnlyLease(leases, client.role, environment); +} diff --git a/src/cli/tree.ts b/src/cli/tree.ts index 68298dc88..91980c5e8 100644 --- a/src/cli/tree.ts +++ b/src/cli/tree.ts @@ -131,6 +131,7 @@ export const COMMANDS: readonly CommandNode[] = [ { name: "simctl", load: () => import("./commands/passthrough.js") }, { name: "adb", load: () => import("./commands/passthrough.js") }, { name: "rotate", load: () => import("./commands/rotate.js") }, + { name: "tunnel", load: () => import("./commands/tunnel.js") }, { name: "mcp", load: () => import("./commands/mcp.js") }, { name: "instructions", load: () => import("./commands/instructions.js") }, { name: "setup", load: () => import("./commands/setup.js") }, diff --git a/src/cli/tunnel.test.ts b/src/cli/tunnel.test.ts new file mode 100644 index 000000000..f4d0fc609 --- /dev/null +++ b/src/cli/tunnel.test.ts @@ -0,0 +1,804 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + TUNNEL_MAX_DATA_BYTES, + TUNNEL_TAG, + decodeTunnelFrame, + encodeTunnelFrame, +} from "../contract/index.js"; +import { buildCliEnvironment, runCli } from "./index.js"; +import { + FakeClock, + FakeDaemonLauncher, + FakeHttpJsonClient, + FakeSystemStats, + FakeTcpPeer, + FakeTcpStreamConnector, + FakeWebSocketClientConnector, + WebSocketRefusedError, + MemoryFilesystem, + MemoryIpcTransport, +} from "../ports/index.js"; + +type Listener = () => void; + +// why: the CLI's signal source, so a test sends Ctrl-C without signalling the test process. +class TestSignals { + readonly #listeners = new Map>(); + on(signal: string, listener: Listener): this { + const set = this.#listeners.get(signal) ?? new Set(); + set.add(listener); + this.#listeners.set(signal, set); + return this; + } + off(signal: string, listener: Listener): this { + this.#listeners.get(signal)?.delete(listener); + return this; + } + emit(signal: string): void { + for (const listener of this.#listeners.get(signal) ?? []) listener(); + } +} + +function command(env: NodeJS.ProcessEnv) { + const signals = new TestSignals(); + const out: string[] = []; + const err: string[] = []; + const webSocket = new FakeWebSocketClientConnector(); + const httpJson = new FakeHttpJsonClient(); + const clock = new FakeClock(0); + const tcpStreams = new FakeTcpStreamConnector(); + const environment = buildCliEnvironment( + { + clock, + daemonHome: { dataDirectory: "/unused", gatewayPresent: false, role: "worker" }, + filesystem: new MemoryFilesystem(), + homeDirectory: "/home/caller", + hostPlatform: "linux", + httpJson, + ipc: new MemoryIpcTransport(), + launcher: new FakeDaemonLauncher(), + runTool: async () => ({ outcome: "not-found" }), + signals, + stderr: { write: (value) => err.push(value) }, + stdout: { write: (value) => out.push(value) }, + systemStats: new FakeSystemStats({ cpuCount: 2, totalRamBytes: 2 ** 30 }), + tcpStreams, + webSocket, + workingDirectory: "/work", + }, + env, + ); + return { + clock, + err, + httpJson, + out, + run: (argv: readonly string[]) => runCli(argv, environment), + signals, + tcpStreams, + webSocket, + }; +} + +const READY = encodeTunnelFrame(TUNNEL_TAG.ready, 0, "{}"); + +const ENV = { SIMLOCK_TOKEN: "sk_agent_x", SIMLOCK_URL: "http://127.0.0.1:7300" }; + +describe("simlock tunnel that cannot run", () => { + it("exits 2 with a USAGE line, before it connects anywhere, for each bad invocation", async () => { + const accepted = command(ENV); + const acceptedExit = accepted.run(["tunnel", "reverse", "5173", "--lease", "L1"]); + await vi.waitFor(() => expect(accepted.webSocket.connections).toHaveLength(1)); + expect(accepted.webSocket.connections[0]?.url).toBe("ws://127.0.0.1:7300/v1/leases/L1/tunnel"); + accepted.signals.emit("SIGINT"); + expect(await acceptedExit).toBe(0); + + const longest = command({ + SIMLOCK_TOKEN: "t".repeat(4096), + SIMLOCK_URL: `https://${"a".repeat(2040)}`, + }); + const longestExit = longest.run(["tunnel", "reverse", "5173", "--lease", "L".repeat(256)]); + await vi.waitFor(() => expect(longest.webSocket.connections).toHaveLength(1)); + longest.signals.emit("SIGINT"); + expect(await longestExit).toBe(0); + + const slashed = command({ ...ENV, SIMLOCK_URL: "http://127.0.0.1:7300/" }); + const slashedExit = slashed.run(["tunnel", "reverse", "5173", "--lease", "L1"]); + await vi.waitFor(() => expect(slashed.webSocket.connections).toHaveLength(1)); + expect(slashed.webSocket.connections[0]?.url).toBe("ws://127.0.0.1:7300/v1/leases/L1/tunnel"); + slashed.signals.emit("SIGINT"); + expect(await slashedExit).toBe(0); + + const cases: readonly { + readonly argv: readonly string[]; + readonly env?: NodeJS.ProcessEnv; + readonly lease?: string; + readonly message: string; + }[] = [ + { + argv: ["reverse", "70000"], + message: 'device port "70000" is not an integer from 1 to 65535', + }, + { + argv: ["reverse", "65536"], + message: 'device port "65536" is not an integer from 1 to 65535', + }, + { argv: ["reverse", "abc"], message: 'device port "abc" is not an integer from 1 to 65535' }, + { + argv: ["reverse", "5173:"], + message: 'caller port "" is not an integer from 1 to 65535', + }, + { + argv: ["reverse", "5173:0"], + message: 'caller port "0" is not an integer from 1 to 65535', + }, + { argv: [], message: "Name at least one tunnel: reverse [:]" }, + { + argv: ["reverse", "5173", "reverse", "6000:5173"], + message: "Caller port 5173 is named by two tunnels", + }, + { + argv: ["forward", "5173"], + message: 'Unknown tunnel kind "forward": only reverse is available', + }, + { + argv: ["--url", "http://10.0.0.5:7300", "reverse", "5173"], + message: "--url must be https://, or http:// only for 127.0.0.1, [::1] or localhost", + }, + ...[ + "http://127.0.0.1:7300/?x=1", + "http://127.0.0.1:7300?x=1", + "http://127.0.0.1:7300/#top", + "http://127.0.0.1:7300/base", + "http://127.0.0.1:7300/?", + ].map((url) => ({ + argv: ["--url", url, "reverse", "5173"], + message: "--url must be the worker's origin only: no path, query or fragment", + })), + { + argv: ["reverse", "5173"], + env: { ...ENV, SIMLOCK_URL: "https://worker.example/v1" }, + message: "--url must be the worker's origin only: no path, query or fragment", + }, + { + argv: ["reverse", "5173"], + env: { SIMLOCK_TOKEN: "sk_agent_x" }, + message: "No worker URL: pass --url or set SIMLOCK_URL", + }, + { + argv: ["reverse", "5173"], + env: { SIMLOCK_URL: "http://127.0.0.1:7300" }, + message: "No token: pass --token or set SIMLOCK_TOKEN", + }, + { + argv: ["reverse", "5173"], + lease: "", + message: "--lease must be 1 to 256 characters", + }, + { + argv: ["reverse", "5173"], + lease: "L".repeat(257), + message: "--lease must be 1 to 256 characters", + }, + { + argv: ["reverse", "5173"], + env: { ...ENV, SIMLOCK_URL: `https://${"a".repeat(2041)}` }, + message: "--url must be https://, or http:// only for 127.0.0.1, [::1] or localhost", + }, + { + argv: ["reverse", "5173"], + env: { ...ENV, SIMLOCK_TOKEN: "t".repeat(4097) }, + message: "No token: pass --token or set SIMLOCK_TOKEN", + }, + { + argv: Array.from({ length: 9 }, (_, index) => ["reverse", String(5000 + index)]).flat(), + message: "At most 8 tunnels", + }, + ]; + for (const { argv, env, lease, message } of cases) { + const cli = command(env ?? ENV); + const exit = cli.run(["tunnel", ...argv, "--lease", lease ?? "L1"]); + await vi.waitFor(() => + expect({ argv, err: cli.err.join("") }).not.toEqual({ argv, err: "" }), + ); + expect(await exit).toBe(2); + expect({ argv, error: JSON.parse(cli.err.join("")) }).toEqual({ + argv, + error: { error: { code: "USAGE", message } }, + }); + expect(cli.webSocket.connections).toEqual([]); + expect(cli.httpJson.requests).toEqual([]); + } + }); +}); + +describe("simlock tunnel that runs", () => { + it("prints one line per tunnel, naming the lease the flags, the token or its only lease gave", async () => { + const ok: readonly { + readonly argv: readonly string[]; + readonly env?: NodeJS.ProcessEnv; + readonly lines: readonly string[]; + readonly url: string; + readonly authorization?: string; + }[] = [ + { + argv: ["reverse", "65535:1", "--lease", "L1"], + lines: ["reverse device:65535 -> localhost:1 (lease L1)"], + url: "ws://127.0.0.1:7300/v1/leases/L1/tunnel", + }, + { + argv: ["reverse", "5173", "--lease", "L1"], + lines: ["reverse device:5173 -> localhost:5173 (lease L1)"], + url: "ws://127.0.0.1:7300/v1/leases/L1/tunnel", + }, + { + argv: ["reverse", "8081:3000", "reverse", "9000", "--lease", "L1"], + lines: [ + "reverse device:8081 -> localhost:3000 (lease L1)", + "reverse device:9000 -> localhost:9000 (lease L1)", + ], + url: "ws://127.0.0.1:7300/v1/leases/L1/tunnel", + }, + { + argv: [ + "--url", + "https://worker.example:7400/", + "--token", + "sk_flag", + "reverse", + "5173", + "--lease", + "L 2", + ], + authorization: "Bearer sk_flag", + lines: ["reverse device:5173 -> localhost:5173 (lease L 2)"], + url: "wss://worker.example:7400/v1/leases/L%202/tunnel", + }, + ...["localhost", "[::1]"].map((host) => ({ + argv: ["--url", `http://${host}:7300`, "reverse", "5173", "--lease", "L1"], + lines: ["reverse device:5173 -> localhost:5173 (lease L1)"], + url: `ws://${host}:7300/v1/leases/L1/tunnel`, + })), + { + argv: ["reverse", "5173"], + lines: ["reverse device:5173 -> localhost:5173 (lease only)"], + url: "ws://127.0.0.1:7300/v1/leases/only/tunnel", + }, + ]; + for (const { argv, authorization, lines, url } of ok) { + const cli = command(ENV); + cli.httpJson.answers.set("http://127.0.0.1:7300/v1/identity", { + body: { role: "agent" }, + status: 200, + }); + cli.httpJson.answers.set("http://127.0.0.1:7300/v1/leases", { + body: { leases: [{ id: "only", requesterId: "agent-1" }] }, + status: 200, + }); + const exit = cli.run(["tunnel", ...argv]); + await vi.waitFor(() => expect(cli.webSocket.connections).toHaveLength(1)); + const connection = cli.webSocket.connections[0]; + expect(connection?.url).toBe(url); + expect(connection?.options.headers.authorization).toBe(authorization ?? "Bearer sk_agent_x"); + expect(connection?.options.handshakeTimeoutMs).toBe(10_000); + const hello = decodeTunnelFrame(connection?.peer.sent[0] ?? new Uint8Array()); + expect(hello?.tag).toBe(TUNNEL_TAG.hello); + expect(JSON.parse(new TextDecoder().decode(hello?.payload))).toEqual({ + tunnels: lines.map((text) => ({ + devicePort: Number(/device:(\d+)/.exec(text)?.[1]), + kind: "reverse", + })), + }); + connection?.peer.receive(READY); + await vi.waitFor(() => expect(cli.out.join("").split("\n").slice(0, -1)).toEqual(lines)); + cli.signals.emit("SIGINT"); + expect(await exit).toBe(0); + } + + const refused: readonly { + readonly leases: readonly { id: string; requesterId: string }[]; + readonly role: string; + readonly message: string; + }[] = [ + { + leases: [], + message: + "This token holds no lease: start one with `simlock lease` on the worker, or pass --lease ", + role: "agent", + }, + { + leases: [ + { id: "A", requesterId: "agent-1" }, + { id: "B", requesterId: "agent-1" }, + ], + message: + "This token holds more than one lease (A, B); pass --lease to name the device you mean", + role: "agent", + }, + { + leases: [{ id: "A", requesterId: "agent-1" }], + message: "An operator token must name its lease: pass --lease ", + role: "admin", + }, + ]; + for (const { leases, message, role } of refused) { + const cli = command(ENV); + cli.httpJson.answers.set("http://127.0.0.1:7300/v1/identity", { + body: { role }, + status: 200, + }); + cli.httpJson.answers.set("http://127.0.0.1:7300/v1/leases", { + body: { leases }, + status: 200, + }); + const exit = cli.run(["tunnel", "reverse", "5173"]); + await vi.waitFor(() => expect(cli.err.join("")).not.toBe("")); + expect(await exit).toBe(2); + expect(JSON.parse(cli.err.join(""))).toEqual({ error: { code: "USAGE", message } }); + expect(cli.webSocket.connections).toEqual([]); + } + }); +}); + +function open(conn: number, devicePort: number): Uint8Array { + return encodeTunnelFrame(TUNNEL_TAG.open, conn, JSON.stringify({ devicePort, kind: "reverse" })); +} + +function sentFrames(cli: ReturnType) { + return (cli.webSocket.connections[0]?.peer.sent ?? []).flatMap((bytes) => { + const frame = decodeTunnelFrame(bytes); + return frame === undefined ? [] : [frame]; + }); +} + +async function started(argv: readonly string[]) { + const cli = command(ENV); + const exit = cli.run(["tunnel", ...argv, "--lease", "L1"]); + await vi.waitFor(() => expect(cli.webSocket.connections).toHaveLength(1)); + const peer = cli.webSocket.connections[0]?.peer; + if (peer === undefined) throw new Error("no socket"); + peer.receive(READY); + return { cli, exit, peer }; +} + +async function warningsPerTunnel(): Promise { + const quiet = await started(["reverse", "5173:5174", "reverse", "6000"]); + quiet.cli.tcpStreams.refusedPorts.add(5174); + quiet.cli.tcpStreams.refusedPorts.add(6000); + const opening = async (conn: number, port: number) => { + quiet.peer.receive(open(conn, port)); + await vi.waitFor(() => + expect(sentFrames(quiet.cli).filter((f) => f.tag === TUNNEL_TAG.reset)).toHaveLength( + (conn + 1) / 2, + ), + ); + }; + const warnings = () => + quiet.cli.err + .join("") + .split("\n") + .filter((line) => line !== ""); + quiet.peer.receive(open(9, 7000)); + await opening(1, 5173); + expect(warnings()).toEqual(["reverse 5173: nothing listening on localhost:5174"]); + quiet.cli.clock.advance(9_999); + await opening(3, 5173); + expect(warnings()).toEqual(["reverse 5173: nothing listening on localhost:5174"]); + await opening(5, 6000); + expect(warnings()).toEqual([ + "reverse 5173: nothing listening on localhost:5174", + "reverse 6000: nothing listening on localhost:6000", + ]); + quiet.cli.clock.advance(1); + await opening(7, 5173); + expect(warnings()).toHaveLength(3); + expect(warnings()[2]).toBe("reverse 5173: nothing listening on localhost:5174"); + expect( + sentFrames(quiet.cli) + .filter((f) => f.tag === TUNNEL_TAG.reset) + .map((f) => f.conn), + ).toEqual([1, 3, 5, 7]); + expect(quiet.cli.tcpStreams.connections).toEqual([]); + expect(quiet.peer.closedWith).toBeUndefined(); + quiet.cli.signals.emit("SIGINT"); + expect(await quiet.exit).toBe(0); +} + +async function responseThroughTheTunnel() { + const page = await started(["reverse", "5173:5174"]); + page.peer.receive(open(1, 5173)); + await vi.waitFor(() => expect(page.cli.tcpStreams.connections).toHaveLength(1)); + expect(page.cli.tcpStreams.connections[0]?.port).toBe(5174); + const local = page.cli.tcpStreams.connections[0]?.peer; + if (local === undefined) throw new Error("no local connection"); + const response = Uint8Array.from({ length: 1_048_576 }, (_, index) => index % 251); + for (let at = 0; at < response.length; at += 131_072) + local.send(response.subarray(at, at + 131_072)); + local.end(); + const received: number[] = []; + let ended = false; + let before = 0; + const credit = (conn: number, size: number) => { + const granted = new Uint8Array(4); + new DataView(granted.buffer).setUint32(0, size); + page.peer.receive(encodeTunnelFrame(TUNNEL_TAG.credit, conn, granted)); + }; + const drain = () => { + const frames = sentFrames(page.cli); + for (const frame of frames.slice(before)) { + if (frame.tag === TUNNEL_TAG.data) for (const byte of frame.payload) received.push(byte); + else if (frame.tag === TUNNEL_TAG.end) ended = true; + } + before = frames.length; + }; + await vi.waitFor(() => { + drain(); + expect(received.length).toBe(262_144); + }); + await new Promise((done) => setTimeout(done, 20)); + drain(); + expect(received).toHaveLength(262_144); + while (!ended) { + const have = received.length; + credit(1, 65_536); + await vi.waitFor(() => { + drain(); + expect(received.length > have || ended).toBe(true); + }); + } + expect(received).toHaveLength(1_048_576); + expect(Uint8Array.from(received)).toEqual(response); + const dataSizes = sentFrames(page.cli) + .filter((f) => f.tag === TUNNEL_TAG.data) + .map((f) => f.payload.length); + expect(Math.max(...dataSizes)).toBe(TUNNEL_MAX_DATA_BYTES); + expect(dataSizes.every((size) => size <= TUNNEL_MAX_DATA_BYTES)).toBe(true); + + return { local, page }; +} + +async function writesToTheCaller( + page: Awaited>, + local: FakeTcpPeer, +): Promise { + for (const size of [65_536, 30_000]) { + page.peer.receive(encodeTunnelFrame(TUNNEL_TAG.data, 1, new Uint8Array(size))); + } + await vi.waitFor(() => + expect(local.written.map((chunk) => chunk.length)).toEqual([65_536, 30_000]), + ); + await vi.waitFor(() => { + const credits = sentFrames(page.cli) + .filter((f) => f.tag === TUNNEL_TAG.credit) + .map((f) => new DataView(f.payload.buffer, f.payload.byteOffset).getUint32(0)); + expect(credits).toEqual([65_536, 30_000]); + }); + page.peer.receive(encodeTunnelFrame(TUNNEL_TAG.end, 1)); + await vi.waitFor(() => expect(local.writeEnded).toBe(true)); + page.peer.receive(open(3, 5173)); + await vi.waitFor(() => expect(page.cli.tcpStreams.connections).toHaveLength(2)); + const second = page.cli.tcpStreams.connections[1]?.peer; + expect(second?.closed).toBe(false); + page.peer.receive(encodeTunnelFrame(TUNNEL_TAG.reset, 3)); + await vi.waitFor(() => expect(second?.closed).toBe(true)); +} + +async function brokenWrite(page: Awaited>): Promise { + page.peer.receive(open(5, 5173)); + await vi.waitFor(() => expect(page.cli.tcpStreams.connections).toHaveLength(3)); + const broken = page.cli.tcpStreams.connections[2]?.peer; + if (broken === undefined) throw new Error("no third connection"); + broken.writeFailure = new Error("write EPIPE"); + page.peer.receive(encodeTunnelFrame(TUNNEL_TAG.data, 5, new Uint8Array(10))); + page.peer.receive(encodeTunnelFrame(TUNNEL_TAG.end, 5)); + await vi.waitFor(() => + expect( + sentFrames(page.cli) + .filter((f) => f.tag === TUNNEL_TAG.reset) + .map((f) => f.conn), + ).toEqual([5]), + ); + await settle(); + expect(broken.closed).toBe(true); + expect(sentFrames(page.cli).filter((f) => f.tag === TUNNEL_TAG.credit && f.conn === 5)).toEqual( + [], + ); + expect(page.cli.err).toEqual([]); + page.peer.receive(open(7, 5173)); + await vi.waitFor(() => expect(page.cli.tcpStreams.connections).toHaveLength(4)); + expect(page.cli.tcpStreams.connections[3]?.peer.closed).toBe(false); + page.cli.signals.emit("SIGINT"); + expect(await page.exit).toBe(0); +} + +describe("simlock tunnel carrying connections", () => { + it("warns once per 10 s per tunnel when nothing listens, keeps the tunnel open, and a 1 MiB response arrives whole", async () => { + await warningsPerTunnel(); + const { local, page } = await responseThroughTheTunnel(); + await writesToTheCaller(page, local); + await brokenWrite(page); + }); +}); + +// why: a failure reaches stderr through a chain of promises, so a check that nothing was written lets them run first. +function settle(): Promise { + return new Promise((done) => setTimeout(done, 0)); +} + +async function withLocalConnection( + cli: ReturnType, + peer: { receive(bytes: Uint8Array): void }, + devicePort: number, +) { + const before = cli.tcpStreams.connections.length; + peer.receive(open(1 + 2 * before, devicePort)); + await vi.waitFor(() => expect(cli.tcpStreams.connections).toHaveLength(before + 1)); + const local = cli.tcpStreams.connections[before]?.peer; + if (local === undefined) throw new Error("no local connection"); + expect(local.closed).toBe(false); + return local; +} + +function refusedFrame(code: string, message: string): Uint8Array { + return encodeTunnelFrame(TUNNEL_TAG.refused, 0, JSON.stringify({ code, message })); +} + +function errorBody(code: string, message: string) { + return { error: { code, message } }; +} + +function line(cli: ReturnType): unknown { + return JSON.parse(cli.err.join("")); +} + +async function upgradeRefusals(): Promise { + const upgrades: readonly { + readonly refusal: WebSocketRefusedError; + readonly exit?: number; + readonly code: string; + readonly message: string; + }[] = [ + { + code: "UNAUTHENTICATED", + message: "No valid token", + refusal: new WebSocketRefusedError( + 401, + JSON.stringify(errorBody("UNAUTHENTICATED", "No valid token")), + ), + }, + { + code: "UNKNOWN_LEASE", + message: "Unknown lease L1", + refusal: new WebSocketRefusedError( + 404, + JSON.stringify(errorBody("UNKNOWN_LEASE", "Unknown lease L1")), + ), + }, + { + code: "TUNNEL_UNAVAILABLE", + message: "Tunnels are off", + refusal: new WebSocketRefusedError( + 503, + JSON.stringify(errorBody("TUNNEL_UNAVAILABLE", "Tunnels are off")), + ), + }, + { + code: "UNKNOWN_LEASE", + message: "Lease L1 is not known to this worker", + refusal: new WebSocketRefusedError(404, "Not Found"), + }, + { + code: "BAD_REQUEST", + exit: 2, + message: "Bad upgrade", + refusal: new WebSocketRefusedError( + 400, + JSON.stringify(errorBody("BAD_REQUEST", "Bad upgrade")), + ), + }, + { + code: "TUNNEL_DISCONNECTED", + message: "Lease L1: the worker answered 502", + refusal: new WebSocketRefusedError(502, "Bad Gateway"), + }, + ]; + for (const { code, exit, message, refusal } of upgrades) { + const cli = command(ENV); + cli.webSocket.failure = refusal; + expect(await cli.run(["tunnel", "reverse", "5173", "--lease", "L1"])).toBe(exit ?? 1); + expect(line(cli)).toEqual(errorBody(code, message)); + } +} + +async function lookupFailures(): Promise { + const lookups: readonly { + readonly identity?: { status: number; body: unknown }; + readonly code: string; + readonly message: string; + }[] = [ + { + code: "UNAUTHENTICATED", + identity: { body: errorBody("UNAUTHENTICATED", "No valid token"), status: 401 }, + message: "No valid token", + }, + { + code: "FORBIDDEN", + identity: { body: errorBody("FORBIDDEN", "Not allowed"), status: 403 }, + message: "Not allowed", + }, + { + code: "TUNNEL_DISCONNECTED", + identity: { body: undefined, status: 502 }, + message: "The worker answered 502", + }, + { + code: "TUNNEL_DISCONNECTED", + message: "No answer from http://127.0.0.1:7300", + }, + ]; + for (const { code, identity, message } of lookups) { + const cli = command(ENV); + if (identity !== undefined) + cli.httpJson.answers.set("http://127.0.0.1:7300/v1/identity", identity); + expect(await cli.run(["tunnel", "reverse", "5173"])).toBe(1); + expect(line(cli)).toEqual(errorBody(code, message)); + expect(cli.webSocket.connections).toEqual([]); + } +} + +async function refusalFrame(): Promise { + const refused = await started(["reverse", "80"]); + const refusedLocal = await withLocalConnection(refused.cli, refused.peer, 80); + refused.peer.receive(refusedFrame("TUNNEL_BAD_PORT", "Device port 80 is below 1024")); + expect(await refused.exit).toBe(1); + expect(refusedLocal.closed).toBe(true); + expect(refused.peer.closedWith?.code).toBe(1000); + expect(refused.cli.clock.pendingTimerCount).toBe(0); + expect(line(refused.cli)).toEqual( + errorBody("TUNNEL_BAD_PORT", "Lease L1: Device port 80 is below 1024"), + ); + const unknown = await started(["reverse", "5173"]); + unknown.peer.receive(refusedFrame("NOT_A_CODE", "something new")); + expect(await unknown.exit).toBe(1); + expect(line(unknown.cli)).toEqual(errorBody("TUNNEL_FAILED", "Lease L1: something new")); + const garbled = await started(["reverse", "5173"]); + garbled.peer.receive(open(1, 7000)); + garbled.peer.receive(encodeTunnelFrame(TUNNEL_TAG.open, 3, "not json")); + garbled.peer.receive(encodeTunnelFrame(TUNNEL_TAG.refused, 0, "not json")); + expect(await garbled.exit).toBe(1); + expect(line(garbled.cli)).toEqual( + errorBody("TUNNEL_FAILED", "Lease L1: the worker refused the tunnel"), + ); + expect(garbled.cli.tcpStreams.connections).toEqual([]); +} + +async function lossesOfTheSocket(): Promise { + const losses: readonly { + readonly drop: [number, string]; + readonly exit: number; + readonly error: unknown; + }[] = [ + { + drop: [4001, "device released"], + error: errorBody("TUNNEL_LEASE_ENDED", "Lease L1 ended: device released"), + exit: 14, + }, + ...[1011, 1001, 1006].map((code) => ({ + drop: [code, ""] as [number, string], + error: errorBody( + "TUNNEL_DISCONNECTED", + `Lease L1: the connection to ${ENV.SIMLOCK_URL} was lost`, + ), + exit: 1, + })), + ]; + for (const { drop, error, exit } of losses) { + const lost = await started(["reverse", "5173"]); + const lostLocal = await withLocalConnection(lost.cli, lost.peer, 5173); + lost.peer.dropped(...drop); + expect(await lost.exit).toBe(exit); + expect(lostLocal.closed).toBe(true); + expect(lost.cli.clock.pendingTimerCount).toBe(0); + expect(line(lost.cli)).toEqual(error); + } +} + +async function silentSocket(): Promise { + const silent = await started(["reverse", "5173"]); + silent.cli.clock.advance(30_000); + silent.peer.ping(); + silent.cli.clock.advance(44_999); + await settle(); + expect(silent.cli.err).toEqual([]); + const silentLocal = await withLocalConnection(silent.cli, silent.peer, 5173); + silent.cli.clock.advance(44_999); + await settle(); + expect(silent.cli.err).toEqual([]); + silent.cli.clock.advance(1); + await settle(); + expect(silent.cli.err).toHaveLength(1); + expect(await silent.exit).toBe(1); + expect(silentLocal.closed).toBe(true); + expect(silent.peer.closedWith?.code).toBe(1000); + expect(silent.peer.terminated).toBe(true); + expect(silent.cli.clock.pendingTimerCount).toBe(0); + expect(line(silent.cli)).toEqual( + errorBody("TUNNEL_DISCONNECTED", "Lease L1: nothing was heard from the worker for 45 s"), + ); +} + +async function noReadySocket(): Promise { + const noReady = command(ENV); + const noReadyExit = noReady.run(["tunnel", "reverse", "5173", "--lease", "L1"]); + await vi.waitFor(() => expect(noReady.webSocket.connections).toHaveLength(1)); + const quietPeer = noReady.webSocket.connections[0]?.peer; + for (let at = 0; at < 89_999; at += 15_000) { + noReady.clock.advance(Math.min(15_000, 89_999 - at)); + quietPeer?.ping(); + } + await settle(); + expect(noReady.err).toEqual([]); + noReady.clock.advance(1); + await settle(); + expect(noReady.err).toHaveLength(1); + expect(await noReadyExit).toBe(1); + expect(quietPeer?.closedWith?.code).toBe(1000); + expect(quietPeer?.terminated).toBe(true); + expect(noReady.clock.pendingTimerCount).toBe(0); + expect(line(noReady)).toEqual( + errorBody("TUNNEL_DISCONNECTED", "Lease L1: no READY from the worker within 90 s"), + ); +} + +async function ctrlC(): Promise { + const idle = await started(["reverse", "5173"]); + for (let at = 0; at < 90_000; at += 15_000) { + idle.cli.clock.advance(15_000); + idle.peer.ping(); + } + await settle(); + expect(idle.cli.err).toEqual([]); + expect(idle.peer.closedWith).toBeUndefined(); + const idleLocal = await withLocalConnection(idle.cli, idle.peer, 5173); + idle.peer.silentOnClose = true; + idle.cli.signals.emit("SIGINT"); + expect(idle.peer.closedWith?.code).toBe(1000); + let settled = false; + void idle.exit.then(() => { + settled = true; + }); + idle.cli.clock.advance(1_999); + await settle(); + expect(settled).toBe(false); + idle.cli.clock.advance(1); + await settle(); + expect(settled).toBe(true); + expect(await idle.exit).toBe(0); + expect(idleLocal.closed).toBe(true); + expect(idle.peer.terminated).toBe(true); + expect(idle.cli.clock.pendingTimerCount).toBe(0); +} + +async function sigterm(): Promise { + const term = await started(["reverse", "5173"]); + const termLocal = await withLocalConnection(term.cli, term.peer, 5173); + term.cli.signals.emit("SIGTERM"); + expect(term.peer.closedWith?.code).toBe(1000); + expect(await term.exit).toBe(0); + expect(termLocal.closed).toBe(true); + expect(term.cli.clock.pendingTimerCount).toBe(0); +} + +describe("simlock tunnel that is refused or loses its worker", () => { + it("exits with the worker's code and one JSON line, and a Ctrl-C closes and waits at most 2 s", async () => { + await upgradeRefusals(); + await lookupFailures(); + await refusalFrame(); + await lossesOfTheSocket(); + await silentSocket(); + await noReadySocket(); + await ctrlC(); + await sigterm(); + }); +}); diff --git a/src/cli/types.ts b/src/cli/types.ts index 70255542e..58416bb7c 100644 --- a/src/cli/types.ts +++ b/src/cli/types.ts @@ -10,11 +10,14 @@ import type { DaemonHome, DaemonLauncher, Filesystem, + HttpJsonClient, IpcConnector, ParentWatch, ServiceDefinition, ServiceManager, SystemStats, + TcpStreamConnector, + WebSocketClientConnector, } from "../ports/index.js"; export interface Signals { @@ -91,6 +94,13 @@ export interface CliEnvironment { readonly stdout: Output; readonly confirm?: ((question: string) => Promise) | undefined; readonly runPassthrough?: (command: PassthroughCommand) => Promise; + /** why: `simlock tunnel` reaches a worker or gateway over HTTP and WebSocket, not the daemon's socket; each port loads its adapter on first use. */ + readonly webSocket: WebSocketClientConnector; + readonly httpJson: HttpJsonClient; + readonly tcpStreams: TcpStreamConnector; + /** why: `SIMLOCK_URL` and `SIMLOCK_TOKEN` name the daemon `simlock tunnel` calls and the credential it sends. */ + readonly tunnelUrl?: string; + readonly tunnelToken?: string; readonly readStdin?: () => Promise; } @@ -115,4 +125,7 @@ export interface CliEnvironmentPorts { readonly runPassthrough?: (command: PassthroughCommand) => Promise; readonly readStdin?: () => Promise; readonly parentPid?: number; + readonly webSocket?: WebSocketClientConnector; + readonly httpJson?: HttpJsonClient; + readonly tcpStreams?: TcpStreamConnector; } diff --git a/src/daemon/tunnel-cli.e2e.test.ts b/src/daemon/tunnel-cli.e2e.test.ts new file mode 100644 index 000000000..9511c5a77 --- /dev/null +++ b/src/daemon/tunnel-cli.e2e.test.ts @@ -0,0 +1,207 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { createServer, type Server, type Socket } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { buildCliEnvironment, runCli } from "../cli/index.js"; +import { FakeDeviceTcp, FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; +import { + FakeClock, + FakeDaemonLauncher, + FakeSystemStats, + MemoryFilesystem, + MemoryIpcTransport, + NoopLogger, + SystemClock, +} from "../ports/index.js"; +import type { DispatchSession } from "./dispatch.js"; +import { startDaemon } from "./main.js"; +import type { DaemonServer } from "./server.js"; + +async function freeLoopbackPort(): Promise { + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + await new Promise((resolve) => server.close(() => resolve())); + if (typeof address !== "object" || address === null) throw new Error("no port bound"); + return address.port; +} + +const admin: DispatchSession = { + manageEventSubscription: () => undefined, + via: "socket", + principal: "test-operator", + role: "admin", +}; + +const agent: DispatchSession = { + manageEventSubscription: () => undefined, + via: "socket", + principal: "agent-1", + role: "agent", +}; + +type Listener = () => void; + +// why: the CLI's signal source, so a test sends Ctrl-C without signalling the test process. +class TestSignals { + readonly #listeners = new Map>(); + on(signal: string, listener: Listener): this { + const set = this.#listeners.get(signal) ?? new Set(); + set.add(listener); + this.#listeners.set(signal, set); + return this; + } + off(signal: string, listener: Listener): this { + this.#listeners.get(signal)?.delete(listener); + return this; + } + emit(signal: string): void { + for (const listener of this.#listeners.get(signal) ?? []) listener(); + } +} + +describe("simlock tunnel against a lone worker", () => { + const daemons: DaemonServer[] = []; + const directories: string[] = []; + const servers: Server[] = []; + const sockets: Socket[] = []; + + afterEach(async () => { + for (const socket of sockets.splice(0)) socket.destroy(); + await Promise.all( + servers + .splice(0) + .map((server) => new Promise((resolve) => server.close(() => resolve()))), + ); + await Promise.all(daemons.splice(0).map((daemon) => daemon.stop("test"))); + await Promise.all( + directories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })), + ); + }); + + async function worker() { + const port = await freeLoopbackPort(); + const path = await mkdtemp(join(tmpdir(), "simlock-e2e-tunnel-cli-")); + directories.push(path); + const deviceTcp = new FakeDeviceTcp(); + const daemon = await startDaemon({ + configOverrides: { + capabilities: { tunnel: { enabled: true } }, + http: { enabled: true, host: "127.0.0.1", port }, + }, + dataDirectory: path, + deviceDataTables: fakeDeviceDataTables, + drivers: [ + new FakeDriver({ + availableOsVersions: ["18.0"], + clock: new SystemClock(), + deviceTcp, + knownModels: ["Pixel-A"], + platform: "android", + }), + ], + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + version: "1.0.0-e2e", + }); + daemons.push(daemon); + const holder = await daemon.dispatch("token.create", { label: "holder", role: "agent" }, admin); + const granted = await daemon.dispatch( + "lease.request", + { model: "Pixel-A", platform: "android" }, + { ...agent, principal: holder.token.id }, + ); + return { + deviceTcp, + leaseId: (granted as { lease: { id: string } }).lease.id, + token: holder.secret, + url: `http://127.0.0.1:${String(port)}`, + }; + } + + async function callerServer(received: string[]): Promise { + const server = createServer((socket) => { + sockets.push(socket); + socket.on("data", (chunk) => { + received.push(chunk.toString("utf8")); + socket.write("from-caller"); + }); + }); + servers.push(server); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (typeof address !== "object" || address === null) throw new Error("no port bound"); + return address.port; + } + + function command(env: NodeJS.ProcessEnv) { + const signals = new TestSignals(); + const out: string[] = []; + const err: string[] = []; + const environment = buildCliEnvironment( + { + clock: new FakeClock(0), + daemonHome: { dataDirectory: "/unused", gatewayPresent: false, role: "worker" }, + filesystem: new MemoryFilesystem(), + homeDirectory: "/home/caller", + hostPlatform: process.platform, + ipc: new MemoryIpcTransport(), + launcher: new FakeDaemonLauncher(), + runTool: async () => ({ outcome: "not-found" }), + signals, + stderr: { write: (value) => err.push(value) }, + stdout: { write: (value) => out.push(value) }, + systemStats: new FakeSystemStats({ cpuCount: 2, totalRamBytes: 2 ** 30 }), + workingDirectory: "/work", + }, + env, + ); + return { + err, + out, + run: (argv: readonly string[]) => runCli(argv, environment), + signals, + }; + } + + it("opens a reverse tunnel, carries bytes, refuses with the worker's code, and its rules are gone after Ctrl-C", async () => { + const lone = await worker(); + const received: string[] = []; + const callerPort = await callerServer(received); + const cli = command({ SIMLOCK_TOKEN: lone.token, SIMLOCK_URL: lone.url }); + + const exit = cli.run(["tunnel", "reverse", `5173:${String(callerPort)}`]); + await vi.waitFor(() => expect(cli.out.join("")).toContain("reverse device:5173"), { + timeout: 10_000, + }); + expect(cli.out.join("")).toBe( + `reverse device:5173 -> localhost:${String(callerPort)} (lease ${lone.leaseId})\n`, + ); + expect(lone.deviceTcp.reversed).toEqual([5173]); + + const peer = lone.deviceTcp.connect(5173); + peer.send("from-device"); + await vi.waitFor(() => expect(received.join("")).toBe("from-device"), { timeout: 10_000 }); + await vi.waitFor(() => expect(peer.writtenText()).toBe("from-caller"), { timeout: 10_000 }); + + cli.signals.emit("SIGINT"); + expect(await exit).toBe(0); + await vi.waitFor(() => expect(lone.deviceTcp.reversed).toEqual([]), { timeout: 10_000 }); + expect(cli.err.join("")).toBe(""); + + const refused = command({ SIMLOCK_TOKEN: lone.token, SIMLOCK_URL: lone.url }); + const refusedExit = refused.run(["tunnel", "reverse", "80"]); + await vi.waitFor(() => expect(refused.err.join("")).not.toBe(""), { timeout: 10_000 }); + expect(await refusedExit).toBe(1); + expect(refused.out.join("")).toBe(""); + expect(JSON.parse(refused.err.join(""))).toEqual({ + error: { + code: "TUNNEL_BAD_PORT", + message: `Lease ${lone.leaseId}: reverse 80: device ports are 1024 to 65535`, + }, + }); + }); +}); diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index cd12e9b2d..105f7c77c 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -28,6 +28,8 @@ Uses: nothing from other components. Imported by: every component that touches t | `HostInfo` | `host-info.ts` | `NodeHostInfo` | `FakeHostInfo` | OS, version (`sw_vers` on macOS), arch | | `HostLoadProbe` | `host-load.ts` | `DarwinHostLoadProbe`, `WindowsHostLoadProbe`, `LinuxHostLoadProbe` | `FakeHostLoadProbe` | CPU, memory, disk counters | | `TcpProbe` | `tcp-probe.ts` | `NodeTcpProbe` | `FakeTcpProbe` | Is a loopback port listening; send bytes | +| `WebSocketClientConnector` | `websocket-client.ts` | `NodeWebSocketClientConnector` (`ws`, loaded by `import()` on the first `connect`; a refused upgrade rejects with `WebSocketRefusedError` carrying its status and body) | `FakeWebSocketClientConnector` | A caller's WebSocket to a lease socket: headers, `send`, `close`, `onMessage`, `onPing`, `onClose`; 10 s handshake | +| `HttpJsonClient` | `http-json.ts` | `FetchHttpJsonClient` | `FakeHttpJsonClient` | One GET with a bearer token: 10 s, no redirects, body at most 1 MiB, answer `{status, body}` | | `TcpStreamConnector` | `tcp-stream.ts` | `NodeTcpStreamConnector` | `FakeTcpStreamConnector` | A long-lived loopback connection, bytes both ways | | `TcpListenerFactory` | `tcp-listener.ts` | `NodeTcpListenerFactory` | `FakeTcpListenerFactory` | A loopback port the worker listens on; each accepted connection is a `TcpStream` (`end()` half-closes); a taken port answers `undefined` | | `BytePipeLauncher` | `byte-pipe.ts` | `NodeBytePipeLauncher` | `FakeBytePipeLauncher` | A child with binary stdout; stdin is its liveness, or the commands `writeStdin` sends it (the fake records `stdinWrites`); no console window on Windows (`windowsHide`) | @@ -54,7 +56,7 @@ loaded with a dynamic `import()` on first open (Node 22.13 or later; below it `o `fs` or `child_process` import (`no-fs-or-process` in `.dependency-cruiser.mjs`). - The real adapters are built once, in the composition root (`src/daemon/main.ts`, or the CLI and MCP environment builders), and injected. -- Only `uplink-websocket.ts` and `upgrade-router.ts` import `ws`, so the CLI and MCP never load it. +- Only `uplink-websocket.ts`, `upgrade-router.ts` and `websocket-client.ts` name `ws`, and the last loads it with `import()` on its first `connect`, so only `simlock tunnel` ever loads it: the CLI and MCP never do otherwise. - A port is as small as its callers need. What the bytes mean is the caller's business (`TcpProbe.send` knows nothing of adb). diff --git a/src/ports/http-json.test.ts b/src/ports/http-json.test.ts new file mode 100644 index 000000000..0f5961054 --- /dev/null +++ b/src/ports/http-json.test.ts @@ -0,0 +1,56 @@ +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { FetchHttpJsonClient } from "./http-json.js"; + +const servers: Server[] = []; + +async function serve(handler: Parameters[1]): Promise { + const server = createServer(handler); + servers.push(server); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return `http://127.0.0.1:${String((server.address() as AddressInfo).port)}`; +} + +afterEach(async () => { + for (const server of servers.splice(0)) { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +// why: an adapter over fetch, proven by what a real HTTP server does with the bearer token, the body cap and a redirect, which the fake cannot show. +describe("FetchHttpJsonClient", () => { + it("sends the bearer token, answers status and JSON body, and rejects a redirect or a body past 1 MiB", async () => { + let authorization: string | undefined; + const base = await serve((request, response) => { + authorization = request.headers.authorization; + if (request.url === "/redirect") { + response.writeHead(302, { location: "/answer" }).end(); + } else if (request.url === "/big") { + response.writeHead(200).end("x".repeat(1_048_577)); + } else if (request.url === "/edge") { + response.writeHead(200).end(JSON.stringify({ pad: "x".repeat(1_048_576 - 10) })); + } else if (request.url === "/text") { + response.writeHead(502).end("bad gateway"); + } else { + response + .writeHead(401, { "content-type": "application/json" }) + .end('{"error":{"code":"X"}}'); + } + }); + const client = new FetchHttpJsonClient(); + + expect(await client.get(`${base}/answer`, "sk_token")).toEqual({ + body: { error: { code: "X" } }, + status: 401, + }); + expect(authorization).toBe("Bearer sk_token"); + expect((await client.get(`${base}/edge`, "t")).status).toBe(200); + expect(await client.get(`${base}/text`, "t")).toEqual({ body: undefined, status: 502 }); + await expect(client.get(`${base}/big`, "t")).rejects.toThrow("longer than 1048576 bytes"); + await expect(client.get(`${base}/redirect`, "t")).rejects.toThrow(); + }); +}); diff --git a/src/ports/http-json.timing.test.ts b/src/ports/http-json.timing.test.ts new file mode 100644 index 000000000..c9b0afdd6 --- /dev/null +++ b/src/ports/http-json.timing.test.ts @@ -0,0 +1,32 @@ +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { FetchHttpJsonClient } from "./http-json.js"; + +const servers: Server[] = []; + +afterEach(async () => { + for (const server of servers.splice(0)) { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +// why: the 10 s bound is real time against a server that never answers, so it lives in the timing project, not in a unit test where a loaded runner would move it. +describe("FetchHttpJsonClient's time limit", () => { + it("rejects a server that never answers after 10 s, not before", async () => { + const server = createServer(() => undefined); + servers.push(server); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const url = `http://127.0.0.1:${String((server.address() as AddressInfo).port)}/`; + + const started = Date.now(); + await expect(new FetchHttpJsonClient().get(url, "t")).rejects.toThrow(); + const elapsed = Date.now() - started; + + expect(elapsed).toBeGreaterThanOrEqual(9_900); + expect(elapsed).toBeLessThan(12_000); + }, 20_000); +}); diff --git a/src/ports/http-json.ts b/src/ports/http-json.ts new file mode 100644 index 000000000..8c2f217e8 --- /dev/null +++ b/src/ports/http-json.ts @@ -0,0 +1,61 @@ +const REQUEST_TIMEOUT_MS = 10_000; +const MAX_BODY_BYTES = 1_048_576; + +export interface HttpJsonAnswer { + readonly status: number; + readonly body: unknown; +} + +export interface HttpJsonClient { + // why: one GET with a bearer token; a connection that fails, a silent server and a body past 1 MiB all reject. + get(url: string, token: string): Promise; +} + +async function readCapped(response: Response): Promise { + const reader = response.body?.getReader(); + if (reader === undefined) return ""; + const chunks: Uint8Array[] = []; + let total = 0; + for (;;) { + const step = await reader.read(); + if (step.done) break; + total += step.value.length; + if (total > MAX_BODY_BYTES) { + await reader.cancel(); + throw new Error(`The answer is longer than ${String(MAX_BODY_BYTES)} bytes`); + } + chunks.push(step.value); + } + return Buffer.concat(chunks).toString("utf8"); +} + +export class FetchHttpJsonClient implements HttpJsonClient { + async get(url: string, token: string): Promise { + const response = await fetch(url, { + headers: { authorization: `Bearer ${token}` }, + redirect: "error", + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + const text = await readCapped(response); + let body: unknown; + try { + body = JSON.parse(text); + } catch { + body = undefined; + } + return { body, status: response.status }; + } +} + +export class FakeHttpJsonClient implements HttpJsonClient { + readonly requests: { readonly url: string; readonly token: string }[] = []; + // why: a test scripts each URL's answer; a URL with no entry rejects, as an unreachable host does. + readonly answers = new Map(); + + async get(url: string, token: string): Promise { + this.requests.push({ token, url }); + const answer = this.answers.get(url); + if (answer === undefined) throw new Error(`no answer scripted for ${url}`); + return answer; + } +} diff --git a/src/ports/index.ts b/src/ports/index.ts index 61ec4837b..3ed99bbf0 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -57,9 +57,10 @@ export { type LeaseSocket, type LeaseSocketAccept, MemoryLeaseSocket } from "./l export { type Clock, FakeClock, SystemClock, type TimerHandle } from "./clock.js"; /** * why: ADR 0005 §33's uplink port and its in-memory adapter. The WebSocket adapters are - * deliberately *not* re-exported here: they live in `./uplink-websocket.js`, the one module - * that imports `ws`, and only the daemon entrypoint needs them -- so the CLI and the MCP - * server, which import this barrel, never load a WebSocket implementation they never use. + * deliberately *not* re-exported here: they live in `./uplink-websocket.js`, which imports `ws` + * statically, and only the daemon entrypoint needs them. `websocket-client.ts` (re-exported) + * loads `ws` with `import()` on its first `connect`, so only `simlock tunnel` loads it in the + * CLI; the MCP server never does. */ export { createConnectionPair, @@ -180,3 +181,11 @@ export { NodeUpdaterLauncher, type UpdaterLauncher, } from "./updater-launcher.js"; +export { + FakeWebSocketClientConnector, + NodeWebSocketClientConnector, + WebSocketRefusedError, + type WebSocketClient, + type WebSocketClientConnector, +} from "./websocket-client.js"; +export { FakeHttpJsonClient, FetchHttpJsonClient, type HttpJsonClient } from "./http-json.js"; diff --git a/src/ports/tcp-stream.ts b/src/ports/tcp-stream.ts index a7485447b..df6893680 100644 --- a/src/ports/tcp-stream.ts +++ b/src/ports/tcp-stream.ts @@ -156,7 +156,13 @@ export class FakeTcpPeer { export class FakeTcpStreamConnector implements TcpStreamConnector { readonly connections: { readonly port: number; readonly peer: FakeTcpPeer }[] = []; + // why: a test lists the ports nothing listens on; connecting to one rejects, as a refused loopback connection does. + readonly refusedPorts = new Set(); + async connect(port: number): Promise { + if (this.refusedPorts.has(port)) { + throw new Error(`connect ECONNREFUSED 127.0.0.1:${String(port)}`); + } const peer = new FakeTcpPeer(); this.connections.push({ peer, port }); return peer.stream; diff --git a/src/ports/upgrade-router.ts b/src/ports/upgrade-router.ts index ee823e5a6..8fbaf9e5f 100644 --- a/src/ports/upgrade-router.ts +++ b/src/ports/upgrade-router.ts @@ -1,6 +1,6 @@ // why: the one `upgrade` listener of an HTTP server: `/v1/uplink` goes to the uplink's own handler, // `/v1/leases/{id}/` to the app's lease socket resolution, and anything else gets a 404 and its -// socket destroyed. With `uplink-websocket.ts`, the only code that imports `ws`; the ports barrel does +// socket destroyed. It imports `ws` statically, as `uplink-websocket.ts` does; the ports barrel does // not re-export it, so the CLI and MCP server never load it. import type { IncomingMessage, Server } from "node:http"; import type { Duplex } from "node:stream"; diff --git a/src/ports/uplink-websocket.ts b/src/ports/uplink-websocket.ts index 25d19ba6d..7b0d1f837 100644 --- a/src/ports/uplink-websocket.ts +++ b/src/ports/uplink-websocket.ts @@ -1,12 +1,13 @@ /** - * why: The WebSocket adapters behind the uplink port (`./uplink.ts`) -- the one file in the tree - * that imports `ws`, kept out of the ports barrel so processes that never open an uplink (the - * CLI, the MCP server) never load it. + * why: The WebSocket adapters behind the uplink port (`./uplink.ts`) -- imports `ws` statically, + * kept out of the ports barrel so processes that never open an uplink (the CLI, the MCP + * server) never load it. * - * Why `ws` at all: Node 22 ships a WebSocket *client* and no server, and its client cannot set - * request headers -- and the join token and the worker id both travel in headers at upgrade - * time (ADR 0005 §4). Both halves therefore use `ws`, pinned to an exact version in - * package.json. + * Why `ws` at all: Node 22 ships a WebSocket *client* and no server, so the gateway's half needs + * it, and the join token and the worker id both travel in headers at upgrade time (ADR 0005 §4). + * Node's client can set headers too; `ws` is chosen for this client because it exposes a refused + * upgrade's status and body and every ping, which Node's client hides. `ws` is pinned to an exact + * version in package.json. * * The gateway's half is deliberately `noServer: true`: the uplink lives on the gateway's * *existing* HTTP listener, upgraded on `/v1/uplink`, so the whole fleet still has exactly one diff --git a/src/ports/websocket-client.test.ts b/src/ports/websocket-client.test.ts new file mode 100644 index 000000000..3966f737e --- /dev/null +++ b/src/ports/websocket-client.test.ts @@ -0,0 +1,105 @@ +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; + +import { afterEach, describe, expect, it, vi } from "vitest"; +import { WebSocketServer } from "ws"; + +import { NodeWebSocketClientConnector, WebSocketRefusedError } from "./websocket-client.js"; + +const servers: Server[] = []; + +async function listen(server: Server): Promise { + servers.push(server); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return `ws://127.0.0.1:${String((server.address() as AddressInfo).port)}`; +} + +afterEach(async () => { + for (const server of servers.splice(0)) { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +// why: an adapter over ws, proven by what a real upgrade does: the refusal's status and body, the headers sent, and the pings, close and bytes that arrive. +describe("NodeWebSocketClientConnector", () => { + it("rejects a refused upgrade with its status and body, and reports headers, messages, pings and the close", async () => { + const refusing = createServer(); + refusing.on("upgrade", (_request, socket) => { + const body = '{"error":{"code":"TUNNEL_UNAVAILABLE"}}'; + socket.end( + `HTTP/1.1 503 Service Unavailable\r\ncontent-length: ${String(body.length)}\r\n\r\n${body}`, + ); + }); + const connector = new NodeWebSocketClientConnector(); + const options = { handshakeTimeoutMs: 5_000, headers: { authorization: "Bearer sk_x" } }; + const refused = await connector + .connect(await listen(refusing), options) + .catch((e: unknown) => e); + expect(refused).toBeInstanceOf(WebSocketRefusedError); + expect(refused).toMatchObject({ body: '{"error":{"code":"TUNNEL_UNAVAILABLE"}}', status: 503 }); + + const http = createServer(); + const wss = new WebSocketServer({ server: http }); + let authorization: string | undefined; + const clientCloses: [number, string][] = []; + wss.on("connection", (socket, request) => { + authorization = request.headers.authorization; + socket.on("close", (code, reason) => clientCloses.push([code, reason.toString("utf8")])); + let hellos = 0; + socket.on("message", (data) => { + hellos += 1; + if (hellos === 1) { + socket.ping(); + socket.send(Buffer.from([1, 2, 3])); + } else socket.close(4001, `got ${String((data as Buffer).length)}`); + }); + }); + const client = await connector.connect(await listen(http), options); + const messages: number[][] = []; + let pings = 0; + const closes: [number, string][] = []; + client.onMessage((bytes) => messages.push([...bytes])); + client.onPing(() => { + pings += 1; + }); + client.onClose((code, reason) => closes.push([code, reason])); + client.send(new Uint8Array([7])); + await vi.waitFor(() => expect(messages).toEqual([[1, 2, 3]])); + expect(pings).toBe(1); + expect(authorization).toBe("Bearer sk_x"); + client.send(new Uint8Array([9, 9])); + await vi.waitFor(() => expect(closes).toEqual([[4001, "got 2"]])); + const second = await connector.connect( + `ws://127.0.0.1:${String((http.address() as AddressInfo).port)}`, + options, + ); + second.close(1000, "bye"); + await vi.waitFor(() => expect(clientCloses).toContainEqual([1000, "bye"])); + + const silent = createServer(); + const held: { destroy(): void }[] = []; + silent.on("upgrade", (_request, socket) => held.push(socket)); + await expect( + connector.connect(await listen(silent), { ...options, handshakeTimeoutMs: 100 }), + ).rejects.toThrow(); + for (const socket of held) socket.destroy(); + const stallingHttp = createServer(); + const stalled = new WebSocketServer({ server: stallingHttp }); + stalled.on("connection", (_socket, request) => { + request.socket.pause(); + held.push(request.socket); + }); + const stuck = await connector.connect(await listen(stallingHttp), options); + const stuckCloses: number[] = []; + stuck.onClose((code) => stuckCloses.push(code)); + stuck.close(1000, ""); + stuck.terminate(); + await vi.waitFor(() => expect(stuckCloses).toEqual([1006])); + for (const socket of held) socket.destroy(); + + const late: [number, string][] = []; + client.onClose((code, reason) => late.push([code, reason])); + expect(late).toEqual([[4001, "got 2"]]); + }); +}); diff --git a/src/ports/websocket-client.ts b/src/ports/websocket-client.ts new file mode 100644 index 000000000..ecbd7bb70 --- /dev/null +++ b/src/ports/websocket-client.ts @@ -0,0 +1,186 @@ +import type { RawData, WebSocket as WsSocket } from "ws"; + +export interface WebSocketClientOptions { + readonly headers: Readonly>; + readonly handshakeTimeoutMs: number; +} + +// why: `connect` rejects with this when the server answers the upgrade with a plain HTTP response, so a caller can read the refusal's status and JSON body, which Node's own WebSocket client hides. +export class WebSocketRefusedError extends Error { + constructor( + readonly status: number, + readonly body: string, + ) { + super(`The server refused the WebSocket upgrade with ${String(status)}`); + this.name = "WebSocketRefusedError"; + } +} + +export interface WebSocketClient { + send(bytes: Uint8Array): void; + close(code: number, reason: string): void; + // why: `close` waits for the server's close frame, and `ws` keeps a timer and the TCP socket alive for 30 s when none comes; a caller that gave up waiting tears the socket down so nothing holds the process open. + terminate(): void; + onMessage(listener: (bytes: Uint8Array) => void): void; + // why: a server's ping is the only sign of life on an idle socket, and `ws` answers it without telling the caller. + onPing(listener: () => void): void; + // why: a socket that dropped without a close frame reports 1006, as `ws` does. + onClose(listener: (code: number, reason: string) => void): void; +} + +export interface WebSocketClientConnector { + connect(url: string, options: WebSocketClientOptions): Promise; +} + +function bytesOf(data: RawData): Uint8Array { + if (Array.isArray(data)) return Buffer.concat(data); + return Buffer.isBuffer(data) ? data : new Uint8Array(data); +} + +class NodeWebSocketClient implements WebSocketClient { + readonly #socket: WsSocket; + readonly #messages: ((bytes: Uint8Array) => void)[] = []; + readonly #pings: (() => void)[] = []; + readonly #closes: ((code: number, reason: string) => void)[] = []; + #closed: { readonly code: number; readonly reason: string } | undefined; + + constructor(socket: WsSocket) { + this.#socket = socket; + socket.on("message", (data: RawData) => { + for (const listener of this.#messages) listener(bytesOf(data)); + }); + socket.on("ping", () => { + for (const listener of this.#pings) listener(); + }); + socket.on("close", (code: number, reason: Buffer) => { + this.#closed = { code, reason: reason.toString("utf8") }; + for (const listener of this.#closes) listener(code, this.#closed.reason); + }); + socket.on("error", () => undefined); + } + + send(bytes: Uint8Array): void { + this.#socket.send(bytes); + } + + close(code: number, reason: string): void { + this.#socket.close(code, reason); + } + + terminate(): void { + this.#socket.terminate(); + } + + onMessage(listener: (bytes: Uint8Array) => void): void { + this.#messages.push(listener); + } + + onPing(listener: () => void): void { + this.#pings.push(listener); + } + + onClose(listener: (code: number, reason: string) => void): void { + this.#closes.push(listener); + if (this.#closed !== undefined) listener(this.#closed.code, this.#closed.reason); + } +} + +// why: `ws` is loaded with `import()` on the first `connect`, so the CLI and the MCP server, which import the ports barrel, load it only when a command opens a socket (ADR 0054 section 8). +export class NodeWebSocketClientConnector implements WebSocketClientConnector { + async connect(url: string, options: WebSocketClientOptions): Promise { + const { WebSocket } = await import("ws"); + return new Promise((resolve, reject) => { + const socket = new WebSocket(url, { + autoPong: true, + handshakeTimeout: options.handshakeTimeoutMs, + headers: { ...options.headers }, + }); + socket.once("unexpected-response", (_request, response) => { + const chunks: Buffer[] = []; + response.on("data", (chunk: Buffer) => chunks.push(chunk)); + response.on("end", () => { + reject( + new WebSocketRefusedError( + response.statusCode ?? 0, + Buffer.concat(chunks).toString("utf8"), + ), + ); + }); + response.on("error", () => { + reject(new WebSocketRefusedError(response.statusCode ?? 0, "")); + }); + }); + socket.once("error", reject); + socket.once("open", () => { + socket.off("error", reject); + resolve(new NodeWebSocketClient(socket)); + }); + }); + } +} + +class FakeWebSocketPeer implements WebSocketClient { + readonly sent: Uint8Array[] = []; + closedWith: { readonly code: number; readonly reason: string } | undefined; + terminated = false; + // why: a real socket answers `close` with its own close event; a test sets this to play a server that never answers. + silentOnClose = false; + readonly #messages: ((bytes: Uint8Array) => void)[] = []; + readonly #pings: (() => void)[] = []; + readonly #closes: ((code: number, reason: string) => void)[] = []; + + send(bytes: Uint8Array): void { + this.sent.push(bytes); + } + + close(code: number, reason: string): void { + this.closedWith = { code, reason }; + if (this.silentOnClose) return; + for (const listener of this.#closes) listener(code, reason); + } + + terminate(): void { + this.terminated = true; + } + + onMessage(listener: (bytes: Uint8Array) => void): void { + this.#messages.push(listener); + } + + onPing(listener: () => void): void { + this.#pings.push(listener); + } + + onClose(listener: (code: number, reason: string) => void): void { + this.#closes.push(listener); + } + + receive(bytes: Uint8Array): void { + for (const listener of this.#messages) listener(bytes); + } + + ping(): void { + for (const listener of this.#pings) listener(); + } + + dropped(code: number, reason: string): void { + for (const listener of this.#closes) listener(code, reason); + } +} + +export class FakeWebSocketClientConnector implements WebSocketClientConnector { + readonly connections: { + readonly url: string; + readonly options: WebSocketClientOptions; + readonly peer: FakeWebSocketPeer; + }[] = []; + // why: a test sets this to make the next `connect` fail, as a refused upgrade or an unreachable host does. + failure: Error | undefined; + + async connect(url: string, options: WebSocketClientOptions): Promise { + if (this.failure !== undefined) throw this.failure; + const peer = new FakeWebSocketPeer(); + this.connections.push({ options, peer, url }); + return peer; + } +} diff --git a/website/src/content/docs/docs/reference/cli.mdx b/website/src/content/docs/docs/reference/cli.mdx index 3567463d8..2429eec41 100644 --- a/website/src/content/docs/docs/reference/cli.mdx +++ b/website/src/content/docs/docs/reference/cli.mdx @@ -48,7 +48,7 @@ These flags work anywhere on the command line, before or after the command. | Flag | Meaning | Default | | --- | --- | --- | -| `--token ` | Connect as admin with this token. `--token=` also works. | See [Admin credential](#admin-credential) | +| `--token ` | The credential a command sends: the admin token for the local daemon, or the bearer token `simlock tunnel` sends to a worker or gateway. `--token=` also works. | See [Admin credential](#admin-credential) | | `--gateway` | Send the command to this machine's gateway, the daemon in `~/.simlock/gateway`. Takes no value. | See [Which daemon a command reaches](#which-daemon-a-command-reaches) | | `--local` | Send the command to this machine's worker, the daemon in `~/.simlock`. Takes no value. | See [Which daemon a command reaches](#which-daemon-a-command-reaches) | | `--help`, `-h` | As the first word, or with no command: print the list of commands. | — | @@ -203,6 +203,23 @@ simlock rotate [--lease ] It prints `Rotated lease to `, with the orientation spelled `portrait`, `portrait_upside_down`, `landscape_left` or `landscape_right`. An orientation Simlock does not know, or several leases without `--lease`, is a usage error (exit 2). A lease on an Android emulator, a physical device or an Apple TV fails with `ROTATION_UNSUPPORTED` (exit 12); an input helper that cannot start fails with `INPUT_UNAVAILABLE` (exit 1). +## simlock tunnel + +Reach your leased Android emulator back to ports on your own machine, from another machine, while the command runs. It talks to a lone worker or a gateway over HTTP and WebSocket, so it needs no local daemon. + +```text +simlock tunnel reverse [:] [reverse ...] [--lease ] [--url ] +``` + +| Flag | Meaning | Default | +| --- | --- | --- | +| `reverse [:]` | Make the device's `localhost:` reach `localhost:` on this machine. Both are integers 1 to 65535; the worker accepts device ports from 1024. Repeat the word `reverse` for up to 8 tunnels; a caller port may appear once. | The caller port is the device port | +| `--lease ` | The lease to reach, 1 to 256 characters. | An agent token's only lease; an operator token must name one | +| `--url ` | The worker or gateway: `https://`, or `http://` only for `127.0.0.1`, `[::1]` or `localhost`; the origin only, with no path, query or fragment (a trailing `/` is fine); at most 2048 characters. A `--url` that is not, is a usage error. | `SIMLOCK_URL` | +| `--token ` | The bearer token, 1 to 4096 characters. | `SIMLOCK_TOKEN` | + +It prints one line per tunnel, `reverse device: -> localhost: (lease )`, and runs until you press Ctrl-C or the process gets SIGTERM, which close the tunnels and exit 0. A tunnel whose caller port has nothing listening writes a warning to stderr at most once every 10 seconds and stays open. A missing `--url`, token or lease, an invalid port, or a repeated caller port is a usage error (exit 2). A refusal exits 1 with its code, for example `TUNNEL_BAD_PORT` for a device port below 1024. A lost connection, 45 seconds with no message or ping, or 90 seconds with no answer to the request exits 1 with `TUNNEL_DISCONNECTED`; the lease ending exits 14 with `TUNNEL_LEASE_ENDED`. + ## simlock catalog Show what you can lease: per platform, the installed runtimes and the default, the models grouped by class with the default model of each class, and, on Android, the installed system images. See [Choosing a device](/simlock/docs/using-devices/choosing-a-device). @@ -712,6 +729,8 @@ Flags that take a duration (`--ttl`, `--timeout`, `--since`) accept a whole numb | `SIMLOCK_HOME` | The folder Simlock keeps everything in. The worker uses it directly; a gateway uses its `gateway` subfolder. A path so long that the daemon's socket path would pass the system limit fails with `USAGE` (exit 2). | `~/.simlock` | | `SIMLOCK_ADMIN_TOKEN` | An admin credential: an operator token or the daemon's `admin.token` secret. Used when `--token` is not given. | Unset: the CLI reads `admin.token` | | `SIMLOCK_AGENT_ID` | The requester identity. When set, it wins over the session variables below. | Unset | +| `SIMLOCK_URL` | The worker or gateway `simlock tunnel` calls, when `--url` is not given; the same rules as `--url`. | Unset | +| `SIMLOCK_TOKEN` | The bearer token `simlock tunnel` sends, when `--token` is not given. | Unset | | `CLAUDE_CODE_SESSION_ID` | Set by Claude Code. Gives the identity `claude-code:`. | — | | `CODEX_SESSION_ID` | Set by Codex. Gives the identity `codex:`. | — | | `PI_SESSION_ID` | Set by [pi](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/environment-variables.md#shell-tool-session-environment) for the commands its `bash` and `powershell` tools run. Gives the identity `pi:`. | — |