Skip to content

Commit 59a9874

Browse files
anandgupta42claude
andcommitted
fix(drivers): keep our command line out of a driver's own resolution
`@mapbox/node-pre-gyp`, which packages several native modules including DuckDB, resolves a module's manifest by parsing the **host application's** `process.argv`. `find()` passes `argv: process.argv` into its own `Run`, `nopt` abbreviation-matches whatever it finds against node-pre-gyp's option list, and `node-pre-gyp.js:164` then does: package_json_path = path.join(this.opts.directory, package_json_path) `path.join`, not `path.resolve` — so an absolute manifest path is not discarded. Our `--dir` abbreviates to node-pre-gyp's `--directory`, so `altimate-code run --dir <project>` made the driver look for its manifest at `<project>` concatenated with the manifest's own absolute path, and the load failed with an ENOENT naming a path that had never existed. That the failing path also looked cwd-prefixed was a coincidence: `--dir` is what sets the working directory, so the two values were always equal. Driver loads now run with `process.argv` trimmed to `[argv[0], argv[1]]`. Swapping a global is safe here in a way `process.chdir()` would not be: the load is a synchronous `require`, JavaScript is single-threaded, and there is no `await` between the swap and the restore, so no concurrent work can observe it. The asynchronous ESM fallback is deliberately left alone for that reason. Considered and rejected: renaming `--dir`. The collision is real, but the flag is public, renaming breaks every existing invocation, and it would fix only the one option name that happens to collide today rather than the mechanism. Not specific to us, to DuckDB, or to a compiled binary — any CLI embedding a node-pre-gyp-packaged module and accepting a flag that abbreviates to `--directory` is exposed. A long argv in a compiled binary only made it visible. Of the drivers installed here, only `duckdb` pulls in node-pre-gyp today; the fix is applied to every driver load rather than to DuckDB, because the exposure is a property of the packaging tool, not of the driver. The regression test reproduces the arithmetic of the one line that broke: a fixture that reads `--dir` out of `process.argv` and joins it onto its own absolute manifest path. With the neutralisation reverted it fails, reporting the flag as seen. Two further tests pin that the command line is restored afterwards, including when the load throws. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VqnuBDGkh1ZT65Ti7e6DHZ
1 parent 6ba55f3 commit 59a9874

2 files changed

Lines changed: 151 additions & 1 deletion

File tree

‎packages/drivers/src/resolve.ts‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -519,9 +519,50 @@ function entryFromManifest(pkgDir: string, specifier: string, pkg: string): stri
519519
* under concurrency, so it would corrupt resolution for unrelated work
520520
* non-deterministically — worse than the fault it patches.
521521
*/
522+
/**
523+
* Run `fn` with this process's command line hidden from it.
524+
*
525+
* `@mapbox/node-pre-gyp`, which packages several native drivers, resolves a
526+
* module's manifest by parsing the **host application's** `process.argv` —
527+
* `find()` passes `argv: process.argv` into its own `Run`, `nopt`
528+
* abbreviation-matches whatever it sees against node-pre-gyp's option list, and
529+
* `node-pre-gyp.js:164` then does:
530+
*
531+
* package_json_path = path.join(this.opts.directory, package_json_path)
532+
*
533+
* `path.join`, not `path.resolve`, so an absolute manifest path is **not**
534+
* discarded. Our `--dir` abbreviates to node-pre-gyp's `--directory`, so
535+
* `altimate-code run --dir <project>` made the driver look for its manifest at
536+
* `<project>` + the manifest's own absolute path, and the load failed with an
537+
* ENOENT naming a path that had never existed.
538+
*
539+
* Nothing about that is specific to us, to DuckDB, or to a compiled binary: any
540+
* CLI that embeds a node-pre-gyp-packaged module and accepts a flag
541+
* abbreviating to `--directory` is exposed. Reported upstream; this keeps our
542+
* users working in the meantime.
543+
*
544+
* **Why swapping a global here is safe when `process.chdir()` would not be.**
545+
* `fn` is a synchronous `require`. JavaScript is single-threaded and there is
546+
* no `await` between the swap and the restore, so no other task can run while
547+
* the command line is hidden and no concurrent load can observe it. The same
548+
* trick around an awaited dynamic `import()` would be a genuine hazard, and is
549+
* deliberately not done below.
550+
*/
551+
function withNeutralArgv<T>(fn: () => T): T {
552+
const saved = process.argv
553+
// Keep argv[0] and argv[1] — the executable and the entry script. nopt only
554+
// parses what follows, and node-pre-gyp expects those two to be present.
555+
process.argv = saved.slice(0, 2)
556+
try {
557+
return fn()
558+
} finally {
559+
process.argv = saved
560+
}
561+
}
562+
522563
function requireFromLocation(resolved: string): unknown {
523564
const requireFrom = createRequire(pathToFileURL(resolved).href)
524-
return requireFrom(resolved)
565+
return withNeutralArgv(() => requireFrom(resolved))
525566
}
526567

527568
/** True when a require failed only because the target is an ES module. */
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
2+
import fs from "node:fs"
3+
import os from "node:os"
4+
import path from "node:path"
5+
6+
import { loadOptionalDriver } from "../src/resolve"
7+
8+
// `@mapbox/node-pre-gyp` resolves a native module's manifest by parsing the
9+
// HOST APPLICATION's `process.argv`. `find()` passes `argv: process.argv` into
10+
// its own `Run`, `nopt` abbreviation-matches our flags against node-pre-gyp's
11+
// option list, and `node-pre-gyp.js:164` then does
12+
//
13+
// package_json_path = path.join(this.opts.directory, package_json_path)
14+
//
15+
// `path.join`, not `path.resolve` — so an absolute manifest path is not
16+
// discarded. Our `--dir` abbreviates to `--directory`, and the driver ended up
17+
// looking for its manifest at `<--dir value>` + the manifest's absolute path.
18+
//
19+
// The fixture below reproduces exactly that arithmetic. It does not stand in
20+
// for node-pre-gyp in general; it stands in for the one line that broke.
21+
22+
const FIXTURE = "altimate-argv-fixture"
23+
const savedArgv = process.argv
24+
25+
let root = ""
26+
let nodeModules = ""
27+
let pkgDir = ""
28+
29+
beforeEach(() => {
30+
root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "resolve-argv-")))
31+
nodeModules = path.join(root, "node_modules")
32+
pkgDir = path.join(nodeModules, FIXTURE)
33+
fs.mkdirSync(pkgDir, { recursive: true })
34+
fs.writeFileSync(
35+
path.join(pkgDir, "package.json"),
36+
JSON.stringify({ name: FIXTURE, version: "1.0.0", main: "index.js" }),
37+
)
38+
fs.writeFileSync(
39+
path.join(pkgDir, "index.js"),
40+
[
41+
"const path = require('path')",
42+
"const i = process.argv.indexOf('--dir')",
43+
"const directory = i !== -1 ? process.argv[i + 1] : undefined",
44+
"const manifest = path.join(__dirname, 'package.json')",
45+
"module.exports = {",
46+
" sawDirFlag: directory !== undefined,",
47+
" manifestPath: directory ? path.join(directory, manifest) : manifest,",
48+
"}",
49+
"",
50+
].join("\n"),
51+
)
52+
})
53+
54+
afterEach(() => {
55+
process.argv = savedArgv
56+
if (root) fs.rmSync(root, { recursive: true, force: true })
57+
})
58+
59+
/** Reach the fixture the way the real failure does: via the harvested root. */
60+
function importerThrowingAt(target: string) {
61+
const ambient = Object.assign(new Error(`ENOENT: no such file or directory, open '${target}'`), { code: "ENOENT" })
62+
return async () => {
63+
throw ambient
64+
}
65+
}
66+
67+
describe("a driver load does not see the host's command line", () => {
68+
test("the loaded module cannot observe --dir", async () => {
69+
process.argv = [savedArgv[0], savedArgv[1], "run", "--dir", "/some/project", "--print-logs"]
70+
71+
const loaded: any = await loadOptionalDriver(
72+
"duckdb",
73+
FIXTURE,
74+
importerThrowingAt(path.join(pkgDir, "package.json")),
75+
)
76+
const mod = loaded?.default ?? loaded
77+
78+
// Without argv neutralisation the fixture sees the flag and joins, which is
79+
// precisely what sent the driver after a manifest that never existed.
80+
expect(mod.sawDirFlag).toBe(false)
81+
expect(mod.manifestPath).toBe(path.join(pkgDir, "package.json"))
82+
expect(mod.manifestPath.startsWith("/some/project")).toBe(false)
83+
})
84+
85+
test("restores the command line afterwards", async () => {
86+
const argv = [savedArgv[0], savedArgv[1], "run", "--dir", "/some/project"]
87+
process.argv = argv
88+
89+
await loadOptionalDriver("duckdb", FIXTURE, importerThrowingAt(path.join(pkgDir, "package.json")))
90+
91+
expect(process.argv).toEqual(argv)
92+
})
93+
94+
test("restores the command line even when the load throws", async () => {
95+
fs.writeFileSync(path.join(pkgDir, "index.js"), "throw new Error('broken driver')\n")
96+
const argv = [savedArgv[0], savedArgv[1], "run", "--dir", "/some/project"]
97+
process.argv = argv
98+
99+
let failed = false
100+
try {
101+
await loadOptionalDriver("duckdb", FIXTURE, importerThrowingAt(path.join(pkgDir, "package.json")))
102+
} catch {
103+
failed = true
104+
}
105+
106+
expect(failed).toBe(true)
107+
expect(process.argv).toEqual(argv)
108+
})
109+
})

0 commit comments

Comments
 (0)