Files
orca/src/main/ssh/ssh-relay-node-headers.test.ts
T
Neil 36a826ff48 fix(ssh): compile node-pty from the host's own Node headers instead of nodejs.org (STA-6674) (#18774)
* fix(ssh): compile node-pty from the host's own Node headers instead of nodejs.org

STA-6674: a Linux SSH host that cannot reach nodejs.org never came up. node-pty
ships no Linux prebuild, so npm hands it to node-gyp, and node-gyp's default is
to download node-v<ver>-headers.tar.gz before configuring. The host refused
that connection (ECONNREFUSED) and the relay deploy failed inside npm install,
which the UI showed only as "Disconnected".

Every official Node build and every version manager that unpacks one already
has those exact headers at <prefix>/include/node. Export node-gyp's nodedir to
that prefix, on every command that can compile node-pty (npm install, npm
rebuild, the cloexec patch's rebuild), when the shipped node_version.h matches
the running Node. Both npm_config_nodedir (node-gyp 10, Node 20) and
npm_package_config_node_gyp_nodedir (node-gyp >= 11.4) are set so every Node
the relay runs on reads it. A version mismatch leaves it unset, which is the
existing behaviour.

When a host is both header-less and offline, name that in the deploy error
instead of forty lines of gyp http output, with the two remedies.

Reproduced and verified with a Docker sshd whose nodejs.org resolves to
127.0.0.1, on node:24.12.0 (the user's version), node:20 and node:26:
ssh-relay-offline-node-headers.docker.test.ts.

* fix(ssh): fail loudly when node-gyp ignores the exported Node headers dir

The headers export relies on npm forwarding npm_config_nodedir /
npm_package_config_node_gyp_nodedir into lifecycle scripts. If a future npm
drops that, node-gyp would silently fall back to downloading, and an offline
host would fail with the same "install an official Node" diagnosis -- wrong,
since the host did ship headers.

The prefix now echoes ORCA-NODE-HEADERS:<dir|none> into the command's output
before the compile, and the download-failure diagnosis reads it back: an
exported dir plus a download attempt is reported as an Orca defect naming
the dir, not as a host problem. Nothing else changes when it works.

* fix(ssh): address review on the relay node-headers export

- Unset any inherited npm_config_nodedir / npm_package_config_node_gyp_nodedir
  before the conditional export, so a stale header dir from the remote profile
  cannot bypass the version check and build a wrong-ABI binding (CodeRabbit).
- Require `gyp ERR! configure error` and a real network errno in the
  headers-download matcher; node-gyp's fetch client logs retried attempts it
  recovers from, and a FetchError can be a non-2xx mirror answer (pullfrog).
- Say "no local headers matching its own version", since the probe also
  rejects a version mismatch, not only absent headers (CodeRabbit).
- Log the same diagnosis from the non-fatal `npm rebuild` fallback (CodeRabbit).
- Docker test waits for the SSH banner on the mapped port before connecting
  instead of trusting `docker run -d` (CodeRabbit).

* fix(ssh): read the node-headers marker from the host output, not the quoted command

execCommand rejects with `Command "<command>" failed (exit N): <output>`, and
<command> quotes the whole prefix, marker echo included. The first-match
parser hit that copy and returned `${ORCA_NODE_HEADERS_DIR:-none}"; ...` as a
"dir", so every real no-headers failure was misreported as an Orca defect
(measured by an independent Docker exercise of 609685e). Strip the exec-
failure head before scanning; keep first-match so gyp output cannot spoof it.

The unit fixture hid this by rejecting with `Command "npm install" failed`,
a string production never builds. It now rejects from the command the mock
actually received, and the Docker test gains a no-headers failure case on the
same offline fixture that asserts the host-remedy message.

Also unset NPM_CONFIG_NODEDIR (npm accepts either case), and narrow the claim:
a ~/.npmrc nodedir= is not overridable from the env (measured: empty env
override is ignored on npm 10 and 11), so it stays the operator's setting.
Copy the node binary via fs in the unit test so a failed copy fails the test.

* docs(ssh): state the header-mismatch refusal as a conservative default, not an observed crash

* docs(ssh): note why the exec-failure head regex may match lazily
2026-09-04 23:47:32 -07:00

165 lines
7.1 KiB
TypeScript

import { spawnSync } from 'node:child_process'
import {
chmodSync,
copyFileSync,
mkdtempSync,
mkdirSync,
rmSync,
symlinkSync,
writeFileSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import process from 'node:process'
import { afterEach, describe, expect, it } from 'vitest'
import { exportLocalNodeHeadersPrefix, localNodeHeadersFromOutput } from './ssh-relay-node-headers'
const POSIX = process.platform !== 'win32'
/** Runs the prefix under /bin/sh exactly as the relay does, then prints what node-gyp would see. */
function runPrefix(nodePath: string): {
nodedir: string
pkgNodedir: string
marker: string | null | undefined
} {
const script = `${exportLocalNodeHeadersPrefix(nodePath)}printf '%s\\n%s\\n' "$npm_config_nodedir" "$npm_package_config_node_gyp_nodedir"`
const result = spawnSync('/bin/sh', ['-c', script], { encoding: 'utf8' })
expect(result.status).toBe(0)
const marker = localNodeHeadersFromOutput(result.stdout)
const [nodedir = '', pkgNodedir = ''] = result.stdout
.split('\n')
.filter((line) => !line.startsWith('ORCA-NODE-HEADERS:'))
return { nodedir, pkgNodedir, marker }
}
/** A fake `<prefix>/bin/node` whose `include/node/node_version.h` claims `version`. */
function fakeNodePrefix(root: string, version: string): string {
const prefix = join(root, 'prefix')
mkdirSync(join(prefix, 'bin'), { recursive: true })
mkdirSync(join(prefix, 'include', 'node'), { recursive: true })
const [major, minor, patch] = version.split('.')
writeFileSync(
join(prefix, 'include', 'node', 'node_version.h'),
`#define NODE_MAJOR_VERSION ${major}\n#define NODE_MINOR_VERSION ${minor}\n#define NODE_PATCH_VERSION ${patch}\n`
)
// Why a symlink to the real binary: the probe reads process.execPath, which Node resolves
// through symlinks -- so this stands in for `/usr/bin/node -> /opt/node/bin/node` shims too.
symlinkSync(process.execPath, join(prefix, 'bin', 'node'))
return join(prefix, 'bin', 'node')
}
describe.skipIf(!POSIX)('exportLocalNodeHeadersPrefix', () => {
const roots: string[] = []
afterEach(() => {
for (const root of roots.splice(0)) {
rmSync(root, { recursive: true, force: true })
}
})
it('exports nodedir when the running Node ships headers for its own version', () => {
// The test runner's Node is an official build, so its prefix has include/node.
const prefix = dirname(dirname(process.execPath))
const { nodedir, pkgNodedir, marker } = runPrefix(process.execPath)
expect(nodedir).toBe(prefix)
expect(pkgNodedir).toBe(prefix)
expect(marker).toBe(prefix)
})
it('leaves nodedir unset when the shipped headers are for another Node version', () => {
// A symlinked node resolves execPath to the real binary, whose prefix is the real one; so
// to stage a mismatch the probe must run a node whose execPath lands in the fake prefix.
// A copy does that.
const root = mkdtempSync(join(tmpdir(), 'orca-node-headers-'))
roots.push(root)
const prefix = join(root, 'prefix')
mkdirSync(join(prefix, 'bin'), { recursive: true })
mkdirSync(join(prefix, 'include', 'node'), { recursive: true })
writeFileSync(
join(prefix, 'include', 'node', 'node_version.h'),
'#define NODE_MAJOR_VERSION 1\n#define NODE_MINOR_VERSION 0\n#define NODE_PATCH_VERSION 0\n'
)
const copied = join(prefix, 'bin', 'node')
copyFileSync(process.execPath, copied)
chmodSync(copied, 0o755)
const { nodedir, pkgNodedir, marker } = runPrefix(copied)
expect(nodedir).toBe('')
expect(pkgNodedir).toBe('')
expect(marker).toBeNull()
})
it('leaves nodedir unset when the prefix has no headers at all', () => {
const root = mkdtempSync(join(tmpdir(), 'orca-node-headers-'))
roots.push(root)
const copied = join(root, 'bin', 'node')
mkdirSync(dirname(copied), { recursive: true })
copyFileSync(process.execPath, copied)
chmodSync(copied, 0o755)
const { nodedir } = runPrefix(copied)
expect(nodedir).toBe('')
})
it('follows a symlinked node to the install that owns the headers', () => {
const root = mkdtempSync(join(tmpdir(), 'orca-node-headers-'))
roots.push(root)
const shim = fakeNodePrefix(root, '0.0.0')
// The shim's own fake headers are ignored: execPath resolves to the real binary, and the
// real prefix's headers are the ones that match.
const { nodedir } = runPrefix(shim)
expect(nodedir).toBe(dirname(dirname(process.execPath)))
})
it('clears an inherited nodedir when the probe finds no matching headers', () => {
// A remote profile's stale nodedir must not survive past the version check.
const root = mkdtempSync(join(tmpdir(), 'orca-node-headers-'))
roots.push(root)
const copied = join(root, 'bin', 'node')
mkdirSync(dirname(copied), { recursive: true })
copyFileSync(process.execPath, copied)
chmodSync(copied, 0o755)
const script = `${exportLocalNodeHeadersPrefix(copied)}printf '%s|%s|%s' "$npm_config_nodedir" "$NPM_CONFIG_NODEDIR" "$npm_package_config_node_gyp_nodedir"`
const result = spawnSync('/bin/sh', ['-c', script], {
encoding: 'utf8',
env: {
...process.env,
npm_config_nodedir: '/usr/stale-headers',
NPM_CONFIG_NODEDIR: '/usr/stale-headers',
npm_package_config_node_gyp_nodedir: '/usr/stale-headers'
}
})
expect(result.status).toBe(0)
expect(result.stdout.split('\n').at(-1)).toBe('||')
})
it('does not fail the command line when node itself cannot run', () => {
const script = `${exportLocalNodeHeadersPrefix('/nonexistent/node')}echo "after:$npm_config_nodedir"`
const result = spawnSync('/bin/sh', ['-c', script], { encoding: 'utf8' })
expect(result.status).toBe(0)
expect(result.stdout.trim()).toBe('ORCA-NODE-HEADERS:none\nafter:')
})
})
describe('localNodeHeadersFromOutput', () => {
it('reads the host answer, not the copy of the marker echo quoted in an exec-failure head', () => {
// The real shape: execCommand quotes the whole command line, prefix included, before the output.
const command = `export PATH='/usr/local/bin':$PATH && cd '/root/.orca-remote/relay-x' && ${exportLocalNodeHeadersPrefix('/usr/local/bin/node')}npm install node-pty 2>&1`
const failed = (hostOutput: string): string =>
`Command "${command}" failed (exit 1): ${hostOutput}`
expect(
localNodeHeadersFromOutput(failed('ORCA-NODE-HEADERS:none\ngyp ERR! configure error'))
).toBeNull()
expect(
localNodeHeadersFromOutput(failed('ORCA-NODE-HEADERS:/usr/local\ngyp ERR! configure error'))
).toBe('/usr/local')
// No host output at all after the head: the command copy alone must not count as a marker.
expect(localNodeHeadersFromOutput(failed(''))).toBeUndefined()
})
it('distinguishes an exported dir, an explicit none, and no marker at all', () => {
expect(localNodeHeadersFromOutput('x\nORCA-NODE-HEADERS:/usr/local\ngyp ERR!')).toBe(
'/usr/local'
)
expect(localNodeHeadersFromOutput('ORCA-NODE-HEADERS:none\ngyp ERR!')).toBeNull()
expect(localNodeHeadersFromOutput('gyp ERR! only')).toBeUndefined()
})
})