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.

fix(ssh): share probe never runs an unrecognised server; refuse unsafe values; tmux-message kill verdicts

review92de54e8ff7d
diff --git a/src/core/remote-ssh/share-team-remote.test.ts b/src/core/remote-ssh/share-team-remote.test.ts
index 256928dc5..9a2e93184 100644
--- a/src/core/remote-ssh/share-team-remote.test.ts
+++ b/src/core/remote-ssh/share-team-remote.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest'
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import fs from 'node:fs'
@@ -10,18 +10,26 @@ import {
} from './share-team-remote'
const run = promisify(execFile)
-let dir: string, home: string, bin: string, state: string
+let dir: string, home: string, bin: string, state: string, wrongSocketLog: string, nodeLog: string
const write = (p: string, body: string, mode = 0o644): void => {
fs.mkdirSync(path.dirname(p), { recursive: true })
fs.writeFileSync(p, body, { mode })
}
+const REAL_TIMEOUT = ['/usr/bin/timeout', '/bin/timeout'].find((p) => fs.existsSync(p)) ?? ''
+const findTool = (name: string): string => ['/usr/bin', '/bin'].map((d) => path.join(d, name)).find((p) => fs.existsSync(p)) ?? ''
+// A server bundle that knows `team bootstrap` carries its usage row as text; the probe detects the
+// verb from that text and never by running the bundle.
+const NEW_MAIN = '// nodeterm-server\nconst USAGE = " bootstrap --owner-key <key> --adopt <dir> [--owner-label <name>] [--json]"\n'
+const OLD_MAIN = '// an older nodeterm-server, from before the team admin CLI\n'
beforeAll(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-share-'))
home = path.join(dir, 'home')
bin = path.join(dir, 'bin')
state = path.join(dir, 'tmux-state')
+ wrongSocketLog = path.join(dir, 'tmux-wrong-socket.log')
+ nodeLog = path.join(dir, 'node-calls.log')
fs.mkdirSync(state, { recursive: true })
fs.mkdirSync(path.join(home, 'proj'), { recursive: true })
write(path.join(bin, 'uname'), '#!/bin/sh\necho Linux\n', 0o755)
@@ -29,14 +37,24 @@ beforeAll(() => {
write(path.join(bin, 'git'), '#!/bin/sh\nexit 0\n', 0o755)
// A fake tmux: sessions are files in $STATE; a "*.stuck" one survives kill-session. Like real
// tmux, a target WITHOUT the leading `=` that matches no session exactly falls back to a prefix
- // match, so a missing `=` in the generated command would kill a longer id's session.
+ // match, and a miss prints tmux's own message (measured on tmux 3.4) with exit 1. Any socket but
+ // this desktop's `nodeterm-rmt` is recorded and refused, so a kill aimed at another socket fails.
+ // FAKE_TMUX_MODE makes every call fail with one of tmux's connect or version errors.
write(
path.join(bin, 'tmux'),
[
'#!/bin/sh',
`S=${JSON.stringify(state)}`,
- 'cmd=""; target=""',
- 'while [ $# -gt 0 ]; do case "$1" in -L) shift;; -t) shift; target="$1";; kill-session|has-session|list-panes) cmd="$1";; esac; shift; done',
+ `W=${JSON.stringify(wrongSocketLog)}`,
+ 'cmd=""; target=""; sock=""',
+ 'while [ $# -gt 0 ]; do case "$1" in -L) shift; sock="$1";; -t) shift; target="$1";; kill-session|has-session|list-panes) cmd="$1";; esac; shift; done',
+ 'if [ "$sock" != nodeterm-rmt ]; then echo "$sock $cmd $target" >> "$W"; echo "fake tmux: unexpected socket" >&2; exit 99; fi',
+ 'case "$FAKE_TMUX_MODE" in',
+ " mismatch) echo 'protocol version mismatch (client 8, server 7)' >&2; exit 1;;",
+ " denied) echo 'error connecting to /tmp/tmux-1000/nodeterm-rmt (Permission denied)' >&2; exit 1;;",
+ " nofile) echo 'error connecting to /tmp/tmux-1000/nodeterm-rmt (No such file or directory)' >&2; exit 1;;",
+ " refused) echo 'error connecting to /tmp/tmux-1000/nodeterm-rmt (Connection refused)' >&2; exit 1;;",
+ 'esac',
'name="${target#=}"',
'exact=0; [ "$name" != "$target" ] && exact=1',
'resolve() {',
@@ -45,23 +63,25 @@ beforeAll(() => {
' for f in "$S/$name"*; do [ -e "$f" ] || continue; b=$(basename "$f"); name="${b%.stuck}"; return 0; done',
' return 1',
'}',
+ "missing() { if [ -n \"$(ls \"$S\")\" ]; then echo \"can't find session: $name\" >&2; else echo 'no server running on /tmp/tmux-1000/nodeterm-rmt' >&2; fi; exit 1; }",
'case "$cmd" in',
' list-panes) for f in "$S"/*; do [ -e "$f" ] || continue; b=$(basename "$f"); b="${b%.stuck}"; echo "$b|$(cat "$f")"; done; exit 0;;',
- ' kill-session) resolve || exit 1; [ -e "$S/$name.stuck" ] && exit 0; rm -f "$S/$name"; exit 0;;',
- ' has-session) resolve && exit 0; exit 1;;',
+ ' kill-session) resolve || missing; [ -e "$S/$name.stuck" ] && exit 0; rm -f "$S/$name"; exit 0;;',
+ ' has-session) resolve && exit 0; missing;;',
'esac',
'exit 1'
].join('\n'),
0o755
)
- // A fake node that answers `team --help`, `team … status --json` and echoes argv + stdin for other verbs.
+ // A fake node: records every call, answers `team … status --json`, and echoes argv + stdin for
+ // other verbs. It has no `--help`: bootstrap support is read from main.cjs's contents.
write(
path.join(bin, 'node'),
[
'#!/bin/sh',
+ `echo "$*" >> ${JSON.stringify(nodeLog)}`,
'shift', // main.cjs
'case "$*" in',
- ` "team --help") printf 'usage: team <command>\\n init create\\n bootstrap --owner-key <key> set up\\n';;`,
` *" status --json") printf '{\\n "enabled": true,\\n "off": null\\n}\\n';;`,
` *" --no-newline") printf '{"a":1}';;`,
` *) printf '{"argv":"%s","stdin":"%s"}\\n' "$*" "$(cat | tr -d '\\n"')";;`,
@@ -70,7 +90,7 @@ beforeAll(() => {
0o755
)
const main = path.join(home, '.nodeterm-server-app', 'out', 'server', 'main.cjs')
- write(main, '')
+ write(main, NEW_MAIN)
write(
path.join(home, '.config', 'systemd', 'user', 'nodeterm-server.service'),
`[Service]\nEnvironment=NODETERM_HEADLESS=1\nExecStart=${path.join(bin, 'node')} ${main}\n`
@@ -78,12 +98,32 @@ beforeAll(() => {
write(path.join(home, '.nodeterm-server', 'install-meta.json'), '{"commit":"abc1234","installedAt":"x","version":"0.4.0"}\n')
})
afterAll(() => fs.rmSync(dir, { recursive: true, force: true }))
+afterEach(() => {
+ // Only this desktop's socket may ever be addressed (see the fake tmux).
+ const wrong = fs.existsSync(wrongSocketLog) ? fs.readFileSync(wrongSocketLog, 'utf8') : ''
+ fs.rmSync(wrongSocketLog, { force: true })
+ expect(wrong).toBe('')
+})
-const sh = async (command: string, stdin?: string): Promise<string> => {
- const p = run('/bin/sh', ['-c', command], { env: { HOME: home, PATH: `${bin}:/usr/bin:/bin` } })
+const sh = async (command: string, stdin?: string, env: Record<string, string> = {}): Promise<string> => {
+ const p = run('/bin/sh', ['-c', command], { env: { HOME: home, PATH: `${bin}:/usr/bin:/bin`, ...env } })
if (stdin !== undefined) p.child.stdin?.end(stdin)
return (await p).stdout
}
+/** A home holding one user unit that runs `nodeBin` on a main.cjs with `mainBody`. */
+const homeWithUnit = (name: string, nodeBin: string, mainBody: string): string => {
+ const h = path.join(dir, name)
+ const main = path.join(h, '.nodeterm-server-app', 'out', 'server', 'main.cjs')
+ write(main, mainBody)
+ write(path.join(h, '.config', 'systemd', 'user', 'nodeterm-server.service'), `[Service]\nExecStart=${nodeBin} ${main}\n`)
+ return h
+}
+/** The script inside `sh -c '<script>'`, decoded the way POSIX sh decodes the single quotes. */
+const innerScript = (command: string): string => {
+ expect(command.startsWith("sh -c '") && command.endsWith("'")).toBe(true)
+ return command.slice("sh -c '".length, -1).split("'\\''").join("'")
+}
+const noSystemUnit = (): string => path.join(dir, 'etc', 'no-such.service')
describe.skipIf(process.platform === 'win32')('share-team remote shell (real /bin/sh, fake host)', () => {
it('probes a user install: unit, node, main, data dir, meta, bootstrap verb, status, real cwd, panes', async () => {
@@ -106,8 +146,7 @@ describe.skipIf(process.platform === 'win32')('share-team remote shell (real /bi
it('a host with nothing installed and a missing folder', async () => {
const bare = path.join(dir, 'bare-home')
fs.mkdirSync(bare, { recursive: true })
- const cmd = shareProbeCommand('~/nope', path.join(dir, 'etc', 'no-such.service'))
- const out = (await run('/bin/sh', ['-c', cmd], { env: { HOME: bare, PATH: `${bin}:/usr/bin:/bin` } })).stdout
+ const out = await sh(shareProbeCommand('~/nope', noSystemUnit()), undefined, { HOME: bare })
const p = parseShareProbe(out)
if ('error' in p) throw new Error(p.error)
expect(p).toMatchObject({ unit: 'none', node: '', main: '', hasBootstrap: false, statusRc: null, adoptCwd: null, meta: null })
@@ -117,11 +156,56 @@ describe.skipIf(process.platform === 'win32')('share-team remote shell (real /bi
fs.mkdirSync(bare, { recursive: true })
const unit = path.join(dir, 'etc', 'nodeterm-server.service')
write(unit, '[Service]\nExecStart=/usr/bin/node /opt/nodeterm/out/server/main.cjs\n')
- const out = (await run('/bin/sh', ['-c', shareProbeCommand('~', unit)], { env: { HOME: bare, PATH: `${bin}:/usr/bin:/bin` } })).stdout
- const p = parseShareProbe(out)
+ const p = parseShareProbe(await sh(shareProbeCommand('~', unit), undefined, { HOME: bare }))
if ('error' in p) throw new Error(p.error)
expect(p).toMatchObject({ unit: 'system', node: '', main: '', adoptCwd: fs.realpathSync(bare) })
})
+ it('never runs an installed server too old to know the team CLI (it would boot a second server)', async () => {
+ // Before the team CLI, `main.cjs team …` ignored `team` and started a full server that never exits.
+ const bootLog = path.join(dir, 'old-server-ran.log')
+ const booting = path.join(dir, 'bin-old', 'node')
+ write(booting, ['#!/bin/sh', `echo "$*" >> ${JSON.stringify(bootLog)}`, 'echo "nodeterm-server listening on http 127.0.0.1:7681"', 'exec sleep 30'].join('\n'), 0o755)
+ const oldHome = homeWithUnit('old-home', booting, OLD_MAIN)
+ const started = Date.now()
+ const p = parseShareProbe(await sh(shareProbeCommand('~', noSystemUnit()), undefined, { HOME: oldHome }))
+ expect(Date.now() - started).toBeLessThan(4000)
+ if ('error' in p) throw new Error(p.error)
+ expect(p).toMatchObject({ unit: 'user', node: booting, hasBootstrap: false, statusRc: null, teamExists: false })
+ expect(fs.existsSync(bootLog)).toBe(false)
+ })
+ it('bounds the status call with `timeout 10`, and gives the server no stdin', async () => {
+ // A server new enough for the team CLI that does not answer: the probe still finishes.
+ const hangLog = path.join(dir, 'hung-server.log')
+ const hung = path.join(dir, 'bin-hung', 'node')
+ write(hung, ['#!/bin/sh', 'if read -r line; then echo "stdin:$line" >> ' + JSON.stringify(hangLog) + '; fi', `echo "$*" >> ${JSON.stringify(hangLog)}`, 'exec sleep 30'].join('\n'), 0o755)
+ const hungHome = homeWithUnit('hung-home', hung, NEW_MAIN)
+ // A stand-in `timeout` records the duration it was given and then waits 1 s instead of it.
+ const timeoutLog = path.join(dir, 'timeout-calls.log')
+ const fastTimeout = path.join(dir, 'bin-fast-timeout')
+ write(path.join(fastTimeout, 'timeout'), ['#!/bin/sh', `echo "$1" >> ${JSON.stringify(timeoutLog)}`, 'shift', `exec ${REAL_TIMEOUT} 1 "$@"`].join('\n'), 0o755)
+ const started = Date.now()
+ const out = await sh(shareProbeCommand('~', noSystemUnit()), 'leaked\n', { HOME: hungHome, PATH: `${fastTimeout}:${bin}:/usr/bin:/bin` })
+ expect(Date.now() - started).toBeLessThan(4000)
+ const p = parseShareProbe(out)
+ if ('error' in p) throw new Error(p.error)
+ expect(p).toMatchObject({ hasBootstrap: true, statusRc: 124, teamExists: false })
+ expect(fs.readFileSync(timeoutLog, 'utf8')).toBe('10\n')
+ const calls = fs.readFileSync(hangLog, 'utf8')
+ expect(calls).toContain('team --data-dir')
+ expect(calls).not.toContain('stdin:')
+ })
+ it('without a `timeout` binary the server is not run at all and its status is unknown', async () => {
+ // Only what the probe needs besides `timeout`: the fakes plus a few real tools.
+ const minimal = path.join(dir, 'bin-min')
+ fs.mkdirSync(minimal, { recursive: true })
+ for (const t of ['uname', 'id', 'tmux']) fs.symlinkSync(path.join(bin, t), path.join(minimal, t))
+ for (const t of ['sh', 'sed', 'head', 'grep', 'basename', 'cat', 'ls']) fs.symlinkSync(findTool(t), path.join(minimal, t))
+ fs.rmSync(nodeLog, { force: true })
+ const p = parseShareProbe(await sh(shareProbeCommand('~/proj', noSystemUnit()), undefined, { PATH: minimal }))
+ if ('error' in p) throw new Error(p.error)
+ expect(p).toMatchObject({ hasBootstrap: true, statusRc: null, teamExists: false })
+ expect(fs.existsSync(nodeLog)).toBe(false)
+ })
it('a cut-off probe is an error, never a half-filled probe', () => {
expect(parseShareProbe("##NTP 1\n##OS Linux\n")).toMatchObject({ error: expect.any(String) })
expect(parseShareProbe('')).toMatchObject({ error: expect.any(String) })
@@ -130,11 +214,41 @@ describe.skipIf(process.platform === 'win32')('share-team remote shell (real /bi
expect(parseShareProbe('##NTP 1\n##UNIT none\n##CWD /p\n##PANES\nnt-a|bash\n')).toMatchObject({ error: expect.any(String) })
expect(parseShareProbe('##NTP 1\n##UNIT bogus\n##END\n')).toMatchObject({ error: expect.any(String) })
})
+ it('a line named like an Object prototype member is not a block start', () => {
+ for (const line of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) {
+ const p = parseShareProbe(`##NTP 1\n${line}\n##UNIT none\n##CWD /p\n##END\n`)
+ if ('error' in p) throw new Error(`${line}: ${p.error}`)
+ expect(p).toMatchObject({ unit: 'none', adoptCwd: '/p' })
+ }
+ })
+ it('teamExists: on when hosting, on when it is off for a reason other than no team, off with no team', () => {
+ const withStatus = (json: string): unknown => {
+ const p = parseShareProbe(`##NTP 1\n##UNIT user\n##STATUSRC 0\n##STATUS\n${json}\n##STATUSEND\n##END\n`)
+ if ('error' in p) throw new Error(p.error)
+ return p.teamExists
+ }
+ expect(withStatus('{"enabled":true,"off":null}')).toBe(true)
+ expect(withStatus('{"enabled":false,"off":{"reason":"no-team"}}')).toBe(false)
+ expect(withStatus('{"enabled":false,"off":{"reason":"stopped"}}')).toBe(true)
+ expect(withStatus('{"enabled":false,"off":{"reason":"host-key-unreadable","detail":"x"}}')).toBe(true)
+ expect(withStatus('{"enabled":false,"off":null}')).toBe(false)
+ expect(withStatus('{"ok":false,"error":"no server"}')).toBe(false)
+ expect(withStatus('not json')).toBe(false)
+ })
+ it('install meta keeps version and commit only when both are strings', () => {
+ const metaOf = (json: string): unknown => {
+ const p = parseShareProbe(`##NTP 1\n##UNIT user\n##META\n${json}\n##METAEND\n##END\n`)
+ if ('error' in p) throw new Error(p.error)
+ return p.meta
+ }
+ expect(metaOf('{"version":"0.4.0","commit":"abc"}')).toEqual({ version: '0.4.0', commit: 'abc' })
+ expect(metaOf('{"version":4,"commit":"abc"}')).toBeNull()
+ expect(metaOf('{"version":"0.4.0","commit":null}')).toBeNull()
+ expect(metaOf('{"version":"0.4.0"}')).toBeNull()
+ expect(metaOf('[1,2]')).toBeNull()
+ })
it('a hostile folder name cannot inject shell', async () => {
- const out = await sh(shareProbeCommand("~/x'; touch /tmp/nt-pwned-$$; '"))
- expect('error' in parseShareProbe(out)).toBe(false)
- expect(fs.readdirSync('/tmp').some((f) => f.startsWith('nt-pwned-'))).toBe(false)
- // Unquoted breakouts too: a separator and a command substitution in the folder name.
+ // Unquoted breakouts: a separator, a command substitution and backticks in the folder name.
for (const [name, marker] of [
[`~/x; touch ${path.join(dir, 'pwned-a')}`, 'pwned-a'],
[`/x$(touch ${path.join(dir, 'pwned-b')})`, 'pwned-b'],
@@ -145,20 +259,49 @@ describe.skipIf(process.platform === 'win32')('share-team remote shell (real /bi
expect(fs.existsSync(path.join(dir, marker))).toBe(false)
}
})
+ it('refuses a quote or backslash in any value it would embed (not every login shell can take them nested)', () => {
+ expect(() => shareProbeCommand("~/x'; touch /tmp/nt-pwned-$$; '")).toThrow(/folder path contains a quote or backslash/)
+ expect(() => shareProbeCommand('~/a\\b')).toThrow(/folder path contains a quote or backslash/)
+ const p = { node: '/usr/bin/node', main: '/x/main.cjs', dataDir: '/d' }
+ expect(() => teamCliCommand(p, ['bootstrap', '--owner-label', "Enes's Mac"])).toThrow(/team command argument contains a quote or backslash/)
+ expect(() => teamCliCommand(p, ['status', 'a\\b'])).toThrow(/team command argument contains a quote or backslash/)
+ expect(() => teamCliCommand({ ...p, dataDir: "/d'x" }, ['status'])).toThrow(/install path contains a quote or backslash/)
+ expect(() => teamCliCommand({ ...p, node: '/n\\ode' }, ['status'])).toThrow(/install path contains a quote or backslash/)
+ expect(() => killVerifyCommand(['term-1', "a'b"])).toThrow(/node id/)
+ expect(() => killVerifyCommand(['a\\b'])).toThrow(/node id/)
+ expect(() => killVerifyCommand(['..'])).toThrow(/node id/)
+ expect(() => killVerifyCommand([''])).toThrow(/node id/)
+ })
+ it('every generated script is safe inside fish single quotes (no \\\' and no \\\\ in the script)', () => {
+ const scripts = [
+ innerScript(shareProbeCommand('~/proj')),
+ innerScript(teamCliCommand({ node: '/usr/bin/node', main: '/x/main.cjs', dataDir: '/d d' }, ['resume', '--project', 'p 1', '--json'])),
+ innerScript(killVerifyCommand(['term-1', 'term-a.1'])),
+ SHARE_INSTALL_SCRIPT
+ ]
+ for (const s of scripts) {
+ expect(s).not.toContain("\\'")
+ expect(s).not.toContain('\\\\')
+ }
+ })
it('runs the team CLI with argv quoted and stdin passed, fenced so login noise cannot corrupt it', async () => {
- const cmd = teamCliCommand({ node: path.join(bin, 'node'), main: '/x/main.cjs', dataDir: '/d d' }, ['resume', '--project', "p'1", '--json'])
+ const cmd = teamCliCommand({ node: path.join(bin, 'node'), main: '/x/main.cjs', dataDir: '/d d' }, ['resume', '--project', 'p 1;$x', '--json'])
const r = parseTeamCliOutput('motd line\n' + (await sh(cmd, '[{"a":1}]')))
if ('error' in r) throw new Error(r.error)
expect(r.rc).toBe(0)
- expect(r.body).toEqual({ argv: "team --data-dir /d d resume --project p'1 --json", stdin: '[{a:1}]' })
+ expect(r.body).toEqual({ argv: 'team --data-dir /d d resume --project p 1;$x --json', stdin: '[{a:1}]' })
})
- it('a non-JSON CLI reply is an error that quotes it (bounded)', () => {
- expect(parseTeamCliOutput("##NTB\nboom\n##NTRC 1\n")).toMatchObject({ error: expect.stringContaining('boom') })
+ it('a non-JSON CLI reply is an error that names the exit code and quotes the output (bounded)', () => {
+ const boom = parseTeamCliOutput('##NTB\nboom\n##NTRC 1\n')
+ expect(boom).toEqual({ error: 'The team command printed no JSON (exit 1): boom' })
+ expect(parseTeamCliOutput('##NTB\n##NTRC 127\n')).toEqual({ error: 'The team command printed no JSON (exit 127): (nothing)' })
const long = parseTeamCliOutput(`##NTB\n${'x'.repeat(5000)}\n##NTRC 1\n`)
expect('error' in long && long.error.length < 400).toBe(true)
})
it('a quoted reply carries no control or text-direction characters', () => {
- const r = parseTeamCliOutput('##NTB\nab\u202Ecd\u001b[31m\n##NTRC 1\n')
+ const rlo = String.fromCharCode(0x202e)
+ const esc = String.fromCharCode(0x1b)
+ const r = parseTeamCliOutput(`##NTB\nab${rlo}cd${esc}[31m\n##NTRC 1\n`)
if (!('error' in r)) throw new Error('expected an error')
expect(r.error).toContain('ab cd [31m')
})
@@ -188,11 +331,26 @@ describe.skipIf(process.platform === 'win32')('share-team remote shell (real /bi
expect(fs.existsSync(path.join(state, 'nt-term-9x'))).toBe(true)
fs.rmSync(path.join(state, 'nt-term-9x'))
})
+ it('gone needs tmux to say so: no server, or nothing to connect to, is gone', async () => {
+ // An empty socket: the fake answers "no server running", as tmux does.
+ expect(parseKillVerify(await sh(killVerifyCommand(['term-1'])), ['term-1'])).toEqual([{ nodeId: 'term-1', state: 'gone' }])
+ for (const mode of ['nofile', 'refused']) {
+ const out = await sh(killVerifyCommand(['term-1']), undefined, { FAKE_TMUX_MODE: mode })
+ expect(parseKillVerify(out, ['term-1'])).toEqual([{ nodeId: 'term-1', state: 'gone' }])
+ }
+ })
+ it('an exit 1 that is not one of tmux\'s absence messages is unknown, never gone', async () => {
+ fs.writeFileSync(path.join(state, 'nt-term-1'), 'x')
+ for (const mode of ['mismatch', 'denied']) {
+ const out = await sh(killVerifyCommand(['term-1']), undefined, { FAKE_TMUX_MODE: mode })
+ expect(parseKillVerify(out, ['term-1'])).toEqual([{ nodeId: 'term-1', state: 'unknown' }])
+ }
+ fs.rmSync(path.join(state, 'nt-term-1'))
+ })
it('a host where tmux cannot run reports every node unknown, never gone', async () => {
const noTmux = path.join(dir, 'bin-notmux')
- fs.mkdirSync(noTmux, { recursive: true })
write(path.join(noTmux, 'tmux'), '#!/bin/sh\nexit 127\n', 0o755)
- const out = (await run('/bin/sh', ['-c', killVerifyCommand(['term-1'])], { env: { HOME: home, PATH: `${noTmux}:/usr/bin:/bin` } })).stdout
+ const out = await sh(killVerifyCommand(['term-1']), undefined, { PATH: `${noTmux}:/usr/bin:/bin` })
expect(parseKillVerify(out, ['term-1'])).toEqual([{ nodeId: 'term-1', state: 'unknown' }])
})
it('a kill reply missing a node is unknown for that node; a cut-off reply is an error', () => {
@@ -208,7 +366,7 @@ describe.skipIf(process.platform === 'win32')('share-team remote shell (real /bi
expect(SHARE_INSTALL_SCRIPT).toContain(SERVER_INSTALL_URL)
expect(SHARE_INSTALL_SCRIPT).not.toMatch(/\|\s*bash/)
})
- it('the install script runs the download, passes its exit code through and removes the temp file', async () => {
+ it('the install script runs the download, passes its exit code through and removes the temp file on every exit', async () => {
const curlBin = path.join(dir, 'bin-curl')
const tmp = path.join(dir, 'install-tmp')
fs.mkdirSync(tmp, { recursive: true })
@@ -219,26 +377,32 @@ describe.skipIf(process.platform === 'win32')('share-team remote shell (real /bi
'out=""; url=""',
'while [ $# -gt 0 ]; do case "$1" in -o) shift; out="$1";; -*) ;; *) url="$1";; esac; shift; done',
'[ -n "$FAKE_CURL_FAIL" ] && exit 22',
- `printf 'echo "installer from %s"; exit 3\\n' "$url" > "$out"`
+ `printf 'echo "installer from %s"; exit 3\\n' "$url" > "$out"`,
+ // The session is torn down while the download finishes (an ssh drop, the runner's timeout).
+ '[ -n "$FAKE_CURL_TERM_PARENT" ] && kill -TERM "$PPID"',
+ 'exit 0'
].join('\n'),
0o755
)
- const runInstall = async (fail: boolean): Promise<{ code: number; stdout: string; stderr: string }> => {
- const env = { HOME: home, TMPDIR: tmp, PATH: `${curlBin}:/usr/bin:/bin`, ...(fail ? { FAKE_CURL_FAIL: '1' } : {}) }
+ const runInstall = async (env: Record<string, string>): Promise<{ code: number; stdout: string; stderr: string }> => {
try {
- const r = await run('/bin/sh', ['-c', SHARE_INSTALL_SCRIPT], { env })
+ const r = await run('/bin/sh', ['-c', SHARE_INSTALL_SCRIPT], { env: { HOME: home, TMPDIR: tmp, PATH: `${curlBin}:/usr/bin:/bin`, ...env } })
return { code: 0, stdout: r.stdout, stderr: r.stderr }
} catch (e) {
- const err = e as { code: number; stdout: string; stderr: string }
- return { code: err.code, stdout: err.stdout, stderr: err.stderr }
+ const err = e as { code: number | null; signal?: string; stdout: string; stderr: string }
+ return { code: err.code ?? -1, stdout: err.stdout, stderr: err.stderr }
}
}
- const ok = await runInstall(false)
- expect(ok).toMatchObject({ code: 3, stdout: `installer from ${SERVER_INSTALL_URL}\n` })
- const failed = await runInstall(true)
+ expect(await runInstall({})).toMatchObject({ code: 3, stdout: `installer from ${SERVER_INSTALL_URL}\n` })
+ expect(fs.readdirSync(tmp)).toEqual([])
+ const failed = await runInstall({ FAKE_CURL_FAIL: '1' })
expect(failed.code).toBe(1)
expect(failed.stdout).toBe('')
expect(failed.stderr).toContain('could not download the installer')
expect(fs.readdirSync(tmp)).toEqual([])
+ const killed = await runInstall({ FAKE_CURL_TERM_PARENT: '1' })
+ expect(killed.code).not.toBe(0)
+ expect(killed.stdout).toBe('')
+ expect(fs.readdirSync(tmp)).toEqual([])
})
})
diff --git a/src/core/remote-ssh/share-team-remote.ts b/src/core/remote-ssh/share-team-remote.ts
index c74f15740..092b974ef 100644
--- a/src/core/remote-ssh/share-team-remote.ts
+++ b/src/core/remote-ssh/share-team-remote.ts
@@ -2,15 +2,22 @@
// generated here and run over the project's ControlMaster by src/main. Generated shell no compiler
// checks, so share-team-remote.test.ts runs each one under a real /bin/sh against a fake host.
// Rules:
-// - every script runs under `sh -c '…'`, never the login shell, which may be zsh or fish;
+// - every command is `sh -c '<script>'`. The login shell (sh, bash, zsh or fish) still parses that
+// one line to find `sh` and its single-quoted argument; only the script itself runs under sh.
+// Inside fish single quotes `\'` and `\\` are escapes, so a nested quote does not survive every
+// login shell: a VALUE embedded in a script that contains `'` or `\` is refused, never
+// nested-quoted, and the scripts' own text carries neither sequence;
// - fence markers are printed QUOTED, because an unquoted `#` starts a comment;
// - paths are quoted;
-// - session names come only from `sessionName`;
+// - session names come only from `sessionName`, for safe node ids only;
// - kills target `=nt-<id>` exactly, on `nodeterm-rmt` ONLY. That is this desktop's socket. The
// server core's `node-terminal` sessions are the ones being resumed, so the every-socket kill
-// used elsewhere would stop exactly the sessions the handover exists to start.
+// used elsewhere would stop exactly the sessions the handover exists to start;
+// - the probe never RUNS an installed server it has not first recognised as new enough: a build
+// from before the `team` CLI ignores `team` and boots a whole second server.
import { posixQuote, quoteRemotePath, remoteTmuxPathPrologue } from '../../shared/ssh'
import type { ShareProbe } from '../../shared/share-team'
+import { isSafeNodeId } from '../../shared/safe-id'
import { RMT_TMUX_SOCKET } from './control-master'
import { sessionName } from '../tmux-naming'
import { CONTROL_RE } from '../relay/team-admin'
@@ -22,16 +29,39 @@ const SYSTEM_UNIT_PATH = '/etc/systemd/system/nodeterm-server.service'
const STATUS_MAX = 65536
/** The most of a non-JSON team reply quoted in an error. */
const SHOWN_MAX = 300
+/** The longest the probe lets the installed server answer `team status`, in seconds. The CLI only
+ * asks the running server over a local socket, so a healthy answer takes well under a second. */
+const STATUS_TIMEOUT_S = 10
+/**
+ * Text that only a server bundle which knows `team bootstrap` carries: its usage row
+ * (`src/server/team-cli.ts`, pinned there by a test). The probe greps `main.cjs` for it instead of
+ * running `team --help`, because a bundle from before the `team` CLI ignores `team` and boots a
+ * full second server on the live data dir. The bundle is not minified, so the literal survives.
+ */
+export const BOOTSTRAP_MARKER = 'bootstrap --owner-key'
const CONTROL_G = new RegExp(CONTROL_RE.source, 'gu')
const sh = (script: string): string => `sh -c ${posixQuote(script)}`
+const QUOTE_OR_BACKSLASH = /['\\]/
+/** Refuse a value that cannot be nested inside `sh -c '…'` for every login shell (see the header). */
+function refuseNested(value: string, what: string): void {
+ if (QUOTE_OR_BACKSLASH.test(value)) {
+ throw new Error(`${what} contains a quote or backslash, which cannot be passed safely to every login shell.`)
+ }
+}
+
/** The official installer, downloaded first: `curl … | bash` runs an EMPTY script and exits 0 when
- * the download fails (no pipefail), so a failed download would look like a successful install. */
+ * the download fails (no pipefail), so a failed download would look like a successful install.
+ * The temp file goes on every exit: a hang-up or kill (the ssh session dropped, the runner's
+ * timeout) runs the EXIT trap through the signal traps, which sh does not do on its own. */
export const SHARE_INSTALL_SCRIPT = [
'f=$(mktemp) || exit 1',
- `if ! curl -fsSL ${posixQuote(SERVER_INSTALL_URL)} -o "$f"; then rm -f "$f"; echo 'nodeterm: could not download the installer.' >&2; exit 1; fi`,
+ `trap 'rm -f "$f"' EXIT`,
+ "trap 'exit 129' HUP",
+ "trap 'exit 130' INT",
+ "trap 'exit 143' TERM",
+ `if ! curl -fsSL ${posixQuote(SERVER_INSTALL_URL)} -o "$f"; then echo 'nodeterm: could not download the installer.' >&2; exit 1; fi`,
'bash "$f"; rc=$?',
- 'rm -f "$f"',
'exit $rc'
].join('\n')
@@ -41,10 +71,16 @@ export const SHARE_INSTALL_SCRIPT = [
* that build knows `team bootstrap`, whether the CLI answers `team status`, the project folder's
* real path, and the live panes on this desktop's remote tmux socket. Read by `parseShareProbe`.
*
+ * Bootstrap support is read from main.cjs's text (`BOOTSTRAP_MARKER`), and the server is run only
+ * when that text is there: under `timeout`, with no stdin. A host with no `timeout` binary does
+ * not run it at all, and its status is reported unknown.
+ *
* `systemUnit` exists so a test can point the system-unit check at a fake host tree; the only
* production value is the default.
*/
export function shareProbeCommand(remoteCwd: string, systemUnit: string = SYSTEM_UNIT_PATH): string {
+ refuseNested(remoteCwd, 'The folder path')
+ refuseNested(systemUnit, 'The system unit path')
return sh(
[
// `set -- $X` below splits the unit's ExecStart into words; it must never glob them.
@@ -73,11 +109,13 @@ export function shareProbeCommand(remoteCwd: string, systemUnit: string = SYSTEM
`printf '##MAIN %s\\n' "$MAIN"`,
`printf '##DATADIR %s\\n' "$DD"`,
`if [ -r "$DD/install-meta.json" ]; then echo '##META'; head -c 4096 "$DD/install-meta.json"; echo; echo '##METAEND'; fi`,
- 'if [ -n "$NODE" ] && [ -x "$NODE" ] && [ -r "$MAIN" ]; then',
- ` if "$NODE" "$MAIN" team --help 2>/dev/null | grep -q '^ bootstrap '; then echo '##BOOTSTRAP yes'; else echo '##BOOTSTRAP no'; fi`,
- ' S=$("$NODE" "$MAIN" team --data-dir "$DD" status --json 2>/dev/null); RC=$?',
- ` printf '##STATUSRC %s\\n' "$RC"`,
- ` echo '##STATUS'; printf '%s\\n' "$S" | head -c ${STATUS_MAX}; echo; echo '##STATUSEND'`,
+ `if [ -n "$NODE" ] && [ -x "$NODE" ] && [ -r "$MAIN" ] && grep -qF ${posixQuote(BOOTSTRAP_MARKER)} "$MAIN" 2>/dev/null; then`,
+ " echo '##BOOTSTRAP yes'",
+ ' if command -v timeout >/dev/null 2>&1; then',
+ ` S=$(timeout ${STATUS_TIMEOUT_S} "$NODE" "$MAIN" team --data-dir "$DD" status --json </dev/null 2>/dev/null); RC=$?`,
+ ` printf '##STATUSRC %s\\n' "$RC"`,
+ ` echo '##STATUS'; printf '%s\\n' "$S" | head -c ${STATUS_MAX}; echo; echo '##STATUSEND'`,
+ ' fi',
'else',
" echo '##BOOTSTRAP no'",
'fi',
@@ -91,7 +129,12 @@ export function shareProbeCommand(remoteCwd: string, systemUnit: string = SYSTEM
const PROBE_CUT = 'The host did not finish the probe.'
const PANE_SESSION_RE = /^nt-[A-Za-z0-9_-]+$/
type ProbeBlock = 'meta' | 'status' | 'panes'
-const BLOCK_START: Record<string, ProbeBlock> = { '##META': 'meta', '##STATUS': 'status', '##PANES': 'panes' }
+// A Map, not an object literal: a line like `constructor` must not find Object's own members.
+const BLOCK_START = new Map<string, ProbeBlock>([
+ ['##META', 'meta'],
+ ['##STATUS', 'status'],
+ ['##PANES', 'panes']
+])
const BLOCK_END: Record<ProbeBlock, string> = { meta: '##METAEND', status: '##STATUSEND', panes: '##PANESEND' }
const parseJson = (text: string): unknown => {
@@ -163,8 +206,9 @@ export function parseShareProbe(stdout: string): ShareProbe | { error: string }
done = true
break
}
- if (BLOCK_START[line]) {
- block = BLOCK_START[line]
+ const opens = BLOCK_START.get(line)
+ if (opens) {
+ block = opens
continue
}
const space = line.indexOf(' ')
@@ -227,6 +271,8 @@ export function parseShareProbe(stdout: string): ShareProbe | { error: string }
* so a login banner cannot be mistaken for it; the exit code rides its own marker line, after a
* newline so a reply without a trailing one cannot swallow it. */
export function teamCliCommand(p: Pick<ShareProbe, 'node' | 'main' | 'dataDir'>, args: readonly string[]): string {
+ for (const v of [p.node, p.main, p.dataDir]) refuseNested(v, 'The nodeterm-server install path')
+ for (const a of args) refuseNested(a, 'A team command argument')
const argv = [p.node, p.main, 'team', '--data-dir', p.dataDir, ...args].map(posixQuote).join(' ')
return sh(`echo '##NTB'; ${argv}; rc=$?; printf '\\n##NTRC %s\\n' "$rc"`)
}
@@ -246,28 +292,48 @@ export function parseTeamCliOutput(stdout: string): { rc: number; body: unknown
try {
return { rc: Number.isNaN(rc) ? 1 : rc, body: JSON.parse(text) }
} catch {
- return { error: `The server answered something that is not JSON: ${shown(text) || '(nothing)'}` }
+ const code = Number.isNaN(rc) ? '?' : String(rc)
+ return { error: `The team command printed no JSON (exit ${code}): ${shown(text) || '(nothing)'}` }
}
}
+/**
+ * Reads a `has-session` exit code and its output. Exit 1 is "gone" only with one of tmux's own
+ * absence messages (measured on tmux 3.4: a missing session, no server behind the socket, no
+ * socket file; a refused connect is the same fact). tmux also exits 1 for a protocol-version
+ * mismatch and for a permission-denied socket, and in those cases the kill failed too: reading
+ * them as "gone" would resume a second agent beside a live one. Anything else is "unknown".
+ */
+const KILL_STATE_FN = [
+ 'nt_state() {',
+ ' case $1 in',
+ ' 0) echo alive ;;',
+ ` 1) case $2 in *"can't find session"*|*"no server running"*|*"error connecting to "*"(No such file or directory)"*|*"error connecting to "*"(Connection refused)"*) echo gone ;; *) echo unknown ;; esac ;;`,
+ ' *) echo unknown ;;',
+ ' esac',
+ '}'
+].join('\n')
+
/**
* Stop each node's session on this desktop's remote tmux socket and check that it is gone. Every
* target is exact (`=nt-<id>`): without `=` tmux falls back to prefix matching on a miss, and
- * `nt-…-1` is a prefix of `nt-…-12`. `has-session` exiting 1 means "gone" — tmux answers 1 both
- * for "can't find session" and for "no server running", and either way nothing is running there.
- * Any other code (126/127: tmux could not run) is "unknown", and only a `gone` node is resumed.
+ * `nt-…-1` is a prefix of `nt-…-12`. Only a `gone` node is resumed (see `KILL_STATE_FN`). Node
+ * ids must be safe ids; anything else is refused before a script is built.
*/
export function killVerifyCommand(nodeIds: readonly string[]): string {
+ for (const id of nodeIds) {
+ if (!isSafeNodeId(id)) throw new Error('A terminal node id is not a safe id (letters, digits, ".", "_" and "-" only).')
+ }
const body = nodeIds.map((id) => {
const t = posixQuote(`=${sessionName(id)}`)
const n = posixQuote(sessionName(id))
return [
`tmux -L ${RMT_TMUX_SOCKET} kill-session -t ${t} >/dev/null 2>&1`,
- `tmux -L ${RMT_TMUX_SOCKET} has-session -t ${t} >/dev/null 2>&1; r=$?`,
- `case $r in 0) s=alive;; 1) s=gone;; *) s=unknown;; esac; printf '##K %s %s\\n' ${n} "$s"`
+ `o=$(tmux -L ${RMT_TMUX_SOCKET} has-session -t ${t} 2>&1); r=$?`,
+ `printf '##K %s %s\\n' ${n} "$(nt_state "$r" "$o")"`
].join('\n')
})
- return sh([`${remoteTmuxPathPrologue()}echo '##NTK'`, ...body, "echo '##NTKEND'"].join('\n'))
+ return sh([KILL_STATE_FN, `${remoteTmuxPathPrologue()}echo '##NTK'`, ...body, "echo '##NTKEND'"].join('\n'))
}
export type KillVerifyState = 'gone' | 'alive' | 'unknown'
diff --git a/src/server/team-cli.test.ts b/src/server/team-cli.test.ts
index c41ef7a1c..6c863d97e 100644
--- a/src/server/team-cli.test.ts
+++ b/src/server/team-cli.test.ts
@@ -7,6 +7,7 @@ import { startTeamAdmin, adminSocketPath, type AdminStatusResult, type TeamAdmin
import { genKeyPair, publicKeyToB64 } from '../core/relay/e2ee'
import type { HostedService, HostedStatus } from '../core/relay/hosted-service'
import { POP_REFUSED_MESSAGE } from '../core/relay/relay-pop'
+import { BOOTSTRAP_MARKER } from '../core/remote-ssh/share-team-remote'
const KEY = publicKeyToB64(genKeyPair().publicKey)
@@ -74,7 +75,8 @@ describe('team argv', () => {
})
})
- it('`team --help` lists bootstrap at the row start a remote probe greps for', () => {
+ it('the usage row carries the text the desktop greps main.cjs for (it never runs the bundle)', () => {
+ expect(TEAM_USAGE).toContain(BOOTSTRAP_MARKER)
expect(TEAM_USAGE).toMatch(/^ {2}bootstrap /m)
})
diff --git a/src/server/team-cli.ts b/src/server/team-cli.ts
index f798e3bf0..e6d5c6ac6 100644
--- a/src/server/team-cli.ts
+++ b/src/server/team-cli.ts
@@ -35,7 +35,8 @@ const safeJson = (v: unknown): string =>
const USAGE_ROWS: Array<[string, string]> = [
['init', 'create the host key and the team, and start hosting'],
- // The desktop's Share with team probes for this verb by grepping `team --help` for `^ bootstrap `.
+ // The desktop's Share with team detects this verb by grepping the built main.cjs for this row's
+ // `bootstrap --owner-key` (BOOTSTRAP_MARKER); it never runs an unrecognised bundle. Keep that text.
[
'bootstrap --owner-key <key> --adopt <dir> [--owner-label <name>] [--json]',
'set up the team, an owner and a shared project in one step'