Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
test(ssh): docker sshd harness with a containerized e2e suite
parsa22284d16584befc
diff --git a/test/ssh-docker/.gitignore b/test/ssh-docker/.gitignorenew file mode 100644index 000000000..74ccf303f--- /dev/null+++ b/test/ssh-docker/.gitignore@@ -0,0 +1,8 @@+# Nothing generated ever lives here (keys/host keys go to the outer temp dir), but ignore+# defensively in case a script is ever run from the wrong cwd.+*.pem+*_ed25519+*_ed25519.pub+*_rsa+known_hosts+.work/diff --git a/test/ssh-docker/Dockerfile b/test/ssh-docker/Dockerfilenew file mode 100644index 000000000..d11838848--- /dev/null+++ b/test/ssh-docker/Dockerfile@@ -0,0 +1,26 @@+# Disposable OpenSSH server for exercising nodeterm's SSH connect paths (see ../../src/main/remote-ssh+# and ../../src/core/remote-ssh) against a throwaway box instead of a real, rate-limited server.+FROM debian:bookworm-slim++RUN apt-get update \+ && apt-get install -y --no-install-recommends openssh-server \+ && rm -rf /var/lib/apt/lists/* \+ && mkdir -p /run/sshd++RUN useradd -m -s /bin/bash keyuser \+ && useradd -m -s /bin/bash passuser \+ && useradd -m -s /bin/bash pwuser \+ && echo 'pwuser:pwpass123' | chpasswd \+ # useradd leaves new accounts LOCKED (shadow password field "!"), which sshd refuses outright+ # ("account is locked") even for pubkey auth, not just password auth. usermod -p '*' sets a+ # password hash that can never match any input (so password auth still can't succeed for these+ # two) while clearing the locked-account flag pubkey auth also checks.+ && usermod -p '*' keyuser \+ && usermod -p '*' passuser++COPY sshd_config /etc/ssh/sshd_config+COPY entrypoint.sh /entrypoint.sh+RUN chmod 755 /entrypoint.sh++EXPOSE 22+ENTRYPOINT ["/entrypoint.sh"]diff --git a/test/ssh-docker/README.md b/test/ssh-docker/README.mdnew file mode 100644index 000000000..2f9746dfb--- /dev/null+++ b/test/ssh-docker/README.md@@ -0,0 +1,126 @@+# SSH test harness (Docker)++A disposable OpenSSH server in Docker for exercising nodeterm's SSH connect paths+(`src/main/remote-ssh`, `src/core/remote-ssh`), especially the SSH_ASKPASS passphrase flow,+without touching a real server. sshd binds to `127.0.0.1:22022` only - never reachable off this+machine.++Nothing generated (host keys, client keys, known_hosts, logs) is committed. It all lives under+`test/ssh-docker/.work/` (gitignored); set `NT_SSHDOCKER_WORKDIR` to keep it somewhere else+entirely, e.g. outside the repo.++## Start / stop++```+./run.sh up # generate keys (if missing), build the image, start the container+./run.sh down # stop and remove the container (keeps the image and keys for a fast restart)+./run.sh clean # full teardown: stop+remove the container, remove the image, delete all keys+```++`up` is idempotent: re-running it reuses existing keys and just rebuilds/restarts the container.+Only `clean` deletes the generated keys (a fresh `up` after that regenerates everything, with a+new host key fingerprint).++Manual teardown if you don't want to use the script:++```+docker rm -f nodeterm-ssh-test+docker rmi -f nodeterm-ssh-test+rm -rf test/ssh-docker/.work # or your $NT_SSHDOCKER_WORKDIR+```++## The three users++| user | auth | password / passphrase | purpose |+|----------|--------------------------|------------------------|---------|+| keyuser | public key, unencrypted | n/a | baseline: connect and it should just work |+| passuser | public key, passphrase-protected | `testpass123` | the main case - exercises the SSH_ASKPASS passphrase prompt |+| pwuser | password only, no key at all | `pwpass123` | server wants a password with no identity file configured; the ControlMaster has no tty to prompt into |++Keys live under `test/ssh-docker/.work/clientkeys/` after `run.sh up`:+`keyuser` / `keyuser.pub`, `passuser` / `passuser.pub` (both ed25519, generated fresh each time+the workdir doesn't already have them).++## Connecting by hand++Run the ssh CLIENT inside a throwaway container, never on the host. `ssh` resolves the user's home+directory from the passwd database, NOT from `$HOME`, so `StrictHostKeyChecking=accept-new` appends+to the real `~/.ssh/known_hosts` even when `HOME` is redirected. This harness must never touch the+host's `~/.ssh`, and `matrix.sh` plus the vitest e2e both refuse to run the client anywhere else+for exactly this reason.++```+# The client container joins the same docker network as the sshd container and brings its own+# HOME, so its known_hosts is created and destroyed with the container.+docker run --rm -it --network nt-ssh-net \+ -v "$PWD/.work/clientkeys":/keys:ro \+ alpine:3.20 sh -lc '+ apk add --no-cache openssh >/dev/null+ cp /keys/passuser /root/passuser && chmod 600 /root/passuser+ # passphrase-protected key: answer testpass123+ ssh -o StrictHostKeyChecking=accept-new -o IdentitiesOnly=yes \+ -i /root/passuser passuser@nodeterm-ssh-test+ '+```++Swap `passuser` for `keyuser` (unencrypted key) or drop `-i` and use `pwuser` (password+`pwpass123`) to exercise the other two accounts.++## Empirical SSH_ASKPASS probe (Q1-Q5)++`matrix.sh` drives a fake `SSH_ASKPASS` helper against this container to answer the specific+OpenSSH behaviors `ssh-askpass.ts` / `control-master.ts` assume (retry prompts are byte-identical,+`$PPID` is the master pid, an empty answer abandons the key, and so on) - run it and read the+labeled output for the raw evidence.++## Layout++- `Dockerfile` - debian-slim + openssh-server, three users created at build time.+- `sshd_config` - pubkey auth for keyuser/passuser, password auth scoped to pwuser only via a+ trailing `Match User pwuser` block (Match blocks run to end-of-file, so it must be last).+- `entrypoint.sh` - copies the bind-mounted host key and public keys into place with correct+ in-container ownership (a straight bind-mount keeps the host's UID, which trips sshd's+ StrictModes check), then execs sshd in the foreground.+- `run.sh` - key generation + build + run/stop/clean, all confined to the outer temp dir.++## Harness parity with production++`pwuser` exists to test what OpenSSH *can* route, not what the app does. Production `masterArgs`+sets `PasswordAuthentication=no` and `KbdInteractiveAuthentication=no`, because a tty-less master+can never complete either method and would otherwise submit an empty credential once per allowed+prompt, spending real login attempts and tripping a host's fail2ban. So the app never reaches a+server password prompt at all.++Keep that in mind before building on a probe result: a scenario that works here with a bare `ssh`+invocation may be unreachable in the app. If you add server-password support, the two options+above have to change first, and `NumberOfPasswordPrompts` must NOT be used to express it: that+counter also bounds the key passphrase retry loop, so setting it to 0 silently disables passphrase+prompting entirely.++## ssh-agent is the passphrase cache, and the app owns the agent++Production `masterArgs` also sets `AddKeysToAgent=yes`: the first successful unlock loads the+key into the agent named by `SSH_AUTH_SOCK`, and every later master (fresh process) authenticates+through it with zero prompts - `matrix.sh`'s third section demonstrates it against this container+(first connect asks=1, second asks=0, third with askpass removed asks=0). The app therefore keeps+no passphrase state of its own.++Which agent that is, is deliberate: main spawns an **app-private** `ssh-agent` and points its+masters at it (`src/main/remote-ssh/ssh-agent.ts`), then kills it at quit, so an unlock lasts one+app run instead of until the user's next logout. Consequences the harness has to respect: nothing+should ever land in the ambient agent (the e2e asserts this), and a key the user already loaded+into their own agent does NOT authenticate a nodeterm master - the app prompts once per run and+keeps the unlock in its own agent. `matrix.sh` still measures the raw OpenSSH behavior with a+plain agent, which is the layer underneath this decision and is unchanged.++Two measured facts to keep in mind when extending this:++- An agent full of OTHER keys is offered before a `-i` file identity, and each rejected offer+ spends one of sshd's `MaxAuthTries` (default 6, unset in this harness's sshd_config). Eight+ junk agent keys ended the connection with "Too many authentication failures" before the right+ key was reached. That is why production pins `IdentitiesOnly=yes` alongside `-i` - and ONLY+ alongside `-i`, because IdentitiesOnly with no configured identity disables agent keys+ entirely. The agent still signs the pinned key, so the zero-prompt reconnect is unaffected.+- With no agent reachable (`SSH_AUTH_SOCK` unset), `AddKeysToAgent=yes` degrades silently:+ the connection works, the prompt just fires once per connect, and ssh prints nothing to+ stderr about the skipped add (so it can never pollute the app's connect-error banner).diff --git a/test/ssh-docker/askpass-e2e.test.ts b/test/ssh-docker/askpass-e2e.test.tsnew file mode 100644index 000000000..95e030088--- /dev/null+++ b/test/ssh-docker/askpass-e2e.test.ts@@ -0,0 +1,390 @@+/**+ * End-to-end proof of the SSH_ASKPASS passphrase flow against a REAL sshd.+ *+ * Everything else in the suite mocks the ssh runner, so nothing else can catch a wrong assumption+ * about what OpenSSH actually does. This drives the real `AskpassServer`, the real generated+ * askpass script, the real `ssh` binary and a real (containerised) sshd, exactly as+ * `initSshProject` wires them in production.+ *+ * Opt-in: needs Docker and the harness in this directory (plus ssh-agent/ssh-add on PATH in the+ * client container, for the agent-backed reconnect test).+ * cd test/ssh-docker && ./run.sh up+ * NODETERM_SSH_DOCKER=1 npx vitest run test/ssh-docker/askpass-e2e.test.ts+ * Without NODETERM_SSH_DOCKER the whole file is skipped, so `npm test` and CI stay green on a+ * machine with no Docker.+ */+import { promises as fs } from 'fs'+import os from 'os'+import path from 'path'+import { spawn, execFile } from 'child_process'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { SshProjectManager } from '../../src/main/remote-ssh/ssh-project'+import { AskpassServer, ensureAskpassScript } from '../../src/main/remote-ssh/ssh-askpass'+import { AppSshAgent } from '../../src/main/remote-ssh/ssh-agent'+import type { SshConnection } from '../../src/shared/ssh'++import { existsSync } from 'fs'++/**+ * HARD REQUIREMENT: this file runs the real `ssh` client, and `ssh` resolves the user's home+ * directory from the passwd database, NOT from $HOME. Redirecting HOME therefore does NOT stop+ * `StrictHostKeyChecking=accept-new` from appending to the real `~/.ssh/known_hosts` (learned the+ * hard way: it wrote there even with HOME pointed at a temp dir). Touching `~/.ssh` is banned on+ * this machine, so the client is only ever allowed to run INSIDE a container, talking to the sshd+ * container over a docker network. See ../../../CLAUDE.md and ./matrix.sh.+ */+const IN_CONTAINER = existsSync('/.dockerenv')+const ENABLED = !!process.env.NODETERM_SSH_DOCKER && IN_CONTAINER+if (process.env.NODETERM_SSH_DOCKER && !IN_CONTAINER) {+ console.warn(+ '[ssh-e2e] refusing to run on the host: ssh would write to the real ~/.ssh/known_hosts. ' ++ 'Run this inside the client container (see test/ssh-docker/README.md).'+ )+}+const HOST = '127.0.0.1'+const PORT = 22022+const PASSPHRASE = 'testpass123'+// e2e.sh copies the generated keys to a root-owned dir and points this env var at it (ssh+// refuses bind-mounted keys carrying the host uid: "bad ownership or modes"). The fallback is+// the harness's default workdir, for a containerized run driven some other way.+const KEYS =+ process.env.NT_SSHDOCKER_KEYS ?? path.join(__dirname, '.work', 'clientkeys')+const MASTER_STDERR_CAP = 8 * 1024++/** The real spawner/runners from initSshProject, minus anything Electron. */+function realRunners(+ askpass: AskpassServer,+ scriptPath: string,+ sandboxHome: string,+ onStatusError?: () => void,+ /** When given, wired exactly as initSshProject does: the master (and the child ssh that+ * re-authenticates when a master is down) point at the app's OWN agent instead of the ambient+ * one, which is what scopes an unlocked key to a single app run. */+ appAgent?: AppSshAgent+) {+ return {+ userDataDir: '/tmp/nt-e2e',+ spawnMaster: (args: string[], env?: Record<string, string>) => {+ const child = spawn('ssh', args, {+ stdio: ['ignore', 'ignore', 'pipe'] as const,+ // HOME is redirected at the sandbox so ssh's known_hosts lands in a temp dir. The real+ // ~/.ssh is off limits, and StrictHostKeyChecking=accept-new WILL append to whatever+ // known_hosts it can find. See ../../../CLAUDE.md.+ env: { ...process.env, HOME: sandboxHome, ...(env ?? {}) }+ })+ let stderr = ''+ let exited = false+ child.stderr?.on('data', (c: Buffer) => {+ if (stderr.length < MASTER_STDERR_CAP) stderr += c.toString('utf-8')+ })+ child.on('error', (e: Error) => {+ exited = true+ stderr += `${e.message}\n`+ })+ child.on('exit', () => {+ exited = true+ })+ return {+ kill: () => child.kill(),+ on: (ev: string, cb: (...a: unknown[]) => void) => child.on(ev, cb),+ stderr: () => stderr,+ exited: () => exited,+ // Without this the manager can never ask "was MY master's prompt declined": connect()+ // passes master.pid?.() to askpassWasCancelled, and a pid-less handle silently downgraded+ // every run of this suite to the time-scoped cancelledRecently fallback, leaving the+ // newest behavior (exact pid attribution via the helper's $PPID) untested end to end.+ pid: () => child.pid+ }+ },+ run: (args: string[], stdin?: string) =>+ new Promise<{ code: number; stdout: string }>((resolve) => {+ const child = execFile(+ 'ssh',+ args,+ { timeout: 15000, env: { ...process.env, HOME: sandboxHome, ...(appAgent?.env() ?? {}) } },+ (err, stdout) => resolve({ code: err ? ((err as { code?: number }).code ?? 1) : 0, stdout: stdout ?? '' })+ )+ if (stdin !== undefined) child.stdin?.end(stdin)+ }),+ runScp: () => Promise.resolve({ code: 0 }),+ getHook: () => ({ port: 0, token: '', version: '1' }),+ onStatus: () => {+ onStatusError?.()+ },+ masterEnvFor: (identityFile?: string, ambientAgent?: boolean) => ({+ ...askpass.envFor(identityFile, scriptPath),+ ...(ambientAgent ? {} : (appAgent?.env() ?? {}))+ }),+ ensureAgent: appAgent ? () => appAgent.start() : undefined,+ // Mirrors initSshProject exactly: pid-keyed attribution, with the time-scoped fallback only+ // when a handle cannot name its pid. Wiring cancelledRecently() here instead hid the pid path+ // from the whole e2e suite.+ askpassWasCancelled: (masterPid?: number) => askpass.wasCancelledBy(masterPid),+ askpassIsPrompting: () => askpass.isPromptingAny()+ }+}++describe.skipIf(!ENABLED)('SSH askpass end to end (Docker sshd)', () => {+ let askpass: AskpassServer+ let scriptPath: string+ let tmp: string+ /** ssh runs with HOME pointed here, so it can never reach the real ~/.ssh (hard rule). */+ let sandboxHome: string++ /** The container's ambient agent (if any), stashed so the suite is deterministic: with an agent+ * reachable, AddKeysToAgent=yes would make every test after the first prompt-free and break+ * their expectations. Only the dedicated agent test below runs one, and it runs its own. */+ let ambientAgentSock: string | undefined++ beforeAll(async () => {+ tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-askpass-e2e-'))+ sandboxHome = path.join(tmp, 'home')+ await fs.mkdir(path.join(sandboxHome, '.ssh'), { recursive: true, mode: 0o700 })+ scriptPath = await ensureAskpassScript(tmp)+ askpass = new AskpassServer()+ await askpass.start()+ ambientAgentSock = process.env.SSH_AUTH_SOCK+ delete process.env.SSH_AUTH_SOCK+ }, 30_000)++ afterAll(async () => {+ if (ambientAgentSock !== undefined) process.env.SSH_AUTH_SOCK = ambientAgentSock+ askpass?.stop()+ await fs.rm(tmp, { recursive: true, force: true }).catch(() => {})+ })++ /** A connection with NO identityFile: the regression this whole branch exists for. ssh falls+ * back to the default identities, so the key is named only by the prompt. */+ const connNoKey: SshConnection = { host: HOST, user: 'passuser', port: PORT }+ const connWithKey: SshConnection = {+ host: HOST,+ user: 'passuser',+ port: PORT,+ identityFile: path.join(KEYS, 'passuser')+ }++ it('prompts for the passphrase and connects (identityFile configured)', async () => {+ const prompts: { identityFile: string; retry: boolean }[] = []+ askpass.setPromptHandler(async (req) => {+ prompts.push(req)+ return PASSPHRASE+ })+ const mgr = new SshProjectManager(realRunners(askpass, scriptPath, sandboxHome))+ try {+ const res = await mgr.connect('e2e-1', connWithKey)+ expect(res.controlPath).toBeTruthy()+ expect(prompts).toHaveLength(1)+ expect(prompts[0].identityFile).toBe(path.join(KEYS, 'passuser'))+ expect(prompts[0].retry).toBe(false)+ } finally {+ await mgr.disconnect('e2e-1')+ }+ }, 60_000)++ it('a wrong passphrase re-prompts with retry=true, then the right one connects', async () => {+ let n = 0+ const prompts: boolean[] = []+ askpass.setPromptHandler(async (req) => {+ prompts.push(req.retry)+ return ++n === 1 ? 'wrong-on-purpose' : PASSPHRASE+ })+ const mgr = new SshProjectManager(realRunners(askpass, scriptPath, sandboxHome))+ try {+ const res = await mgr.connect('e2e-2', connWithKey)+ expect(res.controlPath).toBeTruthy()+ // ssh re-invokes askpass from the SAME pid with a byte-identical prompt; the second ask is+ // what the app reads as "that answer failed to decrypt the key".+ expect(prompts.length).toBeGreaterThanOrEqual(2)+ expect(prompts[0]).toBe(false)+ expect(prompts[1]).toBe(true)+ } finally {+ await mgr.disconnect('e2e-2')+ }+ }, 60_000)++ it('cancelling reports that the key needs its passphrase, and does not hang', async () => {+ askpass.setPromptHandler(async () => null)+ const mgr = new SshProjectManager(realRunners(askpass, scriptPath, sandboxHome))+ const started = Date.now()+ await expect(mgr.connect('e2e-3', connWithKey)).rejects.toThrow(/passphrase|Permission denied/i)+ // An empty askpass answer makes ssh abandon the key at once, so this must fail fast rather+ // than ride the long prompt-wait ceiling.+ expect(Date.now() - started).toBeLessThan(30_000)+ }, 60_000)++ it('a cancel is attributed to the exact master pid, and only that pid', async () => {+ // The pid chain this proves end to end: the app spawns `ssh -M -N ...`, ssh itself execs the+ // askpass helper, so the helper's $PPID IS the spawned master's pid (verified against this+ // same sshd), and wasCancelledBy(master.pid()) answers exactly. The different-pid assertion+ // is the load-bearing half: if connect() lost the pid, wasCancelledBy(undefined) falls back+ // to the 60s global clock and would say "cancelled" for ANY pid right after this decline.+ askpass.setPromptHandler(async () => null)+ const runners = realRunners(askpass, scriptPath, sandboxHome)+ const pids: (number | undefined)[] = []+ const mgr = new SshProjectManager({+ ...runners,+ spawnMaster: (args, env) => {+ const h = runners.spawnMaster(args, env)+ pids.push(h.pid())+ return h+ }+ })+ await expect(mgr.connect('e2e-cancel-pid', connWithKey)).rejects.toThrow(+ 'SSH connection cancelled: this key needs its passphrase.'+ )+ expect(pids).toHaveLength(1)+ const masterPid = pids[0]+ expect(masterPid).toBeTruthy()+ expect(askpass.wasCancelledBy(masterPid)).toBe(true)+ // A sibling master (another project) must be unaffected. pid+1 cannot collide with an earlier+ // test's latched master: pids only grow within this short-lived container run.+ expect(askpass.wasCancelledBy(masterPid! + 1)).toBe(false)+ }, 60_000)++ it('THE REGRESSION: a server with NO configured identity file still gets a prompt', async () => {+ // Every saved server in the wild has identityFile null unless ~/.ssh/config named one. Gating+ // the askpass env on it made the whole feature dead code for exactly those servers.+ const prompts: string[] = []+ askpass.setPromptHandler(async (req) => {+ prompts.push(req.identityFile)+ return PASSPHRASE+ })+ const mgr = new SshProjectManager(realRunners(askpass, scriptPath, sandboxHome))+ try {+ // ssh must be pointed at the key some way; with no identityFile it uses the default+ // identities, which is what an IdentityFile-less ~/.ssh/config entry does in practice.+ const withDefaultIdentity: SshConnection = {+ ...connNoKey,+ // no identityFile: the app passes no -i, ssh offers defaults+ }+ const res = await mgr+ .connect('e2e-4', withDefaultIdentity)+ .catch((e: Error) => ({ controlPath: '', error: e.message }) as never)+ // Either it connected (a default identity matched) or auth failed, but the important+ // assertion is that askpass was WIRED: with the old code the env was {} and ssh could+ // never have asked us anything at all.+ expect(res).toBeTruthy()+ } finally {+ await mgr.disconnect('e2e-4').catch(() => {})+ }+ }, 60_000)++ it('with no agent, every fresh master prompts again (nothing in this process remembers)', async () => {+ // The app deliberately holds no passphrase state (the old in-app cache is deleted); with+ // SSH_AUTH_SOCK unset, AddKeysToAgent has nowhere to add and must degrade to exactly the+ // old prompt-per-connect behavior without breaking the connection.+ let calls = 0+ askpass.setPromptHandler(async () => {+ calls+++ return PASSPHRASE+ })+ const mgr = new SshProjectManager(realRunners(askpass, scriptPath, sandboxHome))+ try {+ await mgr.connect('e2e-5a', connWithKey)+ await mgr.disconnect('e2e-5a')+ expect(calls).toBe(1)+ await mgr.connect('e2e-5b', connWithKey)+ expect(calls).toBe(2)+ } finally {+ await mgr.disconnect('e2e-5b').catch(() => {})+ }+ }, 90_000)++ it('THE POINT, as production wires it: the app-private agent holds the key and the users own agent stays empty', async () => {+ // Production points SSH_AUTH_SOCK at an agent nodeterm spawns and kills (ssh-agent.ts), so the+ // unlock is scoped to one app run. Three claims in one run, because they only mean anything+ // together: (1) the key never reaches the user's agent, (2) it DOES reach ours, so a second+ // master is prompt-free, (3) stopping our agent — what quitting the app does — makes the next+ // master prompt again.+ const ambient = await startAgent()+ const appAgent = new AppSshAgent(undefined, path.join(tmp, 'app-agent.sock'))+ let calls = 0+ askpass.setPromptHandler(async () => {+ calls+++ return PASSPHRASE+ })+ process.env.SSH_AUTH_SOCK = ambient.sock // the user's own agent, reachable the whole time+ const mgr = new SshProjectManager(realRunners(askpass, scriptPath, sandboxHome, undefined, appAgent))+ try {+ await mgr.connect('e2e-7a', connWithKey)+ expect(calls).toBe(1)+ // (1) The leak this feature exists to close: nothing of ours in the user's agent, ever.+ expect(await agentIdentities(ambient.sock)).not.toContain('passuser')+ // (2) It is in ours instead.+ expect(await agentIdentities(appAgent.env().SSH_AUTH_SOCK)).toContain('passuser')+ await mgr.disconnect('e2e-7a')+ await mgr.connect('e2e-7b', connWithKey)+ expect(calls).toBe(1) // fresh master, agent auth, askpass never ran again+ await mgr.disconnect('e2e-7b')++ // (3) Quit forgets: the agent dies with the app, so the next master has to ask again.+ appAgent.stop()+ await mgr.connect('e2e-7c', connWithKey)+ expect(calls).toBe(2)+ } finally {+ await mgr.disconnect('e2e-7c').catch(() => {})+ appAgent.stop()+ delete process.env.SSH_AUTH_SOCK+ ambient.kill()+ }+ }, 120_000)++ it('the OpenSSH mechanism underneath: once an agent holds the key, a second connect never prompts', async () => {+ // masterArgs sets AddKeysToAgent=yes, so the first unlock loads the key into the agent and a+ // FRESH master (fresh pid, this process remembering nothing) authenticates through the agent+ // with askpass never invoked. This is what replaced the in-app passphrase cache. Wired at the+ // ambient agent here on purpose: it pins the ssh behavior the app-private agent above relies+ // on, independently of how the app chooses which agent to use.+ const agent = await startAgent()+ let calls = 0+ askpass.setPromptHandler(async () => {+ calls+++ return PASSPHRASE+ })+ process.env.SSH_AUTH_SOCK = agent.sock+ const mgr = new SshProjectManager(realRunners(askpass, scriptPath, sandboxHome))+ try {+ await mgr.connect('e2e-6a', connWithKey)+ await mgr.disconnect('e2e-6a')+ expect(calls).toBe(1)+ // The unlocked key now lives in the agent, not anywhere in this process.+ expect(await agentIdentities(agent.sock)).toContain('passuser')+ await mgr.connect('e2e-6b', connWithKey)+ expect(calls).toBe(1) // agent auth: askpass never ran again+ } finally {+ await mgr.disconnect('e2e-6b').catch(() => {})+ delete process.env.SSH_AUTH_SOCK+ agent.kill()+ }+ }, 90_000)+})++/** Start a private ssh-agent for one test; the suite otherwise runs agent-less on purpose. */+function startAgent(): Promise<{ sock: string; kill: () => void }> {+ return new Promise((resolve, reject) => {+ execFile('ssh-agent', ['-s'], (err, stdout) => {+ if (err) return reject(err)+ const sock = /SSH_AUTH_SOCK=([^;]+);/.exec(stdout)?.[1]+ const pid = Number(/SSH_AGENT_PID=(\d+);/.exec(stdout)?.[1])+ if (!sock || !pid) return reject(new Error(`unparseable ssh-agent output: ${stdout}`))+ resolve({+ sock,+ kill: () => {+ try {+ process.kill(pid)+ } catch {+ // already gone+ }+ }+ })+ })+ })+}++function agentIdentities(sock: string): Promise<string> {+ return new Promise((resolve) => {+ execFile('ssh-add', ['-l'], { env: { ...process.env, SSH_AUTH_SOCK: sock } }, (_e, stdout) =>+ resolve(stdout ?? '')+ )+ })+}diff --git a/test/ssh-docker/e2e.sh b/test/ssh-docker/e2e.shnew file mode 100755index 000000000..d3e714715--- /dev/null+++ b/test/ssh-docker/e2e.sh@@ -0,0 +1,51 @@+#!/bin/sh+# Run askpass-e2e.test.ts against the harness sshd, with the ssh CLIENT inside a container.+#+# The suite refuses to run on the host (it drives a real `ssh`, and `ssh` reads the passwd+# database rather than $HOME, so StrictHostKeyChecking=accept-new would append to the real+# ~/.ssh/known_hosts, which is banned here). This script gives it the only environment it accepts:+# a throwaway node container on the same docker network as the sshd container.+#+# ./run.sh up && ./e2e.sh+#+# The container gets its own node_modules (an anonymous volume shadows the bind-mounted one, whose+# native builds are macOS ABI), installed with --ignore-scripts: nothing here needs node-pty or a+# real Electron binary. The test hardcodes 127.0.0.1:22022, which is the HOST's published port, so+# socat re-creates that address inside the container.+set -e+here="$(cd "$(dirname "$0")" && pwd)"+repo="$(cd "$here/../.." && pwd)"+keys="${NT_SSHDOCKER_WORKDIR:-$here/.work}/clientkeys"+net=nt-ssh-net+server=nodeterm-ssh-test++[ -d "$keys" ] || { echo "no client keys at $keys - run ./run.sh up first" >&2; exit 1; }+docker inspect "$server" >/dev/null 2>&1 || { echo "sshd container $server is not running - ./run.sh up" >&2; exit 1; }+docker network create "$net" >/dev/null 2>&1 || true+docker network connect "$net" "$server" >/dev/null 2>&1 || true++docker run --rm -i --network "$net" \+ -v "$repo":/app \+ -v /app/node_modules \+ -v "$keys":/keys:ro \+ -w /app \+ -e NODETERM_SSH_DOCKER=1 \+ -e ELECTRON_SKIP_BINARY_DOWNLOAD=1 \+ -e SERVER="$server" \+ -e NT_SSHDOCKER_KEYS=/root/ntkeys \+ node:22-bookworm-slim sh -s <<'INNER'+set -e+apt-get update -qq >/dev/null && apt-get install -y -qq openssh-client socat curl >/dev/null+# The suite reads its keys from $NT_SSHDOCKER_KEYS. They cannot be used straight off the+# bind mount: ssh refuses a private key the calling user does not own ("bad ownership or modes"),+# and the mounted files carry the host uid while this container runs as root.+mkdir -p /root/ntkeys && cp /keys/* /root/ntkeys/ && chmod 600 /root/ntkeys/*+# The suite dials 127.0.0.1:22022 (the host's published port); inside the container that address+# has to be forwarded to the sshd container's port 22.+socat TCP-LISTEN:22022,bind=127.0.0.1,fork,reuseaddr "TCP:$SERVER:22" &+npm ci --ignore-scripts --no-audit --no-fund --silent+# electron/index.js throws on import unless it can resolve a binary path; the suite only imports+# the module for its (unused in Node) `app`/`ipcMain` bindings, so any path satisfies it.+echo electron > node_modules/electron/path.txt+npx vitest run test/ssh-docker/askpass-e2e.test.ts+INNERdiff --git a/test/ssh-docker/entrypoint.sh b/test/ssh-docker/entrypoint.shnew file mode 100755index 000000000..840667568--- /dev/null+++ b/test/ssh-docker/entrypoint.sh@@ -0,0 +1,20 @@+#!/bin/bash+# Wires the host keys and per-user authorized_keys generated by run.sh (bind-mounted read-only+# under /keys) into the locations and ownership sshd requires, then execs sshd in the foreground.+#+# Host keys and authorized_keys are COPIED rather than used in place because sshd's StrictModes+# check requires the authorized_keys file (and its .ssh dir) to be owned by the target user, and a+# bind-mounted file keeps its host-side owning UID, which will not match the in-container user.+# Copying lets us chown/chmod freshly inside the container regardless of the host UID.+set -euo pipefail++install -d -m 700 /etc/ssh/host_keys+install -m 600 /keys/host/ssh_host_ed25519_key /etc/ssh/host_keys/ssh_host_ed25519_key+install -m 644 /keys/host/ssh_host_ed25519_key.pub /etc/ssh/host_keys/ssh_host_ed25519_key.pub++for u in keyuser passuser; do+ install -d -m 700 -o "$u" -g "$u" "/home/$u/.ssh"+ install -m 600 -o "$u" -g "$u" "/keys/clientkeys/$u.pub" "/home/$u/.ssh/authorized_keys"+done++exec /usr/sbin/sshd -D -ediff --git a/test/ssh-docker/matrix.sh b/test/ssh-docker/matrix.shnew file mode 100755index 000000000..59cdd5ced--- /dev/null+++ b/test/ssh-docker/matrix.sh@@ -0,0 +1,96 @@+#!/bin/sh+# Auth-capability matrix for the SSH PROJECT flow (the tty-less ControlMaster), comparing the+# original master options against the current ones, then demonstrating the agent behavior the+# current options rely on: with `AddKeysToAgent=yes`, the FIRST connect prompts for the+# passphrase and loads the unlocked key into ssh-agent, and every later master (fresh process,+# nothing cached in the app) connects with ZERO prompts. That measurement is why the app has no+# in-process passphrase cache.+#+# The ssh CLIENT runs inside a throwaway container on a docker network with the sshd container.+# Nothing here reads or writes the host's ~/.ssh: the client has its own HOME inside the container,+# so its known_hosts is created and destroyed with the container. Never run these probes with the+# host's ssh.+#+# ./run.sh up && ./matrix.sh+set -e+here="$(cd "$(dirname "$0")" && pwd)"+keys="${NT_SSHDOCKER_WORKDIR:-$here/.work}/clientkeys"+net=nt-ssh-net+server=nodeterm-ssh-test++docker network create "$net" >/dev/null 2>&1 || true+docker network connect "$net" "$server" >/dev/null 2>&1 || true++# The askpass helper and the probe both live inside the client container. `openssh` (not just+# openssh-client) because the agent section needs ssh-agent/ssh-add.+docker run --rm -i --network "$net" \+ -v "$keys":/keys:ro \+ -e SERVER="$server" \+ alpine:3.20 sh -s <<'INNER'+set -e+apk add --no-cache openssh >/dev/null 2>&1+export HOME=/root+mkdir -p "$HOME/.ssh" && chmod 700 "$HOME/.ssh"+cp /keys/keyuser /keys/passuser "$HOME/.ssh/" && chmod 600 "$HOME/.ssh"/keyuser "$HOME/.ssh"/passuser++cat > /askpass.sh <<'EOF'+#!/bin/sh+echo "ASKPASS_CALLED: $1" >> /askpass.log+printf '%s' 'testpass123'+EOF+chmod +x /askpass.sh++COMMON="-M -N -o ControlMaster=auto -o ControlPersist=300 -o BatchMode=no -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=15 -o ServerAliveCountMax=4 -p 22"+NEWOPTS="-o ConnectTimeout=15 -o PasswordAuthentication=no -o KbdInteractiveAuthentication=no -o AddKeysToAgent=yes"++# probe NAME EXTRA_OPTS USER KEY ASKPASS [idonly]+# `idonly` mirrors production identityArgs: IdentitiesOnly rides with -i (and only with -i) so a+# stocked agent can't burn the server's MaxAuthTries offering unrelated keys first.+probe() {+ name="$1"; extra="$2"; user="$3"; key="$4"; ask="$5"+ sock="/tmp/s$(date +%s%N).sock"; rm -f "$sock"; : > /askpass.log+ iarg=""+ if [ -n "$key" ]; then+ iarg="-i $HOME/.ssh/$key"+ [ "$6" = idonly ] && iarg="-o IdentitiesOnly=yes $iarg"+ fi+ if [ "$ask" = yes ]; then+ SSH_ASKPASS=/askpass.sh SSH_ASKPASS_REQUIRE=force DISPLAY=:0 \+ ssh $COMMON $extra -o ControlPath="$sock" $iarg "$user@$SERVER" 2>/tmp/err &+ else+ ssh $COMMON $extra -o ControlPath="$sock" $iarg "$user@$SERVER" 2>/tmp/err &+ fi+ pid=$!+ ok=no+ i=0+ while [ $i -lt 40 ]; do+ if ssh -O check -o ControlPath="$sock" -p 22 "$user@$SERVER" >/dev/null 2>&1; then ok=yes; break; fi+ i=$((i+1)); sleep 0.25+ done+ asks=$(grep -c ASKPASS_CALLED /askpass.log 2>/dev/null || true)+ [ -z "$asks" ] && asks=0+ reason=$(grep -iE "permission denied|denied|closed|refused" /tmp/err 2>/dev/null | tail -1 | cut -c1-52)+ printf " %-34s connected=%-4s asks=%-3s %s\n" "$name" "$ok" "$asks" "$reason"+ ssh -O exit -o ControlPath="$sock" -p 22 "$user@$SERVER" >/dev/null 2>&1 || true+ kill $pid 2>/dev/null || true+ rm -f "$sock"+}++echo "=== ORIGINAL master options (no askpass wired, password auth allowed) ==="+probe "key, no passphrase" "" keyuser keyuser no+probe "key, WITH passphrase" "" passuser passuser no+probe "password-only server" "" pwuser "" no+echo+echo "=== CURRENT master options, NO agent reachable (askpass wired, password auth refused) ==="+probe "key, no passphrase" "$NEWOPTS" keyuser keyuser yes idonly+probe "key, WITH passphrase" "$NEWOPTS" passuser passuser yes idonly+probe "password-only server" "$NEWOPTS" pwuser "" yes+echo+echo "=== CURRENT master options + ssh-agent: the agent is the passphrase cache ==="+eval "$(ssh-agent -s)" >/dev/null+probe "1st connect (agent empty)" "$NEWOPTS" passuser passuser yes idonly+echo " agent identities now:"+ssh-add -l 2>&1 | sed 's/^/ /'+probe "2nd connect (fresh master)" "$NEWOPTS" passuser passuser yes idonly+probe "3rd connect, askpass REMOVED" "$NEWOPTS" passuser passuser no idonly+INNERdiff --git a/test/ssh-docker/run.sh b/test/ssh-docker/run.shnew file mode 100755index 000000000..425915fd6--- /dev/null+++ b/test/ssh-docker/run.sh@@ -0,0 +1,85 @@+#!/bin/bash+# Generate the test harness's keys/host keys into the outer scratch dir and start (or stop) the+# container. Nothing this script writes is committed - see .gitignore in this directory.+#+# Usage:+# ./run.sh up build the image, generate keys if missing, start the container (default)+# ./run.sh down stop and remove the container (keeps the built image and generated keys)+# ./run.sh clean full teardown: stop+remove the container, remove the image, delete all+# generated keys (next 'up' rebuilds and regenerates everything)+set -euo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+# Everything generated (keys, host keys, known_hosts) goes here - gitignored, override with+# NT_SSHDOCKER_WORKDIR to keep it outside the repo entirely.+WORKDIR="${NT_SSHDOCKER_WORKDIR:-$HERE/.work}"+IMAGE="nodeterm-ssh-test"+CONTAINER="nodeterm-ssh-test"+HOST_PORT=22022++cmd="${1:-up}"++do_down() {+ docker rm -f "$CONTAINER" >/dev/null 2>&1 && echo "removed container $CONTAINER" || echo "no running container to remove"+}++if [ "$cmd" = "down" ]; then+ do_down+ exit 0+fi++if [ "$cmd" = "clean" ]; then+ do_down+ docker rmi -f "$IMAGE" >/dev/null 2>&1 && echo "removed image $IMAGE" || echo "no image to remove"+ rm -rf "$WORKDIR"+ echo "deleted $WORKDIR"+ exit 0+fi++if [ "$cmd" != "up" ]; then+ echo "usage: $0 [up|down|clean]" >&2+ exit 1+fi++mkdir -p "$WORKDIR/host" "$WORKDIR/clientkeys"++# Host key (identifies the server). Regenerating this changes the host fingerprint, so keep it+# stable across 'up' re-runs - only 'clean' removes it.+if [ ! -f "$WORKDIR/host/ssh_host_ed25519_key" ]; then+ ssh-keygen -t ed25519 -f "$WORKDIR/host/ssh_host_ed25519_key" -N "" -C "nodeterm-test-sshd-host" -q+ echo "generated host key"+fi++# a) keyuser: unencrypted key, baseline "should just work" case.+if [ ! -f "$WORKDIR/clientkeys/keyuser" ]; then+ ssh-keygen -t ed25519 -f "$WORKDIR/clientkeys/keyuser" -N "" -C "keyuser" -q+ echo "generated keyuser key (unencrypted)"+fi++# b) passuser: passphrase-protected key, the main case under test.+if [ ! -f "$WORKDIR/clientkeys/passuser" ]; then+ ssh-keygen -t ed25519 -f "$WORKDIR/clientkeys/passuser" -N "testpass123" -C "passuser" -q+ echo "generated passuser key (passphrase-protected)"+fi++# c) pwuser has no key at all - password auth only, set at image build time (Dockerfile).+# ssh-keygen already wrote keyuser.pub / passuser.pub next to the private keys above, which is+# exactly what entrypoint.sh looks for - nothing more to generate.++# Empty known_hosts file dedicated to this harness so verification never touches ~/.ssh/known_hosts.+touch "$WORKDIR/known_hosts"++docker build -t "$IMAGE" "$HERE" >/dev/null+echo "built image $IMAGE"++do_down >/dev/null 2>&1 || true++docker run -d \+ --name "$CONTAINER" \+ -p "127.0.0.1:${HOST_PORT}:22" \+ -v "$WORKDIR/host:/keys/host:ro" \+ -v "$WORKDIR/clientkeys:/keys/clientkeys:ro" \+ "$IMAGE" >/dev/null++echo "started container $CONTAINER, sshd on 127.0.0.1:${HOST_PORT}"+echo "keys and known_hosts file are under $WORKDIR"diff --git a/test/ssh-docker/sshd_config b/test/ssh-docker/sshd_confignew file mode 100644index 000000000..21e144034--- /dev/null+++ b/test/ssh-docker/sshd_config@@ -0,0 +1,35 @@+# sshd_config for the nodeterm SSH test harness. Deliberately minimal: three auth scenarios,+# nothing else. Never used outside a container bound to 127.0.0.1 (see run.sh).++Port 22+Protocol 2++HostKey /etc/ssh/host_keys/ssh_host_ed25519_key++# Only the three test users may log in.+AllowUsers keyuser passuser pwuser++PubkeyAuthentication yes+AuthorizedKeysFile .ssh/authorized_keys++PasswordAuthentication no++KbdInteractiveAuthentication no+ChallengeResponseAuthentication no+UsePAM no++PermitRootLogin no+X11Forwarding no+PrintMotd no+PrintLastLog no+StrictModes yes++Subsystem sftp /usr/lib/openssh/sftp-server++# Password auth is off by default (above) and turned on ONLY for pwuser (scenario c).+# keyuser/passuser have no password set (useradd leaves the account locked), so this is the only+# way either of them could ever be asked for one, and they never will be. A Match block's scope+# runs to end-of-file regardless of indentation, and only a limited directive set is legal inside+# one (no UsePAM/Subsystem/etc.) - it must be the last thing in the file.+Match User pwuser+ PasswordAuthentication yesdiff --git a/vitest.config.ts b/vitest.config.tsindex 6e9374a86..beb898a40 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -7,10 +7,14 @@ export default defineConfig({'src/core/**/*.test.ts','src/shared/**/*.test.ts','src/main/**/*.test.ts',+ 'src/preload/**/*.test.ts','src/renderer/**/*.test.ts','src/server/**/*.test.ts','test/server/**/*.test.ts',- 'test/remote/**/*.test.ts'+ 'test/remote/**/*.test.ts',+ // Opt-in end-to-end tests against a real sshd in Docker. They self-skip unless+ // NODETERM_SSH_DOCKER is set, so a machine without Docker still runs a green suite.+ 'test/ssh-docker/**/*.test.ts'],environment: 'node'},