From 6a87186633787c6c76deb51507b80dcff054b898 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 00:51:34 -0300 Subject: [PATCH 01/31] 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 02/31] 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 21516b5767f4e33d8bea64e60193b6cadb9e6511 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 00:54:36 -0300 Subject: [PATCH 03/31] 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 04/31] 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 2084eab68ff183201f54e2441e66ee000bdc89fa Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:06:49 -0300 Subject: [PATCH 05/31] 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 06/31] 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 07/31] 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 0751cc129d8971e3730da2e5a7fee50d8997a1ac Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:09:00 -0300 Subject: [PATCH 08/31] 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 09/31] 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 746b8d011f463e422cce920d4be05b7ff61f95b3 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:10:46 -0300 Subject: [PATCH 10/31] 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 e330b80a5c4a3ac9a1565da7fe423786d8e89c94 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:13:32 -0300 Subject: [PATCH 11/31] 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 12/31] 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 38af91d9c929f114a01f3bee91bfc76848a6a1b6 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:18:36 -0300 Subject: [PATCH 13/31] 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 14/31] 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 075987923c1aee2a77d25a003064a8803913c72e Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:21:00 -0300 Subject: [PATCH 15/31] 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 16/31] 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 617b3dd7e70569409aa48f26ccad15c9f2f93eae Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:23:31 -0300 Subject: [PATCH 17/31] 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 29c7aec318e3db81d702988bd4d9c5c1530a2de0 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:24:24 -0300 Subject: [PATCH 18/31] 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 5a8d932e3afdf086faba5556bb8f1822dc20893a Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:27:59 -0300 Subject: [PATCH 19/31] 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 20/31] 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 12d19c766d4d6afbde51d3aa47cc729d01aa4ee7 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:32:21 -0300 Subject: [PATCH 21/31] 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 bc08674d6f3014402718679d48e86e14867dcbdb Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:32:44 -0300 Subject: [PATCH 22/31] 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 19d0ca403081fc033c97587f6222b6e5052a6c51 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:33:36 -0300 Subject: [PATCH 23/31] 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 10496974ed5c23df74aa3b4d27dfaa5dc3e9be5a Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:51:32 -0300 Subject: [PATCH 24/31] 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 22169a864944c31c56d2556fed466c64eeadf177 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:17:14 -0300 Subject: [PATCH 25/31] 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 26/31] 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 22f1d60d027132f73a1eb6d71485925c72086828 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 1 Nov 2026 17:04:27 +0100 Subject: [PATCH 27/31] fix(tunnel): the lease's end waits for a removal the socket's close began (#1112) --- src/tunnel/sessions.ts | 16 ++++++++++------ src/tunnel/worker.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/tunnel/sessions.ts b/src/tunnel/sessions.ts index 9c1d65328..e4f40edc4 100644 --- a/src/tunnel/sessions.ts +++ b/src/tunnel/sessions.ts @@ -151,7 +151,6 @@ export function createTunnelSessions(options: { 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()) { connection.closed = true; @@ -159,11 +158,16 @@ export function createTunnelSessions(options: { connection.wake?.(); } connections.clear(); - if (!removeRules) return; - // 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)); + try { + if (!removeRules) return; + // 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)); + } + } finally { + // why: the session stays listed until its removals are done, so the lease's end finds a removal the socket's close began and waits for it before reclaim. + sessions.get(leaseId)?.delete(session); } })(); return finished; diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index 8f5868678..27ea45a59 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -600,6 +600,28 @@ describe("a worker's tunnel socket", () => { expect(ended.device.closed).toBe(true); expect(ended.socket.closed).toEqual({ code: 4001, reason: "expired" }); + const dropped = await open(); + let releaseDropped: () => void = () => undefined; + dropped.deviceTcp.closeGate = new Promise((resolve) => { + releaseDropped = resolve; + }); + dropped.socket.drop(); + await vi.waitFor(() => expect(dropped.device.closed).toBe(true)); + let droppedReturned = false; + const droppedHook = dropped.worker.hooks + ?.beforeDeviceReclaim?.(ending("expired"), new AbortController().signal) + .then(() => { + droppedReturned = true; + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect({ reversed: dropped.deviceTcp.reversed, droppedReturned }).toEqual({ + reversed: [5173], + droppedReturned: false, + }); + releaseDropped(); + await droppedHook; + expect(dropped.deviceTcp.reversed).toEqual([]); + const pair = await open(); const bystander = await attach(pair.worker, "L-2"); bystander.receive(hello({ devicePort: 5180, kind: "reverse" })); From 5ee15c2a6d197d064a3c4435609ddfd44ad790fb Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 1 Nov 2026 17:05:17 +0100 Subject: [PATCH 28/31] test(tunnel): the start sweep is awaited before the daemon serves (#1112) --- src/core/fake-device-tcp.ts | 3 +++ src/daemon/tunnel-lease.e2e.test.ts | 17 +++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/core/fake-device-tcp.ts b/src/core/fake-device-tcp.ts index cbe784aaf..b15529e15 100644 --- a/src/core/fake-device-tcp.ts +++ b/src/core/fake-device-tcp.ts @@ -44,6 +44,8 @@ export class FakeDeviceTcp implements DeviceTcp { 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[])[] = []; + // why: a test sets this to hold every `sweep` until it settles, as an adb call that is slow to answer does. + sweepGate: Promise | undefined; readonly #reverses = new Map(); #nextHostPort = 47_000; @@ -57,6 +59,7 @@ export class FakeDeviceTcp implements DeviceTcp { async sweep(devices: readonly SweptDevice[]): Promise { this.sweeps.push(devices); + await this.sweepGate; } async reverse( diff --git a/src/daemon/tunnel-lease.e2e.test.ts b/src/daemon/tunnel-lease.e2e.test.ts index 00e4e461c..f15beefdc 100644 --- a/src/daemon/tunnel-lease.e2e.test.ts +++ b/src/daemon/tunnel-lease.e2e.test.ts @@ -225,8 +225,21 @@ describe("a lease's tunnel socket", () => { await second.stop("test"); const idle = new FakeDeviceTcp(); - daemons.push(await start(idle)); - expect(idle.sweeps).toHaveLength(1); + let releaseSweep: () => void = () => undefined; + idle.sweepGate = new Promise((resolve) => { + releaseSweep = resolve; + }); + let started = false; + const starting = start(idle).then((daemon) => { + started = true; + return daemon; + }); + await vi.waitFor(() => expect(idle.sweeps).toHaveLength(1)); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(started).toBe(false); + releaseSweep(); + daemons.push(await starting); + expect(started).toBe(true); expect(idle.sweeps[0]).toEqual([ { device: expect.objectContaining({ physical: false }), leased: false }, ]); From 09226bbc5cb689e2102f6df7c8c62b8383dc7f5c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 1 Nov 2026 17:08:16 +0100 Subject: [PATCH 29/31] fix(android): reclaim and the start sweep never remove a rule on a phone, and a port a phone's rule points to stays held (#1112) --- src/drivers/android/device-tcp.ts | 31 +++++++++++---- src/drivers/android/index.test.ts | 40 +++++++++++++++++++- src/drivers/android/index.ts | 15 +++----- src/drivers/android/physical-handler.test.ts | 32 +++++++++------- 4 files changed, 87 insertions(+), 31 deletions(-) diff --git a/src/drivers/android/device-tcp.ts b/src/drivers/android/device-tcp.ts index b61c8906b..72576fabb 100644 --- a/src/drivers/android/device-tcp.ts +++ b/src/drivers/android/device-tcp.ts @@ -24,7 +24,7 @@ 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 isOwn: (device: VirtualDriverDevice) => 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: ( @@ -102,10 +102,11 @@ async function tunnelRules( run: RunAdb, warn: Warn, device: Target, -): Promise<{ readonly deviceSide: string; readonly port: number }[]> { +): Promise<{ readonly deviceSide: string; readonly port: number }[] | undefined> { const listed = await attempt(run, warn, device, ["reverse", "--list"]); + if (listed === undefined) return undefined; const rules: { deviceSide: string; port: number }[] = []; - for (const [, deviceSide, hostSide] of fields(listed ?? "")) { + for (const [, deviceSide, hostSide] of fields(listed)) { 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 }); @@ -120,8 +121,8 @@ interface HeldPort { } 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; + // why: called by the driver's reclaim of a device: an emulator's rules are gone, so every port held for it is free; a phone's rules are only read, and a port some rule on it still points to stays held. + release(device: VirtualDriverDevice | PhysicalDriverDevice): Promise; } export function createAndroidDeviceTcp(options: AndroidDeviceTcpOptions): AndroidDeviceTcp { @@ -137,14 +138,28 @@ export function createAndroidDeviceTcp(options: AndroidDeviceTcpOptions): Androi supports: () => true, async release(device): Promise { const mine = held.get(device.deviceId); - held.delete(device.deviceId); - await Promise.all([...(mine ?? [])].map((entry) => entry.listener?.close())); + if (mine === undefined) return; + // why: Simlock removes no rule it did not set on a phone, so a port a rule there still points to stays reserved; a phone whose rules cannot be read keeps all its ports. + const rules = device.physical ? await tunnelRules(options.runAdb, options.warn, device) : []; + const pointed = new Set(rules?.map(({ port }) => port) ?? [...mine].map(({ port }) => port)); + const freed = [...mine].filter((entry) => !pointed.has(entry.port)); + for (const entry of freed) mine.delete(entry); + if (mine.size === 0) held.delete(device.deviceId); + await Promise.all(freed.map((entry) => entry.listener?.close())); }, async sweep(devices: readonly SweptDevice[]): Promise { await Promise.all( devices.map(async ({ device, leased }) => { + // why: a phone is a person's device whose other rules Simlock cannot tell from its own, so the sweep only reads its rules and keeps the ports they point to from the next `reverse`. + if (device.physical) { + for (const { port } of (await tunnelRules(options.runAdb, options.warn, device)) ?? + []) { + keep(device.deviceId, { port }); + } + return; + } if (!(await options.isOwn(device))) return; - const rules = await tunnelRules(options.runAdb, options.warn, device); + const rules = (await tunnelRules(options.runAdb, options.warn, device)) ?? []; for (const { deviceSide, port } of rules) { if (leased) keep(device.deviceId, { port }); else { diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 171fd7e75..e4d4b8aea 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -3722,7 +3722,7 @@ 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 () => { + 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, touches nothing on an emulator that answers as another's, and on an idle phone removes nothing and keeps the ports its rules point to from the next reverse", async () => { const own = await driverWith([ avdPathExpectation("emulator-5586"), { @@ -3746,6 +3746,44 @@ describe("AndroidDriver deviceTcp", () => { await own.driver.deviceTcp?.sweep([{ device: emulator, leased: false }]); expect(own.runner.calls.filter((call) => call.args.includes("--remove"))).toHaveLength(2); + const probe = new FakeTcpProbe([5038, 5037]); + probe.replyWith("OKAY00040029"); + const phones = 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, "reverse", "--list"), + result: { + code: 0, + stderr: "", + stdout: "UsbFfs tcp:5173 tcp:47000\nUsbFfs tcp:3000 tcp:3001\n", + }, + }, + { + match: adb( + "-P", + "5037", + "-s", + PHYSICAL_DEVICE.address, + "reverse", + "--no-rebind", + "tcp:5174", + "tcp:47001", + ), + result: ok, + }, + ], + new FakeTcpListenerFactory(), + probe, + ); + await phones.driver.deviceTcp?.sweep([{ device: PHYSICAL_DEVICE, leased: false }]); + const onPhone = await phones.driver.deviceTcp?.reverse(PHYSICAL_DEVICE, 5174, signal()); + expect(onPhone?.hostPort).toBe(47_001); + expect(phones.runner.calls.some((call) => call.args.includes("--remove"))).toBe(false); + 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); diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index f8d9b5853..c2b172df6 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -1143,7 +1143,9 @@ export class AndroidDriver implements Driver { options: { readonly clean: "standard" | "full" }, ): Promise { const result = await this.#reclaimDevice(device, options); - await this.deviceTcp?.release(device); + await this.deviceTcp?.release( + isPhysicalDriverDevice(device) ? device : { ...device, physical: false as const }, + ); return result; } @@ -1152,7 +1154,6 @@ 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); @@ -1206,11 +1207,8 @@ 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 { + // why: reclaim of an emulator proved its own leaves no rule of the lease; it never throws, so a failed removal does not fail the reclaim. + async #removeRules(device: VirtualDriverDevice, serial: string): Promise { await removeDeviceRules( (target, args, timeoutMs) => this.#runAdbOn(target, args, timeoutMs), this.#warnCleanup, @@ -1219,8 +1217,7 @@ export class AndroidDriver implements Driver { ); } - async #deviceIsOwn(device: VirtualDriverDevice | PhysicalDriverDevice): Promise { - if (isPhysicalDriverDevice(device)) return true; + async #deviceIsOwn(device: VirtualDriverDevice): Promise { const data = this.#dataFor(device); return data.serial !== "" && (await this.#serialIsOwn(data)); } diff --git a/src/drivers/android/physical-handler.test.ts b/src/drivers/android/physical-handler.test.ts index 952d0ffb3..15d7100e4 100644 --- a/src/drivers/android/physical-handler.test.ts +++ b/src/drivers/android/physical-handler.test.ts @@ -1138,7 +1138,7 @@ 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, goes on when a removal fails, and frees the loopback port a failed tunnel removal kept", async () => { + it("removes no reverse or forward rule of the phone on reclaim, and frees only the loopback ports no rule on it points to", async () => { const listeners = new FakeTcpListenerFactory(); const { driver, runner } = await world({ listeners }); runner.override((rest) => { @@ -1146,24 +1146,23 @@ describe("Android physical handler: reclaim", () => { 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; + if (body === "reverse --list") return OK("UsbFfs tcp:5173 tcp:47000\n"); + if (body.startsWith("reverse --remove tcp:")) 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); + for (const port of [5173, 5174]) { + const kept = await driver.deviceTcp?.reverse(PHYSICAL, port, new AbortController().signal); + await kept?.close().catch(() => undefined); + } + expect(listeners.listeners.map((listener) => listener.closed)).toEqual([false, false]); const result = await driver.reclaim(PHYSICAL, { clean: "standard" }); - expect(listeners.listeners[0]?.closed).toBe(true); expect(result).toMatchObject({ strategy: "uninstall" }); + expect(listeners.listeners.map((listener) => listener.closed)).toEqual([false, true]); 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"], - ]); + runner.rests.filter((rest) => rest[2] === "reverse" || rest[2] === "forward").slice(4), + ).toEqual([["-s", PHONE, "reverse", "--list"]]); }); it("with nothing off the list runs no uninstall", async () => { @@ -1318,7 +1317,14 @@ describe("Android physical handler: reclaim", () => { }); 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(); + const { driver, runner } = await world({ listeners: new FakeTcpListenerFactory() }); + runner.override((rest) => { + const body = rest.slice(2).join(" "); + if (body.startsWith("reverse --remove tcp:")) return FAILED; + return body.startsWith("reverse --no-rebind") ? OK() : undefined; + }); + const held = await driver.deviceTcp?.reverse(PHYSICAL, 5173, new AbortController().signal); + await held?.close().catch(() => undefined); await driver.inspectPhysical(PHONE); await driver.listPresentPhysical([PHONE]); From 181af2d5c05e0949e746b16419ed3e5570856d92 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 1 Nov 2026 17:08:54 +0100 Subject: [PATCH 30/31] docs(tunnel): phones keep their rules, a tunnel's port is open to the worker's other devices, and which codes a worker sends (#1112) --- docs/internal/flows/startup.md | 2 +- src/drivers/android/AGENTS.md | 2 +- src/tunnel/AGENTS.md | 4 ++-- website/src/content/docs/docs/reference/configuration.mdx | 2 +- website/src/content/docs/docs/reference/errors.mdx | 2 +- website/src/content/docs/docs/using-devices/remote-agents.mdx | 2 ++ 6 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/internal/flows/startup.md b/docs/internal/flows/startup.md index 15bd298e8..2da924fe3 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 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`. +Before step 16, a driver with `deviceTcp` sweeps the reverse rules into 47000-47999 a stopped daemon's tunnels left, on its idle owned emulators; on a leased emulator it only reads the rules and reserves their ports, and its reclaim removes them; on a phone it only reads them and reserves their ports, which its reclaim frees once no rule points to 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/drivers/android/AGENTS.md b/src/drivers/android/AGENTS.md index ba7a188b9..96beaf97a 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, 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. +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; a phone's reclaim reads its `reverse --list` first and frees only the ports no rule there points to (a failed read frees none). 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 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, and a phone's reclaim runs neither (safety rule 1: only the tunnel's own `reverse --remove` at socket close touches a phone). `deviceTcp.sweep` (only with `tcpListener`), called by the daemon before any request is served, removes on every present idle owned emulator the `reverse --list` rules whose host side is `tcp:47000`-`tcp:47999`; on a leased emulator it removes nothing and keeps the ports those rules point to from the next `reverse` until its reclaim; on a phone, idle or leased, it only reads the rules and keeps those ports the same way. 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/tunnel/AGENTS.md b/src/tunnel/AGENTS.md index d8fddd936..0c1b4c119 100644 --- a/src/tunnel/AGENTS.md +++ b/src/tunnel/AGENTS.md @@ -23,10 +23,10 @@ The HTTP layer resolves the lease for the caller, then `socket.open` finds the l 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 (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. +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, a removal the socket's close began included (10 s per removal); a signal that is aborted, or aborts between removals, skips the rest and reclaim does them. ## 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. +- A removal that fails is logged at `warn`; the driver keeps the loopback port reserved until reclaim, and on a phone until no rule there points to it. diff --git a/website/src/content/docs/docs/reference/configuration.mdx b/website/src/content/docs/docs/reference/configuration.mdx index 2129768a0..c5342b123 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, or, on a device that is leased then, when its lease ends, 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. A phone's rules are never removed that way; see [Tunnels](/docs/using-devices/remote-agents/#tunnels) for what a tunnel's port is open to. | 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 213269f67..16892501c 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -74,7 +74,7 @@ Branch on `code`, not on the message: the message wording can change, the code d ## 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. +A lease's tunnel socket (`GET /v1/leases/{id}/tunnel`, on a worker with `capabilities.tunnel.enabled`) refuses a `HELLO` in a `REFUSED` frame and closes with 4003, with `TUNNEL_UNSUPPORTED`, `TUNNEL_PORT_IN_USE`, `TUNNEL_BAD_PORT`, `TUNNEL_LIMIT` or `TUNNEL_FAILED`. `TUNNEL_UNAVAILABLE`, `TUNNEL_DISCONNECTED`, `TUNNEL_CALLER_PORT_IN_USE` and `TUNNEL_LEASE_ENDED` are not sent by a worker's tunnel socket; the rows below say who raises them. | Code | Exit | HTTP | Meaning | What to do | | --- | --- | --- | --- | --- | 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..ed487d66e 100644 --- a/website/src/content/docs/docs/using-devices/remote-agents.mdx +++ b/website/src/content/docs/docs/using-devices/remote-agents.mdx @@ -189,6 +189,8 @@ Each message is one binary frame: a tag byte, a 4-byte big-endian connection num 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`. +While a tunnel is open, its port on the worker is reachable by others on that machine: any process on the worker, an emulator of another lease at `10.0.2.2`, and any other lease's device that has an `adb reverse` rule to it set through `exec`. Treat what a tunnel carries as open to them. On a phone, Simlock removes only the rules its own tunnels set, when their socket closes; it never clears the phone's other `adb reverse` or `adb forward` rules. A tunnel rule left by a worker crash stays on the phone until it reboots or you remove it with `adb reverse --remove`, and the worker keeps that rule's port out of use for new tunnels. + ## When something goes wrong Errors come back as JSON with an HTTP status: From 42f31b54b2d9dee25ab8d0f371a915e6d1f9d404 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 1 Nov 2026 17:19:47 +0100 Subject: [PATCH 31/31] fix(tunnel): on a phone an aborted lease end still removes the tunnel's own rules (#1112) --- src/drivers/android/index.ts | 2 +- src/tunnel/AGENTS.md | 2 +- src/tunnel/sessions.ts | 13 +++++++++---- src/tunnel/worker.test.ts | 10 ++++++++++ 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index c2b172df6..2153a98b5 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -1137,7 +1137,7 @@ 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. + // why: the loopback ports held for a device's tunnels are freed after its reclaim: on an emulator the reclaim removed the rules, on a phone it removes none and only the ports no rule points to are freed. async reclaim( device: DriverDevice, options: { readonly clean: "standard" | "full" }, diff --git a/src/tunnel/AGENTS.md b/src/tunnel/AGENTS.md index 0c1b4c119..750d5f9fe 100644 --- a/src/tunnel/AGENTS.md +++ b/src/tunnel/AGENTS.md @@ -23,7 +23,7 @@ The HTTP layer resolves the lease for the caller, then `socket.open` finds the l 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 (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, a removal the socket's close began included (10 s per removal); a signal that is aborted, or aborts between removals, skips the rest and reclaim does them. +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, a removal the socket's close began included (10 s per removal); on an emulator a signal that is aborted, or aborts between removals, skips the rest and reclaim does them; on a phone the removals run anyway, because its reclaim removes no rules. ## Rules diff --git a/src/tunnel/sessions.ts b/src/tunnel/sessions.ts index e4f40edc4..14ff11f45 100644 --- a/src/tunnel/sessions.ts +++ b/src/tunnel/sessions.ts @@ -115,7 +115,7 @@ 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. +// why: one socket's state that the lease's end and the daemon's stop reach from outside: `finish` closes its connections and removes its rules, except on an emulator whose end is aborted, where the reclaim that follows does it. interface Session { readonly socket: LeaseSocket; finish(removeRules: boolean, signal?: AbortSignal): Promise; @@ -148,7 +148,12 @@ export function createTunnelSessions(options: { const connections = new Map(); const reverses: DeviceReverse[] = []; - function finish(removeRules: boolean, signal?: AbortSignal): Promise { + // why: a phone's reclaim removes no rules, so an end whose signal is aborted still removes this session's own; only an emulator's reclaim does that for it. + const phone = toDriverDevice(device).physical; + + function finish(removeRulesAsked: boolean, signalAsked?: AbortSignal): Promise { + const removeRules = removeRulesAsked || phone; + const signal = phone ? undefined : signalAsked; finished ??= (async () => { endedWith = { remove: removeRules, signal }; counts.set(leaseId, (counts.get(leaseId) ?? 0) - reserved); @@ -160,7 +165,7 @@ export function createTunnelSessions(options: { connections.clear(); try { if (!removeRules) return; - // why: one after another, so a lease-end signal that aborts mid-way stops the removals that reclaim is about to do. + // why: one after another, so on an emulator 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)); @@ -470,7 +475,7 @@ export function createTunnelSessions(options: { return { attach, drain: () => endSessions(undefined, CLOSE_GOING_AWAY, "Simlock is stopping", true), - // 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. + // why: with the signal aborted the daemon is stopping or in maintenance; an emulator's reclaim removes the rules, so none starts after that, while a phone's reclaim removes none, so its session still does; the hook returns only when the removals it began are done. end: (leaseId, reason, signal) => endSessions(leaseId, CLOSE_LEASE_ENDED, reason, !signal.aborted, signal), }; diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index 27ea45a59..378fe4f03 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -712,6 +712,16 @@ describe("a worker's tunnel socket", () => { expect(reclaimed.deviceTcp.reversed).toEqual([5173]); expect(reclaimed.deviceTcp.connect(5173).closed).toBe(true); + // why: a phone's reclaim removes no rules, so an aborted end still removes the tunnel's own. + const phone = await setup("android", true); + const phoneSocket = await attach(phone.worker); + phoneSocket.receive(hello(tunnel)); + await vi.waitFor(() => expect(phone.deviceTcp.reversed).toEqual([5173])); + const phoneAborted = new AbortController(); + phoneAborted.abort(); + await phone.worker.hooks?.beforeDeviceReclaim?.(ending("device-lost"), phoneAborted.signal); + expect(phone.deviceTcp.reversed).toEqual([]); + const racing = await setup(); let release: () => void = () => undefined; racing.deviceTcp.gate = new Promise((resolve) => {