OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
import { createTemporaryDirectoriesSync } from "./support/temporary-directories.js";
import { execFileSync, spawnSync } from "node:child_process";
import {
chmodSync,
existsSync,
mkdirSync,
readFileSync,
renameSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { dirname, join, relative, sep, win32 } from "node:path";
import { afterEach, describe, expect, test } from "bun:test";
import { PLUGIN_ROOT } from "./plugin-root.js";
import { writeSource as write } from "./support/shell.js";
const helper = join(PLUGIN_ROOT, "mcp", "helpers.mjs");
const temporaryDirectories = createTemporaryDirectoriesSync();
function posixAccount(): { username: string; homedir: string } {
// Bun's userInfo can reflect USER and HOME instead of the account database.
return JSON.parse(
execFileSync(
"node",
["-p", "JSON.stringify(require('node:os').userInfo())"],
{
encoding: "utf8",
},
),
);
}
function fixture(name = "repository") {
const directory = temporaryDirectories.create("security-policy-helper-");
const root = join(directory, name);
const output = join(directory, "output");
mkdirSync(root);
return { root, output };
}
function run(args: string[], env = process.env, cwd?: string) {
return spawnSync("node", [helper, "resolve-security-md", ...args], {
encoding: "utf8",
env,
maxBuffer: Infinity,
cwd,
});
}
function inventory(root: string) {
return run(["--repo", root, "--list"]);
}
function resolve(root: string, scope: string, output = "-") {
return run(["--repo", root, "--scope", scope, "--out", output]);
}
function expectGuidance(text: string, policies: [string, string][]): void {
const headings = [
...text.matchAll(/^## [^\r\n]*: ("(?:[^"\\]|\\.)*")\r?$/gm),
];
const sections = headings.map((heading, index) => [
JSON.parse(heading[1]!) as string,
text
.slice(heading.index! + heading[0].length, headings[index + 1]?.index)
.replace(/^[\r\n]+|[\r\n]+$/gu, ""),
]);
expect(sections).toEqual(
policies.map(([source, content]) => [
source,
content.replace(/^[\r\n]+|[\r\n]+$/gu, ""),
]),
);
}
afterEach(temporaryDirectories.cleanup);
describe("built SECURITY.md helper", () => {
test("accepts dash-prefixed paths with equals syntax", () => {
const { root } = fixture();
for (const [repo, scope, output] of [
["-1", "-2", "-3"],
["--repo space", "--scope space", "--output= guidance"],
] as const) {
write(root, `${repo}/${scope}/SECURITY.md`, "dash path policy\n");
const result = run(
[`--repo=${repo}`, `--scope=${scope}`, `--out=${output}`],
process.env,
root,
);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toBe("");
expect(readFileSync(join(root, output), "utf8")).toContain(
"dash path policy",
);
}
});
test.skipIf(process.platform !== "win32")(
"preserves Windows home-variable precedence and drive-relative homes",
() => {
const { root } = fixture();
const home = join(root, "current");
write(home, "project/SECURITY.md", "home-variable policy\n");
const drive = win32.parse(home).root.slice(0, 2);
const hook = join(root, "home-env.cjs");
function homeEnv(variables: NodeJS.ProcessEnv) {
// libuv restores omitted Windows home variables when spawning a child.
writeFileSync(
hook,
`
for (const name of ["USERPROFILE", "HOMEDRIVE", "HOMEPATH"]) delete process.env[name];
Object.assign(process.env, ${JSON.stringify(variables)});
`,
);
return {
...process.env,
NODE_OPTIONS: `${process.env["NODE_OPTIONS"] ?? ""} --require ${JSON.stringify(hook)}`,
};
}
const variants: [NodeJS.ProcessEnv, string, string][] = [
[
{ HOMEDRIVE: drive, HOMEPATH: home.slice(drive.length) },
"~/project",
root,
],
[{ HOMEPATH: home }, "~/project", root],
[
{ USERPROFILE: home, HOMEDRIVE: "Z:", HOMEPATH: "\\missing" },
"~/project",
root,
],
[{ HOMEDRIVE: drive, HOMEPATH: "current" }, "~/project", root],
[{ USERPROFILE: `${drive}current` }, "~/project", root],
[{ USERPROFILE: drive }, "~/project", home],
[{ HOMEDRIVE: drive, HOMEPATH: "" }, "~/project", home],
[{ USERPROFILE: "" }, "~", join(home, "project")],
[{ HOMEDRIVE: drive, HOMEPATH: "" }, "~", join(home, "project")],
];
for (const [variables, repo, cwd] of variants) {
const result = run(
["--repo", repo, "--scope", "."],
homeEnv(variables),
cwd,
);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain("home-variable policy");
}
expect(
run(["--repo", root, "--scope", "~"], homeEnv({})).status,
).not.toBe(0);
const other = homeEnv({ USERPROFILE: home, USERNAME: "different" });
expect(run(["--repo", "~other", "--scope", "."], other).status).not.toBe(
0,
);
for (const profile of [
"\\\\host\\share\\",
"\\\\?\\UNC\\host\\share\\",
"\\\\?\\unc\\host\\share",
]) {
const shareRoot = homeEnv({ USERPROFILE: profile, USERNAME: "share" });
const result = run(["--repo", root, "--scope", "~other"], shareRoot);
expect(result.status, result.stderr).not.toBe(0);
expect(result.stderr).toContain("Could not determine home directory.");
}
},
);
test("inventories sorted hidden, regular, and file-linked policies without Git metadata", () => {
const { root } = fixture();
write(root, "SECURITY.md", "root policy\n");
write(root, ".hidden/SECURITY.md", "hidden policy\n");
write(root, ".git/objects/SECURITY.md", "not a policy\n");
write(root, "shared-policy.md", "shared policy\n");
mkdirSync(join(root, "services", "api"), { recursive: true });
symlinkSync(
join(root, "shared-policy.md"),
join(root, "services", "api", "SECURITY.md"),
"file",
);
const result = inventory(root);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toBe(
'[".hidden/SECURITY.md", "SECURITY.md", "services/api/SECURITY.md"]\n',
);
expect(result.stderr).toBe("");
});
test.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"inventories unrelated files without requiring directory search permission",
() => {
const { root } = fixture();
write(root, "SECURITY.md", "root policy\n");
write(root, "readable/other.txt", "unrelated\n");
mkdirSync(join(root, "readable", ".git"));
const directory = join(root, "readable");
chmodSync(directory, 0o400);
try {
const result = inventory(root);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toBe('["SECURITY.md"]\n');
} finally {
chmodSync(directory, 0o700);
}
},
);
test("ignores files and directory links replaced after enumeration", () => {
const { root, output } = fixture();
write(root, "SECURITY.md", "root policy\n");
write(root, "nested/SECURITY.md", "nested policy\n");
write(root, "temporary.tmp", "temporary file");
write(root, "unrelated.txt", "unrelated file");
write(root, "changed-directory/placeholder", "temporary directory");
write(output, "outside/SECURITY.md", "outside policy\n");
const hook = join(output, "remove-after-readdir.cjs");
write(
output,
"remove-after-readdir.cjs",
`
const fs = require("node:fs");
const { join } = require("node:path");
const windows = process.platform === "win32";
const backend = windows
? require(join(${JSON.stringify(dirname(helper))}, "native", "win32-" + process.arch, "windows.node"))
: fs;
const method = windows ? "windowsDirectoryEntries" : "readdirSync";
const directory = fs.realpathSync.native(${JSON.stringify(root)});
const original = backend[method];
if (windows) {
const openFile = backend.openWindowsFile;
backend.openWindowsFile = (path, ...args) => {
if (require("node:path").basename(path.toString("utf16le")) === "unrelated.txt") throw new Error("unrelated file must not be opened");
return openFile(path, ...args);
};
}
backend[method] = (path, ...options) => {
const entries = original(path, ...options);
const text = path.toString(windows ? "utf16le" : "utf8");
if (fs.realpathSync.native(text) === directory) {
fs.unlinkSync(${JSON.stringify(join(root, "temporary.tmp"))});
fs.rmSync(${JSON.stringify(join(root, "changed-directory"))}, { recursive: true });
fs.symlinkSync(${JSON.stringify(join(output, "outside"))}, ${JSON.stringify(join(root, "changed-directory"))}, windows ? "junction" : "dir");
}
return entries;
};
require("node:module").syncBuiltinESMExports();
`,
);
const result = run(["--repo", root, "--list"], {
...process.env,
NODE_OPTIONS: `${process.env["NODE_OPTIONS"] ?? ""} --require ${JSON.stringify(hook)}`,
});
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toBe('["SECURITY.md", "nested/SECURITY.md"]\n');
expect(result.stderr).toBe("");
expect(existsSync(join(root, "temporary.tmp"))).toBe(false);
});
test
.skipIf(process.platform === "win32")
.each(["ENOENT", "ENOTDIR", "EACCES"])(
"handles %s for an unrelated raw directory entry",
(code) => {
const { root, output } = fixture();
write(root, "SECURITY.md", "root policy\n");
write(root, "unrelated.txt", "temporary file\n");
const hook = join(output, "raw-entry-race.cjs");
write(
output,
"raw-entry-race.cjs",
`
const fs = require("node:fs");
const readdir = fs.readdirSync;
const lstat = fs.lstatSync;
const directory = fs.realpathSync.native(${JSON.stringify(root)});
const unrelated = require("node:path").join(directory, "unrelated.txt");
fs.readdirSync = (path, options) => {
if (String(path) !== directory) return readdir(path, options);
const entries = readdir(path, { encoding: "buffer" });
if (${JSON.stringify(code)} === "ENOENT") fs.unlinkSync(unrelated);
return entries;
};
fs.lstatSync = (path, ...args) => {
if (String(path) === unrelated && ${JSON.stringify(code)} !== "ENOENT") {
throw Object.assign(new Error("synthetic raw entry ${code}"), { code: ${JSON.stringify(code)} });
}
return lstat(path, ...args);
};
require("node:module").syncBuiltinESMExports();
`,
);
const result = run(["--repo", root, "--list"], {
...process.env,
NODE_OPTIONS: `${process.env["NODE_OPTIONS"] ?? ""} --require ${JSON.stringify(hook)}`,
});
if (code === "EACCES") {
expect(result.status).toBe(2);
expect(result.stderr).toContain("synthetic raw entry EACCES");
} else {
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toBe('["SECURITY.md"]\n');
expect(result.stderr).toBe("");
}
},
);
test("frames Unicode paths as ASCII JSON in standard string order", () => {
const { root } = fixture();
for (const name of ["\u{10000}", "\ue000", "\u0080", "\u007f"]) {
write(root, `${name}/SECURITY.md`, "policy\n");
}
const result = inventory(root);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toBe(
'["\\u007f/SECURITY.md", "\\u0080/SECURITY.md", "\\ud800\\udc00/SECURITY.md", "\\ue000/SECURITY.md"]\n',
);
const guidance = resolve(root, "\u{10000}").stdout;
expectGuidance(guidance, [["\u{10000}/SECURITY.md", "policy"]]);
expect(guidance.split("\n", 1)[0]).toMatch(
/"\\ud800\\udc00\/SECURITY\.md"$/u,
);
});
test.skipIf(process.platform !== "linux")(
"traverses undecodable filenames and frames policy paths with surrogate escapes",
() => {
const { root } = fixture();
write(root, "SECURITY.md", "root policy\n");
writeFileSync(
Buffer.concat([
Buffer.from(join(root, "legacy-")),
Buffer.from([0xff]),
Buffer.from(".txt"),
]),
"unrelated file",
);
const directory = Buffer.concat([
Buffer.from(join(root, "é")),
Buffer.from([0xff]),
]);
mkdirSync(directory);
writeFileSync(
Buffer.concat([directory, Buffer.from("/SECURITY.md")]),
"byte-name policy\n",
);
write(root, "é\ue000/SECURITY.md", "BMP policy\n");
write(root, "é\u{10000}/SECURITY.md", "supplementary policy\n");
const rawRoot = Buffer.concat([Buffer.from(root), Buffer.from([0xff])]);
renameSync(root, rawRoot);
symlinkSync(rawRoot, root);
for (const runtime of ["node", process.execPath]) {
const result = spawnSync(
runtime,
[helper, "resolve-security-md", "--repo", root, "--list"],
{ encoding: "utf8" },
);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toBe(
'["SECURITY.md", "\\u00e9\\ud800\\udc00/SECURITY.md", "\\u00e9\\udcff/SECURITY.md", "\\u00e9\\ue000/SECURITY.md"]\n',
);
expect(result.stderr).toBe("");
const scoped = spawnSync(
runtime,
[helper, "resolve-security-md", "--repo", root, "--scope", "."],
{ encoding: "utf8" },
);
expect(scoped.status, scoped.stderr).toBe(0);
expectGuidance(scoped.stdout, [["SECURITY.md", "root policy"]]);
}
},
);
test.skipIf(process.platform === "win32")(
"reads policies when filesystem directory entry types are unknown",
() => {
const { root } = fixture();
write(root, "SECURITY.md", "root policy\n");
write(root, "nested/SECURITY.md", "nested policy\n");
const preload = join(dirname(root), "unknown-entry-types.cjs");
writeFileSync(
preload,
`
const binding = process.binding("fs");
const original = binding.readdir;
binding.readdir = function (...args) {
const result = original.apply(this, args);
if (args[2] === true && result?.[1]) result[1].fill(0);
return result;
};
`,
);
for (const args of [["--list"], ["--scope", "."]]) {
const result = spawnSync(
"node",
[
"--require",
preload,
helper,
"resolve-security-md",
"--repo",
root,
...args,
],
{ encoding: "utf8" },
);
expect(result.status, result.stderr).toBe(0);
if (args[0] === "--list") {
expect(result.stdout).toBe('["SECURITY.md", "nested/SECURITY.md"]\n');
} else {
expectGuidance(result.stdout, [["SECURITY.md", "root policy"]]);
}
}
},
);
test.skipIf(process.platform === "win32")(
"escapes newlines and terminal controls in inventory paths",
() => {
const { root } = fixture();
write(root, "service\n\u001b[31mname/SECURITY.md", "policy\n");
const result = inventory(root);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toBe('["service\\n\\u001b[31mname/SECURITY.md"]\n');
},
);
test.skipIf(process.platform !== "win32")(
"uses directory identity for canonical Windows containment",
() => {
const { root } = fixture("İrepository");
const sibling = join(dirname(root), "i\u0307repository");
write(root, "child/SECURITY.md", "child policy\n");
write(sibling, "SECURITY.md", "sibling policy\n");
const scoped = resolve(root, sibling);
expect(scoped.status).toBe(2);
expect(scoped.stderr).toContain("scan scope is outside the scan root");
expect(scoped.stdout).toBe("");
symlinkSync(join(sibling, "SECURITY.md"), join(root, "SECURITY.md"));
const linked = resolve(root, ".");
expect(linked.status).toBe(2);
expect(linked.stderr).toContain("SECURITY.md is outside the scan root");
expect(linked.stdout).toBe("");
},
);
test.skipIf(process.platform !== "linux")(
"reads a raw-byte policy target without following its replacement-character sibling",
() => {
const { root, output } = fixture();
const target = Buffer.concat([
Buffer.from(join(root, "policy-")),
Buffer.from([0xff]),
]);
writeFileSync(target, "inside policy\n");
write(output, "outside.md", "outside policy\n");
symlinkSync(join(output, "outside.md"), join(root, "policy-\ufffd"));
symlinkSync(target, join(root, "SECURITY.md"));
const result = resolve(root, ".");
expect(result.status, result.stderr).toBe(0);
expectGuidance(result.stdout, [["SECURITY.md", "inside policy"]]);
},
);
test.skipIf(process.platform !== "linux")(
"resolves repository and scope aliases into raw-byte directories",
() => {
const { root, output } = fixture();
const directory = Buffer.concat([
Buffer.from(join(root, "component-")),
Buffer.from([0xff]),
]);
mkdirSync(directory);
writeFileSync(
Buffer.concat([directory, Buffer.from("/SECURITY.md")]),
"component policy\n",
);
write(root, "SECURITY.md", "root policy\n");
write(output, "SECURITY.md", "outside policy\n");
symlinkSync(output, join(root, "component-\ufffd"));
const alias = join(root, "alias");
symlinkSync(directory, alias);
const scoped = resolve(root, "alias");
expect(scoped.status, scoped.stderr).toBe(0);
expectGuidance(scoped.stdout, [
["SECURITY.md", "root policy"],
["component-\udcff/SECURITY.md", "component policy"],
]);
const rooted = resolve(alias, ".");
expect(rooted.status, rooted.stderr).toBe(0);
expectGuidance(rooted.stdout, [["SECURITY.md", "component policy"]]);
const listed = inventory(alias);
expect(listed.status, listed.stderr).toBe(0);
expect(listed.stdout).toBe('["SECURITY.md"]\n');
},
);
test.skipIf(process.platform !== "linux")(
"preserves actual POSIX argv bytes for repository, scope, and output paths",
() => {
const { root, output } = fixture();
const repository = Buffer.concat([
Buffer.from(join(root, "repo-")),
Buffer.from([0xff]),
]);
const scope = Buffer.concat([
repository,
Buffer.from("/scope-"),
Buffer.from([0xfe]),
]);
mkdirSync(scope, { recursive: true });
writeFileSync(
Buffer.concat([scope, Buffer.from("/SECURITY.md")]),
"raw argument policy\n",
);
write(root, "repo-\ufffd/scope-\ufffd/SECURITY.md", "wrong policy\n");
const result = spawnSync(
"/bin/sh",
[
"-c",
'exec "$1" --helper resolve-security-md --repo "$2/repo-$(printf \'\\377\')" --scope "scope-$(printf \'\\376\')" --out "$3/out-$(printf \'\\375\')/guidance.md"',
"helper-test",
join(PLUGIN_ROOT, "scripts", "launch_codex_security_mcp"),
root,
output,
],
{ encoding: "utf8" },
);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toBe("");
const destination = Buffer.concat([
Buffer.from(join(output, "out-")),
Buffer.from([0xfd]),
Buffer.from("/guidance.md"),
]);
expectGuidance(readFileSync(destination, "utf8"), [
["scope-\udcfe/SECURITY.md", "raw argument policy"],
]);
},
);
test("does not inventory or follow directory links, even when named SECURITY.md", () => {
for (const linkType of ["dir", "junction"] as const) {
if (linkType === "junction" && process.platform !== "win32") continue;
const { root, output } = fixture();
write(output, "SECURITY.md", "outside policy\n");
symlinkSync(output, join(root, "outside-link"), linkType);
symlinkSync(output, join(root, "SECURITY.md"), linkType);
const result = inventory(root);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toBe("[]\n");
}
});
test.each(["file", "dir"] as const)(
"inventories broken %s links and outside file links without reading their contents",
(linkType) => {
const { root, output } = fixture();
write(output, "outside.md", "outside policy\n");
mkdirSync(join(root, "broken"));
symlinkSync(
join(root, "missing.md"),
join(root, "broken", "SECURITY.md"),
linkType,
);
symlinkSync(
join(output, "outside.md"),
join(root, "SECURITY.md"),
"file",
);
const result = inventory(root);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toBe('["SECURITY.md", "broken/SECURITY.md"]\n');
},
);
test("concatenates plain-folder guidance from root to leaf", () => {
const { root } = fixture();
write(root, "SECURITY.md", "root policy\n");
write(root, "services/SECURITY.md", "service policy\n");
write(root, "services/api/SECURITY.md", "api policy");
write(root, "services/api/handler.ts", "export {};\n");
const result = resolve(root, join(root, "services", "api", "handler.ts"));
expect(result.status, result.stderr).toBe(0);
expectGuidance(result.stdout, [
["SECURITY.md", "root policy"],
["services/SECURITY.md", "service policy"],
["services/api/SECURITY.md", "api policy"],
]);
expect(result.stdout).toEndWith("api policy\n");
});
test("uses a file's parent, skips whitespace-only guidance, and preserves a BOM", () => {
const { root } = fixture();
write(root, "SECURITY.md", "\ufeff");
write(root, "src/SECURITY.md", " \n\t\u0085\u001c");
write(root, "src/app.ts", "export {};\n");
const result = resolve(root, "src/app.ts");
expect(result.status, result.stderr).toBe(0);
expectGuidance(result.stdout, [["SECURITY.md", "\ufeff"]]);
});
test.skipIf(process.platform === "win32")(
"resolves parent components after directory symlinks",
() => {
const { root, output } = fixture();
write(root, "nested/SECURITY.md", "nested policy\n");
mkdirSync(join(root, "nested", "child"));
symlinkSync("nested/child", join(root, "alias"), "dir");
const result = resolve(root, "alias/..");
expect(result.status, result.stderr).toBe(0);
expectGuidance(result.stdout, [["nested/SECURITY.md", "nested policy"]]);
write(output, "SECURITY.md", "outside policy\n");
mkdirSync(join(output, "child"));
symlinkSync(join(output, "child"), join(root, "outside"), "dir");
const outside = resolve(root, "outside/..");
expect(outside.status).not.toBe(0);
expect(outside.stdout).toBe("");
expect(outside.stderr).toContain("outside the scan root");
},
);
test.skipIf(process.platform === "win32")("rejects scope link cycles", () => {
const { root } = fixture();
symlinkSync("second", join(root, "first"), "dir");
symlinkSync("first", join(root, "second"), "dir");
const result = resolve(root, "first");
expect(result.status).not.toBe(0);
expect(result.stdout).toBe("");
expect(result.stderr).toContain("scan scope does not exist");
});
test("creates output directories and writes empty guidance when no policy exists", () => {
const { root, output } = fixture();
const destination = join(output, "artifacts", "guidance.md");
const result = resolve(root, ".", destination);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toBe("");
expect(readFileSync(destination, "utf8")).toBe("");
});
test("writes UTF-8 guidance independently of the console locale", () => {
const { root, output } = fixture();
const content = "Unicode policy: 🔐 東京\n";
write(root, "SECURITY.md", content);
const args = ["--repo", root, "--scope", "."];
const result = run(args, { ...process.env, LANG: "C", LC_ALL: "C" });
expect(result.status, result.stderr).toBe(0);
expectGuidance(result.stdout, [["SECURITY.md", content]]);
const destination = join(output, "guidance.md");
expect(resolve(root, ".", destination).status).toBe(0);
expect(readFileSync(destination, "utf8")).toBe(
process.platform === "win32"
? result.stdout.replace(/\n/g, "\r\n")
: result.stdout,
);
});
test("expands the current home directory for repository and scope paths", () => {
const { root } = fixture();
write(root, "SECURITY.md", "home policy\n");
const result = run(["--repo", "~", "--scope", "~"], {
...process.env,
HOME: root,
USERPROFILE: root,
});
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain("home policy\n");
});
test.skipIf(process.platform !== "linux")(
"preserves raw HOME bytes for tilde expansion and keeps output tildes literal",
() => {
const { root } = fixture();
const home = Buffer.concat([
Buffer.from(join(root, "home-")),
Buffer.from([0xff]),
]);
mkdirSync(Buffer.concat([home, Buffer.from("/project")]), {
recursive: true,
});
writeFileSync(
Buffer.concat([home, Buffer.from("/SECURITY.md")]),
"raw home policy\n",
);
writeFileSync(
Buffer.concat([home, Buffer.from("/project/SECURITY.md")]),
"project policy\n",
);
write(root, "home-\ufffd/SECURITY.md", "replacement sibling\n");
write(root, "home-\ufffd/project/SECURITY.md", "replacement project\n");
const result = spawnSync(
"/bin/sh",
[
"-c",
'HOME="$2/home-$(printf \'\\377\')"; export HOME; exec "$1" --helper resolve-security-md --repo "~" --scope "~/project" --out "~/guidance.md"',
"helper-test",
join(PLUGIN_ROOT, "scripts", "launch_codex_security_mcp"),
root,
],
{ cwd: root, encoding: "utf8" },
);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toBe("");
expectGuidance(readFileSync(join(root, "~", "guidance.md"), "utf8"), [
["SECURITY.md", "raw home policy"],
["project/SECURITY.md", "project policy"],
]);
},
);
test.skipIf(process.platform === "win32")(
"distinguishes ordinary, unset, and empty HOME for quoted tilde paths",
() => {
const { root } = fixture();
write(root, "project/SECURITY.md", "project policy\n");
const project = join(root, "project");
for (const [home, path] of [
[root, "~/project"],
[`${root}/`, "~/project"],
[`${root}///`, "~/project"],
["/", `~${project}`],
[undefined, `~/${relative(posixAccount().homedir, project)}`],
["", `~${project}`],
] as const) {
const result = spawnSync(
join(PLUGIN_ROOT, "scripts", "launch_codex_security_mcp"),
["--helper", "resolve-security-md", "--repo", path, "--scope", path],
{ encoding: "utf8", env: { ...process.env, HOME: home } },
);
expect(result.status, result.stderr).toBe(0);
expectGuidance(result.stdout, [["SECURITY.md", "project policy"]]);
}
},
);
test.skipIf(process.platform === "win32")(
"expands named homes with quoted and control characters in the remaining path",
() => {
const { root } = fixture();
const info = posixAccount();
const directory = 'space "quote" back\\slash\nline\ttab\b';
write(root, `${directory}/SECURITY.md`, "named-home policy\n");
const path = `~${info.username}/${relative(info.homedir, join(root, directory))}`;
const result = run(["--repo", path, "--scope", path], {
...process.env,
HOME: join(root, "unused home"),
});
expect(result.status, result.stderr).toBe(0);
expectGuidance(result.stdout, [["SECURITY.md", "named-home policy"]]);
},
);
test.skipIf(process.platform === "win32")(
"expands named homes without invoking Git or Python",
() => {
const { root, output } = fixture();
write(root, "SECURITY.md", "independent policy\n");
const tools = join(output, "tools");
const marker = join(output, "tool-invoked");
for (const name of ["git", "python", "python3"]) {
write(
tools,
name,
'#!/bin/sh\nprintf invoked > "$HELPER_TOOL_MARKER"\nexit 99\n',
);
chmodSync(join(tools, name), 0o755);
}
const info = posixAccount();
const path = `~${info.username}/${relative(info.homedir, root)}`;
const result = spawnSync(
"/bin/sh",
[
join(PLUGIN_ROOT, "scripts", "launch_codex_security_mcp"),
"--helper",
"resolve-security-md",
"--repo",
path,
"--scope",
path,
],
{
encoding: "utf8",
env: {
...process.env,
PATH: tools,
CODEX_MCP_NODE_PATH: Bun.which("node") ?? undefined,
HELPER_TOOL_MARKER: marker,
},
},
);
expect(result.status, result.stderr).toBe(0);
expectGuidance(result.stdout, [["SECURITY.md", "independent policy"]]);
expect(result.stderr).toBe("");
expect(existsSync(marker)).toBe(false);
},
);
test.skipIf(process.platform !== "win32")(
"expands named Windows profiles beside the current profile",
() => {
const { root } = fixture();
const profiles = join(root, "profiles");
write(profiles, "current/SECURITY.md", "current policy\n");
write(profiles, "sibling/SECURITY.md", "sibling policy\n");
for (const [home, cwd, scope] of [
[join(profiles, "current"), undefined, "~sibling"],
[`${join(profiles, "current")}\\`, undefined, "~sibling"],
[`${root.slice(0, 2)}current`, profiles, "."],
] as const) {
const result = run(
["--repo", "~sibling", "--scope", scope],
{
...process.env,
USERPROFILE: home,
USERNAME: "current",
},
cwd,
);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain("sibling policy\n");
}
},
);
test("resolves repository-local file and directory links", () => {
const { root } = fixture();
write(root, "policies/shared.md", "shared policy\n");
symlinkSync(
join(root, "policies", "shared.md"),
join(root, "SECURITY.md"),
"file",
);
write(root, "components/SECURITY.md", "component policy\n");
write(root, "components/app.ts", "export {};\n");
mkdirSync(join(root, "components", "leaf"));
symlinkSync(
join(root, "components", "leaf"),
join(root, "alias"),
process.platform === "win32" ? "junction" : "dir",
);
const scope =
process.platform === "win32" ? "alias" : `alias${sep}..${sep}app.ts`;
const result = resolve(root, scope);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain("shared policy\n");
expect(result.stdout).toContain("component policy\n");
});
test("rejects missing, non-directory, or outside repository and scope paths", () => {
const { root, output } = fixture();
mkdirSync(output);
write(root, "file.ts", "export {};\n");
for (const [result, message] of [
[inventory(join(root, "missing")), "scan root does not exist"],
[inventory(join(root, "file.ts")), "scan root is not a directory"],
[resolve(root, "missing"), "scan scope does not exist"],
[resolve(root, output), "scan scope is outside the scan root"],
] as const) {
expect(result.status, result.stderr).toBe(2);
expect(result.stderr).toContain(message);
expect(result.stdout).toBe("");
}
});
test.skipIf(process.platform !== "win32")(
"resolves Windows scopes using the repository drive and native normalization",
() => {
const { root } = fixture("İrepository");
write(root, "src/SECURITY.md", "component policy\n");
write(root, "src/app.ts", "export {};\n");
const literalRoot = win32.toNamespacedPath(join(root, "src."));
write(literalRoot, "SECURITY.md", "literal directory policy\n");
const drive = root.slice(0, 2);
for (const scope of [
`${drive}src\\app.ts`,
"src/app.ts",
"src/../src/app.ts",
"src.",
"src ",
`${drive}src.`,
`${drive}src `,
win32.toNamespacedPath(join(root, "src", "app.ts")),
join(root, "src", "app.ts").slice(2),
`${join(root, "src")}.`,
`${join(root, "src").slice(2)}.`,
]) {
const result = run(
["--repo", root, "--scope", scope],
process.env,
process.env["SystemRoot"] ?? dirname(root),
);
expect(result.status, result.stderr).toBe(0);
expectGuidance(result.stdout, [
["src/SECURITY.md", "component policy"],
]);
}
for (const [repo, scope, source] of [
[literalRoot, ".", "SECURITY.md"],
[win32.toNamespacedPath(root), "src.", "src./SECURITY.md"],
] as const) {
const result = run(["--repo", repo, "--scope", scope]);
expect(result.status, result.stderr).toBe(0);
expectGuidance(result.stdout, [[source, "literal directory policy"]]);
}
},
);
test("rejects scope and policy links outside the repository", () => {
const { root, output } = fixture();
write(output, "outside.md", "outside policy\n");
symlinkSync(join(output, "outside.md"), join(root, "SECURITY.md"), "file");
symlinkSync(
output,
join(root, "outside"),
process.platform === "win32" ? "junction" : "dir",
);
for (const [scope, message] of [
[".", "SECURITY.md is outside the scan root"],
["outside", "scan scope is outside the scan root"],
]) {
const result = resolve(root, scope!);
expect(result.status, result.stderr).toBe(2);
expect(result.stderr).toContain(message!);
expect(result.stdout).toBe("");
}
});
test("rejects non-UTF-8 regular or linked policies", () => {
for (const kind of ["regular", "linked"]) {
const { root } = fixture();
write(
root,
kind === "linked" ? "policy.md" : "SECURITY.md",
Buffer.from([0xff]),
);
if (kind === "linked")
symlinkSync(join(root, "policy.md"), join(root, "SECURITY.md"), "file");
const result = resolve(root, ".");
expect(result.status, result.stderr).toBe(2);
expect(result.stderr).toContain("not valid UTF-8");
expect(result.stdout).toBe("");
}
});
test("resolves complete root and linked nested policies larger than 1 MiB", () => {
const { root } = fixture();
const rootContent = `${"root policy é\n".repeat(100_000)}root policy end\n`;
const nestedContent = `${"nested policy 文\n".repeat(100_000)}nested policy end\n`;
expect(Buffer.byteLength(rootContent)).toBeGreaterThan(1024 * 1024);
expect(Buffer.byteLength(nestedContent)).toBeGreaterThan(1024 * 1024);
write(root, "SECURITY.md", rootContent);
write(root, "policies/component.md", nestedContent);
mkdirSync(join(root, "component"));
symlinkSync(
join(root, "policies/component.md"),
join(root, "component/SECURITY.md"),
"file",
);
const result = resolve(root, "component");
expect(result.status, result.stderr).toBe(0);
expectGuidance(result.stdout, [
["SECURITY.md", rootContent],
["component/SECURITY.md", nestedContent],
]);
});
test("preserves required and mutually exclusive helper arguments", () => {
const { root } = fixture();
for (const flag of ["--help", "-h"]) {
const result = run([flag]);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain("Usage:");
}
for (const args of [["--unknown"], ["--scope"], ["positional"]]) {
const result = run(["--repo", root, ...args]);
expect(result.status, result.stderr).toBe(2);
expect(result.stdout).toBe("");
}
for (const [args, message] of [
[["--list"], "--repo is required"],
[["--repo", root], "--scope is required unless --list is specified"],
[
["--repo", root, "--list", "--scope", "."],
"--list cannot be combined with --scope",
],
] as const) {
const result = run([...args]);
expect(result.status, result.stderr).toBe(2);
expect(result.stderr).toContain(message);
expect(result.stdout).toBe("");
}
});
});