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