Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
152 commits
Select commit Hold shift + click to select a range
d1f74bc
test: a holder's rotate of its iOS-simulator lease answers and sends …
leonardoxr Oct 31, 2026
6a87186
test: a holder opens the tunnel socket, sends HELLO with reverse tunn…
leonardoxr Oct 31, 2026
98cfb13
feat(tunnel): a reverse tunnel answers READY and carries device conne…
leonardoxr Oct 31, 2026
a42ade3
feat(daemon): device.rotate turns a leased simulator through its devi…
leonardoxr Oct 31, 2026
21516b5
test: a holder's HELLO that cannot be met is refused whole with REFUS…
leonardoxr Oct 31, 2026
e308d56
feat(tunnel): a HELLO that cannot be met is refused whole with its co…
leonardoxr Oct 31, 2026
fe1c197
test: a caller rotates a lease it may not touch, or names a bad orien…
leonardoxr Oct 31, 2026
2f1ebec
feat(contract): device.rotate is authorized like device.exec (#1107)
leonardoxr Oct 31, 2026
e54e3f2
test: a holder rotates a lease not on an iOS phone or tablet simulato…
leonardoxr Oct 31, 2026
18acbd7
feat(daemon): device.rotate refuses a lease not on an iOS phone or ta…
leonardoxr Oct 31, 2026
642a392
test: a holder rotates when the helper cannot start or the write fail…
leonardoxr Oct 31, 2026
770e4f0
feat(daemon): device.rotate answers INPUT_UNAVAILABLE with the reason…
leonardoxr Oct 31, 2026
50dac1b
test: an input socket opened after a rotate's helper closed gets a fr…
leonardoxr Oct 31, 2026
2084eab
test: bytes flow both ways under a 262144-byte window per direction, …
leonardoxr Oct 31, 2026
c4f93c0
feat(tunnel): data flows both ways under a per-connection window and …
leonardoxr Oct 31, 2026
42899a1
test: a bad frame is refused BAD_REQUEST and closed 4003, a frame for…
leonardoxr Oct 31, 2026
22b171d
feat(daemon): one device input per lease, shared by the input module'…
leonardoxr Oct 31, 2026
0751cc1
feat(tunnel): a bad frame is refused BAD_REQUEST with close 4003 (#1112)
leonardoxr Oct 31, 2026
7afdb40
test: the worker removes a tunnel's rules and closes its connections …
leonardoxr Oct 31, 2026
736d3ba
test: a client program calls client.rotate(leaseId, orientation) and …
leonardoxr Oct 31, 2026
746b8d0
feat(tunnel): closing the socket, the lease's end and a drain remove …
leonardoxr Oct 31, 2026
e778c34
feat(client): client.rotate turns a lease's simulator through device.…
leonardoxr Oct 31, 2026
a4d9f18
test: an agent calls POST /v1/leases/{id}/rotate on a worker and thro…
leonardoxr Oct 31, 2026
e330b80
test: a caller reaches the tunnel route on a lone worker only when it…
leonardoxr Oct 31, 2026
45ad185
feat(tunnel): a holder or operator reaches the tunnel route on a lone…
leonardoxr Oct 31, 2026
0dc922c
feat(http): POST /v1/leases/{id}/rotate on a worker and through a gat…
leonardoxr Oct 31, 2026
6f2f973
docs: rotate over HTTP and its two error codes (#1107)
leonardoxr Oct 31, 2026
d8d222b
test: the alias parser maps a spelling to an orientation or the unkno…
leonardoxr Oct 31, 2026
4bae4e7
feat(contract): parseOrientation maps an alias to an orientation or t…
leonardoxr Oct 31, 2026
c6834bc
test: the gateway coordinator forwards device.rotate and names the ca…
leonardoxr Oct 31, 2026
38af91d
feat(android): the driver's reverse sets adb reverse --no-rebind to a…
leonardoxr Oct 31, 2026
cd00d68
feat(tunnel): an iOS lease is refused TUNNEL_UNSUPPORTED and a driver…
leonardoxr Oct 31, 2026
c267dac
test: a user runs simlock rotate <orientation> and sees Rotated lease…
leonardoxr Oct 31, 2026
adb10f2
feat(cli): simlock rotate turns the holder's only lease (#1108)
leonardoxr Oct 31, 2026
0759879
test: two tunnels, END half-closes from each side, and a device conne…
leonardoxr Oct 31, 2026
661ddab
feat(tunnel): END half-closes a connection from each side and a devic…
leonardoxr Oct 31, 2026
8972aca
test: --lease names the lease to rotate before or after the orientati…
leonardoxr Oct 31, 2026
fa9b7cf
feat(cli): simlock rotate --lease names the lease (#1108)
leonardoxr Oct 31, 2026
617b3dd
fix(ports): a peer's half-close ends a TCP stream's readable (#1112)
leonardoxr Oct 31, 2026
17858cd
test: simlock rotate takes aliases, refuses unknown names and ambiguo…
leonardoxr Oct 31, 2026
9f1396f
test: an MCP client calls rotate_device {orientation} and the held le…
leonardoxr Oct 31, 2026
29c7aec
docs(tunnel): the tunnel socket on a lone worker, its capability, por…
leonardoxr Oct 31, 2026
bc1a869
feat(mcp): rotate_device turns the session's held lease (#1108)
leonardoxr Oct 31, 2026
a8dda2f
test: rotate_device answers NO_LEASE, BAD_REQUEST and the daemon's re…
leonardoxr Oct 31, 2026
77edefa
test: simlock instructions lists simlock rotate and rotate_device (#1…
leonardoxr Oct 31, 2026
eae80be
test: a socket whose write fails closes 1013 while the daemon keeps r…
leonardoxr Oct 31, 2026
6d6c5ea
feat(instructions): simlock instructions lists simlock rotate and rot…
leonardoxr Oct 31, 2026
e5bb97b
test: simlock rotate --help and the root usage name the command (#1108)
leonardoxr Oct 31, 2026
aced7b4
test: fold the coordinator's rotate case into the HTTP gateway test t…
leonardoxr Oct 31, 2026
0844848
chore: name how the coordinator's rotate is reached for Fallow (#1107)
leonardoxr Oct 31, 2026
600ec74
test: a holder opens the tunnel socket through a gateway and it is re…
leonardoxr Oct 31, 2026
5a8d932
test: a socket closing while hello awaits reverse leaves no rule set …
leonardoxr Oct 31, 2026
bb30a14
fix(tunnel): a rule that arrives after the socket closed is removed (…
leonardoxr Oct 31, 2026
01f44f7
feat(tunnel): a gateway relays the tunnel socket to the lease's worke…
leonardoxr Oct 31, 2026
d679267
test: a worker with tunnels off answers 503 TUNNEL_UNAVAILABLE throug…
leonardoxr Oct 31, 2026
c28989a
feat(tunnel): a worker with tunnels off answers 503 TUNNEL_UNAVAILABL…
leonardoxr Oct 31, 2026
364bb73
test: a full-size DATA is relayed and a worker's REFUSED closes the h…
leonardoxr Oct 31, 2026
8c98b94
feat(cli): simlock rotate --help, the root usage, the CLI reference a…
leonardoxr Oct 31, 2026
892278a
feat(tunnel): the worker's close frame closes the holder's socket wit…
leonardoxr Oct 31, 2026
68d70ac
test: a caller frame over 65541 bytes is refused BAD_REQUEST and clos…
leonardoxr Oct 31, 2026
12d19c7
feat(android): reclaim and daemon start remove stale tunnel rules, on…
leonardoxr Oct 31, 2026
1db9bab
feat(tunnel): a caller frame over 65541 bytes is refused BAD_REQUEST …
leonardoxr Oct 31, 2026
bc08674
docs(android): the cleanup of stale tunnel rules at reclaim and start…
leonardoxr Oct 31, 2026
a859b67
test: through a gateway the lease's end closes 4001, a stopping worke…
leonardoxr Oct 31, 2026
19d0ca4
chore(tunnel): Fallow findings of the tunnel cycles (#1112)
leonardoxr Oct 31, 2026
18735fc
Merge remote-tracking branch 'origin/task/1107' into task/1108
leonardoxr Oct 31, 2026
3f09619
feat(tunnel): a stopping worker closes the holder 1011 and a draining…
leonardoxr Oct 31, 2026
f09c789
test: the gateway's tunnel bridge bounds every wait on the worker (#1…
leonardoxr Oct 31, 2026
4c09bca
feat(tunnel): the gateway bounds its open to 10 s and a lease's remov…
leonardoxr Oct 31, 2026
719e405
feat(tunnel): the worker's relay door sends a heartbeat every 5 s and…
leonardoxr Oct 31, 2026
277d2fa
test: the tunnel route's 503 TUNNEL_UNAVAILABLE and WORKER_UNREACHABL…
leonardoxr Oct 31, 2026
f3a35d5
feat(tunnel): the route's 503 statuses, the remote-agents page and th…
leonardoxr Oct 31, 2026
f18c495
chore(tunnel): merge task/1108 into task/1114 (#1114)
leonardoxr Oct 31, 2026
766482d
chore(tunnel): merge origin/task/1112 into task/1113 (#1113)
leonardoxr Oct 31, 2026
6442e27
test: the CLI against a lone worker with fake devices opens a reverse…
leonardoxr Oct 31, 2026
34eb975
feat(cli): simlock tunnel reverse opens a tunnel on a lone worker and…
leonardoxr Oct 31, 2026
1672cab
fix(tunnel): a channel frame is at most one message, the heartbeat st…
leonardoxr Oct 31, 2026
53e0ec8
test: the CLI against a lone worker with fake devices refuses with th…
leonardoxr Oct 31, 2026
945fa70
feat(cli): a tunnel the worker refuses exits with the worker's code (…
leonardoxr Oct 31, 2026
dc91fe1
test: a user's simlock tunnel that cannot run exits with its code and…
leonardoxr Oct 31, 2026
12a5613
feat(cli): simlock tunnel checks its arguments, url and token before …
leonardoxr Oct 31, 2026
2a2f2f8
test: simlock tunnel prints one line per tunnel and words its lease e…
leonardoxr Oct 31, 2026
0fb0d01
feat(cli): simlock tunnel words its lease errors for the token and an…
leonardoxr Oct 31, 2026
5ee8b88
test: nothing listening warns once per 10 s per tunnel and a 1 MiB re…
leonardoxr Oct 31, 2026
1049697
test(tunnel): the audit's missing cases, the reclaim fixtures and the…
leonardoxr Oct 31, 2026
c315e7d
feat(cli): simlock tunnel warns when nothing listens and honours the …
leonardoxr Oct 31, 2026
5e55c81
test: simlock tunnel that is refused or loses its worker exits with t…
leonardoxr Oct 31, 2026
287bfd0
feat(cli): simlock tunnel exits with the worker's code, times out sil…
leonardoxr Oct 31, 2026
7a59360
test: lazy-loading shows ws loaded by simlock tunnel alone (#1114)
leonardoxr Oct 31, 2026
5029153
test: the http-json and websocket-client adapters against a real serv…
leonardoxr Oct 31, 2026
92e4024
docs(cli): the tunnel command, its lease resolver and the lazy ws ada…
leonardoxr Oct 31, 2026
e999928
test: a page on the caller's loopback port loads on a real emulator t…
leonardoxr Oct 31, 2026
e08812e
chore(tunnel): Fallow findings of the cli and ports cycles (#1114)
leonardoxr Oct 31, 2026
49a5f23
Merge remote-tracking branch 'origin/task/1112' into task/1114
leonardoxr Oct 31, 2026
da7a020
Merge remote-tracking branch 'origin/task/1113' into task/1115
leonardoxr Oct 31, 2026
7603ff6
fix: the website's MCP summaries say six tools; rotate_device's alias…
leonardoxr Oct 31, 2026
c529bf6
test: a user runs simlock tunnel forward and the caller's loopback po…
leonardoxr Oct 31, 2026
a1ec60b
feat(tunnel): a forward tunnel's caller port reaches the device port …
leonardoxr Oct 31, 2026
982efb6
test: forward caller port below 1024 and a caller port named across d…
leonardoxr Oct 31, 2026
35077e8
feat(cli): a forward caller port below 1024 is a usage error (#1115)
leonardoxr Oct 31, 2026
e50820a
test: forward binds before HELLO, holds connections until READY and c…
leonardoxr Oct 31, 2026
7aa86a7
fix(gateway): name the caller's lease id in every worker error, and p…
leonardoxr Oct 31, 2026
6382188
docs: list POST /v1/leases/{id}/rotate and device.rotate in the manua…
leonardoxr Oct 31, 2026
6479fe4
feat(cli): forward connections accepted before READY wait and close o…
leonardoxr Oct 31, 2026
5b85def
test: forward device port closed resets the caller's connection and c…
leonardoxr Oct 31, 2026
73b40e6
feat(tunnel): a device port with nothing listening resets the forward…
leonardoxr Oct 31, 2026
5fd0764
test: the worker validates caller-opened connections and counts them …
leonardoxr Oct 31, 2026
ee9cdcc
feat(tunnel): the worker validates caller-opened connections and sets…
leonardoxr Oct 31, 2026
de2bc7b
Merge remote-tracking branch 'origin/task/1107' into task/1108
leonardoxr Oct 31, 2026
bb0b80b
test: the android driver opens a device port through adb's host proto…
leonardoxr Oct 31, 2026
33b7b53
test: pin rotate's agent role, client close and the rotate_device inp…
leonardoxr Oct 31, 2026
e0e04b4
feat(android): open a device port through adb's host protocol for for…
leonardoxr Oct 31, 2026
22169a8
fix(android): hold tunnel ports until reclaim, keep a leased device's…
leonardoxr Oct 31, 2026
8c319cc
test: reverse and forward both work on a real emulator through a gate…
leonardoxr Oct 31, 2026
c19bc15
chore(tunnel): Fallow findings of the review fixes (#1112)
leonardoxr Oct 31, 2026
c841598
docs(tunnel): forward in the CLI reference, the wire description and …
leonardoxr Oct 31, 2026
dedafb1
test: drop a leftover debug assertion from the MCP smoke table (#1108)
leonardoxr Oct 31, 2026
6f575ca
chore(tunnel): Fallow findings of the forward cycles (#1115)
leonardoxr Oct 31, 2026
5087165
Merge remote-tracking branch 'origin/task/1112' into task/1115
leonardoxr Oct 31, 2026
4893d50
chore(tunnel): merge origin/task/1112 and share one relay-channel imp…
leonardoxr Oct 31, 2026
53012f8
fix(modules): drop the pipe type from the index now that only the rel…
leonardoxr Oct 31, 2026
eb7baaf
test(tunnel): the audit's missing cases, safe frame JSON and the http…
leonardoxr Oct 31, 2026
49aba08
Merge remote-tracking branch 'origin/task/1114' into task/1115
leonardoxr Oct 31, 2026
3771e5a
Merge remote-tracking branch 'origin/task/1113' into task/1115
leonardoxr Oct 31, 2026
2d0c579
Merge remote-tracking branch 'origin/task/1112' into task/1114
leonardoxr Oct 31, 2026
facfe9c
Merge remote-tracking branch 'origin/task/1113' into task/1114
leonardoxr Oct 31, 2026
cefda33
Merge remote-tracking branch 'origin/task/1108' into task/1114
leonardoxr Oct 31, 2026
e48d5a1
test: audit boundary cases for forward tunnels, and one wording for a…
leonardoxr Oct 31, 2026
11d80a8
fix(tunnel): close every connection and the socket on each exit, rese…
leonardoxr Oct 31, 2026
aeb76cf
refactor(tunnel): split checkedUrl and the carrying-connections test …
leonardoxr Oct 31, 2026
3a410cd
test: the closed-gate case uses a server that differs from Simlock's …
leonardoxr Oct 31, 2026
8a2903a
test: split the forward listener test's helpers out of its body (#1115)
leonardoxr Oct 31, 2026
d8fc2f9
chore(tunnel): merge task/1114 into task/1115 and hold forward connec…
leonardoxr Oct 31, 2026
abe9221
test(tunnel): a forward connection made before the socket exists is c…
leonardoxr Oct 31, 2026
5f36b92
fix(tunnel): a forward OPEN after the session ends opens nothing, and…
leonardoxr Oct 31, 2026
9d5f58a
test(tunnel): a device's END half-closes the caller's forwarded conne…
leonardoxr Oct 31, 2026
ef0194e
Merge origin/main into task/1112
V3RON Nov 1, 2026
01e7d87
Merge task/1112 (with origin/main) into task/1113
V3RON Nov 1, 2026
a66d101
Merge task/1113 (with origin/main) into task/1114
V3RON Nov 1, 2026
4c9bc00
Merge task/1114 (with origin/main) into task/1115
V3RON Nov 1, 2026
f744ed0
test(tunnel): input and tunnel together on one lease through a gatewa…
V3RON Nov 1, 2026
92871a5
test(tunnel): input and a reverse tunnel together on a real emulator …
V3RON Nov 1, 2026
7cb381f
test(tunnel): gateway slow-lane adb calls run as the lease's agent wi…
V3RON Nov 1, 2026
d67450a
Merge origin/main into task/1115
V3RON Nov 1, 2026
0107541
test(tunnel): input and tunnel together on one lease through a gatewa…
V3RON Nov 1, 2026
2e80011
test(tunnel): input and a reverse tunnel together on a real emulator …
V3RON Nov 1, 2026
015c3b8
test(tunnel): gateway slow-lane adb calls run as the lease's agent wi…
V3RON Nov 1, 2026
f38b02c
test(tunnel): through a gateway simlock adb needs no closed stdin (AD…
V3RON Nov 1, 2026
4ec57d6
test(tunnel): cover the driver's connect, bound the forward client at…
V3RON Nov 1, 2026
f6dd512
test(android): the connect-timeout case waits for the open socket bef…
V3RON Nov 1, 2026
0d7c22b
test(e2e): read the emulator's rules once its reclaim has finished, n…
V3RON Nov 1, 2026
ac517aa
test(e2e): read the worker's device state, not the gateway's, before …
V3RON Nov 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/internal/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘
| agent-device | Optional edge: the two agent-device daemons (simulators, phones) beside a worker, its HTTP front | [agent-device](../../src/agent-device/AGENTS.md) |
| stream | Optional edge: a running device's live screen over HTTP, relayed by a gateway | [stream](../../src/stream/AGENTS.md) |
| input | Optional edge: a lease holder's taps and keys over a WebSocket, relayed by a gateway | [input](../../src/input/AGENTS.md) |
| tunnel | Optional edge: a lease holder's reverse tunnels from its Android device over a WebSocket, on a lone worker or through a gateway | [tunnel](../../src/tunnel/AGENTS.md) |
| tunnel | Optional edge: a lease holder's reverse tunnels (device to caller) and forward tunnels (caller to device) on its Android device over a WebSocket, on a lone worker or through a gateway | [tunnel](../../src/tunnel/AGENTS.md) |
| auth | Credential → identity: tokens, admin secret, `hello`, uplink join token, HTTP strategies | [auth](../../src/auth/AGENTS.md) |
| http | HTTP frontend: routes, SSE | [http](../../src/http/AGENTS.md) |
| cli | Operator command surface | [cli](../../src/cli/AGENTS.md) |
Expand Down
525 changes: 523 additions & 2 deletions e2e/slow-android-tunnel.test.ts

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/cli/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,12 @@ Surface: [cli.mdx](../../website/src/content/docs/docs/reference/cli.mdx) — ev
orientation, an unknown one is a usage error (exit 2); the lease is `--lease` (anywhere on the line)
or the requester's only lease (`resolveRemoteLeaseId`); `device.rotate` answers, and the line printed
is `Rotated lease <id> to <orientation>` from the answer. Worker or gateway alike.
5b. **`simlock tunnel reverse <d>[:<c>] … [--lease <id>] [--url <u>]`** — talks to a worker or gateway over
5b. **`simlock tunnel reverse|forward <d>[:<c>] … [--lease <id>] [--url <u>]`** — talks to a worker or gateway over
HTTP and a WebSocket, never the local daemon: `--url`/`SIMLOCK_URL` (`https://`, or `http://` on loopback only; the origin, no path, query or fragment)
and `--token`/`SIMLOCK_TOKEN`. Without `--lease`, `GET /v1/identity` and `/v1/leases` pick an agent token's only
lease (`selectOnlyLease`; an operator token must name one). One line per tunnel on `READY`; each `OPEN` connects
to the caller's loopback port (no listener: `RESET` and a stderr warning per tunnel every 10 s), and `CREDIT`
flows both ways. Failures print one JSON line itself: a refused upgrade or `REFUSED` frame with the worker's code,
flows both ways. A `forward` tunnel binds its caller port (loopback, 1024 and up) through `tcpListeners` before anything else (busy: exit 1 `TUNNEL_CALLER_PORT_IN_USE`), holds accepted connections until `READY` (closed on `REFUSED`), opens each with an even-id `OPEN`, and closes every listener when the command ends. Failures print one JSON line itself: a refused upgrade or `REFUSED` frame with the worker's code,
close 4001 exit 14 `TUNNEL_LEASE_ENDED`, a lost socket, 45 s of silence or 90 s without `READY` `TUNNEL_DISCONNECTED`.
Ctrl-C and SIGTERM close the socket, wait at most 2 s, exit 0. `ws` loads on the first connect, for this command only.
6. **`simlock events --follow`** — subscribe, then replay, then print buffered pushes not
Expand Down
124 changes: 91 additions & 33 deletions src/cli/commands/tunnel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
TUNNEL_WINDOW_BYTES,
} from "../../contract/index.js";
import {
type TcpListener,
type TcpStream,
type TimerHandle,
type WebSocketClient,
Expand All @@ -20,6 +21,7 @@ import { selectOnlyLease } from "../remote-lease.js";
import type { CommandContext } from "../tree.js";
import type { CliEnvironment } from "../types.js";

const FORWARD_CALLER_PORT_MIN = 1024;
const HANDSHAKE_TIMEOUT_MS = 10_000;
const CALLER_CONNECT_TIMEOUT_MS = 5_000;
const CLOSE_NORMAL = 1000;
Expand All @@ -28,7 +30,8 @@ const MAX_URL_CHARS = 2048;
const MAX_TOKEN_CHARS = 4096;
const MAX_LEASE_CHARS = 256;

interface ReverseSpec {
interface TunnelSpec {
readonly kind: "reverse" | "forward";
readonly devicePort: number;
readonly callerPort: number;
}
Expand All @@ -41,27 +44,31 @@ function portOf(text: string, what: string): number {
return port;
}

function parseReverse(words: readonly string[], index: number): ReverseSpec {
function parseTunnel(words: readonly string[], index: number): TunnelSpec {
const kind = words[index] as string;
if (kind !== "reverse") {
throw new UsageError(`Unknown tunnel kind "${kind}": only reverse is available`);
if (kind !== "reverse" && kind !== "forward") {
throw new UsageError(`Unknown tunnel kind "${kind}": use reverse or forward`);
}
const text = words[index + 1] ?? "";
const colon = text.indexOf(":");
const device = colon === -1 ? text : text.slice(0, colon);
const devicePort = portOf(device, "device");
return {
callerPort: portOf(colon === -1 ? device : text.slice(colon + 1), "caller"),
devicePort,
};
const callerText = colon === -1 ? device : text.slice(colon + 1);
const callerPort = portOf(callerText, "caller");
if (kind === "forward" && callerPort < FORWARD_CALLER_PORT_MIN) {
throw new UsageError(
`forward caller port "${callerText}" is below ${String(FORWARD_CALLER_PORT_MIN)}`,
);
}
return { callerPort, devicePort, kind };
}

function parseReverses(words: readonly string[]): readonly ReverseSpec[] {
function parseTunnels(words: readonly string[]): readonly TunnelSpec[] {
if (words.length === 0) {
throw new UsageError("Name at least one tunnel: reverse <device-port>[:<caller-port>]");
throw new UsageError("Name at least one tunnel: reverse|forward <device-port>[:<caller-port>]");
}
const specs: ReverseSpec[] = [];
for (let index = 0; index < words.length; index += 2) specs.push(parseReverse(words, index));
const specs: TunnelSpec[] = [];
for (let index = 0; index < words.length; index += 2) specs.push(parseTunnel(words, index));
if (specs.length > TUNNEL_MAX_TUNNELS)
throw new UsageError(`At most ${String(TUNNEL_MAX_TUNNELS)} tunnels`);
const callerPorts = specs.map(({ callerPort }) => callerPort);
Expand Down Expand Up @@ -178,15 +185,7 @@ function relayConnections(
new DataView(credit.buffer).setUint32(0, size);
socket.send(encodeTunnelFrame(TUNNEL_TAG.credit, conn, credit));
};
const openConnection = async (spec: ReverseSpec, conn: number): Promise<void> => {
let stream: TcpStream;
try {
stream = await environment.tcpStreams.connect(spec.callerPort, CALLER_CONNECT_TIMEOUT_MS);
} catch {
warn(spec.devicePort, spec.callerPort);
socket.send(encodeTunnelFrame(TUNNEL_TAG.reset, conn));
return;
}
const adopt = (conn: number, stream: TcpStream): void => {
const relayed: Relayed = {
stream,
wake: undefined,
Expand All @@ -196,6 +195,17 @@ function relayConnections(
streams.set(conn, relayed);
void pump(conn, relayed);
};
const openConnection = async (spec: TunnelSpec, conn: number): Promise<void> => {
let stream: TcpStream;
try {
stream = await environment.tcpStreams.connect(spec.callerPort, CALLER_CONNECT_TIMEOUT_MS);
} catch {
warn(spec.devicePort, spec.callerPort);
socket.send(encodeTunnelFrame(TUNNEL_TAG.reset, conn));
return;
}
adopt(conn, stream);
};
const onFrame = (
connection: Relayed,
frame: { tag: number; conn: number; payload: Uint8Array },
Expand All @@ -222,7 +232,7 @@ function relayConnections(
}
};
const handle = async (
spec: ReverseSpec | undefined,
spec: TunnelSpec | undefined,
frame: { tag: number; conn: number; payload: Uint8Array },
): Promise<void> => {
if (frame.tag === TUNNEL_TAG.open) {
Expand All @@ -240,7 +250,13 @@ function relayConnections(
wake?.();
}
};
return { closeAll, handle };
return { adopt, closeAll, handle };
}

// why: a forward listener accepts at bind, before the lease and the socket exist, so its connections wait here until READY and the command closes what is left when it ends.
interface ForwardGate {
open: ((spec: TunnelSpec, stream: TcpStream) => void) | undefined;
readonly held: { spec: TunnelSpec; stream: TcpStream }[];
}

const HELLO_TIMEOUT_MS = 90_000;
Expand Down Expand Up @@ -359,7 +375,8 @@ function frameFailure(frame: { payload: Uint8Array }, leaseId: string): TunnelFa
function serve(
environment: CliEnvironment,
socket: WebSocketClient,
specs: readonly ReverseSpec[],
specs: readonly TunnelSpec[],
gate: ForwardGate,
leaseId: string,
base: string,
): Promise<number> {
Expand All @@ -373,6 +390,19 @@ function serve(
`reverse ${String(devicePort)}: nothing listening on localhost:${String(callerPort)}\n`,
);
});
let nextCallerConnection = 2;
const announce = (spec: TunnelSpec, stream: TcpStream): void => {
const conn = nextCallerConnection;
nextCallerConnection += 2;
socket.send(
encodeTunnelFrame(
TUNNEL_TAG.open,
conn,
JSON.stringify({ devicePort: spec.devicePort, kind: "forward" }),
),
);
relay.adopt(conn, stream);
};
// why: an OPEN waits for its loopback connect, and the DATA behind it must not overtake it, so frames are handled one at a time.
let handled = Promise.resolve();
let socketClosed = false;
Expand All @@ -398,6 +428,7 @@ function serve(
environment.clock.cancel(helloTimer);
if (silence !== undefined) environment.clock.cancel(silence);
if (closeTimer !== undefined) environment.clock.cancel(closeTimer);
gate.open = undefined;
relay.closeAll();
if (!socketClosed) {
socket.close(CLOSE_NORMAL, "");
Expand Down Expand Up @@ -443,17 +474,23 @@ function serve(
}
if (frame.tag === TUNNEL_TAG.ready) {
environment.clock.cancel(helloTimer);
for (const { callerPort, devicePort } of specs) {
environment.stdout.write(
`reverse device:${String(devicePort)} -> localhost:${String(callerPort)} (lease ${leaseId})\n`,
);
gate.open = announce;
for (const { spec, stream } of gate.held.splice(0)) announce(spec, stream);
for (const { callerPort, devicePort, kind } of specs) {
const route =
kind === "reverse"
? `reverse device:${String(devicePort)} -> localhost:${String(callerPort)}`
: `forward localhost:${String(callerPort)} -> device:${String(devicePort)}`;
environment.stdout.write(`${route} (lease ${leaseId})\n`);
}
return;
}
const opened =
frame.tag === TUNNEL_TAG.open
? specs.find(
({ devicePort }) => field(payloadJson(frame.payload), "devicePort") === devicePort,
({ devicePort, kind }) =>
kind === "reverse" &&
field(payloadJson(frame.payload), "devicePort") === devicePort,
)
: undefined;
handled = handled.then(() => relay.handle(opened, frame)).catch(() => undefined);
Expand All @@ -463,7 +500,7 @@ function serve(
TUNNEL_TAG.hello,
0,
JSON.stringify({
tunnels: specs.map(({ devicePort }) => ({ devicePort, kind: "reverse" })),
tunnels: specs.map(({ devicePort, kind }) => ({ devicePort, kind })),
}),
),
);
Expand All @@ -481,24 +518,45 @@ async function run(
});
if (help) {
environment.stdout.write(
"Usage: simlock tunnel reverse <device-port>[:<caller-port>] [reverse ...] [--lease <id>] [--url <url>]\n",
"Usage: simlock tunnel reverse|forward <device-port>[:<caller-port>] [reverse|forward ...] [--lease <id>] [--url <url>]\n",
);
return 0;
}
const specs = parseReverses(positionals);
const specs = parseTunnels(positionals);
const base = checkedUrl(typeof url === "string" ? url : environment.tunnelUrl);
const secret = checkedToken(token ?? environment.tunnelToken);
const named = checkedLease(typeof lease === "string" ? lease : undefined);
const listeners: TcpListener[] = [];
const gate: ForwardGate = { held: [], open: undefined };
try {
for (const spec of specs) {
if (spec.kind !== "forward") continue;
const listener = await environment.tcpListeners.listen(spec.callerPort);
if (listener === undefined) {
throw new TunnelFailure(
"TUNNEL_CALLER_PORT_IN_USE",
`forward ${String(spec.devicePort)}: localhost:${String(spec.callerPort)} is already in use`,
ERROR_TABLE.TUNNEL_CALLER_PORT_IN_USE.cliExitCode,
);
}
listener.onConnection((stream) => {
if (gate.open === undefined) gate.held.push({ spec, stream });
else gate.open(spec, stream);
});
listeners.push(listener);
}
const leaseId = await leaseToUse(environment, base, secret, named);
const socket = await openSocket(environment, base, secret, leaseId);
return await serve(environment, socket, specs, leaseId, base);
return await serve(environment, socket, specs, gate, leaseId, base);
} catch (error) {
if (!(error instanceof TunnelFailure)) throw error;
environment.stderr.write(
`${JSON.stringify({ error: { code: error.code, message: error.message } })}\n`,
);
return error.exitCode;
} finally {
await Promise.all(listeners.map((listener) => listener.close()));
for (const { stream } of gate.held.splice(0)) stream.close();
}
}

Expand Down
25 changes: 19 additions & 6 deletions src/cli/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,24 @@ function lazyNodeParentWatch(): ParentWatch {
};
}

// why: each adapter loads on first use, so a command that never touches a TCP port loads none of them.
function tcpPorts(ports: CliEnvironmentPorts): Pick<CliEnvironment, "tcpListeners" | "tcpStreams"> {
return {
tcpListeners: ports.tcpListeners ?? {
listen: async (port) => {
const { NodeTcpListenerFactory } = await import("../ports/index.js");
return new NodeTcpListenerFactory().listen(port);
},
},
tcpStreams: ports.tcpStreams ?? {
connect: async (port, timeoutMs) => {
const { NodeTcpStreamConnector } = await import("../ports/index.js");
return new NodeTcpStreamConnector().connect(port, timeoutMs);
},
},
};
}

export function buildCliEnvironment(
ports: CliEnvironmentPorts,
env: NodeJS.ProcessEnv = process.env,
Expand Down Expand Up @@ -419,12 +437,7 @@ export function buildCliEnvironment(
return new FetchHttpJsonClient().get(url, token);
},
},
tcpStreams: ports.tcpStreams ?? {
connect: async (port, timeoutMs) => {
const { NodeTcpStreamConnector } = await import("../ports/index.js");
return new NodeTcpStreamConnector().connect(port, timeoutMs);
},
},
...tcpPorts(ports),
...(env.SIMLOCK_URL === undefined ? {} : { tunnelUrl: env.SIMLOCK_URL }),
...(env.SIMLOCK_TOKEN === undefined ? {} : { tunnelToken: env.SIMLOCK_TOKEN }),
writeConfigFile: async (contents) => {
Expand Down
2 changes: 2 additions & 0 deletions src/cli/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import {
import {
FakeHttpJsonClient,
FakeSystemStats,
FakeTcpListenerFactory,
FakeTcpStreamConnector,
FakeWebSocketClientConnector,
} from "../ports/index.js";
Expand Down Expand Up @@ -8508,6 +8509,7 @@ function outputCapture(ports?: CliEnvironmentPorts, env: NodeJS.ProcessEnv = {})
confirm: async () => true,
webSocket: new FakeWebSocketClientConnector(),
httpJson: new FakeHttpJsonClient(),
tcpListeners: new FakeTcpListenerFactory(),
tcpStreams: new FakeTcpStreamConnector(),
...overrides,
};
Expand Down
Loading
Loading