Skip to content

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.

feat(ssh): serve the askpass relay on a 0600 unix socket

parsa222ddbd3ebe600c
diff --git a/src/main/remote-ssh/ssh-agent.ts b/src/main/remote-ssh/ssh-agent.ts
index 8d38bc032..f7f2638b5 100644
--- a/src/main/remote-ssh/ssh-agent.ts
+++ b/src/main/remote-ssh/ssh-agent.ts
@@ -90,8 +90,13 @@ function defaultDataDirKey(): string {
* (`NT_MULTI=1`, ./dev-test.sh, a dev build next to the installed app) binds its own socket
* instead of unlinking the first one's and silently leaving that app agentless when it quits. */
export function agentSockPath(dataDirKey = defaultDataDirKey()): string {
- const id = createHash('sha256').update(dataDirKey).digest('hex').slice(0, 8)
- return path.join(os.homedir(), '.nodeterm', `agent-${id}.sock`)
+ return path.join(os.homedir(), '.nodeterm', `agent-${instanceSockId(dataDirKey)}.sock`)
+}
+
+/** The per-instance hash shared by every socket this app run binds under ~/.nodeterm (the agent
+ * above, the askpass relay), so NT_MULTI instances never unlink each other's sockets. */
+export function instanceSockId(dataDirKey = defaultDataDirKey()): string {
+ return createHash('sha256').update(dataDirKey).digest('hex').slice(0, 8)
}
export class AppSshAgent {
diff --git a/src/main/remote-ssh/ssh-askpass.test.ts b/src/main/remote-ssh/ssh-askpass.test.ts
index c42da1fb7..5930a2832 100644
--- a/src/main/remote-ssh/ssh-askpass.test.ts
+++ b/src/main/remote-ssh/ssh-askpass.test.ts
@@ -1,9 +1,39 @@
import { afterEach, describe, expect, it } from 'vitest'
+import { request as httpRequest } from 'http'
+import { promises as fsp } from 'fs'
+import os from 'os'
+import path from 'path'
import { AskpassServer, buildAskpassScript, classifyPrompt, type AskpassPromptRequest } from './ssh-askpass'
/** ssh's real passphrase prompt (sshconnect2.c), byte-identical on every retry. */
const passphrasePrompt = (key: string) => `Enter passphrase for key '${key}': `
+let sockSeq = 0
+/** A unique tmpdir socket per server: the production default under ~/.nodeterm must not be
+ * touched by tests, and unix sockets cannot be double-bound like port 0 could. */
+const tmpSock = (): string => path.join(os.tmpdir(), `nt-ap-${process.pid}-${sockSeq++}.sock`)
+
+/** fetch() cannot speak unix sockets; this is the minimal http.request equivalent. */
+function sockReq(
+ sock: string,
+ urlPath: string,
+ opts: { method?: string; headers?: Record<string, string>; body?: string } = {}
+): Promise<{ status: number; body: string }> {
+ return new Promise((resolve, reject) => {
+ const req = httpRequest(
+ { socketPath: sock, path: urlPath, method: opts.method ?? 'POST', headers: opts.headers },
+ (res) => {
+ let data = ''
+ res.on('data', (c) => (data += String(c)))
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body: data }))
+ }
+ )
+ req.on('error', reject)
+ if (opts.body) req.write(opts.body)
+ req.end()
+ })
+}
+
describe('classifyPrompt', () => {
it('recognizes the key-passphrase prompt and extracts the key ssh actually wants', () => {
expect(classifyPrompt(passphrasePrompt('/home/u/.ssh/id_ed25519'))).toEqual({
@@ -27,12 +57,12 @@ describe('classifyPrompt', () => {
})
describe('buildAskpassScript', () => {
- it('is a POSIX-sh script that curls the loopback server with the expected fields', () => {
+ it('is a POSIX-sh script that curls the unix socket with the expected fields', () => {
const script = buildAskpassScript()
expect(script.startsWith('#!/bin/sh')).toBe(true)
- expect(script).toContain('curl')
+ expect(script).toContain('--unix-socket')
expect(script).toContain('/prompt')
- expect(script).toContain('NODETERM_ASKPASS_PORT')
+ expect(script).toContain('NODETERM_ASKPASS_SOCK')
expect(script).toContain('NODETERM_ASKPASS_TOKEN')
expect(script).toContain('NODETERM_ASKPASS_IDENTITY')
// The invoking ssh pid: a SECOND ask from the same pid selects the "didn't work" dialog copy
@@ -53,7 +83,7 @@ describe('AskpassServer', () => {
async function makeServer(handler?: (req: AskpassPromptRequest) => Promise<string | null>) {
const s = new AskpassServer()
if (handler) s.setPromptHandler(handler)
- await s.start()
+ await s.start(tmpSock())
server = s
return s
}
@@ -64,15 +94,13 @@ describe('AskpassServer', () => {
caller: string,
prompt = passphrasePrompt(identity)
): Promise<{ status: number; body: string }> {
- const res = await fetch(`http://127.0.0.1:${s.getPort()}/prompt`, {
- method: 'POST',
+ return sockReq(s.getSockPath(), '/prompt', {
headers: {
'content-type': 'application/x-www-form-urlencoded',
'x-nodeterm-askpass-token': s.getToken()
},
body: new URLSearchParams({ identity, caller, prompt }).toString()
})
- return { status: res.status, body: await res.text() }
}
it('answers a throwing prompt handler with an empty 200, and a wrong route with a clean 404', async () => {
@@ -86,20 +114,30 @@ describe('AskpassServer', () => {
const res = await post(s, '/home/u/.ssh/id_ed25519', '111')
expect(res.status).toBe(200)
expect(res.body).toBe('')
- const wrongRoute = await fetch(`http://127.0.0.1:${s.getPort()}/nope`, { method: 'GET' })
+ const wrongRoute = await sockReq(s.getSockPath(), '/nope', { method: 'GET' })
expect(wrongRoute.status).toBe(404)
- expect(await wrongRoute.text()).toBe('')
+ expect(wrongRoute.body).toBe('')
})
it('rejects a bad token with 403', async () => {
const s = await makeServer()
- const res = await fetch(`http://127.0.0.1:${s.getPort()}/prompt`, {
- method: 'POST',
+ const res = await sockReq(s.getSockPath(), '/prompt', {
headers: { 'x-nodeterm-askpass-token': 'wrong' }
})
expect(res.status).toBe(403)
})
+ it('binds the socket owner-only (0600) and unlinks it on stop', async () => {
+ // The socket's file mode IS the access control now: any other user must be refused by the
+ // kernel, not by guessing wrong at the token.
+ const s = await makeServer()
+ const sock = s.getSockPath()
+ expect(((await fsp.stat(sock)).mode & 0o777).toString(8)).toBe('600')
+ s.stop()
+ server = undefined
+ await expect(fsp.stat(sock)).rejects.toThrow()
+ })
+
it('holds no passphrase state: every NEW ssh process prompts (prompt-free reconnects are the agent, not us)', async () => {
// The old in-app cache served a second master from memory. AddKeysToAgent=yes replaced it:
// once the agent holds the key, ssh never invokes askpass at all, so any ask that DOES reach
@@ -312,8 +350,7 @@ describe('AskpassServer', () => {
it('drops an oversized body without wedging the server', async () => {
const s = await makeServer(async () => 'never-asked')
const big = 'x'.repeat(80_000)
- await fetch(`http://127.0.0.1:${s.getPort()}/prompt`, {
- method: 'POST',
+ await sockReq(s.getSockPath(), '/prompt', {
headers: {
'content-type': 'application/x-www-form-urlencoded',
'x-nodeterm-askpass-token': s.getToken()
diff --git a/src/main/remote-ssh/ssh-askpass.ts b/src/main/remote-ssh/ssh-askpass.ts
index 7e588fb4f..264f55e59 100644
--- a/src/main/remote-ssh/ssh-askpass.ts
+++ b/src/main/remote-ssh/ssh-askpass.ts
@@ -1,8 +1,8 @@
// SSH_ASKPASS support for the project ControlMaster (ssh-project.ts), which spawns ssh with no
// tty (stdio ignored), so OpenSSH has nowhere to prompt for an encrypted identity file's
-// passphrase. This gives it somewhere: a generated askpass script that curls a loopback server
+// passphrase. This gives it somewhere: a generated askpass script that curls a unix socket served
// here, which in turn asks the renderer (via an injected prompt handler). No electron import,
-// unit-testable like hook-server.ts's HookServer, against a real ephemeral port.
+// unit-testable like hook-server.ts's HookServer, against a real socket in a tmpdir.
//
// This server deliberately holds NO passphrase state. masterArgs sets `AddKeysToAgent=yes`, so a
// successful unlock loads the key into an ssh-agent and every later connect (reconnect, watchdog
@@ -36,8 +36,10 @@
// askpass existed.
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'
import { randomUUID, timingSafeEqual } from 'crypto'
-import { promises as fs } from 'fs'
+import { promises as fs, rmSync } from 'fs'
+import os from 'os'
import path from 'path'
+import { instanceSockId } from './ssh-agent'
const ASKPASS_SCRIPT_NAME = 'ssh-askpass.sh'
/** A passphrase prompt body is a few bytes; cap generously against a misbehaving caller. */
@@ -88,17 +90,25 @@ export function classifyPrompt(prompt: string): { passphrase: boolean; keyPath?:
/**
* The SSH_ASKPASS helper ssh invokes when it needs a passphrase and has no tty to prompt into.
- * One curl POST to our loopback server, printing whatever it returns (the passphrase, or nothing
+ * One curl POST to our 0600 unix socket, printing whatever it returns (the passphrase, or nothing
* on cancel) to stdout, which is exactly SSH_ASKPASS's contract. Generated at runtime into
* userData rather than bundled via electron-builder, so packaging needs no changes (mirrors how
* hook-server.ts writes hook-endpoint.env there); curl is already a hard runtime dependency of
* this app's agent hooks, so this introduces nothing new. Values are env-expanded by sh and the
* results are never re-parsed, so hostile characters in a path cannot inject.
*/
+/** Per-instance socket path, sharing the app agent's short dir and hashing (a unix socket path
+ * is capped near 104 bytes, which userData eats). OS file permissions are the primary access
+ * control: the dir is 0700 and the socket is chmod'd 0600 right after bind, so only this user
+ * can connect at all. The bearer token stays as a second factor. */
+export function askpassSockPath(): string {
+ return path.join(os.homedir(), '.nodeterm', `askpass-${instanceSockId()}.sock`)
+}
+
export function buildAskpassScript(): string {
return [
'#!/bin/sh',
- 'answer=$(curl -sS --max-time 300 -X POST "http://127.0.0.1:${NODETERM_ASKPASS_PORT}/prompt" \\',
+ 'answer=$(curl -sS --max-time 300 --unix-socket "${NODETERM_ASKPASS_SOCK}" -X POST "http://localhost/prompt" \\',
' -H "X-Nodeterm-Askpass-Token: ${NODETERM_ASKPASS_TOKEN}" \\',
' --data-urlencode "identity=${NODETERM_ASKPASS_IDENTITY}" \\',
' --data-urlencode "caller=$PPID" \\',
@@ -107,7 +117,7 @@ export function buildAskpassScript(): string {
// the key, and the connect dies with a bare "Permission denied (publickey)" that says nothing
// about the helper. (Exactly how a container with no curl looked.) The breadcrumb goes to
// stderr, which is the master's captured stderr, so it reaches the app's log.
- '[ $? -eq 0 ] || { echo "nodeterm-askpass: no answer from the app on 127.0.0.1:${NODETERM_ASKPASS_PORT} (curl missing or the app is gone)" >&2; exit 1; }',
+ '[ $? -eq 0 ] || { echo "nodeterm-askpass: no answer from the app on ${NODETERM_ASKPASS_SOCK} (curl missing or the app is gone)" >&2; exit 1; }',
"printf '%s' \"$answer\"",
''
].join('\n')
@@ -140,7 +150,7 @@ type PromptHandler = (req: AskpassPromptRequest) => Promise<string | null | unde
export class AskpassServer {
private server: Server | null = null
- private port = 0
+ private sockPath = ''
private token = ''
private promptHandler: PromptHandler | null = null
/** Caller pids (the ssh process the askpass helper reported as its $PPID) whose prompt the user
@@ -174,8 +184,8 @@ export class AskpassServer {
* report the generic connection error instead of the "needs its passphrase" one. */
private inflight = new Map<string, { done: Promise<string | null>; callers: Set<string> }>()
- getPort(): number {
- return this.port
+ getSockPath(): string {
+ return this.sockPath
}
getToken(): string {
return this.token
@@ -185,9 +195,13 @@ export class AskpassServer {
this.promptHandler = cb
}
- async start(): Promise<void> {
+ async start(sockPath: string = askpassSockPath()): Promise<void> {
if (this.server) return
this.token = randomUUID()
+ this.sockPath = sockPath
+ // The dir gates the pre-chmod window below; a stale socket file from a crash would EADDRINUSE.
+ await fs.mkdir(path.dirname(sockPath), { recursive: true, mode: 0o700 })
+ await fs.rm(sockPath, { force: true })
this.server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
try {
if (req.method !== 'POST' || !(req.url ?? '').startsWith('/prompt')) {
@@ -227,20 +241,28 @@ export class AskpassServer {
const onOk = (): void => {
this.server?.off('error', onErr)
this.server?.on('error', (e) => console.error('[ssh-askpass] server error', e))
- const addr = this.server!.address()
- if (addr && typeof addr === 'object') this.port = addr.port
resolve()
}
this.server!.once('error', onErr)
- this.server!.listen(0, '127.0.0.1', onOk)
+ this.server!.listen(sockPath, onOk)
})
+ // listen() binds with umask permissions; tighten to owner-only. The 0700 dir above closes
+ // the window between bind and this chmod.
+ await fs.chmod(sockPath, 0o600)
}
stop(): void {
this.server?.close()
this.server = null
- this.port = 0
this.token = ''
+ if (this.sockPath) {
+ try {
+ rmSync(this.sockPath, { force: true })
+ } catch {
+ // best effort: a leftover socket file is unlinked by the next start()
+ }
+ this.sockPath = ''
+ }
}
private async resolvePassphrase(
@@ -365,7 +387,7 @@ export class AskpassServer {
// OpenSSH instead gates askpass on DISPLAY being set (with no tty); set both for portability.
SSH_ASKPASS_REQUIRE: 'force',
DISPLAY: process.env.DISPLAY || ':0',
- NODETERM_ASKPASS_PORT: String(this.port),
+ NODETERM_ASKPASS_SOCK: this.sockPath,
NODETERM_ASKPASS_TOKEN: this.token,
// Only a hint, and often absent: a saved server usually has no configured identity file.
// The prompt names the key ssh actually wants, and that is what the latch/counting key by.
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index 73a0189e4..9c0fd0fb3 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -1,4 +1,5 @@
import { promises as fs, writeFileSync } from 'fs'
+import { request as httpRequest } from 'http'
import os from 'os'
import path from 'path'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -1596,21 +1597,35 @@ describe('SshProjectManager', () => {
// Real timers: the exit-grace loop is only ~5 checks x 100ms per connect.
const s = new AskpassServer()
s.setPromptHandler(async () => null) // the user hits Cancel
- await s.start()
+ await s.start(path.join(os.tmpdir(), `nt-ap-proj-${process.pid}.sock`))
try {
// Drive the decline the way the real helper does: a POST whose caller field is the $PPID
- // the askpass script reports, which is the pid of the master the app spawned.
- await fetch(`http://127.0.0.1:${s.getPort()}/prompt`, {
- method: 'POST',
- headers: {
- 'content-type': 'application/x-www-form-urlencoded',
- 'x-nodeterm-askpass-token': s.getToken()
- },
- body: new URLSearchParams({
- identity: '/home/u/.ssh/id_ed25519',
- caller: '4242',
- prompt: "Enter passphrase for key '/home/u/.ssh/id_ed25519': "
- }).toString()
+ // the askpass script reports, which is the pid of the master the app spawned. fetch()
+ // cannot speak unix sockets, so this is the raw http.request equivalent.
+ await new Promise<void>((resolve, reject) => {
+ const req = httpRequest(
+ {
+ socketPath: s.getSockPath(),
+ path: '/prompt',
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/x-www-form-urlencoded',
+ 'x-nodeterm-askpass-token': s.getToken()
+ }
+ },
+ (res) => {
+ res.resume()
+ res.on('end', () => resolve())
+ }
+ )
+ req.on('error', reject)
+ req.end(
+ new URLSearchParams({
+ identity: '/home/u/.ssh/id_ed25519',
+ caller: '4242',
+ prompt: "Enter passphrase for key '/home/u/.ssh/id_ed25519': "
+ }).toString()
+ )
})
const mgrWithMasterPid = (pid: number) =>
new SshProjectManager({