Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as NetService from "@t3tools/shared/Net";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as Layer from "effect/Layer";
8import * as Result from "effect/Result";
9import * as Sink from "effect/Sink";
10import * as Stream from "effect/Stream";
11import { TestClock } from "effect/testing";
12import { HttpClient, HttpClientResponse } from "effect/unstable/http";
13import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
14
15import { SshPasswordPrompt } from "./auth.ts";
16import {
17 buildRemoteLaunchScript,
18 buildRemotePairingScript,
19 buildRemoteStopScript,
20 buildRemoteT3RunnerScript,
21 describeReadinessCause,
22 issueRemotePairingToken,
23 launchOrReuseRemoteServer,
24 REMOTE_PICK_PORT_SCRIPT,
25 SshEnvironmentManager,
26 waitForHttpReady,
27} from "./tunnel.ts";
28
29const TEST_NODE_ENGINE_RANGE = "^22.16 || ^23.11 || >=24.10";
30
31const makeSuccessfulProcess = (stdout: string) => {
32 const stdoutStream = Stream.make(new TextEncoder().encode(stdout));
33 return ChildProcessSpawner.makeHandle({
34 pid: ChildProcessSpawner.ProcessId(123),
35 stdout: stdoutStream,
36 stderr: Stream.empty,
37 all: stdoutStream,
38 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
39 isRunning: Effect.succeed(false),
40 kill: () => Effect.void,
41 stdin: Sink.drain,
42 getInputFd: () => Sink.drain,
43 getOutputFd: () => Stream.empty,
44 unref: Effect.succeed(Effect.void),
45 });
46};
47
48const makeDelayedSuccessfulProcess = (stdout: string, delayMs: number) => {
49 const process = makeSuccessfulProcess(stdout);
50 return {
51 ...process,
52 exitCode: Effect.sleep(Duration.millis(delayMs)).pipe(
53 Effect.as(ChildProcessSpawner.ExitCode(0)),
54 ),
55 };
56};
57
58const makeRunningProcess = (onKill: () => void) => {
59 let finish: ((exitCode: ChildProcessSpawner.ExitCode) => void) | null = null;
60 return ChildProcessSpawner.makeHandle({
61 pid: ChildProcessSpawner.ProcessId(123),
62 stdout: Stream.empty,
63 stderr: Stream.empty,
64 all: Stream.empty,
65 exitCode: Effect.callback<ChildProcessSpawner.ExitCode>((resume) => {
66 finish = (exitCode) => resume(Effect.succeed(exitCode));
67 return Effect.sync(() => {
68 finish = null;
69 });
70 }),
71 isRunning: Effect.succeed(true),
72 kill: () =>
73 Effect.sync(() => {
74 onKill();
75 finish?.(ChildProcessSpawner.ExitCode(143));
76 }),
77 stdin: Sink.drain,
78 getInputFd: () => Sink.drain,
79 getOutputFd: () => Stream.empty,
80 unref: Effect.succeed(Effect.void),
81 });
82};
83
84const testHttpClient = HttpClient.make((request) =>
85 Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))),
86);
87
88const hangingHttpClient = HttpClient.make(() => Effect.never);
89
90const testNetService = NetService.NetService.of({
91 canListenOnHost: () => Effect.succeed(true),
92 isPortAvailableOnLoopback: () => Effect.succeed(true),
93 hasListenerOnHost: () => Effect.succeed(false),
94 reserveLoopbackPort: () => Effect.succeed(41_773),
95 findAvailablePort: (preferred) => Effect.succeed(preferred),
96});
97
98function commandArgs(command: ChildProcess.Command): ReadonlyArray<string> {
99 return command._tag === "StandardCommand" ? command.args : [];
100}
101
102describe("ssh tunnel scripts", () => {
103 it("builds the remote t3 runner with npx and npm fallbacks", () => {
104 const script = buildRemoteT3RunnerScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE });
105
106 assert.include(script, "T3_NODE_SCRIPT_PATH=''");
107 assert.include(script, 'exec t3 "$@"');
108 assert.include(script, "exec npx --yes 't3@latest' \"$@\"");
109 assert.include(script, "exec npm exec --yes 't3@latest' -- \"$@\"");
110 assert.include(script, "could not install 't3@latest'");
111 assert.include(script, 'prepend_path_if_dir "$HOME/.local/bin"');
112 assert.include(script, `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`);
113 assert.include(script, "remote_node_satisfies_engine()");
114 assert.include(script, "function satisfiesSemverRange");
115 assert.include(script, "satisfiesSemverRange(rawVersion, range)");
116 assert.include(script, 'prepend_path_if_dir "$VOLTA_HOME/bin"');
117 assert.include(script, 'prepend_path_if_dir "$HOME/.asdf/shims"');
118 assert.include(script, 'prepend_path_if_dir "$HOME/.local/share/mise/shims"');
119 assert.include(script, 'eval "$(fnm env --shell bash)"');
120 assert.include(script, "fnm use --silent-if-unchanged");
121 assert.include(script, "fnm use default");
122 assert.include(script, 'prepend_path_if_dir "$HOME/.nodenv/shims"');
123 assert.include(script, 'NVM_DIR="$HOME/.nvm"');
124 assert.include(script, "nvm use --silent default");
125 assert.include(script, 'for T3_NODE_BIN in "$NVM_DIR"/versions/node/*/bin');
126 assert.notInclude(script, "ensure $NVM_DIR/nvm.sh is available");
127 });
128
129 it("does not hard-code a remote node engine range", () => {
130 const script = buildRemoteT3RunnerScript();
131
132 assert.include(script, "T3_NODE_ENGINE_RANGE=''");
133 assert.notInclude(script, TEST_NODE_ENGINE_RANGE);
134 });
135
136 it("shell-quotes package specs in the remote t3 runner", () => {
137 const script = buildRemoteT3RunnerScript({
138 packageSpec: "t3@nightly; touch /tmp/t3-owned",
139 });
140
141 assert.include(script, "exec npx --yes 't3@nightly; touch /tmp/t3-owned' \"$@\"");
142 assert.include(script, "exec npm exec --yes 't3@nightly; touch /tmp/t3-owned' -- \"$@\"");
143 assert.notInclude(script, "exec npx --yes t3@nightly; touch /tmp/t3-owned");
144 });
145
146 it("builds the remote t3 runner with a node script override", () => {
147 const script = buildRemoteT3RunnerScript({
148 nodeScriptPath: "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs",
149 });
150
151 assert.include(
152 script,
153 "T3_NODE_SCRIPT_PATH='/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs'",
154 );
155 assert.include(script, 'exec node "$T3_NODE_SCRIPT_PATH" "$@"');
156 });
157
158 it("uses the remote t3 runner for launch and pairing scripts", () => {
159 const target = {
160 alias: "devbox",
161 hostname: "devbox.example.com",
162 username: "julius",
163 port: 2222,
164 } as const;
165
166 assert.include(
167 buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
168 '[ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null',
169 );
170 assert.include(buildRemoteLaunchScript(), "RUNNER_CHANGED=1");
171 assert.include(buildRemoteLaunchScript(), "ensure_remote_node_path()");
172 assert.include(buildRemoteLaunchScript(), "if ! ensure_remote_node_path; then");
173 assert.include(
174 buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
175 `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`,
176 );
177 assert.include(
178 buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
179 "does not satisfy required range ",
180 );
181 assert.include(buildRemoteLaunchScript(), 'kill "$REMOTE_PID" 2>/dev/null || true');
182 assert.include(buildRemoteLaunchScript(), "wait_ready");
183 assert.include(buildRemoteLaunchScript(), '"$RUNNER_FILE" serve --host 127.0.0.1');
184 assert.include(buildRemoteLaunchScript(), '--base-dir "$DEFAULT_SERVER_HOME"');
185 assert.notInclude(buildRemoteLaunchScript(), "server-home");
186 assert.include(buildRemoteLaunchScript(), "Remote T3 server did not become ready");
187 assert.include(buildRemoteLaunchScript(), 'wait_ready "60000"');
188 assert.include(buildRemoteLaunchScript({ packageSpec: "t3@nightly" }), "t3@nightly");
189 assert.include(
190 buildRemotePairingScript(target),
191 '"$RUNNER_FILE" auth pairing create --base-dir "$PAIRING_BASE_DIR" --json',
192 );
193 assert.include(buildRemotePairingScript(target), 'PAIRING_BASE_DIR="$DEFAULT_SERVER_HOME"');
194 assert.notInclude(buildRemotePairingScript(target), "server-home");
195 assert.include(buildRemotePairingScript(target, { packageSpec: "t3@nightly" }), "t3@nightly");
196 assert.include(
197 buildRemoteStopScript(target),
198 'if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ]',
199 );
200 assert.include(buildRemoteStopScript(target), 'kill "$REMOTE_PID" 2>/dev/null || true');
201 assert.include(buildRemoteStopScript(target), 'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"');
202 assert.include(
203 buildRemoteLaunchScript(),
204 'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"',
205 );
206 assert.include(buildRemoteLaunchScript(), "resolve_default_runtime_port()");
207 assert.include(
208 buildRemoteLaunchScript(),
209 'DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port',
210 );
211 assert.include(
212 buildRemoteLaunchScript(),
213 "if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port))",
214 );
215 assert.include(buildRemoteLaunchScript(), 'PID_TO_STOP="${REMOTE_PID:-$DEFAULT_RUNTIME_PID}"');
216 assert.include(buildRemoteLaunchScript(), 'REMOTE_PORT="$DEFAULT_REMOTE_PORT"');
217 assert.include(buildRemoteLaunchScript(), 'rm -f "$PID_FILE"');
218 assert.include(buildRemoteLaunchScript(), "printf 'external\\n' >\"$MANAGED_FILE\"");
219 assert.include(buildRemoteLaunchScript(), 'if [ -z "$REMOTE_PORT" ]; then');
220 assert.isBelow(
221 buildRemoteLaunchScript().indexOf('if [ "$REMOTE_MANAGED" = "managed" ]'),
222 buildRemoteLaunchScript().indexOf("printf 'external\\n' >\"$MANAGED_FILE\""),
223 );
224 assert.isBelow(
225 buildRemoteLaunchScript().indexOf('DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port'),
226 buildRemoteLaunchScript().indexOf('elif [ -n "$REMOTE_PID" ]'),
227 );
228 });
229
230 it.effect("accepts launch JSON after remote shell startup noise", () => {
231 const target = {
232 alias: "devbox",
233 hostname: "devbox.example.com",
234 username: "julius",
235 port: 2222,
236 } as const;
237 const spawner = ChildProcessSpawner.make(() =>
238 Effect.succeed(makeSuccessfulProcess('loaded nvm default\n{"remotePort":3774}\n')),
239 );
240 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
241 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
242
243 return Effect.gen(function* () {
244 const result = yield* launchOrReuseRemoteServer(target);
245 assert.equal(result.remotePort, 3774);
246 }).pipe(Effect.provide(processLayer));
247 });
248
249 it.effect("allows cold remote launches to exceed the default SSH command timeout", () => {
250 const target = {
251 alias: "devbox",
252 hostname: "devbox.example.com",
253 username: "julius",
254 port: 2222,
255 } as const;
256 const spawner = ChildProcessSpawner.make(() =>
257 Effect.succeed(makeDelayedSuccessfulProcess('{"remotePort":3774}\n', 75_000)),
258 );
259 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
260 const processLayer = Layer.mergeAll(NodeServices.layer, spawnerLayer, TestClock.layer());
261
262 return Effect.gen(function* () {
263 const fiber = yield* Effect.forkChild(launchOrReuseRemoteServer(target));
264 yield* Effect.yieldNow;
265 yield* TestClock.adjust(Duration.seconds(75));
266
267 const result = yield* Fiber.join(fiber);
268 assert.equal(result.remotePort, 3774);
269 }).pipe(Effect.provide(processLayer));
270 });
271
272 it("allows the remote port picker to run without a state file path", () => {
273 assert.include(REMOTE_PICK_PORT_SCRIPT, 'const filePath = process.argv[2] ?? "";');
274 });
275
276 it.effect("bounds each HTTP readiness probe so retries cannot hang on one request", () =>
277 Effect.gen(function* () {
278 const fiber = yield* Effect.forkChild(
279 Effect.result(
280 waitForHttpReady({
281 baseUrl: "http://127.0.0.1:41773/",
282 timeoutMs: 1_000,
283 intervalMs: 100,
284 probeTimeoutMs: 250,
285 }),
286 ),
287 );
288 yield* Effect.yieldNow;
289 yield* TestClock.adjust(Duration.millis(1_000));
290
291 const result = yield* Fiber.join(fiber);
292
293 assert.isTrue(Result.isFailure(result));
294 if (Result.isFailure(result)) {
295 assert.include(result.failure.message, "Timed out waiting 1000ms");
296 }
297 }).pipe(
298 Effect.provide(
299 Layer.merge(TestClock.layer(), Layer.succeed(HttpClient.HttpClient, hangingHttpClient)),
300 ),
301 ),
302 );
303
304 it("preserves primitive readiness reason values in diagnostic output", () => {
305 assert.deepEqual(
306 describeReadinessCause({
307 _tag: "HttpClientError",
308 message: "Backend readiness probe failed.",
309 reason: "authentication failed",
310 cause: "upstream closed",
311 }),
312 {
313 _tag: "HttpClientError",
314 message: "Backend readiness probe failed.",
315 reason: "authentication failed",
316 cause: "upstream closed",
317 },
318 );
319 });
320
321 it.effect("accepts pretty-printed pairing JSON from the remote CLI", () => {
322 const target = {
323 alias: "devbox",
324 hostname: "devbox.example.com",
325 username: "julius",
326 port: 2222,
327 } as const;
328 const spawner = ChildProcessSpawner.make(() =>
329 Effect.succeed(
330 makeSuccessfulProcess(`{
331 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
332 "credential": "LCL4R2TPHDKQ",
333 "scopes": ["orchestration:read"],
334 "expiresAt": "2026-04-29T01:01:20.994Z"
335}
336
337`),
338 ),
339 );
340 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
341 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
342 return Effect.gen(function* () {
343 const result = yield* issueRemotePairingToken(target);
344 assert.equal(result.credential, "LCL4R2TPHDKQ");
345 }).pipe(Effect.provide(processLayer));
346 });
347
348 it.effect("accepts pretty-printed pairing JSON after remote shell startup noise", () => {
349 const target = {
350 alias: "devbox",
351 hostname: "devbox.example.com",
352 username: "julius",
353 port: 2222,
354 } as const;
355 const spawner = ChildProcessSpawner.make(() =>
356 Effect.succeed(
357 makeSuccessfulProcess(`loaded nvm default
358{
359 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
360 "credential": "LCL4R2TPHDKQ",
361 "scopes": ["orchestration:read"],
362 "expiresAt": "2026-04-29T01:01:20.994Z"
363}
364
365`),
366 ),
367 );
368 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
369 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
370 return Effect.gen(function* () {
371 const result = yield* issueRemotePairingToken(target);
372 assert.equal(result.credential, "LCL4R2TPHDKQ");
373 }).pipe(Effect.provide(processLayer));
374 });
375
376 it.effect("closes the tunnel scope and starts fresh after disconnect", () => {
377 const spawnedCommands: Array<ReadonlyArray<string>> = [];
378 let tunnelKillCount = 0;
379 let stopCommandCount = 0;
380 const spawner = ChildProcessSpawner.make((command) =>
381 Effect.sync(() => {
382 const args = commandArgs(command);
383 spawnedCommands.push(args);
384 if (args.includes("-N")) {
385 return makeRunningProcess(() => {
386 tunnelKillCount += 1;
387 });
388 }
389 if (args.includes("sh") && args.includes("--")) {
390 return makeSuccessfulProcess('{"remotePort":3773}\n');
391 }
392 if (args.includes("sh")) {
393 stopCommandCount += 1;
394 return makeSuccessfulProcess('{"stopped":true}\n');
395 }
396 return makeSuccessfulProcess("\n");
397 }),
398 );
399 const layer = Layer.mergeAll(
400 NodeServices.layer,
401 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
402 Layer.succeed(HttpClient.HttpClient, testHttpClient),
403 Layer.succeed(NetService.NetService, testNetService),
404 SshPasswordPrompt.disabledLayer,
405 SshEnvironmentManager.layer(),
406 );
407 const target = {
408 alias: "devbox",
409 hostname: "devbox.example.com",
410 username: "julius",
411 port: 2222,
412 } as const;
413
414 return Effect.gen(function* () {
415 const manager = yield* SshEnvironmentManager;
416
417 const first = yield* manager.ensureEnvironment(target);
418 assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
419 const firstTunnelArgs = spawnedCommands.find((args) => args.includes("-N"));
420 assert.isDefined(firstTunnelArgs);
421 assert.include(firstTunnelArgs, "ControlMaster=no");
422 assert.include(firstTunnelArgs, "ControlPath=none");
423 assert.include(firstTunnelArgs, "ControlPersist=no");
424
425 yield* manager.disconnectEnvironment(target);
426 assert.equal(tunnelKillCount, 1);
427 assert.equal(stopCommandCount, 1);
428
429 yield* manager.ensureEnvironment(target);
430
431 assert.equal(spawnedCommands.filter((args) => args.includes("-N")).length, 2);
432 assert.equal(tunnelKillCount, 1);
433 }).pipe(Effect.provide(layer), Effect.scoped);
434 });
435});