diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts index 972a9a2b150b2..2f21d264bc194 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -15,6 +15,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NetService from "@t3tools/shared/Net"; import { SshCommandError } from "@t3tools/ssh/errors"; +import { SYMLINK_HINT } from "./sshDeviceScript.ts"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Deferred from "effect/Deferred"; @@ -525,14 +526,14 @@ describe("device setup consent", () => { exitCode: 1, stderr: "private diagnostics", expected: - "Connected over SSH, but this host runs Windows, and SSH device hosts currently need macOS or Linux. To use this machine's devices, run T3 Code on it and connect to that environment.", + "Connected over SSH, but the device host check failed on this Windows host. Windows SSH device hosts need a POSIX sh, such as Git for Windows, on the PATH for non-interactive SSH commands. To use this machine's devices without one, run T3 Code on it and connect to that environment.", }, { name: "a Windows host returning 9009", exitCode: 9009, stderr: "private diagnostics", expected: - "Connected over SSH, but this host runs Windows, and SSH device hosts currently need macOS or Linux. To use this machine's devices, run T3 Code on it and connect to that environment.", + "Connected over SSH, but the device host check failed on this Windows host. Windows SSH device hosts need a POSIX sh, such as Git for Windows, on the PATH for non-interactive SSH commands. To use this machine's devices without one, run T3 Code on it and connect to that environment.", }, { name: "missing Node on a Windows host with a POSIX shell", @@ -541,21 +542,47 @@ describe("device setup consent", () => { expected: "Connected over SSH, but Node is not on this host's PATH for non-interactive SSH commands.", }, + ...[ + ["Node 22.12 or newer C:/private", "this host's Node is older than 22.12."], + [ + "npm is missing: C:/private", + "npm is not on this host's PATH for non-interactive SSH commands.", + ], + ["No compatible Node C:/private", "this host has no npm compatible with Node 22.12+."], + ["npm probe failed: C:/private EACCES SIGTERM", "npm failed to run on this host."], + [SYMLINK_HINT, SYMLINK_HINT, "start"], + [ + "npm probe failed: C:/private", + "Connected over SSH, but npm failed to run on this host.", + "start", + ], + [ + "Node 22.12 or newer C:/private", + "Connected over SSH, but this host's Node is older than 22.12.", + "agent-start", + ], + ].map(([diagnostic, expected, step = "probe"]) => ({ + name: `a Windows host reporting ${diagnostic}`, + exitCode: 1, + stderr: `private diagnostics\n${diagnostic}`, + expected: step === "probe" ? `Connected over SSH, but ${expected}` : expected, + step, + })), ])( "reports SSH probe failure on $name through readiness and host status", - ({ exitCode, stderr, expected }) => + ({ exitCode, stderr, expected, ...options }) => Effect.gen(function* () { + const step = "step" in options ? options.step : "probe"; + const cause = new SshCommandError({ + command: ["ssh", "private arguments"], + exitCode, + stderr, + message: "private diagnostics", + }); const failure = new DeviceHost.DeviceHostError({ hostId: LOCAL_DEVICE_HOST_ID, - step: "probe", - cause: new SshDeviceHost.SshWindowsHostError({ - cause: new SshCommandError({ - command: ["ssh", "private arguments"], - exitCode, - stderr, - message: "private diagnostics", - }), - }), + step, + cause: step === "probe" ? new SshDeviceHost.SshWindowsHostError({ cause }) : cause, }); const { service, settings } = yield* fixture(Effect.void, undefined, false, failure); yield* Ref.update(settings, (current) => ({ diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.ts index cf8aece6745e0..1e28139cf6fc1 100644 --- a/apps/server/src/device/DeviceService.ts +++ b/apps/server/src/device/DeviceService.ts @@ -78,6 +78,7 @@ import * as SecretResolverLayer from "../secrets/SecretResolver.ts"; import { requireSettingsSecret } from "../secrets/settingsSecretValue.ts"; import * as DeviceHost from "./DeviceHost.ts"; import * as SshDeviceHost from "./SshDeviceHost.ts"; +import { NODE_MINIMUM, SYMLINK_HINT } from "./sshDeviceScript.ts"; import * as EasDeviceHost from "./EasDeviceHost.ts"; import * as SimlockDeviceHost from "./SimlockDeviceHost.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -89,6 +90,14 @@ export const DEVICE_HUB_ROUTE_PREFIX = "/api/device-hub"; const isSshCommandError = Schema.is(SshCommandError); +// Only known bootstrap diagnostics are safe to expose; their details stay in the cause. +const sshProbeDiagnostics = [ + [/^Node is missing from/u, "Node is not on this host's PATH for non-interactive SSH commands."], + [/^Node [\d.]+ or newer/u, `this host's Node is older than ${NODE_MINIMUM}.`], + [/^npm is missing/u, "npm is not on this host's PATH for non-interactive SSH commands."], + [/^No compatible Node/u, `this host has no npm compatible with Node ${NODE_MINIMUM}+.`], + [/^npm probe failed/u, "npm failed to run on this host."], +] as const; const sshProbeFailureMessage = (error: DeviceHost.DeviceHostError): string => { if (SshDeviceHost.isSshConnectError(error.cause)) return error.cause.message; const windows = SshDeviceHost.isSshWindowsHostError(error.cause) ? error.cause : null; @@ -101,14 +110,10 @@ const sshProbeFailureMessage = (error: DeviceHost.DeviceHostError): string => { ) return "Could not connect to this host over SSH."; - // Only the known bootstrap diagnostic is safe to expose as Node guidance. - if ( - cause.exitCode === 1 && - cause.stderr - .split(/\r?\n/u) - .some((line) => line.trim() === "Node is missing from the non-interactive SSH PATH") - ) - return "Connected over SSH, but Node is not on this host's PATH for non-interactive SSH commands."; + const lines = cause.exitCode === 1 ? cause.stderr.split(/\r?\n/u).map((line) => line.trim()) : []; + if (lines.includes(SYMLINK_HINT)) return SYMLINK_HINT; + const known = sshProbeDiagnostics.find(([pattern]) => lines.some((line) => pattern.test(line))); + if (known) return `Connected over SSH, but ${known[1]}`; if (windows) return windows.message; return `Connected over SSH, but the device host check failed (exit code ${cause.exitCode}).`; @@ -117,7 +122,13 @@ const sshProbeFailureMessage = (error: DeviceHost.DeviceHostError): string => { const isToolchainInstallError = Schema.is(DeviceToolchainInstallError); const actionableHostFailure = (error: DeviceHost.DeviceHostError): string | undefined => { - if (error.step === "probe") return sshProbeFailureMessage(error); + const message = sshProbeFailureMessage(error); + if ( + error.step === "probe" || + message === SYMLINK_HINT || + sshProbeDiagnostics.some(([, guidance]) => message === `Connected over SSH, but ${guidance}`) + ) + return message; if (isToolchainInstallError(error.cause) && error.cause.reason === "npm_not_found") return error.cause.message; return undefined; diff --git a/apps/server/src/device/SshDeviceHost.test.ts b/apps/server/src/device/SshDeviceHost.test.ts index 54b7d03c480f3..b0c9cae4979e8 100644 --- a/apps/server/src/device/SshDeviceHost.test.ts +++ b/apps/server/src/device/SshDeviceHost.test.ts @@ -1,6 +1,8 @@ import { expect, it } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Net from "@t3tools/shared/Net"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -30,6 +32,8 @@ it.effect("preserves installed status after probes and cleans failed agent activ let forwards = 0; let failForward = true; let rejectConfig = true; + const nativeSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const platform = yield* HostProcess.Platform; const releases: Array = []; const spawner = ChildProcessSpawner.make((command) => Effect.gen(function* () { @@ -72,6 +76,22 @@ it.effect("preserves installed status after probes and cleans failed agent activ ), ); const mode = /const mode = "([^"]+)"/.exec(script)?.[1] ?? ""; + if (!mode && script.includes("readFileSync")) { + return yield* nativeSpawner.spawn( + ChildProcess.make( + platform === "win32" ? "powershell.exe" : "sh", + platform === "win32" + ? [ + "-NoProfile", + "-NonInteractive", + "-Command", + `${command.args.slice(-2).join(" ")}; exit $LASTEXITCODE`, + ] + : ["-c", command.args.slice(-2).join(" ")], + { stdin, env: { ...process.env, HOME: home } }, + ), + ); + } modes.push(mode); owners.push(/const owner = "([^"]+)"/.exec(script)?.[1] ?? ""); output = JSON.stringify({ @@ -133,7 +153,28 @@ it.effect("preserves installed status after probes and cleans failed agent activ ), ), ); - yield* host.ensureReady(() => Effect.void); + const initial = yield* host.ensureReady(() => Effect.void); + const owner = owners[0]!; + yield* fs.makeDirectory(home + "/.t3/device/hosts/" + owner, { recursive: true }); + const value = "quotes ' \" $HOME \nno trailing newline"; + const args = [value, "/sdcard", "/sdcard/DCIM"]; + const input = value + "\r\nCR\rNUL\0backslash \\ \\0015 %s"; + const code = + "process.stdout.write(JSON.stringify({args:process.argv.slice(1),input:require('node:fs').readFileSync(0,'utf8'),cwd:process.cwd()}));process.exitCode=23"; + const exact = yield* initial.run( + process.execPath.replaceAll("\\", "/"), + ["-e", code, ...args], + { + stdin: input, + }, + ); + expect(exact.code).toBe(23); + const received = JSON.parse(exact.stdout); + expect(received.args).toEqual(args); + expect(received.input).toBe(input); + expect(received.cwd.replaceAll("\\", "/")).toBe( + (yield* fs.realPath(home + "/.t3/device/hosts/" + owner)).replaceAll("\\", "/"), + ); yield* SshDeviceHost.probe({ kind: "ssh", id: "test", @@ -186,7 +227,7 @@ it.effect("preserves installed status after probes and cleans failed agent activ expect(args.slice(args.indexOf("test.example") + 1)).toEqual([ "sh", "-c", - "'exec cat >/dev/null'", + '"exec cat >/dev/null"', ]); } expect(tunnelStdins).toEqual(tunnelArgs.map(() => "pipe")); diff --git a/apps/server/src/device/SshDeviceHost.ts b/apps/server/src/device/SshDeviceHost.ts index c85607a17d616..ca1dec4c8927e 100644 --- a/apps/server/src/device/SshDeviceHost.ts +++ b/apps/server/src/device/SshDeviceHost.ts @@ -26,7 +26,7 @@ import * as ServerConfig from "../config.ts"; import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts"; import * as DeviceHost from "./DeviceHost.ts"; import { makeDeviceHubOperations } from "./DeviceHubOperations.ts"; -import { quoteRemoteArg, remoteDeviceEnvironment, remoteDeviceScript } from "./sshDeviceScript.ts"; +import { quoteRemoteArg, remoteDeviceCommand, remoteDeviceScript } from "./sshDeviceScript.ts"; const UNHEALTHY_PROBE_LIMIT = 3; @@ -36,7 +36,7 @@ export class SshWindowsHostError extends Schema.TaggedError { cause: Schema.Defect() }, ) { override get message(): string { - return "Connected over SSH, but this host runs Windows, and SSH device hosts currently need macOS or Linux. To use this machine's devices, run T3 Code on it and connect to that environment."; + return "Connected over SSH, but the device host check failed on this Windows host. Windows SSH device hosts need a POSIX sh, such as Git for Windows, on the PATH for non-interactive SSH commands. To use this machine's devices without one, run T3 Code on it and connect to that environment."; } } export const isSshWindowsHostError = Schema.is(SshWindowsHostError); @@ -95,11 +95,6 @@ const targetFor = (config: SshDeviceHostConfig) => ({ }); const identityArgs = (config: SshDeviceHostConfig) => config.identityFile ? ["-i", config.identityFile] : []; -const commandArgs = (script: string) => [ - "sh", - "-c", - quoteRemoteArg(remoteDeviceEnvironment + script), -]; const bootstrap = ( config: SshDeviceHostConfig, owner: string, @@ -107,10 +102,11 @@ const bootstrap = ( ) => runSshCommand(targetFor(config), { preHostArgs: identityArgs(config), - remoteCommandArgs: commandArgs( + ...remoteDeviceCommand( 'command -v node >/dev/null 2>&1 || { echo "Node is missing from the non-interactive SSH PATH" >&2; exit 1; }; exec node', + remoteDeviceScript(owner, mode), + { nodeBootstrap: true }, ), - stdin: remoteDeviceScript(owner, mode), timeoutMs: mode === "start" || mode === "agent-start" ? 1_300_000 : 45_000, }).pipe( Effect.mapError( @@ -303,11 +299,11 @@ export const make = Effect.fn("SshDeviceHost.make")(function* ( runSshCommand(targetFor(config), { preHostArgs: identityArgs(config), // Match the hub cwd so relative executables and PATH entries resolve identically. - remoteCommandArgs: commandArgs( + ...remoteDeviceCommand( `cd "$HOME/.t3/device/hosts/${owner}" && exec ${[command, ...args].map(quoteRemoteArg).join(" ")}`, + options?.stdin, ), keepErrorOutputTail: true, - ...(options?.stdin === undefined ? {} : { stdin: options.stdin }), ...(options?.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }), }), ).pipe( @@ -414,7 +410,7 @@ export const make = Effect.fn("SshDeviceHost.make")(function* ( // close, instead of being orphaned. "sh", "-c", - quoteRemoteArg("exec cat >/dev/null"), + '"exec cat >/dev/null"', ], { stdin: "pipe", stdout: "ignore", stderr: "pipe" }, ), diff --git a/apps/server/src/device/sshDeviceScript.test.ts b/apps/server/src/device/sshDeviceScript.test.ts index 9cfa6f27e01ed..ee1f946476e44 100644 --- a/apps/server/src/device/sshDeviceScript.test.ts +++ b/apps/server/src/device/sshDeviceScript.test.ts @@ -3,24 +3,79 @@ import * as Effect from "effect/Effect"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { expect, it } from "@effect/vitest"; import * as NodeChildProcess from "node:child_process"; +import * as NodeEvents from "node:events"; +import * as NodeStreamConsumers from "node:stream/consumers"; import * as NodeFSP from "node:fs/promises"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeUtil from "node:util"; import { DEVICE_HUB_VERSION } from "./DeviceToolchain.ts"; -import { quoteRemoteArg, remoteDeviceEnvironment, remoteDeviceScript } from "./sshDeviceScript.ts"; +import { + quoteRemoteArg, + remoteDeviceCommand, + remoteDeviceEnvironment, + remoteDeviceScript, + SYMLINK_HINT, +} from "./sshDeviceScript.ts"; const exec = NodeUtil.promisify(NodeChildProcess.execFile); +const windowsHost = HostProcess.Platform.defaultValue() === "win32"; +const writeNpmPackage = async (directory: string, version: string, nodeEngine: string) => { + const root = NodePath.join(directory, "node_modules/npm"); + await NodeFSP.mkdir(NodePath.join(root, "bin"), { recursive: true }); + await NodeFSP.writeFile( + NodePath.join(root, "package.json"), + JSON.stringify({ version, engines: { node: nodeEngine } }), + ); + const located = await exec(windowsHost ? "where.exe" : "which", ["npm"]); + const launcher = await NodeFSP.realpath(located.stdout.trim().split(/\r?\n/)[0]!); + const npmRoot = NodePath.resolve( + NodePath.dirname(launcher), + windowsHost ? "node_modules/npm" : "..", + ); + await NodeFSP.cp( + NodePath.join(npmRoot, "node_modules/semver"), + NodePath.join(root, "node_modules/semver"), + { recursive: true }, + ); +}; +const writeNodeRuntime = async (directory: string) => { + await NodeFSP.copyFile(process.execPath, NodePath.join(directory, "node.exe")); + if (!windowsHost) await NodeFSP.symlink("node.exe", NodePath.join(directory, "node")); +}; +it("passes bootstrap code through the remote login shell without reinterpreting quotes", () => { + const value = "spaces 'single' \"double\" $HOME `literal`\nsecond line"; + const command = remoteDeviceCommand( + "exec node", + `process.stdout.write(${JSON.stringify(value)});`, + { + nodeBootstrap: true, + }, + ); + const result = NodeChildProcess.spawnSync( + windowsHost ? "powershell.exe" : "sh", + windowsHost + ? ["-NoProfile", "-NonInteractive", "-Command", command.remoteCommandArgs.join(" ")] + : ["-c", command.remoteCommandArgs.join(" ")], + { input: command.stdin, encoding: "utf8", timeout: 10000 }, + ); + expect(result.error).toBeUndefined(); + expect(result.stderr).toBe(""); + expect(result.status).toBe(0); + expect(result.stdout).toBe(value); +}); const executable = async (file: string, body = "exit 0") => { await NodeFSP.mkdir(NodePath.dirname(file), { recursive: true }); await NodeFSP.writeFile(file, `#!/bin/sh\n${body}\n`, { mode: 0o755 }); }; -const completeSdk = async (sdk: string, adb = "echo Android Debug Bridge") => { - await executable(NodePath.join(sdk, "platform-tools/adb"), adb); - await executable(NodePath.join(sdk, "emulator/emulator")); - await executable(NodePath.join(sdk, "cmdline-tools/latest/bin/avdmanager")); +const completeSdk = async (sdk: string, adb = "echo Android Debug Bridge", windows = false) => { + await executable(NodePath.join(sdk, `platform-tools/adb${windows ? ".exe" : ""}`), adb); + await executable(NodePath.join(sdk, `emulator/emulator${windows ? ".exe" : ""}`)); + await executable( + NodePath.join(sdk, `cmdline-tools/latest/bin/avdmanager${windows ? ".bat" : ""}`), + ); }; /** Runs the probe through the SSH shell setup, then `after` in that same shell. */ @@ -34,7 +89,7 @@ const probeAndroid = (setup: (home: string) => Promise>, await NodeFSP.writeFile(probe, remoteDeviceScript("fixture", "probe")); const result = await exec( "/bin/sh", - ["-c", `${remoteDeviceEnvironment}\n"$NODE" "$PROBE" && ${after}`], + ["-c", `${remoteDeviceEnvironment()}\n"$NODE" "$PROBE" && ${after}`], { env: { HOME: home, @@ -104,6 +159,220 @@ it.effect("uses the SDK the probe accepted for later SSH commands", () => }), ); +it("runs Windows npm probe and installation through Node with paths containing spaces", (context) => { + let active: NodeChildProcess.ChildProcess | undefined; + // Terminate the owned Windows tree or POSIX group before joining fixture teardown. + context.onTestFinished(async () => { + const child = active; + try { + if (child?.pid && child.exitCode === null && child.signalCode === null) { + if (!windowsHost) process.kill(-child.pid, "SIGKILL"); + else + await exec("taskkill", ["/pid", String(child.pid), "/T", "/F"], { + windowsHide: true, + timeout: 10000, + }); + } + } finally { + await running.catch(() => {}); + } + }); + const running = (async () => { + const home = await NodeFSP.realpath( + await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3 npm fixture ")), + ); + try { + const node = NodePath.join(home, "Node runtime", "node.exe"); + const npm = NodePath.join(NodePath.dirname(node), "node_modules/npm/bin/npm-cli.js"); + const calls = NodePath.join(home, "npm calls.jsonl"); + const sdk = NodePath.join(home, "sdk"); + await completeSdk(sdk, undefined, true); + await writeNpmPackage(NodePath.dirname(node), "11.0.0", "^20.17.0 || >=22.13.0"); + await writeNodeRuntime(NodePath.dirname(node)); + const npmFixture = `const fs = require('node:fs'); +const args = process.argv.slice(2); +const child = require('node:child_process').spawnSync(process.env.ComSpec || '/bin/sh', + process.platform === 'win32' ? ['/d', '/s', '/c', 'node -p process.execPath'] : ['-c', 'node -p process.execPath'], + { cwd: ${JSON.stringify(home)}, encoding: 'utf8' }); +if (child.error || child.status !== 0) { console.error(child.error?.message || child.stderr); process.exit(29); } +fs.appendFileSync(${JSON.stringify(calls)}, JSON.stringify({ node: process.execPath, args, childNode: child.stdout.trim() }) + '\\n'); +if (args[0] === 'install') { console.error('fixture registry unavailable'); process.exitCode = 23; } +else console.log(require('../package.json').version);`; + await NodeFSP.writeFile(npm, npmFixture); + type NpmArgs = [path?: string, node?: string, key?: "PATH" | "Path", sibling?: string]; + let denyLock = false; + const invoke = async ( + mode: "probe" | "start", + ...[npmPath = "", nodeVersion, pathKey = "PATH", siblingVersion]: NpmArgs + ) => { + const script = NodePath.join(home, `${mode}.cjs`); + await NodeFSP.writeFile( + script, + `Object.defineProperty(process, 'platform', { value: 'win32' }); +${nodeVersion ? `Object.defineProperty(process.versions, 'node', { value: ${JSON.stringify(nodeVersion)} });` : ""} +require('node:os').homedir = () => ${JSON.stringify(home)}; +if (${denyLock}) require('node:fs').symlinkSync = () => { throw Object.assign(Error('fixture symlink blocked'), { code: 'EPERM' }); }; +const childProcess = require('node:child_process'); +const originalSpawnSync = childProcess.spawnSync; +childProcess.spawnSync = (command, args, options) => command.endsWith('adb.exe') + ? { status: 0, stdout: '', stderr: '' } + ${siblingVersion ? `: args[0] === '-p' ? { status: 0, stdout: ${JSON.stringify(siblingVersion)}, stderr: '' }` : ""} + : originalSpawnSync(command, args, options); +` + remoteDeviceScript("fixture", mode), + ); + const env = Object.fromEntries( + Object.entries(process.env).filter(([key]) => key.toLowerCase() !== "path"), + ); + context.signal.throwIfAborted(); + const child = NodeChildProcess.spawn(node, [script], { + env: { ...env, [pathKey]: npmPath, ANDROID_HOME: sdk }, + detached: !windowsHost, + }); + active = child; + const [[code], stdout, stderr] = await Promise.all([ + NodeEvents.EventEmitter.once(child, "close"), + NodeStreamConsumers.text(child.stdout), + NodeStreamConsumers.text(child.stderr), + ]); + if (code !== 0) throw Object.assign(new Error(`${code}: ${stderr}`), { stdout, stderr }); + return { stdout, stderr }; + }; + const rejects = (result: ReturnType, diagnostic: string) => + expect(result).rejects.toMatchObject({ stderr: expect.stringContaining(diagnostic) }); + const checkNpm = async (runtime: string, ...args: NpmArgs) => { + await NodeFSP.writeFile(calls, ""); + const probe = await invoke("probe", ...args); + expect(JSON.parse(probe.stdout).nodePath).toBe(node); + expect(JSON.parse(probe.stdout).platforms).toContainEqual({ + platform: "android", + available: true, + }); + await rejects( + invoke("start", ...args), + "Installing expo-device-hub: exit code 23: fixture registry unavailable", + ); + const recent = (await NodeFSP.readFile(calls, "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + const prefix = expect.stringContaining(home); + const packageSpec = `expo-device-hub@${DEVICE_HUB_VERSION}`; + expect(recent).toEqual( + [ + ["--version"], + ["--version"], + ["install", "--prefix", prefix, "--no-fund", "--no-audit", packageSpec], + ].map((args) => ({ node: runtime, childNode: runtime, args })), + ); + }; + await checkNpm(node); + await NodeFSP.writeFile(calls, ""); + denyLock = true; + await rejects(invoke("start"), SYMLINK_HINT); + expect(await NodeFSP.readFile(calls, "utf8")).toBe(""); + denyLock = false; + const competitor = NodePath.join(home, "Competing runtime"); + await NodeFSP.mkdir(competitor); + await writeNodeRuntime(competitor); + await checkNpm(node, competitor, undefined, "Path"); + await writeNpmPackage(NodePath.dirname(node), "10.0.0", "^18.17.0 || >=20.0.0"); + await checkNpm(node, "", "22.12.0"); + await writeNpmPackage(NodePath.dirname(node), "11.0.0", "^20.17.0 || >=22.13.0"); + for (const mode of ["probe", "start"] as const) { + await rejects( + invoke(mode, "", "22.12.0"), + `No compatible Node 22.12+ and npm pair: npm 11.0.0 at ${npm} requires Node ^20.17.0 || >=22.13.0; found 22.12.0 at ${node}`, + ); + } + for (const [method, code, message, prefix, mode] of [ + ["error", 17, "fixture npm configuration invalid", "npm probe failed: ", "probe"], + ["log", 19, "fixture stdout-only failure", "", "probe"], + ["log", 19, "fixture stdout-only failure", "", "start"], + ] as const) { + const source = `console.${method}('${message}'); process.exitCode = ${code};`; + await NodeFSP.writeFile(npm, source); + await rejects(invoke(mode), `${prefix}exit code ${code}: ${message}`); + } + await rejects(invoke("probe", "", "18.0.0"), `Found 18.0.0 at ${node}.`); + await NodeFSP.rm(npm); + await rejects(invoke("probe"), "npm is missing:"); + const fallback = NodePath.join(home, "npm on PATH"); + const fallbackEntry = NodePath.join(fallback, "node_modules/npm/bin/npm-cli.js"); + await writeNpmPackage(fallback, "10.0.0", "^18.17.0 || >=20.0.0"); + await NodeFSP.writeFile(fallbackEntry, "console.log('10.0.0');"); + expect(JSON.parse((await invoke("probe", `"${fallback}"`, "22.12.0")).stdout).nodePath).toBe( + node, + ); + await writeNpmPackage(fallback, "11.0.0", "^20.17.0 || >=22.13.0"); + await rejects(invoke("probe", fallback, "22.12.0"), "npm 11.0.0"); + const sibling = NodePath.join(fallback, "node.exe"); + await writeNodeRuntime(fallback); + await NodeFSP.writeFile(fallbackEntry, npmFixture); + await checkNpm(sibling, fallback, "22.12.0"); + await checkNpm(node, fallback, undefined, "PATH", "18.0.0"); + await writeNpmPackage(NodePath.dirname(node), "10.0.0", "^18.17.0 || >=20.0.0"); + await NodeFSP.writeFile(npm, npmFixture); + await checkNpm(node, fallback, "22.12.0"); + for (const [file, contents] of [ + ["package.json", undefined], + ["package.json", "{"], + ["package.json", "null"], + ["package.json", "{}"], + ["node_modules/semver", undefined], + ["bin/npm-cli.js", "throw Error('fixture damaged CLI');"], + ] as const) { + await writeNpmPackage(NodePath.dirname(node), "10.0.0", ">=22"); + const target = NodePath.resolve(NodePath.dirname(npm), "..", file); + if (contents === undefined) await NodeFSP.rm(target, { recursive: true }); + else await NodeFSP.writeFile(target, contents); + await checkNpm(sibling, fallback); + await rejects( + invoke("probe"), + `${file === "bin/npm-cli.js" ? "npm probe failed" : "No compatible Node 22.12+ and npm pair"}: npm at ${npm}:`, + ); + } + } finally { + await NodeFSP.rm(home, { recursive: true, force: true }); + } + })(); + return running; +}); +it.effect.each([{ supported: true }, { supported: false }])( + "preserves a working SSH Node/npm pair and replaces an old Node: supported=$supported", + ({ supported }) => + Effect.promise(async () => { + const home = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-ssh-path-")); + try { + const bin = NodePath.join(home, "selected-node/bin"); + const fallback = NodePath.join(home, ".local/bin"); + const sdk = NodePath.join(home, "android-sdk"); + const jvm = NodePath.join(home, "java-home"); + for (const [tool, directory] of [ + ["adb", NodePath.join(sdk, "platform-tools")], + ["java", NodePath.join(jvm, "bin")], + ] as const) { + await executable(NodePath.join(directory, tool), `echo configured-${tool}`); + await executable(NodePath.join(fallback, tool), `echo wrong-${tool}`); + } + for (const tool of ["node", "npm"]) { + const probe = (status: number) => `if [ "$1" = "-e" ]; then exit ${status}; fi`; + await executable(NodePath.join(bin, tool), `${probe(supported ? 0 : 1)}\necho selected`); + await executable(NodePath.join(fallback, tool), `${probe(0)}\necho fallback`); + } + const script = `${remoteDeviceEnvironment({ nodeBootstrap: true })}\nnode; npm; adb; java`; + const result = await exec("/bin/sh", ["-c", script], { + env: { HOME: home, PATH: bin, JAVA_HOME: jvm, ANDROID_HOME: sdk }, + }); + expect(result.stdout).toBe( + (supported ? "selected\nselected\n" : "fallback\nfallback\n") + + "configured-adb\nconfigured-java\n", + ); + } finally { + await NodeFSP.rm(home, { recursive: true, force: true }); + } + }), + { skip: windowsHost }, +); it.effect("finds Android Studio Java for a non-interactive SSH session", () => Effect.gen(function* () { if ((yield* HostProcess.Platform) === "win32") return; @@ -117,7 +386,7 @@ it.effect("finds Android Studio Java for a non-interactive SSH session", () => "#!/bin/sh\necho test-java\n", { mode: 0o755 }, ); - const result = await exec("/bin/sh", ["-c", `${remoteDeviceEnvironment}\njava`], { + const result = await exec("/bin/sh", ["-c", `${remoteDeviceEnvironment()}\njava`], { env: { HOME: home, PATH: "/nonexistent", JAVA_HOME: "" }, }); expect(result.stdout.trim()).toBe("test-java"); diff --git a/apps/server/src/device/sshDeviceScript.ts b/apps/server/src/device/sshDeviceScript.ts index cc3c147fa9b70..ea11bc5e792d0 100644 --- a/apps/server/src/device/sshDeviceScript.ts +++ b/apps/server/src/device/sshDeviceScript.ts @@ -3,7 +3,32 @@ import { AGENT_DEVICE_VERSION, DEVICE_HUB_VERSION } from "./DeviceToolchain.ts"; export const quoteRemoteArg = (value: string) => `'${value.replaceAll("'", "'\"'\"'")}'`; -export const remoteDeviceEnvironment = `export PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH" +export const NODE_MINIMUM = "22.12"; +export const SYMLINK_HINT = "Windows SSH account needs symbolic-link permission or Developer Mode."; +const [nodeMajor, nodeMinor] = NODE_MINIMUM.split("."); +// Shared by the SSH shell setup and the remote script, so it must not contain single quotes. +const nodeSupported = `((version) => { const [major, minor] = version.split(".").map(Number); return major > ${nodeMajor} || (major === ${nodeMajor} && minor >= ${nodeMinor}); })`; +// Shells drop NUL, and Git for Windows sh drops CR, while reading script source. +const printfEscaped = (value: string) => + value.replaceAll("\\", "\\\\").replaceAll("\r", "\\0015").replaceAll("\0", "\\0000"); +export const remoteDeviceCommand = ( + script: string, + stdin?: string, + options?: { readonly nodeBootstrap?: boolean }, +) => ({ + remoteCommandArgs: ["sh", "-s"], + stdin: + remoteDeviceEnvironment(options) + + (stdin === undefined + ? `${script} `export MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' +export PATH="$PATH:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin" +${options?.nodeBootstrap ? `node -e 'process.exit(${nodeSupported}(process.versions.node) ? 0 : 1)' 2>/dev/null || export PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"` : ""} if [ -z "$ANDROID_HOME" ]; then if [ -n "$ANDROID_SDK_ROOT" ]; then export ANDROID_HOME="$ANDROID_SDK_ROOT"; elif [ -d "$HOME/Library/Android/sdk" ]; then export ANDROID_HOME="$HOME/Library/Android/sdk"; @@ -38,7 +63,51 @@ const net = require('node:net'); const { spawn, spawnSync } = require('node:child_process'); const root = path.join(os.homedir(), '.t3', 'device'); const state = path.join(root, 'hosts', owner); +const nodeSupported = ${nodeSupported}; const run = (command, args, options = {}) => spawnSync(command, args, { encoding: 'utf8', timeout: 30000, ...options }); +const runNpm = (args, options) => { + if (process.platform !== 'win32') return run('npm', args, options); + const env = { ...process.env, ...options?.env }; + const pathKeys = Object.keys(env).filter(key => key.toLowerCase() === 'path'); + const inheritedPath = pathKeys.map(key => env[key]).filter(Boolean).join(path.delimiter); + for (const key of pathKeys) delete env[key]; + const directories = [path.dirname(process.execPath), ...inheritedPath.split(path.delimiter)]; + const failures = []; + let npmLaunchFailed = false; + for (const directory of [...new Set(directories.filter(Boolean).map(dir => dir.replace(/^"|"$/g, '')))]) { + const npmRoot = path.join(directory, 'node_modules', 'npm'); + const entry = path.join(npmRoot, 'bin', 'npm-cli.js'); + if (!fs.existsSync(entry)) continue; + let npm, semver; + try { + npm = JSON.parse(fs.readFileSync(path.join(npmRoot, 'package.json'), 'utf8')); + if (typeof npm?.engines?.node !== 'string') throw Error('package.json has no engines.node'); + semver = require(path.join(npmRoot, 'node_modules', 'semver')); + } catch (error) { + failures.push('npm at ' + entry + ': ' + error.message); + continue; + } + const sibling = path.join(directory, 'node.exe'); + const nodes = [...new Set([...(fs.existsSync(sibling) ? [sibling] : []), process.execPath])]; + for (const node of nodes) { + const version = node === process.execPath ? null : run(node, ['-p', 'process.versions.node']); + if (version && (version.error || version.status !== 0)) { failures.push('Node at ' + node + ': ' + commandFailure(version)); continue; } + const nodeVersion = version ? version.stdout.trim() : process.versions.node; + if (!nodeSupported(nodeVersion) || !semver.satisfies(nodeVersion, npm.engines.node)) { failures.push('npm ' + npm.version + ' at ' + entry + ' requires Node ' + npm.engines.node + '; found ' + nodeVersion + ' at ' + node); continue; } + const pairedOptions = { ...options, env: { ...env, PATH: path.dirname(node) + path.delimiter + inheritedPath } }; + const probe = run(node, [entry, '--version'], pairedOptions); + if (probe.error || probe.status !== 0) { npmLaunchFailed = true; failures.push('npm at ' + entry + ': npm probe failed: ' + commandFailure(probe)); continue; } + return args.length === 1 && args[0] === '--version' ? probe : run(node, [entry, ...args], pairedOptions); + } + } + if (failures.length) throw Error((npmLaunchFailed ? 'npm probe failed: ' : 'No compatible Node ${NODE_MINIMUM}+ and npm pair: ') + failures.join('; ')); + throw Error('npm is missing: could not find node_modules/npm/bin/npm-cli.js beside Node or on the non-interactive SSH PATH.'); +}; +const commandFailure = result => [ + result.error?.message, + result.signal ? 'signal ' + result.signal : result.status !== null ? 'exit code ' + result.status : null, + (result.stderr?.trim() || result.stdout?.trim())?.slice(-2000), +].filter(Boolean).join(': '); const read = (file) => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; } }; const write = (file, value) => { const tmp = file + '.' + process.pid; fs.writeFileSync(tmp, JSON.stringify(value), { mode: 0o600 }); fs.renameSync(tmp, file); }; const toolVersions = (name, requiredVersion, entry, record) => { @@ -90,6 +159,7 @@ async function acquireLock(lock, complete = () => false) { fs.symlinkSync(token, lock); return () => { if (owner() === token) fs.unlinkSync(lock); }; } catch (error) { + if (process.platform === 'win32' && error.code === 'EPERM') throw Error(${JSON.stringify(SYMLINK_HINT)}); if (error.code !== 'EEXIST') throw error; if (complete()) return null; const previous = owner(); @@ -120,8 +190,8 @@ async function install(name, version, entry) { try { if (complete()) return file; staging = fs.mkdtempSync(path.join(path.dirname(dir), '.install-')); - const result = run('npm', ['install', '--prefix', staging, '--no-fund', '--no-audit', name + '@' + version], { timeout: 600000, maxBuffer: 8 * 1024 * 1024 }); - if (result.status !== 0) throw Error('Installing ' + name + ': ' + (result.error?.message || result.stderr?.slice(-2000))); + const result = runNpm(['install', '--prefix', staging, '--no-fund', '--no-audit', name + '@' + version], { timeout: 600000, maxBuffer: 8 * 1024 * 1024 }); + if (result.error || result.status !== 0) throw Error('Installing ' + name + ': ' + commandFailure(result)); if (!fs.existsSync(path.join(staging, 'node_modules', name, entry))) throw Error('Missing installed entry for ' + name); fs.writeFileSync(path.join(staging, '.install-complete'), version); fs.rmSync(dir, { recursive: true, force: true }); @@ -136,9 +206,10 @@ async function install(name, version, entry) { const ios = process.platform === 'darwin' && run('xcrun', ['simctl', 'help']).status === 0; // The SSH shell setup chose ANDROID_HOME, so later commands use the SDK accepted here. const sdk = process.env.ANDROID_HOME; + const sdkTool = relative => path.join(sdk, relative + (process.platform === 'win32' ? (relative.endsWith('avdmanager') ? '.bat' : '.exe') : '')); const executable = (relative) => { try { - const file = path.join(sdk, relative); + const file = sdkTool(relative); fs.accessSync(file, fs.constants.X_OK); return fs.statSync(file).isFile(); } catch { @@ -149,7 +220,7 @@ async function install(name, version, entry) { : !executable('platform-tools/adb') ? 'Android SDK Platform-Tools are missing from ' + sdk + '. Install them in Android Studio SDK Manager.' : !executable('emulator/emulator') ? 'Android Emulator is missing from ' + sdk + '. Install it in Android Studio SDK Manager.' : !executable('cmdline-tools/latest/bin/avdmanager') ? 'Android SDK Command-line Tools (latest) are missing from ' + sdk + '. Install them in Android Studio SDK Manager.' - : run(path.join(sdk, 'platform-tools', 'adb'), ['version']).status !== 0 ? 'adb in ' + sdk + ' failed to run. Reinstall Android SDK Platform-Tools.' + : run(sdkTool('platform-tools/adb'), ['version']).status !== 0 ? 'adb in ' + sdk + ' failed to run. Reinstall Android SDK Platform-Tools.' : null; const android = androidReason === null; const platforms = [ @@ -157,9 +228,9 @@ async function install(name, version, entry) { { platform: 'android', available: android, ...(!android ? { reason: androidReason } : {}) }, ]; if (mode === 'probe') { - const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(Number); - if (nodeMajor < 22 || (nodeMajor === 22 && nodeMinor < 12)) throw Error('Node 22.12 or newer is required on the device host.'); - if (run('npm', ['--version']).status !== 0) throw Error('npm is missing from the non-interactive SSH PATH.'); + if (!nodeSupported(process.versions.node)) throw Error('Node ${NODE_MINIMUM} or newer is required on the device host. Found ' + process.versions.node + ' at ' + process.execPath + '.'); + const npm = runNpm(['--version']); + if (npm.error || npm.status !== 0) throw Error(npm.error?.code === 'ENOENT' ? 'npm is missing from the non-interactive SSH PATH: ' + npm.error.message : 'npm probe failed: ' + commandFailure(npm)); console.log(JSON.stringify({ nodePath: process.execPath, platforms, tools: versions() })); return; } fs.mkdirSync(state, { recursive: true, mode: 0o700 }); @@ -199,8 +270,7 @@ async function install(name, version, entry) { // Only a Mac can list Apple simulators. Recording the filter replaces hubs started without it. const hubPlatform = process.platform === 'darwin' ? undefined : 'android'; const cameraArgs = android ? ['front', 'back'].flatMap(facing => { - const emulator = process.env.ANDROID_HOME ? path.join(process.env.ANDROID_HOME, 'emulator', 'emulator') : 'emulator'; - const help = run(emulator, ['-help-camera-' + facing], { timeout: 5000 }); + const help = run(sdkTool('emulator/emulator'), ['-help-camera-' + facing], { timeout: 5000 }); const text = (help.stdout || '') + '\n' + (help.stderr || ''); // The hub's imagefile camera mode is not supported by every installed SDK emulator. return help.status === 0 && /\bemulated\b/.test(text) && !/\bimagefile\b/.test(text) ? ['-camera-' + facing, 'emulated'] : []; diff --git a/docs/user/devices.md b/docs/user/devices.md index 3130e4aa45c6c..cc908b33a15a2 100644 --- a/docs/user/devices.md +++ b/docs/user/devices.md @@ -108,9 +108,8 @@ not supported. anything, with a result for each selected environment. Targets that resolve to the environment’s own machine are skipped, since its devices are already local. The first device listing installs pinned device tools on the host. -SSH device hosts currently need macOS or Linux. To use devices on a Windows -machine, run T3 Code on that machine and connect to its environment. -Node 22.12 or newer and npm must be available to non-interactive SSH commands. +Node 22.12 or newer and a compatible npm version must be available to non-interactive SSH commands. +SSH device hosts also need a POSIX-compatible `sh` available to non-interactive SSH commands. On Windows hosts, Git for Windows provides `sh.exe` in its `bin` directory (for example `C:\Program Files\Git\bin`), which its default installation does not add to PATH; add that directory to the PATH SSH sessions use. The Windows SSH account must also be allowed to create symbolic links, through Developer Mode or the symbolic-link creation privilege, for device-tool installation and runtime locks. T3 checks common Homebrew and Android SDK locations; custom installations need the appropriate PATH and `ANDROID_HOME` or `ANDROID_SDK_ROOT` on the host. Android on an SSH host needs the same SDK tools as a local environment; adb on