From d1f74bc24d6634c3220fa494ab202e4ae5c8af23 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 00:50:22 -0300 Subject: [PATCH 001/103] test: a holder's rotate of its iOS-simulator lease answers and sends the helper that orientation (#1107) --- .agents/scripts/protocol-bump-check.mjs | 1 + src/contract/index.ts | 1 + src/contract/operations.ts | 16 +++++ src/contract/orientation.ts | 7 +++ src/daemon/device-rotate.e2e.test.ts | 84 +++++++++++++++++++++++++ src/daemon/dispatcher.ts | 6 ++ src/gateway/dispatcher.ts | 6 ++ 7 files changed, 121 insertions(+) create mode 100644 src/contract/orientation.ts create mode 100644 src/daemon/device-rotate.e2e.test.ts diff --git a/.agents/scripts/protocol-bump-check.mjs b/.agents/scripts/protocol-bump-check.mjs index b45074bc7..da68d4e63 100644 --- a/.agents/scripts/protocol-bump-check.mjs +++ b/.agents/scripts/protocol-bump-check.mjs @@ -14,6 +14,7 @@ const NOT_SHAPES = new Set([ "index.ts", "console-url.ts", "duration.ts", + "orientation.ts", "os-range.ts", "version-order.ts", ]); diff --git a/src/contract/index.ts b/src/contract/index.ts index bc2d913ea..c4ed8d5e1 100644 --- a/src/contract/index.ts +++ b/src/contract/index.ts @@ -2,6 +2,7 @@ export * from "./console-url.js"; export * from "./duration.js"; export * from "./errors.js"; export * from "./operations.js"; +export * from "./orientation.js"; export * from "./os-range.js"; export * from "./protocol.js"; export * from "./pushes.js"; diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 42b9f090b..435b5be4b 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -7,6 +7,7 @@ import { EVENTS_PAGE_WITH_SINCE_MESSAGE, eventsPageWithoutSince, } from "./events-page.js"; +import { INPUT_ORIENTATIONS } from "./orientation.js"; import { parseOsConstraint } from "./os-range.js"; import { relayChannelSchema, relayHeadersSchema, relayIdSchema } from "./relay.js"; import { ownsLease, type AuthorizeContext, type Role } from "./roles.js"; @@ -1074,6 +1075,20 @@ const identityGet = defineOperation({ }), }); +/** + * why: turns a leased iOS phone or tablet simulator, through the lease's device input, whether or not the input module is on. + */ +// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. +export const deviceRotate = defineOperation({ + name: "device.rotate", + role: "agent", + effect: "write", + input: z + .object({ leaseId: z.string().min(1).max(256), orientation: z.enum(INPUT_ORIENTATIONS) }) + .strict(), + output: z.object({ leaseId: z.string().max(256), orientation: z.enum(INPUT_ORIENTATIONS) }), +}); + export const OPERATIONS = { "identity.get": identityGet, "catalog.get": catalogGet, @@ -1086,6 +1101,7 @@ export const OPERATIONS = { "lease.get": leaseGet, "driver.passthrough": driverPassthrough, "device.exec": deviceExec, + "device.rotate": deviceRotate, "doctor.run": doctorRun, "lease.release-all": leaseReleaseAll, "list.get": listGet, diff --git a/src/contract/orientation.ts b/src/contract/orientation.ts new file mode 100644 index 000000000..d4cc3829f --- /dev/null +++ b/src/contract/orientation.ts @@ -0,0 +1,7 @@ +// why: the four names a rotate takes over the contract and the input socket's `0x07` frame. +export const INPUT_ORIENTATIONS = [ + "portrait", + "portrait_upside_down", + "landscape_left", + "landscape_right", +] as const; diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts new file mode 100644 index 000000000..e559241a8 --- /dev/null +++ b/src/daemon/device-rotate.e2e.test.ts @@ -0,0 +1,84 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { FakeDriver, FakeInputFactory, fakeDeviceDataTables } from "../core/testing.js"; +import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; +import type { DispatchSession } from "./dispatch.js"; +import { startDaemon } from "./main.js"; +import type { DaemonServer } from "./server.js"; + +const holder: DispatchSession = { + manageEventSubscription: () => undefined, + via: "socket", + principal: "holder-1", + role: "agent", +}; + +describe("device.rotate", () => { + const daemons: DaemonServer[] = []; + const directories: string[] = []; + + afterEach(async () => { + 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(options: { + readonly inputModule: boolean; + readonly input: FakeInputFactory; + }) { + const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-rotate-")); + directories.push(dataDirectory); + const daemon = await startDaemon({ + configOverrides: { capabilities: { input: { enabled: options.inputModule } } }, + dataDirectory, + deviceDataTables: fakeDeviceDataTables, + drivers: [ + new FakeDriver({ + availableOsVersions: ["18.0"], + clock: new SystemClock(), + input: options.input, + knownModels: ["iPhone 15"], + platform: "ios", + }), + ], + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + version: "1.0.0-e2e", + }); + daemons.push(daemon); + const granted = await daemon.dispatch( + "lease.request", + { model: "iPhone 15", platform: "ios" }, + holder, + ); + return { daemon, leaseId: (granted as { lease: { id: string } }).lease.id }; + } + + it( + "answers a holder's rotate of its iOS-simulator lease and sends the helper that orientation", + { timeout: 60_000 }, + async () => { + const input = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); + const { daemon, leaseId } = await worker({ input, inputModule: false }); + + const answer = await daemon.dispatch( + "device.rotate", + { leaseId, orientation: "landscape_left" }, + holder, + ); + + expect(answer).toEqual({ leaseId, orientation: "landscape_left" }); + expect(input.opened).toHaveLength(1); + expect(input.opened[0]?.sent).toEqual([ + { kind: "orientation", orientation: "landscape_left" }, + ]); + expect(input.opened[0]?.closes).toBe(1); + }, + ); +}); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 46a065717..f0e53343e 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -261,6 +261,7 @@ export class Dispatcher { "lease.get": this.#leaseGet, "driver.passthrough": this.#driverPassthrough, "device.exec": this.#deviceExec, + "device.rotate": this.#deviceRotate, "relay.request": this.#relayRequest, "relay.cancel": this.#relayCancel, "doctor.run": this.#doctorRun, @@ -657,6 +658,11 @@ export class Dispatcher { * so a command that writes a gigabyte costs this process nothing, and a client sees the * first line while the command is still running. */ + #deviceRotate: Handler<"device.rotate"> = async (input) => ({ + leaseId: input.leaseId, + orientation: "portrait", + }); + #deviceExec: Handler<"device.exec"> = async (input, session) => { if (this.options.passthrough === undefined) { throw new DispatchError("INTERNAL", "Tool passthrough is unavailable"); diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index b4f41291f..36d51fbd4 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -280,6 +280,7 @@ export class GatewayDispatcher { "lease.cancel": this.#leaseCancel, "lease.release-all": this.#leaseReleaseAll, "device.exec": this.#deviceExec, + "device.rotate": this.#deviceRotate, "relay.request": relayRefused, "relay.cancel": relayRefused, // why: "daemon.stop" is absent for the same reason it is absent from the worker's table: the @@ -730,6 +731,11 @@ export class GatewayDispatcher { return { leaseIds: [...leaseIds] }; }; + #deviceRotate: Handler<"device.rotate"> = async (input) => ({ + leaseId: input.leaseId, + orientation: "portrait", + }); + #deviceExec: Handler<"device.exec"> = async (input, session) => this.options.coordinator.exec( { From 6a87186633787c6c76deb51507b80dcff054b898 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 00:51:34 -0300 Subject: [PATCH 002/103] test: a holder opens the tunnel socket, sends HELLO with reverse tunnels and gets READY, and a device connection arrives as OPEN with its bytes as DATA (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/core/device-tcp.ts | 20 ++++++++ src/core/driver-catalog.ts | 12 +++++ src/core/driver.ts | 3 ++ src/core/fake-device-tcp.ts | 56 ++++++++++++++++++++++ src/core/fake-driver.ts | 4 ++ src/core/index.ts | 1 + src/core/testing.ts | 1 + src/daemon/main.ts | 4 ++ src/modules/index.ts | 1 + src/modules/testing.ts | 1 + src/modules/types.ts | 12 +++++ src/ports/index.ts | 1 + src/tunnel/definition.ts | 14 ++++++ src/tunnel/index.ts | 1 + src/tunnel/worker.test.ts | 93 +++++++++++++++++++++++++++++++++++++ src/tunnel/worker.ts | 8 ++++ 16 files changed, 232 insertions(+) create mode 100644 src/core/device-tcp.ts create mode 100644 src/core/fake-device-tcp.ts create mode 100644 src/tunnel/definition.ts create mode 100644 src/tunnel/index.ts create mode 100644 src/tunnel/worker.test.ts create mode 100644 src/tunnel/worker.ts diff --git a/src/core/device-tcp.ts b/src/core/device-tcp.ts new file mode 100644 index 000000000..ed8231015 --- /dev/null +++ b/src/core/device-tcp.ts @@ -0,0 +1,20 @@ +import type { TcpStream } from "../ports/index.js"; +import type { PhysicalDriverDevice, VirtualDriverDevice } from "./driver.js"; + +// why: one device port reversed to a loopback listener on the worker; every connection the device +// opens to that port arrives on `onConnection`, until `close` removes the rule and the listener. +export interface DeviceReverse { + readonly hostPort: number; + onConnection(listener: (stream: TcpStream) => void): void; + close(): Promise; +} + +// why: an optional driver member beside `input`; a platform whose device cannot reach a worker port +// leaves it out, and the tunnel module learns that from its absence rather than from a platform name. +export interface DeviceTcp { + reverse( + device: VirtualDriverDevice | PhysicalDriverDevice, + devicePort: number, + signal: AbortSignal, + ): Promise; +} diff --git a/src/core/driver-catalog.ts b/src/core/driver-catalog.ts index ac6187f67..d7b2f6686 100644 --- a/src/core/driver-catalog.ts +++ b/src/core/driver-catalog.ts @@ -10,6 +10,7 @@ import type { PhysicalDriverDevice, VirtualDriverDevice, } from "./driver.js"; +import type { DeviceReverse } from "./device-tcp.js"; import type { DeviceInput, UnavailableDeviceInput } from "./input.js"; import { type ScreenFeed, ScreenNotSupportedError, type ScreenSettings } from "./screen.js"; import { stableError } from "./stable-error.js"; @@ -102,6 +103,17 @@ export class DriverCatalog { return await factory.open(device, signal); } + async reverseDevicePort( + platform: Platform, + device: VirtualDriverDevice | PhysicalDriverDevice, + devicePort: number, + signal: AbortSignal, + ): Promise { + const deviceTcp = this.#drivers.get(platform)?.deviceTcp; + if (deviceTcp === undefined) throw new Error(`${platform} devices take no tunnel`); + return await deviceTcp.reverse(device, devicePort, signal); + } + async screenAvailability(): Promise { return await Promise.all( [...this.#drivers.values()].flatMap((driver) => diff --git a/src/core/driver.ts b/src/core/driver.ts index 0bae95733..4c8c8ba53 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -1,6 +1,7 @@ import type { EventMap } from "../bus/index.js"; import type { Filesystem, SqliteDatabase, SqliteSchemaOwner } from "../ports/index.js"; import type { RootRejectionReason } from "./device-root.js"; +import type { DeviceTcp } from "./device-tcp.js"; import type { DeviceInputFactory } from "./input.js"; import type { ScreenCapture } from "./screen.js"; import type { @@ -306,6 +307,8 @@ export interface Driver { // why: optional like `screenCapture`: a platform whose device takes no input leaves it out, and a // lease's input socket then says the device is unavailable. readonly input?: DeviceInputFactory | undefined; + // why: optional like `input`: a platform whose device cannot reach a port on the worker leaves it out, and a tunnel is then refused as unsupported. + readonly deviceTcp?: DeviceTcp | undefined; /** why: `device.exec` has no pseudo-terminal (ADR 0005 §19c), so a driver may refuse there what it allows locally. */ passthrough?( tool: string, diff --git a/src/core/fake-device-tcp.ts b/src/core/fake-device-tcp.ts new file mode 100644 index 000000000..7586b4ff2 --- /dev/null +++ b/src/core/fake-device-tcp.ts @@ -0,0 +1,56 @@ +import { FakeTcpPeer, type TcpStream } from "../ports/index.js"; +import type { DeviceReverse, DeviceTcp } from "./device-tcp.js"; + +class FakeReverse implements DeviceReverse { + closed = false; + readonly #listeners: ((stream: TcpStream) => void)[] = []; + + constructor( + readonly hostPort: number, + private readonly onClose: () => void, + ) {} + + onConnection(listener: (stream: TcpStream) => void): void { + this.#listeners.push(listener); + } + + async close(): Promise { + this.closed = true; + this.onClose(); + } + + accept(stream: TcpStream): void { + for (const listener of this.#listeners) listener(stream); + } +} + +// why: a driver's `deviceTcp` member for tests: `reversed` holds the device ports whose rule is set, +// and `connect` plays the device opening a connection to one of them. +export class FakeDeviceTcp implements DeviceTcp { + readonly #reverses = new Map(); + #nextHostPort = 47_000; + + get reversed(): readonly number[] { + return [...this.#reverses.keys()]; + } + + async reverse( + _device: unknown, + devicePort: number, + _signal?: AbortSignal, + ): Promise { + const hostPort = this.#nextHostPort; + this.#nextHostPort += 1; + const reverse = new FakeReverse(hostPort, () => { + this.#reverses.delete(devicePort); + }); + this.#reverses.set(devicePort, reverse); + return reverse; + } + + connect(devicePort: number): FakeTcpPeer { + const peer = new FakeTcpPeer(); + this.#reverses.get(devicePort)?.accept(peer.stream); + return peer; + } +} diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index a292d5cc8..39692d669 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -39,6 +39,7 @@ import { UnknownModelError, uninstallPlan, } from "./driver.js"; +import type { DeviceTcp } from "./device-tcp.js"; import type { DeviceInputFactory } from "./input.js"; import type { ScreenCapture } from "./screen.js"; @@ -103,6 +104,7 @@ export interface FakeDriverOptions { readonly passthroughTools?: readonly string[]; readonly screenCapture?: ScreenCapture; readonly input?: DeviceInputFactory; + readonly deviceTcp?: DeviceTcp; readonly passthrough?: ( tool: string, device: VirtualDriverDevice | PhysicalDriverDevice | undefined, @@ -167,6 +169,7 @@ export class FakeDriver implements Driver { readonly passthroughTools: readonly string[] | undefined; readonly screenCapture: ScreenCapture | undefined; readonly input: DeviceInputFactory | undefined; + readonly deviceTcp: DeviceTcp | undefined; readonly #passthrough: FakeDriverOptions["passthrough"]; #nextDeviceNumber = 1; readonly #pendingMakeReady: (() => void)[] = []; @@ -207,6 +210,7 @@ export class FakeDriver implements Driver { this.passthroughTools = options.passthroughTools; this.screenCapture = options.screenCapture; this.input = options.input; + this.deviceTcp = options.deviceTcp; this.#passthrough = options.passthrough; this.platform = options.platform; this.deviceRoot = options.deviceRoot ?? `/fake/${options.platform}`; diff --git a/src/core/index.ts b/src/core/index.ts index 348306a56..08256718f 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -102,6 +102,7 @@ export { type ScreenAvailability, UnknownPassthroughToolError, } from "./driver-catalog.js"; +export type { DeviceReverse, DeviceTcp } from "./device-tcp.js"; export { closeReason, type DeviceInput, diff --git a/src/core/testing.ts b/src/core/testing.ts index 6f9e7ddf4..01d518566 100644 --- a/src/core/testing.ts +++ b/src/core/testing.ts @@ -32,6 +32,7 @@ export { type ResourceStrategyOptions, } from "./capacity/index.js"; export { readyTransitionUpdate } from "./driver.js"; +export { FakeDeviceTcp } from "./fake-device-tcp.js"; export { FakeInputFactory } from "./fake-device-input.js"; export { FakeDriver, fakeDeviceDataTable } from "./fake-driver.js"; export type { FakeDriverOptions } from "./fake-driver.js"; diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 1e4853885..05ef324fe 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -516,6 +516,10 @@ async function composeDaemon( processRunner, processSupervisor, registry, + deviceTcp: { + reverse: (platform, device, devicePort, signal) => + catalog.reverseDevicePort(platform, device, devicePort, signal), + }, inputs: { openInput: (platform, device, signal) => catalog.openInput(platform, device, signal), }, diff --git a/src/modules/index.ts b/src/modules/index.ts index bb4063d71..9b22c6416 100644 --- a/src/modules/index.ts +++ b/src/modules/index.ts @@ -8,6 +8,7 @@ export type { GatewayContext, GatewayModule, ModuleCapabilitySource, + ModuleDeviceTcp, ModuleDispatch, ModuleEndedLease, ModuleFinding, diff --git a/src/modules/testing.ts b/src/modules/testing.ts index 17766ced7..1a86ef6b0 100644 --- a/src/modules/testing.ts +++ b/src/modules/testing.ts @@ -191,6 +191,7 @@ export async function fakeWorkerContext(name: string, config: C): Promise Promise.reject(new Error("no device port in a fake context")) }, inputs: { openInput: () => Promise.resolve({ unavailable: "no input in a fake context" }) }, screens: { openScreen: () => Promise.reject(new Error("no screen in a fake context")), diff --git a/src/modules/types.ts b/src/modules/types.ts index 1a34d940c..4a5e39e39 100644 --- a/src/modules/types.ts +++ b/src/modules/types.ts @@ -12,6 +12,7 @@ import type { Config, DeviceInput, DeviceRecord, + DeviceReverse, UnavailableDeviceInput, LeaseRecord, PhysicalDriverDevice, @@ -196,6 +197,16 @@ export interface ModuleInputs { ): Promise; } +// why: the drivers' device ports, routed by platform, without handing a module the drivers. +export interface ModuleDeviceTcp { + reverse( + platform: Platform, + device: VirtualDriverDevice | PhysicalDriverDevice, + devicePort: number, + signal: AbortSignal, + ): Promise; +} + export interface WorkerContext { readonly name: string; readonly instanceId: string; @@ -219,6 +230,7 @@ export interface WorkerContext { readonly registry: ModuleRegistryView; readonly screens: ModuleScreens; readonly inputs: ModuleInputs; + readonly deviceTcp: ModuleDeviceTcp; cancelPending(requesterId: string): Promise; readonly events: { subscribe(event: Event, handler: EventHandler): () => void; diff --git a/src/ports/index.ts b/src/ports/index.ts index a89e7ba68..4d15f8133 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -106,6 +106,7 @@ export type { ProcessSupervisor } from "./process-supervisor.js"; export type { SignalRecord } from "./process-supervisor.js"; export { FakeTcpProbe, NodeTcpProbe } from "./tcp-probe.js"; export { + FakeTcpPeer, FakeTcpStreamConnector, NodeTcpStreamConnector, type TcpStream, diff --git a/src/tunnel/definition.ts b/src/tunnel/definition.ts new file mode 100644 index 000000000..1ef5fa261 --- /dev/null +++ b/src/tunnel/definition.ts @@ -0,0 +1,14 @@ +import { objectValidator } from "../core/index.js"; +import type { OptionalModuleDefinition } from "../modules/index.js"; + +export type TunnelModuleConfig = Record; + +export const tunnelModule: OptionalModuleDefinition = { + config: { + defaults: {}, + gatewayKeys: [], + validator: objectValidator({}), + }, + loadWorker: () => import("./worker.js"), + name: "tunnel", +}; diff --git a/src/tunnel/index.ts b/src/tunnel/index.ts new file mode 100644 index 000000000..ecac20e2c --- /dev/null +++ b/src/tunnel/index.ts @@ -0,0 +1 @@ +export { tunnelModule } from "./definition.js"; diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts new file mode 100644 index 000000000..810f96b15 --- /dev/null +++ b/src/tunnel/worker.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it, vi } from "vitest"; + +import type { DeviceRecord, LeaseRecord } from "../core/index.js"; +import { FakeDeviceTcp } from "../core/testing.js"; +import type { WorkerModule } from "../modules/index.js"; +import { fakeWorkerContext } from "../modules/testing.js"; +import { MemoryLeaseSocket } from "../ports/index.js"; +import { tunnelModule } from "./index.js"; + +const IDENTITY = { principal: "tok_holder", role: "agent" } as const; + +function frame(tag: number, conn: number, body = ""): Uint8Array { + const bytes = new TextEncoder().encode(body); + const out = new Uint8Array(5 + bytes.length); + out[0] = tag; + new DataView(out.buffer).setUint32(1, conn); + out.set(bytes, 5); + return out; +} + +function frames(socket: MemoryLeaseSocket): { tag: number; conn: number; body: string }[] { + return socket.sent.map((sent) => ({ + body: new TextDecoder().decode(sent.subarray(5)), + conn: new DataView(sent.buffer, sent.byteOffset).getUint32(1), + tag: sent[0] ?? -1, + })); +} + +function hello(...tunnels: { kind: string; devicePort: number }[]): Uint8Array { + return frame(0x01, 0, JSON.stringify({ tunnels })); +} + +async function setup(): Promise<{ + readonly worker: WorkerModule; + readonly deviceTcp: FakeDeviceTcp; +}> { + const { ctx } = await fakeWorkerContext("tunnel", {}); + const deviceTcp = new FakeDeviceTcp(); + const registry = { + snapshot: { + devices: [{ id: "dev_1", spec: { platform: "android" } } as unknown as DeviceRecord], + leases: [{ deviceId: "dev_1", id: "L-1" } as unknown as LeaseRecord], + }, + }; + const loaded = await tunnelModule.loadWorker(); + const worker = loaded.createWorker({ + ...ctx, + deviceTcp: { + reverse: (_platform, device, port, signal) => deviceTcp.reverse(device, port, signal), + }, + registry, + }); + return { deviceTcp, worker }; +} + +async function attach(worker: WorkerModule): Promise { + const opened = await worker.socket?.open(new Request("http://simlock/tunnel"), IDENTITY, { + deviceId: "dev_1", + id: "L-1", + }); + expect(opened).toBeTypeOf("function"); + const socket = new MemoryLeaseSocket(); + if (typeof opened === "function") opened(socket); + return socket; +} + +describe("a worker's tunnel socket", () => { + it("answers HELLO with READY, announces a device connection as OPEN and carries what the device writes as DATA", async () => { + const { deviceTcp, worker } = await setup(); + const socket = await attach(worker); + + socket.receive(hello({ devicePort: 5173, kind: "reverse" })); + await vi.waitFor(() => + expect(frames(socket)).toEqual([ + { body: '{"tunnels":[{"kind":"reverse","devicePort":5173}]}', conn: 0, tag: 0x81 }, + ]), + ); + expect(deviceTcp.reversed).toEqual([5173]); + + const device = deviceTcp.connect(5173); + await vi.waitFor(() => + expect(frames(socket).at(-1)).toEqual({ + body: '{"kind":"reverse","devicePort":5173}', + conn: 1, + tag: 0x02, + }), + ); + device.send("from the device"); + await vi.waitFor(() => + expect(frames(socket).at(-1)).toEqual({ body: "from the device", conn: 1, tag: 0x03 }), + ); + }); +}); diff --git a/src/tunnel/worker.ts b/src/tunnel/worker.ts new file mode 100644 index 000000000..ea9d41e4e --- /dev/null +++ b/src/tunnel/worker.ts @@ -0,0 +1,8 @@ +import type { WorkerContext, WorkerModule } from "../modules/index.js"; +import type { TunnelModuleConfig } from "./definition.js"; + +export function createWorker(ctx: WorkerContext): WorkerModule { + return { + capability: { name: ctx.name, read: () => Promise.resolve({ state: "available" }) }, + }; +} From 98cfb132fb89ddfa572f322ee9356c43a41281c1 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 00:52:16 -0300 Subject: [PATCH 003/103] feat(tunnel): a reverse tunnel answers READY and carries device connections as OPEN and DATA (#1112) Co-Authored-By: Claude Sonnet 5.5 --- .agents/scripts/protocol-bump-check.mjs | 1 + src/contract/index.ts | 1 + src/contract/tunnel-frames.ts | 39 +++++++++++++++++ src/tunnel/sessions.ts | 57 +++++++++++++++++++++++++ src/tunnel/worker.ts | 15 +++++++ 5 files changed, 113 insertions(+) create mode 100644 src/contract/tunnel-frames.ts create mode 100644 src/tunnel/sessions.ts diff --git a/.agents/scripts/protocol-bump-check.mjs b/.agents/scripts/protocol-bump-check.mjs index b45074bc7..cb02f0d90 100644 --- a/.agents/scripts/protocol-bump-check.mjs +++ b/.agents/scripts/protocol-bump-check.mjs @@ -15,6 +15,7 @@ const NOT_SHAPES = new Set([ "console-url.ts", "duration.ts", "os-range.ts", + "tunnel-frames.ts", "version-order.ts", ]); const RANGE = /PROTOCOL_VERSION_RANGE[^=]*=\s*\{\s*min:\s*(\d+),\s*max:\s*(\d+)/; diff --git a/src/contract/index.ts b/src/contract/index.ts index bc2d913ea..65122e721 100644 --- a/src/contract/index.ts +++ b/src/contract/index.ts @@ -8,6 +8,7 @@ export * from "./pushes.js"; export * from "./relay.js"; export * from "./roles.js"; export * from "./schemas.js"; +export * from "./tunnel-frames.js"; export * from "./events-page.js"; export * from "./inbox.js"; export * from "./usage-window.js"; diff --git a/src/contract/tunnel-frames.ts b/src/contract/tunnel-frames.ts new file mode 100644 index 000000000..dc4ee43ed --- /dev/null +++ b/src/contract/tunnel-frames.ts @@ -0,0 +1,39 @@ +// why: the frames of a lease's tunnel socket (ADR 0054 section 3). They are not daemon-contract +// operations, but the worker's module and the CLI's `simlock tunnel` must agree on every byte, so the +// codec sits here, imported by both: one binary message is `[tag u8][conn u32 big-endian][payload]`. +export const TUNNEL_TAG = { + data: 0x03, + hello: 0x01, + open: 0x02, + ready: 0x81, +} as const; + +export interface TunnelFrame { + readonly tag: number; + readonly conn: number; + readonly payload: Uint8Array; +} + +const HEADER_BYTES = 5; + +export function encodeTunnelFrame( + tag: number, + conn: number, + payload: Uint8Array | string = new Uint8Array(), +): Uint8Array { + const body = typeof payload === "string" ? new TextEncoder().encode(payload) : payload; + const frame = new Uint8Array(HEADER_BYTES + body.length); + frame[0] = tag; + new DataView(frame.buffer).setUint32(1, conn); + frame.set(body, HEADER_BYTES); + return frame; +} + +export function decodeTunnelFrame(bytes: Uint8Array): TunnelFrame | undefined { + if (bytes.length < HEADER_BYTES) return undefined; + return { + conn: new DataView(bytes.buffer, bytes.byteOffset, bytes.length).getUint32(1), + payload: bytes.subarray(HEADER_BYTES), + tag: bytes[0] ?? 0, + }; +} diff --git a/src/tunnel/sessions.ts b/src/tunnel/sessions.ts new file mode 100644 index 000000000..2ba37647c --- /dev/null +++ b/src/tunnel/sessions.ts @@ -0,0 +1,57 @@ +import { decodeTunnelFrame, encodeTunnelFrame, TUNNEL_TAG } from "../contract/index.js"; +import { toDriverDevice, type DeviceRecord } from "../core/index.js"; +import type { ModuleDeviceTcp } from "../modules/index.js"; +import type { LeaseSocket, TcpStream } from "../ports/index.js"; + +interface Tunnel { + readonly kind: "reverse"; + readonly devicePort: number; +} + +export interface TunnelSessions { + attach(device: DeviceRecord, socket: LeaseSocket): void; +} + +export function createTunnelSessions(options: { + readonly deviceTcp: ModuleDeviceTcp; +}): TunnelSessions { + function attach(device: DeviceRecord, socket: LeaseSocket): void { + let nextConnection = 1; + + async function pump(conn: number, stream: TcpStream): Promise { + const reader = stream.readable.getReader(); + for (;;) { + const step = await reader.read(); + if (step.done) return; + socket.send(encodeTunnelFrame(TUNNEL_TAG.data, conn, step.value)); + } + } + + async function hello(payload: Uint8Array): Promise { + const named = JSON.parse(new TextDecoder().decode(payload)) as { tunnels: Tunnel[] }; + const tunnels = named.tunnels.map(({ devicePort, kind }) => ({ kind, devicePort })); + for (const tunnel of tunnels) { + const reverse = await options.deviceTcp.reverse( + device.spec.platform, + toDriverDevice(device), + tunnel.devicePort, + new AbortController().signal, + ); + reverse.onConnection((stream) => { + const conn = nextConnection; + nextConnection += 2; + socket.send(encodeTunnelFrame(TUNNEL_TAG.open, conn, JSON.stringify(tunnel))); + void pump(conn, stream); + }); + } + socket.send(encodeTunnelFrame(TUNNEL_TAG.ready, 0, JSON.stringify({ tunnels }))); + } + + socket.onMessage((data) => { + const frame = decodeTunnelFrame(data); + if (frame?.tag === TUNNEL_TAG.hello) void hello(frame.payload); + }); + } + + return { attach }; +} diff --git a/src/tunnel/worker.ts b/src/tunnel/worker.ts index ea9d41e4e..2c5caec93 100644 --- a/src/tunnel/worker.ts +++ b/src/tunnel/worker.ts @@ -1,8 +1,23 @@ +import type { LeaseRecord } from "../core/index.js"; import type { WorkerContext, WorkerModule } from "../modules/index.js"; import type { TunnelModuleConfig } from "./definition.js"; +import { createTunnelSessions } from "./sessions.js"; export function createWorker(ctx: WorkerContext): WorkerModule { + const sessions = createTunnelSessions({ deviceTcp: ctx.deviceTcp }); return { capability: { name: ctx.name, read: () => Promise.resolve({ state: "available" }) }, + socket: { + open: (_request, _identity, held) => { + const lease: LeaseRecord | undefined = ctx.registry.snapshot.leases.find( + (entry) => entry.id === held.id, + ); + const device = ctx.registry.snapshot.devices.find((entry) => entry.id === lease?.deviceId); + if (device === undefined) return Promise.resolve(new Response(null, { status: 404 })); + return Promise.resolve((socket) => { + sessions.attach(device, socket); + }); + }, + }, }; } From a42ade373d49c6767571da627a0d07113c157b39 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 00:54:12 -0300 Subject: [PATCH 004/103] feat(daemon): device.rotate turns a leased simulator through its device input (#1107) --- src/contract/AGENTS.md | 2 +- src/contract/operations.test.ts | 10 +++++++ src/contract/protocol.ts | 2 +- src/core/fake-device-input.ts | 3 +- src/core/input.ts | 2 +- src/daemon-protocol/index.test.ts | 2 +- src/daemon/AGENTS.md | 2 +- src/daemon/dispatcher.ts | 33 +++++++++++++++++++--- src/daemon/main.ts | 3 ++ src/daemon/server.ts | 2 ++ src/drivers/android/input/device-input.ts | 31 +++++++++++--------- src/drivers/ios/input/device-input.test.ts | 5 ++-- src/drivers/ios/input/device-input.ts | 16 +++++------ src/input/sessions.ts | 2 +- 14 files changed, 80 insertions(+), 35 deletions(-) diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index dd79e43dc..1e70704e4 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -57,7 +57,7 @@ Three identities: ## Protocol version -- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 66, max: 66 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`. +- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 67, max: 67 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`. - Every change to a contract shape bumps it by one in the same PR. Move `min` too, unless a compatibility path stays side by side. `.agents/scripts/protocol-bump-check.mjs` checks it on push and in CI; it counts every file here as a shape but tests, `index.ts` and the diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 533a1d4a1..bf402ba72 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -49,6 +49,11 @@ const ROLE_MATRIX: ReadonlyArray<{ input: { args: ["devices"], leaseId: "lease_1", tool: "adb" }, role: "agent", }, + { + name: "device.rotate", + input: { leaseId: "lease_1", orientation: "landscape_left" }, + role: "agent", + }, { name: "identity.get", input: {}, role: "agent" }, { name: "token.list", input: {}, role: "admin" }, { name: "token.revoke", input: { id: "tok_1" }, role: "admin" }, @@ -138,6 +143,11 @@ const EFFECT_MATRIX: ReadonlyArray<{ input: { args: ["devices"], leaseId: "lease_1", tool: "adb" }, effect: "write", }, + { + name: "device.rotate", + input: { leaseId: "lease_1", orientation: "landscape_left" }, + effect: "write", + }, { name: "identity.get", input: {}, effect: "read" }, { name: "token.list", input: {}, effect: "read" }, { name: "token.revoke", input: { id: "tok_1" }, effect: "write" }, diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 5d4d09788..b6d73d4d2 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 66, max: 66 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 67, max: 67 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/core/fake-device-input.ts b/src/core/fake-device-input.ts index 24849529a..b018df012 100644 --- a/src/core/fake-device-input.ts +++ b/src/core/fake-device-input.ts @@ -18,8 +18,9 @@ class FakeDeviceInput implements DeviceInput { this.#config = config; } - send(message: InputMessage): void { + send(message: InputMessage): Promise { this.sent.push(message); + return Promise.resolve(); } onConfig(listener: (config: InputScreenConfig) => void): () => void { diff --git a/src/core/input.ts b/src/core/input.ts index 7fe304b84..ea69da8cb 100644 --- a/src/core/input.ts +++ b/src/core/input.ts @@ -85,7 +85,7 @@ export type InputMessage = // why: what turns messages into taps on one device; one per lease, shared by every socket of it. export interface DeviceInput { - send(message: InputMessage): void; + send(message: InputMessage): Promise; // why: calls the listener with the current screen config at once, then on each change, so a socket // that joins late learns the size as it is now. onConfig(listener: (config: InputScreenConfig) => void): () => void; diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 34803f777..64b593c20 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,7 +9,7 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - expect(DAEMON_PROTOCOL_VERSION).toBe(66); + expect(DAEMON_PROTOCOL_VERSION).toBe(67); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 9292ae23e..20170b255 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -59,7 +59,7 @@ Its stdout lines move the state; a failed line, a non-zero exit or a failed laun 2. **Hello** — first frame must be `hello`, else `HANDSHAKE_REQUIRED` and close. Role: the uplink connection is `admin` by acceptance; otherwise the resolver. Principal: `hello.principal`, else `SIMLOCK_AGENT_ID`, else the daemon's pid. Both are fixed for the connection's life. 3. **Version** — ranges overlap → highest common version. `PROTOCOL_VERSION_RANGE` - is `{ min: 66, max: 66 }` (`src/contract/protocol.ts`). No overlap → the + is `{ min: 67, max: 67 }` (`src/contract/protocol.ts`). No overlap → the connection stays open, and every request but `daemon.stop` gets `PROTOCOL_VERSION_UNSUPPORTED`. 4. **Request** — one frame → one `dispatch()` call. While stopping: `DAEMON_STOPPING`. diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index f0e53343e..758e2e6ea 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -34,9 +34,11 @@ import { type WarmPoolReader, type CatalogReader, type PassthroughResolver, + isUnavailableInput, createUsageReader, type UsageReader, } from "../core/index.js"; +import type { ModuleInputs } from "../modules/index.js"; import { type DeviceModeReader, LeaseIdTakenError, @@ -143,6 +145,8 @@ export interface DispatcherOptions { readonly warmKinds?: WarmKindForgetter; readonly enrollment?: Pick; readonly passthrough?: PassthroughResolver; + /** why: the lease's device input, which `device.rotate` writes to; optional so tests that never rotate need none. */ + readonly inputs?: ModuleInputs; readonly processRunner?: ProcessRunner; /** * why: The environment a `device.exec` child starts from, before the driver's own scoping keys are @@ -658,10 +662,31 @@ export class Dispatcher { * so a command that writes a gigabyte costs this process nothing, and a client sees the * first line while the command is still running. */ - #deviceRotate: Handler<"device.rotate"> = async (input) => ({ - leaseId: input.leaseId, - orientation: "portrait", - }); + #deviceRotate: Handler<"device.rotate"> = async (input) => { + if (this.options.inputs === undefined) { + throw new DispatchError("INTERNAL", "Device input is unavailable"); + } + const lease = this.options.registry.snapshot.leases.find( + (candidate) => candidate.id === input.leaseId, + ); + if (lease === undefined) throw new UnknownLeaseError(input.leaseId); + const record = this.options.registry.snapshot.devices.find( + (candidate) => candidate.id === lease.deviceId, + ); + if (record === undefined) throw new UnknownLeaseError(input.leaseId); + const opened = await this.options.inputs.openInput( + record.spec.platform, + toDriverDevice(record), + new AbortController().signal, + ); + if (isUnavailableInput(opened)) throw new Error(opened.unavailable); + try { + await opened.send({ kind: "orientation", orientation: input.orientation }); + } finally { + await opened.close(); + } + return { leaseId: input.leaseId, orientation: input.orientation }; + }; #deviceExec: Handler<"device.exec"> = async (input, session) => { if (this.options.passthrough === undefined) { diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 1e4853885..dded5b301 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -665,6 +665,9 @@ async function composeDaemon( logger: logger.child("server"), ...(options.protocolVersion === undefined ? {} : { protocolVersion: options.protocolVersion }), passthrough: core.catalog, + inputs: { + openInput: (platform, device, signal) => catalog.openInput(platform, device, signal), + }, processRunner, execEnv: execBaseEnvironment(process.env), queue: leasing, diff --git a/src/daemon/server.ts b/src/daemon/server.ts index f5e056aaa..0aa1bce23 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -163,6 +163,7 @@ export interface DaemonServerEngineOptions { readonly nuke?: Nuke; readonly warmKinds?: WarmKindForgetter; readonly passthrough?: PassthroughResolver; + readonly inputs?: DispatcherOptions["inputs"]; readonly processRunner?: ProcessRunner; readonly relayTargets?: RelayTargets; readonly relayTwoWayTargets?: TwoWayRelayTargets; @@ -315,6 +316,7 @@ function buildDispatcher( ...(options.nuke === undefined ? {} : { nuke: options.nuke }), ...(options.warmKinds === undefined ? {} : { warmKinds: options.warmKinds }), ...(options.passthrough === undefined ? {} : { passthrough: options.passthrough }), + ...(options.inputs === undefined ? {} : { inputs: options.inputs }), ...(options.processRunner === undefined ? {} : { processRunner: options.processRunner }), ...(options.execEnv === undefined ? {} : { execEnv: options.execEnv }), queue: options.queue, diff --git a/src/drivers/android/input/device-input.ts b/src/drivers/android/input/device-input.ts index 1436e2aaa..e736ef8ed 100644 --- a/src/drivers/android/input/device-input.ts +++ b/src/drivers/android/input/device-input.ts @@ -187,34 +187,37 @@ class AndroidDeviceInput implements DeviceInput { // why: a rotation is dropped: scrcpy's only one (ROTATE_DEVICE) toggles between rotations 0 and 1 // through the window manager's rotation lock, so it can name neither upside down nor a landscape side. - send(message: InputMessage): void { + send(message: InputMessage): Promise { const size = this.#config; - if (size === undefined) return; - if (message.kind === "touch") this.#write(touchPacket(message, size)); - else if (message.kind === "scroll") this.#write(scrollPacket(message, size)); - else if (message.kind === "button") this.#press(BUTTON_KEYCODES[message.button]); - else if (message.kind === "key") this.#key(message.type, message.usage); + if (size === undefined) return Promise.resolve(); + if (message.kind === "touch") return this.#write(touchPacket(message, size)); + if (message.kind === "scroll") return this.#write(scrollPacket(message, size)); + if (message.kind === "button") return this.#press(BUTTON_KEYCODES[message.button]); + if (message.kind === "key") return this.#key(message.type, message.usage); + return Promise.resolve(); } - #press(keycode: number): void { - this.#write(keycodePacket("down", keycode, this.#meta)); - this.#write(keycodePacket("up", keycode, this.#meta)); + async #press(keycode: number): Promise { + await Promise.all([ + this.#write(keycodePacket("down", keycode, this.#meta)), + this.#write(keycodePacket("up", keycode, this.#meta)), + ]); } // why: a modifier is held in the meta state of every later key until its `up`; it joins the state // before its own down and leaves it before its own up, as Android's events carry it. - #key(type: "down" | "up", usage: number): void { + #key(type: "down" | "up", usage: number): Promise { const keycode = keycodeOf(usage); - if (keycode === undefined) return; + if (keycode === undefined) return Promise.resolve(); const modifier = modifierOf(usage); if (modifier !== undefined) { this.#meta = type === "down" ? this.#meta | modifier.meta : this.#meta & ~modifier.meta; } - this.#write(keycodePacket(type, keycode, this.#meta)); + return this.#write(keycodePacket(type, keycode, this.#meta)); } - #write(packet: Uint8Array): void { - void this.#stream?.write(packet).catch(() => undefined); + #write(packet: Uint8Array): Promise { + return (this.#stream?.write(packet) ?? Promise.resolve()).catch(() => undefined); } onConfig(listener: (config: InputScreenConfig) => void): () => void { diff --git a/src/drivers/ios/input/device-input.test.ts b/src/drivers/ios/input/device-input.test.ts index 4f3b94a88..c6f7e3d82 100644 --- a/src/drivers/ios/input/device-input.test.ts +++ b/src/drivers/ios/input/device-input.test.ts @@ -222,8 +222,9 @@ describe("iOS device input", () => { const failures: string[] = []; input.onFailed((error) => failures.push(error.message)); broken.launcher.last.writeError = new Error("write EPIPE"); - input.send({ kind: "touch", type: "begin", x: 0.5, y: 0.5 }); - await new Promise((resolve) => setImmediate(resolve)); + await expect(input.send({ kind: "touch", type: "begin", x: 0.5, y: 0.5 })).rejects.toThrow( + "The input helper stopped taking input: write EPIPE", + ); expect(failures).toEqual(["The input helper stopped taking input: write EPIPE"]); expect(broken.launcher.last.stdinClosed).toBe(true); }); diff --git a/src/drivers/ios/input/device-input.ts b/src/drivers/ios/input/device-input.ts index 1ca0ced3a..ea34aad6e 100644 --- a/src/drivers/ios/input/device-input.ts +++ b/src/drivers/ios/input/device-input.ts @@ -172,18 +172,18 @@ class IosDeviceInput implements DeviceInput { this.#config = config; } - send(message: InputMessage): void { + send(message: InputMessage): Promise { if (message.kind === "button") { if (message.button === "home") this.#home(); - return; + return Promise.resolve(); } - if (message.kind === "key" && !this.#keys) return; - this.#child.writeStdin(frameOfMessage(message)).catch((error: unknown) => { - this.#fail( - new Error( - `The input helper stopped taking input: ${error instanceof Error ? error.message : String(error)}`, - ), + if (message.kind === "key" && !this.#keys) return Promise.resolve(); + return this.#child.writeStdin(frameOfMessage(message)).catch((error: unknown) => { + const failure = new Error( + `The input helper stopped taking input: ${error instanceof Error ? error.message : String(error)}`, ); + this.#fail(failure); + throw failure; }); } diff --git a/src/input/sessions.ts b/src/input/sessions.ts index 4e4e933cc..bf03daa30 100644 --- a/src/input/sessions.ts +++ b/src/input/sessions.ts @@ -189,7 +189,7 @@ export function createInputSessions(options: { ); return; } - opened.send(message); + opened.send(message).catch(() => undefined); }); } From 21516b5767f4e33d8bea64e60193b6cadb9e6511 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 00:54:36 -0300 Subject: [PATCH 005/103] test: a holder's HELLO that cannot be met is refused whole with REFUSED and close 4003 (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/tunnel/worker.test.ts | 64 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index 810f96b15..fcb97e081 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -90,4 +90,68 @@ describe("a worker's tunnel socket", () => { expect(frames(socket).at(-1)).toEqual({ body: "from the device", conn: 1, tag: 0x03 }), ); }); + + it("refuses a HELLO that cannot be met whole with REFUSED and close 4003, and leaves nothing it named set up", async () => { + const reverse = (devicePort: number) => ({ devicePort, kind: "reverse" }); + const cases = [ + { + code: "TUNNEL_BAD_PORT", + message: "reverse 80: device ports are 1024 to 65535", + tunnels: [reverse(5173), reverse(80)], + }, + { + code: "TUNNEL_BAD_PORT", + message: "reverse 70000: device ports are 1024 to 65535", + tunnels: [reverse(70_000)], + }, + { + code: "TUNNEL_LIMIT", + message: "the lease already has 9 tunnels; at most 8", + tunnels: Array.from({ length: 9 }, (_, index) => reverse(5000 + index)), + }, + { + code: "TUNNEL_UNSUPPORTED", + message: "forward tunnels are not available yet", + tunnels: [reverse(5173), { devicePort: 9229, kind: "forward" }], + }, + ]; + for (const refused of cases) { + const { deviceTcp, worker } = await setup(); + const socket = await attach(worker); + socket.receive(hello(...refused.tunnels)); + await vi.waitFor(() => + expect(socket.closed).toEqual({ code: 4003, reason: refused.message }), + ); + expect(frames(socket)).toEqual([ + { + body: JSON.stringify({ code: refused.code, message: refused.message }), + conn: 0, + tag: 0x82, + }, + ]); + expect(deviceTcp.reversed).toEqual([]); + } + + const { deviceTcp, worker } = await setup(); + const first = await attach(worker); + first.receive(hello(...[5001, 5002, 5003, 5004].map(reverse))); + await vi.waitFor(() => expect(frames(first).map((sent) => sent.tag)).toEqual([0x81])); + const second = await attach(worker); + second.receive(hello(...[5005, 5006, 5007, 5008, 5009].map(reverse))); + await vi.waitFor(() => + expect(frames(second)).toEqual([ + { + body: JSON.stringify({ + code: "TUNNEL_LIMIT", + message: "the lease already has 9 tunnels; at most 8", + }), + conn: 0, + tag: 0x82, + }, + ]), + ); + expect(second.closed?.code).toBe(4003); + expect(first.closed).toBeUndefined(); + expect(deviceTcp.reversed).toEqual([5001, 5002, 5003, 5004]); + }); }); From e308d56c1d51bf9be0c09c0288fe179196e68ee3 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 00:56:36 -0300 Subject: [PATCH 006/103] feat(tunnel): a HELLO that cannot be met is refused whole with its code and close 4003 (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/AGENTS.md | 2 +- src/contract/errors.ts | 49 ++++++++++++++++ src/contract/protocol.ts | 2 +- src/contract/tunnel-frames.ts | 6 ++ src/daemon-protocol/index.test.ts | 2 +- src/daemon/AGENTS.md | 2 +- src/tunnel/sessions.ts | 57 +++++++++++++++++-- src/tunnel/worker.ts | 2 +- .../content/docs/docs/reference/errors.mdx | 20 ++++++- 9 files changed, 131 insertions(+), 11 deletions(-) diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index dd79e43dc..1e70704e4 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -57,7 +57,7 @@ Three identities: ## Protocol version -- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 66, max: 66 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`. +- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 67, max: 67 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`. - Every change to a contract shape bumps it by one in the same PR. Move `min` too, unless a compatibility path stays side by side. `.agents/scripts/protocol-bump-check.mjs` checks it on push and in CI; it counts every file here as a shape but tests, `index.ts` and the diff --git a/src/contract/errors.ts b/src/contract/errors.ts index 9a285ab4e..0af30ded1 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -89,6 +89,15 @@ export interface ErrorDetailsMap { COMPONENT_IN_USE: { readonly devices: number; readonly foreignDevices: number }; COMPONENT_BUSY: Record; UNKNOWN_LEASE: { readonly leaseId: string }; + TUNNEL_UNSUPPORTED: Record; + TUNNEL_PORT_IN_USE: Record; + TUNNEL_BAD_PORT: Record; + TUNNEL_LIMIT: Record; + TUNNEL_FAILED: Record; + TUNNEL_UNAVAILABLE: Record; + TUNNEL_DISCONNECTED: Record; + TUNNEL_CALLER_PORT_IN_USE: Record; + TUNNEL_LEASE_ENDED: Record; DEVICE_NOT_ENROLLABLE: { readonly platform: Platform; readonly id: string; @@ -314,6 +323,46 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry httpStatus: 422, }, UNKNOWN_LEASE: { code: "UNKNOWN_LEASE", kind: "domain", cliExitCode: 1, httpStatus: 404 }, + // why: a lease's tunnel socket refuses with these (ADR 0054 section 7), so every surface reports them alike. + TUNNEL_UNSUPPORTED: { + code: "TUNNEL_UNSUPPORTED", + kind: "domain", + cliExitCode: 1, + httpStatus: 422, + }, + TUNNEL_PORT_IN_USE: { + code: "TUNNEL_PORT_IN_USE", + kind: "domain", + cliExitCode: 1, + httpStatus: 409, + }, + TUNNEL_BAD_PORT: { code: "TUNNEL_BAD_PORT", kind: "domain", cliExitCode: 1, httpStatus: 422 }, + TUNNEL_LIMIT: { code: "TUNNEL_LIMIT", kind: "domain", cliExitCode: 1, httpStatus: 409 }, + TUNNEL_FAILED: { code: "TUNNEL_FAILED", kind: "domain", cliExitCode: 1, httpStatus: 502 }, + TUNNEL_UNAVAILABLE: { + code: "TUNNEL_UNAVAILABLE", + kind: "domain", + cliExitCode: 1, + httpStatus: 503, + }, + TUNNEL_DISCONNECTED: { + code: "TUNNEL_DISCONNECTED", + kind: "domain", + cliExitCode: 1, + httpStatus: 503, + }, + TUNNEL_CALLER_PORT_IN_USE: { + code: "TUNNEL_CALLER_PORT_IN_USE", + kind: "domain", + cliExitCode: 1, + httpStatus: 409, + }, + TUNNEL_LEASE_ENDED: { + code: "TUNNEL_LEASE_ENDED", + kind: "domain", + cliExitCode: 14, + httpStatus: 410, + }, // A device that cannot be enrolled is a fact about the device, as `RUNTIME_MISSING` is about // the host: 422 and 12. A busy device passes once what holds it ends, as `NO_CAPACITY` does: // 409 and 11. An unknown device is the "what you named does not exist" class: 404 and 12. diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 5d4d09788..b6d73d4d2 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 66, max: 66 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 67, max: 67 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/contract/tunnel-frames.ts b/src/contract/tunnel-frames.ts index dc4ee43ed..95293d95b 100644 --- a/src/contract/tunnel-frames.ts +++ b/src/contract/tunnel-frames.ts @@ -6,6 +6,7 @@ export const TUNNEL_TAG = { hello: 0x01, open: 0x02, ready: 0x81, + refused: 0x82, } as const; export interface TunnelFrame { @@ -37,3 +38,8 @@ export function decodeTunnelFrame(bytes: Uint8Array): TunnelFrame | undefined { tag: bytes[0] ?? 0, }; } + +export const TUNNEL_MAX_TUNNELS = 8; +export const TUNNEL_MIN_DEVICE_PORT = 1024; +export const TUNNEL_MAX_DEVICE_PORT = 65_535; +export const TUNNEL_REFUSED_CLOSE = 4003; diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 34803f777..64b593c20 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,7 +9,7 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - expect(DAEMON_PROTOCOL_VERSION).toBe(66); + expect(DAEMON_PROTOCOL_VERSION).toBe(67); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 9292ae23e..20170b255 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -59,7 +59,7 @@ Its stdout lines move the state; a failed line, a non-zero exit or a failed laun 2. **Hello** — first frame must be `hello`, else `HANDSHAKE_REQUIRED` and close. Role: the uplink connection is `admin` by acceptance; otherwise the resolver. Principal: `hello.principal`, else `SIMLOCK_AGENT_ID`, else the daemon's pid. Both are fixed for the connection's life. 3. **Version** — ranges overlap → highest common version. `PROTOCOL_VERSION_RANGE` - is `{ min: 66, max: 66 }` (`src/contract/protocol.ts`). No overlap → the + is `{ min: 67, max: 67 }` (`src/contract/protocol.ts`). No overlap → the connection stays open, and every request but `daemon.stop` gets `PROTOCOL_VERSION_UNSUPPORTED`. 4. **Request** — one frame → one `dispatch()` call. While stopping: `DAEMON_STOPPING`. diff --git a/src/tunnel/sessions.ts b/src/tunnel/sessions.ts index 2ba37647c..7bac88d7f 100644 --- a/src/tunnel/sessions.ts +++ b/src/tunnel/sessions.ts @@ -1,21 +1,62 @@ -import { decodeTunnelFrame, encodeTunnelFrame, TUNNEL_TAG } from "../contract/index.js"; +import { + decodeTunnelFrame, + encodeTunnelFrame, + TUNNEL_MAX_DEVICE_PORT, + TUNNEL_MAX_TUNNELS, + TUNNEL_MIN_DEVICE_PORT, + TUNNEL_REFUSED_CLOSE, + TUNNEL_TAG, +} from "../contract/index.js"; import { toDriverDevice, type DeviceRecord } from "../core/index.js"; import type { ModuleDeviceTcp } from "../modules/index.js"; import type { LeaseSocket, TcpStream } from "../ports/index.js"; interface Tunnel { - readonly kind: "reverse"; + readonly kind: "reverse" | "forward"; readonly devicePort: number; } +interface Refusal { + readonly code: string; + readonly message: string; +} + export interface TunnelSessions { - attach(device: DeviceRecord, socket: LeaseSocket): void; + attach(leaseId: string, device: DeviceRecord, socket: LeaseSocket): void; } export function createTunnelSessions(options: { readonly deviceTcp: ModuleDeviceTcp; }): TunnelSessions { - function attach(device: DeviceRecord, socket: LeaseSocket): void { + // why: the 8-tunnel limit counts every socket of one lease, so the count is the lease's, not the socket's. + const counts = new Map(); + + function refusal(tunnels: readonly Tunnel[], held: number): Refusal | undefined { + if (held + tunnels.length > TUNNEL_MAX_TUNNELS) { + return { + code: "TUNNEL_LIMIT", + message: `the lease already has ${String(held + tunnels.length)} tunnels; at most ${String(TUNNEL_MAX_TUNNELS)}`, + }; + } + for (const { devicePort, kind } of tunnels) { + if ( + !Number.isInteger(devicePort) || + devicePort < TUNNEL_MIN_DEVICE_PORT || + devicePort > TUNNEL_MAX_DEVICE_PORT + ) { + return { + code: "TUNNEL_BAD_PORT", + message: `${kind} ${String(devicePort)}: device ports are ${String(TUNNEL_MIN_DEVICE_PORT)} to ${String(TUNNEL_MAX_DEVICE_PORT)}`, + }; + } + } + if (tunnels.some(({ kind }) => kind === "forward")) { + return { code: "TUNNEL_UNSUPPORTED", message: "forward tunnels are not available yet" }; + } + return undefined; + } + + function attach(leaseId: string, device: DeviceRecord, socket: LeaseSocket): void { let nextConnection = 1; async function pump(conn: number, stream: TcpStream): Promise { @@ -30,6 +71,14 @@ export function createTunnelSessions(options: { async function hello(payload: Uint8Array): Promise { const named = JSON.parse(new TextDecoder().decode(payload)) as { tunnels: Tunnel[] }; const tunnels = named.tunnels.map(({ devicePort, kind }) => ({ kind, devicePort })); + const held = counts.get(leaseId) ?? 0; + const refused = refusal(tunnels, held); + if (refused !== undefined) { + socket.send(encodeTunnelFrame(TUNNEL_TAG.refused, 0, JSON.stringify(refused))); + socket.close(TUNNEL_REFUSED_CLOSE, refused.message); + return; + } + counts.set(leaseId, held + tunnels.length); for (const tunnel of tunnels) { const reverse = await options.deviceTcp.reverse( device.spec.platform, diff --git a/src/tunnel/worker.ts b/src/tunnel/worker.ts index 2c5caec93..68feb7743 100644 --- a/src/tunnel/worker.ts +++ b/src/tunnel/worker.ts @@ -15,7 +15,7 @@ export function createWorker(ctx: WorkerContext): WorkerModu const device = ctx.registry.snapshot.devices.find((entry) => entry.id === lease?.deviceId); if (device === undefined) return Promise.resolve(new Response(null, { status: 404 })); return Promise.resolve((socket) => { - sessions.attach(device, socket); + sessions.attach(held.id, device, socket); }); }, }, diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index 8caa70698..16c63bc18 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -22,13 +22,13 @@ Branch on `code`, not on the message: the message wording can change, the code d | Exit | Error codes | Meaning | | --- | --- | --- | | 0 | — | Success. For a `simlock lease` that stayed running: the lease ended because you asked. | -| 1 | `INTERNAL`, `PROVISION_FAILED`, `UNKNOWN_LEASE`, `FORBIDDEN`, `ADMIN_AUTHENTICATION_FAILED`, `SETUP_MCP_FAILED`, `DAEMON_STARTUP_FAILED`, `DAEMON_CONNECTION_LOST`, `DAEMON_STOPPING`, `DAEMON_UPDATING`, `HANDSHAKE_REQUIRED`, `PROTOCOL_VERSION_UNSUPPORTED`, `WORKER_UNREACHABLE`, `RELAY_TARGET_MISSING`, `ALERT_SEND_FAILED`, `UPDATE_RESOLVE_FAILED`, `HISTORY_UNAVAILABLE`, `DOCTOR_UNAVAILABLE`, `NUKE_UNAVAILABLE`, `UNKNOWN_DAEMON_ERROR`, `SERVICE_FAILED`, `CANCELLED` | The command failed. Read the code and the message. | +| 1 | `INTERNAL`, `PROVISION_FAILED`, `UNKNOWN_LEASE`, `FORBIDDEN`, `ADMIN_AUTHENTICATION_FAILED`, `SETUP_MCP_FAILED`, `DAEMON_STARTUP_FAILED`, `DAEMON_CONNECTION_LOST`, `DAEMON_STOPPING`, `DAEMON_UPDATING`, `HANDSHAKE_REQUIRED`, `PROTOCOL_VERSION_UNSUPPORTED`, `WORKER_UNREACHABLE`, `RELAY_TARGET_MISSING`, `ALERT_SEND_FAILED`, `UPDATE_RESOLVE_FAILED`, `HISTORY_UNAVAILABLE`, `DOCTOR_UNAVAILABLE`, `NUKE_UNAVAILABLE`, `UNKNOWN_DAEMON_ERROR`, `SERVICE_FAILED`, `CANCELLED`, `TUNNEL_UNSUPPORTED`, `TUNNEL_PORT_IN_USE`, `TUNNEL_BAD_PORT`, `TUNNEL_LIMIT`, `TUNNEL_FAILED`, `TUNNEL_UNAVAILABLE`, `TUNNEL_DISCONNECTED`, `TUNNEL_CALLER_PORT_IN_USE` | The command failed. Read the code and the message. | | 2 | `USAGE`, `BAD_REQUEST`, `BAD_FRAME`, `UNKNOWN_REQUEST`, `IDEMPOTENCY_CONFLICT`, `PASSTHROUGH_REFUSED`, `UNKNOWN_PASSTHROUGH_TOOL`, `SETUP_REFUSED`, `GATEWAY_NOT_PRESENT`, `UPDATE_UNSUPPORTED_INSTALL`, `UPDATE_SHARED_INSTALL`, `UNSUPPORTED_IN_GATEWAY_MODE`, `UNSUPPORTED_IN_WORKER_MODE`, `WORKER_CONNECTED`, `WORKER_NOT_CONNECTED` | The request was wrong. Running it again unchanged fails again. | | 10 | `QUEUE_TIMEOUT`, `EXEC_TIMEOUT`, `DOWNLOAD_TIMEOUT` | A deadline ran out. | | 11 | `NO_CAPACITY`, `DEVICE_BUSY`, `COMPONENT_BUSY` | Busy right now. The same request can pass later. | | 12 | `NO_DRIVER`, `CAPABILITY_MISSING`, `RUNTIME_MISSING`, `UNKNOWN_MODEL`, `INSUFFICIENT_DISK_SPACE`, `LICENSE_NOT_ACCEPTED`, `DOWNLOADS_DISABLED`, `COMPONENT_NOT_OWNED`, `COMPONENT_IN_USE`, `DEVICE_NOT_ENROLLABLE`, `UNKNOWN_DEVICE`, `HISTORY_NOT_KEPT`, `UNKNOWN_WORKER`, `UNKNOWN_ALERT_DESTINATION` | What you named does not exist here, or this machine cannot provide it. | | 13 | `REQUESTER_ALREADY_LEASED`, `LEASE_ID_TAKEN` | The request clashes with a lease or request that already exists. | -| 14 | — | `simlock lease` without `--detach`: the daemon ended the lease before you did (expiry, an operator's release, or a device that could not be recovered). The `lease-lost` line on stderr gives the reason. | +| 14 | `TUNNEL_LEASE_ENDED` | `simlock lease` without `--detach`: the daemon ended the lease before you did (expiry, an operator's release, or a device that could not be recovered). The `lease-lost` line on stderr gives the reason. | | 15 | — | `simlock component install` with `--worker` or `--all-workers`: at least one worker did not end `installed` or `already-installed`. The result on stdout says which. | `simlock simctl` and `simlock adb` exit with the wrapped tool's own exit code, which can be any of these numbers. For those two commands, look for the `{"error":...}` line on stderr, which only Simlock writes. @@ -72,6 +72,22 @@ Branch on `code`, not on the message: the message wording can change, the code d | `DEVICE_BUSY` | 11 | 409 | `device add` or `device remove` of a device that is leased, being cleaned, or held by another operation. | Try again once that ends. | | `UNKNOWN_DEVICE` | 12 | 404 | `device remove` of an ID that is not an enrolled device. | Check the ID with `simlock list --devices`. | +## Tunnels + +A lease's tunnel socket (`GET /v1/leases/{id}/tunnel`, on a worker with `capabilities.tunnel.enabled`) refuses a `HELLO` with one of these codes in a `REFUSED` frame and closes with 4003. + +| Code | Exit | HTTP | Meaning | What to do | +| --- | --- | --- | --- | --- | +| `TUNNEL_UNSUPPORTED` | 1 | 422 | The lease is on an iOS simulator or an iPhone, or the tunnel is a `forward` tunnel, which is not available yet. | Use an Android emulator or phone, and `reverse` tunnels. | +| `TUNNEL_PORT_IN_USE` | 1 | 409 | The device port is already reversed on the device, for example by an `adb reverse` run through `device.exec`. | Remove that rule first. | +| `TUNNEL_BAD_PORT` | 1 | 422 | A device port is not an integer from 1024 to 65535. | Name a port in that range. | +| `TUNNEL_LIMIT` | 1 | 409 | The lease would have more than 8 tunnels across its sockets. | Close a tunnel first. | +| `TUNNEL_FAILED` | 1 | 502 | `adb` could not set the tunnel up, or the worker has no free loopback port in its reserved range. The message carries adb's own words. | Read the message; try again. | +| `TUNNEL_UNAVAILABLE` | 1 | 503 | A gateway's worker has tunnels off. | Turn on `capabilities.tunnel.enabled` on the worker. | +| `TUNNEL_DISCONNECTED` | 1 | 503 | The tunnel client lost its connection. | Open the tunnel again. | +| `TUNNEL_CALLER_PORT_IN_USE` | 1 | 409 | The port the tunnel client listens on is in use on its machine. | Pick another caller port. | +| `TUNNEL_LEASE_ENDED` | 14 | 410 | The lease ended while the tunnel was open. | Take a new lease. | + ## Running commands on a device | Code | Exit | HTTP | Meaning | What to do | From fe1c1974d01119ff62f2f7a7c58d480877244005 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 00:57:26 -0300 Subject: [PATCH 007/103] test: a caller rotates a lease it may not touch, or names a bad orientation, and is refused (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/operations.ts | 6 ++++- src/daemon/device-rotate.e2e.test.ts | 33 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 435b5be4b..6626cd32c 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -1084,7 +1084,11 @@ export const deviceRotate = defineOperation({ role: "agent", effect: "write", input: z - .object({ leaseId: z.string().min(1).max(256), orientation: z.enum(INPUT_ORIENTATIONS) }) + .object({ + leaseId: z.string().min(1).max(256), + orientation: z.enum(INPUT_ORIENTATIONS), + requesterId: z.string().min(1).max(256).optional(), + }) .strict(), output: z.object({ leaseId: z.string().max(256), orientation: z.enum(INPUT_ORIENTATIONS) }), }); diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index e559241a8..4594486c7 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -81,4 +81,37 @@ describe("device.rotate", () => { expect(input.opened[0]?.closes).toBe(1); }, ); + + it( + "refuses a caller that rotates a lease it may not touch, or names a bad orientation", + { timeout: 60_000 }, + async () => { + const input = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); + const { daemon, leaseId } = await worker({ input, inputModule: false }); + const other: DispatchSession = { ...holder, principal: "holder-2" }; + const admin: DispatchSession = { ...holder, principal: "gateway-1", role: "admin" }; + const orientation = "landscape_left"; + + await expect( + daemon.dispatch("device.rotate", { leaseId, orientation }, holder), + ).resolves.toEqual({ leaseId, orientation }); + + const refused: readonly (readonly [object, unknown, DispatchSession])[] = [ + [{ name: "UnknownLeaseError" }, { leaseId: "nope", orientation }, holder], + [{ code: "FORBIDDEN" }, { leaseId, orientation }, other], + [{ code: "FORBIDDEN" }, { leaseId, orientation, requesterId: "holder-1" }, holder], + [{ code: "FORBIDDEN" }, { leaseId, orientation, requesterId: "someone-else" }, admin], + [{ code: "BAD_REQUEST" }, { leaseId, orientation: "landscape-left" }, holder], + [{ code: "BAD_REQUEST" }, { leaseId, orientation: "auto" }, holder], + [{ code: "BAD_REQUEST" }, { leaseId, orientation: "" }, holder], + ]; + for (const [expected, body, session] of refused) { + await expect( + daemon.dispatch("device.rotate", body as never, session), + JSON.stringify(body), + ).rejects.toMatchObject(expected); + } + expect(input.opened).toHaveLength(1); + }, + ); }); From 2f1ebec54bb5a9ce3b8a565d89631c0bc3cbc7bb Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 00:57:53 -0300 Subject: [PATCH 008/103] feat(contract): device.rotate is authorized like device.exec (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/AGENTS.md | 2 +- src/contract/operations.ts | 29 +++++++++++++++++++---------- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index 1e70704e4..6bad06eb6 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -45,7 +45,7 @@ every operation but `daemon.stop`, which `DaemonServer` answers. - `lease.renew`, `lease.release` — `ownsLease`: admin, or `ownerId` = principal. - `lease.cancel` — admin, or the pending request's owner = principal. -- `device.exec` — agent: owns the lease and names no `requesterId`. Admin: the lease's +- `device.exec`, `device.rotate` — agent: owns the lease and names no `requesterId`. Admin: the lease's requester = `requesterId` (default: principal). Three identities: diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 6626cd32c..e4820578b 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -486,16 +486,7 @@ export const deviceExec = defineOperation({ * authorized, the same convention `ownsLease` uses, so the handler's own `UNKNOWN_LEASE` * surfaces instead of a misleading `FORBIDDEN`. */ - authorize: (input, context) => { - if (context.role !== "admin") { - if (input.requesterId !== undefined) return false; - const ownerId = context.ownerId(input.leaseId); - return ownerId === undefined || ownerId === context.principal; - } - const requesterId = input.requesterId ?? context.principal; - const leaseRequesterId = context.leaseRequesterId(input.leaseId); - return leaseRequesterId === undefined || leaseRequesterId === requesterId; - }, + authorize: authorizeOneLeaseCall, }); /** @@ -1075,6 +1066,23 @@ const identityGet = defineOperation({ }), }); +/** + * why: `device.exec`'s and `device.rotate`'s one rule, so a gateway's admin session is held to the lease's requester on both. + */ +function authorizeOneLeaseCall( + input: { readonly leaseId: string; readonly requesterId?: string | undefined }, + context: AuthorizeContext, +): boolean { + if (context.role !== "admin") { + if (input.requesterId !== undefined) return false; + const ownerId = context.ownerId(input.leaseId); + return ownerId === undefined || ownerId === context.principal; + } + const requesterId = input.requesterId ?? context.principal; + const leaseRequesterId = context.leaseRequesterId(input.leaseId); + return leaseRequesterId === undefined || leaseRequesterId === requesterId; +} + /** * why: turns a leased iOS phone or tablet simulator, through the lease's device input, whether or not the input module is on. */ @@ -1091,6 +1099,7 @@ export const deviceRotate = defineOperation({ }) .strict(), output: z.object({ leaseId: z.string().max(256), orientation: z.enum(INPUT_ORIENTATIONS) }), + authorize: authorizeOneLeaseCall, }); export const OPERATIONS = { From e54e3f2f6dbd0f96c285ca2aae4a0b418e52845b Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:00:33 -0300 Subject: [PATCH 009/103] test: a holder rotates a lease not on an iOS phone or tablet simulator and gets ROTATION_UNSUPPORTED naming it (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/device-rotate.e2e.test.ts | 117 ++++++++++++++++++++++++++- 1 file changed, 116 insertions(+), 1 deletion(-) diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 4594486c7..10d7092e0 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -31,6 +31,7 @@ describe("device.rotate", () => { async function worker(options: { readonly inputModule: boolean; readonly input: FakeInputFactory; + readonly androidInput?: FakeInputFactory; }) { const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-rotate-")); directories.push(dataDirectory); @@ -43,9 +44,24 @@ describe("device.rotate", () => { availableOsVersions: ["18.0"], clock: new SystemClock(), input: options.input, - knownModels: ["iPhone 15"], + knownModels: ["iPhone 15", "iPad Pro", "Apple TV 4K", "Mystery Box"], + physicalDevices: [ + { class: "phone", ids: ["PHONE-1"], model: "iPhone 15", osVersion: "18.0" }, + { class: "tablet", ids: ["TABLET-1"], model: "iPad Pro", osVersion: "18.0" }, + ], platform: "ios", }), + new FakeDriver({ + availableOsVersions: ["15"], + clock: new SystemClock(), + ...(options.androidInput === undefined ? {} : { input: options.androidInput }), + knownModels: ["Pixel 8"], + physicalDevices: [ + { class: "phone", ids: ["DROID-1"], model: "Pixel 8", osVersion: "15" }, + { class: "tablet", ids: ["DROID-2"], model: "Pixel Tablet", osVersion: "15" }, + ], + platform: "android", + }), ], filesystem: new MemoryFilesystem(), logger: new NoopLogger(), @@ -114,4 +130,103 @@ describe("device.rotate", () => { expect(input.opened).toHaveLength(1); }, ); + + it( + "refuses a holder's rotate of a lease not on an iOS phone or tablet simulator with ROTATION_UNSUPPORTED naming it", + { timeout: 60_000 }, + async () => { + const input = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); + const androidInput = new FakeInputFactory({ + height: 2400, + orientation: "portrait", + width: 1080, + }); + const { daemon } = await worker({ androidInput, input, inputModule: false }); + const admin: DispatchSession = { ...holder, principal: "admin-1", role: "admin" }; + const orientation = "landscape_left"; + + async function lease(principal: string, request: object, enroll?: string) { + const session: DispatchSession = { ...holder, principal }; + if (enroll !== undefined) { + await daemon.dispatch( + "device.add", + { id: enroll, platform: (request as { platform: "ios" | "android" }).platform }, + admin, + ); + } + const granted = await daemon.dispatch("lease.request", request as never, session); + return { id: (granted as { lease: { id: string } }).lease.id, session }; + } + + const cases: readonly (readonly [string, object, string | undefined, string, object])[] = [ + [ + "tv", + { model: "Apple TV 4K", platform: "ios" }, + undefined, + "an Apple TV simulator", + { class: "tv", physical: false, platform: "ios" }, + ], + [ + "unknown family", + { model: "Mystery Box", platform: "ios" }, + undefined, + "a Mystery Box simulator", + { class: "unknown", physical: false, platform: "ios" }, + ], + [ + "emulator", + { model: "Pixel 8", platform: "android" }, + undefined, + "an Android emulator", + { class: "emulator", physical: false, platform: "android" }, + ], + [ + "android phone", + { model: "Pixel 8", physical: true, platform: "android" }, + "DROID-1", + "an Android phone", + { class: "phone", physical: true, platform: "android" }, + ], + [ + "android tablet", + { model: "Pixel Tablet", physical: true, platform: "android" }, + "DROID-2", + "an Android tablet", + { class: "tablet", physical: true, platform: "android" }, + ], + [ + "iphone", + { model: "iPhone 15", physical: true, platform: "ios" }, + "PHONE-1", + "an iPhone", + { class: "phone", physical: true, platform: "ios" }, + ], + [ + "ipad", + { model: "iPad Pro", physical: true, platform: "ios" }, + "TABLET-1", + "an iPad", + { class: "tablet", physical: true, platform: "ios" }, + ], + ]; + for (const [name, request, enroll, phrase, details] of cases) { + const { id, session } = await lease(`holder-${name}`, request, enroll); + await expect( + daemon.dispatch("device.rotate", { leaseId: id, orientation }, session), + name, + ).rejects.toMatchObject({ + code: "ROTATION_UNSUPPORTED", + details: { leaseId: id, ...details }, + message: `Lease ${id} is on ${phrase}; only an iOS simulator can be rotated`, + }); + } + + const ipad = await lease("holder-ipad-simulator", { model: "iPad Pro", platform: "ios" }); + await expect( + daemon.dispatch("device.rotate", { leaseId: ipad.id, orientation }, ipad.session), + ).resolves.toEqual({ leaseId: ipad.id, orientation }); + expect(input.opened).toHaveLength(1); + expect(androidInput.opened).toHaveLength(0); + }, + ); }); From 18acbd706ee6c3b3925a47d8fd7a09fab8cb9b13 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:03:17 -0300 Subject: [PATCH 010/103] feat(daemon): device.rotate refuses a lease not on an iOS phone or tablet simulator (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/errors.ts | 15 ++++++ src/contract/orientation.ts | 20 +++++++ src/daemon/AGENTS.md | 1 + src/daemon/device-rotate.e2e.test.ts | 54 ++++++++++--------- src/daemon/dispatcher.ts | 3 ++ src/daemon/rotation-refusal.ts | 38 +++++++++++++ .../content/docs/docs/reference/errors.mdx | 3 +- 7 files changed, 107 insertions(+), 27 deletions(-) create mode 100644 src/daemon/rotation-refusal.ts diff --git a/src/contract/errors.ts b/src/contract/errors.ts index 9a285ab4e..7e76418c7 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -100,6 +100,13 @@ export interface ErrorDetailsMap { PASSTHROUGH_REFUSED: { readonly tool: string }; UNKNOWN_PASSTHROUGH_TOOL: { readonly tool: string }; EXEC_TIMEOUT: Record; + /** why: `device.rotate` on a lease that is not on an iOS phone or tablet simulator; `class` is the physical class, the simulator's model family, or `emulator`. */ + ROTATION_UNSUPPORTED: { + readonly leaseId: string; + readonly platform: Platform; + readonly physical: boolean; + readonly class: string; + }; DOCTOR_UNAVAILABLE: Record; HISTORY_NOT_KEPT: { readonly oldestTs: number }; HISTORY_UNAVAILABLE: Record; @@ -193,6 +200,7 @@ const CODES_WITH_DECLARED_DETAILS_BY_CODE: Record DOWNLOADS_DISABLED: true, COMPONENT_IN_USE: true, UNKNOWN_LEASE: true, + ROTATION_UNSUPPORTED: true, DEVICE_NOT_ENROLLABLE: true, DEVICE_BUSY: true, UNKNOWN_DEVICE: true, @@ -344,6 +352,13 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry // out of time" outcome (`QUEUE_TIMEOUT`) already uses -- so a script branching on "timed // out" does not need a second number for the second kind of wait. EXEC_TIMEOUT: { code: "EXEC_TIMEOUT", kind: "domain", cliExitCode: 10, httpStatus: 504 }, + // why: a fact about the lease's device, as `RUNTIME_MISSING` is about the host: 422 and 12. + ROTATION_UNSUPPORTED: { + code: "ROTATION_UNSUPPORTED", + kind: "domain", + cliExitCode: 12, + httpStatus: 422, + }, DOWNLOAD_TIMEOUT: { code: "DOWNLOAD_TIMEOUT", kind: "domain", diff --git a/src/contract/orientation.ts b/src/contract/orientation.ts index d4cc3829f..03849a8fc 100644 --- a/src/contract/orientation.ts +++ b/src/contract/orientation.ts @@ -5,3 +5,23 @@ export const INPUT_ORIENTATIONS = [ "landscape_left", "landscape_right", ] as const; + +export type ModelFamily = "phone" | "tablet" | "tv" | "watch" | "vision" | "unknown"; + +const MODEL_FAMILY_PREFIXES: readonly (readonly [string, ModelFamily])[] = [ + ["iPhone", "phone"], + ["iPad", "tablet"], + ["Apple TV", "tv"], + ["Apple Watch", "watch"], + ["Apple Vision", "vision"], +]; + +// why: every model the iOS driver lists starts with its product family's name, and the device record keeps only the model. +export function modelFamily(model: string): ModelFamily { + return MODEL_FAMILY_PREFIXES.find(([prefix]) => model.startsWith(prefix))?.[1] ?? "unknown"; +} + +export function isRotatableModel(model: string): boolean { + const family = modelFamily(model); + return family === "phone" || family === "tablet"; +} diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 20170b255..1e869f459 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -25,6 +25,7 @@ Flows: [startup](../../docs/internal/flows/startup.md), [device.exec](../../docs | `relay.ts` | `RelayTargets`, `RelayConnection`: relays over the uplink | | `error-code.ts` | `classifyError`: thrown error → contract code | | `enrollment-wake.ts` | `wakingQueueAfter`: wakes the queue after `device.add`/`device.remove` | +| `rotation-refusal.ts` | `rotationRefusal`: `device.rotate`'s `ROTATION_UNSUPPORTED`, with how it names the device | | `exec-env.ts` | `execBaseEnvironment`: the allowlisted keys of `process.env` a `device.exec` child starts from | | `test-relay-support.ts` | Test helpers for relay e2e tests | diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 10d7092e0..71003eb26 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -35,34 +35,35 @@ describe("device.rotate", () => { }) { const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-rotate-")); directories.push(dataDirectory); + const drivers = [ + new FakeDriver({ + availableOsVersions: ["18.0"], + clock: new SystemClock(), + input: options.input, + knownModels: ["iPhone 15", "iPad Pro", "Apple TV 4K", "Mystery Box"], + physicalDevices: [ + { class: "phone", ids: ["PHONE-1"], model: "iPhone 15", osVersion: "18.0" }, + { class: "tablet", ids: ["TABLET-1"], model: "iPad Pro", osVersion: "18.0" }, + ], + platform: "ios", + }), + new FakeDriver({ + availableOsVersions: ["15"], + clock: new SystemClock(), + ...(options.androidInput === undefined ? {} : { input: options.androidInput }), + knownModels: ["Pixel 8"], + physicalDevices: [ + { class: "phone", ids: ["DROID-1"], model: "Pixel 8", osVersion: "15" }, + { class: "tablet", ids: ["DROID-2"], model: "Pixel Tablet", osVersion: "15" }, + ], + platform: "android", + }), + ]; const daemon = await startDaemon({ configOverrides: { capabilities: { input: { enabled: options.inputModule } } }, dataDirectory, deviceDataTables: fakeDeviceDataTables, - drivers: [ - new FakeDriver({ - availableOsVersions: ["18.0"], - clock: new SystemClock(), - input: options.input, - knownModels: ["iPhone 15", "iPad Pro", "Apple TV 4K", "Mystery Box"], - physicalDevices: [ - { class: "phone", ids: ["PHONE-1"], model: "iPhone 15", osVersion: "18.0" }, - { class: "tablet", ids: ["TABLET-1"], model: "iPad Pro", osVersion: "18.0" }, - ], - platform: "ios", - }), - new FakeDriver({ - availableOsVersions: ["15"], - clock: new SystemClock(), - ...(options.androidInput === undefined ? {} : { input: options.androidInput }), - knownModels: ["Pixel 8"], - physicalDevices: [ - { class: "phone", ids: ["DROID-1"], model: "Pixel 8", osVersion: "15" }, - { class: "tablet", ids: ["DROID-2"], model: "Pixel Tablet", osVersion: "15" }, - ], - platform: "android", - }), - ], + drivers, filesystem: new MemoryFilesystem(), logger: new NoopLogger(), version: "1.0.0-e2e", @@ -73,7 +74,7 @@ describe("device.rotate", () => { { model: "iPhone 15", platform: "ios" }, holder, ); - return { daemon, leaseId: (granted as { lease: { id: string } }).lease.id }; + return { daemon, drivers, leaseId: (granted as { lease: { id: string } }).lease.id }; } it( @@ -141,13 +142,14 @@ describe("device.rotate", () => { orientation: "portrait", width: 1080, }); - const { daemon } = await worker({ androidInput, input, inputModule: false }); + const { daemon, drivers } = await worker({ androidInput, input, inputModule: false }); const admin: DispatchSession = { ...holder, principal: "admin-1", role: "admin" }; const orientation = "landscape_left"; async function lease(principal: string, request: object, enroll?: string) { const session: DispatchSession = { ...holder, principal }; if (enroll !== undefined) { + for (const driver of drivers) driver.setPhysicalPresence(enroll, true); await daemon.dispatch( "device.add", { id: enroll, platform: (request as { platform: "ios" | "android" }).platform }, diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 758e2e6ea..2e513b0c4 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -39,6 +39,7 @@ import { type UsageReader, } from "../core/index.js"; import type { ModuleInputs } from "../modules/index.js"; +import { rotationRefusal } from "./rotation-refusal.js"; import { type DeviceModeReader, LeaseIdTakenError, @@ -674,6 +675,8 @@ export class Dispatcher { (candidate) => candidate.id === lease.deviceId, ); if (record === undefined) throw new UnknownLeaseError(input.leaseId); + const refusal = rotationRefusal(input.leaseId, record.spec); + if (refusal !== undefined) throw refusal; const opened = await this.options.inputs.openInput( record.spec.platform, toDriverDevice(record), diff --git a/src/daemon/rotation-refusal.ts b/src/daemon/rotation-refusal.ts new file mode 100644 index 000000000..468bb0fff --- /dev/null +++ b/src/daemon/rotation-refusal.ts @@ -0,0 +1,38 @@ +import { isRotatableModel, modelFamily } from "../contract/index.js"; +import type { DeviceSpec } from "../core/index.js"; +import { DispatchError } from "./dispatch.js"; + +const SIMULATOR_NAMES = { + tv: "an Apple TV simulator", + vision: "an Apple Vision simulator", + watch: "an Apple Watch simulator", +} as const; + +function describeTarget(spec: DeviceSpec): { readonly phrase: string; readonly class: string } { + if (spec.physical) { + const phrase = + spec.platform === "android" + ? `an Android ${spec.class}` + : spec.class === "phone" + ? "an iPhone" + : "an iPad"; + return { class: spec.class, phrase }; + } + if (spec.platform === "android") return { class: "emulator", phrase: "an Android emulator" }; + const family = modelFamily(spec.model); + if (family === "tv" || family === "watch" || family === "vision") { + return { class: family, phrase: SIMULATOR_NAMES[family] }; + } + return { class: family, phrase: `a ${spec.model} simulator` }; +} + +/** why: the one place that says which leases `device.rotate` turns, and how a refusal names the device. */ +export function rotationRefusal(leaseId: string, spec: DeviceSpec): DispatchError | undefined { + if (!spec.physical && spec.platform === "ios" && isRotatableModel(spec.model)) return undefined; + const target = describeTarget(spec); + return new DispatchError( + "ROTATION_UNSUPPORTED", + `Lease ${leaseId} is on ${target.phrase}; only an iOS simulator can be rotated`, + { class: target.class, leaseId, physical: spec.physical, platform: spec.platform }, + ); +} diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index 8caa70698..97d88469e 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -26,7 +26,7 @@ Branch on `code`, not on the message: the message wording can change, the code d | 2 | `USAGE`, `BAD_REQUEST`, `BAD_FRAME`, `UNKNOWN_REQUEST`, `IDEMPOTENCY_CONFLICT`, `PASSTHROUGH_REFUSED`, `UNKNOWN_PASSTHROUGH_TOOL`, `SETUP_REFUSED`, `GATEWAY_NOT_PRESENT`, `UPDATE_UNSUPPORTED_INSTALL`, `UPDATE_SHARED_INSTALL`, `UNSUPPORTED_IN_GATEWAY_MODE`, `UNSUPPORTED_IN_WORKER_MODE`, `WORKER_CONNECTED`, `WORKER_NOT_CONNECTED` | The request was wrong. Running it again unchanged fails again. | | 10 | `QUEUE_TIMEOUT`, `EXEC_TIMEOUT`, `DOWNLOAD_TIMEOUT` | A deadline ran out. | | 11 | `NO_CAPACITY`, `DEVICE_BUSY`, `COMPONENT_BUSY` | Busy right now. The same request can pass later. | -| 12 | `NO_DRIVER`, `CAPABILITY_MISSING`, `RUNTIME_MISSING`, `UNKNOWN_MODEL`, `INSUFFICIENT_DISK_SPACE`, `LICENSE_NOT_ACCEPTED`, `DOWNLOADS_DISABLED`, `COMPONENT_NOT_OWNED`, `COMPONENT_IN_USE`, `DEVICE_NOT_ENROLLABLE`, `UNKNOWN_DEVICE`, `HISTORY_NOT_KEPT`, `UNKNOWN_WORKER`, `UNKNOWN_ALERT_DESTINATION` | What you named does not exist here, or this machine cannot provide it. | +| 12 | `NO_DRIVER`, `CAPABILITY_MISSING`, `RUNTIME_MISSING`, `UNKNOWN_MODEL`, `ROTATION_UNSUPPORTED`, `INSUFFICIENT_DISK_SPACE`, `LICENSE_NOT_ACCEPTED`, `DOWNLOADS_DISABLED`, `COMPONENT_NOT_OWNED`, `COMPONENT_IN_USE`, `DEVICE_NOT_ENROLLABLE`, `UNKNOWN_DEVICE`, `HISTORY_NOT_KEPT`, `UNKNOWN_WORKER`, `UNKNOWN_ALERT_DESTINATION` | What you named does not exist here, or this machine cannot provide it. | | 13 | `REQUESTER_ALREADY_LEASED`, `LEASE_ID_TAKEN` | The request clashes with a lease or request that already exists. | | 14 | — | `simlock lease` without `--detach`: the daemon ended the lease before you did (expiry, an operator's release, or a device that could not be recovered). The `lease-lost` line on stderr gives the reason. | | 15 | — | `simlock component install` with `--worker` or `--all-workers`: at least one worker did not end `installed` or `already-installed`. The result on stdout says which. | @@ -79,6 +79,7 @@ Branch on `code`, not on the message: the message wording can change, the code d | `PASSTHROUGH_REFUSED` | 2 | 422 | Simlock refuses this `simctl`, `adb` or `devicectl` command: a verb that creates, erases or deletes devices or touches every device at once (such as `simctl erase` or `adb kill-server`), a flag that points the tool at another device set or adb server, `simctl` on a physical device, `simctl` or `adb` on a lease of the other platform, a `device.exec` command that names a device other than the lease's (`booted`, another UDID, `adb -s` with another serial, `-e`, `-d`, `-t`, a different `devicectl --device`), or `adb shell` with no command where there is no terminal. | Drop the refused flag or verb, leave the device out of the command, or name the command to run. The message says which. | | `UNKNOWN_PASSTHROUGH_TOOL` | 2 | 422 | A tool Simlock does not wrap. | Use `simctl` or `adb`. | | `EXEC_TIMEOUT` | 10 | 504 | A command run on a device through a gateway ran longer than `exec.timeoutMs` (10 minutes by default) and was stopped. | Split the work, or raise `exec.timeoutMs` on the worker. | +| `ROTATION_UNSUPPORTED` | 12 | 422 | The lease is not on an iOS phone or tablet simulator, so `POST /v1/leases/{id}/rotate` has nothing to turn. The message names what it is on: an Apple TV, Apple Watch or Apple Vision simulator, another iOS model, an Android emulator or phone or tablet, an iPhone or an iPad. | Rotate a lease on an iPhone or iPad simulator. | ## Daemon and connection From 642a3922f5e2f6dad55c5674bcb84d8b4c239c69 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:04:11 -0300 Subject: [PATCH 011/103] test: a holder rotates when the helper cannot start or the write fails and gets INPUT_UNAVAILABLE with the reason (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/core/fake-device-input.ts | 7 +++ src/daemon/device-rotate.e2e.test.ts | 74 +++++++++++++++++++++++++++- 2 files changed, 79 insertions(+), 2 deletions(-) diff --git a/src/core/fake-device-input.ts b/src/core/fake-device-input.ts index b018df012..5e560a4fc 100644 --- a/src/core/fake-device-input.ts +++ b/src/core/fake-device-input.ts @@ -14,11 +14,15 @@ class FakeDeviceInput implements DeviceInput { readonly #failedListeners = new Set<(error: Error) => void>(); #config: InputScreenConfig; + // why: a test sets this to make every write fail, as a helper whose pipe broke does. + sendFailure: Error | undefined; + constructor(config: InputScreenConfig) { this.#config = config; } send(message: InputMessage): Promise { + if (this.sendFailure !== undefined) return Promise.reject(this.sendFailure); this.sent.push(message); return Promise.resolve(); } @@ -57,6 +61,8 @@ export class FakeInputFactory implements DeviceInputFactory { failWith: Error | undefined; // why: a test sets this to hold every open until it resolves, to end a lease while a socket is still opening. gate: Promise | undefined; + // why: a test sets this to make the writes of the inputs it opens next fail. + sendFailure: Error | undefined; opens = 0; constructor(private readonly config: InputScreenConfig) {} @@ -66,6 +72,7 @@ export class FakeInputFactory implements DeviceInputFactory { await this.gate; if (this.failWith !== undefined) throw this.failWith; const input = new FakeDeviceInput(this.config); + input.sendFailure = this.sendFailure; this.opened.push(input); return input; } diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 71003eb26..6e880dc7e 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -30,7 +30,7 @@ describe("device.rotate", () => { async function worker(options: { readonly inputModule: boolean; - readonly input: FakeInputFactory; + readonly input: FakeInputFactory | undefined; readonly androidInput?: FakeInputFactory; }) { const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-rotate-")); @@ -39,7 +39,7 @@ describe("device.rotate", () => { new FakeDriver({ availableOsVersions: ["18.0"], clock: new SystemClock(), - input: options.input, + ...(options.input === undefined ? {} : { input: options.input }), knownModels: ["iPhone 15", "iPad Pro", "Apple TV 4K", "Mystery Box"], physicalDevices: [ { class: "phone", ids: ["PHONE-1"], model: "iPhone 15", osVersion: "18.0" }, @@ -231,4 +231,74 @@ describe("device.rotate", () => { expect(androidInput.opened).toHaveLength(0); }, ); + + it( + "refuses a holder's rotate with INPUT_UNAVAILABLE and the reason when the helper cannot start or the write fails", + { timeout: 60_000 }, + async () => { + const screen = { height: 2556, orientation: "portrait", width: 1179 } as const; + const cut = "x".repeat(300); + const cases: readonly (readonly [ + string, + (input: FakeInputFactory) => void, + string, + boolean, + ])[] = [ + ["no factory", () => undefined, "ios devices take no input", false], + [ + "open rejects", + (input) => { + input.failWith = new Error("helper exploded"); + }, + "helper exploded", + true, + ], + [ + "open rejects with a long message", + (input) => { + input.failWith = new Error(cut); + }, + "x".repeat(200), + true, + ], + [ + "open rejects with no message", + (input) => { + input.failWith = new Error(""); + }, + "unknown error", + true, + ], + [ + "write rejects", + (input) => { + input.sendFailure = new Error("pipe closed"); + }, + "pipe closed", + true, + ], + ]; + for (const [name, arrange, reason, hasFactory] of cases) { + const input = new FakeInputFactory(screen); + arrange(input); + const { daemon, leaseId } = await worker({ + input: hasFactory ? input : undefined, + inputModule: false, + }); + + await expect( + daemon.dispatch("device.rotate", { leaseId, orientation: "landscape_left" }, holder), + name, + ).rejects.toMatchObject({ + code: "INPUT_UNAVAILABLE", + details: { leaseId, reason }, + message: `Lease ${leaseId}'s simulator cannot take input: ${reason}`, + }); + expect( + input.opened.map((opened) => opened.closes), + name, + ).toEqual(input.opened.map(() => 1)); + } + }, + ); }); From 770e4f0635fe895a534b4ee9496c3851543f2df4 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:05:07 -0300 Subject: [PATCH 012/103] feat(daemon): device.rotate answers INPUT_UNAVAILABLE with the reason when the helper or the write fails (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/errors.ts | 5 +++ src/daemon/device-rotate.e2e.test.ts | 1 + src/daemon/dispatcher.ts | 34 ++++++++++++++----- .../content/docs/docs/reference/errors.mdx | 3 +- 4 files changed, 33 insertions(+), 10 deletions(-) diff --git a/src/contract/errors.ts b/src/contract/errors.ts index 7e76418c7..546f96c76 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -107,6 +107,8 @@ export interface ErrorDetailsMap { readonly physical: boolean; readonly class: string; }; + /** why: `device.rotate` could not reach the lease's input helper; `reason` is the driver's text, cut to 200 characters. */ + INPUT_UNAVAILABLE: { readonly leaseId: string; readonly reason: string }; DOCTOR_UNAVAILABLE: Record; HISTORY_NOT_KEPT: { readonly oldestTs: number }; HISTORY_UNAVAILABLE: Record; @@ -201,6 +203,7 @@ const CODES_WITH_DECLARED_DETAILS_BY_CODE: Record COMPONENT_IN_USE: true, UNKNOWN_LEASE: true, ROTATION_UNSUPPORTED: true, + INPUT_UNAVAILABLE: true, DEVICE_NOT_ENROLLABLE: true, DEVICE_BUSY: true, UNKNOWN_DEVICE: true, @@ -359,6 +362,8 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry cliExitCode: 12, httpStatus: 422, }, + // why: the helper that takes the touch is down, like `DOCTOR_UNAVAILABLE`: 503 and 1. + INPUT_UNAVAILABLE: { code: "INPUT_UNAVAILABLE", kind: "domain", cliExitCode: 1, httpStatus: 503 }, DOWNLOAD_TIMEOUT: { code: "DOWNLOAD_TIMEOUT", kind: "domain", diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 6e880dc7e..7f9715631 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -298,6 +298,7 @@ describe("device.rotate", () => { input.opened.map((opened) => opened.closes), name, ).toEqual(input.opened.map(() => 1)); + await daemons.pop()?.stop("test"); } }, ); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 2e513b0c4..7cfb0825b 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -677,16 +677,20 @@ export class Dispatcher { if (record === undefined) throw new UnknownLeaseError(input.leaseId); const refusal = rotationRefusal(input.leaseId, record.spec); if (refusal !== undefined) throw refusal; - const opened = await this.options.inputs.openInput( - record.spec.platform, - toDriverDevice(record), - new AbortController().signal, - ); - if (isUnavailableInput(opened)) throw new Error(opened.unavailable); try { - await opened.send({ kind: "orientation", orientation: input.orientation }); - } finally { - await opened.close(); + const opened = await this.options.inputs.openInput( + record.spec.platform, + toDriverDevice(record), + new AbortController().signal, + ); + if (isUnavailableInput(opened)) throw new Error(opened.unavailable); + try { + await opened.send({ kind: "orientation", orientation: input.orientation }); + } finally { + await opened.close(); + } + } catch (error) { + throw inputUnavailable(input.leaseId, error); } return { leaseId: input.leaseId, orientation: input.orientation }; }; @@ -1135,6 +1139,18 @@ function describeEnrollmentError(error: unknown): unknown { return error; } +const INPUT_REASON_MAX = 200; + +function inputUnavailable(leaseId: string, error: unknown): DispatchError { + const text = error instanceof Error ? error.message : String(error); + const reason = text === "" ? "unknown error" : text.slice(0, INPUT_REASON_MAX); + return new DispatchError( + "INPUT_UNAVAILABLE", + `Lease ${leaseId}'s simulator cannot take input: ${reason}`, + { leaseId, reason }, + ); +} + function unsupportedOnWorker( operation: OperationName, message = `${operation} acts on a gateway's workers, and this daemon is not a gateway`, diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index 97d88469e..ffe15b716 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -22,7 +22,7 @@ Branch on `code`, not on the message: the message wording can change, the code d | Exit | Error codes | Meaning | | --- | --- | --- | | 0 | — | Success. For a `simlock lease` that stayed running: the lease ended because you asked. | -| 1 | `INTERNAL`, `PROVISION_FAILED`, `UNKNOWN_LEASE`, `FORBIDDEN`, `ADMIN_AUTHENTICATION_FAILED`, `SETUP_MCP_FAILED`, `DAEMON_STARTUP_FAILED`, `DAEMON_CONNECTION_LOST`, `DAEMON_STOPPING`, `DAEMON_UPDATING`, `HANDSHAKE_REQUIRED`, `PROTOCOL_VERSION_UNSUPPORTED`, `WORKER_UNREACHABLE`, `RELAY_TARGET_MISSING`, `ALERT_SEND_FAILED`, `UPDATE_RESOLVE_FAILED`, `HISTORY_UNAVAILABLE`, `DOCTOR_UNAVAILABLE`, `NUKE_UNAVAILABLE`, `UNKNOWN_DAEMON_ERROR`, `SERVICE_FAILED`, `CANCELLED` | The command failed. Read the code and the message. | +| 1 | `INTERNAL`, `PROVISION_FAILED`, `UNKNOWN_LEASE`, `FORBIDDEN`, `ADMIN_AUTHENTICATION_FAILED`, `SETUP_MCP_FAILED`, `DAEMON_STARTUP_FAILED`, `DAEMON_CONNECTION_LOST`, `DAEMON_STOPPING`, `DAEMON_UPDATING`, `HANDSHAKE_REQUIRED`, `PROTOCOL_VERSION_UNSUPPORTED`, `WORKER_UNREACHABLE`, `RELAY_TARGET_MISSING`, `ALERT_SEND_FAILED`, `UPDATE_RESOLVE_FAILED`, `HISTORY_UNAVAILABLE`, `DOCTOR_UNAVAILABLE`, `INPUT_UNAVAILABLE`, `NUKE_UNAVAILABLE`, `UNKNOWN_DAEMON_ERROR`, `SERVICE_FAILED`, `CANCELLED` | The command failed. Read the code and the message. | | 2 | `USAGE`, `BAD_REQUEST`, `BAD_FRAME`, `UNKNOWN_REQUEST`, `IDEMPOTENCY_CONFLICT`, `PASSTHROUGH_REFUSED`, `UNKNOWN_PASSTHROUGH_TOOL`, `SETUP_REFUSED`, `GATEWAY_NOT_PRESENT`, `UPDATE_UNSUPPORTED_INSTALL`, `UPDATE_SHARED_INSTALL`, `UNSUPPORTED_IN_GATEWAY_MODE`, `UNSUPPORTED_IN_WORKER_MODE`, `WORKER_CONNECTED`, `WORKER_NOT_CONNECTED` | The request was wrong. Running it again unchanged fails again. | | 10 | `QUEUE_TIMEOUT`, `EXEC_TIMEOUT`, `DOWNLOAD_TIMEOUT` | A deadline ran out. | | 11 | `NO_CAPACITY`, `DEVICE_BUSY`, `COMPONENT_BUSY` | Busy right now. The same request can pass later. | @@ -80,6 +80,7 @@ Branch on `code`, not on the message: the message wording can change, the code d | `UNKNOWN_PASSTHROUGH_TOOL` | 2 | 422 | A tool Simlock does not wrap. | Use `simctl` or `adb`. | | `EXEC_TIMEOUT` | 10 | 504 | A command run on a device through a gateway ran longer than `exec.timeoutMs` (10 minutes by default) and was stopped. | Split the work, or raise `exec.timeoutMs` on the worker. | | `ROTATION_UNSUPPORTED` | 12 | 422 | The lease is not on an iOS phone or tablet simulator, so `POST /v1/leases/{id}/rotate` has nothing to turn. The message names what it is on: an Apple TV, Apple Watch or Apple Vision simulator, another iOS model, an Android emulator or phone or tablet, an iPhone or an iPad. | Rotate a lease on an iPhone or iPad simulator. | +| `INPUT_UNAVAILABLE` | 1 | 503 | The lease's simulator could not take the rotation: its input helper did not start within 10 seconds, or writing to it failed. The message ends with the driver's reason, cut to 200 characters. | Run it again. If it repeats, check `simlock daemon logs`. | ## Daemon and connection From 50dac1b5737e6740135ea8d6325bdc92a18b4f82 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:06:33 -0300 Subject: [PATCH 013/103] test: an input socket opened after a rotate's helper closed gets a fresh helper; a socket open during a rotate keeps its helper (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/device-rotate.e2e.test.ts | 114 ++++++++++++++++++++++++++- 1 file changed, 112 insertions(+), 2 deletions(-) diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 7f9715631..36a10a00a 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -1,8 +1,10 @@ import { mkdtemp, rm } from "node:fs/promises"; +import { createServer } from "node:net"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { WebSocket } from "ws"; import { FakeDriver, FakeInputFactory, fakeDeviceDataTables } from "../core/testing.js"; import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; @@ -10,6 +12,15 @@ 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 holder: DispatchSession = { manageEventSubscription: () => undefined, via: "socket", @@ -21,7 +32,10 @@ describe("device.rotate", () => { const daemons: DaemonServer[] = []; const directories: string[] = []; + const sockets: WebSocket[] = []; + afterEach(async () => { + for (const socket of sockets.splice(0)) socket.terminate(); 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 })), @@ -32,6 +46,7 @@ describe("device.rotate", () => { readonly inputModule: boolean; readonly input: FakeInputFactory | undefined; readonly androidInput?: FakeInputFactory; + readonly httpPort?: number; }) { const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-rotate-")); directories.push(dataDirectory); @@ -60,7 +75,12 @@ describe("device.rotate", () => { }), ]; const daemon = await startDaemon({ - configOverrides: { capabilities: { input: { enabled: options.inputModule } } }, + configOverrides: { + capabilities: { input: { enabled: options.inputModule } }, + ...(options.httpPort === undefined + ? {} + : { http: { enabled: true, host: "127.0.0.1", port: options.httpPort } }), + }, dataDirectory, deviceDataTables: fakeDeviceDataTables, drivers, @@ -302,4 +322,94 @@ describe("device.rotate", () => { } }, ); + + async function holderWithSocketAccess(input: FakeInputFactory) { + const httpPort = await freeLoopbackPort(); + const { daemon } = await worker({ httpPort, input, inputModule: true }); + const admin: DispatchSession = { ...holder, principal: "operator", role: "admin" }; + const created = await daemon.dispatch( + "token.create", + { label: "holder", role: "agent" }, + admin, + ); + const session: DispatchSession = { ...holder, principal: created.token.id }; + const granted = await daemon.dispatch( + "lease.request", + { model: "iPhone 15", platform: "ios" }, + session, + ); + const leaseId = (granted as { lease: { id: string } }).lease.id; + return { + daemon, + leaseId, + openSocket: async () => { + const socket = new WebSocket( + `ws://127.0.0.1:${String(httpPort)}/v1/leases/${leaseId}/input`, + { + headers: { authorization: `Bearer ${created.secret}` }, + }, + ); + sockets.push(socket); + const messages: number[] = []; + const closed: { code: number | undefined } = { code: undefined }; + socket.on("message", (data) => messages.push((data as Buffer)[0] ?? -1)); + socket.on("close", (code) => { + closed.code = code; + }); + await new Promise((resolve, reject) => { + socket.once("open", () => resolve()); + socket.once("error", reject); + }); + await vi.waitFor(() => expect(messages).toEqual([0x83, 0x82]), { timeout: 10_000 }); + return closed; + }, + session, + }; + } + + it( + "gives an input socket opened after a rotate's helper closed a fresh helper, keeps a socket's helper through a rotate, and answers UNKNOWN_LEASE when the lease is reclaimed while the rotate's helper opens", + { timeout: 60_000 }, + async () => { + const input = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); + const { daemon, leaseId, openSocket, session } = await holderWithSocketAccess(input); + const orientation = "landscape_right"; + + await daemon.dispatch("device.rotate", { leaseId, orientation }, session); + expect(input.opened).toHaveLength(1); + expect(input.opened[0]?.closes).toBe(1); + + const socket = await openSocket(); + expect(input.opened).toHaveLength(2); + expect(input.opened[1]?.closes).toBe(0); + + await expect( + daemon.dispatch("device.rotate", { leaseId, orientation: "portrait" }, session), + ).resolves.toEqual({ leaseId, orientation: "portrait" }); + expect(input.opened).toHaveLength(2); + expect(input.opened[1]?.sent).toEqual([{ kind: "orientation", orientation: "portrait" }]); + expect(input.opened[1]?.closes).toBe(0); + + input.opened[1]?.fail(new Error("pipe closed")); + await vi.waitFor(() => expect(socket.code).toBe(1013), { timeout: 10_000 }); + await expect( + daemon.dispatch("device.rotate", { leaseId, orientation }, session), + ).resolves.toEqual({ leaseId, orientation }); + expect(input.opened).toHaveLength(3); + expect(input.opened[2]?.sent).toEqual([{ kind: "orientation", orientation }]); + + let open: () => void = () => undefined; + input.gate = new Promise((resolve) => { + open = resolve; + }); + const rotating = daemon.dispatch("device.rotate", { leaseId, orientation }, session); + const outcome = expect(rotating).rejects.toMatchObject({ name: "UnknownLeaseError" }); + await vi.waitFor(() => expect(input.opens).toBe(4), { timeout: 10_000 }); + await daemon.dispatch("lease.release", { leaseId }, session); + open(); + await outcome; + await vi.waitFor(() => expect(input.opened[3]?.closes).toBe(1), { timeout: 10_000 }); + expect(input.opened[3]?.sent).toEqual([]); + }, + ); }); From 2084eab68ff183201f54e2441e66ee000bdc89fa Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:06:49 -0300 Subject: [PATCH 014/103] test: bytes flow both ways under a 262144-byte window per direction, credit pausing only its connection (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/tunnel/worker.test.ts | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index fcb97e081..4243476f6 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -26,6 +26,15 @@ function frames(socket: MemoryLeaseSocket): { tag: number; conn: number; body: s })); } +function sentData(socket: MemoryLeaseSocket, conn: number): number { + return socket.sent + .filter( + (sent) => + sent[0] === 0x03 && new DataView(sent.buffer, sent.byteOffset).getUint32(1) === conn, + ) + .reduce((total, sent) => total + sent.length - 5, 0); +} + function hello(...tunnels: { kind: string; devicePort: number }[]): Uint8Array { return frame(0x01, 0, JSON.stringify({ tunnels })); } @@ -154,4 +163,34 @@ describe("a worker's tunnel socket", () => { expect(first.closed).toBeUndefined(); expect(deviceTcp.reversed).toEqual([5001, 5002, 5003, 5004]); }); + + it("carries bytes both ways under a 262144-byte window per direction, and a reader that grants no credit pauses only its own connection", async () => { + const { deviceTcp, worker } = await setup(); + const socket = await attach(worker); + socket.receive(hello({ devicePort: 5173, kind: "reverse" })); + await vi.waitFor(() => expect(frames(socket)).toHaveLength(1)); + const first = deviceTcp.connect(5173); + const second = deviceTcp.connect(5173); + await vi.waitFor(() => + expect(frames(socket).map((sent) => sent.tag)).toEqual([0x81, 0x02, 0x02]), + ); + + socket.receive(frame(0x03, 1, "to the device")); + await vi.waitFor(() => expect(first.writtenText()).toBe("to the device")); + await vi.waitFor(() => + expect(socket.sent.at(-1)).toEqual(Uint8Array.from([0x04, 0, 0, 0, 1, 0, 0, 0, 13])), + ); + + first.send(new Uint8Array(300_000)); + await vi.waitFor(() => expect(sentData(socket, 1)).toBe(262_144)); + second.send("still flowing"); + await vi.waitFor(() => expect(sentData(socket, 3)).toBe(13)); + expect(sentData(socket, 1)).toBe(262_144); + + socket.receive(Uint8Array.from([0x04, 0, 0, 0, 1, 0, 0x01, 0x86, 0xa0])); + await vi.waitFor(() => expect(sentData(socket, 1)).toBe(300_000)); + expect(frames(socket).every((sent) => sent.tag !== 0x03 || sent.body.length <= 65_536)).toBe( + true, + ); + }); }); From c4f93c03568bfebcb8ab694669dd46cee90391a6 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:07:12 -0300 Subject: [PATCH 015/103] feat(tunnel): data flows both ways under a per-connection window and credit (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/tunnel-frames.ts | 4 +++ src/tunnel/sessions.ts | 63 +++++++++++++++++++++++++++++++---- 2 files changed, 60 insertions(+), 7 deletions(-) diff --git a/src/contract/tunnel-frames.ts b/src/contract/tunnel-frames.ts index 95293d95b..aa89bf9eb 100644 --- a/src/contract/tunnel-frames.ts +++ b/src/contract/tunnel-frames.ts @@ -2,6 +2,7 @@ // operations, but the worker's module and the CLI's `simlock tunnel` must agree on every byte, so the // codec sits here, imported by both: one binary message is `[tag u8][conn u32 big-endian][payload]`. export const TUNNEL_TAG = { + credit: 0x04, data: 0x03, hello: 0x01, open: 0x02, @@ -43,3 +44,6 @@ export const TUNNEL_MAX_TUNNELS = 8; export const TUNNEL_MIN_DEVICE_PORT = 1024; export const TUNNEL_MAX_DEVICE_PORT = 65_535; export const TUNNEL_REFUSED_CLOSE = 4003; + +export const TUNNEL_WINDOW_BYTES = 262_144; +export const TUNNEL_MAX_DATA_BYTES = 65_536; diff --git a/src/tunnel/sessions.ts b/src/tunnel/sessions.ts index 7bac88d7f..62228b02b 100644 --- a/src/tunnel/sessions.ts +++ b/src/tunnel/sessions.ts @@ -1,11 +1,13 @@ import { decodeTunnelFrame, encodeTunnelFrame, + TUNNEL_MAX_DATA_BYTES, TUNNEL_MAX_DEVICE_PORT, TUNNEL_MAX_TUNNELS, TUNNEL_MIN_DEVICE_PORT, TUNNEL_REFUSED_CLOSE, TUNNEL_TAG, + TUNNEL_WINDOW_BYTES, } from "../contract/index.js"; import { toDriverDevice, type DeviceRecord } from "../core/index.js"; import type { ModuleDeviceTcp } from "../modules/index.js"; @@ -16,6 +18,13 @@ interface Tunnel { readonly devicePort: number; } +interface Connection { + readonly stream: TcpStream; + // why: how many bytes the worker may still send before the caller grants more credit. + window: number; + wake: (() => void) | undefined; +} + interface Refusal { readonly code: string; readonly message: string; @@ -59,15 +68,41 @@ export function createTunnelSessions(options: { function attach(leaseId: string, device: DeviceRecord, socket: LeaseSocket): void { let nextConnection = 1; - async function pump(conn: number, stream: TcpStream): Promise { - const reader = stream.readable.getReader(); + const connections = new Map(); + + // why: a connection reads from its device stream only while the caller has granted window, so a slow reader stops its own connection and no other. + async function pump(conn: number, connection: Connection): Promise { + const reader = connection.stream.readable.getReader(); + let pending: Uint8Array | undefined; for (;;) { - const step = await reader.read(); - if (step.done) return; - socket.send(encodeTunnelFrame(TUNNEL_TAG.data, conn, step.value)); + while (connection.window === 0) { + await new Promise((wake) => { + connection.wake = wake; + }); + } + if (pending === undefined) { + const step = await reader.read(); + if (step.done) return; + pending = step.value; + } + const size = Math.min(pending.length, connection.window, TUNNEL_MAX_DATA_BYTES); + socket.send(encodeTunnelFrame(TUNNEL_TAG.data, conn, pending.subarray(0, size))); + connection.window -= size; + pending = size === pending.length ? undefined : pending.subarray(size); } } + async function received( + conn: number, + connection: Connection, + payload: Uint8Array, + ): Promise { + await connection.stream.write(payload); + const granted = new Uint8Array(4); + new DataView(granted.buffer).setUint32(0, payload.length); + socket.send(encodeTunnelFrame(TUNNEL_TAG.credit, conn, granted)); + } + async function hello(payload: Uint8Array): Promise { const named = JSON.parse(new TextDecoder().decode(payload)) as { tunnels: Tunnel[] }; const tunnels = named.tunnels.map(({ devicePort, kind }) => ({ kind, devicePort })); @@ -90,7 +125,9 @@ export function createTunnelSessions(options: { const conn = nextConnection; nextConnection += 2; socket.send(encodeTunnelFrame(TUNNEL_TAG.open, conn, JSON.stringify(tunnel))); - void pump(conn, stream); + const connection: Connection = { stream, wake: undefined, window: TUNNEL_WINDOW_BYTES }; + connections.set(conn, connection); + void pump(conn, connection); }); } socket.send(encodeTunnelFrame(TUNNEL_TAG.ready, 0, JSON.stringify({ tunnels }))); @@ -98,7 +135,19 @@ export function createTunnelSessions(options: { socket.onMessage((data) => { const frame = decodeTunnelFrame(data); - if (frame?.tag === TUNNEL_TAG.hello) void hello(frame.payload); + if (frame === undefined) return; + if (frame.tag === TUNNEL_TAG.hello) void hello(frame.payload); + const connection = connections.get(frame.conn); + if (connection === undefined) return; + if (frame.tag === TUNNEL_TAG.data) void received(frame.conn, connection, frame.payload); + if (frame.tag === TUNNEL_TAG.credit) { + connection.window += new DataView( + frame.payload.buffer, + frame.payload.byteOffset, + frame.payload.length, + ).getUint32(0); + connection.wake?.(); + } }); } From 42899a17d32d2686ba2d49c6624b78e3fd18ee2b Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:07:54 -0300 Subject: [PATCH 016/103] test: a bad frame is refused BAD_REQUEST and closed 4003, a frame for a closed connection is ignored (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/tunnel/worker.test.ts | 119 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index 4243476f6..a905b2334 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -35,6 +35,13 @@ function sentData(socket: MemoryLeaseSocket, conn: number): number { .reduce((total, sent) => total + sent.length - 5, 0); } +function bigData(conn: number): Uint8Array { + const bytes = new Uint8Array(5 + 65_536); + bytes[0] = 0x03; + new DataView(bytes.buffer).setUint32(1, conn); + return bytes; +} + function hello(...tunnels: { kind: string; devicePort: number }[]): Uint8Array { return frame(0x01, 0, JSON.stringify({ tunnels })); } @@ -193,4 +200,116 @@ describe("a worker's tunnel socket", () => { true, ); }); + + it("refuses a bad frame with BAD_REQUEST and close 4003, while a frame for an already closed connection is ignored and other connections go on", async () => { + const tunnel = { devicePort: 5173, kind: "reverse" }; + const credit = (conn: number, granted: number): Uint8Array => { + const bytes = new Uint8Array(9); + bytes[0] = 0x04; + const view = new DataView(bytes.buffer); + view.setUint32(1, conn); + view.setUint32(5, granted); + return bytes; + }; + const cases: { + readonly message: string; + readonly ready: boolean; + readonly send: (socket: MemoryLeaseSocket) => void; + }[] = [ + { + message: "a frame came before HELLO", + ready: false, + send: (socket) => socket.receive(frame(0x03, 1, "early")), + }, + { + message: "HELLO is not valid JSON", + ready: false, + send: (socket) => socket.receive(frame(0x01, 0, "{not json")), + }, + { + message: "HELLO must name 1 to 8 tunnels", + ready: false, + send: (socket) => socket.receive(frame(0x01, 0, '{"tunnels":[]}')), + }, + { + message: "HELLO must name 1 to 8 tunnels", + ready: false, + send: (socket) => socket.receive(frame(0x01, 0, '{"tunnels":"all"}')), + }, + { + message: "HELLO is longer than 4096 bytes", + ready: false, + send: (socket) => socket.receive(frame(0x01, 0, ` ${" ".repeat(4096)}{"tunnels":[]}`)), + }, + { + message: "HELLO came twice", + ready: true, + send: (socket) => socket.receive(hello(tunnel)), + }, + { + message: "unknown frame tag 127", + ready: true, + send: (socket) => socket.receive(frame(0x7f, 1)), + }, + { + message: "DATA is past the granted window", + ready: true, + send: (socket) => { + for (let sent = 0; sent < 5; sent += 1) { + socket.receive(bigData(1)); + } + }, + }, + { + message: "connection 99 was never opened", + ready: true, + send: (socket) => socket.receive(frame(0x03, 99, "x")), + }, + { + message: "connection 2 was never opened", + ready: true, + send: (socket) => socket.receive(credit(2, 1)), + }, + { + message: "the window is above 2147483648", + ready: true, + send: (socket) => socket.receive(credit(1, 2 ** 31)), + }, + ]; + for (const bad of cases) { + const { deviceTcp, worker } = await setup(); + const socket = await attach(worker); + if (bad.ready) { + socket.receive(hello(tunnel)); + await vi.waitFor(() => expect(frames(socket)).toHaveLength(1)); + deviceTcp.connect(5173); + await vi.waitFor(() => expect(frames(socket)).toHaveLength(2)); + } + expect(socket.closed).toBeUndefined(); + bad.send(socket); + await vi.waitFor(() => expect(socket.closed).toEqual({ code: 4003, reason: bad.message })); + expect(frames(socket).at(-1)).toEqual({ + body: JSON.stringify({ code: "BAD_REQUEST", message: bad.message }), + conn: 0, + tag: 0x82, + }); + } + + const { deviceTcp, worker } = await setup(); + const socket = await attach(worker); + socket.receive(hello(tunnel)); + await vi.waitFor(() => expect(frames(socket)).toHaveLength(1)); + const closing = deviceTcp.connect(5173); + const going = deviceTcp.connect(5173); + await vi.waitFor(() => expect(frames(socket)).toHaveLength(3)); + socket.receive(frame(0x06, 1, '{"reason":"caller closed"}')); + await vi.waitFor(() => expect(closing.closed).toBe(true)); + socket.receive(credit(1, 10)); + socket.receive(frame(0x03, 1, "late")); + going.send("still here"); + await vi.waitFor(() => + expect(frames(socket).at(-1)).toEqual({ body: "still here", conn: 3, tag: 0x03 }), + ); + expect(socket.closed).toBeUndefined(); + }); }); From 22b171d6c0753d8df68c2e2f7441f054527846d7 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:08:21 -0300 Subject: [PATCH 017/103] feat(daemon): one device input per lease, shared by the input module's sockets and device.rotate (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/AGENTS.md | 37 +++++++------- src/daemon/dispatcher.ts | 54 +++++++++++--------- src/daemon/lease-inputs.ts | 100 +++++++++++++++++++++++++++++++++++++ src/daemon/main.ts | 14 +++--- src/input/AGENTS.md | 28 +++++------ src/input/sessions.ts | 28 ++++++----- src/input/worker.test.ts | 9 +++- src/modules/AGENTS.md | 10 ++-- src/modules/index.ts | 1 + src/modules/testing.ts | 8 ++- src/modules/types.ts | 14 ++++-- 11 files changed, 216 insertions(+), 87 deletions(-) create mode 100644 src/daemon/lease-inputs.ts diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 1e869f459..1aa936000 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -10,24 +10,25 @@ Flows: [startup](../../docs/internal/flows/startup.md), [device.exec](../../docs ## Files -| File | Role | -| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -| `main.ts` | Composition root; worker or gateway; driver discovery; log sinks | -| `server.ts` | `DaemonServer`: framing, `hello`, sessions, pushes, readiness, stop | -| `dispatch.ts` | `runDispatch` pipeline, `DispatchSession`, `DispatchError` | -| `dispatcher.ts` | `Dispatcher`: the worker's handlers | -| `connection-host.ts` | `DaemonEndpointHost`: socket claim, stale-socket recovery | -| `owner-routed-facts.ts` | `OwnerRoutedFactBus`: lease facts with their owner | -| `gateway-uplink.ts` | `GatewayUplink`: a worker's dial to its gateway | -| `openapi.ts` | `openApiDocument`, `writeOpenApiDocument`: the HTTP API document from the module registry; run by `pnpm openapi` | -| `update-coordinator.ts` | `createUpdateCoordinator`: `daemon.update`'s state (`waiting`, `installing`), the updater launch, `status.get`'s update fields | -| `version-check.ts` | `startVersionCheck`: npm's `latest` Simlock version, read at start and every 24 h (`update.check`); `status.get`'s `latestVersion`, both roles | -| `relay.ts` | `RelayTargets`, `RelayConnection`: relays over the uplink | -| `error-code.ts` | `classifyError`: thrown error → contract code | -| `enrollment-wake.ts` | `wakingQueueAfter`: wakes the queue after `device.add`/`device.remove` | -| `rotation-refusal.ts` | `rotationRefusal`: `device.rotate`'s `ROTATION_UNSUPPORTED`, with how it names the device | -| `exec-env.ts` | `execBaseEnvironment`: the allowlisted keys of `process.env` a `device.exec` child starts from | -| `test-relay-support.ts` | Test helpers for relay e2e tests | +| File | Role | +| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `main.ts` | Composition root; worker or gateway; driver discovery; log sinks | +| `server.ts` | `DaemonServer`: framing, `hello`, sessions, pushes, readiness, stop | +| `dispatch.ts` | `runDispatch` pipeline, `DispatchSession`, `DispatchError` | +| `dispatcher.ts` | `Dispatcher`: the worker's handlers | +| `connection-host.ts` | `DaemonEndpointHost`: socket claim, stale-socket recovery | +| `owner-routed-facts.ts` | `OwnerRoutedFactBus`: lease facts with their owner | +| `gateway-uplink.ts` | `GatewayUplink`: a worker's dial to its gateway | +| `openapi.ts` | `openApiDocument`, `writeOpenApiDocument`: the HTTP API document from the module registry; run by `pnpm openapi` | +| `update-coordinator.ts` | `createUpdateCoordinator`: `daemon.update`'s state (`waiting`, `installing`), the updater launch, `status.get`'s update fields | +| `version-check.ts` | `startVersionCheck`: npm's `latest` Simlock version, read at start and every 24 h (`update.check`); `status.get`'s `latestVersion`, both roles | +| `relay.ts` | `RelayTargets`, `RelayConnection`: relays over the uplink | +| `error-code.ts` | `classifyError`: thrown error → contract code | +| `enrollment-wake.ts` | `wakingQueueAfter`: wakes the queue after `device.add`/`device.remove` | +| `lease-inputs.ts` | `createLeaseInputs`: the per-lease device input shared by the input module's sockets and `device.rotate`; closed by its last release, its failure or the lease's end | +| `rotation-refusal.ts` | `rotationRefusal`: `device.rotate`'s `ROTATION_UNSUPPORTED`, with how it names the device | +| `exec-env.ts` | `execBaseEnvironment`: the allowlisted keys of `process.env` a `device.exec` child starts from | +| `test-relay-support.ts` | Test helpers for relay e2e tests | ## Composition (`main.ts`) diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 7cfb0825b..e08a4333b 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -644,25 +644,10 @@ export class Dispatcher { return {}; }; - /** - * why: ADR 0005 §19a: the same command `driver.passthrough` would have handed back, run here - * instead of there. Everything a passthrough already decides is reused verbatim -- which - * flag scopes the tool to this daemon's root, which verbs the driver refuses -- because it - * is the same driver call: `#driverPassthrough` above passes no device, this handler passes - * the lease's device and the lease's platform, and it also spawns the result. - * - * `leaseId` is checked against the registry here so an id that names no lease answers - * `UNKNOWN_LEASE` rather than running a command (`authorize`'s `ownsLease` deliberately lets - * an unknown id through so this handler can say that -- see `roles.ts`). Which device the - * command touches is the driver's answer: it fills the lease's device in where the tool - * expects it and refuses a command that names another (ADR 0047 §1-2); this daemon parses - * none of the arguments. That is the same accident boundary ADR 0001 draws for the local - * wrappers, reached over the wire. - * - * Nothing is buffered: each chunk goes straight to `session.onOutput` as it arrives (§19e), - * so a command that writes a gigabyte costs this process nothing, and a client sees the - * first line while the command is still running. - */ + #leaseIsActive(leaseId: string): boolean { + return this.options.registry.snapshot.leases.some((candidate) => candidate.id === leaseId); + } + #deviceRotate: Handler<"device.rotate"> = async (input) => { if (this.options.inputs === undefined) { throw new DispatchError("INTERNAL", "Device input is unavailable"); @@ -678,23 +663,44 @@ export class Dispatcher { const refusal = rotationRefusal(input.leaseId, record.spec); if (refusal !== undefined) throw refusal; try { - const opened = await this.options.inputs.openInput( + const held = await this.options.inputs.leaseInput( + input.leaseId, record.spec.platform, toDriverDevice(record), - new AbortController().signal, ); - if (isUnavailableInput(opened)) throw new Error(opened.unavailable); try { - await opened.send({ kind: "orientation", orientation: input.orientation }); + if (isUnavailableInput(held.input)) throw new Error(held.input.unavailable); + if (!this.#leaseIsActive(input.leaseId)) throw new UnknownLeaseError(input.leaseId); + await held.input.send({ kind: "orientation", orientation: input.orientation }); } finally { - await opened.close(); + held.release(); } } catch (error) { + if (error instanceof UnknownLeaseError) throw error; throw inputUnavailable(input.leaseId, error); } return { leaseId: input.leaseId, orientation: input.orientation }; }; + /** + * why: ADR 0005 §19a: the same command `driver.passthrough` would have handed back, run here + * instead of there. Everything a passthrough already decides is reused verbatim -- which + * flag scopes the tool to this daemon's root, which verbs the driver refuses -- because it + * is the same driver call: `#driverPassthrough` above passes no device, this handler passes + * the lease's device and the lease's platform, and it also spawns the result. + * + * `leaseId` is checked against the registry here so an id that names no lease answers + * `UNKNOWN_LEASE` rather than running a command (`authorize`'s `ownsLease` deliberately lets + * an unknown id through so this handler can say that -- see `roles.ts`). Which device the + * command touches is the driver's answer: it fills the lease's device in where the tool + * expects it and refuses a command that names another (ADR 0047 §1-2); this daemon parses + * none of the arguments. That is the same accident boundary ADR 0001 draws for the local + * wrappers, reached over the wire. + * + * Nothing is buffered: each chunk goes straight to `session.onOutput` as it arrives (§19e), + * so a command that writes a gigabyte costs this process nothing, and a client sees the + * first line while the command is still running. + */ #deviceExec: Handler<"device.exec"> = async (input, session) => { if (this.options.passthrough === undefined) { throw new DispatchError("INTERNAL", "Tool passthrough is unavailable"); diff --git a/src/daemon/lease-inputs.ts b/src/daemon/lease-inputs.ts new file mode 100644 index 000000000..89ab16c4e --- /dev/null +++ b/src/daemon/lease-inputs.ts @@ -0,0 +1,100 @@ +import { + isUnavailableInput, + type DeviceInput, + type PhysicalDriverDevice, + type UnavailableDeviceInput, + type VirtualDriverDevice, +} from "../core/index.js"; +import type { ModuleInputs, ModuleLeaseEndParticipant } from "../modules/index.js"; +import type { Platform } from "../core/index.js"; + +interface Entry { + readonly opening: Promise; + users: number; + closed: boolean; +} + +export interface LeaseInputs extends ModuleInputs { + readonly leaseEnd: ModuleLeaseEndParticipant; +} + +/** + * why: ADR 0053 §1-6: the daemon keeps one device input per lease, shared by the input module's sockets and `device.rotate`, so two users of one lease never start two controllers on one device. The last user to release closes it; a failure or the lease's end drops it, and the next user opens a fresh one. + */ +export function createLeaseInputs(options: { + readonly openInput: ( + platform: Platform, + device: VirtualDriverDevice | PhysicalDriverDevice, + signal: AbortSignal, + ) => Promise; +}): LeaseInputs { + const entries = new Map(); + + // why: every end of a lease's input -- the last release, its failure, the lease's end -- goes through here, so it closes once, and an input still opening closes when it has opened. + function close(leaseId: string, entry: Entry): void { + if (entry.closed) return; + entry.closed = true; + if (entries.get(leaseId) === entry) entries.delete(leaseId); + void entry.opening + .then((opened) => (isUnavailableInput(opened) ? undefined : opened.close())) + .catch(() => undefined); + } + + function create( + leaseId: string, + platform: Platform, + device: VirtualDriverDevice | PhysicalDriverDevice, + ): Entry { + const entry: Entry = { + closed: false, + opening: options.openInput(platform, device, new AbortController().signal).then( + (opened) => { + if (isUnavailableInput(opened)) { + if (entries.get(leaseId) === entry) entries.delete(leaseId); + } else { + opened.onFailed(() => close(leaseId, entry)); + } + return opened; + }, + (error: unknown) => { + if (entries.get(leaseId) === entry) entries.delete(leaseId); + throw error; + }, + ), + users: 0, + }; + entries.set(leaseId, entry); + return entry; + } + + return { + leaseEnd: { + leaseEnded: (ended) => { + const entry = entries.get(ended.leaseId); + if (entry !== undefined) close(ended.leaseId, entry); + return Promise.resolve(); + }, + }, + leaseInput: async (leaseId, platform, device) => { + const entry = entries.get(leaseId) ?? create(leaseId, platform, device); + entry.users += 1; + let input: DeviceInput | UnavailableDeviceInput; + try { + input = await entry.opening; + } catch (error) { + entry.users -= 1; + throw error; + } + let released = false; + return { + input, + release: () => { + if (released) return; + released = true; + entry.users -= 1; + if (entry.users === 0) close(leaseId, entry); + }, + }; + }, + }; +} diff --git a/src/daemon/main.ts b/src/daemon/main.ts index dded5b301..3fbe8e510 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -135,6 +135,7 @@ import { WebSocketUplinkListenerFactory, } from "../ports/uplink-websocket.js"; import { classifyError } from "./error-code.js"; +import { createLeaseInputs } from "./lease-inputs.js"; import { createModuleHost, type OptionalModuleDefinition } from "../modules/index.js"; import { optionalModules } from "../module-registry/index.js"; import { DaemonServer } from "./server.js"; @@ -492,6 +493,9 @@ async function composeDaemon( // why: a module's context is built before leasing exists, so `cancelPending` answers only once leasing does. let cancelPendingRequest: ((requesterId: string) => Promise) | undefined; const catalog = new DriverCatalog(drivers); + const leaseInputs = createLeaseInputs({ + openInput: (platform, device, signal) => catalog.openInput(platform, device, signal), + }); const moduleHost = await createModuleHost({ config, defaulted, @@ -516,9 +520,7 @@ async function composeDaemon( processRunner, processSupervisor, registry, - inputs: { - openInput: (platform, device, signal) => catalog.openInput(platform, device, signal), - }, + inputs: leaseInputs, screens: catalog, tcpProbe, }, @@ -536,7 +538,7 @@ async function composeDaemon( describeFailure: describeLeaseRequestFailure, eventBus, idGenerator, - leaseEndParticipants: [...moduleHost.leaseEndParticipants], + leaseEndParticipants: [leaseInputs.leaseEnd, ...moduleHost.leaseEndParticipants], logger, modelPreferences, }); @@ -665,9 +667,7 @@ async function composeDaemon( logger: logger.child("server"), ...(options.protocolVersion === undefined ? {} : { protocolVersion: options.protocolVersion }), passthrough: core.catalog, - inputs: { - openInput: (platform, device, signal) => catalog.openInput(platform, device, signal), - }, + inputs: leaseInputs, processRunner, execEnv: execBaseEnvironment(process.env), queue: leasing, diff --git a/src/input/AGENTS.md b/src/input/AGENTS.md index 478becd14..83d6096ff 100644 --- a/src/input/AGENTS.md +++ b/src/input/AGENTS.md @@ -9,18 +9,18 @@ Off unless `capabilities.input.enabled` (false). Off: nothing loaded, and the `i ## Files -| File | Role | -| ----------------- | ---------------------------------------------------------------------------------------------- | -| `definition.ts` | `inputModule`: name `input`, empty config section, `http` route data, the two loaders | -| `worker.ts` | The worker side from the host's context: capability, hooks, lease route, socket, relay | -| `gateway.ts` | The gateway side: lease route, socket, `beforeDrain` | -| `create.ts` | The two factories; the 426 lease route | -| `worker-link.ts` | Worker: finds the lease in the registry; the socket door and the relay door, both to a session | -| `sessions.ts` | Worker: one device input per lease, its sockets, config, failure, lease end, drain | -| `channel.ts` | Worker: a relay channel as a `LeaseSocket`; heartbeat, `0xF1` close | -| `gateway-link.ts` | Gateway: the relay open, refusals, one bridge per socket, lease-gone wait, drain | -| `framing.ts` | `[len u32][tag u8][payload]` frames, `readFrames`, the `0xF0` and `0xF1` tags | -| `refusal.ts` | The 404, 426 and 503 bodies | +| File | Role | +| ----------------- | ------------------------------------------------------------------------------------------------------- | +| `definition.ts` | `inputModule`: name `input`, empty config section, `http` route data, the two loaders | +| `worker.ts` | The worker side from the host's context: capability, hooks, lease route, socket, relay | +| `gateway.ts` | The gateway side: lease route, socket, `beforeDrain` | +| `create.ts` | The two factories; the 426 lease route | +| `worker-link.ts` | Worker: finds the lease in the registry; the socket door and the relay door, both to a session | +| `sessions.ts` | Worker: one hold on the daemon's device input per lease, its sockets, config, failure, lease end, drain | +| `channel.ts` | Worker: a relay channel as a `LeaseSocket`; heartbeat, `0xF1` close | +| `gateway-link.ts` | Gateway: the relay open, refusals, one bridge per socket, lease-gone wait, drain | +| `framing.ts` | `[len u32][tag u8][payload]` frames, `readFrames`, the `0xF0` and `0xF1` tags | +| `refusal.ts` | The 404, 426 and 503 bodies | ## How it works @@ -31,8 +31,8 @@ lease id; the worker's `relayTwoWay` finds the lease and attaches a `channelSock gateway's accept carries `abandon` (`gateway-link.ts`), which the router calls when the handshake is refused after the relay opened. 1. Worker session (`sessions.ts` `attach`): a lease gone from the registry → close 4001 `lease ended`; a failed - open within 10 s → close 1013; 8 sockets already → close 1013. Else it opens the lease's one device input - (`ctx.inputs.openInput`, shared by every socket) and, once open, sends `0x83` then `0x82`. + open within 10 s → close 1013; 8 sockets already → close 1013. Else it takes the lease's one device input + (`ctx.inputs.leaseInput`, the daemon's, shared by every socket and by `device.rotate`) and, once open, sends `0x83` then `0x82`. 2. `0x82` is the device input's `onConfig` (called at once, then on each change) and goes to every admitted socket. An unavailable device input sends `{"width":1,"height":1,"orientation":"portrait","inputUnavailable":true}` and drops messages. 3. Client messages go through `parseClientMessage` (core): bad JSON, an unknown tag, a position outside 0..1, diff --git a/src/input/sessions.ts b/src/input/sessions.ts index bf03daa30..68c0f1591 100644 --- a/src/input/sessions.ts +++ b/src/input/sessions.ts @@ -10,7 +10,7 @@ import { type InputScreenConfig, type UnavailableDeviceInput, } from "../core/index.js"; -import type { ModuleInputs } from "../modules/index.js"; +import type { LeaseInputHandle, ModuleInputs } from "../modules/index.js"; import type { Clock, LeaseSocket } from "../ports/index.js"; const MAX_SOCKETS_PER_LEASE = 8; @@ -33,6 +33,8 @@ interface LeaseInput { // why: set once the device input has opened, so an end that finds it open closes it at once instead of after a wait. device: DeviceInput | undefined; readonly opening: Promise; + // why: set with `device`; the entry's one hold on the daemon's shared input, given back when the last socket leaves or the input fails. + handle: LeaseInputHandle | undefined; readonly sockets: Set; config: InputScreenConfig | undefined; closed: boolean; @@ -53,11 +55,11 @@ export function createInputSessions(options: { const failedOpens = new Map(); // why: every end of a lease's device input -- its last socket leaving, its own failure -- goes through here, so it closes once. - function release(leaseId: string, entry: LeaseInput, opened: DeviceInput): void { + function release(leaseId: string, entry: LeaseInput): void { if (entry.closed) return; entry.closed = true; if (leases.get(leaseId) === entry) leases.delete(leaseId); - void opened.close(); + entry.handle?.release(); } // why: an unavailable device input has nothing to close, so its entry is dropped at once instead of staying for the daemon's lifetime. @@ -68,14 +70,14 @@ export function createInputSessions(options: { // why: `unlessJoined` is the last socket leaving: a socket that joined while the input was still opening keeps it, so the close that waited for the open drops out. function releaseWhenOpen(leaseId: string, entry: LeaseInput, unlessJoined = false): void { if (entry.device !== undefined) { - release(leaseId, entry, entry.device); + release(leaseId, entry); return; } void entry.opening.then( (opened) => { if (unlessJoined && entry.sockets.size > 0) return; if (isUnavailableInput(opened)) forget(leaseId, entry); - else release(leaseId, entry, opened); + else release(leaseId, entry); }, () => undefined, ); @@ -105,15 +107,17 @@ export function createInputSessions(options: { closed: false, config: undefined, device: undefined, + handle: undefined, opening: options.inputs - .openInput(device.spec.platform, toDriverDevice(device), new AbortController().signal) + .leaseInput(leaseId, device.spec.platform, toDriverDevice(device)) .then( - (opened) => { - if (!isUnavailableInput(opened)) { - entry.device = opened; - wire(leaseId, entry, opened); + (handle) => { + entry.handle = handle; + if (!isUnavailableInput(handle.input)) { + entry.device = handle.input; + wire(leaseId, entry, handle.input); } - return opened; + return handle.input; }, (error: unknown) => { failedOpens.set(leaseId, options.clock.now()); @@ -135,7 +139,7 @@ export function createInputSessions(options: { } }); opened.onFailed(() => { - release(leaseId, entry, opened); + release(leaseId, entry); for (const attached of entry.sockets) attached.socket.close(CLOSE_FAILED, REASON_FAILED); }); } diff --git a/src/input/worker.test.ts b/src/input/worker.test.ts index d29781992..c7ec24388 100644 --- a/src/input/worker.test.ts +++ b/src/input/worker.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest"; -import type { DeviceRecord, LeaseRecord } from "../core/index.js"; +import { isUnavailableInput, type DeviceRecord, type LeaseRecord } from "../core/index.js"; import { FakeInputFactory } from "../core/testing.js"; import type { ModuleEndedLease, WorkerModule } from "../modules/index.js"; import { fakeWorkerContext } from "../modules/testing.js"; @@ -32,7 +32,12 @@ async function setup(): Promise<{ const loaded = await inputModule.loadWorker(); const worker = loaded.createWorker({ ...ctx, - inputs: { openInput: () => factory.open() }, + inputs: { + leaseInput: async () => { + const input = await factory.open(); + return { input, release: () => void (isUnavailableInput(input) || input.close()) }; + }, + }, registry, }); return { clock, factory, leases, worker }; diff --git a/src/modules/AGENTS.md b/src/modules/AGENTS.md index fd888657c..057ed9b5b 100644 --- a/src/modules/AGENTS.md +++ b/src/modules/AGENTS.md @@ -7,11 +7,11 @@ Imported by: `daemon/main.ts` (the factory and types); on a gateway it is handed ## Files -| File | Role | -| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `types.ts` | `OptionalModuleDefinition` (with optional `http` route data, read only by the OpenAPI document, and optional `localProfile` data), `ModuleTokens`, `ModuleConfig`, `WorkerModule`, `WorkerHooks`, `ModuleLease`, `ModuleLeaseHandler` (a module's lease handler, `leaseRoute` on both sides), `ModuleLeaseSocketHandler` (`socket` on both sides: `open` answers a refusal `Response` or an accept that gets the socket), `ModuleInputs` (`WorkerContext.inputs`), `WorkerContext`, the by-shape copies | -| `host.ts` | `createModuleHost`: checks names, loads turned-on modules (`role: "worker"` or `"gateway"`), runs hooks, collects each module's `mount` and `leaseRoute`, and on a worker `prepareLocalProfiles` (below); a gateway host runs `beforeDrain` under the same 30 s deadline | -| `testing.ts` | Fake module and context for tests and the conformance suite | +| File | Role | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `types.ts` | `OptionalModuleDefinition` (with optional `http` route data, read only by the OpenAPI document, and optional `localProfile` data), `ModuleTokens`, `ModuleConfig`, `WorkerModule`, `WorkerHooks`, `ModuleLease`, `ModuleLeaseHandler` (a module's lease handler, `leaseRoute` on both sides), `ModuleLeaseSocketHandler` (`socket` on both sides: `open` answers a refusal `Response` or an accept that gets the socket), `ModuleInputs`, `LeaseInputHandle` (`WorkerContext.inputs`: the daemon's per-lease device input, held and released), `WorkerContext`, the by-shape copies | +| `host.ts` | `createModuleHost`: checks names, loads turned-on modules (`role: "worker"` or `"gateway"`), runs hooks, collects each module's `mount` and `leaseRoute`, and on a worker `prepareLocalProfiles` (below); a gateway host runs `beforeDrain` under the same 30 s deadline | +| `testing.ts` | Fake module and context for tests and the conformance suite | ## Rules diff --git a/src/modules/index.ts b/src/modules/index.ts index bb4063d71..3a1ab0c40 100644 --- a/src/modules/index.ts +++ b/src/modules/index.ts @@ -13,6 +13,7 @@ export type { ModuleFinding, ModuleHttpResponse, ModuleIdentity, + LeaseInputHandle, ModuleInputs, ModuleLease, ModuleLeaseEndParticipant, diff --git a/src/modules/testing.ts b/src/modules/testing.ts index 17766ced7..de83307f9 100644 --- a/src/modules/testing.ts +++ b/src/modules/testing.ts @@ -191,7 +191,13 @@ export async function fakeWorkerContext(name: string, config: C): Promise Promise.resolve({ unavailable: "no input in a fake context" }) }, + inputs: { + leaseInput: () => + Promise.resolve({ + input: { unavailable: "no input in a fake context" }, + release: () => undefined, + }), + }, screens: { openScreen: () => Promise.reject(new Error("no screen in a fake context")), screenAvailability: () => Promise.resolve([]), diff --git a/src/modules/types.ts b/src/modules/types.ts index 1a34d940c..46552e01d 100644 --- a/src/modules/types.ts +++ b/src/modules/types.ts @@ -187,13 +187,19 @@ export interface ModuleScreens { screenAvailability(): Promise; } -// why: the drivers' device input, routed by platform, without handing a module the drivers. +// why: one user's hold on a lease's shared device input; `release` is how the user says it is done, and the last release closes the input. +export interface LeaseInputHandle { + readonly input: DeviceInput | UnavailableDeviceInput; + release(): void; +} + +// why: the daemon's device input per lease, shared by every user of it (the input module's sockets and `device.rotate`), without handing a module the drivers. export interface ModuleInputs { - openInput( + leaseInput( + leaseId: string, platform: Platform, device: VirtualDriverDevice | PhysicalDriverDevice, - signal: AbortSignal, - ): Promise; + ): Promise; } export interface WorkerContext { From 0751cc129d8971e3730da2e5a7fee50d8997a1ac Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:09:00 -0300 Subject: [PATCH 018/103] feat(tunnel): a bad frame is refused BAD_REQUEST with close 4003 (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/tunnel-frames.ts | 3 + src/tunnel/sessions.ts | 186 ++++++++++++++++++++++++++-------- 2 files changed, 147 insertions(+), 42 deletions(-) diff --git a/src/contract/tunnel-frames.ts b/src/contract/tunnel-frames.ts index aa89bf9eb..5b1fecebf 100644 --- a/src/contract/tunnel-frames.ts +++ b/src/contract/tunnel-frames.ts @@ -8,6 +8,7 @@ export const TUNNEL_TAG = { open: 0x02, ready: 0x81, refused: 0x82, + reset: 0x06, } as const; export interface TunnelFrame { @@ -47,3 +48,5 @@ export const TUNNEL_REFUSED_CLOSE = 4003; export const TUNNEL_WINDOW_BYTES = 262_144; export const TUNNEL_MAX_DATA_BYTES = 65_536; +export const TUNNEL_WINDOW_LIMIT = 2 ** 31; +export const TUNNEL_HELLO_MAX_BYTES = 4096; diff --git a/src/tunnel/sessions.ts b/src/tunnel/sessions.ts index 62228b02b..d6fcea393 100644 --- a/src/tunnel/sessions.ts +++ b/src/tunnel/sessions.ts @@ -1,6 +1,7 @@ import { decodeTunnelFrame, encodeTunnelFrame, + TUNNEL_HELLO_MAX_BYTES, TUNNEL_MAX_DATA_BYTES, TUNNEL_MAX_DEVICE_PORT, TUNNEL_MAX_TUNNELS, @@ -8,6 +9,8 @@ import { TUNNEL_REFUSED_CLOSE, TUNNEL_TAG, TUNNEL_WINDOW_BYTES, + TUNNEL_WINDOW_LIMIT, + type TunnelFrame, } from "../contract/index.js"; import { toDriverDevice, type DeviceRecord } from "../core/index.js"; import type { ModuleDeviceTcp } from "../modules/index.js"; @@ -22,6 +25,9 @@ interface Connection { readonly stream: TcpStream; // why: how many bytes the worker may still send before the caller grants more credit. window: number; + // why: how many bytes the caller may still send before the worker grants more credit. + inbound: number; + closed: boolean; wake: (() => void) | undefined; } @@ -30,6 +36,60 @@ interface Refusal { readonly message: string; } +function field(value: unknown, name: string): unknown { + return typeof value === "object" && value !== null ? Reflect.get(value, name) : undefined; +} + +// why: the HELLO is wire input from a holder, so its size and shape are checked before any of it is used; a string is what was wrong with it. +function parseHello(payload: Uint8Array): readonly Tunnel[] | string { + if (payload.length > TUNNEL_HELLO_MAX_BYTES) { + return `HELLO is longer than ${String(TUNNEL_HELLO_MAX_BYTES)} bytes`; + } + let parsed: unknown; + try { + parsed = JSON.parse(new TextDecoder().decode(payload)); + } catch { + return "HELLO is not valid JSON"; + } + const named = field(parsed, "tunnels"); + if (!Array.isArray(named) || named.length === 0) return "HELLO must name 1 to 8 tunnels"; + const tunnels: Tunnel[] = []; + for (const entry of named) { + const kind = field(entry, "kind"); + const devicePort = field(entry, "devicePort"); + if ( + (kind !== "reverse" && kind !== "forward") || + typeof devicePort !== "number" || + !Number.isInteger(devicePort) + ) { + return "HELLO tunnels must each be {kind, devicePort}"; + } + tunnels.push({ devicePort, kind }); + } + return tunnels; +} + +function refusal(tunnels: readonly Tunnel[], held: number): Refusal | undefined { + if (held + tunnels.length > TUNNEL_MAX_TUNNELS) { + return { + code: "TUNNEL_LIMIT", + message: `the lease already has ${String(held + tunnels.length)} tunnels; at most ${String(TUNNEL_MAX_TUNNELS)}`, + }; + } + for (const { devicePort, kind } of tunnels) { + if (devicePort < TUNNEL_MIN_DEVICE_PORT || devicePort > TUNNEL_MAX_DEVICE_PORT) { + return { + code: "TUNNEL_BAD_PORT", + message: `${kind} ${String(devicePort)}: device ports are ${String(TUNNEL_MIN_DEVICE_PORT)} to ${String(TUNNEL_MAX_DEVICE_PORT)}`, + }; + } + } + if (tunnels.some(({ kind }) => kind === "forward")) { + return { code: "TUNNEL_UNSUPPORTED", message: "forward tunnels are not available yet" }; + } + return undefined; +} + export interface TunnelSessions { attach(leaseId: string, device: DeviceRecord, socket: LeaseSocket): void; } @@ -40,34 +100,9 @@ export function createTunnelSessions(options: { // why: the 8-tunnel limit counts every socket of one lease, so the count is the lease's, not the socket's. const counts = new Map(); - function refusal(tunnels: readonly Tunnel[], held: number): Refusal | undefined { - if (held + tunnels.length > TUNNEL_MAX_TUNNELS) { - return { - code: "TUNNEL_LIMIT", - message: `the lease already has ${String(held + tunnels.length)} tunnels; at most ${String(TUNNEL_MAX_TUNNELS)}`, - }; - } - for (const { devicePort, kind } of tunnels) { - if ( - !Number.isInteger(devicePort) || - devicePort < TUNNEL_MIN_DEVICE_PORT || - devicePort > TUNNEL_MAX_DEVICE_PORT - ) { - return { - code: "TUNNEL_BAD_PORT", - message: `${kind} ${String(devicePort)}: device ports are ${String(TUNNEL_MIN_DEVICE_PORT)} to ${String(TUNNEL_MAX_DEVICE_PORT)}`, - }; - } - } - if (tunnels.some(({ kind }) => kind === "forward")) { - return { code: "TUNNEL_UNSUPPORTED", message: "forward tunnels are not available yet" }; - } - return undefined; - } - function attach(leaseId: string, device: DeviceRecord, socket: LeaseSocket): void { let nextConnection = 1; - + let greeted = false; const connections = new Map(); // why: a connection reads from its device stream only while the caller has granted window, so a slow reader stops its own connection and no other. @@ -79,6 +114,7 @@ export function createTunnelSessions(options: { await new Promise((wake) => { connection.wake = wake; }); + if (connection.closed) return; } if (pending === undefined) { const step = await reader.read(); @@ -92,25 +128,38 @@ export function createTunnelSessions(options: { } } + function refuse(refused: Refusal): void { + socket.send(encodeTunnelFrame(TUNNEL_TAG.refused, 0, JSON.stringify(refused))); + socket.close(TUNNEL_REFUSED_CLOSE, refused.message); + } + + function badRequest(message: string): void { + refuse({ code: "BAD_REQUEST", message }); + } + async function received( conn: number, connection: Connection, payload: Uint8Array, ): Promise { await connection.stream.write(payload); + connection.inbound += payload.length; const granted = new Uint8Array(4); new DataView(granted.buffer).setUint32(0, payload.length); socket.send(encodeTunnelFrame(TUNNEL_TAG.credit, conn, granted)); } async function hello(payload: Uint8Array): Promise { - const named = JSON.parse(new TextDecoder().decode(payload)) as { tunnels: Tunnel[] }; - const tunnels = named.tunnels.map(({ devicePort, kind }) => ({ kind, devicePort })); + const named = parseHello(payload); + if (typeof named === "string") { + badRequest(named); + return; + } + const tunnels = named.map(({ devicePort, kind }) => ({ kind, devicePort })); const held = counts.get(leaseId) ?? 0; const refused = refusal(tunnels, held); if (refused !== undefined) { - socket.send(encodeTunnelFrame(TUNNEL_TAG.refused, 0, JSON.stringify(refused))); - socket.close(TUNNEL_REFUSED_CLOSE, refused.message); + refuse(refused); return; } counts.set(leaseId, held + tunnels.length); @@ -125,7 +174,13 @@ export function createTunnelSessions(options: { const conn = nextConnection; nextConnection += 2; socket.send(encodeTunnelFrame(TUNNEL_TAG.open, conn, JSON.stringify(tunnel))); - const connection: Connection = { stream, wake: undefined, window: TUNNEL_WINDOW_BYTES }; + const connection: Connection = { + closed: false, + inbound: TUNNEL_WINDOW_BYTES, + stream, + wake: undefined, + window: TUNNEL_WINDOW_BYTES, + }; connections.set(conn, connection); void pump(conn, connection); }); @@ -133,21 +188,68 @@ export function createTunnelSessions(options: { socket.send(encodeTunnelFrame(TUNNEL_TAG.ready, 0, JSON.stringify({ tunnels }))); } - socket.onMessage((data) => { - const frame = decodeTunnelFrame(data); - if (frame === undefined) return; - if (frame.tag === TUNNEL_TAG.hello) void hello(frame.payload); + function onData(conn: number, connection: Connection, payload: Uint8Array): void { + if (payload.length > connection.inbound) { + badRequest("DATA is past the granted window"); + return; + } + connection.inbound -= payload.length; + void received(conn, connection, payload); + } + + function onCredit(connection: Connection, payload: Uint8Array): void { + const granted = new DataView(payload.buffer, payload.byteOffset, payload.length).getUint32(0); + if (connection.window + granted > TUNNEL_WINDOW_LIMIT) { + badRequest(`the window is above ${String(TUNNEL_WINDOW_LIMIT)}`); + return; + } + connection.window += granted; + connection.wake?.(); + } + + function handle(frame: TunnelFrame): void { + if (!greeted) { + if (frame.tag !== TUNNEL_TAG.hello) { + badRequest("a frame came before HELLO"); + return; + } + greeted = true; + void hello(frame.payload); + return; + } + if (frame.tag === TUNNEL_TAG.hello) { + badRequest("HELLO came twice"); + return; + } + if ( + frame.tag !== TUNNEL_TAG.data && + frame.tag !== TUNNEL_TAG.credit && + frame.tag !== TUNNEL_TAG.reset + ) { + badRequest(`unknown frame tag ${String(frame.tag)}`); + return; + } + // why: the worker opens odd ids, rising from 1, so an even id or one above the last it opened was never a connection; one it opened and closed is ignored. + if (frame.conn % 2 === 0 || frame.conn > nextConnection - 2) { + badRequest(`connection ${String(frame.conn)} was never opened`); + return; + } const connection = connections.get(frame.conn); if (connection === undefined) return; - if (frame.tag === TUNNEL_TAG.data) void received(frame.conn, connection, frame.payload); - if (frame.tag === TUNNEL_TAG.credit) { - connection.window += new DataView( - frame.payload.buffer, - frame.payload.byteOffset, - frame.payload.length, - ).getUint32(0); + if (frame.tag === TUNNEL_TAG.data) onData(frame.conn, connection, frame.payload); + else if (frame.tag === TUNNEL_TAG.credit) onCredit(connection, frame.payload); + else { + connection.closed = true; + connection.stream.close(); connection.wake?.(); + connections.delete(frame.conn); } + } + + socket.onMessage((data) => { + const frame = decodeTunnelFrame(data); + if (frame === undefined) badRequest("a frame is shorter than its 5-byte header"); + else handle(frame); }); } From 7afdb401460e15bb48e39c014ddd0f7c3cc9573c Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:09:42 -0300 Subject: [PATCH 019/103] test: the worker removes a tunnel's rules and closes its connections when the socket closes, the lease ends or the daemon stops (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/core/fake-device-tcp.ts | 15 +++++-- src/tunnel/worker.test.ts | 82 +++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+), 3 deletions(-) diff --git a/src/core/fake-device-tcp.ts b/src/core/fake-device-tcp.ts index 7586b4ff2..58a8ed0a6 100644 --- a/src/core/fake-device-tcp.ts +++ b/src/core/fake-device-tcp.ts @@ -8,6 +8,7 @@ class FakeReverse implements DeviceReverse { constructor( readonly hostPort: number, private readonly onClose: () => void, + private readonly failure: () => Error | undefined, ) {} onConnection(listener: (stream: TcpStream) => void): void { @@ -15,6 +16,8 @@ class FakeReverse implements DeviceReverse { } async close(): Promise { + const failure = this.failure(); + if (failure !== undefined) throw failure; this.closed = true; this.onClose(); } @@ -27,6 +30,8 @@ class FakeReverse implements DeviceReverse { // why: a driver's `deviceTcp` member for tests: `reversed` holds the device ports whose rule is set, // and `connect` plays the device opening a connection to one of them. export class FakeDeviceTcp implements DeviceTcp { + // why: a test sets this to make every rule removal fail, as an adb that does not answer does. + closeFailure: Error | undefined; readonly #reverses = new Map(); #nextHostPort = 47_000; @@ -41,9 +46,13 @@ export class FakeDeviceTcp implements DeviceTcp { ): Promise { const hostPort = this.#nextHostPort; this.#nextHostPort += 1; - const reverse = new FakeReverse(hostPort, () => { - this.#reverses.delete(devicePort); - }); + const reverse = new FakeReverse( + hostPort, + () => { + this.#reverses.delete(devicePort); + }, + () => this.closeFailure, + ); this.#reverses.set(devicePort, reverse); return reverse; } diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index a905b2334..9c9c2da65 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -312,4 +312,86 @@ describe("a worker's tunnel socket", () => { ); expect(socket.closed).toBeUndefined(); }); + + it("removes the tunnel's rules and closes its connections when the socket closes, the lease ends or the daemon stops, and keeps going when a removal fails", async () => { + const tunnel = { devicePort: 5173, kind: "reverse" }; + async function open(): Promise<{ + readonly deviceTcp: FakeDeviceTcp; + readonly worker: WorkerModule; + readonly socket: MemoryLeaseSocket; + readonly device: ReturnType; + }> { + const { deviceTcp, worker } = await setup(); + const socket = await attach(worker); + socket.receive(hello(tunnel)); + await vi.waitFor(() => expect(frames(socket)).toHaveLength(1)); + const device = deviceTcp.connect(5173); + await vi.waitFor(() => expect(frames(socket)).toHaveLength(2)); + return { device, deviceTcp, socket, worker }; + } + + const client = await open(); + client.socket.drop(); + await vi.waitFor(() => expect(client.deviceTcp.reversed).toEqual([])); + expect(client.device.closed).toBe(true); + const again = await attach(client.worker); + again.receive( + hello( + ...Array.from({ length: 8 }, (_, index) => ({ devicePort: 6000 + index, kind: "reverse" })), + ), + ); + await vi.waitFor(() => expect(frames(again).map((sent) => sent.tag)).toEqual([0x81])); + + const ended = await open(); + await ended.worker.hooks?.beforeDeviceReclaim?.( + { + deviceId: "dev_1", + leaseId: "L-1", + ownerId: "tok_holder", + platform: "android", + reason: "expired", + }, + new AbortController().signal, + ); + expect(ended.deviceTcp.reversed).toEqual([]); + expect(ended.device.closed).toBe(true); + expect(ended.socket.closed).toEqual({ code: 4001, reason: "expired" }); + + const stopped = await open(); + await stopped.worker.hooks?.beforeDrain?.(); + expect(stopped.deviceTcp.reversed).toEqual([]); + expect(stopped.device.closed).toBe(true); + expect(stopped.socket.closed).toEqual({ code: 1001, reason: "Simlock is stopping" }); + + const failing = await open(); + failing.deviceTcp.closeFailure = new Error("adb did not answer"); + await failing.worker.hooks?.beforeDeviceReclaim?.( + { + deviceId: "dev_1", + leaseId: "L-1", + ownerId: "tok_holder", + platform: "android", + reason: "killed", + }, + new AbortController().signal, + ); + expect(failing.socket.closed).toEqual({ code: 4001, reason: "killed" }); + expect(failing.device.closed).toBe(true); + + const reclaimed = await open(); + const aborted = new AbortController(); + aborted.abort(); + await reclaimed.worker.hooks?.beforeDeviceReclaim?.( + { + deviceId: "dev_1", + leaseId: "L-1", + ownerId: "tok_holder", + platform: "android", + reason: "device-lost", + }, + aborted.signal, + ); + expect(reclaimed.socket.closed).toEqual({ code: 4001, reason: "device-lost" }); + expect(reclaimed.deviceTcp.reversed).toEqual([5173]); + }); }); From 736d3baf467130e48167b12ad49e91625ef585cf Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:10:46 -0300 Subject: [PATCH 020/103] test: a client program calls client.rotate(leaseId, orientation) and gets the op's output (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/admin/index.ts | 2 ++ src/cli/index.test.ts | 1 + src/client/index.ts | 2 ++ src/mcp/test-support.ts | 8 +++++++ src/simlock-client/client.test.ts | 37 +++++++++++++++++++++++++++++++ src/simlock-client/client.ts | 21 ++++++++++++++++++ src/simlock-client/types.ts | 3 +++ 7 files changed, 74 insertions(+) diff --git a/src/admin/index.ts b/src/admin/index.ts index ce9f735a6..16e41ec9f 100644 --- a/src/admin/index.ts +++ b/src/admin/index.ts @@ -37,6 +37,8 @@ export type { DeviceUnhealthyPush, ExecInput, ExecOutput, + RotateInput, + RotateOutput, DeviceOutputChunk, ExecOptions, DoctorReport, diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 171517b69..aac3b0875 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -8273,6 +8273,7 @@ function fakeClient(overrides: Partial = {}): SimlockAdminCl requestLease: (_input, _options) => Promise.resolve(grant), resolvePassthrough: () => Promise.resolve({ args: [], command: "adb", env: {} }), exec: () => Promise.resolve({ exitCode: 0 }), + rotate: (leaseId, orientation) => Promise.resolve({ leaseId, orientation }), cancelLease: () => Promise.resolve({ result: "not-found" }), renewLease: () => Promise.resolve(grant.lease as LeaseRecord), releaseLease: (input) => Promise.resolve({ leaseId: input.leaseId }), diff --git a/src/client/index.ts b/src/client/index.ts index 5fe7f7ad5..74cbbc2a3 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -25,6 +25,8 @@ export type { DeviceUnhealthyPush, ExecInput, ExecOutput, + RotateInput, + RotateOutput, DeviceOutputChunk, ExecOptions, DoctorReport, diff --git a/src/mcp/test-support.ts b/src/mcp/test-support.ts index 1f5846153..00e291869 100644 --- a/src/mcp/test-support.ts +++ b/src/mcp/test-support.ts @@ -17,6 +17,7 @@ import { type ExecInput, type ExecOptions, type ExecOutput, + type RotateOutput, type DriverPassthroughInput, type LeaseCancelInput, type LeaseCancelOutput, @@ -78,6 +79,8 @@ export class FakeSimlockClient implements SimlockClient { resolvePassthroughImpl: (input: DriverPassthroughInput) => Promise = notStubbed("resolvePassthrough"); execImpl: (input: ExecInput, options: ExecOptions) => Promise = notStubbed("exec"); + rotateImpl: (leaseId: string, orientation: RotateOutput["orientation"]) => Promise = + notStubbed("rotate"); readonly #leaseLostListeners = new Set<(push: LeaseLostPush) => void>(); readonly #deviceUnhealthyListeners = new Set<(push: DeviceUnhealthyPush) => void>(); @@ -150,6 +153,11 @@ export class FakeSimlockClient implements SimlockClient { return this.#dead ? this.#deadConnection() : this.execImpl(input, options); } + rotate(leaseId: string, orientation: RotateOutput["orientation"]): Promise { + this.calls.push({ input: { leaseId, orientation }, method: "rotate" }); + return this.#dead ? this.#deadConnection() : this.rotateImpl(leaseId, orientation); + } + onLeaseLost(listener: (push: LeaseLostPush) => void): () => void { this.#leaseLostListeners.add(listener); return () => this.#leaseLostListeners.delete(listener); diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index af32f27c7..8d3a00d4a 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -664,6 +664,43 @@ describe("pushes", () => { expect(onOutput).toHaveBeenCalledTimes(2); }); + it("rotate sends device.rotate for the lease and answers its output, or throws the daemon's typed refusal", async () => { + const connection = new ScriptedConnection(); + const connectPromise = connectSimlock({ connection }); + await flushMicrotasks(); + completeHello(connection); + const client = await connectPromise; + + const rotated = client.rotate("lease_1", "landscape_left"); + await flushMicrotasks(); + expect(connection.sent.map((frame) => frame.type)).toContain("device.rotate"); + const call = connection.lastSentOf("device.rotate")!; + expect(call.payload).toEqual({ leaseId: "lease_1", orientation: "landscape_left" }); + connection.reply(call.id, { leaseId: "lease_1", orientation: "landscape_left" }); + await expect(rotated).resolves.toEqual({ leaseId: "lease_1", orientation: "landscape_left" }); + + const refused = client.rotate("lease_2", "portrait", { requesterId: "agent-1" }); + await flushMicrotasks(); + const refusedCall = connection.lastSentOf("device.rotate")!; + expect(refusedCall.payload).toEqual({ + leaseId: "lease_2", + orientation: "portrait", + requesterId: "agent-1", + }); + const details = { class: "tv", leaseId: "lease_2", physical: false, platform: "ios" }; + connection.fail( + refusedCall.id, + "ROTATION_UNSUPPORTED", + "Lease lease_2 is on an Apple TV simulator; only an iOS simulator can be rotated", + details, + ); + await expect(refused).rejects.toMatchObject({ + code: "ROTATION_UNSUPPORTED", + details, + kind: "domain", + }); + }); + it("routes a device.exec started push to that call's onStarted, once, before output, and not to another call in flight", async () => { // ADR 0005 §19a: `started` is request-scoped like `output` -- the fact a transport chooses // its response shape on. Round 5 review: the send site and this route could both be deleted diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index b0ea8053d..268e18458 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -51,6 +51,8 @@ import type { DeviceUnhealthyPush, ExecInput, ExecOutput, + RotateInput, + RotateOutput, DoctorReport, DoctorRunInput, DriverPassthroughInput, @@ -123,6 +125,8 @@ export type { DeviceUnhealthyPush, ExecInput, ExecOutput, + RotateInput, + RotateOutput, DeviceOutputChunk, DoctorReport, DoctorRunInput, @@ -237,6 +241,14 @@ export interface SimlockClient { * line-oriented commands work and full-screen ones do not (§19c). */ exec(input: ExecInput, options?: ExecOptions): Promise; + /** + * why: turns the lease's iOS phone or tablet simulator to `orientation`, whether or not the daemon's input module is on. `requesterId` is for an operator that acts for the lease's requester, as `exec`'s is. + */ + rotate( + leaseId: string, + orientation: RotateInput["orientation"], + options?: { readonly requesterId?: string }, + ): Promise; /** * Reports a lease the *daemon* ended -- an expiry, an operator release, an unrecoverable @@ -429,6 +441,7 @@ function buildDegradedClient( runDoctor: () => rejected(), resolvePassthrough: () => rejected(), exec: () => rejected(), + rotate: () => rejected(), onLeaseLost: () => () => {}, onDeviceUnhealthy: () => () => {}, @@ -623,6 +636,14 @@ class SimlockClientImpl { return this.#parseOutput("device.exec", payload); } + rotate( + _leaseId: string, + _orientation: RotateInput["orientation"], + _options: { readonly requesterId?: string } = {}, + ): Promise { + return Promise.resolve({ leaseId: "", orientation: "portrait" }); + } + onLeaseLost(listener: (push: LeaseLostPush) => void): () => void { this.#leaseLostListeners.add(listener); return () => this.#leaseLostListeners.delete(listener); diff --git a/src/simlock-client/types.ts b/src/simlock-client/types.ts index 32b12a7d0..5e13c4771 100644 --- a/src/simlock-client/types.ts +++ b/src/simlock-client/types.ts @@ -38,6 +38,9 @@ export type DriverPassthroughInput = OpInput<"driver.passthrough">; /** The scoped command `simlock simctl` / `simlock adb` runs; see `passthroughCommandSchema`. */ export type PassthroughCommand = OpOutput<"driver.passthrough">; export type ExecInput = OpInput<"device.exec">; +export type RotateInput = OpInput<"device.rotate">; +/** `{ leaseId, orientation }`: what the lease's simulator was turned to. */ +export type RotateOutput = OpOutput<"device.rotate">; /** `{ exitCode }` -- the output itself arrived as `onOutput` chunks while the command ran * (ADR 0005 §19a). */ export type ExecOutput = OpOutput<"device.exec">; From 746b8d011f463e422cce920d4be05b7ff61f95b3 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:10:46 -0300 Subject: [PATCH 021/103] feat(tunnel): closing the socket, the lease's end and a drain remove a tunnel's rules and close its connections (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/tunnel/sessions.ts | 81 ++++++++++++++++++++++++++++++++++++++++-- src/tunnel/worker.ts | 6 +++- 2 files changed, 83 insertions(+), 4 deletions(-) diff --git a/src/tunnel/sessions.ts b/src/tunnel/sessions.ts index d6fcea393..41ff4e2d9 100644 --- a/src/tunnel/sessions.ts +++ b/src/tunnel/sessions.ts @@ -12,9 +12,17 @@ import { TUNNEL_WINDOW_LIMIT, type TunnelFrame, } from "../contract/index.js"; -import { toDriverDevice, type DeviceRecord } from "../core/index.js"; +import { + stableError, + toDriverDevice, + type DeviceRecord, + type DeviceReverse, +} from "../core/index.js"; import type { ModuleDeviceTcp } from "../modules/index.js"; -import type { LeaseSocket, TcpStream } from "../ports/index.js"; +import type { LeaseSocket, Logger, TcpStream } from "../ports/index.js"; + +const CLOSE_LEASE_ENDED = 4001; +const CLOSE_GOING_AWAY = 1001; interface Tunnel { readonly kind: "reverse" | "forward"; @@ -90,20 +98,63 @@ function refusal(tunnels: readonly Tunnel[], held: number): Refusal | undefined return undefined; } +// why: one socket's state that the lease's end and the daemon's stop reach from outside: `finish` closes its connections and, unless the reclaim that follows does it, removes its rules. +interface Session { + readonly socket: LeaseSocket; + finish(removeRules: boolean): Promise; +} + export interface TunnelSessions { attach(leaseId: string, device: DeviceRecord, socket: LeaseSocket): void; + end(leaseId: string, reason: string, signal: AbortSignal): Promise; + drain(): Promise; } export function createTunnelSessions(options: { readonly deviceTcp: ModuleDeviceTcp; + readonly logger: Logger; }): TunnelSessions { // why: the 8-tunnel limit counts every socket of one lease, so the count is the lease's, not the socket's. const counts = new Map(); + const sessions = new Map>(); function attach(leaseId: string, device: DeviceRecord, socket: LeaseSocket): void { let nextConnection = 1; let greeted = false; + let reserved = 0; + let finished: Promise | undefined; const connections = new Map(); + const reverses: DeviceReverse[] = []; + + function finish(removeRules: boolean): Promise { + finished ??= (async () => { + sessions.get(leaseId)?.delete(session); + counts.set(leaseId, (counts.get(leaseId) ?? 0) - reserved); + for (const connection of connections.values()) { + connection.closed = true; + connection.stream.close(); + connection.wake?.(); + } + connections.clear(); + if (!removeRules) return; + await Promise.all( + reverses.map((reverse) => + reverse.close().catch((error: unknown) => { + options.logger.warn("A tunnel's device rule could not be removed", { + error: stableError(error), + }); + }), + ), + ); + })(); + return finished; + } + + const session: Session = { finish, socket }; + const mine = sessions.get(leaseId) ?? new Set(); + mine.add(session); + sessions.set(leaseId, mine); + socket.onClose(() => void finish(true)); // why: a connection reads from its device stream only while the caller has granted window, so a slow reader stops its own connection and no other. async function pump(conn: number, connection: Connection): Promise { @@ -163,6 +214,7 @@ export function createTunnelSessions(options: { return; } counts.set(leaseId, held + tunnels.length); + reserved = tunnels.length; for (const tunnel of tunnels) { const reverse = await options.deviceTcp.reverse( device.spec.platform, @@ -170,6 +222,7 @@ export function createTunnelSessions(options: { tunnel.devicePort, new AbortController().signal, ); + reverses.push(reverse); reverse.onConnection((stream) => { const conn = nextConnection; nextConnection += 2; @@ -253,5 +306,27 @@ export function createTunnelSessions(options: { }); } - return { attach }; + async function endSessions( + leaseId: string | undefined, + code: number, + reason: string, + removeRules: boolean, + ): Promise { + const ending = + leaseId === undefined + ? [...sessions.values()].flatMap((set) => [...set]) + : [...(sessions.get(leaseId) ?? [])]; + // why: a close that races the end must not remove a rule twice, so each session finishes once, with the end's choice about removal. + const done = ending.map((session) => session.finish(removeRules)); + for (const session of ending) session.socket.close(code, reason); + await Promise.all(done); + } + + return { + attach, + drain: () => endSessions(undefined, CLOSE_GOING_AWAY, "Simlock is stopping", true), + // why: with the signal already aborted the daemon is stopping or in maintenance, and reclaim removes the rules, so no removal runs after reclaim began. + end: (leaseId, reason, signal) => + endSessions(leaseId, CLOSE_LEASE_ENDED, reason, !signal.aborted), + }; } diff --git a/src/tunnel/worker.ts b/src/tunnel/worker.ts index 68feb7743..2ecd937b2 100644 --- a/src/tunnel/worker.ts +++ b/src/tunnel/worker.ts @@ -4,9 +4,13 @@ import type { TunnelModuleConfig } from "./definition.js"; import { createTunnelSessions } from "./sessions.js"; export function createWorker(ctx: WorkerContext): WorkerModule { - const sessions = createTunnelSessions({ deviceTcp: ctx.deviceTcp }); + const sessions = createTunnelSessions({ deviceTcp: ctx.deviceTcp, logger: ctx.logger }); return { capability: { name: ctx.name, read: () => Promise.resolve({ state: "available" }) }, + hooks: { + beforeDeviceReclaim: (ended, signal) => sessions.end(ended.leaseId, ended.reason, signal), + beforeDrain: () => sessions.drain(), + }, socket: { open: (_request, _identity, held) => { const lease: LeaseRecord | undefined = ctx.registry.snapshot.leases.find( From e778c348c010e19ad4f239be22e22a2afbcb2517 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:11:06 -0300 Subject: [PATCH 022/103] feat(client): client.rotate turns a lease's simulator through device.rotate (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/simlock-client/client.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index 268e18458..14ec188e5 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -637,11 +637,11 @@ class SimlockClientImpl { } rotate( - _leaseId: string, - _orientation: RotateInput["orientation"], - _options: { readonly requesterId?: string } = {}, + leaseId: string, + orientation: RotateInput["orientation"], + options: { readonly requesterId?: string } = {}, ): Promise { - return Promise.resolve({ leaseId: "", orientation: "portrait" }); + return this.#call("device.rotate", { leaseId, orientation, ...options }); } onLeaseLost(listener: (push: LeaseLostPush) => void): () => void { From a4d9f18511414e3e2620a9929e0a5cb952fc4d36 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:12:25 -0300 Subject: [PATCH 023/103] test: an agent calls POST /v1/leases/{id}/rotate on a worker and through a gateway (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/device-rotate.e2e.test.ts | 157 ++++++++++++++++++++++++++- 1 file changed, 156 insertions(+), 1 deletion(-) diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 36a10a00a..7b02d4611 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -42,11 +42,12 @@ describe("device.rotate", () => { ); }); - async function worker(options: { + async function startWorker(options: { readonly inputModule: boolean; readonly input: FakeInputFactory | undefined; readonly androidInput?: FakeInputFactory; readonly httpPort?: number; + readonly gateway?: { readonly label: string; readonly token: string; readonly url: string }; }) { const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-rotate-")); directories.push(dataDirectory); @@ -77,6 +78,7 @@ describe("device.rotate", () => { const daemon = await startDaemon({ configOverrides: { capabilities: { input: { enabled: options.inputModule } }, + ...(options.gateway === undefined ? {} : { gateway: options.gateway }), ...(options.httpPort === undefined ? {} : { http: { enabled: true, host: "127.0.0.1", port: options.httpPort } }), @@ -89,6 +91,11 @@ describe("device.rotate", () => { version: "1.0.0-e2e", }); daemons.push(daemon); + return { daemon, drivers }; + } + + async function worker(options: Parameters[0]) { + const { daemon, drivers } = await startWorker(options); const granted = await daemon.dispatch( "lease.request", { model: "iPhone 15", platform: "ios" }, @@ -412,4 +419,152 @@ describe("device.rotate", () => { expect(input.opened[3]?.sent).toEqual([]); }, ); + async function agentTokens(daemon: DaemonServer, labels: readonly string[]) { + const admin: DispatchSession = { ...holder, principal: "operator", role: "admin" }; + return await Promise.all( + labels.map(async (label) => { + const created = await daemon.dispatch("token.create", { label, role: "agent" }, admin); + return { principal: created.token.id, secret: created.secret }; + }), + ); + } + + async function leaseFor( + daemon: DaemonServer, + principal: string, + request: { readonly model: string; readonly platform: "ios" | "android" }, + ): Promise { + const granted = await daemon.dispatch("lease.request", request, { ...holder, principal }); + return (granted as { lease: { id: string } }).lease.id; + } + + it( + "an agent's POST /v1/leases/{id}/rotate answers 200 with the lease and orientation, or the refusal's status, on a worker and through a gateway", + { timeout: 120_000 }, + async () => { + const screen = { height: 2556, orientation: "portrait", width: 1179 } as const; + + async function exercise( + daemon: DaemonServer, + httpPort: number, + input: FakeInputFactory, + ready: () => Promise, + ) { + const [phone, emulator] = await agentTokens(daemon, ["phone", "emulator"]); + const phoneId = await leaseFor(daemon, phone!.principal, { + model: "iPhone 15", + platform: "ios", + }); + const emulatorId = await leaseFor(daemon, emulator!.principal, { + model: "Pixel 8", + platform: "android", + }); + await ready(); + const rotate = async (leaseId: string, token: string, body: unknown) => { + const url = `http://127.0.0.1:${String(httpPort)}/v1/leases/${leaseId}/rotate`; + const response = await fetch(url, { + body: JSON.stringify(body), + headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, + method: "POST", + }); + const text = await response.text(); + return { + body: (text.startsWith("{") ? JSON.parse(text) : {}) as { + error?: { code: string; message: string }; + leaseId?: string; + orientation?: string; + }, + status: response.status, + }; + }; + const orientation = "landscape_left"; + + expect(await rotate(phoneId, phone!.secret, { orientation })).toEqual({ + body: { leaseId: phoneId, orientation }, + status: 200, + }); + expect(input.opened[0]?.sent).toEqual([{ kind: "orientation", orientation }]); + + for (const badOrientation of ["landscape-left", "auto", ""]) { + const refused = await rotate(phoneId, phone!.secret, { orientation: badOrientation }); + expect([badOrientation, refused.status, refused.body.error?.code]).toEqual([ + badOrientation, + 400, + "BAD_REQUEST", + ]); + } + expect((await rotate(phoneId, phone!.secret, {})).status).toBe(400); + + const unknown = await rotate("nope", phone!.secret, { orientation }); + expect([unknown.status, unknown.body.error?.code]).toEqual([404, "UNKNOWN_LEASE"]); + const foreign = await rotate(phoneId, emulator!.secret, { orientation }); + expect([foreign.status, foreign.body.error?.code]).toEqual([403, "FORBIDDEN"]); + + const android = await rotate(emulatorId, emulator!.secret, { orientation }); + expect(android.status).toBe(422); + expect(android.body.error).toEqual({ + code: "ROTATION_UNSUPPORTED", + message: `Lease ${emulatorId} is on an Android emulator; only an iOS simulator can be rotated`, + }); + + input.failWith = new Error("helper is gone"); + const missing = await rotate(phoneId, phone!.secret, { orientation }); + expect(missing.status).toBe(503); + expect(missing.body.error).toEqual({ + code: "INPUT_UNAVAILABLE", + message: `Lease ${phoneId}'s simulator cannot take input: helper is gone`, + }); + input.failWith = undefined; + } + + const workerPort = await freeLoopbackPort(); + const workerInput = new FakeInputFactory(screen); + const { daemon: standalone } = await startWorker({ + httpPort: workerPort, + input: workerInput, + inputModule: false, + }); + await exercise(standalone, workerPort, workerInput, () => Promise.resolve()); + await daemons.pop()?.stop("test"); + + const gatewayPort = await freeLoopbackPort(); + const admin: DispatchSession = { ...holder, principal: "operator", role: "admin" }; + const gatewayDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-rotate-gateway-")); + directories.push(gatewayDirectory); + const gateway = await startDaemon({ + configOverrides: { http: { enabled: true, host: "127.0.0.1", port: gatewayPort } }, + dataDirectory: gatewayDirectory, + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + role: "gateway", + version: "1.0.0-e2e", + }); + daemons.push(gateway); + const workerToken = ( + await gateway.dispatch("token.create", { label: "w", role: "worker" }, admin) + ).secret; + const fleetInput = new FakeInputFactory(screen); + await startWorker({ + gateway: { label: "w", token: workerToken, url: `ws://127.0.0.1:${String(gatewayPort)}` }, + input: fleetInput, + inputModule: false, + }); + await vi.waitFor( + async () => { + const { workers } = await gateway.dispatch("worker.list", {}, admin); + expect(workers[0]?.catalog?.length).toBeGreaterThan(0); + }, + { timeout: 10_000 }, + ); + await exercise(gateway, gatewayPort, fleetInput, async () => { + await vi.waitFor( + async () => { + const { leases } = await gateway.dispatch("lease.list", {}, admin); + expect(leases).toHaveLength(2); + }, + { timeout: 10_000 }, + ); + }); + }, + ); }); From e330b80a5c4a3ac9a1565da7fe423786d8e89c94 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:13:32 -0300 Subject: [PATCH 024/103] test: a caller reaches the tunnel route on a lone worker only when it may (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/tunnel-lease.e2e.test.ts | 181 ++++++++++++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 src/daemon/tunnel-lease.e2e.test.ts diff --git a/src/daemon/tunnel-lease.e2e.test.ts b/src/daemon/tunnel-lease.e2e.test.ts new file mode 100644 index 000000000..b9dc43596 --- /dev/null +++ b/src/daemon/tunnel-lease.e2e.test.ts @@ -0,0 +1,181 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { createServer } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; +import { WebSocket } from "ws"; + +import { FakeDeviceTcp, FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; +import { MemoryFilesystem, 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", +}; + +interface OpenedSocket { + // why: 101 for an upgrade that was accepted, else the status the refusal answered. + readonly status: number; + // why: the error code of a refusal's JSON body, when it has one. + readonly code: string | undefined; + readonly messages: Buffer[]; + readonly socket: WebSocket; +} + +const sockets: WebSocket[] = []; + +async function openTunnel(url: string, token: string | undefined): Promise { + const socket = new WebSocket(url, { + headers: token === undefined ? {} : { authorization: `Bearer ${token}` }, + }); + sockets.push(socket); + const messages: Buffer[] = []; + socket.on("message", (data) => messages.push(data as Buffer)); + const outcome = await new Promise<{ status: number; code: string | undefined }>( + (resolve, reject) => { + socket.once("open", () => resolve({ code: undefined, status: 101 })); + socket.once("unexpected-response", (_request, response) => { + let body = ""; + response.on("data", (chunk: Buffer) => { + body += chunk.toString("utf8"); + }); + response.on("end", () => { + let code: string | undefined; + try { + code = (JSON.parse(body) as { error?: { code?: string } }).error?.code; + } catch { + code = undefined; + } + resolve({ code, status: response.statusCode ?? 0 }); + }); + }); + socket.once("error", reject); + }, + ); + return { ...outcome, messages, socket }; +} + +function hello(devicePort: number): Buffer { + const body = Buffer.from(JSON.stringify({ tunnels: [{ devicePort, kind: "reverse" }] })); + return Buffer.concat([Buffer.from([0x01, 0, 0, 0, 0]), body]); +} + +describe("a lease's tunnel socket", () => { + const daemons: DaemonServer[] = []; + const directories: string[] = []; + + afterEach(async () => { + for (const socket of sockets.splice(0)) socket.terminate(); + 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 standalone(enabled: boolean) { + const port = await freeLoopbackPort(); + const path = await mkdtemp(join(tmpdir(), "simlock-e2e-tunnel-")); + directories.push(path); + const daemon = await startDaemon({ + configOverrides: { + capabilities: { tunnel: { enabled } }, + http: { enabled: true, host: "127.0.0.1", port }, + }, + dataDirectory: path, + deviceDataTables: fakeDeviceDataTables, + drivers: [ + new FakeDriver({ + availableOsVersions: ["18.0"], + clock: new SystemClock(), + deviceTcp: new FakeDeviceTcp(), + knownModels: ["Pixel-A"], + platform: "android", + }), + ], + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + version: "1.0.0-e2e", + }); + daemons.push(daemon); + const make = (label: string, role: "agent" | "operator") => + daemon.dispatch("token.create", { label, role }, admin); + const holder = await make("holder", "agent"); + const operator = await make("op", "operator"); + const other = await make("other", "agent"); + const granted = await daemon.dispatch( + "lease.request", + { model: "Pixel-A", platform: "android" }, + { ...agent, principal: holder.token.id }, + ); + const leaseId = (granted as { lease: { id: string } }).lease.id; + return { + holder: holder.secret, + leaseId, + operator: operator.secret, + other: other.secret, + plainUrl: (id = leaseId) => `http://127.0.0.1:${String(port)}/v1/leases/${id}/tunnel`, + url: (id = leaseId) => `ws://127.0.0.1:${String(port)}/v1/leases/${id}/tunnel`, + }; + } + + async function expectReady(url: string, token: string, devicePort: number): Promise { + const opened = await openTunnel(url, token); + expect(opened.status).toBe(101); + opened.socket.send(hello(devicePort)); + await vi.waitFor(() => expect(opened.messages).toHaveLength(1), { timeout: 10_000 }); + expect(opened.messages[0]?.[0]).toBe(0x81); + expect(JSON.parse(opened.messages[0]?.subarray(5).toString("utf8") ?? "")).toEqual({ + tunnels: [{ devicePort, kind: "reverse" }], + }); + } + + it( + "opens WS /v1/leases/{id}/tunnel on a lone worker for the holder and an operator, and refuses the rest", + { timeout: 60_000 }, + async () => { + const on = await standalone(true); + await expectReady(on.url(), on.holder, 5173); + await expectReady(on.url(), on.operator, 5174); + const unknown = { code: "UNKNOWN_LEASE", status: 404 }; + for (const refused of [ + await openTunnel(on.url(), on.other), + await openTunnel(on.url("L-unknown"), on.holder), + ]) { + expect({ code: refused.code, status: refused.status }).toEqual(unknown); + } + const plain = await fetch(on.plainUrl(), { + headers: { authorization: `Bearer ${on.holder}` }, + }); + expect(plain.status).toBe(426); + + const off = await standalone(false); + const disabled = await openTunnel(off.url(), off.holder); + expect({ code: disabled.code, status: disabled.status }).toEqual({ + code: undefined, + status: 404, + }); + }, + ); +}); From 45ad185b541f09c0890ea9c32af4376bfbf84579 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:14:25 -0300 Subject: [PATCH 025/103] feat(tunnel): a holder or operator reaches the tunnel route on a lone worker (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/http/core-routes.test.ts | 1 + src/http/openapi.test.ts | 8 +++++++- src/module-registry/index.ts | 2 ++ src/tunnel/definition.ts | 21 +++++++++++++++++++++ src/tunnel/refusal.ts | 17 +++++++++++++++++ src/tunnel/worker.ts | 4 +++- 6 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 src/tunnel/refusal.ts diff --git a/src/http/core-routes.test.ts b/src/http/core-routes.test.ts index 94858f6f2..864b78b89 100644 --- a/src/http/core-routes.test.ts +++ b/src/http/core-routes.test.ts @@ -89,6 +89,7 @@ describe("the routes createHttpApp registers", () => { "GET /v1/leases/{id}/input", "GET /v1/stream/workers/{workerId}/devices/{deviceId}", "GET /v1/leases/{id}/stream", + "GET /v1/leases/{id}/tunnel", ]); expect([...documented].sort()).toEqual([...declared, ...moduleRoutes].sort()); expect(coverageProblems([...core, "GET /v1/new"], declared)).toEqual([ diff --git a/src/http/openapi.test.ts b/src/http/openapi.test.ts index cbc11b3b3..95e792e05 100644 --- a/src/http/openapi.test.ts +++ b/src/http/openapi.test.ts @@ -395,7 +395,7 @@ describe("buildOpenApiDocument with a module that carries http", () => { (path) => path.startsWith("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/v1/agent-device") || path === "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/v1/uplink", ), ).toEqual([]); - expect((document.tags ?? []).map((tag) => tag.name)).toEqual(["input", "stream"]); + expect((document.tags ?? []).map((tag) => tag.name)).toEqual(["input", "stream", "tunnel"]); }); }); @@ -410,6 +410,12 @@ describe("buildOpenApiDocument with the input module", () => { expect(errorCodes(input, "404")).toEqual(["UNKNOWN_LEASE"]); expect(errorCodes(input, "426")).toEqual(["BAD_REQUEST"]); expect(errorCodes(input, "503")).toEqual(["INPUT_UNAVAILABLE", "WORKER_UNREACHABLE"]); + + const tunnel = document.paths?.["/v1/leases/{id}/tunnel"]?.get; + expect(tunnel?.tags).toEqual(["tunnel"]); + expect(sortedKeys(tunnel?.responses)).toEqual(["101", "401", "403", "404", "426"]); + expect(errorCodes(tunnel, "404")).toEqual(["UNKNOWN_LEASE"]); + expect(errorCodes(tunnel, "426")).toEqual(["BAD_REQUEST"]); }); }); diff --git a/src/module-registry/index.ts b/src/module-registry/index.ts index 6bd3e555f..c90e6d81d 100644 --- a/src/module-registry/index.ts +++ b/src/module-registry/index.ts @@ -2,9 +2,11 @@ import { agentDeviceModule } from "../agent-device/index.js"; import { inputModule } from "../input/index.js"; import type { OptionalModuleDefinition } from "../modules/index.js"; import { streamModule } from "../stream/index.js"; +import { tunnelModule } from "../tunnel/index.js"; export const optionalModules: readonly OptionalModuleDefinition[] = [ agentDeviceModule as OptionalModuleDefinition, inputModule as OptionalModuleDefinition, streamModule as OptionalModuleDefinition, + tunnelModule as OptionalModuleDefinition, ]; diff --git a/src/tunnel/definition.ts b/src/tunnel/definition.ts index 1ef5fa261..0e1d9e95a 100644 --- a/src/tunnel/definition.ts +++ b/src/tunnel/definition.ts @@ -9,6 +9,27 @@ export const tunnelModule: OptionalModuleDefinition = { gatewayKeys: [], validator: objectValidator({}), }, + http: { + routes: [ + { + method: "get", + path: "/v1/leases/{id}/tunnel", + description: + "Open a tunnel socket for a lease's device over a WebSocket: the lease's holder or an operator. Each message is one tag byte, a 4-byte big-endian connection number and a payload. The holder sends HELLO with up to 8 tunnels, each {kind, devicePort}; the server answers READY with the same list, or REFUSED {code, message} and close 4003, and then nothing the HELLO named stays set up. Today only reverse tunnels are served: the device's connections to devicePort arrive as OPEN and DATA, under a 262144-byte window per direction. The socket closes 4001 with the lease-end reason when the lease ends, and 1001 when the daemon stops. A lease the caller does not own answers 404, as an unknown one does. A plain GET without an upgrade answers 426. Served only when capabilities.tunnel.enabled is true on the daemon that answers.", + statuses: { + 101: { description: "The upgrade to a WebSocket." }, + 404: { + description: "No such lease, or not the caller's.", + errorCodes: ["UNKNOWN_LEASE"], + }, + 426: { + description: "The request is not a WebSocket upgrade.", + errorCodes: ["BAD_REQUEST"], + }, + }, + }, + ], + }, loadWorker: () => import("./worker.js"), name: "tunnel", }; diff --git a/src/tunnel/refusal.ts b/src/tunnel/refusal.ts new file mode 100644 index 000000000..ce5a146d8 --- /dev/null +++ b/src/tunnel/refusal.ts @@ -0,0 +1,17 @@ +function refusal(status: number, code: string, message: string, headers?: HeadersInit): Response { + return new Response(JSON.stringify({ error: { code, message } }), { + headers: { "content-type": "application/json", ...headers }, + status, + }); +} + +// why: a plain GET to the socket's path says what the path is for, so a person who opens it in a browser knows to open a socket. +export function upgradeRequired(): Response { + return refusal(426, "BAD_REQUEST", "This path takes a WebSocket upgrade, not a plain request", { + upgrade: "websocket", + }); +} + +export function unknownLease(leaseId: string): Response { + return refusal(404, "UNKNOWN_LEASE", `Unknown lease: ${leaseId}`); +} diff --git a/src/tunnel/worker.ts b/src/tunnel/worker.ts index 2ecd937b2..9d59b7fea 100644 --- a/src/tunnel/worker.ts +++ b/src/tunnel/worker.ts @@ -1,6 +1,7 @@ import type { LeaseRecord } from "../core/index.js"; import type { WorkerContext, WorkerModule } from "../modules/index.js"; import type { TunnelModuleConfig } from "./definition.js"; +import { unknownLease, upgradeRequired } from "./refusal.js"; import { createTunnelSessions } from "./sessions.js"; export function createWorker(ctx: WorkerContext): WorkerModule { @@ -11,13 +12,14 @@ export function createWorker(ctx: WorkerContext): WorkerModu beforeDeviceReclaim: (ended, signal) => sessions.end(ended.leaseId, ended.reason, signal), beforeDrain: () => sessions.drain(), }, + leaseRoute: () => Promise.resolve(upgradeRequired()), socket: { open: (_request, _identity, held) => { const lease: LeaseRecord | undefined = ctx.registry.snapshot.leases.find( (entry) => entry.id === held.id, ); const device = ctx.registry.snapshot.devices.find((entry) => entry.id === lease?.deviceId); - if (device === undefined) return Promise.resolve(new Response(null, { status: 404 })); + if (device === undefined) return Promise.resolve(unknownLease(held.id)); return Promise.resolve((socket) => { sessions.attach(held.id, device, socket); }); From 0dc922ca785720001083662f69264d02eeced73a Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:15:14 -0300 Subject: [PATCH 026/103] feat(http): POST /v1/leases/{id}/rotate on a worker and through a gateway (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/device-rotate.e2e.test.ts | 8 ++++- src/daemon/server.ts | 2 ++ src/gateway/dispatcher.ts | 10 +++--- src/gateway/fleet-coordinator.ts | 49 ++++++++++++++++++++++++++-- src/http/app.ts | 12 +++++++ src/http/lease-declarations.ts | 22 +++++++++++++ 6 files changed, 96 insertions(+), 7 deletions(-) diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 7b02d4611..1497facc0 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -470,7 +470,7 @@ describe("device.rotate", () => { const text = await response.text(); return { body: (text.startsWith("{") ? JSON.parse(text) : {}) as { - error?: { code: string; message: string }; + error?: Record; leaseId?: string; orientation?: string; }, @@ -503,7 +503,11 @@ describe("device.rotate", () => { const android = await rotate(emulatorId, emulator!.secret, { orientation }); expect(android.status).toBe(422); expect(android.body.error).toEqual({ + class: "emulator", code: "ROTATION_UNSUPPORTED", + leaseId: emulatorId, + physical: false, + platform: "android", message: `Lease ${emulatorId} is on an Android emulator; only an iOS simulator can be rotated`, }); @@ -512,6 +516,8 @@ describe("device.rotate", () => { expect(missing.status).toBe(503); expect(missing.body.error).toEqual({ code: "INPUT_UNAVAILABLE", + leaseId: phoneId, + reason: "helper is gone", message: `Lease ${phoneId}'s simulator cannot take input: helper is gone`, }); input.failWith = undefined; diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 0aa1bce23..7440e5771 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -1211,6 +1211,8 @@ export class DaemonServer { // why: Unlike `driver.passthrough` above, this one runs the command here -- so it needs the // per-call push wiring `lease.request` needs, and gets it the same way. return this.#execDevice(connection, frame.id, frame.payload); + case "device.rotate": + return this.#dispatcher.dispatch("device.rotate", frame.payload, this.#session(connection)); case "relay.request": return this.#relayRequest(connection, frame.id, frame.payload, relayChannel); case "relay.cancel": diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index 36d51fbd4..5c8209f18 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -139,6 +139,7 @@ export interface GatewayDispatcherOptions { | "release" | "releaseAll" | "exec" + | "rotate" | "queueDepth" | "physicalQueueDepth" | "ownerId" @@ -731,10 +732,11 @@ export class GatewayDispatcher { return { leaseIds: [...leaseIds] }; }; - #deviceRotate: Handler<"device.rotate"> = async (input) => ({ - leaseId: input.leaseId, - orientation: "portrait", - }); + #deviceRotate: Handler<"device.rotate"> = async (input, session) => + this.options.coordinator.rotate( + { leaseId: input.leaseId, orientation: input.orientation }, + session, + ); #deviceExec: Handler<"device.exec"> = async (input, session) => this.options.coordinator.exec( diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index b0a037f68..1b7bdc52f 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -43,7 +43,13 @@ * `WORKER_UNREACHABLE` when a target is not reachable *right now*, and nothing more. */ import type { EventBus, EventMap } from "../bus/index.js"; -import type { LeaseGrant, LeaseRecord, SimlockAdminClient } from "../admin/index.js"; +import type { + LeaseGrant, + LeaseRecord, + RotateInput, + RotateOutput, + SimlockAdminClient, +} from "../admin/index.js"; import { isSimlockError, requestedClass, @@ -140,6 +146,11 @@ export interface FleetExecInput { readonly stdin?: string; } +export interface FleetRotateInput { + readonly leaseId: string; + readonly orientation: RotateInput["orientation"]; +} + export interface FleetLeaseCoordinatorOptions { readonly clock: Clock; readonly idGenerator: IdGenerator; @@ -577,6 +588,39 @@ export class FleetLeaseCoordinator { }); } + /** + * why: `device.rotate` forwarded to the worker that owns the lease, with the lease's own namespaced requester, bounded by `gateway.execTimeoutMs` like `exec`. A worker names the lease by its own id in a refusal; the caller holds the gateway's id, so the refusal names that instead. + */ + async rotate(input: FleetRotateInput, _session: DispatchSession): Promise { + const entry = this.#requireEntry(input.leaseId); + const requesterId = `${this.options.leaseIndex.requesterPrefix}${entry.requesterId}`; + try { + const rotated = await this.#forwardToWorker(entry.workerId, (client) => + this.#withExecTimeout( + client.rotate(entry.workerLeaseId, input.orientation, { requesterId }), + entry.workerId, + () => undefined, + "device.rotate", + ), + ); + return { leaseId: input.leaseId, orientation: rotated.orientation }; + } catch (error) { + throw this.#namedForCaller(error, entry); + } + } + + #namedForCaller(error: unknown, entry: FleetLeaseEntry): unknown { + if (!(error instanceof DispatchError)) return error; + if (error.code !== "ROTATION_UNSUPPORTED" && error.code !== "INPUT_UNAVAILABLE") return error; + const details = + typeof error.details === "object" && error.details !== null ? error.details : {}; + return new DispatchError( + error.code, + error.message.replaceAll(entry.workerLeaseId, entry.gatewayLeaseId), + { ...details, leaseId: entry.gatewayLeaseId }, + ); + } + /** * Races a forwarded `device.exec` against `gateway.execTimeoutMs` (ADR §19e). Before this, * `exec` awaited `client.exec` unbounded -- a worker that never answers at all (the case this @@ -593,6 +637,7 @@ export class FleetLeaseCoordinator { promise: Promise, workerId: string, onTimeout: () => void, + operation = "device.exec", ): Promise { return this.#raceTimeout( promise, @@ -600,7 +645,7 @@ export class FleetLeaseCoordinator { () => new DispatchError( "EXEC_TIMEOUT", - `Worker ${workerId} did not answer device.exec within gateway.execTimeoutMs (${String(this.options.execTimeoutMs)}ms)`, + `Worker ${workerId} did not answer ${operation} within gateway.execTimeoutMs (${String(this.options.execTimeoutMs)}ms)`, ), onTimeout, ); diff --git a/src/http/app.ts b/src/http/app.ts index 10335f28b..37f27d24f 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -48,6 +48,7 @@ import { leaseGetRoute, leaseListRoute, leaseReleaseRoute, + leaseRotateRoute, leaseRenewRoute, leaseRequestCancelRoute, leaseRequestCreateRoute, @@ -597,6 +598,17 @@ export function createHttpApp(deps: HttpGatewayDeps): OpenAPIHono & HttpApp ); }); + app.openapi({ ...leaseRotateRoute, middleware: [agentAuth] }, async (c) => { + const { orientation } = c.req.valid("json"); + // why: dispatched directly, like `exec`, so `device.rotate`'s own authorize answers 403 for another requester's lease and the handler 404 for an unknown one. + const rotated = await deps.dispatch( + "device.rotate", + { leaseId: c.req.valid("param").id, orientation }, + buildHttpSession(c.get("identity")), + ); + return c.json(rotated, 200); + }); + app.openapi({ ...leaseReleaseRoute, middleware: [agentAuth] }, async (c) => { const identity = c.get("identity"); const session = buildHttpSession(identity); diff --git a/src/http/lease-declarations.ts b/src/http/lease-declarations.ts index 4698ebc8b..5f789e1de 100644 --- a/src/http/lease-declarations.ts +++ b/src/http/lease-declarations.ts @@ -4,6 +4,7 @@ import { deviceClassSchema, deviceRecordSchema, imageTagSchema, + INPUT_ORIENTATIONS, leaseIdSchema, OPERATIONS, refuseModelWithClass, @@ -160,6 +161,26 @@ export const leaseExecRoute = declareRoute({ errors: { 404: ["UNKNOWN_LEASE"], 501: ["UNSUPPORTED_IN_GATEWAY_MODE"], 504: ["EXEC_TIMEOUT"] }, }); +const rotateBodySchema = z.object({ orientation: z.enum(INPUT_ORIENTATIONS) }).strict(); + +export const leaseRotateRoute = declareRoute({ + method: "post", + path: "/v1/leases/{id}/rotate", + tag: "Leases", + summary: "Rotate the lease's iOS simulator", + role: "agent", + notes: + "Turns an iPhone or iPad simulator, whether or not the input module is on. Answers once the event is written to the simulator's input helper. Any other device answers 422.", + request: { params: leaseParamsSchema, json: rotateBodySchema }, + reply: OPERATIONS["device.rotate"].output, + errors: { + 404: ["UNKNOWN_LEASE"], + 422: ["ROTATION_UNSUPPORTED"], + 503: ["INPUT_UNAVAILABLE", "WORKER_UNREACHABLE"], + 504: ["EXEC_TIMEOUT"], + }, +}); + export const leaseRequestGetRoute = declareRoute({ method: "get", path: "/v1/lease-requests/{id}", @@ -345,6 +366,7 @@ export const LEASE_ROUTES = [ leaseGetRoute, leaseRenewRoute, leaseExecRoute, + leaseRotateRoute, leaseEventsRoute, leaseReleaseRoute, ] as const; From 6f2f9730011f3b75ddfc3e88be10a5897f9a4078 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:15:43 -0300 Subject: [PATCH 027/103] docs: rotate over HTTP and its two error codes (#1107) Co-Authored-By: Claude Sonnet 5.5 --- website/src/content/docs/docs/reference/errors.mdx | 2 +- .../content/docs/docs/using-devices/watching-the-screen.mdx | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index ffe15b716..1933cdfe6 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -80,7 +80,7 @@ Branch on `code`, not on the message: the message wording can change, the code d | `UNKNOWN_PASSTHROUGH_TOOL` | 2 | 422 | A tool Simlock does not wrap. | Use `simctl` or `adb`. | | `EXEC_TIMEOUT` | 10 | 504 | A command run on a device through a gateway ran longer than `exec.timeoutMs` (10 minutes by default) and was stopped. | Split the work, or raise `exec.timeoutMs` on the worker. | | `ROTATION_UNSUPPORTED` | 12 | 422 | The lease is not on an iOS phone or tablet simulator, so `POST /v1/leases/{id}/rotate` has nothing to turn. The message names what it is on: an Apple TV, Apple Watch or Apple Vision simulator, another iOS model, an Android emulator or phone or tablet, an iPhone or an iPad. | Rotate a lease on an iPhone or iPad simulator. | -| `INPUT_UNAVAILABLE` | 1 | 503 | The lease's simulator could not take the rotation: its input helper did not start within 10 seconds, or writing to it failed. The message ends with the driver's reason, cut to 200 characters. | Run it again. If it repeats, check `simlock daemon logs`. | +| `INPUT_UNAVAILABLE` | 1 | 503 | The lease's simulator cannot take input. For `POST /v1/leases/{id}/rotate`, its input helper did not start within 10 seconds or writing to it failed, and the message ends with the driver's reason, cut to 200 characters. Through a gateway, the same code answers an input socket whose worker has input off. | Run it again. If it repeats, check `simlock daemon logs`. | ## Daemon and connection diff --git a/website/src/content/docs/docs/using-devices/watching-the-screen.mdx b/website/src/content/docs/docs/using-devices/watching-the-screen.mdx index 5a463800a..0806f5366 100644 --- a/website/src/content/docs/docs/using-devices/watching-the-screen.mdx +++ b/website/src/content/docs/docs/using-devices/watching-the-screen.mdx @@ -112,12 +112,16 @@ A lease's holder can open a WebSocket for its lease at `GET /v1/leases//rotate` turns it with no socket. `0x10` is answered `0x90` `{"requestId":7,"ok":false}`. On Android, a tap, swipe, scroll, key or button reaches the device through a second, control-only scrcpy server that Simlock starts for the lease; it shows no picture and changes no device setting. Taps and scrolls land on the screen as it is now, in its current rotation, and Simlock reads the size every 2 seconds, so after an agent rotates the device a tap may use the old size for up to 2 seconds, and the socket then gets a new `0x82`. A scroll sends 1 wheel unit for each 1/16 of the screen, up to 16, at the given position or the screen's centre; a positive `dy` moves the content down and a positive `dx` moves it right. `home`, `app_switcher`, `lock` and `back` are Android's Home, Recents, Power and Back keys. A `0x06` key is a USB HID usage typed as a US keyboard: letters, digits, Enter, Escape, Backspace, Tab, Space, the punctuation row, the arrows and the modifiers (Shift, Ctrl, Alt, Meta) work, and a modifier stays held for the keys after it until its `up`; other usages (function keys, the keypad) are dropped. A `0x07` orientation is dropped; rotate an Android device with agent-device. A dark phone screen is not woken, so a tap on it does nothing. A phone whose adb check is closed gets `inputUnavailable`. On an iOS simulator, a tap, swipe, scroll and `home` work, and so do `0x06` keys on iOS 26 and older runtimes. A tap reaches the simulator through a helper process that Simlock starts for the lease; it shows no picture. `home` brings the home screen forward and sends the app to the background. A scroll is sent as a finger drag. `app_switcher`, `lock` and `back` are dropped. A `0x07` orientation turns the simulator with a device-orientation event, as turning a phone in your hand does; this was checked with Xcode 26.4 and Xcode 27, on iOS 26.4 and iOS 27 runtimes. A screen that does not rotate, such as the iPhone home screen, stays as it is, and nothing tells the client. On an iOS 27 or newer runtime the simulator ignores injected keys, so `0x06` keys are dropped and the `0x82` message carries `"keyboardUnavailable":true`. The `0x82` message always says `"orientation":"portrait"`, after a rotation too, and touch positions stay fractions of the screen in its portrait frame. +### Rotate without a socket + +A lease's holder can also rotate its iPhone or iPad simulator with `POST /v1/leases//rotate` and a body such as `{"orientation":"landscape_left"}`, on a worker or on a gateway, whether or not `capabilities.input.enabled` is on. `orientation` is one of `portrait`, `portrait_upside_down`, `landscape_left` or `landscape_right`; any other spelling answers 400 `BAD_REQUEST`. The call answers `200` with `{"leaseId":"","orientation":"landscape_left"}` once the event is written to the simulator's input helper, and it uses the helper an open input socket already has. Through a gateway, `` is the id you hold. A lease on any other device (an Apple TV, Apple Watch or Apple Vision simulator, an Android emulator or phone, a physical iPhone or iPad) answers 422 `ROTATION_UNSUPPORTED`, and a helper that cannot start or a failed write answers 503 `INPUT_UNAVAILABLE`. A lease that is not the caller's answers 403, and one that does not exist answers 404 `UNKNOWN_LEASE`. A worker that gives no answer within `gateway.execTimeoutMs` answers 504 `EXEC_TIMEOUT`. The JS client calls it as `client.rotate(leaseId, orientation)`. + Up to 8 sockets share one lease's device input. The socket closes with: | Code | Reason | When | From d8d222b69df7de433479d92bc2566705c655544f Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:16:08 -0300 Subject: [PATCH 028/103] test: the alias parser maps a spelling to an orientation or the unknown message (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/orientation.test.ts | 33 ++++++++++++++++++++++++++++++++ src/contract/orientation.ts | 10 ++++++++++ 2 files changed, 43 insertions(+) create mode 100644 src/contract/orientation.test.ts diff --git a/src/contract/orientation.test.ts b/src/contract/orientation.test.ts new file mode 100644 index 000000000..36f937821 --- /dev/null +++ b/src/contract/orientation.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; + +import { parseOrientation } from "./orientation.js"; + +// why: a parser with many spellings, each a row; it has no surface above it that lists them. +describe("parseOrientation", () => { + it("maps a spelling to an orientation, ignoring case and surrounding space, or to the unknown message", () => { + const accepted: readonly (readonly [string, string])[] = [ + ["landscape_left", "landscape_left"], + ["landscape-left", "landscape_left"], + ["LEFT", "landscape_left"], + [" Left ", "landscape_left"], + ["landscape_right", "landscape_right"], + ["landscape-right", "landscape_right"], + ["right", "landscape_right"], + ["portrait_upside_down", "portrait_upside_down"], + ["portrait-upside-down", "portrait_upside_down"], + ["upside-down", "portrait_upside_down"], + ["portrait", "portrait"], + ["PORTRAIT", "portrait"], + ]; + for (const [spelling, orientation] of accepted) { + expect(parseOrientation(spelling), spelling).toEqual({ ok: true, orientation }); + } + + for (const spelling of ["auto", "landscapeLeft", "", " ", "up", "landscape"]) { + expect(parseOrientation(spelling), JSON.stringify(spelling)).toEqual({ + message: `Unknown orientation ${spelling}; use portrait, portrait-upside-down, landscape-left or landscape-right`, + ok: false, + }); + } + }); +}); diff --git a/src/contract/orientation.ts b/src/contract/orientation.ts index 03849a8fc..075037011 100644 --- a/src/contract/orientation.ts +++ b/src/contract/orientation.ts @@ -25,3 +25,13 @@ export function isRotatableModel(model: string): boolean { const family = modelFamily(model); return family === "phone" || family === "tablet"; } + +export type Orientation = (typeof INPUT_ORIENTATIONS)[number]; + +export type OrientationParse = + | { readonly ok: true; readonly orientation: Orientation } + | { readonly ok: false; readonly message: string }; + +export function parseOrientation(_input: string): OrientationParse { + return { message: "", ok: false }; +} From 4bae4e7b0da425f2bb34353c60929831c8f42c9f Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:16:44 -0300 Subject: [PATCH 029/103] feat(contract): parseOrientation maps an alias to an orientation or the unknown message (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/AGENTS.md | 1 + src/contract/orientation.ts | 25 +++++++++++++++++++++++-- src/core/input.ts | 10 ++-------- 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index 6bad06eb6..de97bd144 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -22,6 +22,7 @@ Imported by: daemon, gateway, simlock-client, every frontend, core, leasing, his | `os-range.ts` | OS constraint grammar: parse, `satisfies`, `compareVersions` | | `version-order.ts` | `isNewerVersion(candidate, running)`: the one "newer" rule (semver order) every update surface shares; the console imports it by this path, not the index (the index carries zod) | | `duration.ts` | `parseDurationMs`, for the CLI and HTTP | +| `orientation.ts` | `INPUT_ORIENTATIONS`, `parseOrientation` (the aliases the CLI, MCP and agent-device front take), `isRotatableModel`, `modelFamily`; no wire shape | | `relay.ts` | Bounded relay ids, channel ids, headers | | `console-url.ts` | The console address `status.get` reports | diff --git a/src/contract/orientation.ts b/src/contract/orientation.ts index 075037011..6a6199180 100644 --- a/src/contract/orientation.ts +++ b/src/contract/orientation.ts @@ -32,6 +32,27 @@ export type OrientationParse = | { readonly ok: true; readonly orientation: Orientation } | { readonly ok: false; readonly message: string }; -export function parseOrientation(_input: string): OrientationParse { - return { message: "", ok: false }; +// why: the CLI, MCP and the agent-device front take these spellings; HTTP and the client take only the four names. +const ALIASES: Readonly> = { + "landscape-left": "landscape_left", + "landscape-right": "landscape_right", + landscape_left: "landscape_left", + landscape_right: "landscape_right", + left: "landscape_left", + portrait: "portrait", + "portrait-upside-down": "portrait_upside_down", + portrait_upside_down: "portrait_upside_down", + right: "landscape_right", + "upside-down": "portrait_upside_down", +}; + +export function parseOrientation(input: string): OrientationParse { + const orientation = Object.hasOwn(ALIASES, input.trim().toLowerCase()) + ? ALIASES[input.trim().toLowerCase()] + : undefined; + if (orientation !== undefined) return { ok: true, orientation }; + return { + message: `Unknown orientation ${input}; use portrait, portrait-upside-down, landscape-left or landscape-right`, + ok: false, + }; } diff --git a/src/core/input.ts b/src/core/input.ts index ea69da8cb..b194329e8 100644 --- a/src/core/input.ts +++ b/src/core/input.ts @@ -1,4 +1,5 @@ import type { PhysicalDriverDevice, VirtualDriverDevice } from "./driver.js"; +import { INPUT_ORIENTATIONS, type Orientation } from "../contract/index.js"; // why: the one table in TypeScript for the input socket's tags, in the messages expo's serve-sim speaks // (ADR 0049 section 3): a client that already speaks them drives a lease with no Simlock-specific code. @@ -32,14 +33,7 @@ export function closeReason(reason: string): string { const INPUT_BUTTONS = ["home", "app_switcher", "lock", "back"] as const; -const INPUT_ORIENTATIONS = [ - "portrait", - "portrait_upside_down", - "landscape_left", - "landscape_right", -] as const; - -export type InputOrientation = (typeof INPUT_ORIENTATIONS)[number]; +export type InputOrientation = Orientation; // why: serve-sim's `0x82` payload, which T3 Code accepts only with a width and height above 0. export interface InputScreenConfig { From c6834bc976bc2242a447c18f0a4ffe5c6d7d0e35 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:17:45 -0300 Subject: [PATCH 030/103] test: the gateway coordinator forwards device.rotate and names the caller's lease id (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/operations.ts | 3 +- src/gateway/fleet-coordinator.test.ts | 45 +++++++++++++++++++++++++++ src/gateway/test-support.ts | 16 ++++++++++ 3 files changed, 62 insertions(+), 2 deletions(-) diff --git a/src/contract/operations.ts b/src/contract/operations.ts index e4820578b..25bf8567f 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -1086,8 +1086,7 @@ function authorizeOneLeaseCall( /** * why: turns a leased iOS phone or tablet simulator, through the lease's device input, whether or not the input module is on. */ -// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. -export const deviceRotate = defineOperation({ +const deviceRotate = defineOperation({ name: "device.rotate", role: "agent", effect: "write", diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index 3eb03b612..b0ef8dd73 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -1109,6 +1109,51 @@ describe("FleetLeaseCoordinator dispatch", () => { expect(client.calls).toContain(`device.exec:${GATEWAY_PREFIX}agent-1`); }); + it("forwards device.rotate to the worker's own lease id with the namespaced requester, answers and names the caller's lease id", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ + grant: grantFixture({ + lease: { + ...grantFixture().lease, + id: "lse_9", + ownerId: "agent-1", + requesterId: `${GATEWAY_PREFIX}agent-1`, + }, + }), + kind: "grant", + }); + const grant = await coordinator.request(REQUEST, requestOptions()); + const session = { + manageEventSubscription: () => undefined, + via: "socket", + principal: "agent-1", + role: "agent", + } as const; + + await expect( + coordinator.rotate({ leaseId: grant.lease.id, orientation: "landscape_left" }, session), + ).resolves.toEqual({ leaseId: grant.lease.id, orientation: "landscape_left" }); + expect(client.calls).toContain(`device.rotate:lse_9:${GATEWAY_PREFIX}agent-1`); + + client.rotateErrors.push( + fromWireError( + "ROTATION_UNSUPPORTED", + "Lease lse_9 is on an Apple TV simulator; only an iOS simulator can be rotated", + { class: "tv", leaseId: "lse_9", physical: false, platform: "ios" }, + ), + ); + await expect( + coordinator.rotate({ leaseId: grant.lease.id, orientation: "portrait" }, session), + ).rejects.toMatchObject({ + code: "ROTATION_UNSUPPORTED", + details: { class: "tv", leaseId: grant.lease.id, physical: false, platform: "ios" }, + message: `Lease ${grant.lease.id} is on an Apple TV simulator; only an iOS simulator can be rotated`, + }); + }); + it("announces started from the worker's own push, before any output (ADR §19a)", async () => { const { coordinator, directory, workers } = harness(); const client = new ScriptedWorkerClient(); diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index abcede425..1a98aed13 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -16,6 +16,7 @@ import type { ExecInput, ExecOptions, ExecOutput, + RotateOutput, LeaseGrant, LeaseRecord, LeaseReleaseInput, @@ -331,6 +332,8 @@ export class ScriptedWorkerClient { * a test sets this to relay that event from inside the call. */ onReleaseLease: ((leaseId: string) => void) | undefined; readonly execQueue: ExecOutcome[] = []; + /** why: a test queues the error the worker's next `device.rotate` throws; an empty queue answers the rotation. */ + readonly rotateErrors: Error[] = []; /** * H4 (round 3 review): the `options` most recently passed to `exec` -- captured before * `execQueue`'s own outcome is even read, so a `"hang"` outcome (whose returned promise never @@ -496,6 +499,19 @@ export class ScriptedWorkerClient { return { exitCode: outcome?.exitCode ?? 0 }; } + // fallow-ignore-next-line unused-class-member -- reached through the GatewayWorkerClient that asClient() casts this double to. + async rotate( + leaseId: string, + orientation: RotateOutput["orientation"], + options: { readonly requesterId?: string } = {}, + ): Promise { + this.calls.push(`device.rotate:${leaseId}:${options.requesterId ?? ""}`); + this.#throwIfFailing(); + const error = this.rotateErrors.shift(); + if (error !== undefined) throw error; + return { leaseId, orientation }; + } + // fallow-ignore-next-line unused-class-member -- reached through the GatewayWorkerClient that asClient() casts this double to. async installComponent( input: ComponentInstallInput, From 38af91d9c929f114a01f3bee91bfc76848a6a1b6 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:18:36 -0300 Subject: [PATCH 031/103] feat(android): the driver's reverse sets adb reverse --no-rebind to a loopback listener and removes it on close (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/core/device-tcp.ts | 11 ++ src/core/index.ts | 2 +- src/daemon/main.ts | 2 + src/drivers/android/device-tcp.ts | 101 +++++++++++++++++ src/drivers/android/index.test.ts | 140 ++++++++++++++++++++++++ src/drivers/android/index.ts | 29 +++++ src/drivers/android/physical-handler.ts | 16 ++- src/ports/index.ts | 6 + src/ports/tcp-listener.test.ts | 45 ++++++++ src/ports/tcp-listener.ts | 85 ++++++++++++++ src/ports/tcp-stream.ts | 30 ++--- 11 files changed, 452 insertions(+), 15 deletions(-) create mode 100644 src/drivers/android/device-tcp.ts create mode 100644 src/ports/tcp-listener.test.ts create mode 100644 src/ports/tcp-listener.ts diff --git a/src/core/device-tcp.ts b/src/core/device-tcp.ts index ed8231015..e83d37317 100644 --- a/src/core/device-tcp.ts +++ b/src/core/device-tcp.ts @@ -1,6 +1,17 @@ import type { TcpStream } from "../ports/index.js"; import type { PhysicalDriverDevice, VirtualDriverDevice } from "./driver.js"; +// why: the two refusals a driver can name; the tunnel module passes the code on to the holder. +export class DeviceTcpError extends Error { + constructor( + readonly code: "TUNNEL_PORT_IN_USE" | "TUNNEL_FAILED", + message: string, + ) { + super(message); + this.name = "DeviceTcpError"; + } +} + // why: one device port reversed to a loopback listener on the worker; every connection the device // opens to that port arrives on `onConnection`, until `close` removes the rule and the listener. export interface DeviceReverse { diff --git a/src/core/index.ts b/src/core/index.ts index 08256718f..23768ee57 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -102,7 +102,7 @@ export { type ScreenAvailability, UnknownPassthroughToolError, } from "./driver-catalog.js"; -export type { DeviceReverse, DeviceTcp } from "./device-tcp.js"; +export { DeviceTcpError, type DeviceReverse, type DeviceTcp } from "./device-tcp.js"; export { closeReason, type DeviceInput, diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 05ef324fe..445a70e24 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -103,6 +103,7 @@ import { type UpdaterLauncher, NodeBytePipeLauncher, NodeTcpProbe, + NodeTcpListenerFactory, NodeTcpStreamConnector, daemonDataDirectory, resolveDaemonSocketPath, @@ -1424,6 +1425,7 @@ async function discoverAndroidDriver( processSupervisor: options.processSupervisor, scrcpyServerPath: PACKAGED_SCRCPY_SERVER, simlockHome: options.simlockHome, + tcpListener: new NodeTcpListenerFactory(), tcpProbe: options.tcpProbe, tcpStreamConnector: new NodeTcpStreamConnector(), // why: Ambient like `homedir()` above, and read here rather than in the driver so the diff --git a/src/drivers/android/device-tcp.ts b/src/drivers/android/device-tcp.ts new file mode 100644 index 000000000..a1183a415 --- /dev/null +++ b/src/drivers/android/device-tcp.ts @@ -0,0 +1,101 @@ +import { + DeviceTcpError, + type DeviceReverse, + type DeviceTcp, + type PhysicalDriverDevice, + type VirtualDriverDevice, +} from "../../core/index.js"; +import type { + ProcessResult, + TcpListener, + TcpListenerFactory, + TcpStream, +} from "../../ports/index.js"; + +// why: the worker keeps these loopback ports for tunnels, so a rule into them is Simlock's own and a sweep may remove it. +export const TUNNEL_PORT_FIRST = 47_000; +export const TUNNEL_PORT_LAST = 47_999; + +const ADB_TIMEOUT_MS = 10_000; +const MESSAGE_LIMIT = 200; +const CANNOT_REBIND = "cannot rebind existing socket"; + +export interface AndroidDeviceTcpOptions { + readonly listeners: TcpListenerFactory; + // why: the driver decides which adb server and environment a device's command runs on, and for a phone which check it passes first. + readonly runAdb: ( + device: VirtualDriverDevice | PhysicalDriverDevice, + args: readonly string[], + timeoutMs: number, + ) => Promise; +} + +function cut(message: string): string { + return message.length > MESSAGE_LIMIT ? message.slice(0, MESSAGE_LIMIT) : message; +} + +async function listenInRange(listeners: TcpListenerFactory): Promise { + for (let port = TUNNEL_PORT_FIRST; port <= TUNNEL_PORT_LAST; port += 1) { + const listener = await listeners.listen(port); + if (listener !== undefined) return listener; + } + throw new DeviceTcpError("TUNNEL_FAILED", "no free tunnel port on the worker"); +} + +export function createAndroidDeviceTcp(options: AndroidDeviceTcpOptions): DeviceTcp { + return { + async reverse(device, devicePort): Promise { + const listener = await listenInRange(options.listeners); + const refuse = async (error: DeviceTcpError): Promise => { + await listener.close(); + throw error; + }; + let result: ProcessResult; + try { + result = await options.runAdb( + device, + ["reverse", "--no-rebind", `tcp:${String(devicePort)}`, `tcp:${String(listener.port)}`], + ADB_TIMEOUT_MS, + ); + } catch (error) { + return await refuse( + new DeviceTcpError( + "TUNNEL_FAILED", + cut(error instanceof Error ? error.message : String(error)), + ), + ); + } + if (result.code !== 0) { + const message = result.stderr.trim(); + return await refuse( + new DeviceTcpError( + message.includes(CANNOT_REBIND) ? "TUNNEL_PORT_IN_USE" : "TUNNEL_FAILED", + cut(message), + ), + ); + } + // why: once the rule is being removed, or when its removal fails, a connection that still arrives is closed at once. + let accept: ((stream: TcpStream) => void) | undefined; + listener.onConnection((stream) => { + if (accept === undefined) stream.close(); + else accept(stream); + }); + return { + close: async () => { + accept = undefined; + const removed = await options.runAdb( + device, + ["reverse", "--remove", `tcp:${String(devicePort)}`], + ADB_TIMEOUT_MS, + ); + if (removed.code !== 0) throw new Error(cut(removed.stderr.trim())); + await listener.close(); + }, + hostPort: listener.port, + onConnection: (handler) => { + accept = handler; + }, + }; + }, + }; +} diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index f615967f8..0a40de69f 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -6,6 +6,7 @@ import { describe, expect, it, vi } from "vitest"; import { ComponentInUseError, ComponentNotOwnedError, + DeviceTcpError, OWNED_ROOT_MARKER_FILE, OwnedRootError, PassthroughRefusedError, @@ -14,6 +15,7 @@ import { import { FakeClock, FakeProcessSupervisor, + FakeTcpListenerFactory, FakeTcpProbe, FakeTcpStreamConnector, type Filesystem, @@ -3359,6 +3361,143 @@ describe("AndroidDriver", () => { }); }); +describe("AndroidDriver deviceTcp", () => { + const emulator = { + address: "emulator-5586", + deviceId: "simlock_one", + driverData: { avdName: "simlock_one", configHash: "h", port: 5586, serial: "emulator-5586" }, + physical: false, + } as const; + const reverseArgs = (port: number) => [ + "reverse", + "--no-rebind", + "tcp:5173", + `tcp:${String(port)}`, + ]; + const ok = { code: 0, stderr: "", stdout: "" }; + const adb = (...args: string[]) => ({ args, command: binaries.adb }); + const signal = () => new AbortController().signal; + + async function driverWith( + expectations: ScriptedProcessExpectation[], + listeners = new FakeTcpListenerFactory(), + tcpProbe?: FakeTcpProbe, + ) { + const runner = new ScriptedProcessRunner(expectations); + const driver = await createDriver(await androidFilesystem(), runner, { + tcpListener: listeners, + ...(tcpProbe === undefined ? {} : { tcpProbe }), + }); + return { driver, listeners, runner }; + } + + it("sets adb reverse --no-rebind to a loopback listener in 47000-47999 and removes it on close, as an emulator or a phone", async () => { + const { driver, listeners, runner } = await driverWith([ + { match: adb("-P", "5038", "-s", "emulator-5586", ...reverseArgs(47_002)), result: ok }, + { + match: adb("-P", "5038", "-s", "emulator-5586", "reverse", "--remove", "tcp:5173"), + result: ok, + }, + ]); + listeners.busy.add(47_000).add(47_001); + const reverse = await driver.deviceTcp?.reverse(emulator, 5173, signal()); + expect(reverse?.hostPort).toBe(47_002); + expect(runner.calls[0]?.options.env).toEqual(scopedEnv); + const arrived: unknown[] = []; + reverse?.onConnection((stream) => arrived.push(stream)); + listeners.listeners[0]?.connect(); + expect(arrived).toHaveLength(1); + await reverse?.close(); + expect(runner.calls[1]?.args).toEqual([ + "-P", + "5038", + "-s", + "emulator-5586", + "reverse", + "--remove", + "tcp:5173", + ]); + expect(listeners.listeners[0]?.closed).toBe(true); + + const probe = new FakeTcpProbe([5038, 5037]); + probe.replyWith("OKAY00040029"); + const phoneRun = await driverWith( + [ + { + match: adb("version"), + result: { code: 0, stderr: "", stdout: "Android Debug Bridge version 1.0.41\n" }, + }, + { + match: adb("-P", "5037", "-s", PHYSICAL_DEVICE.address, ...reverseArgs(47_000)), + result: ok, + }, + ], + new FakeTcpListenerFactory(), + probe, + ); + const phone = await phoneRun.driver.deviceTcp?.reverse(PHYSICAL_DEVICE, 5173, signal()); + expect(phone?.hostPort).toBe(47_000); + expect(phoneRun.runner.calls[1]?.options.env?.ANDROID_ADB_SERVER_PORT).toBe("5037"); + + const stuck = await driverWith([ + { match: adb("-P", "5038", "-s", "emulator-5586", ...reverseArgs(47_000)), result: ok }, + { + match: adb("-P", "5038", "-s", "emulator-5586", "reverse", "--remove", "tcp:5173"), + result: { code: 1, stderr: "device offline", stdout: "" }, + }, + ]); + const held = await stuck.driver.deviceTcp?.reverse(emulator, 5173, signal()); + const delivered: unknown[] = []; + held?.onConnection((stream) => delivered.push(stream)); + await held?.close().catch(() => undefined); + expect(stuck.listeners.listeners[0]?.closed).toBe(false); + const late = stuck.listeners.listeners[0]?.connect(); + expect({ closed: late?.closed, delivered: delivered.length }).toEqual({ + closed: true, + delivered: 0, + }); + }); + + it("refuses a reverse with TUNNEL_PORT_IN_USE when adb cannot rebind, TUNNEL_FAILED for any other adb failure or when every tunnel port is busy, and frees the port it took", async () => { + const cannotRebind = await driverWith([ + { + match: adb("-P", "5038", "-s", "emulator-5586", ...reverseArgs(47_000)), + result: { code: 1, stderr: "adb.exe: error: cannot rebind existing socket", stdout: "" }, + }, + ]); + await expect(cannotRebind.driver.deviceTcp?.reverse(emulator, 5173, signal())).rejects.toEqual( + expect.objectContaining({ code: "TUNNEL_PORT_IN_USE" }), + ); + expect(cannotRebind.listeners.listeners[0]?.closed).toBe(true); + + const failed = await driverWith([ + { + match: adb("-P", "5038", "-s", "emulator-5586", ...reverseArgs(47_000)), + result: { code: 1, stderr: "x".repeat(300), stdout: "" }, + }, + ]); + const error = await failed.driver.deviceTcp + ?.reverse(emulator, 5173, signal()) + .catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(DeviceTcpError); + expect(error).toEqual( + expect.objectContaining({ code: "TUNNEL_FAILED", message: "x".repeat(200) }), + ); + expect(failed.listeners.listeners[0]?.closed).toBe(true); + + const busy = new FakeTcpListenerFactory(); + for (let port = 47_000; port < 48_000; port += 1) busy.busy.add(port); + const exhausted = await driverWith([], busy); + await expect(exhausted.driver.deviceTcp?.reverse(emulator, 5173, signal())).rejects.toEqual( + expect.objectContaining({ + code: "TUNNEL_FAILED", + message: "no free tunnel port on the worker", + }), + ); + expect(exhausted.runner.calls).toEqual([]); + }); +}); + describe("AndroidDriver screen capture", () => { const serverPath = "/simlock/vendor/scrcpy-server-v5.0.1"; const running = { @@ -6254,6 +6393,7 @@ async function createDriver( readonly onDiagnostic?: (diagnostic: AndroidDriverDiagnostic) => void; readonly readinessTimeoutMs?: number; readonly scrcpyServerPath?: string; + readonly tcpListener?: FakeTcpListenerFactory; readonly tcpProbe?: FakeTcpProbe; readonly tcpStreamConnector?: FakeTcpStreamConnector; } = {}, diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 8782ae034..902fcadb6 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -41,6 +41,7 @@ import { type ReclaimResult, removeListedComponent, type DeviceInputFactory, + type DeviceTcp, type ScreenCapture, ScreenUnavailableError, RuntimeMissingError, @@ -57,10 +58,12 @@ import { type ProcessResult, type ProcessRunner, type ProcessSupervisor, + type TcpListenerFactory, type TcpProbe, type TcpStreamConnector, type TimerHandle, } from "../../ports/index.js"; +import { createAndroidDeviceTcp } from "./device-tcp.js"; import { AdbRegistrar } from "./adb-registrar.js"; import { AdbServerSupervisor, AdbServerUnavailableError } from "./adb-server.js"; import { isAndroidDriverData, type AndroidDriverData } from "./data.js"; @@ -209,6 +212,8 @@ export interface AndroidDriverOptions { // rather than one that fails each stream it is asked for. readonly scrcpyServerPath?: string | undefined; readonly tcpStreamConnector?: TcpStreamConnector | undefined; + // why: optional so a host that leaves it out gets a driver that offers no tunnels. + readonly tcpListener?: TcpListenerFactory | undefined; readonly uid?: number; /** why: the daemon's pid is named in the staging directory of a new root. */ readonly pid?: number; @@ -538,6 +543,7 @@ export class AndroidDriver implements Driver { readonly componentFootprint: { readonly path: string; readonly bytes: number }; readonly screenCapture: ScreenCapture | undefined; readonly input: DeviceInputFactory | undefined; + readonly deviceTcp: DeviceTcp | undefined; private constructor( options: AndroidDriverOptions, @@ -577,6 +583,13 @@ export class AndroidDriver implements Driver { const targetFor = this.#screenTargetFor(options, sdk.adb, adbServerPort); this.screenCapture = this.#screenCaptureFor(options, targetFor); this.input = this.#inputFor(options, targetFor); + this.deviceTcp = + options.tcpListener === undefined + ? undefined + : createAndroidDeviceTcp({ + listeners: options.tcpListener, + runAdb: (device, args, timeoutMs) => this.#runAdbOn(device, args, timeoutMs), + }); // why: Where an AVD Simlock made before it owned a root still sits: the AVD home the user // had configured then, or the SDK's own default. Used only by `findLegacy` / // `destroyLegacy` -- the fallback CP3 deleted from the driver proper, kept exactly here @@ -808,6 +821,22 @@ export class AndroidDriver implements Driver { }); } + // why: one adb call on a device through the server that owns it: a phone's behind the version check, an emulator's on Simlock's own server. + async #runAdbOn( + device: VirtualDriverDevice | PhysicalDriverDevice, + args: readonly string[], + timeoutMs: number, + ): Promise { + if (isPhysicalDriverDevice(device)) return await this.#physical.runAdb(device, args, timeoutMs); + const { serial } = this.#dataFor(device); + if (serial === "") throw new Error("the emulator is not running"); + return await this.#processRunner.run( + this.#sdk.adb, + ["-P", String(this.#adbServerPort), "-s", serial, ...args], + { env: this.#env(), timeoutMs }, + ); + } + #assertProxyable(args: readonly string[], context?: PassthroughContext): void { // why: A shell with nothing to run *is* the interactive shell, and an interactive shell // without a terminal is a process that reads a pipe that will never carry anything -- diff --git a/src/drivers/android/physical-handler.ts b/src/drivers/android/physical-handler.ts index b5fc1a40e..939b4e2b5 100644 --- a/src/drivers/android/physical-handler.ts +++ b/src/drivers/android/physical-handler.ts @@ -10,7 +10,7 @@ import { ScreenUnavailableError, uninstallPlan, } from "../../core/index.js"; -import type { ProcessRunner, TcpStreamConnector } from "../../ports/index.js"; +import type { ProcessResult, ProcessRunner, TcpStreamConnector } from "../../ports/index.js"; import type { ScreenTarget } from "./screen/index.js"; import { type AdbGateAnswer, @@ -126,6 +126,20 @@ export class AndroidPhysicalHandler { }; } + // why: a phone's adb call goes through the same version check as every other phone command. + async runAdb( + device: PhysicalDriverDevice, + args: readonly string[], + timeoutMs: number, + ): Promise { + const answer = await this.#gate.check(); + if (!answer.open) throw new Error(answer.message); + return await this.#processRunner.run(this.#adb, ["-P", PORT, "-s", device.deviceId, ...args], { + env: this.#env, + timeoutMs, + }); + } + async advisories(): Promise { const answer = await this.#gate.check(); if (answer.open) return []; diff --git a/src/ports/index.ts b/src/ports/index.ts index 4d15f8133..61ec4837b 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -105,6 +105,12 @@ export type { ProcessSupervisor } from "./process-supervisor.js"; // fallow-ignore-next-line unused-type -- public shape of FakeProcessSupervisor.signals. export type { SignalRecord } from "./process-supervisor.js"; export { FakeTcpProbe, NodeTcpProbe } from "./tcp-probe.js"; +export { + FakeTcpListenerFactory, + NodeTcpListenerFactory, + type TcpListener, + type TcpListenerFactory, +} from "./tcp-listener.js"; export { FakeTcpPeer, FakeTcpStreamConnector, diff --git a/src/ports/tcp-listener.test.ts b/src/ports/tcp-listener.test.ts new file mode 100644 index 000000000..1c5cb3f96 --- /dev/null +++ b/src/ports/tcp-listener.test.ts @@ -0,0 +1,45 @@ +import { createServer } from "node:net"; + +import { describe, expect, it } from "vitest"; + +import { NodeTcpListenerFactory } from "./tcp-listener.js"; +import { NodeTcpStreamConnector } from "./tcp-stream.js"; + +async function freePort(): 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 (address === null || typeof address === "string") throw new Error("no port"); + return address.port; +} + +// why: an adapter over node:net, proven by what a real loopback socket does, which the fake cannot show. +describe("NodeTcpListenerFactory", () => { + it("hands out a loopback port whose connections arrive as streams, answers undefined for a taken port, and frees the port on close", async () => { + const port = await freePort(); + const factory = new NodeTcpListenerFactory(); + const listener = await factory.listen(port); + expect(listener?.port).toBe(port); + expect(await factory.listen(port)).toBeUndefined(); + + const received = new Promise((resolve) => { + listener?.onConnection((stream) => { + void (async () => { + const chunks: Uint8Array[] = []; + for await (const chunk of stream.readable) chunks.push(chunk); + resolve(Buffer.concat(chunks).toString()); + })(); + }); + }); + const client = await new NodeTcpStreamConnector().connect(port, 1000); + await client.write("hello"); + client.close(); + expect(await received).toBe("hello"); + + await listener?.close(); + const again = await factory.listen(port); + expect(again?.port).toBe(port); + await again?.close(); + }); +}); diff --git a/src/ports/tcp-listener.ts b/src/ports/tcp-listener.ts new file mode 100644 index 000000000..7b5107663 --- /dev/null +++ b/src/ports/tcp-listener.ts @@ -0,0 +1,85 @@ +import { createServer, type Socket } from "node:net"; + +import { FakeTcpPeer, type TcpStream, tcpStreamOf } from "./tcp-stream.js"; + +// why: a device reached through `adb reverse` connects to a port on this machine; the driver owns +// that port for as long as the rule stands, and every connection to it arrives on `onConnection`. +export interface TcpListener { + readonly port: number; + onConnection(listener: (stream: TcpStream) => void): void; + close(): Promise; +} + +export interface TcpListenerFactory { + // why: `undefined` is a port someone else holds, so a caller walking a range can go on to the next. + listen(port: number): Promise; +} + +export class NodeTcpListenerFactory implements TcpListenerFactory { + listen(port: number): Promise { + return new Promise((resolve, reject) => { + const server = createServer(); + const listeners: ((stream: TcpStream) => void)[] = []; + const open = new Set(); + server.on("connection", (socket) => { + open.add(socket); + socket.once("close", () => open.delete(socket)); + const stream = tcpStreamOf(socket); + for (const listener of listeners) listener(stream); + }); + server.once("error", (error: NodeJS.ErrnoException) => { + if (error.code === "EADDRINUSE") resolve(undefined); + else reject(error); + }); + server.listen(port, "127.0.0.1", () => { + server.on("error", () => undefined); + resolve({ + close: () => + new Promise((done) => { + server.close(() => done()); + for (const socket of open) socket.destroy(); + }), + onConnection: (listener) => { + listeners.push(listener); + }, + port, + }); + }); + }); + } +} + +class FakeTcpListener implements TcpListener { + closed = false; + readonly #listeners: ((stream: TcpStream) => void)[] = []; + + constructor(readonly port: number) {} + + onConnection(listener: (stream: TcpStream) => void): void { + this.#listeners.push(listener); + } + + close(): Promise { + this.closed = true; + return Promise.resolve(); + } + + connect(): FakeTcpPeer { + const peer = new FakeTcpPeer(); + for (const listener of this.#listeners) listener(peer.stream); + return peer; + } +} + +export class FakeTcpListenerFactory implements TcpListenerFactory { + // why: a test adds a port here to make it taken, as another process on the machine would. + readonly busy = new Set(); + readonly listeners: FakeTcpListener[] = []; + + listen(port: number): Promise { + if (this.busy.has(port)) return Promise.resolve(undefined); + const listener = new FakeTcpListener(port); + this.listeners.push(listener); + return Promise.resolve(listener); + } +} diff --git a/src/ports/tcp-stream.ts b/src/ports/tcp-stream.ts index 5211e56e7..0d9bee05c 100644 --- a/src/ports/tcp-stream.ts +++ b/src/ports/tcp-stream.ts @@ -13,6 +13,22 @@ export interface TcpStream { close(): void; } +// why: after connect or accept an error ends the readable through `Readable.toWeb`; a listener must +// still exist or Node raises it as an uncaught exception and takes the daemon down. +export function tcpStreamOf(socket: Socket): TcpStream { + socket.on("error", () => undefined); + return { + close: () => { + socket.destroy(); + }, + readable: Readable.toWeb(socket) as ReadableStream, + write: (bytes) => + new Promise((done, failed) => { + socket.write(bytes, (error) => (error ? failed(error) : done())); + }), + }; +} + export class NodeTcpStreamConnector implements TcpStreamConnector { connect(port: number, timeoutMs: number): Promise { return new Promise((resolve, reject) => { @@ -34,19 +50,7 @@ export class NodeTcpStreamConnector implements TcpStreamConnector { socket.once("connect", () => { socket.setTimeout(0); socket.off("error", fail); - // why: after connect an error ends the readable through `Readable.toWeb`; a listener must - // still exist or Node raises it as an uncaught exception and takes the daemon down. - socket.on("error", () => undefined); - resolve({ - close: () => { - socket.destroy(); - }, - readable: Readable.toWeb(socket) as ReadableStream, - write: (bytes) => - new Promise((done, failed) => { - socket.write(bytes, (error) => (error ? failed(error) : done())); - }), - }); + resolve(tcpStreamOf(socket)); }); }); } From cd00d681a262aac3913ca71e607e58e42ca371d0 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:19:38 -0300 Subject: [PATCH 032/103] feat(tunnel): an iOS lease is refused TUNNEL_UNSUPPORTED and a driver's refusal reaches the holder with its code (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/core/device-tcp.ts | 1 + src/core/driver-catalog.ts | 7 ++++++ src/core/fake-device-tcp.ts | 8 +++++++ src/daemon/main.ts | 1 + src/drivers/android/device-tcp.ts | 1 + src/modules/device-tcp-types.test.ts | 18 ++++++++++++++ src/modules/testing.ts | 5 +++- src/modules/types.ts | 1 + src/tunnel/sessions.ts | 31 +++++++++++++++++++----- src/tunnel/worker.test.ts | 35 +++++++++++++++++++++++++--- 10 files changed, 98 insertions(+), 10 deletions(-) create mode 100644 src/modules/device-tcp-types.test.ts diff --git a/src/core/device-tcp.ts b/src/core/device-tcp.ts index e83d37317..40733707d 100644 --- a/src/core/device-tcp.ts +++ b/src/core/device-tcp.ts @@ -23,6 +23,7 @@ export interface DeviceReverse { // why: an optional driver member beside `input`; a platform whose device cannot reach a worker port // leaves it out, and the tunnel module learns that from its absence rather than from a platform name. export interface DeviceTcp { + supports(device: VirtualDriverDevice | PhysicalDriverDevice): boolean; reverse( device: VirtualDriverDevice | PhysicalDriverDevice, devicePort: number, diff --git a/src/core/driver-catalog.ts b/src/core/driver-catalog.ts index d7b2f6686..d7ab480b1 100644 --- a/src/core/driver-catalog.ts +++ b/src/core/driver-catalog.ts @@ -103,6 +103,13 @@ export class DriverCatalog { return await factory.open(device, signal); } + supportsDeviceTcp( + platform: Platform, + device: VirtualDriverDevice | PhysicalDriverDevice, + ): boolean { + return this.#drivers.get(platform)?.deviceTcp?.supports(device) ?? false; + } + async reverseDevicePort( platform: Platform, device: VirtualDriverDevice | PhysicalDriverDevice, diff --git a/src/core/fake-device-tcp.ts b/src/core/fake-device-tcp.ts index 58a8ed0a6..d748352d3 100644 --- a/src/core/fake-device-tcp.ts +++ b/src/core/fake-device-tcp.ts @@ -32,6 +32,8 @@ class FakeReverse implements DeviceReverse { export class FakeDeviceTcp implements DeviceTcp { // why: a test sets this to make every rule removal fail, as an adb that does not answer does. closeFailure: Error | undefined; + // why: a test sets a device port's failure to make its `reverse` refuse, as adb does for a port already reversed. + readonly failures = new Map(); readonly #reverses = new Map(); #nextHostPort = 47_000; @@ -39,11 +41,17 @@ export class FakeDeviceTcp implements DeviceTcp { return [...this.#reverses.keys()]; } + supports(): boolean { + return true; + } + async reverse( _device: unknown, devicePort: number, _signal?: AbortSignal, ): Promise { + const failure = this.failures.get(devicePort); + if (failure !== undefined) throw failure; const hostPort = this.#nextHostPort; this.#nextHostPort += 1; const reverse = new FakeReverse( diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 445a70e24..65aeb285c 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -518,6 +518,7 @@ async function composeDaemon( processSupervisor, registry, deviceTcp: { + supports: (platform, device) => catalog.supportsDeviceTcp(platform, device), reverse: (platform, device, devicePort, signal) => catalog.reverseDevicePort(platform, device, devicePort, signal), }, diff --git a/src/drivers/android/device-tcp.ts b/src/drivers/android/device-tcp.ts index a1183a415..8e679262e 100644 --- a/src/drivers/android/device-tcp.ts +++ b/src/drivers/android/device-tcp.ts @@ -44,6 +44,7 @@ async function listenInRange(listeners: TcpListenerFactory): Promise true, async reverse(device, devicePort): Promise { const listener = await listenInRange(options.listeners); const refuse = async (error: DeviceTcpError): Promise => { diff --git a/src/modules/device-tcp-types.test.ts b/src/modules/device-tcp-types.test.ts new file mode 100644 index 000000000..1b8e43dcf --- /dev/null +++ b/src/modules/device-tcp-types.test.ts @@ -0,0 +1,18 @@ +import { describe, expectTypeOf, it } from "vitest"; + +import type { DeviceTcp, Platform } from "../core/index.js"; +import type { ModuleDeviceTcp } from "./index.js"; + +describe("the device port a module sees, declared by shape", () => { + it("ModuleDeviceTcp is core's DeviceTcp with the platform in front of each call", () => { + expectTypeOf>().toEqualTypeOf< + [Platform, ...Parameters] + >(); + expectTypeOf>().toEqualTypeOf< + [Platform, ...Parameters] + >(); + expectTypeOf>().toEqualTypeOf< + ReturnType + >(); + }); +}); diff --git a/src/modules/testing.ts b/src/modules/testing.ts index 1a86ef6b0..a53e1dec9 100644 --- a/src/modules/testing.ts +++ b/src/modules/testing.ts @@ -191,7 +191,10 @@ export async function fakeWorkerContext(name: string, config: C): Promise Promise.reject(new Error("no device port in a fake context")) }, + deviceTcp: { + reverse: () => Promise.reject(new Error("no device port in a fake context")), + supports: () => false, + }, inputs: { openInput: () => Promise.resolve({ unavailable: "no input in a fake context" }) }, screens: { openScreen: () => Promise.reject(new Error("no screen in a fake context")), diff --git a/src/modules/types.ts b/src/modules/types.ts index 4a5e39e39..f2edc3a50 100644 --- a/src/modules/types.ts +++ b/src/modules/types.ts @@ -199,6 +199,7 @@ export interface ModuleInputs { // why: the drivers' device ports, routed by platform, without handing a module the drivers. export interface ModuleDeviceTcp { + supports(platform: Platform, device: VirtualDriverDevice | PhysicalDriverDevice): boolean; reverse( platform: Platform, device: VirtualDriverDevice | PhysicalDriverDevice, diff --git a/src/tunnel/sessions.ts b/src/tunnel/sessions.ts index 41ff4e2d9..05036d57e 100644 --- a/src/tunnel/sessions.ts +++ b/src/tunnel/sessions.ts @@ -13,6 +13,7 @@ import { type TunnelFrame, } from "../contract/index.js"; import { + DeviceTcpError, stableError, toDriverDevice, type DeviceRecord, @@ -213,15 +214,33 @@ export function createTunnelSessions(options: { refuse(refused); return; } + const target = toDriverDevice(device); + if (!options.deviceTcp.supports(device.spec.platform, target)) { + refuse({ + code: "TUNNEL_UNSUPPORTED", + message: `${device.spec.platform} devices take no tunnel`, + }); + return; + } counts.set(leaseId, held + tunnels.length); reserved = tunnels.length; for (const tunnel of tunnels) { - const reverse = await options.deviceTcp.reverse( - device.spec.platform, - toDriverDevice(device), - tunnel.devicePort, - new AbortController().signal, - ); + let reverse: DeviceReverse; + try { + reverse = await options.deviceTcp.reverse( + device.spec.platform, + target, + tunnel.devicePort, + new AbortController().signal, + ); + } catch (error) { + await finish(true); + refuse({ + code: error instanceof DeviceTcpError ? error.code : "TUNNEL_FAILED", + message: error instanceof Error ? error.message : String(error), + }); + return; + } reverses.push(reverse); reverse.onConnection((stream) => { const conn = nextConnection; diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index 9c9c2da65..f74a7a374 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from "vitest"; import type { DeviceRecord, LeaseRecord } from "../core/index.js"; +import { DeviceTcpError } from "../core/index.js"; import { FakeDeviceTcp } from "../core/testing.js"; import type { WorkerModule } from "../modules/index.js"; import { fakeWorkerContext } from "../modules/testing.js"; @@ -46,7 +47,7 @@ function hello(...tunnels: { kind: string; devicePort: number }[]): Uint8Array { return frame(0x01, 0, JSON.stringify({ tunnels })); } -async function setup(): Promise<{ +async function setup(platform = "android"): Promise<{ readonly worker: WorkerModule; readonly deviceTcp: FakeDeviceTcp; }> { @@ -54,7 +55,7 @@ async function setup(): Promise<{ const deviceTcp = new FakeDeviceTcp(); const registry = { snapshot: { - devices: [{ id: "dev_1", spec: { platform: "android" } } as unknown as DeviceRecord], + devices: [{ id: "dev_1", spec: { platform } } as unknown as DeviceRecord], leases: [{ deviceId: "dev_1", id: "L-1" } as unknown as LeaseRecord], }, }; @@ -62,6 +63,7 @@ async function setup(): Promise<{ const worker = loaded.createWorker({ ...ctx, deviceTcp: { + supports: (named) => named === "android", reverse: (_platform, device, port, signal) => deviceTcp.reverse(device, port, signal), }, registry, @@ -130,9 +132,36 @@ describe("a worker's tunnel socket", () => { message: "forward tunnels are not available yet", tunnels: [reverse(5173), { devicePort: 9229, kind: "forward" }], }, + { + code: "TUNNEL_UNSUPPORTED", + message: "ios devices take no tunnel", + platform: "ios", + tunnels: [reverse(5173)], + }, + { + code: "TUNNEL_PORT_IN_USE", + failures: new Map([ + [5174, new DeviceTcpError("TUNNEL_PORT_IN_USE", "port 5174 is reversed")], + ]), + message: "port 5174 is reversed", + tunnels: [reverse(5173), reverse(5174)], + }, + { + code: "TUNNEL_FAILED", + failures: new Map([[5174, new DeviceTcpError("TUNNEL_FAILED", "device offline")]]), + message: "device offline", + tunnels: [reverse(5173), reverse(5174)], + }, + { + code: "TUNNEL_FAILED", + failures: new Map([[5174, new Error("adb exploded")]]), + message: "adb exploded", + tunnels: [reverse(5173), reverse(5174)], + }, ]; for (const refused of cases) { - const { deviceTcp, worker } = await setup(); + const { deviceTcp, worker } = await setup(refused.platform); + for (const [port, failure] of refused.failures ?? []) deviceTcp.failures.set(port, failure); const socket = await attach(worker); socket.receive(hello(...refused.tunnels)); await vi.waitFor(() => From c267dac86ed72931cd26834b5079027201f258cc Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:20:21 -0300 Subject: [PATCH 033/103] test: a user runs simlock rotate and sees Rotated lease to (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/commands/rotate.ts | 7 ++++++ src/cli/index.test.ts | 44 ++++++++++++++++++++++++++++++++++++++ src/cli/tree.ts | 1 + 3 files changed, 52 insertions(+) create mode 100644 src/cli/commands/rotate.ts diff --git a/src/cli/commands/rotate.ts b/src/cli/commands/rotate.ts new file mode 100644 index 000000000..d32f2723b --- /dev/null +++ b/src/cli/commands/rotate.ts @@ -0,0 +1,7 @@ +import type { CommandContext } from "../tree.js"; + +async function run(_argv: readonly string[], _context: CommandContext): Promise { + return 0; +} + +export { run }; diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index aac3b0875..e6f2dec09 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -10668,3 +10668,47 @@ describe("simlock worker update", () => { } }); }); + +describe("simlock rotate", () => { + const heldLease = { + deviceId: "dev_1", + grantedAt: 0, + id: "lse_mine", + lastRenewedAt: 0, + idChosenByRequester: false, + ownerId: "some-other-principal", + requesterId: "test-requester", + ttlDeadline: 60_000, + ttlMs: 60_000, + }; + + it("prints the lease the answer names and the canonical orientation for the holder's only lease", async () => { + const output = outputCapture(); + const rotations: unknown[] = []; + + await expect( + runCli( + ["rotate", "landscape-left"], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + listLeases: () => Promise.resolve({ leases: [heldLease] }), + rotate: (leaseId, orientation, options) => { + rotations.push({ leaseId, orientation, options }); + return Promise.resolve({ leaseId: "lse_answered", orientation }); + }, + }), + }), + ), + ).resolves.toBe(0); + + expect(rotations).toEqual([ + { + leaseId: "lse_mine", + orientation: "landscape_left", + options: { requesterId: "test-requester" }, + }, + ]); + expect(output.stdout).toBe("Rotated lease lse_answered to landscape_left\n"); + }); +}); diff --git a/src/cli/tree.ts b/src/cli/tree.ts index 75d477671..68298dc88 100644 --- a/src/cli/tree.ts +++ b/src/cli/tree.ts @@ -130,6 +130,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: "mcp", load: () => import("./commands/mcp.js") }, { name: "instructions", load: () => import("./commands/instructions.js") }, { name: "setup", load: () => import("./commands/setup.js") }, From adb10f260acf39f3013ac84e52e531a2c3b1b65f Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:20:44 -0300 Subject: [PATCH 034/103] feat(cli): simlock rotate turns the holder's only lease (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/commands/passthrough.ts | 23 +---------------------- src/cli/commands/rotate.ts | 27 +++++++++++++++++++++++++-- src/cli/remote-lease.ts | 25 +++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 24 deletions(-) create mode 100644 src/cli/remote-lease.ts diff --git a/src/cli/commands/passthrough.ts b/src/cli/commands/passthrough.ts index 39861144b..5a5d0ac67 100644 --- a/src/cli/commands/passthrough.ts +++ b/src/cli/commands/passthrough.ts @@ -1,5 +1,6 @@ import type { SimlockAdminClient } from "../../admin/index.js"; import { asUsageIfRefused, UsageError } from "../errors.js"; +import { resolveRemoteLeaseId } from "../remote-lease.js"; import { connectDaemonClient } from "../connect.js"; import type { CommandContext } from "../tree.js"; @@ -103,26 +104,4 @@ function extractLeaseFlag(args: readonly string[]): { return { leaseFlag, rest: args.slice(index) }; } -async function resolveRemoteLeaseId( - client: SimlockAdminClient, - environment: CommandContext["environment"], -): Promise { - const { leases } = await client.listLeases(); - const own = - client.role === "admin" - ? leases.filter((lease) => lease.requesterId === environment.requesterId) - : leases; - if (own.length === 0) { - throw new UsageError( - `No lease is held by ${environment.requesterId}: run \`simlock lease\` first, or set SIMLOCK_AGENT_ID to the id that holds it`, - ); - } - if (own.length > 1) { - throw new UsageError( - `${environment.requesterId} holds more than one lease (${own.map((lease) => lease.id).join(", ")}); pass --lease to name the device you mean`, - ); - } - return (own[0] as { readonly id: string }).id; -} - export { run }; diff --git a/src/cli/commands/rotate.ts b/src/cli/commands/rotate.ts index d32f2723b..4e6993ec5 100644 --- a/src/cli/commands/rotate.ts +++ b/src/cli/commands/rotate.ts @@ -1,7 +1,30 @@ +import { parseOrientation } from "../../contract/index.js"; +import { commandArgs, requiredPositional, UsageError } from "../args.js"; +import { connectDaemonClient } from "../connect.js"; +import { resolveRemoteLeaseId } from "../remote-lease.js"; import type { CommandContext } from "../tree.js"; -async function run(_argv: readonly string[], _context: CommandContext): Promise { - return 0; +async function run( + argv: readonly string[], + { environment, token }: CommandContext, +): Promise { + const { positionals } = commandArgs(argv, {}); + const parsed = parseOrientation(requiredPositional(positionals, "orientation")); + if (!parsed.ok) throw new UsageError(parsed.message); + const client = await connectDaemonClient(environment, token); + try { + const leaseId = await resolveRemoteLeaseId(client, environment); + const requesterId = client.role === "admin" ? environment.requesterId : undefined; + const rotated = await client.rotate( + leaseId, + parsed.orientation, + requesterId === undefined ? undefined : { requesterId }, + ); + environment.stdout.write(`Rotated lease ${rotated.leaseId} to ${rotated.orientation}\n`); + return 0; + } finally { + await client.close(); + } } export { run }; diff --git a/src/cli/remote-lease.ts b/src/cli/remote-lease.ts new file mode 100644 index 000000000..8f874b8f3 --- /dev/null +++ b/src/cli/remote-lease.ts @@ -0,0 +1,25 @@ +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(); + const own = + client.role === "admin" + ? leases.filter((lease) => lease.requesterId === environment.requesterId) + : leases; + if (own.length === 0) { + throw new UsageError( + `No lease is held by ${environment.requesterId}: run \`simlock lease\` first, or set SIMLOCK_AGENT_ID to the id that holds it`, + ); + } + if (own.length > 1) { + throw new UsageError( + `${environment.requesterId} holds more than one lease (${own.map((lease) => lease.id).join(", ")}); pass --lease to name the device you mean`, + ); + } + return (own[0] as { readonly id: string }).id; +} From 075987923c1aee2a77d25a003064a8803913c72e Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:21:00 -0300 Subject: [PATCH 035/103] test: two tunnels, END half-closes from each side, and a device connection past 256 is closed (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/tunnel-frames.ts | 1 + .../android/input/device-input.test.ts | 1 + src/drivers/android/screen/session.test.ts | 1 + src/ports/tcp-stream.ts | 10 ++++ src/tunnel/worker.test.ts | 56 +++++++++++++++++++ 5 files changed, 69 insertions(+) diff --git a/src/contract/tunnel-frames.ts b/src/contract/tunnel-frames.ts index 5b1fecebf..889e6b020 100644 --- a/src/contract/tunnel-frames.ts +++ b/src/contract/tunnel-frames.ts @@ -4,6 +4,7 @@ export const TUNNEL_TAG = { credit: 0x04, data: 0x03, + end: 0x05, hello: 0x01, open: 0x02, ready: 0x81, diff --git a/src/drivers/android/input/device-input.test.ts b/src/drivers/android/input/device-input.test.ts index bca1ade71..598d28ac9 100644 --- a/src/drivers/android/input/device-input.test.ts +++ b/src/drivers/android/input/device-input.test.ts @@ -109,6 +109,7 @@ class Peer { close: () => { this.close(); }, + end: () => undefined, readable, write: async (bytes) => { this.written.push(typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes); diff --git a/src/drivers/android/screen/session.test.ts b/src/drivers/android/screen/session.test.ts index f70d276bb..693bea75a 100644 --- a/src/drivers/android/screen/session.test.ts +++ b/src/drivers/android/screen/session.test.ts @@ -90,6 +90,7 @@ class Peer { close: () => { this.close(); }, + end: () => undefined, readable, write: async (bytes) => { this.written.push(typeof bytes === "string" ? bytes : new TextDecoder().decode(bytes)); diff --git a/src/ports/tcp-stream.ts b/src/ports/tcp-stream.ts index 0d9bee05c..1c576dd2a 100644 --- a/src/ports/tcp-stream.ts +++ b/src/ports/tcp-stream.ts @@ -10,6 +10,8 @@ export interface TcpStreamConnector { export interface TcpStream { readonly readable: ReadableStream; write(bytes: Uint8Array | string): Promise; + // why: half-close, so the peer sees this side's bytes end while it can still write back; `close` ends both. + end(): void; close(): void; } @@ -21,6 +23,9 @@ export function tcpStreamOf(socket: Socket): TcpStream { close: () => { socket.destroy(); }, + end: () => { + socket.end(); + }, readable: Readable.toWeb(socket) as ReadableStream, write: (bytes) => new Promise((done, failed) => { @@ -60,6 +65,8 @@ export class NodeTcpStreamConnector implements TcpStreamConnector { export class FakeTcpPeer { readonly written: Uint8Array[] = []; closed = false; + // why: the driver half-closed its side, as `stream.end()` does; `end()` on the peer is the device's side ending. + writeEnded = false; #controller!: ReadableStreamDefaultController; readonly stream: TcpStream; @@ -82,6 +89,9 @@ export class FakeTcpPeer { // why: a cancelled readable is already closed; closing the connection is still done. } }, + end: () => { + this.writeEnded = true; + }, readable, write: async (bytes) => { this.written.push(typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes); diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index f74a7a374..2a35ea4e3 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -109,6 +109,62 @@ describe("a worker's tunnel socket", () => { ); }); + it("serves two tunnels, half-closes with END from each side, and closes a device connection past 256 open", async () => { + const { deviceTcp, worker } = await setup(); + const socket = await attach(worker); + socket.receive( + hello({ devicePort: 5173, kind: "reverse" }, { devicePort: 5174, kind: "reverse" }), + ); + await vi.waitFor(() => + expect(frames(socket)).toEqual([ + { + body: '{"tunnels":[{"kind":"reverse","devicePort":5173},{"kind":"reverse","devicePort":5174}]}', + conn: 0, + tag: 0x81, + }, + ]), + ); + const first = deviceTcp.connect(5173); + const second = deviceTcp.connect(5174); + await vi.waitFor(() => + expect(frames(socket).slice(1)).toEqual([ + { body: '{"kind":"reverse","devicePort":5173}', conn: 1, tag: 0x02 }, + { body: '{"kind":"reverse","devicePort":5174}', conn: 3, tag: 0x02 }, + ]), + ); + + first.end(); + await vi.waitFor(() => expect(frames(socket).at(-1)).toEqual({ body: "", conn: 1, tag: 0x05 })); + socket.receive(frame(0x03, 1, "after the device's END")); + await vi.waitFor(() => expect(first.writtenText()).toBe("after the device's END")); + expect(first.writeEnded).toBe(false); + socket.receive(frame(0x05, 1)); + await vi.waitFor(() => expect(first.writeEnded).toBe(true)); + expect(second.writeEnded).toBe(false); + second.send("the other tunnel is untouched"); + await vi.waitFor(() => + expect(frames(socket).at(-1)).toEqual({ + body: "the other tunnel is untouched", + conn: 3, + tag: 0x03, + }), + ); + + const opens = () => frames(socket).filter((sent) => sent.tag === 0x02).length; + const peers = Array.from({ length: 255 }, () => deviceTcp.connect(5173)); + await vi.waitFor(() => expect(opens()).toBe(257)); + expect(peers.every((peer) => !peer.closed)).toBe(true); + const past = deviceTcp.connect(5173); + await vi.waitFor(() => expect(past.closed).toBe(true)); + expect(opens()).toBe(257); + + socket.receive(frame(0x06, 3, '{"reason":"done"}')); + await vi.waitFor(() => expect(second.closed).toBe(true)); + const after = deviceTcp.connect(5173); + await vi.waitFor(() => expect(opens()).toBe(258)); + expect(after.closed).toBe(false); + }); + it("refuses a HELLO that cannot be met whole with REFUSED and close 4003, and leaves nothing it named set up", async () => { const reverse = (devicePort: number) => ({ devicePort, kind: "reverse" }); const cases = [ From 661ddab955551dce8fbd51227670e8e2a130a830 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:21:46 -0300 Subject: [PATCH 036/103] feat(tunnel): END half-closes a connection from each side and a device connection past 256 is closed (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/ports/tcp-listener.ts | 3 ++- src/tunnel/sessions.ts | 31 +++++++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/ports/tcp-listener.ts b/src/ports/tcp-listener.ts index 7b5107663..276d1ee62 100644 --- a/src/ports/tcp-listener.ts +++ b/src/ports/tcp-listener.ts @@ -18,7 +18,8 @@ export interface TcpListenerFactory { export class NodeTcpListenerFactory implements TcpListenerFactory { listen(port: number): Promise { return new Promise((resolve, reject) => { - const server = createServer(); + // why: END is a half-close, so the device ending its bytes must not end the worker's side too. + const server = createServer({ allowHalfOpen: true }); const listeners: ((stream: TcpStream) => void)[] = []; const open = new Set(); server.on("connection", (socket) => { diff --git a/src/tunnel/sessions.ts b/src/tunnel/sessions.ts index 05036d57e..a6cc7c034 100644 --- a/src/tunnel/sessions.ts +++ b/src/tunnel/sessions.ts @@ -24,6 +24,7 @@ import type { LeaseSocket, Logger, TcpStream } from "../ports/index.js"; const CLOSE_LEASE_ENDED = 4001; const CLOSE_GOING_AWAY = 1001; +const MAX_CONNECTIONS = 256; interface Tunnel { readonly kind: "reverse" | "forward"; @@ -37,6 +38,9 @@ interface Connection { // why: how many bytes the caller may still send before the worker grants more credit. inbound: number; closed: boolean; + // why: a connection is done only when both directions have said END, so each side's END is remembered. + deviceEnded: boolean; + callerEnded: boolean; wake: (() => void) | undefined; } @@ -157,6 +161,13 @@ export function createTunnelSessions(options: { sessions.set(leaseId, mine); socket.onClose(() => void finish(true)); + function settle(conn: number, connection: Connection): void { + if (!connection.deviceEnded || !connection.callerEnded) return; + connection.closed = true; + connection.stream.close(); + connections.delete(conn); + } + // why: a connection reads from its device stream only while the caller has granted window, so a slow reader stops its own connection and no other. async function pump(conn: number, connection: Connection): Promise { const reader = connection.stream.readable.getReader(); @@ -170,7 +181,12 @@ export function createTunnelSessions(options: { } if (pending === undefined) { const step = await reader.read(); - if (step.done) return; + if (step.done) { + socket.send(encodeTunnelFrame(TUNNEL_TAG.end, conn)); + connection.deviceEnded = true; + settle(conn, connection); + return; + } pending = step.value; } const size = Math.min(pending.length, connection.window, TUNNEL_MAX_DATA_BYTES); @@ -243,11 +259,17 @@ export function createTunnelSessions(options: { } reverses.push(reverse); reverse.onConnection((stream) => { + if (connections.size >= MAX_CONNECTIONS) { + stream.close(); + return; + } const conn = nextConnection; nextConnection += 2; socket.send(encodeTunnelFrame(TUNNEL_TAG.open, conn, JSON.stringify(tunnel))); const connection: Connection = { + callerEnded: false, closed: false, + deviceEnded: false, inbound: TUNNEL_WINDOW_BYTES, stream, wake: undefined, @@ -296,6 +318,7 @@ export function createTunnelSessions(options: { if ( frame.tag !== TUNNEL_TAG.data && frame.tag !== TUNNEL_TAG.credit && + frame.tag !== TUNNEL_TAG.end && frame.tag !== TUNNEL_TAG.reset ) { badRequest(`unknown frame tag ${String(frame.tag)}`); @@ -310,7 +333,11 @@ export function createTunnelSessions(options: { if (connection === undefined) return; if (frame.tag === TUNNEL_TAG.data) onData(frame.conn, connection, frame.payload); else if (frame.tag === TUNNEL_TAG.credit) onCredit(connection, frame.payload); - else { + else if (frame.tag === TUNNEL_TAG.end) { + connection.stream.end(); + connection.callerEnded = true; + settle(frame.conn, connection); + } else { connection.closed = true; connection.stream.close(); connection.wake?.(); From 8972acaaba57a563c75bbfe372b939778ee3afd7 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:22:14 -0300 Subject: [PATCH 037/103] test: --lease names the lease to rotate before or after the orientation (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/index.test.ts | 57 ++++++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 19 deletions(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index e6f2dec09..f93c9a386 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -10682,33 +10682,52 @@ describe("simlock rotate", () => { ttlMs: 60_000, }; - it("prints the lease the answer names and the canonical orientation for the holder's only lease", async () => { + async function rotateWith(argv: readonly string[], leases: readonly (typeof heldLease)[]) { const output = outputCapture(); const rotations: unknown[] = []; + const exitCode = await runCli( + argv, + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + listLeases: () => Promise.resolve({ leases: [...leases] }), + rotate: (leaseId, orientation, options) => { + rotations.push({ leaseId, orientation, options }); + return Promise.resolve({ leaseId: `${leaseId}_answered`, orientation }); + }, + }), + }), + ); + return { exitCode, output, rotations }; + } - await expect( - runCli( - ["rotate", "landscape-left"], - output.environmentWith({ - connectAdmin: async () => - fakeClient({ - listLeases: () => Promise.resolve({ leases: [heldLease] }), - rotate: (leaseId, orientation, options) => { - rotations.push({ leaseId, orientation, options }); - return Promise.resolve({ leaseId: "lse_answered", orientation }); - }, - }), - }), - ), - ).resolves.toBe(0); - - expect(rotations).toEqual([ + it("a user runs simlock rotate [--lease ] and sees Rotated lease to , or a usage error", async () => { + const only = await rotateWith(["rotate", "landscape-left"], [heldLease]); + expect(only.exitCode).toBe(0); + expect(only.rotations).toEqual([ { leaseId: "lse_mine", orientation: "landscape_left", options: { requesterId: "test-requester" }, }, ]); - expect(output.stdout).toBe("Rotated lease lse_answered to landscape_left\n"); + expect(only.output.stdout).toBe("Rotated lease lse_mine_answered to landscape_left\n"); + + const two = [heldLease, { ...heldLease, deviceId: "dev_2", id: "lse_other" }]; + for (const argv of [ + ["rotate", "--lease", "lse_other", "left"], + ["rotate", "left", "--lease", "lse_other"], + ["rotate", "left", "--lease=lse_other"], + ]) { + const named = await rotateWith(argv, two); + expect(named.exitCode).toBe(0); + expect(named.rotations).toEqual([ + { + leaseId: "lse_other", + orientation: "landscape_left", + options: { requesterId: "test-requester" }, + }, + ]); + } }); }); From fa9b7cf21fed3509a4224b7a2f94f579462a05d2 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:22:29 -0300 Subject: [PATCH 038/103] feat(cli): simlock rotate --lease names the lease (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/commands/rotate.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cli/commands/rotate.ts b/src/cli/commands/rotate.ts index 4e6993ec5..ec012d823 100644 --- a/src/cli/commands/rotate.ts +++ b/src/cli/commands/rotate.ts @@ -8,12 +8,13 @@ async function run( argv: readonly string[], { environment, token }: CommandContext, ): Promise { - const { positionals } = commandArgs(argv, {}); + const { lease, positionals } = commandArgs(argv, { lease: { type: "string" } }); const parsed = parseOrientation(requiredPositional(positionals, "orientation")); if (!parsed.ok) throw new UsageError(parsed.message); const client = await connectDaemonClient(environment, token); try { - const leaseId = await resolveRemoteLeaseId(client, environment); + const leaseId = + typeof lease === "string" ? lease : await resolveRemoteLeaseId(client, environment); const requesterId = client.role === "admin" ? environment.requesterId : undefined; const rotated = await client.rotate( leaseId, From 617b3dd7e70569409aa48f26ccad15c9f2f93eae Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:23:31 -0300 Subject: [PATCH 039/103] fix(ports): a peer's half-close ends a TCP stream's readable (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/ports/tcp-listener.test.ts | 3 ++- src/ports/tcp-stream.ts | 31 +++++++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/ports/tcp-listener.test.ts b/src/ports/tcp-listener.test.ts index 1c5cb3f96..3b2a3b67a 100644 --- a/src/ports/tcp-listener.test.ts +++ b/src/ports/tcp-listener.test.ts @@ -34,8 +34,9 @@ describe("NodeTcpListenerFactory", () => { }); const client = await new NodeTcpStreamConnector().connect(port, 1000); await client.write("hello"); - client.close(); + client.end(); expect(await received).toBe("hello"); + client.close(); await listener?.close(); const again = await factory.listen(port); diff --git a/src/ports/tcp-stream.ts b/src/ports/tcp-stream.ts index 1c576dd2a..b40fea971 100644 --- a/src/ports/tcp-stream.ts +++ b/src/ports/tcp-stream.ts @@ -1,5 +1,4 @@ import { createConnection, type Socket } from "node:net"; -import { Readable } from "node:stream"; // why: `TcpProbe` answers one question and hangs up; a device's video socket reached through adb // keeps talking for as long as someone watches. @@ -15,6 +14,34 @@ export interface TcpStream { close(): void; } +// why: `Readable.toWeb` waits for the socket to close, not for the peer's FIN, so a peer's half-close would never end the stream; this one ends on `end`, and on an error or close too. +function readableOf(socket: Socket): ReadableStream { + let finished = false; + return new ReadableStream({ + cancel: () => { + socket.destroy(); + }, + pull: () => { + socket.resume(); + }, + start: (controller) => { + const finish = () => { + if (finished) return; + finished = true; + controller.close(); + }; + socket.on("data", (chunk: Buffer) => { + if (finished) return; + controller.enqueue(new Uint8Array(chunk)); + if ((controller.desiredSize ?? 0) <= 0) socket.pause(); + }); + socket.on("end", finish); + socket.on("close", finish); + socket.on("error", finish); + }, + }); +} + // why: after connect or accept an error ends the readable through `Readable.toWeb`; a listener must // still exist or Node raises it as an uncaught exception and takes the daemon down. export function tcpStreamOf(socket: Socket): TcpStream { @@ -26,7 +53,7 @@ export function tcpStreamOf(socket: Socket): TcpStream { end: () => { socket.end(); }, - readable: Readable.toWeb(socket) as ReadableStream, + readable: readableOf(socket), write: (bytes) => new Promise((done, failed) => { socket.write(bytes, (error) => (error ? failed(error) : done())); From 17858cda16bd31bb985879564b275d7aba932dc0 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:23:41 -0300 Subject: [PATCH 040/103] test: simlock rotate takes aliases, refuses unknown names and ambiguous leases, and exits 12 for ROTATION_UNSUPPORTED (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/index.test.ts | 64 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index f93c9a386..0ec3933b6 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -10682,6 +10682,8 @@ describe("simlock rotate", () => { ttlMs: 60_000, }; + const two = [heldLease, { ...heldLease, deviceId: "dev_2", id: "lse_other" }]; + async function rotateWith(argv: readonly string[], leases: readonly (typeof heldLease)[]) { const output = outputCapture(); const rotations: unknown[] = []; @@ -10713,7 +10715,6 @@ describe("simlock rotate", () => { ]); expect(only.output.stdout).toBe("Rotated lease lse_mine_answered to landscape_left\n"); - const two = [heldLease, { ...heldLease, deviceId: "dev_2", id: "lse_other" }]; for (const argv of [ ["rotate", "--lease", "lse_other", "left"], ["rotate", "left", "--lease", "lse_other"], @@ -10729,5 +10730,66 @@ describe("simlock rotate", () => { }, ]); } + + for (const [spelling, orientation] of [ + ["LEFT", "landscape_left"], + [" left ", "landscape_left"], + ["upside-down", "portrait_upside_down"], + ]) { + const spelled = await rotateWith(["rotate", spelling as string], [heldLease]); + expect(spelled.exitCode).toBe(0); + expect(spelled.output.stdout).toBe(`Rotated lease lse_mine_answered to ${orientation}\n`); + } + + const refusals: [readonly string[], readonly (typeof heldLease)[], RegExp][] = [ + [["rotate", "sideways"], [heldLease], /^Unknown orientation sideways; use portrait,/], + [["rotate", "auto"], [heldLease], /^Unknown orientation auto;/], + [["rotate", "landscapeLeft"], [heldLease], /^Unknown orientation landscapeLeft;/], + [["rotate"], [heldLease], /^Expected orientation/], + [["rotate", "left"], [], /test-requester/], + [["rotate", "left"], two, /lse_mine.*lse_other.*--lease /s], + ]; + for (const [argv, leases, message] of refusals) { + const refused = await rotateWith(argv, leases); + expect(refused.exitCode).toBe(2); + expect(refused.rotations).toEqual([]); + expect(JSON.parse(refused.output.stderr.trim().split("\n").at(-1) ?? "")).toEqual({ + error: { code: "USAGE", message: expect.stringMatching(message) }, + }); + } + + const unsupported = outputCapture(); + await expect( + runCli( + ["rotate", "left", "--lease", "lse_android"], + unsupported.environmentWith({ + connectAdmin: async () => + fakeClient({ + rotate: () => + Promise.reject( + new SimlockError( + "ROTATION_UNSUPPORTED", + "domain", + "Lease lse_android is on an Android emulator; only an iOS simulator can be rotated", + { + class: "emulator", + leaseId: "lse_android", + physical: false, + platform: "android", + }, + ), + ), + }), + }), + ), + ).resolves.toBe(12); + expect(JSON.parse(unsupported.stderr.trim().split("\n").at(-1) ?? "")).toEqual({ + error: { + code: "ROTATION_UNSUPPORTED", + message: + "Lease lse_android is on an Android emulator; only an iOS simulator can be rotated", + }, + }); + expect(unsupported.stdout).toBe(""); }); }); From 9f1396f7d62f176751961dba7425f1842618b699 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:24:16 -0300 Subject: [PATCH 041/103] test: an MCP client calls rotate_device {orientation} and the held lease rotates (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/mcp/server.test.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index dce4303ea..7ea9f595f 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -906,6 +906,29 @@ describe("MCP run_on_device alongside other tools", () => { }); }); +describe("MCP rotate_device", () => { + it("rotates the session's held lease and returns its id and the canonical orientation", async () => { + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant()); + client.rotateImpl = (leaseId, orientation) => Promise.resolve({ leaseId, orientation }); + const { mcpClient, close } = await connectedServer(client); + try { + await call(mcpClient, "lease_simulator", { model: "iPhone 17 Pro", platform: "ios" }); + const result = await call(mcpClient, "rotate_device", { orientation: "landscape-left" }); + expect(result.isError).not.toBe(true); + expect(result.structuredContent).toEqual({ + leaseId: "lease-1", + orientation: "landscape_left", + }); + expect(client.calls.filter((entry) => entry.method === "rotate")).toEqual([ + { input: { leaseId: "lease-1", orientation: "landscape_left" }, method: "rotate" }, + ]); + } finally { + await close(); + } + }); +}); + function call(client: Client, name: string, arguments_: Record) { return client.request( { method: "tools/call", params: { arguments: arguments_, name } }, From 29c7aec318e3db81d702988bd4d9c5c1530a2de0 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:24:24 -0300 Subject: [PATCH 042/103] docs(tunnel): the tunnel socket on a lone worker, its capability, ports and manuals (#1112) Co-Authored-By: Claude Sonnet 5.5 --- docs/internal/ARCHITECTURE.md | 1 + src/contract/AGENTS.md | 1 + src/drivers/android/AGENTS.md | 2 ++ src/modules/AGENTS.md | 10 +++--- src/ports/AGENTS.md | 1 + src/tunnel/AGENTS.md | 32 +++++++++++++++++++ src/tunnel/CLAUDE.md | 1 + .../docs/docs/reference/configuration.mdx | 1 + .../docs/docs/using-devices/remote-agents.mdx | 14 ++++++++ 9 files changed, 58 insertions(+), 5 deletions(-) create mode 100644 src/tunnel/AGENTS.md create mode 100644 src/tunnel/CLAUDE.md diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index d33c70e77..e1c37c256 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -50,6 +50,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘ | agent-device | Optional edge: the two agent-device daemons (simulators, phones) beside a worker, its HTTP front | [agent-device](../../src/agent-device/AGENTS.md) | | stream | Optional edge: a running device's live screen over HTTP, relayed by a gateway | [stream](../../src/stream/AGENTS.md) | | input | Optional edge: a lease holder's taps and keys over a WebSocket, relayed by a gateway | [input](../../src/input/AGENTS.md) | +| tunnel | Optional edge: a lease holder's reverse tunnels from its Android device over a WebSocket, on a lone worker | [tunnel](../../src/tunnel/AGENTS.md) | | auth | Credential → identity: tokens, admin secret, `hello`, uplink join token, HTTP strategies | [auth](../../src/auth/AGENTS.md) | | http | HTTP frontend: routes, SSE | [http](../../src/http/AGENTS.md) | | cli | Operator command surface | [cli](../../src/cli/AGENTS.md) | diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index 1e70704e4..ef71cf383 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -23,6 +23,7 @@ Imported by: daemon, gateway, simlock-client, every frontend, core, leasing, his | `version-order.ts` | `isNewerVersion(candidate, running)`: the one "newer" rule (semver order) every update surface shares; the console imports it by this path, not the index (the index carries zod) | | `duration.ts` | `parseDurationMs`, for the CLI and HTTP | | `relay.ts` | Bounded relay ids, channel ids, headers | +| `tunnel-frames.ts` | The tunnel socket's frame codec, tags and limits (`encodeTunnelFrame`, `decodeTunnelFrame`, `TUNNEL_*`); a helper with no wire shape, listed in the protocol-bump check | | `console-url.ts` | The console address `status.get` reports | ## Operations diff --git a/src/drivers/android/AGENTS.md b/src/drivers/android/AGENTS.md index 3d2c6a389..174fdece6 100644 --- a/src/drivers/android/AGENTS.md +++ b/src/drivers/android/AGENTS.md @@ -115,6 +115,8 @@ No slim: `resolveSpec` ignores `mode` and returns a full spec. `fresh` is core's Screen — `screenCapture` and `input`, only when `create` got `scrcpyServerPath` and `tcpStreamConnector`: [screen](screen/AGENTS.md), [input](input/AGENTS.md). +Tunnels — `deviceTcp` (`device-tcp.ts`), only when `create` got `tcpListener`: `reverse` listens on a free loopback port in 47000-47999 (busy ones skipped; none free → `TUNNEL_FAILED`) and runs `adb reverse --no-rebind tcp: tcp:` on the device's own server (an emulator's on Simlock's port, a phone's on 5037 behind the gate), 10 s per call; `cannot rebind existing socket` → `TUNNEL_PORT_IN_USE`, any other failure → `TUNNEL_FAILED` (message cut to 200 characters). `close` removes the rule, then the listener; a removal that fails keeps the listener, closing every connection at once. + Plain facts: `listCatalog`, a resolve of a model the library lacks and a library provision (seed) share one `AvdmanagerDeviceList`: `avdmanager list device` runs again only when the size or modified time of a file it reads profiles from changed, or one appeared or went: the tools package's `lib/sdklib/sdklib.core.jar` (legacy `tools/lib/sdklib*.jar`) and `source.properties`, the user's devices.xml, `devices.xml` in each `system-images/*/*/*` and `add-ons/*` directory (a new image is a new path), and `devices.xml` and `source.properties` in each `extras/*/*` directory (avdmanager reads an extra whose `source.properties` says `Extra.Path=DeviceProfiles`). Otherwise the last good answer is served; a failed run is not kept; concurrent callers share one run. The sdkmanager catalog is never read. Existing devices are not re-checked for fit. diff --git a/src/modules/AGENTS.md b/src/modules/AGENTS.md index fd888657c..d0f26ccf3 100644 --- a/src/modules/AGENTS.md +++ b/src/modules/AGENTS.md @@ -7,11 +7,11 @@ Imported by: `daemon/main.ts` (the factory and types); on a gateway it is handed ## Files -| File | Role | -| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `types.ts` | `OptionalModuleDefinition` (with optional `http` route data, read only by the OpenAPI document, and optional `localProfile` data), `ModuleTokens`, `ModuleConfig`, `WorkerModule`, `WorkerHooks`, `ModuleLease`, `ModuleLeaseHandler` (a module's lease handler, `leaseRoute` on both sides), `ModuleLeaseSocketHandler` (`socket` on both sides: `open` answers a refusal `Response` or an accept that gets the socket), `ModuleInputs` (`WorkerContext.inputs`), `WorkerContext`, the by-shape copies | -| `host.ts` | `createModuleHost`: checks names, loads turned-on modules (`role: "worker"` or `"gateway"`), runs hooks, collects each module's `mount` and `leaseRoute`, and on a worker `prepareLocalProfiles` (below); a gateway host runs `beforeDrain` under the same 30 s deadline | -| `testing.ts` | Fake module and context for tests and the conformance suite | +| File | Role | +| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `types.ts` | `OptionalModuleDefinition` (with optional `http` route data, read only by the OpenAPI document, and optional `localProfile` data), `ModuleTokens`, `ModuleConfig`, `WorkerModule`, `WorkerHooks`, `ModuleLease`, `ModuleLeaseHandler` (a module's lease handler, `leaseRoute` on both sides), `ModuleLeaseSocketHandler` (`socket` on both sides: `open` answers a refusal `Response` or an accept that gets the socket), `ModuleInputs` (`WorkerContext.inputs`), `ModuleDeviceTcp` (`WorkerContext.deviceTcp`: `supports`, `reverse`, by shape from core's `DeviceTcp`), `WorkerContext`, the by-shape copies | +| `host.ts` | `createModuleHost`: checks names, loads turned-on modules (`role: "worker"` or `"gateway"`), runs hooks, collects each module's `mount` and `leaseRoute`, and on a worker `prepareLocalProfiles` (below); a gateway host runs `beforeDrain` under the same 30 s deadline | +| `testing.ts` | Fake module and context for tests and the conformance suite | ## Rules diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index 0c85ec260..cd12e9b2d 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -29,6 +29,7 @@ Uses: nothing from other components. Imported by: every component that touches t | `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 | | `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`) | | `KeySetFetcher` | `key-set-fetcher.ts` | `NodeKeySetFetcher` | `FakeKeySetFetcher` | One GET of a key-set URL: no redirects, body capped at 64 KiB | | `SqliteOpener` | `sqlite.ts` | `NodeSqliteOpener` | none; tests use the adapter on a temp file | Open a SQLite file (`:memory:` is not pre-created); `exec`, `prepare`, `close`. `sqlite.ts` also holds `SqliteSchemaOwner` (`name`, `version`, `migrations[i]` takes version `i` to `i + 1`), `passesQuickCheck` and `isLockError` | diff --git a/src/tunnel/AGENTS.md b/src/tunnel/AGENTS.md new file mode 100644 index 000000000..180953cd0 --- /dev/null +++ b/src/tunnel/AGENTS.md @@ -0,0 +1,32 @@ +# Tunnel + +Does: lets a lease's holder (or an operator) reverse device ports of its Android device to its own machine over `WS /v1/leases/{id}/tunnel`, on a lone worker. +Entry: `index.ts` -> `tunnelModule`, an optional module (ADR 0054): `worker.ts` `createWorker`, loaded by the module host only when turned on. +Uses: contract (`tunnel-frames.ts`), core (`DeviceReverse`, `DeviceTcpError`), modules (the context, socket types), ports (`LeaseSocket`). +Never imports: http, gateway, drivers, daemon, leasing, `fs`, `child_process`. Imported by: `module-registry` only. +Off unless `capabilities.tunnel.enabled` (false). Off: nothing loaded, and the `tunnel` capability reads `off`. + +## Files + +| File | Role | +| --------------- | ----------------------------------------------------------------------------------------- | +| `definition.ts` | `tunnelModule`: name `tunnel`, empty config section, `http` route data, the worker loader | +| `worker.ts` | The worker side from the host's context: capability, hooks, lease route (426), socket | +| `sessions.ts` | One session per socket: HELLO, rules, connections, window and credit, lease end, drain | +| `refusal.ts` | The 404 `UNKNOWN_LEASE` and 426 bodies | + +## How it works + +The HTTP layer resolves the lease for the caller, then `socket.open` finds the lease and its device in the worker's registry (404 `UNKNOWN_LEASE` when gone) and attaches a session to the upgraded socket. + +1. The first frame must be `HELLO`. It is checked whole: bad port, more than 8 tunnels per lease (counted across sockets), `forward` (not available yet), a platform whose driver has no `deviceTcp` (`supports`). A refusal sends `REFUSED {code, message}` and closes 4003. +2. Each reverse tunnel is `ctx.deviceTcp.reverse`. A failure removes the tunnels set before it and refuses with the driver's `DeviceTcpError` code (`TUNNEL_PORT_IN_USE`, `TUNNEL_FAILED`), else `TUNNEL_FAILED`. Then `READY`. +3. A device connection is `OPEN` with the next odd id; its bytes go out as `DATA` only while the caller's window allows, and the worker grants `CREDIT` as it writes to the device. `END` half-closes one direction; a connection ends when both have. A 257th open connection is closed at once. +4. A bad frame is `BAD_REQUEST`, close 4003; a frame for a connection already closed is ignored. +5. The socket closing, the lease ending (`beforeDeviceReclaim`, close 4001 with the reason) and a drain (`beforeDrain`, close 1001) close the session's connections and remove its rules; with an already aborted signal the removal is skipped and reclaim does it. + +## Rules + +- The module never checks an owner; the HTTP layer does. +- The module never imports a driver; `ctx.deviceTcp` is the only door to a device. +- A removal that fails is logged at `warn`; the driver keeps the loopback port reserved until reclaim. diff --git a/src/tunnel/CLAUDE.md b/src/tunnel/CLAUDE.md new file mode 100644 index 000000000..43c994c2d --- /dev/null +++ b/src/tunnel/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/website/src/content/docs/docs/reference/configuration.mdx b/website/src/content/docs/docs/reference/configuration.mdx index 806760a5f..29cc04886 100644 --- a/website/src/content/docs/docs/reference/configuration.mdx +++ b/website/src/content/docs/docs/reference/configuration.mdx @@ -314,6 +314,7 @@ A name Simlock does not know is warned about and ignored. | `capabilities.agent-device.ios.provisioningProfile` | non-empty string | not set | Provisioning profile for manual signing of the iPhone runner. Setting it switches agent-device to manual signing. Passed to the phone daemon. | Worker | | `capabilities.agent-device.ios.signingIdentity` | non-empty string | not set | Code-signing identity for manual signing of the iPhone runner. Passed to the phone daemon. | Worker | | `capabilities.input.enabled` | boolean | `false` | Let a lease's holder send taps and keys to its device over `WS /v1/leases/{id}/input`. On a gateway: pass each input socket through to the lease's worker, which needs it on too. | Both | +| `capabilities.tunnel.enabled` | boolean | `false` | Let a lease's holder open `WS /v1/leases/{id}/tunnel` and reverse device ports to its own machine. Only a lone worker serves it for now. The worker reserves loopback ports 47000-47999 for tunnels, and a rule that `adb reverse` points into that range is removed when the worker starts, so keep your own rules out of it. | Worker | | `capabilities.stream.enabled` | boolean | `false` | Let people watch a running device's screen. On a gateway: pass each stream through from the worker. | Both | | `capabilities.stream.fps` | integer `1`–`60` | `30` | Highest frame rate. A still screen sends far fewer frames. | Worker | | `capabilities.stream.maxDimension` | integer `96`–`4096` | `720` | Longest side of the picture, in pixels. The setting that changes bandwidth most. | Worker | diff --git a/website/src/content/docs/docs/using-devices/remote-agents.mdx b/website/src/content/docs/docs/using-devices/remote-agents.mdx index 463d2bb44..5b32c8828 100644 --- a/website/src/content/docs/docs/using-devices/remote-agents.mdx +++ b/website/src/content/docs/docs/using-devices/remote-agents.mdx @@ -175,6 +175,20 @@ Send the same calls to the gateway, with a token created on the gateway. The gat - A request no worker can serve fails at once, with or without `noWait`. - When the worker that holds your lease is not connected, calls for it answer `503 WORKER_UNREACHABLE`. The lease is still yours until it expires; retry. +## Tunnels + +A holder with its own WebSocket client can reach its leased Android device's ports from the worker's side. Open `GET /v1/leases//tunnel` as a WebSocket with your token, on a worker that has `capabilities.tunnel.enabled: true` (it is off by default; a gateway does not relay it yet). The lease's holder and an operator may open it; anyone else gets `404`, as for an unknown lease, and a plain `GET` gets `426`. + +Each message is one binary frame: a tag byte, a 4-byte big-endian connection number and a payload. The first frame is `HELLO` (tag `0x01`, connection 0) with JSON of at most 4 KiB: `{"tunnels":[{"kind":"reverse","devicePort":5173}]}`. Name 1 to 8 tunnels per lease, across all its sockets, with device ports from 1024 to 65535. Only `reverse` works today. + +- The worker answers `READY` (`0x81`) with the same list. Each connection the device then makes to `localhost:` arrives as `OPEN` (`0x02`, JSON `{kind, devicePort}`, odd connection numbers), and its bytes flow as `DATA` (`0x03`, up to 65536 bytes) both ways. +- Each direction of a connection starts with a 262144-byte window. The reader grants more with `CREDIT` (`0x04`, a 4-byte count); a reader that grants none pauses that connection and no other. +- `END` (`0x05`) closes one direction and leaves the other open. `RESET` (`0x06`) from you closes the connection. A worker closes a device connection at once when 256 are already open on the socket. +- A `HELLO` the worker cannot meet gets `REFUSED` (`0x82`, JSON `{code, message}`) and the socket closes with 4003; nothing it named stays set up. The codes are in the [errors reference](/docs/reference/errors/#tunnels). A frame that breaks the protocol is refused `BAD_REQUEST` the same way. +- The socket closes `4001` with the lease-end reason when the lease ends, and `1001` when the daemon stops. Closing the socket removes the device's `adb reverse` rule before the lease can end. + +The worker sets each tunnel up with `adb reverse --no-rebind`, so a port you already reversed with `adb reverse` through `exec` is refused `TUNNEL_PORT_IN_USE`. A rule you set through `exec` after the tunnel, without `--no-rebind`, replaces it and the tunnel's connections stop. iOS leases are refused `TUNNEL_UNSUPPORTED`. + ## When something goes wrong Errors come back as JSON with an HTTP status: From bc1a8691f6e3cce5672a20397f8e8d60acb23e18 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:25:03 -0300 Subject: [PATCH 043/103] feat(mcp): rotate_device turns the session's held lease (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/mcp/contracts.ts | 10 ++++++++++ src/mcp/server.test.ts | 5 ++++- src/mcp/server.ts | 20 ++++++++++++++++++++ src/mcp/session.ts | 19 +++++++++++++++++++ 4 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/mcp/contracts.ts b/src/mcp/contracts.ts index 82a171164..1da44facf 100644 --- a/src/mcp/contracts.ts +++ b/src/mcp/contracts.ts @@ -14,6 +14,7 @@ import { z } from "zod"; import { + INPUT_ORIENTATIONS, leaseRecordSchema, leaseRequestFields, OPERATIONS, @@ -103,4 +104,13 @@ export type ListDevicesOutput = z.infer; export type ReleaseSimulatorInput = z.infer; export type ReleaseSimulatorOutput = z.infer; export type LeaseStatusOutput = z.infer; +export const rotateDeviceInputSchema = z.object({ orientation: z.string().min(1).max(64) }); + +export const rotateDeviceOutputSchema = z.object({ + leaseId: z.string(), + orientation: z.enum(INPUT_ORIENTATIONS), +}); + +export type RotateDeviceInput = z.infer; +export type RotateDeviceOutput = z.infer; export type RunOnDeviceInput = z.infer; diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index 7ea9f595f..fde561c12 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -16,7 +16,7 @@ import { leaseSimulatorInputSchema } from "./contracts.js"; import { createMcpServer } from "./server.js"; describe("MCP server (smoke)", () => { - it("advertises exactly the lease, catalog, status and run_on_device tools, and walks lease -> list -> status -> release", async () => { + it("advertises exactly the lease, catalog, status, run_on_device and rotate_device tools, and walks lease -> list -> status -> release", async () => { const client = new FakeSimlockClient(); const grant = sampleGrant(); client.requestLeaseImpl = () => Promise.resolve(grant); @@ -67,6 +67,7 @@ describe("MCP server (smoke)", () => { "release_simulator", "lease_status", "run_on_device", + "rotate_device", ]); expect(tools.tools.find((tool) => tool.name === "list_devices")?.description).toContain( "modelClasses", @@ -84,6 +85,8 @@ describe("MCP server (smoke)", () => { "stdin", "tool", ]); + const rotateTool = tools.tools.find((tool) => tool.name === "rotate_device"); + expect(Object.keys(rotateTool?.inputSchema.properties ?? {})).toEqual(["orientation"]); expect(runTool?.description).toBe( "Run one simctl, adb or devicectl command on this session's leased device, on the machine that holds it. Leave the device out: Simlock fills in the lease's UDID or serial, and refuses a command that names another device. File paths are on that machine. Output is text: stdout and stderr each keep their last 32768 characters, and truncated says when any was cut. A non-zero exitCode is the command's own answer, not a tool error. There is no terminal: a bare adb shell is refused, and an interactive command hangs until the time limit (10 minutes by default) stops it.", ); diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 83b7f4147..e82a3c51f 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -15,6 +15,8 @@ import { listDevicesOutputSchema, releaseSimulatorInputSchema, releaseSimulatorOutputSchema, + rotateDeviceInputSchema, + rotateDeviceOutputSchema, runOnDeviceInputSchema, runOnDeviceOutputSchema, } from "./contracts.js"; @@ -346,6 +348,24 @@ export function createMcpServer( void server.server.sendLoggingMessage(deviceHealthLoggingMessage(notice)); }); + server.registerTool( + "rotate_device", + { + title: "Rotate device", + description: + "Turn this session's leased iOS simulator to portrait, portrait-upside-down, landscape-left or landscape-right. Only an iOS phone or tablet simulator rotates: an Android emulator, a physical device or an Apple TV is refused with ROTATION_UNSUPPORTED.", + inputSchema: rotateDeviceInputSchema, + outputSchema: rotateDeviceOutputSchema, + }, + async (input) => { + try { + return success(await session.rotateDevice(input)); + } catch (error: unknown) { + return failure(error); + } + }, + ); + return server; } diff --git a/src/mcp/session.ts b/src/mcp/session.ts index 1a6188dd4..1b6e73c2d 100644 --- a/src/mcp/session.ts +++ b/src/mcp/session.ts @@ -8,6 +8,7 @@ import { type LeaseRequestInput, type SimlockClient, } from "../client/index.js"; +import { parseOrientation } from "../contract/index.js"; import { awaitWithin, RELEASE_TIMEOUT_MS, @@ -23,6 +24,8 @@ import type { ListDevicesOutput, ReleaseSimulatorInput, ReleaseSimulatorOutput, + RotateDeviceInput, + RotateDeviceOutput, RunOnDeviceInput, } from "./contracts.js"; @@ -300,6 +303,22 @@ export class McpSession { return client.exec({ ...input, leaseId }, { onOutput }); } + // why: not on `#mutate`, like `runOnDevice`; the parse is first so a bad spelling never reaches the daemon. + async rotateDevice(input: RotateDeviceInput): Promise { + this.#throwIfClosed(); + const parsed = parseOrientation(input.orientation); + if (!parsed.ok) throw new McpSessionError("BAD_REQUEST", parsed.message); + const leaseId = this.#heldLeaseId; + if (leaseId === undefined) { + throw new McpSessionError( + "NO_LEASE", + "This MCP session holds no lease. Call lease_simulator first.", + ); + } + const client = await this.#clientForUse(); + return client.rotate(leaseId, parsed.orientation); + } + /** Notifies when this session's held lease ends elsewhere (expiry or a force-release). */ onLeaseLost(listener: (notice: LeaseLostNotice) => void): () => void { this.#leaseLostListeners.add(listener); From a8dda2f95e10cf45cfb70d64e424767eaeaf0662 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:25:25 -0300 Subject: [PATCH 044/103] test: rotate_device answers NO_LEASE, BAD_REQUEST and the daemon's refusal as tool errors (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/mcp/server.test.ts | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index fde561c12..d32e5f057 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -914,8 +914,12 @@ describe("MCP rotate_device", () => { const client = new FakeSimlockClient(); client.requestLeaseImpl = () => Promise.resolve(sampleGrant()); client.rotateImpl = (leaseId, orientation) => Promise.resolve({ leaseId, orientation }); + client.releaseLeaseImpl = (input) => Promise.resolve({ leaseId: input.leaseId }); const { mcpClient, close } = await connectedServer(client); try { + const never = await call(mcpClient, "rotate_device", { orientation: "left" }); + expect(never.isError).toBe(true); + expect(JSON.parse(text(never)).code).toBe("NO_LEASE"); await call(mcpClient, "lease_simulator", { model: "iPhone 17 Pro", platform: "ios" }); const result = await call(mcpClient, "rotate_device", { orientation: "landscape-left" }); expect(result.isError).not.toBe(true); @@ -926,6 +930,40 @@ describe("MCP rotate_device", () => { expect(client.calls.filter((entry) => entry.method === "rotate")).toEqual([ { input: { leaseId: "lease-1", orientation: "landscape_left" }, method: "rotate" }, ]); + + const accepted = [{ orientation: "LEFT" }, { orientation: " upside-down " }]; + for (const entry of accepted) { + expect((await call(mcpClient, "rotate_device", entry)).isError).not.toBe(true); + } + const unknown = await call(mcpClient, "rotate_device", { orientation: "sideways" }); + expect(unknown.isError).toBe(true); + expect(JSON.parse(text(unknown))).toEqual({ + code: "BAD_REQUEST", + message: + "Unknown orientation sideways; use portrait, portrait-upside-down, landscape-left or landscape-right", + }); + const unsupported = new SimlockError( + "ROTATION_UNSUPPORTED", + "domain", + "Lease lease-1 is on an Android emulator; only an iOS simulator can be rotated", + { class: "emulator", leaseId: "lease-1", physical: false, platform: "android" }, + ); + client.rotateImpl = () => Promise.reject(unsupported); + const refusal = await call(mcpClient, "rotate_device", { orientation: "left" }); + expect(refusal.isError).toBe(true); + expect(JSON.parse(text(refusal))).toEqual({ + code: "ROTATION_UNSUPPORTED", + message: unsupported.message, + }); + client.rotateImpl = (leaseId, orientation) => Promise.resolve({ leaseId, orientation }); + + await call(mcpClient, "release_simulator", { leaseId: "lease-1" }); + const released = await call(mcpClient, "rotate_device", { orientation: "left" }); + expect(released.isError).toBe(true); + expect(JSON.parse(text(released))).toEqual({ + code: "NO_LEASE", + message: "This MCP session holds no lease. Call lease_simulator first.", + }); } finally { await close(); } From 77edefad04f04b86eef25fef74b227629d3bcbde Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:25:52 -0300 Subject: [PATCH 045/103] test: simlock instructions lists simlock rotate and rotate_device (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/instructions/index.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/instructions/index.test.ts b/src/instructions/index.test.ts index 78eacddcd..c5906fdf3 100644 --- a/src/instructions/index.test.ts +++ b/src/instructions/index.test.ts @@ -31,6 +31,7 @@ const TOOL_NAMES = [ "release_simulator", "lease_status", "run_on_device", + "rotate_device", ]; const REQUIRED: Readonly> = { @@ -99,6 +100,7 @@ const REQUIRED: Readonly> = ...REFUSED_ADB_SEQUENCES.map(({ sequence }) => `\`simlock adb ${sequence.join(" ")}\``), "`simlock adb` refuses any option before the subcommand other than `-s`, `-t`, `-d` or `-e`", "`simlock adb shell`", + "`simlock rotate `", ...[ ERROR_TABLE.QUEUE_TIMEOUT.cliExitCode, ERROR_TABLE.NO_CAPACITY.cliExitCode, From eae80be7fa10ed131c2b67af7346131f40dfed07 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:26:00 -0300 Subject: [PATCH 046/103] test: a socket whose write fails closes 1013 while the daemon keeps rotating (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/core/fake-device-input.ts | 7 +++++-- src/daemon/device-rotate.e2e.test.ts | 12 +++++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/core/fake-device-input.ts b/src/core/fake-device-input.ts index 5e560a4fc..2a0d033d3 100644 --- a/src/core/fake-device-input.ts +++ b/src/core/fake-device-input.ts @@ -14,7 +14,7 @@ class FakeDeviceInput implements DeviceInput { readonly #failedListeners = new Set<(error: Error) => void>(); #config: InputScreenConfig; - // why: a test sets this to make every write fail, as a helper whose pipe broke does. + // why: a test sets this to make every write fail and the input report it through `onFailed`, as a helper whose pipe broke does. sendFailure: Error | undefined; constructor(config: InputScreenConfig) { @@ -22,7 +22,10 @@ class FakeDeviceInput implements DeviceInput { } send(message: InputMessage): Promise { - if (this.sendFailure !== undefined) return Promise.reject(this.sendFailure); + if (this.sendFailure !== undefined) { + this.fail(this.sendFailure); + return Promise.reject(this.sendFailure); + } this.sent.push(message); return Promise.resolve(); } diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 1497facc0..7a98bcca9 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -260,7 +260,7 @@ describe("device.rotate", () => { ); it( - "refuses a holder's rotate with INPUT_UNAVAILABLE and the reason when the helper cannot start or the write fails", + "refuses a holder's rotate with INPUT_UNAVAILABLE and the reason when the helper cannot start or the write fails, and closes a socket whose write fails 1013 while the daemon keeps running", { timeout: 60_000 }, async () => { const screen = { height: 2556, orientation: "portrait", width: 1179 } as const; @@ -327,6 +327,16 @@ describe("device.rotate", () => { ).toEqual(input.opened.map(() => 1)); await daemons.pop()?.stop("test"); } + + const failing = new FakeInputFactory(screen); + failing.sendFailure = new Error("pipe closed"); + const { daemon, leaseId, openSocket, session } = await holderWithSocketAccess(failing); + const socket = await openSocket(); + sockets.at(-1)?.send(Buffer.concat([Buffer.from([0x04]), Buffer.from('{"button":"lock"}')])); + await vi.waitFor(() => expect(socket.code).toBe(1013), { timeout: 10_000 }); + await expect( + daemon.dispatch("device.rotate", { leaseId, orientation: "portrait" }, session), + ).rejects.toMatchObject({ code: "INPUT_UNAVAILABLE", details: { reason: "pipe closed" } }); }, ); From 6d6c5ea2feb938cb8d3fc787de96692dded89f9c Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:26:08 -0300 Subject: [PATCH 047/103] feat(instructions): simlock instructions lists simlock rotate and rotate_device (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/instructions/index.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/instructions/index.ts b/src/instructions/index.ts index 757d463bf..f0d53b30c 100644 --- a/src/instructions/index.ts +++ b/src/instructions/index.ts @@ -40,6 +40,7 @@ const SIMLOCK_CLI = `## simlock CLI - The JSON line holds \`lease.id\`, \`lease.ttlDeadline\`, \`device.address\` and \`environment\`. \`--export-env\` prints \`environment\` as shell \`export\` lines. - Release with \`simlock release \`, or stop the background \`simlock lease\`. - Reach the device through \`simlock simctl\` and \`simlock adb -s \`, or through the grant's \`environment\`. On another machine, use \`simlock simctl --lease \` and \`simlock adb --lease \`. +- Turn an iOS simulator with \`simlock rotate \` (\`portrait\`, \`portrait-upside-down\`, \`landscape-left\` or \`landscape-right\`); add \`--lease \` when you hold more than one lease. - If this machine runs a gateway and the operator says to use it, put \`--gateway\` right after \`simlock\`. Some commands are refused on purpose, because they break the device for Simlock or for other agents. Do not work around them; release the lease instead. @@ -61,13 +62,14 @@ Every failure writes one JSON line on stderr, \`{"error":{"code":"...","message" const MCP = `## MCP -When Simlock is connected to you as an MCP server, it has five tools: +When Simlock is connected to you as an MCP server, it has six tools: - \`list_devices\`: what can be leased. Call it before leasing. - \`lease_simulator\`: lease one device. It is renewed for you and released when the server exits. - \`release_simulator\`: give the device back. - \`lease_status\`: whether you still hold a lease, and which. Call it after a context compaction. - \`run_on_device\`: run one \`simctl\`, \`adb\` or \`devicectl\` command on your leased device, for example install and launch an app. Leave the device out; Simlock fills it in. It returns \`exitCode\`, \`stdout\`, \`stderr\` and \`truncated\`; a non-zero exit code is the command's answer, not an error. +- \`rotate_device\`: turn your leased iOS simulator to \`portrait\`, \`portrait-upside-down\`, \`landscape-left\` or \`landscape-right\`. It returns \`leaseId\` and \`orientation\`; an Android emulator is refused. Under Codex and pi, the MCP server and the CLI are two identities: use only one of them per session.`; From e5bb97b5ff10d171cf5e77d081e1e8390aa3a055 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:26:57 -0300 Subject: [PATCH 048/103] test: simlock rotate --help and the root usage name the command (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/index.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 0ec3933b6..7ec5bdf22 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -10791,5 +10791,15 @@ describe("simlock rotate", () => { }, }); expect(unsupported.stdout).toBe(""); + + const help = await rotateWith(["rotate", "--help"], [heldLease]); + expect(help.exitCode).toBe(0); + expect(help.output.stdout).toBe( + "Usage: simlock rotate [--lease ]\n", + ); + expect(help.rotations).toEqual([]); + const listing = outputCapture(); + await runCli(["--help"], listing.environmentWith()); + expect(listing.stdout).toContain(" rotate [--lease ]"); }); }); From aced7b4bf160bf3839846e001151e8de73463940 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:26:59 -0300 Subject: [PATCH 049/103] test: fold the coordinator's rotate case into the HTTP gateway test that proves it (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/gateway/fleet-coordinator.test.ts | 45 --------------------------- src/gateway/test-support.ts | 16 ---------- 2 files changed, 61 deletions(-) diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index b0ef8dd73..3eb03b612 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -1109,51 +1109,6 @@ describe("FleetLeaseCoordinator dispatch", () => { expect(client.calls).toContain(`device.exec:${GATEWAY_PREFIX}agent-1`); }); - it("forwards device.rotate to the worker's own lease id with the namespaced requester, answers and names the caller's lease id", async () => { - const { coordinator, directory, workers } = harness(); - const client = new ScriptedWorkerClient(); - directory.add("wrk_a", client); - connectWorker(workers, "wrk_a"); - client.requestLeaseQueue.push({ - grant: grantFixture({ - lease: { - ...grantFixture().lease, - id: "lse_9", - ownerId: "agent-1", - requesterId: `${GATEWAY_PREFIX}agent-1`, - }, - }), - kind: "grant", - }); - const grant = await coordinator.request(REQUEST, requestOptions()); - const session = { - manageEventSubscription: () => undefined, - via: "socket", - principal: "agent-1", - role: "agent", - } as const; - - await expect( - coordinator.rotate({ leaseId: grant.lease.id, orientation: "landscape_left" }, session), - ).resolves.toEqual({ leaseId: grant.lease.id, orientation: "landscape_left" }); - expect(client.calls).toContain(`device.rotate:lse_9:${GATEWAY_PREFIX}agent-1`); - - client.rotateErrors.push( - fromWireError( - "ROTATION_UNSUPPORTED", - "Lease lse_9 is on an Apple TV simulator; only an iOS simulator can be rotated", - { class: "tv", leaseId: "lse_9", physical: false, platform: "ios" }, - ), - ); - await expect( - coordinator.rotate({ leaseId: grant.lease.id, orientation: "portrait" }, session), - ).rejects.toMatchObject({ - code: "ROTATION_UNSUPPORTED", - details: { class: "tv", leaseId: grant.lease.id, physical: false, platform: "ios" }, - message: `Lease ${grant.lease.id} is on an Apple TV simulator; only an iOS simulator can be rotated`, - }); - }); - it("announces started from the worker's own push, before any output (ADR §19a)", async () => { const { coordinator, directory, workers } = harness(); const client = new ScriptedWorkerClient(); diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index 1a98aed13..abcede425 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -16,7 +16,6 @@ import type { ExecInput, ExecOptions, ExecOutput, - RotateOutput, LeaseGrant, LeaseRecord, LeaseReleaseInput, @@ -332,8 +331,6 @@ export class ScriptedWorkerClient { * a test sets this to relay that event from inside the call. */ onReleaseLease: ((leaseId: string) => void) | undefined; readonly execQueue: ExecOutcome[] = []; - /** why: a test queues the error the worker's next `device.rotate` throws; an empty queue answers the rotation. */ - readonly rotateErrors: Error[] = []; /** * H4 (round 3 review): the `options` most recently passed to `exec` -- captured before * `execQueue`'s own outcome is even read, so a `"hang"` outcome (whose returned promise never @@ -499,19 +496,6 @@ export class ScriptedWorkerClient { return { exitCode: outcome?.exitCode ?? 0 }; } - // fallow-ignore-next-line unused-class-member -- reached through the GatewayWorkerClient that asClient() casts this double to. - async rotate( - leaseId: string, - orientation: RotateOutput["orientation"], - options: { readonly requesterId?: string } = {}, - ): Promise { - this.calls.push(`device.rotate:${leaseId}:${options.requesterId ?? ""}`); - this.#throwIfFailing(); - const error = this.rotateErrors.shift(); - if (error !== undefined) throw error; - return { leaseId, orientation }; - } - // fallow-ignore-next-line unused-class-member -- reached through the GatewayWorkerClient that asClient() casts this double to. async installComponent( input: ComponentInstallInput, From 0844848f7624cff1678d944129c572dea15b8bd9 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:27:31 -0300 Subject: [PATCH 050/103] chore: name how the coordinator's rotate is reached for Fallow (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/gateway/fleet-coordinator.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index 1b7bdc52f..eacae88a2 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -591,6 +591,7 @@ export class FleetLeaseCoordinator { /** * why: `device.rotate` forwarded to the worker that owns the lease, with the lease's own namespaced requester, bounded by `gateway.execTimeoutMs` like `exec`. A worker names the lease by its own id in a refusal; the caller holds the gateway's id, so the refusal names that instead. */ + // fallow-ignore-next-line unused-class-member -- reached only through `GatewayDispatcher`'s `Pick`-typed `coordinator` option. async rotate(input: FleetRotateInput, _session: DispatchSession): Promise { const entry = this.#requireEntry(input.leaseId); const requesterId = `${this.options.leaseIndex.requesterPrefix}${entry.requesterId}`; From 600ec74a60b7f1e31e5892360562ca5b65d7c0a4 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:27:35 -0300 Subject: [PATCH 051/103] test: a holder opens the tunnel socket through a gateway and it is relayed to the lease's worker (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/tunnel-lease.e2e.test.ts | 88 +++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/src/daemon/tunnel-lease.e2e.test.ts b/src/daemon/tunnel-lease.e2e.test.ts index b9dc43596..ada990a3b 100644 --- a/src/daemon/tunnel-lease.e2e.test.ts +++ b/src/daemon/tunnel-lease.e2e.test.ts @@ -94,6 +94,12 @@ describe("a lease's tunnel socket", () => { ); }); + async function directory(name: string): Promise { + const path = await mkdtemp(join(tmpdir(), `simlock-e2e-tunnel-${name}-`)); + directories.push(path); + return path; + } + async function standalone(enabled: boolean) { const port = await freeLoopbackPort(); const path = await mkdtemp(join(tmpdir(), "simlock-e2e-tunnel-")); @@ -140,6 +146,79 @@ describe("a lease's tunnel socket", () => { }; } + async function fleet(options: { + readonly gatewayTunnel: boolean; + readonly workerTunnel: boolean; + }) { + const port = await freeLoopbackPort(); + const gateway = await startDaemon({ + configOverrides: { + capabilities: { tunnel: { enabled: options.gatewayTunnel } }, + http: { enabled: true, host: "127.0.0.1", port }, + }, + dataDirectory: await directory("gateway"), + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + role: "gateway", + version: "1.0.0-e2e", + }); + daemons.push(gateway); + const token = (await gateway.dispatch("token.create", { label: "w", role: "worker" }, admin)) + .secret; + const deviceTcp = new FakeDeviceTcp(); + const worker = await startDaemon({ + configOverrides: { + capabilities: { tunnel: { enabled: options.workerTunnel } }, + gateway: { label: "w", token, url: `ws://127.0.0.1:${String(port)}` }, + }, + dataDirectory: await directory("worker"), + 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(worker); + await vi.waitFor( + async () => { + const { workers } = await gateway.dispatch("worker.list", {}, admin); + expect(workers[0]?.catalog?.length).toBeGreaterThan(0); + }, + { timeout: 10_000 }, + ); + const holder = await gateway.dispatch( + "token.create", + { label: "holder", role: "agent" }, + admin, + ); + const granted = await gateway.dispatch( + "lease.request", + { model: "Pixel-A", platform: "android" }, + { ...agent, principal: holder.token.id }, + ); + const leaseId = (granted as { lease: { id: string } }).lease.id; + await vi.waitFor( + () => gateway.dispatch("lease.get", { leaseId }, { ...agent, principal: holder.token.id }), + { timeout: 10_000 }, + ); + return { + deviceTcp, + gateway, + holder: holder.secret, + leaseId, + url: (id = leaseId) => `ws://127.0.0.1:${String(port)}/v1/leases/${id}/tunnel`, + worker, + }; + } + async function expectReady(url: string, token: string, devicePort: number): Promise { const opened = await openTunnel(url, token); expect(opened.status).toBe(101); @@ -178,4 +257,13 @@ describe("a lease's tunnel socket", () => { }); }, ); + + it( + "opens the tunnel socket through a gateway and relays it to the lease's worker", + { timeout: 60_000 }, + async () => { + const through = await fleet({ gatewayTunnel: true, workerTunnel: true }); + await expectReady(through.url(), through.holder, 5173); + }, + ); }); From 5a8d932e3afdf086faba5556bb8f1822dc20893a Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:27:59 -0300 Subject: [PATCH 052/103] test: a socket closing while hello awaits reverse leaves no rule set (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/core/fake-device-tcp.ts | 2 ++ src/tunnel/worker.test.ts | 11 +++++++++++ 2 files changed, 13 insertions(+) diff --git a/src/core/fake-device-tcp.ts b/src/core/fake-device-tcp.ts index d748352d3..e1869a2c1 100644 --- a/src/core/fake-device-tcp.ts +++ b/src/core/fake-device-tcp.ts @@ -34,6 +34,8 @@ export class FakeDeviceTcp implements DeviceTcp { closeFailure: Error | undefined; // why: a test sets a device port's failure to make its `reverse` refuse, as adb does for a port already reversed. readonly failures = new Map(); + // why: a test sets this to hold every `reverse` until it settles, as an adb call that is slow to answer does. + gate: Promise | undefined; readonly #reverses = new Map(); #nextHostPort = 47_000; diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index 2a35ea4e3..02ee20576 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -478,5 +478,16 @@ describe("a worker's tunnel socket", () => { ); expect(reclaimed.socket.closed).toEqual({ code: 4001, reason: "device-lost" }); expect(reclaimed.deviceTcp.reversed).toEqual([5173]); + + const racing = await setup(); + let release: () => void = () => undefined; + racing.deviceTcp.gate = new Promise((resolve) => { + release = resolve; + }); + const early = await attach(racing.worker); + early.receive(hello(tunnel)); + early.drop(); + release(); + await vi.waitFor(() => expect(racing.deviceTcp.reversed).toEqual([])); }); }); From bb30a14b2ea3a82e53f6f97f70735b03286167f3 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:28:20 -0300 Subject: [PATCH 053/103] fix(tunnel): a rule that arrives after the socket closed is removed (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/core/fake-device-tcp.ts | 1 + src/tunnel/sessions.ts | 23 ++++++++++++++--------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/core/fake-device-tcp.ts b/src/core/fake-device-tcp.ts index e1869a2c1..e19973d4c 100644 --- a/src/core/fake-device-tcp.ts +++ b/src/core/fake-device-tcp.ts @@ -52,6 +52,7 @@ export class FakeDeviceTcp implements DeviceTcp { devicePort: number, _signal?: AbortSignal, ): Promise { + await this.gate; const failure = this.failures.get(devicePort); if (failure !== undefined) throw failure; const hostPort = this.#nextHostPort; diff --git a/src/tunnel/sessions.ts b/src/tunnel/sessions.ts index a6cc7c034..b8a489ee1 100644 --- a/src/tunnel/sessions.ts +++ b/src/tunnel/sessions.ts @@ -142,19 +142,19 @@ export function createTunnelSessions(options: { } connections.clear(); if (!removeRules) return; - await Promise.all( - reverses.map((reverse) => - reverse.close().catch((error: unknown) => { - options.logger.warn("A tunnel's device rule could not be removed", { - error: stableError(error), - }); - }), - ), - ); + await Promise.all(reverses.map(removeRule)); })(); return finished; } + function removeRule(reverse: DeviceReverse): Promise { + return reverse.close().catch((error: unknown) => { + options.logger.warn("A tunnel's device rule could not be removed", { + error: stableError(error), + }); + }); + } + const session: Session = { finish, socket }; const mine = sessions.get(leaseId) ?? new Set(); mine.add(session); @@ -257,6 +257,11 @@ export function createTunnelSessions(options: { }); return; } + // why: the socket can close while `reverse` is awaited, after `finish` read the list; a rule that arrives then is removed here. + if (finished !== undefined) { + await removeRule(reverse); + return; + } reverses.push(reverse); reverse.onConnection((stream) => { if (connections.size >= MAX_CONNECTIONS) { From 01f44f729a092f1441c158aa46c6bca099ae25c9 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:28:48 -0300 Subject: [PATCH 054/103] feat(tunnel): a gateway relays the tunnel socket to the lease's worker (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/tunnel/channel.ts | 45 ++++++++++++++++++++++++ src/tunnel/definition.ts | 1 + src/tunnel/framing.ts | 51 +++++++++++++++++++++++++++ src/tunnel/gateway-link.ts | 71 ++++++++++++++++++++++++++++++++++++++ src/tunnel/gateway.ts | 16 +++++++++ src/tunnel/worker.ts | 10 ++++++ 6 files changed, 194 insertions(+) create mode 100644 src/tunnel/channel.ts create mode 100644 src/tunnel/framing.ts create mode 100644 src/tunnel/gateway-link.ts create mode 100644 src/tunnel/gateway.ts diff --git a/src/tunnel/channel.ts b/src/tunnel/channel.ts new file mode 100644 index 000000000..1b2a206e4 --- /dev/null +++ b/src/tunnel/channel.ts @@ -0,0 +1,45 @@ +import type { ModuleTwoWayPipe } from "../modules/index.js"; +import type { LeaseSocket } from "../ports/index.js"; +import { encodeFrame, readFrames } from "./framing.js"; + +// why: a worker's tunnel session talks to a gateway's client through a relay channel, and the session +// takes a `LeaseSocket` whichever door the client came in by; this is the channel's end of that port, +// a socket whose messages are frames of the channel. +export function channelSocket(pipe: ModuleTwoWayPipe): LeaseSocket { + const writer = pipe.writable.getWriter(); + const messageListeners: ((data: Uint8Array) => void)[] = []; + const closeListeners: (() => void)[] = []; + let writes: Promise = Promise.resolve(); + let closed = false; + const markClosed = (): void => { + if (closed) return; + closed = true; + for (const listener of closeListeners) listener(); + }; + const write = (frame: Uint8Array): void => { + writes = writes.then(() => writer.write(frame)).catch(() => undefined); + }; + void (async () => { + for await (const frame of readFrames(pipe.readable)) { + const message = new Uint8Array(1 + frame.payload.length); + message[0] = frame.tag; + message.set(frame.payload, 1); + for (const listener of messageListeners) listener(message); + } + markClosed(); + })(); + pipe.signal.addEventListener("abort", markClosed, { once: true }); + return { + close: () => { + writes = writes.then(() => writer.close()).catch(() => undefined); + markClosed(); + }, + onClose: (listener) => { + closeListeners.push(listener); + }, + onMessage: (listener) => { + messageListeners.push(listener); + }, + send: (data) => write(encodeFrame(data[0] ?? 0, data.subarray(1))), + }; +} diff --git a/src/tunnel/definition.ts b/src/tunnel/definition.ts index 0e1d9e95a..9db1453f2 100644 --- a/src/tunnel/definition.ts +++ b/src/tunnel/definition.ts @@ -30,6 +30,7 @@ export const tunnelModule: OptionalModuleDefinition = { }, ], }, + loadGateway: () => import("./gateway.js"), loadWorker: () => import("./worker.js"), name: "tunnel", }; diff --git a/src/tunnel/framing.ts b/src/tunnel/framing.ts new file mode 100644 index 000000000..540d48959 --- /dev/null +++ b/src/tunnel/framing.ts @@ -0,0 +1,51 @@ +// why: the channel framing of a two-way relay (ADR 0049 section 5): `[len u32 big-endian][tag u8][payload]`, +// `len` counting the tag and the payload. Only the tunnel module encodes and reads it; the relay moves bytes. +import { TUNNEL_MAX_DATA_BYTES } from "../contract/index.js"; + +// why: a tunnel message is `[tag][conn u32][payload]` with a payload of at most one DATA's bytes, and the channel carries one message per frame. +export const MAX_TUNNEL_MESSAGE_BYTES = 5 + TUNNEL_MAX_DATA_BYTES; + +export interface ChannelFrame { + readonly tag: number; + readonly payload: Uint8Array; +} + +export function encodeFrame(tag: number, payload: Uint8Array): Uint8Array { + const frame = new Uint8Array(5 + payload.length); + new DataView(frame.buffer).setUint32(0, payload.length + 1); + frame[4] = tag; + frame.set(payload, 5); + return frame; +} + +function joined(head: Uint8Array, tail: Uint8Array): Uint8Array { + const all = new Uint8Array(head.length + tail.length); + all.set(head); + all.set(tail, head.length); + return all; +} + +// why: ends quietly on a frame longer than a message may be, a stream that ends mid-frame and a stream +// that errors, so a peer that breaks the framing or drops is the same as one that went away. +export async function* readFrames( + readable: ReadableStream, +): AsyncGenerator { + const reader = readable.getReader(); + let buffer: Uint8Array = new Uint8Array(); + try { + for (;;) { + while (buffer.length >= 4) { + const length = new DataView(buffer.buffer, buffer.byteOffset, buffer.length).getUint32(0); + if (length < 1 || length > MAX_TUNNEL_MESSAGE_BYTES + 1) return; + if (buffer.length < 4 + length) break; + yield { payload: buffer.slice(5, 4 + length), tag: buffer[4] ?? 0 }; + buffer = buffer.subarray(4 + length); + } + const step = await reader.read().catch(() => undefined); + if (step === undefined || step.done) return; + buffer = joined(buffer, step.value); + } + } finally { + void reader.cancel().catch(() => undefined); + } +} diff --git a/src/tunnel/gateway-link.ts b/src/tunnel/gateway-link.ts new file mode 100644 index 000000000..ad83cf46c --- /dev/null +++ b/src/tunnel/gateway-link.ts @@ -0,0 +1,71 @@ +import type { + ModuleIdentity, + ModuleLease, + ModuleLeaseSocketAccept, + ModuleTwoWayRelay, +} from "../modules/index.js"; +import type { LeaseSocket } from "../ports/index.js"; +import { encodeFrame, MAX_TUNNEL_MESSAGE_BYTES, readFrames } from "./framing.js"; + +export interface GatewayTunnelLinkOptions { + readonly relayTwoWay: ( + workerId: string, + request: Request, + tenant: string, + leaseId?: string, + ) => Promise; + readonly requesterPrefix: string; +} + +export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { + open( + request: Request, + identity: ModuleIdentity, + lease: ModuleLease, + ): Promise; +} { + function bridge( + socket: LeaseSocket, + relay: ModuleTwoWayRelay, + controller: AbortController, + lease: ModuleLease, + ): void { + const writer = relay.writable.getWriter(); + let writes: Promise = Promise.resolve(); + socket.onMessage((data) => { + if (data.length > MAX_TUNNEL_MESSAGE_BYTES) return; + const frame = encodeFrame(data[0] ?? 0, data.subarray(1)); + writes = writes.then(() => writer.write(frame)).catch(() => undefined); + }); + socket.onClose(() => controller.abort()); + void (async () => { + for await (const frame of readFrames(relay.readable)) { + const message = new Uint8Array(1 + frame.payload.length); + message[0] = frame.tag; + message.set(frame.payload, 1); + socket.send(message); + } + socket.close(1011, `Worker ${lease.workerId ?? ""} stopped answering`); + controller.abort(); + })(); + } + + return { + open: async (_request, identity, lease) => { + const controller = new AbortController(); + const relay = await options.relayTwoWay( + lease.workerId ?? "", + new Request(`http://simlock-worker/tunnel/leases/${encodeURIComponent(lease.id)}`, { + method: "GET", + signal: controller.signal, + }), + `${options.requesterPrefix}${identity.principal}`, + lease.workerLeaseId, + ); + if (relay instanceof Response) return relay; + return Object.assign((socket: LeaseSocket) => bridge(socket, relay, controller, lease), { + abandon: () => controller.abort(), + }); + }, + }; +} diff --git a/src/tunnel/gateway.ts b/src/tunnel/gateway.ts new file mode 100644 index 000000000..178401530 --- /dev/null +++ b/src/tunnel/gateway.ts @@ -0,0 +1,16 @@ +import type { GatewayContext, GatewayModule } from "../modules/index.js"; +import type { TunnelModuleConfig } from "./definition.js"; +import { createGatewayTunnelLink } from "./gateway-link.js"; +import { upgradeRequired } from "./refusal.js"; + +export function createGateway(ctx: GatewayContext): GatewayModule { + const link = createGatewayTunnelLink({ + relayTwoWay: (workerId, request, tenant, leaseId) => + ctx.relayTwoWay(workerId, request, tenant, leaseId), + requesterPrefix: ctx.requesterPrefix, + }); + return { + leaseRoute: () => Promise.resolve(upgradeRequired()), + socket: { open: link.open }, + }; +} diff --git a/src/tunnel/worker.ts b/src/tunnel/worker.ts index 9d59b7fea..560f22600 100644 --- a/src/tunnel/worker.ts +++ b/src/tunnel/worker.ts @@ -1,6 +1,7 @@ import type { LeaseRecord } from "../core/index.js"; import type { WorkerContext, WorkerModule } from "../modules/index.js"; import type { TunnelModuleConfig } from "./definition.js"; +import { channelSocket } from "./channel.js"; import { unknownLease, upgradeRequired } from "./refusal.js"; import { createTunnelSessions } from "./sessions.js"; @@ -13,6 +14,15 @@ export function createWorker(ctx: WorkerContext): WorkerModu beforeDrain: () => sessions.drain(), }, leaseRoute: () => Promise.resolve(upgradeRequired()), + relayTwoWay: (_request, _tenant, leaseId, pipe) => { + const lease = ctx.registry.snapshot.leases.find((entry) => entry.id === leaseId); + const device = ctx.registry.snapshot.devices.find((entry) => entry.id === lease?.deviceId); + if (lease === undefined || device === undefined) { + return Promise.resolve(unknownLease(leaseId ?? "")); + } + sessions.attach(lease.id, device, channelSocket(pipe)); + return Promise.resolve(new Response(null, { status: 200 })); + }, socket: { open: (_request, _identity, held) => { const lease: LeaseRecord | undefined = ctx.registry.snapshot.leases.find( From d6792673b5dc9c845bfc1bc4ca200516975f197a Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:29:48 -0300 Subject: [PATCH 055/103] test: a worker with tunnels off answers 503 TUNNEL_UNAVAILABLE through a gateway (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/tunnel-lease.e2e.test.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/daemon/tunnel-lease.e2e.test.ts b/src/daemon/tunnel-lease.e2e.test.ts index ada990a3b..03a9007af 100644 --- a/src/daemon/tunnel-lease.e2e.test.ts +++ b/src/daemon/tunnel-lease.e2e.test.ts @@ -264,6 +264,13 @@ describe("a lease's tunnel socket", () => { async () => { const through = await fleet({ gatewayTunnel: true, workerTunnel: true }); await expectReady(through.url(), through.holder, 5173); + + const workerOff = await fleet({ gatewayTunnel: true, workerTunnel: false }); + const refused = await openTunnel(workerOff.url(), workerOff.holder); + expect({ code: refused.code, status: refused.status }).toEqual({ + code: "TUNNEL_UNAVAILABLE", + status: 503, + }); }, ); }); From c28989a64bb0f8532c6f9aa3849aa7725c96c04f Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:30:13 -0300 Subject: [PATCH 056/103] feat(tunnel): a worker with tunnels off answers 503 TUNNEL_UNAVAILABLE through a gateway (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/tunnel/gateway-link.ts | 36 +++++++++++++++++++++++++++--------- src/tunnel/refusal.ts | 4 ++++ 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/src/tunnel/gateway-link.ts b/src/tunnel/gateway-link.ts index ad83cf46c..a60c415cc 100644 --- a/src/tunnel/gateway-link.ts +++ b/src/tunnel/gateway-link.ts @@ -5,6 +5,7 @@ import type { ModuleTwoWayRelay, } from "../modules/index.js"; import type { LeaseSocket } from "../ports/index.js"; +import { unavailable } from "./refusal.js"; import { encodeFrame, MAX_TUNNEL_MESSAGE_BYTES, readFrames } from "./framing.js"; export interface GatewayTunnelLinkOptions { @@ -17,6 +18,17 @@ export interface GatewayTunnelLinkOptions { readonly requesterPrefix: string; } +// why: a worker with tunnels off has no relay target, and a holder must get a 503 that says to turn the capability on there, before the upgrade; an error with no such code is a real fault and goes on to the HTTP layer's 500. +function refusalFor(error: unknown, workerId: string): Response { + if ((error as { readonly code?: unknown }).code === "RELAY_TARGET_MISSING") { + return unavailable( + "TUNNEL_UNAVAILABLE", + `Tunnels are off on worker ${workerId}; turn on capabilities.tunnel.enabled there`, + ); + } + throw error; +} + export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { open( request: Request, @@ -53,15 +65,21 @@ export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { return { open: async (_request, identity, lease) => { const controller = new AbortController(); - const relay = await options.relayTwoWay( - lease.workerId ?? "", - new Request(`http://simlock-worker/tunnel/leases/${encodeURIComponent(lease.id)}`, { - method: "GET", - signal: controller.signal, - }), - `${options.requesterPrefix}${identity.principal}`, - lease.workerLeaseId, - ); + const workerId = lease.workerId ?? ""; + let relay: Response | ModuleTwoWayRelay; + try { + relay = await options.relayTwoWay( + workerId, + new Request(`http://simlock-worker/tunnel/leases/${encodeURIComponent(lease.id)}`, { + method: "GET", + signal: controller.signal, + }), + `${options.requesterPrefix}${identity.principal}`, + lease.workerLeaseId, + ); + } catch (error) { + return refusalFor(error, workerId); + } if (relay instanceof Response) return relay; return Object.assign((socket: LeaseSocket) => bridge(socket, relay, controller, lease), { abandon: () => controller.abort(), diff --git a/src/tunnel/refusal.ts b/src/tunnel/refusal.ts index ce5a146d8..bd4bd542b 100644 --- a/src/tunnel/refusal.ts +++ b/src/tunnel/refusal.ts @@ -12,6 +12,10 @@ export function upgradeRequired(): Response { }); } +export function unavailable(code: string, message: string): Response { + return refusal(503, code, message); +} + export function unknownLease(leaseId: string): Response { return refusal(404, "UNKNOWN_LEASE", `Unknown lease: ${leaseId}`); } From 364bb73bbd0dc753fe8c03f72ea04a4b2a512f20 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:31:15 -0300 Subject: [PATCH 057/103] test: a full-size DATA is relayed and a worker's REFUSED closes the holder's socket 4003 through a gateway (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/tunnel-lease.e2e.test.ts | 31 ++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/daemon/tunnel-lease.e2e.test.ts b/src/daemon/tunnel-lease.e2e.test.ts index 03a9007af..6bc423e57 100644 --- a/src/daemon/tunnel-lease.e2e.test.ts +++ b/src/daemon/tunnel-lease.e2e.test.ts @@ -42,6 +42,8 @@ interface OpenedSocket { readonly code: string | undefined; readonly messages: Buffer[]; readonly socket: WebSocket; + // why: how the socket closed, once it has; read it again after waiting, it changes. + readonly closed: { code: number; reason: string } | undefined; } const sockets: WebSocket[] = []; @@ -53,6 +55,10 @@ async function openTunnel(url: string, token: string | undefined): Promise messages.push(data as Buffer)); + const state: { closed: { code: number; reason: string } | undefined } = { closed: undefined }; + socket.on("close", (code, reason) => { + state.closed = { code, reason: reason.toString("utf8") }; + }); const outcome = await new Promise<{ status: number; code: string | undefined }>( (resolve, reject) => { socket.once("open", () => resolve({ code: undefined, status: 101 })); @@ -74,7 +80,14 @@ async function openTunnel(url: string, token: string | undefined): Promise { const through = await fleet({ gatewayTunnel: true, workerTunnel: true }); await expectReady(through.url(), through.holder, 5173); + const carried = await openTunnel(through.url(), through.holder); + carried.socket.send(hello(5174)); + await vi.waitFor(() => expect(carried.messages).toHaveLength(1), { timeout: 10_000 }); + const device = through.deviceTcp.connect(5174); + await vi.waitFor(() => expect(carried.messages).toHaveLength(2), { timeout: 10_000 }); + expect(carried.messages[1]?.[0]).toBe(0x02); + device.send(new Uint8Array(65_536).fill(7)); + await vi.waitFor(() => expect(carried.messages).toHaveLength(3), { timeout: 10_000 }); + expect(carried.messages[2]?.length).toBe(65_541); + expect(carried.messages[2]?.[0]).toBe(0x03); + + const refusedHello = await openTunnel(through.url(), through.holder); + refusedHello.socket.send(hello(80)); + await vi.waitFor(() => expect(refusedHello.closed?.code).toBe(4003), { timeout: 10_000 }); + expect(refusedHello.messages.map((entry) => entry[0])).toEqual([0x82]); + const workerOff = await fleet({ gatewayTunnel: true, workerTunnel: false }); const refused = await openTunnel(workerOff.url(), workerOff.holder); expect({ code: refused.code, status: refused.status }).toEqual({ From 8c98b94224e160f3cf5c60c78fd7157f9b2524db Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:31:17 -0300 Subject: [PATCH 058/103] feat(cli): simlock rotate --help, the root usage, the CLI reference and the manuals name rotate (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/AGENTS.md | 43 +++++++++++-------- src/cli/commands/rotate.ts | 11 ++++- src/cli/index.ts | 3 ++ src/mcp/AGENTS.md | 8 +++- .../getting-started/connect-your-agent.mdx | 3 +- .../src/content/docs/docs/reference/cli.mdx | 17 +++++++- 6 files changed, 61 insertions(+), 24 deletions(-) diff --git a/src/cli/AGENTS.md b/src/cli/AGENTS.md index dc66206d6..b69dd3f67 100644 --- a/src/cli/AGENTS.md +++ b/src/cli/AGENTS.md @@ -19,25 +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`: a piped stdin for `simctl`/`adb`, read to EOF | -| `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`: a piped stdin for `simctl`/`adb`, read to EOF | +| `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` | `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`. @@ -89,6 +90,10 @@ Surface: [cli.mdx](../../website/src/content/docs/docs/reference/cli.mdx) — ev fills the lease's device in and refuses another (ADR 0047). A piped stdin is read to EOF first; output chunks go to stdout and stderr. `PASSTHROUGH_REFUSED` and `UNKNOWN_PASSTHROUGH_TOOL` become usage errors (exit 2). + 5a. **`simlock rotate [--lease ]`** — `parseOrientation` (contract) spells the + 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. 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/rotate.ts b/src/cli/commands/rotate.ts index ec012d823..ef824ccba 100644 --- a/src/cli/commands/rotate.ts +++ b/src/cli/commands/rotate.ts @@ -8,7 +8,16 @@ async function run( argv: readonly string[], { environment, token }: CommandContext, ): Promise { - const { lease, positionals } = commandArgs(argv, { lease: { type: "string" } }); + const { help, lease, positionals } = commandArgs(argv, { + help: { type: "boolean", short: "h" }, + lease: { type: "string" }, + }); + if (help) { + environment.stdout.write( + "Usage: simlock rotate [--lease ]\n", + ); + return 0; + } const parsed = parseOrientation(requiredPositional(positionals, "orientation")); if (!parsed.ok) throw new UsageError(parsed.message); const client = await connectDaemonClient(environment, token); diff --git a/src/cli/index.ts b/src/cli/index.ts index 05d6474d2..5af26b66f 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -33,6 +33,9 @@ Commands: device add --platform [--json] Enrol a physical device plugged into this host device remove [--json] Forget an enrolled physical device; the device is untouched + rotate [--lease ] + Turn the leased iOS simulator: portrait, portrait-upside-down, + landscape-left or landscape-right simctl Run xcrun simctl against Simlock's iOS device set adb Run adb against Simlock's adb server mcp Start the stdio MCP server diff --git a/src/mcp/AGENTS.md b/src/mcp/AGENTS.md index a76d0ff52..1a3a56572 100644 --- a/src/mcp/AGENTS.md +++ b/src/mcp/AGENTS.md @@ -41,8 +41,12 @@ Surface: [connect-your-agent.mdx](../../website/src/content/docs/docs/getting-st 32 768 characters; a non-zero exit is a result. No held lease: `NO_LEASE`. With a progress token: `notifications/progress` on the first output, then at most one a second, and every 10 s while silent (the session's clock). -4. **Serialize** — every tool call but `run_on_device` queues on one chain in `McpSession`; - `run_on_device` does not queue, so `lease_status` and `release_simulator` run while a command does. + - `rotate_device` → `device.rotate` on the held lease. Input: `orientation`, 1 to 64 characters, + parsed by the contract's `parseOrientation` (an unknown spelling: `BAD_REQUEST` with its + message, before any call). Result `{ leaseId, orientation }`. No held lease: `NO_LEASE`; the + daemon's refusal (`ROTATION_UNSUPPORTED`, `INPUT_UNAVAILABLE`) is the tool error. +4. **Serialize** — every tool call but `run_on_device` and `rotate_device` queues on one chain in + `McpSession`; those two do not queue, so `lease_status` and `release_simulator` run while a command does. 5. **Renew** — a grant starts `startLeaseRenewal` (lease-policy): every third of the TTL. 6. **Pushes** → MCP logging messages, logger `simlock`: lease lost (warning), device unhealthy (warning), device recovered (info). diff --git a/website/src/content/docs/docs/getting-started/connect-your-agent.mdx b/website/src/content/docs/docs/getting-started/connect-your-agent.mdx index 30b1a9ac8..56eb92c1e 100644 --- a/website/src/content/docs/docs/getting-started/connect-your-agent.mdx +++ b/website/src/content/docs/docs/getting-started/connect-your-agent.mdx @@ -66,7 +66,7 @@ While the request waits in the queue or a device boots, `simlock lease` blocks a ## Use the MCP server -`simlock mcp` runs Simlock's MCP server over stdio. It has five tools: +`simlock mcp` runs Simlock's MCP server over stdio. It has six tools: | Tool | What it does | | --- | --- | @@ -75,6 +75,7 @@ While the request waits in the queue or a device boots, `simlock lease` blocks a | `release_simulator` | Releases this session's lease. | | `lease_status` | Reports this session's lease, or `held: false` when it has none. Safe to call any time, for example after the agent's context was compacted. Through a gateway it can report `held: false` for up to about a minute after the worker holding the lease restarts, while the worker is `starting`; do not request a new device on that answer, call it again. | | `run_on_device` | Runs one `simctl`, `adb` or `devicectl` command on this session's lease, on the machine that holds the device. Takes `tool`, `args` and, optionally, `stdin`. Never takes a device or a lease id: Simlock fills in the lease's device and refuses a command that names another. Returns `{exitCode, stdout, stderr, truncated}`; stdout and stderr each keep their last 32768 characters, and `truncated` says when any was cut. A non-zero `exitCode` is the command's own answer, not an error. Without a lease it answers `NO_LEASE`. There is no terminal, and a command that waits for input is stopped after the time limit (10 minutes by default). | +| `rotate_device` | Turns this session's iOS simulator to an orientation. Takes `orientation`: `portrait`, `portrait-upside-down`, `landscape-left` or `landscape-right`. Returns `{leaseId, orientation}`. Without a lease it answers `NO_LEASE`; an unknown spelling is `BAD_REQUEST`; an Android emulator, a physical device or an Apple TV is refused with `ROTATION_UNSUPPORTED`. | The server sends the short version of the rules to the client when it connects, and the full text as the resource `simlock://instructions`. It renews its lease while it runs, and releases it when the agent tool closes the connection. It also starts the daemon if it is not running. diff --git a/website/src/content/docs/docs/reference/cli.mdx b/website/src/content/docs/docs/reference/cli.mdx index 12fa9d3d7..9497fbfc8 100644 --- a/website/src/content/docs/docs/reference/cli.mdx +++ b/website/src/content/docs/docs/reference/cli.mdx @@ -185,6 +185,21 @@ simlock adb [--lease ] The command exits with `adb`'s own exit code. Simlock refuses `adb kill-server`, flags that move adb to a different server, and (through a gateway) `adb shell` with no command, with `PASSTHROUGH_REFUSED` (exit 2). `-s`, `-t`, `-d` and `-e` are allowed before the subcommand. Through a gateway the worker adds `-s ` for an emulator, and refuses `-s` with another serial, `-e`, `-d` and `-t`. +## simlock rotate + +Turn your leased iOS simulator to an orientation, on a worker or through a gateway. It calls `device.rotate`, so only an iOS phone or tablet simulator turns. + +```text +simlock rotate [--lease ] +``` + +| Flag | Meaning | Default | +| --- | --- | --- | +| `` | `portrait`, `portrait-upside-down`, `landscape-left` or `landscape-right`. `left`, `right` and `upside-down` are short for the last three, case and surrounding spaces do not matter, and the underscore spellings (`landscape_left`) work too. | — | +| `--lease ` | The lease to turn, before or after the orientation. | Your only 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 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). @@ -200,7 +215,7 @@ simlock catalog [--platform ] [--json] ## simlock mcp -Start Simlock's MCP server on stdin and stdout, for an agent to call. It offers the tools `list_devices`, `lease_simulator`, `release_simulator`, `lease_status` and `run_on_device`. See [Connect your agent](/simlock/docs/getting-started/connect-your-agent). +Start Simlock's MCP server on stdin and stdout, for an agent to call. It offers the tools `list_devices`, `lease_simulator`, `release_simulator`, `lease_status`, `run_on_device` and `rotate_device`. See [Connect your agent](/simlock/docs/getting-started/connect-your-agent). ```text simlock mcp From 892278a3cdb30ea88ba78bfae298eeb52b07ec2d Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:31:40 -0300 Subject: [PATCH 059/103] feat(tunnel): the worker's close frame closes the holder's socket with its code and reason (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/tunnel/channel.ts | 7 +++++-- src/tunnel/framing.ts | 4 ++++ src/tunnel/gateway-link.ts | 27 ++++++++++++++++++++++++++- 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/tunnel/channel.ts b/src/tunnel/channel.ts index 1b2a206e4..4faf77035 100644 --- a/src/tunnel/channel.ts +++ b/src/tunnel/channel.ts @@ -1,6 +1,6 @@ import type { ModuleTwoWayPipe } from "../modules/index.js"; import type { LeaseSocket } from "../ports/index.js"; -import { encodeFrame, readFrames } from "./framing.js"; +import { CHANNEL_TAG, encodeFrame, readFrames } from "./framing.js"; // why: a worker's tunnel session talks to a gateway's client through a relay channel, and the session // takes a `LeaseSocket` whichever door the client came in by; this is the channel's end of that port, @@ -30,7 +30,10 @@ export function channelSocket(pipe: ModuleTwoWayPipe): LeaseSocket { })(); pipe.signal.addEventListener("abort", markClosed, { once: true }); return { - close: () => { + close: (code, reason) => { + write( + encodeFrame(CHANNEL_TAG.close, new TextEncoder().encode(JSON.stringify({ code, reason }))), + ); writes = writes.then(() => writer.close()).catch(() => undefined); markClosed(); }, diff --git a/src/tunnel/framing.ts b/src/tunnel/framing.ts index 540d48959..df547cd81 100644 --- a/src/tunnel/framing.ts +++ b/src/tunnel/framing.ts @@ -5,6 +5,10 @@ import { TUNNEL_MAX_DATA_BYTES } from "../contract/index.js"; // why: a tunnel message is `[tag][conn u32][payload]` with a payload of at most one DATA's bytes, and the channel carries one message per frame. export const MAX_TUNNEL_MESSAGE_BYTES = 5 + TUNNEL_MAX_DATA_BYTES; +// why: the two channel-only tags: a heartbeat the worker sends while it is alive, and the worker's close +// `{code, reason}`; neither reaches a client, and a client's tags are the tunnel's own. +export const CHANNEL_TAG = { close: 0xf1, heartbeat: 0xf0 } as const; + export interface ChannelFrame { readonly tag: number; readonly payload: Uint8Array; diff --git a/src/tunnel/gateway-link.ts b/src/tunnel/gateway-link.ts index a60c415cc..be95d37cf 100644 --- a/src/tunnel/gateway-link.ts +++ b/src/tunnel/gateway-link.ts @@ -6,7 +6,8 @@ import type { } from "../modules/index.js"; import type { LeaseSocket } from "../ports/index.js"; import { unavailable } from "./refusal.js"; -import { encodeFrame, MAX_TUNNEL_MESSAGE_BYTES, readFrames } from "./framing.js"; +import { closeReason } from "../core/index.js"; +import { CHANNEL_TAG, encodeFrame, MAX_TUNNEL_MESSAGE_BYTES, readFrames } from "./framing.js"; export interface GatewayTunnelLinkOptions { readonly relayTwoWay: ( @@ -29,6 +30,21 @@ function refusalFor(error: unknown, workerId: string): Response { throw error; } +// why: the worker's close is wire input from another process: a code and a reason a socket may close with, or nothing. +function closeOf(payload: Uint8Array): { code: number; reason: string } | undefined { + try { + const { code, reason } = JSON.parse(new TextDecoder().decode(payload)) as Record< + string, + unknown + >; + if (typeof code !== "number" || !Number.isInteger(code)) return undefined; + if (code !== 1001 && code !== 1013 && (code < 4000 || code > 4999)) return undefined; + return typeof reason === "string" ? { code, reason: closeReason(reason) } : undefined; + } catch { + return undefined; + } +} + export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { open( request: Request, @@ -52,6 +68,15 @@ export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { socket.onClose(() => controller.abort()); void (async () => { for await (const frame of readFrames(relay.readable)) { + if (frame.tag === CHANNEL_TAG.close) { + const closing = closeOf(frame.payload); + if (closing !== undefined) { + socket.close(closing.code, closing.reason); + controller.abort(); + return; + } + break; + } const message = new Uint8Array(1 + frame.payload.length); message[0] = frame.tag; message.set(frame.payload, 1); From 68d70ac27b94e9bf98cf3957649ef7ba72a00155 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:32:10 -0300 Subject: [PATCH 060/103] test: a caller frame over 65541 bytes is refused BAD_REQUEST and closed 4003 through a gateway (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/tunnel-lease.e2e.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/daemon/tunnel-lease.e2e.test.ts b/src/daemon/tunnel-lease.e2e.test.ts index 6bc423e57..649edba7d 100644 --- a/src/daemon/tunnel-lease.e2e.test.ts +++ b/src/daemon/tunnel-lease.e2e.test.ts @@ -289,6 +289,16 @@ describe("a lease's tunnel socket", () => { expect(carried.messages[2]?.length).toBe(65_541); expect(carried.messages[2]?.[0]).toBe(0x03); + const tooBig = Buffer.concat([Buffer.from([0x03, 0, 0, 0, 1]), Buffer.alloc(65_537)]); + expect(tooBig.length).toBe(65_542); + carried.socket.send(tooBig); + await vi.waitFor(() => expect(carried.closed?.code).toBe(4003), { timeout: 10_000 }); + const last = carried.messages.at(-1); + expect(last?.[0]).toBe(0x82); + expect(JSON.parse(last?.subarray(5).toString("utf8") ?? "")).toMatchObject({ + code: "BAD_REQUEST", + }); + const refusedHello = await openTunnel(through.url(), through.holder); refusedHello.socket.send(hello(80)); await vi.waitFor(() => expect(refusedHello.closed?.code).toBe(4003), { timeout: 10_000 }); From 12d19c766d4d6afbde51d3aa47cc729d01aa4ee7 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:32:21 -0300 Subject: [PATCH 061/103] feat(android): reclaim and daemon start remove stale tunnel rules, only on a device proved its own (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/core/device-tcp.ts | 6 +- src/core/driver-catalog.ts | 6 +- src/core/fake-device-tcp.ts | 2 + src/daemon/main.ts | 21 ++++++ src/drivers/android/device-tcp.ts | 70 ++++++++++++++++++++ src/drivers/android/index.test.ts | 29 ++++++++ src/drivers/android/index.ts | 27 +++++++- src/drivers/android/physical-handler.test.ts | 20 ++++++ 8 files changed, 176 insertions(+), 5 deletions(-) diff --git a/src/core/device-tcp.ts b/src/core/device-tcp.ts index 40733707d..f6bd9cd9c 100644 --- a/src/core/device-tcp.ts +++ b/src/core/device-tcp.ts @@ -1,10 +1,10 @@ import type { TcpStream } from "../ports/index.js"; import type { PhysicalDriverDevice, VirtualDriverDevice } from "./driver.js"; -// why: the two refusals a driver can name; the tunnel module passes the code on to the holder. +// why: the refusals a driver or the catalog can name; the tunnel module passes the code on to the holder. export class DeviceTcpError extends Error { constructor( - readonly code: "TUNNEL_PORT_IN_USE" | "TUNNEL_FAILED", + readonly code: "TUNNEL_PORT_IN_USE" | "TUNNEL_FAILED" | "TUNNEL_UNSUPPORTED", message: string, ) { super(message); @@ -24,6 +24,8 @@ export interface DeviceReverse { // leaves it out, and the tunnel module learns that from its absence rather than from a platform name. export interface DeviceTcp { supports(device: VirtualDriverDevice | PhysicalDriverDevice): boolean; + // why: called once at daemon start, before any lease is served: removes the rules a stopped daemon's tunnels left on devices proved Simlock's own, leased or idle. + sweep(devices: readonly (VirtualDriverDevice | PhysicalDriverDevice)[]): Promise; reverse( device: VirtualDriverDevice | PhysicalDriverDevice, devicePort: number, diff --git a/src/core/driver-catalog.ts b/src/core/driver-catalog.ts index d7ab480b1..5c84e49c9 100644 --- a/src/core/driver-catalog.ts +++ b/src/core/driver-catalog.ts @@ -10,7 +10,7 @@ import type { PhysicalDriverDevice, VirtualDriverDevice, } from "./driver.js"; -import type { DeviceReverse } from "./device-tcp.js"; +import { DeviceTcpError, type DeviceReverse } from "./device-tcp.js"; import type { DeviceInput, UnavailableDeviceInput } from "./input.js"; import { type ScreenFeed, ScreenNotSupportedError, type ScreenSettings } from "./screen.js"; import { stableError } from "./stable-error.js"; @@ -117,7 +117,9 @@ export class DriverCatalog { signal: AbortSignal, ): Promise { const deviceTcp = this.#drivers.get(platform)?.deviceTcp; - if (deviceTcp === undefined) throw new Error(`${platform} devices take no tunnel`); + if (deviceTcp === undefined) { + throw new DeviceTcpError("TUNNEL_UNSUPPORTED", `${platform} devices take no tunnel`); + } return await deviceTcp.reverse(device, devicePort, signal); } diff --git a/src/core/fake-device-tcp.ts b/src/core/fake-device-tcp.ts index e19973d4c..68888fbbb 100644 --- a/src/core/fake-device-tcp.ts +++ b/src/core/fake-device-tcp.ts @@ -47,6 +47,8 @@ export class FakeDeviceTcp implements DeviceTcp { return true; } + async sweep(): Promise {} + async reverse( _device: unknown, devicePort: number, diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 65aeb285c..aa09e1fea 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -41,7 +41,9 @@ import { warmPoolOwner, Nuke, SerializedDecision, + stableError, sweepWriteLeftovers, + toDriverDevice, } from "../core/index.js"; import { createLeasing } from "../leasing/index.js"; import { openStateDatabase, type StateDatabase } from "../state/index.js"; @@ -618,6 +620,25 @@ async function composeDaemon( processSupervisor, ...(process.getuid === undefined ? {} : { uid: process.getuid() }), }); + // why: before any request is served, so a tunnel rule a stopped daemon left is gone before a lease uses its device; each driver proves a device its own first. + await Promise.all( + drivers.map(async (driver) => { + try { + await driver.deviceTcp?.sweep( + registry.snapshot.devices + .filter( + (device) => device.spec.platform === driver.platform && device.state !== "deleted", + ) + .map((device) => toDriverDevice(device)), + ); + } catch (error) { + logger.warn("A driver's start sweep of tunnel rules failed", { + error: stableError(error), + platform: driver.platform, + }); + } + }), + ); await leasing.settleRequests(); const read = await core.readStartup(); const steps = [ diff --git a/src/drivers/android/device-tcp.ts b/src/drivers/android/device-tcp.ts index 8e679262e..37a3826ef 100644 --- a/src/drivers/android/device-tcp.ts +++ b/src/drivers/android/device-tcp.ts @@ -22,6 +22,9 @@ const CANNOT_REBIND = "cannot rebind existing socket"; export interface AndroidDeviceTcpOptions { readonly listeners: TcpListenerFactory; + // why: a sweep acts on a device only once the driver proved it Simlock's own; an emulator on a recorded serial may answer as another's (#284). + readonly isOwn: (device: VirtualDriverDevice | PhysicalDriverDevice) => Promise; + readonly warn: (message: string, detail: Record) => void; // why: the driver decides which adb server and environment a device's command runs on, and for a phone which check it passes first. readonly runAdb: ( device: VirtualDriverDevice | PhysicalDriverDevice, @@ -42,9 +45,76 @@ async function listenInRange(listeners: TcpListenerFactory): Promise { + try { + const result = await run(device, args, ADB_TIMEOUT_MS); + if (result.code === 0) return result.stdout; + warn("An adb tunnel cleanup call failed", { args, stderr: cut(result.stderr.trim()) }); + } catch (error) { + warn("An adb tunnel cleanup call failed", { + args, + error: cut(error instanceof Error ? error.message : String(error)), + }); + } + return undefined; +} + +function fields(output: string): string[][] { + return output + .split(/\r?\n/) + .map((line) => line.trim().split(/\s+/)) + .filter((parts) => parts.length >= 3); +} + +// why: reclaim of a device proved its own leaves none of the lease's rules: every reverse rule of this serial, and this serial's forwards one by one, because `forward --remove-all` would end every device's on the server. +export async function removeDeviceRules( + run: RunAdb, + warn: Warn, + device: Target, + serial: string, +): Promise { + await attempt(run, warn, device, ["reverse", "--remove-all"]); + const listed = await attempt(run, warn, device, ["forward", "--list"]); + for (const [owner, local] of fields(listed ?? "")) { + if (owner === serial && local !== undefined) { + await attempt(run, warn, device, ["forward", "--remove", local]); + } + } +} + +// why: at start only a rule into the loopback range the worker keeps for tunnels is Simlock's own; a holder's other rules stay. +async function removeTunnelRules(run: RunAdb, warn: Warn, device: Target): Promise { + const listed = await attempt(run, warn, device, ["reverse", "--list"]); + for (const [, deviceSide, hostSide] of fields(listed ?? "")) { + const port = /^tcp:(\d{1,5})$/.exec(hostSide ?? "")?.[1]; + if (port === undefined || deviceSide === undefined) continue; + if (Number(port) < TUNNEL_PORT_FIRST || Number(port) > TUNNEL_PORT_LAST) continue; + await attempt(run, warn, device, ["reverse", "--remove", deviceSide]); + } +} + export function createAndroidDeviceTcp(options: AndroidDeviceTcpOptions): DeviceTcp { return { supports: () => true, + async sweep(devices): Promise { + await Promise.all( + devices.map(async (device) => { + if (await options.isOwn(device)) { + await removeTunnelRules(options.runAdb, options.warn, device); + } + }), + ); + }, async reverse(device, devicePort): Promise { const listener = await listenInRange(options.listeners); const refuse = async (error: DeviceTcpError): Promise => { diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 0a40de69f..143233596 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -3458,6 +3458,35 @@ describe("AndroidDriver deviceTcp", () => { }); }); + it("sweeps at start only the reverse rules into 47000-47999 on a device proved its own, and removes nothing on an emulator that answers as another's", async () => { + const own = await driverWith([ + avdPathExpectation("emulator-5586"), + { + match: adb("-P", "5038", "-s", "emulator-5586", "reverse", "--list"), + result: { + code: 0, + stderr: "", + stdout: + "host-19 tcp:5173 tcp:47003\nhost-19 tcp:8081 tcp:8082\nhost-19 tcp:3000 tcp:47999\n", + }, + }, + { + match: adb("-P", "5038", "-s", "emulator-5586", "reverse", "--remove", "tcp:5173"), + result: ok, + }, + { + match: adb("-P", "5038", "-s", "emulator-5586", "reverse", "--remove", "tcp:3000"), + result: ok, + }, + ]); + await own.driver.deviceTcp?.sweep([emulator]); + expect(own.runner.calls.filter((call) => call.args.includes("--remove"))).toHaveLength(2); + + const foreign = await driverWith([avdPathExpectation("emulator-5586", "simlock_two")]); + await foreign.driver.deviceTcp?.sweep([emulator]); + expect(foreign.runner.calls.some((call) => call.args.includes("reverse"))).toBe(false); + }); + it("refuses a reverse with TUNNEL_PORT_IN_USE when adb cannot rebind, TUNNEL_FAILED for any other adb failure or when every tunnel port is busy, and frees the port it took", async () => { const cannotRebind = await driverWith([ { diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 902fcadb6..6d8800155 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -63,7 +63,7 @@ import { type TcpStreamConnector, type TimerHandle, } from "../../ports/index.js"; -import { createAndroidDeviceTcp } from "./device-tcp.js"; +import { createAndroidDeviceTcp, removeDeviceRules } from "./device-tcp.js"; import { AdbRegistrar } from "./adb-registrar.js"; import { AdbServerSupervisor, AdbServerUnavailableError } from "./adb-server.js"; import { isAndroidDriverData, type AndroidDriverData } from "./data.js"; @@ -530,6 +530,7 @@ export class AndroidDriver implements Driver { readonly #emulatorFlags: readonly string[]; readonly #baselineLaunchInputs: readonly string[]; readonly #locks = new Map>(); + readonly #warnCleanup: (message: string, detail: Record) => void; readonly #onDiagnostic: ((diagnostic: AndroidDriverDiagnostic) => void) | undefined; readonly #portAllocator: PortAllocator; readonly #processRunner: ProcessRunner; @@ -588,8 +589,11 @@ export class AndroidDriver implements Driver { ? undefined : createAndroidDeviceTcp({ listeners: options.tcpListener, + isOwn: (device) => this.#deviceIsOwn(device), runAdb: (device, args, timeoutMs) => this.#runAdbOn(device, args, timeoutMs), + warn: (message, detail) => options.logger?.warn(message, detail), }); + this.#warnCleanup = (message, detail) => options.logger?.warn(message, detail); // why: Where an AVD Simlock made before it owned a root still sits: the AVD home the user // had configured then, or the SDK's own default. Used only by `findLegacy` / // `destroyLegacy` -- the fallback CP3 deleted from the driver proper, kept exactly here @@ -1133,6 +1137,7 @@ export class AndroidDriver implements Driver { options: { readonly clean: "standard" | "full" }, ): Promise { if (isPhysicalDriverDevice(device)) { + await this.#removeRules(device, device.deviceId); return this.#physical.reclaim(device); } const data = this.#dataFor(device); @@ -1167,6 +1172,7 @@ export class AndroidDriver implements Driver { state.baselineCaptured = false; return { state: "shutdown", strategy: "wipe" }; } + await this.#removeRules({ ...device, physical: false as const }, data.serial); const restored = await this.#runOrThrow(this.#sdk.adb, [ "-s", data.serial, @@ -1190,6 +1196,25 @@ export class AndroidDriver implements Driver { }); } + // why: reclaim leaves no rule of the lease on a device proved its own; it never throws, so a failed removal does not fail the reclaim. + async #removeRules( + device: VirtualDriverDevice | PhysicalDriverDevice, + serial: string, + ): Promise { + await removeDeviceRules( + (target, args, timeoutMs) => this.#runAdbOn(target, args, timeoutMs), + this.#warnCleanup, + device, + serial, + ); + } + + async #deviceIsOwn(device: VirtualDriverDevice | PhysicalDriverDevice): Promise { + if (isPhysicalDriverDevice(device)) return true; + const data = this.#dataFor(device); + return data.serial !== "" && (await this.#serialIsOwn(data)); + } + reclaimStrategy( device: DriverDevice, options: { readonly clean: "standard" | "full" }, diff --git a/src/drivers/android/physical-handler.test.ts b/src/drivers/android/physical-handler.test.ts index 82f4afff4..1e0c42a83 100644 --- a/src/drivers/android/physical-handler.test.ts +++ b/src/drivers/android/physical-handler.test.ts @@ -1131,6 +1131,26 @@ describe("Android physical handler: reclaim", () => { expect(runner.installed).toEqual(["com.example.kept"]); }); + it("removes every reverse rule of the phone and only its own forwards, and goes on when a removal fails", async () => { + const { driver, runner } = await world(); + runner.override((rest) => + rest.slice(2).join(" ") === "forward --list" + ? OK(`${PHONE} tcp:18790 tcp:18791\nOTHER tcp:18792 tcp:18793\n`) + : rest.slice(2).join(" ") === "reverse --remove-all" + ? FAILED + : undefined, + ); + + const result = await driver.reclaim(PHYSICAL, { clean: "standard" }); + + expect(result).toMatchObject({ strategy: "uninstall" }); + expect(runner.rests.filter((rest) => rest[2] === "reverse" || rest[2] === "forward")).toEqual([ + ["-s", PHONE, "reverse", "--remove-all"], + ["-s", PHONE, "forward", "--list"], + ["-s", PHONE, "forward", "--remove", "tcp:18790"], + ]); + }); + it("with nothing off the list runs no uninstall", async () => { const { driver, runner } = await world(); runner.installed.splice(0, runner.installed.length, "com.example.kept"); From 1db9bab2cc3fa1c8b57b42aef66e11eb0443bcdf Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:32:28 -0300 Subject: [PATCH 062/103] feat(tunnel): a caller frame over 65541 bytes is refused BAD_REQUEST and closed 4003 through a gateway (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/tunnel/gateway-link.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/tunnel/gateway-link.ts b/src/tunnel/gateway-link.ts index be95d37cf..3608c1f32 100644 --- a/src/tunnel/gateway-link.ts +++ b/src/tunnel/gateway-link.ts @@ -6,6 +6,7 @@ import type { } from "../modules/index.js"; import type { LeaseSocket } from "../ports/index.js"; import { unavailable } from "./refusal.js"; +import { encodeTunnelFrame, TUNNEL_REFUSED_CLOSE, TUNNEL_TAG } from "../contract/index.js"; import { closeReason } from "../core/index.js"; import { CHANNEL_TAG, encodeFrame, MAX_TUNNEL_MESSAGE_BYTES, readFrames } from "./framing.js"; @@ -61,7 +62,20 @@ export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { const writer = relay.writable.getWriter(); let writes: Promise = Promise.resolve(); socket.onMessage((data) => { - if (data.length > MAX_TUNNEL_MESSAGE_BYTES) return; + if (data.length > MAX_TUNNEL_MESSAGE_BYTES) { + // why: a frame over the limit would break the channel for the whole lease, so the gateway refuses it as the worker refuses a bad frame. + const message = `a frame is longer than ${String(MAX_TUNNEL_MESSAGE_BYTES)} bytes`; + socket.send( + encodeTunnelFrame( + TUNNEL_TAG.refused, + 0, + JSON.stringify({ code: "BAD_REQUEST", message }), + ), + ); + socket.close(TUNNEL_REFUSED_CLOSE, message); + controller.abort(); + return; + } const frame = encodeFrame(data[0] ?? 0, data.subarray(1)); writes = writes.then(() => writer.write(frame)).catch(() => undefined); }); From bc08674d6f3014402718679d48e86e14867dcbdb Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:32:44 -0300 Subject: [PATCH 063/103] docs(android): the cleanup of stale tunnel rules at reclaim and start (#1112) Co-Authored-By: Claude Sonnet 5.5 --- docs/internal/flows/startup.md | 2 ++ src/drivers/android/AGENTS.md | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/internal/flows/startup.md b/docs/internal/flows/startup.md index 55295ece7..d8ccfc67d 100644 --- a/docs/internal/flows/startup.md +++ b/docs/internal/flows/startup.md @@ -54,6 +54,8 @@ reaches its settle step, the steps after the read are skipped. Before step 16 it removes the `....tmp` files and `....staging` directories of dead writers beside each device root and in the data directory (`sweepWriteLeftovers`). +Before step 16, a driver with `deviceTcp` sweeps the reverse rules into 47000-47999 a stopped daemon's tunnels left, on its owned devices, leased or idle (Android: `AndroidDriver` manual); a failure is a `warn`. + 16. Settle open requests — `leasing.settleRequests`: every `open` request fails `INTERNAL`; `lease.rejected` with reason `daemon-restarted`. 17. Startup read — `core.readStartup`: one `listManaged` per driver, side by side, diff --git a/src/drivers/android/AGENTS.md b/src/drivers/android/AGENTS.md index 174fdece6..b11b53fc7 100644 --- a/src/drivers/android/AGENTS.md +++ b/src/drivers/android/AGENTS.md @@ -115,7 +115,7 @@ No slim: `resolveSpec` ignores `mode` and returns a full spec. `fresh` is core's Screen — `screenCapture` and `input`, only when `create` got `scrcpyServerPath` and `tcpStreamConnector`: [screen](screen/AGENTS.md), [input](input/AGENTS.md). -Tunnels — `deviceTcp` (`device-tcp.ts`), only when `create` got `tcpListener`: `reverse` listens on a free loopback port in 47000-47999 (busy ones skipped; none free → `TUNNEL_FAILED`) and runs `adb reverse --no-rebind tcp: tcp:` on the device's own server (an emulator's on Simlock's port, a phone's on 5037 behind the gate), 10 s per call; `cannot rebind existing socket` → `TUNNEL_PORT_IN_USE`, any other failure → `TUNNEL_FAILED` (message cut to 200 characters). `close` removes the rule, then the listener; a removal that fails keeps the listener, closing every connection at once. +Tunnels — `deviceTcp` (`device-tcp.ts`), only when `create` got `tcpListener`: `reverse` listens on a free loopback port in 47000-47999 (busy ones skipped; none free → `TUNNEL_FAILED`) and runs `adb reverse --no-rebind tcp: tcp:` on the device's own server (an emulator's on Simlock's port, a phone's on 5037 behind the gate), 10 s per call; `cannot rebind existing socket` → `TUNNEL_PORT_IN_USE`, any other failure → `TUNNEL_FAILED` (message cut to 200 characters). `close` removes the rule, then the listener; a removal that fails keeps the listener, closing every connection at once. Cleanup: reclaim (with or without `tcpListener`) of a phone, and of an emulator once its ownership probe passed, runs `reverse --remove-all` and removes this serial's `forward --list` lines one by one with `forward --remove ` (never `--remove-all`); an emulator not proved its own is left alone. `deviceTcp.sweep` (only with `tcpListener`), called by the daemon before any request is served, removes on every present owned emulator and phone, leased or idle, the `reverse --list` rules whose host side is `tcp:47000`-`tcp:47999`. A failed removal is a `warn`; reclaim and start go on. Plain facts: `listCatalog`, a resolve of a model the library lacks and a library provision (seed) share one `AvdmanagerDeviceList`: `avdmanager list device` runs again only when the size or modified time of a file it reads profiles from changed, or one appeared or went: the tools package's `lib/sdklib/sdklib.core.jar` (legacy `tools/lib/sdklib*.jar`) and `source.properties`, the user's devices.xml, `devices.xml` in each `system-images/*/*/*` and `add-ons/*` directory (a new image is a new path), and `devices.xml` and `source.properties` in each `extras/*/*` directory (avdmanager reads an extra whose `source.properties` says `Extra.Path=DeviceProfiles`). Otherwise the last good answer is served; a failed run is not kept; concurrent callers share one run. The sdkmanager catalog is never read. Existing devices are not re-checked for fit. From a859b678527aff5c8416ea9b3c70d3cfa8c511fe Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:33:04 -0300 Subject: [PATCH 064/103] test: through a gateway the lease's end closes 4001, a stopping worker 1011 and a stopping gateway 1001 (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/tunnel-lease.e2e.test.ts | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/daemon/tunnel-lease.e2e.test.ts b/src/daemon/tunnel-lease.e2e.test.ts index 649edba7d..1d8557d82 100644 --- a/src/daemon/tunnel-lease.e2e.test.ts +++ b/src/daemon/tunnel-lease.e2e.test.ts @@ -227,6 +227,7 @@ describe("a lease's tunnel socket", () => { gateway, holder: holder.secret, leaseId, + owner: { ...agent, principal: holder.token.id }, url: (id = leaseId) => `ws://127.0.0.1:${String(port)}/v1/leases/${id}/tunnel`, worker, }; @@ -304,6 +305,40 @@ describe("a lease's tunnel socket", () => { await vi.waitFor(() => expect(refusedHello.closed?.code).toBe(4003), { timeout: 10_000 }); expect(refusedHello.messages.map((entry) => entry[0])).toEqual([0x82]); + const ends = await fleet({ gatewayTunnel: true, workerTunnel: true }); + const ending = await openTunnel(ends.url(), ends.holder); + ending.socket.send(hello(5173)); + await vi.waitFor(() => expect(ending.messages).toHaveLength(1), { timeout: 10_000 }); + await ends.gateway.dispatch("lease.release", { leaseId: ends.leaseId }, ends.owner); + await vi.waitFor(() => expect(ending.closed).toEqual({ code: 4001, reason: "explicit" }), { + timeout: 10_000, + }); + + const stopping = await fleet({ gatewayTunnel: true, workerTunnel: true }); + const viaWorker = await openTunnel(stopping.url(), stopping.holder); + viaWorker.socket.send(hello(5173)); + await vi.waitFor(() => expect(viaWorker.messages).toHaveLength(1), { timeout: 10_000 }); + const { workers } = await stopping.gateway.dispatch("worker.list", {}, admin); + await stopping.worker.stop("test"); + await vi.waitFor( + () => + expect(viaWorker.closed).toEqual({ + code: 1011, + reason: `Worker ${workers[0]?.id ?? ""} stopped answering`, + }), + { timeout: 10_000 }, + ); + + const draining = await fleet({ gatewayTunnel: true, workerTunnel: true }); + const viaGateway = await openTunnel(draining.url(), draining.holder); + viaGateway.socket.send(hello(5173)); + await vi.waitFor(() => expect(viaGateway.messages).toHaveLength(1), { timeout: 10_000 }); + await draining.gateway.stop("test"); + await vi.waitFor( + () => expect(viaGateway.closed).toEqual({ code: 1001, reason: "Simlock is stopping" }), + { timeout: 10_000 }, + ); + const workerOff = await fleet({ gatewayTunnel: true, workerTunnel: false }); const refused = await openTunnel(workerOff.url(), workerOff.holder); expect({ code: refused.code, status: refused.status }).toEqual({ From 19d0ca403081fc033c97587f6222b6e5052a6c51 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:33:36 -0300 Subject: [PATCH 065/103] chore(tunnel): Fallow findings of the tunnel cycles (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/drivers/android/device-tcp.ts | 4 ++-- src/ports/tcp-stream.ts | 4 +++- src/tunnel/sessions.ts | 3 +++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/drivers/android/device-tcp.ts b/src/drivers/android/device-tcp.ts index 37a3826ef..5903176e8 100644 --- a/src/drivers/android/device-tcp.ts +++ b/src/drivers/android/device-tcp.ts @@ -13,8 +13,8 @@ import type { } from "../../ports/index.js"; // why: the worker keeps these loopback ports for tunnels, so a rule into them is Simlock's own and a sweep may remove it. -export const TUNNEL_PORT_FIRST = 47_000; -export const TUNNEL_PORT_LAST = 47_999; +const TUNNEL_PORT_FIRST = 47_000; +const TUNNEL_PORT_LAST = 47_999; const ADB_TIMEOUT_MS = 10_000; const MESSAGE_LIMIT = 200; diff --git a/src/ports/tcp-stream.ts b/src/ports/tcp-stream.ts index b40fea971..bcd7a8dd6 100644 --- a/src/ports/tcp-stream.ts +++ b/src/ports/tcp-stream.ts @@ -88,7 +88,6 @@ export class NodeTcpStreamConnector implements TcpStreamConnector { } } -// fallow-ignore-next-line unused-export -- the public shape of FakeTcpStreamConnector.connections. export class FakeTcpPeer { readonly written: Uint8Array[] = []; closed = false; @@ -126,15 +125,18 @@ export class FakeTcpPeer { }; } + // fallow-ignore-next-line unused-class-member -- read by the tests that drive a fake stream. writtenText(): string { return this.written.map((chunk) => new TextDecoder().decode(chunk)).join(""); } + // fallow-ignore-next-line unused-class-member -- the device's side of a fake stream, called by tests. send(bytes: Uint8Array | string): void { if (this.closed) return; this.#controller.enqueue(typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes); } + // fallow-ignore-next-line unused-class-member -- the device's side ending, called by tests. end(): void { this.stream.close(); } diff --git a/src/tunnel/sessions.ts b/src/tunnel/sessions.ts index b8a489ee1..4178d85bd 100644 --- a/src/tunnel/sessions.ts +++ b/src/tunnel/sessions.ts @@ -54,6 +54,7 @@ function field(value: unknown, name: string): unknown { } // why: the HELLO is wire input from a holder, so its size and shape are checked before any of it is used; a string is what was wrong with it. +// fallow-ignore-next-line complexity -- one validator: each branch is one refusal the spec words. function parseHello(payload: Uint8Array): readonly Tunnel[] | string { if (payload.length > TUNNEL_HELLO_MAX_BYTES) { return `HELLO is longer than ${String(TUNNEL_HELLO_MAX_BYTES)} bytes`; @@ -217,6 +218,7 @@ export function createTunnelSessions(options: { socket.send(encodeTunnelFrame(TUNNEL_TAG.credit, conn, granted)); } + // fallow-ignore-next-line complexity -- one HELLO answer: each branch is one refusal or step the spec lists. async function hello(payload: Uint8Array): Promise { const named = parseHello(payload); if (typeof named === "string") { @@ -306,6 +308,7 @@ export function createTunnelSessions(options: { connection.wake?.(); } + // fallow-ignore-next-line complexity -- one frame dispatcher: each branch is one tag or refusal the spec lists. function handle(frame: TunnelFrame): void { if (!greeted) { if (frame.tag !== TUNNEL_TAG.hello) { From 3f09619154d5ee35840a5b643b3aab1184263fe7 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:33:50 -0300 Subject: [PATCH 066/103] feat(tunnel): a stopping worker closes the holder 1011 and a draining gateway 1001 (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/tunnel/gateway-link.ts | 42 ++++++++++++++++++++++++++++---------- src/tunnel/gateway.ts | 1 + 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/src/tunnel/gateway-link.ts b/src/tunnel/gateway-link.ts index 3608c1f32..386dbb067 100644 --- a/src/tunnel/gateway-link.ts +++ b/src/tunnel/gateway-link.ts @@ -31,6 +31,10 @@ function refusalFor(error: unknown, workerId: string): Response { throw error; } +interface Bridge { + readonly stop: (code: number, reason: string) => void; +} + // why: the worker's close is wire input from another process: a code and a reason a socket may close with, or nothing. function closeOf(payload: Uint8Array): { code: number; reason: string } | undefined { try { @@ -52,7 +56,10 @@ export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { identity: ModuleIdentity, lease: ModuleLease, ): Promise; + drain(): void; } { + const bridges = new Set(); + function bridge( socket: LeaseSocket, relay: ModuleTwoWayRelay, @@ -61,6 +68,16 @@ export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { ): void { const writer = relay.writable.getWriter(); let writes: Promise = Promise.resolve(); + let ended = false; + const mine: Bridge = { stop: (code, reason) => stop(code, reason) }; + bridges.add(mine); + function stop(code: number, reason: string): void { + if (ended) return; + ended = true; + bridges.delete(mine); + socket.close(code, closeReason(reason)); + controller.abort(); + } socket.onMessage((data) => { if (data.length > MAX_TUNNEL_MESSAGE_BYTES) { // why: a frame over the limit would break the channel for the whole lease, so the gateway refuses it as the worker refuses a bad frame. @@ -72,36 +89,39 @@ export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { JSON.stringify({ code: "BAD_REQUEST", message }), ), ); - socket.close(TUNNEL_REFUSED_CLOSE, message); - controller.abort(); + stop(TUNNEL_REFUSED_CLOSE, message); return; } const frame = encodeFrame(data[0] ?? 0, data.subarray(1)); writes = writes.then(() => writer.write(frame)).catch(() => undefined); }); - socket.onClose(() => controller.abort()); + socket.onClose(() => { + ended = true; + bridges.delete(mine); + controller.abort(); + }); void (async () => { for await (const frame of readFrames(relay.readable)) { if (frame.tag === CHANNEL_TAG.close) { const closing = closeOf(frame.payload); - if (closing !== undefined) { - socket.close(closing.code, closing.reason); - controller.abort(); - return; - } - break; + // why: a worker that is stopping says 1001, which is a statement about the gateway to a holder; to the holder the worker is gone. + if (closing === undefined || closing.code === 1001) break; + stop(closing.code, closing.reason); + return; } const message = new Uint8Array(1 + frame.payload.length); message[0] = frame.tag; message.set(frame.payload, 1); socket.send(message); } - socket.close(1011, `Worker ${lease.workerId ?? ""} stopped answering`); - controller.abort(); + stop(1011, `Worker ${lease.workerId ?? ""} stopped answering`); })(); } return { + drain: () => { + for (const each of bridges) each.stop(1001, "Simlock is stopping"); + }, open: async (_request, identity, lease) => { const controller = new AbortController(); const workerId = lease.workerId ?? ""; diff --git a/src/tunnel/gateway.ts b/src/tunnel/gateway.ts index 178401530..399a47f1d 100644 --- a/src/tunnel/gateway.ts +++ b/src/tunnel/gateway.ts @@ -10,6 +10,7 @@ export function createGateway(ctx: GatewayContext): GatewayM requesterPrefix: ctx.requesterPrefix, }); return { + hooks: { beforeDrain: () => Promise.resolve(link.drain()) }, leaseRoute: () => Promise.resolve(upgradeRequired()), socket: { open: link.open }, }; From f09c789478b55a452ac52184cf2e17e11d2b8e6a Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:34:18 -0300 Subject: [PATCH 067/103] test: the gateway's tunnel bridge bounds every wait on the worker (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/tunnel/gateway.test.ts | 114 +++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 src/tunnel/gateway.test.ts diff --git a/src/tunnel/gateway.test.ts b/src/tunnel/gateway.test.ts new file mode 100644 index 000000000..915b674be --- /dev/null +++ b/src/tunnel/gateway.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, it, vi } from "vitest"; + +import type { GatewayModule, ModuleLease, ModuleLeaseSocketAccept } from "../modules/index.js"; +import { fakeGatewayContext } from "../modules/testing.js"; +import { MemoryLeaseSocket } from "../ports/index.js"; +import { tunnelModule } from "./index.js"; + +const IDENTITY = { principal: "tok_holder", role: "agent" } as const; +const LEASE: ModuleLease = { + deviceId: "dev_1", + id: "L-42", + workerId: "w1", + workerLeaseId: "L-7", +}; + +const REMOVED = { + gatewayLeaseId: "L-42", + grantedAt: 0, + ownerId: "tok_holder", + requesterId: "gw:gw-test:tok_holder", + workerId: "w1", + workerLeaseId: "L-7", +}; + +// why: a relay that answers nothing until the gateway gives up on it, as a worker that never sends a head does. +function silentRelay(request: Request): Promise { + return new Promise((_resolve, reject) => { + request.signal.addEventListener("abort", () => reject(request.signal.reason), { once: true }); + }); +} + +async function gatewayWith(facts: Parameters[2]) { + const fake = await fakeGatewayContext("tunnel", {}, facts); + const loaded = await tunnelModule.loadGateway?.(); + const gateway: GatewayModule | undefined = loaded?.createGateway(fake.ctx); + if (gateway?.socket === undefined) throw new Error("the tunnel module has no gateway socket"); + return { clock: fake.clock, removeLease: fake.removeLease, socket: gateway.socket }; +} + +// why: the worker's end of a relay: `toGateway` writes what the worker sends, and the gateway's own writes go nowhere. +function relayPair() { + const toGateway = new TransformStream(); + const fromGateway = new TransformStream(); + return { + relay: { + headers: new Headers(), + readable: toGateway.readable, + status: 200, + writable: fromGateway.writable, + }, + worker: toGateway.writable.getWriter(), + }; +} + +// why: the worker's close frame written out by hand (`[len u32][0xF1][json]`), so the test does not read it with the code it tests. +function closeFrame(code: number, reason: string): Uint8Array { + const json = new TextEncoder().encode(JSON.stringify({ code, reason })); + return Uint8Array.from([0, 0, (json.length + 1) >> 8, (json.length + 1) & 0xff, 0xf1, ...json]); +} + +async function attached() { + const pair = relayPair(); + const built = await gatewayWith({ relayTwoWay: () => Promise.resolve(pair.relay) }); + const accept = await built.socket.open(new Request("http://simlock/tunnel"), IDENTITY, LEASE); + if (typeof accept !== "function") throw new Error("the socket was refused"); + const client = new MemoryLeaseSocket(); + (accept as ModuleLeaseSocketAccept)(client); + return { ...built, client, worker: pair.worker }; +} + +describe("a gateway's tunnel bridge", () => { + it("bounds every wait on the worker: no head in 10 s, a relay that ends, a lease removed with no worker close in 2 s", async () => { + const { clock, socket } = await gatewayWith({ relayTwoWay: silentRelay }); + let outcome: unknown; + void socket.open(new Request("http://simlock/tunnel"), IDENTITY, LEASE).then((answer) => { + outcome = answer; + }); + clock.advance(9_999); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(outcome).toBeUndefined(); + clock.advance(1); + await vi.waitFor(() => expect(outcome).toBeInstanceOf(Response)); + const refusal = outcome as Response; + expect(refusal.status).toBe(503); + expect(await refusal.json()).toEqual({ + error: { + code: "WORKER_UNREACHABLE", + message: "Worker w1 did not answer the tunnel socket within 10 s", + }, + }); + + const ended = await attached(); + await ended.worker.close(); + await vi.waitFor(() => + expect(ended.client.closed).toEqual({ code: 1011, reason: "Worker w1 stopped answering" }), + ); + + const reasoned = await attached(); + reasoned.removeLease(REMOVED); + reasoned.clock.advance(1_999); + expect(reasoned.client.closed).toBeUndefined(); + await reasoned.worker.write(closeFrame(4001, "expired")); + await vi.waitFor(() => + expect(reasoned.client.closed).toEqual({ code: 4001, reason: "expired" }), + ); + + const silent = await attached(); + silent.removeLease(REMOVED); + silent.clock.advance(1_999); + expect(silent.client.closed).toBeUndefined(); + silent.clock.advance(1); + expect(silent.client.closed).toEqual({ code: 4001, reason: "lease ended" }); + }); +}); From 4c09bca6caff7a0c71d411416b3649ae16a6cb8e Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:34:43 -0300 Subject: [PATCH 068/103] feat(tunnel): the gateway bounds its open to 10 s and a lease's removal to 2 s (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/tunnel/gateway-link.ts | 60 ++++++++++++++++++++++++++++++++------ src/tunnel/gateway.ts | 2 ++ 2 files changed, 53 insertions(+), 9 deletions(-) diff --git a/src/tunnel/gateway-link.ts b/src/tunnel/gateway-link.ts index 386dbb067..c9ecb3826 100644 --- a/src/tunnel/gateway-link.ts +++ b/src/tunnel/gateway-link.ts @@ -1,10 +1,11 @@ import type { + FleetLeases, ModuleIdentity, ModuleLease, ModuleLeaseSocketAccept, ModuleTwoWayRelay, } from "../modules/index.js"; -import type { LeaseSocket } from "../ports/index.js"; +import type { Clock, LeaseSocket, TimerHandle } from "../ports/index.js"; import { unavailable } from "./refusal.js"; import { encodeTunnelFrame, TUNNEL_REFUSED_CLOSE, TUNNEL_TAG } from "../contract/index.js"; import { closeReason } from "../core/index.js"; @@ -18,8 +19,18 @@ export interface GatewayTunnelLinkOptions { leaseId?: string, ) => Promise; readonly requesterPrefix: string; + readonly clock: Clock; + readonly leases: FleetLeases; } +// why: the relay's own head deadline is 330 s, far too long for a person waiting on a socket; the +// socket's open is bounded here and aborts the relay's open when it runs out. +const OPEN_BOUND_MS = 10_000; + +// why: the worker's `0xF1` usually follows the relayed lease event, and it carries the reason; the gateway +// waits this long for it before closing a socket whose lease it saw go. +const LEASE_END_WAIT_MS = 2_000; + // why: a worker with tunnels off has no relay target, and a holder must get a 503 that says to turn the capability on there, before the upgrade; an error with no such code is a real fault and goes on to the HTTP layer's 500. function refusalFor(error: unknown, workerId: string): Response { if ((error as { readonly code?: unknown }).code === "RELAY_TARGET_MISSING") { @@ -32,6 +43,7 @@ function refusalFor(error: unknown, workerId: string): Response { } interface Bridge { + readonly leaseGone: () => void; readonly stop: (code: number, reason: string) => void; } @@ -58,7 +70,10 @@ export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { ): Promise; drain(): void; } { - const bridges = new Set(); + const bridges = new Map>(); + options.leases.onRemoved((entry) => { + for (const each of bridges.get(entry.gatewayLeaseId) ?? []) each.leaseGone(); + }); function bridge( socket: LeaseSocket, @@ -69,12 +84,25 @@ export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { const writer = relay.writable.getWriter(); let writes: Promise = Promise.resolve(); let ended = false; - const mine: Bridge = { stop: (code, reason) => stop(code, reason) }; - bridges.add(mine); + let wait: TimerHandle | undefined; + const mine: Bridge = { + leaseGone: () => { + wait ??= options.clock.setTimer(LEASE_END_WAIT_MS, () => stop(4001, "lease ended")); + }, + stop: (code, reason) => stop(code, reason), + }; + const set = bridges.get(lease.id) ?? new Set(); + set.add(mine); + bridges.set(lease.id, set); + function forget(): void { + ended = true; + if (wait !== undefined) options.clock.cancel(wait); + set.delete(mine); + if (set.size === 0) bridges.delete(lease.id); + } function stop(code: number, reason: string): void { if (ended) return; - ended = true; - bridges.delete(mine); + forget(); socket.close(code, closeReason(reason)); controller.abort(); } @@ -96,8 +124,7 @@ export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { writes = writes.then(() => writer.write(frame)).catch(() => undefined); }); socket.onClose(() => { - ended = true; - bridges.delete(mine); + forget(); controller.abort(); }); void (async () => { @@ -120,12 +147,19 @@ export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { return { drain: () => { - for (const each of bridges) each.stop(1001, "Simlock is stopping"); + for (const set of bridges.values()) { + for (const each of set) each.stop(1001, "Simlock is stopping"); + } }, open: async (_request, identity, lease) => { const controller = new AbortController(); const workerId = lease.workerId ?? ""; let relay: Response | ModuleTwoWayRelay; + let timedOut = false; + const timer = options.clock.setTimer(OPEN_BOUND_MS, () => { + timedOut = true; + controller.abort(); + }); try { relay = await options.relayTwoWay( workerId, @@ -137,7 +171,15 @@ export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { lease.workerLeaseId, ); } catch (error) { + if (timedOut) { + return unavailable( + "WORKER_UNREACHABLE", + `Worker ${workerId} did not answer the tunnel socket within 10 s`, + ); + } return refusalFor(error, workerId); + } finally { + options.clock.cancel(timer); } if (relay instanceof Response) return relay; return Object.assign((socket: LeaseSocket) => bridge(socket, relay, controller, lease), { diff --git a/src/tunnel/gateway.ts b/src/tunnel/gateway.ts index 399a47f1d..80f9a89ec 100644 --- a/src/tunnel/gateway.ts +++ b/src/tunnel/gateway.ts @@ -5,6 +5,8 @@ import { upgradeRequired } from "./refusal.js"; export function createGateway(ctx: GatewayContext): GatewayModule { const link = createGatewayTunnelLink({ + clock: ctx.clock, + leases: ctx.leases, relayTwoWay: (workerId, request, tenant, leaseId) => ctx.relayTwoWay(workerId, request, tenant, leaseId), requesterPrefix: ctx.requesterPrefix, From 719e40592ff7c69f4d5f6d47da73b12b0400b972 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:35:44 -0300 Subject: [PATCH 069/103] feat(tunnel): the worker's relay door sends a heartbeat every 5 s and the gateway keeps it from the holder (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/tunnel/channel.ts | 15 +++++++-- src/tunnel/gateway-link.ts | 1 + src/tunnel/gateway.test.ts | 2 ++ src/tunnel/worker.test.ts | 62 ++++++++++++++++++++++++++++++++++++-- src/tunnel/worker.ts | 2 +- 5 files changed, 76 insertions(+), 6 deletions(-) diff --git a/src/tunnel/channel.ts b/src/tunnel/channel.ts index 4faf77035..40751ea51 100644 --- a/src/tunnel/channel.ts +++ b/src/tunnel/channel.ts @@ -1,24 +1,35 @@ import type { ModuleTwoWayPipe } from "../modules/index.js"; -import type { LeaseSocket } from "../ports/index.js"; +import type { Clock, LeaseSocket, TimerHandle } from "../ports/index.js"; import { CHANNEL_TAG, encodeFrame, readFrames } from "./framing.js"; +const HEARTBEAT_MS = 5_000; + // why: a worker's tunnel session talks to a gateway's client through a relay channel, and the session // takes a `LeaseSocket` whichever door the client came in by; this is the channel's end of that port, // a socket whose messages are frames of the channel. -export function channelSocket(pipe: ModuleTwoWayPipe): LeaseSocket { +export function channelSocket(pipe: ModuleTwoWayPipe, clock: Clock): LeaseSocket { const writer = pipe.writable.getWriter(); const messageListeners: ((data: Uint8Array) => void)[] = []; const closeListeners: (() => void)[] = []; let writes: Promise = Promise.resolve(); let closed = false; + let beat: TimerHandle | undefined; const markClosed = (): void => { if (closed) return; closed = true; + if (beat !== undefined) clock.cancel(beat); for (const listener of closeListeners) listener(); }; const write = (frame: Uint8Array): void => { writes = writes.then(() => writer.write(frame)).catch(() => undefined); }; + // why: the gateway ends a relay whose worker direction is silent for 15 s, and a tunnel with nothing to say still has to be seen alive. + const heartbeat = (): void => { + if (closed) return; + write(encodeFrame(CHANNEL_TAG.heartbeat, new Uint8Array())); + beat = clock.setTimer(HEARTBEAT_MS, heartbeat); + }; + beat = clock.setTimer(HEARTBEAT_MS, heartbeat); void (async () => { for await (const frame of readFrames(pipe.readable)) { const message = new Uint8Array(1 + frame.payload.length); diff --git a/src/tunnel/gateway-link.ts b/src/tunnel/gateway-link.ts index c9ecb3826..dbda3f32f 100644 --- a/src/tunnel/gateway-link.ts +++ b/src/tunnel/gateway-link.ts @@ -136,6 +136,7 @@ export function createGatewayTunnelLink(options: GatewayTunnelLinkOptions): { stop(closing.code, closing.reason); return; } + if (frame.tag === CHANNEL_TAG.heartbeat) continue; const message = new Uint8Array(1 + frame.payload.length); message[0] = frame.tag; message.set(frame.payload, 1); diff --git a/src/tunnel/gateway.test.ts b/src/tunnel/gateway.test.ts index 915b674be..b2ecf1145 100644 --- a/src/tunnel/gateway.test.ts +++ b/src/tunnel/gateway.test.ts @@ -99,10 +99,12 @@ describe("a gateway's tunnel bridge", () => { reasoned.removeLease(REMOVED); reasoned.clock.advance(1_999); expect(reasoned.client.closed).toBeUndefined(); + await reasoned.worker.write(Uint8Array.from([0, 0, 0, 1, 0xf0])); await reasoned.worker.write(closeFrame(4001, "expired")); await vi.waitFor(() => expect(reasoned.client.closed).toEqual({ code: 4001, reason: "expired" }), ); + expect(reasoned.client.sent).toEqual([]); const silent = await attached(); silent.removeLease(REMOVED); diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index 2a35ea4e3..92f8cdc77 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -5,7 +5,7 @@ import { DeviceTcpError } from "../core/index.js"; import { FakeDeviceTcp } from "../core/testing.js"; import type { WorkerModule } from "../modules/index.js"; import { fakeWorkerContext } from "../modules/testing.js"; -import { MemoryLeaseSocket } from "../ports/index.js"; +import { type FakeClock, MemoryLeaseSocket } from "../ports/index.js"; import { tunnelModule } from "./index.js"; const IDENTITY = { principal: "tok_holder", role: "agent" } as const; @@ -50,8 +50,9 @@ function hello(...tunnels: { kind: string; devicePort: number }[]): Uint8Array { async function setup(platform = "android"): Promise<{ readonly worker: WorkerModule; readonly deviceTcp: FakeDeviceTcp; + readonly clock: FakeClock; }> { - const { ctx } = await fakeWorkerContext("tunnel", {}); + const { clock, ctx } = await fakeWorkerContext("tunnel", {}); const deviceTcp = new FakeDeviceTcp(); const registry = { snapshot: { @@ -68,7 +69,7 @@ async function setup(platform = "android"): Promise<{ }, registry, }); - return { deviceTcp, worker }; + return { clock, deviceTcp, worker }; } async function attach(worker: WorkerModule): Promise { @@ -479,4 +480,59 @@ describe("a worker's tunnel socket", () => { expect(reclaimed.socket.closed).toEqual({ code: 4001, reason: "device-lost" }); expect(reclaimed.deviceTcp.reversed).toEqual([5173]); }); + + it("keeps an idle relay alive with a heartbeat every 5 s and closes it with an 0xF1 {code, reason}", async () => { + const { clock, worker } = await setup(); + const toGateway = new TransformStream(); + const fromGateway = new TransformStream(); + const written: number[] = []; + void toGateway.readable.pipeTo( + new WritableStream({ + write: (chunk) => { + written.push(...chunk); + }, + }), + ); + const answer = await worker.relayTwoWay?.(new Request("http://simlock/tunnel"), "gw:t", "L-1", { + readable: fromGateway.readable, + signal: new AbortController().signal, + writable: toGateway.writable, + }); + expect(answer?.status).toBe(200); + const heartbeat = [0, 0, 0, 1, 0xf0]; + const heartbeats = (): number => { + let count = 0; + for (let at = 0; at + 5 <= written.length; at += 1) { + if (heartbeat.every((byte, offset) => written[at + offset] === byte)) count += 1; + } + return count; + }; + + clock.advance(4_999); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(heartbeats()).toBe(0); + clock.advance(1); + await vi.waitFor(() => expect(heartbeats()).toBe(1)); + clock.advance(5_000); + await vi.waitFor(() => expect(heartbeats()).toBe(2)); + + await worker.hooks?.beforeDeviceReclaim?.( + { leaseId: "L-1", reason: "explicit" } as never, + new AbortController().signal, + ); + const json = new TextEncoder().encode(JSON.stringify({ code: 4001, reason: "explicit" })); + await vi.waitFor(() => + expect(written.slice(-(json.length + 5))).toEqual([ + 0, + 0, + (json.length + 1) >> 8, + (json.length + 1) & 0xff, + 0xf1, + ...json, + ]), + ); + clock.advance(20_000); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(heartbeats()).toBe(2); + }); }); diff --git a/src/tunnel/worker.ts b/src/tunnel/worker.ts index 560f22600..b9f69165b 100644 --- a/src/tunnel/worker.ts +++ b/src/tunnel/worker.ts @@ -20,7 +20,7 @@ export function createWorker(ctx: WorkerContext): WorkerModu if (lease === undefined || device === undefined) { return Promise.resolve(unknownLease(leaseId ?? "")); } - sessions.attach(lease.id, device, channelSocket(pipe)); + sessions.attach(lease.id, device, channelSocket(pipe, ctx.clock)); return Promise.resolve(new Response(null, { status: 200 })); }, socket: { From 277d2faeebbd77ca4205dc8e067d85036859d74a Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:36:02 -0300 Subject: [PATCH 070/103] test: the tunnel route's 503 TUNNEL_UNAVAILABLE and WORKER_UNREACHABLE are in the OpenAPI document (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/http/openapi.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/http/openapi.test.ts b/src/http/openapi.test.ts index 95e792e05..d24db9260 100644 --- a/src/http/openapi.test.ts +++ b/src/http/openapi.test.ts @@ -413,9 +413,10 @@ describe("buildOpenApiDocument with the input module", () => { const tunnel = document.paths?.["/v1/leases/{id}/tunnel"]?.get; expect(tunnel?.tags).toEqual(["tunnel"]); - expect(sortedKeys(tunnel?.responses)).toEqual(["101", "401", "403", "404", "426"]); + expect(sortedKeys(tunnel?.responses)).toEqual(["101", "401", "403", "404", "426", "503"]); expect(errorCodes(tunnel, "404")).toEqual(["UNKNOWN_LEASE"]); expect(errorCodes(tunnel, "426")).toEqual(["BAD_REQUEST"]); + expect(errorCodes(tunnel, "503")).toEqual(["TUNNEL_UNAVAILABLE", "WORKER_UNREACHABLE"]); }); }); From f3a35d5bd62129a91f1c6c16fd8b3ef090668e91 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:36:40 -0300 Subject: [PATCH 071/103] feat(tunnel): the route's 503 statuses, the remote-agents page and the manual describe tunnels through a gateway (#1113) Co-Authored-By: Claude Sonnet 5.5 --- docs/internal/ARCHITECTURE.md | 2 +- src/tunnel/AGENTS.md | 31 +++++++++++++------ src/tunnel/definition.ts | 7 ++++- .../docs/docs/using-devices/remote-agents.mdx | 4 +-- 4 files changed, 31 insertions(+), 13 deletions(-) diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index e1c37c256..075665dff 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -50,7 +50,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘ | agent-device | Optional edge: the two agent-device daemons (simulators, phones) beside a worker, its HTTP front | [agent-device](../../src/agent-device/AGENTS.md) | | stream | Optional edge: a running device's live screen over HTTP, relayed by a gateway | [stream](../../src/stream/AGENTS.md) | | input | Optional edge: a lease holder's taps and keys over a WebSocket, relayed by a gateway | [input](../../src/input/AGENTS.md) | -| tunnel | Optional edge: a lease holder's reverse tunnels from its Android device over a WebSocket, on a lone worker | [tunnel](../../src/tunnel/AGENTS.md) | +| tunnel | Optional edge: a lease holder's reverse tunnels from its Android device over a WebSocket, on a lone worker or through a gateway | [tunnel](../../src/tunnel/AGENTS.md) | | auth | Credential → identity: tokens, admin secret, `hello`, uplink join token, HTTP strategies | [auth](../../src/auth/AGENTS.md) | | http | HTTP frontend: routes, SSE | [http](../../src/http/AGENTS.md) | | cli | Operator command surface | [cli](../../src/cli/AGENTS.md) | diff --git a/src/tunnel/AGENTS.md b/src/tunnel/AGENTS.md index 180953cd0..ec1b36d7c 100644 --- a/src/tunnel/AGENTS.md +++ b/src/tunnel/AGENTS.md @@ -1,19 +1,23 @@ # Tunnel -Does: lets a lease's holder (or an operator) reverse device ports of its Android device to its own machine over `WS /v1/leases/{id}/tunnel`, on a lone worker. -Entry: `index.ts` -> `tunnelModule`, an optional module (ADR 0054): `worker.ts` `createWorker`, loaded by the module host only when turned on. -Uses: contract (`tunnel-frames.ts`), core (`DeviceReverse`, `DeviceTcpError`), modules (the context, socket types), ports (`LeaseSocket`). +Does: lets a lease's holder (or an operator) reverse device ports of its Android device to its own machine over `WS /v1/leases/{id}/tunnel`, on a lone worker or through a gateway. +Entry: `index.ts` -> `tunnelModule`, an optional module (ADR 0054): `worker.ts` `createWorker` and `gateway.ts` `createGateway`, loaded by the module host only when turned on. +Uses: contract (`tunnel-frames.ts`), core (`DeviceReverse`, `DeviceTcpError`, `closeReason`), modules (the context, socket and relay types), ports (`LeaseSocket`, `Clock`). Never imports: http, gateway, drivers, daemon, leasing, `fs`, `child_process`. Imported by: `module-registry` only. Off unless `capabilities.tunnel.enabled` (false). Off: nothing loaded, and the `tunnel` capability reads `off`. ## Files -| File | Role | -| --------------- | ----------------------------------------------------------------------------------------- | -| `definition.ts` | `tunnelModule`: name `tunnel`, empty config section, `http` route data, the worker loader | -| `worker.ts` | The worker side from the host's context: capability, hooks, lease route (426), socket | -| `sessions.ts` | One session per socket: HELLO, rules, connections, window and credit, lease end, drain | -| `refusal.ts` | The 404 `UNKNOWN_LEASE` and 426 bodies | +| File | Role | +| ----------------- | ----------------------------------------------------------------------------------------------------------- | +| `definition.ts` | `tunnelModule`: name `tunnel`, empty config section, `http` route data, the two loaders | +| `worker.ts` | The worker side from the host's context: capability, hooks, lease route (426), socket, relay | +| `gateway.ts` | The gateway side: lease route (426), socket, `beforeDrain` | +| `gateway-link.ts` | Gateway: the relay open, refusals, one bridge per socket, lease-gone wait, drain | +| `channel.ts` | Worker: a relay channel as a `LeaseSocket`; heartbeat, `0xF1` close | +| `framing.ts` | `[len u32][tag u8][payload]` frames (a message up to 65541 bytes), `readFrames`, the `0xF0` and `0xF1` tags | +| `sessions.ts` | One session per socket: HELLO, rules, connections, window and credit, lease end, drain | +| `refusal.ts` | The 404 `UNKNOWN_LEASE` and 426 bodies | ## How it works @@ -25,6 +29,15 @@ The HTTP layer resolves the lease for the caller, then `socket.open` finds the l 4. A bad frame is `BAD_REQUEST`, close 4003; a frame for a connection already closed is ignored. 5. The socket closing, the lease ending (`beforeDeviceReclaim`, close 4001 with the reason) and a drain (`beforeDrain`, close 1001) close the session's connections and remove its rules; with an already aborted signal the removal is skipped and reclaim does it. +## Through a gateway + +The gateway's `socket.open` calls `relayTwoWay` (`tunnel` target) with the worker's lease id; the worker's `relayTwoWay` finds the lease and device and attaches a `channelSocket` to the same session. The worker sends `0xF0` every 5 s and `0xF1 {code, reason}` when its session closes. + +- Holder frames up to 65541 bytes go to the channel; a longer one is refused `BAD_REQUEST` by the gateway, close 4003. +- The channel goes to the holder except `0xF0`. `0xF1` closes the holder with its code and reason (1001 from a stopping worker is reported as 1011). A channel that ends or breaks closes 1011 `Worker stopped answering`. +- `leases.onRemoved` waits 2 s for the worker's `0xF1`, then closes 4001 `lease ended`. `beforeDrain` closes 1001 `Simlock is stopping`. +- Before the upgrade: `RELAY_TARGET_MISSING` is 503 `TUNNEL_UNAVAILABLE`; no head in 10 s is 503 `WORKER_UNREACHABLE`. + ## Rules - The module never checks an owner; the HTTP layer does. diff --git a/src/tunnel/definition.ts b/src/tunnel/definition.ts index 9db1453f2..23bf555ae 100644 --- a/src/tunnel/definition.ts +++ b/src/tunnel/definition.ts @@ -15,7 +15,7 @@ export const tunnelModule: OptionalModuleDefinition = { method: "get", path: "/v1/leases/{id}/tunnel", description: - "Open a tunnel socket for a lease's device over a WebSocket: the lease's holder or an operator. Each message is one tag byte, a 4-byte big-endian connection number and a payload. The holder sends HELLO with up to 8 tunnels, each {kind, devicePort}; the server answers READY with the same list, or REFUSED {code, message} and close 4003, and then nothing the HELLO named stays set up. Today only reverse tunnels are served: the device's connections to devicePort arrive as OPEN and DATA, under a 262144-byte window per direction. The socket closes 4001 with the lease-end reason when the lease ends, and 1001 when the daemon stops. A lease the caller does not own answers 404, as an unknown one does. A plain GET without an upgrade answers 426. Served only when capabilities.tunnel.enabled is true on the daemon that answers.", + "Open a tunnel socket for a lease's device over a WebSocket: the lease's holder or an operator. Each message is one tag byte, a 4-byte big-endian connection number and a payload. The holder sends HELLO with up to 8 tunnels, each {kind, devicePort}; the server answers READY with the same list, or REFUSED {code, message} and close 4003, and then nothing the HELLO named stays set up. Today only reverse tunnels are served: the device's connections to devicePort arrive as OPEN and DATA, under a 262144-byte window per direction. The socket closes 4001 with the lease-end reason when the lease ends, and 1001 when the daemon stops. A lease the caller does not own answers 404, as an unknown one does. A plain GET without an upgrade answers 426. Served only when capabilities.tunnel.enabled is true on the daemon that answers; through a gateway the lease's worker needs it too, and the socket also closes 1011 when that worker stops answering and 1001 when the gateway stops.", statuses: { 101: { description: "The upgrade to a WebSocket." }, 404: { @@ -26,6 +26,11 @@ export const tunnelModule: OptionalModuleDefinition = { description: "The request is not a WebSocket upgrade.", errorCodes: ["BAD_REQUEST"], }, + 503: { + description: + "A gateway's worker does not take tunnels, or does not answer the socket within 10 s.", + errorCodes: ["TUNNEL_UNAVAILABLE", "WORKER_UNREACHABLE"], + }, }, }, ], diff --git a/website/src/content/docs/docs/using-devices/remote-agents.mdx b/website/src/content/docs/docs/using-devices/remote-agents.mdx index 5b32c8828..cd56b99d7 100644 --- a/website/src/content/docs/docs/using-devices/remote-agents.mdx +++ b/website/src/content/docs/docs/using-devices/remote-agents.mdx @@ -177,7 +177,7 @@ Send the same calls to the gateway, with a token created on the gateway. The gat ## Tunnels -A holder with its own WebSocket client can reach its leased Android device's ports from the worker's side. Open `GET /v1/leases//tunnel` as a WebSocket with your token, on a worker that has `capabilities.tunnel.enabled: true` (it is off by default; a gateway does not relay it yet). The lease's holder and an operator may open it; anyone else gets `404`, as for an unknown lease, and a plain `GET` gets `426`. +A holder with its own WebSocket client can reach its leased Android device's ports from the worker's side. Open `GET /v1/leases//tunnel` as a WebSocket with your token, on a worker that has `capabilities.tunnel.enabled: true`, or on a gateway whose lease's worker has it (it is off by default; turn it on at the gateway and at the worker, as with input). Through a gateway the socket is relayed to the lease's worker with the same frames, each up to 65541 bytes; a frame longer than that is refused `BAD_REQUEST` and the socket closes with 4003. The lease's holder and an operator may open it; anyone else gets `404`, as for an unknown lease, and a plain `GET` gets `426`. Each message is one binary frame: a tag byte, a 4-byte big-endian connection number and a payload. The first frame is `HELLO` (tag `0x01`, connection 0) with JSON of at most 4 KiB: `{"tunnels":[{"kind":"reverse","devicePort":5173}]}`. Name 1 to 8 tunnels per lease, across all its sockets, with device ports from 1024 to 65535. Only `reverse` works today. @@ -185,7 +185,7 @@ Each message is one binary frame: a tag byte, a 4-byte big-endian connection num - Each direction of a connection starts with a 262144-byte window. The reader grants more with `CREDIT` (`0x04`, a 4-byte count); a reader that grants none pauses that connection and no other. - `END` (`0x05`) closes one direction and leaves the other open. `RESET` (`0x06`) from you closes the connection. A worker closes a device connection at once when 256 are already open on the socket. - A `HELLO` the worker cannot meet gets `REFUSED` (`0x82`, JSON `{code, message}`) and the socket closes with 4003; nothing it named stays set up. The codes are in the [errors reference](/docs/reference/errors/#tunnels). A frame that breaks the protocol is refused `BAD_REQUEST` the same way. -- The socket closes `4001` with the lease-end reason when the lease ends, and `1001` when the daemon stops. Closing the socket removes the device's `adb reverse` rule before the lease can end. +- The socket closes `4001` with the lease-end reason when the lease ends, and `1001` when the daemon stops. Through a gateway it also closes `1011` when the lease's worker stops or stops answering, and `1001` when the gateway stops. A worker with tunnels off answers `503 TUNNEL_UNAVAILABLE` before the upgrade, and one that gives no answer within 10 seconds `503 WORKER_UNREACHABLE`. Closing the socket removes the device's `adb reverse` rule before the lease can end. The worker sets each tunnel up with `adb reverse --no-rebind`, so a port you already reversed with `adb reverse` through `exec` is refused `TUNNEL_PORT_IN_USE`. A rule you set through `exec` after the tunnel, without `--no-rebind`, replaces it and the tunnel's connections stop. iOS leases are refused `TUNNEL_UNSUPPORTED`. From 6442e277304a7a14489e93924d77aa2895fd0cf0 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:39:47 -0300 Subject: [PATCH 072/103] test: the CLI against a lone worker with fake devices opens a reverse tunnel, carries bytes, and its rules are gone after Ctrl-C (#1114) --- src/daemon/tunnel-cli.e2e.test.ts | 195 ++++++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 src/daemon/tunnel-cli.e2e.test.ts diff --git a/src/daemon/tunnel-cli.e2e.test.ts b/src/daemon/tunnel-cli.e2e.test.ts new file mode 100644 index 000000000..5a9cb2bbd --- /dev/null +++ b/src/daemon/tunnel-cli.e2e.test.ts @@ -0,0 +1,195 @@ +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, 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(""); + }); +}); From 34eb975dadba53dfc92a1e90540bd44dc22c9303 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:43:12 -0300 Subject: [PATCH 073/103] feat(cli): simlock tunnel reverse opens a tunnel on a lone worker and relays its bytes (#1114) --- src/cli/commands/tunnel.ts | 172 +++++++++++++++++ src/cli/environment.ts | 20 ++ src/cli/index.test.ts | 10 +- src/cli/index.ts | 7 +- src/cli/remote-lease.ts | 18 +- src/cli/tree.ts | 1 + src/cli/types.ts | 13 ++ src/ports/AGENTS.md | 4 +- src/ports/http-json.ts | 61 ++++++ src/ports/index.ts | 15 ++ src/ports/websocket-client.ts | 174 ++++++++++++++++++ .../src/content/docs/docs/reference/cli.mdx | 21 ++- 12 files changed, 505 insertions(+), 11 deletions(-) create mode 100644 src/cli/commands/tunnel.ts create mode 100644 src/ports/http-json.ts create mode 100644 src/ports/websocket-client.ts diff --git a/src/cli/commands/tunnel.ts b/src/cli/commands/tunnel.ts new file mode 100644 index 000000000..e4051f359 --- /dev/null +++ b/src/cli/commands/tunnel.ts @@ -0,0 +1,172 @@ +import { + decodeTunnelFrame, + encodeTunnelFrame, + TUNNEL_MAX_DATA_BYTES, + TUNNEL_TAG, +} from "../../contract/index.js"; +import type { TcpStream, WebSocketClient } from "../../ports/index.js"; +import { commandArgs } 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; + +interface ReverseSpec { + readonly devicePort: number; + readonly callerPort: number; +} + +function parseReverses(words: readonly string[]): readonly ReverseSpec[] { + const specs: ReverseSpec[] = []; + for (let index = 0; index < words.length; index += 2) { + const [device = "", caller = device] = (words[index + 1] ?? "").split(":"); + specs.push({ callerPort: Number(caller), devicePort: Number(device) }); + } + return specs; +} + +function field(value: unknown, name: string): unknown { + return typeof value === "object" && value !== null ? Reflect.get(value, name) : undefined; +} + +async function leaseToUse( + environment: CliEnvironment, + base: string, + token: string, + lease: string | undefined, +): Promise { + if (lease !== undefined) return lease; + const identity = await environment.httpJson.get(`${base}/v1/identity`, token); + const leases = await environment.httpJson.get(`${base}/v1/leases`, token); + return selectOnlyLease( + (field(leases.body, "leases") as { id: string; requesterId: string }[] | undefined) ?? [], + field(identity.body, "role") === "admin" ? "admin" : "agent", + environment, + ); +} + +// 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. +function relayConnections(socket: WebSocketClient, environment: CliEnvironment) { + const streams = new Map }>(); + return async ( + spec: ReverseSpec | undefined, + frame: { tag: number; conn: number; payload: Uint8Array }, + ): Promise => { + if (frame.tag === TUNNEL_TAG.open && spec !== undefined) { + const stream = await environment.tcpStreams.connect( + spec.callerPort, + CALLER_CONNECT_TIMEOUT_MS, + ); + streams.set(frame.conn, { stream, writes: Promise.resolve() }); + void (async () => { + const reader = stream.readable.getReader(); + for (;;) { + const step = await reader.read(); + if (step.done) break; + for (let at = 0; at < step.value.length; at += TUNNEL_MAX_DATA_BYTES) { + socket.send( + encodeTunnelFrame( + TUNNEL_TAG.data, + frame.conn, + step.value.subarray(at, at + TUNNEL_MAX_DATA_BYTES), + ), + ); + } + } + socket.send(encodeTunnelFrame(TUNNEL_TAG.end, frame.conn)); + })(); + return; + } + const connection = streams.get(frame.conn); + if (connection === undefined) return; + if (frame.tag === TUNNEL_TAG.data) { + connection.writes = connection.writes.then(() => connection.stream.write(frame.payload)); + } else if (frame.tag === TUNNEL_TAG.end) { + connection.writes = connection.writes.then(() => connection.stream.end()); + } else if (frame.tag === TUNNEL_TAG.reset) { + connection.stream.close(); + streams.delete(frame.conn); + } + }; +} + +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 = String(url ?? environment.tunnelUrl).replace(/\/$/, ""); + const secret = String(token ?? environment.tunnelToken); + const leaseId = await leaseToUse( + environment, + base, + secret, + typeof lease === "string" ? lease : undefined, + ); + const socket = await environment.webSocket.connect( + `${base.replace(/^http/, "ws")}/v1/leases/${encodeURIComponent(leaseId)}/tunnel`, + { + handshakeTimeoutMs: HANDSHAKE_TIMEOUT_MS, + headers: { authorization: `Bearer ${secret}` }, + }, + ); + const relay = relayConnections(socket, environment); + // 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(); + return new Promise((resolve) => { + const stop = () => { + environment.signals.off("SIGINT", stop); + environment.signals.off("SIGTERM", stop); + socket.close(CLOSE_NORMAL, ""); + resolve(0); + }; + environment.signals.on("SIGINT", stop); + environment.signals.on("SIGTERM", stop); + socket.onMessage((bytes) => { + const frame = decodeTunnelFrame(bytes); + if (frame === undefined) return; + if (frame.tag === TUNNEL_TAG.ready) { + 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(JSON.parse(new TextDecoder().decode(frame.payload)), "devicePort") === + devicePort, + ) + : undefined; + handled = handled.then(() => relay(opened, frame)).catch(() => undefined); + }); + socket.send( + encodeTunnelFrame( + TUNNEL_TAG.hello, + 0, + JSON.stringify({ + tunnels: specs.map(({ devicePort }) => ({ devicePort, kind: "reverse" })), + }), + ), + ); + }); +} + +export { run }; diff --git a/src/cli/environment.ts b/src/cli/environment.ts index 6df470e25..1ba88159a 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -400,6 +400,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 7ec5bdf22..31d25f4c6 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"; @@ -8401,6 +8406,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/remote-lease.ts b/src/cli/remote-lease.ts index 8f874b8f3..302b98020 100644 --- a/src/cli/remote-lease.ts +++ b/src/cli/remote-lease.ts @@ -2,13 +2,13 @@ import type { SimlockAdminClient } from "../admin/index.js"; import { UsageError } from "./errors.js"; import type { CommandContext } from "./tree.js"; -export async function resolveRemoteLeaseId( - client: SimlockAdminClient, +export function selectOnlyLease( + leases: readonly { readonly id: string; readonly requesterId: string }[], + role: "admin" | "agent", environment: CommandContext["environment"], -): Promise { - const { leases } = await client.listLeases(); +): string { const own = - client.role === "admin" + role === "admin" ? leases.filter((lease) => lease.requesterId === environment.requesterId) : leases; if (own.length === 0) { @@ -23,3 +23,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/types.ts b/src/cli/types.ts index 703b8c98b..7bbe7d1a9 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 { @@ -92,6 +95,13 @@ export interface CliEnvironment { readonly confirm?: ((question: string) => Promise) | undefined; readonly runPassthrough?: (command: PassthroughCommand) => Promise; readonly readStdin?: () => 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; } export interface CliEnvironmentPorts { @@ -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/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.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..e70b7d763 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -180,3 +180,18 @@ export { NodeUpdaterLauncher, type UpdaterLauncher, } from "./updater-launcher.js"; +export { + FakeWebSocketClientConnector, + FakeWebSocketPeer, + NodeWebSocketClientConnector, + WebSocketRefusedError, + type WebSocketClient, + type WebSocketClientConnector, + type WebSocketClientOptions, +} from "./websocket-client.js"; +export { + FakeHttpJsonClient, + FetchHttpJsonClient, + type HttpJsonAnswer, + type HttpJsonClient, +} from "./http-json.js"; diff --git a/src/ports/websocket-client.ts b/src/ports/websocket-client.ts new file mode 100644 index 000000000..918486c1a --- /dev/null +++ b/src/ports/websocket-client.ts @@ -0,0 +1,174 @@ +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; + 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); + } + + 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)); + }); + }); + } +} + +export class FakeWebSocketPeer implements WebSocketClient { + readonly sent: Uint8Array[] = []; + closedWith: { readonly code: number; readonly reason: string } | undefined; + 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 }; + } + + 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); + } + + // fallow-ignore-next-line unused-class-member -- the server's side of a fake socket, called by tests. + receive(bytes: Uint8Array): void { + for (const listener of this.#messages) listener(bytes); + } + + // fallow-ignore-next-line unused-class-member -- the server's side of a fake socket, called by tests. + ping(): void { + for (const listener of this.#pings) listener(); + } + + // fallow-ignore-next-line unused-class-member -- the server's side of a fake socket, called by tests. + 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 9497fbfc8..54ece130c 100644 --- a/website/src/content/docs/docs/reference/cli.mdx +++ b/website/src/content/docs/docs/reference/cli.mdx @@ -47,7 +47,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. | — | @@ -200,6 +200,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`; at most 2048 characters. | `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). @@ -707,6 +724,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. | 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:`. | — | From 1672cab47b349f48d0aabc7d15b0c959d94f4525 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:44:39 -0300 Subject: [PATCH 074/103] fix(tunnel): a channel frame is at most one message, the heartbeat stops with the channel and the largest DATA is tested (#1113) --- src/daemon/tunnel-lease.e2e.test.ts | 7 +++++++ src/tunnel/AGENTS.md | 2 +- src/tunnel/channel.ts | 1 - src/tunnel/framing.ts | 2 +- src/tunnel/worker.test.ts | 3 +++ 5 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/daemon/tunnel-lease.e2e.test.ts b/src/daemon/tunnel-lease.e2e.test.ts index 1d8557d82..3290cc8c6 100644 --- a/src/daemon/tunnel-lease.e2e.test.ts +++ b/src/daemon/tunnel-lease.e2e.test.ts @@ -290,6 +290,13 @@ describe("a lease's tunnel socket", () => { expect(carried.messages[2]?.length).toBe(65_541); expect(carried.messages[2]?.[0]).toBe(0x03); + const largest = Buffer.concat([Buffer.from([0x03, 0, 0, 0, 1]), Buffer.alloc(65_536)]); + expect(largest.length).toBe(65_541); + carried.socket.send(largest); + await vi.waitFor(() => expect(carried.messages).toHaveLength(4), { timeout: 10_000 }); + expect(carried.messages[3]?.[0]).toBe(0x04); + expect(carried.closed).toBeUndefined(); + const tooBig = Buffer.concat([Buffer.from([0x03, 0, 0, 0, 1]), Buffer.alloc(65_537)]); expect(tooBig.length).toBe(65_542); carried.socket.send(tooBig); diff --git a/src/tunnel/AGENTS.md b/src/tunnel/AGENTS.md index ec1b36d7c..1af24826b 100644 --- a/src/tunnel/AGENTS.md +++ b/src/tunnel/AGENTS.md @@ -2,7 +2,7 @@ Does: lets a lease's holder (or an operator) reverse device ports of its Android device to its own machine over `WS /v1/leases/{id}/tunnel`, on a lone worker or through a gateway. Entry: `index.ts` -> `tunnelModule`, an optional module (ADR 0054): `worker.ts` `createWorker` and `gateway.ts` `createGateway`, loaded by the module host only when turned on. -Uses: contract (`tunnel-frames.ts`), core (`DeviceReverse`, `DeviceTcpError`, `closeReason`), modules (the context, socket and relay types), ports (`LeaseSocket`, `Clock`). +Uses: contract (`src/contract/tunnel-frames.ts`), core (`DeviceReverse`, `DeviceTcpError`, `closeReason`), modules (the context, socket and relay types), ports (`LeaseSocket`, `Clock`). Never imports: http, gateway, drivers, daemon, leasing, `fs`, `child_process`. Imported by: `module-registry` only. Off unless `capabilities.tunnel.enabled` (false). Off: nothing loaded, and the `tunnel` capability reads `off`. diff --git a/src/tunnel/channel.ts b/src/tunnel/channel.ts index 40751ea51..5a8aeb3d9 100644 --- a/src/tunnel/channel.ts +++ b/src/tunnel/channel.ts @@ -25,7 +25,6 @@ export function channelSocket(pipe: ModuleTwoWayPipe, clock: Clock): LeaseSocket }; // why: the gateway ends a relay whose worker direction is silent for 15 s, and a tunnel with nothing to say still has to be seen alive. const heartbeat = (): void => { - if (closed) return; write(encodeFrame(CHANNEL_TAG.heartbeat, new Uint8Array())); beat = clock.setTimer(HEARTBEAT_MS, heartbeat); }; diff --git a/src/tunnel/framing.ts b/src/tunnel/framing.ts index df547cd81..205cd04ee 100644 --- a/src/tunnel/framing.ts +++ b/src/tunnel/framing.ts @@ -40,7 +40,7 @@ export async function* readFrames( for (;;) { while (buffer.length >= 4) { const length = new DataView(buffer.buffer, buffer.byteOffset, buffer.length).getUint32(0); - if (length < 1 || length > MAX_TUNNEL_MESSAGE_BYTES + 1) return; + if (length < 1 || length > MAX_TUNNEL_MESSAGE_BYTES) return; if (buffer.length < 4 + length) break; yield { payload: buffer.slice(5, 4 + length), tag: buffer[4] ?? 0 }; buffer = buffer.subarray(4 + length); diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index 55e210f7d..54ee894fc 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -504,6 +504,7 @@ describe("a worker's tunnel socket", () => { }, }), ); + const idleTimers = clock.pendingTimerCount; const answer = await worker.relayTwoWay?.(new Request("http://simlock/tunnel"), "gw:t", "L-1", { readable: fromGateway.readable, signal: new AbortController().signal, @@ -542,8 +543,10 @@ describe("a worker's tunnel socket", () => { ...json, ]), ); + expect(clock.pendingTimerCount).toBe(idleTimers); clock.advance(20_000); await new Promise((resolve) => setTimeout(resolve, 20)); expect(heartbeats()).toBe(2); + expect(clock.pendingTimerCount).toBe(idleTimers); }); }); From 53e0ec898036f79c31243714ba7ba6d425d5dadf Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:44:43 -0300 Subject: [PATCH 075/103] test: the CLI against a lone worker with fake devices refuses with the worker's code (#1114) --- src/daemon/tunnel-cli.e2e.test.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/daemon/tunnel-cli.e2e.test.ts b/src/daemon/tunnel-cli.e2e.test.ts index 5a9cb2bbd..9511c5a77 100644 --- a/src/daemon/tunnel-cli.e2e.test.ts +++ b/src/daemon/tunnel-cli.e2e.test.ts @@ -167,7 +167,7 @@ describe("simlock tunnel against a lone worker", () => { }; } - it("opens a reverse tunnel, carries bytes, and its rules are gone after Ctrl-C", async () => { + 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); @@ -191,5 +191,17 @@ describe("simlock tunnel against a lone worker", () => { 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`, + }, + }); }); }); From 945fa7081b97757ce5be3f521b328024630d87fd Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:45:08 -0300 Subject: [PATCH 076/103] feat(cli): a tunnel the worker refuses exits with the worker's code (#1114) --- src/cli/commands/tunnel.ts | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/cli/commands/tunnel.ts b/src/cli/commands/tunnel.ts index e4051f359..2bbaab67f 100644 --- a/src/cli/commands/tunnel.ts +++ b/src/cli/commands/tunnel.ts @@ -1,6 +1,9 @@ import { decodeTunnelFrame, encodeTunnelFrame, + ERROR_TABLE, + SimlockError, + type SimlockErrorCode, TUNNEL_MAX_DATA_BYTES, TUNNEL_TAG, } from "../../contract/index.js"; @@ -127,10 +130,13 @@ async function run( const relay = relayConnections(socket, environment); // 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(); - return new Promise((resolve) => { - const stop = () => { + return new Promise((resolve, reject) => { + const settle = () => { environment.signals.off("SIGINT", stop); environment.signals.off("SIGTERM", stop); + }; + const stop = () => { + settle(); socket.close(CLOSE_NORMAL, ""); resolve(0); }; @@ -139,6 +145,22 @@ async function run( socket.onMessage((bytes) => { const frame = decodeTunnelFrame(bytes); if (frame === undefined) return; + if (frame.tag === TUNNEL_TAG.refused) { + settle(); + const refusal: unknown = JSON.parse(new TextDecoder().decode(frame.payload)); + const code = field(refusal, "code"); + reject( + new SimlockError( + typeof code === "string" && code in ERROR_TABLE + ? (code as SimlockErrorCode) + : "TUNNEL_FAILED", + "domain", + `Lease ${leaseId}: ${String(field(refusal, "message"))}`, + {} as never, + ), + ); + return; + } if (frame.tag === TUNNEL_TAG.ready) { for (const { callerPort, devicePort } of specs) { environment.stdout.write( From dc91fe1950ca376ca68ff37830f2714f6458c048 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:46:31 -0300 Subject: [PATCH 077/103] test: a user's simlock tunnel that cannot run exits with its code and one JSON error line (#1114) --- src/cli/tunnel.test.ts | 140 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 src/cli/tunnel.test.ts diff --git a/src/cli/tunnel.test.ts b/src/cli/tunnel.test.ts new file mode 100644 index 000000000..a1aeace87 --- /dev/null +++ b/src/cli/tunnel.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, it, vi } from "vitest"; + +import { buildCliEnvironment, runCli } from "./index.js"; +import { + FakeClock, + FakeDaemonLauncher, + FakeHttpJsonClient, + FakeSystemStats, + FakeTcpStreamConnector, + FakeWebSocketClientConnector, + 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 environment = buildCliEnvironment( + { + clock: new FakeClock(0), + 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: new FakeTcpStreamConnector(), + webSocket, + workingDirectory: "/work", + }, + env, + ); + return { + err, + httpJson, + out, + run: (argv: readonly string[]) => runCli(argv, environment), + signals, + webSocket, + }; +} + +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 cases: readonly { + readonly argv: readonly string[]; + readonly env?: NodeJS.ProcessEnv; + readonly message: string; + }[] = [ + { + argv: ["reverse", "70000"], + message: 'device port "70000" 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", + }, + { + 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", + }, + ]; + for (const { argv, env, message } of cases) { + const cli = command(env ?? ENV); + const exit = cli.run(["tunnel", ...argv, "--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([]); + } + }); +}); From 12a5613970f18d5b059f5208fe7ab3aa03dd011e Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:47:09 -0300 Subject: [PATCH 078/103] feat(cli): simlock tunnel checks its arguments, url and token before it connects (#1114) --- src/cli/commands/tunnel.ts | 73 +++++++++++++++++++++++++++++++++++--- 1 file changed, 68 insertions(+), 5 deletions(-) diff --git a/src/cli/commands/tunnel.ts b/src/cli/commands/tunnel.ts index 2bbaab67f..67216929c 100644 --- a/src/cli/commands/tunnel.ts +++ b/src/cli/commands/tunnel.ts @@ -5,10 +5,12 @@ import { SimlockError, type SimlockErrorCode, TUNNEL_MAX_DATA_BYTES, + TUNNEL_MAX_DEVICE_PORT, + TUNNEL_MAX_TUNNELS, TUNNEL_TAG, } from "../../contract/index.js"; import type { TcpStream, WebSocketClient } from "../../ports/index.js"; -import { commandArgs } from "../args.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"; @@ -16,21 +18,82 @@ import type { CliEnvironment } from "../types.js"; const HANDSHAKE_TIMEOUT_MS = 10_000; const CALLER_CONNECT_TIMEOUT_MS = 5_000; const CLOSE_NORMAL = 1000; +const MAX_URL_CHARS = 2048; +const MAX_TOKEN_CHARS = 4096; 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 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) { - const [device = "", caller = device] = (words[index + 1] ?? "").split(":"); - specs.push({ callerPort: Number(caller), devicePort: Number(device) }); + 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"); + specs.push({ + callerPort: portOf(colon === -1 ? device : text.slice(colon + 1), "caller"), + devicePort, + }); + } + if (specs.length > TUNNEL_MAX_TUNNELS) + throw new UsageError(`At most ${String(TUNNEL_MAX_TUNNELS)} tunnels`); + const seen = new Set(); + for (const { callerPort } of specs) { + if (seen.has(callerPort)) { + throw new UsageError(`Caller port ${String(callerPort)} is named by two tunnels`); + } + seen.add(callerPort); } return specs; } +const LOOPBACK_HOSTS: ReadonlySet = new Set(["127.0.0.1", "[::1]", "localhost"]); + +function checkedUrl(text: string | undefined): string { + if (text === undefined || text === "") { + throw new UsageError("No worker URL: pass --url or set SIMLOCK_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 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 field(value: unknown, name: string): unknown { return typeof value === "object" && value !== null ? Reflect.get(value, name) : undefined; } @@ -112,8 +175,8 @@ async function run( return 0; } const specs = parseReverses(positionals); - const base = String(url ?? environment.tunnelUrl).replace(/\/$/, ""); - const secret = String(token ?? environment.tunnelToken); + const base = checkedUrl(typeof url === "string" ? url : environment.tunnelUrl); + const secret = checkedToken(token ?? environment.tunnelToken); const leaseId = await leaseToUse( environment, base, From 2a2f2f839ed40e7ff6fdf5bdb00f674548ace4ce Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:50:01 -0300 Subject: [PATCH 079/103] test: simlock tunnel prints one line per tunnel and words its lease errors for the token (#1114) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/tunnel.test.ts | 118 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 116 insertions(+), 2 deletions(-) diff --git a/src/cli/tunnel.test.ts b/src/cli/tunnel.test.ts index a1aeace87..ed2a84dc3 100644 --- a/src/cli/tunnel.test.ts +++ b/src/cli/tunnel.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from "vitest"; +import { TUNNEL_TAG, encodeTunnelFrame } from "../contract/index.js"; import { buildCliEnvironment, runCli } from "./index.js"; import { FakeClock, @@ -38,9 +39,11 @@ function command(env: NodeJS.ProcessEnv) { const err: string[] = []; const webSocket = new FakeWebSocketClientConnector(); const httpJson = new FakeHttpJsonClient(); + const clock = new FakeClock(0); + const tcpStreams = new FakeTcpStreamConnector(); const environment = buildCliEnvironment( { - clock: new FakeClock(0), + clock, daemonHome: { dataDirectory: "/unused", gatewayPresent: false, role: "worker" }, filesystem: new MemoryFilesystem(), homeDirectory: "/home/caller", @@ -53,22 +56,26 @@ function command(env: NodeJS.ProcessEnv) { stderr: { write: (value) => err.push(value) }, stdout: { write: (value) => out.push(value) }, systemStats: new FakeSystemStats({ cpuCount: 2, totalRamBytes: 2 ** 30 }), - tcpStreams: new FakeTcpStreamConnector(), + 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", () => { @@ -138,3 +145,110 @@ describe("simlock tunnel that cannot run", () => { } }); }); + +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", "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", + }, + { + 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"); + 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, + }); + expect(await cli.run(["tunnel", "reverse", "5173"])).toBe(2); + expect(JSON.parse(cli.err.join(""))).toEqual({ error: { code: "USAGE", message } }); + expect(cli.webSocket.connections).toEqual([]); + } + }); +}); From 0fb0d0126dab49d837a47e5315e69a81197fda3a Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:50:18 -0300 Subject: [PATCH 080/103] feat(cli): simlock tunnel words its lease errors for the token and an operator names its lease (#1114) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/commands/tunnel.ts | 1 - src/cli/remote-lease.ts | 19 ++++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/cli/commands/tunnel.ts b/src/cli/commands/tunnel.ts index 67216929c..6ef40bf46 100644 --- a/src/cli/commands/tunnel.ts +++ b/src/cli/commands/tunnel.ts @@ -110,7 +110,6 @@ async function leaseToUse( return selectOnlyLease( (field(leases.body, "leases") as { id: string; requesterId: string }[] | undefined) ?? [], field(identity.body, "role") === "admin" ? "admin" : "agent", - environment, ); } diff --git a/src/cli/remote-lease.ts b/src/cli/remote-lease.ts index 302b98020..91933ebcb 100644 --- a/src/cli/remote-lease.ts +++ b/src/cli/remote-lease.ts @@ -2,11 +2,28 @@ import type { SimlockAdminClient } from "../admin/index.js"; import { UsageError } from "./errors.js"; import type { CommandContext } from "./tree.js"; +// 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"], + 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 = role === "admin" ? leases.filter((lease) => lease.requesterId === environment.requesterId) From 5ee8b88650bfeca75d286d5e35f8019ac69608e8 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:51:16 -0300 Subject: [PATCH 081/103] test: nothing listening warns once per 10 s per tunnel and a 1 MiB response arrives whole (#1114) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/tunnel.test.ts | 124 +++++++++++++++++++++++++++++++++++++++- src/ports/tcp-stream.ts | 6 ++ 2 files changed, 129 insertions(+), 1 deletion(-) diff --git a/src/cli/tunnel.test.ts b/src/cli/tunnel.test.ts index ed2a84dc3..bc52a398c 100644 --- a/src/cli/tunnel.test.ts +++ b/src/cli/tunnel.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest"; -import { TUNNEL_TAG, encodeTunnelFrame } from "../contract/index.js"; +import { TUNNEL_TAG, decodeTunnelFrame, encodeTunnelFrame } from "../contract/index.js"; import { buildCliEnvironment, runCli } from "./index.js"; import { FakeClock, @@ -252,3 +252,125 @@ describe("simlock tunnel that runs", () => { } }); }); + +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 }; +} + +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 () => { + const quiet = await started(["reverse", "5173", "reverse", "6000"]); + quiet.cli.tcpStreams.refusedPorts.add(5173); + 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 !== ""); + await opening(1, 5173); + expect(warnings()).toEqual(["reverse 5173: nothing listening on localhost:5173"]); + quiet.cli.clock.advance(9_999); + await opening(3, 5173); + expect(warnings()).toEqual(["reverse 5173: nothing listening on localhost:5173"]); + await opening(5, 6000); + expect(warnings()).toEqual([ + "reverse 5173: nothing listening on localhost:5173", + "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:5173"); + expect( + sentFrames(quiet.cli) + .filter((f) => f.tag === TUNNEL_TAG.reset) + .map((f) => f.conn), + ).toEqual([1, 3, 5, 7]); + expect(quiet.peer.closedWith).toBeUndefined(); + quiet.cli.signals.emit("SIGINT"); + expect(await quiet.exit).toBe(0); + + const page = await started(["reverse", "5173"]); + page.peer.receive(open(1, 5173)); + await vi.waitFor(() => expect(page.cli.tcpStreams.connections).toHaveLength(1)); + 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 += 65_536) + local.send(response.subarray(at, at + 65_536)); + 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) received.push(...frame.payload); + 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); + + 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.cli.signals.emit("SIGINT"); + expect(await page.exit).toBe(0); + }); +}); diff --git a/src/ports/tcp-stream.ts b/src/ports/tcp-stream.ts index bcd7a8dd6..2f0c2a4a5 100644 --- a/src/ports/tcp-stream.ts +++ b/src/ports/tcp-stream.ts @@ -145,7 +145,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; From 10496974ed5c23df74aa3b4d27dfaa5dc3e9be5a Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:51:32 -0300 Subject: [PATCH 082/103] test(tunnel): the audit's missing cases, the reclaim fixtures and the manual budgets (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/tunnel-frames.test.ts | 28 ++++++ src/core/fake-device-tcp.ts | 3 + src/drivers/android/AGENTS.md | 1 - src/drivers/android/index.test.ts | 34 +++++++- src/drivers/android/physical-handler.test.ts | 13 ++- src/ports/tcp-listener.test.ts | 7 +- src/tunnel/AGENTS.md | 2 +- src/tunnel/worker.test.ts | 91 ++++++++++++++++---- 8 files changed, 156 insertions(+), 23 deletions(-) create mode 100644 src/contract/tunnel-frames.test.ts diff --git a/src/contract/tunnel-frames.test.ts b/src/contract/tunnel-frames.test.ts new file mode 100644 index 000000000..d9ba57c2c --- /dev/null +++ b/src/contract/tunnel-frames.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; + +import { decodeTunnelFrame, encodeTunnelFrame, TUNNEL_TAG } from "./index.js"; + +describe("the tunnel frame codec", () => { + it("encodes [tag][conn u32 big-endian][payload], decodes it from a view that does not start at byte 0, and answers undefined for fewer than 5 bytes", () => { + expect([...encodeTunnelFrame(TUNNEL_TAG.data, 0x01020304, "hi")]).toEqual([ + 3, 1, 2, 3, 4, 104, 105, + ]); + expect([...encodeTunnelFrame(TUNNEL_TAG.data, 1, Uint8Array.of(9, 8))]).toEqual([ + 3, 0, 0, 0, 1, 9, 8, + ]); + expect([...encodeTunnelFrame(TUNNEL_TAG.end, 7)]).toEqual([5, 0, 0, 0, 7]); + + const pooled = Uint8Array.of(0xff, 0xff, 3, 0xff, 0xff, 0xff, 0xfe, 104, 105).subarray(2); + const decoded = decodeTunnelFrame(pooled); + expect(decoded?.tag).toBe(3); + expect(decoded?.conn).toBe(0xff_ff_ff_fe); + expect([...(decoded?.payload ?? [])]).toEqual([104, 105]); + + expect(decodeTunnelFrame(Uint8Array.of(5, 0, 0, 0, 7))).toEqual({ + conn: 7, + payload: new Uint8Array(), + tag: 5, + }); + expect(decodeTunnelFrame(Uint8Array.of(1, 0, 0, 0))).toBeUndefined(); + }); +}); diff --git a/src/core/fake-device-tcp.ts b/src/core/fake-device-tcp.ts index 68888fbbb..56bab8ef6 100644 --- a/src/core/fake-device-tcp.ts +++ b/src/core/fake-device-tcp.ts @@ -34,6 +34,8 @@ export class FakeDeviceTcp implements DeviceTcp { closeFailure: Error | undefined; // why: a test sets a device port's failure to make its `reverse` refuse, as adb does for a port already reversed. readonly failures = new Map(); + // why: every device port a `reverse` ever set, in order, so a test can tell a rule that arrived late from one that never came. + readonly reverseLog: number[] = []; // why: a test sets this to hold every `reverse` until it settles, as an adb call that is slow to answer does. gate: Promise | undefined; readonly #reverses = new Map(); @@ -57,6 +59,7 @@ export class FakeDeviceTcp implements DeviceTcp { await this.gate; const failure = this.failures.get(devicePort); if (failure !== undefined) throw failure; + this.reverseLog.push(devicePort); const hostPort = this.#nextHostPort; this.#nextHostPort += 1; const reverse = new FakeReverse( diff --git a/src/drivers/android/AGENTS.md b/src/drivers/android/AGENTS.md index b11b53fc7..63c3d5c2b 100644 --- a/src/drivers/android/AGENTS.md +++ b/src/drivers/android/AGENTS.md @@ -114,7 +114,6 @@ Lease environment: virtual `ANDROID_ADB_SERVER_PORT=`; physical `ANDROID_A No slim: `resolveSpec` ignores `mode` and returns a full spec. `fresh` is core's. Screen — `screenCapture` and `input`, only when `create` got `scrcpyServerPath` and `tcpStreamConnector`: [screen](screen/AGENTS.md), [input](input/AGENTS.md). - Tunnels — `deviceTcp` (`device-tcp.ts`), only when `create` got `tcpListener`: `reverse` listens on a free loopback port in 47000-47999 (busy ones skipped; none free → `TUNNEL_FAILED`) and runs `adb reverse --no-rebind tcp: tcp:` on the device's own server (an emulator's on Simlock's port, a phone's on 5037 behind the gate), 10 s per call; `cannot rebind existing socket` → `TUNNEL_PORT_IN_USE`, any other failure → `TUNNEL_FAILED` (message cut to 200 characters). `close` removes the rule, then the listener; a removal that fails keeps the listener, closing every connection at once. Cleanup: reclaim (with or without `tcpListener`) of a phone, and of an emulator once its ownership probe passed, runs `reverse --remove-all` and removes this serial's `forward --list` lines one by one with `forward --remove ` (never `--remove-all`); an emulator not proved its own is left alone. `deviceTcp.sweep` (only with `tcpListener`), called by the daemon before any request is served, removes on every present owned emulator and phone, leased or idle, the `reverse --list` rules whose host side is `tcp:47000`-`tcp:47999`. A failed removal is a `warn`; reclaim and start go on. Plain facts: `listCatalog`, a resolve of a model the library lacks and a library provision (seed) share one `AvdmanagerDeviceList`: `avdmanager list device` runs again only when the size or modified time of a file it reads profiles from changed, or one appeared or went: the tools package's `lib/sdklib/sdklib.core.jar` (legacy `tools/lib/sdklib*.jar`) and `source.properties`, the user's devices.xml, `devices.xml` in each `system-images/*/*/*` and `add-ons/*` directory (a new image is a new path), and `devices.xml` and `source.properties` in each `extras/*/*` directory (avdmanager reads an extra whose `source.properties` says `Extra.Path=DeviceProfiles`). diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 143233596..ce760850c 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -796,7 +796,7 @@ describe("AndroidDriver", () => { }); }); - it("captures a named clean baseline once and restores it on a standard reclaim", async () => { + it("captures a named clean baseline once and restores it on a standard reclaim, after removing the emulator's adb rules", async () => { const harness = await provisionedHarness({ forBaselineReclaim: true }); const ready = await harness.driver.makeReady(harness.device); @@ -812,6 +812,13 @@ describe("AndroidDriver", () => { }); const saves = harness.runner.calls.filter((call) => call.args.includes("save")); expect(saves).toHaveLength(1); + const commands = harness.runner.calls.map((call) => call.args.join(" ")); + const removed = commands.indexOf("-P 5038 -s emulator-5586 reverse --remove-all"); + expect(removed).toBeGreaterThan(-1); + expect(commands.indexOf("-P 5038 -s emulator-5586 forward --list")).toBe(removed + 1); + expect(commands.indexOf("-s emulator-5586 emu avd snapshot load simlock_clean_baseline")).toBe( + removed + 2, + ); }); it("tags the baseline with the emulator-normalized post-boot configuration", async () => { @@ -846,6 +853,7 @@ describe("AndroidDriver", () => { const restartedRunner = new ScriptedProcessRunner([ processResult(binaries.emulator, ["-version"], "Android emulator version 36.1.9"), avdPathExpectation("emulator-5586"), + ...ruleCleanupExpectations("emulator-5586"), processResult( binaries.adb, ["-s", "emulator-5586", "emu", "avd", "snapshot", "load", "simlock_clean_baseline"], @@ -4759,7 +4767,7 @@ describe("AndroidDriver console ports across a restart", () => { }); it.each(["shutdown", "full reclaim", "standard reclaim"] as const)( - "%s after a restart sends neither kill nor snapshot load to another device on the stored serial (#284)", + "%s after a restart sends no kill, snapshot load or rule removal to another device on the stored serial (#284)", async (operation) => { const spec = { physical: false, @@ -4792,6 +4800,14 @@ describe("AndroidDriver console ports across a restart", () => { expect({ running: host.avdAnswering(running.address), + ruleCalls: runner.calls + .slice(callStart) + .filter( + (call) => + call.args.includes(running.address) && + (call.args.includes("reverse") || call.args.includes("forward")), + ) + .map((call) => call.args), mutations: runner.calls .slice(callStart) .filter( @@ -4802,7 +4818,7 @@ describe("AndroidDriver console ports across a restart", () => { call.args.slice(2, 6).join(" ") === "emu avd snapshot load"), ) .map((call) => call.args), - }).toEqual({ running: "simlock_two", mutations: [] }); + }).toEqual({ running: "simlock_two", ruleCalls: [], mutations: [] }); }, ); @@ -5539,6 +5555,7 @@ async function provisionedHarness( expectations.push( processResult(binaries.emulator, ["-version"], "Android emulator version 36.1.9"), avdPathExpectation("emulator-5586"), + ...ruleCleanupExpectations("emulator-5586"), processResult( binaries.adb, ["-s", "emulator-5586", "emu", "avd", "snapshot", "load", "simlock_clean_baseline"], @@ -6468,9 +6485,11 @@ function onlyProvided(options: { readonly onDiagnostic?: (diagnostic: AndroidDriverDiagnostic) => void; readonly readinessTimeoutMs?: number; readonly scrcpyServerPath?: string; + readonly tcpListener?: FakeTcpListenerFactory; readonly tcpStreamConnector?: FakeTcpStreamConnector; }) { return { + ...(options.tcpListener === undefined ? {} : { tcpListener: options.tcpListener }), ...(options.scrcpyServerPath === undefined ? {} : { scrcpyServerPath: options.scrcpyServerPath }), @@ -7125,6 +7144,15 @@ function avdPathExpectation(serial: string, avdName = "simlock_one"): ScriptedPr ); } +// why: a reclaim that passed its ownership probe removes the device's rules before it loads the snapshot: every reverse rule, then a look at the forwards (none here). +function ruleCleanupExpectations(serial: string): ScriptedProcessExpectation[] { + const onServer = ["-P", String(adbServerPort), "-s", serial]; + return [ + processResult(binaries.adb, [...onServer, "reverse", "--remove-all"]), + processResult(binaries.adb, [...onServer, "forward", "--list"]), + ]; +} + function markWriteExpectation(serial: string, token: string): ScriptedProcessExpectation { return processResult(binaries.adb, [ "-s", diff --git a/src/drivers/android/physical-handler.test.ts b/src/drivers/android/physical-handler.test.ts index 1e0c42a83..cb9754546 100644 --- a/src/drivers/android/physical-handler.test.ts +++ b/src/drivers/android/physical-handler.test.ts @@ -364,6 +364,10 @@ function isUninstall(rest: readonly string[]): boolean { return rest.includes("uninstall"); } +function isRuleCommand(rest: readonly string[]): boolean { + return rest[2] === "reverse" || rest[2] === "forward"; +} + function defaultServerSends(probe: FakeTcpProbe) { return probe.sends.filter((send) => send.port === 5037); } @@ -1302,7 +1306,7 @@ describe("Android physical handler: reclaim", () => { expect(crlf.runner.rests.filter(isUninstall)).toHaveLength(1); }); - it("passes a 30 000 ms limit with every read and a 60 000 ms limit with every uninstall to the process runner", async () => { + it("passes a 30 000 ms limit with every read, a 60 000 ms limit with every uninstall and a 10 000 ms limit with every rule removal to the process runner", async () => { const { driver, runner } = await world(); await driver.inspectPhysical(PHONE); @@ -1310,9 +1314,14 @@ describe("Android physical handler: reclaim", () => { await driver.reclaim(PHYSICAL, { clean: "standard" }); const uninstalls = runner.commands.filter((call) => isUninstall(restOf(call))); - const reads = runner.calls.filter((call) => !isUninstall(restOf(call))); + const removals = runner.calls.filter((call) => isRuleCommand(restOf(call))); + const reads = runner.calls.filter( + (call) => !isUninstall(restOf(call)) && !isRuleCommand(restOf(call)), + ); expect(uninstalls).not.toHaveLength(0); + expect(removals).not.toHaveLength(0); expect(uninstalls.map((call) => call.options.timeoutMs)).toEqual(uninstalls.map(() => 60_000)); + expect(removals.map((call) => call.options.timeoutMs)).toEqual(removals.map(() => 10_000)); expect(reads.map((call) => call.options.timeoutMs)).toEqual(reads.map(() => 30_000)); }); }); diff --git a/src/ports/tcp-listener.test.ts b/src/ports/tcp-listener.test.ts index 3b2a3b67a..0d0de1a72 100644 --- a/src/ports/tcp-listener.test.ts +++ b/src/ports/tcp-listener.test.ts @@ -16,7 +16,7 @@ async function freePort(): Promise { // why: an adapter over node:net, proven by what a real loopback socket does, which the fake cannot show. describe("NodeTcpListenerFactory", () => { - it("hands out a loopback port whose connections arrive as streams, answers undefined for a taken port, and frees the port on close", async () => { + it("hands out a loopback port whose connections arrive as streams, lets the worker answer after the peer half-closed, answers undefined for a taken port, and frees the port on close", async () => { const port = await freePort(); const factory = new NodeTcpListenerFactory(); const listener = await factory.listen(port); @@ -29,6 +29,8 @@ describe("NodeTcpListenerFactory", () => { const chunks: Uint8Array[] = []; for await (const chunk of stream.readable) chunks.push(chunk); resolve(Buffer.concat(chunks).toString()); + await stream.write("reply"); + stream.end(); })(); }); }); @@ -36,6 +38,9 @@ describe("NodeTcpListenerFactory", () => { await client.write("hello"); client.end(); expect(await received).toBe("hello"); + const reply: Uint8Array[] = []; + for await (const chunk of client.readable) reply.push(chunk); + expect(Buffer.concat(reply).toString()).toBe("reply"); client.close(); await listener?.close(); diff --git a/src/tunnel/AGENTS.md b/src/tunnel/AGENTS.md index 180953cd0..829f0bb0c 100644 --- a/src/tunnel/AGENTS.md +++ b/src/tunnel/AGENTS.md @@ -2,7 +2,7 @@ Does: lets a lease's holder (or an operator) reverse device ports of its Android device to its own machine over `WS /v1/leases/{id}/tunnel`, on a lone worker. Entry: `index.ts` -> `tunnelModule`, an optional module (ADR 0054): `worker.ts` `createWorker`, loaded by the module host only when turned on. -Uses: contract (`tunnel-frames.ts`), core (`DeviceReverse`, `DeviceTcpError`), modules (the context, socket types), ports (`LeaseSocket`). +Uses: contract (the tunnel frame codec), core (`DeviceReverse`, `DeviceTcpError`), modules (the context, socket types), ports (`LeaseSocket`). Never imports: http, gateway, drivers, daemon, leasing, `fs`, `child_process`. Imported by: `module-registry` only. Off unless `capabilities.tunnel.enabled` (false). Off: nothing loaded, and the `tunnel` capability reads `off`. diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index 02ee20576..f3d20e36b 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -56,7 +56,10 @@ async function setup(platform = "android"): Promise<{ const registry = { snapshot: { devices: [{ id: "dev_1", spec: { platform } } as unknown as DeviceRecord], - leases: [{ deviceId: "dev_1", id: "L-1" } as unknown as LeaseRecord], + leases: [ + { deviceId: "dev_1", id: "L-1" } as unknown as LeaseRecord, + { deviceId: "dev_1", id: "L-2" } as unknown as LeaseRecord, + ], }, }; const loaded = await tunnelModule.loadWorker(); @@ -71,10 +74,10 @@ async function setup(platform = "android"): Promise<{ return { deviceTcp, worker }; } -async function attach(worker: WorkerModule): Promise { +async function attach(worker: WorkerModule, leaseId = "L-1"): Promise { const opened = await worker.socket?.open(new Request("http://simlock/tunnel"), IDENTITY, { deviceId: "dev_1", - id: "L-1", + id: leaseId, }); expect(opened).toBeTypeOf("function"); const socket = new MemoryLeaseSocket(); @@ -113,23 +116,23 @@ describe("a worker's tunnel socket", () => { const { deviceTcp, worker } = await setup(); const socket = await attach(worker); socket.receive( - hello({ devicePort: 5173, kind: "reverse" }, { devicePort: 5174, kind: "reverse" }), + hello({ devicePort: 1024, kind: "reverse" }, { devicePort: 65535, kind: "reverse" }), ); await vi.waitFor(() => expect(frames(socket)).toEqual([ { - body: '{"tunnels":[{"kind":"reverse","devicePort":5173},{"kind":"reverse","devicePort":5174}]}', + body: '{"tunnels":[{"kind":"reverse","devicePort":1024},{"kind":"reverse","devicePort":65535}]}', conn: 0, tag: 0x81, }, ]), ); - const first = deviceTcp.connect(5173); - const second = deviceTcp.connect(5174); + const first = deviceTcp.connect(1024); + const second = deviceTcp.connect(65535); await vi.waitFor(() => expect(frames(socket).slice(1)).toEqual([ - { body: '{"kind":"reverse","devicePort":5173}', conn: 1, tag: 0x02 }, - { body: '{"kind":"reverse","devicePort":5174}', conn: 3, tag: 0x02 }, + { body: '{"kind":"reverse","devicePort":1024}', conn: 1, tag: 0x02 }, + { body: '{"kind":"reverse","devicePort":65535}', conn: 3, tag: 0x02 }, ]), ); @@ -151,16 +154,16 @@ describe("a worker's tunnel socket", () => { ); const opens = () => frames(socket).filter((sent) => sent.tag === 0x02).length; - const peers = Array.from({ length: 255 }, () => deviceTcp.connect(5173)); + const peers = Array.from({ length: 255 }, () => deviceTcp.connect(1024)); await vi.waitFor(() => expect(opens()).toBe(257)); expect(peers.every((peer) => !peer.closed)).toBe(true); - const past = deviceTcp.connect(5173); + const past = deviceTcp.connect(1024); await vi.waitFor(() => expect(past.closed).toBe(true)); expect(opens()).toBe(257); socket.receive(frame(0x06, 3, '{"reason":"done"}')); await vi.waitFor(() => expect(second.closed).toBe(true)); - const after = deviceTcp.connect(5173); + const after = deviceTcp.connect(1024); await vi.waitFor(() => expect(opens()).toBe(258)); expect(after.closed).toBe(false); }); @@ -321,6 +324,33 @@ describe("a worker's tunnel socket", () => { ready: false, send: (socket) => socket.receive(frame(0x01, 0, '{"tunnels":"all"}')), }, + { + message: "HELLO tunnels must each be {kind, devicePort}", + ready: false, + send: (socket) => socket.receive(hello({ devicePort: 5173, kind: "bogus" })), + }, + { + message: "HELLO tunnels must each be {kind, devicePort}", + ready: false, + send: (socket) => + socket.receive(frame(0x01, 0, '{"tunnels":[{"kind":"reverse","devicePort":5173.5}]}')), + }, + { + message: "HELLO tunnels must each be {kind, devicePort}", + ready: false, + send: (socket) => + socket.receive(frame(0x01, 0, '{"tunnels":[{"kind":"reverse","devicePort":"5173"}]}')), + }, + { + message: "HELLO tunnels must each be {kind, devicePort}", + ready: false, + send: (socket) => socket.receive(frame(0x01, 0, '{"tunnels":[null]}')), + }, + { + message: "a frame is shorter than its 5-byte header", + ready: false, + send: (socket) => socket.receive(Uint8Array.of(0x01, 0, 0, 0)), + }, { message: "HELLO is longer than 4096 bytes", ready: false, @@ -340,9 +370,11 @@ describe("a worker's tunnel socket", () => { message: "DATA is past the granted window", ready: true, send: (socket) => { - for (let sent = 0; sent < 5; sent += 1) { + for (let sent = 0; sent < 4; sent += 1) { socket.receive(bigData(1)); } + expect(socket.closed).toBeUndefined(); + socket.receive(bigData(1)); }, }, { @@ -350,6 +382,11 @@ describe("a worker's tunnel socket", () => { ready: true, send: (socket) => socket.receive(frame(0x03, 99, "x")), }, + { + message: "connection 5 was never opened", + ready: true, + send: (socket) => socket.receive(frame(0x03, 5, "x")), + }, { message: "connection 2 was never opened", ready: true, @@ -358,7 +395,11 @@ describe("a worker's tunnel socket", () => { { message: "the window is above 2147483648", ready: true, - send: (socket) => socket.receive(credit(1, 2 ** 31)), + send: (socket) => { + socket.receive(credit(1, 2 ** 31 - 262_144)); + expect(socket.closed).toBeUndefined(); + socket.receive(credit(1, 1)); + }, }, ]; for (const bad of cases) { @@ -368,7 +409,8 @@ describe("a worker's tunnel socket", () => { socket.receive(hello(tunnel)); await vi.waitFor(() => expect(frames(socket)).toHaveLength(1)); deviceTcp.connect(5173); - await vi.waitFor(() => expect(frames(socket)).toHaveLength(2)); + deviceTcp.connect(5173); + await vi.waitFor(() => expect(frames(socket)).toHaveLength(3)); } expect(socket.closed).toBeUndefined(); bad.send(socket); @@ -442,6 +484,24 @@ describe("a worker's tunnel socket", () => { expect(ended.device.closed).toBe(true); expect(ended.socket.closed).toEqual({ code: 4001, reason: "expired" }); + const pair = await open(); + const bystander = await attach(pair.worker, "L-2"); + bystander.receive(hello({ devicePort: 5180, kind: "reverse" })); + await vi.waitFor(() => expect(frames(bystander)).toHaveLength(1)); + await pair.worker.hooks?.beforeDeviceReclaim?.( + { + deviceId: "dev_1", + leaseId: "L-1", + ownerId: "tok_holder", + platform: "android", + reason: "expired", + }, + new AbortController().signal, + ); + expect(pair.socket.closed).toEqual({ code: 4001, reason: "expired" }); + expect(bystander.closed).toBeUndefined(); + expect(pair.deviceTcp.reversed).toEqual([5180]); + const stopped = await open(); await stopped.worker.hooks?.beforeDrain?.(); expect(stopped.deviceTcp.reversed).toEqual([]); @@ -488,6 +548,7 @@ describe("a worker's tunnel socket", () => { early.receive(hello(tunnel)); early.drop(); release(); + await vi.waitFor(() => expect(racing.deviceTcp.reverseLog).toEqual([5173])); await vi.waitFor(() => expect(racing.deviceTcp.reversed).toEqual([])); }); }); From c315e7db6e0c0eec5bd0f9bb05e95799443d7557 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:52:08 -0300 Subject: [PATCH 083/103] feat(cli): simlock tunnel warns when nothing listens and honours the credit window both ways (#1114) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/commands/tunnel.ts | 103 +++++++++++++++++++++++++++---------- 1 file changed, 76 insertions(+), 27 deletions(-) diff --git a/src/cli/commands/tunnel.ts b/src/cli/commands/tunnel.ts index 6ef40bf46..8cc3d4663 100644 --- a/src/cli/commands/tunnel.ts +++ b/src/cli/commands/tunnel.ts @@ -8,6 +8,7 @@ import { TUNNEL_MAX_DEVICE_PORT, TUNNEL_MAX_TUNNELS, TUNNEL_TAG, + TUNNEL_WINDOW_BYTES, } from "../../contract/index.js"; import type { TcpStream, WebSocketClient } from "../../ports/index.js"; import { commandArgs, UsageError } from "../args.js"; @@ -18,6 +19,7 @@ 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; @@ -113,42 +115,80 @@ async function leaseToUse( ); } -// 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. -function relayConnections(socket: WebSocketClient, environment: CliEnvironment) { - const streams = new Map }>(); +// 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; + } + relayed.window -= size; + socket.send(encodeTunnelFrame(TUNNEL_TAG.data, conn, step.value.subarray(at, at + size))); + at += size; + } + } + socket.send(encodeTunnelFrame(TUNNEL_TAG.end, 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)); + }; return async ( spec: ReverseSpec | undefined, frame: { tag: number; conn: number; payload: Uint8Array }, ): Promise => { if (frame.tag === TUNNEL_TAG.open && spec !== undefined) { - const stream = await environment.tcpStreams.connect( - spec.callerPort, - CALLER_CONNECT_TIMEOUT_MS, - ); - streams.set(frame.conn, { stream, writes: Promise.resolve() }); - void (async () => { - const reader = stream.readable.getReader(); - for (;;) { - const step = await reader.read(); - if (step.done) break; - for (let at = 0; at < step.value.length; at += TUNNEL_MAX_DATA_BYTES) { - socket.send( - encodeTunnelFrame( - TUNNEL_TAG.data, - frame.conn, - step.value.subarray(at, at + TUNNEL_MAX_DATA_BYTES), - ), - ); - } - } - socket.send(encodeTunnelFrame(TUNNEL_TAG.end, frame.conn)); - })(); + 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, frame.conn)); + return; + } + const relayed: Relayed = { + stream, + wake: undefined, + window: TUNNEL_WINDOW_BYTES, + writes: Promise.resolve(), + }; + streams.set(frame.conn, relayed); + void pump(frame.conn, relayed); return; } const connection = streams.get(frame.conn); if (connection === undefined) return; if (frame.tag === TUNNEL_TAG.data) { - connection.writes = connection.writes.then(() => connection.stream.write(frame.payload)); + connection.writes = connection.writes + .then(() => connection.stream.write(frame.payload)) + .then(() => grant(frame.conn, frame.payload.length)); + } 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()); } else if (frame.tag === TUNNEL_TAG.reset) { @@ -189,7 +229,16 @@ async function run( headers: { authorization: `Bearer ${secret}` }, }, ); - const relay = relayConnections(socket, environment); + 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(); return new Promise((resolve, reject) => { From 5e55c816268de5368d04d1ec619d4822672b1eed Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:53:50 -0300 Subject: [PATCH 084/103] test: simlock tunnel that is refused or loses its worker exits with the worker's code and one JSON line (#1114) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/tunnel.test.ts | 169 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 169 insertions(+) diff --git a/src/cli/tunnel.test.ts b/src/cli/tunnel.test.ts index bc52a398c..46aab0e34 100644 --- a/src/cli/tunnel.test.ts +++ b/src/cli/tunnel.test.ts @@ -9,6 +9,7 @@ import { FakeSystemStats, FakeTcpStreamConnector, FakeWebSocketClientConnector, + WebSocketRefusedError, MemoryFilesystem, MemoryIpcTransport, } from "../ports/index.js"; @@ -374,3 +375,171 @@ describe("simlock tunnel carrying connections", () => { expect(await page.exit).toBe(0); }); }); + +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 } }; +} + +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 () => { + const line = (cli: ReturnType) => JSON.parse(cli.err.join("")) as unknown; + const upgrades: readonly { + readonly refusal: WebSocketRefusedError; + 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"), + }, + ]; + for (const { code, message, refusal } of upgrades) { + const cli = command(ENV); + cli.webSocket.failure = refusal; + expect(await cli.run(["tunnel", "reverse", "5173", "--lease", "L1"])).toBe(1); + expect(line(cli)).toEqual(errorBody(code, message)); + } + + 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", + 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([]); + } + + const refused = await started(["reverse", "80"]); + refused.peer.receive(refusedFrame("TUNNEL_BAD_PORT", "Device port 80 is below 1024")); + expect(await refused.exit).toBe(1); + expect(line(refused.cli)).toEqual( + errorBody("TUNNEL_BAD_PORT", "Lease L1: Device port 80 is below 1024"), + ); + + 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 the worker was lost"), + exit: 1, + })), + ]; + for (const { drop, error, exit } of losses) { + const lost = await started(["reverse", "5173"]); + lost.peer.dropped(...drop); + expect(await lost.exit).toBe(exit); + expect(line(lost.cli)).toEqual(error); + } + + const silent = await started(["reverse", "5173"]); + silent.cli.clock.advance(30_000); + silent.peer.ping(); + silent.cli.clock.advance(44_999); + expect(silent.cli.err).toEqual([]); + silent.peer.receive(open(1, 5173)); + silent.cli.clock.advance(44_999); + expect(silent.cli.err).toEqual([]); + silent.cli.clock.advance(1); + expect(await silent.exit).toBe(1); + expect(line(silent.cli)).toEqual( + errorBody("TUNNEL_DISCONNECTED", "Lease L1: nothing was heard from the worker for 45 s"), + ); + + 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(); + } + expect(noReady.err).toEqual([]); + noReady.clock.advance(1); + expect(await noReadyExit).toBe(1); + expect(line(noReady)).toEqual( + errorBody("TUNNEL_DISCONNECTED", "Lease L1: no READY from the worker within 90 s"), + ); + + 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(); + } + expect(idle.cli.err).toEqual([]); + expect(idle.peer.closedWith).toBeUndefined(); + 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 Promise.resolve(); + expect(settled).toBe(false); + idle.cli.clock.advance(1); + expect(await idle.exit).toBe(0); + + const term = await started(["reverse", "5173"]); + term.cli.signals.emit("SIGTERM"); + expect(term.peer.closedWith?.code).toBe(1000); + term.peer.dropped(1000, ""); + expect(await term.exit).toBe(0); + }); +}); From 287bfd0bdf646aa44a5c954817f2ee99a82b989e Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:56:15 -0300 Subject: [PATCH 085/103] feat(cli): simlock tunnel exits with the worker's code, times out silent sockets and closes on Ctrl-C (#1114) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/commands/tunnel.ts | 264 ++++++++++++++++++++++++++-------- src/cli/tunnel.test.ts | 2 +- src/ports/websocket-client.ts | 4 + 3 files changed, 206 insertions(+), 64 deletions(-) diff --git a/src/cli/commands/tunnel.ts b/src/cli/commands/tunnel.ts index 8cc3d4663..30da58d00 100644 --- a/src/cli/commands/tunnel.ts +++ b/src/cli/commands/tunnel.ts @@ -2,7 +2,6 @@ import { decodeTunnelFrame, encodeTunnelFrame, ERROR_TABLE, - SimlockError, type SimlockErrorCode, TUNNEL_MAX_DATA_BYTES, TUNNEL_MAX_DEVICE_PORT, @@ -10,7 +9,12 @@ import { TUNNEL_TAG, TUNNEL_WINDOW_BYTES, } from "../../contract/index.js"; -import type { TcpStream, WebSocketClient } from "../../ports/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"; @@ -100,21 +104,6 @@ function field(value: unknown, name: string): unknown { return typeof value === "object" && value !== null ? Reflect.get(value, name) : undefined; } -async function leaseToUse( - environment: CliEnvironment, - base: string, - token: string, - lease: string | undefined, -): Promise { - if (lease !== undefined) return lease; - const identity = await environment.httpJson.get(`${base}/v1/identity`, token); - const leases = await environment.httpJson.get(`${base}/v1/leases`, token); - return selectOnlyLease( - (field(leases.body, "leases") as { id: string; requesterId: string }[] | undefined) ?? [], - field(identity.body, "role") === "admin" ? "admin" : "agent", - ); -} - // 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, @@ -198,37 +187,124 @@ function relayConnections( }; } -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", +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 0; } - const specs = parseReverses(positionals); - const base = checkedUrl(typeof url === "string" ? url : environment.tunnelUrl); - const secret = checkedToken(token ?? environment.tunnelToken); - const leaseId = await leaseToUse( - environment, - base, - secret, - typeof lease === "string" ? lease : undefined, + 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", ); - const socket = await environment.webSocket.connect( - `${base.replace(/^http/, "ws")}/v1/leases/${encodeURIComponent(leaseId)}/tunnel`, - { - handshakeTimeoutMs: HANDSHAKE_TIMEOUT_MS, - headers: { authorization: `Bearer ${secret}` }, - }, +} + +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: unknown = JSON.parse(new TextDecoder().decode(frame.payload)); + const code = field(refusal, "code"); + const known = + typeof code === "string" && code in ERROR_TABLE ? (code as SimlockErrorCode) : "TUNNEL_FAILED"; + return new TunnelFailure( + known, + `Lease ${leaseId}: ${String(field(refusal, "message"))}`, + ERROR_TABLE[known].cliExitCode, ); +} + +function serve( + environment: CliEnvironment, + socket: WebSocketClient, + specs: readonly ReverseSpec[], + leaseId: string, +): Promise { const warned = new Map(); const relay = relayConnections(socket, environment, (devicePort, callerPort) => { const now = environment.clock.now(); @@ -242,37 +318,63 @@ async function run( // 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(); return new Promise((resolve, reject) => { - const settle = () => { + let silence: TimerHandle | undefined; + let finished = false; + let stopping = false; + const helloTimer = environment.clock.setTimer(HELLO_TIMEOUT_MS, () => { + end(disconnected(`Lease ${leaseId}: no READY from the worker within 90 s`)); + }); + 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`)); + }); + }; + function end(failure: TunnelFailure | undefined): void { + if (finished) return; + finished = true; environment.signals.off("SIGINT", stop); environment.signals.off("SIGTERM", stop); - }; - const stop = () => { - settle(); + environment.clock.cancel(helloTimer); + if (silence !== undefined) environment.clock.cancel(silence); + if (failure === undefined) resolve(0); + else reject(failure); + } + function stop(): void { + if (finished) return; + stopping = true; + environment.clock.setTimer(CLOSE_WAIT_MS, () => end(undefined)); socket.close(CLOSE_NORMAL, ""); - resolve(0); - }; + } environment.signals.on("SIGINT", stop); environment.signals.on("SIGTERM", stop); + heard(); + socket.onPing(heard); + socket.onClose((code, reason) => { + 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 the worker was lost`), + ); + }); socket.onMessage((bytes) => { + heard(); const frame = decodeTunnelFrame(bytes); if (frame === undefined) return; if (frame.tag === TUNNEL_TAG.refused) { - settle(); - const refusal: unknown = JSON.parse(new TextDecoder().decode(frame.payload)); - const code = field(refusal, "code"); - reject( - new SimlockError( - typeof code === "string" && code in ERROR_TABLE - ? (code as SimlockErrorCode) - : "TUNNEL_FAILED", - "domain", - `Lease ${leaseId}: ${String(field(refusal, "message"))}`, - {} as never, - ), - ); + 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`, @@ -302,4 +404,40 @@ async function run( }); } +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); + try { + const leaseId = await leaseToUse( + environment, + base, + secret, + typeof lease === "string" ? lease : undefined, + ); + const socket = await openSocket(environment, base, secret, leaseId); + return await serve(environment, socket, specs, leaseId); + } 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/tunnel.test.ts b/src/cli/tunnel.test.ts index 46aab0e34..75ed0cda9 100644 --- a/src/cli/tunnel.test.ts +++ b/src/cli/tunnel.test.ts @@ -524,6 +524,7 @@ describe("simlock tunnel that is refused or loses its worker", () => { } expect(idle.cli.err).toEqual([]); expect(idle.peer.closedWith).toBeUndefined(); + idle.peer.silentOnClose = true; idle.cli.signals.emit("SIGINT"); expect(idle.peer.closedWith?.code).toBe(1000); let settled = false; @@ -539,7 +540,6 @@ describe("simlock tunnel that is refused or loses its worker", () => { const term = await started(["reverse", "5173"]); term.cli.signals.emit("SIGTERM"); expect(term.peer.closedWith?.code).toBe(1000); - term.peer.dropped(1000, ""); expect(await term.exit).toBe(0); }); }); diff --git a/src/ports/websocket-client.ts b/src/ports/websocket-client.ts index 918486c1a..bdafa7779 100644 --- a/src/ports/websocket-client.ts +++ b/src/ports/websocket-client.ts @@ -116,6 +116,8 @@ export class NodeWebSocketClientConnector implements WebSocketClientConnector { export class FakeWebSocketPeer implements WebSocketClient { readonly sent: Uint8Array[] = []; closedWith: { readonly code: number; readonly reason: string } | undefined; + // 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)[] = []; @@ -126,6 +128,8 @@ export class FakeWebSocketPeer implements WebSocketClient { close(code: number, reason: string): void { this.closedWith = { code, reason }; + if (this.silentOnClose) return; + for (const listener of this.#closes) listener(code, reason); } onMessage(listener: (bytes: Uint8Array) => void): void { From 7a593600f7f74234f4104df36069d457bc94396c Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:57:09 -0300 Subject: [PATCH 086/103] test: lazy-loading shows ws loaded by simlock tunnel alone (#1114) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/lazy-loading.test.ts | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) 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"); + }); }); From 502915389b7846ed98adbe4090fdc6864892cafc Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:58:04 -0300 Subject: [PATCH 087/103] test: the http-json and websocket-client adapters against a real server (#1114) Co-Authored-By: Claude Sonnet 5.5 --- src/ports/http-json.test.ts | 56 ++++++++++++++++++++++ src/ports/websocket-client.test.ts | 75 ++++++++++++++++++++++++++++++ 2 files changed, 131 insertions(+) create mode 100644 src/ports/http-json.test.ts create mode 100644 src/ports/websocket-client.test.ts diff --git a/src/ports/http-json.test.ts b/src/ports/http-json.test.ts new file mode 100644 index 000000000..8fa10b5a7 --- /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 - 12) })); + } 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/websocket-client.test.ts b/src/ports/websocket-client.test.ts new file mode 100644 index 000000000..2637df686 --- /dev/null +++ b/src/ports/websocket-client.test.ts @@ -0,0 +1,75 @@ +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; + wss.on("connection", (socket, request) => { + authorization = request.headers.authorization; + 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 late: [number, string][] = []; + client.onClose((code, reason) => late.push([code, reason])); + expect(late).toEqual([[4001, "got 2"]]); + }); +}); From 92e4024d487a33670cb78e6080196a9202dc4925 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:58:28 -0300 Subject: [PATCH 088/103] docs(cli): the tunnel command, its lease resolver and the lazy ws adapter in the manuals (#1114) Co-Authored-By: Claude Sonnet 5.5 --- docs/internal/ARCHITECTURE.md | 2 +- src/cli/AGENTS.md | 48 ++++++++++++++++++++--------------- src/ports/uplink-websocket.ts | 9 ++++--- 3 files changed, 34 insertions(+), 25 deletions(-) diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index e1c37c256..23f89dccf 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/src/cli/AGENTS.md b/src/cli/AGENTS.md index b69dd3f67..14eb9b496 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`: a piped stdin for `simctl`/`adb`, read to EOF | -| `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`: a piped stdin for `simctl`/`adb`, read to EOF | +| `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`. @@ -94,6 +94,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) + 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/ports/uplink-websocket.ts b/src/ports/uplink-websocket.ts index 815f5a14f..12a56a99a 100644 --- a/src/ports/uplink-websocket.ts +++ b/src/ports/uplink-websocket.ts @@ -3,10 +3,11 @@ * 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 `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 From e999928c9bd05d4972469007f73734129f3bd8fd Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:59:17 -0300 Subject: [PATCH 089/103] test: a page on the caller's loopback port loads on a real emulator through simlock tunnel reverse (#1114) Co-Authored-By: Claude Sonnet 5.5 --- e2e/slow-android-tunnel.test.ts | 108 ++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 e2e/slow-android-tunnel.test.ts 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); + } + }, + ); + }, +); From e08812e20e46f634d2485ed0b90636baefb0eb3b Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:00:36 -0300 Subject: [PATCH 090/103] chore(tunnel): Fallow findings of the cli and ports cycles (#1114) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/commands/tunnel.ts | 94 +++++----- src/cli/tunnel.test.ts | 328 ++++++++++++++++++---------------- src/ports/index.ts | 9 +- src/ports/websocket-client.ts | 5 +- 4 files changed, 231 insertions(+), 205 deletions(-) diff --git a/src/cli/commands/tunnel.ts b/src/cli/commands/tunnel.ts index 30da58d00..1c0299072 100644 --- a/src/cli/commands/tunnel.ts +++ b/src/cli/commands/tunnel.ts @@ -40,33 +40,33 @@ function portOf(text: string, what: string): number { 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) { - 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"); - specs.push({ - callerPort: portOf(colon === -1 ? device : text.slice(colon + 1), "caller"), - devicePort, - }); - } + 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 seen = new Set(); - for (const { callerPort } of specs) { - if (seen.has(callerPort)) { - throw new UsageError(`Caller port ${String(callerPort)} is named by two tunnels`); - } - seen.add(callerPort); + 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; } @@ -142,31 +142,28 @@ function relayConnections( new DataView(credit.buffer).setUint32(0, size); socket.send(encodeTunnelFrame(TUNNEL_TAG.credit, conn, credit)); }; - return async ( - spec: ReverseSpec | undefined, - frame: { tag: number; conn: number; payload: Uint8Array }, - ): Promise => { - if (frame.tag === TUNNEL_TAG.open && spec !== undefined) { - 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, frame.conn)); - return; - } - const relayed: Relayed = { - stream, - wake: undefined, - window: TUNNEL_WINDOW_BYTES, - writes: Promise.resolve(), - }; - streams.set(frame.conn, relayed); - void pump(frame.conn, relayed); + 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 connection = streams.get(frame.conn); - if (connection === undefined) 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)) @@ -185,6 +182,17 @@ function relayConnections( streams.delete(frame.conn); } }; + return 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 HELLO_TIMEOUT_MS = 90_000; diff --git a/src/cli/tunnel.test.ts b/src/cli/tunnel.test.ts index 75ed0cda9..d4fbd5c9c 100644 --- a/src/cli/tunnel.test.ts +++ b/src/cli/tunnel.test.ts @@ -384,162 +384,190 @@ function errorBody(code: string, message: string) { return { error: { code, message } }; } -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 () => { - const line = (cli: ReturnType) => JSON.parse(cli.err.join("")) as unknown; - const upgrades: readonly { - readonly refusal: WebSocketRefusedError; - 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"), - }, - ]; - for (const { code, message, refusal } of upgrades) { - const cli = command(ENV); - cli.webSocket.failure = refusal; - expect(await cli.run(["tunnel", "reverse", "5173", "--lease", "L1"])).toBe(1); - expect(line(cli)).toEqual(errorBody(code, message)); - } +function line(cli: ReturnType): unknown { + return JSON.parse(cli.err.join("")); +} - 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", - 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 upgradeRefusals(): Promise { + const upgrades: readonly { + readonly refusal: WebSocketRefusedError; + 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"), + }, + ]; + for (const { code, message, refusal } of upgrades) { + const cli = command(ENV); + cli.webSocket.failure = refusal; + expect(await cli.run(["tunnel", "reverse", "5173", "--lease", "L1"])).toBe(1); + expect(line(cli)).toEqual(errorBody(code, message)); + } +} - const refused = await started(["reverse", "80"]); - refused.peer.receive(refusedFrame("TUNNEL_BAD_PORT", "Device port 80 is below 1024")); - expect(await refused.exit).toBe(1); - expect(line(refused.cli)).toEqual( - errorBody("TUNNEL_BAD_PORT", "Lease L1: Device port 80 is below 1024"), - ); +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", + 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([]); + } +} - 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 the worker was lost"), - exit: 1, - })), - ]; - for (const { drop, error, exit } of losses) { - const lost = await started(["reverse", "5173"]); - lost.peer.dropped(...drop); - expect(await lost.exit).toBe(exit); - expect(line(lost.cli)).toEqual(error); - } +async function refusalFrame(): Promise { + const refused = await started(["reverse", "80"]); + refused.peer.receive(refusedFrame("TUNNEL_BAD_PORT", "Device port 80 is below 1024")); + expect(await refused.exit).toBe(1); + expect(line(refused.cli)).toEqual( + errorBody("TUNNEL_BAD_PORT", "Lease L1: Device port 80 is below 1024"), + ); +} - const silent = await started(["reverse", "5173"]); - silent.cli.clock.advance(30_000); - silent.peer.ping(); - silent.cli.clock.advance(44_999); - expect(silent.cli.err).toEqual([]); - silent.peer.receive(open(1, 5173)); - silent.cli.clock.advance(44_999); - expect(silent.cli.err).toEqual([]); - silent.cli.clock.advance(1); - expect(await silent.exit).toBe(1); - expect(line(silent.cli)).toEqual( - errorBody("TUNNEL_DISCONNECTED", "Lease L1: nothing was heard from the worker for 45 s"), - ); +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 the worker was lost"), + exit: 1, + })), + ]; + for (const { drop, error, exit } of losses) { + const lost = await started(["reverse", "5173"]); + lost.peer.dropped(...drop); + expect(await lost.exit).toBe(exit); + expect(line(lost.cli)).toEqual(error); + } +} - 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(); - } - expect(noReady.err).toEqual([]); - noReady.clock.advance(1); - expect(await noReadyExit).toBe(1); - expect(line(noReady)).toEqual( - errorBody("TUNNEL_DISCONNECTED", "Lease L1: no READY from the worker within 90 s"), - ); +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); + expect(silent.cli.err).toEqual([]); + silent.peer.receive(open(1, 5173)); + silent.cli.clock.advance(44_999); + expect(silent.cli.err).toEqual([]); + silent.cli.clock.advance(1); + expect(await silent.exit).toBe(1); + expect(line(silent.cli)).toEqual( + errorBody("TUNNEL_DISCONNECTED", "Lease L1: nothing was heard from the worker for 45 s"), + ); +} - 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(); - } - expect(idle.cli.err).toEqual([]); - expect(idle.peer.closedWith).toBeUndefined(); - 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 Promise.resolve(); - expect(settled).toBe(false); - idle.cli.clock.advance(1); - expect(await idle.exit).toBe(0); +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(); + } + expect(noReady.err).toEqual([]); + noReady.clock.advance(1); + expect(await noReadyExit).toBe(1); + 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(); + } + expect(idle.cli.err).toEqual([]); + expect(idle.peer.closedWith).toBeUndefined(); + 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 Promise.resolve(); + expect(settled).toBe(false); + idle.cli.clock.advance(1); + expect(await idle.exit).toBe(0); +} - const term = await started(["reverse", "5173"]); - term.cli.signals.emit("SIGTERM"); - expect(term.peer.closedWith?.code).toBe(1000); - expect(await term.exit).toBe(0); +async function sigterm(): Promise { + const term = await started(["reverse", "5173"]); + term.cli.signals.emit("SIGTERM"); + expect(term.peer.closedWith?.code).toBe(1000); + expect(await term.exit).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/ports/index.ts b/src/ports/index.ts index e70b7d763..bbf7eccec 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -182,16 +182,9 @@ export { } from "./updater-launcher.js"; export { FakeWebSocketClientConnector, - FakeWebSocketPeer, NodeWebSocketClientConnector, WebSocketRefusedError, type WebSocketClient, type WebSocketClientConnector, - type WebSocketClientOptions, } from "./websocket-client.js"; -export { - FakeHttpJsonClient, - FetchHttpJsonClient, - type HttpJsonAnswer, - type HttpJsonClient, -} from "./http-json.js"; +export { FakeHttpJsonClient, FetchHttpJsonClient, type HttpJsonClient } from "./http-json.js"; diff --git a/src/ports/websocket-client.ts b/src/ports/websocket-client.ts index bdafa7779..19d91e3d6 100644 --- a/src/ports/websocket-client.ts +++ b/src/ports/websocket-client.ts @@ -113,7 +113,7 @@ export class NodeWebSocketClientConnector implements WebSocketClientConnector { } } -export class FakeWebSocketPeer implements WebSocketClient { +class FakeWebSocketPeer implements WebSocketClient { readonly sent: Uint8Array[] = []; closedWith: { readonly code: number; readonly reason: string } | undefined; // why: a real socket answers `close` with its own close event; a test sets this to play a server that never answers. @@ -144,17 +144,14 @@ export class FakeWebSocketPeer implements WebSocketClient { this.#closes.push(listener); } - // fallow-ignore-next-line unused-class-member -- the server's side of a fake socket, called by tests. receive(bytes: Uint8Array): void { for (const listener of this.#messages) listener(bytes); } - // fallow-ignore-next-line unused-class-member -- the server's side of a fake socket, called by tests. ping(): void { for (const listener of this.#pings) listener(); } - // fallow-ignore-next-line unused-class-member -- the server's side of a fake socket, called by tests. dropped(code: number, reason: string): void { for (const listener of this.#closes) listener(code, reason); } From 7603ff63aec25963bd39204290efdeed1cbe1515 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:05:18 -0300 Subject: [PATCH 091/103] fix: the website's MCP summaries say six tools; rotate_device's alias test asserts the canonical names (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/mcp/server.test.ts | 10 +++++++--- website/src/content/docs/docs/introduction/index.mdx | 2 +- website/src/site/content.ts | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index d32e5f057..96a4eccc3 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -931,9 +931,13 @@ describe("MCP rotate_device", () => { { input: { leaseId: "lease-1", orientation: "landscape_left" }, method: "rotate" }, ]); - const accepted = [{ orientation: "LEFT" }, { orientation: " upside-down " }]; - for (const entry of accepted) { - expect((await call(mcpClient, "rotate_device", entry)).isError).not.toBe(true); + for (const [spelling, canonical] of [ + ["LEFT", "landscape_left"], + [" upside-down ", "portrait_upside_down"], + ]) { + const spelled = await call(mcpClient, "rotate_device", { orientation: spelling }); + expect(spelled.isError).not.toBe(true); + expect(spelled.structuredContent).toEqual({ leaseId: "lease-1", orientation: canonical }); } const unknown = await call(mcpClient, "rotate_device", { orientation: "sideways" }); expect(unknown.isError).toBe(true); diff --git a/website/src/content/docs/docs/introduction/index.mdx b/website/src/content/docs/docs/introduction/index.mdx index ae51c80fc..c6cac2ca7 100644 --- a/website/src/content/docs/docs/introduction/index.mdx +++ b/website/src/content/docs/docs/introduction/index.mdx @@ -32,7 +32,7 @@ Simlock works by agreement, not by force. It does not hide other devices or bloc | Way in | Who it is for | | --- | --- | | CLI (`simlock lease`, `simlock release`) | Any agent that can run shell commands, and you at a terminal. | -| MCP server (`simlock mcp`) | Agents that use the Model Context Protocol. Five tools: list, lease, release, status, run a command. | +| MCP server (`simlock mcp`) | Agents that use the Model Context Protocol. Six tools: list, lease, release, status, run a command, rotate. | | HTTP API | Agents on another machine. They need a token from the operator. | | Programmatic client (`simlock/client`) | Node.js tools on the same machine that want to lease devices without running the CLI. | diff --git a/website/src/site/content.ts b/website/src/site/content.ts index 86bde6c90..05dc4b5c5 100644 --- a/website/src/site/content.ts +++ b/website/src/site/content.ts @@ -195,7 +195,7 @@ export const home = { lang: "json", code: code.mcp, pkg: "simlock mcp", - note: "Five tools for agents that speak MCP: list, lease, release, status and run a command.", + note: "Six tools for agents that speak MCP: list, lease, release, status, run a command and rotate.", href: docs.connect, }, { From 7aa86a7886633d86cf4dabec6fc6ba5b2e495a81 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:10:32 -0300 Subject: [PATCH 092/103] fix(gateway): name the caller's lease id in every worker error, and prove rotate's cases (#1107) The coordinator rewrote the worker's lease id only for two codes and with a substring replace; it now maps every coded error's details.leaseId and replaces the id only as a whole token. The rotate e2e test sends all four orientation names, covers a rejected open and a failed shared input, and no longer waits on the daemon's real host-load probe on Linux; the registry's lease-end close and failure drop get a unit test. Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/device-rotate.e2e.test.ts | 102 ++++++++++++++++++++------- src/daemon/lease-inputs.test.ts | 60 ++++++++++++++++ src/gateway/fleet-coordinator.ts | 27 +++++-- 3 files changed, 157 insertions(+), 32 deletions(-) create mode 100644 src/daemon/lease-inputs.test.ts diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 7a98bcca9..02f122958 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -7,7 +7,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { WebSocket } from "ws"; import { FakeDriver, FakeInputFactory, fakeDeviceDataTables } from "../core/testing.js"; -import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; +import { FakeSystemStats, MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; import type { DispatchSession } from "./dispatch.js"; import { startDaemon } from "./main.js"; import type { DaemonServer } from "./server.js"; @@ -88,6 +88,7 @@ describe("device.rotate", () => { drivers, filesystem: new MemoryFilesystem(), logger: new NoopLogger(), + systemStats: new FakeSystemStats({ cpuCount: 16, totalRamBytes: 64 * 1024 ** 3 }), version: "1.0.0-e2e", }); daemons.push(daemon); @@ -105,24 +106,28 @@ describe("device.rotate", () => { } it( - "answers a holder's rotate of its iOS-simulator lease and sends the helper that orientation", + "answers a holder's rotate of its iOS-simulator lease to each of the four orientation names and sends the helper that orientation", { timeout: 60_000 }, async () => { const input = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); const { daemon, leaseId } = await worker({ input, inputModule: false }); - const answer = await daemon.dispatch( - "device.rotate", - { leaseId, orientation: "landscape_left" }, - holder, - ); - - expect(answer).toEqual({ leaseId, orientation: "landscape_left" }); - expect(input.opened).toHaveLength(1); - expect(input.opened[0]?.sent).toEqual([ - { kind: "orientation", orientation: "landscape_left" }, - ]); - expect(input.opened[0]?.closes).toBe(1); + const names = [ + "landscape_left", + "portrait_upside_down", + "landscape_right", + "portrait", + ] as const; + for (const [index, orientation] of names.entries()) { + const answer = await daemon.dispatch("device.rotate", { leaseId, orientation }, holder); + + expect(answer, orientation).toEqual({ leaseId, orientation }); + expect(input.opened, orientation).toHaveLength(index + 1); + expect(input.opened[index]?.sent, orientation).toEqual([ + { kind: "orientation", orientation }, + ]); + expect(input.opened[index]?.closes, orientation).toBe(1); + } }, ); @@ -385,13 +390,23 @@ describe("device.rotate", () => { } it( - "gives an input socket opened after a rotate's helper closed a fresh helper, keeps a socket's helper through a rotate, and answers UNKNOWN_LEASE when the lease is reclaimed while the rotate's helper opens", + "gives a rotate after a failed open, an input socket opened after a rotate's helper closed, and a rotate after the shared helper failed a fresh helper, keeps a socket's helper through a rotate, and answers UNKNOWN_LEASE when the lease is reclaimed while the rotate's helper opens", { timeout: 60_000 }, async () => { const input = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); const { daemon, leaseId, openSocket, session } = await holderWithSocketAccess(input); const orientation = "landscape_right"; + input.failWith = new Error("helper exploded"); + await expect( + daemon.dispatch("device.rotate", { leaseId, orientation }, session), + ).rejects.toMatchObject({ + code: "INPUT_UNAVAILABLE", + details: { reason: "helper exploded" }, + }); + input.failWith = undefined; + expect(input.opened).toHaveLength(0); + await daemon.dispatch("device.rotate", { leaseId, orientation }, session); expect(input.opened).toHaveLength(1); expect(input.opened[0]?.closes).toBe(1); @@ -408,12 +423,13 @@ describe("device.rotate", () => { expect(input.opened[1]?.closes).toBe(0); input.opened[1]?.fail(new Error("pipe closed")); - await vi.waitFor(() => expect(socket.code).toBe(1013), { timeout: 10_000 }); await expect( daemon.dispatch("device.rotate", { leaseId, orientation }, session), ).resolves.toEqual({ leaseId, orientation }); expect(input.opened).toHaveLength(3); + expect(input.opened[1]?.sent).toEqual([{ kind: "orientation", orientation: "portrait" }]); expect(input.opened[2]?.sent).toEqual([{ kind: "orientation", orientation }]); + await vi.waitFor(() => expect(socket.code).toBe(1013), { timeout: 10_000 }); let open: () => void = () => undefined; input.gate = new Promise((resolve) => { @@ -421,7 +437,7 @@ describe("device.rotate", () => { }); const rotating = daemon.dispatch("device.rotate", { leaseId, orientation }, session); const outcome = expect(rotating).rejects.toMatchObject({ name: "UnknownLeaseError" }); - await vi.waitFor(() => expect(input.opens).toBe(4), { timeout: 10_000 }); + await vi.waitFor(() => expect(input.opens).toBe(5), { timeout: 10_000 }); await daemon.dispatch("lease.release", { leaseId }, session); open(); await outcome; @@ -459,6 +475,7 @@ describe("device.rotate", () => { httpPort: number, input: FakeInputFactory, ready: () => Promise, + reclaimOnWorker?: (leaseId: string) => Promise, ) { const [phone, emulator] = await agentTokens(daemon, ["phone", "emulator"]); const phoneId = await leaseFor(daemon, phone!.principal, { @@ -531,6 +548,21 @@ describe("device.rotate", () => { message: `Lease ${phoneId}'s simulator cannot take input: helper is gone`, }); input.failWith = undefined; + + if (reclaimOnWorker !== undefined) { + let open: () => void = () => undefined; + input.gate = new Promise((resolve) => { + open = resolve; + }); + const opensBefore = input.opens; + const rotating = rotate(phoneId, phone!.secret, { orientation }); + await vi.waitFor(() => expect(input.opens).toBe(opensBefore + 1), { timeout: 10_000 }); + await reclaimOnWorker(phoneId); + open(); + const gone = await rotating; + expect([gone.status, gone.body.error?.code]).toEqual([404, "UNKNOWN_LEASE"]); + expect(gone.body.error?.message).toBe(`Unknown lease: ${phoneId}`); + } } const workerPort = await freeLoopbackPort(); @@ -560,7 +592,7 @@ describe("device.rotate", () => { await gateway.dispatch("token.create", { label: "w", role: "worker" }, admin) ).secret; const fleetInput = new FakeInputFactory(screen); - await startWorker({ + const { daemon: fleetWorker } = await startWorker({ gateway: { label: "w", token: workerToken, url: `ws://127.0.0.1:${String(gatewayPort)}` }, input: fleetInput, inputModule: false, @@ -572,15 +604,31 @@ describe("device.rotate", () => { }, { timeout: 10_000 }, ); - await exercise(gateway, gatewayPort, fleetInput, async () => { - await vi.waitFor( - async () => { - const { leases } = await gateway.dispatch("lease.list", {}, admin); - expect(leases).toHaveLength(2); - }, - { timeout: 10_000 }, - ); - }); + await exercise( + gateway, + gatewayPort, + fleetInput, + async () => { + await vi.waitFor( + async () => { + const { leases } = await gateway.dispatch("lease.list", {}, admin); + expect(leases).toHaveLength(2); + }, + { timeout: 10_000 }, + ); + }, + async (leaseId) => { + const { leases } = await gateway.dispatch("lease.list", {}, admin); + const owner = leases.find((lease) => lease.id === leaseId)?.requesterId; + const held = await fleetWorker.dispatch("lease.list", {}, admin); + const workerLease = held.leases.find((lease) => lease.requesterId.endsWith(owner ?? "")); + await fleetWorker.dispatch( + "lease.release", + { leaseId: workerLease?.id ?? "", requesterId: workerLease?.requesterId ?? "" }, + admin, + ); + }, + ); }, ); }); diff --git a/src/daemon/lease-inputs.test.ts b/src/daemon/lease-inputs.test.ts new file mode 100644 index 000000000..304eb74e2 --- /dev/null +++ b/src/daemon/lease-inputs.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from "vitest"; + +import { FakeInputFactory } from "../core/testing.js"; +import { createLeaseInputs } from "./lease-inputs.js"; + +const device = { id: "device-1", platform: "ios" } as never; +const ended = { + deviceId: "device-1", + leaseId: "lease-1", + ownerId: "owner-1", + platform: "ios", + reason: "explicit", +} as const; + +// why: the surface cannot force a user that holds the input past its lease's end: the input module and `device.rotate` both release at once, so only the registry's own lease-end participant is left to close it. +describe("createLeaseInputs", () => { + it("closes the input of a lease whose user never releases it when the lease ends, and gives the next user of that lease a fresh one", async () => { + const factory = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); + const inputs = createLeaseInputs({ openInput: () => factory.open() }); + await inputs.leaseInput("lease-1", "ios", device); + await inputs.leaseInput("lease-1", "ios", device); + expect(factory.opened).toHaveLength(1); + expect(factory.opened[0]?.closes).toBe(0); + + await inputs.leaseEnd.leaseEnded(ended, new AbortController().signal); + await Promise.resolve(); + + expect(factory.opened[0]?.closes).toBe(1); + await inputs.leaseInput("lease-1", "ios", device); + expect(factory.opened).toHaveLength(2); + }); + + it("drops an input that failed while another user still holds it, so the next user opens a fresh one", async () => { + const factory = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); + const inputs = createLeaseInputs({ openInput: () => factory.open() }); + await inputs.leaseInput("lease-1", "ios", device); + await inputs.leaseInput("lease-1", "ios", device); + + factory.opened[0]?.fail(new Error("pipe closed")); + await Promise.resolve(); + + expect(factory.opened[0]?.closes).toBe(1); + const fresh = await inputs.leaseInput("lease-1", "ios", device); + expect(factory.opened).toHaveLength(2); + expect(fresh.input).toBe(factory.opened[1]); + }); + + it("opens a fresh input for the next user after an open rejected", async () => { + const factory = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); + const inputs = createLeaseInputs({ openInput: () => factory.open() }); + factory.failWith = new Error("helper exploded"); + await expect(inputs.leaseInput("lease-1", "ios", device)).rejects.toThrow("helper exploded"); + factory.failWith = undefined; + + await inputs.leaseInput("lease-1", "ios", device); + + expect(factory.opens).toBe(2); + expect(factory.opened).toHaveLength(1); + }); +}); diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index eacae88a2..212a155f0 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -589,7 +589,7 @@ export class FleetLeaseCoordinator { } /** - * why: `device.rotate` forwarded to the worker that owns the lease, with the lease's own namespaced requester, bounded by `gateway.execTimeoutMs` like `exec`. A worker names the lease by its own id in a refusal; the caller holds the gateway's id, so the refusal names that instead. + * why: `device.rotate` forwarded to the worker that owns the lease, with the lease's own namespaced requester, bounded by `gateway.execTimeoutMs` like `exec`. A worker names the lease by its own id in any coded error; the caller holds the gateway's id, so the error names that instead. */ // fallow-ignore-next-line unused-class-member -- reached only through `GatewayDispatcher`'s `Pick`-typed `coordinator` option. async rotate(input: FleetRotateInput, _session: DispatchSession): Promise { @@ -612,13 +612,15 @@ export class FleetLeaseCoordinator { #namedForCaller(error: unknown, entry: FleetLeaseEntry): unknown { if (!(error instanceof DispatchError)) return error; - if (error.code !== "ROTATION_UNSUPPORTED" && error.code !== "INPUT_UNAVAILABLE") return error; const details = - typeof error.details === "object" && error.details !== null ? error.details : {}; + typeof error.details === "object" && error.details !== null ? error.details : undefined; + const names = (details as { leaseId?: unknown } | undefined)?.leaseId === entry.workerLeaseId; + const message = replaceWholeId(error.message, entry.workerLeaseId, entry.gatewayLeaseId); + if (!names && message === error.message) return error; return new DispatchError( error.code, - error.message.replaceAll(entry.workerLeaseId, entry.gatewayLeaseId), - { ...details, leaseId: entry.gatewayLeaseId }, + message, + names ? { ...details, leaseId: entry.gatewayLeaseId } : error.details, ); } @@ -1597,3 +1599,18 @@ function routable(waiter: FleetWaiter): RoutableRequest { ...(waiter.options.requires === undefined ? {} : { requires: waiter.options.requires }), }; } + +// why: a lease id is replaced only as a whole token, so a short id inside a longer word or id is left alone. +function replaceWholeId(text: string, id: string, replacement: string): string { + const isIdCharacter = (character: string | undefined): boolean => + character !== undefined && /[\w-]/.test(character); + let result = ""; + let from = 0; + for (let at = text.indexOf(id); at !== -1; at = text.indexOf(id, from)) { + const end = at + id.length; + const whole = !isIdCharacter(text[at - 1]) && !isIdCharacter(text[end]); + result += text.slice(from, at) + (whole ? replacement : id); + from = end; + } + return result + text.slice(from); +} From 638218804376c0ad364482b40ac4ef6f2a5579c1 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:10:38 -0300 Subject: [PATCH 093/103] docs: list POST /v1/leases/{id}/rotate and device.rotate in the manuals, and reword the orientation claims (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/AGENTS.md | 4 ++-- src/contract/orientation.ts | 2 +- src/daemon/AGENTS.md | 40 ++++++++++++++++++------------------- src/http/AGENTS.md | 1 + 4 files changed, 23 insertions(+), 24 deletions(-) diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index de97bd144..748f8abf8 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -22,7 +22,7 @@ Imported by: daemon, gateway, simlock-client, every frontend, core, leasing, his | `os-range.ts` | OS constraint grammar: parse, `satisfies`, `compareVersions` | | `version-order.ts` | `isNewerVersion(candidate, running)`: the one "newer" rule (semver order) every update surface shares; the console imports it by this path, not the index (the index carries zod) | | `duration.ts` | `parseDurationMs`, for the CLI and HTTP | -| `orientation.ts` | `INPUT_ORIENTATIONS`, `parseOrientation` (the aliases the CLI, MCP and agent-device front take), `isRotatableModel`, `modelFamily`; no wire shape | +| `orientation.ts` | `INPUT_ORIENTATIONS`, `parseOrientation` (the aliases a spelling maps to an orientation or the unknown message), `isRotatableModel`, `modelFamily`; no wire shape | | `relay.ts` | Bounded relay ids, channel ids, headers | | `console-url.ts` | The console address `status.get` reports | @@ -34,7 +34,7 @@ park on readiness (all but `status.get`) → handler → parse output. every operation but `daemon.stop`, which `DaemonServer` answers. - `agent`: `catalog.get`, `status.get`, `component.list`, `lease.request`, `lease.cancel`, - `lease.renew`, `lease.release`, `lease.list`, `lease.get`, `driver.passthrough`, `device.exec`, + `lease.renew`, `lease.release`, `lease.list`, `lease.get`, `driver.passthrough`, `device.exec`, `device.rotate`, `doctor.run` without `fix` or `purgeOrphans`. - `admin`: every other operation (`list.get`, `config.get`, `inbox.get`, `daemon.stop`, `events.*`, `token.*`, `worker.*`, `component.install`, `device.add`, `relay.request`, ...). diff --git a/src/contract/orientation.ts b/src/contract/orientation.ts index 6a6199180..050470e1c 100644 --- a/src/contract/orientation.ts +++ b/src/contract/orientation.ts @@ -32,7 +32,7 @@ export type OrientationParse = | { readonly ok: true; readonly orientation: Orientation } | { readonly ok: false; readonly message: string }; -// why: the CLI, MCP and the agent-device front take these spellings; HTTP and the client take only the four names. +// why: the spellings `parseOrientation` accepts for a caller that takes more than the four names; HTTP and the client take only the four names. const ALIASES: Readonly> = { "landscape-left": "landscape_left", "landscape-right": "landscape_right", diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 1aa936000..2862c26f0 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -10,25 +10,24 @@ Flows: [startup](../../docs/internal/flows/startup.md), [device.exec](../../docs ## Files -| File | Role | -| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `main.ts` | Composition root; worker or gateway; driver discovery; log sinks | -| `server.ts` | `DaemonServer`: framing, `hello`, sessions, pushes, readiness, stop | -| `dispatch.ts` | `runDispatch` pipeline, `DispatchSession`, `DispatchError` | -| `dispatcher.ts` | `Dispatcher`: the worker's handlers | -| `connection-host.ts` | `DaemonEndpointHost`: socket claim, stale-socket recovery | -| `owner-routed-facts.ts` | `OwnerRoutedFactBus`: lease facts with their owner | -| `gateway-uplink.ts` | `GatewayUplink`: a worker's dial to its gateway | -| `openapi.ts` | `openApiDocument`, `writeOpenApiDocument`: the HTTP API document from the module registry; run by `pnpm openapi` | -| `update-coordinator.ts` | `createUpdateCoordinator`: `daemon.update`'s state (`waiting`, `installing`), the updater launch, `status.get`'s update fields | -| `version-check.ts` | `startVersionCheck`: npm's `latest` Simlock version, read at start and every 24 h (`update.check`); `status.get`'s `latestVersion`, both roles | -| `relay.ts` | `RelayTargets`, `RelayConnection`: relays over the uplink | -| `error-code.ts` | `classifyError`: thrown error → contract code | -| `enrollment-wake.ts` | `wakingQueueAfter`: wakes the queue after `device.add`/`device.remove` | -| `lease-inputs.ts` | `createLeaseInputs`: the per-lease device input shared by the input module's sockets and `device.rotate`; closed by its last release, its failure or the lease's end | -| `rotation-refusal.ts` | `rotationRefusal`: `device.rotate`'s `ROTATION_UNSUPPORTED`, with how it names the device | -| `exec-env.ts` | `execBaseEnvironment`: the allowlisted keys of `process.env` a `device.exec` child starts from | -| `test-relay-support.ts` | Test helpers for relay e2e tests | +| File | Role | +| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `main.ts` | Composition root; worker or gateway; driver discovery; log sinks | +| `server.ts` | `DaemonServer`: framing, `hello`, sessions, pushes, readiness, stop | +| `dispatch.ts` | `runDispatch` pipeline, `DispatchSession`, `DispatchError` | +| `dispatcher.ts` | `Dispatcher`: the worker's handlers | +| `connection-host.ts` | `DaemonEndpointHost`: socket claim, stale-socket recovery | +| `owner-routed-facts.ts` | `OwnerRoutedFactBus`: lease facts with their owner | +| `gateway-uplink.ts` | `GatewayUplink`: a worker's dial to its gateway | +| `openapi.ts` | `openApiDocument`, `writeOpenApiDocument`: the HTTP API document from the module registry; run by `pnpm openapi` | +| `update-coordinator.ts` | `createUpdateCoordinator`: `daemon.update`'s state (`waiting`, `installing`), the updater launch, `status.get`'s update fields | +| `version-check.ts` | `startVersionCheck`: npm's `latest` Simlock version, read at start and every 24 h (`update.check`); `status.get`'s `latestVersion`, both roles | +| `relay.ts` | `RelayTargets`, `RelayConnection`: relays over the uplink | +| `error-code.ts` | `classifyError`: thrown error → contract code | +| `enrollment-wake.ts` | `wakingQueueAfter`: wakes the queue after `device.add`/`device.remove` | +| `lease-inputs.ts` | `createLeaseInputs`: the per-lease device input shared by the input module's sockets and `device.rotate`, closed by its last release, failure or the lease's end; `rotation-refusal.ts`: `rotationRefusal`, `device.rotate`'s `ROTATION_UNSUPPORTED` | +| `exec-env.ts` | `execBaseEnvironment`: the allowlisted keys of `process.env` a `device.exec` child starts from | +| `test-relay-support.ts` | Test helpers for relay e2e tests | ## Composition (`main.ts`) @@ -147,6 +146,5 @@ Security model: cooperative identity, not a hostile-process boundary. - The claim comes before any write to `admin.token` and before converge. - On a worker, no request but `hello`, `status.get` and `daemon.stop` runs before converge ends. -- `daemon.stop` releases nothing. Leases persist with their deadlines. -- A closed connection ends no lease and kills no command. +- `daemon.stop` releases nothing; leases persist with their deadlines. A closed connection ends no lease and kills no command. - `daemon.started` is emitted only after converge, and never after `daemon.stopping`. diff --git a/src/http/AGENTS.md b/src/http/AGENTS.md index 562159c42..c167cf8e1 100644 --- a/src/http/AGENTS.md +++ b/src/http/AGENTS.md @@ -96,6 +96,7 @@ A route with a `socket` handler also takes a WebSocket upgrade: `app.leaseSocket - `POST /v1/update` (optional body `{version, force}`, strict) → `daemon.update`: 202 when the call began the update (`started`), 200 when it followed one or found nothing to do (`upToDate`). The route declares both (`alsoStatus`). The role check is the dispatcher's; on a gateway it updates the gateway itself, with no lease wait. - `POST /v1/workers/{id}/update` (optional body `{version, force}`, strict) → `worker.update`: the same 202 and 200; `UNKNOWN_WORKER` 404, `WORKER_NOT_CONNECTED` 409, and a worker daemon answers 501. - `GET /v1/leases/{id}/events` — the lease's notices; ends on `lease_lost`. +- `POST /v1/leases/{id}/rotate` (body `{orientation}`, one of the four names, strict) → `device.rotate`: 200 with `{leaseId, orientation}`; `ROTATION_UNSUPPORTED` 422, `INPUT_UNAVAILABLE` 503, 403 for another requester's lease, 404 for an unknown one (`src/http/lease-declarations.ts`, `src/http/app.ts`). - `POST /v1/leases/{id}/exec` → `device.exec`. The stream opens on `onStarted`; a failure before that is a plain error response. Events: `output`, then `exit` or `error`. - `POST /v1/components/install` → `component.install`, or `worker.install-component` with From 33b7b5313766f3deec391a15685f04aed5699fc4 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:16:14 -0300 Subject: [PATCH 094/103] test: pin rotate's agent role, client close and the rotate_device input bound (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/index.test.ts | 27 +++++++++++++++++++++++++-- src/mcp/server.test.ts | 13 +++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 7ec5bdf22..a6d2ebc74 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -10684,14 +10684,24 @@ describe("simlock rotate", () => { const two = [heldLease, { ...heldLease, deviceId: "dev_2", id: "lse_other" }]; - async function rotateWith(argv: readonly string[], leases: readonly (typeof heldLease)[]) { + async function rotateWith( + argv: readonly string[], + leases: readonly (typeof heldLease)[], + role: "admin" | "agent" = "admin", + ) { const output = outputCapture(); const rotations: unknown[] = []; + let closes = 0; const exitCode = await runCli( argv, output.environmentWith({ connectAdmin: async () => fakeClient({ + role, + close: () => { + closes += 1; + return Promise.resolve(); + }, listLeases: () => Promise.resolve({ leases: [...leases] }), rotate: (leaseId, orientation, options) => { rotations.push({ leaseId, orientation, options }); @@ -10700,7 +10710,7 @@ describe("simlock rotate", () => { }), }), ); - return { exitCode, output, rotations }; + return { closes: () => closes, exitCode, output, rotations }; } it("a user runs simlock rotate [--lease ] and sees Rotated lease to , or a usage error", async () => { @@ -10714,6 +10724,13 @@ describe("simlock rotate", () => { }, ]); expect(only.output.stdout).toBe("Rotated lease lse_mine_answered to landscape_left\n"); + expect(only.closes()).toBe(1); + + const asAgent = await rotateWith(["rotate", "landscape-left"], [heldLease], "agent"); + expect(asAgent.exitCode).toBe(0); + expect(asAgent.rotations).toEqual([ + { leaseId: "lse_mine", orientation: "landscape_left", options: undefined }, + ]); for (const argv of [ ["rotate", "--lease", "lse_other", "left"], @@ -10759,12 +10776,17 @@ describe("simlock rotate", () => { } const unsupported = outputCapture(); + let unsupportedCloses = 0; await expect( runCli( ["rotate", "left", "--lease", "lse_android"], unsupported.environmentWith({ connectAdmin: async () => fakeClient({ + close: () => { + unsupportedCloses += 1; + return Promise.resolve(); + }, rotate: () => Promise.reject( new SimlockError( @@ -10791,6 +10813,7 @@ describe("simlock rotate", () => { }, }); expect(unsupported.stdout).toBe(""); + expect(unsupportedCloses).toBe(1); const help = await rotateWith(["rotate", "--help"], [heldLease]); expect(help.exitCode).toBe(0); diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index 96a4eccc3..d27745835 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -237,6 +237,7 @@ describe("MCP server (smoke)", () => { client.calls.length = 0; const refused = await call(mcpClient, tool, wrong); expect(refused.isError).toBe(true); + expect(text(refused)).toBe("DBG"); expect(text(refused)).toContain("Input validation error"); expect(client.calls).toEqual([]); } finally { @@ -939,6 +940,18 @@ describe("MCP rotate_device", () => { expect(spelled.isError).not.toBe(true); expect(spelled.structuredContent).toEqual({ leaseId: "lease-1", orientation: canonical }); } + for (const [orientation, bound] of [ + ["", "expected string to have >=1 characters"], + ["x".repeat(65), "expected string to have <=64 characters"], + ] as const) { + const refused = await call(mcpClient, "rotate_device", { orientation }); + expect(refused.isError).toBe(true); + expect(text(refused)).toContain(`Invalid arguments for tool rotate_device: Too `); + expect(text(refused)).toContain(bound); + } + const longest = await call(mcpClient, "rotate_device", { orientation: "x".repeat(64) }); + expect(JSON.parse(text(longest)).code).toBe("BAD_REQUEST"); + expect(client.calls.filter((entry) => entry.method === "rotate")).toHaveLength(3); const unknown = await call(mcpClient, "rotate_device", { orientation: "sideways" }); expect(unknown.isError).toBe(true); expect(JSON.parse(text(unknown))).toEqual({ From 22169a864944c31c56d2556fed466c64eeadf177 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:17:14 -0300 Subject: [PATCH 095/103] fix(android): hold tunnel ports until reclaim, keep a leased device's rules at start, name the call in refusals (#1112) A removal that fails keeps the loopback listener reserved and the device's reclaim frees it; the start sweep only reads a leased device's rules and reserves their ports; refusal texts follow the spec's shared values; a cancelled TcpStream no longer closes its readable twice. Co-Authored-By: Claude Sonnet 5.5 --- docs/internal/flows/startup.md | 2 +- src/core/device-tcp.ts | 17 +- src/core/driver-catalog.test.ts | 30 ++ src/core/driver-catalog.ts | 7 +- src/core/fake-device-tcp.ts | 13 +- src/core/index.ts | 8 +- src/daemon/main.ts | 5 +- src/daemon/tunnel-lease.e2e.test.ts | 54 +++ src/drivers/android/AGENTS.md | 2 +- src/drivers/android/device-tcp.ts | 104 ++++- src/drivers/android/index.test.ts | 145 ++++-- src/drivers/android/index.ts | 15 +- src/drivers/android/physical-handler.test.ts | 31 +- src/ports/tcp-listener.test.ts | 1 + src/ports/tcp-listener.ts | 6 + src/ports/tcp-stream.test.ts | 52 ++- src/ports/tcp-stream.ts | 29 +- src/tunnel/AGENTS.md | 6 +- src/tunnel/sessions.ts | 128 +++++- src/tunnel/worker.test.ts | 432 ++++++++++++------ src/tunnel/worker.ts | 6 +- .../docs/docs/reference/configuration.mdx | 2 +- .../content/docs/docs/reference/errors.mdx | 2 +- 23 files changed, 836 insertions(+), 261 deletions(-) diff --git a/docs/internal/flows/startup.md b/docs/internal/flows/startup.md index d8ccfc67d..52e4f6d8c 100644 --- a/docs/internal/flows/startup.md +++ b/docs/internal/flows/startup.md @@ -54,7 +54,7 @@ reaches its settle step, the steps after the read are skipped. Before step 16 it removes the `....tmp` files and `....staging` directories of dead writers beside each device root and in the data directory (`sweepWriteLeftovers`). -Before step 16, a driver with `deviceTcp` sweeps the reverse rules into 47000-47999 a stopped daemon's tunnels left, on its owned devices, leased or idle (Android: `AndroidDriver` manual); a failure is a `warn`. +Before step 16, a driver with `deviceTcp` sweeps the reverse rules into 47000-47999 a stopped daemon's tunnels left, on its idle owned devices; on a leased one it only reads the rules and reserves their ports, and its reclaim removes them (Android: `AndroidDriver` manual); a failure is a `warn`. 16. Settle open requests — `leasing.settleRequests`: every `open` request fails `INTERNAL`; `lease.rejected` with reason `daemon-restarted`. diff --git a/src/core/device-tcp.ts b/src/core/device-tcp.ts index f6bd9cd9c..790f00651 100644 --- a/src/core/device-tcp.ts +++ b/src/core/device-tcp.ts @@ -12,6 +12,13 @@ export class DeviceTcpError extends Error { } } +// why: one wording for a lease whose device cannot take a tunnel, so the catalog's refusal and the tunnel module's read the same to the holder. +export function unsupportedTunnelMessage(platform: string, physical: boolean): string { + let noun = `a ${platform} device`; + if (platform === "ios") noun = physical ? "an iPhone" : "an iOS simulator"; + return `the lease is on ${noun}; tunnels need an Android emulator or phone`; +} + // why: one device port reversed to a loopback listener on the worker; every connection the device // opens to that port arrives on `onConnection`, until `close` removes the rule and the listener. export interface DeviceReverse { @@ -20,12 +27,18 @@ export interface DeviceReverse { close(): Promise; } +// why: the sweep treats a leased device differently from an idle one, and only the registry knows which is which. +export interface SweptDevice { + readonly device: VirtualDriverDevice | PhysicalDriverDevice; + readonly leased: boolean; +} + // why: an optional driver member beside `input`; a platform whose device cannot reach a worker port // leaves it out, and the tunnel module learns that from its absence rather than from a platform name. export interface DeviceTcp { supports(device: VirtualDriverDevice | PhysicalDriverDevice): boolean; - // why: called once at daemon start, before any lease is served: removes the rules a stopped daemon's tunnels left on devices proved Simlock's own, leased or idle. - sweep(devices: readonly (VirtualDriverDevice | PhysicalDriverDevice)[]): Promise; + // why: called once at daemon start, before any lease is served: removes the rules a stopped daemon's tunnels left on idle devices proved Simlock's own; a leased device's rules stay until its reclaim, and the ports they point to are kept from new tunnels. + sweep(devices: readonly SweptDevice[]): Promise; reverse( device: VirtualDriverDevice | PhysicalDriverDevice, devicePort: number, diff --git a/src/core/driver-catalog.test.ts b/src/core/driver-catalog.test.ts index a5ec5f1c9..8649b1da2 100644 --- a/src/core/driver-catalog.test.ts +++ b/src/core/driver-catalog.test.ts @@ -6,6 +6,7 @@ import { type PassthroughCommand, type PassthroughContext, } from "./driver.js"; +import { FakeDeviceTcp } from "./fake-device-tcp.js"; import { FakeDriver } from "./fake-driver.js"; import { DriverCatalog, NoDriverError, UnknownPassthroughToolError } from "./driver-catalog.js"; @@ -43,7 +44,36 @@ function route( ); } +// why: the catalog is pure routing by platform with many cases (passthrough tools, class defaults, device ports), driven through the fake drivers it routes to. describe("DriverCatalog", () => { + it("reverses a device port through its driver's deviceTcp, and answers TUNNEL_UNSUPPORTED, naming the device, for a platform with none", async () => { + const clock = new FakeClock(); + const deviceTcp = new FakeDeviceTcp(); + const catalog = new DriverCatalog([ + new FakeDriver({ availableOsVersions: ["14"], clock, deviceTcp, platform: "android" }), + new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }), + ]); + const simulator = { address: "", deviceId: "sim", driverData: {}, physical: false } as const; + const phone = { ...simulator, enrolledApps: [], physical: true } as const; + const signal = new AbortController().signal; + + expect(catalog.supportsDeviceTcp("android", simulator)).toBe(true); + expect(catalog.supportsDeviceTcp("ios", simulator)).toBe(false); + await catalog.reverseDevicePort("android", simulator, 5173, signal); + expect(deviceTcp.reversed).toEqual([5173]); + for (const [device, noun] of [ + [simulator, "an iOS simulator"], + [phone, "an iPhone"], + ] as const) { + await expect(catalog.reverseDevicePort("ios", device, 5173, signal)).rejects.toEqual( + expect.objectContaining({ + code: "TUNNEL_UNSUPPORTED", + message: `the lease is on ${noun}; tunnels need an Android emulator or phone`, + }), + ); + } + }); + it("resolves a request through its registered driver", async () => { const clock = new FakeClock(); const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); diff --git a/src/core/driver-catalog.ts b/src/core/driver-catalog.ts index 5c84e49c9..388655493 100644 --- a/src/core/driver-catalog.ts +++ b/src/core/driver-catalog.ts @@ -10,7 +10,7 @@ import type { PhysicalDriverDevice, VirtualDriverDevice, } from "./driver.js"; -import { DeviceTcpError, type DeviceReverse } from "./device-tcp.js"; +import { DeviceTcpError, unsupportedTunnelMessage, type DeviceReverse } from "./device-tcp.js"; import type { DeviceInput, UnavailableDeviceInput } from "./input.js"; import { type ScreenFeed, ScreenNotSupportedError, type ScreenSettings } from "./screen.js"; import { stableError } from "./stable-error.js"; @@ -118,7 +118,10 @@ export class DriverCatalog { ): Promise { const deviceTcp = this.#drivers.get(platform)?.deviceTcp; if (deviceTcp === undefined) { - throw new DeviceTcpError("TUNNEL_UNSUPPORTED", `${platform} devices take no tunnel`); + throw new DeviceTcpError( + "TUNNEL_UNSUPPORTED", + unsupportedTunnelMessage(platform, device.physical), + ); } return await deviceTcp.reverse(device, devicePort, signal); } diff --git a/src/core/fake-device-tcp.ts b/src/core/fake-device-tcp.ts index 56bab8ef6..cbe784aaf 100644 --- a/src/core/fake-device-tcp.ts +++ b/src/core/fake-device-tcp.ts @@ -1,5 +1,5 @@ import { FakeTcpPeer, type TcpStream } from "../ports/index.js"; -import type { DeviceReverse, DeviceTcp } from "./device-tcp.js"; +import type { DeviceReverse, DeviceTcp, SweptDevice } from "./device-tcp.js"; class FakeReverse implements DeviceReverse { closed = false; @@ -9,6 +9,7 @@ class FakeReverse implements DeviceReverse { readonly hostPort: number, private readonly onClose: () => void, private readonly failure: () => Error | undefined, + private readonly gate: () => Promise | undefined, ) {} onConnection(listener: (stream: TcpStream) => void): void { @@ -16,6 +17,7 @@ class FakeReverse implements DeviceReverse { } async close(): Promise { + await this.gate(); const failure = this.failure(); if (failure !== undefined) throw failure; this.closed = true; @@ -38,6 +40,10 @@ export class FakeDeviceTcp implements DeviceTcp { readonly reverseLog: number[] = []; // why: a test sets this to hold every `reverse` until it settles, as an adb call that is slow to answer does. gate: Promise | undefined; + // why: a test sets this to hold every rule removal until it settles, as an adb call that is slow to answer does. + closeGate: Promise | undefined; + // why: every device list a `sweep` was given, in order, so a test can tell what the daemon asked a platform's driver to sweep. + readonly sweeps: (readonly SweptDevice[])[] = []; readonly #reverses = new Map(); #nextHostPort = 47_000; @@ -49,7 +55,9 @@ export class FakeDeviceTcp implements DeviceTcp { return true; } - async sweep(): Promise {} + async sweep(devices: readonly SweptDevice[]): Promise { + this.sweeps.push(devices); + } async reverse( _device: unknown, @@ -68,6 +76,7 @@ export class FakeDeviceTcp implements DeviceTcp { this.#reverses.delete(devicePort); }, () => this.closeFailure, + () => this.closeGate, ); this.#reverses.set(devicePort, reverse); return reverse; diff --git a/src/core/index.ts b/src/core/index.ts index 23768ee57..0af821ec0 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -102,7 +102,13 @@ export { type ScreenAvailability, UnknownPassthroughToolError, } from "./driver-catalog.js"; -export { DeviceTcpError, type DeviceReverse, type DeviceTcp } from "./device-tcp.js"; +export { + DeviceTcpError, + unsupportedTunnelMessage, + type DeviceReverse, + type DeviceTcp, + type SweptDevice, +} from "./device-tcp.js"; export { closeReason, type DeviceInput, diff --git a/src/daemon/main.ts b/src/daemon/main.ts index aa09e1fea..531982762 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -629,7 +629,10 @@ async function composeDaemon( .filter( (device) => device.spec.platform === driver.platform && device.state !== "deleted", ) - .map((device) => toDriverDevice(device)), + .map((device) => ({ + device: toDriverDevice(device), + leased: device.state === "leased", + })), ); } catch (error) { logger.warn("A driver's start sweep of tunnel rules failed", { diff --git a/src/daemon/tunnel-lease.e2e.test.ts b/src/daemon/tunnel-lease.e2e.test.ts index b9dc43596..00e4e461c 100644 --- a/src/daemon/tunnel-lease.e2e.test.ts +++ b/src/daemon/tunnel-lease.e2e.test.ts @@ -178,4 +178,58 @@ describe("a lease's tunnel socket", () => { }); }, ); + + it( + "sweeps each platform's driver at start with its devices, a leased one marked leased, before any request is served", + { timeout: 120_000 }, + async () => { + const path = await mkdtemp(join(tmpdir(), "simlock-e2e-sweep-")); + directories.push(path); + const start = async (deviceTcp: FakeDeviceTcp): Promise => + await startDaemon({ + configOverrides: { http: { enabled: false } }, + 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", + }); + + const empty = new FakeDeviceTcp(); + const first = await start(empty); + expect(empty.sweeps).toEqual([[]]); + const holder = await first.dispatch( + "token.create", + { label: "holder", role: "agent" }, + admin, + ); + const session = { ...agent, principal: holder.token.id }; + await first.dispatch("lease.request", { model: "Pixel-A", platform: "android" }, session); + await first.stop("test"); + + const whileLeased = new FakeDeviceTcp(); + const second = await start(whileLeased); + expect(whileLeased.sweeps).toHaveLength(1); + expect(whileLeased.sweeps[0]).toEqual([ + { device: expect.objectContaining({ physical: false }), leased: true }, + ]); + await second.stop("test"); + + const idle = new FakeDeviceTcp(); + daemons.push(await start(idle)); + expect(idle.sweeps).toHaveLength(1); + expect(idle.sweeps[0]).toEqual([ + { device: expect.objectContaining({ physical: false }), leased: false }, + ]); + }, + ); }); diff --git a/src/drivers/android/AGENTS.md b/src/drivers/android/AGENTS.md index 63c3d5c2b..0ab3b44a4 100644 --- a/src/drivers/android/AGENTS.md +++ b/src/drivers/android/AGENTS.md @@ -114,7 +114,7 @@ Lease environment: virtual `ANDROID_ADB_SERVER_PORT=`; physical `ANDROID_A No slim: `resolveSpec` ignores `mode` and returns a full spec. `fresh` is core's. Screen — `screenCapture` and `input`, only when `create` got `scrcpyServerPath` and `tcpStreamConnector`: [screen](screen/AGENTS.md), [input](input/AGENTS.md). -Tunnels — `deviceTcp` (`device-tcp.ts`), only when `create` got `tcpListener`: `reverse` listens on a free loopback port in 47000-47999 (busy ones skipped; none free → `TUNNEL_FAILED`) and runs `adb reverse --no-rebind tcp: tcp:` on the device's own server (an emulator's on Simlock's port, a phone's on 5037 behind the gate), 10 s per call; `cannot rebind existing socket` → `TUNNEL_PORT_IN_USE`, any other failure → `TUNNEL_FAILED` (message cut to 200 characters). `close` removes the rule, then the listener; a removal that fails keeps the listener, closing every connection at once. Cleanup: reclaim (with or without `tcpListener`) of a phone, and of an emulator once its ownership probe passed, runs `reverse --remove-all` and removes this serial's `forward --list` lines one by one with `forward --remove ` (never `--remove-all`); an emulator not proved its own is left alone. `deviceTcp.sweep` (only with `tcpListener`), called by the daemon before any request is served, removes on every present owned emulator and phone, leased or idle, the `reverse --list` rules whose host side is `tcp:47000`-`tcp:47999`. A failed removal is a `warn`; reclaim and start go on. +Tunnels — `deviceTcp` (`device-tcp.ts`), only when `create` got `tcpListener`: `reverse` listens on a free loopback port in 47000-47999 (busy ones skipped; none free → `TUNNEL_FAILED`) and runs `adb reverse --no-rebind tcp: tcp:` on the device's own server (an emulator's on Simlock's port, a phone's on 5037 behind the gate), 10 s per call; `cannot rebind existing socket` → `TUNNEL_PORT_IN_USE`, any other failure → `TUNNEL_FAILED` (message cut to 200 characters). `close` removes the rule, then the listener; a removal that fails keeps the listener, closing every connection at once, and the driver's `reclaim` of that device frees every port still held for it (`release`) once its rules are gone. The refusal messages name the call (`reverse : the device port is already reversed; remove that rule first`, `reverse : `). Cleanup: reclaim (with or without `tcpListener`) of a phone, and of an emulator once its ownership probe passed, runs `reverse --remove-all` and removes this serial's `forward --list` lines one by one with `forward --remove ` (never `--remove-all`); an emulator not proved its own is left alone. `deviceTcp.sweep` (only with `tcpListener`), called by the daemon before any request is served, removes on every present idle owned emulator and phone the `reverse --list` rules whose host side is `tcp:47000`-`tcp:47999`; on a leased one it removes nothing and keeps the ports those rules point to from the next `reverse` until its reclaim. A failed removal is a `warn`; reclaim and start go on. Plain facts: `listCatalog`, a resolve of a model the library lacks and a library provision (seed) share one `AvdmanagerDeviceList`: `avdmanager list device` runs again only when the size or modified time of a file it reads profiles from changed, or one appeared or went: the tools package's `lib/sdklib/sdklib.core.jar` (legacy `tools/lib/sdklib*.jar`) and `source.properties`, the user's devices.xml, `devices.xml` in each `system-images/*/*/*` and `add-ons/*` directory (a new image is a new path), and `devices.xml` and `source.properties` in each `extras/*/*` directory (avdmanager reads an extra whose `source.properties` says `Extra.Path=DeviceProfiles`). Otherwise the last good answer is served; a failed run is not kept; concurrent callers share one run. The sdkmanager catalog is never read. Existing devices are not re-checked for fit. diff --git a/src/drivers/android/device-tcp.ts b/src/drivers/android/device-tcp.ts index 5903176e8..b61c8906b 100644 --- a/src/drivers/android/device-tcp.ts +++ b/src/drivers/android/device-tcp.ts @@ -3,6 +3,7 @@ import { type DeviceReverse, type DeviceTcp, type PhysicalDriverDevice, + type SweptDevice, type VirtualDriverDevice, } from "../../core/index.js"; import type { @@ -37,8 +38,12 @@ function cut(message: string): string { return message.length > MESSAGE_LIMIT ? message.slice(0, MESSAGE_LIMIT) : message; } -async function listenInRange(listeners: TcpListenerFactory): Promise { +async function listenInRange( + listeners: TcpListenerFactory, + skip: ReadonlySet, +): Promise { for (let port = TUNNEL_PORT_FIRST; port <= TUNNEL_PORT_LAST; port += 1) { + if (skip.has(port)) continue; const listener = await listeners.listen(port); if (listener !== undefined) return listener; } @@ -92,35 +97,74 @@ export async function removeDeviceRules( } } -// why: at start only a rule into the loopback range the worker keeps for tunnels is Simlock's own; a holder's other rules stay. -async function removeTunnelRules(run: RunAdb, warn: Warn, device: Target): Promise { +// why: at start only a rule into the loopback range the worker keeps for tunnels is Simlock's own; a holder's other rules are not read as such. +async function tunnelRules( + run: RunAdb, + warn: Warn, + device: Target, +): Promise<{ readonly deviceSide: string; readonly port: number }[]> { const listed = await attempt(run, warn, device, ["reverse", "--list"]); + const rules: { deviceSide: string; port: number }[] = []; for (const [, deviceSide, hostSide] of fields(listed ?? "")) { - const port = /^tcp:(\d{1,5})$/.exec(hostSide ?? "")?.[1]; - if (port === undefined || deviceSide === undefined) continue; - if (Number(port) < TUNNEL_PORT_FIRST || Number(port) > TUNNEL_PORT_LAST) continue; - await attempt(run, warn, device, ["reverse", "--remove", deviceSide]); + const port = Number(/^tcp:(\d{1,5})$/.exec(hostSide ?? "")?.[1]); + if (deviceSide === undefined || port < TUNNEL_PORT_FIRST || port > TUNNEL_PORT_LAST) continue; + rules.push({ deviceSide, port }); } + return rules; +} + +// why: a loopback port the worker still owes a device: a listener whose rule is set or could not be removed, or a rule a leased device kept at start; the device's reclaim frees them. +interface HeldPort { + readonly port: number; + readonly listener?: TcpListener | undefined; +} + +export interface AndroidDeviceTcp extends DeviceTcp { + // why: called by the driver's reclaim of a device once its rules are gone, so every port held for it is free again. + release(device: { readonly deviceId: string }): Promise; } -export function createAndroidDeviceTcp(options: AndroidDeviceTcpOptions): DeviceTcp { +export function createAndroidDeviceTcp(options: AndroidDeviceTcpOptions): AndroidDeviceTcp { + const held = new Map>(); + const keep = (deviceId: string, entry: HeldPort): void => { + const mine = held.get(deviceId) ?? new Set(); + mine.add(entry); + held.set(deviceId, mine); + }; + const heldPorts = (): Set => + new Set([...held.values()].flatMap((mine) => [...mine].map((entry) => entry.port))); return { supports: () => true, - async sweep(devices): Promise { + async release(device): Promise { + const mine = held.get(device.deviceId); + held.delete(device.deviceId); + await Promise.all([...(mine ?? [])].map((entry) => entry.listener?.close())); + }, + async sweep(devices: readonly SweptDevice[]): Promise { await Promise.all( - devices.map(async (device) => { - if (await options.isOwn(device)) { - await removeTunnelRules(options.runAdb, options.warn, device); + devices.map(async ({ device, leased }) => { + if (!(await options.isOwn(device))) return; + const rules = await tunnelRules(options.runAdb, options.warn, device); + for (const { deviceSide, port } of rules) { + if (leased) keep(device.deviceId, { port }); + else { + await attempt(options.runAdb, options.warn, device, [ + "reverse", + "--remove", + deviceSide, + ]); + } } }), ); }, async reverse(device, devicePort): Promise { - const listener = await listenInRange(options.listeners); + const listener = await listenInRange(options.listeners, heldPorts()); const refuse = async (error: DeviceTcpError): Promise => { await listener.close(); throw error; }; + const named = `reverse ${String(devicePort)}`; let result: ProcessResult; try { result = await options.runAdb( @@ -132,19 +176,23 @@ export function createAndroidDeviceTcp(options: AndroidDeviceTcpOptions): Device return await refuse( new DeviceTcpError( "TUNNEL_FAILED", - cut(error instanceof Error ? error.message : String(error)), + `${named}: ${cut(error instanceof Error ? error.message : String(error))}`, ), ); } if (result.code !== 0) { const message = result.stderr.trim(); return await refuse( - new DeviceTcpError( - message.includes(CANNOT_REBIND) ? "TUNNEL_PORT_IN_USE" : "TUNNEL_FAILED", - cut(message), - ), + message.includes(CANNOT_REBIND) + ? new DeviceTcpError( + "TUNNEL_PORT_IN_USE", + `${named}: the device port is already reversed; remove that rule first`, + ) + : new DeviceTcpError("TUNNEL_FAILED", `${named}: ${cut(message)}`), ); } + const mine: HeldPort = { listener, port: listener.port }; + keep(device.deviceId, mine); // why: once the rule is being removed, or when its removal fails, a connection that still arrives is closed at once. let accept: ((stream: TcpStream) => void) | undefined; listener.onConnection((stream) => { @@ -154,12 +202,20 @@ export function createAndroidDeviceTcp(options: AndroidDeviceTcpOptions): Device return { close: async () => { accept = undefined; - const removed = await options.runAdb( - device, - ["reverse", "--remove", `tcp:${String(devicePort)}`], - ADB_TIMEOUT_MS, - ); - if (removed.code !== 0) throw new Error(cut(removed.stderr.trim())); + let failure: Error | undefined; + try { + const removed = await options.runAdb( + device, + ["reverse", "--remove", `tcp:${String(devicePort)}`], + ADB_TIMEOUT_MS, + ); + if (removed.code !== 0) failure = new Error(cut(removed.stderr.trim())); + } catch (error) { + failure = new Error(cut(error instanceof Error ? error.message : String(error))); + } + // why: a rule that is still set points at this port, so the listener stays reserved until the device's reclaim removes the rule. + if (failure !== undefined) throw failure; + held.get(device.deviceId)?.delete(mine); await listener.close(); }, hostPort: listener.port, diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index ce760850c..62cc2eaf3 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -796,8 +796,11 @@ describe("AndroidDriver", () => { }); }); - it("captures a named clean baseline once and restores it on a standard reclaim, after removing the emulator's adb rules", async () => { - const harness = await provisionedHarness({ forBaselineReclaim: true }); + it("captures a named clean baseline once and restores it on a standard reclaim, after removing every reverse rule of the emulator and its own forwards, and keeping another device's forward", async () => { + const harness = await provisionedHarness({ + forBaselineReclaim: true, + forwardList: "emulator-5586 tcp:18790 tcp:18791\nemulator-5590 tcp:18792 tcp:18793\n", + }); const ready = await harness.driver.makeReady(harness.device); await expect(harness.driver.reclaim(ready, { clean: "standard" })).resolves.toEqual({ @@ -816,9 +819,13 @@ describe("AndroidDriver", () => { const removed = commands.indexOf("-P 5038 -s emulator-5586 reverse --remove-all"); expect(removed).toBeGreaterThan(-1); expect(commands.indexOf("-P 5038 -s emulator-5586 forward --list")).toBe(removed + 1); - expect(commands.indexOf("-s emulator-5586 emu avd snapshot load simlock_clean_baseline")).toBe( + expect(commands.indexOf("-P 5038 -s emulator-5586 forward --remove tcp:18790")).toBe( removed + 2, ); + expect(commands.some((command) => command.includes("tcp:18792"))).toBe(false); + expect(commands.indexOf("-s emulator-5586 emu avd snapshot load simlock_clean_baseline")).toBe( + removed + 3, + ); }); it("tags the baseline with the emulator-normalized post-boot configuration", async () => { @@ -3399,7 +3406,7 @@ describe("AndroidDriver deviceTcp", () => { return { driver, listeners, runner }; } - it("sets adb reverse --no-rebind to a loopback listener in 47000-47999 and removes it on close, as an emulator or a phone", async () => { + it("sets adb reverse --no-rebind to a loopback listener in 47000-47999 and removes it on close, as an emulator or a phone, keeps the port of a rule that could not be removed until the device's reclaim, and refuses with TUNNEL_PORT_IN_USE when adb cannot rebind and TUNNEL_FAILED for any other adb failure or when every tunnel port is busy", async () => { const { driver, listeners, runner } = await driverWith([ { match: adb("-P", "5038", "-s", "emulator-5586", ...reverseArgs(47_002)), result: ok }, { @@ -3453,6 +3460,19 @@ describe("AndroidDriver deviceTcp", () => { match: adb("-P", "5038", "-s", "emulator-5586", "reverse", "--remove", "tcp:5173"), result: { code: 1, stderr: "device offline", stdout: "" }, }, + { + match: adb( + "-P", + "5038", + "-s", + "emulator-5586", + "reverse", + "--no-rebind", + "tcp:5174", + "tcp:47001", + ), + result: ok, + }, ]); const held = await stuck.driver.deviceTcp?.reverse(emulator, 5173, signal()); const delivered: unknown[] = []; @@ -3464,38 +3484,11 @@ describe("AndroidDriver deviceTcp", () => { closed: true, delivered: 0, }); - }); - - it("sweeps at start only the reverse rules into 47000-47999 on a device proved its own, and removes nothing on an emulator that answers as another's", async () => { - const own = await driverWith([ - avdPathExpectation("emulator-5586"), - { - match: adb("-P", "5038", "-s", "emulator-5586", "reverse", "--list"), - result: { - code: 0, - stderr: "", - stdout: - "host-19 tcp:5173 tcp:47003\nhost-19 tcp:8081 tcp:8082\nhost-19 tcp:3000 tcp:47999\n", - }, - }, - { - match: adb("-P", "5038", "-s", "emulator-5586", "reverse", "--remove", "tcp:5173"), - result: ok, - }, - { - match: adb("-P", "5038", "-s", "emulator-5586", "reverse", "--remove", "tcp:3000"), - result: ok, - }, - ]); - await own.driver.deviceTcp?.sweep([emulator]); - expect(own.runner.calls.filter((call) => call.args.includes("--remove"))).toHaveLength(2); - - const foreign = await driverWith([avdPathExpectation("emulator-5586", "simlock_two")]); - await foreign.driver.deviceTcp?.sweep([emulator]); - expect(foreign.runner.calls.some((call) => call.args.includes("reverse"))).toBe(false); - }); + const second = await stuck.driver.deviceTcp?.reverse(emulator, 5174, signal()); + expect(second?.hostPort).toBe(47_001); + await stuck.driver.deviceTcp?.release(emulator); + expect(stuck.listeners.listeners.map((listener) => listener.closed)).toEqual([true, true]); - it("refuses a reverse with TUNNEL_PORT_IN_USE when adb cannot rebind, TUNNEL_FAILED for any other adb failure or when every tunnel port is busy, and frees the port it took", async () => { const cannotRebind = await driverWith([ { match: adb("-P", "5038", "-s", "emulator-5586", ...reverseArgs(47_000)), @@ -3503,7 +3496,10 @@ describe("AndroidDriver deviceTcp", () => { }, ]); await expect(cannotRebind.driver.deviceTcp?.reverse(emulator, 5173, signal())).rejects.toEqual( - expect.objectContaining({ code: "TUNNEL_PORT_IN_USE" }), + expect.objectContaining({ + code: "TUNNEL_PORT_IN_USE", + message: "reverse 5173: the device port is already reversed; remove that rule first", + }), ); expect(cannotRebind.listeners.listeners[0]?.closed).toBe(true); @@ -3518,7 +3514,10 @@ describe("AndroidDriver deviceTcp", () => { .catch((caught: unknown) => caught); expect(error).toBeInstanceOf(DeviceTcpError); expect(error).toEqual( - expect.objectContaining({ code: "TUNNEL_FAILED", message: "x".repeat(200) }), + expect.objectContaining({ + code: "TUNNEL_FAILED", + message: `reverse 5173: ${"x".repeat(200)}`, + }), ); expect(failed.listeners.listeners[0]?.closed).toBe(true); @@ -3533,6 +3532,63 @@ describe("AndroidDriver deviceTcp", () => { ); expect(exhausted.runner.calls).toEqual([]); }); + + it("sweeps at start only the reverse rules into 47000-47999 on an idle device proved its own, only reads a leased device's rules and keeps their ports from the next reverse until its reclaim, and touches nothing on an emulator that answers as another's", async () => { + const own = await driverWith([ + avdPathExpectation("emulator-5586"), + { + match: adb("-P", "5038", "-s", "emulator-5586", "reverse", "--list"), + result: { + code: 0, + stderr: "", + stdout: + "host-19 tcp:5173 tcp:47003\nhost-19 tcp:8081 tcp:8082\nhost-19 tcp:3000 tcp:47999\n", + }, + }, + { + match: adb("-P", "5038", "-s", "emulator-5586", "reverse", "--remove", "tcp:5173"), + result: ok, + }, + { + match: adb("-P", "5038", "-s", "emulator-5586", "reverse", "--remove", "tcp:3000"), + result: ok, + }, + ]); + await own.driver.deviceTcp?.sweep([{ device: emulator, leased: false }]); + expect(own.runner.calls.filter((call) => call.args.includes("--remove"))).toHaveLength(2); + + const foreign = await driverWith([avdPathExpectation("emulator-5586", "simlock_two")]); + await foreign.driver.deviceTcp?.sweep([{ device: emulator, leased: false }]); + expect(foreign.runner.calls.some((call) => call.args.includes("reverse"))).toBe(false); + + const onServer = ["-P", "5038", "-s", "emulator-5586"]; + const leased = await driverWith([ + avdPathExpectation("emulator-5586"), + { + match: adb(...onServer, "reverse", "--list"), + result: { + code: 0, + stderr: "", + stdout: "host-19 tcp:5173 tcp:47000\nhost-19 tcp:3000 tcp:3001\n", + }, + }, + { + match: adb(...onServer, "reverse", "--no-rebind", "tcp:5174", "tcp:47001"), + result: ok, + }, + { + match: adb(...onServer, "reverse", "--no-rebind", "tcp:5175", "tcp:47000"), + result: ok, + }, + ]); + await leased.driver.deviceTcp?.sweep([{ device: emulator, leased: true }]); + expect(leased.runner.calls.filter((call) => call.args.includes("--remove"))).toEqual([]); + const next = await leased.driver.deviceTcp?.reverse(emulator, 5174, signal()); + expect(next?.hostPort).toBe(47_001); + await leased.driver.deviceTcp?.release(emulator); + const afterReclaim = await leased.driver.deviceTcp?.reverse(emulator, 5175, signal()); + expect(afterReclaim?.hostPort).toBe(47_000); + }); }); describe("AndroidDriver screen capture", () => { @@ -5492,6 +5548,8 @@ async function provisionedHarness( readonly emulator?: AndroidEmulatorLaunchOptions; readonly emulatorFlags?: readonly string[]; readonly forBaselineReclaim?: boolean; + // why: what the emulator's server answers to `forward --list` at reclaim, so a test can set another device's forward beside its own. + readonly forwardList?: string; readonly forFullCleanBoot?: boolean; readonly forReclaim?: boolean; readonly ids?: readonly string[]; @@ -5555,7 +5613,7 @@ async function provisionedHarness( expectations.push( processResult(binaries.emulator, ["-version"], "Android emulator version 36.1.9"), avdPathExpectation("emulator-5586"), - ...ruleCleanupExpectations("emulator-5586"), + ...ruleCleanupExpectations("emulator-5586", options.forwardList), processResult( binaries.adb, ["-s", "emulator-5586", "emu", "avd", "snapshot", "load", "simlock_clean_baseline"], @@ -7145,11 +7203,18 @@ function avdPathExpectation(serial: string, avdName = "simlock_one"): ScriptedPr } // why: a reclaim that passed its ownership probe removes the device's rules before it loads the snapshot: every reverse rule, then a look at the forwards (none here). -function ruleCleanupExpectations(serial: string): ScriptedProcessExpectation[] { +function ruleCleanupExpectations(serial: string, forwards = ""): ScriptedProcessExpectation[] { const onServer = ["-P", String(adbServerPort), "-s", serial]; + const own = forwards + .split("\n") + .map((line) => line.trim().split(/\s+/)) + .filter((parts) => parts[0] === serial && parts[1] !== undefined); return [ processResult(binaries.adb, [...onServer, "reverse", "--remove-all"]), - processResult(binaries.adb, [...onServer, "forward", "--list"]), + processResult(binaries.adb, [...onServer, "forward", "--list"], forwards), + ...own.map((parts) => + processResult(binaries.adb, [...onServer, "forward", "--remove", parts[1] ?? ""]), + ), ]; } diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 6d8800155..2d6d396a3 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -41,7 +41,6 @@ import { type ReclaimResult, removeListedComponent, type DeviceInputFactory, - type DeviceTcp, type ScreenCapture, ScreenUnavailableError, RuntimeMissingError, @@ -63,7 +62,7 @@ import { type TcpStreamConnector, type TimerHandle, } from "../../ports/index.js"; -import { createAndroidDeviceTcp, removeDeviceRules } from "./device-tcp.js"; +import { createAndroidDeviceTcp, removeDeviceRules, type AndroidDeviceTcp } from "./device-tcp.js"; import { AdbRegistrar } from "./adb-registrar.js"; import { AdbServerSupervisor, AdbServerUnavailableError } from "./adb-server.js"; import { isAndroidDriverData, type AndroidDriverData } from "./data.js"; @@ -544,7 +543,7 @@ export class AndroidDriver implements Driver { readonly componentFootprint: { readonly path: string; readonly bytes: number }; readonly screenCapture: ScreenCapture | undefined; readonly input: DeviceInputFactory | undefined; - readonly deviceTcp: DeviceTcp | undefined; + readonly deviceTcp: AndroidDeviceTcp | undefined; private constructor( options: AndroidDriverOptions, @@ -1132,9 +1131,19 @@ export class AndroidDriver implements Driver { : { ...data, port: state.port, serial: serialFor(state.port) }; } + // why: the loopback ports held for a device's tunnels are freed only after its reclaim removed the rules they serve. async reclaim( device: DriverDevice, options: { readonly clean: "standard" | "full" }, + ): Promise { + const result = await this.#reclaimDevice(device, options); + await this.deviceTcp?.release(device); + return result; + } + + async #reclaimDevice( + device: DriverDevice, + options: { readonly clean: "standard" | "full" }, ): Promise { if (isPhysicalDriverDevice(device)) { await this.#removeRules(device, device.deviceId); diff --git a/src/drivers/android/physical-handler.test.ts b/src/drivers/android/physical-handler.test.ts index cb9754546..952d0ffb3 100644 --- a/src/drivers/android/physical-handler.test.ts +++ b/src/drivers/android/physical-handler.test.ts @@ -8,6 +8,7 @@ import { import { FakeClock, FakeProcessSupervisor, + FakeTcpListenerFactory, FakeTcpProbe, FakeTcpStreamConnector, type Filesystem, @@ -282,6 +283,7 @@ async function world( readonly filesystem?: Filesystem; readonly processRunner?: (phone: PhoneAdb) => ProcessRunner; readonly serverReply?: string; + readonly listeners?: FakeTcpListenerFactory; } = {}, ): Promise { const log: string[] = []; @@ -306,6 +308,7 @@ async function world( processRunner: options.processRunner?.(runner) ?? runner, processSupervisor: new FakeProcessSupervisor([4242]), simlockHome, + ...(options.listeners === undefined ? {} : { tcpListener: options.listeners }), tcpProbe: probe, }); return { driver, filesystem, log: runner.log, probe, runner }; @@ -1135,20 +1138,28 @@ describe("Android physical handler: reclaim", () => { expect(runner.installed).toEqual(["com.example.kept"]); }); - it("removes every reverse rule of the phone and only its own forwards, and goes on when a removal fails", async () => { - const { driver, runner } = await world(); - runner.override((rest) => - rest.slice(2).join(" ") === "forward --list" - ? OK(`${PHONE} tcp:18790 tcp:18791\nOTHER tcp:18792 tcp:18793\n`) - : rest.slice(2).join(" ") === "reverse --remove-all" - ? FAILED - : undefined, - ); + it("removes every reverse rule of the phone and only its own forwards, goes on when a removal fails, and frees the loopback port a failed tunnel removal kept", async () => { + const listeners = new FakeTcpListenerFactory(); + const { driver, runner } = await world({ listeners }); + runner.override((rest) => { + const body = rest.slice(2).join(" "); + if (body === "forward --list") { + return OK(`${PHONE} tcp:18790 tcp:18791\nOTHER tcp:18792 tcp:18793\n`); + } + if (body === "reverse --remove-all" || body === "reverse --remove tcp:5173") return FAILED; + return body.startsWith("reverse --no-rebind") ? OK() : undefined; + }); + const kept = await driver.deviceTcp?.reverse(PHYSICAL, 5173, new AbortController().signal); + await kept?.close().catch(() => undefined); + expect(listeners.listeners[0]?.closed).toBe(false); const result = await driver.reclaim(PHYSICAL, { clean: "standard" }); + expect(listeners.listeners[0]?.closed).toBe(true); expect(result).toMatchObject({ strategy: "uninstall" }); - expect(runner.rests.filter((rest) => rest[2] === "reverse" || rest[2] === "forward")).toEqual([ + expect( + runner.rests.filter((rest) => rest[2] === "reverse" || rest[2] === "forward").slice(2), + ).toEqual([ ["-s", PHONE, "reverse", "--remove-all"], ["-s", PHONE, "forward", "--list"], ["-s", PHONE, "forward", "--remove", "tcp:18790"], diff --git a/src/ports/tcp-listener.test.ts b/src/ports/tcp-listener.test.ts index 0d0de1a72..00ba1e5e2 100644 --- a/src/ports/tcp-listener.test.ts +++ b/src/ports/tcp-listener.test.ts @@ -21,6 +21,7 @@ describe("NodeTcpListenerFactory", () => { const factory = new NodeTcpListenerFactory(); const listener = await factory.listen(port); expect(listener?.port).toBe(port); + expect(listener?.address).toBe("127.0.0.1"); expect(await factory.listen(port)).toBeUndefined(); const received = new Promise((resolve) => { diff --git a/src/ports/tcp-listener.ts b/src/ports/tcp-listener.ts index 276d1ee62..74a2cd435 100644 --- a/src/ports/tcp-listener.ts +++ b/src/ports/tcp-listener.ts @@ -6,6 +6,8 @@ import { FakeTcpPeer, type TcpStream, tcpStreamOf } from "./tcp-stream.js"; // that port for as long as the rule stands, and every connection to it arrives on `onConnection`. export interface TcpListener { readonly port: number; + // why: the interface the listener is bound to, so a test can prove a tunnel's port is reachable from this machine only. + readonly address: string; onConnection(listener: (stream: TcpStream) => void): void; close(): Promise; } @@ -34,7 +36,9 @@ export class NodeTcpListenerFactory implements TcpListenerFactory { }); server.listen(port, "127.0.0.1", () => { server.on("error", () => undefined); + const bound = server.address(); resolve({ + address: typeof bound === "object" && bound !== null ? bound.address : "", close: () => new Promise((done) => { server.close(() => done()); @@ -54,6 +58,8 @@ class FakeTcpListener implements TcpListener { closed = false; readonly #listeners: ((stream: TcpStream) => void)[] = []; + readonly address = "127.0.0.1"; + constructor(readonly port: number) {} onConnection(listener: (stream: TcpStream) => void): void { diff --git a/src/ports/tcp-stream.test.ts b/src/ports/tcp-stream.test.ts index ec00af0a6..3868bf4cd 100644 --- a/src/ports/tcp-stream.test.ts +++ b/src/ports/tcp-stream.test.ts @@ -1,12 +1,14 @@ -import { createServer, type Server, type Socket } from "node:net"; +import { createConnection, createServer, type Server, type Socket } from "node:net"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; -import { NodeTcpStreamConnector } from "./tcp-stream.js"; +import { NodeTcpStreamConnector, tcpStreamOf } from "./tcp-stream.js"; let server: Server | undefined; +const held: Socket[] = []; afterEach(async () => { + for (const socket of held.splice(0)) socket.destroy(); await new Promise((resolve) => (server ? server.close(() => resolve()) : resolve())); server = undefined; }); @@ -19,6 +21,7 @@ async function listen(onConnection: (socket: Socket) => void): Promise { return address.port; } +// why: an adapter over node:net, proven by what a real loopback socket does, which the fake cannot show. describe("NodeTcpStreamConnector", () => { it("carries bytes both ways until the peer hangs up", async () => { const port = await listen((socket) => { @@ -51,4 +54,47 @@ describe("NodeTcpStreamConnector", () => { }); await expect(peerClosed).resolves.toBeUndefined(); }); + + it("ends its readable when the peer closes or the socket errors, pauses the socket while the reader is behind, and destroys it when the reader cancels", async () => { + let accepted: Socket | undefined; + const port = await listen((socket) => { + accepted = socket; + socket.on("error", () => undefined); + }); + const open = async (): Promise<{ + socket: Socket; + peer: Socket; + stream: ReturnType; + }> => { + const socket = createConnection({ host: "127.0.0.1", port }); + await new Promise((resolve) => socket.once("connect", () => resolve())); + await vi.waitFor(() => expect(accepted).toBeDefined()); + const peer = accepted as Socket; + accepted = undefined; + held.push(socket, peer); + return { peer, socket, stream: tcpStreamOf(socket) }; + }; + + const closing = await open(); + closing.peer.destroy(); + await expect(closing.stream.readable.getReader().read()).resolves.toEqual({ + done: true, + value: undefined, + }); + + const failing = await open(); + const failed = failing.stream.readable.getReader().read(); + failing.socket.emit("error", new Error("the connection broke")); + await expect(failed).resolves.toEqual({ done: true, value: undefined }); + + const behind = await open(); + behind.peer.write("one"); + await vi.waitFor(() => expect(behind.socket.isPaused()).toBe(true)); + const reader = behind.stream.readable.getReader(); + await expect(reader.read()).resolves.toMatchObject({ done: false }); + await vi.waitFor(() => expect(behind.socket.isPaused()).toBe(false)); + + await reader.cancel(); + expect(behind.socket.destroyed).toBe(true); + }); }); diff --git a/src/ports/tcp-stream.ts b/src/ports/tcp-stream.ts index bcd7a8dd6..a7485447b 100644 --- a/src/ports/tcp-stream.ts +++ b/src/ports/tcp-stream.ts @@ -18,7 +18,9 @@ export interface TcpStream { function readableOf(socket: Socket): ReadableStream { let finished = false; return new ReadableStream({ + // why: a cancelled stream is already closed, and the `close` the destroy raises must not close it again, which throws outside any handler. cancel: () => { + finished = true; socket.destroy(); }, pull: () => { @@ -42,8 +44,7 @@ function readableOf(socket: Socket): ReadableStream { }); } -// why: after connect or accept an error ends the readable through `Readable.toWeb`; a listener must -// still exist or Node raises it as an uncaught exception and takes the daemon down. +// why: a socket error with no listener is raised by Node as an uncaught exception and takes the daemon down, so one always exists; `readableOf` ends the readable on it. export function tcpStreamOf(socket: Socket): TcpStream { socket.on("error", () => undefined); return { @@ -91,6 +92,10 @@ export class NodeTcpStreamConnector implements TcpStreamConnector { export class FakeTcpPeer { readonly written: Uint8Array[] = []; closed = false; + // why: the device's side ended its bytes, which a test tells from the worker having closed the connection. + ended = false; + // why: a test sets this to make every write to the device fail, as a broken device socket does. + writeFailure: Error | undefined; // why: the driver half-closed its side, as `stream.end()` does; `end()` on the peer is the device's side ending. writeEnded = false; #controller!: ReadableStreamDefaultController; @@ -109,17 +114,14 @@ export class FakeTcpPeer { close: () => { if (this.closed) return; this.closed = true; - try { - this.#controller.close(); - } catch { - // why: a cancelled readable is already closed; closing the connection is still done. - } + this.#closeReadable(); }, end: () => { this.writeEnded = true; }, readable, write: async (bytes) => { + if (this.writeFailure !== undefined) throw this.writeFailure; this.written.push(typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes); }, }; @@ -132,13 +134,22 @@ export class FakeTcpPeer { // fallow-ignore-next-line unused-class-member -- the device's side of a fake stream, called by tests. send(bytes: Uint8Array | string): void { - if (this.closed) return; + if (this.closed || this.ended) return; this.#controller.enqueue(typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes); } // fallow-ignore-next-line unused-class-member -- the device's side ending, called by tests. end(): void { - this.stream.close(); + this.ended = true; + this.#closeReadable(); + } + + #closeReadable(): void { + try { + this.#controller.close(); + } catch { + // why: a cancelled or already ended readable is closed; ending the connection is still done. + } } } diff --git a/src/tunnel/AGENTS.md b/src/tunnel/AGENTS.md index 829f0bb0c..d8fddd936 100644 --- a/src/tunnel/AGENTS.md +++ b/src/tunnel/AGENTS.md @@ -19,11 +19,11 @@ Off unless `capabilities.tunnel.enabled` (false). Off: nothing loaded, and the ` The HTTP layer resolves the lease for the caller, then `socket.open` finds the lease and its device in the worker's registry (404 `UNKNOWN_LEASE` when gone) and attaches a session to the upgraded socket. -1. The first frame must be `HELLO`. It is checked whole: bad port, more than 8 tunnels per lease (counted across sockets), `forward` (not available yet), a platform whose driver has no `deviceTcp` (`supports`). A refusal sends `REFUSED {code, message}` and closes 4003. +1. The first frame must be `HELLO`. It is checked whole: bad port, more than 8 tunnels per lease (counted across sockets), `forward` (not available yet), a platform whose driver has no `deviceTcp` (`supports`). A refusal sends `REFUSED {code, message}` and closes 4003 (the close reason is cut to 123 bytes, the message is whole). 2. Each reverse tunnel is `ctx.deviceTcp.reverse`. A failure removes the tunnels set before it and refuses with the driver's `DeviceTcpError` code (`TUNNEL_PORT_IN_USE`, `TUNNEL_FAILED`), else `TUNNEL_FAILED`. Then `READY`. 3. A device connection is `OPEN` with the next odd id; its bytes go out as `DATA` only while the caller's window allows, and the worker grants `CREDIT` as it writes to the device. `END` half-closes one direction; a connection ends when both have. A 257th open connection is closed at once. -4. A bad frame is `BAD_REQUEST`, close 4003; a frame for a connection already closed is ignored. -5. The socket closing, the lease ending (`beforeDeviceReclaim`, close 4001 with the reason) and a drain (`beforeDrain`, close 1001) close the session's connections and remove its rules; with an already aborted signal the removal is skipped and reclaim does it. +4. A bad frame (a `CREDIT` that is not 4 bytes, a `DATA` of 0 or over 65536 bytes included) is `BAD_REQUEST`, close 4003, never a throw; a frame for a connection already closed is ignored; a device stream that fails resets its own connection. +5. The socket closing, the lease ending (`beforeDeviceReclaim`, close 4001 with the reason) and a drain (`beforeDrain`, close 1001) close the session's connections and remove its rules, the hook returning when they are done (10 s per removal); a signal that is aborted, or aborts between removals, skips the rest and reclaim does them. ## Rules diff --git a/src/tunnel/sessions.ts b/src/tunnel/sessions.ts index 4178d85bd..0e2537e57 100644 --- a/src/tunnel/sessions.ts +++ b/src/tunnel/sessions.ts @@ -16,15 +16,20 @@ import { DeviceTcpError, stableError, toDriverDevice, + unsupportedTunnelMessage, type DeviceRecord, type DeviceReverse, } from "../core/index.js"; import type { ModuleDeviceTcp } from "../modules/index.js"; -import type { LeaseSocket, Logger, TcpStream } from "../ports/index.js"; +import type { Clock, LeaseSocket, Logger, TcpStream, TimerHandle } from "../ports/index.js"; const CLOSE_LEASE_ENDED = 4001; const CLOSE_GOING_AWAY = 1001; const MAX_CONNECTIONS = 256; +// why: a WebSocket close reason is at most 123 bytes, and `ws` throws on a longer one, so a long message is cut for the close and sent whole in REFUSED. +const CLOSE_REASON_MAX_BYTES = 123; +const REMOVAL_TIMEOUT_MS = 10_000; +const CREDIT_BYTES = 4; interface Tunnel { readonly kind: "reverse" | "forward"; @@ -83,11 +88,17 @@ function parseHello(payload: Uint8Array): readonly Tunnel[] | string { return tunnels; } +function closeReason(message: string): string { + const bytes = new TextEncoder().encode(message); + if (bytes.length <= CLOSE_REASON_MAX_BYTES) return message; + return new TextDecoder().decode(bytes.subarray(0, CLOSE_REASON_MAX_BYTES)).replace(/�+$/u, ""); +} + function refusal(tunnels: readonly Tunnel[], held: number): Refusal | undefined { if (held + tunnels.length > TUNNEL_MAX_TUNNELS) { return { code: "TUNNEL_LIMIT", - message: `the lease already has ${String(held + tunnels.length)} tunnels; at most ${String(TUNNEL_MAX_TUNNELS)}`, + message: `the lease already has ${String(held)} tunnels; at most ${String(TUNNEL_MAX_TUNNELS)}`, }; } for (const { devicePort, kind } of tunnels) { @@ -107,7 +118,7 @@ function refusal(tunnels: readonly Tunnel[], held: number): Refusal | undefined // why: one socket's state that the lease's end and the daemon's stop reach from outside: `finish` closes its connections and, unless the reclaim that follows does it, removes its rules. interface Session { readonly socket: LeaseSocket; - finish(removeRules: boolean): Promise; + finish(removeRules: boolean, signal?: AbortSignal): Promise; } export interface TunnelSessions { @@ -119,6 +130,7 @@ export interface TunnelSessions { export function createTunnelSessions(options: { readonly deviceTcp: ModuleDeviceTcp; readonly logger: Logger; + readonly clock: Clock; }): TunnelSessions { // why: the 8-tunnel limit counts every socket of one lease, so the count is the lease's, not the socket's. const counts = new Map(); @@ -129,11 +141,16 @@ export function createTunnelSessions(options: { let greeted = false; let reserved = 0; let finished: Promise | undefined; + // why: a rule that arrives after `finish` read the list is removed only if the end that finished the session removed its own. + let endedWith: + | { readonly remove: boolean; readonly signal: AbortSignal | undefined } + | undefined; const connections = new Map(); const reverses: DeviceReverse[] = []; - function finish(removeRules: boolean): Promise { + function finish(removeRules: boolean, signal?: AbortSignal): Promise { finished ??= (async () => { + endedWith = { remove: removeRules, signal }; sessions.get(leaseId)?.delete(session); counts.set(leaseId, (counts.get(leaseId) ?? 0) - reserved); for (const connection of connections.values()) { @@ -143,11 +160,28 @@ export function createTunnelSessions(options: { } connections.clear(); if (!removeRules) return; - await Promise.all(reverses.map(removeRule)); + // why: one after another, so a lease-end signal that aborts mid-way stops the removals that reclaim is about to do. + for (const reverse of reverses) { + if (signal?.aborted === true) return; + await bounded(removeRule(reverse)); + } })(); return finished; } + // why: an adb call that never answers must not hold the lease's end or the daemon's stop, so each removal waits at most 10 s. + async function bounded(work: Promise): Promise { + let handle: TimerHandle | undefined; + const timeout = new Promise((resolve) => { + handle = options.clock.setTimer(REMOVAL_TIMEOUT_MS, () => { + options.logger.warn("A tunnel's device rule removal timed out", {}); + resolve(); + }); + }); + await Promise.race([work, timeout]); + if (handle !== undefined) options.clock.cancel(handle); + } + function removeRule(reverse: DeviceReverse): Promise { return reverse.close().catch((error: unknown) => { options.logger.warn("A tunnel's device rule could not be removed", { @@ -183,6 +217,7 @@ export function createTunnelSessions(options: { if (pending === undefined) { const step = await reader.read(); if (step.done) { + if (connection.closed) return; socket.send(encodeTunnelFrame(TUNNEL_TAG.end, conn)); connection.deviceEnded = true; settle(conn, connection); @@ -199,19 +234,40 @@ export function createTunnelSessions(options: { function refuse(refused: Refusal): void { socket.send(encodeTunnelFrame(TUNNEL_TAG.refused, 0, JSON.stringify(refused))); - socket.close(TUNNEL_REFUSED_CLOSE, refused.message); + socket.close(TUNNEL_REFUSED_CLOSE, closeReason(refused.message)); } function badRequest(message: string): void { refuse({ code: "BAD_REQUEST", message }); } + // why: a connection whose device stream failed ends alone, with RESET, so one broken device socket never takes the others or the daemon down. + function drop(conn: number, connection: Connection): void { + if (connections.get(conn) !== connection) return; + connection.closed = true; + connection.stream.close(); + connection.wake?.(); + connections.delete(conn); + socket.send( + encodeTunnelFrame( + TUNNEL_TAG.reset, + conn, + JSON.stringify({ reason: "the device connection failed" }), + ), + ); + } + async function received( conn: number, connection: Connection, payload: Uint8Array, ): Promise { - await connection.stream.write(payload); + try { + await connection.stream.write(payload); + } catch { + drop(conn, connection); + return; + } connection.inbound += payload.length; const granted = new Uint8Array(4); new DataView(granted.buffer).setUint32(0, payload.length); @@ -236,7 +292,7 @@ export function createTunnelSessions(options: { if (!options.deviceTcp.supports(device.spec.platform, target)) { refuse({ code: "TUNNEL_UNSUPPORTED", - message: `${device.spec.platform} devices take no tunnel`, + message: unsupportedTunnelMessage(device.spec.platform, target.physical), }); return; } @@ -253,20 +309,27 @@ export function createTunnelSessions(options: { ); } catch (error) { await finish(true); - refuse({ - code: error instanceof DeviceTcpError ? error.code : "TUNNEL_FAILED", - message: error instanceof Error ? error.message : String(error), - }); + const message = error instanceof Error ? error.message : String(error); + refuse( + error instanceof DeviceTcpError + ? { code: error.code, message } + : { + code: "TUNNEL_FAILED", + message: `${tunnel.kind} ${String(tunnel.devicePort)}: ${message}`, + }, + ); return; } // why: the socket can close while `reverse` is awaited, after `finish` read the list; a rule that arrives then is removed here. if (finished !== undefined) { - await removeRule(reverse); + if (endedWith?.remove === true && endedWith.signal?.aborted !== true) { + await bounded(removeRule(reverse)); + } return; } reverses.push(reverse); reverse.onConnection((stream) => { - if (connections.size >= MAX_CONNECTIONS) { + if (finished !== undefined || connections.size >= MAX_CONNECTIONS) { stream.close(); return; } @@ -283,13 +346,17 @@ export function createTunnelSessions(options: { window: TUNNEL_WINDOW_BYTES, }; connections.set(conn, connection); - void pump(conn, connection); + void pump(conn, connection).catch(() => drop(conn, connection)); }); } socket.send(encodeTunnelFrame(TUNNEL_TAG.ready, 0, JSON.stringify({ tunnels }))); } function onData(conn: number, connection: Connection, payload: Uint8Array): void { + if (payload.length === 0 || payload.length > TUNNEL_MAX_DATA_BYTES) { + badRequest(`DATA is 1 to ${String(TUNNEL_MAX_DATA_BYTES)} bytes`); + return; + } if (payload.length > connection.inbound) { badRequest("DATA is past the granted window"); return; @@ -299,6 +366,10 @@ export function createTunnelSessions(options: { } function onCredit(connection: Connection, payload: Uint8Array): void { + if (payload.length !== CREDIT_BYTES) { + badRequest(`CREDIT is ${String(CREDIT_BYTES)} bytes`); + return; + } const granted = new DataView(payload.buffer, payload.byteOffset, payload.length).getUint32(0); if (connection.window + granted > TUNNEL_WINDOW_LIMIT) { badRequest(`the window is above ${String(TUNNEL_WINDOW_LIMIT)}`); @@ -316,7 +387,11 @@ export function createTunnelSessions(options: { return; } greeted = true; - void hello(frame.payload); + void hello(frame.payload).catch((error: unknown) => { + options.logger.warn("A tunnel's HELLO failed", { error: stableError(error) }); + void finish(true); + refuse({ code: "TUNNEL_FAILED", message: "the worker could not set the tunnels up" }); + }); return; } if (frame.tag === TUNNEL_TAG.hello) { @@ -353,10 +428,16 @@ export function createTunnelSessions(options: { } } + // why: wire input never throws past this handler: whatever a frame does to the session, the holder gets BAD_REQUEST and the daemon goes on. socket.onMessage((data) => { - const frame = decodeTunnelFrame(data); - if (frame === undefined) badRequest("a frame is shorter than its 5-byte header"); - else handle(frame); + try { + const frame = decodeTunnelFrame(data); + if (frame === undefined) badRequest("a frame is shorter than its 5-byte header"); + else handle(frame); + } catch (error) { + options.logger.warn("A tunnel frame could not be handled", { error: stableError(error) }); + badRequest("a frame could not be handled"); + } }); } @@ -365,22 +446,23 @@ export function createTunnelSessions(options: { code: number, reason: string, removeRules: boolean, + signal?: AbortSignal, ): Promise { const ending = leaseId === undefined ? [...sessions.values()].flatMap((set) => [...set]) : [...(sessions.get(leaseId) ?? [])]; // why: a close that races the end must not remove a rule twice, so each session finishes once, with the end's choice about removal. - const done = ending.map((session) => session.finish(removeRules)); - for (const session of ending) session.socket.close(code, reason); + const done = ending.map((session) => session.finish(removeRules, signal)); + for (const session of ending) session.socket.close(code, closeReason(reason)); await Promise.all(done); } return { attach, drain: () => endSessions(undefined, CLOSE_GOING_AWAY, "Simlock is stopping", true), - // why: with the signal already aborted the daemon is stopping or in maintenance, and reclaim removes the rules, so no removal runs after reclaim began. + // why: with the signal aborted the daemon is stopping or in maintenance, and reclaim removes the rules, so no removal starts after that; the hook returns only when the removals it began are done. end: (leaseId, reason, signal) => - endSessions(leaseId, CLOSE_LEASE_ENDED, reason, !signal.aborted), + endSessions(leaseId, CLOSE_LEASE_ENDED, reason, !signal.aborted, signal), }; } diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index f3d20e36b..8f5868678 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -5,7 +5,7 @@ import { DeviceTcpError } from "../core/index.js"; import { FakeDeviceTcp } from "../core/testing.js"; import type { WorkerModule } from "../modules/index.js"; import { fakeWorkerContext } from "../modules/testing.js"; -import { MemoryLeaseSocket } from "../ports/index.js"; +import { type FakeClock, MemoryLeaseSocket } from "../ports/index.js"; import { tunnelModule } from "./index.js"; const IDENTITY = { principal: "tok_holder", role: "agent" } as const; @@ -43,19 +43,40 @@ function bigData(conn: number): Uint8Array { return bytes; } +function oversizeData(conn: number): Uint8Array { + const bytes = new Uint8Array(5 + 65_537); + bytes[0] = 0x03; + new DataView(bytes.buffer).setUint32(1, conn); + return bytes; +} + +function ending(reason: "device-lost" | "expired" | "explicit" | "killed") { + return { + deviceId: "dev_1", + leaseId: "L-1", + ownerId: "tok_holder", + platform: "android", + reason, + } as const; +} + function hello(...tunnels: { kind: string; devicePort: number }[]): Uint8Array { return frame(0x01, 0, JSON.stringify({ tunnels })); } -async function setup(platform = "android"): Promise<{ +async function setup( + platform = "android", + physical = false, +): Promise<{ readonly worker: WorkerModule; readonly deviceTcp: FakeDeviceTcp; + readonly clock: FakeClock; }> { - const { ctx } = await fakeWorkerContext("tunnel", {}); + const { clock, ctx } = await fakeWorkerContext("tunnel", {}); const deviceTcp = new FakeDeviceTcp(); const registry = { snapshot: { - devices: [{ id: "dev_1", spec: { platform } } as unknown as DeviceRecord], + devices: [{ id: "dev_1", physical, spec: { platform } } as unknown as DeviceRecord], leases: [ { deviceId: "dev_1", id: "L-1" } as unknown as LeaseRecord, { deviceId: "dev_1", id: "L-2" } as unknown as LeaseRecord, @@ -71,7 +92,7 @@ async function setup(platform = "android"): Promise<{ }, registry, }); - return { deviceTcp, worker }; + return { clock, deviceTcp, worker }; } async function attach(worker: WorkerModule, leaseId = "L-1"): Promise { @@ -85,87 +106,143 @@ async function attach(worker: WorkerModule, leaseId = "L-1"): Promise { - it("answers HELLO with READY, announces a device connection as OPEN and carries what the device writes as DATA", async () => { - const { deviceTcp, worker } = await setup(); - const socket = await attach(worker); +async function carriesOneTunnel(): Promise { + const { deviceTcp, worker } = await setup(); + const socket = await attach(worker); + + socket.receive(hello({ devicePort: 5173, kind: "reverse" })); + await vi.waitFor(() => + expect(frames(socket)).toEqual([ + { body: '{"tunnels":[{"kind":"reverse","devicePort":5173}]}', conn: 0, tag: 0x81 }, + ]), + ); + expect(deviceTcp.reversed).toEqual([5173]); + + const device = deviceTcp.connect(5173); + await vi.waitFor(() => + expect(frames(socket).at(-1)).toEqual({ + body: '{"kind":"reverse","devicePort":5173}', + conn: 1, + tag: 0x02, + }), + ); + device.send("from the device"); + await vi.waitFor(() => + expect(frames(socket).at(-1)).toEqual({ body: "from the device", conn: 1, tag: 0x03 }), + ); +} - socket.receive(hello({ devicePort: 5173, kind: "reverse" })); - await vi.waitFor(() => - expect(frames(socket)).toEqual([ - { body: '{"tunnels":[{"kind":"reverse","devicePort":5173}]}', conn: 0, tag: 0x81 }, - ]), - ); - expect(deviceTcp.reversed).toEqual([5173]); +async function halfClosesAndLimitsConnections(): Promise { + const { deviceTcp, worker } = await setup(); + const socket = await attach(worker); + socket.receive( + hello({ devicePort: 1024, kind: "reverse" }, { devicePort: 65535, kind: "reverse" }), + ); + await vi.waitFor(() => + expect(frames(socket)).toEqual([ + { + body: '{"tunnels":[{"kind":"reverse","devicePort":1024},{"kind":"reverse","devicePort":65535}]}', + conn: 0, + tag: 0x81, + }, + ]), + ); + const first = deviceTcp.connect(1024); + const second = deviceTcp.connect(65535); + await vi.waitFor(() => + expect(frames(socket).slice(1)).toEqual([ + { body: '{"kind":"reverse","devicePort":1024}', conn: 1, tag: 0x02 }, + { body: '{"kind":"reverse","devicePort":65535}', conn: 3, tag: 0x02 }, + ]), + ); + + first.end(); + await vi.waitFor(() => expect(frames(socket).at(-1)).toEqual({ body: "", conn: 1, tag: 0x05 })); + expect(first.closed).toBe(false); + socket.receive(frame(0x03, 1, "after the device's END")); + await vi.waitFor(() => expect(first.writtenText()).toBe("after the device's END")); + expect(first.writeEnded).toBe(false); + socket.receive(frame(0x05, 1)); + await vi.waitFor(() => expect(first.writeEnded).toBe(true)); + await vi.waitFor(() => expect(first.closed).toBe(true)); + expect(second.writeEnded).toBe(false); + second.send("the other tunnel is untouched"); + await vi.waitFor(() => + expect(frames(socket).at(-1)).toEqual({ + body: "the other tunnel is untouched", + conn: 3, + tag: 0x03, + }), + ); + + const opens = () => frames(socket).filter((sent) => sent.tag === 0x02).length; + const peers = Array.from({ length: 255 }, () => deviceTcp.connect(1024)); + await vi.waitFor(() => expect(opens()).toBe(257)); + expect(peers.every((peer) => !peer.closed)).toBe(true); + const past = deviceTcp.connect(1024); + await vi.waitFor(() => expect(past.closed).toBe(true)); + expect(opens()).toBe(257); + + socket.receive(frame(0x06, 3, '{"reason":"done"}')); + await vi.waitFor(() => expect(second.closed).toBe(true)); + const after = deviceTcp.connect(1024); + await vi.waitFor(() => expect(opens()).toBe(258)); + expect(after.closed).toBe(false); +} - const device = deviceTcp.connect(5173); - await vi.waitFor(() => - expect(frames(socket).at(-1)).toEqual({ - body: '{"kind":"reverse","devicePort":5173}', - conn: 1, - tag: 0x02, - }), - ); - device.send("from the device"); - await vi.waitFor(() => - expect(frames(socket).at(-1)).toEqual({ body: "from the device", conn: 1, tag: 0x03 }), - ); - }); +async function pausesOnlyTheConnectionWithoutCredit(): Promise { + const { deviceTcp, worker } = await setup(); + const socket = await attach(worker); + socket.receive(hello({ devicePort: 5173, kind: "reverse" })); + await vi.waitFor(() => expect(frames(socket)).toHaveLength(1)); + const first = deviceTcp.connect(5173); + const second = deviceTcp.connect(5173); + await vi.waitFor(() => + expect(frames(socket).map((sent) => sent.tag)).toEqual([0x81, 0x02, 0x02]), + ); + + socket.receive(frame(0x03, 1, "to the device")); + await vi.waitFor(() => expect(first.writtenText()).toBe("to the device")); + await vi.waitFor(() => + expect(socket.sent.at(-1)).toEqual(Uint8Array.from([0x04, 0, 0, 0, 1, 0, 0, 0, 13])), + ); + + first.send(new Uint8Array(300_000)); + await vi.waitFor(() => expect(sentData(socket, 1)).toBe(262_144)); + second.send("still flowing"); + await vi.waitFor(() => expect(sentData(socket, 3)).toBe(13)); + expect(sentData(socket, 1)).toBe(262_144); + + socket.receive(Uint8Array.from([0x04, 0, 0, 0, 1, 0, 0x01, 0x86, 0xa0])); + await vi.waitFor(() => expect(sentData(socket, 1)).toBe(300_000)); + expect(frames(socket).every((sent) => sent.tag !== 0x03 || sent.body.length <= 65_536)).toBe( + true, + ); +} - it("serves two tunnels, half-closes with END from each side, and closes a device connection past 256 open", async () => { - const { deviceTcp, worker } = await setup(); - const socket = await attach(worker); - socket.receive( - hello({ devicePort: 1024, kind: "reverse" }, { devicePort: 65535, kind: "reverse" }), - ); - await vi.waitFor(() => - expect(frames(socket)).toEqual([ - { - body: '{"tunnels":[{"kind":"reverse","devicePort":1024},{"kind":"reverse","devicePort":65535}]}', - conn: 0, - tag: 0x81, - }, - ]), - ); - const first = deviceTcp.connect(1024); - const second = deviceTcp.connect(65535); - await vi.waitFor(() => - expect(frames(socket).slice(1)).toEqual([ - { body: '{"kind":"reverse","devicePort":1024}', conn: 1, tag: 0x02 }, - { body: '{"kind":"reverse","devicePort":65535}', conn: 3, tag: 0x02 }, - ]), - ); +describe("a worker's tunnel socket", () => { + it("opens the tunnel socket on a lone worker: answers HELLO with READY, announces device connections as OPEN, carries bytes both ways under credit, half-closes with END from each side, closes the 257th connection, pauses only the connection whose reader grants no credit, and refuses a lease that is gone", async () => { + await carriesOneTunnel(); + await halfClosesAndLimitsConnections(); + await pausesOnlyTheConnectionWithoutCredit(); + + const exact = await setup(); + const padded = `{"tunnels":[{"kind":"reverse","devicePort":5173}]}`.padEnd(4096, " "); + expect(new TextEncoder().encode(padded)).toHaveLength(4096); + const socket = await attach(exact.worker); + socket.receive(frame(0x01, 0, padded)); + await vi.waitFor(() => expect(frames(socket).map((sent) => sent.tag)).toEqual([0x81])); + expect(socket.closed).toBeUndefined(); - first.end(); - await vi.waitFor(() => expect(frames(socket).at(-1)).toEqual({ body: "", conn: 1, tag: 0x05 })); - socket.receive(frame(0x03, 1, "after the device's END")); - await vi.waitFor(() => expect(first.writtenText()).toBe("after the device's END")); - expect(first.writeEnded).toBe(false); - socket.receive(frame(0x05, 1)); - await vi.waitFor(() => expect(first.writeEnded).toBe(true)); - expect(second.writeEnded).toBe(false); - second.send("the other tunnel is untouched"); - await vi.waitFor(() => - expect(frames(socket).at(-1)).toEqual({ - body: "the other tunnel is untouched", - conn: 3, - tag: 0x03, - }), + const gone = await exact.worker.socket?.open(new Request("http://simlock/tunnel"), IDENTITY, { + deviceId: "dev_1", + id: "L-gone", + }); + expect(gone).toBeInstanceOf(Response); + expect((gone as Response).status).toBe(404); + expect(((await (gone as Response).json()) as { error: { code: string } }).error.code).toBe( + "UNKNOWN_LEASE", ); - - const opens = () => frames(socket).filter((sent) => sent.tag === 0x02).length; - const peers = Array.from({ length: 255 }, () => deviceTcp.connect(1024)); - await vi.waitFor(() => expect(opens()).toBe(257)); - expect(peers.every((peer) => !peer.closed)).toBe(true); - const past = deviceTcp.connect(1024); - await vi.waitFor(() => expect(past.closed).toBe(true)); - expect(opens()).toBe(257); - - socket.receive(frame(0x06, 3, '{"reason":"done"}')); - await vi.waitFor(() => expect(second.closed).toBe(true)); - const after = deviceTcp.connect(1024); - await vi.waitFor(() => expect(opens()).toBe(258)); - expect(after.closed).toBe(false); }); it("refuses a HELLO that cannot be met whole with REFUSED and close 4003, and leaves nothing it named set up", async () => { @@ -183,7 +260,7 @@ describe("a worker's tunnel socket", () => { }, { code: "TUNNEL_LIMIT", - message: "the lease already has 9 tunnels; at most 8", + message: "the lease already has 0 tunnels; at most 8", tunnels: Array.from({ length: 9 }, (_, index) => reverse(5000 + index)), }, { @@ -193,38 +270,62 @@ describe("a worker's tunnel socket", () => { }, { code: "TUNNEL_UNSUPPORTED", - message: "ios devices take no tunnel", + message: "the lease is on an iOS simulator; tunnels need an Android emulator or phone", + platform: "ios", + tunnels: [reverse(5173)], + }, + { + code: "TUNNEL_UNSUPPORTED", + message: "the lease is on an iPhone; tunnels need an Android emulator or phone", + physical: true, platform: "ios", tunnels: [reverse(5173)], }, { code: "TUNNEL_PORT_IN_USE", failures: new Map([ - [5174, new DeviceTcpError("TUNNEL_PORT_IN_USE", "port 5174 is reversed")], + [ + 5174, + new DeviceTcpError( + "TUNNEL_PORT_IN_USE", + "reverse 5174: the device port is already reversed; remove that rule first", + ), + ], ]), - message: "port 5174 is reversed", + message: "reverse 5174: the device port is already reversed; remove that rule first", tunnels: [reverse(5173), reverse(5174)], }, { code: "TUNNEL_FAILED", - failures: new Map([[5174, new DeviceTcpError("TUNNEL_FAILED", "device offline")]]), - message: "device offline", + failures: new Map([ + [5174, new DeviceTcpError("TUNNEL_FAILED", "reverse 5174: device offline")], + ]), + message: "reverse 5174: device offline", tunnels: [reverse(5173), reverse(5174)], }, { code: "TUNNEL_FAILED", failures: new Map([[5174, new Error("adb exploded")]]), - message: "adb exploded", + message: "reverse 5174: adb exploded", + tunnels: [reverse(5173), reverse(5174)], + }, + { + code: "TUNNEL_FAILED", + failures: new Map([ + [5174, new DeviceTcpError("TUNNEL_FAILED", `reverse 5174: ${"x".repeat(300)}`)], + ]), + message: `reverse 5174: ${"x".repeat(300)}`, + reason: `reverse 5174: ${"x".repeat(109)}`, tunnels: [reverse(5173), reverse(5174)], }, ]; for (const refused of cases) { - const { deviceTcp, worker } = await setup(refused.platform); + const { deviceTcp, worker } = await setup(refused.platform, refused.physical); for (const [port, failure] of refused.failures ?? []) deviceTcp.failures.set(port, failure); const socket = await attach(worker); socket.receive(hello(...refused.tunnels)); await vi.waitFor(() => - expect(socket.closed).toEqual({ code: 4003, reason: refused.message }), + expect(socket.closed).toEqual({ code: 4003, reason: refused.reason ?? refused.message }), ); expect(frames(socket)).toEqual([ { @@ -247,7 +348,7 @@ describe("a worker's tunnel socket", () => { { body: JSON.stringify({ code: "TUNNEL_LIMIT", - message: "the lease already has 9 tunnels; at most 8", + message: "the lease already has 4 tunnels; at most 8", }), conn: 0, tag: 0x82, @@ -259,36 +360,6 @@ describe("a worker's tunnel socket", () => { expect(deviceTcp.reversed).toEqual([5001, 5002, 5003, 5004]); }); - it("carries bytes both ways under a 262144-byte window per direction, and a reader that grants no credit pauses only its own connection", async () => { - const { deviceTcp, worker } = await setup(); - const socket = await attach(worker); - socket.receive(hello({ devicePort: 5173, kind: "reverse" })); - await vi.waitFor(() => expect(frames(socket)).toHaveLength(1)); - const first = deviceTcp.connect(5173); - const second = deviceTcp.connect(5173); - await vi.waitFor(() => - expect(frames(socket).map((sent) => sent.tag)).toEqual([0x81, 0x02, 0x02]), - ); - - socket.receive(frame(0x03, 1, "to the device")); - await vi.waitFor(() => expect(first.writtenText()).toBe("to the device")); - await vi.waitFor(() => - expect(socket.sent.at(-1)).toEqual(Uint8Array.from([0x04, 0, 0, 0, 1, 0, 0, 0, 13])), - ); - - first.send(new Uint8Array(300_000)); - await vi.waitFor(() => expect(sentData(socket, 1)).toBe(262_144)); - second.send("still flowing"); - await vi.waitFor(() => expect(sentData(socket, 3)).toBe(13)); - expect(sentData(socket, 1)).toBe(262_144); - - socket.receive(Uint8Array.from([0x04, 0, 0, 0, 1, 0, 0x01, 0x86, 0xa0])); - await vi.waitFor(() => expect(sentData(socket, 1)).toBe(300_000)); - expect(frames(socket).every((sent) => sent.tag !== 0x03 || sent.body.length <= 65_536)).toBe( - true, - ); - }); - it("refuses a bad frame with BAD_REQUEST and close 4003, while a frame for an already closed connection is ignored and other connections go on", async () => { const tunnel = { devicePort: 5173, kind: "reverse" }; const credit = (conn: number, granted: number): Uint8Array => { @@ -377,6 +448,30 @@ describe("a worker's tunnel socket", () => { socket.receive(bigData(1)); }, }, + { + message: "CREDIT is 4 bytes", + ready: true, + send: (socket) => socket.receive(Uint8Array.of(0x04, 0, 0, 0, 1, 0, 0)), + }, + { + message: "CREDIT is 4 bytes", + ready: true, + send: (socket) => socket.receive(Uint8Array.of(0x04, 0, 0, 0, 1, 0, 0, 0, 1, 0)), + }, + { + message: "DATA is 1 to 65536 bytes", + ready: true, + send: (socket) => socket.receive(frame(0x03, 1)), + }, + { + message: "DATA is 1 to 65536 bytes", + ready: true, + send: (socket) => { + socket.receive(bigData(1)); + expect(socket.closed).toBeUndefined(); + socket.receive(oversizeData(1)); + }, + }, { message: "connection 99 was never opened", ready: true, @@ -438,23 +533,36 @@ describe("a worker's tunnel socket", () => { expect(frames(socket).at(-1)).toEqual({ body: "still here", conn: 3, tag: 0x03 }), ); expect(socket.closed).toBeUndefined(); + + going.writeFailure = new Error("the device socket broke"); + socket.receive(frame(0x03, 3, "into a broken socket")); + await vi.waitFor(() => + expect(frames(socket).at(-1)).toEqual({ + body: '{"reason":"the device connection failed"}', + conn: 3, + tag: 0x06, + }), + ); + expect(going.closed).toBe(true); + expect(socket.closed).toBeUndefined(); }); it("removes the tunnel's rules and closes its connections when the socket closes, the lease ends or the daemon stops, and keeps going when a removal fails", async () => { const tunnel = { devicePort: 5173, kind: "reverse" }; async function open(): Promise<{ + readonly clock: FakeClock; readonly deviceTcp: FakeDeviceTcp; readonly worker: WorkerModule; readonly socket: MemoryLeaseSocket; readonly device: ReturnType; }> { - const { deviceTcp, worker } = await setup(); + const { clock, deviceTcp, worker } = await setup(); const socket = await attach(worker); socket.receive(hello(tunnel)); await vi.waitFor(() => expect(frames(socket)).toHaveLength(1)); const device = deviceTcp.connect(5173); await vi.waitFor(() => expect(frames(socket)).toHaveLength(2)); - return { device, deviceTcp, socket, worker }; + return { clock, device, deviceTcp, socket, worker }; } const client = await open(); @@ -470,16 +578,24 @@ describe("a worker's tunnel socket", () => { await vi.waitFor(() => expect(frames(again).map((sent) => sent.tag)).toEqual([0x81])); const ended = await open(); - await ended.worker.hooks?.beforeDeviceReclaim?.( - { - deviceId: "dev_1", - leaseId: "L-1", - ownerId: "tok_holder", - platform: "android", - reason: "expired", - }, - new AbortController().signal, - ); + let releaseRemoval: () => void = () => undefined; + ended.deviceTcp.closeGate = new Promise((resolve) => { + releaseRemoval = resolve; + }); + let returned = false; + const hook = ended.worker.hooks + ?.beforeDeviceReclaim?.(ending("expired"), new AbortController().signal) + .then(() => { + returned = true; + }); + await vi.waitFor(() => expect(ended.device.closed).toBe(true)); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect({ reversed: ended.deviceTcp.reversed, returned }).toEqual({ + reversed: [5173], + returned: false, + }); + releaseRemoval(); + await hook; expect(ended.deviceTcp.reversed).toEqual([]); expect(ended.device.closed).toBe(true); expect(ended.socket.closed).toEqual({ code: 4001, reason: "expired" }); @@ -523,6 +639,40 @@ describe("a worker's tunnel socket", () => { expect(failing.socket.closed).toEqual({ code: 4001, reason: "killed" }); expect(failing.device.closed).toBe(true); + const twoRules = await setup(); + const both = await attach(twoRules.worker); + both.receive( + hello({ devicePort: 5173, kind: "reverse" }, { devicePort: 5174, kind: "reverse" }), + ); + await vi.waitFor(() => expect(frames(both)).toHaveLength(1)); + let releaseFirst: () => void = () => undefined; + twoRules.deviceTcp.closeGate = new Promise((resolve) => { + releaseFirst = resolve; + }); + const midway = new AbortController(); + const interrupted = twoRules.worker.hooks?.beforeDeviceReclaim?.( + ending("expired"), + midway.signal, + ); + await vi.waitFor(() => expect(both.closed).toEqual({ code: 4001, reason: "expired" })); + midway.abort(); + releaseFirst(); + await interrupted; + expect(twoRules.deviceTcp.reversed).toEqual([5174]); + + const hung = await open(); + hung.deviceTcp.closeGate = new Promise(() => undefined); + let hungReturned = false; + void hung.worker.hooks + ?.beforeDeviceReclaim?.(ending("expired"), new AbortController().signal) + .then(() => { + hungReturned = true; + }); + await vi.waitFor(() => expect(hung.device.closed).toBe(true)); + expect(hungReturned).toBe(false); + hung.clock.advance(10_000); + await vi.waitFor(() => expect(hungReturned).toBe(true)); + const reclaimed = await open(); const aborted = new AbortController(); aborted.abort(); @@ -538,6 +688,7 @@ describe("a worker's tunnel socket", () => { ); expect(reclaimed.socket.closed).toEqual({ code: 4001, reason: "device-lost" }); expect(reclaimed.deviceTcp.reversed).toEqual([5173]); + expect(reclaimed.deviceTcp.connect(5173).closed).toBe(true); const racing = await setup(); let release: () => void = () => undefined; @@ -550,5 +701,20 @@ describe("a worker's tunnel socket", () => { release(); await vi.waitFor(() => expect(racing.deviceTcp.reverseLog).toEqual([5173])); await vi.waitFor(() => expect(racing.deviceTcp.reversed).toEqual([])); + + const abortedRace = await setup(); + let releaseReverse: () => void = () => undefined; + abortedRace.deviceTcp.gate = new Promise((resolve) => { + releaseReverse = resolve; + }); + const pending = await attach(abortedRace.worker); + pending.receive(hello(tunnel)); + const stopping = new AbortController(); + stopping.abort(); + await abortedRace.worker.hooks?.beforeDeviceReclaim?.(ending("device-lost"), stopping.signal); + releaseReverse(); + await vi.waitFor(() => expect(abortedRace.deviceTcp.reverseLog).toEqual([5173])); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(abortedRace.deviceTcp.reversed).toEqual([5173]); }); }); diff --git a/src/tunnel/worker.ts b/src/tunnel/worker.ts index 9d59b7fea..7b8d78117 100644 --- a/src/tunnel/worker.ts +++ b/src/tunnel/worker.ts @@ -5,7 +5,11 @@ import { unknownLease, upgradeRequired } from "./refusal.js"; import { createTunnelSessions } from "./sessions.js"; export function createWorker(ctx: WorkerContext): WorkerModule { - const sessions = createTunnelSessions({ deviceTcp: ctx.deviceTcp, logger: ctx.logger }); + const sessions = createTunnelSessions({ + clock: ctx.clock, + deviceTcp: ctx.deviceTcp, + logger: ctx.logger, + }); return { capability: { name: ctx.name, read: () => Promise.resolve({ state: "available" }) }, hooks: { diff --git a/website/src/content/docs/docs/reference/configuration.mdx b/website/src/content/docs/docs/reference/configuration.mdx index 29cc04886..c7a47886d 100644 --- a/website/src/content/docs/docs/reference/configuration.mdx +++ b/website/src/content/docs/docs/reference/configuration.mdx @@ -314,7 +314,7 @@ A name Simlock does not know is warned about and ignored. | `capabilities.agent-device.ios.provisioningProfile` | non-empty string | not set | Provisioning profile for manual signing of the iPhone runner. Setting it switches agent-device to manual signing. Passed to the phone daemon. | Worker | | `capabilities.agent-device.ios.signingIdentity` | non-empty string | not set | Code-signing identity for manual signing of the iPhone runner. Passed to the phone daemon. | Worker | | `capabilities.input.enabled` | boolean | `false` | Let a lease's holder send taps and keys to its device over `WS /v1/leases/{id}/input`. On a gateway: pass each input socket through to the lease's worker, which needs it on too. | Both | -| `capabilities.tunnel.enabled` | boolean | `false` | Let a lease's holder open `WS /v1/leases/{id}/tunnel` and reverse device ports to its own machine. Only a lone worker serves it for now. The worker reserves loopback ports 47000-47999 for tunnels, and a rule that `adb reverse` points into that range is removed when the worker starts, so keep your own rules out of it. | Worker | +| `capabilities.tunnel.enabled` | boolean | `false` | Let a lease's holder open `WS /v1/leases/{id}/tunnel` and reverse device ports to its own machine. Only a lone worker serves it for now. The worker reserves loopback ports 47000-47999 for tunnels, and a rule that `adb reverse` points into that range is removed when the worker starts, or, on a device that is leased then, when its lease ends, so keep your own rules out of it. | Worker | | `capabilities.stream.enabled` | boolean | `false` | Let people watch a running device's screen. On a gateway: pass each stream through from the worker. | Both | | `capabilities.stream.fps` | integer `1`–`60` | `30` | Highest frame rate. A still screen sends far fewer frames. | Worker | | `capabilities.stream.maxDimension` | integer `96`–`4096` | `720` | Longest side of the picture, in pixels. The setting that changes bandwidth most. | Worker | diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index 16c63bc18..9aaf6134f 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -80,7 +80,7 @@ A lease's tunnel socket (`GET /v1/leases/{id}/tunnel`, on a worker with `capabil | --- | --- | --- | --- | --- | | `TUNNEL_UNSUPPORTED` | 1 | 422 | The lease is on an iOS simulator or an iPhone, or the tunnel is a `forward` tunnel, which is not available yet. | Use an Android emulator or phone, and `reverse` tunnels. | | `TUNNEL_PORT_IN_USE` | 1 | 409 | The device port is already reversed on the device, for example by an `adb reverse` run through `device.exec`. | Remove that rule first. | -| `TUNNEL_BAD_PORT` | 1 | 422 | A device port is not an integer from 1024 to 65535. | Name a port in that range. | +| `TUNNEL_BAD_PORT` | 1 | 422 | A device port is an integer outside 1024 to 65535. A port that is not an integer at all is refused `BAD_REQUEST`. | Name a port in that range. | | `TUNNEL_LIMIT` | 1 | 409 | The lease would have more than 8 tunnels across its sockets. | Close a tunnel first. | | `TUNNEL_FAILED` | 1 | 502 | `adb` could not set the tunnel up, or the worker has no free loopback port in its reserved range. The message carries adb's own words. | Read the message; try again. | | `TUNNEL_UNAVAILABLE` | 1 | 503 | A gateway's worker has tunnels off. | Turn on `capabilities.tunnel.enabled` on the worker. | From c19bc1502a7ca5e06cb8ad288d39f217852d1f12 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:18:04 -0300 Subject: [PATCH 096/103] chore(tunnel): Fallow findings of the review fixes (#1112) Co-Authored-By: Claude Sonnet 5.5 --- src/drivers/android/index.test.ts | 1 + src/tunnel/sessions.ts | 13 +++++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 62cc2eaf3..506a6e356 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -3406,6 +3406,7 @@ describe("AndroidDriver deviceTcp", () => { return { driver, listeners, runner }; } + // fallow-ignore-next-line complexity -- one Tests line: the driver's reverse, its close and each refusal are the cases of one scenario. it("sets adb reverse --no-rebind to a loopback listener in 47000-47999 and removes it on close, as an emulator or a phone, keeps the port of a rule that could not be removed until the device's reclaim, and refuses with TUNNEL_PORT_IN_USE when adb cannot rebind and TUNNEL_FAILED for any other adb failure or when every tunnel port is busy", async () => { const { driver, listeners, runner } = await driverWith([ { match: adb("-P", "5038", "-s", "emulator-5586", ...reverseArgs(47_002)), result: ok }, diff --git a/src/tunnel/sessions.ts b/src/tunnel/sessions.ts index 0e2537e57..9c1d65328 100644 --- a/src/tunnel/sessions.ts +++ b/src/tunnel/sessions.ts @@ -203,6 +203,14 @@ export function createTunnelSessions(options: { connections.delete(conn); } + // why: a connection a RESET or a failure already closed sends no END for the device's end. + function deviceEnded(conn: number, connection: Connection): void { + if (connection.closed) return; + socket.send(encodeTunnelFrame(TUNNEL_TAG.end, conn)); + connection.deviceEnded = true; + settle(conn, connection); + } + // why: a connection reads from its device stream only while the caller has granted window, so a slow reader stops its own connection and no other. async function pump(conn: number, connection: Connection): Promise { const reader = connection.stream.readable.getReader(); @@ -217,10 +225,7 @@ export function createTunnelSessions(options: { if (pending === undefined) { const step = await reader.read(); if (step.done) { - if (connection.closed) return; - socket.send(encodeTunnelFrame(TUNNEL_TAG.end, conn)); - connection.deviceEnded = true; - settle(conn, connection); + deviceEnded(conn, connection); return; } pending = step.value; From dedafb10019398cbfa3642be649b6e1421bcf840 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:20:56 -0300 Subject: [PATCH 097/103] test: drop a leftover debug assertion from the MCP smoke table (#1108) Co-Authored-By: Claude Sonnet 5.5 --- src/mcp/server.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index d27745835..177507238 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -237,7 +237,6 @@ describe("MCP server (smoke)", () => { client.calls.length = 0; const refused = await call(mcpClient, tool, wrong); expect(refused.isError).toBe(true); - expect(text(refused)).toBe("DBG"); expect(text(refused)).toContain("Input validation error"); expect(client.calls).toEqual([]); } finally { From 53012f8b58faf9caa78f23a41236afc5ed45f703 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:25:24 -0300 Subject: [PATCH 098/103] fix(modules): drop the pipe type from the index now that only the relay channel names it (#1113) Co-Authored-By: Claude Sonnet 5.5 --- src/modules/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/modules/index.ts b/src/modules/index.ts index 13bbbf208..adf51bbaa 100644 --- a/src/modules/index.ts +++ b/src/modules/index.ts @@ -24,7 +24,6 @@ export type { ModuleRegistryView, ModuleRelayTarget, ModuleRelayTwoWayTarget, - ModuleTwoWayPipe, ModuleTwoWayRelay, ModuleTokenRecord, ModuleTokens, From eb7baaf23d4ec731b4d85af57381db9af2721945 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:25:34 -0300 Subject: [PATCH 099/103] test(tunnel): the audit's missing cases, safe frame JSON and the http-json timing bound (#1114) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/commands/tunnel.ts | 34 ++++-- src/cli/tunnel.test.ts | 162 ++++++++++++++++++++++++++--- src/ports/http-json.test.ts | 2 +- src/ports/http-json.timing.test.ts | 32 ++++++ src/ports/websocket-client.test.ts | 16 +++ 5 files changed, 217 insertions(+), 29 deletions(-) create mode 100644 src/ports/http-json.timing.test.ts diff --git a/src/cli/commands/tunnel.ts b/src/cli/commands/tunnel.ts index 1c0299072..8b186c4b8 100644 --- a/src/cli/commands/tunnel.ts +++ b/src/cli/commands/tunnel.ts @@ -26,6 +26,7 @@ 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; @@ -100,6 +101,22 @@ function checkedToken(text: string | undefined): string { 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; } @@ -296,13 +313,14 @@ async function openSocket( } function frameFailure(frame: { payload: Uint8Array }, leaseId: string): TunnelFailure { - const refusal: unknown = JSON.parse(new TextDecoder().decode(frame.payload)); + 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}: ${String(field(refusal, "message"))}`, + `Lease ${leaseId}: ${typeof message === "string" ? message : "the worker refused the tunnel"}`, ERROR_TABLE[known].cliExitCode, ); } @@ -393,9 +411,7 @@ function serve( const opened = frame.tag === TUNNEL_TAG.open ? specs.find( - ({ devicePort }) => - field(JSON.parse(new TextDecoder().decode(frame.payload)), "devicePort") === - devicePort, + ({ devicePort }) => field(payloadJson(frame.payload), "devicePort") === devicePort, ) : undefined; handled = handled.then(() => relay(opened, frame)).catch(() => undefined); @@ -430,13 +446,9 @@ async function run( 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, - typeof lease === "string" ? lease : undefined, - ); + const leaseId = await leaseToUse(environment, base, secret, named); const socket = await openSocket(environment, base, secret, leaseId); return await serve(environment, socket, specs, leaseId); } catch (error) { diff --git a/src/cli/tunnel.test.ts b/src/cli/tunnel.test.ts index d4fbd5c9c..a0b5c37d9 100644 --- a/src/cli/tunnel.test.ts +++ b/src/cli/tunnel.test.ts @@ -1,6 +1,11 @@ import { describe, expect, it, vi } from "vitest"; -import { TUNNEL_TAG, decodeTunnelFrame, encodeTunnelFrame } from "../contract/index.js"; +import { + TUNNEL_MAX_DATA_BYTES, + TUNNEL_TAG, + decodeTunnelFrame, + encodeTunnelFrame, +} from "../contract/index.js"; import { buildCliEnvironment, runCli } from "./index.js"; import { FakeClock, @@ -88,15 +93,29 @@ describe("simlock tunnel that cannot run", () => { 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 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:"], @@ -129,10 +148,34 @@ describe("simlock tunnel that cannot run", () => { 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, message } of cases) { + for (const { argv, env, lease, message } of cases) { const cli = command(env ?? ENV); - const exit = cli.run(["tunnel", ...argv, "--lease", "L1"]); + const exit = cli.run(["tunnel", ...argv, "--lease", lease ?? "L1"]); await vi.waitFor(() => expect({ argv, err: cli.err.join("") }).not.toEqual({ argv, err: "" }), ); @@ -156,6 +199,11 @@ describe("simlock tunnel that runs", () => { 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)"], @@ -184,6 +232,11 @@ describe("simlock tunnel that runs", () => { 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)"], @@ -205,6 +258,15 @@ describe("simlock tunnel that runs", () => { 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"); @@ -247,7 +309,9 @@ describe("simlock tunnel that runs", () => { body: { leases }, status: 200, }); - expect(await cli.run(["tunnel", "reverse", "5173"])).toBe(2); + 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([]); } @@ -277,8 +341,8 @@ async function started(argv: readonly string[]) { 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 () => { - const quiet = await started(["reverse", "5173", "reverse", "6000"]); - quiet.cli.tcpStreams.refusedPorts.add(5173); + 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)); @@ -293,37 +357,40 @@ describe("simlock tunnel carrying connections", () => { .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: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:5173"]); + expect(warnings()).toEqual(["reverse 5173: nothing listening on localhost:5174"]); await opening(5, 6000); expect(warnings()).toEqual([ - "reverse 5173: nothing listening on localhost:5173", + "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:5173"); + 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); - const page = await started(["reverse", "5173"]); + 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 += 65_536) - local.send(response.subarray(at, at + 65_536)); + 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; @@ -336,7 +403,7 @@ describe("simlock tunnel carrying connections", () => { const drain = () => { const frames = sentFrames(page.cli); for (const frame of frames.slice(before)) { - if (frame.tag === TUNNEL_TAG.data) received.push(...frame.payload); + 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; @@ -358,6 +425,11 @@ describe("simlock tunnel carrying connections", () => { } 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); for (const size of [65_536, 30_000]) { page.peer.receive(encodeTunnelFrame(TUNNEL_TAG.data, 1, new Uint8Array(size))); @@ -371,11 +443,24 @@ describe("simlock tunnel carrying connections", () => { .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)); page.cli.signals.emit("SIGINT"); expect(await page.exit).toBe(0); }); }); +// 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)); +} + function refusedFrame(code: string, message: string): Uint8Array { return encodeTunnelFrame(TUNNEL_TAG.refused, 0, JSON.stringify({ code, message })); } @@ -391,6 +476,7 @@ function line(cli: ReturnType): unknown { async function upgradeRefusals(): Promise { const upgrades: readonly { readonly refusal: WebSocketRefusedError; + readonly exit?: number; readonly code: string; readonly message: string; }[] = [ @@ -423,11 +509,25 @@ async function upgradeRefusals(): Promise { 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, message, refusal } of upgrades) { + 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(1); + expect(await cli.run(["tunnel", "reverse", "5173", "--lease", "L1"])).toBe(exit ?? 1); expect(line(cli)).toEqual(errorBody(code, message)); } } @@ -448,6 +548,11 @@ async function lookupFailures(): Promise { 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", @@ -470,6 +575,19 @@ async function refusalFrame(): Promise { 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 { @@ -502,11 +620,15 @@ async function silentSocket(): Promise { silent.cli.clock.advance(30_000); silent.peer.ping(); silent.cli.clock.advance(44_999); + await settle(); expect(silent.cli.err).toEqual([]); silent.peer.receive(open(1, 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(line(silent.cli)).toEqual( errorBody("TUNNEL_DISCONNECTED", "Lease L1: nothing was heard from the worker for 45 s"), @@ -522,8 +644,11 @@ async function noReadySocket(): Promise { 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(line(noReady)).toEqual( errorBody("TUNNEL_DISCONNECTED", "Lease L1: no READY from the worker within 90 s"), @@ -536,6 +661,7 @@ async function ctrlC(): Promise { idle.cli.clock.advance(15_000); idle.peer.ping(); } + await settle(); expect(idle.cli.err).toEqual([]); expect(idle.peer.closedWith).toBeUndefined(); idle.peer.silentOnClose = true; @@ -546,9 +672,11 @@ async function ctrlC(): Promise { settled = true; }); idle.cli.clock.advance(1_999); - await Promise.resolve(); + await settle(); expect(settled).toBe(false); idle.cli.clock.advance(1); + await settle(); + expect(settled).toBe(true); expect(await idle.exit).toBe(0); } diff --git a/src/ports/http-json.test.ts b/src/ports/http-json.test.ts index 8fa10b5a7..0f5961054 100644 --- a/src/ports/http-json.test.ts +++ b/src/ports/http-json.test.ts @@ -32,7 +32,7 @@ describe("FetchHttpJsonClient", () => { } 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 - 12) })); + 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 { 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/websocket-client.test.ts b/src/ports/websocket-client.test.ts index 2637df686..4cae0372e 100644 --- a/src/ports/websocket-client.test.ts +++ b/src/ports/websocket-client.test.ts @@ -42,8 +42,10 @@ describe("NodeWebSocketClientConnector", () => { 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; @@ -68,6 +70,20 @@ describe("NodeWebSocketClientConnector", () => { 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 late: [number, string][] = []; client.onClose((code, reason) => late.push([code, reason])); expect(late).toEqual([[4001, "got 2"]]); From 11d80a80f56fc40e45b7a709027ce14abfe3db88 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:39:05 -0300 Subject: [PATCH 100/103] fix(tunnel): close every connection and the socket on each exit, reset a connection whose write failed, refuse a --url with a path, query or fragment (#1114) Also corrects the comments on which ports files import ws. Co-Authored-By: Claude Sonnet 5.5 --- src/cli/AGENTS.md | 2 +- src/cli/commands/tunnel.ts | 41 ++++++++-- src/cli/tunnel.test.ts | 80 ++++++++++++++++++- src/ports/index.ts | 7 +- src/ports/upgrade-router.ts | 2 +- src/ports/uplink-websocket.ts | 6 +- .../src/content/docs/docs/reference/cli.mdx | 4 +- 7 files changed, 125 insertions(+), 17 deletions(-) diff --git a/src/cli/AGENTS.md b/src/cli/AGENTS.md index 14eb9b496..8e164c928 100644 --- a/src/cli/AGENTS.md +++ b/src/cli/AGENTS.md @@ -95,7 +95,7 @@ Surface: [cli.mdx](../../website/src/content/docs/docs/reference/cli.mdx) — ev 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) + 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` diff --git a/src/cli/commands/tunnel.ts b/src/cli/commands/tunnel.ts index 8b186c4b8..476faf900 100644 --- a/src/cli/commands/tunnel.ts +++ b/src/cli/commands/tunnel.ts @@ -91,6 +91,9 @@ function checkedUrl(text: string | undefined): string { parsed.protocol === "https:" || (parsed.protocol === "http:" && LOOPBACK_HOSTS.has(parsed.hostname)); if (!allowed || text.length > MAX_URL_CHARS) throw refusal; + if (parsed.pathname !== "/" || /[?#]/.test(text)) { + throw new UsageError("--url must be the worker's origin only: no path, query or fragment"); + } return text.replace(/\/$/, ""); } @@ -147,12 +150,20 @@ function relayConnections( }); 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; } } - socket.send(encodeTunnelFrame(TUNNEL_TAG.end, conn)); + 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); @@ -184,7 +195,8 @@ function relayConnections( if (frame.tag === TUNNEL_TAG.data) { connection.writes = connection.writes .then(() => connection.stream.write(frame.payload)) - .then(() => grant(frame.conn, frame.payload.length)); + .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, @@ -193,13 +205,15 @@ function relayConnections( ).getUint32(0); connection.wake?.(); } else if (frame.tag === TUNNEL_TAG.end) { - connection.writes = connection.writes.then(() => connection.stream.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); } }; - return async ( + const handle = async ( spec: ReverseSpec | undefined, frame: { tag: number; conn: number; payload: Uint8Array }, ): Promise => { @@ -210,6 +224,15 @@ function relayConnections( 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; @@ -343,10 +366,12 @@ function serve( }); // 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`)); }); @@ -363,13 +388,16 @@ function serve( 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, ""); if (failure === undefined) resolve(0); else reject(failure); } function stop(): void { if (finished) return; stopping = true; - environment.clock.setTimer(CLOSE_WAIT_MS, () => end(undefined)); + closeTimer = environment.clock.setTimer(CLOSE_WAIT_MS, () => end(undefined)); socket.close(CLOSE_NORMAL, ""); } environment.signals.on("SIGINT", stop); @@ -377,6 +405,7 @@ function serve( heard(); socket.onPing(heard); socket.onClose((code, reason) => { + socketClosed = true; if (stopping) { end(undefined); return; @@ -414,7 +443,7 @@ function serve( ({ devicePort }) => field(payloadJson(frame.payload), "devicePort") === devicePort, ) : undefined; - handled = handled.then(() => relay(opened, frame)).catch(() => undefined); + handled = handled.then(() => relay.handle(opened, frame)).catch(() => undefined); }); socket.send( encodeTunnelFrame( diff --git a/src/cli/tunnel.test.ts b/src/cli/tunnel.test.ts index a0b5c37d9..47e5a22c5 100644 --- a/src/cli/tunnel.test.ts +++ b/src/cli/tunnel.test.ts @@ -102,6 +102,13 @@ describe("simlock tunnel that cannot run", () => { 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; @@ -138,6 +145,21 @@ describe("simlock tunnel that cannot run", () => { 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" }, @@ -451,6 +473,30 @@ describe("simlock tunnel carrying connections", () => { expect(second?.closed).toBe(false); page.peer.receive(encodeTunnelFrame(TUNNEL_TAG.reset, 3)); await vi.waitFor(() => expect(second?.closed).toBe(true)); + + 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); }); @@ -461,6 +507,20 @@ 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 })); } @@ -570,8 +630,12 @@ async function lookupFailures(): Promise { 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"), ); @@ -609,8 +673,11 @@ async function lossesOfTheSocket(): Promise { ]; 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); } } @@ -622,7 +689,7 @@ async function silentSocket(): Promise { silent.cli.clock.advance(44_999); await settle(); expect(silent.cli.err).toEqual([]); - silent.peer.receive(open(1, 5173)); + const silentLocal = await withLocalConnection(silent.cli, silent.peer, 5173); silent.cli.clock.advance(44_999); await settle(); expect(silent.cli.err).toEqual([]); @@ -630,6 +697,9 @@ async function silentSocket(): Promise { 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.cli.clock.pendingTimerCount).toBe(0); expect(line(silent.cli)).toEqual( errorBody("TUNNEL_DISCONNECTED", "Lease L1: nothing was heard from the worker for 45 s"), ); @@ -650,6 +720,8 @@ async function noReadySocket(): Promise { await settle(); expect(noReady.err).toHaveLength(1); expect(await noReadyExit).toBe(1); + expect(quietPeer?.closedWith?.code).toBe(1000); + expect(noReady.clock.pendingTimerCount).toBe(0); expect(line(noReady)).toEqual( errorBody("TUNNEL_DISCONNECTED", "Lease L1: no READY from the worker within 90 s"), ); @@ -664,6 +736,7 @@ async function ctrlC(): Promise { 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); @@ -678,13 +751,18 @@ async function ctrlC(): Promise { await settle(); expect(settled).toBe(true); expect(await idle.exit).toBe(0); + expect(idleLocal.closed).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", () => { diff --git a/src/ports/index.ts b/src/ports/index.ts index bbf7eccec..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, 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 12a56a99a..aed71d257 100644 --- a/src/ports/uplink-websocket.ts +++ b/src/ports/uplink-websocket.ts @@ -1,7 +1,7 @@ /** - * 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, 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). diff --git a/website/src/content/docs/docs/reference/cli.mdx b/website/src/content/docs/docs/reference/cli.mdx index 54ece130c..625afb626 100644 --- a/website/src/content/docs/docs/reference/cli.mdx +++ b/website/src/content/docs/docs/reference/cli.mdx @@ -212,7 +212,7 @@ simlock tunnel reverse [:] [reverse ...] [--lease [:]` | 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`; at most 2048 characters. | `SIMLOCK_URL` | +| `--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`. @@ -724,7 +724,7 @@ 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. | 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:`. | — | From aeb76cf4e825566ce575451f22649cbf14eaee8f Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:41:34 -0300 Subject: [PATCH 101/103] refactor(tunnel): split checkedUrl and the carrying-connections test into helpers under the CRAP threshold (#1114) Co-Authored-By: Claude Sonnet 5.5 --- src/cli/commands/tunnel.ts | 16 ++- src/cli/tunnel.test.ts | 287 ++++++++++++++++++++----------------- 2 files changed, 165 insertions(+), 138 deletions(-) diff --git a/src/cli/commands/tunnel.ts b/src/cli/commands/tunnel.ts index 476faf900..76a6b1422 100644 --- a/src/cli/commands/tunnel.ts +++ b/src/cli/commands/tunnel.ts @@ -74,10 +74,7 @@ function parseReverses(words: readonly string[]): readonly ReverseSpec[] { const LOOPBACK_HOSTS: ReadonlySet = new Set(["127.0.0.1", "[::1]", "localhost"]); -function checkedUrl(text: string | undefined): string { - if (text === undefined || text === "") { - throw new UsageError("No worker URL: pass --url or set SIMLOCK_URL"); - } +function parsedUrl(text: string): URL { const refusal = new UsageError( "--url must be https://, or http:// only for 127.0.0.1, [::1] or localhost", ); @@ -91,9 +88,20 @@ function checkedUrl(text: string | undefined): string { 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(/\/$/, ""); } diff --git a/src/cli/tunnel.test.ts b/src/cli/tunnel.test.ts index 47e5a22c5..35ef3c672 100644 --- a/src/cli/tunnel.test.ts +++ b/src/cli/tunnel.test.ts @@ -12,6 +12,7 @@ import { FakeDaemonLauncher, FakeHttpJsonClient, FakeSystemStats, + FakeTcpPeer, FakeTcpStreamConnector, FakeWebSocketClientConnector, WebSocketRefusedError, @@ -361,144 +362,162 @@ async function started(argv: readonly string[]) { return { cli, exit, peer }; } -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 () => { - 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); - - 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); - - for (const size of [65_536, 30_000]) { - page.peer.receive(encodeTunnelFrame(TUNNEL_TAG.data, 1, new Uint8Array(size))); - } +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(local.written.map((chunk) => chunk.length)).toEqual([65_536, 30_000]), + 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(() => { - 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]); + drain(); + expect(received.length > have || ended).toBe(true); }); - 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)); - - 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); + } + 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); }); }); From 137b7dd88c9ae6f702b222ce46de041740470424 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 1 Nov 2026 18:08:08 +0100 Subject: [PATCH 102/103] fix(tunnel): terminate the socket after the 2 s Ctrl-C bound; name the connected URL when the connection is lost (#1114) --- src/cli/commands/tunnel.ts | 19 ++++++++++++------- src/cli/tunnel.test.ts | 6 +++++- src/ports/websocket-client.test.ts | 14 ++++++++++++++ src/ports/websocket-client.ts | 11 +++++++++++ 4 files changed, 42 insertions(+), 8 deletions(-) diff --git a/src/cli/commands/tunnel.ts b/src/cli/commands/tunnel.ts index 76a6b1422..13c0e3c9d 100644 --- a/src/cli/commands/tunnel.ts +++ b/src/cli/commands/tunnel.ts @@ -361,6 +361,7 @@ function serve( socket: WebSocketClient, specs: readonly ReverseSpec[], leaseId: string, + base: string, ): Promise { const warned = new Map(); const relay = relayConnections(socket, environment, (devicePort, callerPort) => { @@ -381,15 +382,15 @@ function serve( 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`)); + 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`)); + end(disconnected(`Lease ${leaseId}: nothing was heard from the worker for 45 s`), true); }); }; - function end(failure: TunnelFailure | undefined): void { + function end(failure: TunnelFailure | undefined, unresponsive = false): void { if (finished) return; finished = true; environment.signals.off("SIGINT", stop); @@ -398,14 +399,18 @@ function serve( if (silence !== undefined) environment.clock.cancel(silence); if (closeTimer !== undefined) environment.clock.cancel(closeTimer); relay.closeAll(); - if (!socketClosed) socket.close(CLOSE_NORMAL, ""); + 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)); + closeTimer = environment.clock.setTimer(CLOSE_WAIT_MS, () => end(undefined, true)); socket.close(CLOSE_NORMAL, ""); } environment.signals.on("SIGINT", stop); @@ -425,7 +430,7 @@ function serve( `Lease ${leaseId} ended: ${reason}`, ERROR_TABLE.TUNNEL_LEASE_ENDED.cliExitCode, ) - : disconnected(`Lease ${leaseId}: the connection to the worker was lost`), + : disconnected(`Lease ${leaseId}: the connection to ${base} was lost`), ); }); socket.onMessage((bytes) => { @@ -487,7 +492,7 @@ async function run( try { const leaseId = await leaseToUse(environment, base, secret, named); const socket = await openSocket(environment, base, secret, leaseId); - return await serve(environment, socket, specs, leaseId); + return await serve(environment, socket, specs, leaseId, base); } catch (error) { if (!(error instanceof TunnelFailure)) throw error; environment.stderr.write( diff --git a/src/cli/tunnel.test.ts b/src/cli/tunnel.test.ts index 35ef3c672..24f2a3cc9 100644 --- a/src/cli/tunnel.test.ts +++ b/src/cli/tunnel.test.ts @@ -686,7 +686,10 @@ async function lossesOfTheSocket(): Promise { }, ...[1011, 1001, 1006].map((code) => ({ drop: [code, ""] as [number, string], - error: errorBody("TUNNEL_DISCONNECTED", "Lease L1: the connection to the worker was lost"), + error: errorBody( + "TUNNEL_DISCONNECTED", + `Lease L1: the connection to ${ENV.SIMLOCK_URL} was lost`, + ), exit: 1, })), ]; @@ -771,6 +774,7 @@ async function ctrlC(): Promise { 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); } diff --git a/src/ports/websocket-client.test.ts b/src/ports/websocket-client.test.ts index 4cae0372e..3966f737e 100644 --- a/src/ports/websocket-client.test.ts +++ b/src/ports/websocket-client.test.ts @@ -84,6 +84,20 @@ describe("NodeWebSocketClientConnector", () => { 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 index 19d91e3d6..ecbd7bb70 100644 --- a/src/ports/websocket-client.ts +++ b/src/ports/websocket-client.ts @@ -19,6 +19,8 @@ export class WebSocketRefusedError extends Error { 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; @@ -65,6 +67,10 @@ class NodeWebSocketClient implements WebSocketClient { this.#socket.close(code, reason); } + terminate(): void { + this.#socket.terminate(); + } + onMessage(listener: (bytes: Uint8Array) => void): void { this.#messages.push(listener); } @@ -116,6 +122,7 @@ export class NodeWebSocketClientConnector implements WebSocketClientConnector { 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)[] = []; @@ -132,6 +139,10 @@ class FakeWebSocketPeer implements WebSocketClient { for (const listener of this.#closes) listener(code, reason); } + terminate(): void { + this.terminated = true; + } + onMessage(listener: (bytes: Uint8Array) => void): void { this.#messages.push(listener); } From 50c1f696c733e31ffac6bf25b9feaf0984149a3d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 1 Nov 2026 18:19:20 +0100 Subject: [PATCH 103/103] test(tunnel): the 45 s silence and 90 s no-READY ends terminate the socket (#1114) --- src/cli/tunnel.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cli/tunnel.test.ts b/src/cli/tunnel.test.ts index 24f2a3cc9..f4d0fc609 100644 --- a/src/cli/tunnel.test.ts +++ b/src/cli/tunnel.test.ts @@ -721,6 +721,7 @@ async function silentSocket(): Promise { 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"), @@ -743,6 +744,7 @@ async function noReadySocket(): Promise { 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"),