The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { assert, describe, it } from "@effect/vitest"; |
| 2 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 3 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 4 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Fiber from "effect/Fiber"; |
| 7 | import * as Layer from "effect/Layer"; |
| 8 | import * as Result from "effect/Result"; |
| 9 | import * as Schema from "effect/Schema"; |
| 10 | import * as Sink from "effect/Sink"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import * as TestClock from "effect/testing/TestClock"; |
| 13 | import { ChildProcess, ChildProcessSpawner } from "effect/process"; |
| 14 | |
| 15 | import { baseSshArgs, parseSshResolveOutput, remoteStateKey, runSshCommand } from "./command.ts"; |
| 16 | import { SshCommandError } from "./errors.ts"; |
| 17 | |
| 18 | const encoder = new TextEncoder(); |
| 19 | const isSshCommandError = Schema.is(SshCommandError); |
| 20 | |
| 21 | const makeFailedProcess = (input: { readonly stdout: string; readonly stderr?: string }) => { |
| 22 | const stdoutStream = Stream.make(encoder.encode(input.stdout)); |
| 23 | const stderrStream = input.stderr ? Stream.make(encoder.encode(input.stderr)) : Stream.empty; |
| 24 | return ChildProcessSpawner.makeHandle({ |
| 25 | pid: ChildProcessSpawner.ProcessId(123), |
| 26 | stdout: stdoutStream, |
| 27 | stderr: stderrStream, |
| 28 | all: Stream.empty, |
| 29 | exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), |
| 30 | isRunning: Effect.succeed(false), |
| 31 | kill: () => Effect.void, |
| 32 | stdin: Sink.drain, |
| 33 | getInputFd: () => Sink.drain, |
| 34 | getOutputFd: () => Stream.empty, |
| 35 | unref: Effect.succeed(Effect.void), |
| 36 | }); |
| 37 | }; |
| 38 | |
| 39 | describe("ssh command", () => { |
| 40 | it.effect("parses resolved ssh config output into a target", () => |
| 41 | Effect.sync(() => { |
| 42 | assert.deepEqual( |
| 43 | parseSshResolveOutput( |
| 44 | "devbox", |
| 45 | ["hostname devbox.example.com", "user julius", "port 2222", ""].join("\n"), |
| 46 | ), |
| 47 | { |
| 48 | alias: "devbox", |
| 49 | hostname: "devbox.example.com", |
| 50 | username: "julius", |
| 51 | port: 2222, |
| 52 | }, |
| 53 | ); |
| 54 | }), |
| 55 | ); |
| 56 | |
| 57 | it.effect("passes an option-shaped alias to ssh as the destination", () => { |
| 58 | const spawned: Array<ReadonlyArray<string>> = []; |
| 59 | const spawner = ChildProcessSpawner.make((command) => { |
| 60 | if (ChildProcess.isStandardCommand(command)) spawned.push(command.args.map(String)); |
| 61 | return Effect.succeed(makeFailedProcess({ stdout: "", stderr: "bad hostname\n" })); |
| 62 | }); |
| 63 | return runSshCommand( |
| 64 | { alias: "-oProxyCommand=false", hostname: "devbox", username: null, port: null }, |
| 65 | { remoteCommandArgs: ["sh", "-s"] }, |
| 66 | ).pipe( |
| 67 | Effect.flip, |
| 68 | Effect.map(() => { |
| 69 | assert.deepEqual(spawned[0]?.slice(-4), ["--", "-oProxyCommand=false", "sh", "-s"]); |
| 70 | }), |
| 71 | Effect.provide( |
| 72 | Layer.merge( |
| 73 | Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), |
| 74 | Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 75 | ), |
| 76 | ), |
| 77 | ); |
| 78 | }); |
| 79 | |
| 80 | it.effect("overrides an alias's RemoteCommand and RequestTTY", () => |
| 81 | Effect.sync(() => { |
| 82 | assert.deepEqual( |
| 83 | baseSshArgs( |
| 84 | { alias: "devbox", hostname: "devbox", username: null, port: 2222 }, |
| 85 | { batchMode: "yes" }, |
| 86 | ), |
| 87 | [ |
| 88 | "-o", |
| 89 | "BatchMode=yes", |
| 90 | "-o", |
| 91 | "ConnectTimeout=10", |
| 92 | "-o", |
| 93 | "RemoteCommand=none", |
| 94 | "-o", |
| 95 | "RequestTTY=no", |
| 96 | "-p", |
| 97 | "2222", |
| 98 | ], |
| 99 | ); |
| 100 | }), |
| 101 | ); |
| 102 | |
| 103 | // Remote servers store state under this key, so it must not change across releases. |
| 104 | it.effect("derives a stable remote state key", () => |
| 105 | Effect.gen(function* () { |
| 106 | assert.equal( |
| 107 | yield* remoteStateKey({ |
| 108 | alias: "devbox", |
| 109 | hostname: "devbox.example.com", |
| 110 | username: "julius", |
| 111 | port: 2222, |
| 112 | }), |
| 113 | "711bc738002d72fd", |
| 114 | ); |
| 115 | assert.equal( |
| 116 | yield* remoteStateKey({ |
| 117 | alias: "fixture", |
| 118 | hostname: "fixture", |
| 119 | username: null, |
| 120 | port: null, |
| 121 | }), |
| 122 | "326264c4f08c8a0c", |
| 123 | ); |
| 124 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 125 | ); |
| 126 | |
| 127 | it.live.each([ |
| 128 | { name: "default head", keepErrorOutputTail: undefined, exitCode: 1, stderr: "" }, |
| 129 | { |
| 130 | name: "opt-in tail", |
| 131 | keepErrorOutputTail: true, |
| 132 | exitCode: 1, |
| 133 | stderr: "stderr failure ".repeat(400), |
| 134 | }, |
| 135 | { name: "successful output", keepErrorOutputTail: true, exitCode: 0, stderr: "" }, |
| 136 | ])("preserves process output: $name", ({ keepErrorOutputTail, exitCode, stderr }) => |
| 137 | Effect.gen(function* () { |
| 138 | const prefix = `HEAD\n${"verbose-prefix ".repeat(400)}`; |
| 139 | const secret = "synthetic-secret".repeat(400); |
| 140 | const diagnostic = "\nPANIC: emulator SDK is broken\n"; |
| 141 | const stdout = `${prefix}{"credential":"${secret}"}${diagnostic}`; |
| 142 | const nativeSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 143 | // Replace only the SSH endpoint with a real, deterministic process. |
| 144 | const spawner = ChildProcessSpawner.make(() => |
| 145 | nativeSpawner.spawn( |
| 146 | ChildProcess.make(process.execPath, [ |
| 147 | "-e", |
| 148 | `process.stdout.write(${JSON.stringify(stdout)}); process.stderr.write(${JSON.stringify(stderr)}); process.exitCode = ${exitCode};`, |
| 149 | ]), |
| 150 | ), |
| 151 | ); |
| 152 | const command = runSshCommand( |
| 153 | { alias: "synthetic-fixture", hostname: "synthetic-fixture", username: null, port: null }, |
| 154 | keepErrorOutputTail === undefined ? {} : { keepErrorOutputTail }, |
| 155 | ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)); |
| 156 | if (exitCode === 0) { |
| 157 | assert.deepEqual(yield* command, { stdout, stderr }); |
| 158 | return; |
| 159 | } |
| 160 | const failure = yield* Effect.flip(command); |
| 161 | assert.instanceOf(failure, SshCommandError); |
| 162 | assert.equal(failure.exitCode, 1); |
| 163 | assert.equal(failure.stderr, stderr); |
| 164 | assert.equal(failure.message, stderr.trim() || failure.stdout?.trim()); |
| 165 | const redacted = `${prefix}{"credential":"[redacted]"}${diagnostic}`; |
| 166 | assert.equal( |
| 167 | failure.stdout, |
| 168 | keepErrorOutputTail |
| 169 | ? `[truncated]\n${redacted.slice(-4_000)}` |
| 170 | : `${redacted.slice(0, 4_000)}\n[truncated]`, |
| 171 | ); |
| 172 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 173 | ); |
| 174 | |
| 175 | it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( |
| 176 | "a timed-out command leaves no helper running that ignored SIGTERM", |
| 177 | () => |
| 178 | Effect.gen(function* () { |
| 179 | const nativeSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 180 | // Stands in for ssh and a ProxyCommand: ssh exits on SIGTERM, the proxy ignores it. |
| 181 | const spawner = ChildProcessSpawner.make((command) => |
| 182 | nativeSpawner.spawn( |
| 183 | ChildProcess.make( |
| 184 | process.execPath, |
| 185 | [ |
| 186 | "-e", |
| 187 | `const proxy = require("node:child_process").spawn("sh", ["-c", "trap '' TERM; exec sleep 60"], { stdio: "ignore" }); |
| 188 | process.stdout.write(proxy.pid + "\\n"); |
| 189 | setInterval(() => {}, 1000);`, |
| 190 | ], |
| 191 | command._tag === "StandardCommand" ? command.options : {}, |
| 192 | ), |
| 193 | ), |
| 194 | ); |
| 195 | const failure = yield* runSshCommand( |
| 196 | { alias: "synthetic-fixture", hostname: "synthetic-fixture", username: null, port: null }, |
| 197 | { timeoutMs: 1_000, keepErrorOutputTail: true }, |
| 198 | ).pipe( |
| 199 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 200 | Effect.flip, |
| 201 | ); |
| 202 | assert.instanceOf(failure, SshCommandError); |
| 203 | assert.equal(failure.message, "SSH command timed out after 1000ms."); |
| 204 | const proxyPid = Number(failure.stdout?.trim()); |
| 205 | assert.isTrue(Number.isSafeInteger(proxyPid) && proxyPid > 1); |
| 206 | const state = (yield* nativeSpawner.string( |
| 207 | ChildProcess.make("ps", ["-p", String(proxyPid), "-o", "stat="]), |
| 208 | )).trim(); |
| 209 | if (state !== "" && !state.startsWith("Z")) process.kill(proxyPid, "SIGKILL"); |
| 210 | assert.isTrue(state === "" || state.startsWith("Z"), `proxy still running (${state})`); |
| 211 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 212 | ); |
| 213 | |
| 214 | it.live("enables server-alive checks for long remote commands", () => |
| 215 | Effect.gen(function* () { |
| 216 | // Ask OpenSSH for its effective configuration without opening a connection. |
| 217 | const { stdout } = yield* runSshCommand( |
| 218 | { alias: "synthetic-fixture", hostname: "synthetic-fixture", username: null, port: null }, |
| 219 | { preHostArgs: ["-F", "none", "-G"], timeoutMs: 900_000 }, |
| 220 | ); |
| 221 | assert.match(stdout, /^serveraliveinterval 15\r?$/mu); |
| 222 | assert.match(stdout, /^serveralivecountmax 3\r?$/mu); |
| 223 | }).pipe(Effect.provide(NodeServices.layer)), |
| 224 | ); |
| 225 | |
| 226 | it.effect("redacts credentials from stdout in non-zero command failures", () => { |
| 227 | const spawner = ChildProcessSpawner.make(() => |
| 228 | Effect.succeed(makeFailedProcess({ stdout: '{"credential":"pairing-secret"}\n' })), |
| 229 | ); |
| 230 | const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner); |
| 231 | const layerProcess = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerSpawner); |
| 232 | |
| 233 | return Effect.gen(function* () { |
| 234 | const result = yield* Effect.result( |
| 235 | runSshCommand( |
| 236 | { |
| 237 | alias: "devbox", |
| 238 | hostname: "devbox.example.com", |
| 239 | username: "julius", |
| 240 | port: 2222, |
| 241 | }, |
| 242 | { remoteCommandArgs: ["sh", "-s"] }, |
| 243 | ), |
| 244 | ); |
| 245 | |
| 246 | assert.isTrue(Result.isFailure(result)); |
| 247 | if (Result.isFailure(result)) { |
| 248 | assert.instanceOf(result.failure, SshCommandError); |
| 249 | assert.equal(result.failure.message, '{"credential":"[redacted]"}'); |
| 250 | assert.equal(result.failure.stdout, '{"credential":"[redacted]"}\n'); |
| 251 | } |
| 252 | }).pipe(Effect.provide(layerProcess)); |
| 253 | }); |
| 254 | |
| 255 | it.effect("keeps redacted output the command emitted before timing out", () => { |
| 256 | const spawner = ChildProcessSpawner.make(() => |
| 257 | Effect.succeed( |
| 258 | ChildProcessSpawner.makeHandle({ |
| 259 | pid: ChildProcessSpawner.ProcessId(123), |
| 260 | stdout: Stream.concat( |
| 261 | Stream.make(encoder.encode('PROGRESS: extracting\n{"credential":"pairing-secret"}\n')), |
| 262 | Stream.never, |
| 263 | ), |
| 264 | stderr: Stream.concat( |
| 265 | Stream.make(encoder.encode("REMOTE: waiting for archive extraction\n")), |
| 266 | Stream.never, |
| 267 | ), |
| 268 | all: Stream.empty, |
| 269 | exitCode: Effect.never, |
| 270 | isRunning: Effect.succeed(true), |
| 271 | kill: () => Effect.void, |
| 272 | stdin: Sink.drain, |
| 273 | getInputFd: () => Sink.drain, |
| 274 | getOutputFd: () => Stream.empty, |
| 275 | unref: Effect.succeed(Effect.void), |
| 276 | }), |
| 277 | ), |
| 278 | ); |
| 279 | const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner); |
| 280 | |
| 281 | return Effect.gen(function* () { |
| 282 | const fiber = yield* runSshCommand( |
| 283 | { alias: "devbox", hostname: "devbox", username: null, port: null }, |
| 284 | { remoteCommandArgs: ["sh", "-s"], timeoutMs: 1_000, keepErrorOutputTail: true }, |
| 285 | ).pipe(Effect.flip, Effect.forkChild); |
| 286 | yield* TestClock.adjust("1 second"); |
| 287 | const failure = yield* Fiber.join(fiber); |
| 288 | |
| 289 | assert.instanceOf(failure, SshCommandError); |
| 290 | assert.equal(failure.exitCode, null); |
| 291 | assert.equal(failure.stdout, 'PROGRESS: extracting\n{"credential":"[redacted]"}\n'); |
| 292 | assert.equal(failure.stderr, "REMOTE: waiting for archive extraction\n"); |
| 293 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerSpawner))); |
| 294 | }); |
| 295 | |
| 296 | const changedKeyStderr = |
| 297 | "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\r\n" + |
| 298 | "@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @\r\n" + |
| 299 | " ssh-keygen -f '/home/me/.ssh/known_hosts' -R 'devbox'\r\n" + |
| 300 | "Host key verification failed.\r\n"; |
| 301 | |
| 302 | it.effect.each([ |
| 303 | { |
| 304 | name: "quotes the terminal command for a POSIX shell", |
| 305 | target: { alias: "my host", username: "o'brien" }, |
| 306 | platform: "linux", |
| 307 | stderr: "Host key verification failed.\r\n", |
| 308 | expected: ["`ssh 'o'\\''brien@my host'`"], |
| 309 | }, |
| 310 | { |
| 311 | name: "quotes the terminal command for a Windows shell", |
| 312 | target: { alias: "my host", username: "me" }, |
| 313 | platform: "win32", |
| 314 | stderr: "Host key verification failed.\r\n", |
| 315 | expected: ['`ssh "me@my host"`'], |
| 316 | }, |
| 317 | { |
| 318 | name: "keeps an option-shaped alias out of the option list", |
| 319 | target: { alias: "-oProxyCommand=false", username: null }, |
| 320 | platform: "linux", |
| 321 | stderr: "Host key verification failed.\r\n", |
| 322 | expected: ["`ssh -- -oProxyCommand=false`"], |
| 323 | }, |
| 324 | { |
| 325 | name: "tells the user to remove a changed host key first", |
| 326 | target: { alias: "devbox", username: null }, |
| 327 | platform: "linux", |
| 328 | stderr: changedKeyStderr, |
| 329 | expected: ["has changed", "`ssh-keygen -R`", "`ssh devbox`", "-R 'devbox'"], |
| 330 | }, |
| 331 | ] as const)("$name", ({ target, platform, stderr, expected }) => { |
| 332 | const spawner = ChildProcessSpawner.make(() => |
| 333 | Effect.succeed(makeFailedProcess({ stdout: "", stderr })), |
| 334 | ); |
| 335 | return runSshCommand({ ...target, hostname: "devbox", port: null }).pipe( |
| 336 | Effect.flip, |
| 337 | Effect.map((error) => { |
| 338 | assert.isTrue(isSshCommandError(error)); |
| 339 | for (const text of expected) assert.include(error.message, text); |
| 340 | if (isSshCommandError(error)) assert.equal(error.stderr, stderr); |
| 341 | }), |
| 342 | Effect.provideService(HostProcess.Platform, platform), |
| 343 | Effect.provide( |
| 344 | Layer.mergeAll( |
| 345 | NodeServices.layer, |
| 346 | NodeCrypto.layer, |
| 347 | Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 348 | ), |
| 349 | ), |
| 350 | ); |
| 351 | }); |
| 352 | }); |