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, "require_installed_t3_cli npx --yes --package 't3@latest'");
112 assert.include(script, "require_installed_t3_cli npm exec --yes --package 't3@latest'");
113 assert.include(script, "npm produced no t3 executable");
114 assert.include(script, 'prepend_path_if_dir "$HOME/.local/bin"');
115 assert.include(script, `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`);
116 assert.include(script, "remote_node_satisfies_engine()");
117 assert.include(script, "function satisfiesSemverRange");
118 assert.include(script, "satisfiesSemverRange(rawVersion, range)");
119 assert.include(script, 'prepend_path_if_dir "$VOLTA_HOME/bin"');
120 assert.include(script, 'prepend_path_if_dir "$HOME/.asdf/shims"');
121 assert.include(script, 'prepend_path_if_dir "$HOME/.local/share/mise/shims"');
122 assert.include(script, 'eval "$(fnm env --shell bash)"');
123 assert.include(script, "fnm use --silent-if-unchanged");
124 assert.include(script, "fnm use default");
125 assert.include(script, 'prepend_path_if_dir "$HOME/.nodenv/shims"');
126 assert.include(script, 'NVM_DIR="$HOME/.nvm"');
127 assert.include(script, "nvm use --silent default");
128 assert.include(script, 'for T3_NODE_BIN in "$NVM_DIR"/versions/node/*/bin');
129 assert.notInclude(script, "ensure $NVM_DIR/nvm.sh is available");
130 });
131
132 it("does not hard-code a remote node engine range", () => {
133 const script = buildRemoteT3RunnerScript();
134
135 assert.include(script, "T3_NODE_ENGINE_RANGE=''");
136 assert.notInclude(script, TEST_NODE_ENGINE_RANGE);
137 });
138
139 it("shell-quotes package specs in the remote t3 runner", () => {
140 const script = buildRemoteT3RunnerScript({
141 packageSpec: "t3@nightly; touch /tmp/t3-owned",
142 });
143
144 assert.include(script, "exec npx --yes 't3@nightly; touch /tmp/t3-owned' \"$@\"");
145 assert.include(script, "exec npm exec --yes 't3@nightly; touch /tmp/t3-owned' -- \"$@\"");
146 assert.include(
147 script,
148 "require_installed_t3_cli npx --yes --package 't3@nightly; touch /tmp/t3-owned'",
149 );
150 assert.notInclude(script, "exec npx --yes t3@nightly; touch /tmp/t3-owned");
151 });
152
153 it("builds the remote t3 runner with a node script override", () => {
154 const script = buildRemoteT3RunnerScript({
155 nodeScriptPath: "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs",
156 });
157
158 assert.include(
159 script,
160 "T3_NODE_SCRIPT_PATH='/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs'",
161 );
162 assert.include(script, 'exec node "$T3_NODE_SCRIPT_PATH" "$@"');
163 });
164
165 it("uses the remote t3 runner for launch and pairing scripts", () => {
166 const target = {
167 alias: "devbox",
168 hostname: "devbox.example.com",
169 username: "julius",
170 port: 2222,
171 } as const;
172
173 assert.include(
174 buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
175 '[ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null',
176 );
177 assert.include(buildRemoteLaunchScript(), "RUNNER_CHANGED=1");
178 assert.include(buildRemoteLaunchScript(), "ensure_remote_node_path()");
179 assert.include(buildRemoteLaunchScript(), "if ! ensure_remote_node_path; then");
180 assert.include(
181 buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
182 `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`,
183 );
184 assert.include(
185 buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
186 "does not satisfy required range ",
187 );
188 assert.include(buildRemoteLaunchScript(), 'kill "$REMOTE_PID" 2>/dev/null || true');
189 assert.include(buildRemoteLaunchScript(), "wait_ready");
190 assert.include(buildRemoteLaunchScript(), '"$RUNNER_FILE" serve --host 127.0.0.1');
191 assert.include(buildRemoteLaunchScript(), '--base-dir "$DEFAULT_SERVER_HOME"');
192 assert.notInclude(buildRemoteLaunchScript(), "server-home");
193 assert.include(buildRemoteLaunchScript(), "Remote T3 server did not become ready");
194 assert.include(buildRemoteLaunchScript(), 'wait_ready "60000"');
195 assert.include(buildRemoteLaunchScript(), 'if [ -s "$LOG_FILE" ]; then');
196 assert.include(buildRemoteLaunchScript(), "It wrote nothing to %s");
197 assert.include(buildRemoteLaunchScript({ packageSpec: "t3@nightly" }), "t3@nightly");
198 assert.include(
199 buildRemotePairingScript(target),
200 '"$RUNNER_FILE" auth pairing create --base-dir "$PAIRING_BASE_DIR" --json',
201 );
202 assert.include(buildRemotePairingScript(target), 'PAIRING_BASE_DIR="$DEFAULT_SERVER_HOME"');
203 assert.notInclude(buildRemotePairingScript(target), "server-home");
204 assert.include(buildRemotePairingScript(target, { packageSpec: "t3@nightly" }), "t3@nightly");
205 assert.include(
206 buildRemoteStopScript(target),
207 'if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ]',
208 );
209 assert.include(buildRemoteStopScript(target), 'kill "$REMOTE_PID" 2>/dev/null || true');
210 assert.include(buildRemoteStopScript(target), 'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"');
211 assert.include(
212 buildRemoteLaunchScript(),
213 'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"',
214 );
215 assert.include(buildRemoteLaunchScript(), "resolve_default_runtime_port()");
216 assert.include(
217 buildRemoteLaunchScript(),
218 'DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port',
219 );
220 assert.include(
221 buildRemoteLaunchScript(),
222 "if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port))",
223 );
224 assert.include(buildRemoteLaunchScript(), 'PID_TO_STOP="${REMOTE_PID:-$DEFAULT_RUNTIME_PID}"');
225 assert.include(buildRemoteLaunchScript(), 'REMOTE_PORT="$DEFAULT_REMOTE_PORT"');
226 assert.include(buildRemoteLaunchScript(), 'rm -f "$PID_FILE"');
227 assert.include(buildRemoteLaunchScript(), "printf 'external\\n' >\"$MANAGED_FILE\"");
228 assert.include(buildRemoteLaunchScript(), 'if [ -z "$REMOTE_PORT" ]; then');
229 assert.isBelow(
230 buildRemoteLaunchScript().indexOf('if [ "$REMOTE_MANAGED" = "managed" ]'),
231 buildRemoteLaunchScript().indexOf("printf 'external\\n' >\"$MANAGED_FILE\""),
232 );
233 assert.isBelow(
234 buildRemoteLaunchScript().indexOf('DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port'),
235 buildRemoteLaunchScript().indexOf('elif [ -n "$REMOTE_PID" ]'),
236 );
237 });
238
239 it.effect("accepts launch JSON after remote shell startup noise", () => {
240 const target = {
241 alias: "devbox",
242 hostname: "devbox.example.com",
243 username: "julius",
244 port: 2222,
245 } as const;
246 const spawnedCommands: Array<ReadonlyArray<string>> = [];
247 const spawner = ChildProcessSpawner.make((command) =>
248 Effect.sync(() => {
249 spawnedCommands.push(commandArgs(command));
250 return makeSuccessfulProcess('loaded nvm default\n{"remotePort":3774}\n');
251 }),
252 );
253 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
254 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
255
256 return Effect.gen(function* () {
257 const result = yield* launchOrReuseRemoteServer(target);
258 assert.equal(result.remotePort, 3774);
259 assert.deepEqual(spawnedCommands[0]?.slice(-5, -1), ["sh", "-l", "-s", "--"]);
260 }).pipe(Effect.provide(processLayer));
261 });
262
263 it.effect("allows cold remote launches to exceed the default SSH command timeout", () => {
264 const target = {
265 alias: "devbox",
266 hostname: "devbox.example.com",
267 username: "julius",
268 port: 2222,
269 } as const;
270 const spawner = ChildProcessSpawner.make(() =>
271 Effect.succeed(makeDelayedSuccessfulProcess('{"remotePort":3774}\n', 75_000)),
272 );
273 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
274 const processLayer = Layer.mergeAll(NodeServices.layer, spawnerLayer, TestClock.layer());
275
276 return Effect.gen(function* () {
277 const fiber = yield* Effect.forkChild(launchOrReuseRemoteServer(target));
278 yield* Effect.yieldNow;
279 yield* TestClock.adjust(Duration.seconds(75));
280
281 const result = yield* Fiber.join(fiber);
282 assert.equal(result.remotePort, 3774);
283 }).pipe(Effect.provide(processLayer));
284 });
285
286 it("allows the remote port picker to run without a state file path", () => {
287 assert.include(REMOTE_PICK_PORT_SCRIPT, 'const filePath = process.argv[2] ?? "";');
288 });
289
290 it.effect("bounds each HTTP readiness probe so retries cannot hang on one request", () =>
291 Effect.gen(function* () {
292 const fiber = yield* Effect.forkChild(
293 Effect.result(
294 waitForHttpReady({
295 baseUrl: "http://127.0.0.1:41773/",
296 timeoutMs: 1_000,
297 intervalMs: 100,
298 probeTimeoutMs: 250,
299 }),
300 ),
301 );
302 yield* Effect.yieldNow;
303 yield* TestClock.adjust(Duration.millis(1_000));
304
305 const result = yield* Fiber.join(fiber);
306
307 assert.isTrue(Result.isFailure(result));
308 if (Result.isFailure(result)) {
309 assert.include(result.failure.message, "Timed out waiting 1000ms");
310 }
311 }).pipe(
312 Effect.provide(
313 Layer.merge(TestClock.layer(), Layer.succeed(HttpClient.HttpClient, hangingHttpClient)),
314 ),
315 ),
316 );
317
318 it("preserves primitive readiness reason values in diagnostic output", () => {
319 assert.deepEqual(
320 describeReadinessCause({
321 _tag: "HttpClientError",
322 message: "Backend readiness probe failed.",
323 reason: "authentication failed",
324 cause: "upstream closed",
325 }),
326 {
327 _tag: "HttpClientError",
328 message: "Backend readiness probe failed.",
329 reason: "authentication failed",
330 cause: "upstream closed",
331 },
332 );
333 });
334
335 it.effect("accepts pretty-printed pairing JSON from the remote CLI", () => {
336 const target = {
337 alias: "devbox",
338 hostname: "devbox.example.com",
339 username: "julius",
340 port: 2222,
341 } as const;
342 const spawner = ChildProcessSpawner.make(() =>
343 Effect.succeed(
344 makeSuccessfulProcess(`{
345 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
346 "credential": "LCL4R2TPHDKQ",
347 "scopes": ["orchestration:read"],
348 "expiresAt": "2026-04-29T01:01:20.994Z"
349}
350
351`),
352 ),
353 );
354 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
355 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
356 return Effect.gen(function* () {
357 const result = yield* issueRemotePairingToken(target);
358 assert.equal(result.credential, "LCL4R2TPHDKQ");
359 }).pipe(Effect.provide(processLayer));
360 });
361
362 it.effect("accepts pretty-printed pairing JSON after remote shell startup noise", () => {
363 const target = {
364 alias: "devbox",
365 hostname: "devbox.example.com",
366 username: "julius",
367 port: 2222,
368 } as const;
369 const spawner = ChildProcessSpawner.make(() =>
370 Effect.succeed(
371 makeSuccessfulProcess(`loaded nvm default
372{
373 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
374 "credential": "LCL4R2TPHDKQ",
375 "scopes": ["orchestration:read"],
376 "expiresAt": "2026-04-29T01:01:20.994Z"
377}
378
379`),
380 ),
381 );
382 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
383 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
384 return Effect.gen(function* () {
385 const result = yield* issueRemotePairingToken(target);
386 assert.equal(result.credential, "LCL4R2TPHDKQ");
387 }).pipe(Effect.provide(processLayer));
388 });
389
390 it.effect("closes the tunnel scope and starts fresh after disconnect", () => {
391 const spawnedCommands: Array<ReadonlyArray<string>> = [];
392 let tunnelKillCount = 0;
393 let stopCommandCount = 0;
394 const spawner = ChildProcessSpawner.make((command) =>
395 Effect.sync(() => {
396 const args = commandArgs(command);
397 spawnedCommands.push(args);
398 if (args.includes("-N")) {
399 return makeRunningProcess(() => {
400 tunnelKillCount += 1;
401 });
402 }
403 if (args.includes("sh") && args.includes("--")) {
404 return makeSuccessfulProcess('{"remotePort":3773}\n');
405 }
406 if (args.includes("sh")) {
407 stopCommandCount += 1;
408 return makeSuccessfulProcess('{"stopped":true}\n');
409 }
410 return makeSuccessfulProcess("\n");
411 }),
412 );
413 const layer = Layer.mergeAll(
414 NodeServices.layer,
415 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
416 Layer.succeed(HttpClient.HttpClient, testHttpClient),
417 Layer.succeed(NetService.NetService, testNetService),
418 SshPasswordPrompt.disabledLayer,
419 SshEnvironmentManager.layer(),
420 );
421 const target = {
422 alias: "devbox",
423 hostname: "devbox.example.com",
424 username: "julius",
425 port: 2222,
426 } as const;
427
428 return Effect.gen(function* () {
429 const manager = yield* SshEnvironmentManager;
430
431 const first = yield* manager.ensureEnvironment(target);
432 assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
433 const firstTunnelArgs = spawnedCommands.find((args) => args.includes("-N"));
434 assert.isDefined(firstTunnelArgs);
435 assert.include(firstTunnelArgs, "ControlMaster=no");
436 assert.include(firstTunnelArgs, "ControlPath=none");
437 assert.include(firstTunnelArgs, "ControlPersist=no");
438
439 yield* manager.disconnectEnvironment(target);
440 assert.equal(tunnelKillCount, 1);
441 assert.equal(stopCommandCount, 1);
442
443 yield* manager.ensureEnvironment(target);
444
445 assert.equal(spawnedCommands.filter((args) => args.includes("-N")).length, 2);
446 assert.equal(tunnelKillCount, 1);
447 }).pipe(Effect.provide(layer), Effect.scoped);
448 });
449});